path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
src/docs/components/animate/AnimateSlideExample.js
karatechops/grommet-docs
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import Animate from 'grommet/components/Animate'; import Box from 'grommet/components/Box'; import Button from 'grommet/components/Button'; import Paragraph from 'grommet/components/Paragraph'; import Example from '../../Example'; export default class AnimateSlideExample extends Component { constructor () { super(); this.state = { active: true }; } render () { const { active } = this.state; return ( <Example code={ <Box pad={{between: 'small'}}> <Button label="Slide" primary={true} onClick={() => this.setState({active: !active})} /> <Animate enter={{ animation: 'slide-up', duration: 1000 }} leave={{ animation: 'slide-down', duration: 1000 }} visible={active}> <Paragraph> Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. </Paragraph> </Animate> </Box> } /> ); } };
src/store/shared/app.js
cezerin/cezerin
import React from 'react'; import { Route } from 'react-router'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import { animateScroll } from 'react-scroll'; import IndexContainer from './containers/index'; import SharedContainer from './containers/shared'; import CategoryContainer from './containers/category'; import ProductContainer from './containers/product'; import PageContainer from './containers/page'; import CheckoutContainer from './containers/checkout'; import CheckoutSuccessContainer from './containers/checkoutSuccess'; import NotFoundContainer from './containers/notfound'; import SearchContainer from './containers/search'; import { setCurrentPage } from './actions'; import { PAGE, PRODUCT_CATEGORY, PRODUCT, RESERVED, SEARCH } from './pageTypes'; class SwitchContainers extends React.Component { constructor(props) { super(props); } componentWillReceiveProps(nextProps) { this.props.setCurrentPage(nextProps.location); if (nextProps.location && this.props.location) { const pathnameChanged = nextProps.location.pathname !== this.props.location.pathname; const queryChanged = nextProps.location.search !== this.props.location.search; const isSearchPage = nextProps.location.pathname === '/search'; if (pathnameChanged || (queryChanged && isSearchPage)) { animateScroll.scrollToTop({ duration: 500, delay: 100, smooth: true }); } } } render() { const { history, location, currentPage } = this.props; const locationPathname = location && location.pathname ? location.pathname : '/'; switch (currentPage.type) { case PRODUCT: return <ProductContainer />; case PRODUCT_CATEGORY: return <CategoryContainer />; case SEARCH: return <SearchContainer />; case PAGE: if (locationPathname === '/') { return <IndexContainer />; } else if (locationPathname === '/checkout') { return <CheckoutContainer />; } if (locationPathname === '/checkout-success') { return <CheckoutSuccessContainer />; } else { return <PageContainer />; } default: return <NotFoundContainer />; } } } const mapStateToProps = (state, ownProps) => { return { currentPage: state.app.currentPage }; }; const mapDispatchToProps = (dispatch, ownProps) => { return { setCurrentPage: location => { dispatch(setCurrentPage(location)); } }; }; const SwitchContainersConnected = connect( mapStateToProps, mapDispatchToProps )(SwitchContainers); const App = () => ( <SharedContainer> <Route component={SwitchContainersConnected} /> </SharedContainer> ); export default App;
app/templates/src/app.js
jermspeaks/generator-react-vertical
import 'babel/polyfill'; import React from 'react'; import ReactDOM from 'react-dom'; import FastClick from 'fastclick'; import Dispatcher from './core/Dispatcher'; import getRoutes from './routes' import Location from './core/Location'; import ActionTypes from './common/constants/ActionTypes'; import { addEventListener, removeEventListener } from './common/utils/DOMUtils'; import App from './main/components/App' import ContactPage from './main/components/ContactPage'; import Router from 'react-router'; import createBrowserHistory from 'history/lib/createBrowserHistory' import LoginActions from './auth/actions/LoginActions'; // Create application containers for React app and CSS let appContainer = document.getElementById('app'); let cssContainer = document.getElementById('css'); // Set context of the DOM let context = { onSetTitle: value => document.title = value, onSetMeta: (name, content) => { // Remove and create a new <meta /> tag in order to make it work // with bookmarks in Safari let elements = document.getElementsByTagName('meta'); [].slice.call(elements).forEach((element) => { if (element.getAttribute('name') === name) { element.parentNode.removeChild(element); } }); let meta = document.createElement('meta'); meta.setAttribute('name', name); meta.setAttribute('content', content); document.getElementsByTagName('head')[0].appendChild(meta); } }; /** * Render React App on Client */ function render() { // set routes with history const history = createBrowserHistory(); let routes = getRoutes(history); // Render routes ReactDOM.render(routes, appContainer); } /** * Authenticate user with localStorage jwt (JSON Web Token) */ function authenticateUser() { let jwt = localStorage.getItem('jwt'); if (jwt) { LoginActions.loginUser(jwt); } } /** * Run React Application */ function run() { let currentLocation = null; let currentState = null; // Make taps on links and buttons work fast on mobiles FastClick.attach(document.body); // Re-render the app when window.location changes const unlisten = Location.listen( location => { currentLocation = location; currentState = Object.assign({}, location.state, { path: location.pathname, query: location.query, state: location.state, context }); render(); }); // Save the page scroll position into the current location's state var supportPageOffset = window.pageXOffset !== undefined; var isCSS1Compat = ((document.compatMode || '') === 'CSS1Compat'); const setPageOffset = () => { currentLocation.state = currentLocation.state || Object.create(null); currentLocation.state.scrollX = supportPageOffset ? window.pageXOffset : isCSS1Compat ? document.documentElement.scrollLeft : document.body.scrollLeft; currentLocation.state.scrollY = supportPageOffset ? window.pageYOffset : isCSS1Compat ? document.documentElement.scrollTop : document.body.scrollTop; }; addEventListener(window, 'scroll', setPageOffset); addEventListener(window, 'pagehide', () => { removeEventListener(window, 'scroll', setPageOffset); unlisten(); }); } // Run the application when both DOM is ready // and page content is loaded if (window.addEventListener) { window.addEventListener('DOMContentLoaded', run); } else { window.attachEvent('onload', run); }
src/svg-icons/av/pause.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvPause = (props) => ( <SvgIcon {...props}> <path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/> </SvgIcon> ); AvPause = pure(AvPause); AvPause.displayName = 'AvPause'; AvPause.muiName = 'SvgIcon'; export default AvPause;
src/svg-icons/communication/call-end.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationCallEnd = (props) => ( <SvgIcon {...props}> <path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"/> </SvgIcon> ); CommunicationCallEnd = pure(CommunicationCallEnd); CommunicationCallEnd.displayName = 'CommunicationCallEnd'; CommunicationCallEnd.muiName = 'SvgIcon'; export default CommunicationCallEnd;
features/common/components/searchInput.js
zymokey/mission-park
import React from 'react'; import { connect } from 'react-redux'; import { searchInput } from '../actions'; class SearchInput extends React.Component { constructor(props){ super(props); this.state = { search: '' } } handleInputChange(event){ const { model, attr, parentId } = this.props; const target = event.target; const value = target.value; const name = target.name; this.setState({ [name]: value }); let searchObj = {}; searchObj[attr.keyName] = value; this.props.searchInput(model, searchObj, parentId); } render(){ return( <div className="toolbar-btn" role="group" aria-label="search"> <input className="form-control" name="search" placeholder={`按${this.props.attr.name}查找`} onChange={this.handleInputChange.bind(this)} value={this.state.search} /> </div> ); } } const mapDispatchToProps = dispatch => ({ searchInput: (value, model, keyName, parentId) => { dispatch(searchInput(value, model, keyName, parentId)); } }); export default connect(null, mapDispatchToProps)(SearchInput);
apps/wmb/priv/www/static/js/src/containers/filters/index.js
black13ua/wmb
import React from 'react'; import FiltersMenuView from '../../view/filters/main'; // import RandomButtonContainer from './random-button'; import FiltersContainer from './filters/main-filter'; const RightSidebarContainer = () => <FiltersMenuView> {/* <RandomButtonContainer />*/} <FiltersContainer /> </FiltersMenuView>; export default RightSidebarContainer;
definitions/npm/styled-components_v2.x.x/flow_v0.42.x-v0.52.x/test_styled-components_native_v2.x.x.js
orlandoc01/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, // Temporary ReactComponentFunctional as NativeReactComponentFunctional, 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); // $ExpectError const NativeWithComponentError1: NativeReactComponentStyled<*> = nativeStyled.View.withComponent(0); // $ExpectError const NativeWithComponentError2: NativeReactComponentStyled<*> = nativeStyled.View.withComponent('NotHere'); // ---- WithTheme ---- const NativeComponent: NativeReactComponentFunctional<{ theme: NativeTheme }> = ({ theme }) => ( <NativeThemeProvider theme={theme}> <NativeWrapper> <NativeTitleStyled>Hello World, this is my first styled component!</NativeTitleStyled> </NativeWrapper> </NativeThemeProvider> ); const NativeComponentWithTheme: NativeReactComponentFunctional<{}> = nativeWithTheme(NativeComponent); const NativeComponent2: NativeReactComponentFunctional<{}> = () => ( <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 { props: { foo: string, theme: NativeTheme } render() { return <div />; } } class NativeReactClass extends React.Component { props: { 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: NativeReactComponentFunctional<{ foo: string, theme: NativeTheme }> = props => <View />; const NativeNeedsFoo1: NativeReactComponentFunctional<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeFunctionalComponent)` background-color: red; `; // $ExpectError const NativeNeedsFoo1Error: NativeReactComponentFunctional<{ foo: number }> = nativeStyled(NativeFunctionalComponent)` background-color: red; `; const NativeNeedsFoo2: NativeReactComponentFunctional<{ foo: string, theme: NativeTheme }> = nativeStyled(NativeNeedsFoo1)` background-color: red; `; // $ExpectError const NativeNeedsFoo2Error: NativeReactComponentFunctional<{ foo: number }> = nativeStyled(NativeNeedsFoo1)` background-color: red; `; // ---- FUNCTIONAL COMPONENT TESTS (nativeWithTheme)---- const NativeNeedsFoo1Functional: NativeReactComponentFunctional<{ foo: string }> = nativeWithTheme(NativeFunctionalComponent); const NativeNeedsFoo2Functional: NativeReactComponentFunctional<{ foo: string }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo1ErrorFunctional: NativeReactComponentFunctional<{ foo: number }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo2ErrorFunctional: NativeReactComponentFunctional<{ foo: string }, { theme: string }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo3ErrorFunctional: NativeReactComponentFunctional<{ foo: number, theme: NativeTheme }> = nativeWithTheme(NativeFunctionalComponent); // $ExpectError const NativeNeedsFoo4ErrorFunctional: NativeReactComponentFunctional<{ foo: number }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo5ErrorFunctional: NativeReactComponentFunctional<{ foo: string }, { theme: string }> = nativeWithTheme(NativeNeedsFoo1Functional); // $ExpectError const NativeNeedsFoo6ErrorFunctional: NativeReactComponentFunctional<{ foo: number }, { theme: NativeTheme }> = nativeWithTheme(NativeNeedsFoo1Functional);
src/interface/report/Results/Character/PlayerInfo/Gear.js
sMteX/WoWAnalyzer
import React from 'react'; import PropTypes from 'prop-types'; import Icon from 'common/Icon'; import ItemLink from 'common/ItemLink'; import ITEM_QUALITIES from 'game/ITEM_QUALITIES'; const EPIC_ITEMS_ILVL = 340; class Gear extends React.PureComponent { static propTypes = { gear: PropTypes.array.isRequired, }; render() { const { gear } = this.props; return ( <> { gear.filter(item => item.id !== 0) .map(item => { // Items seem to turn epic from 340 item level, but WCL doesn't show this properly let quality = item.itemLevel >= EPIC_ITEMS_ILVL ? ITEM_QUALITIES.EPIC : item.quality; if (!quality) { quality = ITEM_QUALITIES.EPIC; // relics don't have a quality, but they're always epic } const gearSlot = gear.indexOf(item); return ( <div key={`${gearSlot}_${item.id}`} style={{ display: 'inline-block', textAlign: 'center', gridArea: `item-slot-${gearSlot}` }} className={`item-slot-${gearSlot}`}> <ItemLink id={item.id} quality={quality} details={item} style={{ display: 'block', fontSize: '46px', lineHeight: 1 }} icon={false} > <Icon className="gear-icon icon" icon={item.icon} /> <div className="gear-ilvl">{item.itemLevel}</div> </ItemLink> </div> ); }) } </> ); } } export default Gear;
src/parser/druid/guardian/modules/features/FrenziedRegenGoEProcs.js
FaideWW/WoWAnalyzer
import React from 'react'; import { formatPercentage } from 'common/format'; import SpellIcon from 'common/SpellIcon'; import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import SPELLS from 'common/SPELLS'; import Analyzer from 'parser/core/Analyzer'; import GuardianOfElune from './GuardianOfElune'; class FrenziedRegenGoEProcs extends Analyzer { static dependencies = { guardianOfElune: GuardianOfElune, }; constructor(...args) { super(...args); this.active = this.selectedCombatant.hasTalent(SPELLS.GUARDIAN_OF_ELUNE_TALENT.id); } statistic() { const nonGoEFRegen = this.guardianOfElune.nonGoEFRegen; const GoEFRegen = this.guardianOfElune.GoEFRegen; if ((nonGoEFRegen + GoEFRegen) === 0) { return null; } return ( <StatisticBox icon={<SpellIcon id={SPELLS.FRENZIED_REGENERATION.id} />} value={`${formatPercentage(nonGoEFRegen / (nonGoEFRegen + GoEFRegen))}%`} label="Unbuffed Frenzied Regen" tooltip={`You cast <b>${nonGoEFRegen + GoEFRegen}</b> total ${SPELLS.FRENZIED_REGENERATION.name} and <b> ${GoEFRegen}</b> were buffed by 20%.`} /> ); } statisticOrder = STATISTIC_ORDER.CORE(8); } export default FrenziedRegenGoEProcs;
lib/Highlighter/stories/Highlighter.stories.js
folio-org/stripes-components
import React from 'react'; import { storiesOf } from '@storybook/react'; import withReadme from 'storybook-readme/with-readme'; import readme from '../readme.md'; import BasicUsage from './BasicUsage'; storiesOf('Highlighter', module) .addDecorator(withReadme(readme)) .add('Basic Usage', () => <BasicUsage />);
src/modules/keywords/routes/index.js
CtrHellenicStudies/Commentary
import React from 'react'; import { Route } from 'react-router'; import PrivateRoute from '../../../routes/PrivateRoute'; import EditKeywordLayout from '../layouts/EditKeywordLayout'; import KeywordPage from '../components/KeywordPage'; import KeywordDetailContainer from '../containers/KeywordDetailContainer'; const editKeywordRoute = ( <PrivateRoute exact path="/tags/:slug/edit" component={EditKeywordLayout} roles={['commenter', 'editor', 'admin']} /> ); const addKeywordRoute = ( <PrivateRoute exact path="/tags/create" component={EditKeywordLayout} roles={['commenter', 'editor', 'admin']} /> ); const keywordDetailRoute = ( <Route exact path="/tags/:slug" component={KeywordDetailContainer} /> ); const wordsListRoute = ( <Route path="/words" render={() => ( <KeywordPage type="word" title="Words" /> )} /> ); const ideasListRoute = ( <Route path="/ideas" render={() => ( <KeywordPage type="idea" title="Ideas" /> )} /> ); export { editKeywordRoute, addKeywordRoute, keywordDetailRoute, wordsListRoute, ideasListRoute, };
app/javascript/mastodon/components/relative_timestamp.js
primenumber/mastodon
import React from 'react'; import { injectIntl, defineMessages } from 'react-intl'; import PropTypes from 'prop-types'; const messages = defineMessages({ today: { id: 'relative_time.today', defaultMessage: 'today' }, just_now: { id: 'relative_time.just_now', defaultMessage: 'now' }, seconds: { id: 'relative_time.seconds', defaultMessage: '{number}s' }, minutes: { id: 'relative_time.minutes', defaultMessage: '{number}m' }, hours: { id: 'relative_time.hours', defaultMessage: '{number}h' }, days: { id: 'relative_time.days', defaultMessage: '{number}d' }, moments_remaining: { id: 'time_remaining.moments', defaultMessage: 'Moments remaining' }, seconds_remaining: { id: 'time_remaining.seconds', defaultMessage: '{number, plural, one {# second} other {# seconds}} left' }, minutes_remaining: { id: 'time_remaining.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}} left' }, hours_remaining: { id: 'time_remaining.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}} left' }, days_remaining: { id: 'time_remaining.days', defaultMessage: '{number, plural, one {# day} other {# days}} left' }, }); const dateFormatOptions = { hour12: false, year: 'numeric', month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit', }; const shortDateFormatOptions = { month: 'short', day: 'numeric', }; const SECOND = 1000; const MINUTE = 1000 * 60; const HOUR = 1000 * 60 * 60; const DAY = 1000 * 60 * 60 * 24; const MAX_DELAY = 2147483647; const selectUnits = delta => { const absDelta = Math.abs(delta); if (absDelta < MINUTE) { return 'second'; } else if (absDelta < HOUR) { return 'minute'; } else if (absDelta < DAY) { return 'hour'; } return 'day'; }; const getUnitDelay = units => { switch (units) { case 'second': return SECOND; case 'minute': return MINUTE; case 'hour': return HOUR; case 'day': return DAY; default: return MAX_DELAY; } }; export const timeAgoString = (intl, date, now, year, timeGiven = true) => { const delta = now - date.getTime(); let relativeTime; if (delta < DAY && !timeGiven) { relativeTime = intl.formatMessage(messages.today); } else if (delta < 10 * SECOND) { relativeTime = intl.formatMessage(messages.just_now); } else if (delta < 7 * DAY) { if (delta < MINUTE) { relativeTime = intl.formatMessage(messages.seconds, { number: Math.floor(delta / SECOND) }); } else if (delta < HOUR) { relativeTime = intl.formatMessage(messages.minutes, { number: Math.floor(delta / MINUTE) }); } else if (delta < DAY) { relativeTime = intl.formatMessage(messages.hours, { number: Math.floor(delta / HOUR) }); } else { relativeTime = intl.formatMessage(messages.days, { number: Math.floor(delta / DAY) }); } } else if (date.getFullYear() === year) { relativeTime = intl.formatDate(date, shortDateFormatOptions); } else { relativeTime = intl.formatDate(date, { ...shortDateFormatOptions, year: 'numeric' }); } return relativeTime; }; const timeRemainingString = (intl, date, now, timeGiven = true) => { const delta = date.getTime() - now; let relativeTime; if (delta < DAY && !timeGiven) { relativeTime = intl.formatMessage(messages.today); } else if (delta < 10 * SECOND) { relativeTime = intl.formatMessage(messages.moments_remaining); } else if (delta < MINUTE) { relativeTime = intl.formatMessage(messages.seconds_remaining, { number: Math.floor(delta / SECOND) }); } else if (delta < HOUR) { relativeTime = intl.formatMessage(messages.minutes_remaining, { number: Math.floor(delta / MINUTE) }); } else if (delta < DAY) { relativeTime = intl.formatMessage(messages.hours_remaining, { number: Math.floor(delta / HOUR) }); } else { relativeTime = intl.formatMessage(messages.days_remaining, { number: Math.floor(delta / DAY) }); } return relativeTime; }; export default @injectIntl class RelativeTimestamp extends React.Component { static propTypes = { intl: PropTypes.object.isRequired, timestamp: PropTypes.string.isRequired, year: PropTypes.number.isRequired, futureDate: PropTypes.bool, }; state = { now: this.props.intl.now(), }; static defaultProps = { year: (new Date()).getFullYear(), }; shouldComponentUpdate (nextProps, nextState) { // As of right now the locale doesn't change without a new page load, // but we might as well check in case that ever changes. return this.props.timestamp !== nextProps.timestamp || this.props.intl.locale !== nextProps.intl.locale || this.state.now !== nextState.now; } componentWillReceiveProps (nextProps) { if (this.props.timestamp !== nextProps.timestamp) { this.setState({ now: this.props.intl.now() }); } } componentDidMount () { this._scheduleNextUpdate(this.props, this.state); } componentWillUpdate (nextProps, nextState) { this._scheduleNextUpdate(nextProps, nextState); } componentWillUnmount () { clearTimeout(this._timer); } _scheduleNextUpdate (props, state) { clearTimeout(this._timer); const { timestamp } = props; const delta = (new Date(timestamp)).getTime() - state.now; const unitDelay = getUnitDelay(selectUnits(delta)); const unitRemainder = Math.abs(delta % unitDelay); const updateInterval = 1000 * 10; const delay = delta < 0 ? Math.max(updateInterval, unitDelay - unitRemainder) : Math.max(updateInterval, unitRemainder); this._timer = setTimeout(() => { this.setState({ now: this.props.intl.now() }); }, delay); } render () { const { timestamp, intl, year, futureDate } = this.props; const timeGiven = timestamp.includes('T'); const date = new Date(timestamp); const relativeTime = futureDate ? timeRemainingString(intl, date, this.state.now, timeGiven) : timeAgoString(intl, date, this.state.now, year, timeGiven); return ( <time dateTime={timestamp} title={intl.formatDate(date, dateFormatOptions)}> {relativeTime} </time> ); } }
src/svg-icons/action/event.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionEvent = (props) => ( <SvgIcon {...props}> <path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/> </SvgIcon> ); ActionEvent = pure(ActionEvent); ActionEvent.displayName = 'ActionEvent'; ActionEvent.muiName = 'SvgIcon'; export default ActionEvent;
fields/types/relationship/RelationshipField.js
helloworld3q3q/keystone
import async from 'async'; import Field from '../Field'; import { listsByKey } from '../../../admin/client/utils/lists'; import React from 'react'; import Select from 'react-select'; import xhr from 'xhr'; import { Button, InputGroup } from 'elemental'; import _ from 'lodash'; function compareValues (current, next) { const currentLength = current ? current.length : 0; const nextLength = next ? next.length : 0; if (currentLength !== nextLength) return false; for (let i = 0; i < currentLength; i++) { if (current[i] !== next[i]) return false; } return true; } module.exports = Field.create({ displayName: 'RelationshipField', statics: { type: 'Relationship', }, getInitialState () { return { value: null, createIsOpen: false, }; }, componentDidMount () { this._itemsCache = {}; this.loadValue(this.props.value); }, componentWillReceiveProps (nextProps) { if (nextProps.value === this.props.value || nextProps.many && compareValues(this.props.value, nextProps.value)) return; this.loadValue(nextProps.value); }, shouldCollapse () { if (this.props.many) { // many:true relationships have an Array for a value return this.props.collapse && !this.props.value.length; } return this.props.collapse && !this.props.value; }, buildFilters () { var filters = {}; _.forEach(this.props.filters, (value, key) => { if (typeof value === 'string' && value[0] === ':') { var fieldName = value.slice(1); var val = this.props.values[fieldName]; if (val) { filters[key] = val; return; } // check if filtering by id and item was already saved if (fieldName === ':_id' && Keystone.item) { filters[key] = Keystone.item.id; return; } } else { filters[key] = value; } }, this); var parts = []; _.forEach(filters, function (val, key) { parts.push('filters[' + key + '][value]=' + encodeURIComponent(val)); }); return parts.join('&'); }, cacheItem (item) { item.href = Keystone.adminPath + '/' + this.props.refList.path + '/' + item.id; this._itemsCache[item.id] = item; }, loadValue (values) { if (!values) { return this.setState({ loading: false, value: null, }); }; values = Array.isArray(values) ? values : values.split(','); const cachedValues = values.map(i => this._itemsCache[i]).filter(i => i); if (cachedValues.length === values.length) { this.setState({ loading: false, value: this.props.many ? cachedValues : cachedValues[0], }); return; } this.setState({ loading: true, value: null, }); async.map(values, (value, done) => { xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '/' + value + '?basic', responseType: 'json', }, (err, resp, data) => { if (err || !data) return done(err); this.cacheItem(data); done(err, data); }); }, (err, expanded) => { if (!this.isMounted()) return; this.setState({ loading: false, value: this.props.many ? expanded : expanded[0], }); }); }, // NOTE: this seems like the wrong way to add options to the Select loadOptionsCallback: {}, loadOptions (input, callback) { // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback = callback; const filters = this.buildFilters(); xhr({ url: Keystone.adminPath + '/api/' + this.props.refList.path + '?basic&search=' + input + '&' + filters, responseType: 'json', }, (err, resp, data) => { if (err) { console.error('Error loading items:', err); return callback(null, []); } data.results.forEach(this.cacheItem); callback(null, { options: data.results, complete: data.results.length === data.count, }); }); }, valueChanged (value) { this.props.onChange({ path: this.props.path, value: value, }); }, openCreate () { this.setState({ createIsOpen: true, }); }, closeCreate () { this.setState({ createIsOpen: false, }); }, onCreate (item) { this.cacheItem(item); if (Array.isArray(this.state.value)) { // For many relationships, append the new item to the end const values = this.state.value.map((item) => item.id); values.push(item.id); this.valueChanged(values.join(',')); } else { this.valueChanged(item.id); } // NOTE: this seems like the wrong way to add options to the Select this.loadOptionsCallback(null, { complete: true, options: Object.keys(this._itemsCache).map((k) => this._itemsCache[k]), }); this.closeCreate(); }, renderSelect (noedit) { return ( <Select.Async multi={this.props.many} disabled={noedit} loadOptions={this.loadOptions} labelKey="name" name={this.getInputName(this.props.path)} onChange={this.valueChanged} simpleValue value={this.state.value} valueKey="id" /> ); }, renderInputGroup () { // TODO: find better solution // when importing the CreateForm using: import CreateForm from '../../../admin/client/App/shared/CreateForm'; // CreateForm was imported as a blank object. This stack overflow post suggested lazilly requiring it: // http://stackoverflow.com/questions/29807664/cyclic-dependency-returns-empty-object-in-react-native // TODO: Implement this somewhere higher in the app, it breaks the encapsulation of the RelationshipField component const CreateForm = require('../../../admin/client/App/shared/CreateForm'); return ( <InputGroup> <InputGroup.Section grow> {this.renderSelect()} </InputGroup.Section> <InputGroup.Section> <Button onClick={this.openCreate} type="success">+</Button> </InputGroup.Section> <CreateForm list={listsByKey[this.props.refList.key]} isOpen={this.state.createIsOpen} onCreate={this.onCreate} onCancel={this.closeCreate} /> </InputGroup> ); }, renderValue () { return this.renderSelect(true); }, renderField () { if (this.props.createInline) { return this.renderInputGroup(); } else { return this.renderSelect(); } }, });
css-modules-demo/demo01/index.js
zhangjunhd/react-examples
import React from 'react'; import ReactDOM from 'react-dom'; import App from './components/App'; ReactDOM.render( <App/>, document.body.appendChild(document.createElement('div')) );
packages/react/components/block.js
AdrianV/Framework7
import React from 'react'; import Utils from '../utils/utils'; import Mixins from '../utils/mixins'; import __reactComponentEl from '../runtime-helpers/react-component-el.js'; import __reactComponentDispatchEvent from '../runtime-helpers/react-component-dispatch-event.js'; import __reactComponentSlots from '../runtime-helpers/react-component-slots.js'; import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js'; class F7Block extends React.Component { constructor(props, context) { super(props, context); } onTabShow(e) { this.dispatchEvent('tabShow tab:show', e); } onTabHide(e) { this.dispatchEvent('tabHide tab:hide', e); } render() { const self = this; const props = self.props; const { className, inset, strong, accordionList, tabletInset, tabs, tab, tabActive, noHairlines, noHairlinesIos, noHairlinesMd, id, style } = props; const classes = Utils.classNames(className, 'block', { inset, 'block-strong': strong, 'accordion-list': accordionList, 'tablet-inset': tabletInset, tabs, tab, 'tab-active': tabActive, 'no-hairlines': noHairlines, 'no-hairlines-md': noHairlinesMd, 'no-hairlines-ios': noHairlinesIos }, Mixins.colorClasses(props)); return React.createElement('div', { id: id, style: style, className: classes }, this.slots['default']); } componentWillUnmount() { const el = this.el; if (!el) return; el.removeEventListener('tab:show', this.onTabShowBound); el.removeEventListener('tab:hide', this.onTabHideBound); } componentDidMount() { const el = this.el; if (!el) return; this.onTabShowBound = this.onTabShow.bind(this); this.onTabHideBound = this.onTabHide.bind(this); el.addEventListener('tab:show', this.onTabShowBound); el.addEventListener('tab:hide', this.onTabHideBound); } get slots() { return __reactComponentSlots(this.props); } get el() { return __reactComponentEl(this); } dispatchEvent(events, ...args) { return __reactComponentDispatchEvent(this, events, ...args); } } __reactComponentSetProps(F7Block, Object.assign({ id: [String, Number], inset: Boolean, tabletInset: Boolean, strong: Boolean, tabs: Boolean, tab: Boolean, tabActive: Boolean, accordionList: Boolean, noHairlines: Boolean, noHairlinesMd: Boolean, noHairlinesIos: Boolean }, Mixins.colorProps)); F7Block.displayName = 'f7-block'; export default F7Block;
src/native/todos/Todos.js
skallet/este
// @flow import type { State, Todo } from '../../common/types'; import Checkbox from './Checkbox'; import Footer from './Footer'; import React from 'react'; import todosMessages from '../../common/todos/todosMessages'; import { Box, Text, TextInput } from '../../common/components'; import { FormattedMessage } from 'react-intl'; import { Image, ScrollView, StyleSheet } from 'react-native'; import { compose, isEmpty, prop, reverse, sortBy, values } from 'ramda'; import { connect } from 'react-redux'; import { toggleTodoCompleted } from '../../common/todos/actions'; type TodoItemProps = { todo: Todo, toggleTodoCompleted: typeof toggleTodoCompleted, }; const TodoItem = ({ todo, toggleTodoCompleted, }: TodoItemProps) => ( <Box borderBottomWidth={1} flexDirection="row" flexWrap="nowrap" height={2} style={theme => ({ borderBottomColor: theme.colors.open.gray3, borderBottomWidth: StyleSheet.hairlineWidth, })} > <Checkbox alignItems="center" checked={todo.completed} height={2} marginVertical={0} onPress={() => toggleTodoCompleted(todo)} width={2} /> <TextInput editable={false} flex={1} height={2} marginHorizontal={0.5} value={todo.title} /> </Box> ); const IsEmpty = () => ( <Box alignItems="center" justifyContent="center" flex={1}> <Image source={require('./img/EmptyState.png')} /> <FormattedMessage {...todosMessages.empty}> {message => <Text bold color="gray" marginTop={1} size={1} >{message}</Text> } </FormattedMessage> </Box> ); type TodosProps = { todos: Array<Todo>, toggleTodoCompleted: typeof toggleTodoCompleted, }; const Todos = ({ todos, toggleTodoCompleted, }: TodosProps) => { if (isEmpty(todos)) { return <IsEmpty />; } const sortedTodos = compose( reverse, sortBy(prop('createdAt')), values, // object values to array )(todos); return ( <ScrollView> {sortedTodos.map(todo => <TodoItem todo={todo} toggleTodoCompleted={toggleTodoCompleted} key={todo.id} />, )} <Footer /> </ScrollView> ); }; export default connect( (state: State) => ({ todos: state.todos.all, }), { toggleTodoCompleted }, )(Todos);
src/components/Start/Start.js
foglerek/yn-mafia
import React from 'react' import { IndexLink, Link } from 'react-router' // import classes from './Start.scss' import { FormGroup, FormControl, ControlLabel, ButtonToolbar, Button } from 'react-bootstrap'; import { connect } from 'react-redux'; import { addUser } from '../../redux/modules/UserActions'; import { bindActionCreators } from 'redux'; import io from 'socket.io-client'; const Start = React.createClass({ getInitialState() { return { name: '' }; }, addUser() { console.log(this.state.name); this.socket.emit('JOIN_GAME', { name: this.state.name }); }, handleNameChange(e) { this.setState({name: e.target.value}); }, componentWillMount() { this.socket = io('http://localhost:3000'); this.socket.on('state', (state) => { console.log('state', state); }); }, render() { return (<div> <FormGroup> <FormControl type="text" placeholder="Pick a name" onChange={this.handleNameChange} /> </FormGroup> <Button onClick={this.addUser} bsStyle="primary">Join Game</Button> </div>); } }); function mapDispatchToProps(dispatch) { return { ...bindActionCreators({ addUser }), dispatch }; } export default connect(null, mapDispatchToProps)(Start);
app/components/Header/index.js
gihrig/react-boilerplate
import React from 'react'; import { FormattedMessage } from 'react-intl'; import A from './A'; import Img from './Img'; import NavBar from './NavBar'; import HeaderLink from './HeaderLink'; import Banner from './banner.jpg'; import messages from './messages'; class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <A href="https://twitter.com/mxstbr"> <Img src={Banner} alt="react-boilerplate - Logo" /> </A> <NavBar> <HeaderLink to="/"> <FormattedMessage {...messages.home} /> </HeaderLink> <HeaderLink to="/features"> <FormattedMessage {...messages.features} /> </HeaderLink> </NavBar> </div> ); } } export default Header;
src/svg-icons/communication/stay-current-landscape.js
frnk94/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let CommunicationStayCurrentLandscape = (props) => ( <SvgIcon {...props}> <path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/> </SvgIcon> ); CommunicationStayCurrentLandscape = pure(CommunicationStayCurrentLandscape); CommunicationStayCurrentLandscape.displayName = 'CommunicationStayCurrentLandscape'; CommunicationStayCurrentLandscape.muiName = 'SvgIcon'; export default CommunicationStayCurrentLandscape;
src/svg-icons/image/filter-tilt-shift.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageFilterTiltShift = (props) => ( <SvgIcon {...props}> <path d="M11 4.07V2.05c-2.01.2-3.84 1-5.32 2.21L7.1 5.69c1.11-.86 2.44-1.44 3.9-1.62zm7.32.19C16.84 3.05 15.01 2.25 13 2.05v2.02c1.46.18 2.79.76 3.9 1.62l1.42-1.43zM19.93 11h2.02c-.2-2.01-1-3.84-2.21-5.32L18.31 7.1c.86 1.11 1.44 2.44 1.62 3.9zM5.69 7.1L4.26 5.68C3.05 7.16 2.25 8.99 2.05 11h2.02c.18-1.46.76-2.79 1.62-3.9zM4.07 13H2.05c.2 2.01 1 3.84 2.21 5.32l1.43-1.43c-.86-1.1-1.44-2.43-1.62-3.89zM15 12c0-1.66-1.34-3-3-3s-3 1.34-3 3 1.34 3 3 3 3-1.34 3-3zm3.31 4.9l1.43 1.43c1.21-1.48 2.01-3.32 2.21-5.32h-2.02c-.18 1.45-.76 2.78-1.62 3.89zM13 19.93v2.02c2.01-.2 3.84-1 5.32-2.21l-1.43-1.43c-1.1.86-2.43 1.44-3.89 1.62zm-7.32-.19C7.16 20.95 9 21.75 11 21.95v-2.02c-1.46-.18-2.79-.76-3.9-1.62l-1.42 1.43z"/> </SvgIcon> ); ImageFilterTiltShift = pure(ImageFilterTiltShift); ImageFilterTiltShift.displayName = 'ImageFilterTiltShift'; ImageFilterTiltShift.muiName = 'SvgIcon'; export default ImageFilterTiltShift;
web/src/viewer/DateLabel.js
bolddp/pixerva
import React, { Component } from 'react'; export default class DateLabel extends Component { toDate(timestamp) { return new Date(timestamp * 1000).toISOString().substring(0,10); } render() { return ( this.props.dateTaken ? ( <label id="imageDate" style={{ fontSize: '20px', float: 'right' }}> {this.toDate(this.props.dateTaken)} </label> ) : null ); } }
packages/showcase/axes/custom-axes-orientation.js
uber/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 { XYPlot, XAxis, YAxis, HorizontalGridLines, VerticalGridLines, LineSeries } from 'react-vis'; export default function Example() { return ( <XYPlot margin={{top: 40, right: 40, left: 10, bottom: 10}} width={300} height={300} > <HorizontalGridLines /> <VerticalGridLines /> <XAxis orientation="top" title="X Axis" /> <YAxis orientation="right" title="Y Axis" /> <LineSeries data={[ {x: 1, y: 3, z: 10}, {x: 2, y: 4, z: 10}, {x: 3, y: 8, z: 10}, {x: 4, y: 11, z: 10} ]} /> <LineSeries data={null} /> <LineSeries data={[ {x: 1, y: 3, z: 10}, {x: 2, y: 9, z: 10}, {x: 3, y: 2, z: 10}, {x: 4, y: 11, z: 10} ]} /> </XYPlot> ); }
app/src/index.js
grantrules/bikeindustryjobs
import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; import registerServiceWorker from './registerServiceWorker'; ReactDOM.render(<App />, document.getElementById('root')); registerServiceWorker();
src/common/components/Routes.js
suttonj/topshelf
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import App from './App'; import LoginPage from '../../pages/login/page'; import HomePage from '../../pages/home/page'; import TopicPage from '../../pages/topic/page'; import BookListPage from '../../pages/booklist/page'; export default ( <Route path="/" component={App}> <IndexRoute component={HomePage} /> <Route path="/topic/:id" component={TopicPage} /> <Route path="/booklist/:id" component={BookListPage} /> </Route> ); // <Route path="/" component={App}> // <IndexRoute component={LoginPage} /> // <Route path="home" component={HomePage} /> // </Route>
node_modules/semantic-ui-react/src/views/Item/ItemImage.js
mowbell/clickdelivery-fed-test
import React from 'react' import { createShorthandFactory, getUnhandledProps, META, } from '../../lib' import Image from '../../elements/Image' /** * An item can contain an image. */ function ItemImage(props) { const { size } = props const rest = getUnhandledProps(ItemImage, props) return <Image {...rest} size={size} ui={!!size} wrapped /> } ItemImage._meta = { name: 'ItemImage', parent: 'Item', type: META.TYPES.VIEW, } ItemImage.propTypes = { /** An image may appear at different sizes. */ size: Image.propTypes.size, } ItemImage.create = createShorthandFactory(ItemImage, src => ({ src })) export default ItemImage
analysis/warriorarms/src/modules/core/Execute/EarlyDotRefresh.js
anom0ly/WoWAnalyzer
import { t } from '@lingui/macro'; import { formatPercentage } from 'common/format'; import SPELLS from 'common/SPELLS'; import { SpellLink } from 'interface'; import React from 'react'; import EarlyDotRefreshesCore from './EarlyDotRefreshes'; const MINOR_THRESHOLD = 0.9; const AVERAGE_THRESHOLD = 0.8; const MAJOR_THRESHOLD = 0.6; class EarlyDotRefresh extends EarlyDotRefreshesCore { get suggestionThresholdsDeepwoundsEfficiency() { return this.makeSuggestionThresholds( SPELLS.MORTAL_STRIKE, MINOR_THRESHOLD, AVERAGE_THRESHOLD, MAJOR_THRESHOLD, ); } static dots = [ { name: 'Deepwounds', debuffId: SPELLS.MASTERY_DEEP_WOUNDS_DEBUFF.id, castId: SPELLS.MORTAL_STRIKE.id, duration: 12000, }, ]; // Checks the status of the last cast and marks it accordingly. getLastBadCastText(event, dot) { return super.getLastBadCastText(event, dot); } suggestions(when) { when(this.suggestionThresholdsDeepwoundsEfficiency).addSuggestion( (suggest, actual, recommended) => suggest( <> You refreshed <SpellLink id={SPELLS.MASTERY_DEEP_WOUNDS_DEBUFF.id} icon /> early{' '} {this.suggestionThresholdsDeepwoundsEfficiency.count} times on a target in{' '} <SpellLink id={SPELLS.EXECUTE.id} icon /> range. Try to prioritize{' '} <SpellLink id={SPELLS.EXECUTE.id} icon /> as it deals more damage than{' '} <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon />. </>, ) .icon(SPELLS.MASTERY_DEEP_WOUNDS_DEBUFF.icon) .actual( t({ id: 'shared.suggestions.dots.badRefreshes', message: `${formatPercentage(actual)}% bad dot refreshes.`, }), ) .recommended(`<${formatPercentage(recommended)}% is recommended`), ); } } export default EarlyDotRefresh;
src/pages/organize/list.js
yiweimatou/admin-antd
import React, { Component } from 'react'; import { Table, message, Button } from 'antd' import { Link } from 'react-router' import { info, list } from 'services/organize' import SearchInput from '../../components/SearchInput' class OrganizeList extends Component { constructor(props) { super(props) this.state = { title: '', total: 0, current: 1, dataSource: [], loading: false } } componentWillMount() { this.getInfo() } getInfo = () => { info({ title: this.state.title }).then((data) => { if (data.count === 0) { this.setState({ total: data.count, dataSource: [] }) } else { this.setState({ total: data.count, current: 1 }) this.getList(1) } }).catch(error => message.error(error)) } getList = (offset) => { this.setState({ loading: true, current: offset }) list({ title: this.state.title, offset, limit: 6 }).then((data) => { this.setState({ loading: false, dataSource: data.list }) }).catch((error) => { this.setState({ loading: false }) message.error(error) }) } render() { const { loading, dataSource, total, current } = this.state const pagination = { total, current, showTotal: num => `共${num}条`, pageSize: 6, onChange: this.getList } const columns = [{ title: '机构名称', dataIndex: 'title', key: 'title' }, { title: '创建时间', dataIndex: 'add_ms', key: 'add_ms', render: text => (new Date(text * 1000)).toLocaleString() }, { title: '操作', key: 'operate', render: (text, record) => <Button><Link to={`/organize/edit/${record.id}`}>编辑</Link></Button> }] return ( <div> <SearchInput placeholder="机构名称" onSearch={(value) => { Promise.resolve(this.setState({ title: value })) .then(this.getInfo) }} style={{ width: 200, marginBottom: 20 }} /> <Button style={{ float: 'right' }} type="primary"><Link to="/organize/add">添加机构</Link></Button> <Table columns={columns} loading={loading} pagination={pagination} dataSource={dataSource} /> </div> ); } } export default OrganizeList;
src/client/js/components/App.js
dstaver/greedy-alligator
import React, { Component } from 'react'; import Header from '../containers/Header'; export default class App extends Component { render() { return ( <div> <Header /> {this.props.children} </div> ); } }
lib/codemod/src/transforms/__testfixtures__/storiesof-to-csf/story-parameters.input.js
storybooks/react-storybook
/* eslint-disable */ import React from 'react'; import Button from './Button'; import { storiesOf } from '@storybook/react'; storiesOf('Button', module) .add('with story parameters', () => <Button label="The Button" />, { header: false, inline: true, }) .add('foo', () => <Button label="Foo" />, { bar: 1, });
app/src/chart/chart.js
tmlewallen/PongPing
import React from 'react'; import 'whatwg-fetch'; import d3 from './d3'; import moment from 'moment'; import * as _ from 'lodash'; export default class Chart extends React.Component { constructor() { super(); this.state = { data: [], maxPoints : 1000, pollPeriod : 5, timeWindow : 10 }; this.getPongStats(moment().subtract(this.state.timeWindow,'minutes')); this.pollPongStats(this.state.pollPeriod * 1000); } componentDidMount() { this.svg = d3.select('.chart'); d3.select(window).on('resize', this.rebuildChart.bind(this)); this.svg.append('g') .attr('class', 'path-container') .append('path'); this.svg.append('g') .attr('class', 'x-axis'); this.svg.append('g') .attr('class', 'y-axis'); this.rebuildChart(); } rebuildChart() { console.info(`Num of Points : ${this.state.data.length}`) let width = Number.parseFloat(_.trim(this.svg.style('width'), 'px')); let height = Number.parseFloat(_.trim(this.svg.style('height'), 'px')); let paddingRight = Number.parseFloat(_.trim(this.svg.style('padding-right'), 'px')); let paddingLeft = Number.parseFloat(_.trim(this.svg.style('padding-left'), 'px')); let paddingTop = Number.parseFloat(_.trim(this.svg.style('padding-top'), 'px')); let paddingBottom = Number.parseFloat(_.trim(this.svg.style('padding-bottom'), 'px')); width = width - paddingRight - paddingLeft; height = height - paddingTop - paddingBottom; let timeFormat = d3.timeFormat('%b %d %I:%M:%S %p') let x = d3.scaleLinear() .domain([d3.min(this.state.data, (d) => d.timestamp * 1000), d3.max(this.state.data, (d) => d.timestamp * 1000)]) .range([0, width]); let y = d3.scaleLinear() .domain([d3.min(this.state.data, (d) => d.delta), d3.max(this.state.data, (d) => d.delta)]) .range([height - 20, 0]); let graph = d3.line() .x((d) => x(new Date(d.timestamp * 1000))) .y((d) => y(d.delta)); let xAxis = d3.axisBottom(x) .ticks(this.state.timeWindow * 5) .tickSizeInner(-height) .tickFormat(timeFormat); // .tickPadding(5); let yAxis = d3.axisLeft(y) .tickSizeInner(-width) .tickPadding(5); let p = this.svg.select('path') .datum(this.state.data) .attr('stroke', '#F96302') .attr('stroke-width', 1) .attr('fill', 'none'); // .transition() if (this.state.data.length < this.state.maxPoints){ p = p.transition(); } p.attr('d', graph); this.svg.select('.x-axis') .attr('transform', 'translate(0,' + (height - 20) + ')') .call(xAxis) .selectAll('text') .attr("transform", "rotate(-45)") .style("text-anchor", "end"); this.svg.select('.y-axis') .call(yAxis); } getPongStats(d) { let dt = d ? d : moment().subtract(this.state.timeWindow, 'minutes'); console.log(dt.format()); fetch(`./data/list/${dt.format()}`).then((response) => { response.json().then((d) => { this.state.data = d; // let newSize = this.state.data.length + d.length; // if (this.state.data.length === 0 && d.length > this.state.maxPoints){ // d = d.splice(d.length - this.state.maxPoints); // } // else if (newSize > this.state.maxPoints){ // this.state.data = this.state.data.splice(newSize - this.state.maxPoints); // } // d.forEach( (el) => { // this.state.data.push(el); // }); this.rebuildChart(); }); }).catch((err) => { console.error(err); }); } pollPongStats(period) { setTimeout(() => { this.getPongStats(); this.pollPongStats(period); }, period); } render() { return ( <div id="chart-container" className="col-md-12"> <svg className="chart"/> </div> ); } }
test/PageItemSpec.js
jakubsikora/react-bootstrap
import React from 'react'; import ReactTestUtils from 'react/lib/ReactTestUtils'; import PageItem from '../src/PageItem'; describe('PageItem', function () { it('Should output a "list item" as root element, and an "anchor" as a child item', function () { let instance = ReactTestUtils.renderIntoDocument( <PageItem href="#">Text</PageItem> ); let node = React.findDOMNode(instance); assert.equal(node.nodeName, 'LI'); assert.equal(node.children.length, 1); assert.equal(node.children[0].nodeName, 'A'); }); it('Should output "disabled" attribute as a class', function () { let instance = ReactTestUtils.renderIntoDocument( <PageItem disabled href="#">Text</PageItem> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'disabled')); }); it('Should output "next" attribute as a class', function () { let instance = ReactTestUtils.renderIntoDocument( <PageItem previous href="#">Previous</PageItem> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'previous')); }); it('Should output "previous" attribute as a class', function () { let instance = ReactTestUtils.renderIntoDocument( <PageItem next href="#">Next</PageItem> ); assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'next')); }); it('Should call "onSelect" when item is clicked', function (done) { function handleSelect(key, href) { assert.equal(key, 1); assert.equal(href, undefined); done(); } let instance = ReactTestUtils.renderIntoDocument( <PageItem eventKey={1} onSelect={handleSelect}>Next</PageItem> ); ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a')); }); it('Should not call "onSelect" when item disabled and is clicked', function () { function handleSelect() { throw new Error('onSelect should not be called'); } let instance = ReactTestUtils.renderIntoDocument( <PageItem disabled onSelect={handleSelect}>Next</PageItem> ); ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a')); }); it('Should set target attribute on anchor', function () { let instance = ReactTestUtils.renderIntoDocument( <PageItem next href="#" target="_blank">Next</PageItem> ); let anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a'); assert.equal(React.findDOMNode(anchor).getAttribute('target'), '_blank'); }); it('Should call "onSelect" with target attribute', function (done) { function handleSelect(key, href, target) { assert.equal(target, '_blank'); done(); } let instance = ReactTestUtils.renderIntoDocument( <PageItem eventKey={1} onSelect={handleSelect} target="_blank">Next</PageItem> ); ReactTestUtils.Simulate.click(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a')); }); });
src/js/components/icons/base/Multiple.js
kylebyerly-hp/grommet
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP import React, { Component } from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import CSSClassnames from '../../../utils/CSSClassnames'; import Intl from '../../../utils/Intl'; import Props from '../../../utils/Props'; const CLASS_ROOT = CSSClassnames.CONTROL_ICON; const COLOR_INDEX = CSSClassnames.COLOR_INDEX; export default class Icon extends Component { render () { const { className, colorIndex } = this.props; let { a11yTitle, size, responsive } = this.props; let { intl } = this.context; const classes = classnames( CLASS_ROOT, `${CLASS_ROOT}-multiple`, className, { [`${CLASS_ROOT}--${size}`]: size, [`${CLASS_ROOT}--responsive`]: responsive, [`${COLOR_INDEX}-${colorIndex}`]: colorIndex } ); a11yTitle = a11yTitle || Intl.getMessage(intl, 'multiple'); const restProps = Props.omit(this.props, Object.keys(Icon.propTypes)); return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M19,15 L23,15 L23,1 L9,1 L9,5 M15,19 L19,19 L19,5 L5,5 L5,9 M1,23 L15,23 L15,9 L1,9 L1,23 L1,23 L1,23 Z"/></svg>; } }; Icon.contextTypes = { intl: PropTypes.object }; Icon.defaultProps = { responsive: true }; Icon.displayName = 'Multiple'; Icon.icon = true; Icon.propTypes = { a11yTitle: PropTypes.string, colorIndex: PropTypes.string, size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']), responsive: PropTypes.bool };
src/Components/Header/index.js
gabriel-lopez-lopez/gll-billin-code-challenge
/** * Componente cabecera principal de navegación de la aplicación * */ import React, { Component } from 'react'; import { Link, withRouter } from 'react-router-dom'; import { connect } from 'react-redux'; // Logo import image from '../../assets/images/logo-billin.png'; // Estilos personalizados import './navbar.less'; // Exportar y utilizar el nombre de la clase no conectada para los tests export class Header extends Component { constructor(props) { super(props); this.handleHome = this.handleHome.bind(this); this.handleActive = this.handleActive.bind(this); this.clearActiveMenu = this.clearActiveMenu.bind(this); } /** * Limpia los estilos de las opciones del menú de la aplicación */ clearActiveMenu () { document.getElementById('header-navbar-collapse').childNodes[0].childNodes.forEach(li => { li.classList.remove('active'); }); } /** * Va a la página principal de la aplicación previa limpieza de estilos del menú */ handleHome () { this.clearActiveMenu(); this.props.history.push('/'); } /** * Marca la opción de menú seleccionada * @param {Event} e Evento */ handleActive (e) { // Si no se recibe el evento if (e === undefined) { // Ruta actual let pathname = this.props.history.location.pathname; if (document.getElementById('header-navbar-collapse')) { // Elementos LI del menú principal de la aplicación document.getElementById('header-navbar-collapse').childNodes[0].childNodes.forEach(function (elem) { // Se restablecen las clases del elemento LI elem.classList.remove('active'); // Se itera por los nodos que puede tener el elemento elem.childNodes.forEach(function (node) { // Si el nodo es un enlace y su valor de enlace es igual que la ruta actual // se le agrega la clase "active" al elemento LI if (node.tagName === 'A' && pathname.indexOf(node.attributes.href.value) !== -1) { node.parentNode.className = 'active'; } }); }); } return; } // Antes se eliminan estilos previos this.clearActiveMenu(); // Se marca la opción con el estilo e.currentTarget.parentNode.classList.add('active'); } // Cuando el componente ha sido montado componentDidMount () { // this.selectOptionMenu(); this.handleActive(); } // Cuando el componente se actualiza componentDidUpdate () { // this.selectOptionMenu(); this.handleActive(); } render () { return ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="container-fluid"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#header-navbar-collapse" aria-expanded="false"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <img src={image} alt="Billin code-challenge" onClick={ this.handleHome } /> <Link to='/' onClick={ this.clearActiveMenu } className="navbar-brand"> code-challenge </Link> </div> <div className="collapse navbar-collapse" id="header-navbar-collapse"> <ul className="nav navbar-nav navbar-right"> <li> <Link to='/authors' onClick={ this.handleActive }>Autores</Link> </li> <li> <Link to='/articles' onClick={ this.handleActive }>Artículos</Link> </li> </ul> </div> </div> </nav> ); } } const mapStateToProps = null; const mapDispatchToProps = null; /** * Para poder navegar desde el código react-router-dom * ofrece un decorador withRouter() para envolver cualquier * componente en el árbol del router (al estilo connect() de Redux), * es decir, cualquier componente que sea hijo de alguno de los que * se están pintando como parte de la ruta. * Va a inyectar como prop un objeto router con métodos al componente que está envolviendo. */ // Utilizar la exportación predeterminada para el componente conectado pra la aplicación export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Header));
test/unit/lib/static/components/error-boundary.js
gemini-testing/html-reporter
import React from 'react'; import ErrorBoundary from 'lib/static/components/error-boundary'; describe('<ErrorBoundary />', () => { const sandbox = sinon.sandbox.create(); beforeEach(() => { sandbox.stub(console, 'error'); }); afterEach(() => sandbox.restore()); it('should render child component if it is ok', () => { const component = mount(<ErrorBoundary>ok text</ErrorBoundary>); const textContent = component.text(); assert.equal(textContent, 'ok text'); }); it('should render nothing when child component fails and no fallback provided', () => { const FailingComponent = function() { throw new Error('Failed functional component.'); }; const component = mount( <ErrorBoundary> <FailingComponent/> </ErrorBoundary> ); const textContent = component.text(); assert.equal(textContent, ''); }); it('should render fallback component on child component fail when specified', () => { const FailingComponent = function() { throw new Error('Failed functional component.'); }; const component = mount( <ErrorBoundary fallback='fallback text'> <FailingComponent/> ignored text </ErrorBoundary> ); const textContent = component.text(); assert.equal(textContent, 'fallback text'); }); });
node_modules/react-router/es6/Link.js
jwilkinson/tiff16-films
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; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object]).isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; !this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(location); }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(location); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(location, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
client/test/components/homePage/Footer.spec.js
EricDav/PostIt
import React from 'react'; import { shallow } from 'enzyme'; import expect from 'expect'; import Footer from '../../../components/Footer.jsx'; describe('Footer Component', () => { it('should render footer component', () => { const wrapper = shallow(<Footer/>); expect(wrapper.node.props.className) .toEqual('page-footer purple darken-1 footer'); expect(wrapper.node.props.children.props.className) .toEqual('footer-copyright'); expect(wrapper.node.type).toEqual('footer'); }); });
fixtures/attribute-behavior/src/App.js
aickin/react
import React from 'react'; import {createElement} from 'glamor/react'; // eslint-disable-line /* @jsx createElement */ import {MultiGrid, AutoSizer} from 'react-virtualized'; import 'react-virtualized/styles.css'; import FileSaver from 'file-saver'; import { inject as injectErrorOverlay, uninject as uninjectErrorOverlay, } from 'react-error-overlay/lib/overlay'; import attributes from './attributes'; const types = [ { name: 'string', testValue: 'a string', testDisplayValue: "'a string'", }, { name: 'empty string', testValue: '', testDisplayValue: "''", }, { name: 'array with string', testValue: ['string'], testDisplayValue: "['string']", }, { name: 'empty array', testValue: [], testDisplayValue: '[]', }, { name: 'object', testValue: { toString() { return 'result of toString()'; }, }, testDisplayValue: "{ toString() { return 'result of toString()'; } }", }, { name: 'numeric string', testValue: '42', displayValue: "'42'", }, { name: '-1', testValue: -1, }, { name: '0', testValue: 0, }, { name: 'integer', testValue: 1, }, { name: 'NaN', testValue: NaN, }, { name: 'float', testValue: 99.99, }, { name: 'true', testValue: true, }, { name: 'false', testValue: false, }, { name: "string 'true'", testValue: 'true', displayValue: "'true'", }, { name: "string 'false'", testValue: 'false', displayValue: "'false'", }, { name: "string 'on'", testValue: 'on', displayValue: "'on'", }, { name: "string 'off'", testValue: 'off', displayValue: "'off'", }, { name: 'symbol', testValue: Symbol('foo'), testDisplayValue: "Symbol('foo')", }, { name: 'function', testValue: function f() {}, }, { name: 'null', testValue: null, }, { name: 'undefined', testValue: undefined, }, ]; const ALPHABETICAL = 'alphabetical'; const REV_ALPHABETICAL = 'reverse_alphabetical'; const GROUPED_BY_ROW_PATTERN = 'grouped_by_row_pattern'; const ALL = 'all'; const COMPLETE = 'complete'; const INCOMPLETE = 'incomplete'; function getCanonicalizedValue(value) { switch (typeof value) { case 'undefined': return '<undefined>'; case 'object': if (value === null) { return '<null>'; } if ('baseVal' in value) { return getCanonicalizedValue(value.baseVal); } if (value instanceof SVGLength) { return '<SVGLength: ' + value.valueAsString + '>'; } if (value instanceof SVGRect) { return ( '<SVGRect: ' + [value.x, value.y, value.width, value.height].join(',') + '>' ); } if (value instanceof SVGPreserveAspectRatio) { return ( '<SVGPreserveAspectRatio: ' + value.align + '/' + value.meetOrSlice + '>' ); } if (value instanceof SVGNumber) { return value.value; } if (value instanceof SVGMatrix) { return ( '<SVGMatrix ' + value.a + ' ' + value.b + ' ' + value.c + ' ' + value.d + ' ' + value.e + ' ' + value.f + '>' ); } if (value instanceof SVGTransform) { return ( getCanonicalizedValue(value.matrix) + '/' + value.type + '/' + value.angle ); } if (typeof value.length === 'number') { return ( '[' + Array.from(value) .map(v => getCanonicalizedValue(v)) .join(', ') + ']' ); } let name = (value.constructor && value.constructor.name) || 'object'; return '<' + name + '>'; case 'function': return '<function>'; case 'symbol': return '<symbol>'; case 'number': return `<number: ${value}>`; case 'string': if (value === '') { return '<empty string>'; } return '"' + value + '"'; case 'boolean': return `<boolean: ${value}>`; default: throw new Error('Switch statement should be exhaustive.'); } } let _didWarn = false; function warn(str) { _didWarn = true; } const UNKNOWN_HTML_TAGS = new Set(['keygen', 'time', 'command']); function getRenderedAttributeValue( react, renderer, serverRenderer, attribute, type ) { const originalConsoleError = console.error; console.error = warn; const containerTagName = attribute.containerTagName || 'div'; const tagName = attribute.tagName || 'div'; function createContainer() { if (containerTagName === 'svg') { return document.createElementNS('http://www.w3.org/2000/svg', 'svg'); } else if (containerTagName === 'document') { return document.implementation.createHTMLDocument(''); } else { return document.createElement(containerTagName); } } const read = attribute.read; let testValue = type.testValue; if (attribute.overrideStringValue !== undefined) { switch (type.name) { case 'string': testValue = attribute.overrideStringValue; break; case 'array with string': testValue = [attribute.overrideStringValue]; break; default: break; } } let baseProps = { ...attribute.extraProps, }; if (attribute.type) { baseProps.type = attribute.type; } const props = { ...baseProps, [attribute.name]: testValue, }; let defaultValue; let canonicalDefaultValue; let result; let canonicalResult; let ssrResult; let canonicalSsrResult; let didWarn; let didError; let ssrDidWarn; let ssrDidError; _didWarn = false; try { let container = createContainer(); renderer.render(react.createElement(tagName, baseProps), container); defaultValue = read(container.firstChild); canonicalDefaultValue = getCanonicalizedValue(defaultValue); container = createContainer(); renderer.render(react.createElement(tagName, props), container); result = read(container.firstChild); canonicalResult = getCanonicalizedValue(result); didWarn = _didWarn; didError = false; } catch (error) { result = null; didWarn = _didWarn; didError = true; } _didWarn = false; let hasTagMismatch = false; let hasUnknownElement = false; try { let container; if (containerTagName === 'document') { const html = serverRenderer.renderToString( react.createElement(tagName, props) ); container = createContainer(); container.innerHTML = html; } else { const html = serverRenderer.renderToString( react.createElement( containerTagName, null, react.createElement(tagName, props) ) ); const outerContainer = document.createElement('div'); outerContainer.innerHTML = html; container = outerContainer.firstChild; } if ( !container.lastChild || container.lastChild.tagName.toLowerCase() !== tagName.toLowerCase() ) { hasTagMismatch = true; } if ( container.lastChild instanceof HTMLUnknownElement && !UNKNOWN_HTML_TAGS.has(container.lastChild.tagName.toLowerCase()) ) { hasUnknownElement = true; } ssrResult = read(container.lastChild); canonicalSsrResult = getCanonicalizedValue(ssrResult); ssrDidWarn = _didWarn; ssrDidError = false; } catch (error) { ssrResult = null; ssrDidWarn = _didWarn; ssrDidError = true; } console.error = originalConsoleError; if (hasTagMismatch) { throw new Error('Tag mismatch. Expected: ' + tagName); } if (hasUnknownElement) { throw new Error('Unexpected unknown element: ' + tagName); } let ssrHasSameBehavior; let ssrHasSameBehaviorExceptWarnings; if (didError && ssrDidError) { ssrHasSameBehavior = true; } else if (!didError && !ssrDidError) { if (canonicalResult === canonicalSsrResult) { ssrHasSameBehaviorExceptWarnings = true; ssrHasSameBehavior = didWarn === ssrDidWarn; } ssrHasSameBehavior = didWarn === ssrDidWarn && canonicalResult === canonicalSsrResult; } else { ssrHasSameBehavior = false; } return { tagName, containerTagName, testValue, defaultValue, result, canonicalResult, canonicalDefaultValue, didWarn, didError, ssrResult, canonicalSsrResult, ssrDidWarn, ssrDidError, ssrHasSameBehavior, ssrHasSameBehaviorExceptWarnings, }; } function prepareState(initGlobals) { function getRenderedAttributeValues(attribute, type) { const { ReactStable, ReactDOMStable, ReactDOMServerStable, ReactNext, ReactDOMNext, ReactDOMServerNext, } = initGlobals(attribute, type); const reactStableValue = getRenderedAttributeValue( ReactStable, ReactDOMStable, ReactDOMServerStable, attribute, type ); const reactNextValue = getRenderedAttributeValue( ReactNext, ReactDOMNext, ReactDOMServerNext, attribute, type ); let hasSameBehavior; if (reactStableValue.didError && reactNextValue.didError) { hasSameBehavior = true; } else if (!reactStableValue.didError && !reactNextValue.didError) { hasSameBehavior = reactStableValue.didWarn === reactNextValue.didWarn && reactStableValue.canonicalResult === reactNextValue.canonicalResult && reactStableValue.ssrHasSameBehavior === reactNextValue.ssrHasSameBehavior; } else { hasSameBehavior = false; } return { reactStable: reactStableValue, reactNext: reactNextValue, hasSameBehavior, }; } const table = new Map(); const rowPatternHashes = new Map(); // Disable error overlay while testing each attribute uninjectErrorOverlay(); for (let attribute of attributes) { const results = new Map(); let hasSameBehaviorForAll = true; let rowPatternHash = ''; for (let type of types) { const result = getRenderedAttributeValues(attribute, type); results.set(type.name, result); if (!result.hasSameBehavior) { hasSameBehaviorForAll = false; } rowPatternHash += [result.reactStable, result.reactNext] .map(res => [ res.canonicalResult, res.canonicalDefaultValue, res.didWarn, res.didError, ].join('||') ) .join('||'); } const row = { results, hasSameBehaviorForAll, rowPatternHash, // "Good enough" id that we can store in localStorage rowIdHash: `${attribute.name} ${attribute.tagName} ${ attribute.overrideStringValue }`, }; const rowGroup = rowPatternHashes.get(rowPatternHash) || new Set(); rowGroup.add(row); rowPatternHashes.set(rowPatternHash, rowGroup); table.set(attribute, row); } // Renable error overlay injectErrorOverlay(); return { table, rowPatternHashes, }; } const successColor = 'white'; const warnColor = 'yellow'; const errorColor = 'red'; function RendererResult({ result, canonicalResult, defaultValue, canonicalDefaultValue, didWarn, didError, ssrHasSameBehavior, ssrHasSameBehaviorExceptWarnings, }) { let backgroundColor; if (didError) { backgroundColor = errorColor; } else if (didWarn) { backgroundColor = warnColor; } else if (canonicalResult !== canonicalDefaultValue) { backgroundColor = 'cyan'; } else { backgroundColor = successColor; } let style = { display: 'flex', alignItems: 'center', position: 'absolute', height: '100%', width: '100%', backgroundColor, }; if (!ssrHasSameBehavior) { const color = ssrHasSameBehaviorExceptWarnings ? 'gray' : 'magenta'; style.border = `3px dotted ${color}`; } return <div css={style}>{canonicalResult}</div>; } function ResultPopover(props) { return ( <pre css={{ padding: '1em', width: '25em', }}> {JSON.stringify( { reactStable: props.reactStable, reactNext: props.reactNext, hasSameBehavior: props.hasSameBehavior, }, null, 2 )} </pre> ); } class Result extends React.Component { state = {showInfo: false}; onMouseEnter = () => { if (this.timeout) { clearTimeout(this.timeout); } this.timeout = setTimeout(() => { this.setState({showInfo: true}); }, 250); }; onMouseLeave = () => { if (this.timeout) { clearTimeout(this.timeout); } this.setState({showInfo: false}); }; componentWillUnmount() { if (this.timeout) { clearTimeout(this.interval); } } render() { const {reactStable, reactNext, hasSameBehavior} = this.props; const style = { position: 'absolute', width: '100%', height: '100%', }; let highlight = null; let popover = null; if (this.state.showInfo) { highlight = ( <div css={{ position: 'absolute', height: '100%', width: '100%', border: '2px solid blue', }} /> ); popover = ( <div css={{ backgroundColor: 'white', border: '1px solid black', position: 'absolute', top: '100%', zIndex: 999, }}> <ResultPopover {...this.props} /> </div> ); } if (!hasSameBehavior) { style.border = '4px solid purple'; } return ( <div css={style} onMouseEnter={this.onMouseEnter} onMouseLeave={this.onMouseLeave}> <div css={{position: 'absolute', width: '50%', height: '100%'}}> <RendererResult {...reactStable} /> </div> <div css={{ position: 'absolute', width: '50%', left: '50%', height: '100%', }}> <RendererResult {...reactNext} /> </div> {highlight} {popover} </div> ); } } function ColumnHeader({children}) { return ( <div css={{ position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: 'center', }}> {children} </div> ); } function RowHeader({children, checked, onChange}) { return ( <div css={{ position: 'absolute', width: '100%', height: '100%', display: 'flex', alignItems: 'center', }}> <input type="checkbox" checked={checked} onChange={onChange} /> {children} </div> ); } function CellContent(props) { const { columnIndex, rowIndex, attributesInSortedOrder, completedHashes, toggleAttribute, table, } = props; const attribute = attributesInSortedOrder[rowIndex - 1]; const type = types[columnIndex - 1]; if (columnIndex === 0) { if (rowIndex === 0) { return null; } const row = table.get(attribute); const rowPatternHash = row.rowPatternHash; return ( <RowHeader checked={completedHashes.has(rowPatternHash)} onChange={() => toggleAttribute(rowPatternHash)}> {row.hasSameBehaviorForAll ? ( attribute.name ) : ( <b css={{color: 'purple'}}>{attribute.name}</b> )} </RowHeader> ); } if (rowIndex === 0) { return <ColumnHeader>{type.name}</ColumnHeader>; } const row = table.get(attribute); const result = row.results.get(type.name); return <Result {...result} />; } function saveToLocalStorage(completedHashes) { const str = JSON.stringify([...completedHashes]); localStorage.setItem('completedHashes', str); } function restoreFromLocalStorage() { const str = localStorage.getItem('completedHashes'); if (str) { const completedHashes = new Set(JSON.parse(str)); return completedHashes; } return new Set(); } const useFastMode = /[?&]fast\b/.test(window.location.href); class App extends React.Component { state = { sortOrder: ALPHABETICAL, filter: ALL, completedHashes: restoreFromLocalStorage(), table: null, rowPatternHashes: null, }; renderCell = props => { return ( <div style={props.style}> <CellContent toggleAttribute={this.toggleAttribute} completedHashes={this.state.completedHashes} table={this.state.table} attributesInSortedOrder={this.attributes} {...props} /> </div> ); }; onUpdateSort = e => { this.setState({sortOrder: e.target.value}); }; onUpdateFilter = e => { this.setState({filter: e.target.value}); }; toggleAttribute = rowPatternHash => { const completedHashes = new Set(this.state.completedHashes); if (completedHashes.has(rowPatternHash)) { completedHashes.delete(rowPatternHash); } else { completedHashes.add(rowPatternHash); } this.setState({completedHashes}, () => saveToLocalStorage(completedHashes)); }; async componentDidMount() { const sources = { ReactStable: 'https://unpkg.com/react@latest/umd/react.development.js', ReactDOMStable: 'https://unpkg.com/react-dom@latest/umd/react-dom.development.js', ReactDOMServerStable: 'https://unpkg.com/react-dom@latest/umd/react-dom-server.browser.development.js', ReactNext: '/react.development.js', ReactDOMNext: '/react-dom.development.js', ReactDOMServerNext: '/react-dom-server.browser.development.js', }; const codePromises = Object.values(sources).map(src => fetch(src).then(res => res.text()) ); const codesByIndex = await Promise.all(codePromises); const pool = []; function initGlobals(attribute, type) { if (useFastMode) { // Note: this is not giving correct results for warnings. // But it's much faster. if (pool[0]) { return pool[0].globals; } } else { document.title = `${attribute.name} (${type.name})`; } // Creating globals for every single test is too slow. // However caching them between runs won't work for the same attribute names // because warnings will be deduplicated. As a result, we only share globals // between different attribute names. for (let i = 0; i < pool.length; i++) { if (!pool[i].testedAttributes.has(attribute.name)) { pool[i].testedAttributes.add(attribute.name); return pool[i].globals; } } let globals = {}; Object.keys(sources).forEach((name, i) => { eval.call(window, codesByIndex[i]); // eslint-disable-line globals[name] = window[name.replace(/Stable|Next/g, '')]; }); // Cache for future use (for different attributes). pool.push({ globals, testedAttributes: new Set([attribute.name]), }); return globals; } const {table, rowPatternHashes} = prepareState(initGlobals); document.title = 'Ready'; this.setState({ table, rowPatternHashes, }); } componentWillUpdate(nextProps, nextState) { if ( nextState.sortOrder !== this.state.sortOrder || nextState.filter !== this.state.filter || nextState.completedHashes !== this.state.completedHashes || nextState.table !== this.state.table ) { this.attributes = this.getAttributes( nextState.table, nextState.rowPatternHashes, nextState.sortOrder, nextState.filter, nextState.completedHashes ); if (this.grid) { this.grid.forceUpdateGrids(); } } } getAttributes(table, rowPatternHashes, sortOrder, filter, completedHashes) { // Filter let filteredAttributes; switch (filter) { case ALL: filteredAttributes = attributes.filter(() => true); break; case COMPLETE: filteredAttributes = attributes.filter(attribute => { const row = table.get(attribute); return completedHashes.has(row.rowPatternHash); }); break; case INCOMPLETE: filteredAttributes = attributes.filter(attribute => { const row = table.get(attribute); return !completedHashes.has(row.rowPatternHash); }); break; default: throw new Error('Switch statement should be exhuastive'); } // Sort switch (sortOrder) { case ALPHABETICAL: return filteredAttributes.sort( (attr1, attr2) => attr1.name.toLowerCase() < attr2.name.toLowerCase() ? -1 : 1 ); case REV_ALPHABETICAL: return filteredAttributes.sort( (attr1, attr2) => attr1.name.toLowerCase() < attr2.name.toLowerCase() ? 1 : -1 ); case GROUPED_BY_ROW_PATTERN: { return filteredAttributes.sort((attr1, attr2) => { const row1 = table.get(attr1); const row2 = table.get(attr2); const patternGroup1 = rowPatternHashes.get(row1.rowPatternHash); const patternGroupSize1 = (patternGroup1 && patternGroup1.size) || 0; const patternGroup2 = rowPatternHashes.get(row2.rowPatternHash); const patternGroupSize2 = (patternGroup2 && patternGroup2.size) || 0; return patternGroupSize2 - patternGroupSize1; }); } default: throw new Error('Switch statement should be exhuastive'); } } handleSaveClick = e => { e.preventDefault(); if (useFastMode) { alert( 'Fast mode is not accurate. Please remove ?fast from the query string, and reload.' ); return; } let log = ''; for (let attribute of attributes) { log += `## \`${attribute.name}\` (on \`<${attribute.tagName || 'div'}>\` inside \`<${attribute.containerTagName || 'div'}>\`)\n`; log += '| Test Case | Flags | Result |\n'; log += '| --- | --- | --- |\n'; const attributeResults = this.state.table.get(attribute).results; for (let type of types) { const { didError, didWarn, canonicalResult, canonicalDefaultValue, ssrDidError, ssrHasSameBehavior, ssrHasSameBehaviorExceptWarnings, } = attributeResults.get(type.name).reactNext; let descriptions = []; if (canonicalResult === canonicalDefaultValue) { descriptions.push('initial'); } else { descriptions.push('changed'); } if (didError) { descriptions.push('error'); } if (didWarn) { descriptions.push('warning'); } if (ssrDidError) { descriptions.push('ssr error'); } if (!ssrHasSameBehavior) { if (ssrHasSameBehaviorExceptWarnings) { descriptions.push('ssr warning'); } else { descriptions.push('ssr mismatch'); } } log += `| \`${attribute.name}=(${type.name})\`` + `| (${descriptions.join(', ')})` + `| \`${canonicalResult || ''}\` |\n`; } log += '\n'; } const blob = new Blob([log], {type: 'text/plain;charset=utf-8'}); FileSaver.saveAs(blob, 'AttributeTableSnapshot.md'); }; render() { if (!this.state.table) { return ( <div> <h1>Loading...</h1> {!useFastMode && ( <h3>The progress is reported in the window title.</h3> )} </div> ); } return ( <div> <div> <select value={this.state.sortOrder} onChange={this.onUpdateSort}> <option value={ALPHABETICAL}>alphabetical</option> <option value={REV_ALPHABETICAL}>reverse alphabetical</option> <option value={GROUPED_BY_ROW_PATTERN}> grouped by row pattern :) </option> </select> <select value={this.state.filter} onChange={this.onUpdateFilter}> <option value={ALL}>all</option> <option value={INCOMPLETE}>incomplete</option> <option value={COMPLETE}>complete</option> </select> <button style={{marginLeft: '10px'}} onClick={this.handleSaveClick}> Save latest results to a file{' '} <span role="img" aria-label="Save"> 💾 </span> </button> </div> <AutoSizer disableHeight={true}> {({width}) => ( <MultiGrid ref={input => { this.grid = input; }} cellRenderer={this.renderCell} columnWidth={200} columnCount={1 + types.length} fixedColumnCount={1} enableFixedColumnScroll={true} enableFixedRowScroll={true} height={1200} rowHeight={40} rowCount={this.attributes.length + 1} fixedRowCount={1} width={width} /> )} </AutoSizer> </div> ); } } export default App;
client/src/app/components/navigation/components/BigBreadcrumbs.js
zraees/sms-project
import React from 'react' import _ from 'lodash' // import NavigationStore from '../stores/NavigationStore' export default class BigBreadcrumbs extends React.Component { // mixins: [Reflux.listenTo(NavigationStore, 'onNavigationChange')], constructor(props) { super(props); this.state = { items: this.props.items || [], icon: this.props.icon || 'fa fa-fw fa-home' } } componentWillMount() { // if(!this.props.items && NavigationStore.getData().item){ // this.onNavigationChange({ // item: NavigationStore.getData().item // }) // } } onNavigationChange(data) { let item = data.item; if (item.route) { this.state.items = []; this.state.icon = ''; this._addCrumb(item); this.forceUpdate() } } _addCrumb(item) { this.state.items.unshift(item.title) if (!this.state.icon && item.icon) this.state.icon = item.icon if (item.parent) this._addCrumb(item.parent) } render() { const first = _.head(this.state.items); return ( <div className={this.props.className + ' big-breadcrumbs'}> <h1 className="page-title txt-color-blueDark"> <i className={this.state.icon}/>{' ' + first} {_.tail(this.state.items).map((item) => { return <span key={_.uniqueId('big-breadcrumb-')}> <span className="page-title-separator">&gt;</span> {item}</span> })} </h1> </div> ) } }
app/components/Header/components/SessionInfo.js
kme211/srt-maker
import React from 'react'; import getRelativeTimeAgo from '../../../utils/getRelativeTimeAgo'; import styles from './SessionInfo.css'; const SessionInfo = ({ name, status, lastSaved }) => ( <div className={styles.session}> <div className={styles.session__name}>{name}</div> <div className={ lastSaved ? styles.session__saveTime : styles.session__saveTimeDanger } > {lastSaved ? `${status} ${getRelativeTimeAgo(lastSaved)}` : '*Session has not been saved yet. Ctrl-S to save.'} </div> </div> ); export default SessionInfo;
src/components/companies/companies-edit.js
Xabadu/VendOS
import React, { Component } from 'react'; import { Link } from 'react-router'; import { connect } from 'react-redux'; import { reduxForm } from 'redux-form'; import { getCompany, updateCompany } from '../../actions/companies'; class CompaniesEdit extends Component { constructor(props) { super(props); this.state = { success: false }; } componentWillMount() { this.props.getCompany(this.props.params.id); } onSubmit(props) { this.props.updateCompany(props, this.props.companyId) .then(() => { this.setState({success: true}); window.scrollTo(0, 0); }); } _successAlert() { if(this.state.success) { return ( <div className="row"> <div className="col-md-12"> <div className="alert alert-success"> La empresa ha sido editada exitosamente. <Link to='/companies'>Volver al listado de empresas.</Link> </div> </div> </div> ); } } render() { const { fields: { name }, handleSubmit } = this.props; return ( <div> <form onSubmit={handleSubmit(this.onSubmit.bind(this))}> <div className="page-breadcrumb"> <ol className="breadcrumb container"> <li><Link to='/'>Inicio</Link></li> <li><a href="#">Empresas</a></li> <li className="active">Actualizar Empresa</li> </ol> </div> <div className="page-title"> <div className="container"> <h3>Actualizar Empresa</h3> </div> </div> <div id="main-wrapper" className="container"> {this._successAlert()} <div className="row"> <div className="col-md-6"> <div className="panel panel-white"> <div className="panel-heading clearfix"> <h4 className="panel-title">Informaci&oacute;n general</h4> </div> <div className="panel-body"> <div className="form-group"> <label for="input-Default" className="control-label">Nombre</label> <input type="text" className={`form-control ${name.touched && name.invalid ? 'b-error' : ''}`} id="input-Default" placeholder="Nombre" {...name} /> <span className="text-danger">{name.touched ? name.error : ''}</span> </div> </div> </div> </div> <div className="col-md-6"> </div> <div className="col-md-6"> </div> <div className="col-md-12"> <div className="panel panel-white"> <div className="panel-body"> <button type="submit" className="btn btn-info left">Actualizar empresa</button> </div> </div> </div> </div> </div> </form> </div> ); } } function validate(values) { const errors = {}; if(!values.name) { errors.name = 'Ingresa un nombre'; } return errors; } function mapStateToProps(state) { return { initialValues: state.companies.companyDetail, companyId: state.companies.companyId }; } export default reduxForm({ form: 'EditCompanyForm', fields: ['name'], validate }, mapStateToProps, { getCompany, updateCompany })(CompaniesEdit);
react-flux-mui/js/material-ui/src/svg-icons/action/verified-user.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionVerifiedUser = (props) => ( <SvgIcon {...props}> <path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm-2 16l-4-4 1.41-1.41L10 14.17l6.59-6.59L18 9l-8 8z"/> </SvgIcon> ); ActionVerifiedUser = pure(ActionVerifiedUser); ActionVerifiedUser.displayName = 'ActionVerifiedUser'; ActionVerifiedUser.muiName = 'SvgIcon'; export default ActionVerifiedUser;
nailgun/static/views/cluster_page.js
huntxu/fuel-web
/* * Copyright 2015 Mirantis, Inc. * * Licensed under the Apache License, Version 2.0 (the 'License'); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an 'AS IS' BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. **/ import $ from 'jquery'; import _ from 'underscore'; import i18n from 'i18n'; import React from 'react'; import utils from 'utils'; import models from 'models'; import dispatcher from 'dispatcher'; import {backboneMixin, pollingMixin, dispatcherMixin} from 'component_mixins'; import DashboardTab from 'views/cluster_page_tabs/dashboard_tab'; import NodesTab from 'views/cluster_page_tabs/nodes_tab'; import NetworkTab from 'views/cluster_page_tabs/network_tab'; import SettingsTab from 'views/cluster_page_tabs/settings_tab'; import LogsTab from 'views/cluster_page_tabs/logs_tab'; import HealthCheckTab from 'views/cluster_page_tabs/healthcheck_tab'; import {VmWareTab, VmWareModels} from 'plugins/vmware/vmware'; var ClusterPage = React.createClass({ mixins: [ pollingMixin(5), backboneMixin('cluster', 'change:name change:is_customized change:release'), backboneMixin({ modelOrCollection: (props) => props.cluster.get('nodes') }), backboneMixin({ modelOrCollection: (props) => props.cluster.get('tasks'), renderOn: 'update change' }), dispatcherMixin('networkConfigurationUpdated', 'removeFinishedNetworkTasks'), dispatcherMixin('deploymentTasksUpdated', 'removeFinishedDeploymentTasks'), dispatcherMixin('deploymentTaskStarted', function() { this.refreshCluster().always(this.startPolling); }), dispatcherMixin('networkVerificationTaskStarted', function() { this.startPolling(); }), dispatcherMixin('deploymentTaskFinished', function() { this.refreshCluster().always(() => dispatcher.trigger('updateNotifications')); }) ], statics: { navbarActiveElement: 'clusters', breadcrumbsPath(pageOptions) { var cluster = pageOptions.cluster; var tabOptions = pageOptions.tabOptions[0]; var addScreenBreadcrumb = tabOptions && tabOptions.match(/^(?!list$)\w+$/); var breadcrumbs = [ ['home', '#'], ['environments', '#clusters'], [cluster.get('name'), '#cluster/' + cluster.get('id'), {skipTranslation: true}], [i18n('cluster_page.tabs.' + pageOptions.activeTab), '#cluster/' + cluster.get('id') + '/' + pageOptions.activeTab, {active: !addScreenBreadcrumb}] ]; if (addScreenBreadcrumb) { breadcrumbs.push([i18n('cluster_page.nodes_tab.breadcrumbs.' + tabOptions), null, {active: true}]); } return breadcrumbs; }, title(pageOptions) { return pageOptions.cluster.get('name'); }, getTabs() { return [ {url: 'dashboard', tab: DashboardTab}, {url: 'nodes', tab: NodesTab}, {url: 'network', tab: NetworkTab}, {url: 'settings', tab: SettingsTab}, {url: 'vmware', tab: VmWareTab}, {url: 'logs', tab: LogsTab}, {url: 'healthcheck', tab: HealthCheckTab} ]; }, fetchData(id, activeTab, ...tabOptions) { var cluster, promise, currentClusterId; var nodeNetworkGroups = app.nodeNetworkGroups; var tab = _.find(this.getTabs(), {url: activeTab}).tab; try { currentClusterId = app.page.props.cluster.id; } catch (ignore) {} if (currentClusterId == id) { // just another tab has been chosen, do not load cluster again cluster = app.page.props.cluster; promise = tab.fetchData ? tab.fetchData({cluster: cluster, tabOptions: tabOptions}) : $.Deferred().resolve(); } else { cluster = new models.Cluster({id: id}); var settings = new models.Settings(); settings.url = _.result(cluster, 'url') + '/attributes'; cluster.set({settings: settings}); var roles = new models.Roles(); roles.url = _.result(cluster, 'url') + '/roles'; cluster.set({roles: roles}); var pluginLinks = new models.PluginLinks(); pluginLinks.url = _.result(cluster, 'url') + '/plugin_links'; cluster.set({pluginLinks: pluginLinks}); cluster.get('nodes').fetch = function(options) { return this.constructor.__super__.fetch.call(this, _.extend({data: {cluster_id: id}}, options)); }; promise = $.when( cluster.fetch(), cluster.get('settings').fetch(), cluster.get('roles').fetch(), cluster.get('pluginLinks').fetch({cache: true}), cluster.fetchRelated('nodes'), cluster.fetchRelated('tasks'), nodeNetworkGroups.fetch({cache: true}) ) .then(() => { var networkConfiguration = new models.NetworkConfiguration(); networkConfiguration.url = _.result(cluster, 'url') + '/network_configuration/' + cluster.get('net_provider'); cluster.set({ networkConfiguration: networkConfiguration, release: new models.Release({id: cluster.get('release_id')}) }); return $.when(cluster.get('networkConfiguration').fetch(), cluster.get('release').fetch()); }) .then(() => { var useVcenter = cluster.get('settings').get('common.use_vcenter.value'); if (!useVcenter) { return true; } var vcenter = new VmWareModels.VCenter({id: id}); cluster.set({vcenter: vcenter}); return vcenter.fetch(); }) .then(() => { return tab.fetchData ? tab.fetchData({cluster: cluster, tabOptions: tabOptions}) : $.Deferred().resolve(); }); } return promise.then((data) => { return { cluster: cluster, nodeNetworkGroups: nodeNetworkGroups, activeTab: activeTab, tabOptions: tabOptions, tabData: data }; }); } }, getDefaultProps() { return { defaultLogLevel: 'INFO' }; }, getInitialState() { return { activeSettingsSectionName: this.pickDefaultSettingGroup(), activeNetworkSectionName: this.props.nodeNetworkGroups.find({is_default: true}).get('name'), selectedNodeIds: {}, selectedLogs: {type: 'local', node: null, source: 'app', level: this.props.defaultLogLevel} }; }, removeFinishedNetworkTasks(callback) { var request = this.removeFinishedTasks(this.props.cluster.tasks({group: 'network'})); if (callback) request.always(callback); return request; }, removeFinishedDeploymentTasks() { return this.removeFinishedTasks(this.props.cluster.tasks({group: 'deployment'})); }, removeFinishedTasks(tasks) { var requests = []; _.each(tasks, (task) => { if (task.match({active: false})) { this.props.cluster.get('tasks').remove(task); requests.push(task.destroy({silent: true})); } }); return $.when(...requests); }, shouldDataBeFetched() { return this.props.cluster.task({group: ['deployment', 'network'], active: true}); }, fetchData() { var task = this.props.cluster.task({group: 'deployment', active: true}); if (task) { return task.fetch() .done(() => { if (task.match({active: false})) dispatcher.trigger('deploymentTaskFinished'); }) .then(() => this.props.cluster.fetchRelated('nodes') ); } else { task = this.props.cluster.task({name: 'verify_networks', active: true}); return task ? task.fetch() : $.Deferred().resolve(); } }, refreshCluster() { return $.when( this.props.cluster.fetch(), this.props.cluster.fetchRelated('nodes'), this.props.cluster.fetchRelated('tasks'), this.props.cluster.get('pluginLinks').fetch() ); }, componentWillMount() { this.props.cluster.on('change:release_id', () => { var release = new models.Release({id: this.props.cluster.get('release_id')}); release.fetch().done(() => { this.props.cluster.set({release: release}); }); }); this.updateLogSettings(); }, componentWillReceiveProps(newProps) { this.updateLogSettings(newProps); }, updateLogSettings(props) { props = props || this.props; // FIXME: the following logs-related logic should be moved to Logs tab code // to keep parent component tightly coupled to its children if (props.activeTab == 'logs') { var selectedLogs; if (props.tabOptions[0]) { selectedLogs = utils.deserializeTabOptions(_.compact(props.tabOptions).join('/')); selectedLogs.level = selectedLogs.level ? selectedLogs.level.toUpperCase() : props.defaultLogLevel; this.setState({selectedLogs: selectedLogs}); } } }, changeLogSelection(selectedLogs) { this.setState({selectedLogs: selectedLogs}); }, getAvailableTabs(cluster) { return _.filter(this.constructor.getTabs(), (tabData) => !tabData.tab.isVisible || tabData.tab.isVisible(cluster)); }, pickDefaultSettingGroup() { return _.first(this.props.cluster.get('settings').getGroupList()); }, setActiveSettingsGroupName(value) { if (_.isUndefined(value)) value = this.pickDefaultSettingGroup(); this.setState({activeSettingsSectionName: value}); }, setActiveNetworkSectionName(name) { this.setState({activeNetworkSectionName: name}); }, selectNodes(ids, checked) { if (ids && ids.length) { var nodeSelection = this.state.selectedNodeIds; _.each(ids, (id) => { if (checked) { nodeSelection[id] = true; } else { delete nodeSelection[id]; } }); this.setState({selectedNodeIds: nodeSelection}); } else { this.setState({selectedNodeIds: {}}); } }, render() { var cluster = this.props.cluster; var availableTabs = this.getAvailableTabs(cluster); var tabUrls = _.pluck(availableTabs, 'url'); var tab = _.find(availableTabs, {url: this.props.activeTab}); if (!tab) return null; var Tab = tab.tab; return ( <div className='cluster-page' key={cluster.id}> <div className='page-title'> <h1 className='title'> {cluster.get('name')} <div className='title-node-count'>({i18n('common.node', {count: cluster.get('nodes').length})})</div> </h1> </div> <div className='tabs-box'> <div className='tabs'> {tabUrls.map((url) => { return ( <a key={url} className={url + ' ' + utils.classNames({'cluster-tab': true, active: this.props.activeTab == url})} href={'#cluster/' + cluster.id + '/' + url} > <div className='icon'></div> <div className='label'>{i18n('cluster_page.tabs.' + url)}</div> </a> ); })} </div> </div> <div key={tab.url + cluster.id} className={'content-box tab-content ' + tab.url + '-tab'}> <Tab ref='tab' cluster={cluster} nodeNetworkGroups={this.props.nodeNetworkGroups} tabOptions={this.props.tabOptions} setActiveSettingsGroupName={this.setActiveSettingsGroupName} setActiveNetworkSectionName={this.setActiveNetworkSectionName} selectNodes={this.selectNodes} changeLogSelection={this.changeLogSelection} {...this.state} {...this.props.tabData} /> </div> </div> ); } }); export default ClusterPage;
tests/routes/Counter/components/Counter.spec.js
GreGGus/MIMApp
import React from 'react' import { bindActionCreators } from 'redux' import { Counter } from 'routes/Counter/components/Counter' import { shallow } from 'enzyme' describe('(Component) Counter', () => { let _props, _spies, _wrapper beforeEach(() => { _spies = {} _props = { counter : 5, ...bindActionCreators({ doubleAsync : (_spies.doubleAsync = sinon.spy()), increment : (_spies.increment = sinon.spy()) }, _spies.dispatch = sinon.spy()) } _wrapper = shallow(<Counter {..._props} />) }) it('renders as a <div>.', () => { expect(_wrapper.is('div')).to.equal(true) }) it('renders with an <h2> that includes Counter label.', () => { expect(_wrapper.find('h2').text()).to.match(/Counter:/) }) it('renders {props.counter} at the end of the sample counter <h2>.', () => { expect(_wrapper.find('h2').text()).to.match(/5$/) _wrapper.setProps({ counter: 8 }) expect(_wrapper.find('h2').text()).to.match(/8$/) }) it('renders exactly two buttons.', () => { expect(_wrapper.find('button')).to.have.length(2) }) describe('Increment', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment') }) it('exists', () => { expect(_button).to.exist() }) it('is a primary button', () => { expect(_button.hasClass('btn btn-primary')).to.be.true() }) it('Calls props.increment when clicked', () => { _spies.dispatch.should.have.not.been.called() _button.simulate('click') _spies.dispatch.should.have.been.called() _spies.increment.should.have.been.called() }) }) describe('Double Async Button', () => { let _button beforeEach(() => { _button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)') }) it('exists', () => { expect(_button).to.exist() }) it('is a secondary button', () => { expect(_button.hasClass('btn btn-secondary')).to.be.true() }) it('Calls props.doubleAsync when clicked', () => { _spies.dispatch.should.have.not.been.called() _button.simulate('click') _spies.dispatch.should.have.been.called() _spies.doubleAsync.should.have.been.called() }) }) })
config/routes.js
dkfann/cinesythesia
import React from 'react'; import {Route, Router, IndexRoute, hashHistory} from 'react-router'; import MainContainer from '../containers/MainContainer'; import HomeContainer from '../containers/HomeContainer'; export default ( <Router history={hashHistory}> <Route path="/" component={ MainContainer }> <IndexRoute component={ HomeContainer }/> </Route> </Router> );
mobile/Simplenote/src/components/screen-activity-indicator.js
abhaydgarg/Simplenote
import React from 'react'; import PropTypes from 'prop-types'; import { ActivityIndicator, View } from 'react-native'; const ScreenActivityIndicator = (props) => { return ( <View style={{flex: 1, justifyContent: 'center', alignItems: 'center'}}> <ActivityIndicator animating color={props.color} size='large' /> </View> ); }; ScreenActivityIndicator.defaultProps = { color: 'black' }; ScreenActivityIndicator.propTypes = { color: PropTypes.string }; export default ScreenActivityIndicator;
ui/js/components/Image.js
ericsoderberg/pbc-web
import React from 'react'; import PropTypes from 'prop-types'; const Image = (props) => { const { avatar, className, full, image, style } = props; const classes = ['image']; if (avatar) { classes.push('image--avatar'); } if (full) { classes.push('image--full'); } if (className) { classes.push(className); } return ( <img className={classes.join(' ')} alt="" src={image ? (image.data || image.path) : ''} style={style} /> ); }; Image.propTypes = { avatar: PropTypes.bool, className: PropTypes.string, full: PropTypes.bool, image: PropTypes.shape({ data: PropTypes.string, }), style: PropTypes.object, }; Image.defaultProps = { avatar: false, className: undefined, full: false, image: {}, style: undefined, }; export default Image;
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/data/ScopeValidation.js
thusithak/carbon-apimgt
/* * Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved. * * WSO2 Inc. licenses this file to you under the Apache License, * Version 2.0 (the "License"); you may not use this file except * in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ "use strict"; import React from 'react'; import AuthManager from './AuthManager' import {Button} from 'antd' const resourcePath = { APIS : "/apis", SINGLE_API :"/apis/{apiId}", API_SWAGGER : "/apis/{apiId}/swagger", API_WSDL : "/apis/{apiId}/wsdl", API_GW_CONFIG : "/apis/{apiId}/gateway-config", API_THUMBNAIL : "/apis/{apiId}/thumbnail", API_COPY : "/apis/copy-api", API_LC_HISTORY : "/apis/{apiId}/lifecycle-history", API_CHANGE_LC : "/apis/change-lifecycle", API_LC : "/apis/{apiId}/lifecycle", API_LC_PENDING_TASK : "/apis/{apiId}/lifecycle/lifecycle-pending-task", API_DEF : "/apis/import-definition", API_VALIDATE_DEF : "/apis/validate-definition", API_DOCS : "/apis/{apiId}/documents", API_DOC : "'/apis/{apiId}/documents/{documentId}'", API_DOC_CONTENT : "'/apis/{apiId}/documents/{documentId}/content'", EXPORT_APIS : "/export/apis", IMPORT_APIS : "/import/apis", SUBSCRIPTION : "/subscriptions", SUBSCRIPTIONS : "/subscriptions", BLOCK_SUBSCRIPTION : "/subscriptions/block-subscription:", UNBLOCK_SUBSCRIPTION : "/subscriptions/unblock-subscription", POLICIES : "'/policies/{tierLevel}'", POLICY : "'/policies/{tierLevel}/{tierName}'", ENDPOINTS : "/endpoints", ENDPOINT : "/endpoints/{endpointId}", LABLES : "/labels", WORKFLOW : "/workflows/{workflowReferenceId}" }; const resourceMethod = { POST : "post", PUT : "put", GET : "get", DELETE : "delete" } class ScopeValidation extends React.Component { constructor(props){ super(props); this.state = {}; } componentDidMount(){ let hasScope = AuthManager.hasScopes(this.props.resourcePath, this.props.resourceMethod); hasScope.then(haveScope => {this.setState({haveScope: haveScope})}) } render() { if(this.state.haveScope) { return (this.props.children); } return null; } } module.exports = { ScopeValidation, resourceMethod, resourcePath }
app/components/About.js
kdemoya/seriesly
import React, { Component } from 'react'; import { Text, View } from 'react-native'; class About extends Component { static navigationOptions = { title: 'About', }; render() { return ( <View> <Text> This is an awesome app! Nothing to watch here... Yet. </Text> </View> ); } } export default About;
node_modules/@material-ui/core/esm/Breadcrumbs/BreadcrumbSeparator.js
pcclarke/civ-techs
import _extends from "@babel/runtime/helpers/extends"; import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties"; import React from 'react'; import PropTypes from 'prop-types'; import clsx from 'clsx'; import withStyles from '../styles/withStyles'; var styles = { root: { display: 'flex', userSelect: 'none', marginLeft: 8, marginRight: 8 } }; /** * @ignore - internal component. */ function BreadcrumbSeparator(props) { var classes = props.classes, className = props.className, other = _objectWithoutProperties(props, ["classes", "className"]); return React.createElement("li", _extends({ "aria-hidden": true, className: clsx(classes.root, className) }, other)); } process.env.NODE_ENV !== "production" ? BreadcrumbSeparator.propTypes = { children: PropTypes.node.isRequired, classes: PropTypes.object.isRequired, className: PropTypes.string } : void 0; export default withStyles(styles, { name: 'PrivateBreadcrumbSeparator' })(BreadcrumbSeparator);
DevTools.js
mattkrick/redux-operations-counter-example
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey='ctrl-h' changePositionKey='ctrl-q'> <LogMonitor /> </DockMonitor> );
blueocean-material-icons/src/js/components/svg-icons/action/settings-ethernet.js
kzantow/blueocean-plugin
import React from 'react'; import SvgIcon from '../../SvgIcon'; const ActionSettingsEthernet = (props) => ( <SvgIcon {...props}> <path d="M7.77 6.76L6.23 5.48.82 12l5.41 6.52 1.54-1.28L3.42 12l4.35-5.24zM7 13h2v-2H7v2zm10-2h-2v2h2v-2zm-6 2h2v-2h-2v2zm6.77-7.52l-1.54 1.28L20.58 12l-4.35 5.24 1.54 1.28L23.18 12l-5.41-6.52z"/> </SvgIcon> ); ActionSettingsEthernet.displayName = 'ActionSettingsEthernet'; ActionSettingsEthernet.muiName = 'SvgIcon'; export default ActionSettingsEthernet;
app/javascript/mastodon/components/column.js
nonoz/mastodon
import React from 'react'; import PropTypes from 'prop-types'; import detectPassiveEvents from 'detect-passive-events'; import { scrollTop } from '../scroll'; export default class Column extends React.PureComponent { static propTypes = { children: PropTypes.node, }; scrollTop () { const scrollable = this.node.querySelector('.scrollable'); if (!scrollable) { return; } this._interruptScrollAnimation = scrollTop(scrollable); } handleWheel = () => { if (typeof this._interruptScrollAnimation !== 'function') { return; } this._interruptScrollAnimation(); } setRef = c => { this.node = c; } componentDidMount () { this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents ? { passive: true } : false); } componentWillUnmount () { this.node.removeEventListener('wheel', this.handleWheel); } render () { const { children } = this.props; return ( <div role='region' className='column' ref={this.setRef}> {children} </div> ); } }
milestones/05-webpack-intro-css/After/src/index.js
jaketrent/react-drift
import React from 'react' import ReactDOM from 'react-dom' import DriftApp from './app.js' ReactDOM.render(<DriftApp />, document.getElementById('app'))
src/svg-icons/toggle/radio-button-checked.js
pradel/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ToggleRadioButtonChecked = (props) => ( <SvgIcon {...props}> <path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/> </SvgIcon> ); ToggleRadioButtonChecked = pure(ToggleRadioButtonChecked); ToggleRadioButtonChecked.displayName = 'ToggleRadioButtonChecked'; export default ToggleRadioButtonChecked;
packages/react-scripts/fixtures/kitchensink/src/features/syntax/DestructuringAndAwait.js
andrewmaudsley/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; async function load() { return { users: [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, { id: 4, name: '4' }, ], }; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const { users } = await load(); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-destructuring-and-await"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
components/react-semantify/src/collections/table.js
react-douban/douban-book-web
import React from 'react'; import ClassGenerator from '../mixins/classGenerator'; let defaultClassName = 'ui table'; const Table = React.createClass({ mixins: [ClassGenerator], render: function () { let {className, ...other} = this.props; return ( <table {...other} className={this.getClassName(defaultClassName)} > {this.props.children} </table> ); } }); export default Table;
packages/vx-glyph/src/glyphs/Square.js
Flaque/vx
import React from 'react'; import cx from 'classnames'; import { symbol, symbolSquare } from 'd3-shape'; import Glyph from './Glyph'; import additionalProps from '../util/additionalProps'; export default function GlyphSquare({ children, className, top, left, size, ...restProps }) { const path = symbol(); path.type(symbolSquare); if (size) path.size(size); return ( <Glyph top={top} left={left}> <path className={cx('vx-glyph-square', className)} d={path()} {...additionalProps(restProps)} /> {children} </Glyph> ); }
src/svg-icons/device/access-alarm.js
mmrtnz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceAccessAlarm = (props) => ( <SvgIcon {...props}> <path d="M22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM12.5 8H11v6l4.75 2.85.75-1.23-4-2.37V8zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/> </SvgIcon> ); DeviceAccessAlarm = pure(DeviceAccessAlarm); DeviceAccessAlarm.displayName = 'DeviceAccessAlarm'; DeviceAccessAlarm.muiName = 'SvgIcon'; export default DeviceAccessAlarm;
src/svg-icons/social/sentiment-very-satisfied.js
nathanmarks/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialSentimentVerySatisfied = (props) => ( <SvgIcon {...props}> <path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm1-10.06L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zm-4.12 0L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zM12 17.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/> </SvgIcon> ); SocialSentimentVerySatisfied = pure(SocialSentimentVerySatisfied); SocialSentimentVerySatisfied.displayName = 'SocialSentimentVerySatisfied'; SocialSentimentVerySatisfied.muiName = 'SvgIcon'; export default SocialSentimentVerySatisfied;
examples/week.js
react-component/calendar
/* eslint react/no-multi-comp:0, no-console:0 */ import '../assets/index.less'; import React from 'react'; import moment from 'moment'; import Calendar from '../src'; import DatePicker from '../src/Picker'; import zhCN from '../src/locale/zh_CN'; import enUS from '../src/locale/en_US'; import 'moment/locale/zh-cn'; import 'moment/locale/en-gb'; const format = 'YYYY-Wo'; const cn = window.location.search.indexOf('cn') !== -1; const now = moment(); if (cn) { now.locale('zh-cn').utcOffset(8); } else { now.locale('en-gb').utcOffset(0); } const style = ` .week-calendar { width: 386px; } .week-calendar .rc-calendar-tbody > tr:hover .rc-calendar-date { background: #ebfaff; } .week-calendar .rc-calendar-tbody > tr:hover .rc-calendar-selected-day .rc-calendar-date { background: #3fc7fa; } .week-calendar .week-calendar-sidebar { position:absolute; top:0; left:0; bottom:0; width:100px; border-right: 1px solid #ccc; } .week-calendar .rc-calendar-panel { margin-left: 100px; } `; class Demo extends React.Component { state = { value: undefined, open: false, }; onChange = value => { console.log('DatePicker change: ', value && value.format(format)); this.setState({ value, }); }; onOpenChange = open => { this.setState({ open, }); }; dateRender = current => { const selectedValue = this.state.value; if ( selectedValue && current.year() === selectedValue.year() && current.week() === selectedValue.week() ) { return ( <div className="rc-calendar-selected-day"> <div className="rc-calendar-date">{current.date()}</div> </div> ); } return <div className="rc-calendar-date">{current.date()}</div>; }; lastWeek = () => { const { state } = this; const value = state.value || now; value.add(-1, 'weeks'); this.setState({ value, open: false, }); }; renderSidebar = () => ( <div className="week-calendar-sidebar" key="sidebar"> <button onClick={() => this.lastWeek()} type="button" style={{ margin: 20 }}> 上一周 </button> </div> ); render() { const { state } = this; const calendar = ( <Calendar className="week-calendar" showWeekNumber renderSidebar={this.renderSidebar} dateRender={this.dateRender} locale={cn ? zhCN : enUS} format={format} style={{ zIndex: 1000 }} dateInputPlaceholder="please input" defaultValue={now} showDateInput /> ); return ( <div style={{ width: 400, margin: 20 }}> <div style={{ boxSizing: 'border-box', position: 'relative', display: 'block', lineHeight: 1.5, marginBottom: 22, }} > <DatePicker onOpenChange={this.onOpenChange} open={this.state.open} animation="slide-up" calendar={calendar} value={state.value} onChange={this.onChange} > {({ value }) => ( <span tabIndex="0"> <input placeholder="please select week" style={{ width: 250 }} disabled={state.disabled} readOnly tabIndex="-1" className="ant-calendar-picker-input ant-input" value={(value && value.format(format)) || ''} /> </span> )} </DatePicker> </div> </div> ); } } export default () => ( <div style={{ zIndex: 1000, position: 'relative', width: 900, margin: '20px auto', }} > <style dangerouslySetInnerHTML={{ __html: style }} /> <div> <Demo /> </div> </div> );
app/components/Work/ToolsSection/index.js
yasserhennawi/yasserhennawi
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'utils/styled-components'; import WorkSection from '../WorkSection'; import Tool from '../Tool'; const StyledTool = styled(Tool)` margin: 10px 20px 0 0; `; const ToolsWrapper = styled.div` display: flex; flex-wrap: wrap; `; const getTools = (tools, toolsBgColor, width, secondary) => ( <ToolsWrapper> {tools.map((tool, index) => ( <StyledTool bgColor={toolsBgColor} key={index} padding={tool.padding} secondary={secondary} width={width} name={tool.name} logoImage={tool.logoImage} logo={tool.logo} /> ))} </ToolsWrapper> ); const ToolsSection = ({ toolsBgColor, secondary, tools, width }) => ( <WorkSection title="Tools"> {getTools(tools, toolsBgColor, width, secondary)} </WorkSection> ); ToolsSection.propTypes = { toolsBgColor: PropTypes.string, secondary: PropTypes.bool, tools: PropTypes.array, width: PropTypes.string, }; export default ToolsSection;
src/components/Surrounder.js
codeforboston/cliff-effects
import React from 'react'; const Surrounder = function ({ Top, Left, Right, Bottom, children }) { let contents = { top: null, left: null, right: null, bottom: null }; if (Top) { contents.top = (<div className={ `top horizontal` }>{ Top }</div>); } if (Left) { contents.left = (<div className={ `left vertical` }>{ Left }</div>); } if (Right) { contents.right = (<div className={ `right vertical` }>{ Right }</div>); } if (Bottom) { contents.bottom = (<div className={ `bottom horizontal` }>{ Bottom }</div>); } return ( <div className={ `surrounder` }> { contents.top } <div className={ `middle horizontal` }> { contents.left } <div className={ `center horizontal content` }> { children } </div> { contents.right } </div> { contents.bottom } </div> ); }; // Ends <Surrounder> export { Surrounder };
src/components/App.js
sivael/simpleBlogThingie
import React from 'react' import Header from 'components/Header' import { Link } from 'react-router' class App extends React.Component { render() { return ( <div> <Header /> { this.props.children } </div> ) } } export default App;
app-course-sync/containers/PageContainer.js
globant-ui-rosario/progress-tracker
import React, { Component } from 'react'; class PageContainer extends Component { render () { return ( <div>{this.props.children}</div> ); } }; export default PageContainer;
src/components/searchbar.js
ShaneFairweather/React-iTunes
import React, { Component } from 'react'; export default class SearchBar extends Component { constructor(props) { super(props); this.state = { term: '' } this.onInputChange = this.onInputChange.bind(this); } onInputChange(term) { this.setState({term}) this.props.getResults(term); } render() { return ( <div className='searchBarContainer'> <input type='text' value={this.state.term} onChange={event => this.onInputChange(event.target.value)} /> </div> ) } } {/*<button><i id="searchIcon" className="fa fa-search" /></button>*/}
src/resources/assets/react-app/components/PreHeader.js
darrenmerrett/ruf
import React, { Component } from 'react'; class PreHeader extends Component { render() { return null; } } export default PreHeader;
src/components/TabIcon.js
phodal/growth-ng
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text } from 'react-native'; import { Icon } from 'react-native-elements'; import AppColors from '../theme/colors'; class TabIcon extends React.Component { componentName = 'TabIcon'; render() { return ( <View> <Icon name={this.props.iconName} type={this.props.iconType} color={this.props.selected ? AppColors.brand.primary : '#767676'} /> <Text style={{ color: this.props.selected ? AppColors.brand.primary : '#767676' }}>{this.props.title}</Text> </View> ); } } TabIcon.propTypes = { title: PropTypes.string.isRequired, selected: PropTypes.bool, iconName: PropTypes.string.isRequired, iconType: PropTypes.string.isRequired }; TabIcon.defaultProps = { title: 'Home', selected: false, iconName: 'md-home', iconType: 'ionicon' }; export default TabIcon;
test/components/Counter.spec.js
Andrew-Hird/bFM-desktop
/* eslint-disable no-unused-expressions */ import { spy } from 'sinon'; import React from 'react'; import { shallow } from 'enzyme'; import Counter from '../../app/components/Counter'; function setup() { const actions = { increment: spy(), incrementIfOdd: spy(), incrementAsync: spy(), decrement: spy() }; const component = shallow(<Counter counter={1} {...actions} />); return { component, actions, buttons: component.find('button'), p: component.find('.counter') }; } describe('Counter component', () => { it('should should display count', () => { const { p } = setup(); expect(p.text()).toMatch(/^1$/); }); it('should first button should call increment', () => { const { buttons, actions } = setup(); buttons.at(0).simulate('click'); expect(actions.increment.called).toBe(true); }); it('should second button should call decrement', () => { const { buttons, actions } = setup(); buttons.at(1).simulate('click'); expect(actions.decrement.called).toBe(true); }); it('should third button should call incrementIfOdd', () => { const { buttons, actions } = setup(); buttons.at(2).simulate('click'); expect(actions.incrementIfOdd.called).toBe(true); }); it('should fourth button should call incrementAsync', () => { const { buttons, actions } = setup(); buttons.at(3).simulate('click'); expect(actions.incrementAsync.called).toBe(true); }); });
pages/product.js
NigelEarle/SSR-shopping
import React, { Component } from 'react'; import { Provider } from 'mobx-react'; import { initProductStore } from '../store/product'; import { SingleProduct } from '../components'; class Product extends Component { static async getInitialProps(context) { const isServer = !!context.req; const store = initProductStore(isServer); await store.fetchSingleProduct(parseInt(context.query.id)); return { products: store.products, singleProduct: store.singleProduct, error: store.error, isServer, } } constructor(props) { super(props); this.store = initProductStore( props.isServer, props.products, props.singleProduct, props.error ); } render() { return ( <Provider productStore={this.store}> <SingleProduct /> </Provider> ); } }; export default Product;
src/Table.js
kwnccc/react-bootstrap
import React from 'react'; import classNames from 'classnames'; const Table = React.createClass({ propTypes: { striped: React.PropTypes.bool, bordered: React.PropTypes.bool, condensed: React.PropTypes.bool, hover: React.PropTypes.bool, responsive: React.PropTypes.bool }, getDefaultProps() { return { bordered: false, condensed: false, hover: false, responsive: false, striped: false }; }, render() { let classes = { 'table': true, 'table-striped': this.props.striped, 'table-bordered': this.props.bordered, 'table-condensed': this.props.condensed, 'table-hover': this.props.hover }; let table = ( <table {...this.props} className={classNames(this.props.className, classes)}> {this.props.children} </table> ); return this.props.responsive ? ( <div className="table-responsive"> {table} </div> ) : table; } }); export default Table;
demo/src/demo-components/user-list.js
Strikersoft/striker-store
import React from 'react'; import { shape, func, number, arrayOf } from 'prop-types'; import { observer } from 'mobx-react'; import Status from './indicators'; import UserItem from './user-item'; const UserList = observer(({ users, isReloading, isLoading, ...rest }) => ( <div> {users.map( user => ( <UserItem key={user.id} user={user} {...rest} /> ) )} {isReloading ? <Status indicator={isReloading} type="Reloading..." /> : null} {isLoading ? <Status indicator={isLoading} type="Loading..." /> : null} </div> )); UserList.propTypes = { users: arrayOf( shape({ id: number }) ).isRequired, isReloading: shape({ get: func, set: func }), isLoading: shape({ get: func, set: func }) }; UserList.displayName = 'UserList'; export default UserList;
src/components/shared/import-geometry/import-geometry.component.js
GeoTIFF/geotiff.io
import React from 'react'; const ImportGeometryComponent = ({ geometry, importGeometry }) => ( <div className='import-geojson'> <p>Import Geometry from file</p> <div className='content-row'> <label className='gt-button-secondary' htmlFor="import-geojson-input" > Import GeoJSON </label> <input id='import-geojson-input' type='file' className='gt-input' onChange={importGeometry} /> </div> </div> ); export default ImportGeometryComponent;
exemplos/ExemploMenuItem.js
vitoralvesdev/react-native-componentes
import React, { Component } from 'react'; import { View, Text, StyleSheet, TouchableOpacity } from 'react-native'; import { MenuItem } from 'react-native-componentes'; const ITENS = [ {nome: 'Criar'}, {nome: 'Atualizar'}, {nome: 'Deletar'}, ] export default class ExemploMenuItem extends Component { constructor(props) { super(props); this.state = { abrirMenu: false } } _itemSelecionado(item) { console.log(item) this.setState({ abrirMenu: false }) } render() { return( <View style={estilos.corpo}> <MenuItem visivel={this.state.abrirMenu} fechar={()=>this.setState({ abrirMenu: false })} itens={ITENS} itemSelecionado={(item)=>this._itemSelecionado(item)} /> <TouchableOpacity onPress={()=>this.setState({ abrirMenu: true })}> <Text style={estilos.titulo}> Abrir o Menu </Text> </TouchableOpacity> </View> ) } } const estilos = StyleSheet.create({ corpo : { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, titulo : { textAlign: 'center', color: '#333333', marginBottom: 5, } })
src/svg-icons/content/drafts.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ContentDrafts = (props) => ( <SvgIcon {...props}> <path d="M21.99 8c0-.72-.37-1.35-.94-1.7L12 1 2.95 6.3C2.38 6.65 2 7.28 2 8v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2l-.01-10zM12 13L3.74 7.84 12 3l8.26 4.84L12 13z"/> </SvgIcon> ); ContentDrafts = pure(ContentDrafts); ContentDrafts.displayName = 'ContentDrafts'; ContentDrafts.muiName = 'SvgIcon'; export default ContentDrafts;
components/link/Link.js
showings/react-toolbox
import React from 'react'; import PropTypes from 'prop-types'; import classnames from 'classnames'; import { themr } from 'react-css-themr'; import { LINK } from '../identifiers'; import { FontIcon } from '../font_icon/FontIcon'; const Link = ({ active, children, className, count, icon, label, theme, ...others }) => { const _className = classnames(theme.link, { [theme.active]: active, }, className); return ( <a data-react-toolbox="link" className={_className} {...others}> {icon ? <FontIcon className={theme.icon} value={icon} /> : null} {label ? <abbr>{label}</abbr> : null} {count && parseInt(count, 10) !== 0 ? <small>{count}</small> : null} {children} </a> ); }; Link.propTypes = { active: PropTypes.bool, children: PropTypes.node, className: PropTypes.string, count: PropTypes.number, icon: PropTypes.oneOfType([ PropTypes.string, PropTypes.element, ]), label: PropTypes.string, theme: PropTypes.shape({ active: PropTypes.string, icon: PropTypes.string, link: PropTypes.string, }), }; Link.defaultProps = { active: false, className: '', }; export default themr(LINK)(Link); export { Link };
lib/Components/IdeaInput.js
DanGrund/Daily-Bullet
import React from 'react'; export default class IdeaInput extends React.Component{ constructor(props){ super(props); this.state = { newTask: {value: ''}, } } handleChange(e){ let task = this.state.newTask task.value = e.target.value this.setState({newTask: task}) } handleSave(){ this.props.saveNewTask(this.state.newTask); this.setState({newTask: {value: ''}}) } render(){ return( <div> <input className = "journalInput" value={this.state.newTask.value} onChange={(e) => this.handleChange(e)} placeholder="write down yo' task" ></input> <button className = "saveButton" disabled={!this.state.newTask.value} onClick={()=> this.handleSave()}>Save</button> </div> ) } }
app/views/STF/Voting/Panels/Vote/Vote.js
RcKeller/STF-Refresh
import React from 'react' import PropTypes from 'prop-types' import { compose, bindActionCreators } from 'redux' import { connect } from 'react-redux' import { Form, Alert, Switch, Button, message } from 'antd' const FormItem = Form.Item const connectForm = Form.create() import { layout } from '../../../../../util/form' import api from '../../../../../services' import { makeManifestByID, makeManifestReview } from '../../../../../selectors' import { Loading } from '../../../../../components' /* VOTE PANEL: Allows members to cast their FINAL, OVERALL VOTES NOTE: The requirements for voting changed at the end of the project, so this is slightly unintuitive. Please refactor when bandwith is avail. */ @compose( connect( (state, props) => { const manifest = makeManifestByID(props.id)(state) const review = makeManifestReview(manifest)(state) || {} const { docket, proposal } = manifest return { review, manifest: manifest._id, author: state.user._id, active: docket.voting, proposal: proposal._id // review: reviews // .find(review => review.author._id === state.user._id) || {}, } }, dispatch => ({ api: bindActionCreators(api, dispatch) }) ), connectForm ) class Vote extends React.Component { static propTypes = { form: PropTypes.object, api: PropTypes.object, id: PropTypes.string.isRequired, proposal: PropTypes.string, review: PropTypes.object, manifest: PropTypes.string, author: PropTypes.string } componentDidMount () { const { form, review } = this.props if (form && review) { // Consistent fields let { approved } = review if (typeof approved === 'undefined') approved = false form.setFieldsValue({ approved }) } } handleSubmit = (e) => { e.preventDefault() let { form, api, proposal, manifest, review, author } = this.props form.validateFields((err, values) => { if (!err) { const { _id: id } = review const submission = { proposal, manifest, author, ...values } const params = { id, populate: ['author'], transform: manifests => ({ manifests }), update: ({ manifests: (prev, next) => { let change = prev.slice() let manifestIndex = change.findIndex(m => m._id === manifest) let reviewIndex = manifestIndex >= 0 ? change[manifestIndex].reviews .findIndex(r => r._id === id) : -1 reviewIndex >= 0 ? change[manifestIndex].reviews[reviewIndex] = next : change[manifestIndex].reviews.push(next) return change }}) } params.id ? api.patch('review', submission, params) .then(message.success('Vote updated!'), 10) .catch(err => { message.warning('Vote failed to update - Unexpected client error') console.warn(err) }) : api.post('review', submission, params) .then(message.success('Vote posted!')) .catch(err => { message.warning('Vote failed to post - Unexpected client error') console.warn(err) }) } }) } render ( { form, active, questions, manifest, review } = this.props ) { return ( <section> <Loading render={manifest} title='Voting Panel'> {review && typeof review.approved === 'boolean' && <Alert showIcon banner type={review.approved ? 'success' : 'error'} message={`You have voted ${review.approved ? 'in favor' : 'against'} this budget`} description='You may change this value later if this was a mistake.' /> } <Form onSubmit={this.handleSubmit} style={{ paddingTop: 16 }}> <FormItem label={<b>Final Vote</b>} {...layout} > {form.getFieldDecorator('approved', { valuePropName: 'checked' })( // Valueprop is a selector for antd switches, it's in the docs. <Switch checkedChildren='APPROVE' unCheckedChildren='DENY' /> )} </FormItem> <FormItem label='Submit' {...layout}> <Button size='large' type='primary' htmlType='submit' ghost disabled={!active} >Save Vote</Button> </FormItem> </Form> </Loading> </section> ) } } export default Vote
client/modules/App/components/DevTools.js
mygithub1216/MERN_SelfCar_Dashboard
import React from 'react'; import { createDevTools } from 'redux-devtools'; import LogMonitor from 'redux-devtools-log-monitor'; import DockMonitor from 'redux-devtools-dock-monitor'; export default createDevTools( <DockMonitor toggleVisibilityKey="ctrl-h" changePositionKey="ctrl-w" > <LogMonitor /> </DockMonitor> );
src/components/buttons/CreateButton.js
shrimpliu/shradmin
import React from 'react'; import PropTypes from 'prop-types'; import { Button } from 'antd'; import { actions } from 'mirrorx'; import { translate } from '../../i18n'; const CreateButton = ({ translate, model }) => ( <Button type="primary" icon="plus" onClick={() => actions.routing.push(`/${model}/create`)}> {translate("actions.create")} </Button> ); CreateButton.propTypes = { model: PropTypes.string.isRequired, translate: PropTypes.func.isRequired, }; export default translate(CreateButton);
node_modules/react-bootstrap/es/DropdownMenu.js
firdiansyah/crud-req
import _extends from 'babel-runtime/helpers/extends'; import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _Array$from from 'babel-runtime/core-js/array/from'; 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 keycode from 'keycode'; import React from 'react'; import PropTypes from 'prop-types'; import ReactDOM from 'react-dom'; import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper'; import { bsClass, getClassSet, prefix, splitBsPropsAndOmit } from './utils/bootstrapUtils'; import createChainedFunction from './utils/createChainedFunction'; import ValidComponentChildren from './utils/ValidComponentChildren'; var propTypes = { open: PropTypes.bool, pullRight: PropTypes.bool, onClose: PropTypes.func, labelledBy: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), onSelect: PropTypes.func, rootCloseEvent: PropTypes.oneOf(['click', 'mousedown']) }; var defaultProps = { bsRole: 'menu', pullRight: false }; var DropdownMenu = function (_React$Component) { _inherits(DropdownMenu, _React$Component); function DropdownMenu(props) { _classCallCheck(this, DropdownMenu); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props)); _this.handleRootClose = _this.handleRootClose.bind(_this); _this.handleKeyDown = _this.handleKeyDown.bind(_this); return _this; } DropdownMenu.prototype.handleRootClose = function handleRootClose(event) { this.props.onClose(event, { source: 'rootClose' }); }; DropdownMenu.prototype.handleKeyDown = function handleKeyDown(event) { switch (event.keyCode) { case keycode.codes.down: this.focusNext(); event.preventDefault(); break; case keycode.codes.up: this.focusPrevious(); event.preventDefault(); break; case keycode.codes.esc: case keycode.codes.tab: this.props.onClose(event, { source: 'keydown' }); break; default: } }; DropdownMenu.prototype.getItemsAndActiveIndex = function getItemsAndActiveIndex() { var items = this.getFocusableMenuItems(); var activeIndex = items.indexOf(document.activeElement); return { items: items, activeIndex: activeIndex }; }; DropdownMenu.prototype.getFocusableMenuItems = function getFocusableMenuItems() { var node = ReactDOM.findDOMNode(this); if (!node) { return []; } return _Array$from(node.querySelectorAll('[tabIndex="-1"]')); }; DropdownMenu.prototype.focusNext = function focusNext() { var _getItemsAndActiveInd = this.getItemsAndActiveIndex(), items = _getItemsAndActiveInd.items, activeIndex = _getItemsAndActiveInd.activeIndex; if (items.length === 0) { return; } var nextIndex = activeIndex === items.length - 1 ? 0 : activeIndex + 1; items[nextIndex].focus(); }; DropdownMenu.prototype.focusPrevious = function focusPrevious() { var _getItemsAndActiveInd2 = this.getItemsAndActiveIndex(), items = _getItemsAndActiveInd2.items, activeIndex = _getItemsAndActiveInd2.activeIndex; if (items.length === 0) { return; } var prevIndex = activeIndex === 0 ? items.length - 1 : activeIndex - 1; items[prevIndex].focus(); }; DropdownMenu.prototype.render = function render() { var _extends2, _this2 = this; var _props = this.props, open = _props.open, pullRight = _props.pullRight, labelledBy = _props.labelledBy, onSelect = _props.onSelect, className = _props.className, rootCloseEvent = _props.rootCloseEvent, children = _props.children, props = _objectWithoutProperties(_props, ['open', 'pullRight', 'labelledBy', 'onSelect', 'className', 'rootCloseEvent', 'children']); var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['onClose']), bsProps = _splitBsPropsAndOmit[0], elementProps = _splitBsPropsAndOmit[1]; var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'right')] = pullRight, _extends2)); return React.createElement( RootCloseWrapper, { disabled: !open, onRootClose: this.handleRootClose, event: rootCloseEvent }, React.createElement( 'ul', _extends({}, elementProps, { role: 'menu', className: classNames(className, classes), 'aria-labelledby': labelledBy }), ValidComponentChildren.map(children, function (child) { return React.cloneElement(child, { onKeyDown: createChainedFunction(child.props.onKeyDown, _this2.handleKeyDown), onSelect: createChainedFunction(child.props.onSelect, onSelect) }); }) ) ); }; return DropdownMenu; }(React.Component); DropdownMenu.propTypes = propTypes; DropdownMenu.defaultProps = defaultProps; export default bsClass('dropdown-menu', DropdownMenu);
src/svg-icons/hardware/keyboard.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let HardwareKeyboard = (props) => ( <SvgIcon {...props}> <path d="M20 5H4c-1.1 0-1.99.9-1.99 2L2 17c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z"/> </SvgIcon> ); HardwareKeyboard = pure(HardwareKeyboard); HardwareKeyboard.displayName = 'HardwareKeyboard'; HardwareKeyboard.muiName = 'SvgIcon'; export default HardwareKeyboard;
local-cli/templates/HelloWorld/index.android.js
tadeuzagallo/react-native
/** * Sample React Native App * https://github.com/facebook/react-native * @flow */ import React, { Component } from 'react'; import { AppRegistry, StyleSheet, Text, View } from 'react-native'; export default class HelloWorld extends Component { render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native! </Text> <Text style={styles.instructions}> To get started, edit index.android.js </Text> <Text style={styles.instructions}> Double tap R on your keyboard to reload,{'\n'} Shake or press menu button for dev menu </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, instructions: { textAlign: 'center', color: '#333333', marginBottom: 5, }, }); AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
docs/app/Components/ComponentDoc/ComponentProps/ComponentPropsHeader.js
shengnian/shengnian-ui-react
import cx from 'classnames' import PropTypes from 'prop-types' import React from 'react' import { Header, Icon } from 'shengnian-ui-react' import { updateForKeys } from 'docs/app/HOC' const headerStyle = { cursor: 'pointer', display: 'inline-flex', margin: '1em 0.5em', marginLeft: 0, } const linkStyle = { color: 'inherit' } const ComponentPropsHeader = ({ hasSubComponents, onClick, showProps }) => { const iconClasses = cx( showProps ? 'on' : 'off', 'toggle', ) return ( <Header as='h4' className='no-anchor' color={showProps ? 'green' : 'grey'} style={headerStyle} onClick={onClick} > <a style={linkStyle}> <Icon name={iconClasses} /> Props{hasSubComponents && ':'} </a> </Header> ) } ComponentPropsHeader.propTypes = { hasSubComponents: PropTypes.bool, onClick: PropTypes.func, showProps: PropTypes.bool, } export default updateForKeys(['hasSubComponents', 'showProps'])(ComponentPropsHeader)
app/index.js
feijihn/lotto
require('smoothscroll-polyfill').polyfill(); import React from 'react'; import ReactDOM from 'react-dom'; import {Provider} from 'react-redux'; import configureStore from './store/configureStore'; import {Router, hashHistory} from 'react-router'; import routes from './routes'; const initialState = window.__INITIAL_STATE__; const store = configureStore(); const rootElement = document.getElementById('container'); let ComponentEl; if (process.env.NODE_ENV === 'development') { const DevTools = require('./containers/DevTools').default; // If using routes ComponentEl = ( <div> <Router history={hashHistory} routes={routes} useAutoKey={true}/> <DevTools /> </div> ); } else { ComponentEl = ( <div> <Router history={hashHistory} routes={routes} useAutoKey={true}/> </div> ); } ReactDOM.render( <Provider store={store}> {ComponentEl} </Provider>, rootElement );
stories/AutoComplete/ExampleStandard.js
skyiea/wix-style-react
import React from 'react'; import AutoComplete from 'wix-style-react/AutoComplete'; const style = { display: 'inline-block', padding: '0 5px 0', width: '200px', lineHeight: '22px' }; const options = [ {id: 0, value: 'First option'}, {id: 1, value: 'Unselectable option', unselectable: true}, {id: 2, value: 'Third option'}, {id: 4, value: 'Very long option text jldlkasj ldk jsalkdjsal kdjaklsjdlkasj dklasj'} ]; const rtlOptions = [ {id: 0, value: 'אפשרות ראשונה'}, {id: 1, value: 'אפשרות שניה'}, {id: 2, value: 'אפשרות שלישית'} ]; export default () => <div> <div style={style} className="ltr"> Left to right <AutoComplete options={options} /> </div> <div style={style} className="rtl"> Right to left<AutoComplete options={rtlOptions}/> </div> <div style={style} className="ltr"> Disabled<AutoComplete disabled options={rtlOptions}/> </div> </div>;
admin/client/Signin/index.js
danielmahon/keystone
/** * The signin page, it renders a page with a username and password input form. * * This is decoupled from the main app (in the "App/" folder) because we inject * lots of data into the other screens (like the lists that exist) that we don't * want to have injected here, so this is a completely separate route and template. */ import qs from 'qs'; import React from 'react'; import ReactDOM from 'react-dom'; import Signin from './Signin'; const params = qs.parse(window.location.search.replace(/^\?/, '')); const from = typeof params.from === 'string' && params.from.charAt(0) === '/' ? params.from : undefined; ReactDOM.render( <Signin brand={Keystone.brand} from={from} logo={Keystone.logo} user={Keystone.user} userCanAccessKeystone={Keystone.userCanAccessKeystone} />, document.getElementById('signin-view') );
node_modules/react-bootstrap/es/MediaBody.js
superKaigon/TheCave
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 'prop-types-extra/lib/elementType'; import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils'; var propTypes = { componentClass: elementType }; var defaultProps = { componentClass: 'div' }; var MediaBody = function (_React$Component) { _inherits(MediaBody, _React$Component); function MediaBody() { _classCallCheck(this, MediaBody); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } MediaBody.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 MediaBody; }(React.Component); MediaBody.propTypes = propTypes; MediaBody.defaultProps = defaultProps; export default bsClass('media-body', MediaBody);
packages/@lyra/imagetool/src/ImageLoader.js
VegaPublish/vega-studio
import PropTypes from 'prop-types' import React from 'react' export default class ImageLoader extends React.Component { static propTypes = { src: PropTypes.string.isRequired, children: PropTypes.func.isRequired } state = { isLoading: true, image: null, error: null } componentWillMount() { this.loadImage(this.props.src) } loadImage(src) { const image = new Image() this.setState({ image: null, error: null }) image.onload = () => { this.setState({ image: image, error: null, isLoading: false }) } image.onerror = () => { this.setState({ error: new Error( `Could not load image from ${JSON.stringify(this.props.src)}` ), isLoading: false }) } image.src = src } componentWillReceiveProps(nextProps) { if (nextProps.src !== this.props.src) { this.loadImage(nextProps.src) } } render() { const {error, image, isLoading} = this.state return this.props.children({image, error, isLoading}) } }
src/components/DoneFooter.js
rollo-zhou/look
import React from 'react'; import { ActivityIndicator, StyleSheet, Image, Text, View, ListView, TouchableOpacity } from 'react-native'; import Dimensions from 'Dimensions'; const {width, height} = Dimensions.get('window'); import globalVariables from '../globalVariables.js'; const DoneFooter = React.createClass({ getInitialState() { return { }; }, shouldComponentUpdate: function(nextProps, nextState) { return JSON.stringify(nextState)!=JSON.stringify(this.state); }, render() { return( <View style={styles.doneView}> <Text style={styles.ILoveYou}>- I Love You -</Text> </View> ); }, }); const styles = StyleSheet.create({ doneView: { flexDirection: 'row', justifyContent: 'center', height:40, width:width, marginTop:20, marginBottom:0, }, ILoveYou: { paddingTop:10, fontSize: 10, color: "#d8d2d6", // fontWeight: "400", // lineHeight: 18 }, doneImage: { width: 302 / 5, height: 252 / 5 }, }); export default DoneFooter;
src/Fade.js
brynjagr/react-bootstrap
import React from 'react'; import Transition from 'react-overlays/lib/Transition'; import CustomPropTypes from './utils/CustomPropTypes'; import deprecationWarning from './utils/deprecationWarning'; class Fade extends React.Component { render() { let timeout = this.props.timeout || this.props.duration; return ( <Transition {...this.props} timeout={timeout} className="fade" enteredClassName="in" enteringClassName="in" > {this.props.children} </Transition> ); } } // Explicitly copied from Transition for doc generation. // TODO: Remove duplication once #977 is resolved. Fade.propTypes = { /** * Show the component; triggers the fade in or fade out animation */ in: React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is faded out */ unmountOnExit: React.PropTypes.bool, /** * Run the fade in animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * Duration of the fade animation in milliseconds, to ensure that finishing * callbacks are fired even if the original browser transition end events are * canceled */ timeout: React.PropTypes.number, /** * duration * @private */ duration: CustomPropTypes.all([ React.PropTypes.number, (props)=> { if (props.duration != null) { deprecationWarning('Fade `duration`', 'the `timeout` prop'); } return null; } ]), /** * Callback fired before the component fades in */ onEnter: React.PropTypes.func, /** * Callback fired after the component starts to fade in */ onEntering: React.PropTypes.func, /** * Callback fired after the has component faded in */ onEntered: React.PropTypes.func, /** * Callback fired before the component fades out */ onExit: React.PropTypes.func, /** * Callback fired after the component starts to fade out */ onExiting: React.PropTypes.func, /** * Callback fired after the component has faded out */ onExited: React.PropTypes.func }; Fade.defaultProps = { in: false, timeout: 300, unmountOnExit: false, transitionAppear: false }; export default Fade;
packages/mineral-ui-icons/src/IconFolderShared.js
mineral-ui/mineral-ui
/* @flow */ import React from 'react'; import Icon from 'mineral-ui/Icon'; import type { IconProps } from 'mineral-ui/Icon/types'; /* eslint-disable prettier/prettier */ export default function IconFolderShared(props: IconProps) { const iconProps = { rtl: false, ...props }; return ( <Icon {...iconProps}> <g> <path d="M20 6h-8l-2-2H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm-5 3c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm4 8h-8v-1c0-1.33 2.67-2 4-2s4 .67 4 2v1z"/> </g> </Icon> ); } IconFolderShared.displayName = 'IconFolderShared'; IconFolderShared.category = 'file';
docs/src/app/components/pages/components/Menu/ExampleDisable.js
w01fgang/material-ui
import React from 'react'; import Paper from 'material-ui/Paper'; import Menu from 'material-ui/Menu'; import MenuItem from 'material-ui/MenuItem'; import Divider from 'material-ui/Divider'; const style = { display: 'inline-block', margin: '16px 32px 16px 0', }; const MenuExampleDisable = () => ( <div> <Paper style={style}> <Menu desktop={true}> <MenuItem primaryText="Back" /> <MenuItem primaryText="Forward" disabled={true} /> <Divider /> <MenuItem primaryText="Recently closed" disabled={true} /> <MenuItem primaryText="Google" disabled={true} /> <MenuItem primaryText="YouTube" /> </Menu> </Paper> <Paper style={style}> <Menu desktop={true}> <MenuItem primaryText="Undo" /> <MenuItem primaryText="Redo" disabled={true} /> <Divider /> <MenuItem primaryText="Cut" disabled={true} /> <MenuItem primaryText="Copy" disabled={true} /> <MenuItem primaryText="Paste" /> </Menu> </Paper> </div> ); export default MenuExampleDisable;
src/components/Root.js
kmcarter/karaoke-song-lister
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { ConnectedRouter } from 'react-router-redux'; import { Provider } from 'react-redux'; import App from './App'; export default class Root extends Component { render() { const { store, history } = this.props; return ( <Provider store={store}> <ConnectedRouter history={history}> <App /> </ConnectedRouter> </Provider> ); } } Root.propTypes = { store: PropTypes.object.isRequired, history: PropTypes.object.isRequired };
src/scripts/NavBar.js
lixmal/keepass4web
import React from 'react' import Timer from './Timer' window.$ = window.jQuery = require('jquery') var Bootstrap = require('bootstrap') export default class NavBar extends React.Component { constructor() { super() this.onLogout = this.onLogout.bind(this) this.onCloseDB = this.onCloseDB.bind(this) this.onTimeUp = this.onTimeUp.bind(this) } onLogout() { this.serverRequest = KeePass4Web.ajax('logout', { success: function () { KeePass4Web.clearStorage() this.props.router.replace('/user_login') }.bind(this), error: KeePass4Web.error.bind(this), }) } onCloseDB(event, state) { this.serverRequest = KeePass4Web.ajax('close_db', { success: function () { // redirect to home, so checks for proper login can be made var router = this.props.router // we haven't changed page, so need a workaround router.replace('/db_login') router.replace({ state: state, pathname: '/' }) }.bind(this), error: KeePass4Web.error.bind(this), }) } onTimeUp() { this.onCloseDB(null, { info: 'Database session expired' }) } componentDidMount() { if (KeePass4Web.getSettings().cn) { document.getElementById('logout').addEventListener('click', this.onLogout) document.getElementById('closeDB').addEventListener('click', this.onCloseDB) } } componentWillUnmount() { if (this.serverRequest) this.serverRequest.abort() } render() { var cn = KeePass4Web.getSettings().cn var dropdown, search, timer if (cn) { dropdown = ( <ul className="dropdown-menu"> <li><a id="logout">Logout</a></li> <li role="separator" className="divider"></li> <li><a id="closeDB">Close Database</a></li> </ul> ) } else { cn = 'Not logged in' dropdown = ( <ul className="dropdown-menu"> <li><a href="#/">Login</a></li> </ul> ) } if (this.props.showSearch) { search = ( <form className="navbar-form navbar-left" role="search" onSubmit={this.props.onSearch.bind(this, this.refs)}> <div className="input-group"> <input autoComplete="on" type="search" ref="term" className="form-control" placeholder="Search" autoFocus /> <div className="input-group-btn"> <button type="submit" className="btn btn-default"><span className="glyphicon glyphicon-search"></span></button> </div> </div> </form> ) let timeout = KeePass4Web.getSettings().timeout if (timeout) { timer = ( <div className="navbar-text"> <Timer format='{hh}:{mm}:{ss}' timeout={timeout} onTimeUp={this.onTimeUp} restart={KeePass4Web.restartTimer} /> <label type="button" className="btn btn-secondary btn-xs" onClick={KeePass4Web.restartTimer.bind(this, true)}> <span className="glyphicon glyphicon-repeat"></span> </label> </div> ) } } return ( <nav className="navbar navbar-default navbar-fixed-top"> <div className="navbar-header"> <button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar-collapse-1" aria-expanded="false"> <span className="sr-only">Toggle navigation</span> <span className="icon-bar"></span> <span className="icon-bar"></span> <span className="icon-bar"></span> </button> <a className="navbar-brand" href="#">KeePass 4 Web</a> {timer} </div> <div className="collapse navbar-collapse" id="navbar-collapse-1"> {search} <ul className="nav navbar-nav navbar-right"> <li className="dropdown"> <a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"> {cn} <span className="caret"></span> </a> {dropdown} </li> </ul> </div> </nav> ) } }
src/js/containers/LoginContainer/LoginContainer.js
shane-arthur/react-redux-and-more-boilerplate
import React, { Component } from 'react'; // eslint-disable-line import/first import LoginPanel from '../../components/LoginPanel/LoginPanel'; export default class LoginContainer extends Component { render(){ return ( <div><LoginPanel /></div> ); } }
src/popup/components/PackEdit/Time.js
fluany/fluany
/** * @fileOverview A component to change interval of the package * @name Time.js * @license GNU General Public License v3.0 */ import React from 'react' import PropTypes from 'prop-types' import InputRange from 'react-input-range' import { connect } from 'react-redux' import { changeTimePackage } from 'actions/pack' import { getIndexThingById } from 'reducers/stateManipulate' import * as translator from 'shared/constants/i18n' let Time = ({ onChangeTimePackage, packs, packageid }) => { const handleTimeChange = (component, value) => { onChangeTimePackage(value, packageid) } return ( <section className='time-container'> <h2 className='time-title'>{translator.INTERVAL_MESSAGE}</h2> <InputRange maxValue={60} minValue={1} value={packs[getIndexThingById(packs, packageid)].timeMinutes} onChange={handleTimeChange} defaultValue={5} labelSuffix='min' /> </section> ) } function mapDispatchToProps (dispatch) { return { onChangeTimePackage: (...props) => dispatch(changeTimePackage(...props)) } } const { func, array, string } = PropTypes /** * PropTypes * @property {Function} onChangeTimePackage A action to change the package interval * @property {Array} packs All package availables * @property {String} packageid Id of the package to edit your interval */ Time.propTypes = { onChangeTimePackage: func.isRequired, packs: array.isRequired, packageid: string.isRequired } export default connect(null, mapDispatchToProps)(Time)
src/routes/home/Home.js
bobbybeckner/ha-catalyst-test
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import PropTypes from 'prop-types'; import withStyles from 'isomorphic-style-loader/lib/withStyles'; import s from './Home.css'; class Home extends React.Component { static propTypes = { news: PropTypes.arrayOf( PropTypes.shape({ title: PropTypes.string.isRequired, link: PropTypes.string.isRequired, content: PropTypes.string, }), ).isRequired, }; render() { return ( <div className={s.root}> <div className={s.container}> <h1>React.js News</h1> {this.props.news.map(item => <article key={item.link} className={s.newsItem}> <h1 className={s.newsTitle}> <a href={item.link}> {item.title} </a> </h1> <div className={s.newsDesc} // eslint-disable-next-line react/no-danger dangerouslySetInnerHTML={{ __html: item.content }} /> </article>, )} </div> </div> ); } } export default withStyles(s)(Home);
src/components/LoadingIndicator.js
davendesai/twitchcast
import React, { Component } from 'react'; import { CircularProgress } from 'material-ui'; import '../styles/LoadingIndicator.css'; export default class LoadingIndicator extends Component { render() { return( <div id="twitchcast-loadingindicator"> {this.props.show ? <CircularProgress size={35} color="white" /> : null} </div> ); } } LoadingIndicator.propTypes = { show: React.PropTypes.bool.isRequired }