path
stringlengths
5
296
repo_name
stringlengths
5
85
content
stringlengths
25
1.05M
docs/src/app/components/pages/components/SvgIcon/Page.js
igorbt/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import iconReadmeText from './README'; import IconExampleSimple from './ExampleSimple'; import iconExampleSimpleCode from '!raw!./ExampleSimple'; import IconExampleIcons from './ExampleIcons'; import iconExampleIconsCode from '!raw!./ExampleIcons'; import iconCode from '!raw!material-ui/SvgIcon/SvgIcon'; const descriptions = { custom: 'This example uses a custom svg icon. The third example has a `hoverColor` defined.', material: 'This examples demonstrates how to use the included _Material icon_ components.', }; const SvgIconPage = () => ( <div> <Title render={(previousTitle) => `Svg Icon - ${previousTitle}`} /> <MarkdownElement text={iconReadmeText} /> <CodeExample title="Custom SVG icon" description={descriptions.custom} code={iconExampleSimpleCode} > <IconExampleSimple /> </CodeExample> <CodeExample title="Material icons" description={descriptions.material} code={iconExampleIconsCode} > <IconExampleIcons /> </CodeExample> <PropTypeDescription code={iconCode} /> </div> ); export default SvgIconPage;
src/components/RadioButton/RadioButton-story.js
wfp/ui
import React from 'react'; import { storiesOf } from '@storybook/react'; import { action } from '@storybook/addon-actions'; import { withKnobs, boolean, text } from '@storybook/addon-knobs'; import RadioButton from '../RadioButton'; import RadioButtonSkeleton from '../RadioButton/RadioButton.Skeleton'; const radioProps = () => ({ className: 'some-class', name: text('Form item name (name)', 'test'), value: text('Value (value)', 'standard'), labelText: text('Label text (labelText)', 'Standard Radio Button'), checked: boolean('Checked (checked)', false), disabled: boolean('Disabled (disabled)', false), onChange: action('onChange'), }); storiesOf('Components|RadioButton', module) .addDecorator(withKnobs) .add('Default', () => <RadioButton id="radio-1" {...radioProps()} />) .add('skeleton', () => ( <div> <RadioButtonSkeleton /> </div> ));
packages/wix-style-react/src/ListItemSection/docs/index.story.js
wix/wix-style-react
import React from 'react'; import Star from 'wix-ui-icons-common/Star'; import Download from 'wix-ui-icons-common/Download'; import Hint from 'wix-ui-icons-common/Hint'; import { header, tabs, tab, description, importExample, title, columns, divider, example as baseExample, playground, api, testkit, } from 'wix-storybook-utils/Sections'; import { storySettings } from '../test/storySettings'; import ListItemSection from '..'; import Box from '../../Box'; const example = config => baseExample({ components: { Star, Download, Hint }, ...config, }); export default { category: storySettings.category, storyName: 'ListItemSection', component: ListItemSection, componentPath: '..', componentProps: { title: 'List item Section title', suffix: 'Suffix', type: 'title', ellipsis: false, }, sections: [ header({ component: ( <Box width="500px" backgroundColor="#f0f4f7" padding="25px" border="1px solid #e5e5e5" > <ListItemSection title="List Item Section" suffix="Suffix" /> </Box> ), }), tabs([ tab({ title: 'Description', sections: [ columns([ description({ title: 'Description', text: 'ListItemSection is an internal component which is used to build dropdown or menu like components. Usually this item should not be used by consumers, though custom options builder is exposed for usage with DropdownBase.', }), ]), importExample(` // Use directly import { ListItemSection } from 'wix-style-react'; // Or use a builder import { listItemSectionBuilder } from 'wix-style-react'; `), divider(), title('Examples'), example({ title: 'Types', text: 'Component divides lists by 4 types – adding title, subheader, divider or simnple whitespace.', source: ` <Layout cols={1}> <ListItemSection title="Section title" /> <ListItemSection type="subheader" title="Subheader title" /> <ListItemSection type="divider" /> <ListItemSection type="whitespace" /> </Layout> `, }), example({ title: 'Suffix', text: 'For actions title and subheader types support a suffix.', source: ` <Layout cols={1}> <ListItemSection title="Title area" suffix="Suffix Action" /> <ListItemSection title="Title area" suffix={<InfoIcon content="Tooltip content!" />} /> <ListItemSection type="subheader" title="Title area" suffix="Suffix Action" /> <ListItemSection type="subheader" title="Title area" suffix={<InfoIcon content="Tooltip content!" />} /> </Layout> `, }), example({ title: 'Text cropping', text: 'By default component wraps the text. If needed it can be configured to show ellipsis and display full value on hover.', source: ` <Layout cols={1}> <Cell> <ListItemSection ellipsis title="This is a very very very very long text that will be cropped by ellipsis at some point" suffix="Nice long long long long long Suffix" /> </Cell> <Cell> <ListItemSection title="This is a very very very very long text that will *not* be cropped by ellipsis at some point" suffix="Nice long long long long long Suffix" /> </Cell> </Layout> `, }), example({ title: 'Advanced Example 1', source: ` <Box height='230px'> <DropdownLayout visible selectedId={2} options={[ listItemSectionBuilder({ title: 'Most Popular', }), listItemSelectBuilder({ id: 0, title: 'Wix Stores', }), listItemSelectBuilder({ id: 1, title: 'Wix Bookings', }), listItemSelectBuilder({ id: 2, title: 'Wix Blog', }), listItemSectionBuilder({ title: 'Other', }), listItemSelectBuilder({ title: 'Wix Events', }), listItemSelectBuilder({ id: 3, title: 'Wix Forum', }), listItemSelectBuilder({ id: 4, title: 'Wix Restaurants', }), listItemActionBuilder({ id: 5, title: 'See All Results', }), ]} /> </Box> `, }), example({ title: 'Advanced Example 2', source: ` <Box height='230px'> <DropdownLayout visible selectedId={2} options={[ listItemActionBuilder({ id: 0, skin: 'dark', size: 'small', title: 'Edit', prefixIcon: <Icons.EditSmall />, }), listItemActionBuilder({ id: 1, skin: 'dark', size: 'small', title: 'Duplicate', prefixIcon: <Icons.EditSmall />, }), listItemActionBuilder({ id: 3, skin: 'dark', size: 'small', title: 'Move to', prefixIcon: <Icons.MoveToSmall />, }), listItemSectionBuilder({ type: 'divider', }), listItemActionBuilder({ id: 4, skin: 'dark', size: 'small', title: 'Archive', prefixIcon: <Icons.ArchiveSmall />, }), listItemActionBuilder({ id: 4, skin: 'destructive', size: 'small', title: 'Delete', prefixIcon: <Icons.DeleteSmall />, }), ]} /> </Box> `, }), example({ title: 'Advanced Example 3', source: ` <Box height='230px'> <DropdownLayout visible selectedId={2} options={[ listItemSectionBuilder({ title: 'Admins', type: 'subheader', suffix: 'Edit', }), listItemSelectBuilder({ id: 0, title: 'John Wilson', }), listItemSelectBuilder({ id: 1, title: 'Silvester Grant', }), listItemSectionBuilder({ title: 'Members', type: 'subheader', suffix: 'Edit', }), listItemSelectBuilder({ title: 'Jason Angel', }), listItemSelectBuilder({ id: 3, title: 'Kalvin Mcleod', }), listItemSelectBuilder({ id: 4, title: 'Ro Giberton', }), ]} /> </Box> `, }), ], }), ...[ { title: 'API', sections: [api()] }, { title: 'Testkit', sections: [testkit()] }, { title: 'Playground', sections: [playground()] }, ].map(tab), ]), ], };
src/svg-icons/notification/airline-seat-recline-normal.js
lawrence-yu/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationAirlineSeatReclineNormal = (props) => ( <SvgIcon {...props}> <path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/> </SvgIcon> ); NotificationAirlineSeatReclineNormal = pure(NotificationAirlineSeatReclineNormal); NotificationAirlineSeatReclineNormal.displayName = 'NotificationAirlineSeatReclineNormal'; NotificationAirlineSeatReclineNormal.muiName = 'SvgIcon'; export default NotificationAirlineSeatReclineNormal;
src/icons/IosGameControllerB.js
fbfeix/react-icons
import React from 'react'; import IconBase from './../components/IconBase/IconBase'; export default class IosGameControllerB extends React.Component { render() { if(this.props.bare) { return <g> <g> <path d="M135.123,204.568c-10.688,0-19.343,8.717-19.343,19.441c0,10.727,8.655,19.447,19.343,19.447 c10.641,0,19.297-8.721,19.297-19.447C154.42,213.285,145.764,204.568,135.123,204.568z"></path> <path d="M466.279,248.866c-21.157-88.471-43.631-135.489-88.454-148.83C368.06,97.135,359.748,96,352.076,96 c-27.598,0-46.938,14.683-96.08,14.683c-49.174,0-68.502-14.681-96.062-14.683c-7.665,0-15.963,1.135-25.721,4.036 c-44.869,13.341-67.342,60.359-88.461,148.83c-21.181,88.473-17.334,152.363,7.679,164.289C57.502,415.1,61.662,416,65.885,416 c21.694,0,45.139-23.838,67.659-52.047C159.198,331.848,165.658,331,243.822,331h24.343c78.147,0,84.628,0.846,110.282,32.953 c22.526,28.207,45.97,52.004,67.665,52.004c4.226,0,8.384-0.879,12.457-2.823C483.574,401.208,487.421,337.339,466.279,248.866z M135.234,263.633C113.594,263.633,96,245.875,96,224.01c0-21.84,17.594-39.643,39.234-39.643 c21.655,0,39.249,17.803,39.249,39.643C174.483,245.875,156.89,263.633,135.234,263.633z M308.076,244.14 c-11.058,0-20.076-9.019-20.076-20.107c0-11.09,9.019-20.104,20.076-20.104c11.131,0,20.148,9.014,20.148,20.104 C328.225,235.121,319.207,244.14,308.076,244.14z M351.988,288c-11.058,0-20.053-8.951-20.053-20.016 c0-11.157,8.995-20.106,20.053-20.106c11.146,0,20.148,8.949,20.148,20.106C372.137,279.049,363.134,288,351.988,288z M351.988,200.19c-11.058,0-20.053-8.993-20.053-20.083c0-11.094,8.995-20.107,20.053-20.107c11.146,0,20.148,9.014,20.148,20.107 C372.137,191.197,363.134,200.19,351.988,200.19z M395.947,244.14c-11.105,0-20.101-9.019-20.101-20.107 c0-11.09,8.995-20.104,20.101-20.104c11.059,0,20.053,9.014,20.053,20.104C416,235.121,407.006,244.14,395.947,244.14z"></path> </g> </g>; } return <IconBase> <g> <path d="M135.123,204.568c-10.688,0-19.343,8.717-19.343,19.441c0,10.727,8.655,19.447,19.343,19.447 c10.641,0,19.297-8.721,19.297-19.447C154.42,213.285,145.764,204.568,135.123,204.568z"></path> <path d="M466.279,248.866c-21.157-88.471-43.631-135.489-88.454-148.83C368.06,97.135,359.748,96,352.076,96 c-27.598,0-46.938,14.683-96.08,14.683c-49.174,0-68.502-14.681-96.062-14.683c-7.665,0-15.963,1.135-25.721,4.036 c-44.869,13.341-67.342,60.359-88.461,148.83c-21.181,88.473-17.334,152.363,7.679,164.289C57.502,415.1,61.662,416,65.885,416 c21.694,0,45.139-23.838,67.659-52.047C159.198,331.848,165.658,331,243.822,331h24.343c78.147,0,84.628,0.846,110.282,32.953 c22.526,28.207,45.97,52.004,67.665,52.004c4.226,0,8.384-0.879,12.457-2.823C483.574,401.208,487.421,337.339,466.279,248.866z M135.234,263.633C113.594,263.633,96,245.875,96,224.01c0-21.84,17.594-39.643,39.234-39.643 c21.655,0,39.249,17.803,39.249,39.643C174.483,245.875,156.89,263.633,135.234,263.633z M308.076,244.14 c-11.058,0-20.076-9.019-20.076-20.107c0-11.09,9.019-20.104,20.076-20.104c11.131,0,20.148,9.014,20.148,20.104 C328.225,235.121,319.207,244.14,308.076,244.14z M351.988,288c-11.058,0-20.053-8.951-20.053-20.016 c0-11.157,8.995-20.106,20.053-20.106c11.146,0,20.148,8.949,20.148,20.106C372.137,279.049,363.134,288,351.988,288z M351.988,200.19c-11.058,0-20.053-8.993-20.053-20.083c0-11.094,8.995-20.107,20.053-20.107c11.146,0,20.148,9.014,20.148,20.107 C372.137,191.197,363.134,200.19,351.988,200.19z M395.947,244.14c-11.105,0-20.101-9.019-20.101-20.107 c0-11.09,8.995-20.104,20.101-20.104c11.059,0,20.053,9.014,20.053,20.104C416,235.121,407.006,244.14,395.947,244.14z"></path> </g> </IconBase>; } };IosGameControllerB.defaultProps = {bare: false}
src/components/TopBar.js
dkadrios/zendrum-stompblock-client
import React from 'react' import PropTypes from 'prop-types' import { withStyles, AppBar, Toolbar, SvgIcon, Typography } from '@material-ui/core' import UserInfo from './UserInfo' import ZendrumLogo from '../images/ZendrumLogo.svg.js' import RestompAd from './RestompAd' const styles = { title: { flex: 1, fontFamily: 'Armalite-Rifle', fontSize: '42px', fontWeight: 'normal', marginLeft: '4px', }, icon: { width: 45, height: 45, }, toolbar: { paddingLeft: '8px', }, } const TopBar = ({ classes }) => ( <AppBar position="static"> <Toolbar className={classes.toolbar}> <SvgIcon className={classes.icon}> <ZendrumLogo /> </SvgIcon> <Typography type="title" color="inherit" className={classes.title} > STOMPBLOCK </Typography> <RestompAd /> <div> <UserInfo /> </div> </Toolbar> </AppBar> ) TopBar.propTypes = { classes: PropTypes.object.isRequired } export default withStyles(styles)(TopBar)
src/components/custom-drawer-content.js
Doko-Demo-Doa/CSClient-RN
/** * @flow */ 'use strict'; import React from 'react'; import { View, Image, Alert } from 'react-native'; import { NavigationActions } from 'react-navigation'; import { Body, Icon, Left, ListItem, Text } from 'native-base'; import { connect } from 'react-redux'; import md5 from 'blueimp-md5'; import { requestLogout } from '../actions/actions-users'; const CustomDrawerContent = props => { const { logout, user } = props; const { dispatch } = props.navigation; const closeDrawer = NavigationActions.navigate({ routeName: 'DrawerClose', }); const goToScreen = screenName => { const navigateAction = NavigationActions.navigate({ routeName: screenName, }); dispatch(closeDrawer); setTimeout(() => dispatch(navigateAction), 700); }; const onPressLogout = () => { Alert.alert( 'Clip-sub', 'You will be logged out, are you sure?', [ { text: 'OK', onPress: () => logout() }, { text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel', }, ], { cancelable: false }, ); dispatch(NavigationActions.navigate({ routeName: 'DrawerClose' })); }; const userItem = !user ? ( <ListItem icon onPress={() => goToScreen('Auth')}> <Left> <Icon name="person" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Login / Register</Text> </Body> </ListItem> ) : ( <ListItem icon onPress={() => goToScreen('Profile')}> <Left> <Icon name="person" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Profile</Text> </Body> </ListItem> ); return ( <View style={drawerStyle.drawerMenuContainer}> <View style={drawerStyle.drawerHeader}> <View style={drawerStyle.miniProfile}> <Image source={ user ? { uri: 'https://gravatar.com/avatar/' + md5(user.email) + '?s=200', } : require('../assets/default_avatar.png') } style={{ width: 90, height: 90, borderRadius: 45, zIndex: 9 }} /> <Text suppressHighlighting style={{ color: '#fff' }}> {user ? user.nickname : ''} </Text> <Text style={{ fontSize: 10, color: '#fff' }}> {user ? user.email : ''} </Text> </View> </View> <ListItem icon onPress={() => dispatch(closeDrawer)}> <Left> <Icon name="home" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Home</Text> </Body> </ListItem> {userItem} <ListItem icon style={{ alignSelf: 'flex-end' }} onPress={() => goToScreen('Preference')} > <Left> <Icon name="ios-construct-outline" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Settings (soon)</Text> </Body> </ListItem> {user && user.id !== null ? ( <ListItem icon onPress={() => onPressLogout()}> <Left> <Icon name="ios-exit-outline" style={{ color: '#EF5350' }} /> </Left> <Body> <Text style={drawerStyle.itemText}>Log out</Text> </Body> </ListItem> ) : null} </View> ); }; const drawerStyle = { drawerMenuContainer: { backgroundColor: '#fff9f9', flex: 1, alignSelf: 'stretch', flexDirection: 'column', }, drawerHeader: { height: 160, backgroundColor: '#fe686a', }, miniProfile: { position: 'absolute', left: 18, bottom: 12, }, itemText: { fontFamily: 'Hoefler Text', color: '#706b6b', }, }; const mapStateToProps = state => { const { user } = state; return { user, }; }; const mapDispatchToProps = dispatch => { return { logout: () => { return dispatch(requestLogout()); }, }; }; export default connect(mapStateToProps, mapDispatchToProps)( CustomDrawerContent, );
docs/src/components/Typography/Typography.js
seekinternational/seek-asia-style-guide
import React from 'react'; import { Helmet } from 'react-helmet'; import PropTypes from 'prop-types'; import { PageBlock, Card, Section, Paragraph, Text, TextLink, Strong, Positive, Critical, Secondary } from 'seek-asia-style-guide/react'; import { ScreenReaderOnly } from 'seek-asia-style-guide/react'; import Demo from '../Demo/Demo'; import textDemoSpec from 'seek-asia-style-guide/react/Text/Text.demo'; const BackgroundContainer = ({ component: DemoComponent, componentProps }) => ( <PageBlock> <Section style={{ maxWidth: 720 }}> <DemoComponent {...componentProps} /> </Section> </PageBlock> ); BackgroundContainer.propTypes = { component: PropTypes.any, componentProps: PropTypes.object.isRequired }; const loremIpsum = [ 'Lorem ipsum dolor sit amet, consectetur adipiscing elit,', 'sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.', 'Ut convallis elit convallis, bibendum mauris et, lacinia mi.', 'Pellentesque quis arcu dignissim nibh tempor placerat et et lorem.' ].join('\n'); const loremIpsumShort = `${loremIpsum.split(',')[0]}.`; const pageTitle = 'Typography - SEEK Asia Style Guide'; export default () => ( <div> <ScreenReaderOnly> <h1>{pageTitle}</h1> </ScreenReaderOnly> <Helmet> <title>{pageTitle}</title> </Helmet> <PageBlock> <Section header> <Text screaming>Typography</Text> </Section> <Card transparent style={{ maxWidth: 720 }}> <Section> <Paragraph> <Text>Since typography forms the backbone of our design language, we have a suite of responsive typographical components to support semantic usage of our type hierarchy.</Text> </Paragraph> <Paragraph> <Text>The core typographical building block is the &ldquo;Text&rdquo; component, which renders a block-level span element with a single grid row below it, to leave room for descenders.</Text> </Paragraph> <Paragraph> <Text>It accepts a wide range of options, which can be seen below.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ ...textDemoSpec, title: null }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Paragraph> <Text>To better understand these options, let's step through them one by one.</Text> </Paragraph> </Section> <Section> <Text shouting>Standard Text</Text> <Paragraph> <Text>By default, when no options are provided, standard text is rendered.</Text> </Paragraph> <Paragraph> <Text>Standard text is 14px over 2 grid rows on desktop, and 18px over 3 grid rows on mobile.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { children: loremIpsum }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Weight Variants</Text> <Paragraph> <Text>While all elements in our type hierarchy include a default weight, you can also override these with the provided weight variants.</Text> </Paragraph> </Section> <Section> <Text shouting>Strong Text</Text> <Paragraph> <Text>Any text element can be explicity marked as strong with the &ldquo;strong&rdquo; property, which also causes the element to render a &ldquo;strong&rdquo; tag.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { strong: true, children: loremIpsumShort }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Paragraph> <Text>In cases where only a portion of a text block should be marked as strong, a &ldquo;Strong&rdquo; component is provided.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Strong>strong.</Strong>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Regular Text</Text> <Paragraph> <Text>Any text element can be explicity set to regular weight with the &ldquo;regular&rdquo; property.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { screaming: true, regular: true, children: loremIpsumShort }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Light Text</Text> <Paragraph> <Text>Finally, any text element can be explicity set to light weight with the &ldquo;light&rdquo; property.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { screaming: true, light: true, children: loremIpsumShort }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Tone Variants</Text> <Paragraph> <Text>All text is rendered in our standard neutral shade of black by default, but sometimes text needs to be displayed with different tones.</Text> </Paragraph> </Section> <Section> <Text shouting>Positive Text</Text> <Paragraph> <Text>Any text element can be explicity marked as positive with the &ldquo;positive&rdquo; property or the inline &ldquo;Positive&rdquo; component.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { positive: true, children: loremIpsumShort }, options: [] }} /> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { superstandard: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Positive>positive.</Positive>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Critical Text</Text> <Paragraph> <Text>Any text element can be explicity marked as critical with the &ldquo;critical&rdquo; property or the inline &ldquo;Critical&rdquo; component.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { critical: true, children: loremIpsumShort }, options: [] }} /> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Critical>critical.</Critical>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Secondary Text</Text> <Paragraph> <Text>Any text element can be explicity marked as secondary with the &ldquo;secondary&rdquo; property or the inline &ldquo;Secondary&rdquo; component.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { secondary: true, children: loremIpsumShort }, options: [] }} /> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is ', <Secondary>secondary.</Secondary>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Text Links</Text> <Paragraph> <Text>To create a standard text-based link, a &ldquo;TextLink&rdquo; component is provided.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { loud: true, // eslint-disable-next-line react/jsx-key children: ['The last word of this sentence is a ', <TextLink href="#">link</TextLink>] }, options: [] }} /> <PageBlock> <Card transparent style={{ maxWidth: 720 }}> <Section> <Text shouting>Disabling Baseline</Text> <Paragraph> <Text>By default, all text is adjusted to sit correctly on baseline using <TextLink href="https://github.com/michaeltaranto/basekick">basekick</TextLink>.</Text> </Paragraph> <Paragraph> <Text>In some cases, when text needs to be vertically centred within a container, this isn&rsquo;t the desired behaviour. To deal with this, you can optionally disable the baseline adjustment.</Text> </Paragraph> </Section> </Card> </PageBlock> <Demo spec={{ component: Text, container: BackgroundContainer, block: true, initialProps: { screaming: true, baseline: false, children: loremIpsumShort }, options: [] }} /> </div> );
src/components/SummaryDetail/SummaryDetail.js
propertybase/react-lds
import React from 'react'; import PropTypes from 'prop-types'; import cx from 'classnames'; import { ButtonIcon, IconButton } from '../Button'; const SummaryDetail = ({ children, containerClassName, iconButtonClassName, isOpen, onOpen, renderTitle, title, }) => ( <div className={cx('slds-summary-detail', { 'slds-is-open': isOpen })}> {onOpen && ( <IconButton onClick={onOpen} className={cx('slds-m-right_x-small', iconButtonClassName)} > <ButtonIcon className="slds-summary-detail__action-icon" icon="switch" sprite="utility" /> </IconButton> )} <div className={cx(containerClassName)}> <div className="slds-summary-detail__title"> {renderTitle(title)} </div> {children && ( <div aria-hidden={!isOpen} className="slds-summary-detail__content"> {children({ isOpen })} </div> )} </div> </div> ); SummaryDetail.defaultProps = { children: null, containerClassName: null, iconButtonClassName: null, isOpen: false, onOpen: null, renderTitle: title => ( <h3 className="slds-text-heading_small slds-truncate"> {title} </h3> ), }; SummaryDetail.propTypes = { /** * Function that renders the content. Takes { isOpen } as arguments */ children: PropTypes.func, /** * Additional className for container */ containerClassName: PropTypes.string, /** * Additional className for the expand icon */ iconButtonClassName: PropTypes.string, /** * Whether the content is expanded */ isOpen: PropTypes.bool, /** * Triggered on open icon and title click */ onOpen: PropTypes.func, /** * Renders custom title markup if provided. Receives title as an argument */ renderTitle: PropTypes.func, /** * Title to be used by the renderTitle function */ title: PropTypes.string.isRequired, }; export default SummaryDetail;
src/components/texts/subtitle-text.js
tuantle/hypertoxin
/** * Copyright 2016-present Tuan Le. * * Licensed under the MIT License. * You may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://opensource.org/licenses/mit-license.html * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * *------------------------------------------------------------------------ * * @module SubtitleText * @description - Subtitle text component. * * @author Tuan Le (tuan.t.lei@gmail.com) * * * @flow */ 'use strict'; // eslint-disable-line import React from 'react'; import ReactNative from 'react-native'; // eslint-disable-line import PropTypes from 'prop-types'; import { Text as AnimatedText } from 'react-native-animatable'; import { DefaultTheme, DefaultThemeContext } from '../../themes/default-theme'; const DEFAULT_ANIMATION_DURATION_MS = 300; const DEFAULT_SUBTITLE_TEXT_STYLE = DefaultTheme.text.font.subtitle; const readjustStyle = (newStyle = { shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, indentation: 0, color: `themed` }, prevAdjustedStyle = DEFAULT_SUBTITLE_TEXT_STYLE, Theme = DefaultTheme) => { const { shade, alignment, decoration, font, indentation, color, style } = newStyle; const themedShade = shade === `themed` ? Theme.text.subtitle.shade : shade; let themedColor; if (color === `themed`) { if (Theme.text.color.subtitle.hasOwnProperty(Theme.text.subtitle.color)) { themedColor = Theme.text.color.subtitle[Theme.text.subtitle.color][themedShade]; } else { themedColor = Theme.text.subtitle.color; } } else if (Theme.text.color.subtitle.hasOwnProperty(color)) { themedColor = Theme.text.color.subtitle[color][themedShade]; } else { themedColor = color; } return { small: { ...prevAdjustedStyle.small, ...Theme.text.font.subtitle.small, fontFamily: font === `themed` ? Theme.text.font.subtitle.small.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, normal: { ...prevAdjustedStyle.normal, ...Theme.text.font.subtitle.normal, fontFamily: font === `themed` ? Theme.text.font.subtitle.normal.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) }, large: { ...prevAdjustedStyle.large, ...Theme.text.font.subtitle.large, fontFamily: font === `themed` ? Theme.text.font.subtitle.large.fontFamily : font, textAlign: alignment, textDecorationLine: decoration, paddingLeft: indentation > 0 ? indentation : 0, paddingRight: indentation < 0 ? -indentation : 0, color: themedColor, ...(typeof style === `object` ? style : {}) } }; }; export default class SubtitleText extends React.Component { static contextType = DefaultThemeContext static propTypes = { exclusions: PropTypes.arrayOf(PropTypes.string), room: PropTypes.oneOf([ `none`, `content-left`, `content-middle`, `content-right`, `content-bottom`, `content-top`, `media`, `activity-indicator` ]), shade: PropTypes.oneOf([ `themed`, `light`, `dark` ]), alignment: PropTypes.oneOf([ `left`, `center`, `right` ]), decoration: PropTypes.oneOf([ `none`, `underline`, `line-through` ]), size: PropTypes.oneOf([ `themed`, `small`, `normal`, `large` ]), font: PropTypes.string, indentation: PropTypes.number, uppercased: PropTypes.bool, lowercased: PropTypes.bool, color: PropTypes.string, initialAnimation: PropTypes.oneOfType([ PropTypes.string, PropTypes.shape({ refName: PropTypes.string, transitions: PropTypes.arrayOf(PropTypes.shape({ to: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), from: PropTypes.oneOfType([ PropTypes.func, PropTypes.object ]), option: PropTypes.shape({ duration: PropTypes.number, delay: PropTypes.number, easing: PropTypes.string }) })), onTransitionBegin: PropTypes.func, onTransitionEnd: PropTypes.func, onAnimationBegin: PropTypes.func, onAnimationEnd: PropTypes.func }) ]) } static defaultProps = { exclusions: [ `` ], room: `none`, shade: `themed`, alignment: `left`, decoration: `none`, font: `themed`, size: `themed`, indentation: 0, uppercased: false, lowercased: false, color: `themed`, initialAnimation: `themed` } static getDerivedStateFromProps (props, state) { const { shade, alignment, decoration, font, indentation, color, style } = props; const { Theme } = state.context; return { adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, state.adjustedStyle, Theme) }; } constructor (props) { super(props); const component = this; component.refCache = {}; component.state = { context: { Theme: DefaultTheme }, adjustedStyle: DEFAULT_SUBTITLE_TEXT_STYLE }; } animate (animation = { onTransitionBegin: () => null, onTransitionEnd: () => null, onAnimationBegin: () => null, onAnimationEnd: () => null }) { const component = this; const { Theme } = component.context; if (typeof animation === `string` && animation !== `none`) { const animationName = animation.replace(/-([a-z])/g, (match, word) => word.toUpperCase()); if (Theme.text.animation.subtitle.hasOwnProperty(animationName)) { animation = Theme.text.animation.subtitle[animationName]; } } if (typeof animation === `object`) { const { refName, transitions, onTransitionBegin, onTransitionEnd, onAnimationBegin, onAnimationEnd } = animation; const componentRef = component.refCache[refName]; if (componentRef !== undefined && Array.isArray(transitions)) { let transitionDuration = 0; const transitionPromises = transitions.map((transition, transitionIndex) => { let transitionBeginPromise; let transitionEndPromise; if (typeof transition === `object`) { let transitionType; let componentRefTransition = { from: {}, to: {} }; let componentRefTransitionOption = { duration: DEFAULT_ANIMATION_DURATION_MS, delay: 0, easing: `linear` }; if (transition.hasOwnProperty(`from`)) { let from = typeof transition.from === `function` ? transition.from(component.props, component.state, component.context) : transition.from; componentRefTransition.from = typeof from === `object` ? from : {}; transitionType = `from`; } if (transition.hasOwnProperty(`to`)) { let to = typeof transition.to === `function` ? transition.to(component.props, component.state, component.context) : transition.to; componentRefTransition.to = typeof to === `object` ? to : {}; transitionType = transitionType === `from` ? `from-to` : `to`; } if (transition.hasOwnProperty(`option`) && typeof transition.option === `object`) { componentRefTransitionOption = { ...componentRefTransitionOption, ...transition.option }; } transitionBeginPromise = new Promise((resolve) => { setTimeout(() => { if (transitionType === `to`) { componentRef.transitionTo( componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing, componentRefTransitionOption.delay ); } else if (transitionType === `from-to`) { setTimeout(() => { componentRef.transition( componentRefTransition.from, componentRefTransition.to, componentRefTransitionOption.duration, componentRefTransitionOption.easing ); }, componentRefTransitionOption.delay); } (typeof onTransitionBegin === `function` ? onTransitionBegin : () => null)(transitionIndex); resolve((_onTransitionBegin) => (typeof _onTransitionBegin === `function` ? _onTransitionBegin : () => null)(_onTransitionBegin)); }, transitionDuration + 5); }); transitionDuration += componentRefTransitionOption.duration + componentRefTransitionOption.delay; transitionEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onTransitionEnd === `function` ? onTransitionEnd : () => null)(transitionIndex); resolve((_onTransitionEnd) => (typeof _onTransitionEnd === `function` ? _onTransitionEnd : () => null)(transitionIndex)); }, transitionDuration); }); } return [ transitionBeginPromise, transitionEndPromise ]; }); const animationBeginPromise = new Promise((resolve) => { (typeof onAnimationBegin === `function` ? onAnimationBegin : () => null)(); resolve((_onAnimationBegin) => (typeof _onAnimationBegin === `function` ? _onAnimationBegin : () => null)()); }); const animationEndPromise = new Promise((resolve) => { setTimeout(() => { (typeof onAnimationEnd === `function` ? onAnimationEnd : () => null)(); resolve((_onAnimationEnd) => (typeof _onAnimationEnd === `function` ? _onAnimationEnd : () => null)()); }, transitionDuration + 5); }); return Promise.all([ animationBeginPromise, ...transitionPromises.flat(), animationEndPromise ].filter((animationPromise) => animationPromise !== undefined)); } } } componentDidMount () { const component = this; const { shade, alignment, decoration, font, indentation, color, initialAnimation, style } = component.props; const { Theme } = component.context; component.setState((prevState) => { return { context: { Theme }, adjustedStyle: readjustStyle({ shade, alignment, decoration, font, indentation, color, style }, prevState.adjustedStyle, Theme) }; }, () => { if ((typeof initialAnimation === `string` && initialAnimation !== `none`) || typeof initialAnimation === `object`) { component.animate(initialAnimation); } }); } componentWillUnMount () { const component = this; component.refCache = {}; } render () { const component = this; const { size, uppercased, lowercased, children } = component.props; const { adjustedStyle } = component.state; const { Theme } = component.context; const themedSize = size === `themed` ? Theme.text.subtitle.size : size; let contentChildren = null; if (React.Children.count(children) > 0) { contentChildren = React.Children.toArray(React.Children.map(children, (child) => { if (uppercased) { return child.toUpperCase(); } else if (lowercased) { return child.toLowerCase(); } return child; })); } return ( <AnimatedText ref = {(componentRef) => { component.refCache[`animated-text`] = componentRef; }} style = { adjustedStyle[themedSize] } ellipsizeMode = 'tail' numberOfLines = { 1 } useNativeDriver = { true } > { contentChildren } </AnimatedText> ); } }
pages/error/index.js
koistya/react-static-boilerplate
/** * React Static Boilerplate * https://github.com/kriasoft/react-static-boilerplate * * Copyright © 2015-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import history from '../../core/history'; import Link from '../../components/Link'; import s from './styles.css'; class ErrorPage extends React.Component { static propTypes = { error: React.PropTypes.object, }; componentDidMount() { document.title = this.props.error && this.props.error.status === 404 ? 'Page Not Found' : 'Error'; } goBack = event => { event.preventDefault(); history.goBack(); }; render() { if (this.props.error) console.error(this.props.error); // eslint-disable-line no-console const [code, title] = this.props.error && this.props.error.status === 404 ? ['404', 'Page not found'] : ['Error', 'Oups, something went wrong']; return ( <div className={s.container}> <main className={s.content}> <h1 className={s.code}>{code}</h1> <p className={s.title}>{title}</p> {code === '404' && <p className={s.text}> The page you're looking for does not exist or an another error occurred. </p> } <p className={s.text}> <a href="/" onClick={this.goBack}>Go back</a>, or head over to the&nbsp; <Link to="/">home page</Link> to choose a new direction. </p> </main> </div> ); } } export default ErrorPage;
src/helpers/__tests__/connectData-test.js
Justkant/WhatAShop
import { expect } from 'chai'; import React from 'react'; import { div } from 'react-dom'; import connectData from '../connectData'; describe('connectData', () => { let fetchData; let fetchDataDeferred; let WrappedComponent; let DataComponent; beforeEach(() => { fetchData = 'fetchDataFunction'; fetchDataDeferred = 'fetchDataDeferredFunction'; WrappedComponent = () => <div />; DataComponent = connectData(fetchData, fetchDataDeferred)(WrappedComponent); }); it('should set fetchData as a static property of the final component', () => { expect(DataComponent.fetchData).to.equal(fetchData); }); it('should set fetchDataDeferred as a static property of the final component', () => { expect(DataComponent.fetchDataDeferred).to.equal(fetchDataDeferred); }); });
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/StateUninitialized.js
facebook/flow
// @flow import React from 'react'; class MyComponent extends React.Component { props: Props; state: State; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} } const expression = () => class extends React.Component { props: Props; state: State; defaultProps: T; static props: T; static state: T; a: T; b = 5; c: T = 5; method() {} }
jiuzhou/RootScene.js
Cowboy1995/JZWXZ
/** * Created by Tong on 2017/5/10. */ /** * Copyright (c) 2017-present, Liu Jinyong * All rights reserved. * * https://github.com/huanxsd/MeiTuan * @flow */ //import liraries import React, { Component } from 'react'; import { Text, StyleSheet, View, TextInput, TouchableOpacity, ToastAndroid, Dimensions, Image, Button }from 'react-native'; import { StackNavigator,TabNavigator,TabBarBottom } from 'react-navigation'; import screen from './common/screen'; import color from './common/color'; import TabBarItem from './common/TabBarItem'; import Login from './page/RegisterLogin/Login'; import Register from './page/RegisterLogin/Register'; import SMSLogin from './page/RegisterLogin/SMSLogin'; import SetPassword from './page/RegisterLogin/SetPassword'; import HomeScene from './page/Home/HomeScene'; import WikiScene from './page/Wiki/WikiScene'; import MomentsScene from './page/Moments/MomentsScene'; import MineScene from './page/Mine/MineScene'; class YinDao extends Component { static navigationOptions = ({ navigation }) => ({ header:null, }); render() { const { navigate } = this.props.navigation; return ( <View> <TouchableOpacity onPress={() => navigate('Login')}> <Image source={require('./img/yindao.jpg')} style={styles.yindao} /> </TouchableOpacity> <Image source={require('./img/yindao.jpg')} style={styles.yindao} /> </View> ) } } class MyNotificationsScreen extends Component { render() { return ( <Button onPress={() => this.props.navigation.goBack()} title="Go back home" /> ); } } const styles = StyleSheet.create({ icon: { width: 26, height: 26, }, yindao: { height:screen.height, width:screen.width, }, }); const MyApp = TabNavigator({ Home: { screen: HomeScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '主页', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/pfb_tabbar_homepage@2x.png')} selectedImage={require('./img/pfb_tabbar_homepage_selected@2x.png')} /> ) }), }, Wiki: { screen: WikiScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '百科', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/pfb_tabbar_discover@2x.png')} selectedImage={require('./img/pfb_tabbar_discover_selected@2x.png')} /> ) }), }, Moments: { screen: MomentsScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '朋友圈', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/pfb_tabbar_merchant@2x.png')} selectedImage={require('./img/pfb_tabbar_merchant_selected@2x.png')} /> ) }), }, Mine: { screen: MineScene, navigationOptions: ({ navigation }) => ({ tabBarLabel: '我的', tabBarIcon: ({ focused, tintColor }) => ( <TabBarItem tintColor={tintColor} focused={focused} normalImage={require('./img/pfb_tabbar_mine@2x.png')} selectedImage={require('./img/pfb_tabbar_mine_selected@2x.png')} /> ) }), }, }, { tabBarComponent: TabBarBottom, tabBarPosition: 'bottom', swipeEnabled: true, animationEnabled: true, lazy: true, tabBarOptions: { activeTintColor: color.theme, inactiveTintColor: '#979797', style: { backgroundColor: '#ffffff' }, }, } ); const Navigator = StackNavigator( { MyApp:{ screen:MyApp }, Home:{ screen:YinDao }, Login:{ screen:Login }, Register:{ screen:Register }, SMSLogin:{ screen:SMSLogin }, SetPassword:{ screen:SetPassword }, // Tab: { screen: Tab }, }, { navigationOptions: { // headerStyle: { backgroundColor: color.theme } headerBackTitle: null, headerTintColor: '#333333', showIcon: true, }, } ); const prevGetStateForAction = Navigator.router.getStateForAction; Navigator.router.getStateForAction = (action, state) => { // Do not allow to go back from Login if (action.type === "Navigation/BACK" && state && state.routes[state.index].routeName === "Login") { return null; } if (action.type === "Navigation/BACK" && state && state.routes[state.index].routeName === "MyApp") { return null; } // Do not allow to go back to Login // if (action.type === "Navigation/BACK" && state) { // const newRoutes = state.routes.filter(r => r.routeName !== "Login"); // const newIndex = newRoutes.length - 1; // return prevGetStateForAction(action, { index: newIndex, routes: newRoutes }); // } // return prevGetStateForAction(action, state); }; //make this component available to the app export default Navigator;
modules/RouteUtils.js
littlefoot32/react-router
import React from 'react' import warning from 'warning' function isValidChild(object) { return object == null || React.isValidElement(object) } export function isReactChildren(object) { return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild)) } function checkPropTypes(componentName, propTypes, props) { componentName = componentName || 'UnknownComponent' for (var propName in propTypes) { if (propTypes.hasOwnProperty(propName)) { var error = propTypes[propName](props, propName, componentName) if (error instanceof Error) warning(false, error.message) } } } function createRoute(defaultProps, props) { return { ...defaultProps, ...props } } export function createRouteFromReactElement(element) { var type = element.type var route = createRoute(type.defaultProps, element.props) if (type.propTypes) checkPropTypes(type.displayName || type.name, type.propTypes, route) if (route.children) { var childRoutes = createRoutesFromReactChildren(route.children, route) if (childRoutes.length) route.childRoutes = childRoutes delete route.children } return route } /** * Creates and returns a routes object from the given ReactChildren. JSX * provides a convenient way to visualize how routes in the hierarchy are * nested. * * import { Route, createRoutesFromReactChildren } from 'react-router' * * var routes = createRoutesFromReactChildren( * <Route component={App}> * <Route path="home" component={Dashboard}/> * <Route path="news" component={NewsFeed}/> * </Route> * ) * * Note: This method is automatically used when you provide <Route> children * to a <Router> component. */ export function createRoutesFromReactChildren(children, parentRoute) { var routes = [] React.Children.forEach(children, function (element) { if (React.isValidElement(element)) { // Component classes may have a static create* method. if (element.type.createRouteFromReactElement) { var route = element.type.createRouteFromReactElement(element, parentRoute) if (route) routes.push(route) } else { routes.push(createRouteFromReactElement(element)) } } }) return routes } /** * Creates and returns an array of routes from the given object which * may be a JSX route, a plain object route, or an array of either. */ export function createRoutes(routes) { if (isReactChildren(routes)) { routes = createRoutesFromReactChildren(routes) } else if (!Array.isArray(routes)) { routes = [ routes ] } return routes }
react-ui/src/Navbar.js
Swoodend/pollster-heroku
import React, { Component } from 'react'; import NavbarNotLoggedIn from './NavbarNotLoggedIn'; import NavbarLoggedIn from './NavbarLoggedIn'; class Navbar extends Component { constructor(props){ super(props); this.state = { loggedIn : false } } componentWillMount(){ let user = localStorage.getItem("currentUser"); if (user){ this.setState({ loggedIn:user }); } } render(){ console.log('rendering nav', this.state); let nav = this.state.loggedIn ? <NavbarLoggedIn username={this.state.loggedIn}/> : <NavbarNotLoggedIn/> return ( <div> {nav} </div> ); } } export default Navbar;
src/components/common/icons/Open.js
WendellLiu/GoodJobShare
import React from 'react'; /* eslint-disable */ const Open = (props) => ( <svg {...props} width="148" height="148" viewBox="0 0 148 148"> <g transform="translate(41.625 46.25)"> <polygon points="27.75 0 27.75 60.125 37 60.125 37 0"/> <polygon points="62.438 25.438 2.313 25.438 2.313 34.688 62.438 34.688"/> </g> </svg> ); /* eslint-enable */ export default Open;
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch02/02_07/start/src/index.js
yevheniyc/C
import React from 'react' import { render } from 'react-dom' import { hello, goodbye } from './lib' render( <div> {hello} {goodbye} </div>, document.getElementById('react-container') )
pages/nintama.js
ybiquitous/next-todo
import React from 'react' const QUESTIONS = [ { image: 'http://www.line-tatsujin.com/stamp/outline/a00227-0.png', choices: [ '猪名寺乱太郎', '猪奈寺乱太郎', '猪名寺乱太朗', ], correct: 0, }, { image: 'http://neoapo.com/images/character/13006/a4de7d3b0dcadf1d1e9a5fd51f8fe9b5.png', choices: [ '摂子きり丸', '摂津きり丸', '説津きり丸', ], correct: 1, }, { image: 'http://neoapo.com/images/character/13007/bbd72bb531cb56e884bd53c1ae454807.png', choices: [ '福富しんべえ', '副富しんべえ', '福富しんべヱ', ], correct: 2, }, ] export default class extends React.Component { constructor(props) { super(props) this.state = { questions: QUESTIONS.map(q => ({ ...q, answered: false })), } this.handleClick = this.handleClick.bind(this) this.renderQuestion = this.renderQuestion.bind(this) } handleClick(index) { const { questions } = this.state const question = questions[index] question.answered = true this.setState({ questions }) } renderQuestion({ image, imageAlt, choices, correct, answered }, index) { return ( <div className="block" key={index}> <div> <img src={image} alt={imageAlt} /> </div> <div> {choices.map((choice, i) => ( <p key={choice} className={correct === i && 'correct'} data-answered={answered}> <input type="radio" name={`question${index}`} id={`question${index}-${i}`} /> <label htmlFor={`question${index}-${i}`}>{i + 1}. {choice}</label> </p> ))} <p> <span onClick={() => this.handleClick(index)} role="button" tabIndex="0">正解は?</span> </p> </div> <style jsx>{` .block { display: flex; font-size: 2rem; margin: 2rem 0; } img { width: 200px; } input[type="radio"] { margin: 0 2em; } [role="button"] { color: blue; } [role="button"]:hover { cursor: pointer; } strong { color: red; font-size: 1.5em; margin-left: 1em; } .correct[data-answered="true"] { border: 0.2em solid red; } `}</style> </div> ) } render() { return ( <div> {this.state.questions.map(this.renderQuestion)} </div> ) } }
react-flux-mui/js/material-ui/src/svg-icons/editor/format-quote.js
pbogdan/react-flux-mui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let EditorFormatQuote = (props) => ( <SvgIcon {...props}> <path d="M6 17h3l2-4V7H5v6h3zm8 0h3l2-4V7h-6v6h3z"/> </SvgIcon> ); EditorFormatQuote = pure(EditorFormatQuote); EditorFormatQuote.displayName = 'EditorFormatQuote'; EditorFormatQuote.muiName = 'SvgIcon'; export default EditorFormatQuote;
src/svg-icons/notification/confirmation-number.js
pomerantsev/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let NotificationConfirmationNumber = (props) => ( <SvgIcon {...props}> <path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/> </SvgIcon> ); NotificationConfirmationNumber = pure(NotificationConfirmationNumber); NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber'; NotificationConfirmationNumber.muiName = 'SvgIcon'; export default NotificationConfirmationNumber;
main.js
manojadd/bob-demo
import React from 'react'; import ReactDOM from 'react-dom'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Bob from './components/Bob.jsx'; import ProjectDetails from './components/ProjectDetails.jsx'; import {Router,Route,IndexRoute,hashHistory} from 'react-router'; import Feedback from './components/Feedback.jsx'; import Header from './components/Header.jsx'; import Login from './components/Login.jsx'; import cookie from "react-cookie"; import LayoutComponent from './components/LayoutComponent.jsx'; import {cyan500,cyan50,indigo700,grey900,grey600,white,red,fullBlack, cyan700, pinkA200,grey100, grey300, grey400, grey500, darkBlack,} from 'material-ui/styles/colors'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import {fade} from 'material-ui/utils/colorManipulator'; import muiThemeable from 'material-ui/styles/muiThemeable'; const muiTheme = getMuiTheme({ palette: { primary1Color: indigo700, primary2Color: cyan700, primary3Color: grey400, accent1Color: pinkA200, accent2Color: grey100, accent3Color: grey500, textColor: darkBlack, alternateTextColor: white, canvasColor: white, borderColor: grey300, disabledColor: fade(darkBlack, 0.3), pickerHeaderColor: cyan500, clockCircleColor: fade(darkBlack, 0.07), shadowColor: fullBlack, } }); function checkAuth(nextState,replace){ //console.log(cookie.load("Token")); if(cookie.load("Token")==undefined) { replace({ pathname: '/' }) } } function checkLoggedIn(nextState,replace){ //console.log(cookie.load("Token")); if(cookie.load("Token")!=undefined) { replace({ pathname: 'bob' }) } } ReactDOM.render( <MuiThemeProvider muiTheme={muiTheme}> <div> <Router history={hashHistory}> <Route path = '/' component={Header}> <IndexRoute component={Login} onEnter={checkLoggedIn}/> <Route path='/project' component={ProjectDetails} onEnter={checkAuth}/> <Route path='/bob' component={Bob} onEnter={checkAuth}/> <Route path='/notification' component={LayoutComponent} onEnter={checkAuth}/> <Route path='/feedback' component={Feedback}/> </Route> </Router> </div> </MuiThemeProvider>, document.getElementById('root') );
example/index.android.js
line64/react-native-checkout-mercadopago
import React from 'react'; import { AppRegistry, StyleSheet, Text, View, TouchableHighlight } from 'react-native'; import * as MercadoPago from 'react-native-checkout-mercadopago'; import env from './app.json'; export default class Example extends React.Component { state = { status: null }; handleClick = async () => { try { const payment = await MercadoPago.startCheckout(env['public_key'], env['preference_id']); this.setState({ status: JSON.stringify(payment) }); } catch (error) { this.setState({ status: error.toString() }); } }; render() { return ( <View style={styles.container}> <Text style={styles.welcome}> Welcome to React Native MercadoPago Checkout </Text> <Text style={styles.instructions}> Tap the following button to start the checkout flow </Text> <TouchableHighlight onPress={this.handleClick}> <Text style={styles.button}> CHECKOUT PRODUCT FOR $100 </Text> </TouchableHighlight> <Text> {this.state.status} </Text> </View> ); } } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#F5FCFF', }, welcome: { fontSize: 20, textAlign: 'center', margin: 10, }, button: { backgroundColor: 'blue', color: 'white', padding: 10 } }); AppRegistry.registerComponent('example', () => Example);
src/containers/app/AppBase.js
mikebarkmin/react-to-everything
import React from 'react'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import getMuiTheme from 'material-ui/styles/getMuiTheme'; import injectTapEventPlugin from 'react-tap-event-plugin'; import theme from '../../theme/theme'; import Header from '../../components/header/Header'; import Navigation from '../../components/navigation/Navigation'; injectTapEventPlugin(); const styles = { content: { maxWidth: 800, margin: '0 auto', }, }; export default class Base extends React.Component { render() { return ( <MuiThemeProvider muiTheme={getMuiTheme(theme)}> <div> <Header /> <Navigation /> <div style={styles.content}> {this.renderRoute()} </div> </div> </MuiThemeProvider> ); } } Base.propTypes = { children: React.PropTypes.element, };
client/src/containers/LandingPage/index.js
pqmcgill/stamp-wedding-app
import React, { Component } from 'react'; import { connect } from 'react-redux'; import detectWebpSupport from '../../util/detectWebpSupport'; import CompatibleImg from '../../components/CompatibleImg'; import { css } from 'aphrodite'; import { Grid, Row, Col } from 'react-flexbox-grid-aphrodite'; import styles from './styles'; import Quiz from '../Quiz'; import { startQuiz } from '../../actions/quiz'; import Paper from 'material-ui/Paper'; import smoothscroll from 'smoothscroll'; const contextTypes = { router: React.PropTypes.object }; export class App extends Component { constructor (props, context) { super(props, context); this.linkTo = this.linkTo.bind(this); } linkTo (path) { this.context.router.transitionTo(path); } render() { const parallaxStyles = detectWebpSupport() ? css(styles.parallax, styles.parallaxWebp) : css(styles.parallax, styles.parallaxJpg); return ( <div className={ css(styles.wrapper) }> <div className={ css(styles.content) }> <div className={ css(styles.antiWrapper) }> <Grid fluid> <Row center="xs"> <Col> <CompatibleImg imgName="flower1" fallback="png" className={ css(styles.flower, styles.img) } /> </Col> </Row> <Row center="xs" middle="xs"> <Col xs={12} className={ css(styles.info) + ' quicksandLight' } onClick={ this.linkTo.bind(null, '/info') } > <h2 className={ css(styles.infoHeader) + ' quicksandRegular' }>June 10, 2017 4:30pm</h2> </Col> </Row> <Row center="xs"> <Col xs={6}> <CompatibleImg imgName="flower2" fallback="png" data-aos="fade-right" data-aos-offset="300" className={ css(styles.flower, styles.flower2, styles.img) } /> </Col> </Row> </Grid> </div> </div> <div className={ parallaxStyles }> </div> <Paper zDepth={3}> <div className={ css(styles.quizWrapper) } onClick={ this.props.startQuiz }> <Grid fluid className={ css(styles.quizLink) + ' quicksandMedium' }> <Row center="xs"> <Col id="startQuiz" xs={12}> Think you know Sam and Pat? Take the quiz to find out! </Col> </Row> </Grid> </div> </Paper> <Quiz /> </div> ); } } App.contextTypes = contextTypes; const mapDispatchToProps = dispatch => { return { startQuiz() { dispatch(startQuiz()); setTimeout(() => { smoothscroll(document.getElementById('startQuiz')); }, 100); } }; }; export default connect(() => ({}), mapDispatchToProps)(App);
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ArraySpread.js
liamhu/create-react-app
/** * Copyright (c) 2015-present, Facebook, Inc. * * This source code is licensed under the MIT license found in the * LICENSE file in the root directory of this source tree. */ import React, { Component } from 'react'; import PropTypes from 'prop-types'; function load(users) { return [ { id: 1, name: '1' }, { id: 2, name: '2' }, { id: 3, name: '3' }, ...users, ]; } export default class extends Component { static propTypes = { onReady: PropTypes.func.isRequired, }; constructor(props) { super(props); this.state = { users: [] }; } async componentDidMount() { const users = load([{ id: 42, name: '42' }]); this.setState({ users }); } componentDidUpdate() { this.props.onReady(); } render() { return ( <div id="feature-array-spread"> {this.state.users.map(user => <div key={user.id}>{user.name}</div>)} </div> ); } }
examples/with-loading/pages/index.js
sedubois/next.js
import React from 'react' import Header from '../components/Header' export default () => ( <div> <Header /> <p>Hello Next!</p> </div> )
pages/index.js
jubearsun/innovative-design
import anime from 'animejs'; import React from 'react'; import classNames from 'classnames'; import DocumentTitle from 'react-document-title'; import FontAwesome from 'react-fontawesome'; import KeyHandler, { KEYDOWN } from 'react-key-handler'; import { prefixLink } from 'gatsby-helpers'; import _ from 'lodash'; import Logo, { LOGO_TEXT, LOGO_ICON } from './components/logo'; import Typing from './components/typing'; const DISPLAY_NONE = 'none'; const DISPLAY_BLOCK = 'block'; const sectionTitles = [ 'home', 'about', 'tiers', 'decals' ]; const numOfSections = sectionTitles.length; let slideAnimations = {}; let slideAnimationsOut = {}; function generateSlideAnimations(win) { slideAnimations = { slide0: [ { targets: '.splash__container', translateX: [win.innerWidth, 0], delay: 25, easing: "easeOutCirc", duration: 400 }, { targets: '.slide__button--wrapper', translateX: [-win.innerWidth, 0], delay: 50, easing: "easeOutCirc", duration: 400 } ], slide1: [ { targets: '.circle--one', scale: [0, 1], delay: 25, easing: "easeOutCirc", duration: 275 }, { targets: '.circle--two', scale: [0, 1], delay: 110, easing: "easeOutCirc", duration: 275 }, { targets: '.circle--three', scale: [0, 1], delay: 200, easing: "easeOutCirc", duration: 275 }, { targets: '.info__container--circles', translateY: [win.innerHeight, 0], delay: 200, easing: "easeOutCirc", duration: 275 } ], slide2: [ { targets: '.blue', scale: [0, 1], delay: 50, easing: "easeOutCirc", duration: 200 }, { targets: '.gold', scale: [0, 1], delay: 100, easing: "easeOutCirc", duration: 200 }, { targets: '.photo', scale: [0, 1], delay: 150, easing: "easeOutCirc", duration: 200 }, { targets: '.web', scale: [0, 1], delay: 200, easing: "easeOutCirc", duration: 200 }, { targets: '.video', scale: [0, 1], delay: 250, easing: "easeOutCirc", duration: 200 }, { targets: '.info__container--icons', translateY: [win.innerHeight, 0], delay: 200, easing: "easeOutCirc", duration: 250 } ], slide3: [ { targets: '.decal--intro', scale: [0, 1], delay: 25, easing: "easeOutCirc", duration: 275 }, { targets: '.decal--gdp', scale: [0, 1], delay: 110, easing: "easeOutCirc", duration: 275 }, { targets: '.decal--photo', scale: [0, 1], delay: 200, easing: "easeOutCirc", duration: 275 }, { targets: '.decal__container--decals', translateY: [win.innerHeight, 0], delay: 200, easing: "easeOutCirc", duration: 275 } ] }; slideAnimationsOut = { slide0: [ { targets: '.splash__container', translateX: [0, -win.innerWidth], delay: 25, easing: "linear", duration: 400 }, { targets: '.slide__button--wrapper', translateX: [0, win.innerWidth], delay: 50, easing: "linear", duration: 400 } ], slide1: [ { targets: '.circle--one', scale: [1, 0], delay: 25, easing: "linear", duration: 250 }, { targets: '.circle--two', scale: [1, 0], delay: 110, easing: "linear", duration: 250 }, { targets: '.circle--three', scale: [1, 0], delay: 200, easing: "linear", duration: 250 }, { targets: '.info__container--circles', translateY: [0, win.innerHeight], delay: 25, easing: "linear", duration: 250 } ], slide2: [ { targets: '.blue', scale: [1, 0], delay: 50, easing: "linear", duration: 200 }, { targets: '.gold', scale: [1, 0], delay: 100, easing: "linear", duration: 200 }, { targets: '.photo', scale: [1, 0], delay: 150, easing: "linear", duration: 200 }, { targets: '.web', scale: [1, 0], delay: 200, easing: "linear", duration: 200 }, { targets: '.video', scale: [1, 0], delay: 250, easing: "linear", duration: 200 }, { targets: '.decal__container--decals', translateY: [0, win.innerHeight], delay: 50, easing: "linear", duration: 250 } ], slide3: [ { targets: '.decal--intro', scale: [1, 0], delay: 25, easing: "linear", duration: 250 }, { targets: '.decal--gdp', scale: [1, 0], delay: 110, easing: "linear", duration: 250 }, { targets: '.decal--photo', scale: [1, 0], delay: 200, easing: "linear", duration: 250 }, { targets: '.info__container--circles', translateY: [0, win.innerHeight], delay: 25, easing: "linear", duration: 250 } ] }; } export default class Index extends React.Component { constructor(props) { super(props); this.state = { previousIndex: 0, slideIndex: 0 }; } componentDidMount() { if (window) { generateSlideAnimations(window); } this.refs.slide1.style.display = DISPLAY_NONE; this.refs.slide2.style.display = DISPLAY_NONE; } componentDidUpdate() { const slideInName = `slide${this.state.slideIndex}`; const slideOutName = `slide${this.state.previousIndex}`; const animations = slideAnimations[slideInName]; const outAnimations = slideAnimationsOut[slideOutName]; if (outAnimations) { for (let animation of outAnimations) { anime(animation); } } setTimeout(() => { this.refs[slideOutName].style.display = DISPLAY_NONE; this.refs[slideInName].style.display = DISPLAY_BLOCK; if (animations) { for (let animation of animations) { anime(animation); } } }, 500); } _handleKeyboardArrows(e, increment) { this._handleArrowClick(e, increment); } _handleArrowClick(e, increment) { e.preventDefault(); const currentIndex = this.state.slideIndex; const nextIndex = increment ? (currentIndex + 1) : (currentIndex - 1) this.setState({ previousIndex: currentIndex, slideIndex: nextIndex < 0 ? numOfSections - 1 : nextIndex % numOfSections }); } _handleDotsClick(e, index) { e.preventDefault(); if (index != this.state.slideIndex) { this.setState({ previousIndex: this.state.slideIndex, slideIndex: index }); } } render () { const stringsToType = [ 'Design', 'Graphic Design', 'Photography', 'Web Design', 'Videography', 'Design' ]; const navDots = _.map(sectionTitles, (title, idx) => { return ( <li key={ `dots-${idx}` } className="dot" onClick={ (e) => { this._handleDotsClick(e, idx); } } > <div className="dot__tooltip" > { title } </div> <div className={ classNames('circle', { 'circle--active': this.state.slideIndex === idx }) } > </div> </li> ); }); return ( <DocumentTitle title="Innovative Design"> <div> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowDown" onKeyHandle={(e) => { this._handleKeyboardArrows(e, true); }} /> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowUp" onKeyHandle={(e) => { this._handleKeyboardArrows(e, false); }} /> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowRight" onKeyHandle={(e) => { this._handleKeyboardArrows(e, true); }} /> <KeyHandler keyEventName={KEYDOWN} keyValue="ArrowLeft" onKeyHandle={(e) => { this._handleKeyboardArrows(e, false); }} /> <div className="page__wrapper home"> <div className="slideshow"> <div ref="slide0" className={ classNames( "slide__layout", "slide__layout--1", { "slide__layout--selected": this.state.slideIndex === 0 } ) } > <div className="splash__container"> <Logo logoType={ LOGO_TEXT } logoClass={ 'logo__svg--color' } /> <Typing defaultString="Design" strings={ stringsToType } interval={ { letter: 50, string: 500 } } backspace={ true } cursor={ '|' } startDelay={ 750 } hideCursorOnDone={ true } /> </div> <div className="slide__button--wrapper"> <div className="slide__button slide__button--1" style={{ backgroundImage: `url("${prefixLink('/img/club-one.jpg')}")` }} ></div> <a href="http://makeberkeleybeautiful.com" target="_blank"> <div className="slide__button slide__button--2"> <div className="apply__text">portfolio</div> <div className="slide__fill"></div> </div> </a> </div> </div> <div ref="slide1" style={{ display: DISPLAY_NONE }} className={ classNames( "slide__layout", "slide__layout--2", { "slide__layout--selected": this.state.slideIndex === 1 } ) } > <div className="circle__container"> <div className="circle circle--one" style={{ backgroundImage: `url("${prefixLink('/img/calday.jpg')}")` }} ></div> <div className="circle circle--two" style={{ backgroundImage: `url("${prefixLink('/img/marketing.png')}")` }} ></div> <div className="circle circle--three" style={{ backgroundImage: `url("${prefixLink('/img/flyers.png')}")` }} ></div> </div> <div className="info__container--circles"> Innovative Design is a family of graphic and web designers, photographers, and videographers at the University of California, Berkeley. We are creative individuals who are continuously evolving by collaborating, inspiring and educating one another. </div> </div> <div ref="slide2" style={{ display: DISPLAY_NONE }} className={ classNames( "slide__layout", "slide__layout--3", { "slide__layout--selected": this.state.slideIndex === 2 } ) } > <div className="icons__container"> <div className="icon blue" style={{ backgroundImage: `url("${prefixLink('/img/tiers/blue.png')}")` }} ></div> <div className="icon gold" style={{ backgroundImage: `url("${prefixLink('/img/tiers/gold.png')}")` }} ></div> <div className="icon photo" style={{ backgroundImage: `url("${prefixLink('/img/tiers/photo.png')}")` }} ></div> <div className="icon web" style={{ backgroundImage: `url("${prefixLink('/img/tiers/web.png')}")` }} ></div> <div className="icon video" style={{ backgroundImage: `url("${prefixLink('/img/tiers/video.png')}")` }} ></div> </div> <div className="info__container--icons"> <p> Innovative Design has five tiers that students can apply to be a member on: Blue, Gold, Photo, Video, and Web. </p> <p> There are two design tiers, Gold and Blue Tier. <b>Blue Tier</b> is a group of intermediate to advanced designers that offers design services to off-campus groups while <b>Gold Tier</b> offers graphic design education and experience for beginner to intermediate designers to on-campus groups. </p> <p> <b>Photo Tier</b> is a hands-on experience in shooting professional headshots, event photography, stock photos and more. </p> <p> <b>Web Tier</b> works for clients that are in need of technical help in designing their websites. Tier members learn new skills and put existing knowledge to use through hands-on experience. </p> <p> <b>Video Tier</b> creates video campaigns for clients on and off campus -- everything from logo animations, event recap videos and Kickstarter campaigns. </p> <p> Visit <b><a href="http://makeberkeleybeautiful.com" target="_blank">makeberkeleybeautiful.com</a></b> for a full portfolio. </p> </div> </div> <div ref="slide3" style={{ display: DISPLAY_NONE }} className={ classNames( "slide__layout", "slide__layout--4", { "slide__layout--selected": this.state.slideIndex === 3 } ) } > <div className="decal__container"> <div className="decal decal--intro" style={{ backgroundImage: `url("${prefixLink('/img/decal-info/intro.png')}")` }} ></div> <div className="decal decal--gdp" style={{ backgroundImage: `url("${prefixLink('/img/decal-info/gdp.png')}")` }} ></div> <div className="decal decal--photo" style={{ backgroundImage: `url("${prefixLink('/img/decal-info/photo.png')}")` }} ></div> </div> <div className="decal__container--decals"> <p> Innovative Design also teaches 3 decals separate from the club that are open to the public. You can register for these decals at the beginning of each semester at <b><a href="http://decal.berkeley.edu" target="_blank">decal.berkeley.edu</a></b>. Infosessions are mandatory, so check our <b>Events</b> tab or like us on Facebook for details and updates. </p> <p> <b>Intro to Photoshop and Illustrator</b> teaches graphic design through the use of Adobe Illustrator and Photoshop. This class is built for students who do not have any prior experience or knowledge of these programs. </p> <p> <b>Graphic Design Principles</b> is a technical course in which students are taught extensive knowledge of Adobe programs (such as Illustrator and/or Photoshop). The class also covers conceptual and theoretical aspects of design such as color theory, branding, and user interface design. </p> <p> <b>Photography Principles</b> is for students interested in learning photography. We start off with the basics (camera manipulations and shooting in RAW) and quickly move onto composition rules and tricks to get better, more thought out photos, and from there move onto how to be a professional photographer, photo ethics, and integrating art into photography. </p> <p> You can take a look at lessons and homework for each of these decals in the <b>Decal Students</b> tab above. </p> </div> </div> </div> <div className="slideshow__nav"> <div className="slideshow__dots"> <ul className="dots"> { navDots } </ul> </div> <div className="slideshow__arrows"> <div className="arrow arrow--left" onClick={(e) => { this._handleArrowClick(e, false) }} > <div className="text">back</div> <div className="arrow__triangle"></div> </div> <div className="arrow arrow--right" onClick={(e) => { this._handleArrowClick(e, true) }} > <div className="text">next</div> <div className="arrow__triangle"></div> </div> </div> </div> </div> </div> </DocumentTitle> ); } }
dva/antdmobile/test/index/index-test.js
gubaojian/trylearn
/** * @file index-test * @author anima */ import {expect, assert} from 'chai'; import React from 'react'; import dva from 'dva/mobile'; import {call, put} from 'dva/effects'; import CountModel, {delay} from '../../src/pages/index/models/model'; describe('index', () => { const app = dva(); app.model(CountModel); app.router(() => <div />); app.start(); it('init value', () => { expect(app._store.getState().amas.current).to.equal(0); }); it('reducer -- count/add', () => { app._store.dispatch({type: 'count/add'}); expect(app._store.getState().amas.current).to.equal(1); }); it('reducer -- count/minus', () => { app._store.dispatch({type: 'count/minus'}); expect(app._store.getState().amas.current).to.equal(0); }); it('effects -- count/add', () => { const generator = CountModel.effects['count/add'](); assert.deepEqual(generator.next().value, call(delay, 1000)); assert.deepEqual(generator.next().value, put({type: 'count/minus'})); assert.deepEqual(generator.next(), {done: true, value: undefined}); }); });
webapp/app/components/RestoreHistory/index.js
EIP-SAM/SAM-Solution-Server
// // Page history save // import React from 'react'; import { PageHeader } from 'react-bootstrap'; import RestoreHistoryButtons from 'containers/RestoreHistory/Buttons'; import RestoreHistoryTable from 'containers/RestoreHistory/Table'; import styles from 'components/RestoreHistory/styles.css'; /* eslint-disable react/prefer-stateless-function */ export default class RestoreHistory extends React.Component { componentDidMount() { const username = window.location.pathname.split('/')[2]; this.props.getHistoryRestoresByUserRequest(username); } render() { let username = ''; if (this.props.userIsAdmin) { username = <PageHeader className={styles.title}><small>{window.location.pathname.split('/')[2]}</small></PageHeader>; } return ( <div> <PageHeader>Restore</PageHeader> {username} <RestoreHistoryButtons /> <RestoreHistoryTable /> </div> ); } } RestoreHistory.propTypes = { userIsAdmin: React.PropTypes.bool, getHistoryRestoresByUserRequest: React.PropTypes.func, };
src/react/JSONTree/JSONArrow.js
josebalius/redux-devtools
import React from 'react'; const styles = { base: { display: 'inline-block', marginLeft: 0, marginTop: 8, marginRight: 5, 'float': 'left', transition: '150ms', WebkitTransition: '150ms', MozTransition: '150ms', borderLeft: '5px solid transparent', borderRight: '5px solid transparent', borderTopWidth: 5, borderTopStyle: 'solid', WebkitTransform: 'rotateZ(-90deg)', MozTransform: 'rotateZ(-90deg)', transform: 'rotateZ(-90deg)' }, open: { WebkitTransform: 'rotateZ(0deg)', MozTransform: 'rotateZ(0deg)', transform: 'rotateZ(0deg)' } }; export default class JSONArrow extends React.Component { render() { let style = { ...styles.base, borderTopColor: this.props.theme.base0D }; if (this.props.open) { style = { ...style, ...styles.open }; } return <div style={style} onClick={this.props.onClick}/>; } }
source/containers/App/Header/ChatButton.js
mikey1384/twin-kle
import PropTypes from 'prop-types'; import React from 'react'; import Button from 'components/Button'; import Icon from 'components/Icon'; ChatButton.propTypes = { chatMode: PropTypes.bool, loading: PropTypes.bool, numUnreads: PropTypes.number, onClick: PropTypes.func.isRequired }; export default function ChatButton({ onClick, chatMode, loading, numUnreads = 0, ...props }) { const newMessages = !chatMode && numUnreads > 0; return ( <Button {...props} transparent={!newMessages} color={newMessages ? 'gold' : 'black'} onClick={onClick} disabled={loading} > {!loading && !chatMode && <Icon icon="comments" />} {loading && <Icon icon="spinner" pulse />} <span style={{ marginLeft: chatMode ? '0.7rem' : '0.8rem' }}>Talk</span> </Button> ); }
src/Parser/Hunter/Marksmanship/Modules/Items/MKIIGyroscopicStabilizer.js
enragednuke/WoWAnalyzer
import React from 'react'; import ITEMS from 'common/ITEMS'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import Wrapper from 'common/Wrapper'; import Analyzer from 'Parser/Core/Analyzer'; import Combatants from 'Parser/Core/Modules/Combatants'; /** * Equip: Your Aimed Shot grants you gyroscopic stabilization, increasing the critical strike chance of your next Aimed Shot by 15% and making it castable while moving. */ class MKIIGyroscopicStabilizer extends Analyzer { static dependencies = { combatants: Combatants, }; usedBuffs = 0; on_initialized() { this.active = this.combatants.selected.hasHands(ITEMS.MKII_GYROSCOPIC_STABILIZER.id); } on_byPlayer_removebuff(event) { const buffId = event.ability.guid; if (buffId !== SPELLS.GYROSCOPIC_STABILIZATION.id) { return; } this.usedBuffs += 1; } item() { return { item: ITEMS.MKII_GYROSCOPIC_STABILIZER, result: <Wrapper>This allowed you to move while casting {this.usedBuffs} <SpellLink id={SPELLS.AIMED_SHOT.id} />s throughout the fight, these <SpellLink id={SPELLS.AIMED_SHOT.id} />s also had 15% increased crit chance.</Wrapper>, }; } } export default MKIIGyroscopicStabilizer;
src/svg-icons/action/assignment-returned.js
tan-jerene/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ActionAssignmentReturned = (props) => ( <SvgIcon {...props}> <path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 15l-5-5h3V9h4v4h3l-5 5z"/> </SvgIcon> ); ActionAssignmentReturned = pure(ActionAssignmentReturned); ActionAssignmentReturned.displayName = 'ActionAssignmentReturned'; ActionAssignmentReturned.muiName = 'SvgIcon'; export default ActionAssignmentReturned;
src/parser/rogue/subtlety/modules/core/NightbladeDuringSymbols.js
sMteX/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellLink from 'common/SpellLink'; import DamageTracker from 'parser/shared/modules/AbilityTracker'; import SymbolsDamageTracker from './SymbolsDamageTracker'; class NightbladeDuringSymbols extends Analyzer { static dependencies = { damageTracker: DamageTracker, symbolsDamageTracker: SymbolsDamageTracker, }; constructor(...args) { super(...args); this.symbolsDamageTracker.subscribeInefficientCast( [SPELLS.NIGHTBLADE], (s) => `Try to refresh Nightblade before Symbols of Death` ); } get thresholds() { const total = this.damageTracker.getAbility(SPELLS.NIGHTBLADE.id); const filtered = this.symbolsDamageTracker.getAbility(SPELLS.NIGHTBLADE.id); return { actual: filtered.casts, isGreaterThan: { minor: total.casts/10, average: total.casts/5, major: total.casts, }, style: 'number', }; } suggestions(when) { when(this.thresholds).isGreaterThan(0) .addSuggestion((suggest, actual, recommended) => { return suggest(<>Do not refresh <SpellLink id={SPELLS.NIGHTBLADE.id} /> during <SpellLink id={SPELLS.SYMBOLS_OF_DEATH.id} /> - cast <SpellLink id={SPELLS.EVISCERATE.id} /> instead. You can refresh <SpellLink id={SPELLS.NIGHTBLADE.id} /> early to make sure that its up for the full duration of <SpellLink id={SPELLS.SYMBOLS_OF_DEATH.id} />. </>) .icon(SPELLS.NIGHTBLADE.icon) .actual(`You refreshed Nightblade ${actual} times during Symbols of Death.`) .recommended(`${recommended} is recommended`); }); } } export default NightbladeDuringSymbols;
src/universal/modules/auth/signup/components/Signup/Signup.js
ruffers9/django-react-boilerplate
import React, { Component } from 'react'; import { Field, reduxForm } from 'redux-form'; import TextField from 'material-ui/TextField'; import RaisedButton from 'material-ui/RaisedButton'; import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'; import Paper from 'material-ui/Paper'; import { Link } from 'react-router-dom'; import '../../../styles/auth.scss'; const validate = values => { const errors = {} if (!values.username) { errors.username = 'Required'; } else if (values.username.length > 15) { errors.username = 'Must be 15 characters or less'; } if (!values.password) { errors.password = 'Required'; } else if (values.password !== values.passwordAgain) { errors.password = 'Passwords do not match'; } if (!values.passwordAgain) { errors.passwordAgain = 'Required'; } return errors } const renderField = ({ input, label, type, meta: { touched, error } }) => ( <TextField {...input} floatingLabelText={label} errorText={touched && error ? error : null} type={type} /> ); const renderAsyncError = statusText => { if (statusText) { return ( <div className="asyncError">{statusText}</div> ); } }; const Signup = props => { const { handleSubmit, pristine, submitting, username, password, statusText } = props; return ( <MuiThemeProvider> <div> <Paper className="formContainer"> <h4 className="form-banner">Signup</h4> <form className="form" onSubmit={e => handleSubmit(e, username, password)}> {renderAsyncError(statusText)} <Field name="username" type="text" component={renderField} label="Username"/> <Field name="password" type="password" component={renderField} label="Password"/> <Field name="passwordAgain" type="password" component={renderField} label="Password (Again)"/> <RaisedButton className="formButton" type="submit" primary={true} label="Submit" disabled={pristine || submitting} /> </form> </Paper> <p className="help-text">Already have an account? <Link to='/login'>Login</Link></p> </div> </MuiThemeProvider> ); } // Decorate the form component export default reduxForm({ form: 'signup', // a unique name for this form validate })(Signup);
packages/react-router-website/modules/components/Logo.js
justjavac/react-router-CN
import React from 'react' import { Block, Row } from 'jsxstyle' import { DARK_GRAY } from '../Theme' import LogoImage from '../logo.png' const Logo = ({ size = 230, shadow = true }) => ( <Row background={DARK_GRAY} width={size+'px'} height={size+'px'} alignItems="center" justifyContent="center" borderRadius="50%" boxShadow={shadow ? `2px ${size/20}px ${size/5}px hsla(0, 0%, 0%, 0.35)` : null} > <Block position="relative" top="-4%" textAlign="center" width="100%"> <img src={LogoImage} width="75%"/> </Block> </Row> ) export default Logo
examples/todomvc/config/react.js
lore/lore
/** * Configuration file for React * * This file is where you define overrides for the default mounting behavior. */ // import React from 'react'; // import ReactDOM from 'react-dom'; // import { Provider } from 'react-redux'; // import { Router } from 'react-router'; export default { /** * ID of DOM Element the application will be mounted to */ // domElementId: 'root', /** * Generate the root component that will be mounted to the DOM. This * function will be invoked by lore after all hooks have been loaded. */ // getRootComponent: function(lore) { // const store = lore.store; // const routes = lore.router.routes; // const history = lore.router.history; // // return ( // <Provider store={store}> // <Router history={history}> // {routes} // </Router> // </Provider> // ); // }, /** * Mount the root component to the DOM */ // mount: function(Root, lore) { // const config = lore.config.react; // ReactDOM.render(Root, document.getElementById(config.domElementId), cb); // } }
src/routes/home/index.js
quasicrial/quasicrial
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-2016 Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Home from './Home'; import fetch from '../../core/fetch'; import Layout from '../../components/Layout'; export default { path: '/', async action() { const resp = await fetch('/graphql', { method: 'post', headers: { Accept: 'application/json', 'Content-Type': 'application/json', }, body: JSON.stringify({ query: '{news{title,link,publishedDate,contentSnippet}}', }), credentials: 'include', }); const { data } = await resp.json(); if (!data || !data.news) throw new Error('Failed to load the news feed.'); return { title: 'React Starter Kit', component: <Layout><Home news={data.news} /></Layout>, }; }, };
www/app/components/main_panel/email_section.js
kalikaneko/bitmask-dev
import React from 'react' //import { Button, Glyphicon, Alert } from 'react-bootstrap' import SectionLayout from './section_layout' import Account from 'models/account' import Spinner from 'components/spinner' import bitmask from 'lib/bitmask' export default class EmailSection extends React.Component { static get defaultProps() {return{ account: null }} constructor(props) { super(props) this.state = { status: null } this.openKeys = this.openKeys.bind(this) this.openApp = this.openApp.bind(this) this.openPrefs = this.openPrefs.bind(this) console.log('email constructor') } openKeys() {} openApp() {} openPrefs() {} render () { //let message = null //if (this.state.error) { // // style may be: success, warning, danger, info // message = ( // <Alert bsStyle="danger">{this.state.error}</Alert> // ) //} let button = null if (this.state.status == 'ready') { button = <Button onClick={this.openApp}>Open Email</Button> } return ( <SectionLayout icon="envelope" status="on" button={button}> <h1>inbox: </h1> </SectionLayout> ) } }
src/components/common/AsyncElement.js
ajkhatibi/wheevy
import React from 'react'; import Router from 'react-router'; import { Route, RouteHandler, Link } from 'react-router'; var AsyncElement = { loadedComponent: null, load: function () { if (this.constructor.loadedComponent) {return;} this.bundle((component) => { this.constructor.loadedComponent = component; this.forceUpdate(); }); }, componentDidMount: function () { setTimeout(this.load, 1000); }, render: function () { var Component = this.constructor.loadedComponent; if (Component) { // can't find RouteHandler in the loaded component, so we just grab // it here first. this.props.activeRoute = <RouteHandler/>; return <Component {...this.props}/>; } return this.preRender(); } }; export default AsyncElement;
src/containers/GameOfLifePage.js
svitekpavel/Conway-s-Game-of-Life
import React from 'react'; import { connect } from 'react-redux'; import GameOfLife from '../components/GameOfLife'; import { setEpoch, setSpeed, setEvolutionRunning, } from '../actions/gameOfLifeActions'; import getNextEpoch from '../utils/getNextEpoch'; import createGrid from '../utils/createGrid'; import gridInsertPattern from '../utils/gridInsertPattern'; class GameOfLifePage extends React.Component { constructor(props) { super(props); this.handleStartEvolution = this.handleStartEvolution.bind(this); this.handleStopEvolution = this.handleStopEvolution.bind(this); this.handleChangeSpeed = this.handleChangeSpeed.bind(this); this.handlePatternInsert = this.handlePatternInsert.bind(this); this.handleInsertBeacon = this.handlePatternInsert.bind(this, 'beacon'); this.handleInsertGlider = this.handlePatternInsert.bind(this, 'glider'); this.handleInsertLwss = this.handlePatternInsert.bind(this, 'lwss'); } componentDidMount() { const { dispatch } = this.props; // create grid and insert some nice patterns let epoch = createGrid(38, 30); // add simple glider and one Lightweight spaceship (LWSS) epoch = gridInsertPattern('glider', epoch, 15, 7); epoch = gridInsertPattern('lwss', epoch, 0, 5); // add static blocks to top rows to expose colors [0, 3, 6, 9, 12, 15, 18, 21, 24, 27, 30, 33, 36].map((i) => { epoch = gridInsertPattern('block', epoch, i, 0); }); // add nice blinkers to the bottom of the grid [0, 4, 8, 12, 16, 20, 24, 28, 32].map((i) => { epoch = gridInsertPattern('blinker2', epoch, i+1, 20); }); // add nice beacons to the very bottom of the grid [0, 6, 12, 18, 24, 30].map((i) => { epoch = gridInsertPattern('beacon', epoch, i+2, 26); }); dispatch(setEpoch(epoch)); } componentWillUnmount() { clearInterval(this.evolutionInterval); } calculateNextEpoch() { const { dispatch, speed, } = this.props; setTimeout(() => { const { evolutionRunning, epoch, } = this.props; const nextEpoch = getNextEpoch(epoch); dispatch(setEpoch(nextEpoch)); if (evolutionRunning) { this.calculateNextEpoch(); } }, speed); } handlePatternInsert(patterName, x, y) { const { epoch, dispatch, } = this.props; const nextEpoch = gridInsertPattern(patterName, epoch, x, y); dispatch(setEpoch(nextEpoch)); } handleStartEvolution() { // start the evolution here const { dispatch } = this.props; dispatch(setEvolutionRunning(true)); this.calculateNextEpoch(); } handleStopEvolution() { const { dispatch } = this.props; dispatch(setEvolutionRunning(false)); clearInterval(this.evolutionInterval); } handleChangeSpeed(event) { const { dispatch } = this.props; const { value } = event.target; dispatch(setSpeed(value)); // restart interval } render() { return ( <GameOfLife epoch={this.props.epoch} speed={this.props.speed} evolutionRunning={this.props.evolutionRunning} onStartEvolution={this.handleStartEvolution} onStopEvolution={this.handleStopEvolution} onChangeSpeed={this.handleChangeSpeed} onGridClick={this.handlePatternInsert} onInsertBeacon={this.handleInsertBeacon} onInsertGlider={this.handleInsertGlider} onInsertLwss={this.handleInsertLwss} /> ); } } GameOfLifePage.propTypes = { epoch: React.PropTypes.array.isRequired, evolutionRunning: React.PropTypes.bool.isRequired, dispatch: React.PropTypes.func.isRequired, }; function mapStateToProps(state) { return { epoch: state.gameOfLife.epoch, evolutionRunning: state.gameOfLife.evolutionRunning, speed: state.gameOfLife.speed, }; } function mapDispatchToProps(dispatch) { return { dispatch: dispatch, }; } export default connect( mapStateToProps, mapDispatchToProps )(GameOfLifePage);
src/component/event-form/index.js
vagabond0079/casehawk-frontend
import React from 'react'; import * as util from '../../lib/util.js'; import './event-form.scss'; class EventForm extends React.Component { constructor(props){ super(props); this.state = props.event ? {...props.event} : {title: '', allDay: false, start: '', end: '', eventType: null, tag: '', notify: false}; this.handleChange = this.handleChange.bind(this); this.handleSubmit = this.handleSubmit.bind(this); } componentWillReceiveProps(props){ if(props.event) this.setState(props.event); } handleChange(e){ let {type, name, value} = e.target; type === 'checkbox' ? e.target.checked === false ? this.setState({[name]: false}) : this.setState({[name]: true}) : type === 'datetime-local' ? this.setState({[name]: new Date(value)}) : this.setState({[name]: value}); } handleSubmit(e){ e.preventDefault(); this.props.onComplete(this.state); } render(){ return ( <form className='event-form' onSubmit={this.handleSubmit} > <p> <label htmlFor='start-date-time'> Start Date/Time: </label> <input type='datetime-local' id='start-date-time' name='start' onInput={this.handleChange} /> </p> <p> <label htmlFor='end-date-time'> End Date/Time: </label> <input type='datetime-local' id='end-date-time' name='end' onInput={this.handleChange} /> </p> <p> <input placeholder='Title' type='text' name='title' onChange={this.handleChange} value={this.state.name} /> </p> <p> <label htmlFor='allday'> All Day: </label> <input type='checkbox' id='allday' name='allDay' onChange={this.handleChange} /> </p> <select defaultValue="---" id='event-type' name='eventType' onChange={this.handleChange} > <option value="---"> --- </option> <option value="appointment"> Appointment </option> <option value="court-date"> Court Date </option> <option value="deadline"> Deadline </option> <option value="task"> Task </option> </select> <p> <label htmlFor='notify'> Notify: </label> <input type='checkbox' id='notify' name='notify' onChange={this.handleChange} /> </p> <input placeholder='tags' type='text' name='tag' onChange={this.handleChange} /> <p> <button type='submit'> {this.props.buttonText} </button> </p> </form> ); } } export default EventForm;
actor-apps/app-web/src/app/components/Main.react.js
hejunbinlan/actor-platform
import React from 'react'; import requireAuth from 'utils/require-auth'; import VisibilityActionCreators from '../actions/VisibilityActionCreators'; import FaviconActionCreators from 'actions/FaviconActionCreators'; import FaviconStore from 'stores/FaviconStore'; import ActivitySection from 'components/ActivitySection.react'; import SidebarSection from 'components/SidebarSection.react'; import ToolbarSection from 'components/ToolbarSection.react'; import DialogSection from 'components/DialogSection.react'; import Favicon from 'components/common/Favicon.react'; //import AppCacheStore from 'stores/AppCacheStore'; //import AppCacheUpdateModal from 'components/modals/AppCacheUpdate.react'; const visibilitychange = 'visibilitychange'; const onVisibilityChange = () => { if (!document.hidden) { VisibilityActionCreators.createAppVisible(); FaviconActionCreators.setDefaultFavicon(); } else { VisibilityActionCreators.createAppHidden(); } }; const getStateFromStores = () => { return { faviconPath: FaviconStore.getFaviconPath() }; }; class Main extends React.Component { constructor(props) { super(props); this.state = getStateFromStores(); document.addEventListener(visibilitychange, onVisibilityChange); FaviconStore.addChangeListener(this.onChange); if (!document.hidden) { VisibilityActionCreators.createAppVisible(); } } onChange = () => { this.setState(getStateFromStores()); } render() { //let appCacheUpdateModal; //if (this.state.isAppUpdateModalOpen) { // appCacheUpdateModal = <AppCacheUpdateModal/>; //} return ( <div className="app row"> <Favicon path={this.state.faviconPath}/> <SidebarSection/> <section className="main col-xs"> <ToolbarSection/> <DialogSection/> </section> <ActivitySection/> {/*appCacheUpdateModal*/} </div> ); } } export default requireAuth(Main);
fields/types/datearray/DateArrayFilter.js
joerter/keystone
import React from 'react'; import ReactDOM from 'react-dom'; import moment from 'moment'; import DayPicker from 'react-day-picker'; import { FormField, FormInput, FormRow, FormSelect } from 'elemental'; const PRESENCE_OPTIONS = [ { label: 'At least one element', value: 'some' }, { label: 'No element', value: 'none' }, ]; const MODE_OPTIONS = [ { label: 'On', value: 'on' }, { label: 'After', value: 'after' }, { label: 'Before', value: 'before' }, { label: 'Between', value: 'between' }, ]; var DayPickerIndicator = React.createClass({ render () { return ( <span className="DayPicker-Indicator"> <span className="DayPicker-Indicator__border" /> <span className="DayPicker-Indicator__bg" /> </span> ); }, }); function getDefaultValue () { return { mode: MODE_OPTIONS[0].value, presence: PRESENCE_OPTIONS[0].value, value: moment(0, 'HH').format(), before: moment(0, 'HH').format(), after: moment(0, 'HH').format(), }; } var DateFilter = React.createClass({ displayName: 'DateFilter', propTypes: { filter: React.PropTypes.shape({ mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)), presence: React.PropTypes.string, }), }, statics: { getDefaultValue: getDefaultValue, }, getDefaultProps () { return { format: 'DD-MM-YYYY', filter: getDefaultValue(), value: moment().startOf('day').toDate(), }; }, getInitialState () { return { activeInputField: 'after', month: new Date(), // The month to display in the calendar }; }, componentDidMount () { // focus the text input if (this.props.filter.mode === 'between') { ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus(); } else { ReactDOM.findDOMNode(this.refs.input).focus(); } }, updateFilter (value) { this.props.onChange({ ...this.props.filter, ...value }); }, selectPresence (presence) { this.updateFilter({ presence }); ReactDOM.findDOMNode(this.refs.input).focus(); }, selectMode (mode) { this.updateFilter({ mode }); if (mode === 'between') { setTimeout(() => { ReactDOM.findDOMNode(this.refs[this.state.activeInputField]).focus(); }, 200); } else { ReactDOM.findDOMNode(this.refs.input).focus(); } }, handleInputChange (e) { const { value } = e.target; let { month } = this.state; // Change the current month only if the value entered by the user is a valid // date, according to the `L` format if (moment(value, 'L', true).isValid()) { month = moment(value, 'L').toDate(); } this.updateFilter({ value: value }); this.setState({ month }, this.showCurrentDate); }, setActiveField (field) { this.setState({ activeInputField: field, }); }, switchBetweenActiveInputFields (e, day, modifiers) { if (modifiers.indexOf('disabled') > -1) return; const { activeInputField } = this.state; const send = {}; send[activeInputField] = day; this.updateFilter(send); const newActiveField = (activeInputField === 'before') ? 'after' : 'before'; this.setState( { activeInputField: newActiveField }, () => { ReactDOM.findDOMNode(this.refs[newActiveField]).focus(); } ); }, selectDay (e, day, modifiers) { if (modifiers.indexOf('disabled') > -1) return; this.updateFilter({ value: day }); }, showCurrentDate () { this.refs.daypicker.showMonth(this.state.month); }, renderControls () { let controls; const { field, filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const placeholder = field.label + ' is ' + mode.label.toLowerCase() + '...'; // DayPicker stuff const modifiers = { selected: (day) => moment(filter.value).isSame(day), }; if (mode.value === 'between') { controls = ( <div> <FormRow> <FormField width="one-half"> <FormInput ref="after" placeholder="From" onFocus={(e) => { this.setActiveField('after'); }} value={moment(filter.after).format(this.props.format)} /> </FormField> <FormField width="one-half"> <FormInput ref="before" placeholder="To" onFocus={(e) => { this.setActiveField('before'); }} value={moment(filter.before).format(this.props.format)} /> </FormField> </FormRow> <div style={{ position: 'relative' }}> <DayPicker modifiers={modifiers} className="DayPicker--chrome" onDayClick={this.switchBetweenActiveInputFields} /> <DayPickerIndicator /> </div> </div> ); } else { controls = ( <div> <FormField> <FormInput ref="input" placeholder={placeholder} value={moment(filter.value).format(this.props.format)} onChange={this.handleInputChange} onFocus={this.showCurrentDate} /> </FormField> <div style={{ position: 'relative' }}> <DayPicker ref="daypicker" modifiers={modifiers} className="DayPicker--chrome" onDayClick={this.selectDay} /> <DayPickerIndicator /> </div> </div> ); } return controls; }, render () { const { filter } = this.props; const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0]; const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0]; return ( <div> <FormSelect options={PRESENCE_OPTIONS} onChange={this.selectPresence} value={presence.value} /> <FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={mode.value} /> {this.renderControls()} </div> ); }, }); module.exports = DateFilter;
src/components/Contentful/Event/presenter.js
ndlib/usurper
// Presenter component for a Event content type from Contentful import React from 'react' import PropTypes from 'prop-types' import typy from 'typy' import 'static/css/global.css' import LibMarkdown from 'components/LibMarkdown' import Link from 'components/Interactive/Link' import Related from '../Related' import Image from 'components/Image' import Librarians from 'components/Librarians' import PageTitle from 'components/Layout/PageTitle' import SearchProgramaticSet from 'components/SearchProgramaticSet' import ServicePoint from '../ServicePoint' import ShareLinks from 'components/Interactive/ShareLinks' import EmailSubscribeBox from 'components/Interactive/EmailSubscribeBox' import OpenGraph from 'components/OpenGraph' import Canonical from 'components/Canonical' import Media from 'components/Media' import RecurringIndicator from './RecurringIndicator' import Presenters from '../../Presenters' import Sponsorships from '../../Sponsorships' import AddToCalendar from 'components/Interactive/AddToCalendar' import InternalLink from '../InternalLink' import PageLink from '../PageLink' import styles from './style.module.css' const PagePresenter = ({ entry }) => { let body = entry.content if (entry.audience) { body += `\n\nOpen to ${typy(entry.audience).safeArray.join(', ')}.` } return ( <article className='container-fluid content-area' itemScope itemType='http://schema.org/Event' itemProp='mainEntity' > {entry.shortDescription && (<meta itemProp='about' content={entry.shortDescription} />)} <meta itemProp='startDate' content={entry.startDate} /> <meta itemProp='endDate' content={entry.endDate} /> <Canonical /> <PageTitle title={entry.title} itemProp='name' /> <OpenGraph title={entry.title} description={entry.shortDescription} image={entry.representationalImage} /> <SearchProgramaticSet open={false} /> <div className='row'> <main className='col-md-8 article'> <div className='event-info'> <div className='event-details'> <div className='event-detail-date' aria-label='Date'> {entry.displayDate} <RecurringIndicator entry={entry} inline /> </div> <div className='event-detail-time' aria-label='Time'> <LibMarkdown>{entry.displayTime}</LibMarkdown> </div> { entry.locationText && ( <div className='event-detail-location' aria-label='Location' itemScope itemType='http://schema.org/Place' itemProp='location' > <LibMarkdown itemProp='address'>{entry.locationText}</LibMarkdown> </div> ) } </div> <div className='event-buttons'> <ShareLinks title={entry.title} /> <AddToCalendar title={entry.title} description={entry.shortDescription} location={entry.locationText} startDate={entry.startDate} endDate={entry.endDate} /> </div> </div> <LibMarkdown itemProp='description'>{body}</LibMarkdown> <Related className='p-resources' title='Resources' showImages={false}>{entry.relatedResources}</Related> <Sponsorships sponsors={entry.sponsors} /> {typy(entry, 'group.eventGroupType').safeString === 'series' && ( <div className={styles.seriesDescription}> <LibMarkdown>{entry.group.eventGroupDescription}</LibMarkdown> <Link to={`/events/series/${entry.group.id}`}>View all events in this series.</Link> </div> )} <Presenters presenters={typy(entry, 'presenters').safeArray} /> </main> <aside className='col-md-4 right'> <Image cfImage={entry.representationalImage} className='cover' itemProp='image' /> <Link to={entry.registrationUrl} className='button callout' hideIfNull>Register for this event</Link> {typy(entry.callOutLinks).safeArray.map(link => link.sys.contentType.sys.id === 'internalLink' ? ( <InternalLink key={link.sys.id} className='button callout' cfEntry={link} /> ) : ( <PageLink key={link.sys.id} className='button callout' cfPage={link} /> ))} <Media data={entry.media} /> <Librarians netids={entry.contactPeople} /> <ServicePoint cfServicePoint={entry.location} showDetails={false} /> <Related className='p-pages' title='Related Pages' showImages={false}>{entry.relatedPages}</Related> <EmailSubscribeBox type='events' htag={2} /> </aside> </div> <Link to='/events' className='viewAllEvents' arrow>View All Library Events</Link> </article> ) } PagePresenter.propTypes = { entry: PropTypes.object.isRequired, } export default PagePresenter
src/components/usershow/UseritemComponent.js
WishTreeGroup/wishtree_web
'use strict'; import React from 'react'; require('styles/usershow/Useritem.sass'); class UseritemComponent extends React.Component { render() { return ( <div className="useritem-component"> <span>{this.props.itemname}</span>{this.props.itemvalue} </div> ); } } UseritemComponent.displayName = 'UsershowUseritemComponent'; // Uncomment properties you need // UseritemComponent.propTypes = {}; // UseritemComponent.defaultProps = {}; export default UseritemComponent;
web/src/client/createRoutes.js
vampolo/react-experiments
import App from './app/app.react'; import Home from './pages/home.react'; import Login from './pages/auth.react'; import Me from './pages/me.react'; import NotFound from './pages/notFound.react'; import React from 'react'; import Todos from './pages/todos.react'; import Sysdig from './pages/sysdig.react'; import {IndexRoute, Route} from 'react-router'; export default function createRoutes(getState) { function requireAuth(nextState, replaceState) { const loggedIn = getState().users.viewer; if (!loggedIn) { replaceState({nextPathname: nextState.location.pathname}, '/login'); } } return ( <Route component={App} path="/"> <IndexRoute component={Home} /> <Route component={Login} path="login" /> <Route component={Me} onEnter={requireAuth} path="me" /> <Route component={Todos} path="todos" /> <Route component={Sysdig} path="sysdig" /> <Route component={NotFound} path="*" /> </Route> ); }
src/index.js
ldstudio-ca/react-pdfjs-mobile
import React from 'react'; import ReactDOM from 'react-dom'; import App from './App'; export default App; // let root = document.getElementById('root'); // ReactDOM.render(<App url="../how-to-setup.pdf" // onClose={ () => { // ReactDOM.unmountComponentAtNode(root); // } } />, root);
src/Parser/Hunter/Survival/Modules/Talents/SteelTrap.js
hasseboulen/WoWAnalyzer
import React from 'react'; import SPELLS from 'common/SPELLS'; import Analyzer from 'Parser/Core/Analyzer'; import SpellIcon from 'common/SpellIcon'; import Combatants from 'Parser/Core/Modules/Combatants'; import SpellUsable from 'Parser/Core/Modules/SpellUsable'; import SpellLink from 'common/SpellLink'; import ItemDamageDone from 'Main/ItemDamageDone'; class SteelTrap extends Analyzer { static dependencies = { combatants: Combatants, spellUsable: SpellUsable, }; bonusDamage = 0; casts = 0; on_initialized() { this.active = this.combatants.selected.hasTalent(SPELLS.STEEL_TRAP_TALENT.id); } on_byPlayer_cast(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.STEEL_TRAP_TALENT.id) { return; } this.casts++; } on_byPlayer_damage(event) { const spellId = event.ability.guid; if (spellId !== SPELLS.STEEL_TRAP_DEBUFF.id) { return; } if (this.casts === 0) { this.casts++; this.spellUsable.beginCooldown(SPELLS.STEEL_TRAP_TALENT.id); } this.bonusDamage += event.amount + (event.absorbed || 0); } subStatistic() { return ( <div className="flex"> <div className="flex-main"> <SpellLink id={SPELLS.STEEL_TRAP_TALENT.id}> <SpellIcon id={SPELLS.STEEL_TRAP_TALENT.id} noLink /> Steel Trap </SpellLink> </div> <div className="flex-sub text-right"> <ItemDamageDone amount={this.bonusDamage} /> </div> </div> ); } } export default SteelTrap;
Realization/frontend/czechidm-core/src/components/advanced/Filter/FilterToogleButton.js
bcvsolutions/CzechIdMng
import React from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; // import AbstractContextComponent from '../../basic/AbstractContextComponent/AbstractContextComponent'; import * as Basic from '../../basic'; import * as Domain from '../../../domain'; import { DataManager, IdentityManager } from '../../../redux'; // const dataManager = new DataManager(); const identityManager = new IdentityManager(); /** * Button for closable filter mainly for advanced table. * * @author Radek Tomiška */ class FilterToogleButton extends AbstractContextComponent { constructor(props, context) { super(props, context); // this.state = { filterOpened: this.props.filterOpened }; } _filterOpen(opened) { const { filterOpen, uiKey, userContext } = this.props; // this.setState({ filterOpened: opened }, () => { if (uiKey) { if (opened) { this.context.store.dispatch(dataManager.expandFilter(uiKey)); if (userContext && userContext.username) { this.context.store.dispatch(identityManager.expandPanel(userContext.username, uiKey)); } } else { this.context.store.dispatch(dataManager.collapseFilter(uiKey)); if (userContext && userContext.username) { this.context.store.dispatch(identityManager.collapsePanel(userContext.username, uiKey)); } } } if (filterOpen) { filterOpen(opened); } }); } render() { const { rendered, showLoading, searchParameters, forceSearchParameters, ...others } = this.props; const { filterOpened } = this.state; if (!rendered) { return null; } let level = 'default'; let tooltip = this.i18n('component.advanced.Table.filter.empty'); if (!Domain.SearchParameters.isEmptyFilter(searchParameters, forceSearchParameters)) { level = 'info'; tooltip = this.i18n('component.advanced.Table.filter.notEmpty'); } // return ( <Basic.Tooltip value={tooltip}> <span> <Basic.Button level={ level } buttonSize="xs" onClick={ this._filterOpen.bind(this, !filterOpened) } showLoading={ showLoading } icon="filter" endIcon={ <Basic.Icon value={ !filterOpened ? 'triangle-bottom' : 'triangle-top' } style={{ fontSize: '0.8em' }}/> } text={ this.i18n('button.filter.toogle') } { ...others }/> </span> </Basic.Tooltip> ); } } FilterToogleButton.propTypes = { ...Basic.AbstractContextComponent.propTypes, /** * Callback, when filter is opened * @type {function} function(bool) */ filterOpen: PropTypes.func, /** * Filter is opened * @type {bool} */ filterOpened: PropTypes.bool, /** * Used search parameters in redux * * @type {SearchParameters} */ searchParameters: PropTypes.object, /** * "Hard filters" * * @type {SearchParameters} */ forceSearchParameters: PropTypes.object, }; FilterToogleButton.defaultProps = { ...Basic.AbstractContextComponent.defaultProps }; function select(state) { return { userContext: state.security.userContext }; } export default connect(select)(FilterToogleButton);
src/decorators/withViewport.js
cheshire137/cheevo-plotter
/** * 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;
test/fixtures/builds-with-multiple-runtimes/src/index.js
mangomint/create-react-app
import React from 'react'; import dva from 'dva'; import createHistory from 'history/createHashHistory'; import ky from 'ky'; const app = dva({ history: createHistory() }); app.router(() => { ky.get('https://canihazip.com/s') .then(r => r.text()) .then(console.log, console.error) .then(() => console.log('ok')); return <div>Test</div>; }); app.start('#root');
site/demos/earthquake-reporter/src/index.js
appbaseio/reactivesearch
import React from 'react'; import ReactDOM from 'react-dom'; import { ReactiveBase, SelectedFilters, RangeSlider, DynamicRangeSlider, SingleList, } from '@appbaseio/reactivesearch'; import { ReactiveGoogleMap, ReactiveOpenStreetMap } from '@appbaseio/reactivemaps'; import Dropdown from '@appbaseio/reactivesearch/lib/components/shared/Dropdown'; import './index.css'; const providers = [ { label: 'Google Map', value: 'googleMap', }, { label: 'OpenStreet Map', value: 'openstreetMap', }, ]; class App extends React.Component { constructor() { super(); this.state = { mapProvider: providers[0], }; this.setProvider = this.setProvider.bind(this); } setProvider(mapProvider) { this.setState({ mapProvider, }); } render() { const mapProps = { dataField: 'location', defaultMapStyle: 'Light Monochrome', title: 'Reactive Maps', defaultZoom: 3, size: 50, react: { and: ['magnitude-filter', 'year-filter', 'places'], }, onPopoverClick: item => <div>{item.place}</div>, showMapStyles: true, renderItem: result => ({ custom: ( <div style={{ background: 'dodgerblue', color: '#fff', paddingLeft: 5, paddingRight: 5, borderRadius: 3, padding: 10, }} > <i className="fas fa-globe-europe" /> &nbsp;{result.magnitude} </div> ), }), }; return ( <ReactiveBase app="earthquakes" url="https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io" enableAppbase mapKey="AIzaSyA9JzjtHeXg_C_hh_GdTBdLxREWdj3nsOU" > <div className="container"> <div className="filters-container"> {' '} <h1>Earthquakes Reporter</h1> <SelectedFilters /> <hr /> <SingleList title="Filter By Places" componentId="places" dataField="place.keyword" size={50} showSearch /> <hr /> <RangeSlider title="Filter By Magnitude" componentId="magnitude-filter" dataField="magnitude" range={{ start: 1, end: 10, }} rangeLabels={{ start: '1', end: '10', }} tooltipTrigger="hover" /> <hr /> <DynamicRangeSlider title="Filter By Year" componentId="year-filter" dataField="time" queryFormat="date" rangeLabels={(min, max) => ({ start: new Date(min).toISOString().substring(0, 10), end: new Date(max).toISOString().substring(0, 10), })} /> </div> <div className="maps-container"> <div style={{ marginTop: '10px' }}> {' '} <div style={{ position: 'relative', zIndex: 9999999, marginBottom: '1rem', }} > <div style={{ marginTop: '20px', marginBottom: '5px', fontSize: '1 rem', }} > <b>Select Map Provider</b> </div> <Dropdown items={providers} onChange={this.setProvider} selectedItem={this.state.mapProvider} keyField="label" returnsObject /> </div> <hr /> {this.state.mapProvider.value === 'googleMap' ? ( <ReactiveGoogleMap style={{ height: '90vh' }} componentId="googleMap" {...mapProps} /> ) : ( <ReactiveOpenStreetMap style={{ height: '90vh' }} componentId="openstreetMap" {...mapProps} /> )} </div> </div> </div> </ReactiveBase> ); } } ReactDOM.render(<App />, document.getElementById('root'));
src/components/extensions/overview/blocks/cost.js
vFujin/HearthLounge
import React from 'react'; import PropTypes from 'prop-types'; const Cost = ({extensionCost}) => { const PriceTableRows = ({price}) => { return ( <tr> <th>{price.desc}</th> <td>{price.gold}</td> <td>{price.usd}</td> <td>{price.eur}</td> <td>{price.gbp}</td> </tr> ) }; const CostTable = ({cost}) => { return ( <table> <thead> <tr> <th>Wing</th> <th>Gold</th> <th>USD</th> <th>EUR</th> <th>GBP</th> </tr> </thead> <tbody> {cost.map((price, i) => <PriceTableRows key={i} price={price}/>)} </tbody> </table> ) }; return ( <div className="cost inner-container"> <CostTable cost={extensionCost}/> </div> ); }; export default Cost; Cost.propTypes = { extensionCost: PropTypes.array.isRequired };
src/RegionSelect.js
casavi/react-region-select
import React, { Component } from 'react'; import { PropTypes } from 'prop-types'; import objectAssign from 'object-assign'; import Region from './Region'; import style from './style'; class RegionSelect extends Component { constructor (props) { super(props); this.onComponentMouseTouchDown = this.onComponentMouseTouchDown.bind(this); this.onDocMouseTouchMove = this.onDocMouseTouchMove.bind(this); this.onDocMouseTouchEnd = this.onDocMouseTouchEnd.bind(this); this.onRegionMoveStart = this.onRegionMoveStart.bind(this); this.regionCounter = 0; } componentDidMount() { document.addEventListener('mousemove', this.onDocMouseTouchMove); document.addEventListener('touchmove', this.onDocMouseTouchMove); document.addEventListener('mouseup', this.onDocMouseTouchEnd); document.addEventListener('touchend', this.onDocMouseTouchEnd); document.addEventListener('touchcancel', this.onDocMouseTouchEnd); } componentWillUnmount() { document.removeEventListener('mousemove', this.onDocMouseTouchMove); document.removeEventListener('touchmove', this.onDocMouseTouchMove); document.removeEventListener('mouseup', this.onDocMouseTouchEnd); document.removeEventListener('touchend', this.onDocMouseTouchEnd); document.removeEventListener('touchcancel', this.onDocMouseTouchEnd); } getClientPos(e) { let pageX, pageY; if (e.touches) { pageX = e.touches[0].pageX; pageY = e.touches[0].pageY; } else { pageX = e.pageX; pageY = e.pageY; } return { x: pageX, y: pageY }; } onDocMouseTouchMove (event) { if (!this.isChanging) { return; } const index = this.regionChangeIndex; const updatingRegion = this.props.regions[index]; const clientPos = this.getClientPos(event); const regionChangeData = this.regionChangeData; let x, y, width, height; if (!regionChangeData.isMove) { let x1Pc, y1Pc, x2Pc, y2Pc; x1Pc = (regionChangeData.clientPosXStart - regionChangeData.imageOffsetLeft) / regionChangeData.imageWidth * 100; y1Pc = (regionChangeData.clientPosYStart - regionChangeData.imageOffsetTop) / regionChangeData.imageHeight * 100; x2Pc = (clientPos.x - regionChangeData.imageOffsetLeft) / regionChangeData.imageWidth * 100; y2Pc = (clientPos.y - regionChangeData.imageOffsetTop) / regionChangeData.imageHeight * 100; x = Math.min(x1Pc, x2Pc); y = Math.min(y1Pc, y2Pc); width = Math.abs(x1Pc - x2Pc); height = Math.abs(y1Pc - y2Pc); if(this.props.constraint){ if (x2Pc >= 100) { x = x1Pc; width = 100 - x1Pc; } if (y2Pc >= 100) { y = y1Pc; height = 100 - y1Pc; } if (x2Pc <= 0) { x = 0; width = x1Pc; } if (y2Pc <= 0) { y = 0; height = y1Pc; } } } else { x = (clientPos.x + regionChangeData.clientPosXOffset - regionChangeData.imageOffsetLeft) / regionChangeData.imageWidth * 100; y = (clientPos.y + regionChangeData.clientPosYOffset - regionChangeData.imageOffsetTop) / regionChangeData.imageHeight * 100; width = updatingRegion.width; height = updatingRegion.height; if(this.props.constraint){ if (x + width >= 100) { x = Math.round(100 - width); } if (y + height >= 100) { y = Math.round(100 - height); } if (x <= 0) { x = 0; } if (y <= 0) { y = 0; } } } const rect = { x: x, y: y, width: width, height: height, isChanging: true }; this.props.onChange([ ...this.props.regions.slice(0, index), objectAssign({}, updatingRegion, rect), ...this.props.regions.slice(index + 1) ]); } onDocMouseTouchEnd () { if (this.isChanging) { this.isChanging = false; const index = this.regionChangeIndex; const updatingRegion = this.props.regions[index]; const changes = { new: false, isChanging: false }; this.regionChangeIndex = null; this.regionChangeData = null; this.props.onChange([ ...this.props.regions.slice(0, index), objectAssign({}, updatingRegion, changes), ...this.props.regions.slice(index + 1) ]); } } onComponentMouseTouchDown (event) { if (event.target.dataset.wrapper || event.target.dataset.dir || isSubElement(event.target, (el) => el.dataset && el.dataset.wrapper)) { return; } event.preventDefault(); const clientPos = this.getClientPos(event); const imageOffset = this.getElementOffset(this.refs.image); const xPc = (clientPos.x - imageOffset.left) / this.refs.image.offsetWidth * 100; const yPc = (clientPos.y - imageOffset.top) / this.refs.image.offsetHeight * 100; this.isChanging = true; const rect = { x: xPc, y: yPc, width: 0, height: 0, new: true, data: { index: this.regionCounter }, isChanging: true }; this.regionCounter += 1; this.regionChangeData = { imageOffsetLeft: imageOffset.left, imageOffsetTop: imageOffset.top, clientPosXStart: clientPos.x, clientPosYStart: clientPos.y, imageWidth: this.refs.image.offsetWidth, imageHeight: this.refs.image.offsetHeight, isMove: false }; if (this.props.regions.length < this.props.maxRegions) { this.props.onChange(this.props.regions.concat(rect)); this.regionChangeIndex = this.props.regions.length; } else { this.props.onChange([ ...this.props.regions.slice(0, this.props.maxRegions - 1), rect ]); this.regionChangeIndex = this.props.maxRegions - 1; } } getElementOffset (el) { const rect = el.getBoundingClientRect(); const docEl = document.documentElement; const rectTop = rect.top + window.pageYOffset - docEl.clientTop; const rectLeft = rect.left + window.pageXOffset - docEl.clientLeft; return { top: rectTop, left: rectLeft }; } onRegionMoveStart (event, index) { if (!event.target.dataset.wrapper && !event.target.dataset.dir) { return; } event.preventDefault(); const clientPos = this.getClientPos(event); const imageOffset = this.getElementOffset(this.refs.image); let clientPosXStart, clientPosYStart; const currentRegion = this.props.regions[index]; const regionLeft = (currentRegion.x / 100 * this.refs.image.offsetWidth) + imageOffset.left; const regionTop = (currentRegion.y / 100 * this.refs.image.offsetHeight) + imageOffset.top; const regionWidth = (currentRegion.width / 100 * this.refs.image.offsetWidth); const regionHeight = (currentRegion.height / 100 * this.refs.image.offsetHeight); const clientPosDiffX = regionLeft - clientPos.x; const clientPosDiffY = regionTop - clientPos.y; const resizeDir = event.target.dataset.dir; if (resizeDir) { if (resizeDir === 'se') { clientPosXStart = regionLeft; clientPosYStart = regionTop; } else if (resizeDir === 'sw') { clientPosXStart = regionLeft + regionWidth; clientPosYStart = regionTop; } else if (resizeDir === 'nw') { clientPosXStart = regionLeft + regionWidth; clientPosYStart = regionTop + regionHeight; } else if (resizeDir === 'ne') { clientPosXStart = regionLeft; clientPosYStart = regionTop + regionHeight; } } else { clientPosXStart = clientPos.x; clientPosYStart = clientPos.y; } this.isChanging = true; this.regionChangeData = { imageOffsetLeft: imageOffset.left, imageOffsetTop: imageOffset.top, clientPosXStart: clientPosXStart, clientPosYStart: clientPosYStart, clientPosXOffset: clientPosDiffX, clientPosYOffset: clientPosDiffY, imageWidth: this.refs.image.offsetWidth, imageHeight: this.refs.image.offsetHeight, isMove: resizeDir ? false : true, resizeDir: resizeDir }; this.regionChangeIndex = index; } renderRect (rect, index) { return <Region x={rect.x} y={rect.y} width={rect.width} height={rect.height} handles={!rect.new} data={rect.data} key={index} index={index} customStyle={this.props.regionStyle} dataRenderer={this.props.regionRenderer} onCropStart={(event) => this.onRegionMoveStart(event, index)} changing={index === this.regionChangeIndex} />; } render () { const regions = this.props.regions; return ( <div ref='image' style={objectAssign({}, style.RegionSelect, this.props.style)} className={this.props.className} onTouchStart={this.onComponentMouseTouchDown} onMouseDown={this.onComponentMouseTouchDown}> {regions.map(this.renderRect.bind(this))} {this.props.debug ? <table style={{position:'absolute', right: 0, top: 0}}> <tbody> {regions.map((rect, index) => { return ( <tr key={index}> <td>x: {Math.round(rect.x, 1)}</td> <td>y: {Math.round(rect.y, 1)}</td> <td>width: {Math.round(rect.width, 1)}</td> <td>height: {Math.round(rect.height, 1)}</td> </tr> ); })} </tbody> </table> : null } {this.props.children} </div> ); } } RegionSelect.propTypes = { constraint: PropTypes.bool, regions: PropTypes.array, children: PropTypes.any, onChange: PropTypes.func.isRequired, regionRenderer: PropTypes.func, maxRegions: PropTypes.number, debug: PropTypes.bool, className: PropTypes.string, style: PropTypes.object, regionStyle: PropTypes.object }; RegionSelect.defaultProps = { maxRegions: Infinity, debug: false, regions: [], constraint: false }; function isSubElement (el, check) { if (el === null) { return false; } else if (check(el)) { return true; } else { return isSubElement(el.parentNode, check); } } // support both es6 modules and common js module.exports = RegionSelect; module.exports.default = RegionSelect;
client/modules/DangTin/DangTinPages.js
tranphong001/BIGVN
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import { Modal, Button } from 'react-bootstrap'; import { getCategories, getCities, getDistricts, getWards, getId } from '../App/AppReducer'; import { fetchDistricts, fetchWards, addDistricts, addWards, setNotify } from '../App/AppActions'; import { postNews, uploadImage } from './DangTinActions'; import CKEditor from 'react-ckeditor-component'; import styles from '../../main.css'; import 'react-image-crop/dist/ReactCrop.css'; import {Cropper} from 'react-image-cropper' import numeral from 'numeral'; class DangTinPages extends Component { constructor(props) { super(props); this.state = { category: '', city: 'none', district: 'none', ward: 'none', address: '', title: '', price: '', content: '', name: '', phone: '', addressContact: '', check: false, images: [], imagesBase64: [], isCrop: false, cropSrc: '', thumbnail: 0, thumbnailTemp: 0, isAction: false, isSubmitting: false, }; } componentWillMount() { if (this.props.id === '') { this.context.router.push('/'); } } isNumeric = (n) => { return !isNaN(parseFloat(n)) && isFinite(n); }; updateContent = (newContent) => { this.setState({ content: newContent }); }; onChange = (evt) => { const newContent = evt.editor.getData(); this.setState({ content: newContent }); }; selectCategory = (event) => { this.setState({ category: event.target.value }); }; selectCity = (event) => { this.setState({ city: event.target.value }); if (event.target.value !== 'none') { this.props.dispatch(fetchDistricts(event.target.value)); } else { this.setState({ district: 'none', ward: 'none' }); this.props.dispatch(addDistricts([])); this.props.dispatch(addWards([])); } }; selectDistrict = (event) => { this.setState({ district: event.target.value }); if (event.target.value !== 'none') { this.props.dispatch(fetchWards(event.target.value)); } else { this.setState({ ward: 'none' }); this.props.dispatch(addWards([])); } }; selectWard = (event) => { this.setState({ ward: event.target.value }); }; handleAddress = (eventKey) => { this.setState({ address: eventKey.target.value }); }; handleTitle = (eventKey) => { this.setState({ title: eventKey.target.value }); }; handlePrice = (eventKey) => { if (this.isNumeric(eventKey.target.value.trim().replace(/,/g, ''))) { this.setState({ price: eventKey.target.value.trim().replace(/,/g, '') }); } else { this.setState({ price: '' }); } }; handleName = (eventKey) => { this.setState({ name: eventKey.target.value }); }; handlePhone = (eventKey) => { this.setState({ phone: eventKey.target.value.trim()}); }; handleAddressContact = (eventKey) => { this.setState({ addressContact: eventKey.target.value }); }; handleCheck = () => { this.setState({ check: !this.state.check }); }; submit = () => { if (this.state.check) { if (this.state.imagesBase64.length === 0) { this.props.dispatch(setNotify('Bạn phải upload ít nhất một hình')); return; } if (this.state.category.trim() === '') { this.props.dispatch(setNotify('Vui lòng chọn danh mục')); return; } if (this.state.price.trim() === '') { this.props.dispatch(setNotify('Vui lòng nhập giá')); return; } if (this.state.city.trim() === '') { this.props.dispatch(setNotify('Vui lòng chọn Tỉnh/Thành')); return; } if (this.state.district.trim() === '') { this.props.dispatch(setNotify('Vui lòng chọn Quận/Huyện')); return; } if (this.state.ward.trim() === '') { this.props.dispatch(setNotify('Vui lòng chọn Phường/Xã')); return; } if (this.state.address.trim() === '') { this.props.dispatch(setNotify('Vui lòng nhập địa chỉ')); return; } if (this.state.title.trim() === '') { this.props.dispatch(setNotify('Vui lòng nhập tiêu đề tin rao vặt')); return; } if (this.state.content.trim() === '') { this.props.dispatch(setNotify('Vui lòng nhập nội dung tin rao vặt')); return; } if (this.state.name.trim() === '') { this.props.dispatch(setNotify('Vui lòng nhập tên liên lạc')); return; } if (this.state.phone.trim() === '') { this.props.dispatch(setNotify('Vui lòng nhập số điện thoại liên lạc')); return; } if (this.state.addressContact.trim() === '') { this.props.dispatch(setNotify('Vui lòng nhập địa chỉ liên lạc')); return; } const news = { category: this.state.category, userId: this.props.id, city: this.state.city, district: this.state.district, ward: this.state.ward, type: 'news', address: this.state.address, keywords: [], title: this.state.title, price: this.state.price, content: this.state.content, check: this.state.check, imagesBase64: this.state.imagesBase64, thumbnail: this.state.thumbnail, contact: { name: this.state.name, phone: this.state.phone, address: this.state.addressContact, }, }; this.setState({ isSubmitting: true }); this.props.dispatch(postNews(news)).then((res) => { console.log(res); this.setState({ isSubmitting: false }); if (res.news === 'success') { this.context.router.push('/'); this.props.dispatch(setNotify('Tin đang được chờ phê duyệt!')); } else { this.props.dispatch(setNotify('Tin đã bị cấm đăng')); } }); } else { this.props.dispatch(setNotify('Bạn chưa cam đoán thông tin của tin rao!')); } }; onCrop = (e) => { e.preventDefault(); const reader = new FileReader(); const file = e.target.files[0]; let base64image = null; reader.onload = (readerEvt) => { base64image = readerEvt.target.result; }; reader.onloadend = () => { this.setState({ cropSrc: base64image, isCrop: true }); }; reader.readAsDataURL(file); }; hideCrop = () => { this.setState({ isCrop: false }); }; saveCrop = () => { this.setState({ imagesBase64: [...this.state.imagesBase64, this.refs.cropper.crop()], isCrop: false }); }; onAction = (index) => { this.setState({ isAction: true, thumbnailTemp: index }); }; onHideAction = () => { this.setState({ isAction: false }); }; pickThumbnail = () => { this.setState({ thumbnail: this.state.thumbnailTemp, isAction: false }); }; deleteUploadImage = () => { if (this.state.thumbnailTemp >= this.state.thumbnail) { this.setState({ imagesBase64: this.state.imagesBase64.filter((image, index) => index != this.state.thumbnailTemp), isAction: false, thumbnail: 0 }); } else { this.setState({ imagesBase64: this.state.imagesBase64.filter((image, index) => index != this.state.thumbnailTemp), isAction: false }); } }; render() { return ( <div> <div className="panel panel-default col-md-8 col-md-offset-2 col-sm-8 col-sm-offset-2"> <div className="col-md-10 col-md-offset-1"> <div className={styles.registerTitle}> <p className={styles.postNews}>ĐĂNG TIN</p> <div className="form-horizontal"> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Chọn danh mục</label> <div className="col-sm-9"> <select className="input-large form-control" onChange={this.selectCategory}> <option value="none" style={{ fontSize: '11pt' }}>Chọn danh mục</option> { this.props.categories.map((cate, index) => ( <option key={`${index}Cate`} value={cate._id} style={{ fontSize: '11pt' }}>{cate.title}</option> )) } </select> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Tỉnh thành</label> <div className="col-sm-9"> <select className="input-large form-control" onChange={this.selectCity}> <option value="none" style={{ fontSize: '11pt' }}>Chọn tỉnh thành</option> { this.props.cities.map((city, index) => ( <option key={`${index}City`} value={city._id} style={{ fontSize: '11pt' }}>{city.name}</option> )) } </select> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Quận/Huyện</label> <div className="col-sm-9"> <select className="input-large form-control" onChange={this.selectDistrict}> <option value="none"> { (this.state.city === 'none') ? 'Vui lòng chọn tỉnh thành' : this.props.districts.length > 0 ? 'Chọn Quận/Huyện' : 'Đang tải' } </option> { this.props.districts.map((district, index) => ( <option key={`${index}District`} value={district._id} style={{ fontSize: '11pt' }}>{district.name}</option> )) } </select> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Phường/Xã</label> <div className="col-sm-9"> <select className="input-large form-control" onChange={this.selectWard}> <option value="none"> { (this.state.district === 'none') ? 'Vui lòng chọn Quận/Huyện' : this.props.wards.length > 0 ? 'Chọn Phường/Xã' : 'Đang tải' } </option> { this.props.wards.map((ward, index) => ( <option key={`${index}Ward`} value={ward._id} style={{ fontSize: '11pt' }}>{ward.name}</option> )) } </select> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Địa chỉ</label> <div className="col-sm-9"> <input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.address} onChange={this.handleAddress} /> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Tiêu đề</label> <div className="col-sm-9"> <input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.title} onChange={this.handleTitle} maxLength="200" /> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Giá (VNĐ)</label> <div className="col-sm-9"> <input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} onChange={this.handlePrice} /> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}> Nội dung<br /><p style={{ color: 'rgb(204, 204, 204)', fontSize: '10pt', fontStyle: 'italic', paddingTop: '16px' }}>(Tối đa 2000 kí tự)</p> </label> <div className="col-sm-9"> <CKEditor activeClass={`p10 ${styles.customCKeditor}`} content={this.state.content} events={{ change: this.onChange, blur: () => {}, afterPaste: () => {} }} /> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Hình ảnh</label> <div className="col-sm-9"> <div style={{ overflow: 'auto' }}> { this.state.imagesBase64.map((r, index) => { if (this.state.thumbnail === index) { return ( <div key={`${index}Newser`} className={styles.containerImages}> <a onClick={() => this.onAction(index)}> <div style={{ position: 'relative' }}> <img width={100} height={75} src={r}/> <div style={{ position: 'absolute', width: '100%', height: '100%', top: '0', left: '0', border: '3px solid rgb(243, 146, 31)', borderRadius: '3px' }}> <div style={{ display: 'table', verticalAlign: 'middle', textAlign: 'center',width: '100%', height: '100%' }}> <span style={{ display: 'table-cell', verticalAlign: 'middle' }}> Hình nền </span> </div> </div> </div> </a> </div> ) } else { return ( <div key={`${index}Newser`} className={styles.containerImages}> <a onClick={() => this.onAction(index)}> <img width={100} height={75} src={r}/> </a> </div> ) } }) } { (this.state.imagesBase64.length < 5) ? ( <div className={styles.containerImages}> <label htmlFor="file-upload" className={styles.customUpload}> <i className="fa fa-cloud-upload" style={{ color: '#03a9f4' }} /> Tải hình ảnh </label> <input id="file-upload" accept="image/jpeg, image/png" type="file" style={{ display: 'none' }} onChange={this.onCrop} /> </div> ) : '' } </div> <div><p style={{ fontSize: '10pt', color: '#ccc', textAlign: 'left', paddingTop: '10px', fontStyle: 'italic' }}>(Số lượng hình tối đa 5 hình, kích thước hình uu tiên là 960x720px)</p></div> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Tên liên hệ</label> <div className="col-sm-9"> <input className="form-control"type="text" style={{ fontSize: '11pt' }} value={this.state.name} onChange={this.handleName} /> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Số điện thoại</label> <div className="col-sm-9"> <input className="form-control" type="text" style={{ fontSize: '11pt' }} value={this.state.phone} onChange={this.handlePhone} /> </div> </div> <div className="form-group"> <label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Địa chỉ</label> <div className="col-sm-9"> <input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.addressContact} onChange={this.handleAddressContact} /> </div> </div> <div className="form-group"> <div className="col-md-3"></div> <div className="col-sm-9" style={{ textAlign: 'left', fontSize: '11pt' }}> <label> <input type="checkbox" checked={this.state.check} onChange={this.handleCheck} className={styles.marginRight10} /> <span style={{ paddingLeft: '5px', fontSize: '10pt' }}>Cam đoan tính xác thực của tin rao này</span> </label> </div> </div> <div className="form-group"> <div className="col-md-3"></div> <div className="col-sm-9"> <button onClick={this.submit} className={styles.submitNews} disabled={this.state.isSubmitting} style={{ fontSize: '11pt', fontWeight: 'bold' }} > {this.state.isSubmitting ? 'ĐANG GỬI' : 'ĐĂNG TIN'} </button> </div> </div> </div> </div> </div> <Modal show={this.state.isCrop} onHide={this.hideCrop} backdrop="static" > <Modal.Header closeButton> <Modal.Title>Cắt hình</Modal.Title> </Modal.Header> <Modal.Body> <Cropper src={this.state.cropSrc} ref="cropper" ratio={4/3} /> </Modal.Body> <Modal.Footer> <Button onClick={this.saveCrop}>Chọn</Button> <Button onClick={this.hideCrop}>Thoát</Button> </Modal.Footer> </Modal> <Modal show={this.state.isAction} onHide={this.onHideAction} backdrop="static" > <Modal.Header closeButton> <Modal.Title>Thao tác</Modal.Title> </Modal.Header> <Modal.Body> Xóa ảnh hoặc chọn ảnh làm hình nền </Modal.Body> <Modal.Footer> <Button onClick={this.onHideAction}>Thoát</Button> <Button onClick={this.deleteUploadImage}>Xóa</Button> <Button onClick={this.pickThumbnail}>Chọn làm hình nền</Button> </Modal.Footer> </Modal> </div> </div> ); } } // Retrieve data from store as props function mapStateToProps(state) { return { categories: getCategories(state), cities: getCities(state), districts: getDistricts(state), wards: getWards(state), id: getId(state), }; } DangTinPages.propTypes = { dispatch: PropTypes.func.isRequired, id: PropTypes.string.isRequired, categories: PropTypes.array.isRequired, cities: PropTypes.array.isRequired, districts: PropTypes.array.isRequired, wards: PropTypes.array.isRequired, }; DangTinPages.contextTypes = { router: PropTypes.object, }; export default connect(mapStateToProps)(DangTinPages);
src/svg-icons/image/navigate-before.js
hwo411/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageNavigateBefore = (props) => ( <SvgIcon {...props}> <path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/> </SvgIcon> ); ImageNavigateBefore = pure(ImageNavigateBefore); ImageNavigateBefore.displayName = 'ImageNavigateBefore'; ImageNavigateBefore.muiName = 'SvgIcon'; export default ImageNavigateBefore;
src/client.js
derek-duncan/challenge
'use strict'; import Iso from 'iso'; import Router from 'react-router'; import React from 'react'; import createBrowserHistory from 'history/lib/createBrowserHistory' import reactRoutes from './routes/client'; import alt from './alt'; Iso.bootstrap((state, _, container) => { alt.bootstrap(state); let history = createBrowserHistory() React.render(<Router history={history}>{reactRoutes}</Router>, container); });
example/src/screens/types/tabs/TabOne.js
luggit/react-native-navigation
import React from 'react'; import { StyleSheet, View, Text, Dimensions, Button } from 'react-native'; class TabOne extends React.Component { render() { return ( <View> <Text>Tab One</Text> </View> ); } } export default TabOne;
docs/src/NotFoundPage.js
Firfi/meteor-react-bootstrap
import React from 'react'; import NavMain from './NavMain'; import PageHeader from './PageHeader'; import PageFooter from './PageFooter'; const NotFoundPage = React.createClass({ render() { return ( <div> <NavMain activePage='' /> <PageHeader title='404' subTitle='Hmmm this is awkward.' /> <PageFooter /> </div> ); } }); export default NotFoundPage;
node_modules/react-router/es6/Link.js
sharonjean/React-Netflix
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; } import React from 'react'; import warning from './routerWarning'; import invariant from 'invariant'; import { routerShape } from './PropTypes'; var _React$PropTypes = React.PropTypes; var bool = _React$PropTypes.bool; var object = _React$PropTypes.object; var string = _React$PropTypes.string; var func = _React$PropTypes.func; var oneOfType = _React$PropTypes.oneOfType; function isLeftClickEvent(event) { return event.button === 0; } function isModifiedEvent(event) { return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey); } // TODO: De-duplicate against hasAnyProperties in createTransitionManager. function isEmptyObject(object) { for (var p in object) { if (Object.prototype.hasOwnProperty.call(object, p)) return false; }return true; } function createLocationDescriptor(to, _ref) { var query = _ref.query; var hash = _ref.hash; var state = _ref.state; if (query || hash || state) { return { pathname: to, query: query, hash: hash, state: state }; } return to; } /** * A <Link> is used to create an <a> element that links to a route. * When that route is active, the link gets the value of its * activeClassName prop. * * For example, assuming you have the following route: * * <Route path="/posts/:postID" component={Post} /> * * You could use the following component to link to that route: * * <Link to={`/posts/${post.id}`} /> * * Links may pass along location state and/or query string parameters * in the state/query props, respectively. * * <Link ... query={{ show: true }} state={{ the: 'state' }} /> */ var Link = React.createClass({ displayName: 'Link', contextTypes: { router: routerShape }, propTypes: { to: oneOfType([string, object]).isRequired, query: object, hash: string, state: object, activeStyle: object, activeClassName: string, onlyActiveOnIndex: bool.isRequired, onClick: func, target: string }, getDefaultProps: function getDefaultProps() { return { onlyActiveOnIndex: false, style: {} }; }, handleClick: function handleClick(event) { if (this.props.onClick) this.props.onClick(event); if (event.defaultPrevented) return; !this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0; if (isModifiedEvent(event) || !isLeftClickEvent(event)) return; // If target prop is set (e.g. to "_blank"), let browser handle link. /* istanbul ignore if: untestable with Karma */ if (this.props.target) return; event.preventDefault(); var _props = this.props; var to = _props.to; var query = _props.query; var hash = _props.hash; var state = _props.state; var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); this.context.router.push(location); }, render: function render() { var _props2 = this.props; var to = _props2.to; var query = _props2.query; var hash = _props2.hash; var state = _props2.state; var activeClassName = _props2.activeClassName; var activeStyle = _props2.activeStyle; var onlyActiveOnIndex = _props2.onlyActiveOnIndex; var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']); process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0; // Ignore if rendered outside the context of router, simplifies unit testing. var router = this.context.router; if (router) { var location = createLocationDescriptor(to, { query: query, hash: hash, state: state }); props.href = router.createHref(location); if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) { if (router.isActive(location, onlyActiveOnIndex)) { if (activeClassName) { if (props.className) { props.className += ' ' + activeClassName; } else { props.className = activeClassName; } } if (activeStyle) props.style = _extends({}, props.style, activeStyle); } } } return React.createElement('a', _extends({}, props, { onClick: this.handleClick })); } }); export default Link;
src/back-office/components/Logo.js
mihailgaberov/es6-bingo-game
import React from 'react'; class Logo extends React.Component { render() { return <div id="logo" />; } } export default Logo;
__tests__/index.android.js
king-smith/collector-alpha
import 'react-native'; import React from 'react'; import Index from '../index.android.js'; // Note: test renderer must be required after react-native. import renderer from 'react-test-renderer'; it('renders correctly', () => { const tree = renderer.create( <Index /> ); });
client/src/transforms/FormAction/ownerAwareUnpublish.js
open-sausages/silverstripe-asset-admin
/* global confirm */ import React from 'react'; import i18n from 'i18n'; const ownerAwareUnpublish = (FormAction) => (props) => { const originalOnclick = props.onClick; const newProps = { ...props, onClick(e, nameOrID) { const { owners } = props.data; let message = null; if (owners && parseInt(owners, 10) > 0) { message = [ i18n.inject( i18n._t( 'AssetAdmin.SINGLE_OWNED_WARNING_1', 'This file is being used in {count} other published section(s).', ), { count: owners } ), i18n._t( 'AssetAdmin.SINGLE_OWNED_WARNING_2', 'Ensure files are removed from content areas prior to unpublishing them. Otherwise, they will appear as broken links.' ), i18n._t( 'AssetAdmin.SINGLE_OWNED_WARNING_3', 'Do you want to unpublish this file anyway?' ) ].join('\n\n'); } else { message = i18n._t('AssetAdmin.CONFIRMUNPUBLISH', 'Are you sure you want to unpublish this record?'); } // eslint-disable-next-line no-alert if (confirm(message)) { originalOnclick(e, nameOrID); } else { e.preventDefault(); } } }; return <FormAction {...newProps} />; }; export default ownerAwareUnpublish;
app/components/UGFooterSitemap/index.js
perry-ugroop/ugroop-react-dup2
import React from 'react'; import messages from './messages'; import { FormattedMessage } from 'react-intl'; import { Grid, Row, Col, FormGroup } from 'react-bootstrap'; import UGFooterSitemap from './UGFooterSitemap'; import UGFooterBtn from './UGFooterBtn'; import UGFooterH3 from './UGFooterH3'; import UGFooterULWithIcon from './UGFooterULWithIcon'; import UGFooterULDefault from './UGFooterULDefault'; import FollowUsList from './FollowUsList'; import CustomerServiceList from './CustomerServiceList'; import AboutUsList from './AboutUsList'; import UGFooterInput from './UGFooterInput'; function FooterSiteMap() { return ( <UGFooterSitemap> <Grid> <Row> <Col md={3} sm={6}> <UGFooterH3>Follow Us:</UGFooterH3> <UGFooterULWithIcon> {FollowUsList} </UGFooterULWithIcon> </Col> <Col md={3} sm={6}> <UGFooterH3>About Us</UGFooterH3> <UGFooterULDefault> {AboutUsList} </UGFooterULDefault> </Col> <Col md={3} sm={6}> <UGFooterH3>Customer Service</UGFooterH3> <UGFooterULDefault> {CustomerServiceList} </UGFooterULDefault> </Col> <Col md={3} sm={6}> <UGFooterH3> Promotion &amp; offers</UGFooterH3> <p><FormattedMessage {...messages.promotionMessage} /></p> <form> <FormGroup> <UGFooterInput type="text" id="fc-name" placeholder="Name" /> </FormGroup> <FormGroup> <UGFooterInput type="email" id="fc-email" placeholder="Email" /> </FormGroup> <UGFooterBtn>Submit</UGFooterBtn> </form> </Col> </Row> </Grid> </UGFooterSitemap> ); } export default FooterSiteMap;
src/lib/reactors/Showcase/ItemThumbnail.js
EsriJapan/photospot-finder
// Copyright (c) 2016 Yusuke Nunokawa (https://ynunokawa.github.io) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. import React from 'react'; import { Thumbnail } from 'react-bootstrap'; class ItemThumbnail extends React.Component { constructor (props) { super(props); this._onClickThumbnail = this._onClickThumbnail.bind(this); this._onMouseoverThumbnail = this._onMouseoverThumbnail.bind(this); this._onMouseoutThumbnail = this._onMouseoutThumbnail.bind(this); } _onClickThumbnail () { const coordinates = [this.props.feature.geometry.coordinates[1], this.props.feature.geometry.coordinates[0]]; this.props.onClickThumbnail(coordinates, 15); } _onMouseoverThumbnail () { const feature = this.props.feature; this.props.onMouseoverThumbnail(feature); } _onMouseoutThumbnail () { this.props.onMouseoutThumbnail(null); } render () { const feature = this.props.feature; const layoutFields = this.props.layoutFields; let imageUrl = feature.properties[layoutFields.image]; const name = feature.properties[layoutFields.name]; const description = feature.properties[layoutFields.description]; if (layoutFields.imageUrlPrefix !== undefined && layoutFields.imageUrlPrefix !== '') { imageUrl = layoutFields.imageUrlPrefix + imageUrl; } return ( <Thumbnail src={imageUrl} onClick={this._onClickThumbnail} onMouseOver={this._onMouseoverThumbnail} onMouseOut={this._onMouseoutThumbnail} className="react-webmap-item-thumbnail" > <h3>{name}</h3> <p>{description}</p> </Thumbnail> ); } } ItemThumbnail.propTypes = { feature: React.PropTypes.any, layoutFields: React.PropTypes.object, onClickThumbnail: React.PropTypes.func, onMouseoverThumbnail: React.PropTypes.func, onMouseoutThumbnail: React.PropTypes.func }; ItemThumbnail.displayName = 'ItemThumbnail'; export default ItemThumbnail;
src/containers/entitysetforms/CreateEntitySet.js
kryptnostic/gallery
import React from 'react'; import Immutable, { List } from 'immutable'; import PropTypes from 'prop-types'; import Select from 'react-select'; import styled from 'styled-components'; import { FormControl, FormGroup, ControlLabel, Button, Alert } from 'react-bootstrap'; import { connect } from 'react-redux'; import { bindActionCreators } from 'redux'; import StyledCheckbox from '../../components/controls/StyledCheckbox'; import AsyncContent, { AsyncStatePropType } from '../../components/asynccontent/AsyncContent'; import { fetchAllEntityTypesRequest } from '../edm/EdmActionFactory'; import { createEntitySetRequest } from './CreateEntitySetActionFactories'; import { fetchWritableOrganizations } from '../organizations/actions/OrganizationsActionFactory'; const ENTITY_SET_TYPES = { ENTITY_SET: 'Entity Set', LINKED_ENTITY_SET: 'Linked Entity Set' }; const PERSON_TYPE_FQN = 'general.person'; const SubmitButton = styled(Button)` margin-top: 10px; `; const FormGroupMarginTop = styled(FormGroup)` margin-top: 10px; `; class CreateEntitySet extends React.Component { static propTypes = { actions: PropTypes.shape({ onCreateEntitySet: PropTypes.func.isRequired, fetchAllEntityTypesRequest: PropTypes.func.isRequired, fetchWritableOrganizations: PropTypes.func.isRequired }).isRequired, createEntitySetAsyncState: AsyncStatePropType.isRequired, defaultContact: PropTypes.string, entityTypes: PropTypes.instanceOf(Immutable.Map).isRequired, entitySets: PropTypes.instanceOf(Immutable.Map).isRequired, isAdmin: PropTypes.bool.isRequired, personEntityTypeId: PropTypes.string.isRequired, writableOrganizations: PropTypes.instanceOf(Immutable.List).isRequired }; constructor(props) { super(props); this.state = { type: ENTITY_SET_TYPES.ENTITY_SET, title: '', description: '', name: '', contact: props.defaultContact, entityTypeId: null, organizationId: null, entitySetIds: [], external: true }; } componentDidMount() { this.props.actions.fetchAllEntityTypesRequest(); this.props.actions.fetchWritableOrganizations(); } onTypeChange = (option) => { const entityTypeId = (option.value === ENTITY_SET_TYPES.LINKED_ENTITY_SET) ? this.props.personEntityTypeId : null; this.setState({ type: option.value, entityTypeId, entitySetIds: [] }); } onTitleChange = (event) => { this.setState({ title: event.target.value }); }; onNameChange = (event) => { this.setState({ name: event.target.value }); }; onDescriptionChange = (event) => { this.setState({ description: event.target.value }); }; onContactChange = (event) => { this.setState({ contact: event.target.value }); } onEntityTypeChange = (option) => { const entityTypeId = (option) ? option.value : null; this.setState({ entityTypeId }); }; onOrganizationChange = (option) => { const organizationId = (option) ? option.value : null; this.setState({ organizationId }); }; onEntitySetsChange = (entitySetIds) => { const entityTypeId = (entitySetIds.length) ? entitySetIds[0].entityTypeId : null; this.setState({ entitySetIds, entityTypeId }); } onSubmit = () => { const { type, title, name, description, contact, entityTypeId, organizationId, entitySetIds, personEntityTypeId, external } = this.state; const isLinking = type === ENTITY_SET_TYPES.LINKED_ENTITY_SET; const flags = []; if (isLinking) { flags.push('LINKING'); } if (external) { flags.push('EXTERNAL'); } const entitySet = { title, name, description, entityTypeId, organizationId, contacts: [contact], linkedEntitySets: isLinking ? entitySetIds.map(({ value }) => value) : [], flags }; this.props.actions.onCreateEntitySet(entitySet); } getTypeOptions = () => { const options = []; Object.values(ENTITY_SET_TYPES).forEach((type) => { options.push({ value: type, label: type }); }); return options; } getEntityTypeOptions() { const options = []; this.props.entityTypes.forEach((entityType) => { if (!entityType.isEmpty()) { options.push({ value: entityType.get('id'), label: entityType.get('title') }); } }); return options; } getOrganizationOptions() { const options = []; this.props.writableOrganizations.forEach((organization) => { if (!organization.isEmpty()) { options.push({ value: organization.get('id'), label: organization.get('title') }); } }); return options; } getEntitySetOptions = () => { const options = []; this.props.entitySets.valueSeq().filter(entitySet => !entitySet.get('flags', List()).includes('LINKING')).forEach((entitySet) => { if (!this.state.entityTypeId || this.state.entityTypeId === entitySet.get('entityTypeId')) { options.push({ value: entitySet.get('id'), label: entitySet.get('title'), entityTypeId: entitySet.get('entityTypeId') }); } }); return options; } renderEntityTypeOrEntitySetSelection = () => { if (this.state.type === ENTITY_SET_TYPES.LINKED_ENTITY_SET) { return ( <FormGroup> <ControlLabel>Entity sets</ControlLabel> <Select multi value={this.state.entitySetIds} options={this.getEntitySetOptions()} onChange={this.onEntitySetsChange} /> </FormGroup> ); } return ( <FormGroup> <ControlLabel>Entity type</ControlLabel> <Select value={this.state.entityTypeId} options={this.getEntityTypeOptions()} onChange={this.onEntityTypeChange} /> </FormGroup> ); } renderPending = () => { return ( <form onSubmit={this.onSubmit}> { this.props.isAdmin && ( <FormGroup> <ControlLabel>Type</ControlLabel> <Select value={this.state.type} options={this.getTypeOptions()} onChange={this.onTypeChange} /> </FormGroup> ) } <FormGroup> <ControlLabel>Title</ControlLabel> <FormControl type="text" onChange={this.onTitleChange} /> </FormGroup> <FormGroup> <ControlLabel>Name</ControlLabel> <FormControl type="text" onChange={this.onNameChange} /> </FormGroup> <FormGroup> <ControlLabel>Description</ControlLabel> <FormControl componentClass="textarea" onChange={this.onDescriptionChange} /> </FormGroup> <FormGroup> <ControlLabel>Contact</ControlLabel> <FormControl type="text" value={this.state.contact} onChange={this.onContactChange} /> </FormGroup> { this.renderEntityTypeOrEntitySetSelection() } <FormGroup> <ControlLabel>Organization</ControlLabel> <Select value={this.state.organizationId} options={this.getOrganizationOptions()} onChange={this.onOrganizationChange} /> </FormGroup> <FormGroupMarginTop> <StyledCheckbox name="external" label="External" checked={this.state.external} onChange={({ target }) => this.setState({ external: target.checked })} /> </FormGroupMarginTop> <SubmitButton type="submit" bsStyle="primary">Create</SubmitButton> </form> ); }; renderSuccess = () => { return ( <Alert bsStyle="success"> Successfully saved Dataset </Alert> ); }; render() { return ( <AsyncContent {...this.props.createEntitySetAsyncState} pendingContent={this.renderPending()} content={this.renderSuccess} /> ); } } function mapStateToProps(state) { const createEntitySetState = state.get('createEntitySet').toJS(); const entityTypes = state.getIn(['edm', 'entityTypes'], Immutable.Map()); const entitySets = state.getIn(['edm', 'entitySets'], Immutable.Map()); const writableOrganizations = state.getIn(['organizations', 'writableOrganizations'], Immutable.List()); let personEntityTypeId = ''; entityTypes.valueSeq().forEach((entityType) => { const namespace = `${entityType.getIn(['type', 'namespace'])}`; const name = `${entityType.getIn(['type', 'name'])}`; if (`${namespace}.${name}` === PERSON_TYPE_FQN) personEntityTypeId = entityType.get('id'); }); return { entityTypes, entitySets, personEntityTypeId, writableOrganizations, createEntitySetAsyncState: createEntitySetState.createEntitySetAsyncState }; } function mapDispatchToProps(dispatch) { const actions = { fetchAllEntityTypesRequest, fetchWritableOrganizations, onCreateEntitySet: createEntitySetRequest }; return { actions: bindActionCreators(actions, dispatch) }; } export default connect(mapStateToProps, mapDispatchToProps)(CreateEntitySet);
app/javascript/mastodon/features/standalone/hashtag_timeline/index.js
MastodonCloud/mastodon
import React from 'react'; import { connect } from 'react-redux'; import PropTypes from 'prop-types'; import StatusListContainer from '../../ui/containers/status_list_container'; import { expandHashtagTimeline } from '../../../actions/timelines'; import Column from '../../../components/column'; import ColumnHeader from '../../../components/column_header'; import { connectHashtagStream } from '../../../actions/streaming'; @connect() export default class HashtagTimeline extends React.PureComponent { static propTypes = { dispatch: PropTypes.func.isRequired, hashtag: PropTypes.string.isRequired, }; handleHeaderClick = () => { this.column.scrollTop(); } setRef = c => { this.column = c; } componentDidMount () { const { dispatch, hashtag } = this.props; dispatch(expandHashtagTimeline(hashtag)); this.disconnect = dispatch(connectHashtagStream(hashtag)); } componentWillUnmount () { if (this.disconnect) { this.disconnect(); this.disconnect = null; } } handleLoadMore = maxId => { this.props.dispatch(expandHashtagTimeline(this.props.hashtag, { maxId })); } render () { const { hashtag } = this.props; return ( <Column ref={this.setRef}> <ColumnHeader icon='hashtag' title={hashtag} onClick={this.handleHeaderClick} /> <StatusListContainer trackScroll={false} scrollKey='standalone_hashtag_timeline' timelineId={`hashtag:${hashtag}`} onLoadMore={this.handleLoadMore} /> </Column> ); } }
client/containers/overview.js
nearform/vidi-dashboard
'use strict' import React from 'react' import {connect} from 'react-redux' import {Link} from 'react-router' import {Panel, PageHeader, HealthList} from '../components/index' import ChartistGraph from 'react-chartist' import {subscribe, unsubscribe} from '../actions/vidi' import _ from 'lodash' export const Overview = React.createClass({ componentDidMount () { this.props.dispatch(subscribe('processes')) this.props.dispatch(subscribe('event_loop')) }, componentWillUnmount () { this.props.dispatch(unsubscribe('processes')) this.props.dispatch(unsubscribe('event_loop')) }, render () { var sections = [] var groups = _.groupBy(this.props.process_stats, 'tag') _.each(groups, (group) => { if (group) { var proc_sections = [] var data = _.orderBy(group, ['pid'], ['desc']) var count = data.length var tag = '' _.each(data, (process) => { if (process) { tag = process.tag var event_loop = _.find(this.props.event_loop_stats, ['pid', process.pid]) proc_sections.push(make_process_sections(process, event_loop)) } }) sections.push( <div key={tag} className="process-group panel"> <div className="panel-heading cf"> <h3 className="m0 fl-left">Processes tagged with <strong>{tag}</strong></h3> <a href="" className="fl-right icon icon-collapse"></a> </div> <div className="panel-body"> <HealthList count={count}/> {proc_sections} </div> </div> ) } }) return ( <div className="page page-processes"> <div className="container-fluid"> <PageHeader title={'Overview'} /> </div> <div className="container-fluid"> {sections} </div> </div> ) } }) export default connect((state) => { var vidi = state.vidi var processes = vidi.processes || {data: [null]} var event_loop = vidi.event_loop || {data: [null]} return { process_stats: processes.data, event_loop_stats: event_loop.data } })(Overview) function make_search () { return ( <div className="row middle-xs search-wrapper"> <div className="col-xs-12 col-sm-8 col-md-8 search-input-wrapper"> <input type="search" className="input-large" placeholder="Find a process"/> </div> <div className="col-xs-12 col-sm-4 col-md-4 txt-left search-btn-wrapper"> <button className="btn btn-large btn-search">Search</button> </div> </div> ) } function make_process_sections (data, event_loop) { var section = [] var now = data.latest var delay = (Math.round(event_loop.latest.delay * 100) / 100) var link = `/process/${now.pid}` return ( <div key={now.pid} className="process-card"> <div className="process-heading has-icon"> <span className="status status-healthy status-small" title="Status: healthy"></span> <Link to={link}>{now.pid}</Link> </div> <div className="process-stats-row cf row no-gutter"> <div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated"> <ul className="list-unstyled list-inline cf"> <li><h4 className="m0">Process uptime:</h4></li> <li>{now.proc_uptime}</li> </ul> </div> <div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated"> <ul className="list-unstyled list-inline cf"> <li><h4 className="m0">System uptime:</h4></li> <li>{now.sys_uptime}</li> </ul> </div> <div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated"> <ul className="list-unstyled list-inline cf"> <li><h4 className="m0">Heap usage:</h4></li> <li>{`${now.heap_used} out of ${now.heap_total} (${now.heap_rss} RSS)`}</li> </ul> </div> <div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated"> <ul className="list-unstyled list-inline cf"> <li><h4 className="m0">Event loop:</h4></li> <li>{`${delay}s delay (${event_loop.latest.limit}s limit)`}</li> </ul> </div> </div> </div> ) }
Faw.Web.Client/src/routes/Achivment/Details/components/AchivmentDetails.js
Demenovich-A-J/Family-s-adventure-world
import React from 'react' import { Grid, Cell, Button } from 'react-mdl' import { Stepper, Step, SelectField, Option } from 'react-mdl-extra' import AchivmentDetailsForm from './AchivmentDetailsForm' import PropertyEditor from './PropertyEditor' import AchivmentStepperButtons from './AchivmentStepperButtons' import AchivmentExpressionList from './AchivmentExpressionList' import './AchivmentDetails.scss' export const AchivmentDetails = (props) => ( <Grid className='faw-achivment-details-conatiner'> <Cell col={7} shadow={0}> <Cell col={12} className='-section-title mdl-typography--headline' component='h4'> Achivment Details </Cell> <Cell col={12}> <AchivmentDetailsForm enabled={props.achivmentEnabled} disabled={props.achivmentSubmitting || props.achivmentLoading} /> <Button raised ripple primary onClick={props.submitAchivmentInfo} disabled={props.achivmentSubmitting || props.achivmentLoading}> Save </Button> </Cell> </Cell> <Cell col={5} shadow={0}> <Cell col={12} className='-section-title mdl-typography--headline' component='h4'> Achivment condition </Cell> <Cell col={12}> <AchivmentExpressionList expressionProperties={props.expressionProperties} removeAchivmentExpression={props.removeAchivmentExpression} editAchivmentExpression={props.editAchivmentExpression} disabled={props.achivmentSubmitting || props.achivmentLoading} /> </Cell> </Cell> <Cell col={12}> <Stepper activeStep={props.activeStep} onStepTitleClick={props.onStepTitleClick} disabled={props.achivmentSubmitting || props.achivmentLoading} > <Step title={'Introduction'}> <div className='-stepper-content'> <h4>Welcom to achivment condition stepper</h4> <p>Here you can configure achivment expression step by step</p> <AchivmentStepperButtons length={2} activeStep={props.activeStep} previousStep={props.previousStep} nextStep={props.nextStep} restart={props.restart} finish={props.finish} selectedModelName={props.selectedModelName} disabled={props.achivmentSubmitting || props.achivmentLoading} /> </div> </Step> <Step title={'Expression model selection'}> <div className='-stepper-content'> <p>Select model name to use for expression</p> <SelectField floatingLabel label={'Select model name'} value={props.selectedModelName} onChange={props.selectModelName} disabled={props.achivmentSubmitting || props.achivmentLoading} > { props.modelNames && props.modelNames.map((name, index) => ( <Option key={index} value={name}>{name}</Option> )) } </SelectField> <SelectField floatingLabel label={'Conncetor'} value={props.selectedConnector} onChange={props.selectConnector} className='-connector-select' disabled={props.achivmentSubmitting || props.achivmentLoading} > { props.connectors && props.connectors.map((name, index) => ( <Option key={index} value={name}>{name}</Option> )) } </SelectField> <AchivmentStepperButtons length={2} activeStep={props.activeStep} previousStep={props.previousStep} nextStep={props.nextStep} restart={props.restart} finish={props.finish} selectedModelName={props.selectedModelName} disabled={props.achivmentSubmitting || props.achivmentLoading} /> </div> </Step> <Step title={'Condition setup'}> <div className='-stepper-content'> <Grid className='-stepper-editor'> <Cell col={12}> <p>Fill folowing inputs to add condition</p> </Cell> <PropertyEditor propertyNames={props.modelProperties} propertyNameChanged={props.propertyNameChanged} propertyValueChanged={props.propertyValueChanged} propertyTypeChanged={props.propertyTypeChanged} valueMode={false} propertyValue={props.leftPropertyValue} selectedModelName={props.selectedModelName} side={'left'} valueTypes={props.valueTypes} disabled={props.achivmentSubmitting || props.achivmentLoading} /> <Cell col={4}> <SelectField floatingLabel label={'Comparer'} value={props.selectedComparer} onChange={props.selectComparer} className='-comparer-select' disabled={props.achivmentSubmitting || props.achivmentLoading} > { props.comparers && props.comparers.map((name, index) => ( <Option key={index} value={name}>{name}</Option> )) } </SelectField> </Cell> <PropertyEditor propertyNames={props.modelProperties} propertyNameChanged={props.propertyNameChanged} propertyValueChanged={props.propertyValueChanged} propertyTypeChanged={props.propertyTypeChanged} valueMode propertyValue={props.rightPropertyValue} selectedModelName={props.selectedModelName} side={'right'} valueTypes={props.valueTypes} disabled={props.achivmentSubmitting || props.achivmentLoading} /> </Grid> <AchivmentStepperButtons length={2} activeStep={props.activeStep} previousStep={props.previousStep} nextStep={props.nextStep} restart={props.restart} finish={props.finish} selectedModelName={props.selectedModelName} disabled={props.achivmentSubmitting || props.achivmentLoading} /> </div> </Step> </Stepper> </Cell> </Grid> ) AchivmentDetails.propTypes = { submitAchivmentInfo: React.PropTypes.func.isRequired, modelNames: React.PropTypes.array.isRequired, modelProperties: React.PropTypes.object.isRequired, leftPropertyValue: React.PropTypes.object.isRequired, rightPropertyValue: React.PropTypes.object.isRequired, selectedModelName: React.PropTypes.string, selectedComparer: React.PropTypes.string, selectedConnector: React.PropTypes.string, activeStep: React.PropTypes.number.isRequired, max: React.PropTypes.number.isRequired, previousStep: React.PropTypes.func.isRequired, nextStep: React.PropTypes.func.isRequired, restart: React.PropTypes.func.isRequired, onStepTitleClick: React.PropTypes.func.isRequired, selectModelName: React.PropTypes.func.isRequired, connectors: React.PropTypes.array.isRequired, selectConnector: React.PropTypes.func.isRequired, selectComparer: React.PropTypes.func.isRequired, propertyNameChanged: React.PropTypes.func.isRequired, propertyValueChanged: React.PropTypes.func.isRequired, propertyTypeChanged: React.PropTypes.func.isRequired, valueTypes: React.PropTypes.array.isRequired, comparers: React.PropTypes.array.isRequired, finish: React.PropTypes.func.isRequired, expressionProperties: React.PropTypes.array.isRequired, achivmentEnabled: React.PropTypes.bool.isRequired, removeAchivmentExpression: React.PropTypes.func.isRequired, editAchivmentExpression: React.PropTypes.func.isRequired, achivmentSubmitting: React.PropTypes.bool.isRequired, achivmentLoading: React.PropTypes.bool.isRequired } export default AchivmentDetails
client/routes.js
izolate/skeleton
import React from 'react' import { Router, Route, IndexRoute, browserHistory } from 'react-router' import DefaultLayout from './layouts/Default' import HomePage from './pages/Home' import Error404Page from './pages/404' const routes = <Router history={browserHistory}> <Route path='/' component={DefaultLayout}> <IndexRoute component={HomePage} /> <Route path='*' status={404} component={Error404Page} /> </Route> </Router> export default routes
js/src/modals/CreateWallet/createWalletStore.js
BSDStudios/parity
// Copyright 2015-2017 Parity Technologies (UK) Ltd. // This file is part of Parity. // Parity is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, either version 3 of the License, or // (at your option) any later version. // Parity is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the // GNU General Public License for more details. // You should have received a copy of the GNU General Public License // along with Parity. If not, see <http://www.gnu.org/licenses/>. import { observable, computed, action, transaction } from 'mobx'; import React from 'react'; import { FormattedMessage } from 'react-intl'; import Contract from '~/api/contract'; import { ERROR_CODES } from '~/api/transport/error'; import Contracts from '~/contracts'; import { wallet as walletAbi } from '~/contracts/abi'; import { wallet as walletCode, walletLibraryRegKey, fullWalletCode } from '~/contracts/code/wallet'; import { validateUint, validateAddress, validateName } from '~/util/validation'; import { toWei } from '~/api/util/wei'; import WalletsUtils from '~/util/wallets'; const STEPS = { TYPE: { title: ( <FormattedMessage id='createWallet.steps.type' defaultMessage='wallet type' /> ) }, DETAILS: { title: ( <FormattedMessage id='createWallet.steps.details' defaultMessage='wallet details' /> ) }, DEPLOYMENT: { title: ( <FormattedMessage id='createWallet.steps.deployment' defaultMessage='wallet deployment' /> ), waiting: true }, INFO: { title: ( <FormattedMessage id='createWallet.steps.info' defaultMessage='wallet informaton' /> ) } }; export default class CreateWalletStore { @observable step = null; @observable rejected = false; @observable deployState = null; @observable deployError = null; @observable deployed = false; @observable txhash = null; @observable wallet = { account: '', address: '', owners: [], required: 1, daylimit: toWei(1), name: '', description: '' }; @observable walletType = 'MULTISIG'; @observable errors = { account: null, address: null, owners: null, required: null, daylimit: null, name: null }; @computed get stage () { return this.stepsKeys.findIndex((k) => k === this.step); } @computed get hasErrors () { return !!Object.keys(this.errors) .filter((errorKey) => { if (this.walletType === 'WATCH') { return ['address', 'name'].includes(errorKey); } return errorKey !== 'address'; }) .find((key) => !!this.errors[key]); } @computed get stepsKeys () { return this.steps.map((s) => s.key); } @computed get steps () { return Object .keys(STEPS) .map((key) => { return { ...STEPS[key], key }; }) .filter((step) => { return (this.walletType !== 'WATCH' || step.key !== 'DEPLOYMENT'); }); } @computed get waiting () { this.steps .map((s, idx) => ({ idx, waiting: s.waiting })) .filter((s) => s.waiting) .map((s) => s.idx); } constructor (api, accounts) { this.api = api; this.step = this.stepsKeys[0]; this.wallet.account = Object.values(accounts)[0].address; this.validateWallet(this.wallet); } @action onTypeChange = (type) => { this.walletType = type; this.validateWallet(this.wallet); } @action onNext = () => { const stepIndex = this.stepsKeys.findIndex((k) => k === this.step) + 1; this.step = this.stepsKeys[stepIndex]; } @action onChange = (_wallet) => { const newWallet = Object.assign({}, this.wallet, _wallet); this.validateWallet(newWallet); } @action onAdd = () => { if (this.hasErrors) { return; } const walletContract = new Contract(this.api, walletAbi).at(this.wallet.address); return Promise .all([ WalletsUtils.fetchRequire(walletContract), WalletsUtils.fetchOwners(walletContract), WalletsUtils.fetchDailylimit(walletContract) ]) .then(([ require, owners, dailylimit ]) => { transaction(() => { this.wallet.owners = owners; this.wallet.required = require.toNumber(); this.wallet.dailylimit = dailylimit.limit; }); return this.addWallet(this.wallet); }); } @action onCreate = () => { if (this.hasErrors) { return; } this.step = 'DEPLOYMENT'; const { account, owners, required, daylimit } = this.wallet; Contracts .get() .registry .lookupAddress(walletLibraryRegKey) .catch(() => { return null; // exception when registry is not available }) .then((address) => { const walletLibraryAddress = (address || '').replace(/^0x/, '').toLowerCase(); const code = walletLibraryAddress.length && !/^0+$/.test(walletLibraryAddress) ? walletCode.replace(/(_)+WalletLibrary(_)+/g, walletLibraryAddress) : fullWalletCode; const options = { data: code, from: account }; return this.api .newContract(walletAbi) .deploy(options, [ owners, required, daylimit ], this.onDeploymentState); }) .then((address) => { this.deployed = true; this.wallet.address = address; return this.addWallet(this.wallet); }) .catch((error) => { if (error.code === ERROR_CODES.REQUEST_REJECTED) { this.rejected = true; return; } console.error('error deploying contract', error); this.deployError = error; }); } @action addWallet = (wallet) => { const { address, name, description } = wallet; return Promise .all([ this.api.parity.setAccountName(address, name), this.api.parity.setAccountMeta(address, { abi: walletAbi, wallet: true, timestamp: Date.now(), deleted: false, description, name, tags: ['wallet'] }) ]) .then(() => { this.step = 'INFO'; }); } onDeploymentState = (error, data) => { if (error) { return console.error('createWallet::onDeploymentState', error); } switch (data.state) { case 'estimateGas': case 'postTransaction': this.deployState = ( <FormattedMessage id='createWallet.states.preparing' defaultMessage='Preparing transaction for network transmission' /> ); return; case 'checkRequest': this.deployState = ( <FormattedMessage id='createWallet.states.waitingConfirm' defaultMessage='Waiting for confirmation of the transaction in the Parity Secure Signer' /> ); return; case 'getTransactionReceipt': this.deployState = ( <FormattedMessage id='createWallet.states.waitingReceipt' defaultMessage='Waiting for the contract deployment transaction receipt' /> ); this.txhash = data.txhash; return; case 'hasReceipt': case 'getCode': this.deployState = ( <FormattedMessage id='createWallet.states.validatingCode' defaultMessage='Validating the deployed contract code' /> ); return; case 'completed': this.deployState = ( <FormattedMessage id='createWallet.states.completed' defaultMessage='The contract deployment has been completed' /> ); return; default: console.error('createWallet::onDeploymentState', 'unknow contract deployment state', data); return; } } @action validateWallet = (_wallet) => { const addressValidation = validateAddress(_wallet.address); const accountValidation = validateAddress(_wallet.account); const requiredValidation = validateUint(_wallet.required); const daylimitValidation = validateUint(_wallet.daylimit); const nameValidation = validateName(_wallet.name); const errors = { address: addressValidation.addressError, account: accountValidation.addressError, required: requiredValidation.valueError, daylimit: daylimitValidation.valueError, name: nameValidation.nameError }; const wallet = { ..._wallet, address: addressValidation.address, account: accountValidation.address, required: requiredValidation.value, daylimit: daylimitValidation.value, name: nameValidation.name }; transaction(() => { this.wallet = wallet; this.errors = errors; }); } }
examples/js/selection/unselectable-table.js
AllenFang/react-bootstrap-table
/* eslint max-len: 0 */ import React from 'react'; import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table'; const products = []; function addProducts(quantity) { const startId = products.length; for (let i = 0; i < quantity; i++) { const id = startId + i; products.push({ id: id, name: 'Item name ' + id, price: 2100 + i }); } } addProducts(5); const selectRowProp = { mode: 'checkbox', clickToSelect: true, unselectable: [ 1, 3 ] // give rowkeys for unselectable row }; export default class UnSelectableTable extends React.Component { render() { return ( <BootstrapTable data={ products } selectRow={ selectRowProp }> <TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn> <TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn> <TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn> </BootstrapTable> ); } }
local-cli/templates/HelloNavigation/views/MainNavigator.js
cpunion/react-native
'use strict'; /** * This is an example React Native app demonstrates ListViews, text input and * navigation between a few screens. * https://github.com/facebook/react-native */ import React, { Component } from 'react'; import { StackNavigator } from 'react-navigation'; import HomeScreenTabNavigator from './HomeScreenTabNavigator'; import ChatScreen from './chat/ChatScreen'; /** * Top-level navigator. Renders the application UI. */ const MainNavigator = StackNavigator({ Home: { screen: HomeScreenTabNavigator, }, Chat: { screen: ChatScreen, }, }); export default MainNavigator;
webpack/components/accounts/ProfileEditor.js
CDCgov/SDP-Vocabulary-Service
import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { Modal } from 'react-bootstrap'; import values from 'lodash/values'; import filter from 'lodash/filter'; import clone from 'lodash/clone'; import Errors from '../Errors.js'; import NestedSearchBar from '../NestedSearchBar'; import { surveillanceSystemsProps }from '../../prop-types/surveillance_system_props'; import { surveillanceProgramsProps } from '../../prop-types/surveillance_program_props'; import currentUserProps from '../../prop-types/current_user_props'; // This is an abstract class that is never intended to // be used directly. export default class ProfileEditor extends Component { constructor(props) { super(props); this.programSearch = this.programSearch.bind(this); this.systemSearch = this.systemSearch.bind(this); } componentWillReceiveProps(nextProps){ var surveillanceSystems = values(nextProps.surveillanceSystems); var surveillancePrograms = values(nextProps.surveillancePrograms); this.setState({surveillanceSystems: surveillanceSystems, surveillancePrograms: surveillancePrograms, defaultProgramId: (surveillancePrograms[0] && surveillancePrograms[0].id) || -1, defaultSystemId: (surveillanceSystems[0] && surveillanceSystems[0].id) || -1 }); } render() { return ( <Modal animation={false} show={this.props.show} onHide={this.props.closer} aria-label={this.title()}> <Modal.Header closeButton> <Modal.Title componentClass="h1">{this.title()}</Modal.Title> </Modal.Header> <Modal.Body> <form> <Errors errors={this.state.errors} /> {this.userInfo() } {this.extraContent()} <div className="field"> {this.surveillanceProgramsField()} </div><br/> <div className="field"> {this.surveillanceSystemsField()} </div> </form> </Modal.Body> <Modal.Footer> <button type="button" className="btn btn-default" onClick={this.props.closer}>Close</button> {this.actionButton()} </Modal.Footer> </Modal> ); } userInfo(){ if(this.props.disableUserUpdate == 'true'){ return(""); }else{ return this.renderUserInfo(); } } renderUserInfo(){ return( <div> <div className="form-group"> <label className="control-label" htmlFor="email">E-mail</label> <input autoFocus="autofocus" placeholder="" className="form-control" type="email" value={this.state.email} name="email" id="email" onChange={this.handleChange('email')} /> <span className="help-block">Please provide your E-mail</span> </div> <div className="row"> <div className="form-group col-sm-6"> <label className="control-label" htmlFor="firstName">First name</label> <input className="form-control" type="text" name="firstName" id="firstName" value={this.state.firstName} onChange={this.handleChange('firstName')}/> </div> <div className="form-group col-sm-6"> <label className="control-label" htmlFor="lastName">Last name</label> <input className="form-control" type="text" name="lastName" id="lastName" value={this.state.lastName} onChange={this.handleChange('lastName')}/> </div> </div> <div className="form-group"> <label className="control-label">Roles</label><br/> { this.props.currentUser && this.props.currentUser.admin && <text>Admin, </text>} { this.props.currentUser && this.props.currentUser.publisher && <text>Publisher, </text>} { this.props.currentUser && this.props.currentUser.author ? ( <text>Author</text> ) : ( <text>Collaborator</text> )} </div> <div className="form-group"> <label className="control-label">Groups</label> <p>{this.state.groups.length > 0 ? (this.state.groups.map((group, i) => { if (i+1 < this.state.groups.length) { return (<text key={group.id}>{group.name}, </text>); } else { return (<text key={group.id}>{group.name}</text>); } })) : ( <text>No groups, contact admin to be added to a group.</text> )}</p> </div> </div>); } programSearch(programSearchTerm){ var surveillancePrograms = values(this.props.surveillancePrograms); if(programSearchTerm && programSearchTerm.length > 1){ surveillancePrograms = filter(surveillancePrograms, (sp) => sp.name.toLowerCase().includes(programSearchTerm.toLowerCase()) || sp.id === this.state.lastProgramId || sp.id.toString() === this.state.lastProgramId); } this.setState({surveillancePrograms: surveillancePrograms, defaultProgramId: (surveillancePrograms[0] && surveillancePrograms[0].id) || -1}); } systemSearch(systemSearchTerm){ var surveillanceSystems = values(this.props.surveillanceSystems); if(systemSearchTerm && systemSearchTerm.length > 1){ surveillanceSystems = filter(surveillanceSystems, (ss) => ss.name.toLowerCase().includes(systemSearchTerm.toLowerCase()) || ss.id === this.state.lastSystemId || ss.id.toString() === this.state.lastSystemId); } this.setState({surveillanceSystems: surveillanceSystems, defaultSystemId:(surveillanceSystems[0] && surveillanceSystems[0].id) || -1}); } surveillanceProgramsField() { return (<div id="search-programs"> <label className="control-label" htmlFor="lastProgramId">Default Surveillance Program</label> <NestedSearchBar onSearchTermChange={this.programSearch} modelName="Program" /> <select size='5' className="form-control" name="lastProgramId" id="lastProgramId" value={this.state.lastProgramId} onChange={this.handleChange('lastProgramId')} > {this.state.surveillancePrograms && this.state.surveillancePrograms.map((sp) => { return <option key={sp.id} value={sp.id}>{sp.name}</option>; })} </select> </div>); } surveillanceSystemsField() { return (<div id="search-systems"> <label className="control-label" htmlFor="lastSystemId">Default Surveillance System</label> <NestedSearchBar onSearchTermChange={this.systemSearch} modelName="System" /> <select size='5' className="form-control" name="lastSystemId" id="lastSystemId" value={this.state.lastSystemId} onChange={this.handleChange('lastSystemId')} > {this.state.surveillanceSystems && this.state.surveillanceSystems.map((ss) => { return <option key={ss.id} value={ss.id}>{ss.name}</option>; })} </select> </div>); } profileInformation() { let profileInformation = clone(this.state); delete profileInformation.errors; if (profileInformation.lastSystemId === -1) { if (profileInformation.defaultSystemId !== -1){ profileInformation.lastSystemId = profileInformation.defaultSystemId; } else { delete profileInformation.lastSystemId; } } if (profileInformation.lastProgramId === -1) { if (profileInformation.defaultProgramId !== -1){ profileInformation.lastProgramId = profileInformation.defaultProgramId; } else { delete profileInformation.lastProgramId; } } return profileInformation; } handleChange(field) { return (event) => { let newState = {}; newState[field] = event.target.value; this.setState(newState); }; } } ProfileEditor.propTypes = { closer: PropTypes.func.isRequired, show: PropTypes.bool.isRequired, disableUserUpdate:PropTypes.string, surveillanceSystems: surveillanceSystemsProps, surveillancePrograms: surveillanceProgramsProps, currentUser: currentUserProps };
examples/react-refetch/src/index.js
gaearon/react-hot-loader
import React from 'react'; import { render } from 'react-dom'; import App from './App'; const root = document.createElement('div'); document.body.appendChild(root); render(<App />, root);
app/m_components/Hotdot.js
kongchun/BigData-Web
import React from 'react'; import { Link } from 'react-router'; import HotdotActions from '../actions/HotdotActions'; import HotdotObjStore from '../stores/HotdotObjStore'; import MyInfoNavbar from './MyInfoNavbar'; import Weixin from './Weixin'; class Hotdot extends React.Component { constructor(props) { super(props); this.state = HotdotObjStore.getState(); this.onChange = this.onChange.bind(this); } componentDidMount() { HotdotActions.getHotdotDatas(); $(".month-search").hide(); $(".navbar-hotdot").on("touchend",function(){ var index = $(this).index(); if(index==0){ //本周 $(".month-search").hide(); $(".week-search").show(); }else{ //本月 $(".month-search").show(); $(".week-search").hide(); } }); HotdotObjStore.listen(this.onChange); Weixin.getUrl(); Weixin.weixinReady(); } componentWillUnmount() { HotdotObjStore.unlisten(this.onChange); } onChange(state) { this.setState(state); } getUpOrDown(curData,preData,isWeek){ var preDataItem = isWeek ? preData.week:preData.month; if(preData==false || preData == [] || preDataItem==undefined){ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); }else{ for(var i = 0;i < preDataItem.length;i++){ if(preDataItem[i].word == curData.word){ if(preDataItem[i].value < curData.value){ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); }else{ return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-down"></span> <span className="badge" style={{backgroundColor:"#4F81E3"}}>{curData.value}</span></span>); } } } } return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span> <span className="badge">{curData.value}</span></span>); } render() { var hotdotData = (this.state.data); var firstHotData = hotdotData[0]; var preHotData ; if(hotdotData.length > 7){ preHotData = hotdotData[7]; }else{ preHotData = []; } if(firstHotData){ var weekList = firstHotData.week.map((weekItem,i)=>( <li className="list-group-item" key={i}> {this.getUpOrDown(weekItem,preHotData,true)} {weekItem.word} </li> )); if(weekList.length==0){ weekList = <div className = "noData">数据还没有准备好,要不去其他页面瞅瞅?</div> } var monthList = firstHotData.month.map((monthItem,i)=>( <li className="list-group-item" key={i}> {this.getUpOrDown(monthItem,preHotData,false)} {monthItem.word} </li> )); if(monthList.length==0){ monthList = <div className = "noData">Whops,这个页面的数据没有准备好,去其他页面瞅瞅?</div> } }else{ var weekList = (<span>正在构建,敬请期待...</span>); var monthList = (<span>正在构建,敬请期待...</span>); } return (<div> <div className="content-container"> <div className="week-search"> <div className="panel panel-back"> <div className="panel-heading"> <span className="panel-title">本周关键字排行榜</span> <div className="navbar-key-container"> <span className="navbar-hotdot navbar-week navbar-hotdot-active">本周</span> <span className="navbar-hotdot navbar-month">本月</span> </div> </div> <div className="panel-body"> <ul className="list-group"> {weekList} </ul> </div> </div> </div> <div className="month-search"> <div className="panel panel-back"> <div className="panel-heading"> <span className="panel-title">本月关键字排行榜</span> <div className="navbar-key-container"> <span className="navbar-hotdot navbar-week">本周</span> <span className="navbar-hotdot navbar-month navbar-hotdot-active">本月</span> </div> </div> <div className="panel-body"> <ul className="list-group"> {monthList} </ul> </div> </div> </div> </div> </div>); } } export default Hotdot;
examples/passing-props-to-children/app.js
taion/rrtr
import React from 'react' import { render } from 'react-dom' import { browserHistory, Router, Route, Link } from 'rrtr' import './app.css' const App = React.createClass({ contextTypes: { router: React.PropTypes.object.isRequired }, getInitialState() { return { tacos: [ { name: 'duck confit' }, { name: 'carne asada' }, { name: 'shrimp' } ] } }, addTaco() { let name = prompt('taco name?') this.setState({ tacos: this.state.tacos.concat({ name }) }) }, handleRemoveTaco(removedTaco) { this.setState({ tacos: this.state.tacos.filter(function (taco) { return taco.name != removedTaco }) }) this.context.router.push('/') }, render() { let links = this.state.tacos.map(function (taco, i) { return ( <li key={i}> <Link to={`/taco/${taco.name}`}>{taco.name}</Link> </li> ) }) return ( <div className="App"> <button onClick={this.addTaco}>Add Taco</button> <ul className="Master"> {links} </ul> <div className="Detail"> {this.props.children && React.cloneElement(this.props.children, { onRemoveTaco: this.handleRemoveTaco })} </div> </div> ) } }) const Taco = React.createClass({ remove() { this.props.onRemoveTaco(this.props.params.name) }, render() { return ( <div className="Taco"> <h1>{this.props.params.name}</h1> <button onClick={this.remove}>remove</button> </div> ) } }) render(( <Router history={browserHistory}> <Route path="/" component={App}> <Route path="taco/:name" component={Taco} /> </Route> </Router> ), document.getElementById('example'))
src/components/docs/breadcrumbs.js
nordsoftware/react-foundation-docs
import React from 'react'; import Playground from 'component-playground'; import { Inline, Grid, Cell, Breadcrumbs, BreadcrumbItem, } from 'react-foundation'; export const BreadcrumbsDocs = () => ( <section className="breadcrumbs-docs"> <Grid> <Cell large={12}> <h2>Breadcrumbs</h2> <Playground codeText={require('raw-loader!../examples/breadcrumbs/basics').default} scope={{ React, Inline, Breadcrumbs, BreadcrumbItem }} theme="eiffel"/> </Cell> </Grid> </section> ); export default BreadcrumbsDocs;
src/svg-icons/image/timer-10.js
skarnecki/material-ui
import React from 'react'; import pure from 'recompose/pure'; import SvgIcon from '../../SvgIcon'; let ImageTimer10 = (props) => ( <SvgIcon {...props}> <path d="M0 7.72V9.4l3-1V18h2V6h-.25L0 7.72zm23.78 6.65c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39 0-.14.03-.28.09-.41.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59C21.49 9.07 21 9 20.46 9c-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.69.23.96c.15.28.36.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02zm-9.96-7.32c-.34-.4-.75-.7-1.23-.88-.47-.18-1.01-.27-1.59-.27-.58 0-1.11.09-1.59.27-.48.18-.89.47-1.23.88-.34.41-.6.93-.79 1.59-.18.65-.28 1.45-.28 2.39v1.92c0 .94.09 1.74.28 2.39.19.66.45 1.19.8 1.6.34.41.75.71 1.23.89.48.18 1.01.28 1.59.28.59 0 1.12-.09 1.59-.28.48-.18.88-.48 1.22-.89.34-.41.6-.94.78-1.6.18-.65.28-1.45.28-2.39v-1.92c0-.94-.09-1.74-.28-2.39-.18-.66-.44-1.19-.78-1.59zm-.92 6.17c0 .6-.04 1.11-.12 1.53-.08.42-.2.76-.36 1.02-.16.26-.36.45-.59.57-.23.12-.51.18-.82.18-.3 0-.58-.06-.82-.18s-.44-.31-.6-.57c-.16-.26-.29-.6-.38-1.02-.09-.42-.13-.93-.13-1.53v-2.5c0-.6.04-1.11.13-1.52.09-.41.21-.74.38-1 .16-.25.36-.43.6-.55.24-.11.51-.17.81-.17.31 0 .58.06.81.17.24.11.44.29.6.55.16.25.29.58.37.99.08.41.13.92.13 1.52v2.51z"/> </SvgIcon> ); ImageTimer10 = pure(ImageTimer10); ImageTimer10.displayName = 'ImageTimer10'; export default ImageTimer10;
scripts/index.js
doron2402/flux-react-router-example
import React from 'react'; import BrowserHistory from 'react-router/lib/BrowserHistory'; import HashHistory from 'react-router/lib/HashHistory'; import Root from './Root'; const rootEl = document.getElementById('root'); // Use hash location for Github Pages // but switch to HTML5 history locally. const history = process.env.NODE_ENV === 'production' ? new HashHistory() : new BrowserHistory(); React.render(<Root history={history} />, rootEl);
src/parser/deathknight/blood/modules/features/BoneShield.js
FaideWW/WoWAnalyzer
import React from 'react'; import Analyzer from 'parser/core/Analyzer'; import SPELLS from 'common/SPELLS'; import SpellIcon from 'common/SpellIcon'; import { formatDuration, formatPercentage } from 'common/format'; import { STATISTIC_ORDER } from 'interface/others/StatisticBox'; import StatisticBox from 'interface/others/StatisticBox'; import StatTracker from 'parser/shared/modules/StatTracker'; import BoneShieldTimesByStacks from './/BoneShieldTimesByStacks'; class BoneShield extends Analyzer { static dependencies = { statTracker: StatTracker, boneShieldTimesByStacks: BoneShieldTimesByStacks, }; get boneShieldTimesByStack() { return this.boneShieldTimesByStacks.boneShieldTimesByStacks; } get uptime() { return this.selectedCombatant.getBuffUptime(SPELLS.BONE_SHIELD.id) / this.owner.fightDuration; } get uptimeSuggestionThresholds() { return { actual: this.uptime, isLessThan: { minor: 0.95, average: 0.9, major: .8, }, style: 'percentage', }; } suggestions(when) { when(this.uptimeSuggestionThresholds) .addSuggestion((suggest, actual, recommended) => { return suggest('Your Bone Shield uptime can be improved. Try to keep it up at all times.') .icon(SPELLS.BONE_SHIELD.icon) .actual(`${formatPercentage(actual)}% Bone Shield uptime`) .recommended(`>${formatPercentage(recommended)}% is recommended`); }); } statistic() { return ( <StatisticBox icon={<SpellIcon id={SPELLS.BONE_SHIELD.id} />} value={`${formatPercentage(this.uptime)} %`} label="Bone Shield uptime" > <table className="table table-condensed"> <thead> <tr> <th>Stacks</th> <th>Time (s)</th> <th>Time (%)</th> </tr> </thead> <tbody> {Object.values(this.boneShieldTimesByStack).map((e, i) => ( <tr key={i}> <th>{i}</th> <td>{formatDuration(e.reduce((a, b) => a + b, 0) / 1000)}</td> <td>{formatPercentage(e.reduce((a, b) => a + b, 0) / this.owner.fightDuration)}%</td> </tr> ))} </tbody> </table> </StatisticBox> ); } statisticOrder = STATISTIC_ORDER.CORE(5); } export default BoneShield;
src/components/navigation.js
inkdropapp/docs
import { StaticQuery, graphql, Link } from 'gatsby' import { Container } from 'semantic-ui-react' import React from 'react' import { GatsbyImage } from 'gatsby-plugin-image' import './navigation.less' const Navigation = () => ( <Container className="app--navigation"> <nav className="ui grid"> <div className="row"> <Link to="/" className="app--logo"> <StaticQuery query={graphql` query { placeholderImage: file( relativePath: { eq: "navbar-logo.png" } ) { childImageSharp { gatsbyImageData(layout: FIXED, width: 142, height: 45) } } } `} render={data => ( <GatsbyImage image={data.placeholderImage.childImageSharp.gatsbyImageData} /> )} /> </Link> <ul className="app--navbar reset-list un-select"> <li> <a href="https://inkdrop.app/">Home</a> </li> <li> <a href="https://my.inkdrop.app/plugins">Plugins</a> </li> <li className="ui simple dropdown item"> More <i className="dropdown icon" /> <div className="menu"> <a className="item" href="https://inkdrop.app/pricing"> Pricing </a> <Link className="item" to="/faq"> FAQ </Link> <div className="divider" /> <a className="item" href="https://forum.inkdrop.app/"> User Forum </a> <div className="divider" /> <a className="item" href="https://twitter.com/inkdrop_app"> Twitter </a> <a className="item" href="https://medium.com/@inkdrop"> Blog </a> </div> </li> <li> <a href="https://my.inkdrop.app/" className="login"> <i className="sign in icon" /> Log in </a> </li> </ul> </div> </nav> </Container> ) export default Navigation
src/components/SitePage/index.js
narendrasoni1989/react-site
import React from 'react' class SitePage extends React.Component { render() { const post = this.props.data.post return <div dangerouslySetInnerHTML={{ __html: post.html }} /> } } export default SitePage
es/AppBar/AppBar.js
uplevel-technology/material-ui-next
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; } // @inheritedComponent Paper import React from 'react'; import classNames from 'classnames'; import withStyles from '../styles/withStyles'; import { capitalizeFirstLetter } from '../utils/helpers'; import Paper from '../Paper'; export const styles = theme => ({ root: { display: 'flex', flexDirection: 'column', width: '100%', boxSizing: 'border-box', // Prevent padding issue with the Modal and fixed positioned AppBar. zIndex: theme.zIndex.appBar, flexShrink: 0 }, positionFixed: { position: 'fixed', top: 0, left: 'auto', right: 0 }, positionAbsolute: { position: 'absolute', top: 0, left: 'auto', right: 0 }, positionStatic: { position: 'static', flexShrink: 0 }, colorDefault: { backgroundColor: theme.palette.background.appBar, color: theme.palette.getContrastText(theme.palette.background.appBar) }, colorPrimary: { backgroundColor: theme.palette.primary[500], color: theme.palette.getContrastText(theme.palette.primary[500]) }, colorAccent: { backgroundColor: theme.palette.secondary.A200, color: theme.palette.getContrastText(theme.palette.secondary.A200) } }); class AppBar extends React.Component { render() { const _props = this.props, { children, classes, className: classNameProp, color, position } = _props, other = _objectWithoutProperties(_props, ['children', 'classes', 'className', 'color', 'position']); const className = classNames(classes.root, classes[`position${capitalizeFirstLetter(position)}`], { [classes[`color${capitalizeFirstLetter(color)}`]]: color !== 'inherit', 'mui-fixed': position === 'fixed' // Useful for the Dialog }, classNameProp); return React.createElement( Paper, _extends({ square: true, component: 'header', elevation: 4, className: className }, other), children ); } } AppBar.defaultProps = { color: 'primary', position: 'fixed' }; export default withStyles(styles, { name: 'MuiAppBar' })(AppBar);
src/routes/privacy/index.js
chaudhryjunaid/chaudhryjunaid.com
/** * React Starter Kit (https://www.reactstarterkit.com/) * * Copyright © 2014-present Kriasoft, LLC. All rights reserved. * * This source code is licensed under the MIT license found in the * LICENSE.txt file in the root directory of this source tree. */ import React from 'react'; import Layout from '../../components/Layout'; import Page from '../../components/Page'; import privacy from './privacy.md'; function action() { return { chunks: ['privacy'], title: privacy.title, component: ( <Layout> <Page {...privacy} /> </Layout> ), }; } export default action;
src/components/components/mobile_list.js
highcoder1/ReactNews
import React from 'react'; import {Row,Col} from 'antd'; import {Link} from 'react-router-dom'; export default class MobileList extends React.Component { constructor() { super(); this.state = { news: '' }; } componentWillMount() { var myFetchOptions = { method: 'GET' }; fetch('http://newsapi.gugujiankong.com/Handler.ashx?action=getnews&type=' + this.props.type + '&count=' + this.props.count, myFetchOptions).then(response => response.json()).then(json => this.setState({news: json})); } render() { const {news} = this.state; const newsList = news.length ? news.map((newsItem, index) => ( <section key={index} className='m_article list-item special_section clearfix'> <Link to={`details/${newsItem.uniquekey}`}> <div className='m_article_img'> <img src={newsItem.thumbnail_pic_s} alt={newsItem.title} /> </div> <div className='m_article_info'> <div className='m_article_title'> <span>{newsItem.title}</span> </div> <div className='m_article_desc clearfix'> <div className='m_article_desc_l'> <span className='m_article_channel'>{newsItem.realtype}</span> <span className='m_article_time'>{newsItem.date}</span> </div> </div> </div> </Link> </section> )) : '没有加载到任何新闻'; return ( <div> <Row> <Col span={24}> {newsList} </Col> </Row> </div> ); } }
src/components/hand-signal/hand-signal.js
greaveselliott/rock-paper-scissors
import React from 'react' import './hand-signal.scss'; import Icon from '../icon'; import PropTypes from 'prop-types'; const HandSignal = ({name, className, modifier, click_handler}) => { return ( <figure onClick={click_handler} className={`${className} m-hand-signal${modifier}`}> <div className="m-hand-signal__face"> <Icon className="m-hand-signal__icon" icon={name}/> <figcaption className="m-hand-signal__name">{name}</figcaption> </div> <div className="m-hand-signal__back"> <Icon className="m-hand-signal__icon--small" icon="rock"/> <Icon className="m-hand-signal__icon--small" icon="paper"/> <Icon className="m-hand-signal__icon--small" icon="scissors"/> </div> </figure> ); }; HandSignal.propTypes = { name: PropTypes.string.isRequired, modifier: PropTypes.string } export default HandSignal;
server/sonar-web/src/main/js/components/controls/DateInput.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import $ from 'jquery'; import React from 'react'; import { pick } from 'lodash'; import './styles.css'; export default class DateInput extends React.Component { static propTypes = { value: React.PropTypes.string, format: React.PropTypes.string, name: React.PropTypes.string, placeholder: React.PropTypes.string, onChange: React.PropTypes.func.isRequired }; static defaultProps = { value: '', format: 'yy-mm-dd' }; componentDidMount() { this.attachDatePicker(); } componentWillReceiveProps(nextProps) { this.refs.input.value = nextProps.value; } handleChange() { const { value } = this.refs.input; this.props.onChange(value); } attachDatePicker() { const opts = { dateFormat: this.props.format, changeMonth: true, changeYear: true, onSelect: this.handleChange.bind(this) }; if ($.fn && $.fn.datepicker) { $(this.refs.input).datepicker(opts); } } render() { const inputProps = pick(this.props, ['placeholder', 'name']); /* eslint max-len: 0 */ return ( <span className="date-input-control"> <input className="date-input-control-input" ref="input" type="text" initialValue={this.props.value} readOnly={true} {...inputProps} /> <span className="date-input-control-icon"> <svg width="14" height="14" viewBox="0 0 16 16"> <path d="M5.5 6h2v2h-2V6zm3 0h2v2h-2V6zm3 0h2v2h-2V6zm-9 6h2v2h-2v-2zm3 0h2v2h-2v-2zm3 0h2v2h-2v-2zm-3-3h2v2h-2V9zm3 0h2v2h-2V9zm3 0h2v2h-2V9zm-9 0h2v2h-2V9zm11-9v1h-2V0h-7v1h-2V0h-2v16h15V0h-2zm1 15h-13V4h13v11z" /> </svg> </span> </span> ); } }
src/view/header.js
alexreardon/fullon-markdown
import React, { Component } from 'react'; import injectStyles from 'react-jss'; import ReactPlayer from 'react-player'; import Modal from 'react-modal'; import headerImage from '../img/header-image_860x391.jpg'; import logo from '../img/full-on-2020-logo.svg' import config from '../../config'; import { button, gutters, contentWidth } from './global-style'; import { relative } from 'path'; const modalStyles = { content: { backgroundColor: 'black', border: 'none', display: 'flex', flexDirection: 'column', alignItems: 'center', }, overlay: { position: 'fixed', top: 0, left: 0, right: 0, bottom: 0, backgroundColor: 'black', }, }; const style = { container: { display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', backgroundSize: 'contain', }, logo: { position: 'relative', maxWidth: contentWidth, width: '100%', marginBottom: gutters.medium, marginTop: 0, overflow: 'hidden' }, button, closeModalButton: { ...button, display: 'block', marginLeft: 'auto', marginRight: 'auto', marginTop: gutters.large * 2, }, }; @injectStyles(style) class Header extends Component { state = { isModalOpen: false, }; closeModal = () => { this.setState({ isModalOpen: false, }); }; openModal = () => { this.setState({ isModalOpen: true, }); }; render() { const {sheet: {classes}} = this.props; const {isModalOpen} = this.state; return ( <div className={classes.container}> <div className={classes.logo}> <img src={headerImage} alt='Full On 2020 Youth Camp' style={{ filter: 'blur(3px)', paddingTop: '0px', paddingBottom: '0px', transform: 'scale(1.1)' }} /> <img src={logo} style={{ position: 'absolute', paddingTop: '0px', paddingBottom: '0px', top: '0px', left: '0px', }} /> </div> <Modal isOpen={isModalOpen} onRequestClose={this.closeModal} style={modalStyles} > <ReactPlayer url={config.trailerUrl} playing onEnded={this.closeModal} width={800} height={450} style={{maxWidth: '100vw'}} /> <button className={classes.closeModalButton} onClick={this.closeModal} > Close Video </button> </Modal> <button onClick={this.openModal} className={classes.button} > What is Full On? (Video) </button> </div> ); } } export default Header;
clientwebapp/src/index.js
jcocchi/IoTPlantWatering
import React from 'react' import ReactDOM from 'react-dom' import App from './components/App' import registerServiceWorker from './registerServiceWorker' import './css/index.css' ReactDOM.render(<App />, document.getElementById('root')) registerServiceWorker()
docs/src/app/components/pages/components/Dialog/Page.js
frnk94/material-ui
import React from 'react'; import Title from 'react-title-component'; import CodeExample from '../../../CodeExample'; import PropTypeDescription from '../../../PropTypeDescription'; import MarkdownElement from '../../../MarkdownElement'; import dialogReadmeText from './README'; import DialogExampleSimple from './ExampleSimple'; import dialogExampleSimpleCode from '!raw!./ExampleSimple'; import DialogExampleModal from './ExampleModal'; import dialogExampleModalCode from '!raw!./ExampleModal'; import DialogExampleCustomWidth from './ExampleCustomWidth'; import dialogExampleCustomWidthCode from '!raw!./ExampleCustomWidth'; import DialogExampleDialogDatePicker from './ExampleDialogDatePicker'; import dialogExampleDialogDatePickerCode from '!raw!./ExampleDialogDatePicker'; import DialogExampleScrollable from './ExampleScrollable'; import DialogExampleScrollableCode from '!raw!./ExampleScrollable'; import DialogExampleAlert from './ExampleAlert'; import DialogExampleAlertCode from '!raw!./ExampleAlert'; import dialogCode from '!raw!material-ui/Dialog/Dialog'; const DialogPage = () => ( <div> <Title render={(previousTitle) => `Dialog - ${previousTitle}`} /> <MarkdownElement text={dialogReadmeText} /> <CodeExample title="Simple dialog" code={dialogExampleSimpleCode} > <DialogExampleSimple /> </CodeExample> <CodeExample title="Modal dialog" code={dialogExampleModalCode} > <DialogExampleModal /> </CodeExample> <CodeExample title="Styled dialog" code={dialogExampleCustomWidthCode} > <DialogExampleCustomWidth /> </CodeExample> <CodeExample title="Nested dialogs" code={dialogExampleDialogDatePickerCode} > <DialogExampleDialogDatePicker /> </CodeExample> <CodeExample title="Scrollable dialog" code={DialogExampleScrollableCode} > <DialogExampleScrollable /> </CodeExample> <CodeExample title="Alert dialog" code={DialogExampleAlertCode} > <DialogExampleAlert /> </CodeExample> <PropTypeDescription code={dialogCode} /> </div> ); export default DialogPage;
examples/Overlay.js
BespokeInsights/react-overlays
import React from 'react'; import Overlay from 'react-overlays/Overlay'; import Button from 'react-bootstrap/lib/Button'; // Styles Mostly from Bootstrap const TooltipStyle = { position: 'absolute', padding: '0 5px' }; const TooltipInnerStyle = { padding: '3px 8px', color: '#fff', textAlign: 'center', borderRadius: 3, backgroundColor: '#000', opacity: .75 }; const TooltipArrowStyle = { position: 'absolute', width: 0, height: 0, borderRightColor: 'transparent', borderLeftColor: 'transparent', borderTopColor: 'transparent', borderBottomColor: 'transparent', borderStyle: 'solid', opacity: .75 }; const PlacementStyles = { left: { tooltip: { marginLeft: -3, padding: '0 5px' }, arrow: { right: 0, marginTop: -5, borderWidth: '5px 0 5px 5px', borderLeftColor: '#000' } }, right: { tooltip: { marginRight: 3, padding: '0 5px' }, arrow: { left: 0, marginTop: -5, borderWidth: '5px 5px 5px 0', borderRightColor: '#000' } }, top: { tooltip: { marginTop: -3, padding: '5px 0' }, arrow: { bottom: 0, marginLeft: -5, borderWidth: '5px 5px 0', borderTopColor: '#000' } }, bottom: { tooltip: { marginBottom: 3, padding: '5px 0' }, arrow: { top: 0, marginLeft: -5, borderWidth: '0 5px 5px', borderBottomColor: '#000' } } }; class ToolTip { render(){ let placementStyle = PlacementStyles[this.props.placement]; let { style, arrowOffsetLeft: left = placementStyle.arrow.left, arrowOffsetTop: top = placementStyle.arrow.top, ...props } = this.props; return ( <div style={{...TooltipStyle, ...placementStyle.tooltip, ...style}}> <div style={{...TooltipArrowStyle, ...placementStyle.arrow, left, top }}/> <div style={TooltipInnerStyle}> { props.children } </div> </div> ); } } const OverlayExample = React.createClass({ getInitialState(){ return { show: false }; }, toggle(){ let show = this.state.show; let placements = ['left', 'top', 'right', 'bottom']; let placement = this.state.placement; placement = placements[placements.indexOf(placement) + 1]; if (!show) { show = true; placement = placements[0]; } else if (!placement) { show = false; } return this.setState({ show, placement }); }, render(){ return ( <div className='overlay-example'> <Button bsStyle='primary' ref='target' onClick={this.toggle}> I am an Overlay target </Button> <p> keep clicking to see the overlay placement change </p> <Overlay show={this.state.show} onHide={() => this.setState({ show: false })} placement={this.state.placement} container={this} target={ props => React.findDOMNode(this.refs.target)} > <ToolTip> I'm placed to the: <strong>{this.state.placement}</strong> </ToolTip> </Overlay> </div> ); } }); export default OverlayExample;
js/components/nutrientList.js
codeocelot/soylent-industries
import React from 'react' import NutrientStore from '../stores/nutrientStore' import {Cell} from 'react-pure' import {Table} from 'elemental' import Nutrient from './nutrient' import constants from '../constants/constants' export default class NutrientList extends React.Component{ constructor(props){ super(props); this.state = {nutrients:[]} } componentDidMount = () =>{ NutrientStore.listen((type,data)=>{ switch(type){ case constants.ALL_NUTRIENTS: this.setState({nutrients:data}) break; } }) } render(){ let nutrients = this.state.nutrients.map((n,i)=>{ return(<Nutrient {...n} key={i}/>) }) return( <Table style={{width:"100%"}}> <colgroup> <col width="70%" /> <col width=""/> <col width="15%"/> </colgroup> <thead> <tr> <th>Nutrient</th> <th>Quantity</th> <th>Recommended Amount</th> </tr> </thead> <tbody> {nutrients} </tbody> </Table> ) } }
example/app.js
georgeOsdDev/react-ellipsis-text
'use strict'; import React from 'react'; import ReactDom from 'react-dom'; import EllipsisText from '../lib/components/EllipsisText'; //allow react dev tools work window.React = React; const styles = { title: { marginTop: '40px' }, content: { padding: '10px' }, removed:{ marginTop: '40px', textDecoration: 'line-through' } } class App extends React.Component { constructor(props) { super(props); } render() { return ( <div> <h2 style={styles.title}>Simple ellipsify</h2> <p>text='1234567890'</p> <p>length= -1 ~ 11</p> <div style={styles.content}> <EllipsisText text={'1234567890'} length={-1} /> <br/> <EllipsisText text={'1234567890'} length={0} /> <br/> <EllipsisText text={'1234567890'} length={1} /> <br/> <EllipsisText text={'1234567890'} length={2} /> <br/> <EllipsisText text={'1234567890'} length={3} /> <br/> <EllipsisText text={'1234567890'} length={4} /> <br/> <EllipsisText text={'1234567890'} length={5} /> <br/> <EllipsisText text={'1234567890'} length={6} /> <br/> <EllipsisText text={'1234567890'} length={7} /> <br/> <EllipsisText text={'1234567890'} length={8} /> <br/> <EllipsisText text={'1234567890'} length={9} /> <br/> <EllipsisText text={'1234567890'} length={10} /> <br/> <EllipsisText text={'1234567890'} length={11} /> <br/> </div> <h2 style={styles.title}>Custom tail</h2> <div style={styles.content}> <EllipsisText text={'1234567890'} length={8} tailClassName={'myTail'}/> <br/> <EllipsisText text={'1234567890'} length={8} tail={'~~~'}/> <br/> </div> <h2 style={styles.removed}>Tooltip</h2> <div style={styles.content}> Tooltip feature is removed from V1.0. You should implement it by your self with <code>onMouseEnter</code> and <code>onMouseLeave</code> </div> <h2 style={styles.removed}>Tooltip with Clipboard copy</h2> <div style={styles.content}> Clipboard feature is removed from V1.0. You should implement it by your self with <code>onClick</code> </div> </div> ) } }; ReactDom.render(<App/>, document.getElementById('out'));
src/routes.js
raulmatei/frux-table-test
import React from 'react'; import { Route, IndexRoute } from 'react-router'; import Root from './root'; import NotFound from './not-found'; import TableView from './components/table-view'; export default ( <Route path='/' component={Root}> <IndexRoute component={TableView}/> <Route path='show' component={TableView}/> <Route path='*' component={NotFound}/> </Route> );
server/sonar-web/src/main/js/apps/permission-templates/components/Defaults.js
lbndev/sonarqube
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ import React from 'react'; import { sortBy } from 'lodash'; import { translate } from '../../../helpers/l10n'; import { PermissionTemplateType } from '../propTypes'; export default class Defaults extends React.Component { static propTypes = { organization: React.PropTypes.object, permissionTemplate: PermissionTemplateType.isRequired }; render() { const qualifiersToDisplay = this.props.organization && !this.props.organization.isDefault ? ['TRK'] : this.props.permissionTemplate.defaultFor; const qualifiers = sortBy(qualifiersToDisplay) .map(qualifier => translate('qualifiers', qualifier)) .join(', '); return ( <div> <span className="badge spacer-right"> {translate('default')} for {qualifiers} </span> </div> ); } }
client/app.js
Eschocolat/Pinbook
import React from 'react'; import { render } from 'react-dom'; import { Router, browserHistory } from 'react-router'; import { AppContainer as HotReloader } from 'react-hot-loader'; import routes from './routes'; const appElement = document.getElementById('app'); const root = ( <Router history={browserHistory}> {routes} </Router> ); render( <HotReloader>{root}</HotReloader>, appElement ); const renderRoot = () => { const routes = require('./routes').default; render( <HotReloader> <Router history={browserHistory}> {routes} </Router> </HotReloader>, appElement) }; if (module.hot) { module.hot.accept('./routes', renderRoot); }
app/pages/index.js
booee/nextfire
import React from 'react' export default class extends React.Component { render() { return ( <div>Hello, World!</div> ) } }