path
stringlengths
5
195
repo_name
stringlengths
5
79
content
stringlengths
25
1.01M
src/pages/articlePage.js
MartinP-C/my-site
import React from 'react'; import ReactDom from 'react-dom'; const ArticlePage = ({ match }) => ( <div> <p>Article is: {match.params.name}</p> <p>Needs to be built.</p> </div> ) export default ArticlePage;
src/components/FloorSearch/Empty/presenter.js
ndlib/usurper
import React from 'react' import PropTypes from 'prop-types' import PageTitle from 'components/Layout/PageTitle' import SearchProgramaticSet from 'components/SearchProgramaticSet' import SearchCallout from 'components/Contentful/Floor/SearchCallout/index' import Contact from 'components/Contact/ServicePoint' const Empty = (props) => { return ( <div className='contact-page'> <PageTitle title='Unable to Find Map' /> <SearchProgramaticSet open={false} /> <div className='row'> <div className='col-md-8 col-sm-7 floor'> <p>A map cannot be found for this item. Please contact the Circulation Desk for help finding it.</p> <SearchCallout location={props.location} /> {props.points.map(point => ( <div className='point-card' key={point.sys.id}> <h3>{point.fields.title}</h3> <Contact servicePoint={point} /> </div> ))} </div> </div> </div> ) } Empty.propTypes = { location: PropTypes.object, points: PropTypes.arrayOf(PropTypes.shape({ sys: PropTypes.shape({ id: PropTypes.string.isRequired, }).isRequired, fields: PropTypes.shape({ title: PropTypes.string.isRequired, }).isRequired, })).isRequired, } export default Empty
src/stories/index.js
gedeonix/gedeonix-react
import React from 'react'; import { storiesOf, action, linkTo } from '@kadira/storybook'; import {ThemeProvider} from "styled-components"; import theme, { dark } from "../theme"; import Body from "../components/Body"; import Avatar from '../components/Avatar'; import { Container, FluidContainer } from '../components/Container'; import Button, {PrimaryButton, SuccessButton, WarningButton, DangerButton, LightButton, DarkButton} from '../components/Button'; import { TwitterButton, FacebookButton, GoogleButton, GithubButton, RssButton } from '../components/Social'; import { Input } from '../components/Input'; import { Icon, IconButton } from '../components/Icon'; import { Row, Col } from '../components/Grid'; import { Table, Th, Td } from '../components/Table'; import AppBar from '../components/AppBar'; import Drawer, { DrawerHeader, DrawerItem } from '../components/Drawer'; storiesOf('Components', module) .add('Button', () => ( <ThemeProvider theme={theme}> <dev> <h1>Button</h1> <Button onClick={action('clicked')}>Button</Button> <h2>Block</h2> <Button onClick={action('clicked')} block>Block</Button> <h2>Colors</h2> <Button onClick={action('clicked')}>Default</Button> <PrimaryButton onClick={action('clicked')}>Primary</PrimaryButton> <SuccessButton onClick={action('clicked')}>Success</SuccessButton> <WarningButton onClick={action('clicked')}>Warning</WarningButton> <DangerButton onClick={action('clicked')}>Danger</DangerButton> <LightButton onClick={action('clicked')}>Light</LightButton> <DarkButton onClick={action('clicked')}>Dark</DarkButton> <h2>Round</h2> <Button onClick={action('clicked')} round>Default</Button> <PrimaryButton onClick={action('clicked')} round>Primary</PrimaryButton> <SuccessButton onClick={action('clicked')} round>Success</SuccessButton> <WarningButton onClick={action('clicked')} round>Warning</WarningButton> <DangerButton onClick={action('clicked')} round>Danger</DangerButton> <LightButton onClick={action('clicked')} round>Light</LightButton> <DarkButton onClick={action('clicked')} round>Dark</DarkButton> <h2>Reset radius</h2> <Button onClick={action('clicked')} resetRadius>Default</Button> <PrimaryButton onClick={action('clicked')} resetRadius>Primary</PrimaryButton> <SuccessButton onClick={action('clicked')} resetRadius>Success</SuccessButton> <WarningButton onClick={action('clicked')} resetRadius>Warning</WarningButton> <DangerButton onClick={action('clicked')} resetRadius>Danger</DangerButton> <LightButton onClick={action('clicked')} resetRadius>Light</LightButton> <DarkButton onClick={action('clicked')} resetRadius>Dark</DarkButton> <h2>Outline</h2> <Button onClick={action('clicked')} outline>Default</Button> <PrimaryButton onClick={action('clicked')} outline>Primary</PrimaryButton> <SuccessButton onClick={action('clicked')} outline>Success</SuccessButton> <WarningButton onClick={action('clicked')} outline>Warning</WarningButton> <DangerButton onClick={action('clicked')} outline>Danger</DangerButton> <LightButton onClick={action('clicked')} outline>Light</LightButton> <DarkButton onClick={action('clicked')} outline>Dark</DarkButton> <h2>Size</h2> <Button xs>Extra small</Button> <Button sm>Small</Button> <Button>Normal</Button> <Button md>Middle</Button> <Button lg>Large</Button> <h2>Disabled</h2> <Button disabled onClick={action('clicked')}>Default</Button> <PrimaryButton disabled onClick={action('clicked')}>Primary</PrimaryButton> <SuccessButton disabled onClick={action('clicked')}>Success</SuccessButton> <WarningButton disabled onClick={action('clicked')}>Warning</WarningButton> <DangerButton disabled onClick={action('clicked')}>Danger</DangerButton> <LightButton disabled onClick={action('clicked')}>Light</LightButton> <DarkButton disabled onClick={action('clicked')}>Dark</DarkButton> <h2>Icon & text</h2> <Button onClick={action('clicked')}><Icon name="check"/> Default</Button> <PrimaryButton onClick={action('clicked')}><Icon name="check"/> Primary</PrimaryButton> <SuccessButton onClick={action('clicked')}><Icon name="check"/> Success</SuccessButton> <WarningButton onClick={action('clicked')}><Icon name="check"/> Warning</WarningButton> <DangerButton onClick={action('clicked')}><Icon name="check"/> Danger</DangerButton> <LightButton onClick={action('clicked')}><Icon name="check"/> Light</LightButton> <DarkButton onClick={action('clicked')}><Icon name="check"/> Dark</DarkButton> <h2>Only icon</h2> <Button onClick={action('clicked')}><Icon name="check"/></Button> <PrimaryButton onClick={action('clicked')}><Icon name="check"/></PrimaryButton> <SuccessButton onClick={action('clicked')}><Icon name="check"/></SuccessButton> <WarningButton onClick={action('clicked')}><Icon name="check"/></WarningButton> <DangerButton onClick={action('clicked')}><Icon name="check"/></DangerButton> <LightButton onClick={action('clicked')}><Icon name="check"/></LightButton> <DarkButton onClick={action('clicked')}><Icon name="check"/></DarkButton> <h2>Square</h2> <Button onClick={action('clicked')} square><Icon name="check"/></Button> <PrimaryButton onClick={action('clicked')} square><Icon name="check"/></PrimaryButton> <SuccessButton onClick={action('clicked')} square><Icon name="check"/></SuccessButton> <WarningButton onClick={action('clicked')} square><Icon name="check"/></WarningButton> <DangerButton onClick={action('clicked')} square><Icon name="check"/></DangerButton> <LightButton onClick={action('clicked')} square><Icon name="check"/></LightButton> <DarkButton onClick={action('clicked')} square><Icon name="check"/></DarkButton> <br/> <Button onClick={action('clicked')} square xs><Icon name="check"/></Button> <Button onClick={action('clicked')} square sm><Icon name="check"/></Button> <Button onClick={action('clicked')} square><Icon name="check"/></Button> <Button onClick={action('clicked')} square md><Icon name="check"/></Button> <Button onClick={action('clicked')} square lg><Icon name="check"/></Button> <h2>Circle</h2> <Button onClick={action('clicked')} circle><Icon name="check"/></Button> <PrimaryButton onClick={action('clicked')} circle><Icon name="check"/></PrimaryButton> <SuccessButton onClick={action('clicked')} circle><Icon name="check"/></SuccessButton> <WarningButton onClick={action('clicked')} circle><Icon name="check"/></WarningButton> <DangerButton onClick={action('clicked')} circle><Icon name="check"/></DangerButton> <LightButton onClick={action('clicked')} circle><Icon name="check"/></LightButton> <DarkButton onClick={action('clicked')} circle><Icon name="check"/></DarkButton> <br/> <Button onClick={action('clicked')} circle xs><Icon name="check"/></Button> <Button onClick={action('clicked')} circle sm><Icon name="check"/></Button> <Button onClick={action('clicked')} circle><Icon name="check"/></Button> <Button onClick={action('clicked')} circle md><Icon name="check"/></Button> <Button onClick={action('clicked')} circle lg><Icon name="check"/></Button> <h2>Social</h2> <TwitterButton onClick={action('clicked')}><Icon name="twitter"/> Twitter</TwitterButton> <FacebookButton onClick={action('clicked')}><Icon name="facebook"/> Facebook</FacebookButton> <GoogleButton onClick={action('clicked')}><Icon name="google"/> Google</GoogleButton> <GithubButton onClick={action('clicked')}><Icon name="github"/> Github</GithubButton> <RssButton onClick={action('clicked')}><Icon name="rss"/> Rss</RssButton> <br/> <TwitterButton onClick={action('clicked')} circle><Icon name="twitter"/></TwitterButton> <FacebookButton onClick={action('clicked')} circle><Icon name="facebook"/></FacebookButton> <GoogleButton onClick={action('clicked')} circle><Icon name="google"/></GoogleButton> <GithubButton onClick={action('clicked')} circle><Icon name="github"/></GithubButton> <RssButton onClick={action('clicked')} circle><Icon name="rss"/></RssButton> <h2>Misc</h2> <Button onClick={action('clicked')}><Icon name="angle-left"/></Button> <Button onClick={action('clicked')}><Icon name="angle-right"/></Button> <PrimaryButton onClick={action('clicked')}><Icon name="plus"/> Add</PrimaryButton> <DangerButton onClick={action('clicked')}>Remove <Icon name="remove"/></DangerButton> <DarkButton onClick={action('clicked')}>Options <Icon name="chevron-down"/></DarkButton> <WarningButton onClick={action('clicked')} outline>Print <Icon name="print"/></WarningButton> <LightButton onClick={action('clicked')} outline>Download <Icon name="download"/></LightButton> <SuccessButton onClick={action('clicked')} circle><Icon name="thumbs-o-up"/></SuccessButton> <DangerButton onClick={action('clicked')} circle><Icon name="thumbs-o-down"/></DangerButton> </dev> </ThemeProvider> )) .add('Icon & IconButton', () => ( <ThemeProvider theme={theme}> <dev> <h1>Icon</h1> <Icon name="plus"/> <Icon name="bars"/> <Icon name="minus"/> <h2>Spin</h2> <Icon spin name="circle-o-notch"/> <Icon spin name="refresh"/> <Icon spin name="spinner"/> <Icon spin name="cog"/> <h2>Pulse</h2> <Icon pulse name="cog"/> <Icon pulse name="refresh"/> <Icon pulse name="spinner"/> <Icon pulse name="cog"/> <h1>IconButton</h1> <IconButton icon="plus" onClick={action('clicked')}/> </dev> </ThemeProvider> )) .add('Input', () => ( <ThemeProvider theme={theme}> <dev> <h1>Input</h1> <Input placeholder="input..."/> <h2>Size</h2> <Input placeholder="xs..." xs/> <br/><br/> <Input placeholder="sm..." sm/> <br/><br/> <Input placeholder="default..."/> <br/><br/> <Input placeholder="md..." md/> <br/><br/> <Input placeholder="lg..." lg/> </dev> </ThemeProvider> )) .add('Link', () => ( <div> todo... </div> )) .add('Group', () => ( <div> todo... </div> )) .add('Checkbox', () => ( <div> todo... </div> )) .add('Radio', () => ( <div> todo... </div> )) .add('Select', () => ( <div> todo... </div> )) .add('Textarea', () => ( <div> todo... </div> )) .add('Close button', () => ( <div> todo... </div> )) .add('Label', () => ( <div> todo... </div> )) .add('Tag', () => ( <div> todo... </div> )) .add('Badge', () => ( <div> todo... </div> )) .add('Popup', () => ( <div> todo... </div> )) .add('Alert', () => ( <div> todo... </div> )) .add('Avatar', () => ( <div> <Avatar url="http://placekitten.com/g/64/64" /> <Avatar url="http://placekitten.com/g/64/64" round /> <Avatar url="http://placekitten.com/g/200/200" size="100" /> <Avatar url="http://placekitten.com/g/200/200" size="100" round /> </div> )) ; storiesOf('Containers', module) .add('Container & Fluid', () => ( <div> <Container style={{backgroundColor: '#ffff80', outline: '1px dashed #ff0000'}}>Container</Container> <br/> <FluidContainer style={{backgroundColor: '#ffff80', outline: '1px dashed #ff0000'}}>Fluid container</FluidContainer> </div> )) .add('Cards', () => ( <div> todo... </div> )) .add('Tables', () => ( <dev> <Table> <thead> <tr> <Th>A</Th> <Th>B</Th> <Th>C</Th> </tr> </thead> <tbody> <tr> <Td>1</Td> <Td>2</Td> <Td>3</Td> </tr> <tr> <Td>4</Td> <Td>5</Td> <Td>6</Td> </tr> </tbody> </Table> </dev> )) .add('Tiles', () => ( <div> todo... </div> )) ; storiesOf('Grids', module) .add('Flex grid', () => ( <dev> <Row> <Col>1</Col> <Col>2</Col> <Col>3</Col> <Col>4</Col> <Col>5</Col> <Col>6</Col> <Col>7</Col> <Col>8</Col> <Col>9</Col> <Col>10</Col> <Col>11</Col> <Col>12</Col> </Row> </dev> )) ; storiesOf('Navigation', module) .add('Drawer', () => ( <dev> <Drawer open items={[]} position="relative"> <DrawerHeader>Title</DrawerHeader> <DrawerItem>Item 1</DrawerItem> <DrawerItem>Item 2</DrawerItem> <DrawerItem>Item 3</DrawerItem> </Drawer> </dev> )) .add('AppBar', () => ( <dev> <AppBar title="Title" toggleDrawer={action('toggle')} /> </dev> )) ; storiesOf('Forms', module) ; storiesOf('Modal', module) ; storiesOf('Typography', module) ; storiesOf('Themes', module) .add('Light', () => ( <ThemeProvider theme={theme}> <dev> <DangerButton>Button</DangerButton> </dev> </ThemeProvider> )) .add('Dark', () => ( <ThemeProvider theme={dark}> <dev> <DangerButton>Button</DangerButton> </dev> </ThemeProvider> )) ;
tosort/2016/jspm/lib_react_101/components/step/index.js
Offirmo/web-tech-experiments
import React from 'react'; import ListItem from 'material-ui/lib/lists/list-item'; import Colors from 'material-ui/lib/styles/colors'; import IconButton from 'material-ui/lib/icon-button'; import MoreVertIcon from 'material-ui/lib/svg-icons/navigation/more-vert'; import IconMenu from 'material-ui/lib/menus/icon-menu'; import MenuItem from 'material-ui/lib/menus/menu-item'; import FontIcon from 'material-ui/lib/font-icon'; import moment from 'moment' import 'moment/locale/fr' const LOCALE = 'fr' const DATE_FORMAT = 'lll' const iconStyles = { marginRight: 24, }; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left" > <MoreVertIcon color={Colors.grey400} /> </IconButton> ); const rightIconMenu = ( <IconMenu iconButtonElement={iconButtonElement}> <MenuItem>Reply</MenuItem> <MenuItem>Forward</MenuItem> <MenuItem>Delete</MenuItem> </IconMenu> ); export default class Step extends React.Component { render () { let icon, color switch(this.props.type) { default: icon = 'flight_takeoff' color = Colors.red500 break } const date_string = moment(this.props.start_date).locale(LOCALE).format(DATE_FORMAT) const primary_text = `${date_string} - ${this.props.start_place}` const secondaryText = `${this.props.duration_min} min.` return ( <ListItem leftIcon={<FontIcon className="material-icons" style={iconStyles} color={color}>{icon}</FontIcon>} rightIconButton={rightIconMenu} primaryText={primary_text} secondaryText={secondaryText} secondaryTextLines={1} /> ) } } Step.propTypes = { type: React.PropTypes.string, start_place: React.PropTypes.string, start_date: React.PropTypes.object, duration_min: React.PropTypes.number } Step.defaultProps = { type: 'visit', start_place: '?', start_date: Date.now(), duration_min: 30 }
app/containers/Sign/SubMenu.js
coocooooo/webapp
import React, { Component } from 'react'; import styled from 'styled-components'; import { Link } from 'react-router'; const Menu = styled.div` margin-left: 0em; margin-right: 0em; border-bottom: 2px solid rgba(34, 36, 38, 0.15); background: none; border-radius: 0em; border: none; box-shadow: none; font-size: 1rem; min-height: 2.85714286em; display: flex; font-family: 'Lato', 'Helvetica Neue', Arial, Helvetica, sans-serif; margin-bottom: 1rem; `; const Right = styled.div` margin-left: auto; display: flex; border-bottom: 2px solid rgba(34,36,38,.15); `; const StyledLink = styled(Link) ` border-bottom-color: transparent; border-bottom-style: solid; border-radius: 0em; align-self: flex-end; margin: 0em 0em -2px; padding: 0.85714286em 1.14285714em; border-bottom-width: 2px; transition: color 0.1s ease; display: flex; align-items: center; position: relative; vertical-align: middle; line-height: 1; text-decoration: none; user-select: none; flex: 0 0 auto; text-transform: none; color: rgba(0, 0, 0, 0.87); font-weight: normal; cursor: pointer; `; const activeStyle = { backgroundColor: 'transparent', boxShadow: 'none', borderColor: '#1B1C1D', fontWeight: '700', color: 'rgba(0,0,0,.95)', }; class SubMenu extends Component { render() { return ( <Menu> <Right> <StyledLink to="/emailsignup/signup" activeStyle={activeStyle}> SignUp</StyledLink> <StyledLink to="/emailsignup/signin" activeStyle={activeStyle}> SignIn</StyledLink> </Right> </Menu> ); } } export default SubMenu;
app/client/src/components/SignupRegisterLogin/components/ActionSignupModal/ActionSignupModal.js
uprisecampaigns/uprise-app
/* eslint-disable max-len */ import PropTypes from 'prop-types'; import React, { Component } from 'react'; import { connect } from 'react-redux'; import { compose, graphql } from 'react-apollo'; import moment from 'moment'; import isEqual from 'lodash.isequal'; import Checkbox from 'material-ui/Checkbox'; import Divider from 'material-ui/Divider'; import Dialog from 'material-ui/Dialog'; import Link from 'components/Link'; import ConfirmEmailPrompt from 'components/ConfirmEmailPrompt'; import withTimeWithZone from 'lib/withTimeWithZone'; import { notify } from 'actions/NotificationsActions'; import { closedModal } from 'actions/ActionSignupActions'; import MeQuery from 'schemas/queries/MeQuery.graphql'; import ActionSignupMutation from 'schemas/mutations/ActionSignupMutation.graphql'; import CancelActionSignupMutation from 'schemas/mutations/CancelActionSignupMutation.graphql'; import s from 'styles/SignupRegisterLogin.scss'; export class ActionSignupModal extends Component { static propTypes = { action: PropTypes.object, userObject: PropTypes.object.isRequired, timeWithZone: PropTypes.func.isRequired, dispatch: PropTypes.func.isRequired, signup: PropTypes.func.isRequired, cancelAttendance: PropTypes.func.isRequired, }; static defaultProps = { action: undefined, }; constructor(props) { super(props); const { action } = props; const startingPage = action.ongoing ? 1 : 0; const shifts = Array.isArray(action.shifts) ? [...action.shifts].map(this.mapShift) : []; if (Array.isArray(action.signedUpShifts)) { action.signedUpShifts.forEach((signedUpShift) => { shifts.find((shift) => shift.id === signedUpShift.id).selected = true; }); } this.state = { agreeToShare: false, page: startingPage, shifts, attending: action.attending, }; } mapShift = (shift) => ({ id: shift.id, start: shift.start, end: shift.end, selected: shift.selected, }); toggleCheck = (toggleShift) => { const shifts = [...this.state.shifts].map(this.mapShift); // eslint-disable-next-line no-restricted-syntax for (const shift of shifts) { if (isEqual(shift, this.mapShift(toggleShift))) { shift.selected = !shift.selected; } } this.setState({ shifts }); }; selectShifts = () => { if (this.state.shifts.filter((shift) => shift.selected).length) { this.setState({ page: 1 }); } else { this.props.dispatch(notify('Please select at least one shift')); } }; confirmSignup = async () => { if (this.state.agreeToShare) { try { await this.props.signup({ variables: { actionId: this.props.action.id, shifts: this.state.shifts .filter((shift) => shift.selected) .map((shift) => ({ id: shift.id, start: shift.start, end: shift.end })), }, // TODO: decide between refetch and update refetchQueries: ['ActionCommitmentsQuery', 'SignedUpVolunteersQuery', 'ActionQuery'], }); this.props.dispatch(notify('Signed up!')); this.setState({ page: 2 }); } catch (e) { console.error(e); this.props.dispatch( notify( 'There was an error with your request. Please reload the page or contact [email protected] for support.', ), ); } } else { this.props.dispatch(notify('In order to sign up for this, you must agree to share your contact info.')); } }; cancelAttendance = async () => { try { await this.props.cancelAttendance({ variables: { actionId: this.props.action.id, }, // TODO: decide between refetch and update refetchQueries: ['ActionCommitmentsQuery', 'SignedUpVolunteersQuery', 'ActionQuery'], }); this.setState({ page: 2 }); } catch (e) { console.error(e); this.props.dispatch( notify('There was an error with your request. Please reload the page or contact [email protected] for support.'), ); } }; formatShiftLine = (shift) => { const { action, timeWithZone } = this.props; let zipcode = action.zipcode; if (!action.zipcode && action.campaign && action.campaign.zipcode) { zipcode = action.campaign.zipcode; } return `${timeWithZone(shift.start, zipcode, 'ddd MMM Do: h:mm')} - ${timeWithZone( shift.end, zipcode, 'h:mm a z', )}`; }; render() { const { action, userObject } = this.props; const { shifts, page, agreeToShare, attending } = this.state; const { toggleCheck, selectShifts, confirmSignup, formatShiftLine, cancelAttendance } = this; let dialogContent; switch (page) { case 0: { const shiftsList = [...shifts].filter((shift) => moment(shift.end).isAfter(moment())).map((shift) => { const timeDisplay = formatShiftLine(shift); return ( <div key={JSON.stringify(shift)}> <Checkbox label={timeDisplay} checked={shift.selected} onCheck={() => toggleCheck(shift)} className={s.shiftCheckbox} /> </div> ); }); dialogContent = ( <div className={s.container}> <div className={s.header}>Select Shifts</div> {shiftsList} <Divider /> <div className={s.buttonContainer}> {attending && ( <div className={s.cancelButton} onClick={cancelAttendance} onKeyPress={cancelAttendance} role="button" tabIndex="0" > I can no longer attend this event </div> )} <div className={s.primaryButton} onClick={selectShifts} onKeyPress={selectShifts} role="button" tabIndex="0" > Continue </div> </div> </div> ); break; } case 1: { if (attending && action.ongoing) { dialogContent = ( <div className={s.container}> <div className={s.header}>Cancel</div> <div className={s.content}> <div>{action.title}</div> <div>Please cancel my sign-up for this volunteer opportunity and notify the campaign coordinator.</div> </div> <Divider /> <div className={s.cancelButton} onClick={cancelAttendance} onKeyPress={cancelAttendance} role="button" tabIndex="0" > Cancel my signup </div> </div> ); } else { dialogContent = ( <div className={s.container}> {attending ? ( <div className={s.header}>Confirm Changes</div> ) : ( <div className={s.header}>Almost there!</div> )} <div className={s.content}> <div>{action.title}</div> {!action.ongoing && ( <div> <div className={s.label}>Shifts selected</div> {shifts .filter((shift) => shift.selected) .map((shift) => <div key={JSON.stringify(shift)}>{formatShiftLine(shift)}</div>)} </div> )} <div className={s.label}>Your Name:</div> <div> {userObject.first_name} {userObject.last_name} </div> <div className={s.label}>Your Email:</div> <div>{userObject.email}</div> </div> <Divider /> <Checkbox label="Share my contact details with the campaign manager" checked={agreeToShare} onCheck={() => this.setState({ agreeToShare: !agreeToShare })} className={s.checkbox} /> <div className={s.primaryButton} onClick={confirmSignup} onKeyPress={confirmSignup} role="button" tabIndex="0" > Sign up now </div> </div> ); } break; } case 2: { if (attending) { dialogContent = ( <div className={s.container}> <div className={s.header}>Your scheduled shifts have been successfully changed.</div> <div className={s.button} onClick={(e) => this.props.dispatch(closedModal())} onKeyPress={(e) => this.props.dispatch(closedModal())} role="button" tabIndex="0" > Done </div> </div> ); } else { dialogContent = ( <div className={s.container}> <div className={s.header}>You&apos;ve been signed up</div> <div className={s.content}> Thank you so much for signing up. Saved events will show up in your profile so you can easily view them later. </div> <Divider /> <Link to="/volunteer" useAhref={false}> <div className={s.button} onClick={(e) => this.props.dispatch(closedModal())} onKeyPress={(e) => this.props.dispatch(closedModal())} role="button" tabIndex="0" > View Events </div> </Link> </div> ); } break; } default: { dialogContent = null; break; } } // if (userObject.email_confirmed) { return ( <Dialog modal={false} open onRequestClose={() => this.props.dispatch(closedModal())} autoScrollBodyContent autoDetectWindowHeight repositionOnUpdate > {dialogContent} </Dialog> ); // } // return ( // <ConfirmEmailPrompt // modal={false} // handleResend={() => this.props.dispatch(closedModal())} // handleError={() => this.props.dispatch(closedModal())} // /> // ); } } const mapStateToProps = (state) => ({ action: state.actionSignup.action, loggedIn: state.userAuthSession.isLoggedIn, fetchingAuthUpdate: state.userAuthSession.fetchingAuthUpdate, }); const withMeQuery = graphql(MeQuery, { props: ({ data }) => ({ userObject: !data.loading && data.me ? data.me : { email: '', }, }), skip: (ownProps) => !ownProps.loggedIn && !ownProps.fetchingAuthUpdate, }); export default compose( withTimeWithZone, connect(mapStateToProps), withMeQuery, graphql(ActionSignupMutation, { name: 'signup' }), graphql(CancelActionSignupMutation, { name: 'cancelAttendance' }), )(ActionSignupModal);
node_modules/react-bootstrap/es/SplitButton.js
geng890518/editor-ui
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties'; import _classCallCheck from 'babel-runtime/helpers/classCallCheck'; import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn'; import _inherits from 'babel-runtime/helpers/inherits'; import _extends from 'babel-runtime/helpers/extends'; import React from 'react'; import PropTypes from 'prop-types'; import Button from './Button'; import Dropdown from './Dropdown'; import SplitToggle from './SplitToggle'; import splitComponentProps from './utils/splitComponentProps'; var propTypes = _extends({}, Dropdown.propTypes, { // Toggle props. bsStyle: PropTypes.string, bsSize: PropTypes.string, href: PropTypes.string, onClick: PropTypes.func, /** * The content of the split button. */ title: PropTypes.node.isRequired, /** * Accessible label for the toggle; the value of `title` if not specified. */ toggleLabel: PropTypes.string, // Override generated docs from <Dropdown>. /** * @private */ children: PropTypes.node }); var SplitButton = function (_React$Component) { _inherits(SplitButton, _React$Component); function SplitButton() { _classCallCheck(this, SplitButton); return _possibleConstructorReturn(this, _React$Component.apply(this, arguments)); } SplitButton.prototype.render = function render() { var _props = this.props, bsSize = _props.bsSize, bsStyle = _props.bsStyle, title = _props.title, toggleLabel = _props.toggleLabel, children = _props.children, props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'toggleLabel', 'children']); var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent), dropdownProps = _splitComponentProps[0], buttonProps = _splitComponentProps[1]; return React.createElement( Dropdown, _extends({}, dropdownProps, { bsSize: bsSize, bsStyle: bsStyle }), React.createElement( Button, _extends({}, buttonProps, { disabled: props.disabled, bsSize: bsSize, bsStyle: bsStyle }), title ), React.createElement(SplitToggle, { 'aria-label': toggleLabel || title, bsSize: bsSize, bsStyle: bsStyle }), React.createElement( Dropdown.Menu, null, children ) ); }; return SplitButton; }(React.Component); SplitButton.propTypes = propTypes; SplitButton.Toggle = SplitToggle; export default SplitButton;
renderer/vectors/edit.js
wulkano/kap
import React from 'react'; import Svg from './svg'; const EditIcon = props => ( <Svg {...props}> <path d="M3 17.3V21h3.8l11-11-3.7-3.8L3 17.2zM20.7 7c.4-.4.4-1 0-1.4l-2.3-2.3a1 1 0 0 0-1.4 0L15 5 19 9 20.7 7z"/> <path d="M0 0h24v24H0z" fill="none"/> </Svg> ); export default EditIcon;
js/jqwidgets/jqwidgets-react/react_jqxcomplexinput.js
luissancheza/sice
/* jQWidgets v5.3.2 (2017-Sep) Copyright (c) 2011-2017 jQWidgets. License: http://jqwidgets.com/license/ */ import React from 'react'; const JQXLite = window.JQXLite; export const jqx = window.jqx; export default class JqxComplexInput extends React.Component { componentDidMount() { let options = this.manageAttributes(); this.createComponent(options); }; manageAttributes() { let properties = ['decimalNotation','disabled','height','placeHolder','roundedCorners','rtl','spinButtons','spinButtonsStep','template','theme','value','width']; let options = {}; for(let item in this.props) { if(item === 'settings') { for(let itemTwo in this.props[item]) { options[itemTwo] = this.props[item][itemTwo]; } } else { if(properties.indexOf(item) !== -1) { options[item] = this.props[item]; } } } return options; }; createComponent(options) { if(!this.style) { for (let style in this.props.style) { JQXLite(this.componentSelector).css(style, this.props.style[style]); } } if(this.props.className !== undefined) { let classes = this.props.className.split(' '); for (let i = 0; i < classes.length; i++ ) { JQXLite(this.componentSelector).addClass(classes[i]); } } if(!this.template) { JQXLite(this.componentSelector).html(this.props.template); } JQXLite(this.componentSelector).jqxComplexInput(options); }; setOptions(options) { JQXLite(this.componentSelector).jqxComplexInput('setOptions', options); }; getOptions() { if(arguments.length === 0) { throw Error('At least one argument expected in getOptions()!'); } let resultToReturn = {}; for(let i = 0; i < arguments.length; i++) { resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxComplexInput(arguments[i]); } return resultToReturn; }; on(name,callbackFn) { JQXLite(this.componentSelector).on(name,callbackFn); }; off(name) { JQXLite(this.componentSelector).off(name); }; decimalNotation(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('decimalNotation', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('decimalNotation'); } }; disabled(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('disabled', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('disabled'); } }; height(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('height', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('height'); } }; placeHolder(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('placeHolder', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('placeHolder'); } }; roundedCorners(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('roundedCorners', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('roundedCorners'); } }; rtl(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('rtl', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('rtl'); } }; spinButtons(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('spinButtons', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('spinButtons'); } }; spinButtonsStep(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('spinButtonsStep', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('spinButtonsStep'); } }; template(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('template', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('template'); } }; theme(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('theme', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('theme'); } }; value(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('value', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('value'); } }; width(arg) { if (arg !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('width', arg) } else { return JQXLite(this.componentSelector).jqxComplexInput('width'); } }; destroy() { JQXLite(this.componentSelector).jqxComplexInput('destroy'); }; getReal(complexNumber) { return JQXLite(this.componentSelector).jqxComplexInput('getReal', complexNumber); }; getImaginary(complexNumber) { return JQXLite(this.componentSelector).jqxComplexInput('getImaginary', complexNumber); }; getDecimalNotation(part, type) { return JQXLite(this.componentSelector).jqxComplexInput('getDecimalNotation', part, type); }; performRender() { JQXLite(this.componentSelector).jqxComplexInput('render'); }; refresh() { JQXLite(this.componentSelector).jqxComplexInput('refresh'); }; val(value) { if (value !== undefined) { JQXLite(this.componentSelector).jqxComplexInput('val', value) } else { return JQXLite(this.componentSelector).jqxComplexInput('val'); } }; render() { let id = 'jqxComplexInput' + JQXLite.generateID(); this.componentSelector = '#' + id; return ( <div id={id}> <input type='text'></input> <div></div> </div> ) }; };
imports/ui/components/giveaways/nearby-giveaways.js
irvinlim/free4all
import React from 'react'; import { List, ListItem } from 'material-ui/List'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import Avatar from 'material-ui/Avatar'; import * as Helper from '../../../util/helper'; import * as AvatarHelper from '../../../util/avatar'; import * as GiveawaysHelper from '../../../util/giveaways'; import * as Colors from 'material-ui/styles/colors'; const giveawayRow = (touchTapHandler) => (ga) => ( <ListItem key={ ga._id } primaryText={ga.title} secondaryText={ <p>{ GiveawaysHelper.compactDateRange(ga) }<br/>{ ga.location }</p> } leftAvatar={ GiveawaysHelper.makeAvatar(ga, 40) } secondaryTextLines={2} onTouchTap={ touchTapHandler(ga) } /> ); export const NearbyGiveaways = (props) => ( <List> <Subheader> <h3 style={{ margin:"20px 0px 10px" }}>Available Giveaways</h3> <h5 style={{ margin: "10px 0 20px", color: "#6d6d6d" }}>Only ongoing giveaways (up to 1 week in the future) from your communities are displayed here.</h5> </Subheader> <Divider /> { props.giveaways ? Helper.insertDividers(props.giveaways.map(giveawayRow(props.nearbyOnClick))) : <div /> } </List> );
src/components/fluid-commons/fluid-table/TableBody.js
great-design-and-systems/cataloguing-app
import { TABLE_ADD_ROW, TABLE_CANCEL_EDIT, TABLE_EDIT, TABLE_REFRESH, TABLE_SET_NEW_VALUE, TABLE_SUBMIT_NEW_VALUE } from './fluid.info'; import FluidFunc from 'fluid-func'; import PropTypes from 'prop-types'; import React from 'react'; import { TableRow } from './TableRow'; export class TableBody extends React.Component { constructor(props) { super(props); this.state = { value: [], editable: false, column: '', editableIndex: 0, newRow: {} }; this.thisRefresh = this.refresh.bind(this); this.thisSetEditable = this.setEditable.bind(this); this.thisCancelEditable = this.cancelEditable.bind(this); this.thisAddRow = this.addRow.bind(this); this.thisSetNewRowValue = this.setNewRowValue.bind(this); this.thisSubmitNewRowValue = this.submitNewRowValue.bind(this); FluidFunc .create(`${TABLE_REFRESH}${this.props.name}`) .onStart(() => { this.thisCancelEditable(); this.thisRefresh(); }); FluidFunc .create(`${TABLE_EDIT}${this.props.name}`) .onStart(parameter => { const field = parameter.field(); const index = parameter.index(); this.thisSetEditable(field, index); }) .spec('field', { require: true }) .spec('index', { require: true }); FluidFunc .create(`${TABLE_CANCEL_EDIT}${this.props.name}`) .onStart(this.thisCancelEditable); FluidFunc.create(`${TABLE_ADD_ROW}${this.props.name}`) .onStart(this.thisAddRow); FluidFunc.create(`${TABLE_SET_NEW_VALUE}${this.props.name}`) .onStart(this.thisSetNewRowValue) .spec('field', { require: true }) .spec('value') .cache(1000); FluidFunc.create(`${TABLE_SUBMIT_NEW_VALUE}${this.props.name}`) .onStart(this.thisSubmitNewRowValue); } componentWillMount() { this.setTableValue(this.props); this.refresh(); } componentWillReceiveProps(nextProps) { let value = nextProps.value; if (!(value instanceof Function)) { if (this.state.value != value) { this.setTableValue(nextProps); } else if ((this.state.value && value instanceof Array && !!value) && this.state.value.length !== value.length) { this.setTableValue(nextProps); } else if (value instanceof Promise) { this.setTableValue(nextProps); } } } refresh() { if (this.props.value instanceof Function) { const value = this.props.value(); this.setTableValue(value); } } setTableValue(value) { if (value) { if (value instanceof Promise) { value.then(result => { this.setValue(result); }); } else { this.setValue(value); } } } setValue(value) { if (this.state.value != value) { this.setState({ value }); } else if (this.state.value && value && this.state.value.length !== value.length) { this.setState({ value }); } } setEditable(column, editableIndex) { this.setState({ editable: true, column, editableIndex }); } cancelEditable() { this.setState({ editable: false, column: '', editableIndex: 0 }); const value = [...this.state.value]; value.forEach((row, index) => { if (row.isNew) { value.splice(index, 1); } }); this.setState({ value }); } addRow() { const value = [...this.state.value]; value.push({ isNew: true }); this.setState({ value }); } setNewRowValue(parameter) { const field = parameter.field(); const value = parameter.value(); const newRow = { ...this.state.newRow }; newRow[field] = value; this.setState({ newRow }); } submitNewRowValue() { const newRow = { ...this.state.newRow }; const value = [...this.state.value]; value.forEach(row => { if (row.isNew) { row.isNew = false; for (let field in newRow) { if (newRow.hasOwnProperty(field)) { row[field] = newRow[field]; } } } }); this.setState({ value, newRow: {} }); return newRow; } render() { return (<tbody> {this.state.value && this.state.value.map && this.state.value.map((row, index) => (<TableRow editableIndex={this.state.editableIndex} editable={this.state.editable} column={this.state.column} tableName={this.props.name} rowClass={this.props.rowClass} columnClass={this.props.columnClass} index={index} key={this.props.fieldKey ? row[this.props.fieldKey] : index} value={row} columns={this.props.columns} />))} </tbody>); } } TableBody.propTypes = { value: PropTypes.oneOfType([ PropTypes.array, PropTypes.object, PropTypes.func ]), columnClass: PropTypes.string, columns: PropTypes.array, fieldKey: PropTypes.string, name: PropTypes.string.isRequired, rowClass: PropTypes.string };
app/javascript/mastodon/components/column_header.js
riku6460/chikuwagoddon
import React from 'react'; import PropTypes from 'prop-types'; import classNames from 'classnames'; import { FormattedMessage, injectIntl, defineMessages } from 'react-intl'; const messages = defineMessages({ show: { id: 'column_header.show_settings', defaultMessage: 'Show settings' }, hide: { id: 'column_header.hide_settings', defaultMessage: 'Hide settings' }, moveLeft: { id: 'column_header.moveLeft_settings', defaultMessage: 'Move column to the left' }, moveRight: { id: 'column_header.moveRight_settings', defaultMessage: 'Move column to the right' }, }); export default @injectIntl class ColumnHeader extends React.PureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { intl: PropTypes.object.isRequired, title: PropTypes.node, icon: PropTypes.string, active: PropTypes.bool, multiColumn: PropTypes.bool, extraButton: PropTypes.node, showBackButton: PropTypes.bool, children: PropTypes.node, pinned: PropTypes.bool, onPin: PropTypes.func, onMove: PropTypes.func, onClick: PropTypes.func, }; state = { collapsed: true, animating: false, }; historyBack = () => { if (window.history && window.history.length === 1) { this.context.router.history.push('/'); } else { this.context.router.history.goBack(); } } handleToggleClick = (e) => { e.stopPropagation(); this.setState({ collapsed: !this.state.collapsed, animating: true }); } handleTitleClick = () => { this.props.onClick(); } handleMoveLeft = () => { this.props.onMove(-1); } handleMoveRight = () => { this.props.onMove(1); } handleBackClick = () => { this.historyBack(); } handleTransitionEnd = () => { this.setState({ animating: false }); } handlePin = () => { if (!this.props.pinned) { this.historyBack(); } this.props.onPin(); } render () { const { title, icon, active, children, pinned, multiColumn, extraButton, showBackButton, intl: { formatMessage } } = this.props; const { collapsed, animating } = this.state; const wrapperClassName = classNames('column-header__wrapper', { 'active': active, }); const buttonClassName = classNames('column-header', { 'active': active, }); const collapsibleClassName = classNames('column-header__collapsible', { 'collapsed': collapsed, 'animating': animating, }); const collapsibleButtonClassName = classNames('column-header__button', { 'active': !collapsed, }); let extraContent, pinButton, moveButtons, backButton, collapseButton; if (children) { extraContent = ( <div key='extra-content' className='column-header__collapsible__extra'> {children} </div> ); } if (multiColumn && pinned) { pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={this.handlePin}><i className='fa fa fa-times' /> <FormattedMessage id='column_header.unpin' defaultMessage='Unpin' /></button>; moveButtons = ( <div key='move-buttons' className='column-header__setting-arrows'> <button title={formatMessage(messages.moveLeft)} aria-label={formatMessage(messages.moveLeft)} className='text-btn column-header__setting-btn' onClick={this.handleMoveLeft}><i className='fa fa-chevron-left' /></button> <button title={formatMessage(messages.moveRight)} aria-label={formatMessage(messages.moveRight)} className='text-btn column-header__setting-btn' onClick={this.handleMoveRight}><i className='fa fa-chevron-right' /></button> </div> ); } else if (multiColumn) { pinButton = <button key='pin-button' className='text-btn column-header__setting-btn' onClick={this.handlePin}><i className='fa fa fa-plus' /> <FormattedMessage id='column_header.pin' defaultMessage='Pin' /></button>; } if (!pinned && (multiColumn || showBackButton)) { backButton = ( <button onClick={this.handleBackClick} className='column-header__back-button'> <i className='fa fa-fw fa-chevron-left column-back-button__icon' /> <FormattedMessage id='column_back_button.label' defaultMessage='Back' /> </button> ); } const collapsedContent = [ extraContent, ]; if (multiColumn) { collapsedContent.push(moveButtons); collapsedContent.push(pinButton); } if (children || multiColumn) { collapseButton = <button className={collapsibleButtonClassName} title={formatMessage(collapsed ? messages.show : messages.hide)} aria-label={formatMessage(collapsed ? messages.show : messages.hide)} aria-pressed={collapsed ? 'false' : 'true'} onClick={this.handleToggleClick}><i className='fa fa-sliders' /></button>; } const hasTitle = icon && title; return ( <div className={wrapperClassName}> <h1 className={buttonClassName}> {hasTitle && ( <button onClick={this.handleTitleClick}> <i className={`fa fa-fw fa-${icon} column-header__icon`} /> {title} </button> )} {!hasTitle && backButton} <div className='column-header__buttons'> {hasTitle && backButton} {extraButton} {collapseButton} </div> </h1> <div className={collapsibleClassName} tabIndex={collapsed ? -1 : null} onTransitionEnd={this.handleTransitionEnd}> <div className='column-header__collapsible-inner'> {(!collapsed || animating) && collapsedContent} </div> </div> </div> ); } }
docs/app/Examples/views/Item/Content/index.js
ben174/Semantic-UI-React
import React from 'react' import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample' import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection' const Content = () => ( <ExampleSection title='Content'> <ComponentExample title='Image' description='An item can contain an image' examplePath='views/Item/Content/Images' /> <ComponentExample title='Content' description='An item can contain content' examplePath='views/Item/Content/Contents' /> <ComponentExample title='Header' description='An item can contain a header' examplePath='views/Item/Content/Headers' /> <ComponentExample title='Metadata' description='An item can contain a header' examplePath='views/Item/Content/Metadata' /> <ComponentExample title='Link' description='An item can contain contain links as images, headers, or inside content' examplePath='views/Item/Content/Link' /> <ComponentExample title='Description' description='An item can contain contain links as images, headers, or inside content' examplePath='views/Item/Content/Descriptions' /> <ComponentExample title='Extra Content' description='An item can contain contain links as images, headers, or inside content' examplePath='views/Item/Content/ExtraContent' /> <ComponentExample title='Rating' description='An item can contain icons signifying a "like" or "favorite" action' examplePath='views/Item/Content/Ratings' /> </ExampleSection> ) export default Content
source/client/components/CardsBar.js
NAlexandrov/yaw
import React from 'react'; import PropTypes from 'prop-types'; import styled from 'react-emotion'; import { Card, CardDelete } from './'; const Layout = styled.div` display: flex; flex-direction: column; position: relative; background-color: #242424; padding: 20px; `; const Logo = styled.div` width: 147px; height: 28px; margin-bottom: 55px; background-image: url('/assets/yamoney-logo.svg'); `; /* const Edit = styled.div` position: absolute; top: 17px; right: 12px; width: 34px; height: 35px; cursor: pointer; background-image: url('/assets/${({ editable }) => (editable ? 'cards-edit-active' : 'cards-edit')}.svg'); background-repeat: no-repeat; background-position: center center; `; */ const CardsList = styled.div` flex: 1; `; const Footer = styled.footer` color: rgba(255, 255, 255, 0.2); font-size: 15px; `; const CardsBar = ({ // eslint-disable-next-line activeCardIndex, cardsList, onCardChange, onEditChange, isCardsEditable, isCardRemoving, onChangeBarMode, removeCardId, deleteCard, addCard, }) => { const onCardClick = (index) => { if (onCardChange) { onCardChange(index); } }; if (isCardRemoving) { return ( <Layout> <Logo /> <CardDelete deleteCard={deleteCard} data={cardsList.filter((item) => item.id === removeCardId)[0]} /> <Footer>Yamoney Node School</Footer> </Layout> ); } return ( <Layout> <Logo /> <CardsList> {cardsList .filter((item) => !item.hidden) .map((card, index) => ( <Card key={index} data={card} active={index === activeCardIndex} isCardsEditable={isCardsEditable} onChangeBarMode={onChangeBarMode} onClick={() => onCardClick(index)} /> )) } <Card type='new' addCard={addCard} /> </CardsList> <Footer>Yet Another Wallet</Footer> </Layout> ); }; CardsBar.propTypes = { cardsList: PropTypes.arrayOf(PropTypes.object).isRequired, activeCardIndex: PropTypes.number.isRequired, removeCardId: PropTypes.number, onCardChange: PropTypes.func.isRequired, isCardsEditable: PropTypes.bool.isRequired, isCardRemoving: PropTypes.bool.isRequired, deleteCard: PropTypes.func.isRequired, onChangeBarMode: PropTypes.func.isRequired, addCard: PropTypes.func.isRequired, }; export default CardsBar;
imports/Dashboard.js
naustudio/nau-jukebox
/* © 2017 * @author Eric */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Container } from 'flux/utils'; import { withTracker } from 'meteor/react-meteor-data'; import { Link } from 'react-router-dom'; import ReactGA from 'react-ga'; import blockWords from './helpers/block-words.json'; import { errorSignInDashboard } from './events/AppActions'; import { Rooms, Users } from './collections'; import AccountsUIWrapper from './components/AccountUIWrapper'; import AppStore from './events/AppStore'; import UserStore from './events/UserStore'; import Toaster from './components/Toaster'; class Dashboard extends Component { static propTypes = { isSignedIn: PropTypes.bool, history: PropTypes.shape({ push: PropTypes.func, }), rooms: PropTypes.arrayOf(PropTypes.object), }; static defaultProps = { isSignedIn: false, history: null, rooms: [], }; static getStores() { return [AppStore, UserStore]; } static calculateState(/*prevState*/) { return { errorSignIn: UserStore.getState()['errorSignInDashboard'], }; } state = { toasterOpen: false, toasterText: 'Toaster', }; onInputName = e => { const input = e.target; const blockCharacter = /[!@#$%^&*()+=_{}[\]|\\/:;"'><?~`,.]/g; let usingBlockWordFlag = false; if (blockCharacter.test(input.value)) { input.setCustomValidity("Use only alphanumeric characters, space or '-'"); return; } blockWords.forEach(word => { if (input.value.indexOf(word) > -1) { usingBlockWordFlag = true; } }); if (usingBlockWordFlag) { input.setCustomValidity('You are using block words. Please try a different name'); } else { input.setCustomValidity(''); } }; onCreateRoom = e => { e.preventDefault(); if (!this.props.isSignedIn) { errorSignInDashboard(); return; } const form = e.currentTarget; if (form.name && form.name.value) { Meteor.call('createRoom', form.name.value, Meteor.userId(), (err, id) => { if (err) { this.setState({ toasterText: err.toString(), toasterOpen: true, }); } else { ReactGA.event({ category: 'Host', action: 'Created a Room', }); this.props.history.push(`/room/${Rooms.findOne(id).slug}`); } }); } }; onToasterClose = () => { this.setState({ toasterOpen: false, }); }; render() { const { rooms, isSignedIn } = this.props; const { errorSignIn, toasterOpen, toasterText } = this.state; return ( <div className="dashboard"> <img src="/nau-jukebox.svg" alt="nau jukebox logo" className="dashboard__logo" /> <div className="dashboard__content"> <div className="dashboard__login-block"> <AccountsUIWrapper /> {errorSignIn && !isSignedIn ? ( <div className="dashboard__login-block__error"> <p>Please login first!</p> </div> ) : null} </div> {rooms && rooms.length ? ( <div className="dashboard__room-container"> <h5 className="dashboard__room-header">Joined Rooms</h5> <ul className="dashboard__room-list"> {rooms.map(room => ( <li className="dashboard__room" key={room._id}> <span className="dashboard__room-name">{room.name}</span> <Link to={`/room/${room.slug}`} className="dashboard__join-button button"> {Meteor.userId() === room.hostId ? 'JOIN AS HOST' : 'JOIN'} </Link> </li> ))} </ul> </div> ) : null} <form className="dashboard__add-room" onSubmit={this.onCreateRoom}> <label>NEW ROOM</label> <input type="text" placeholder="Room name" required name="name" minLength="4" onInput={this.onInputName} /> <button type="submit" className="dashboard__create-button"> CREATE </button> </form> </div> <Toaster type="error" open={toasterOpen} text={toasterText} onClose={this.onToasterClose} /> <hr /> <details> <summary>Introduction / Giới thiệu</summary> <p> A simple web app which allows groups of people (co-workers, gathering friends, housemates) collectively book and play continuously a list of songs. </p> <p> (TV) Đây là một ứng dụng web đơn giản cho phép một nhóm người dùng cùng đăng ký bài hát vào một danh sách chung và nghe cùng với nhau. Nâu Jukebox rất phù hợp với một nhóm người đang nghe nhạc cùng nhau: tại công sở, quán cà phê, bạn bè cùng lớp, cùng phòng... </p> </details> <details> <summary>Hướng dẫn</summary> <ul> <li>Đầu tiên bạn cần phải đăng nhập với tài khoản Facebook hoặc Google</li> <li>Tiếp theo, bạn tạo một phòng nghe nhạc chung, và trở thành Host (chủ phòng).</li> <li> Một khi phòng nghe nhạc đã được tạo, mọi người đều có thể vào phòng xem danh sách bài hát thông qua một địa chỉ URL dành riêng cho Phòng. </li> <li> Để đăng ký bài hát, các user khác cần đăng nhập. Danh sách những user đã đăng nhập vào phòng sẽ hiện lên bên danh sách Users. </li> <li> Copy đường link trên thanh địa chỉ tại trang bài hát (trang đơn, không phải playlist) của một trong các website nghe nhạc được hỗ trợ. </li> <li>Dán vào ô tìm kiếm và Enter (hoặc bấm Search)</li> <li> <strong>HOẶC</strong> bạn có thể nhập vào từ khoá để tìm kiếm bài hát sẵn có trong cơ sở dữ liệu của Jukebox. </li> <li> Các trang nghe nhạc đang được hỗ trợ là: <ul> <li> <a href="https://youtube.com" target="_blank" rel="noopener noreferrer"> youtube.com </a>: Nhạc quốc tế, nhạc underground, MV mới nhất từ các nghệ sỹ trong và ngoài Việt Nam </li> <li> <a href="https://soundcloud.com" target="_blank" rel="noopener noreferrer"> soundcloud.com </a>: Nhạc indie, nhạc underground... </li> <li> <a href="https://www.nhaccuatui.com" target="_blank" rel="noopener noreferrer"> nhaccuatui.com </a>: V-pop, nhạc xưa, nhạc Hàn, nhạc Âu Mỹ... </li> <li> <a href="https://mp3.zing.vn" target="_blank" rel="noopener noreferrer"> mp3.zing.vn </a>: V-pop, nhạc xưa, nhạc Hàn, nhạc Âu Mỹ... </li> </ul> </li> </ul> </details> <details> <summary>How to?</summary> <ul> <li>First user login with either Facebook or Google account.</li> <li>Next, user will create a room for the group and become the room&#039;s host.</li> <li>Once the room is created, everyone can join the room by visiting a unique URL.</li> <li>To book songs, users must login.</li> <li>Copy the URL to a single song from supported services and paste it to the search box.</li> <li> <strong>Or</strong> search from known songs in Nau Jukebox database and book quickly. </li> <li> Supported services whose song can be booked from:{' '} <a href="https://youtube.com" target="_blank" rel="noopener noreferrer"> youtube.com </a>,{' '} <a href="https://soundcloud.com" target="_blank" rel="noopener noreferrer"> soundcloud.com </a>,{' '} <a href="https://www.nhaccuatui.com" target="_blank" rel="noopener noreferrer"> nhaccuatui.com </a>,{' '} <a href="https://mp3.zing.vn" target="_blank" rel="noopener noreferrer"> mp3.zing.vn </a> </li> </ul> </details> <details> <summary>Hỏi Đáp</summary> <dl> <dt>Nâu Jukebox miễn phí hay có thu phí?</dt> <dd>Nâu Jukebox sẽ luôn miễn phí.</dd> <dt>Tại sao không có thanh tiến trình để qua nhanh?</dt> <dd> Chúng tôi cho rằng mỗi bài hát được book một khi đã chơi, cần được chơi trọn vẹn. Người Host vẫn có quyền bỏ qua bài hát khác. </dd> <dt>Naucoin (trong tab Users) là gì?</dt> <dd> Naucoin là đơn vị tiền ảo (không phải tiền crypto 🙂) được chúng tôi tạo ra để các nhóm có thể dùng làm điểm để thưởng cho các trò chơi trong room. Người host cũng với vai trò là trọng tài có quyền set Naucoin cho bất kỳ ai trong room. Luật chơi do nhóm tự đặt ra, ví dụ, đặt cược và đoán xem ai vừa book bài đang phát. </dd> <dt>Tôi có thể book nhạc từ website X?</dt> <dd> Hiện tại Nâu Jukebox hỗ trợ book nhạc từ các trang:{' '} <a href="https://youtube.com" target="_blank" rel="noopener noreferrer"> youtube.com </a>,{' '} <a href="https://soundcloud.com" target="_blank" rel="noopener noreferrer"> soundcloud.com </a>,{' '} <a href="https://www.nhaccuatui.com" target="_blank" rel="noopener noreferrer"> nhaccuatui.com </a>,{' '} <a href="https://mp3.zing.vn" target="_blank" rel="noopener noreferrer"> mp3.zing.vn </a>. Nếu bạn muốn chúng tôi hỗ trợ thêm một trang nhạc khác ngoài các trang trên, vui lòng tạo một feature request tại <a href="https://github.com/naustudio/nau-jukebox/issues">github</a> của Nâu Jukebox hoặc gửi email về địa chỉ: <a href="mailto:[email protected]">[email protected]</a> </dd> </dl> </details> </div> ); } } export default withTracker(() => { const _id = Meteor.userId(); let joinedRooms = []; const currentUser = Meteor.userId() ? Users.findOne({ _id }) : undefined; joinedRooms = (currentUser && currentUser.joinedRooms) || []; return { isSignedIn: !!Meteor.userId(), rooms: Rooms.find({ _id: { $in: joinedRooms } }).fetch(), }; })(Container.create(Dashboard));
src/components/TodoComponents/Footer.js
kla1nfun/reduxtodo
import React from 'react' import FilterLink from '../../containers/TodoList/FilterLink' const styles = require('../../containers/TodoList/TodoList.scss'); const Footer = () => ( <footer className={styles.footer}> <ul className={styles.filters}> <li> <FilterLink filter="SHOW_ALL"> All </FilterLink> </li> <li> <FilterLink filter="SHOW_ACTIVE"> Active </FilterLink> </li> <li> <FilterLink filter="SHOW_COMPLETED"> Completed </FilterLink> </li> </ul> </footer> ) export default Footer
src/index.js
emyarod/afw
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; import './index.scss'; import * as serviceWorker from './serviceWorker'; // change page title with window visibility document.addEventListener('visibilitychange', () => ( document.hidden ? document.title = document.title.replace(' - ', ' | ') : document.title = document.title.replace(' | ', ' - ') )); console.info(` ▓▓▓▓▓▓▓▓▓ ▄▄▓▓▓▓▓▓▓▓▓▓▄ ▓▓▓▓▓▓▓▓▓▓▄ ▄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▀▀▓▓▓▓▓▓▓▓▓▓▓▓▀─ ▀▓▓▓▓▓▓ ▓▓▓▓▓▓▄▄▄▄▄▄▄▄_ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▄▄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓─ ▄▄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀▀▀▀- ▓▓▓▓▓▓▓▓▓▓▀▀▀▀▓▓▓▓▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓ ▓▓▓▓▓▓▓▓▄▄▄▄▄▄▄▄▄▄▄▄ ▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄_ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▄ ▄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓_ ▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓▀▀▀▀▀▀▀▀▀▀▀▀▓▓▓▓▓▓▓▓▓▓▓▓▓▓_ ▀▓▓▓▓▓▓▓▓▓▓▓▀▀▀─- ▄▓▓▓▓▓▓▓▓▓▓▓▓▓▓▓ ▀▀▀▀▀▀▀▀ ▓▓▓▓▓▓▓▓▓▓▀ Designed and developed by Andrew Wang. `); ReactDOM.render(<App />, document.getElementById('root')); // If you want your app to work offline and load faster, you can change // unregister() to register() below. Note this comes with some pitfalls. // Learn more about service workers: https://bit.ly/CRA-PWA serviceWorker.unregister();
src/svg-icons/social/domain.js
rscnt/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let SocialDomain = (props) => ( <SvgIcon {...props}> <path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"/> </SvgIcon> ); SocialDomain = pure(SocialDomain); SocialDomain.displayName = 'SocialDomain'; export default SocialDomain;
app/containers/AddJob/index.js
theClubhouse-Augusta/JobWeasel-FrontEnd
/* * * AddJob * */ import React from 'react'; import Helmet from 'react-helmet'; import Nav from 'components/Nav'; import './style.css'; import './styleM.css'; import '../../global.css'; export default class AddJob extends React.PureComponent { constructor(){ super(); this.state = { jobTitle: "", jobDescription: "", jobLocation:"", workersNeeded:"", budget:"", startDate:"", timeFrame:"", notification:"", token:sessionStorage.getItem('token') } } postJob = () => { console.log(this.state.token); let data = new FormData; let _this = this; data.append('name', this.state.jobTitle); data.append('location', this.state.jobLocation); data.append('description', this.state.jobDescription); data.append('workers_needed', this.state.workersNeeded); data.append('budget', this.state.budget); data.append('start_date', this.state.startDate); data.append('time_frame', this.state.timeFrame); fetch('http://localhost:8000/api/postJob', { method:'POST', body:data, headers:{"Authorization":"Bearer "+ this.state.token} }) .then(function(response) { return response.json(); }) .then(function(json) { if(json.error) { _this.setState({ notification:json.error }) } else if(json.success){ _this.setState({ notification:json.success }) } setTimeout(function(){ let user = JSON.parse(sessionStorage.getItem('user')); let url = '/Profile/' + user.id; _this.context.router.history.push(url); }, 500); }); this.forceUpdate(); }; handleJobTitle = (event) => { this.setState({ jobTitle:event.target.value }) } handleJobDescription = (event) => { this.setState({ jobDescription:event.target.value }) } handleJobLocation = (event) => { this.setState({ jobLocation:event.target.value }) } handleWorkersNeeded = (event) => { this.setState({ workersNeeded:event.target.value }) } handleBudget = (event) => { this.setState({ budget:event.target.value }) } handleStartDate = (event) => { this.setState({ startDate:event.target.value }) } handleTimeFrame = (event) => { this.setState({ timeFrame:event.target.value }) } render() { let date = new Date(); date = date.toDateString(); return ( <div className="addJobContainer"> <Helmet title="AddJob" meta={[ { name: 'description', content: 'Description of AddJob' }]}/> <div className="addJobFullOverlay"> </div> <Nav/> <div className="jobDetailContainer"> <div className="jobTitle"> <p><b>Job Title:</b></p> <p><input type="text" placeholder="Job Title" onChange={this.handleJobTitle}/></p> </div> <div className="jobDesc"> <p><b>Job Description:</b></p> <p><textarea rows="10" cols="30" wrap="hard" placeholder="Job Description" onChange={this.handleJobDescription}/></p> </div> <div className="jobLocation"> <b>Job Location: </b> <p><input type="text" placeholder="Location" onChange={this.handleJobLocation}/></p> </div> <div className="workers"> <b>Workers Needed: </b> <p><input type="text" placeholder="Workers Needed" onChange={this.handleWorkersNeeded}/></p> </div> <div className="budget"> <b>Budget: </b> <p><input type="text" placeholder="Budget" onChange={this.handleBudget}/></p> </div> <div className="startDate"> <b>Start Date: </b> <p><input type="text" placeholder="Start Date" onChange={this.handleStartDate}/></p> </div> <div className="timeFrame"> <b>Time Frame: </b> <b>(In Months) </b> <p><input type="text" placeholder="Time Frame" onChange={this.handleTimeFrame}/></p> </div> <div className="timeStamp"> <b>Todays Date: </b> <p>{date}</p> </div> <input type="submit" className="postJobButton button" value="Post Job" onClick={this.postJob}/> <p className="submitNote">{this.state.notification}</p> </div> </div> ); } } AddJob.contextTypes = { router: React.PropTypes.object };
packages/material-ui-benchmark/src/core.js
lgollut/material-ui
/* eslint-disable no-console */ import Benchmark from 'benchmark'; import React from 'react'; import ReactDOMServer from 'react-dom/server'; import { StylesProvider } from '@material-ui/styles'; import ButtonBase from '@material-ui/core/ButtonBase'; const suite = new Benchmark.Suite('core', { onError: (event) => { console.log(event.target.error); }, }); Benchmark.options.minSamples = 100; function NakedButton(props) { return <button type="button" {...props} />; } function HocButton(props) { return <NakedButton {...props} />; } suite .add('ButtonBase', () => { ReactDOMServer.renderToString( <StylesProvider sheetsManager={new Map()}> <ButtonBase>Material-UI</ButtonBase> </StylesProvider>, ); }) .add('HocButton', () => { ReactDOMServer.renderToString( <StylesProvider> <HocButton /> </StylesProvider>, ); }) .add('NakedButton', () => { ReactDOMServer.renderToString( <StylesProvider> <NakedButton /> </StylesProvider>, ); }) .add('ButtonBase enable ripple', () => { ReactDOMServer.renderToString(<ButtonBase>Material-UI</ButtonBase>); }) .add('ButtonBase disable ripple', () => { ReactDOMServer.renderToString(<ButtonBase disableRipple>Material-UI</ButtonBase>); }) .on('cycle', (event) => { console.log(String(event.target)); }) .run();
src/components/Navigation/DrawerNavigatorContent.js
Digitova/reactova-framework
import React from 'react'; import { View, ScrollView, Text, StyleSheet } from 'react-native'; import {DrawerItems} from 'react-navigation' export default (props) => ( <View style={ styles.drawer }> <ScrollView style={ styles.drawerScrollView } contentContainerStyle={{flex: 1, alignItems: 'stretch'}}> <DrawerItems {...props} /> </ScrollView> </View> ) const styles = StyleSheet.create({ drawer: { flex: 1, flexDirection: 'column', backgroundColor: '#fff', }, drawerScrollView: { flex: 1, }, drawerScrollViewContainer: { flex: 1, alignItems: 'stretch' }, menuItem: { flex: 1, alignItems: 'flex-start', alignSelf: 'stretch', paddingTop: 5, paddingBottom: 5, paddingLeft: 20, marginTop: 20, backgroundColor: '#000' }, versionTextViewContainer: { flex:1, alignItems: 'center', justifyContent: 'flex-end', flexDirection: 'column', marginBottom: 10 }, versionTextView: { fontSize: 10, color: '#000' } });
app/containers/App/index.js
emise/hoosit
/** * * App * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) */ import React from 'react'; import Helmet from 'react-helmet'; import styled from 'styled-components'; import Header from 'components/Header'; import Footer from 'components/Footer'; import withProgressBar from 'components/ProgressBar'; const AppWrapper = styled.div` max-width: calc(768px + 16px * 2); margin: 0 auto; display: flex; min-height: 100%; padding: 0 16px; flex-direction: column; `; export function App(props) { return ( <AppWrapper> <Helmet titleTemplate="%s - React.js Boilerplate" defaultTitle="React.js Boilerplate" meta={[ { name: 'description', content: 'A React.js Boilerplate application' }, ]} /> <Header /> {React.Children.toArray(props.children)} <Footer /> </AppWrapper> ); } App.propTypes = { children: React.PropTypes.node, }; export default withProgressBar(App);
packages/webpack-walt-examples/src/index.js
ballercat/walt
import ReactDOM from 'react-dom'; import React from 'react'; import App from './App'; ReactDOM.render(<App/>, document.getElementById('app'))
docs/src/PropTable.js
victorzhang17/react-bootstrap
import merge from 'lodash-compat/object/merge'; import React from 'react'; import Glyphicon from '../../src/Glyphicon'; import Label from '../../src/Label'; import Table from '../../src/Table'; let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, ''); let capitalize = str => str[0].toUpperCase() + str.substr(1); function getPropsData(component, metadata) { let componentData = metadata[component] || {}; let props = componentData.props || {}; if (componentData.composes) { componentData.composes.forEach(other => { if (other !== component) { props = merge({}, getPropsData(other, metadata), props); } }); } if (componentData.mixins) { componentData.mixins.forEach( other => { if (other !== component && componentData.composes.indexOf(other) === -1) { props = merge({}, getPropsData(other, metadata), props); } }); } return props; } const PropTable = React.createClass({ contextTypes: { metadata: React.PropTypes.object }, componentWillMount() { this.propsData = getPropsData(this.props.component, this.context.metadata); }, render() { let propsData = this.propsData; if ( !Object.keys(propsData).length) { return <span/>; } return ( <Table bordered striped className="prop-table"> <thead> <tr> <th>Name</th> <th>Type</th> <th>Default</th> <th>Description</th> </tr> </thead> <tbody> { this._renderRows(propsData) } </tbody> </Table> ); }, _renderRows(propsData) { return Object.keys(propsData) .sort() .filter(propName => propsData[propName].type && !propsData[propName].doclets.private ) .map(propName => { let propData = propsData[propName]; return ( <tr key={propName} className="prop-table-row"> <td> {propName} {this.renderRequiredLabel(propData)} </td> <td> <div>{this.getType(propData)}</div> </td> <td>{propData.defaultValue}</td> <td> { propData.doclets.deprecated && <div className="prop-desc-heading"> <strong className="text-danger">{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong> </div> } { this.renderControllableNote(propData, propName) } <div className="prop-desc" dangerouslySetInnerHTML={{__html: propData.descHtml }} /> </td> </tr> ); }); }, renderRequiredLabel(prop) { if (!prop.required) { return null; } return ( <Label>required</Label> ); }, renderControllableNote(prop, propName) { let controllable = prop.doclets.controllable; let isHandler = this.getDisplayTypeName(prop.type.name) === 'function'; if (!controllable) { return false; } let text = isHandler ? ( <span> controls <code>{controllable}</code> </span> ) : ( <span> controlled by: <code>{controllable}</code>, initial prop: <code>{'default' + capitalize(propName)}</code> </span> ); return ( <div className="prop-desc-heading"> <small> <em className="text-info"> <Glyphicon glyph="info-sign"/> &nbsp;{ text } </em> </small> </div> ); }, getType(prop) { let type = prop.type || {}; let name = this.getDisplayTypeName(type.name); let doclets = prop.doclets || {}; switch (name) { case 'object': return name; case 'union': return type.value.reduce((current, val, i, list) => { let item = this.getType({ type: val }); if (React.isValidElement(item)) { item = React.cloneElement(item, {key: i}); } current = current.concat(item); return i === (list.length - 1) ? current : current.concat(' | '); }, []); case 'array': let child = this.getType({ type: type.value }); return <span>{'array<'}{ child }{'>'}</span>; case 'enum': return this.renderEnum(type); case 'custom': return cleanDocletValue(doclets.type || name); default: return name; } }, getDisplayTypeName(typeName) { if (typeName === 'func') { return 'function'; } else if (typeName === 'bool') { return 'boolean'; } return typeName; }, renderEnum(enumType) { const enumValues = enumType.value || []; const renderedEnumValues = []; enumValues.forEach(function renderEnumValue(enumValue, i) { if (i > 0) { renderedEnumValues.push( <span key={`${i}c`}>, </span> ); } renderedEnumValues.push( <code key={i}>{enumValue}</code> ); }); return ( <span>one of: {renderedEnumValues}</span> ); } }); export default PropTable;
pages/api/select.js
cherniavskii/material-ui
import React from 'react'; import withRoot from 'docs/src/modules/components/withRoot'; import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs'; import markdown from './select.md'; function Page() { return <MarkdownDocs markdown={markdown} />; } export default withRoot(Page);
docs/app/Examples/elements/Step/Groups/StepExampleGroups.js
ben174/Semantic-UI-React
import React from 'react' import { Icon, Step } from 'semantic-ui-react' const { Content, Description, Group, Title } = Step const steps = [ { icon: 'truck', title: 'Shipping', description: 'Choose your shipping options' }, { active: true, icon: 'payment', title: 'Billing', description: 'Enter billing information' }, { disabled: true, icon: 'info', title: 'Confirm Order' }, ] const StepExampleGroups = () => ( <div> <Group> <Step> <Icon name='truck' /> <Content> <Title>Shipping</Title> <Description>Choose your shipping options</Description> </Content> </Step> <Step active> <Icon name='payment' /> <Content title='Billing' description='Enter billing information' /> </Step> <Step disabled icon='info' title='Confirm Order' /> </Group> <br /> <Group items={steps} /> </div> ) export default StepExampleGroups
client/components/signup/SignupPage.js
ilijabradas/react_app
import React from 'react'; import SignupForm from './SignupForm'; class SignupPage extends React.Component { render() { return( <div className="row"> <div className="col-md-4 col-offset-4"> <SignupForm/> </div> </div> ); } } export default SignupPage; //TODO: add SignupForm component
client/js/source/components/SearchForm.js
sagneta/AdmitOne
'use strict'; import ReactButton from 'react-button'; import Excel from './Excel'; import React from 'react'; import $ from 'jquery'; class SearchForm extends React.Component { constructor(props) { super(props); this.state = { startshowid: 'Event ID Start', endshowid: 'Event ID End', headers: ['Event ID', 'Customer', '# Tickets'], data: [], displayExcel: false }; this.handleChangeStartShowID = this.handleChangeStartShowID.bind(this); this.handleChangeEndShowID = this.handleChangeEndShowID.bind(this); this.handleSubmit = this.handleSubmit.bind(this); this.onClicked = this.onClicked.bind(this); } handleChangeStartShowID(event) { this.setState({startshowid: event.target.value}); } handleChangeEndShowID(event) { this.setState({endshowid: event.target.value}); } handleSubmit(event) { // console.log('A startshowid was submitted: ' + this.state.startshowid); // console.log('A endshowid was submitted: ' + this.state.endshowid); event.preventDefault(); var mydata = $("form#search-form").serialize(); //console.log("mydata "+ mydata); $.ajax({ type: "POST", url: "/admitone/services/administration/search/form", data: mydata, success: function(results) { //console.log("success: " + JSON.stringify(results)); var purchases = []; results.forEach(function(row) { //console.log("ROW:" + JSON.stringify(row)); purchases.push([row.toShowID, row.username, row.tickets]); }); this.setState( { displayExcel: true, data: purchases } ); }.bind(this), error: function(xhr, textStatus, errorThrown) { console.log("error"); } }); } onClicked() { this.setState( { displayExcel: false } ); } render() { if(this.state.displayExcel) { return ( <div id="exceltable"> <ReactButton onClick={this.onClicked}>Search Again</ReactButton> <br/> <div> <Excel headers={this.state.headers} initialData={this.state.data}/> </div> </div> ); } else { return ( <div id="searchform"> <form id="search-form" onSubmit={this.handleSubmit} > <h1><center>Search</center></h1> <h2><center>Search for Events between ID</center></h2> <label> <input id="searchform-startshowid" name="startshowid" type="text" value={this.state.startshowid} onChange={this.handleChangeStartShowID} /> </label> <p>and</p> <label> <input id="searchform-endshowid" name="endshowid" type="text" value={this.state.endshowid} onChange={this.handleChangeEndShowID} /> </label> <br></br> <input id="searchbutton" type="submit" value="Search" /> </form> </div> ); } } } export default SearchForm;
src/client.js
24v/player-sankey
/** * 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 'whatwg-fetch'; import React from 'react'; import ReactDOM from 'react-dom'; import deepForceUpdate from 'react-deep-force-update'; import queryString from 'query-string'; import { createPath } from 'history/PathUtils'; import App from './components/App'; import createFetch from './createFetch'; import history from './history'; import { updateMeta } from './DOMUtils'; import router from './router'; /* eslint-disable global-require */ // Global (context) variables that can be easily accessed from any React component // https://facebook.github.io/react/docs/context.html const context = { // Enables critical path CSS rendering // https://github.com/kriasoft/isomorphic-style-loader insertCss: (...styles) => { // eslint-disable-next-line no-underscore-dangle const removeCss = styles.map(x => x._insertCss()); return () => { removeCss.forEach(f => f()); }; }, // Universal HTTP client fetch: createFetch(self.fetch, { baseUrl: window.App.apiUrl, }), }; // Switch off the native scroll restoration behavior and handle it manually // https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration const scrollPositionsHistory = {}; if (window.history && 'scrollRestoration' in window.history) { window.history.scrollRestoration = 'manual'; } let onRenderComplete = function initialRenderComplete() { const elem = document.getElementById('css'); if (elem) elem.parentNode.removeChild(elem); onRenderComplete = function renderComplete(route, location) { document.title = route.title; updateMeta('description', route.description); // Update necessary tags in <head> at runtime here, ie: // updateMeta('keywords', route.keywords); // updateCustomMeta('og:url', route.canonicalUrl); // updateCustomMeta('og:image', route.imageUrl); // updateLink('canonical', route.canonicalUrl); // etc. let scrollX = 0; let scrollY = 0; const pos = scrollPositionsHistory[location.key]; if (pos) { scrollX = pos.scrollX; scrollY = pos.scrollY; } else { const targetHash = location.hash.substr(1); if (targetHash) { const target = document.getElementById(targetHash); if (target) { scrollY = window.pageYOffset + target.getBoundingClientRect().top; } } } // Restore the scroll position if it was saved into the state // or scroll to the given #hash anchor // or scroll to top of the page window.scrollTo(scrollX, scrollY); // Google Analytics tracking. Don't send 'pageview' event after // the initial rendering, as it was already sent if (window.ga) { window.ga('send', 'pageview', createPath(location)); } }; }; const container = document.getElementById('app'); let appInstance; let currentLocation = history.location; // Re-render the app when window.location changes async function onLocationChange(location, action) { // Remember the latest scroll position for the previous location scrollPositionsHistory[currentLocation.key] = { scrollX: window.pageXOffset, scrollY: window.pageYOffset, }; // Delete stored scroll position for next page if any if (action === 'PUSH') { delete scrollPositionsHistory[location.key]; } currentLocation = location; try { // Traverses the list of routes in the order they are defined until // it finds the first route that matches provided URL path string // and whose action method returns anything other than `undefined`. const route = await router.resolve({ ...context, pathname: location.pathname, query: queryString.parse(location.search), }); // Prevent multiple page renders during the routing process if (currentLocation.key !== location.key) { return; } if (route.redirect) { history.replace(route.redirect); return; } appInstance = ReactDOM.render( <App context={context}> {route.component} </App>, container, () => onRenderComplete(route, location), ); } catch (error) { if (__DEV__) { throw error; } console.error(error); // Do a full page reload if error occurs during client-side navigation if (action && currentLocation.key === location.key) { window.location.reload(); } } } // Handle client-side navigation by using HTML5 History API // For more information visit https://github.com/mjackson/history#readme history.listen(onLocationChange); onLocationChange(currentLocation); // Enable Hot Module Replacement (HMR) if (module.hot) { module.hot.accept('./router', () => { if (appInstance) { // Force-update the whole tree, including components that refuse to update deepForceUpdate(appInstance); } onLocationChange(currentLocation); }); }
internals/templates/appContainer.js
coocooooo/webapp
/** * * App.react.js * * This component is the skeleton around the actual pages, and should only * contain code that should be seen on all pages. (e.g. navigation bar) * * NOTE: while this component should technically be a stateless functional * component (SFC), hot reloading does not currently support SFCs. If hot * reloading is not a necessity for you then you can refactor it and remove * the linting exception. */ import React from 'react'; export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function static propTypes = { children: React.PropTypes.node, }; render() { return ( <div> {React.Children.toArray(this.props.children)} </div> ); } }
node_modules/react-bootstrap/es/Collapse.js
ProjectSunday/rooibus
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 css from 'dom-helpers/style'; import React from 'react'; import Transition from 'react-overlays/lib/Transition'; import capitalize from './utils/capitalize'; import createChainedFunction from './utils/createChainedFunction'; var MARGINS = { height: ['marginTop', 'marginBottom'], width: ['marginLeft', 'marginRight'] }; // reading a dimension prop will cause the browser to recalculate, // which will let our animations work function triggerBrowserReflow(node) { node.offsetHeight; // eslint-disable-line no-unused-expressions } function getDimensionValue(dimension, elem) { var value = elem['offset' + capitalize(dimension)]; var margins = MARGINS[dimension]; return value + parseInt(css(elem, margins[0]), 10) + parseInt(css(elem, margins[1]), 10); } var propTypes = { /** * Show the component; triggers the expand or collapse animation */ 'in': React.PropTypes.bool, /** * Unmount the component (remove it from the DOM) when it is collapsed */ unmountOnExit: React.PropTypes.bool, /** * Run the expand animation when the component mounts, if it is initially * shown */ transitionAppear: React.PropTypes.bool, /** * Duration of the collapse animation in milliseconds, to ensure that * finishing callbacks are fired even if the original browser transition end * events are canceled */ timeout: React.PropTypes.number, /** * Callback fired before the component expands */ onEnter: React.PropTypes.func, /** * Callback fired after the component starts to expand */ onEntering: React.PropTypes.func, /** * Callback fired after the component has expanded */ onEntered: React.PropTypes.func, /** * Callback fired before the component collapses */ onExit: React.PropTypes.func, /** * Callback fired after the component starts to collapse */ onExiting: React.PropTypes.func, /** * Callback fired after the component has collapsed */ onExited: React.PropTypes.func, /** * The dimension used when collapsing, or a function that returns the * dimension * * _Note: Bootstrap only partially supports 'width'! * You will need to supply your own CSS animation for the `.width` CSS class._ */ dimension: React.PropTypes.oneOfType([React.PropTypes.oneOf(['height', 'width']), React.PropTypes.func]), /** * Function that returns the height or width of the animating DOM node * * Allows for providing some custom logic for how much the Collapse component * should animate in its specified dimension. Called with the current * dimension prop value and the DOM node. */ getDimensionValue: React.PropTypes.func, /** * ARIA role of collapsible element */ role: React.PropTypes.string }; var defaultProps = { 'in': false, timeout: 300, unmountOnExit: false, transitionAppear: false, dimension: 'height', getDimensionValue: getDimensionValue }; var Collapse = function (_React$Component) { _inherits(Collapse, _React$Component); function Collapse(props, context) { _classCallCheck(this, Collapse); var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context)); _this.handleEnter = _this.handleEnter.bind(_this); _this.handleEntering = _this.handleEntering.bind(_this); _this.handleEntered = _this.handleEntered.bind(_this); _this.handleExit = _this.handleExit.bind(_this); _this.handleExiting = _this.handleExiting.bind(_this); return _this; } /* -- Expanding -- */ Collapse.prototype.handleEnter = function handleEnter(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype.handleEntering = function handleEntering(elem) { var dimension = this._dimension(); elem.style[dimension] = this._getScrollDimensionValue(elem, dimension); }; Collapse.prototype.handleEntered = function handleEntered(elem) { var dimension = this._dimension(); elem.style[dimension] = null; }; /* -- Collapsing -- */ Collapse.prototype.handleExit = function handleExit(elem) { var dimension = this._dimension(); elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px'; triggerBrowserReflow(elem); }; Collapse.prototype.handleExiting = function handleExiting(elem) { var dimension = this._dimension(); elem.style[dimension] = '0'; }; Collapse.prototype._dimension = function _dimension() { return typeof this.props.dimension === 'function' ? this.props.dimension() : this.props.dimension; }; // for testing Collapse.prototype._getScrollDimensionValue = function _getScrollDimensionValue(elem, dimension) { return elem['scroll' + capitalize(dimension)] + 'px'; }; Collapse.prototype.render = function render() { var _props = this.props, onEnter = _props.onEnter, onEntering = _props.onEntering, onEntered = _props.onEntered, onExit = _props.onExit, onExiting = _props.onExiting, className = _props.className, props = _objectWithoutProperties(_props, ['onEnter', 'onEntering', 'onEntered', 'onExit', 'onExiting', 'className']); delete props.dimension; delete props.getDimensionValue; var handleEnter = createChainedFunction(this.handleEnter, onEnter); var handleEntering = createChainedFunction(this.handleEntering, onEntering); var handleEntered = createChainedFunction(this.handleEntered, onEntered); var handleExit = createChainedFunction(this.handleExit, onExit); var handleExiting = createChainedFunction(this.handleExiting, onExiting); var classes = { width: this._dimension() === 'width' }; return React.createElement(Transition, _extends({}, props, { 'aria-expanded': props.role ? props['in'] : null, className: classNames(className, classes), exitedClassName: 'collapse', exitingClassName: 'collapsing', enteredClassName: 'collapse in', enteringClassName: 'collapsing', onEnter: handleEnter, onEntering: handleEntering, onEntered: handleEntered, onExit: handleExit, onExiting: handleExiting })); }; return Collapse; }(React.Component); Collapse.propTypes = propTypes; Collapse.defaultProps = defaultProps; export default Collapse;
src/svg-icons/navigation/arrow-drop-down.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NavigationArrowDropDown = (props) => ( <SvgIcon {...props}> <path d="M7 10l5 5 5-5z"/> </SvgIcon> ); NavigationArrowDropDown = pure(NavigationArrowDropDown); NavigationArrowDropDown.displayName = 'NavigationArrowDropDown'; NavigationArrowDropDown.muiName = 'SvgIcon'; export default NavigationArrowDropDown;
src/containers/molecule.js
OpenChemistry/mongochemclient
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux' import { selectors, molecules, calculations } from '@openchemistry/redux'; import { auth } from '@openchemistry/girder-redux'; import Molecule from '../components/molecule'; import { uploadCalculation } from '../utils/molecules'; import { push } from 'connected-react-router'; class MoleculeContainer extends Component { componentDidMount() { const { id, inchikey, dispatch } = this.props; if (id != null) { dispatch(molecules.loadMoleculeById(id)); } else if (inchikey != null) { dispatch(molecules.loadMolecule(inchikey)); } this.fetchMoleculeCalculations(); } componentDidUpdate(prevProps) { const molecule = this.props.molecule || {}; const prevMolecule = prevProps.molecule || {}; if (molecule._id !== prevMolecule._id) { this.fetchMoleculeCalculations(); } } fetchMoleculeCalculations() { const { molecule, dispatch } = this.props; if (molecule && molecule._id) { dispatch(calculations.loadCalculations({moleculeId: molecule._id})); } } onCalculationClick = (calculation) => { const {dispatch} = this.props; dispatch(push(`/calculations/${calculation._id}`)); } onCreatorClick = (creator) => { const { id, dispatch } = this.props; dispatch(push(`/molecules/${id}/creator`, {creator, type:'molecule', id:id})); } onCalculationUpload = async(file) => { const { dispatch } = this.props; let { data } = await uploadCalculation(file); dispatch(calculations.createCalculation(data)); this.fetchMoleculeCalculations(); } render() { const { molecule, calculations, creator } = this.props; if (molecule) { return ( <Molecule molecule={molecule} calculations={calculations} onCalculationClick={this.onCalculationClick} creator={creator} onCreatorClick={this.onCreatorClick} onCalculationUpload={this.onCalculationUpload}/> ); } else { return null; } } } MoleculeContainer.propTypes = { id: PropTypes.string, inchikey: PropTypes.string, molecule: PropTypes.object, calculations: PropTypes.array } MoleculeContainer.defaultProps = { id: null, inchikey: null, molecule: null, calculations: [] } function mapStateToProps(state, ownProps) { let id = ownProps.match.params.id || null; let inchikey = ownProps.match.params.inchikey || null; let creator = selectors.molecules.getMoleculeCreator(state); let props = { id, inchikey, creator } let molecules = selectors.molecules.getMoleculesById(state); if (id != null && id in molecules) { props.molecule = molecules[id]; } else if (inchikey != null) { let byInchiKey = selectors.molecules.byInchiKey(state); if (inchikey in byInchiKey) { // TODO change we hide this in a selector with a parameter? props.molecule = molecules[byInchiKey[inchikey]]; } } if (props.molecule) { props.calculations = selectors.calculations.getMoleculeCalculations(state, props.molecule._id); } return props; } export default connect(mapStateToProps)(MoleculeContainer)
examples-native/crna-kitchen-sink/storybook/stories/Welcome/index.js
storybooks/react-storybook
import React from 'react'; import PropTypes from 'prop-types'; import { View, Text } from 'react-native'; export default class Welcome extends React.Component { styles = { wrapper: { flex: 1, padding: 24, justifyContent: 'center', }, header: { fontSize: 18, marginBottom: 18, }, content: { fontSize: 12, marginBottom: 10, lineHeight: 18, }, }; showApp = event => { const { showApp } = this.props; event.preventDefault(); if (showApp) { showApp(); } }; render() { return ( <View style={this.styles.wrapper}> <Text style={this.styles.header}>Welcome to React Native Storybook</Text> <Text style={this.styles.content}> This is a UI Component development environment for your React Native app. Here you can display and interact with your UI components as stories. A story is a single state of one or more UI components. You can have as many stories as you want. In other words a story is like a visual test case. </Text> <Text style={this.styles.content}> We have added some stories inside the "storybook/stories" directory for examples. Try editing the "storybook/stories/Welcome.js" file to edit this message. </Text> </View> ); } } Welcome.defaultProps = { showApp: null, }; Welcome.propTypes = { showApp: PropTypes.func, };
client/src/javascript/components/modals/torrent-details-modal/TorrentDetailsModal.js
jfurrow/flood
import {injectIntl} from 'react-intl'; import React from 'react'; import connectStores from '../../../util/connectStores'; import Modal from '../Modal'; import EventTypes from '../../../constants/EventTypes'; import TorrentMediainfo from './TorrentMediainfo'; import TorrentFiles from './TorrentFiles'; import TorrentGeneralInfo from './TorrentGeneralInfo'; import TorrentHeading from './TorrentHeading'; import TorrentPeers from './TorrentPeers'; import TorrentStore from '../../../stores/TorrentStore'; import TorrentTrackers from './TorrentTrackers'; import UIActions from '../../../actions/UIActions'; import UIStore from '../../../stores/UIStore'; class TorrentDetailsModal extends React.Component { componentDidMount() { TorrentStore.fetchTorrentDetails(); } componentWillUnmount() { TorrentStore.stopPollingTorrentDetails(); } dismissModal() { UIActions.dismissModal(); } getModalHeading() { return <TorrentHeading torrent={this.props.torrent} key="torrent-heading" />; } render() { const props = { ...this.props.options, torrent: this.props.torrent, ...this.props.torrentDetails, }; const tabs = { 'torrent-details': { content: TorrentGeneralInfo, label: this.props.intl.formatMessage({ id: 'torrents.details.details', defaultMessage: 'Details', }), props, }, 'torrent-files': { content: TorrentFiles, label: this.props.intl.formatMessage({ id: 'torrents.details.files', defaultMessage: 'Files', }), modalContentClasses: 'modal__content--nested-scroll', props, }, 'torrent-peers': { content: TorrentPeers, label: this.props.intl.formatMessage({ id: 'torrents.details.peers', defaultMessage: 'Peers', }), props, }, 'torrent-trackers': { content: TorrentTrackers, label: this.props.intl.formatMessage({ id: 'torrents.details.trackers', defaultMessage: 'Trackers', }), props, }, 'torrent-mediainfo': { content: TorrentMediainfo, label: this.props.intl.formatMessage({ id: 'torrents.details.mediainfo', defaultMessage: 'Mediainfo', }), props, }, }; return ( <Modal heading={this.getModalHeading()} dismiss={this.dismissModal} size="large" tabs={tabs} orientation="vertical" tabsInBody /> ); } } const ConnectedTorrentDetailsModal = connectStores(injectIntl(TorrentDetailsModal), () => { return [ { store: TorrentStore, event: EventTypes.CLIENT_TORRENT_DETAILS_CHANGE, getValue: ({store}) => { return { torrentDetails: store.getTorrentDetails(UIStore.getTorrentDetailsHash()), }; }, }, { store: TorrentStore, event: EventTypes.CLIENT_TORRENTS_REQUEST_SUCCESS, getValue: ({store}) => { return { torrent: store.getTorrent(UIStore.getTorrentDetailsHash()), }; }, }, ]; }); export default ConnectedTorrentDetailsModal;
src/index.stories.js
serlo-org/serlo-abc
import { storiesOf } from '@storybook/react-native'; import * as R from 'ramda'; import React from 'react'; import { Text, View } from 'react-native'; import { MemoryRouter } from 'react-router-native'; import { CourseInteractorLoader } from '../packages/entities-interactor'; import courses from '../packages/assets/courses.json'; import Storage from './storage/CourseStorage'; import ProgressStorage from './storage/ProgressStorage'; import App, { AppRoutes } from '.'; import { DataPolicy } from './components/screens/DataPolicy'; import { ConsentStatus, default as DataPolicyConsentStorage } from './storage/DataPolicyConsentStorage'; storiesOf('App', module).add('default', () => <App />); const storage = new Storage(courses); const progressStorage = new ProgressStorage(); const interactorLoader = new CourseInteractorLoader(storage, progressStorage); const course = storiesOf('Course', module); const addStory = (entity, level) => { const shortId = entity.id.substr(0, 7); course.add( `${R.times(i => '›', level).join('')} ${entity.title || shortId} ${entity.type || ''}`, () => ( <MemoryRouter initialEntries={[ { pathname: level === 0 ? '/course' : `/node/${entity.id}`, state: { level } } ]} initialIndex={0} > <AppRoutes /> </MemoryRouter> ) ); if (entity.children) { entity.children.forEach(child => addStory(child, level + 1)); } }; interactorLoader .loadCourse('09438926-b170-4005-a6e8-5dd8fba83cde') .then(interactor => { const course = interactor.getStructure(); addStory(course, 0); }); storiesOf('PolicyManager', module) .add('Reset / Set status', () => { new DataPolicyConsentStorage().setConsent(null); return <DataPolicyStorybookComponent />; }) .add('Older version accepted', () => { new DataPolicyConsentStorage().setConsent({ version: '2000-01-01', consent: ConsentStatus.Accepted }); return <DataPolicyStorybookComponent />; }); const DataPolicyStorybookComponent = () => ( <DataPolicy render={accepted => ( <View style={{ top: 50 }} > <Text> That should be saved now. You {accepted ? 'accepted' : 'declined'} the policy. </Text> </View> )} /> );
packages/@lyra/state-router/src/components/RouteScope.js
VegaPublish/vega-studio
// @flow import PropTypes from 'prop-types' import React from 'react' import isEmpty from '../utils/isEmpty' import type {Node} from 'react' import type { RouterProviderContext, NavigateOptions, InternalRouter } from './types' function addScope(routerState: Object, scope: string, scopedState: Object) { return ( scopedState && { ...routerState, [scope]: scopedState } ) } type Props = { scope: string, children: Node } export default class RouteScope extends React.Component<*, *> { props: Props __internalRouter: InternalRouter static childContextTypes = (RouteScope.contextTypes = { __internalRouter: PropTypes.object }) constructor(props: Props, context: RouterProviderContext) { super() const parentInternalRouter = context.__internalRouter this.__internalRouter = { ...parentInternalRouter, resolvePathFromState: this.resolvePathFromState, navigate: this.navigate, getState: this.getScopedState } } getChildContext(): RouterProviderContext { return { __internalRouter: this.__internalRouter } } getScopedState = () => { const {scope} = this.props const parentInternalRouter = this.context.__internalRouter return parentInternalRouter.getState()[scope] } resolvePathFromState = (nextState: Object): string => { const parentInternalRouter = this.context.__internalRouter const scope = this.props.scope const nextStateScoped: Object = isEmpty(nextState) ? {} : addScope(parentInternalRouter.getState(), scope, nextState) return parentInternalRouter.resolvePathFromState(nextStateScoped) } navigate = (nextState: Object, options?: NavigateOptions): void => { const parentInternalRouter = this.context.__internalRouter const nextScopedState = addScope( parentInternalRouter.getState(), this.props.scope, nextState ) parentInternalRouter.navigate(nextScopedState, options) } render() { return this.props.children } }
step5-forms/node_modules/react-router/es6/Router.js
jintoppy/react-training
'use strict'; 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 createHashHistory from 'history/lib/createHashHistory'; import useQueries from 'history/lib/useQueries'; import React from 'react'; import createTransitionManager from './createTransitionManager'; import { routes } from './PropTypes'; import RouterContext from './RouterContext'; import { createRoutes } from './RouteUtils'; import { createRouterObject, createRoutingHistory } from './RouterUtils'; import warning from './routerWarning'; function isDeprecatedHistory(history) { return !history || !history.__v2_compatible__; } var _React$PropTypes = React.PropTypes; var func = _React$PropTypes.func; var object = _React$PropTypes.object; /** * A <Router> is a high-level API for automatically setting up * a router that renders a <RouterContext> with all the props * it needs each time the URL changes. */ var Router = React.createClass({ displayName: 'Router', propTypes: { history: object, children: routes, routes: routes, // alias for children render: func, createElement: func, onError: func, onUpdate: func, // PRIVATE: For client-side rehydration of server match. matchContext: object }, getDefaultProps: function getDefaultProps() { return { render: function render(props) { return React.createElement(RouterContext, props); } }; }, getInitialState: function getInitialState() { return { location: null, routes: null, params: null, components: null }; }, handleError: function handleError(error) { if (this.props.onError) { this.props.onError.call(this, error); } else { // Throw errors by default so we don't silently swallow them! throw error; // This error probably occurred in getChildRoutes or getComponents. } }, componentWillMount: function componentWillMount() { var _this = this; var _props = this.props; var parseQueryString = _props.parseQueryString; var stringifyQuery = _props.stringifyQuery; process.env.NODE_ENV !== 'production' ? warning(!(parseQueryString || stringifyQuery), '`parseQueryString` and `stringifyQuery` are deprecated. Please create a custom history. http://tiny.cc/router-customquerystring') : undefined; var _createRouterObjects = this.createRouterObjects(); var history = _createRouterObjects.history; var transitionManager = _createRouterObjects.transitionManager; var router = _createRouterObjects.router; this._unlisten = transitionManager.listen(function (error, state) { if (error) { _this.handleError(error); } else { _this.setState(state, _this.props.onUpdate); } }); this.history = history; this.router = router; }, createRouterObjects: function createRouterObjects() { var matchContext = this.props.matchContext; if (matchContext) { return matchContext; } var history = this.props.history; var _props2 = this.props; var routes = _props2.routes; var children = _props2.children; if (isDeprecatedHistory(history)) { history = this.wrapDeprecatedHistory(history); } var transitionManager = createTransitionManager(history, createRoutes(routes || children)); var router = createRouterObject(history, transitionManager); var routingHistory = createRoutingHistory(history, transitionManager); return { history: routingHistory, transitionManager: transitionManager, router: router }; }, wrapDeprecatedHistory: function wrapDeprecatedHistory(history) { var _props3 = this.props; var parseQueryString = _props3.parseQueryString; var stringifyQuery = _props3.stringifyQuery; var createHistory = undefined; if (history) { process.env.NODE_ENV !== 'production' ? warning(false, 'It appears you have provided a deprecated history object to `<Router/>`, please use a history provided by ' + 'React Router with `import { browserHistory } from \'react-router\'` or `import { hashHistory } from \'react-router\'`. ' + 'If you are using a custom history please create it with `useRouterHistory`, see http://tiny.cc/router-usinghistory for details.') : undefined; createHistory = function () { return history; }; } else { process.env.NODE_ENV !== 'production' ? warning(false, '`Router` no longer defaults the history prop to hash history. Please use the `hashHistory` singleton instead. http://tiny.cc/router-defaulthistory') : undefined; createHistory = createHashHistory; } return useQueries(createHistory)({ parseQueryString: parseQueryString, stringifyQuery: stringifyQuery }); }, /* istanbul ignore next: sanity check */ componentWillReceiveProps: function componentWillReceiveProps(nextProps) { process.env.NODE_ENV !== 'production' ? warning(nextProps.history === this.props.history, 'You cannot change <Router history>; it will be ignored') : undefined; process.env.NODE_ENV !== 'production' ? warning((nextProps.routes || nextProps.children) === (this.props.routes || this.props.children), 'You cannot change <Router routes>; it will be ignored') : undefined; }, componentWillUnmount: function componentWillUnmount() { if (this._unlisten) this._unlisten(); }, render: function render() { var _state = this.state; var location = _state.location; var routes = _state.routes; var params = _state.params; var components = _state.components; var _props4 = this.props; var createElement = _props4.createElement; var render = _props4.render; var props = _objectWithoutProperties(_props4, ['createElement', 'render']); if (location == null) return null; // Async match // Only forward non-Router-specific props to routing context, as those are // the only ones that might be custom routing context props. Object.keys(Router.propTypes).forEach(function (propType) { return delete props[propType]; }); return render(_extends({}, props, { history: this.history, router: this.router, location: location, routes: routes, params: params, components: components, createElement: createElement })); } }); export default Router;
packages/material-ui-icons/src/Fingerprint.js
AndriusBil/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from 'material-ui/SvgIcon'; let Fingerprint = props => <SvgIcon {...props}> <path d="M17.81 4.47c-.08 0-.16-.02-.23-.06C15.66 3.42 14 3 12.01 3c-1.98 0-3.86.47-5.57 1.41-.24.13-.54.04-.68-.2-.13-.24-.04-.55.2-.68C7.82 2.52 9.86 2 12.01 2c2.13 0 3.99.47 6.03 1.52.25.13.34.43.21.67-.09.18-.26.28-.44.28zM3.5 9.72c-.1 0-.2-.03-.29-.09-.23-.16-.28-.47-.12-.7.99-1.4 2.25-2.5 3.75-3.27C9.98 4.04 14 4.03 17.15 5.65c1.5.77 2.76 1.86 3.75 3.25.16.22.11.54-.12.7-.23.16-.54.11-.7-.12-.9-1.26-2.04-2.25-3.39-2.94-2.87-1.47-6.54-1.47-9.4.01-1.36.7-2.5 1.7-3.4 2.96-.08.14-.23.21-.39.21zm6.25 12.07c-.13 0-.26-.05-.35-.15-.87-.87-1.34-1.43-2.01-2.64-.69-1.23-1.05-2.73-1.05-4.34 0-2.97 2.54-5.39 5.66-5.39s5.66 2.42 5.66 5.39c0 .28-.22.5-.5.5s-.5-.22-.5-.5c0-2.42-2.09-4.39-4.66-4.39-2.57 0-4.66 1.97-4.66 4.39 0 1.44.32 2.77.93 3.85.64 1.15 1.08 1.64 1.85 2.42.19.2.19.51 0 .71-.11.1-.24.15-.37.15zm7.17-1.85c-1.19 0-2.24-.3-3.1-.89-1.49-1.01-2.38-2.65-2.38-4.39 0-.28.22-.5.5-.5s.5.22.5.5c0 1.41.72 2.74 1.94 3.56.71.48 1.54.71 2.54.71.24 0 .64-.03 1.04-.1.27-.05.53.13.58.41.05.27-.13.53-.41.58-.57.11-1.07.12-1.21.12zM14.91 22c-.04 0-.09-.01-.13-.02-1.59-.44-2.63-1.03-3.72-2.1-1.4-1.39-2.17-3.24-2.17-5.22 0-1.62 1.38-2.94 3.08-2.94 1.7 0 3.08 1.32 3.08 2.94 0 1.07.93 1.94 2.08 1.94s2.08-.87 2.08-1.94c0-3.77-3.25-6.83-7.25-6.83-2.84 0-5.44 1.58-6.61 4.03-.39.81-.59 1.76-.59 2.8 0 .78.07 2.01.67 3.61.1.26-.03.55-.29.64-.26.1-.55-.04-.64-.29-.49-1.31-.73-2.61-.73-3.96 0-1.2.23-2.29.68-3.24 1.33-2.79 4.28-4.6 7.51-4.6 4.55 0 8.25 3.51 8.25 7.83 0 1.62-1.38 2.94-3.08 2.94s-3.08-1.32-3.08-2.94c0-1.07-.93-1.94-2.08-1.94s-2.08.87-2.08 1.94c0 1.71.66 3.31 1.87 4.51.95.94 1.86 1.46 3.27 1.85.27.07.42.35.35.61-.05.23-.26.38-.47.38z" /> </SvgIcon>; Fingerprint = pure(Fingerprint); Fingerprint.muiName = 'SvgIcon'; export default Fingerprint;
docs/src/examples/collections/Message/Variations/index.js
Semantic-Org/Semantic-UI-React
import React from 'react' import ExampleSection from 'docs/src/components/ComponentDoc/ExampleSection' import ComponentExample from 'docs/src/components/ComponentDoc/ComponentExample' const MessageVariationsExamples = () => ( <ExampleSection title='Variations'> <ComponentExample title='Floating' description='A message can float above content that it is related to.' examplePath='collections/Message/Variations/MessageExampleFloating' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='collections/Message/Variations/MessageExampleFloatingProps' /> <ComponentExample title='Compact' description='A message can only take up the width of its content.' examplePath='collections/Message/Variations/MessageExampleCompact' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='collections/Message/Variations/MessageExampleCompactProps' /> <ComponentExample title='Attached' description='A message can be formatted to attach itself to other content.' examplePath='collections/Message/Variations/MessageExampleAttached' /> <ComponentExample title='Info' description='A message may be formatted to display information.' examplePath='collections/Message/Variations/MessageExampleInfo' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='collections/Message/Variations/MessageExampleInfoProps' /> <ComponentExample title='Warning' description='A message may be formatted to display warning message.' examplePath='collections/Message/Variations/MessageExampleWarning' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='collections/Message/Variations/MessageExampleWarningProps' /> <ComponentExample title='Positive/Success' description='A message may be formatted to display a positive message.' examplePath='collections/Message/Variations/MessageExamplePositive' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='collections/Message/Variations/MessageExampleSuccess' /> <ComponentExample title='Negative/Error' description='A message may be formatted to display a negative message.' examplePath='collections/Message/Variations/MessageExampleNegative' /> <ComponentExample description='You can also use props to configure the markup.' examplePath='collections/Message/Variations/MessageExampleError' /> <ComponentExample title='Colored' description='A message can be formatted to be different colors.' examplePath='collections/Message/Variations/MessageExampleColor' /> <ComponentExample title='Size' description='A message can have different sizes.' examplePath='collections/Message/Variations/MessageExampleSize' /> </ExampleSection> ) export default MessageVariationsExamples
client/src/containers/creations/CreatedHub.js
JasonProcka/venos
import React from 'react'; class CreatedHub extends React.Component { render() { return ( <div className="createdHub"> <h4>Jason's Hub</h4> <p>Random description</p> </div> ); } } export default CreatedHub;
packages/wix-style-react/src/VerticalTabs/VerticalTabsContext.js
wix/wix-style-react
import React from 'react'; export default React.createContext({ size: 'medium' });
assets/jqwidgets/demos/react/app/panel/fluidsize/app.js
juannelisalde/holter
import React from 'react'; import ReactDOM from 'react-dom'; import JqxPanel from '../../../jqwidgets-react/react_jqxpanel.js'; class App extends React.Component { render () { let innerHtml = '<div style=\'margin: 10px;\'>' + '<h3>Early History of the Internet</h3></div>' + '<!--Content-->' + '<div style=\'white-space: nowrap;\'>' + '<ul>' + '<li>1961 First packet-switching papers</li>' + '<li>1966 Merit Network founded</li>' + '<li>1966 ARPANET planning starts</li>' + '<li>1969 ARPANET carries its first packets</li>' + '<li>1970 Mark I network at NPL (UK)</li>' + '<li>1970 Network Information Center (NIC)</li>' + '<li>1971 Merit Network\'s packet-switched network operational</li>' + '<li>1971 Tymnet packet-switched network</li>' + '<li>1972 Internet Assigned Numbers Authority (IANA) established</li>' + '<li>1973 CYCLADES network demonstrated</li>' + '<li>1974 Telenet packet-switched network</li>' + '<li>1976 X.25 protocol approved</li>' + '<li>1979 Internet Activities Board (IAB)</li>' + '<li>1980 USENET news using UUCP</li>' + '<li>1980 Ethernet standard introduced</li>' + '<li>1981 BITNET established</li>' + '</ul>' + '</div>' + '<!--Header-->' + '<div style=\'margin: 10px;\'>' + '<h3>Merging the networks and creating the Internet</h3></div>' + '<!--Content-->' + '<div>' + '<ul>' + '<li>1981 Computer Science Network (CSNET)</li>' + '<li>1982 TCP/IP protocol suite formalized</li>' + '<li>1982 Simple Mail Transfer Protocol (SMTP)</li>' + '<li>1983 Domain Name System (DNS)</li>' + '<li>1983 MILNET split off from ARPANET</li>' + '<li>1986 NSFNET with 56 kbit/s links</li>' + '<li>1986 Internet Engineering Task Force (IETF)</li>' + '<li>1987 UUNET founded</li>' + '<li>1988 NSFNET upgraded to 1.5 Mbit/s (T1)</li>' + '<li>1988 OSI Reference Model released</li>' + '<li>1988 Morris worm</li>' + '<li>1989 Border Gateway Protocol (BGP)</li>' + '<li>1989 PSINet founded, allows commercial traffic</li>' + '<li>1989 Federal Internet Exchanges (FIXes)</li>' + '<li>1990 GOSIP (without TCP/IP)</li>' + '<li>1990 ARPANET decommissioned</li>' + '</ul>' + '</div>' + '<!--Header-->' + '<div style=\'margin: 10px;\'>' + '<h3>Popular Internet services</h3></div>' + '<!--Content-->' + '<div>' + '<ul>' + '<li>1990 IMDb Internet movie database</li>' + '<li>1995 Amazon.com online retailer</li>' + '<li>1995 eBay online auction and shopping</li>' + '<li>1995 Craigslist classified advertisements</li>' + '<li>1996 Hotmail free web-based e-mail</li>' + '<li>1997 Babel Fish automatic translation</li>' + '<li>1998 Google Search</li>' + '<li>1999 Napster peer-to-peer file sharing</li>' + '<li>2001 Wikipedia, the free encyclopedia</li>' + '<li>2003 LinkedIn business networking</li>' + '<li>2003 Myspace social networking site</li>' + '<li>2003 Skype Internet voice calls</li>' + '<li>2003 iTunes Store</li>' + '<li>2004 Facebook social networking site</li>' + '<li>2004 Podcast media file series</li>' + '<li>2004 Flickr image hosting</li>' + '<li>2005 YouTube video sharing</li>' + '<li>2005 Google Earth virtual globe</li>' + '</ul>' + '</div>'; return ( <JqxPanel width={'50%'} height={'50%'} > <div style={{ margin: 10 }}> <h3>Early History of the Internet</h3></div> <div style={{ whiteSpace: 'nowrap' }}> <ul> <li>1961 First packet-switching papers</li> <li>1966 Merit Network founded</li> <li>1966 ARPANET planning starts</li> <li>1969 ARPANET carries its first packets</li> <li>1970 Mark I network at NPL (UK)</li> <li>1970 Network Information Center (NIC)</li> <li>1971 Merit Network's packet-switched network operational</li> <li>1971 Tymnet packet-switched network</li> <li>1972 Internet Assigned Numbers Authority (IANA) established</li> <li>1973 CYCLADES network demonstrated</li> <li>1974 Telenet packet-switched network</li> <li>1976 X.25 protocol approved</li> <li>1979 Internet Activities Board (IAB)</li> <li>1980 USENET news using UUCP</li> <li>1980 Ethernet standard introduced</li> <li>1981 BITNET established</li> </ul> </div> </JqxPanel> ) } } //template={innerHtml} ReactDOM.render(<App />, document.getElementById('app'));
src/app/components/media/ReportDesigner/ReportDesignerImagePreview.js
meedan/check-web
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedMessage } from 'react-intl'; import escapeHtml from 'escape-html'; function overwriteDocumentHtml(contentDocument, html) { contentDocument.open(); contentDocument.write(html); contentDocument.close(); } function tweakIframeDom({ contentDocument, headline, description, status_label, url, date, defaultReport, }) { const fillInOrHide = (selector, textContent) => { const el = contentDocument.querySelector(selector); if (el) { if (textContent) { if (el.lastChild) { el.lastChild.nodeValue = textContent; } else { el.textContent = textContent; } } else { el.style.display = 'none'; } } }; fillInOrHide('#title', headline); fillInOrHide('#description', description); fillInOrHide('#status', status_label); fillInOrHide('#url', url); fillInOrHide('#date', date); fillInOrHide('#whatsapp', defaultReport.whatsapp); fillInOrHide('#facebook', defaultReport.facebook ? `m.me/${defaultReport.facebook}` : null); fillInOrHide('#twitter', defaultReport.twitter ? `@${defaultReport.twitter}` : null); fillInOrHide('#telegram', defaultReport.telegram ? `t.me/${defaultReport.telegram}` : null); fillInOrHide('#viber', defaultReport.viber ? defaultReport.viber : null); fillInOrHide('#line', defaultReport.line ? defaultReport.line : null); } function ReportImagePreview({ template, teamAvatar, image, style, params, date, defaultReport, }) { const [iframe, setIframe] = React.useState(null); const { theme_color: themeColor, headline, description, status_label, url, dark_overlay, } = params; // TODO don't use 'style' attribute at all const fullStyle = { border: 0, overflow: 'hidden', ...style, }; const html = template .replace(/#CCCCCC/gi, themeColor) .replace(/%IMAGE_URL%/g, escapeHtml(image || '')) .replace('%AVATAR_URL%', escapeHtml(teamAvatar || '')); React.useEffect( () => { if (!iframe) { return; } const { contentDocument } = iframe; overwriteDocumentHtml(contentDocument, html); const theme = dark_overlay ? 'dark' : 'light'; contentDocument.body.className += ` ${theme}`; tweakIframeDom({ contentDocument, headline, description, status_label, url, date, defaultReport, }); }, [iframe, html, headline, description, status_label, url, dark_overlay, date], ); return ( <FormattedMessage id="reportDesigner.reportImagePreviewTitle" description="Image caption spoken by screen readers but not seen by most users" defaultMessage="Report preview" > {title => ( <iframe ref={setIframe /* causing a re-render -- and thus useEffect() -- on load */} src="about:blank" title={title} style={fullStyle} /> )} </FormattedMessage> ); } ReportImagePreview.defaultProps = { image: null, teamAvatar: null, date: null, style: {}, defaultReport: {}, }; ReportImagePreview.propTypes = { template: PropTypes.string.isRequired, image: PropTypes.string, // or null teamAvatar: PropTypes.string, // or null date: PropTypes.string, // or null style: PropTypes.object, // or null. TODO nix this prop params: PropTypes.shape({ headline: PropTypes.string.isRequired, description: PropTypes.string, // or null status_label: PropTypes.string.isRequired, url: PropTypes.string, // or null theme_color: PropTypes.string.isRequired, dark_overlay: PropTypes.bool, // or null }).isRequired, defaultReport: PropTypes.object, // or null }; export default ReportImagePreview;
app/javascript/flavours/glitch/features/ui/components/favourite_modal.js
vahnj/mastodon
import React from 'react'; import ImmutablePropTypes from 'react-immutable-proptypes'; import PropTypes from 'prop-types'; import { defineMessages, injectIntl, FormattedMessage } from 'react-intl'; import Button from 'flavours/glitch/components/button'; import StatusContent from 'flavours/glitch/components/status_content'; import Avatar from 'flavours/glitch/components/avatar'; import RelativeTimestamp from 'flavours/glitch/components/relative_timestamp'; import DisplayName from 'flavours/glitch/components/display_name'; import ImmutablePureComponent from 'react-immutable-pure-component'; const messages = defineMessages({ favourite: { id: 'status.favourite', defaultMessage: 'Favourite' }, }); @injectIntl export default class FavouriteModal extends ImmutablePureComponent { static contextTypes = { router: PropTypes.object, }; static propTypes = { status: ImmutablePropTypes.map.isRequired, onFavourite: PropTypes.func.isRequired, onClose: PropTypes.func.isRequired, intl: PropTypes.object.isRequired, }; componentDidMount() { this.button.focus(); } handleFavourite = () => { this.props.onFavourite(this.props.status); this.props.onClose(); } handleAccountClick = (e) => { if (e.button === 0) { e.preventDefault(); this.props.onClose(); this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`); } } setRef = (c) => { this.button = c; } render () { const { status, intl } = this.props; return ( <div className='modal-root__modal favourite-modal'> <div className='favourite-modal__container'> <div className='status light'> <div className='favourite-modal__status-header'> <div className='favourite-modal__status-time'> <a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a> </div> <a onClick={this.handleAccountClick} href={status.getIn(['account', 'url'])} className='status__display-name'> <div className='status__avatar'> <Avatar account={status.get('account')} size={48} /> </div> <DisplayName account={status.get('account')} /> </a> </div> <StatusContent status={status} /> </div> </div> <div className='favourite-modal__action-bar'> <div><FormattedMessage id='favourite_modal.combo' defaultMessage='You can press {combo} to skip this next time' values={{ combo: <span>Shift + <i className='fa fa-star' /></span> }} /></div> <Button text={intl.formatMessage(messages.favourite)} onClick={this.handleFavourite} ref={this.setRef} /> </div> </div> ); } }
client/src/index.js
jordonmckoy/product-tracker
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();
examples/huge-apps/routes/Messages/components/Messages.js
opichals/react-router
import React from 'react'; class Messages extends React.Component { render () { return ( <div> <h2>Messages</h2> </div> ); } } export default Messages;
docs/src/app/components/pages/components/List/ExampleMessages.js
IsenrichO/mui-with-arrows
import React from 'react'; import MobileTearSheet from '../../../MobileTearSheet'; import {List, ListItem} from 'material-ui/List'; import Divider from 'material-ui/Divider'; import Subheader from 'material-ui/Subheader'; import Avatar from 'material-ui/Avatar'; import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors'; import IconButton from 'material-ui/IconButton'; import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert'; import IconMenu from 'material-ui/IconMenu'; import MenuItem from 'material-ui/MenuItem'; const iconButtonElement = ( <IconButton touch={true} tooltip="more" tooltipPosition="bottom-left" > <MoreVertIcon color={grey400} /> </IconButton> ); const rightIconMenu = ( <IconMenu iconButtonElement={iconButtonElement}> <MenuItem>Reply</MenuItem> <MenuItem>Forward</MenuItem> <MenuItem>Delete</MenuItem> </IconMenu> ); const ListExampleMessages = () => ( <div> <MobileTearSheet> <List> <Subheader>Today</Subheader> <ListItem leftAvatar={<Avatar src="images/ok-128.jpg" />} primaryText="Brunch this weekend?" secondaryText={ <p> <span style={{color: darkBlack}}>Brendan Lim</span> -- I&apos;ll be in your neighborhood doing errands this weekend. Do you want to grab brunch? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kolage-128.jpg" />} primaryText={ <p>Summer BBQ&nbsp;&nbsp;<span style={{color: lightBlack}}>4</span></p> } secondaryText={ <p> <span style={{color: darkBlack}}>to me, Scott, Jennifer</span> -- Wish I could come, but I&apos;m out of town this weekend. </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/uxceo-128.jpg" />} primaryText="Oui oui" secondaryText={ <p> <span style={{color: darkBlack}}>Grace Ng</span> -- Do you have Paris recommendations? Have you ever been? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kerem-128.jpg" />} primaryText="Birdthday gift" secondaryText={ <p> <span style={{color: darkBlack}}>Kerem Suer</span> -- Do you have any ideas what we can get Heidi for her birthday? How about a pony? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />} primaryText="Recipe to try" secondaryText={ <p> <span style={{color: darkBlack}}>Raquel Parrado</span> -- We should eat this: grated squash. Corn and tomatillo tacos. </p> } secondaryTextLines={2} /> </List> </MobileTearSheet> <MobileTearSheet> <List> <Subheader>Today</Subheader> <ListItem leftAvatar={<Avatar src="images/ok-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Brendan Lim" secondaryText={ <p> <span style={{color: darkBlack}}>Brunch this weekend?</span><br /> I&apos;ll be in your neighborhood doing errands this weekend. Do you want to grab brunch? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kolage-128.jpg" />} rightIconButton={rightIconMenu} primaryText="me, Scott, Jennifer" secondaryText={ <p> <span style={{color: darkBlack}}>Summer BBQ</span><br /> Wish I could come, but I&apos;m out of town this weekend. </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/uxceo-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Grace Ng" secondaryText={ <p> <span style={{color: darkBlack}}>Oui oui</span><br /> Do you have any Paris recs? Have you ever been? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/kerem-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Kerem Suer" secondaryText={ <p> <span style={{color: darkBlack}}>Birthday gift</span><br /> Do you have any ideas what we can get Heidi for her birthday? How about a pony? </p> } secondaryTextLines={2} /> <Divider inset={true} /> <ListItem leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />} rightIconButton={rightIconMenu} primaryText="Raquel Parrado" secondaryText={ <p> <span style={{color: darkBlack}}>Recipe to try</span><br /> We should eat this: grated squash. Corn and tomatillo tacos. </p> } secondaryTextLines={2} /> </List> </MobileTearSheet> </div> ); export default ListExampleMessages;
src/components/protractor/plain/ProtractorPlain.js
fpoumian/react-devicon
import React from 'react' import PropTypes from 'prop-types' import SVGDeviconInline from '../../_base/SVGDeviconInline' import iconSVG from './ProtractorPlain.svg' /** ProtractorPlain */ function ProtractorPlain({ width, height, className }) { return ( <SVGDeviconInline className={'ProtractorPlain' + ' ' + className} iconSVG={iconSVG} width={width} height={height} /> ) } ProtractorPlain.propTypes = { className: PropTypes.string, width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]), } export default ProtractorPlain
Paths/React/05.Building Scalable React Apps/4-react-boilerplate-building-scalable-apps-m4-exercise-files/Before/app/app.js
phiratio/Pluralsight-materials
/** * app.js * * This is the entry file for the application, only setup and boilerplate * code. */ import 'babel-polyfill'; /* eslint-disable import/no-unresolved */ // Load the manifest.json file and the .htaccess file import '!file?name=[name].[ext]!./manifest.json'; import 'file?name=[name].[ext]!./.htaccess'; /* eslint-enable import/no-unresolved */ // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { applyRouterMiddleware, Router, browserHistory } from 'react-router'; import { syncHistoryWithStore } from 'react-router-redux'; import useScroll from 'react-router-scroll'; import LanguageProvider from 'containers/LanguageProvider'; import configureStore from './store'; // Import i18n messages import { translationMessages } from './i18n'; // Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder import 'sanitize.css/sanitize.css'; // Create redux store with history // this uses the singleton browserHistory provided by react-router // Optionally, this could be changed to leverage a created history // e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();` const initialState = {}; const store = configureStore(initialState, browserHistory); // Sync history and store, as the react-router-redux reducer // is under the non-default key ("routing"), selectLocationState // must be provided for resolving how to retrieve the "route" in the state import { selectLocationState } from 'containers/App/selectors'; const history = syncHistoryWithStore(browserHistory, store, { selectLocationState: selectLocationState(), }); // Set up the router, wrapping all Routes in the App component import App from 'containers/App'; import createRoutes from './routes'; const rootRoute = { component: App, childRoutes: createRoutes(store), }; const render = (translatedMessages) => { ReactDOM.render( <Provider store={store}> <LanguageProvider messages={translatedMessages}> <Router history={history} routes={rootRoute} render={ // Scroll to top when going to a new page, imitating default browser // behaviour applyRouterMiddleware(useScroll()) } /> </LanguageProvider> </Provider>, document.getElementById('app') ); }; // Hot reloadable translation json files if (module.hot) { // modules.hot.accept does not accept dynamic dependencies, // have to be constants at compile-time module.hot.accept('./i18n', () => { render(translationMessages); }); } // Chunked polyfill for browsers without Intl support if (!window.Intl) { Promise.all([ System.import('intl'), System.import('intl/locale-data/jsonp/en.js'), ]).then(() => render(translationMessages)); } else { render(translationMessages); } // Install ServiceWorker and AppCache in the end since // it's not most important operation and if main code fails, // we do not want it installed import { install } from 'offline-plugin/runtime'; install();
packages/wix-style-react/src/TableListItem/test/TableListItem.visual.js
wix/wix-style-react
import React from 'react'; import { storiesOf } from '@storybook/react'; import TableListItem, { VERTICAL_PADDING } from '../TableListItem'; import Text from '../../Text'; import WixStyleReactProvider from '../../WixStyleReactProvider'; import Input from '../../Input'; const sizes = Object.values(VERTICAL_PADDING); const commonProps = { options: [ { value: 'Investing', width: '2fr', align: 'right' }, { value: '4 posts', width: '1fr', align: 'center' }, { value: '30 April 2020', width: '20%', align: 'left' }, ], }; const tests = [ { describe: 'sanity', its: [ { it: 'with everything enabled', props: { showDivider: true, checkbox: true, checked: true, draggable: true, }, }, { it: 'with everything disabled', props: { showDivider: true, checkbox: true, checkboxDisabled: true, draggable: true, dragDisabled: true, }, }, ], }, { describe: 'vertical padding', its: sizes.map(verticalPadding => ({ it: verticalPadding, props: { verticalPadding, checkbox: true, draggable: true, showDivider: true, options: [{ value: 'Personal Finance' }], }, })), }, { describe: 'ellipsis', its: [ { it: 'should work with Text ellipsis properly', props: { options: [ { value: ( <Text ellipsis> Very very very very long messagenVery very very very long message Very very very very long message Very very very very long message Very very very very long message Very very very very long message Very very very very long message </Text> ), }, ], }, }, ], }, { describe: 'children', its: [ { it: 'children that are not aligned should stretch to 100%', props: { draggable: true, options: [{ value: <Input /> }], }, }, ], }, ]; export const runTests = ( { themeName, testWithTheme } = { testWithTheme: i => i }, ) => { tests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { storiesOf( `${themeName ? `${themeName}|${TableListItem.displayName}/` : ''}${ describe ? '/' + describe : '' }`, module, ).add(it, () => testWithTheme(<TableListItem {...commonProps} {...props} />), ); }); }); tests.forEach(({ describe, its }) => { its.forEach(({ it, props }) => { storiesOf( `${ themeName ? `${themeName}|${TableListItem.displayName}/` : '' }Layout And Spacing| ${TableListItem.displayName}/${describe}`, module, ).add(it, () => testWithTheme( <WixStyleReactProvider features={{ reducedSpacingAndImprovedLayout: true }} > <TableListItem {...commonProps} {...props} /> </WixStyleReactProvider>, ), ); }); }); };
src/collections/Form/FormTextArea.js
Semantic-Org/Semantic-UI-React
import PropTypes from 'prop-types' import React from 'react' import { getElementType, getUnhandledProps } from '../../lib' import TextArea from '../../addons/TextArea' import FormField from './FormField' /** * Sugar for <Form.Field control={TextArea} />. * @see Form * @see TextArea */ function FormTextArea(props) { const { control } = props const rest = getUnhandledProps(FormTextArea, props) const ElementType = getElementType(FormTextArea, props) return <ElementType {...rest} control={control} /> } FormTextArea.propTypes = { /** An element type to render as (string or function). */ as: PropTypes.elementType, /** A FormField control prop. */ control: FormField.propTypes.control, } FormTextArea.defaultProps = { as: FormField, control: TextArea, } export default FormTextArea
example/app.js
marcello3d/react-leaflet
import React from 'react'; import SimpleExample from './simple'; import EventsExample from './events'; import VectorLayersExample from './vector-layers'; const examples = <div> <h1>React-Leaflet examples</h1> <h2>Popup with Marker</h2> <SimpleExample /> <h2>Events</h2> <p>Click the map to show a marker at your detected location</p> <EventsExample /> <h2>Vector layers</h2> <VectorLayersExample /> </div>; React.render(examples, document.getElementById('app'));
src/components/routes/calendar/Calendar.js
fredmarques/petshop
import './react-big-calendar.css' import './Calendar.css'; import React, { Component } from 'react'; import BigCalendar from 'react-big-calendar'; import moment from 'moment'; import { Field, reduxForm } from 'redux-form'; import { Link } from 'react-router-dom'; import { connect } from 'react-redux'; import DateTime from 'react-datetime'; import { addEvent, getEvents } from '../../../actions/events'; import { getAllEvents } from '../../../reducers/events'; moment.defineLocale('pt-br', { months: 'janeiro_fevereiro_março_abril_maio_junho_julho_agosto_setembro_outubro_novembro_dezembro'.split('_'), monthsShort: 'jan_fev_mar_abr_mai_jun_jul_ago_set_out_nov_dez'.split('_'), weekdays: 'domingo_segunda-feira_terça-feira_quarta-feira_quinta-feira_sexta-feira_sábado'.split('_'), weekdaysShort: 'dom_seg_ter_qua_qui_sex_sáb'.split('_'), weekdaysMin: 'dom_2ª_3ª_4ª_5ª_6ª_sáb'.split('_'), longDateFormat: { LT: 'HH:mm', L: 'DD/MM/YYYY', LL: 'D [de] MMMM [de] YYYY', LLL: 'D [de] MMMM [de] YYYY [às] LT', LLLL: 'dddd, D [de] MMMM [de] YYYY [às] LT' }, calendar: { sameDay: '[Hoje às] LT', nextDay: '[Amanhã às] LT', nextWeek: 'dddd [às] LT', lastDay: '[Ontem às] LT', lastWeek: function () { return (this.day() === 0 || this.day() === 6) ? '[Último] dddd [às] LT' : // Saturday + Sunday '[Última] dddd [às] LT'; // Monday - Friday }, sameElse: 'L' }, relativeTime: { future: 'em %s', past: '%s atrás', s: 'segundos', m: 'um minuto', mm: '%d minutos', h: 'uma hora', hh: '%d horas', d: 'um dia', dd: '%d dias', M: 'um mês', MM: '%d meses', y: 'um ano', yy: '%d anos' }, ordinal: '%dº' }); moment.locale('pt-br') BigCalendar.momentLocalizer(moment); // or globalizeLocalizer class Calendar extends Component { componentDidMount() { this.props.getEvents(); } renderField(field) { const { meta: { touched, error } } = field; const className = ''; return ( <div className={className}> <input className="form-control" type={field.type} placeholder={field.placeholder} {...field.input} /> <div className="text-help"> {touched ? error : ''} </div> </div> ); } onSubmit(values) { // Check if service was selected if (values.service === undefined) { alert('Escolha um serviço') // Check if data was selected } else if (values.date === undefined) { alert('Selecione uma data') // Check if data was selected } else if (values.creditcard === undefined) { alert('Insira o número do cartão para pagamento') } else { const newEvent = { title: values.service, start: values.date.toDate(), end: values.date.add(1, 'hour'), desc: `Agendado para ${'fulano'}` } this.props.addEvent(newEvent); alert(newEvent.title + ' agendada para o dia ' + newEvent.start.toString().substring(8, 10) + ' de ' + newEvent.start.toString().substring(4, 7) + ' de ' + newEvent.start.toString().substring(11, 15) + ' as ' + newEvent.start.toString().substring(16, 21) + ' horas'); // values.service = ''; // values.date = ''; // values.creditcard = ''; } } render() { const { handleSubmit, eventsList } = this.props; return ( <div className={"rbc-calendar container-fluid"}> <div className={'scheduleForm'}> <h3>Agende seu serviço</h3> <form onSubmit={handleSubmit(this.onSubmit.bind(this))} className={'form-inline'}> <Field name="service" label="Serviço" placeholder="Serviço" type="text" component={({ input }) => ( <select {...input}> <option value="">Escolha um serviço</option> <option value="consulta">Consulta</option> <option value="vacina">Vacina</option> <option value="banhoTosa">Banho e tosa</option> </select> )} /> <Field name="date" label="Data" type="text" component={ ({ input }) => ( <DateTime {...input} locale="pt-br" placeholder="Dia e hora" />)} /> <Field name="creditcard" label="creditcard" placeholder="Número do cartão" type="text" component={this.renderField} /> <button type="submit" className="btn btn-success">Agendar</button> </form> </div> <BigCalendar views={['month', 'week', 'day', 'agenda']} events={eventsList} scrollToTime={new Date()} /> </div> ); } } const mapStateToProps = (state) => { return { eventsList: state.events.events || [] } } export default reduxForm({ form: 'Calendar' })( connect(mapStateToProps, { addEvent, getEvents })(Calendar) );
js/components/svg/Valve.js
gilesbradshaw/uaQL
// @flow 'use strict'; import React from 'react'; import {compose} from 'recompose'; import Value from './Value'; const Valve = compose( )(({value})=> <g viewBox="0 0 100 125" > <path d="M75.086,39.527c-2.061-0.856-4.481-0.425-6.096,1.069L51.5,52.329V31.798h14.731c0.829,0,1.5-0.671,1.5-1.5 s-0.671-1.5-1.5-1.5H50c-0.829,0-1.5,0.671-1.5,1.5v22.031L31.01,40.594c-1.617-1.496-4.043-1.928-6.108-1.06 c-2.116,0.9-3.484,2.968-3.484,5.268v20.684c0,2.298,1.367,4.366,3.497,5.271c0.713,0.295,1.46,0.445,2.222,0.445 c1.446,0,2.816-0.537,3.873-1.515L50,56.948L68.99,69.69c1.056,0.977,2.425,1.512,3.873,1.512c0.769,0,1.519-0.151,2.235-0.452 c2.116-0.9,3.484-2.967,3.484-5.268V44.798C78.582,42.499,77.214,40.432,75.086,39.527z M29.235,67.266 c-0.075,0.05-0.146,0.107-0.21,0.17c-0.769,0.748-1.966,0.961-2.948,0.554c-1.007-0.429-1.658-1.412-1.658-2.505V44.802 c0-1.095,0.651-2.079,1.652-2.505c0.34-0.143,0.699-0.215,1.067-0.215c0.711,0,1.381,0.271,1.887,0.763 c0.065,0.063,0.135,0.12,0.21,0.17l18.074,12.127L29.235,67.266z M75.582,65.482c0,1.095-0.651,2.079-1.652,2.504 c-0.998,0.419-2.186,0.199-2.954-0.548c-0.065-0.063-0.135-0.12-0.21-0.17L52.693,55.142l18.073-12.125 c0.075-0.05,0.146-0.107,0.21-0.17c0.771-0.748,1.967-0.96,2.948-0.554c1.007,0.428,1.658,1.412,1.658,2.505V65.482z"/> <Value x={0} y={100} value={value}/> </g> ); export default Valve;
react/IconJobAd/IconJobAd.js
seekinternational/seek-asia-style-guide
import svgMarkup from './IconJobAd.svg'; import React from 'react'; import Icon from '../private/Icon/Icon'; export default function IconJobAd(props) { return <Icon markup={svgMarkup} {...props} />; } IconJobAd.displayName = 'Job Ad icon';
packages/icons/src/md/action/Translate.js
suitejs/suitejs
import React from 'react'; import IconBase from '@suitejs/icon-base'; function MdTranslate(props) { return ( <IconBase viewBox="0 0 48 48" {...props}> <path d="M25.74 30.15l-5.08-5.02.06-.06c3.48-3.88 5.96-8.34 7.42-13.06H34V8H20V4h-4v4H2v3.98h22.34A31.586 31.586 0 0 1 18 22.7a31.54 31.54 0 0 1-4.62-6.7h-4c1.46 3.26 3.46 6.34 5.96 9.12L5.17 35.17 8 38l10-10 6.22 6.22 1.52-4.07zM37 20l9 24h-4l-2.25-6h-9.5L28 44h-4l9-24h4zm-5.25 14h6.5L35 25.33 31.75 34z" /> </IconBase> ); } export default MdTranslate;
frontend/src/components/eois/details/overview/results/myResponse.js
unicef/un-partner-portal
import React from 'react'; import PropTypes from 'prop-types'; import Typography from 'material-ui/Typography'; import { connect } from 'react-redux'; import HeaderList from '../../../../common/list/headerList'; import { selectCfeiDetails } from '../../../../../store'; import ResponseForm from './responseForm'; const messages = { title: 'Result', }; const MyResponse = (props) => { const { application, status, cfeiId } = props; return ( <HeaderList header={<Typography style={{ margin: 'auto 0' }} type="headline" >{messages.title}</Typography>} > <ResponseForm cfeiId={cfeiId} application={application} status={status} /> </HeaderList> ); }; MyResponse.propTypes = { status: PropTypes.string, cfeiId: PropTypes.string, application: PropTypes.object, }; const mapStateToProps = (state, ownProps) => { const cfei = selectCfeiDetails(state, ownProps.cfeiId) || {}; const { status } = cfei; return { status, cfeiId: ownProps.cfeiId, }; }; export default connect(mapStateToProps)(MyResponse);
src/FAB/index.js
reactivers/react-material-design
/** * Created by Utku on 25/03/2017. */ import React from 'react'; import PropTypes from 'prop-types'; import '@material/fab/dist/mdc.fab.css'; import classNames from 'classnames'; export default class FAB extends React.PureComponent { static propTypes = { buttonColor: PropTypes.string, buttonSize: PropTypes.number, style: PropTypes.object, mini: PropTypes.bool, icon: PropTypes.string, onClick: PropTypes.func, }; render() { const {style, className, buttonColor, onClick, buttonSize, mini, icon, ...rest} = this.props; let buttonStyle = Object.assign({}, style, { backgroundColor: buttonColor, width: buttonSize, height: buttonSize }); const classes = classNames("mdc-fab", "material-icons", { "mdc-fab--mini": mini }, className) return ( <button className={classes} style={buttonStyle} onClick={onClick} {...rest}> {buttonSize ? React.cloneElement(icon, {iconSize: (buttonSize * 44 / 100)}) : icon } </button> ) } }
client/src/containers/creations/Creations.js
JasonProcka/venos
// Containers import CreatedHub from './CreatedHub'; // React import React from 'react'; import {browserHistory} from 'react-router'; import { push } from 'react-router-redux'; import { bindActionCreators } from 'redux'; import { connect } from 'react-redux'; // Add-ons import FloatingActionButton from 'material-ui/FloatingActionButton'; import ContentAdd from 'material-ui/svg-icons/content/add'; // >>> React Router import {Link} from 'react-router'; // Styles import '../../styles/creations/creations.css'; class Creations extends React.Component { constructor(props) { super(props); } render() { return ( <div className="creationsWrapper"> <div className="creationsHeader"> <h4>Creations</h4> </div> <div className="createdHubsWrapper"> <CreatedHub /> </div> <Link to="/create"> <FloatingActionButton className="createHub" secondary={true}> <ContentAdd /> </FloatingActionButton> </Link> </div> ); } } export default connect()(Creations);
src/svg-icons/action/system-update-alt.js
mtsandeep/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionSystemUpdateAlt = (props) => ( <SvgIcon {...props}> <path d="M12 16.5l4-4h-3v-9h-2v9H8l4 4zm9-13h-6v1.99h6v14.03H3V5.49h6V3.5H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2v-14c0-1.1-.9-2-2-2z"/> </SvgIcon> ); ActionSystemUpdateAlt = pure(ActionSystemUpdateAlt); ActionSystemUpdateAlt.displayName = 'ActionSystemUpdateAlt'; ActionSystemUpdateAlt.muiName = 'SvgIcon'; export default ActionSystemUpdateAlt;
src/app-client.js
guestn/Montagram
'use strict'; import React from 'react'; import ReactDOM from 'react-dom'; import AppRoutes from './components/AppRoutes'; window.onload = () => { ReactDOM.render(<AppRoutes/>, document.getElementById('main')); };
src/index.js
doxxx/chango
import 'bootstrap/dist/css/bootstrap.css'; import 'bootstrap/dist/css/bootstrap-theme.css'; import './index.css' import React from 'react' import ReactDOM from 'react-dom' import { createStore, applyMiddleware } from 'redux' import reduxLogger from 'redux-logger' import reduxPromise from 'redux-promise' import reduxThunk from 'redux-thunk' import { Provider } from 'react-redux' import App from './components/App' import reducer from "./reducers" let middlewares = [ reduxThunk, reduxPromise, reduxLogger() ] let store = createStore(reducer, applyMiddleware(...middlewares)) ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') )
src/Popover.js
gianpaj/react-bootstrap
import React from 'react'; import classNames from 'classnames'; import BootstrapMixin from './BootstrapMixin'; import CustomPropTypes from './utils/CustomPropTypes'; const Popover = React.createClass({ mixins: [ BootstrapMixin ], propTypes: { /** * An html id attribute, necessary for accessibility * @type {string} * @required */ id: CustomPropTypes.isRequiredForA11y( React.PropTypes.oneOfType([ React.PropTypes.string, React.PropTypes.number ]) ), /** * Sets the direction the Popover is positioned towards. */ placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']), /** * The "left" position value for the Popover. */ positionLeft: React.PropTypes.number, /** * The "top" position value for the Popover. */ positionTop: React.PropTypes.number, /** * The "left" position value for the Popover arrow. */ arrowOffsetLeft: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * The "top" position value for the Popover arrow. */ arrowOffsetTop: React.PropTypes.oneOfType([ React.PropTypes.number, React.PropTypes.string ]), /** * Title text */ title: React.PropTypes.node }, getDefaultProps() { return { placement: 'right' }; }, render() { const classes = { 'popover': true, [this.props.placement]: true }; const style = { 'left': this.props.positionLeft, 'top': this.props.positionTop, 'display': 'block', // we don't want to expose the `style` property ...this.props.style // eslint-disable-line react/prop-types }; const arrowStyle = { 'left': this.props.arrowOffsetLeft, 'top': this.props.arrowOffsetTop }; return ( <div role="tooltip" {...this.props} className={classNames(this.props.className, classes)} style={style} title={null}> <div className="arrow" style={arrowStyle} /> {this.props.title ? this.renderTitle() : null} <div className="popover-content"> {this.props.children} </div> </div> ); }, renderTitle() { return ( <h3 className="popover-title">{this.props.title}</h3> ); } }); export default Popover;
node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
martinrajdl/faunafilm
import React from 'react'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; React.render(<HelloWorld />, document.getElementById('react-root'));
index.ios.js
sebm/react-native-audio-recorder-demo
import { AudioRecorder as RNAudioRecorder, AudioUtils as RNAudioUtils } from 'react-native-audio'; import React, { Component } from 'react'; import { Alert, AppRegistry, Button, StyleSheet, Text, View, } from 'react-native'; const Sound = require('react-native-sound'); const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, }); export default class AudioRecorder extends Component { static prepareRecordingPath = (audioPath) => { RNAudioRecorder.prepareRecordingAtPath(audioPath, { SampleRate: 22050, Channels: 1, AudioQuality: 'Low', AudioEncoding: 'aac', AudioEncodingBitRate: 32000, }); } constructor(props) { super(props); this.state = { isRecording: false, currentTime: 0.0, stoppedRecording: false, stoppedPlaying: false, playing: false, finished: false, audioPath: `${RNAudioUtils.DocumentDirectoryPath}/test.aac`, }; } componentDidMount() { AudioRecorder.prepareRecordingPath(this.state.audioPath); RNAudioRecorder.onProgress = (data) => { this.setState({ currentTime: data.currentTime }); }; RNAudioRecorder.onFinished = (data) => { this.setState({ finished: data.finished }); Alert.alert(`Finished recording: ${data.finished}`); }; } buttonTitle = () => { if (this.state.isRecording) { return 'Stop Recording'; } return 'Start Recording'; }; _play = () => { this._stop(); const sound = new Sound(this.state.audioPath, '', (error) => { if (error) { Alert.alert(`failed to load the sound ${error}`); } }); setTimeout(() => { sound.play((success) => { if (success) { Alert.alert('successfully finished playing'); } else { Alert.alert('playback failed due to audio decoding errors'); } }); }, 500); } _record = () => { if (this.state.stoppedRecording) { AudioRecorder.prepareRecordingPath(this.state.audioPath); } RNAudioRecorder.startRecording(); this.setState({ isRecording: true }); } _stop = () => { if (this.state.isRecording) { RNAudioRecorder.stopRecording(); this.setState({ stoppedRecording: true, isRecording: false }); } }; _onPressRecord = () => { if (!this.state.isRecording) { this._record(); } else { this._stop(); } }; _renderPlayButton = () => ( <Button title="play" onPress={this._play} /> ) render() { return ( <View style={styles.container}> <Button onPress={this._onPressRecord} title={this.buttonTitle()} /> <Text>{this.state.currentTime.toFixed(3)}</Text> {this._renderPlayButton()} </View> ); } } AppRegistry.registerComponent('AudioRecorder', () => AudioRecorder);
docs/client/components/pages/Counter/SimpleCounterEditor/index.js
dagopert/draft-js-plugins
import React, { Component } from 'react'; import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor'; import createCounterPlugin from 'draft-js-counter-plugin'; import editorStyles from './editorStyles.css'; const counterPlugin = createCounterPlugin(); const { CharCounter, WordCounter, LineCounter, CustomCounter } = counterPlugin; const plugins = [counterPlugin]; const text = `This editor has counters below! Try typing here and watch the numbers go up. 🙌 Note that the color changes when you pass one of the following limits: - 200 characters - 30 words - 10 lines `; export default class SimpleCounterEditor extends Component { state = { editorState: createEditorStateWithText(text), }; onChange = (editorState) => { this.setState({ editorState }); }; focus = () => { this.editor.focus(); }; customCountFunction(str) { const wordArray = str.match(/\S+/g); // matches words according to whitespace return wordArray ? wordArray.length : 0; } render() { return ( <div> <div className={editorStyles.editor} onClick={this.focus}> <Editor editorState={this.state.editorState} onChange={this.onChange} plugins={plugins} ref={(element) => { this.editor = element; }} /> </div> <div><CharCounter limit={200} /> characters</div> <div><WordCounter limit={30} /> words</div> <div><LineCounter limit={10} /> lines</div> <div> <CustomCounter limit={40} countFunction={this.customCountFunction} /> <span> words (custom function)</span> </div> <br /> <br /> </div> ); } }
components/Type/Type.story.js
NGMarmaduke/bloom
import React from 'react'; import { storiesOf } from '@storybook/react'; import SectionHeader from './SectionHeader/SectionHeader'; import Synopsis from './Synopsis/Synopsis'; import Quote from './Quote/Quote'; import IconLabel from './IconLabel/IconLabel'; import Statement from './Statement/Statement'; import m from '../../globals/modifiers.css'; storiesOf('Type', module) .add('<SectionHeader />', () => ( <SectionHeader className={ [m.pa48].join(' ') } title="Bloom: Pattern library" strapline="A styleguide & library of React components" /> )) .add('<SectionHeader /> centered', () => ( <SectionHeader className={ [m.pa48, m.center].join(' ') } title="Bloom: Pattern library" strapline="A styleguide & library of React components" /> )) .add('<SectionHeader /> reverse', () => ( <SectionHeader className={ [m.fgWhite, m.bgBlack, m.pa48].join(' ') } title="Bloom: Pattern library" strapline="A styleguide & library of React components" /> )) .add('<SectionHeader /> without strapline', () => ( <SectionHeader className={ [m.pa48, m.center].join(' ') } level={ 2 } title="Bloom: Pattern library" /> )) .add('<Synopsis /> default', () => ( <Synopsis className={ [m.pa48].join(' ') } title="Thousands of spaces, for any idea and budget." > Find a space that matches your price, location, and audience, or browse our destination guides for inspiration. </Synopsis> )) .add('<Synopsis /> centered', () => ( <Synopsis className={ [m.pa48, m.center].join(' ') } title="Focus on your idea." > We’ve organised legals & deposits simply so you can focus on the one thing { ' ' }that really matters - making your idea happen. </Synopsis> )) .add('<Synopsis /> advanced', () => ( <Synopsis className={ m.pa48 } title={ <span> <span className={ [m.fontSmI, m.bold, m.db, m.pbs].join(' ') }>Label</span> <span>Focus on your idea.</span> </span> } > We’ve organised legals & deposits simply so you can focus on the one thing { ' ' }that really matters - making your idea happen. </Synopsis> )).add('<Quote /> centered', () => ( <Quote citation="Rhett Butler" className={ m.center }> Frankly my dear, I don’t give a damn </Quote> )).add('<Quote /> left', () => ( <Quote citation="Rhett Butler" className={ m.left }> Frankly my dear, I don’t give a damn </Quote> )).add('<Quote /> right', () => ( <Quote citation="Rhett Butler" className={ m.right }> Frankly my dear, I don’t give a damn </Quote> )) .add('<IconLabel />', () => ( <IconLabel iconName="bogroll"> Bog roll </IconLabel> )) .add('<Statement />', () => ( <Statement> More <span className={ m.fgPrimary }>experiences</span> mean better cities. </Statement> )) .add('<Statement /> with number', () => ( <Statement number={ 1 } > More <span className={ m.fgPrimary }>experiences</span> mean better cities. </Statement> ));
programar/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
ottohernandezgarzon/tanks-colored-of-war
import React from 'react'; import { render } from 'react-dom'; // It's important to not define HelloWorld component right in this file // because in that case it will do full page reload on change import HelloWorld from './HelloWorld.jsx'; render(<HelloWorld />, document.getElementById('react-root'));
src/pages/Editor/pages/MapEditor/pages/EditMap/containers/MapEditor/components/DomainValueEditor.js
caspg/datamaps.co
import React from 'react' import PropTypes from 'prop-types' import NumericInput from '@src/components/NumericInput' const DomainValueEditor = (props) => <div> <p className="DomainValueEditor__paragraph">{props.label}</p> <NumericInput value={props.value} onBlur={props.onDomainValueChange} placeholder={props.placeholder} /> <style jsx>{` .DomainValueEditor__paragraph { margin-top: 10px; margin-bottom: 5px; } `}</style> </div> DomainValueEditor.propTypes = { label: PropTypes.string.isRequired, value: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), onDomainValueChange: PropTypes.func.isRequired, placeholder: PropTypes.oneOfType([PropTypes.number, PropTypes.string]), } export default DomainValueEditor;
app/containers/HomePage.js
bagnz0r/ichigo-player
// @flow import React, { Component } from 'react'; import Home from '../components/Home'; export default class HomePage extends Component { render() { return ( <Home /> ); } }
app/react-icons/fa/fast-forward.js
scampersand/sonos-front
import React from 'react'; import IconBase from 'react-icon-base'; export default class FaFastForward extends React.Component { render() { return ( <IconBase viewBox="0 0 40 40" {...this.props}> <g><path d="m1 36.9q-0.4 0.4-0.7 0.2t-0.3-0.7v-32.8q0-0.6 0.3-0.7t0.7 0.2l15.9 15.9q0.1 0.2 0.2 0.4v-15.8q0-0.6 0.3-0.7t0.7 0.2l15.9 15.9q0.2 0.2 0.3 0.4v-15.1q0-0.6 0.4-1t1-0.4h2.9q0.5 0 1 0.4t0.4 1v31.4q0 0.6-0.4 1t-1 0.4h-2.9q-0.6 0-1-0.4t-0.4-1v-15.1q-0.1 0.2-0.3 0.4l-15.9 15.9q-0.4 0.4-0.7 0.2t-0.3-0.7v-15.8q-0.1 0.2-0.2 0.4z"/></g> </IconBase> ); } }
src/website/app/demos/Dialog/common/DemoLayout.js
mineral-ui/mineral-ui
/* @flow */ import styled from '@emotion/styled'; import React from 'react'; import type { StyledComponent } from '@emotion/styled-base/src/utils'; const Root: StyledComponent<{ [key: string]: any }> = styled('div')( ({ theme }) => ({ padding: `${theme.space_inset_md}`, position: 'relative', '&:not(:last-child)': { paddingBottom: 0 }, '& > div': { position: 'static' }, '& [role="document"]': { width: 'auto' } }) ); const DemoLayout = (props: Object) => <Root {...props} />; export default DemoLayout;
src/js/home/App.js
CT-Data-Collaborative/edi-v2
import React, { Component } from 'react'; import Select from 'react-select'; import MarkdownBlock from './components/markdown_block'; import Links from './components/links'; class App extends Component { constructor(props) { super(props); this.state = { content: window.content, links: window.links }; this.updateSelectedTown = this.updateSelectedTown.bind(this); } componentWillMount() { if (window.choices != 'undefined') { this.setState({'choices': window.choices}); }; } updateSelectedTown(val) { this.setState({ selectedTown: val.value }) } render() { const content = this.state.content; const selectedTown = this.state.selectedTown ? this.state.selectedTown : ''; let choices = this.state.choices ? this.state.choices : ''; choices = this.state.choices.map((c) => { return { value: c.slug, label: c.name } }); return ( <div className="ctdata-edi-app"> <MarkdownBlock content={content}/> <h4>Learn about results in your community!</h4> <h5>To get started, select your town from the list below.</h5> <div className="homepage-dropdown"> <Select name="city-select" value={selectedTown} options={choices} onChange={this.updateSelectedTown} /> <Links links={this.state.links} selectedTown={selectedTown}/> </div> </div> ); } } export default App;
client/index.js
akshatsinha/store-deals
import React from 'react' import ReactDOM from 'react-dom' import { Provider } from 'react-redux' import ReactStormpath from 'react-stormpath' import routes from './routes' import store from './store' ReactStormpath.init({ endpoints: { baseUri: 'https://store-deals.apps.stormpath.io' } }) ReactDOM.render( <Provider store={store}> { routes } </Provider>, document.getElementById('root') )
src/svg-icons/device/nfc.js
matthewoates/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let DeviceNfc = (props) => ( <SvgIcon {...props}> <path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 18H4V4h16v16zM18 6h-5c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v8H8V8h2V6H6v12h12V6z"/> </SvgIcon> ); DeviceNfc = pure(DeviceNfc); DeviceNfc.displayName = 'DeviceNfc'; DeviceNfc.muiName = 'SvgIcon'; export default DeviceNfc;
1m_Redux_Lynda/Ex_Files_Learning_Redux/Exercise Files/Ch05/05_02/start/src/index.js
yevheniyc/C
import C from './constants' import React from 'react' import { render } from 'react-dom' import routes from './routes' import sampleData from './initialState' import storeFactory from './store' import { Provider } from 'react-redux' const initialState = (localStorage["redux-store"]) ? JSON.parse(localStorage["redux-store"]) : sampleData const saveState = () => localStorage["redux-store"] = JSON.stringify(store.getState()) const store = storeFactory(initialState) store.subscribe(saveState) window.React = React window.store = store render( <Provider store={store}> {routes} </Provider>, document.getElementById('react-container') )
app/assets/scripts/components/group.js
energy-data/market-opportunities
import React from 'react' import c from 'classnames' import Indicator from './indicator' const Group = React.createClass({ propTypes: { name: React.PropTypes.string, open: React.PropTypes.bool, layers: React.PropTypes.array, startEditing: React.PropTypes.func, saveEdit: React.PropTypes.func, cancelEdit: React.PropTypes.func, toggleLayerVisibility: React.PropTypes.func, updateLayerFilter: React.PropTypes.func, toggleOpenGroup: React.PropTypes.func }, render: function () { const { name, layers, open } = this.props return ( <section className={c('layer-group', {'layer-group--expanded': open})}> <header className='layer-group__header'> <a onClick={this._toggleOpenGroup} href='#' title='Expand/collapse group' className='layer-group__toggle'> <h1 className='layer-group__title'>{name}</h1> </a> </header> <div className='layer-group__body'> <ul className='layer-list'> {layers.map(layer => { return <Indicator key={layer.id} layer={layer} startEditing={this.props.startEditing} saveEdit={this.props.saveEdit} cancelEdit={this.props.cancelEdit} toggleLayerVisibility={this.props.toggleLayerVisibility} updateLayerFilter={this.props.updateLayerFilter} /> })} </ul> </div> </section> ) }, _toggleOpenGroup: function (e) { this.props.toggleOpenGroup(e, this.props.name) } }) export default Group
src/components/withViewport.js
Jahans3/thecraic
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React, { Component } from 'react'; // eslint-disable-line no-unused-vars import EventEmitter from 'eventemitter3'; import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment'; let EE; let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering const RESIZE_EVENT = 'resize'; function handleWindowResize() { if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) { viewport = { width: window.innerWidth, height: window.innerHeight }; EE.emit(RESIZE_EVENT, viewport); } } function withViewport(ComposedComponent) { return class WithViewport extends Component { constructor() { super(); this.state = { viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport, }; } componentDidMount() { if (!EE) { EE = new EventEmitter(); window.addEventListener('resize', handleWindowResize); window.addEventListener('orientationchange', handleWindowResize); } EE.on(RESIZE_EVENT, this.handleResize, this); } componentWillUnmount() { EE.removeListener(RESIZE_EVENT, this.handleResize, this); if (!EE.listeners(RESIZE_EVENT, true)) { window.removeEventListener('resize', handleWindowResize); window.removeEventListener('orientationchange', handleWindowResize); EE = null; } } render() { return <ComposedComponent {...this.props} viewport={this.state.viewport} />; } handleResize(value) { this.setState({ viewport: value }); // eslint-disable-line react/no-set-state } }; } export default withViewport;
src/svg-icons/action/perm-contact-calendar.js
ArcanisCz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionPermContactCalendar = (props) => ( <SvgIcon {...props}> <path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H6v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1z"/> </SvgIcon> ); ActionPermContactCalendar = pure(ActionPermContactCalendar); ActionPermContactCalendar.displayName = 'ActionPermContactCalendar'; ActionPermContactCalendar.muiName = 'SvgIcon'; export default ActionPermContactCalendar;
client/Components/UI/ErrorIndicator/index.js
myheritage/UiZoo.js
import React from 'react'; import Tooltip from '../Tooltip'; import './index.scss'; /** * @name * ErrorIndicator * * @module * Content * * @description * Show an error tooltip on a container * * @example * <ErrorIndicator error={new Error('message')}> * My error-full content * </ErrorIndicator> * * @param {node} children * @param {String|Error} [error] */ export default function ErrorIndicator ({children, error}) { return ( <div className="library-_-tooltip-error-indicator-wrapper"> {error ? (<div className="library-_-error-indicator-wrapper"> <Tooltip tooltip={<pre>{error.toString && error.toString()}</pre>}> <div className="library-_-error-indicator" /> </Tooltip> </div>) : null} {children} </div> ); }
app/components/Nav/index.js
HRR20-Lotus/affirmation
/** * * Nav * */ import React from 'react'; import { Toolbar, ToolbarGroup, ToolbarTitle } from 'material-ui/Toolbar'; import RaisedButton from 'material-ui/RaisedButton'; class Nav extends React.Component { // eslint-disable-line react/prefer-stateless-function render() { return ( <div> <Toolbar> <ToolbarGroup firstChild={true}> <ToolbarTitle text="Affirmation" /> </ToolbarGroup> <ToolbarGroup> <RaisedButton label="Logout" primary={true} /> </ToolbarGroup> </Toolbar> </div> ); } } export default Nav;
src/components/menu/MenuDivider.js
isogon/material-components
import React from 'react' import MenuItem from './MenuItem' import { MenuDivider as MenuDividerBase } from './Menu.style' export default class MenuDivider extends MenuItem { render() { return ( <MenuDividerBase {...this.props} {...this.state} innerRef={(menuItem) => { this.menuItem = menuItem }} /> ) } }
src/packages/@ncigdc/theme/icons/Table.js
NCI-GDC/portal-ui
// @flow import React from 'react'; export default ({ className = '', ...props }) => ( <i className={`${className} fa fa-table`} {...props} /> );
react-js/flux-demo/src/index.js
vanyaland/react-demos
import React from 'react'; import ReactDOM from 'react-dom'; import {createStore} from 'redux'; import {Provider} from 'react-redux' import App from './App'; import todoApp from './reducers/reducers'; import './index.css'; let store = createStore(todoApp); ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.getElementById('root') );
addons/info/example/story.js
enjoylife/storybook
import React from 'react'; import Button from './Button'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import backgrounds from 'react-storybook-addon-backgrounds'; storiesOf( 'Button' ).addWithInfo( 'simple usage', 'This is the basic usage with the button with providing a label to show the text.', () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> <p> Click the "?" mark at top-right to view the info. </p> </div> ) ); storiesOf('Button').addWithInfo( 'simple usage (inline info)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true } ); storiesOf('Button').addWithInfo( 'simple usage (disable source)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { source: false, inline: true } ); storiesOf('Button').addWithInfo( 'simple usage (no header)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { header: false, inline: true } ); storiesOf('Button').addWithInfo( 'simple usage (no prop tables)', ` This is the basic usage with the button with providing a label to show the text. `, () => <Button label="The Button" onClick={action('onClick')} />, { propTables: false, inline: true } ); storiesOf('Button').addWithInfo( 'simple usage (custom propTables)', ` This is the basic usage with the button with providing a label to show the text. Since, the story source code is wrapped inside a div, info addon can't figure out propTypes on it's own. So, we need to give relevant React component classes manually using \`propTypes\` option as shown below: ~~~js storiesOf('Button') .addWithInfo( 'simple usage (custom propTables)', <info>, <storyFn>, { inline: true, propTables: [Button]} ); ~~~ `, () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> </div> ), { inline: true, propTables: [Button] } ); storiesOf('Button').addWithInfo( 'simple usage (JSX description)', <div> <h2>This is a JSX info section</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare massa rutrum metus commodo, a mattis velit dignissim. Fusce vestibulum turpis sed massa egestas pharetra. Sed at libero nulla. </p> <p> <a href="https://github.com/storybooks/react-storybook-addon-info"> This is a link </a> </p> <p> <img src="http://placehold.it/350x150" /> </p> </div>, () => ( <div> <Button label="The Button" onClick={action('onClick')} /> <br /> <p> Click the "?" mark at top-right to view the info. </p> </div> ) ); storiesOf('Button').addWithInfo( 'simple usage (inline JSX description)', <div> <h2>This is a JSX info section</h2> <p> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed ornare massa rutrum metus commodo, a mattis velit dignissim. Fusce vestibulum turpis sed massa egestas pharetra. Sed at libero nulla. </p> <p> <a href="https://github.com/storybooks/react-storybook-addon-info"> This is a link </a> </p> <p> <img src="http://placehold.it/350x150" /> </p> </div>, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true } ); storiesOf('Button') .addDecorator(backgrounds([{ name: 'dark', value: '#333', default: true }])) .addWithInfo( 'with custom styles', ` This is an example of how to customize the styles of the info components. For the full styles available, see \`./src/components/Story.js\` `, () => <Button label="The Button" onClick={action('onClick')} />, { inline: true, styles: stylesheet => { stylesheet.infoPage = { backgroundColor: '#ccc', }; return stylesheet; }, } );
examples/js/custom/insert-modal/custom-insert-modal-field.js
prajapati-parth/react-bootstrap-table
/* eslint max-len: 0 */ /* eslint no-unused-vars: 0 */ /* eslint no-alert: 0 */ import React from 'react'; import ReactDOM from 'react-dom'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; const fruits = [ 'banana', 'apple', 'orange', 'tomato', 'strawberries' ]; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: fruits[i], sales: i % 2 ? 'Yes' : 'No', price: 100 + i }); } } addProducts(5); class SalesRadioField extends React.Component { getFieldValue = () => { return this.refs.yes.checked ? 'Yes' : 'No'; } render() { return ( <div> <label className='radio-inline'> <input ref='yes' type='radio' name='optradio' value='Yes'/>Yes </label> <label className='radio-inline'> <input ref='no' type='radio' name='optradio' value='No'/>No </label> </div> ); } } export default class CustomInsertModalFieldTable extends React.Component { customKeyField = (column, attr, editorClass, ignoreEditable) => { const seqId = this.refs.table.state.data.length; return ( <input type='text' { ...attr } disabled value={ seqId } className={ `${editorClass}` }/> ); } customNameField = (column, attr, editorClass, ignoreEditable, defaultValue) => { return ( <select className={ `${editorClass}` } { ...attr }> { fruits.map(name => (<option key={ name } value={ name }>{ name }</option>)) } </select> ); } customSaleField = (column, attr, editorClass, ignoreEditable, defaultValue) => { /* Sometime, your field is not only a HTML element, like radio, checkbox etc. In this case, you are suppose to be prodived a specific method name for react-bootstrap-table to get the value for this field. Notes: 1. You are suppose to be added ref to your custom React class 2. You are suppose to be implement getFieldValue function and return the value that user input */ return ( <SalesRadioField ref={ attr.ref } editorClass={ editorClass } ignoreEditable={ ignoreEditable }/> ); } render() { return ( <BootstrapTable ref='table' data={ products } insertRow> <TableHeaderColumn dataField='id' isKey={ true } customInsertEditor={ { getElement: this.customKeyField } }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name' customInsertEditor={ { getElement: this.customNameField } }>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='sales' customInsertEditor={ { getElement: this.customSaleField } }>On Sales?</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
src/containers/SignupPage.js
qandobooking/booking-frontend
import React from 'react'; import { replace } from 'react-router-redux'; import { reduxForm } from 'redux-form'; import { register, clearRegistration } from '../actions/registration'; import { rejectFormErrorsFromResponse } from '../utils/form'; import Spinner from '../components/Spinner'; import ErrorAlert from '../components/ErrorAlert'; import { FormGroup, ControlLabel, FormControl, Button, HelpBlock } from 'react-bootstrap'; import { createValidator, withMessage, required, match, email as emailValidationRule } from '../utils/validation'; function redirectGuest(props) { if (!props.isGuest) { props.replace('/'); } } const submit = (values, dispatch) => { return dispatch(register(values)).then(rejectFormErrorsFromResponse); }; class SignupPage extends React.Component { componentWillMount() { this.props.clearRegistration(); redirectGuest(this.props); } componentWillReceiveProps(nextProps) { if (nextProps.isGuest !== this.props.isGuest) { redirectGuest(nextProps); } } render() { const { signupUser } = this.props; return signupUser ? this.renderWelcome() : this.renderForm(); } renderWelcome() { const { signupUser: { name, email } } = this.props; return ( <div className="container-fluid padding-top-20 text-center"> <h1>Ciao {name}, benvenuto in Qando!</h1> <p> Ti sarà inviata una mail all'indirizzo {email}, apri il link al suo interno per confermare la registrazione a Qando! </p> </div> ); } renderForm() { const { fields: { name, email, password, confirmedPassword }, handleSubmit, signupError, submitting } = this.props return ( <div className="container-fluid padding-top-20"> <form onSubmit={handleSubmit(submit)} noValidate> <FormGroup controlId="formControlsName" validationState={(name.touched && name.error) ? 'error' : null} > <ControlLabel>Nome</ControlLabel> <FormControl type="text" placeholder="Nome" {...name} /> {name.touched && name.error && <HelpBlock>{name.error}</HelpBlock>} </FormGroup> <FormGroup controlId="formControlsEmail" validationState={(email.touched && email.error) ? 'error' : null} > <ControlLabel>Email</ControlLabel> <FormControl type="email" placeholder="Email" {...email} /> {email.touched && email.error && <HelpBlock>{email.error}</HelpBlock>} </FormGroup> <FormGroup controlId="formControlsPassword" validationState={(password.touched && password.error) ? 'error' : null} > <ControlLabel>Password</ControlLabel> <FormControl type="password" placeholder="Password" {...password} /> {password.touched && password.error && <HelpBlock>{password.error}</HelpBlock>} </FormGroup> <FormGroup controlId="formControlsConfirmedPassword" validationState={(confirmedPassword.touched && confirmedPassword.error) ? 'error' : null} > <ControlLabel>Conferma password</ControlLabel> <FormControl type="password" placeholder="Conferma password" {...confirmedPassword} /> {confirmedPassword.touched && confirmedPassword.error && <HelpBlock>{confirmedPassword.error}</HelpBlock>} </FormGroup> {signupError && <ErrorAlert title={`Errore registrazione`} {...signupError} />} { submitting ? <Spinner /> : <FormGroup> <Button type="submit"> Registrati </Button> </FormGroup> } </form> </div> ); } } function mapStateToProps(state) { const isGuest = !state.auth.token; const signupError = state.registration.error; const signupUser = state.registration.userInfo; return { isGuest, signupError, signupUser }; } export default reduxForm({ form: 'signup', fields: ['name', 'email', 'password', 'confirmedPassword'], validate: createValidator({ name: [required], email: [required, emailValidationRule], password: [required], confirmedPassword: [ required, withMessage(match('password'), 'Le due password non combaciano') ] }) }, mapStateToProps, { replace, clearRegistration })(SignupPage)
src/App.js
marcosmiklos/my-reads
import React, { Component } from 'react'; import { Route } from 'react-router-dom'; import * as BooksAPI from './utils/BooksAPI' import 'semantic-ui-css/semantic.min.css'; import { Container, Header, Icon } from 'semantic-ui-react' import Bookcase from './pages/Bookcase'; import SearchBooks from './pages/SearchBooks'; class App extends Component { constructor(props) { super(props); this.state = { books: [] } } componentDidMount() { BooksAPI.getAll().then((books) => { const result = books.map( r => { r.imageLinks = { smallThumbnail: this.resolveImage(r) }; return r; }); this.setState({ books: result }) }) } updateShelf = (event, data, book) => { if(data.value !== book.shelf) { const shelf = data.value; book.shelf = shelf; BooksAPI.update(book, shelf).then(() => { this.setState(state => ({ books: state.books.filter(bk => bk.id !== book.id).concat([book]) })); }); } }; resolveImage = (book) => ( (book.imageLinks && book.imageLinks.smallThumbnail) ? book.imageLinks.smallThumbnail : '/defaultcover.jpg' ) render() { const { books } = this.state; const shelves = [ { key: 'currentlyReading', text: 'Currently Reading', value: 'currentlyReading'}, { key: 'wantToRead', text: 'Want to Read', value: 'wantToRead' }, { key: 'read', text: 'Read', value: 'read' } ]; return ( <div className="App"> <Container style={{ marginTop: '3em', padding: '5em 0em' }}> <Header as='h1' color='teal' dividing> <Icon name='book' /> <Header.Content> My Reads </Header.Content> </Header> <Route exact path='/' render={() => ( <Bookcase books={books} shelves={shelves} onUpdateShelf={this.updateShelf} /> )}/> <Route path='/search' render={({ history }) => ( <SearchBooks books={books} shelves={shelves} onUpdateShelf={this.updateShelf} onResolveImage={this.resolveImage} /> )}/> </Container> </div> ) } } export default App;
src/components/progress/progress.js
woshisbb43/coinMessageWechat
import React from 'react'; import PropTypes from 'prop-types'; import classNames from '../../utils/classnames'; import Icon from '../icon'; /** * progress bar * */ const Progress = (props) => { const { className, showCancel, value, onClick, ...others } = props; const cls = classNames({ 'weui-progress': true, [className]: className }); let pgWdith = value > 100 ? 100 : value < 0 ? 0 : value; return ( <div className={cls} {...others}> <div className="weui-progress__bar"> <div className="weui-progress__inner-bar" style={{width: `${pgWdith}%`}}></div> </div> { showCancel ? <a href="javascript:;" className="weui-progress__opr" onClick={ e=> { if (onClick) onClick(e); } }> <Icon value="cancel"/> </a> : false } </div> ); }; Progress.propTypes = { /** * value of the bar * */ value: PropTypes.number, /** * enable cancel button * */ showCancel: PropTypes.bool }; Progress.defaultProps = { value: 0, showCancel: true }; export default Progress;
assets/jsx/views/courses/components/courseBox.js
Tjorriemorrie/besetfree
import React from 'react' import classNames from 'classnames' class CourseBox extends React.Component { render() { let { course } = this.props console.info('[CourseBox] render', course) return <div className="course_box"> <h3 className="title">{course.title}</h3> <h4 className="subtitle">{course.subtitle}</h4> <p>{course.name}</p> <p>{course.time}</p> <p>{course.venue}</p> <p>{course.cost}</p> <p>{course.description}</p> </div> } } export default CourseBox
src/docs/examples/ProgressBar/Example70Percent.js
Mikhail2k15/ps-react-michael
import React from 'react'; import ProgressBar from 'ps-react/ProgressBar'; export default function Example70Percent(){ return <ProgressBar percent={70} width={150}/> }
src/components/EventsWithData.js
OpenCollective/frontend
import React from 'react'; import PropTypes from 'prop-types'; import { FormattedDate, FormattedMessage } from 'react-intl'; import { graphql } from 'react-apollo'; import gql from 'graphql-tag'; import { Router } from '../server/pages'; class EventsWithData extends React.Component { static propTypes = { collectiveSlug: PropTypes.string.isRequired, onChange: PropTypes.func, }; constructor(props) { super(props); this.renderEventEntry = this.renderEventEntry.bind(this); this.createEvent = this.createEvent.bind(this); this.openEvent = this.openEvent.bind(this); } componentDidMount() { const { onChange } = this.props; this.isIframe = window.self !== window.top && window.location.hostname !== 'localhost'; // cypress is using an iframe for e2e testing; onChange && this.node && onChange({ height: this.node.offsetHeight }); } createEvent(e) { if (this.isIframe) { return; } Router.pushRoute('createEvent').then(() => { window.scrollTo(0, 0); }); e.preventDefault(); } openEvent(e, eventSlug) { if (this.isIframe) { return; // continue with default behavior of <a href> } const { collectiveSlug } = this.props; Router.pushRoute('event', { parentCollectiveSlug: collectiveSlug, eventSlug, }).then(() => { window.scrollTo(0, 0); }); e.preventDefault(); } renderEventEntry(event) { return ( <li key={event.id}> <a href={`/${event.parentCollective.slug}/events/${event.slug}`} onClick={e => this.openEvent(e, event.slug)} target="_top" > {event.name} </a> , &nbsp; {!event.startsAt && console.warn(`EventsWithData: event.startsAt should not be empty. event.id: ${event.id}`)} {event.startsAt && ( <React.Fragment> <FormattedDate value={event.startsAt} timeZone={event.timezone} day="numeric" month="long" />, &nbsp; </React.Fragment> )} {event.location.name} </li> ); } render() { const { loading, allEvents } = this.props.data; if (loading) return <div />; const now = new Date(), pastEvents = [], futureEvents = []; allEvents.map(event => { if (new Date(event.startsAt) > now) futureEvents.push(event); else pastEvents.push(event); }); pastEvents.reverse(); return ( <div className="Events" ref={node => (this.node = node)}> <style jsx> {` .Events { font-size: 1.4rem; line-height: 1.5; } .title { display: flex; align-items: baseline; } .title .action { font-size: 1.1rem; } h2 { font-size: 20px; margin-right: 1rem; margin-bottom: 0; } ul { list-style: none; padding: 0; margin-top: 0.5rem; } .createEvent { text-align: center; } `} </style> <div className="events"> {futureEvents.length === 0 && pastEvents.length === 0 && this.isIframe && ( <div className="createEvent"> <p> <FormattedMessage id="events.widget.noEventScheduled" defaultMessage={'No event has been scheduled yet.'} /> </p> <a href={`/${this.props.collectiveSlug}/events/new`} onClick={this.createEvent} className="btn btn-default" target="_top" > <FormattedMessage id="events.widget.createEvent" defaultMessage={'Create an Event'} /> </a> </div> )} {(futureEvents.length > 0 || pastEvents.length > 0) && ( <div> <div className="title"> <h2> <FormattedMessage id="events.title.futureEvents" values={{ n: futureEvents.length }} defaultMessage={'Next {n, plural, one {event} other {events}}'} /> </h2> {this.isIframe && ( <div className="action"> <a href={`/${this.props.collectiveSlug}/events/new`} onClick={this.createEvent} target="_blank" rel="noopener noreferrer" > <FormattedMessage id="events.widget.createEvent" defaultMessage={'Create an Event'} /> </a> </div> )} </div> <ul> {futureEvents.length === 0 && <div>No event planned.</div>} {futureEvents.map(this.renderEventEntry)} </ul> {pastEvents.length > 0 && ( <div className="pastEvents"> <div className="title"> <h2> <FormattedMessage id="events.title.pastEvents" values={{ n: pastEvents.length }} defaultMessage={'Past {n, plural, one {event} other {events}}'} /> </h2> </div> <ul>{pastEvents.map(this.renderEventEntry)}</ul> </div> )} </div> )} </div> </div> ); } } const getEventsQuery = gql` query allEvents($collectiveSlug: String) { allEvents(slug: $collectiveSlug) { id slug name description longDescription startsAt endsAt timezone location { name address lat long } tiers { id type name description amount } parentCollective { id slug name mission backgroundImage image } } } `; const addEventsData = graphql(getEventsQuery); export default addEventsData(EventsWithData);
src/svg-icons/av/snooze.js
xmityaz/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let AvSnooze = (props) => ( <SvgIcon {...props}> <path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 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 7zm-3-9h3.63L9 15.2V17h6v-2h-3.63L15 10.8V9H9v2z"/> </SvgIcon> ); AvSnooze = pure(AvSnooze); AvSnooze.displayName = 'AvSnooze'; AvSnooze.muiName = 'SvgIcon'; export default AvSnooze;
react-ui/src/components/RealEstateGraph.js
EdwinJow/truthindata
import React, { Component } from 'react'; import axios from 'axios'; import MenuItem from 'material-ui/MenuItem'; import SelectField from 'material-ui/SelectField'; import IconButton from 'material-ui/IconButton'; import Dialog from 'material-ui/Dialog'; import FlatButton from 'material-ui/FlatButton'; import FontIcon from 'material-ui/FontIcon'; import Checkbox from 'material-ui/Checkbox'; import AutoComplete from 'material-ui/AutoComplete'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import ReactTable from 'react-table' import _ from 'lodash' import 'react-table/react-table.css' import { LineChart, Line, CartesianGrid, XAxis, YAxis, Tooltip, Legend, ResponsiveContainer } from 'recharts'; import {orange500, indigo500, blue500, blueGrey100} from 'material-ui/styles/colors'; import GenericLoader from './shared/GenericLoader.js'; import {Tabs, Tab} from 'material-ui/Tabs'; import SwipeableViews from 'react-swipeable-views'; import ModalDemographics from './ModalDemographics.js' import '../css/real-estate-graph.css' import { withGoogleMap, GoogleMap, Marker, Circle } from "react-google-maps"; import mapStyles from './googlemaps/styles/grayscale.json' const LimitToMap = withGoogleMap(props => ( <GoogleMap defaultZoom={7} defaultCenter={{ lat: 33.453566, lng: -112.069103 }} defaultOptions={{ styles: mapStyles }} > {props.markers.map((marker, index) => ( <Marker {...marker} onRightClick={() => props.onMarkerRightClick(index)} /> ))} </GoogleMap> )); class RealEstateGraph extends Component { constructor(props) { super(props); this.state = { startDate: '2015-10', endDate: '2017-01', tableData: [], graphData: [], dateRange: [], metric: 'All', modalOpen: false, modalBody: 'Beepbepp', metricModalOpen: false, mapModalOpen: false, aggregator: 'avg', tableKey: 1, loaderOpen: true, slideIndex: 0, stateSelect: 'AZ', zipDetailTab: 'metric-graph', limitTo: { zip: "", radius: "", zipArr: [] }, regionDetails: { stateName: 'AZ', city: null, zip: null }, demographicsMetrics: [], householdMetrics: [], demographicAverages: { Zip : 85003, PercentInLaborForce : 55.2, PercentUnemployed : 4.7, PercentManagementJobs : 51.2, PercentServiceJobs : 15.6, PercentSalesOfficeJobs : 21.4, PercentConstructionJobs : 3.5, PercentManufacturingTransportationJobs : 8.4, TotalHouseholds : 3945, PercentHouseholdIncome25k : 34.4, PercentHouseholdIncome25k50k : 20.7, PercentHouseholdIncome50k75k : 10.9, PercentHouseholdIncome75k100k : 8, PercentHouseholdIncome100k150k : 15.5, PercentHouseholdIncome150k200k : 5.3, PercentHouseholdIncome200k : 5, TotalHouseholdMedianIncome : 41038, TotalHouseholdMeanIncome : 67808, PerCapitaIncome : 30082, PercentHealthInsured : 82.8, PercentNonHealthInsured : 17.2, PercentFamiliesBelowPovertyLevel : 24.4, PercentPeopleBelowPovertyLevel : 31.5, TotalPop18to24 : 848, Total18to24LessThanHighSchool : 375, Percent18to24LessThanHighSchool : 44.2, Total18to24HighSchoolGraduate : 219, Percent18to24HighSchoolGraduate : 25.8, Total18to24SomeCollegeOrAssociates : 153, Percent18to24SomeCollegeOrAssociates : 18, Total18to24BachelorsOrHigher : 101, Percent18to24BachelorsOrHigher : 11.9, TotalPop25Older : 7096, TotalPop25OlderLessThanHighSchool : 1447, PercentPop25OlderLessThanHighSchool : 20.4, TotalPop25OlderHighSchoolGraduate : 1366, PercentPop25OlderHighschoolGraduate : 19.3, TotalPop25OlderSomeCollege : 1706, PercentPop25OlderSomeCollege : 24, TotalPop25OlderAssociates : 281, PercentPop25OlderAssociates : 4, TotalPop25OlderBachelors : 1258, PercentPop25OlderBachelors : 17.7, TotalPop25OlderGraduates : 1038, PercentPop25OlderGraduates : 14.6, TotalPercentHighschoolOrHigher : 79.6, TotalPercentBachelorsOrHigher : 32.4, Year : 2015 }, demographics: { Zip : 85003, PercentInLaborForce : 55.2, PercentUnemployed : 4.7, PercentManagementJobs : 51.2, PercentServiceJobs : 15.6, PercentSalesOfficeJobs : 21.4, PercentConstructionJobs : 3.5, PercentManufacturingTransportationJobs : 8.4, TotalHouseholds : 3945, PercentHouseholdIncome25k : 34.4, PercentHouseholdIncome25k50k : 20.7, PercentHouseholdIncome50k75k : 10.9, PercentHouseholdIncome75k100k : 8, PercentHouseholdIncome100k150k : 15.5, PercentHouseholdIncome150k200k : 5.3, PercentHouseholdIncome200k : 5, TotalHouseholdMedianIncome : 41038, TotalHouseholdMeanIncome : 67808, PerCapitaIncome : 30082, PercentHealthInsured : 82.8, PercentNonHealthInsured : 17.2, PercentFamiliesBelowPovertyLevel : 24.4, PercentPeopleBelowPovertyLevel : 31.5, TotalPop18to24 : 848, Total18to24LessThanHighSchool : 375, Percent18to24LessThanHighSchool : 44.2, Total18to24HighSchoolGraduate : 219, Percent18to24HighSchoolGraduate : 25.8, Total18to24SomeCollegeOrAssociates : 153, Percent18to24SomeCollegeOrAssociates : 18, Total18to24BachelorsOrHigher : 101, Percent18to24BachelorsOrHigher : 11.9, TotalPop25Older : 7096, TotalPop25OlderLessThanHighSchool : 1447, PercentPop25OlderLessThanHighSchool : 20.4, TotalPop25OlderHighSchoolGraduate : 1366, PercentPop25OlderHighschoolGraduate : 19.3, TotalPop25OlderSomeCollege : 1706, PercentPop25OlderSomeCollege : 24, TotalPop25OlderAssociates : 281, PercentPop25OlderAssociates : 4, TotalPop25OlderBachelors : 1258, PercentPop25OlderBachelors : 17.7, TotalPop25OlderGraduates : 1038, PercentPop25OlderGraduates : 14.6, TotalPercentHighschoolOrHigher : 79.6, TotalPercentBachelorsOrHigher : 32.4, Year : 2015 }, householdAverages: { TotalHousingUnits: 7139, PercentHousingUnitsOccupied: 73.9113581133477, PercentHousingUnitsVacant: 24.1133333217951, PercentOwnerOccupied: 66.6017284662635, PercentRenterOccupied: 30.9298765241364, PercentValue100k: 34.7597530064759, PercentValue100k200k: 30.0266666385863, PercentValue200k300k: 15.0106172981086, PercentValue300k500k: 11.0681481527325, PercentValue500k1m: 4.4330864213867, PercentValue1m: 1.24098765724971, MedianHouseholdValue: 151163, TotalRentalHouseholds: 2107, PercentRent500: 18.3809876479116, PercentRent500to1000: 42.6345679200726, PercentRent1500to2000: 65, PercentRent2000to2500: 32, PercentRent2500to3000: 23, PercentRent3000: 23, Year: 2015 }, household: { TotalHousingUnits: 7139, PercentHousingUnitsOccupied: 73.9113581133477, PercentHousingUnitsVacant: 24.1133333217951, PercentOwnerOccupied: 66.6017284662635, PercentRenterOccupied: 30.9298765241364, PercentValue100k: 34.7597530064759, PercentValue100k200k: 30.0266666385863, PercentValue200k300k: 15.0106172981086, PercentValue300k500k: 11.0681481527325, PercentValue500k1m: 4.4330864213867, PercentValue1m: 1.24098765724971, MedianHouseholdValue: 151163, TotalRentalHouseholds: 2107, PercentRent500: 18.3809876479116, PercentRent500to1000: 42.6345679200726, PercentRent1500to2000: 65, PercentRent2000to2500: 32, PercentRent2500to3000: 23, PercentRent3000: 23, Year: 2015 }, autocompleteZips: [], markers: [] }; this.getPriceToRentData = this.getTableMetricData.bind(this); this.getDateRange = this.getDateRange.bind(this); } componentDidMount(){ this.getDateRange(); this.getTableMetricData(); this.getAutocompleteData(); } handleDateChange = (value, type) => { if(type === 'start'){ this.setState({startDate: value}, function(){ this.getTableMetricData(); }); } if(type === 'end'){ this.setState({endDate: value}, function(){ this.getTableMetricData(); }); } }; handleStateSelectChange = (event, index, value) => { this.setState({ stateSelect: value }, function(){ this.getAutocompleteData(); this.getTableMetricData(); }); } handleAggregateChange = (event, index, value) => { this.setState({ aggregator: value}); } handleMetricChange = (event, index, value) =>{ this.setState({ metric: value }, function(){ this.getTableMetricData(); }); } handleModalOpen = (type) =>{ if(type === 'drilldown'){ this.setState({modalOpen: true}); } else if(type === 'metric'){ this.setState({metricModalOpen: true}); } else if(type === 'map'){ this.setState({mapModalOpen: true}); } }; handleModalClose = (type) =>{ if(type === 'drilldown'){ this.setState({modalOpen: false}); } else if(type === 'metric'){ this.setState({metricModalOpen: false}); } else if(type === 'map'){ this.setState({mapModalOpen: false}); } }; handleMetricDefinitionTabChange = (value) => { this.setState({ slideIndex: value, }); }; handleZipDetailTabChange = (value) => { this.setState({ zipDetailTab: value }); } handleRadiusChange = (event, value) => { this.setState({ limitTo: Object.assign({}, this.state.limitTo, { radius: value }) }); } handleAutocompleteChange = (value) => { this.setState({ limitTo: Object.assign({}, this.state.limitTo, { zip: value }) }); } clearLimitTo = () => { this.setState({ markers: [] }); this.setState({ limitTo: Object.assign({}, this.state.limitTo, { zip: "", zipArr: [], radius: "" }) }, function(){ this.getTableMetricData(); }); } getGeoNearZips = () => { axios.get('/zip-metrics/geo-near',{ params: { Zip: this.state.limitTo.zip, Radius: this.state.limitTo.radius } }) .then(function (response) { debugger; let data = response.data; let zipArr = []; for (let value of data) { zipArr.push(value.Zip); } let markers = data.map(obj => ( { position: { lat: obj.Lat, lng: obj.Lng }, key: obj.Zip, label: obj.Zip.toString(), })); this.setState({ limitTo: Object.assign({}, this.state.limitTo, { zipArr: zipArr }), markers: markers }, function(){ this.getTableMetricData(); }); } .bind(this)) .catch(function (error) { console.log(error); }); } getAutocompleteData = () => { axios.get('/zip-metrics/all-zips',{ params: { State: this.state.stateSelect } }) .then(function (response) { let data = response.data; let zips = []; for (let value of data) { zips.push(value.Zip.toString()); } this.setState({ autocompleteZips: zips }); } .bind(this)) .catch(function (error) { console.log(error); }); } getLimitedDemographicAverages = () => { axios.get('/zip-metrics/recast-demographic-averages',{ params: { LimitToZips: JSON.stringify(this.state.limitTo.zipArr) } }) .then(function (response) { let data = response.data.averages; if(data !== {}){ this.setState({ demographicAverages: data }); } } .bind(this)) .catch(function (error) { console.log(error); }); } getLimitedHouseholdAverages = () => { axios.get('/zip-metrics/recast-household-averages',{ params: { LimitToZips: JSON.stringify(this.state.limitTo.zipArr) } }) .then(function (response) { let data = response.data.averages; if(data !== {}){ this.setState({ householdAverages: data }); } } .bind(this)) .catch(function (error) { console.log(error); }); } getDateRange = () => { axios.get('/zip-metrics/dates') .then(function (response) { let data = response.data; let len = data.dates.length; data.dates.sort(); this.setState({ dateRange: data.dates, endDate: data.dates[len - 1] }); }.bind(this)) .catch(function (error) { console.log(error); }); } getAllZipDemographics = () => { axios.get('/zip-metrics/demographics-all',{ params: { State: this.state.stateSelect } }) .then(function (response) { let data = response.data; this.setState({ demographicsMetrics: data.data, demographicAverages: data.averages }); }.bind(this)) .catch(function (error) { console.log(error); }); } getAllZipHouseholds = () => { axios.get('/zip-metrics/household-all',{ params: { State: this.state.stateSelect } }) .then(function (response) { let data = response.data; this.setState({ householdMetrics: data.data, householdAverages: data.averages }); }.bind(this)) .catch(function (error) { console.log(error); }); } getZipDemographics = () => { axios.get('/zip-metrics/demographics',{ params: { Zip: this.state.regionDetails.zip, State: this.state.stateSelect } }) .then(function (response) { let data = response.data; this.setState({ demographics: data }); console.log(data); }.bind(this)) .catch(function (error) { console.log(error); }); } getZipHousehold = () => { axios.get('/zip-metrics/household',{ params: { Zip: this.state.regionDetails.zip } }) .then(function (response) { let data = response.data; this.setState({ household: data }); }.bind(this)) .catch(function (error) { console.log(error); }); } getTableMetricData = () =>{ this.setState({ loaderOpen: true }); axios.get('/zip-metrics/table', { params: { StartDate: this.state.startDate, EndDate: this.state.endDate, Metric: this.state.metric, LimitToZips: JSON.stringify(this.state.limitTo.zipArr), State: this.state.stateSelect } }) .then(function (response) { var data = response.data; this.setState({ tableData: data.records }, this.setState({ loaderOpen: false }) ); if(this.state.limitTo.zipArr.length > 0 ){ this.getLimitedDemographicAverages(); this.getLimitedHouseholdAverages(); } else{ this.getAllZipDemographics(); this.getAllZipHouseholds(); } }.bind(this)) .catch(function (error) { console.log(error); }); } bindZipDrilldownDetails= (regionDetails, tabState) =>{ this.setState({ loaderOpen: true, zipDetailTab: tabState }); this.setState({ regionDetails:{ stateName: regionDetails.stateName, zip: regionDetails.zip, city: regionDetails.city } }, () => { this.getZipDemographics(); this.getZipHousehold(); }); axios.get('/zip-metrics/graph', { params: { StartDate: this.state.startDate, EndDate: this.state.endDate, Metric: this.state.metric, Zip: regionDetails.zip } }) .then(function (response) { let data = response.data.records; let mean = _.meanBy(data, function(o) { return o.Value; }); let dataLen = data.length; debugger; if (this.state.metric !== 'All') { let tableData = this.state.tableData; let tableDataLen = tableData.length; let hashMap = {}; tableData.filter(row => row.Metric = this.state.metric); for (let i = 0; i < tableDataLen; i++) { let date = tableData[i].Date; let value = tableData[i].Value; if (!hashMap.hasOwnProperty([date])) { hashMap[date] = { total: value, occurances: 0 }; } else { hashMap[date]['total'] += value; } if(value){ hashMap[date]['occurances']++; } } for (let i = 0; i < dataLen; i++) { let row = data[i]; let total = hashMap[row.Date].total; let occurances = hashMap[row.Date].occurances; row.Avg = total / occurances; } } else { for (let i = 0; i < dataLen; i++) { let row = data[i]; row.Avg = mean; } } this.setState({ graphData: data }, () => { this.setState({ loaderOpen: false }); }); this.handleModalOpen('drilldown'); }.bind(this)) .catch(function (error) { console.log(error); }); } render() { let _this = this; const columns = [ { Header: 'Zip', accessor: 'RegionName', PivotValue: ({ value, row }) => { let regionDetails = { stateName: row.State, city: row.City, zip: value }; return <span> {value} <IconButton onTouchTap={() => this.bindZipDrilldownDetails(regionDetails, 'metric-graph')} style={{float: 'right'}} tooltip='Metric Chart' > <FontIcon className='material-icons' color={orange500} style={{marginTop: '5rem'}}>timeline</FontIcon> </IconButton> <IconButton onTouchTap={() => this.bindZipDrilldownDetails(regionDetails, 'zip-details')} style={{float: 'right'}} tooltip='Zip Details' > <FontIcon className='material-icons' color={blue500} style={{marginTop: '5rem'}}>grain</FontIcon> </IconButton> </span> } }, { Header: 'City', accessor: 'City', aggregate: vals => vals[0], PivotValue: ({value}) => <span style={{color: 'darkblue'}}>{value}</span>, filterMethod: (filter, row) => row[filter.id].toLowerCase().includes(filter.value.toLowerCase()) }, { Header: 'State', accessor: 'State', aggregate: vals => vals[0], PivotValue: ({value}) => <span style={{color: 'darkblue'}}>{value}</span> }, { Header: 'Metric', accessor: 'Metric', aggregate: vals =>{ var unique = vals.filter((v, i, a) => a.indexOf(v) === i); return unique.join(', '); } }, { Header: 'Value', accessor: 'Value', aggregate: (vals, rows) => { if(_this.state.aggregator === 'avg'){ let avg = _.round(_.mean(vals)) return { number: avg, template: avg + ' (avg)' }; } if(_this.state.aggregator === 'percent'){ let rowLen = rows.length; let sorted = rows.sort((a, b) => a.Date.localeCompare(b.Date)); let startDate = sorted[0].Date; let endDate = sorted[rowLen - 1].Date; let startObjs = rows.filter(function(obj){ return obj.Date === startDate; }); let endObjs = rows.filter(function(obj){ return obj.Date === endDate; }); let startVal = startObjs.reduce((a, b) => ( a + b.Value), 0); let endVal = endObjs.reduce((a, b) => ( a + b.Value), 0); let percent = Math.round(((endVal - startVal) / startVal) * 100); if(isNaN(percent)){ percent = 0; } if(!isFinite(percent)){ percent = Math.round(endVal - startVal) }; let t = 'increase'; if(percent <=0){ t = 'decrease'; } return { number: percent, template: percent + ' (% ' + t + ')' }; } }, sortMethod: (a, b) => { return a.number > b.number ? 1 : -1; }, Aggregated: row => { let color = row.value.number <= 0 ? 'red' : 'blue'; return <span style={{color: color}}>{row.value.template}</span> } }, { Header: 'Date', accessor: 'Date', PivotValue: ({value}) => <span style={{color: 'darkblue'}}>{value}</span> }]; const modalActions = [ <FlatButton href={"https://www.trulia.com/" + this.state.regionDetails.stateName +"/" + this.state.regionDetails.city + "/"+ this.state.regionDetails.zip + "/"} target="_blank" label="Trulia" labelStyle={{color: orange500}} labelPosition="before" secondary={true} icon={<FontIcon className='material-icons' color={orange500}>home</FontIcon>} />, <FlatButton href={"http://www.realtor.com/realestateandhomes-search/" + this.state.regionDetails.zip} target="_blank" label="Realtor" labelPosition="before" secondary={true} icon={<FontIcon className='material-icons'>home</FontIcon>} />, <FlatButton href={"https://www.zillow.com/homes/for_sale/"+this.state.regionDetails.zip+"_rb/?fromHomePage=true&shouldFireSellPageImplicitClaimGA=false&fromHomePageTab=buy"} target="_blank" label="Zillow" labelPosition="before" labelStyle={{color: blue500}} icon={<FontIcon className='material-icons' color={blue500}>home</FontIcon>} />, <FlatButton label='Cancel' primary={true} onTouchTap={() => this.handleModalClose('drilldown')} /> ] const metricModalActions = [ <FlatButton label='Cancel' primary={true} onTouchTap={() => this.handleModalClose('metric')} /> ] const mapModalActions = [ <FlatButton label='Close' primary={true} onTouchTap={() => this.handleModalClose('map')} /> ] return ( <div className='height100'> <small style={{float:'right', color: {blueGrey100}, marginTop: '5px', marginRight: '5px', fontSize: '70%'}}> Data Sources:&nbsp;&nbsp; <a href="https://www.zillow.com/research/data/" style={{color: {blueGrey100}}} target="_blank">Zillow</a>&nbsp;&nbsp; <a href="https://factfinder.census.gov" style={{color: {blueGrey100}}} target="_blank">US Census</a> </small> <IconButton tooltip="Metric Detail" onTouchTap={() => this.handleModalOpen('metric')} iconClassName="material-icons" style={{ float: 'left' }} tooltipPosition="bottom-right" > select_all </IconButton> <SelectField floatingLabelText='State Select' value={this.state.stateSelect} onChange={this.handleStateSelectChange} style={ { marginLeft: '15px', width: '100px' } } autoWidth={true}> <MenuItem value={'AZ'} primaryText='AZ' /> <MenuItem value={'CA'} primaryText='CA' /> <MenuItem value={'PA'} primaryText='PA' /> </SelectField> <SelectField floatingLabelText='Metric Select' value={this.state.metric} onChange={this.handleMetricChange} style={{ marginLeft: '15px' }} > <MenuItem value={'All'} primaryText='All' /> <MenuItem value={'ZHVI'} primaryText='Home Value Index' /> <MenuItem value={'ZHVR'} primaryText='Home Value Rental Index' /> <MenuItem value={'IncreasingValues'} primaryText='Increasing Value' /> <MenuItem value={'PriceToRent'} primaryText='Price To Rent' /> </SelectField> <SelectField floatingLabelText='Start Date' value={this.state.startDate} style={{ marginLeft: '20px', width: '150px' }} > {this.state.dateRange.map((obj, index) => ( <MenuItem key={index} value={obj} primaryText={obj} onTouchTap={() => this.handleDateChange(obj, 'start')}/> ))} </SelectField> <SelectField floatingLabelText='End Date' value={this.state.endDate} style={{ marginLeft: '20px', width: '150px' }} > {this.state.dateRange.map((obj, index) => ( <MenuItem key={index} value={obj} primaryText={obj} onTouchTap={() => this.handleDateChange(obj, 'end')}/> ))} </SelectField> <SelectField floatingLabelText='Aggregator' value={this.state.aggregator} onChange={this.handleAggregateChange} style={{ marginLeft: '20px', width: '180px' }} > <MenuItem value={"avg"} primaryText={"Average"}/> <MenuItem value={"percent"} primaryText={"% Change"}/> </SelectField> <RaisedButton onTouchTap={() => this.handleModalOpen('map')} className={(this.state.limitTo.zipArr.length > 0 ? 'limit-btn-active': '')} label={(this.state.limitTo.zipArr.length > 0 ? 'FILTER ACTIVE': 'Limit Results')} style={{ top: '-20px', position: 'relative', marginLeft: '20px' }} /> <ReactTable key={this.state.tableKey} data={this.state.tableData} columns={columns} pivotBy={['RegionName']} filterable={true} defaultSorted={[ { id: 'Date' } ]} getTdProps={(state, rowInfo, column, instance) => { return { onClick: e => console.log('Click', { state, rowInfo, column, instance, event: e }) } }} /> <Dialog title={'Zip Detail: ' + this.state.regionDetails.zip} modal={false} actions={modalActions} open={this.state.modalOpen} onRequestClose={() => this.handleModalClose('drilldown')} contentStyle={{width: '100vw', maxWidth: 'none', height:'100vh', maxHeight: 'none', translateX:'0'}} autoScrollBodyContent={true} className={'zip-detail-modal'} > <Tabs value={this.state.zipDetailTab} onChange={this.handleZipDetailTabChange} > <Tab label="Metric Graph" value="metric-graph"> <ResponsiveContainer width='100%' height='100%' minHeight={400} minWidth={400}> <LineChart data={this.state.graphData} margin={{ top: 20, right: 30, left: 20, bottom: 5 }}> <XAxis dataKey='Date' /> <YAxis domain={['dataMin', 'auto']}/> <CartesianGrid strokeDasharray='3 3' /> <Tooltip /> <Legend /> <Line type='monotone' dataKey='Value' stroke='#8884d8'/> <Line type='monotone' dataKey='Avg' name={(this.state.limitTo.zipArr.length > 0 ? 'Active Radius Average' : this.state.regionDetails.stateName + ' Avg')} stroke='#FF9800'/> </LineChart> </ResponsiveContainer> </Tab> <Tab label="Zip Details" value="zip-details"> <ModalDemographics demographics={this.state.demographics} demographicsAvg={this.state.demographicAverages} household={this.state.household} householdAvg={this.state.householdAverages} /> </Tab> </Tabs> </Dialog> <Dialog title={'Restrict Zone'} modal={false} actions={mapModalActions} open={this.state.mapModalOpen} onRequestClose={() => this.handleModalClose('map')} contentStyle={{width: '100vw', maxWidth: 'none', height:'100vh', maxHeight: 'none', translateX:'0'}} autoScrollBodyContent={true} > <div style={{marginBottom: 15}}> <AutoComplete floatingLabelText='Centroid Zip' dataSource={this.state.autocompleteZips} maxSearchResults={10} onNewRequest={this.handleAutocompleteChange} searchText={this.state.limitTo.zip} /> <TextField value={this.state.limitTo.radius} floatingLabelText='Radius' type='number' onChange={this.handleRadiusChange} style={{marginLeft: '15px'}} /> <RaisedButton onTouchTap={this.getGeoNearZips} label={'Submit'} primary={true} disabled={(this.state.limitTo.zip && this.state.limitTo.radius ? false : true)} style={{ position: 'relative', marginLeft: '20px', backgroundColor: blue500 }} /> <RaisedButton onTouchTap={this.clearLimitTo} label={'Clear Limits'} secondary={true} disabled={(this.state.limitTo.zip && this.state.limitTo.radius ? false : true)} style={{ position: 'relative', marginLeft: '20px' }} /> </div> <LimitToMap containerElement={ <div style={{ height: `50vh` }} /> } mapElement={ <div style={{ height: `100%` }} /> } markers={this.state.markers} /> </Dialog> <Dialog title={'Metric Details'} modal={false} actions={metricModalActions} open={this.state.metricModalOpen} onRequestClose={() => this.handleModalClose('metric')} contentStyle={{width: '100%', maxWidth: 'none'}} autoScrollBodyContent={true} > <Tabs onChange={this.handleMetricDefinitionTabChange} value={this.state.slideIndex} > <Tab label="Home Value Index" value={0} /> <Tab label="Home Value Rental Index" value={1} /> <Tab label="Increasing Value" value={2} /> <Tab label="Price To Rent" value={3} /> </Tabs> <SwipeableViews index={this.state.slideIndex} onChangeIndex={this.handleMetricDefinitionTabChange} > <div> <h2>ZHVI</h2> Median estimated home value for all homes of these types within a region. </div> <div> <h2>ZHVR</h2> Median of the estimated rent price for all homes and apartments in a given region. </div> <div> <h2>IncreasingValues</h2> The percentage of homes in an given region with values that have increased in the past year. </div> <div> <h2>PriceToRent</h2> This ratio is first calculated at the individual home level, where the estimated home value is divided by 12 times its estimated monthly rent price. The the median of all home-level price-to-rent ratios for a given region is then calculated. </div> </SwipeableViews> </Dialog> <GenericLoader open={this.state.loaderOpen}/> </div> ); } } export default RealEstateGraph;
components/date-picker/common/yearTable.js
TDFE/td-ui
/** * @Author: Zhengfeng.Yao <yzf> * @Date: 2017-06-22 11:44:29 * @Last modified by: yzf * @Last modified time: 2017-06-26 14:00:11 */ import React from 'react'; import PropTypes from 'prop-types'; import moment from 'moment'; import chunk from 'lodash/chunk'; function isSameYear(one, two) { return one && two && one.isSame(two, 'year'); } function getYears(value) { const min = Math.floor(value.year() / 10) * 10 - 1; const max = Math.ceil(value.year() / 10) * 10; const years = []; for (let i = min; i <= max; i++) { const year = value.clone().year(i); years.push(year); } return years; } export default class YearTable extends React.Component { static propTypes = { prefixCls: PropTypes.string.isRequired, value: PropTypes.object, onSelect: PropTypes.func.isRequired }; renderBody() { const { value, onSelect, prefixCls, disabledDate } = this.props; const years = getYears(value); const yearTable = chunk(getYears(value), 4); const cellClass = `${prefixCls}-cell`; const curYearClass = `${prefixCls}-cur`; const selectedClass = `${prefixCls}-selected`; const disabledClass = `${prefixCls}-disabled-cell`; const minorClass = `${prefixCls}-minor`; const rows = []; for (let i = 0, passed = 0; i < yearTable.length; i++) { const yearCells = []; for (let j = 0; j < yearTable[i].length; j++) { const current = years[passed]; let cls = cellClass; let disabled = false; if (isSameYear(current, value)) { cls += ` ${selectedClass}`; } if (isSameYear(current, moment())) { cls += ` ${curYearClass}`; } if (passed === 0 || passed === years.length - 1) { cls += ` ${minorClass}`; } if (disabledDate && disabledDate(current, value)) { disabled = true; cls += ` ${disabledClass}`; } yearCells.push( <td key={passed} onClick={disabled ? undefined : onSelect.bind(null, current)} title={current.year()} className={cls} > <div> {current.year()} </div> </td> ); passed++; } rows.push( <tr key={`${i}-holder`} className={`${prefixCls}-placeholder`} /> ); rows.push( <tr key={i}> {yearCells} </tr> ); } rows.push( <tr key="last-holder" className={`${prefixCls}-placeholder`} /> ); return ( <tbody className={`${prefixCls}-tbody`}>{rows}</tbody> ); } render() { const { prefixCls } = this.props; return ( <table className={prefixCls} cellSpacing="0" cellPadding="0"> { this.renderBody() } </table> ); } }
test/format.js
concordancejs/react
import test from 'ava' import concordance from 'concordance' import React from 'react' import renderer from 'react-test-renderer' import plugin from '..' import HelloMessage from './fixtures/react/HelloMessage' const plugins = [plugin] const format = (value, options) => concordance.format(value, Object.assign({ plugins }, options)) const snapshot = (t, getValue, options) => { t.snapshot(format(getValue(), options)) } snapshot.title = prefix => `formats ${prefix}` const snapshotRendered = (t, getValue, options) => { const tree = renderer.create(getValue()).toJSON() t.snapshot(format(tree, options)) } snapshotRendered.title = prefix => `formats rendered ${prefix}` const macros = [snapshot, snapshotRendered] test('react elements', macros, () => <HelloMessage name='John' />) test('fragments', macros, () => <React.Fragment><HelloMessage name='John' /></React.Fragment>) test('object properties', macros, () => { return React.createElement('Foo', { object: { baz: 'thud' } }) }) test('array values in object properties', macros, () => { return React.createElement('Foo', { object: { baz: ['thud'] } }) }) test('array values in object properties in children', macros, () => { return React.createElement('Foo', null, React.createElement('Bar', { key: 'bar', object: { baz: ['thud'] } })) }) test('multiline string properties', macros, () => { return React.createElement('Foo', { multiline: 'foo\nbar' }) }) test('illegal spaces in property names', macros, () => { return React.createElement('Foo', { 'foo bar': 'baz' }) }) test('string and number children', macros, () => { return React.createElement('div', null, 'foo', 'bar', 42) }) test('properties and children', macros, () => { return React.createElement('Foo', { foo: 'bar' }, 'baz') }) test('max depth', macros, () => { return ( <div> <div> <div> Hello </div> <div id='foo'>Hello</div> <br id='bar'/> <br/> </div> </div> ) }, { maxDepth: 2 }) test('single line attribute values', snapshot, () => { return React.createElement('Foo', { bool: true }) }) test('opaque children', snapshot, () => { return ( <div> {true} {-0} {() => {}} {new Set(['foo'])} </div> ) })
src-example/components/molecules/Table/index.stories.js
SIB-Colombia/biodiversity_catalogue_v2_frontend
import React from 'react' import { storiesOf } from '@kadira/storybook' import { Table } from 'components' storiesOf('Table', module) .add('default', () => ( <Table> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> </Table> )) .add('with head', () => ( <Table head={ <tr> <th>Heading 1</th> <th>Heading 2</th> <th>Heading 3</th> </tr> } > <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> </Table> )) .add('with foot', () => ( <Table foot={ <tr> <td>Footer 1</td> <td>Footer 2</td> <td>Footer 3</td> </tr> } > <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> </Table> )) .add('with caption', () => ( <Table caption="Hello"> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> <tr> <td>Cell 1</td> <td>Cell 2</td> <td>Cell 3</td> </tr> </Table> ))
src/svg-icons/maps/local-airport.js
manchesergit/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let MapsLocalAirport = (props) => ( <SvgIcon {...props}> <path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/> </SvgIcon> ); MapsLocalAirport = pure(MapsLocalAirport); MapsLocalAirport.displayName = 'MapsLocalAirport'; MapsLocalAirport.muiName = 'SvgIcon'; export default MapsLocalAirport;
src/components/containers/allot-user-list-container.js
HuangXingBin/goldenEast
import React from 'react'; import { Button, AutoComplete, DatePicker, message } from 'antd'; import './user-list-container.css'; import UserListTable from '../views/allot-user-list-view.js'; import SearchUserInput from '../views/SearchUserInput.js'; import store from '../../store'; import { connect } from 'react-redux'; import { updateNoAuthorUserListDataSearch } from '../../actions/app-interaction-actions'; import { getNoAuthorUserListData, deleteSomeUserAuthor } from '../../api/app-interaction-api'; import { Link } from 'react-router'; var UserListContainer = React.createClass({ onChange(value){ store.dispatch(updateNoAuthorUserListDataSearch({ 'search[find]' : value, 'page' : 1 })); }, /* onDateChange(dates, dateStrings){ store.dispatch(updateAuthorUserListDataSearch({ 'search[d_begin]' : dateStrings[0], 'search[d_end]' : dateStrings[1], 'page' : 1 })); this.submitSearch(); },*/ submitSearch() { getNoAuthorUserListData(this.props.searchState); }, componentWillUnmount(){ //清理搜索条件 store.dispatch(updateNoAuthorUserListDataSearch({ 'search[find]' : '', 'search[d_begin]' : '', 'search[d_end]' : '', 'page' : 1 })); }, render(){ const data = this.props.dataState.data; console.log("data",data) function UserData() { if (data.list.length < 5 && data.list.length > 0 ){ userList = <UserListTable data={data.list} />; }else if (data.list.length <= 0 ){ userList = ' '; } else { userList = <h3 className="q-user-txt">同名人数过多,请输入详细信息搜索</h3>; }; }; let userList; if (data.length == 0){ userList = <h3 className="q-user-txt">请输入详细信息搜索</h3>; }else { UserData() }; return this.props.children || ( <div> <div className="userListHeader border-b"> <SearchUserInput placeholder="输入姓名或手机号" search={this.submitSearch} onChange={this.onChange} /> </div> <div className="column-txt"> {userList} </div> </div> ) } }); const mapStateToProps = function (store) { return { dataState : store.allotUserListState.dataState, searchState : store.allotUserListState.searchState } }; export default connect(mapStateToProps)(UserListContainer);