path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/container/navigator/header.js
|
PangPangPangPangPang/react-blog
|
/**
* Created by wangyefeng on 2017-03-31 11:26
*/
import React from 'react'
import { hashHistory } from 'react-router'
import './header.css'
import NormalButton from '../../compontent/normal_button'
import Logo from '../../resource/svg/diamond.svg'
class Header extends React.Component {
constructor(props) {
super(props)
this.state = {
backgroundColor: '',
iconColor: '',
}
}
componentDidMount() {
document.addEventListener('scroll', this.scrollEvent, false)
}
scrollEvent = () => {
if (document.body.scrollTop > 90) {
this.setState({
backgroundColor: 'header-animation',
iconColor: 'header-default-icon-animation',
})
} else if (document.body.scrollTop < 70) {
this.setState({
backgroundColor: 'header-animation-back',
iconColor: 'header-default-icon-animation-back',
})
}
}
clickHome = () => {
hashHistory.push('home')
}
clickArticle = () => {
hashHistory.push('list')
}
clickTags = () => {
hashHistory.push('tag')
}
clickAbout = () => {
hashHistory.push('about')
}
render() {
return (
<div className="header-base">
<div className={`header-default ${this.state.backgroundColor}`} >
<NormalButton title="Home Page" img={'home'} handleClick={this.clickHome} />
<NormalButton title="Article" img={'article'} handleClick={this.clickArticle} />
<NormalButton title="Contact Me" img={'tag'} handleClick={this.clickTags} />
<NormalButton title="About Me" img={'about'} handleClick={this.clickAbout} />
</div>
<Logo className={`header-default-icon ${this.state.iconColor}`} />
</div>
)
}
}
export default Header
|
blueocean-material-icons/src/js/components/svg-icons/image/hdr-strong.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageHdrStrong = (props) => (
<SvgIcon {...props}>
<path d="M17 6c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zM5 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2z"/>
</SvgIcon>
);
ImageHdrStrong.displayName = 'ImageHdrStrong';
ImageHdrStrong.muiName = 'SvgIcon';
export default ImageHdrStrong;
|
src/containers/Home.js
|
pjkarlik/Radial
|
import React from 'react';
import { withRouter } from 'react-router';
import { resolve } from '../styles';
import SiteStyles from '../styles/Site.less';
import RadialNav from '../components/RadialNav';
import RadialStyles from '../components/RadialNav.less';
class Home extends React.Component {
static displayName = 'Home';
static propTypes = {
classes: React.PropTypes.object,
router: React.PropTypes.shape({
push: React.PropTypes.func.isRequired,
}).isRequired,
items: React.PropTypes.array,
history: React.PropTypes.object,
};
static defaultProps = {
classes: SiteStyles,
items: [
{ name: 'dance', link: 'dance' },
{ name: 'ismtk', link: 'ismtk' },
{ name: 'home', link: '' },
],
};
constructor(props) {
super(props);
this.background = ~~(Math.random() * 4);
}
onClick = (path) => {
const { router } = this.props;
router.push(path);
}
render() {
const { items } = this.props;
return (
<div {...resolve(this.props, 'container', `home${this.background}`)}>
<div {...resolve(this.props, 'widget')}>
<RadialNav items = {items} mod = {this.background} classes = {RadialStyles} clickHandler = {this.onClick} />
</div>
</div>
);
}
}
export default withRouter(Home);
|
src/App.js
|
SpencerCornish/gong-web
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
example/src/screens/types/LightBox.js
|
inalist/react-native-navigation
|
import React from 'react';
import {StyleSheet, View, Text, Dimensions, Button} from 'react-native';
class Lightbox extends React.Component {
render() {
return (
<View style={styles.container}>
<View style={{flex: 8}}>
<Text style={styles.title}>{this.props.title}</Text>
<Text style={styles.content}>{this.props.content}</Text>
</View>
<View style={{flex: 2}}>
<Button
title={'Close'}
onPress={() => this.props.onClose()}
/>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
width: Dimensions.get('window').width * 0.7,
height: Dimensions.get('window').height * 0.3,
backgroundColor: '#ffffff',
borderRadius: 5,
padding: 16,
},
title: {
fontSize: 17,
fontWeight: '700',
},
content: {
marginTop: 8,
},
});
export default Lightbox;
|
app/components/Toggle/index.js
|
Dmitry-N-Medvedev/motor-collection
|
/**
*
* LocaleToggle
*
*/
import React from 'react';
import Select from './Select';
import ToggleOption from '../ToggleOption';
function Toggle(props) {
let content = (<option>--</option>);
// If we have items, render them
if (props.values) {
content = props.values.map((value) => (
<ToggleOption key={value} value={value} message={props.messages[value]} />
));
}
return (
<Select value={props.value} onChange={props.onToggle}>
{content}
</Select>
);
}
Toggle.propTypes = {
onToggle: React.PropTypes.func,
values: React.PropTypes.array,
value: React.PropTypes.string,
messages: React.PropTypes.object,
};
export default Toggle;
|
imports/api/interests/interests.js
|
howlround/worldtheatremap
|
// Meteor
import { TAPi18n } from 'meteor/tap:i18n';
// Utilities
import React from 'react';
import ReactSelect from 'react-select';
import { FormattedMessage } from 'react-intl';
import t from 'tcomb-form';
import Checkboxes from '../../ui/components/Checkboxes.jsx';
class InterestsCollection extends TAPi18n.Collection {
// insert(profile, callback) {
// }
// remove(selector, callback) {
// }
}
export const Interests = new InterestsCollection('Interests');
// Deny all client-side updates since we will be using methods to manage this collection
Interests.deny({
insert() { return true; },
update() { return true; },
remove() { return true; },
});
Interests.publicFields = {
value: 1,
label: 1,
};
export const interestsSelectFactory = (locale, multiValue = false) => {
// interestsSelectFactory options
const sortKey = (!locale || locale === 'en') ? 'label' : `i18n.${locale}.label`;
const sort = {};
sort[sortKey] = 1;
const allInterests = Interests.find({}, { sort }).fetch();
// interestsSelectFactory template
const allInterestsTags = t.form.Form.templates.select.clone({
renderSelect: (locals) => {
function onChange(options) {
if (multiValue === true) {
const values = (options || []).map(({ value }) => value);
locals.onChange(values);
} else {
if (options) {
locals.onChange(options.value);
} else {
locals.onChange(null);
}
}
}
const placeholder = (<FormattedMessage
id="forms.selectPlaceholder"
description="Select widget placeholder"
defaultMessage="Select..."
/>);
return (
<ReactSelect
multi
autoBlur
options={allInterests}
value={locals.value}
onChange={onChange}
className="interests-edit"
placeholder={placeholder}
/>
);
},
});
// interestsSelectFactory factory function
class ReactSelectInterestsFactory extends t.form.Component {
getTemplate() {
return allInterestsTags;
}
}
ReactSelectInterestsFactory.transformer = t.form.List.transformer;
return ReactSelectInterestsFactory;
};
export const interestsCheckboxFactory = (locale) => {
// interestsCheckboxFactory options
const sortKey = (!locale || locale === 'en') ? 'label' : `i18n.${locale}.label`;
const sort = {};
sort[sortKey] = 1;
const allInterests = Interests.find({}, { sort }).fetch();
// interestsCheckboxFactory template
const interestsCheckboxes = t.form.Form.templates.select.clone({
renderSelect: (locals) => (
<Checkboxes
options={allInterests}
values={locals.value}
name="interests"
onChange={locals.onChange}
/>
),
});
// interestsCheckboxFactory factory function
class CheckboxesInterestsFactory extends t.form.Component {
getTemplate() {
return interestsCheckboxes;
}
}
CheckboxesInterestsFactory.transformer = t.form.List.transformer;
return CheckboxesInterestsFactory;
};
|
demo-docs-website/src/theme/DocItemFooter/index.js
|
dimsemenov/PhotoSwipe
|
/**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import clsx from 'clsx';
import LastUpdated from '@theme/LastUpdated';
import EditThisPage from '@theme/EditThisPage';
import TagsListInline from '@theme/TagsListInline';
import styles from './styles.module.css';
import {ThemeClassNames} from '@docusaurus/theme-common';
function TagsRow(props) {
return (
<div
className={clsx(
ThemeClassNames.docs.docFooterTagsRow,
'row margin-bottom--sm',
)}>
<div className="col">
<TagsListInline {...props} />
</div>
</div>
);
}
function EditMetaRow({
editUrl,
lastUpdatedAt,
lastUpdatedBy,
formattedLastUpdatedAt,
}) {
return (
<div className={clsx(ThemeClassNames.docs.docFooterEditMetaRow, 'row')}>
<div className="col">
{editUrl && <EditThisPage editUrl={editUrl} />}
<br/>
Updates on <a href="https://twitter.com/photoswipe">Twitter</a>
<br/>
Code on <a href="https://github.com/dimsemenov/photoswipe">GitHub</a>
<br/>
Sponsor on <a href="https://opencollective.com/photoswipe">Open Collective</a>
</div>
<div className={clsx('col', styles.lastUpdated)}>
{(lastUpdatedAt || lastUpdatedBy) && (
<LastUpdated
lastUpdatedAt={lastUpdatedAt}
formattedLastUpdatedAt={formattedLastUpdatedAt}
lastUpdatedBy={lastUpdatedBy}
/>
)}
</div>
</div>
);
}
export default function DocItemFooter(props) {
const {content: DocContent} = props;
const {metadata} = DocContent;
const {editUrl, lastUpdatedAt, formattedLastUpdatedAt, lastUpdatedBy, tags} =
metadata;
const canDisplayTagsRow = tags.length > 0;
const canDisplayEditMetaRow = !!(editUrl || lastUpdatedAt || lastUpdatedBy);
const canDisplayFooter = canDisplayTagsRow || canDisplayEditMetaRow;
if (!canDisplayFooter) {
return null;
}
return (
<footer
className={clsx(ThemeClassNames.docs.docFooter, 'docusaurus-mt-lg')}>
{canDisplayTagsRow && <TagsRow tags={tags} />}
{canDisplayEditMetaRow && (
<EditMetaRow
editUrl={editUrl}
lastUpdatedAt={lastUpdatedAt}
lastUpdatedBy={lastUpdatedBy}
formattedLastUpdatedAt={formattedLastUpdatedAt}
/>
)}
</footer>
);
}
|
src/svg-icons/notification/airline-seat-legroom-extra.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatLegroomExtra = (props) => (
<SvgIcon {...props}>
<path d="M4 12V3H2v9c0 2.76 2.24 5 5 5h6v-2H7c-1.66 0-3-1.34-3-3zm18.83 5.24c-.38-.72-1.29-.97-2.03-.63l-1.09.5-3.41-6.98c-.34-.68-1.03-1.12-1.79-1.12L11 9V3H5v8c0 1.66 1.34 3 3 3h7l3.41 7 3.72-1.7c.77-.36 1.1-1.3.7-2.06z"/>
</SvgIcon>
);
NotificationAirlineSeatLegroomExtra = pure(NotificationAirlineSeatLegroomExtra);
NotificationAirlineSeatLegroomExtra.displayName = 'NotificationAirlineSeatLegroomExtra';
NotificationAirlineSeatLegroomExtra.muiName = 'SvgIcon';
export default NotificationAirlineSeatLegroomExtra;
|
server/sonar-web/src/main/js/apps/web-api/components/Params.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.
*/
// @flow
import React from 'react';
import InternalBadge from './InternalBadge';
import DeprecatedBadge from './DeprecatedBadge';
import type { Param } from '../../../api/web-api';
export default class Params extends React.PureComponent {
props: {
showDeprecated: boolean,
showInternal: boolean,
params: Array<Param>
};
render() {
const { showDeprecated, showInternal, params } = this.props;
const displayedParameters = params
.filter(p => showDeprecated || !p.deprecatedSince)
.filter(p => showInternal || !p.internal);
return (
<div className="web-api-params">
<table>
<tbody>
{displayedParameters.map(param => (
<tr key={param.key}>
<td className="markdown" style={{ width: 180 }}>
<code>{param.key}</code>
{param.internal &&
<div className="little-spacer-top">
<InternalBadge />
</div>}
{param.deprecatedSince &&
<div className="little-spacer-top">
<DeprecatedBadge since={param.deprecatedSince} />
</div>}
{showDeprecated &&
param.deprecatedKey &&
<div className="little-spacer-top">
<code>{param.deprecatedKey}</code>
</div>}
{showDeprecated &&
param.deprecatedKey &&
param.deprecatedKeySince &&
<div className="little-spacer-top">
<DeprecatedBadge since={param.deprecatedKeySince} />
</div>}
<div className="note little-spacer-top">
{param.required ? 'required' : 'optional'}
</div>
{param.since &&
<div className="note little-spacer-top">
since {param.since}
</div>}
</td>
<td>
<div
className="markdown"
dangerouslySetInnerHTML={{ __html: param.description }}
/>
</td>
<td style={{ width: 250 }}>
{param.possibleValues &&
<div>
<h4>Possible values</h4>
<ul className="list-styled">
{param.possibleValues.map(value => (
<li key={value} className="little-spacer-top">
<code>{value}</code>
</li>
))}
</ul>
</div>}
{param.defaultValue &&
<div className="little-spacer-top">
<h4>Default value</h4>
<code>{param.defaultValue}</code>
</div>}
{param.exampleValue &&
<div className="little-spacer-top">
<h4>Example value</h4>
<code>{param.exampleValue}</code>
</div>}
</td>
</tr>
))}
</tbody>
</table>
</div>
);
}
}
|
entry_types/scrolled/package/src/frontend/inlineEditing/TextPlaceholder.js
|
codevise/pageflow
|
import React from 'react';
import styles from './TextPlaceholder.module.css';
export function TextPlaceholder({text, visible}) {
if (!text || !visible) {
return null;
}
return (
<div className={styles.placeholder}>
<div>{text}</div>
</div>
);
}
|
editor/components/ButtonGroups.js
|
VishalRohra/chroma-tone
|
import React from 'react'
import Toolbar from './Toolbar'
export default class ButtonGroups extends React.Component {
render() {
return (
<Toolbar className={this.props.className}>
{['left', 'middle', 'right'].map( position =>
<div key={position} className='toolbar-group'>
{ this.props.children[position] }
</div>
)}
</Toolbar>
);
}
}
|
src/server/frontend/Html.js
|
VigneshRavichandran02/3io
|
/* @flow */
/* eslint-disable react/no-danger */
import React from 'react';
const GoogleAnalytics = ({ id }) => (
<script
dangerouslySetInnerHTML={{ __html: `
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '${id}', 'auto'); ga('send', 'pageview');`,
}}
/>
);
GoogleAnalytics.propTypes = {
id: React.PropTypes.string.isRequired,
};
type Props = {
appCssFilename: string,
bodyHtml: string,
googleAnalyticsId: string,
helmet: Object,
isProduction: boolean,
};
const Html = ({
appCssFilename,
bodyHtml,
googleAnalyticsId,
helmet,
isProduction,
}: Props) => (
<html {...helmet.htmlAttributes.toComponent()}>
<head>
{helmet.title.toComponent()}
{helmet.base.toComponent()}
{helmet.meta.toComponent()}
{helmet.link.toComponent()}
{helmet.script.toComponent()}
{appCssFilename &&
<link href={appCssFilename} rel="stylesheet" />
}
{isProduction && googleAnalyticsId !== 'UA-XXXXXXX-X' &&
<GoogleAnalytics id={googleAnalyticsId} />
}
</head>
<body
dangerouslySetInnerHTML={{ __html: bodyHtml }}
/>
</html>
);
// TODO: Use babel-plugin-flow-react-proptypes one day.
Html.propTypes = {
appCssFilename: React.PropTypes.string,
bodyHtml: React.PropTypes.string.isRequired,
googleAnalyticsId: React.PropTypes.string.isRequired,
helmet: React.PropTypes.object.isRequired,
isProduction: React.PropTypes.bool.isRequired,
};
export default Html;
|
src/common/containers/Profile.js
|
strekmann/samklang
|
import React from 'react';
import { Grid, Row, Col } from 'react-bootstrap';
import { connect } from 'react-redux';
import Immutable from 'immutable';
class Profile extends React.Component {
render() {
const user = this.props.users.get(this.props.user.get('id'));
return (
<Grid>
<Row>
<Col xs={12}>
<h2>{user.get('name')}</h2>
<p>{user.get('email')}</p>
<p>{user.get('created')}</p>
</Col>
</Row>
</Grid>
);
}
}
Profile.propTypes = {
user: React.PropTypes.object,
users: React.PropTypes.instanceOf(Immutable.Map),
};
function select(state) {
return {
user: state.get('user'),
users: state.get('users'),
};
}
export default connect(select)(Profile);
|
src/routes/index.js
|
corydolphin/kanban-github
|
import React from 'react'
import { Route, IndexRoute, Redirect } from 'react-router'
// NOTE: here we're making use of the `resolve.root` configuration
// option in webpack, which allows us to specify import paths as if
// they were from the root of the ~/src directory. This makes it
// very easy to navigate to files regardless of how deeply nested
// your current file is.
import CoreLayout from 'layouts/CoreLayout/CoreLayout'
import HomeView from 'views/HomeView/HomeView'
import NotFoundView from 'views/NotFoundView/NotFoundView'
export default (
<Route path='/' component={CoreLayout}>
<IndexRoute component={HomeView} />
<Route path='/404' component={NotFoundView} />
<Redirect from='*' to='/404' />
</Route>
)
|
src/Parser/Core/Modules/Items/Legion/Legendaries/SephuzsSecret.js
|
enragednuke/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import { formatPercentage } from 'common/format';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
const PASSIVE_HASTE = 0.02;
const ACTIVE_HASTE = 0.25;
/*
* Sephuz's Secret -
* Equip: Gain 10% increased movement speed and 2% Haste. Successfully applying a loss of control effect to an enemy, interrupting an enemy, or dispelling any target increases this effect to 70% increased movement speed and 25% Haste for 10 sec. This increase may occur once every 30 sec.
*/
class SephuzsSecret extends Analyzer {
static dependencies = {
combatants: Combatants,
};
on_initialized() {
this.active = this.combatants.selected.hasFinger(ITEMS.SEPHUZS_SECRET.id);
}
item() {
const uptimePercent = this.combatants.selected.getBuffUptime(SPELLS.SEPHUZS_SECRET_BUFF.id) / this.owner.fightDuration;
const avgHaste = (uptimePercent * ACTIVE_HASTE) + ((1 - uptimePercent) * PASSIVE_HASTE);
return {
item: ITEMS.SEPHUZS_SECRET,
result: (
<span>
<dfn
data-tip={`This is the average haste percentage gained, factoring in both the passive and active bonuses. The active's uptime was <b>${formatPercentage(uptimePercent)}%</b>`}
>
{formatPercentage(avgHaste)} % average haste
</dfn>
</span>
),
};
}
}
export default SephuzsSecret;
|
Skins/VetoccitanT3/ReactSrc/node_modules/react-awesome-slider/src/core/bullets.js
|
MAN-IN-WAN/Kob-Eye
|
import React from 'react';
import PropTypes from 'prop-types';
import { getClassName } from '../helpers/components';
export default class Bullets extends React.Component {
static propTypes = {
cssModule: PropTypes.object,
rootElement: PropTypes.string.isRequired,
media: PropTypes.array,
onClick: PropTypes.func,
selected: PropTypes.number,
};
static defaultProps = {
cssModule: null,
selected: 0,
media: [],
onClick: () => {},
};
constructor(props) {
super(props);
this.rootElement = props.rootElement;
}
bulletClick = event => {
const button = event.currentTarget;
button.classList.add(
getClassName(
`${this.rootElement}__bullets--loading`,
this.props.cssModule
)
);
const index = parseInt(button.getAttribute('data-index'), 10);
const direction = !(this.props.selected > index);
this.props.onClick({ index, direction });
};
renderBullets() {
const { cssModule, selected, media = [] } = this.props;
return media.map((item, index) => {
const className =
index === selected
? getClassName(`${this.rootElement}__bullets--active`, cssModule)
: null;
return (
<button
key={`bullet-${index}`}
data-index={index}
onClick={this.bulletClick}
className={className}
>
{index}
</button>
);
});
}
render() {
const { cssModule, rootElement } = this.props;
return (
<nav className={getClassName(`${rootElement}__bullets`, cssModule)}>
{this.renderBullets()}
</nav>
);
}
}
|
src/components/Footer.js
|
elamperti/OpenWebScrobbler
|
import React from 'react';
import { Trans } from 'react-i18next';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faTwitter, faFacebook, faGithub } from '@fortawesome/free-brands-svg-icons';
import './Footer.css';
function Footer() {
return (
<footer>
<div className="container mt-3 mb-2">
<div className="social text-center my-2">
<a title="Facebook" className="mx-2" href="https://facebook.com/OpenScrobbler">
<FontAwesomeIcon icon={faFacebook} size="2x" />
</a>
<a title="Twitter" className="mx-2" href="https://twitter.com/OpenScrobbler">
<FontAwesomeIcon icon={faTwitter} size="2x" />
</a>
<a title="GitHub" className="mx-2" href="https://github.com/elamperti/openwebscrobbler">
<FontAwesomeIcon icon={faGithub} size="2x" />
</a>
</div>
<p className="text-center">
<Trans i18nKey="footer.joinCommunity">
You are welcome to join our community <a href="https://discord.gg/vcbprTz">on Discord</a>!
</Trans>
<Trans i18nKey="footer.supportThisProject">
Please <a href="https://www.patreon.com/OpenScrobbler">support this project</a> on Patreon :)
</Trans>
<br />
<Trans i18nKey="footer.specialThanks">
{'Special thanks to all our supporters, translators and '}
<a href="https://github.com/elamperti/OpenWebScrobbler/graphs/contributors">contributors</a>
</Trans>
{' ❤ '}
<span className="app-version">v{process.env.REACT_APP_VERSION}</span>
</p>
</div>
</footer>
);
}
export default Footer;
|
src/with-feature-toggles.js
|
paralleldrive/react-feature-toggles
|
import React from 'react';
import { FeatureToggles } from './feature-toggles';
export const withFeatureToggles = ({ features } = {}) => Component => props => (
<FeatureToggles features={features}>
<Component {...props} />
</FeatureToggles>
);
|
src/propTypes/PointPropType.js
|
dingbat/react-native-mock
|
/**
* https://github.com/facebook/react-native/blob/master/Libraries/StyleSheet/PointPropType.js
*/
import React from 'react';
const { PropTypes } = React;
const PointPropType = PropTypes.shape({
x: PropTypes.number,
y: PropTypes.number,
});
module.exports = PointPropType;
|
app/components/__tests__/App_test.js
|
ivanthedeployer/todo
|
import React from 'react'
import { shallow } from 'enzyme'
import { expect } from 'chai'
import App from '../App'
describe('App', () => {
it('renders', () => {
const component = shallow(<App />)
expect(component.find('h1').text()).to.equal("Test Application")
})
})
|
src/shared/components/HistoricTime/index.js
|
CharlesMangwa/Chloe
|
/* @flow */
import React from 'react'
import { Text, View } from 'react-native'
import { getPeriodColor, getPeriodName } from '@helpers/periods'
import Icon from '@components/Icon'
import styles from './styles'
type Props = {
value: 'preHistory' | 'antiquity' | 'middleAge' | 'modernTimes' | 'contemporaryTimes',
pages?: number,
}
const HistoricTime = (props: Props): React$Element<any> => {
const { value, pages } = props
return (
<View style={styles.container}>
<Icon
name={pages ? 'bookmarkIcon' : value}
defaultColor={getPeriodColor(value)}
size={16}
/>
{pages && <Text style={styles.text}><Text style={styles.textBold}>{pages}</Text> pages</Text>}
{!pages && <Text style={styles.text}>{getPeriodName(value)}</Text>}
</View>
)
}
export default HistoricTime
|
src/js/components/App.js
|
nathanbrennan/redux-todo
|
import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodolist from '../containers/VisibleTodoList'
const App = () => (
<div>
<AddTodo />
<VisibleTodolist />
<Footer />
</div>
)
export default App
|
packages/react/src/components/Text/__tests__/Text-test.js
|
carbon-design-system/carbon-components
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { render, screen } from '@testing-library/react';
import React from 'react';
import { TextDirection, Text } from '../';
describe('Text', () => {
it('should support specifying direction with the `dir` prop', () => {
render(
<Text dir="rtl" data-testid="test">
test
</Text>
);
const node = screen.getByTestId('test');
expect(node).toHaveAttribute('dir', 'rtl');
});
it('should support custom elements with the `as` prop', () => {
render(
<Text as="p" data-testid="test">
test
</Text>
);
const node = screen.getByTestId('test');
expect(node.tagName).toBe('P');
});
it('should support spreading props onto the outermost node', () => {
render(
<Text data-testid="test" id="test">
test
</Text>
);
const node = screen.getByTestId('test');
expect(node).toHaveAttribute('id', 'test');
});
it('should not use redundant `dir` attributes on text nodes', () => {
render(
<Text data-testid="outside" dir="rtl">
outside{' '}
<Text data-testid="inside" dir="rtl">
inside
</Text>
</Text>
);
const outside = screen.getByTestId('outside');
expect(outside).toHaveAttribute('dir', 'rtl');
const inside = screen.getByTestId('inside');
expect(inside).not.toHaveAttribute('dir');
});
it('should support overriding `dir` with `getTextDirection`', () => {
const getTextDirection = jest.fn().mockImplementation((input) => {
if (input === 'test') {
return 'auto';
}
if (input === 'inner') {
return 'ltr';
}
return 'rtl';
});
render(
<TextDirection dir="ltr" getTextDirection={getTextDirection}>
<Text data-testid="flat">test</Text>
<Text data-testid="outer">
pre<Text data-testid="inner">inner</Text>post
</Text>
<Text data-testid="inherit">
inherit <Text data-testid="nested">nested</Text>
</Text>
</TextDirection>
);
expect(screen.getByTestId('flat')).toHaveAttribute('dir', 'auto');
expect(getTextDirection).toHaveBeenCalledWith('test');
expect(screen.getByTestId('outer')).toHaveAttribute('dir', 'rtl');
expect(getTextDirection).toHaveBeenCalledWith(['pre', 'post']);
expect(screen.getByTestId('inner')).toHaveAttribute('dir', 'ltr');
expect(getTextDirection).toHaveBeenCalledWith('inner');
expect(screen.getByTestId('inherit')).toHaveAttribute('dir', 'rtl');
expect(getTextDirection).toHaveBeenCalledWith('inherit ');
expect(screen.getByTestId('nested')).not.toHaveAttribute('dir');
expect(getTextDirection).toHaveBeenCalledWith('nested');
});
});
|
packages/material-ui-icons/src/PermDataSetting.js
|
dsslimshaddy/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PermDataSetting = props =>
<SvgIcon {...props}>
<path d="M18.99 11.5c.34 0 .67.03 1 .07L20 0 0 20h11.56c-.04-.33-.07-.66-.07-1 0-4.14 3.36-7.5 7.5-7.5zm3.71 7.99c.02-.16.04-.32.04-.49 0-.17-.01-.33-.04-.49l1.06-.83c.09-.08.12-.21.06-.32l-1-1.73c-.06-.11-.19-.15-.31-.11l-1.24.5c-.26-.2-.54-.37-.85-.49l-.19-1.32c-.01-.12-.12-.21-.24-.21h-2c-.12 0-.23.09-.25.21l-.19 1.32c-.3.13-.59.29-.85.49l-1.24-.5c-.11-.04-.24 0-.31.11l-1 1.73c-.06.11-.04.24.06.32l1.06.83c-.02.16-.03.32-.03.49 0 .17.01.33.03.49l-1.06.83c-.09.08-.12.21-.06.32l1 1.73c.06.11.19.15.31.11l1.24-.5c.26.2.54.37.85.49l.19 1.32c.02.12.12.21.25.21h2c.12 0 .23-.09.25-.21l.19-1.32c.3-.13.59-.29.84-.49l1.25.5c.11.04.24 0 .31-.11l1-1.73c.06-.11.03-.24-.06-.32l-1.07-.83zm-3.71 1.01c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z" />
</SvgIcon>;
PermDataSetting = pure(PermDataSetting);
PermDataSetting.muiName = 'SvgIcon';
export default PermDataSetting;
|
src/server/createSSR.js
|
jcoreio/crater
|
import React from 'react'
import makeStore from '../universal/redux/makeStore'
import {match as _match} from 'react-router'
import Html from './Html'
import {push} from 'react-router-redux'
import {renderToStaticMarkup} from 'react-dom-stream/server'
import fs from 'fs'
import path from 'path'
import {join} from 'path'
import promisify from 'es6-promisify'
import {Map as iMap} from 'immutable'
import {Meteor} from 'meteor/meteor'
import url from 'url'
import type {IncomingMessage, ServerResponse} from 'http'
import type {Store} from '../universal/flowtypes/redux'
const __meteor_runtime_config__ = {
PUBLIC_SETTINGS: Meteor.settings.public || {},
ROOT_URL: process.env.ROOT_URL,
// Not everything is in place to support basename right now (e.g. react-router history config, webpack config)
// but might as well go ahead and use the correct value here anyway
ROOT_URL_PATH_PREFIX: url.parse(process.env.ROOT_URL).pathname.substring(1),
meteorEnv: {
NODE_ENV: process.env.NODE_ENV,
},
meteorRelease: Meteor.release,
}
function handleError(res: ServerResponse, error: Error) {
console.error(error.stack) // eslint-disable-line no-console
res.write(`
<div style="padding: 15px; position: fixed; top: 0; left: 0; right: 0; bottom: 0;">
<h3>An internal server error occurred:</h3>
<p>${error.message}</p>
</div>
`)
res.addTrailers({
'X-Streaming-Error': error.message,
})
res.end()
}
function renderApp(res: ServerResponse, store: Store, assets?: Object, renderProps?: Object) {
res.setHeader('Trailer', 'X-Streaming-Error')
const onError = handleError.bind(null, res)
const location = renderProps && renderProps.location && renderProps.location.pathname || '/'
// Needed so some components can render based on location
store.dispatch(push(location))
const htmlStream = renderToStaticMarkup(
<Html
title="Crater"
store={store}
assets={assets}
__meteor_runtime_config__={__meteor_runtime_config__}
renderProps={renderProps}
onError={onError}
/>
)
res.write('<!DOCTYPE html>')
htmlStream.pipe(res, {end: false})
htmlStream.on('end', (): void => res.end())
htmlStream.on('error', onError)
}
type MatchResult = {
redirectLocation: {pathname: string, search: string},
renderProps: ?Object,
}
function match({routes, location}: {routes: Object, location: string}): Promise<MatchResult> {
return new Promise((resolve: (result: MatchResult) => void, reject: (error: Error) => void) => {
_match({routes, location}, (error: ?Error, redirectLocation: {pathname: string, search: string}, renderProps: ?Object) => {
if (error) {
reject(error)
return
}
resolve({redirectLocation, renderProps})
})
})
}
const createSSR = Meteor.bindEnvironment(async (req: IncomingMessage, res: ServerResponse): Promise<void> => {
try {
const store = makeStore(iMap())
if (process.env.NODE_ENV === 'production') {
const readFile = promisify(fs.readFile)
const assets = JSON.parse(await readFile(path.resolve(__dirname, 'assets.json'), 'utf8'))
assets.manifest.text = await readFile(join(__dirname, assets.manifest.js), 'utf-8')
if (process.env.DISABLE_FULL_SSR) {
return await renderApp(res, store, assets)
}
const makeRoutes = require('../universal/routes').default
const routes = makeRoutes(store)
const {redirectLocation, renderProps} = await match({
routes,
location: req.url
})
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search)
} else if (renderProps) {
renderApp(res, store, assets, renderProps)
} else {
res.status(404).send('Not found')
}
} else {
// just send a cheap html doc + stringified store
renderApp(res, store)
}
} catch (error) {
handleError(res, error)
}
})
export default createSSR
|
app/components/Player/PlayerControls.js
|
Nurasael/WeWatch
|
import React from 'react'
import styles from './PlayerControls.css'
const PlayerControls = (props) => {
const {seekValue, handleSeekChange, prepareTestVideo, togglePause, duration, showTimer} = props
return (
<div className={styles.component}>
<input type="range" min="0" max={duration} value={seekValue} onChange={event => handleSeekChange(event.target.value)} step="0.1" />
<div className={styles.controls}>
<button className={styles.playerPlay} onClick={togglePause} type="button"><i className="fa fa-play" aria-hidden="true"></i></button>
<button className={styles.playerFordward} type="button"><i className="fa fa-forward" aria-hidden="true"></i></button>
<span className={styles.timer}>{showTimer()}</span>
<button className={styles.playerVolume} type="button"><i className="fa fa-volume-up" aria-hidden="true"></i></button>
<button type="button" onClick={prepareTestVideo}>PrepareTestVideo</button>
</div>
</div>
)
}
export default PlayerControls
|
client/vehicle-finder-spa/src/containers/messages/all-message-threads.js
|
Del7a/vehicle-finder
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { requestAllMessageThreads, changeCurrentMessageThread } from '../../actions/messages/';
import { getUserProfile } from '../../actions/user/';
import MessageThreadListComponent from '../../components/messages/list-item-view';
class AllMessageThreads extends Component {
constructor(props) {
super(props)
this.onMessageThreadClick = this.onMessageThreadClick.bind(this)
}
componentDidMount() {
if (!this.props.messages.messageThreads.length) {
this.props.requestAllMessageThreads()
}
if (!this.props.user.currentUserId) {
this.props.getUserProfile()
}
}
onMessageThreadClick(messageThread) {
if (!messageThread.messages) {
messageThread.messages = [];
messageThread.loadingMessages = true;
}
this.props.changeCurrentMessageThread(messageThread)
}
render() {
return (
<div className="modal-body row">
<MessageThreadListComponent
messageThreads={this.props.messages.messageThreads}
onMessageThreadClick={this.onMessageThreadClick}
currentUserId={this.props.user.userId}
/>
</div>
)
}
}
function mapStateToProps({messages, user}) {
return {messages, user};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({requestAllMessageThreads, changeCurrentMessageThread,
getUserProfile}, dispatch)
}
export default connect(mapStateToProps, mapDispatchToProps)(AllMessageThreads)
|
modules/dreamview/frontend/src/components/common/PortalModal.js
|
ApolloAuto/apollo
|
import 'styles/Modal.scss';
import React from 'react';
import ReactDOM from 'react-dom';
class Modal extends React.Component {
constructor(props) {
super(props);
this.setOkButtonRef = (element) => {
this.okButton = element;
};
}
componentDidMount() {
// .focus() has browser restrictions in some cases, where
// the element is not visible when trying to focus().
// The workaround is setting a setTimeout as below.
setTimeout(() => {
if (this.okButton) {
this.okButton.focus();
}
}, 0);
}
componentDidUpdate() {
if (this.okButton) {
this.okButton.focus();
}
}
render() {
const { open, header } = this.props;
if (!open) {
return null;
}
return (
<div>
<div className="modal-background" />
<div className="modal-content">
<div role="dialog" className="modal-dialog">
{header && (
<header>
<span>{this.props.header}</span>
</header>
)}
{this.props.children}
</div>
<button
ref={this.setOkButtonRef}
className="ok-button"
onClick={() => this.props.onClose()}
>
OK
</button>
</div>
</div>
);
}
}
export default class PortalModal extends React.Component {
constructor(props) {
super(props);
this.rootSelector = document.getElementById('root');
this.container = document.createElement('div');
}
componentDidMount() {
this.rootSelector.appendChild(this.container);
}
componentWillUnmount() {
this.rootSelector.removeChild(this.container);
}
render() {
return ReactDOM.createPortal(<Modal {...this.props} />, this.container);
}
}
|
src/components/Header.js
|
jamescchu/jameschu-v5
|
import React from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import { rhythm } from '../utils/typography'
import { media } from '../utils/media'
const Header = styled.header`
width: ${rhythm(2)};
margin: ${rhythm(1 / 2)} ${rhythm(1)};
position: initial;
${media.desktop`
position: fixed;
`};
`
const LogoLink = styled(Link)`
display: block;
`
const Logo = () =>
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20">
<path d="M5.2 18.7c.2-.3.4-.6.6-.8.9-1.2 1.7-2.5 2.4-3.9.2-.6.5-1.1.8-1.6.4-.9.9-1.9 1.2-2.8.4-1.1.8-2.1 1.2-3.2.4-1 .8-2 1.1-3 .2-.7.4-1.5.5-2.3 0-.2 0-.4.1-.6-.7-.2-1.3-.3-2-.4-.2.2-.4.5-.6.7-.6.4-.8.8-1.1 1.3-.4.7-.9 1.4-1.3 2.1-.2.4-.4.8-.6 1.3-.3.8-.8 1.6-1.1 2.5-.3.9-.7 1.8-.9 2.7-.3 1-.5 1.7-.7 2.6-.1.4-.1.8-.1.9 0 .4.1.4 0 .6 0 .2-.4-.1-.4-.5 0-.8 0-1.5.2-2.3.2-.9.5-1.6.7-2.5.2-.9.6-1.7 1-2.6.3-.5.5-1.1.8-1.6.2-.4.3-.8.5-1.2.4-.8.9-1.5 1.4-2.3.3-.6.7-1.2 1.2-1.8H10C4.5 0 0 4.5 0 10c0 3.7 2.1 7 5.2 8.7z" />
<path d="M13.5.6c-.1.8-.3 1.6-.5 2.4-.2.9-.6 1.8-.9 2.7-.3.9-.6 1.8-.9 2.6-.2.6-.5 1.2-.7 1.8-.6 1.3-1.1 2.5-1.7 3.8v.1c.4-.4.7-.9 1.1-1.3l.9-.9c.3-.3.7-.7 1.1-.9.2-.1.6-.2.8-.1.2.1.3.4.3.6 0 .6 0 1.2-.1 1.8 0 .3.1.3.4.2.5-.2.9-.6 1.3-1 .2-.2.4-.4.6-.5.3-.2.7-.2 1-.1.3.2.6.3 1 .5v.2h-.1c-.4 0-.8 0-1.2-.2-.2-.1-.2 0-.4.1-.4.3-.7.7-1.1 1-.4.3-.8.6-1.4.6-.4 0-.6-.2-.6-.6v-2.2c-.2.1-.5.2-.7.4-.8.8-1.6 1.7-2.3 2.6-.5.7-1.1 1.3-1.6 2-.4.6-.7 1.2-1 1.8-.2.4-.4.7-.6 1.1 1.1.6 2.4.9 3.8.9 5.5 0 10-4.5 10-10 0-4.3-2.7-8-6.5-9.4z" />
</svg>
const SiteHeader = () =>
<Header>
<LogoLink to="/">
<Logo />
</LogoLink>
</Header>
export default SiteHeader
|
packages/react-scripts/template/src/App.js
|
dpoineau/create-react-app
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
src/client/js/Layout.js
|
JMJustas/todolist
|
/**
* Layout for the whole page
*/
import React from 'react';
import EntryService from './services/EntryService';
import Header from './Header';
import TodosApp from './components/TodosApp';
export default class Layout extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="full-height">
<Header heading="A simple TODO app"/>
<div className="container full-height">
<div className="row">
<TodosApp entryService={new EntryService()}/>
</div>
</div>
</div>
);
}
}
|
src/components/CategoryCard/CategoryCard.js
|
hologram-io/docs
|
import React from 'react'
import {Link} from '../'
class CategoryCard extends React.Component {
constructor(props) {
super(props);
}
render() {
const {
header = "",
title = "",
image = "",
blurb = "",
cta = "",
ctaLink = ""
} = this.props;
return (
<div className="row">
<h2 className="col-md-3">
{header}
</h2>
<div className="col-md-9">
<div className="row card-category">
<div className="col-xs">
<img className="cat-image" src={image} />
</div>
<div className="col-xs">
<h1>{title}</h1>
<p>{blurb}</p>
<div className="cta">
<Link href={ctaLink}>{cta}</Link>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default CategoryCard;
|
client/modules/Post/__tests__/components/PostList.spec.js
|
BingeTrackr/BingeTrackr
|
import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import PostList from '../../components/PostList';
const posts = [
{ name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" },
{ name: 'Mayank', title: 'Hi Mern', slug: 'hi-mern', cuid: 'f34gb2bh24b24b3', content: "All dogs bark 'mern!'" },
];
test('renders the list', t => {
const wrapper = shallow(
<PostList posts={posts} handleShowPost={() => {}} handleDeletePost={() => {}} />
);
t.is(wrapper.find('PostListItem').length, 2);
});
|
src/component/Dashboard.js
|
hustlrb/yjbAdmin
|
/**
* Created by yangyang on 2017/9/11.
*/
import React from 'react'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
import { Button } from 'antd'
import {configAction, configSelector} from '../util/config'
class Dashboard extends React.Component {
constructor(props) {
super(props)
}
fetchDomain = () => {
this.props.requestDomain({times: 2})
}
render() {
return (
<div>
Dashboard
<div style={{marginTop: 10}}>
<Button type="primary" onClick={this.fetchDomain}>获取域名</Button>
</div>
<div style={{marginTop: 10}}>
{this.props.domain}
</div>
</div>
)
}
}
const mapStateToProps = (state, ownProps) => {
let domain = configSelector.selectDomain(state)
return {
domain,
}
}
const mapDispatchToProps = {
...configAction,
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Dashboard))
|
packages/react/src/components/atoms/buttons/Button/index.js
|
massgov/mayflower
|
/**
* Button module.
* @module @massds/mayflower-react/Button
*/
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
const Button = (button) => {
const buttonClasses = classNames({
ma__button: true,
[`ma__button--${button.usage}`]: button.usage,
[`ma__button--${button.size}`]: button.size,
[`ma__button--${button.theme}`]: button.theme,
'ma__button--disabled': button.disabled,
[button.classes.join(' ')]: button.classes
});
const Element = button.href ? 'a' : 'button';
const onClickCallback = (e) => {
if (typeof button.onClick === 'function') {
e.preventDefault();
button.onClick(e);
}
};
return(
<Element
className={buttonClasses}
type={button.type}
href={button.href}
title={button.info}
aria-label={button.label}
onClick={(e) => onClickCallback(e)}
disabled={button.disabled}
>
{button.children ? button.children : button.text}
</Element>
);
};
Button.propTypes = {
/** Custom click handler function. */
onClick: PropTypes.func,
/** When populated with a url, this component renders an `<a>` vs a `<button>` */
href: PropTypes.string,
/** The text which renders in the standard browser tooltip on hover */
info: PropTypes.string,
/** Aria-label of the button */
label: PropTypes.string,
/** Button or link text */
text: PropTypes.string,
/** HTML button 'type' attribute */
type: PropTypes.oneOf(['submit', 'reset', 'button', '']),
/** Create a smaller button */
size: PropTypes.oneOf(['', 'small', 'large']),
/** Themes correspond to site color scheme i.e. sass variables */
theme: PropTypes.oneOf(['', 'c-primary-alt', 'c-highlight', 'c-gray-dark']),
/** Button usage */
usage: PropTypes.oneOf(['', 'secondary', 'tertiary', 'quaternary']),
/** Set `<button>` to disabled */
disabled: PropTypes.bool,
/** Custom classnames appending to the button */
classes: PropTypes.arrayOf(PropTypes.string)
};
// Only set defaults for the configuration variables which need to be opted in to activate.
Button.defaultProps = {
href: '',
type: '',
size: '',
theme: '',
usage: '',
disabled: false,
classes: ['']
};
export default Button;
|
src/svg-icons/notification/no-encryption.js
|
kasra-co/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationNoEncryption = (props) => (
<SvgIcon {...props}>
<path d="M21 21.78L4.22 5 3 6.22l2.04 2.04C4.42 8.6 4 9.25 4 10v10c0 1.1.9 2 2 2h12c.23 0 .45-.05.66-.12L19.78 23 21 21.78zM8.9 6c0-1.71 1.39-3.1 3.1-3.1s3.1 1.39 3.1 3.1v2H9.66L20 18.34V10c0-1.1-.9-2-2-2h-1V6c0-2.76-2.24-5-5-5-2.56 0-4.64 1.93-4.94 4.4L8.9 7.24V6z"/>
</SvgIcon>
);
NotificationNoEncryption = pure(NotificationNoEncryption);
NotificationNoEncryption.displayName = 'NotificationNoEncryption';
NotificationNoEncryption.muiName = 'SvgIcon';
export default NotificationNoEncryption;
|
__tests__/ActiveJob-test.js
|
kbariotis/async-jobs-ui
|
jest.unmock('../resources/jsx/components/ActiveJob');
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import ActiveJob from '../resources/jsx/components/ActiveJob';
describe('ActiveJob Component', () => {
let job = {
id: 1,
label: 'A long running job',
active: true,
failed: false,
percent: 20
};
const activeJob = TestUtils.renderIntoDocument(
<ActiveJob {...job} />
);
it('outputs the Job title', () => {
const node = TestUtils.findRenderedDOMComponentWithTag(activeJob, 'h5');
expect(node.textContent).toEqual('A long running job');
});
it('outputs the Job ID', () => {
const node = TestUtils.scryRenderedDOMComponentsWithTag(activeJob, 'small');
expect(node[0].textContent).toEqual('ID: #' + job.id);
});
xit('outputs the Created Date', () => {
const node = TestUtils.scryRenderedDOMComponentsWithTag(activeJob, 'small');
});
xit('outputs the Updated Date', () => {
const node = TestUtils.scryRenderedDOMComponentsWithTag(activeJob, 'small');
});
});
|
client/util/react-intl-test-helper.js
|
eantler/simmeme-client
|
/**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import { mount, shallow } from 'enzyme';
// You can pass your messages to the IntlProvider. Optional: remove if unneeded.
const messages = require('../../Intl/localizationData/en');
// Create the IntlProvider to retrieve context for wrapping around.
const intlProvider = new IntlProvider({ locale: 'en', messages }, {});
export const { intl } = intlProvider.getChildContext();
/**
* When using React-Intl `injectIntl` on components, props.intl is required.
*/
const nodeWithIntlProp = node => {
return React.cloneElement(node, { intl });
};
export const shallowWithIntl = node => {
return shallow(nodeWithIntlProp(node), { context: { intl } });
};
export const mountWithIntl = node => {
return mount(nodeWithIntlProp(node), {
context: { intl },
childContextTypes: { intl: intlShape },
});
};
|
src/layouts/CoreLayout/CoreLayout.js
|
TriPSs/react-esc-example
|
import React from 'react'
import { Route, Switch } from 'react-router'
import 'styles/core.scss'
import Header from 'components/Header'
import Home from 'routes/Home'
import Counter from 'routes/Counter'
import Async from 'routes/Async'
import classes from './CoreLayout.scss'
export const CoreLayout = () => (
<div className="container text-center">
<Header />
<div className={classes.mainContainer}>
<Switch>
<Route {...Home} />
<Route {...Counter} />
<Route {...Async} />
</Switch>
</div>
</div>
)
export default CoreLayout
|
renderer/components/Channels/ChannelsViewButtons.js
|
LN-Zap/zap-desktop
|
import React from 'react'
import PropTypes from 'prop-types'
import { useIntl } from 'react-intl'
import { SwitchButton } from 'components/UI'
import LayoutCards from 'components/Icon/LayoutCards'
import LayoutList from 'components/Icon/LayoutList'
import { CHANNEL_LIST_VIEW_MODE_SUMMARY, CHANNEL_LIST_VIEW_MODE_CARD } from './constants'
import messages from './messages'
const ChannelsViewButtons = ({ channelViewMode, setChannelViewMode, ...rest }) => {
const intl = useIntl()
const isCardView = channelViewMode === CHANNEL_LIST_VIEW_MODE_CARD
return (
<SwitchButton
{...rest}
data-hint={intl.formatMessage({
...(isCardView ? messages.view_mode_list : messages.view_mode_card),
})}
Icon1={LayoutList}
Icon2={LayoutCards}
isSwitched={isCardView}
onClick={() =>
setChannelViewMode(
isCardView ? CHANNEL_LIST_VIEW_MODE_SUMMARY : CHANNEL_LIST_VIEW_MODE_CARD
)
}
/>
)
}
ChannelsViewButtons.propTypes = {
channelViewMode: PropTypes.string.isRequired,
setChannelViewMode: PropTypes.func.isRequired,
}
export default ChannelsViewButtons
|
docs/app/Examples/elements/Image/States/index.js
|
ben174/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ImageStatesExamples = () => (
<ExampleSection title='States'>
<ComponentExample
title='Hidden'
description='An image can be hidden.'
examplePath='elements/Image/States/ImageExampleHidden'
/>
<ComponentExample
title='Disabled'
description='An image can show that it is disabled and cannot be selected.'
examplePath='elements/Image/States/ImageExampleDisabled'
/>
</ExampleSection>
)
export default ImageStatesExamples
|
test/ButtonGroupSpec.js
|
zanjs/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import ButtonGroup from '../src/ButtonGroup';
import Button from '../src/Button';
import { shouldWarn } from './helpers';
describe('ButtonGroup', function () {
it('Should output a button group', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.equal(React.findDOMNode(instance).nodeName, 'DIV');
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group\b/));
});
it('Should add size', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup bsSize='large'>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-lg\b/));
});
it('Should add vertical variation', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup vertical>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.equal(React.findDOMNode(instance).className.trim(), 'btn-group-vertical');
});
it('Should add block variation', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup vertical block>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/));
});
it('Should warn about block without vertical', function () {
ReactTestUtils.renderIntoDocument(
<ButtonGroup block>
<Button>
Title
</Button>
</ButtonGroup>
);
shouldWarn('The block property requires the vertical property to be set to have any effect');
});
it('Should add justified variation', function () {
let instance = ReactTestUtils.renderIntoDocument(
<ButtonGroup justified>
<Button>
Title
</Button>
</ButtonGroup>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-group-justified\b/));
});
});
|
browser/components/relationships/relationships-single-bubble.component.js
|
smanwaring/relationship-visualizer
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import Popover, { PopoverAnimationVertical } from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import AddActivityForm from '../forms/add-activity/add-activity.component';
import EditRelationship from '../forms/edit-relationship/edit-relationship.component';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
class SingleRelationship extends Component {
constructor(props){
super(props);
this.state = {
modalOpen: false,
open: false,
modalContent: ""
};
this.handleTouchTap = this.handleTouchTap.bind(this);
this.handleRequestClose = this.handleRequestClose.bind(this);
this.handleAddActivityOpen = this.handleAddActivityOpen.bind(this);
this.handleAddActivityClose = this.handleAddActivityClose.bind(this);
this.handleEditActivityOpen = this.handleEditActivityOpen.bind(this);
}
handleAddActivityOpen() {
this.setState({open: false});
this.setState({ modalOpen: true, modalContent: "add" });
}
handleEditActivityOpen() {
this.setState({open: false});
this.setState({ modalOpen: true, modalContent: "edit" });
}
handleAddActivityClose() {
this.setState({ modalOpen: false });
}
handleTouchTap(event){
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
}
handleRequestClose() {
this.setState({ open: false });
}
renderModalContent() {
if(this.state.modalContent === "add") {
return (
<AddActivityForm
handleAddActivityClose={this.handleAddActivityClose}
relationshipId={this.props.relationship.id} autoFocus="true" />
)
} else if(this.state.modalContent === "edit") {
return (
<EditRelationship
autoFocus="true"
handleClose={this.handleAddActivityClose}
relationship={this.props.relationship}
/>
)
}
}
render(){
const { loggedInUser, relationship, relationshipStyle, name, addActivityStatus } = this.props;
const addActivityActions = [
<FlatButton
label="Cancel"
primary={true}
keyboardFocused={true}
onTouchTap={this.handleAddActivityClose}
/>
]
return (
<div className="bubble-container">
<div className="bubble-container-center vam" onTouchTap={this.handleTouchTap}>
<p>{name}</p>
<div className="flex-bubble" onTouchTap={this.handleTouchTap} style={relationshipStyle} />
</div>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'middle', vertical: 'center'}}
targetOrigin={{horizontal: 'middle', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
animation={PopoverAnimationVertical}
>
<Menu>
<MenuItem primaryText="Add Activity" onClick={this.handleAddActivityOpen} />
<Link to={`/relationships/user/${loggedInUser.id}/rel/${relationship.id}`}><MenuItem primaryText="View Activity History" /></Link>
<MenuItem primaryText="Edit Relationship" onClick={this.handleEditActivityOpen} />
</Menu>
</Popover>
<Dialog
title={`Add an activity for ${relationship.name}`}
actions={addActivityActions}
modal={false}
open={this.state.modalOpen}
onRequestClose={this.handleAddActivityClose}
>
{this.renderModalContent()}
</Dialog>
</div>
);
}
}
/* ----------------- CONTAINER ------------------ */
const mapStateToProps = (state) => {
return {};
};
const mapDispatchToProps = (dispatch) => {
return {};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(SingleRelationship);
|
fixtures/attribute-behavior/src/index.js
|
nhunzaker/react
|
import './index.css';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
tests/routes/Login/components/Login.spec.js
|
willthefirst/book-buddy
|
// import React from 'react'
// import { bindActionCreators } from 'redux'
// import { Login } from 'routes/Login/components/Login'
// import { shallow } from 'enzyme'
//
// describe('(Component) Login', () => {
// let _props, _spies, _wrapper
// beforeEach(() => {
// _spies = {}
// _props = {
// ...bindActionCreators({
// handleLogin : (_spies.handleLogin = sinon.spy()),
// handleSubmit : (_spies.handleSubmit = sinon.spy())
// }, _spies.dispatch = sinon.spy())
// }
// _wrapper = shallow(<Login {..._props} />)
// })
//
// it('Should render as a <div>.', () => {
// expect(_wrapper.is('div')).to.equal(true)
// })
//
// it('Should render exactly one form.', () => {
// expect(_wrapper.find('Form')).to.have.length(1)
// })
//
// describe('Login submit button', () => {
// let _button
//
// beforeEach(() => {
// _button = _wrapper.find('Button').filterWhere(button => button.props().type === 'submit')
// })
//
// it('Should dispatch a `handleSubmit` action when clicked', () => {
// _spies.dispatch.should.have.not.been.called
//
// _button.simulate('click')
//
// _spies.dispatch.should.have.been.called
// _spies.handleSubmit.should.have.been.called
// // // _spies.handleLogin.should.have.been.called
// })
// })
// })
|
client/src/pages/Routes/Routes.js
|
patferguson/solitaire-react
|
import React, { Component } from 'react';
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import App from '../App'
import NotFound from '../NotFound'
import Home from '../Home'
import About from '../About'
import Testing from '../Testing'
class Routes extends Component {
render() {
return (
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="about" component={About}/>
<Route path="testing" component={Testing}/>
<Route path="*" component={NotFound}/>
</Route>
</Router>
);
}
}
export default Routes;
|
src/components/Common/AddressInput.spec.js
|
oraclesorg/ico-wizard
|
import React from 'react'
import { AddressInput } from './AddressInput'
import { TEXT_FIELDS, VALIDATION_MESSAGES, VALIDATION_TYPES } from '../../utils/constants'
import renderer from 'react-test-renderer'
import Adapter from 'enzyme-adapter-react-15'
import { configure, mount } from 'enzyme'
configure({ adapter: new Adapter() })
describe('AddressInput', () => {
it('Should render the component', () => {
const state = {
walletAddress: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
pristine: true,
valid: VALIDATION_TYPES.VALID,
}
const component = renderer.create(
<AddressInput
side="left"
title={TEXT_FIELDS.WALLET_ADDRESS}
address={state.walletAddress}
valid={state.valid}
pristine={state.pristine}
errorMessage={VALIDATION_MESSAGES.WALLET_ADDRESS}
onChange={jest.fn()}
description="Where the money goes after investors transactions. Immediately after each transaction. We
recommend to setup a multisig wallet with hardware based signers."
/>
)
expect(component.toJSON()).toMatchSnapshot()
})
it('Should fail if address is invalid', () => {
const onChange = jest.fn()
const state = {
walletAddress: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
pristine: true,
valid: VALIDATION_TYPES.VALID,
}
const wrapper = mount(
<AddressInput
side="left"
title={TEXT_FIELDS.WALLET_ADDRESS}
address={state.walletAddress}
valid={state.valid}
pristine={state.pristine}
errorMessage={VALIDATION_MESSAGES.WALLET_ADDRESS}
onChange={onChange}
description="Where the money goes after investors transactions. Immediately after each transaction. We
recommend to setup a multisig wallet with hardware based signers."
/>
)
const newAddress = 'abc'
wrapper.find('input[type="text"]').simulate('change', { target: { value: newAddress } })
expect(onChange).toHaveBeenCalled()
expect(onChange).toHaveBeenCalledWith({
address: newAddress,
pristine: false,
valid: VALIDATION_TYPES.INVALID,
})
})
it('Should pass if the new address is valid', () => {
const onChange = jest.fn()
const state = {
walletAddress: '0x90f8bf6a479f320ead074411a4b0e7944ea8c9c1',
pristine: true,
valid: VALIDATION_TYPES.VALID,
}
const wrapper = mount(
<AddressInput
side="left"
title={TEXT_FIELDS.WALLET_ADDRESS}
address={state.walletAddress}
valid={state.valid}
pristine={state.pristine}
errorMessage={VALIDATION_MESSAGES.WALLET_ADDRESS}
onChange={onChange}
description="Where the money goes after investors transactions. Immediately after each transaction. We
recommend to setup a multisig wallet with hardware based signers."
/>
)
const newAddress = '0xffcf8fdee72ac11b5c542428b35eef5769c409f0'
wrapper.find('input[type="text"]').simulate('change', { target: { value: newAddress } })
expect(onChange).toHaveBeenCalled()
expect(onChange).toHaveBeenCalledWith({
address: newAddress,
pristine: false,
valid: VALIDATION_TYPES.VALID,
})
})
})
|
app/jsx/external_apps/components/AppDetails.js
|
venturehive/canvas-lms
|
/*
* Copyright (C) 2014 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas 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 Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import I18n from 'i18n!external_tools'
import React from 'react'
import PropTypes from 'prop-types'
import page from 'page'
import Header from 'jsx/external_apps/components/Header'
import AddApp from 'jsx/external_apps/components/AddApp'
import 'compiled/jquery.rails_flash_notifications'
export default React.createClass({
displayName: 'AppDetails',
propTypes: {
store: PropTypes.object.isRequired,
baseUrl: PropTypes.string.isRequired,
shortName: PropTypes.string.isRequired
},
getInitialState() {
return {
app: null
}
},
componentDidMount() {
var app = this.props.store.findAppByShortName(this.props.shortName);
if (app) {
this.setState({ app: app });
} else {
page('/');
}
},
handleToolInstalled() {
var app = this.state.app;
app.is_installed = true;
this.setState({ app: app });
this.props.store.flagAppAsInstalled(app.short_name);
this.props.store.setState({filter: 'installed', filterText: ''});
$.flashMessage(I18n.t('The app was added successfully'));
page('/');
},
alreadyInstalled() {
if (this.state.app.is_installed) {
return <div className="gray-box-centered">{I18n.t('Installed')}</div>;
}
},
render() {
if (!this.state.app) {
return <img src="/images/ajax-loader-linear.gif" />;
}
return (
<div className="AppDetails">
<Header>
<a href={`${this.props.baseUrl}/configurations`} className="btn view_tools_link lm pull-right">{I18n.t('View App Configurations')}</a>
<a href={this.props.baseUrl} className="btn view_tools_link lm pull-right">{I18n.t('View App Center')}</a>
</Header>
<div className="app_full">
<table className="individual-app">
<tbody>
<tr>
<td className="individual-app-left" valign="top">
<div className="app">
<img className="img-polaroid" src={this.state.app.banner_image_url} />
{this.alreadyInstalled()}
</div>
<AddApp ref="addAppButton" app={this.state.app} handleToolInstalled={this.handleToolInstalled} />
<a href={this.props.baseUrl} className="app_cancel">« {I18n.t('Back to App Center')}</a>
</td>
<td className="individual-app-right" valign="top">
<h2 ref="appName">{this.state.app.name}</h2>
<p ref="appDescription" dangerouslySetInnerHTML={{__html: this.state.app.description}} />
</td>
</tr>
</tbody>
</table>
</div>
</div>
)
}
});
|
js/Search.js
|
aramay/complete-intro-to-react-v2
|
import React from 'react'
import ShowCard from './ShowCard'
import Header from './Header'
import { connect } from 'react-redux'
const { arrayOf, shape, string } = React.PropTypes
// import preload from '../public/data.json'
const Search = React.createClass({
propTypes: {
shows: arrayOf(shape({
title: string,
description: string
})),
searchTerm: string
},
// getInitialState () {
// return {
// searchTerm: ''
// }
// },
// handleSearchTermChange (event) {
// this.setState({
// searchTerm: event.target.value
// })
// },
render () {
return (
<div className='search'>
<Header showSearch />
<div>
{this.props.shows
.filter( (show) => {
return `${show.title} ${show.description}`.toUpperCase().indexOf(this.props.searchTerm.toUpperCase()) >= 0
})
.map((show) => {
return (
// <ShowCard key={show.imdbID} show={show} />
<ShowCard key={show.imdbID} {...show} />
)
})}
</div>
</div>
)
}
})
const mapStateToProps = (state) => {
return {
searchTerm: state.searchTerm
}
}
export default connect(mapStateToProps)(Search)
|
app/index.js
|
fullPistol/React-demo
|
import React from 'react';
import {render} from 'react-dom';
import App from './js/containers/App';
import './css/reset.css'
import './css/index.less';
render(
<App />,
document.getElementById('root')
);
|
src/svg-icons/image/photo-size-select-small.js
|
matthewoates/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoSizeSelectSmall = (props) => (
<SvgIcon {...props}>
<path d="M23 15h-2v2h2v-2zm0-4h-2v2h2v-2zm0 8h-2v2c1 0 2-1 2-2zM15 3h-2v2h2V3zm8 4h-2v2h2V7zm-2-4v2h2c0-1-1-2-2-2zM3 21h8v-6H1v4c0 1.1.9 2 2 2zM3 7H1v2h2V7zm12 12h-2v2h2v-2zm4-16h-2v2h2V3zm0 16h-2v2h2v-2zM3 3C2 3 1 4 1 5h2V3zm0 8H1v2h2v-2zm8-8H9v2h2V3zM7 3H5v2h2V3z"/>
</SvgIcon>
);
ImagePhotoSizeSelectSmall = pure(ImagePhotoSizeSelectSmall);
ImagePhotoSizeSelectSmall.displayName = 'ImagePhotoSizeSelectSmall';
ImagePhotoSizeSelectSmall.muiName = 'SvgIcon';
export default ImagePhotoSizeSelectSmall;
|
packages/ui-toolkit/src/styleguide/tabs.js
|
geek/joyent-portal
|
import React from 'react';
import PropTypes from 'prop-types';
import Styled from 'react-styleguidist/lib/rsg-components/Styled';
import cx from 'classnames';
export const styles = ({
space,
color,
fontFamily,
fontSize,
buttonTextTransform
}) => ({
button: {
padding: [[space[1], 0]],
fontFamily: fontFamily.base,
fontSize: fontSize.base,
color: color.light,
background: 'transparent',
textTransform: buttonTextTransform,
transition: 'color 750ms ease-out',
border: 'none',
cursor: 'pointer',
'&:hover, &:focus': {
isolate: false,
outline: 0,
color: color.linkHover,
transition: 'color 150ms ease-in'
},
'&:focus:not($isActive)': {
isolate: false,
outline: [[1, 'dotted', color.linkHover]]
},
'& + &': {
isolate: false,
marginLeft: space[1]
}
},
isActive: {
borderBottom: [[2, color.linkHover, 'solid']]
}
});
export function TabButtonRenderer({
classes,
name,
className,
onClick,
active,
children
}) {
const classNames = cx(classes.button, className, {
[classes.isActive]: active
});
return (
<button type="button" name={name} className={classNames} onClick={onClick}>
{children}
</button>
);
}
TabButtonRenderer.propTypes = {
classes: PropTypes.object.isRequired,
name: PropTypes.string,
className: PropTypes.string,
onClick: PropTypes.func,
active: PropTypes.bool,
children: PropTypes.node
};
export default Styled(styles)(TabButtonRenderer);
|
test/test_helper.js
|
quebez/react_todolist
|
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/components/error-screen.js
|
gitpoint/git-point
|
import React, { Component } from 'react';
import { colors, fonts, normalize } from 'config';
import { t } from 'utils';
import styled from 'styled-components';
const ViewWrapper = styled.View`
align-items: center;
align-content: center;
height: 100%;
justify-content: center;
`;
const TextStyled = styled.Text`
color: ${colors.white};
${fonts.fontPrimaryBold};
font-size: ${normalize(20)};
text-align: center;
width: 80%;
`;
type Props = {
locale: string,
};
export class ErrorScreen extends Component {
props: Props;
render() {
return (
<ViewWrapper>
<TextStyled>
{t(
'Oops! it seems that you are not connected to the internet!',
this.props.locale
)}
</TextStyled>
</ViewWrapper>
);
}
}
|
src/component/Template.js
|
NHAAHNA/hms
|
import React, { Component } from 'react';
import '../containers/App.css';
export default class Template extends Component{
render(){
return(
<div className="container">
<div className="row">
<div className="col-md-12 twelveDiv">
<h2>12 </h2>
</div>
</div>
<div className="row"><hr/></div>
<div className="row">
<div className="col-md-8 eightDiv">
<h2>8</h2>
</div>
<div className="col-md-4 fourDiv">
<h2>4</h2>
</div>
</div>
</div>
)
}
}
|
src/components/Bottom/Bottom.js
|
Zoomdata/nhtsa-dashboard-2.2
|
import styles from './Bottom.css';
import React from 'react';
import image from '../../images/slot-bottom.png'
const Bottom = () => {
return (
<img
className={styles.root}
width="120" height="3.5"
src={image}
/>
)
};
export default Bottom;
|
src/index.js
|
yfruan/react-simple
|
import React from 'react';
import ReactDom from 'react-dom';
import App from 'app';
ReactDom.render(
<App />,
document.getElementById('content')
);
|
examples/redirect-using-index/app.js
|
okcoker/react-router
|
import React from 'react';
import { Router, Route, IndexRoute, Link } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
{this.props.children}
</div>
);
}
});
var Index = React.createClass({
render () {
return (
<div>
<h1>You should not see this.</h1>
{this.props.children}
</div>
)
}
});
var Child = React.createClass({
render () {
return (
<div>
<h2>Redirected to "/child"</h2>
<Link to="/">Try going to "/"</Link>
</div>
)
}
});
function redirectToChild(location, replaceWith) {
replaceWith(null, '/child');
}
React.render((
<Router>
<Route path="/" component={App}>
<IndexRoute component={Index} onEnter={redirectToChild}/>
<Route path="/child" component={Child}/>
</Route>
</Router>
), document.getElementById('example'));
|
src/svg-icons/action/perm-phone-msg.js
|
pomerantsev/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermPhoneMsg = (props) => (
<SvgIcon {...props}>
<path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/>
</SvgIcon>
);
ActionPermPhoneMsg = pure(ActionPermPhoneMsg);
ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg';
ActionPermPhoneMsg.muiName = 'SvgIcon';
export default ActionPermPhoneMsg;
|
client/src/javascript/components/icons/Ratio.js
|
jfurrow/flood
|
import React from 'react';
import BaseIcon from './BaseIcon';
export default class Ratio extends BaseIcon {
render() {
return (
<svg className={`icon icon--ratio ${this.props.className}`} viewBox={this.getViewBox()}>
<path d="M54.57,15.76a28.56,28.56,0,1,0-10.45,39A28.56,28.56,0,0,0,54.57,15.76ZM9.68,41.86a23.36,23.36,0,1,1,40.39-23.5C40.72,29.74,24.32,39.36,9.68,41.86Z" />
</svg>
);
}
}
|
src/svg-icons/editor/format-paint.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatPaint = (props) => (
<SvgIcon {...props}>
<path d="M18 4V3c0-.55-.45-1-1-1H5c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6h1v4H9v11c0 .55.45 1 1 1h2c.55 0 1-.45 1-1v-9h8V4h-3z"/>
</SvgIcon>
);
EditorFormatPaint = pure(EditorFormatPaint);
EditorFormatPaint.displayName = 'EditorFormatPaint';
export default EditorFormatPaint;
|
public/jspm_packages/npm/react-router@2.0.0/modules/Redirect.js
|
nayashooter/ES6_React-Bootstrap
|
/* */
"format cjs";
import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { formatPattern } from './PatternUtils'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* A <Redirect> is used to declare another URL path a client should
* be sent to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration
* and are traversed in the same manner.
*/
const Redirect = React.createClass({
statics: {
createRouteFromReactElement(element) {
const route = createRouteFromReactElement(element)
if (route.from)
route.path = route.from
route.onEnter = function (nextState, replace) {
const { location, params } = nextState
let pathname
if (route.to.charAt(0) === '/') {
pathname = formatPattern(route.to, params)
} else if (!route.to) {
pathname = location.pathname
} else {
let routeIndex = nextState.routes.indexOf(route)
let parentPattern = Redirect.getRoutePattern(nextState.routes, routeIndex - 1)
let pattern = parentPattern.replace(/\/*$/, '/') + route.to
pathname = formatPattern(pattern, params)
}
replace({
pathname,
query: route.query || location.query,
state: route.state || location.state
})
}
return route
},
getRoutePattern(routes, routeIndex) {
let parentPattern = ''
for (let i = routeIndex; i >= 0; i--) {
const route = routes[i]
const pattern = route.path || ''
parentPattern = pattern.replace(/\/*$/, '/') + parentPattern
if (pattern.indexOf('/') === 0)
break
}
return '/' + parentPattern
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render() {
invariant(
false,
'<Redirect> elements are for router configuration only and should not be rendered'
)
}
})
export default Redirect
|
src/svg-icons/file/cloud-off.js
|
ngbrown/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCloudOff = (props) => (
<SvgIcon {...props}>
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4c-1.48 0-2.85.43-4.01 1.17l1.46 1.46C10.21 6.23 11.08 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3 0 1.13-.64 2.11-1.56 2.62l1.45 1.45C23.16 18.16 24 16.68 24 15c0-2.64-2.05-4.78-4.65-4.96zM3 5.27l2.75 2.74C2.56 8.15 0 10.77 0 14c0 3.31 2.69 6 6 6h11.73l2 2L21 20.73 4.27 4 3 5.27zM7.73 10l8 8H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h1.73z"/>
</SvgIcon>
);
FileCloudOff = pure(FileCloudOff);
FileCloudOff.displayName = 'FileCloudOff';
FileCloudOff.muiName = 'SvgIcon';
export default FileCloudOff;
|
packages/react-dom/src/server/ReactPartialRenderer.js
|
anushreesubramani/react
|
/**
* Copyright (c) 2013-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.
*
* @flow
*/
import type {ReactElement} from 'shared/ReactElementType';
import React from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import emptyObject from 'fbjs/lib/emptyObject';
import hyphenateStyleName from 'fbjs/lib/hyphenateStyleName';
import invariant from 'fbjs/lib/invariant';
import memoizeStringOnly from 'fbjs/lib/memoizeStringOnly';
import warning from 'fbjs/lib/warning';
import checkPropTypes from 'prop-types/checkPropTypes';
import describeComponentFrame from 'shared/describeComponentFrame';
import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
import {
REACT_FRAGMENT_TYPE,
REACT_CALL_TYPE,
REACT_RETURN_TYPE,
REACT_PORTAL_TYPE,
} from 'shared/ReactSymbols';
import {
createMarkupForCustomAttribute,
createMarkupForProperty,
createMarkupForRoot,
} from './DOMMarkupOperations';
import escapeTextForBrowser from './escapeTextForBrowser';
import {
Namespaces,
getIntrinsicNamespace,
getChildNamespace,
} from '../shared/DOMNamespaces';
import ReactControlledValuePropTypes from '../shared/ReactControlledValuePropTypes';
import assertValidProps from '../shared/assertValidProps';
import dangerousStyleValue from '../shared/dangerousStyleValue';
import isCustomComponent from '../shared/isCustomComponent';
import omittedCloseTags from '../shared/omittedCloseTags';
import warnValidStyle from '../shared/warnValidStyle';
import {validateProperties as validateARIAProperties} from '../shared/ReactDOMInvalidARIAHook';
import {validateProperties as validateInputProperties} from '../shared/ReactDOMNullInputValuePropHook';
import {validateProperties as validateUnknownProperties} from '../shared/ReactDOMUnknownPropertyHook';
// Based on reading the React.Children implementation. TODO: type this somewhere?
type ReactNode = string | number | ReactElement;
type FlatReactChildren = Array<null | ReactNode>;
type toArrayType = (children: mixed) => FlatReactChildren;
var toArray = ((React.Children.toArray: any): toArrayType);
var getStackAddendum = emptyFunction.thatReturns('');
if (__DEV__) {
var validatePropertiesInDevelopment = function(type, props) {
validateARIAProperties(type, props);
validateInputProperties(type, props);
validateUnknownProperties(type, props, /* canUseEventSystem */ false);
};
var describeStackFrame = function(element): string {
var source = element._source;
var type = element.type;
var name = getComponentName(type);
var ownerName = null;
return describeComponentFrame(name, source, ownerName);
};
var currentDebugStack = null;
var currentDebugElementStack = null;
var setCurrentDebugStack = function(stack: Array<Frame>) {
var frame: Frame = stack[stack.length - 1];
currentDebugElementStack = ((frame: any): FrameDev).debugElementStack;
// We are about to enter a new composite stack, reset the array.
currentDebugElementStack.length = 0;
currentDebugStack = stack;
ReactDebugCurrentFrame.getCurrentStack = getStackAddendum;
};
var pushElementToDebugStack = function(element: ReactElement) {
if (currentDebugElementStack !== null) {
currentDebugElementStack.push(element);
}
};
var resetCurrentDebugStack = function() {
currentDebugElementStack = null;
currentDebugStack = null;
ReactDebugCurrentFrame.getCurrentStack = null;
};
getStackAddendum = function(): null | string {
if (currentDebugStack === null) {
return '';
}
let stack = '';
let debugStack = currentDebugStack;
for (let i = debugStack.length - 1; i >= 0; i--) {
const frame: Frame = debugStack[i];
let debugElementStack = ((frame: any): FrameDev).debugElementStack;
for (let ii = debugElementStack.length - 1; ii >= 0; ii--) {
stack += describeStackFrame(debugElementStack[ii]);
}
}
return stack;
};
}
var didWarnDefaultInputValue = false;
var didWarnDefaultChecked = false;
var didWarnDefaultSelectValue = false;
var didWarnDefaultTextareaValue = false;
var didWarnInvalidOptionChildren = false;
var didWarnAboutNoopUpdateForComponent = {};
var valuePropNames = ['value', 'defaultValue'];
var newlineEatingTags = {
listing: true,
pre: true,
textarea: true,
};
function getComponentName(type) {
return typeof type === 'string'
? type
: typeof type === 'function' ? type.displayName || type.name : null;
}
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
function validateDangerousTag(tag) {
if (!validatedTagCache.hasOwnProperty(tag)) {
invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag);
validatedTagCache[tag] = true;
}
}
var processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
function createMarkupForStyles(styles): string | null {
var serialized = '';
var delimiter = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var isCustomProperty = styleName.indexOf('--') === 0;
var styleValue = styles[styleName];
if (__DEV__) {
if (!isCustomProperty) {
warnValidStyle(styleName, styleValue, getStackAddendum);
}
}
if (styleValue != null) {
serialized += delimiter + processStyleName(styleName) + ':';
serialized += dangerousStyleValue(
styleName,
styleValue,
isCustomProperty,
);
delimiter = ';';
}
}
return serialized || null;
}
function warnNoop(
publicInstance: React$Component<any, any>,
callerName: string,
) {
if (__DEV__) {
var constructor = publicInstance.constructor;
const componentName =
(constructor && getComponentName(constructor)) || 'ReactClass';
const warningKey = `${componentName}.${callerName}`;
if (didWarnAboutNoopUpdateForComponent[warningKey]) {
return;
}
warning(
false,
'%s(...): Can only update a mounting component. ' +
'This usually means you called %s() outside componentWillMount() on the server. ' +
'This is a no-op.\n\nPlease check the code for the %s component.',
callerName,
callerName,
componentName,
);
didWarnAboutNoopUpdateForComponent[warningKey] = true;
}
}
function shouldConstruct(Component) {
return Component.prototype && Component.prototype.isReactComponent;
}
function getNonChildrenInnerMarkup(props) {
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var content = props.children;
if (typeof content === 'string' || typeof content === 'number') {
return escapeTextForBrowser(content);
}
}
return null;
}
function flattenTopLevelChildren(children: mixed): FlatReactChildren {
if (!React.isValidElement(children)) {
return toArray(children);
}
const element = ((children: any): ReactElement);
if (element.type !== REACT_FRAGMENT_TYPE) {
return [element];
}
const fragmentChildren = element.props.children;
if (!React.isValidElement(fragmentChildren)) {
return toArray(fragmentChildren);
}
const fragmentChildElement = ((fragmentChildren: any): ReactElement);
return [fragmentChildElement];
}
function flattenOptionChildren(children: mixed): string {
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
React.Children.forEach(children, function(child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else {
if (__DEV__) {
if (!didWarnInvalidOptionChildren) {
didWarnInvalidOptionChildren = true;
warning(
false,
'Only strings and numbers are supported as <option> children.',
);
}
}
}
});
return content;
}
function maskContext(type, context) {
var contextTypes = type.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
}
function checkContextTypes(typeSpecs, values, location: string) {
if (__DEV__) {
checkPropTypes(typeSpecs, values, location, 'Component', getStackAddendum);
}
}
function processContext(type, context) {
var maskedContext = maskContext(type, context);
if (__DEV__) {
if (type.contextTypes) {
checkContextTypes(type.contextTypes, maskedContext, 'context');
}
}
return maskedContext;
}
var STYLE = 'style';
var RESERVED_PROPS = {
children: null,
dangerouslySetInnerHTML: null,
suppressContentEditableWarning: null,
suppressHydrationWarning: null,
};
function createOpenTagMarkup(
tagVerbatim: string,
tagLowercase: string,
props: Object,
namespace: string,
makeStaticMarkup: boolean,
isRootElement: boolean,
): string {
var ret = '<' + tagVerbatim;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (propKey === STYLE) {
propValue = createMarkupForStyles(propValue);
}
var markup = null;
if (isCustomComponent(tagLowercase, props)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
markup = createMarkupForCustomAttribute(propKey, propValue);
}
} else {
markup = createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (makeStaticMarkup) {
return ret;
}
if (isRootElement) {
ret += ' ' + createMarkupForRoot();
}
return ret;
}
function validateRenderResult(child, type) {
if (child === undefined) {
invariant(
false,
'%s(...): Nothing was returned from render. This usually means a ' +
'return statement is missing. Or, to render nothing, ' +
'return null.',
getComponentName(type) || 'Component',
);
}
}
function resolve(
child: mixed,
context: Object,
): {|
child: mixed,
context: Object,
|} {
while (React.isValidElement(child)) {
// Safe because we just checked it's an element.
var element: ReactElement = ((child: any): ReactElement);
if (__DEV__) {
pushElementToDebugStack(element);
}
var Component = element.type;
if (typeof Component !== 'function') {
break;
}
var publicContext = processContext(Component, context);
var inst;
var queue = [];
var replace = false;
var updater = {
isMounted: function(publicInstance) {
return false;
},
enqueueForceUpdate: function(publicInstance) {
if (queue === null) {
warnNoop(publicInstance, 'forceUpdate');
return null;
}
},
enqueueReplaceState: function(publicInstance, completeState) {
replace = true;
queue = [completeState];
},
enqueueSetState: function(publicInstance, partialState) {
if (queue === null) {
warnNoop(publicInstance, 'setState');
return null;
}
queue.push(partialState);
},
};
if (shouldConstruct(Component)) {
inst = new Component(element.props, publicContext, updater);
} else {
inst = Component(element.props, publicContext, updater);
if (inst == null || inst.render == null) {
child = inst;
validateRenderResult(child, Component);
continue;
}
}
inst.props = element.props;
inst.context = publicContext;
inst.updater = updater;
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
if (inst.componentWillMount) {
inst.componentWillMount();
if (queue.length) {
var oldQueue = queue;
var oldReplace = replace;
queue = null;
replace = false;
if (oldReplace && oldQueue.length === 1) {
inst.state = oldQueue[0];
} else {
var nextState = oldReplace ? oldQueue[0] : inst.state;
var dontMutate = true;
for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
var partial = oldQueue[i];
var partialState =
typeof partial === 'function'
? partial.call(inst, nextState, element.props, publicContext)
: partial;
if (partialState) {
if (dontMutate) {
dontMutate = false;
nextState = Object.assign({}, nextState, partialState);
} else {
Object.assign(nextState, partialState);
}
}
}
inst.state = nextState;
}
} else {
queue = null;
}
}
child = inst.render();
if (__DEV__) {
if (child === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
child = null;
}
}
validateRenderResult(child, Component);
var childContext;
if (typeof inst.getChildContext === 'function') {
var childContextTypes = Component.childContextTypes;
if (typeof childContextTypes === 'object') {
childContext = inst.getChildContext();
for (let contextKey in childContext) {
invariant(
contextKey in childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
getComponentName(Component) || 'Unknown',
contextKey,
);
}
} else {
warning(
false,
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
getComponentName(Component) || 'Unknown',
);
}
}
if (childContext) {
context = Object.assign({}, context, childContext);
}
}
return {child, context};
}
type Frame = {
domNamespace: string,
children: FlatReactChildren,
childIndex: number,
context: Object,
footer: string,
};
type FrameDev = Frame & {
debugElementStack: Array<ReactElement>,
};
class ReactDOMServerRenderer {
stack: Array<Frame>;
exhausted: boolean;
// TODO: type this more strictly:
currentSelectValue: any;
previousWasTextNode: boolean;
makeStaticMarkup: boolean;
constructor(children: mixed, makeStaticMarkup: boolean) {
const flatChildren = flattenTopLevelChildren(children);
var topFrame: Frame = {
// Assume all trees start in the HTML namespace (not totally true, but
// this is what we did historically)
domNamespace: Namespaces.html,
children: flatChildren,
childIndex: 0,
context: emptyObject,
footer: '',
};
if (__DEV__) {
((topFrame: any): FrameDev).debugElementStack = [];
}
this.stack = [topFrame];
this.exhausted = false;
this.currentSelectValue = null;
this.previousWasTextNode = false;
this.makeStaticMarkup = makeStaticMarkup;
}
read(bytes: number): string | null {
if (this.exhausted) {
return null;
}
var out = '';
while (out.length < bytes) {
if (this.stack.length === 0) {
this.exhausted = true;
break;
}
var frame: Frame = this.stack[this.stack.length - 1];
if (frame.childIndex >= frame.children.length) {
var footer = frame.footer;
out += footer;
if (footer !== '') {
this.previousWasTextNode = false;
}
this.stack.pop();
if (frame.tag === 'select') {
this.currentSelectValue = null;
}
continue;
}
var child = frame.children[frame.childIndex++];
if (__DEV__) {
setCurrentDebugStack(this.stack);
}
out += this.render(child, frame.context, frame.domNamespace);
if (__DEV__) {
// TODO: Handle reentrant server render calls. This doesn't.
resetCurrentDebugStack();
}
}
return out;
}
render(
child: ReactNode | null,
context: Object,
parentNamespace: string,
): string {
if (typeof child === 'string' || typeof child === 'number') {
var text = '' + child;
if (text === '') {
return '';
}
if (this.makeStaticMarkup) {
return escapeTextForBrowser(text);
}
if (this.previousWasTextNode) {
return '<!-- -->' + escapeTextForBrowser(text);
}
this.previousWasTextNode = true;
return escapeTextForBrowser(text);
} else {
var nextChild;
({child: nextChild, context} = resolve(child, context));
if (nextChild === null || nextChild === false) {
return '';
} else if (!React.isValidElement(nextChild)) {
if (nextChild != null && nextChild.$$typeof != null) {
// Catch unexpected special types early.
const $$typeof = nextChild.$$typeof;
invariant(
$$typeof !== REACT_PORTAL_TYPE,
'Portals are not currently supported by the server renderer. ' +
'Render them conditionally so that they only appear on the client render.',
);
invariant(
$$typeof !== REACT_CALL_TYPE && $$typeof !== REACT_RETURN_TYPE,
'The experimental Call and Return types are not currently ' +
'supported by the server renderer.',
);
// Catch-all to prevent an infinite loop if React.Children.toArray() supports some new type.
invariant(
false,
'Unknown element-like object type: %s. This is likely a bug in React. ' +
'Please file an issue.',
($$typeof: any).toString(),
);
}
const nextChildren = toArray(nextChild);
const frame: Frame = {
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
} else if (
((nextChild: any): ReactElement).type === REACT_FRAGMENT_TYPE
) {
const nextChildren = toArray(
((nextChild: any): ReactElement).props.children,
);
const frame: Frame = {
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
} else {
// Safe because we just checked it's an element.
var nextElement = ((nextChild: any): ReactElement);
return this.renderDOM(nextElement, context, parentNamespace);
}
}
}
renderDOM(
element: ReactElement,
context: Object,
parentNamespace: string,
): string {
var tag = element.type.toLowerCase();
let namespace = parentNamespace;
if (parentNamespace === Namespaces.html) {
namespace = getIntrinsicNamespace(tag);
}
if (__DEV__) {
if (namespace === Namespaces.html) {
// Should this check be gated by parent namespace? Not sure we want to
// allow <SVG> or <mATH>.
warning(
tag === element.type,
'<%s /> is using uppercase HTML. Always use lowercase HTML tags ' +
'in React.',
element.type,
);
}
}
validateDangerousTag(tag);
var props = element.props;
if (tag === 'input') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'input',
props,
getStackAddendum,
);
if (
props.checked !== undefined &&
props.defaultChecked !== undefined &&
!didWarnDefaultChecked
) {
warning(
false,
'%s contains an input of type %s with both checked and defaultChecked props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the checked prop, or the defaultChecked prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
'A component',
props.type,
);
didWarnDefaultChecked = true;
}
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultInputValue
) {
warning(
false,
'%s contains an input of type %s with both value and defaultValue props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
'A component',
props.type,
);
didWarnDefaultInputValue = true;
}
}
props = Object.assign(
{
type: undefined,
},
props,
{
defaultChecked: undefined,
defaultValue: undefined,
value: props.value != null ? props.value : props.defaultValue,
checked: props.checked != null ? props.checked : props.defaultChecked,
},
);
} else if (tag === 'textarea') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'textarea',
props,
getStackAddendum,
);
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultTextareaValue
) {
warning(
false,
'Textarea elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled textarea ' +
'and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
didWarnDefaultTextareaValue = true;
}
}
var initialValue = props.value;
if (initialValue == null) {
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var textareaChildren = props.children;
if (textareaChildren != null) {
if (__DEV__) {
warning(
false,
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.',
);
}
invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.',
);
if (Array.isArray(textareaChildren)) {
invariant(
textareaChildren.length <= 1,
'<textarea> can only have at most one child.',
);
textareaChildren = textareaChildren[0];
}
defaultValue = '' + textareaChildren;
}
if (defaultValue == null) {
defaultValue = '';
}
initialValue = defaultValue;
}
props = Object.assign({}, props, {
value: undefined,
children: '' + initialValue,
});
} else if (tag === 'select') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'select',
props,
getStackAddendum,
);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
var isArray = Array.isArray(props[propName]);
if (props.multiple && !isArray) {
warning(
false,
'The `%s` prop supplied to <select> must be an array if ' +
'`multiple` is true.%s',
propName,
'', // getDeclarationErrorAddendum(),
);
} else if (!props.multiple && isArray) {
warning(
false,
'The `%s` prop supplied to <select> must be a scalar ' +
'value if `multiple` is false.%s',
propName,
'', // getDeclarationErrorAddendum(),
);
}
}
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultSelectValue
) {
warning(
false,
'Select elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled select ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
didWarnDefaultSelectValue = true;
}
}
this.currentSelectValue =
props.value != null ? props.value : props.defaultValue;
props = Object.assign({}, props, {
value: undefined,
});
} else if (tag === 'option') {
var selected = null;
var selectValue = this.currentSelectValue;
var optionChildren = flattenOptionChildren(props.children);
if (selectValue != null) {
var value;
if (props.value != null) {
value = props.value + '';
} else {
value = optionChildren;
}
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var j = 0; j < selectValue.length; j++) {
if ('' + selectValue[j] === value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === value;
}
props = Object.assign(
{
selected: undefined,
children: undefined,
},
props,
{
selected: selected,
children: optionChildren,
},
);
}
}
if (__DEV__) {
validatePropertiesInDevelopment(tag, props);
}
assertValidProps(tag, props, getStackAddendum);
var out = createOpenTagMarkup(
element.type,
tag,
props,
namespace,
this.makeStaticMarkup,
this.stack.length === 1,
);
var footer = '';
if (omittedCloseTags.hasOwnProperty(tag)) {
out += '/>';
} else {
out += '>';
footer = '</' + element.type + '>';
}
var children;
var innerMarkup = getNonChildrenInnerMarkup(props);
if (innerMarkup != null) {
children = [];
if (newlineEatingTags[tag] && innerMarkup.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
out += '\n';
}
out += innerMarkup;
} else {
children = toArray(props.children);
}
var frame = {
domNamespace: getChildNamespace(parentNamespace, element.type),
tag,
children,
childIndex: 0,
context: context,
footer: footer,
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
this.previousWasTextNode = false;
return out;
}
}
export default ReactDOMServerRenderer;
|
node_modules/antd/es/input-number/index.js
|
prodigalyijun/demo-by-antd
|
import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var __rest = this && this.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
}return t;
};
import React from 'react';
import classNames from 'classnames';
import RcInputNumber from 'rc-input-number';
var InputNumber = function (_React$Component) {
_inherits(InputNumber, _React$Component);
function InputNumber() {
_classCallCheck(this, InputNumber);
return _possibleConstructorReturn(this, (InputNumber.__proto__ || Object.getPrototypeOf(InputNumber)).apply(this, arguments));
}
_createClass(InputNumber, [{
key: 'render',
value: function render() {
var _classNames;
var _a = this.props,
className = _a.className,
size = _a.size,
others = __rest(_a, ["className", "size"]);
var inputNumberClass = classNames((_classNames = {}, _defineProperty(_classNames, this.props.prefixCls + '-lg', size === 'large'), _defineProperty(_classNames, this.props.prefixCls + '-sm', size === 'small'), _classNames), className);
return React.createElement(RcInputNumber, _extends({ className: inputNumberClass }, others));
}
}]);
return InputNumber;
}(React.Component);
export default InputNumber;
InputNumber.defaultProps = {
prefixCls: 'ant-input-number',
step: 1
};
|
docs/src/app/components/pages/components/TextField/ExampleSimple.js
|
tan-jerene/material-ui
|
import React from 'react';
import TextField from 'material-ui/TextField';
const TextFieldExampleSimple = () => (
<div>
<TextField
hintText="Hint Text"
/><br />
<br />
<TextField
hintText="The hint text can be as long as you want, it will wrap."
/><br />
<TextField
id="text-field-default"
defaultValue="Default Value"
/><br />
<TextField
hintText="Hint Text"
floatingLabelText="Floating Label Text"
/><br />
<TextField
hintText="Hint Text"
floatingLabelText="Fixed Floating Label Text"
floatingLabelFixed={true}
/><br />
<TextField
hintText="Password Field"
floatingLabelText="Password"
type="password"
/><br />
<TextField
hintText="MultiLine with rows: 2 and rowsMax: 4"
multiLine={true}
rows={2}
rowsMax={4}
/><br />
<TextField
hintText="Message Field"
floatingLabelText="MultiLine and FloatingLabel"
multiLine={true}
rows={2}
/><br />
<TextField
hintText="Full width"
fullWidth={true}
/>
</div>
);
export default TextFieldExampleSimple;
|
src/CitySearchPanel.js
|
cqqccqc/city-picker
|
import React, { Component } from 'react';
import { List } from 'immutable';
import './CitySearchPanel.css';
const classnames = require('classnames');
class CitySearchPanel extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<div className="c_address_select">
<div className="c_address_wrap">
<div className="c_address_hd">h,按拼音排序</div>
<div className="c_address_list">
<a data="haerbin|哈尔滨|haerbin|哈尔滨|heb" style="display: block;" className="hover"><span>haerbin</span>哈尔滨</a>
<a data="haian|海安|haian|海安|ha" style="display: block;"><span>haian</span>海安</a>
<a data="haicheng|海城|haicheng|海城|hc" style="display: block;"><span>haicheng</span>海城</a>
<a data="haidong|海东|haidong|海东|hd" style="display: block;"><span>haidong</span>海东</a>
<a data="haifeng|海丰|haifeng|海丰|hf" style="display: block;"><span>haifeng</span>海丰</a>
<a data="haikou|海口|haikou|海口|hk" style="display: block;"><span>haikou</span>海口</a>
<a data="haimen|海门|haimen|海门|hm" style="display: block;"><span>haimen</span>海门</a>
<a data="haining|海宁|haining|海宁|hn" style="display: block;"><span>haining</span>海宁</a>
<a data="haixi|海西|haixi|海西|hx" style="display: block;"><span>haixi</span>海西</a>
<a data="haixing|海兴|haixing|海兴|hx" style="display: block;"><span>haixing</span>海兴</a>
<a data="haiyang|海阳|haiyang|海阳|hy" style="display: block;"><span>haiyang</span>海阳</a>
<a data="haiyuan2|海原|haiyuan2|海原|hy" style="display: block;"><span>haiyuan2</span>海原</a>
</div>
<div className="c_address_pagebreak" style="display: block;">
<a className="address_current" page="0">1</a>
<a page="1">2</a>
<a page="2">3</a>
<a page="3">4</a>
<a page="4">5</a>
<a page="1">-></a> </div>
</div>
</div>
</div>
);
}
}
export default CitySearchPanel;
|
src/components/DevIcon.js
|
abdulhannanali/github-organization-repos
|
import React from 'react';
import classnames from 'classnames';
const DevIcon = ({ language, colored, wikiLink }) => {
if (!language) {
throw new Error('`language` option is required for `DevIcon` component');
}
const devIconClasses = getDevIcon(language, colored);
let iTag = (<i className={devIconClasses} aria-hidden={true}></i>);
let devIconTag = iTag;
if (wikiLink) {
const wikiHref = `https://rosettacode.org/wiki/${language}`;
devIconTag = (
<a
href={wikiHref}
style={{ textDecoration: 'none' }}
aria-label={'Wiki for language ' + language}>{iTag}</a>
);
}
return (
<div className="DevIcon">
{devIconTag}
</div>
);
};
/**
* Gets the DevIcon for the given text
*/
function getDevIcon(language, colored = false) {
if (!language) {
return '';
}
language = language.toLowerCase();
/** Some languages that don't map well by default
* TODO: This should be ideally replaced with a better mechanism
* to better map languages to their correct representation.
*/
switch (language) {
case 'c#':
language = 'csharp';
break;
case 'c++':
language = 'cplusplus';
break;
default:
break;
}
return (
classnames('devicon-' + language + '-plain', {
colored,
})
);
}
export default DevIcon;
|
wrappers/html.js
|
dominictracey/dominictracey.com
|
import React from 'react'
module.exports = React.createClass({
propTypes () {
return {
router: React.PropTypes.object,
}
},
render () {
const post = this.props.route.page.data
return (
<div className="markdown">
<h1 dangerouslySetInnerHTML={{ __html: post.title }} />
<div dangerouslySetInnerHTML={{ __html: post.body }} />
</div>
)
},
})
|
src/js/pages/RegisterPage.js
|
nekuno/client
|
import { SOCIAL_NETWORKS_NAMES, FACEBOOK_SCOPE } from '../constants/Constants';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import FacebookButton from '../components/ui/FacebookButton';
import translate from '../i18n/Translate';
import connectToStores from '../utils/connectToStores';
import ConnectActionCreators from '../actions/ConnectActionCreators';
import * as GroupActionCreators from '../actions/GroupActionCreators';
import RouterActionCreators from '../actions/RouterActionCreators';
import LoginActionCreators from '../actions/LoginActionCreators';
import InvitationStore from '../stores/InvitationStore';
import RegisterStore from '../stores/RegisterStore';
import LocaleStore from '../stores/LocaleStore';
import SocialNetworkService from '../services/SocialNetworkService';
import Framework7Service from '../services/Framework7Service';
function getState(props) {
const error = InvitationStore.error;
const token = InvitationStore.token;
const profile = RegisterStore.profile;
const registerData = RegisterStore.getData();
const invitation = InvitationStore.invitation;
const interfaceLanguage = LocaleStore.locale;
return {
error,
token,
profile,
registerData,
invitation,
interfaceLanguage
};
}
@translate('RegisterPage')
@connectToStores([InvitationStore, LocaleStore], getState)
export default class RegisterPage extends Component {
static propTypes = {
// Injected by @translate:
strings : PropTypes.object,
// Injected by @connectToStores:
error : PropTypes.object,
token : PropTypes.string,
profile : PropTypes.object,
registerData : PropTypes.object,
invitation : PropTypes.object,
interfaceLanguage: PropTypes.string
};
static contextTypes = {
router: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.handleSocialNetwork = this.handleSocialNetwork.bind(this);
this._registerUser = this._registerUser.bind(this);
this.state = {
loginUser: false,
registeringUser: false,
initialToken: null
}
}
componentDidMount() {
const {location, token, profile, registerData} = this.props;
let initialToken = location.query && location.query.token ? location.query.token : null;
if (registerData && registerData.oauth) {
this.handleSocialNetwork(SOCIAL_NETWORKS_NAMES.FACEBOOK, FACEBOOK_SCOPE);
} else if (initialToken) {
this.setState({initialToken});
ConnectActionCreators.validateInvitation(initialToken);
} else if (!token && !profile) {
this.context.router.push('/');
}
}
handleSocialNetwork(resource, scope) {
const {token, invitation, interfaceLanguage, strings} = this.props;
this.setState({loginUser: true});
SocialNetworkService.login(resource, scope, true).then(() => {
const oauthData = SocialNetworkService.buildOauthData(resource);
LoginActionCreators.loginUserByResourceOwner(
resource,
SocialNetworkService.getAccessToken(resource),
SocialNetworkService.getRefreshToken(resource)
).then(
() => {
console.log('User already logged in. Using invitation', invitation);
if (invitation && invitation.hasOwnProperty('group')) {
console.log('Joining group', invitation.group);
return GroupActionCreators.joinGroup(invitation.group.id);
}
return null; // User is logged in
},
() => {
let user = SocialNetworkService.getUser(resource);
let profile = SocialNetworkService.getProfile(resource);
if (!user || !profile) {
Framework7Service.nekunoApp().alert(strings.blockingError);
this.setState({registeringUser: false});
} else {
profile.interfaceLanguage = interfaceLanguage;
profile.orientationRequired = false;
this._registerUser(user, profile, token, oauthData);
}
});
}, (status) => {
Framework7Service.nekunoApp().alert(resource + ' login failed: ' + status.error.message)
});
}
_registerUser(user, profile, token, oauthData) {
LoginActionCreators.preRegister(user, profile, token, oauthData);
setTimeout(() => RouterActionCreators.replaceRoute('answer-username'), 0);
this.setState({
registeringUser: true
});
}
render() {
const {error, token, invitation, strings} = this.props;
const {initialToken, registeringUser, loginUser} = this.state;
return (
<div className="views">
<div className="view view-main register-view">
<div className="page register-page">
<div className="register-image" style={invitation && invitation.image_url && (!initialToken || token || error) ? {background: 'url("' + invitation.image_url + '") no-repeat center top', minHeight: '100%'} : null}>
<div className="gradient-transparency"></div>
</div>
<div className="register-nekuno-logo-wrapper">
<div className="register-nekuno-logo"></div>
</div>
<div id="page-content" className="register-content">
<div className="register-title bold">
<div className="title">{token && invitation ? (invitation.slogan ? invitation.slogan : strings.titleCorrect) : strings.title}</div>
</div>
<div className="register-sub-title bold">
{strings.openSource}
</div>
</div>
<div>
<FacebookButton onClickHandler={this.handleSocialNetwork} text={initialToken ? strings.compatibility : strings.signUp} disabled={registeringUser || loginUser}/>
<br />
<div className="privacy-terms-text">
<p dangerouslySetInnerHTML={{__html: strings.legalTerms}}/>
</div>
<br />
<br />
</div>
</div>
</div>
</div>
);
}
}
RegisterPage.defaultProps = {
strings: {
register : 'Create account',
cancel : 'Cancel',
title : 'Nekuno analyzes your interests to offer you recommendations',
openSource : 'Open & free software',
titleCorrect : 'Awesome! You got an invitation!',
subtitle : 'Please copy the URL that you\'ve received your invitation and paste it into the field below to create your account at Nekuno.',
paste : 'Paste the invitation url here',
correct : 'Just one last step! Connect Facebook:',
loadingMessage : 'Loading',
registeringMessage: 'Registering user',
publishMessage : 'We\'ll never publish anything on your wall',
legalTerms : 'We will never post anything on your networks.</br>By registering, you agree to the <a href="https://nekuno.com/terms-and-conditions" target="_blank">End-user license agreement</a>.',
signUp : 'Analyze',
compatibility : 'Analize compatibility',
blockingError : 'Your browser has blocked a Facebook request and we are not able to register you. Please, disable the blocking configuration or use an other browser.'
}
};
|
packages/mineral-ui-icons/src/IconInvertColorsOff.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconInvertColorsOff(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M20.65 20.87l-2.35-2.35-6.3-6.29-3.56-3.57-1.42-1.41L4.27 4.5 3 5.77l2.78 2.78a8.005 8.005 0 0 0 .56 10.69A7.98 7.98 0 0 0 12 21.58c1.79 0 3.57-.59 5.03-1.78l2.7 2.7L21 21.23l-.35-.36zM12 19.59c-1.6 0-3.11-.62-4.24-1.76A5.945 5.945 0 0 1 6 13.59c0-1.32.43-2.57 1.21-3.6L12 14.77v4.82zM12 5.1v4.58l7.25 7.26c1.37-2.96.84-6.57-1.6-9.01L12 2.27l-3.7 3.7 1.41 1.41L12 5.1z"/>
</g>
</Icon>
);
}
IconInvertColorsOff.displayName = 'IconInvertColorsOff';
IconInvertColorsOff.category = 'communication';
|
client/ui/atoms/card.story.js
|
LestaD/InstaClone
|
/* eslint-disable react/prop-types */
import React from 'react'
import { storiesOf } from '@storybook/react'
import { Card } from './card'
storiesOf('ui/atoms', module)
.addWithJSX('Card', () => (
<Card>Simple content of card</Card>
))
|
app/routes.js
|
oeb25/colio
|
import React from 'react';
import { Route } from 'react-router';
import LandingContainer from './containers/LandingContainer';
import RoomContainer from './containers/RoomContainer';
import CreateRoom from './components/CreateRoom';
const routes = (
<Route>
<Route path="/" component={LandingContainer}/>
<Route path="/room" component={CreateRoom} />
<Route path="/room/:id" component={RoomContainer} />
</Route>
);
export default routes;
|
tests/layouts/CoreLayout.spec.js
|
akossebestyen/getrecd-client-redux
|
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import CoreLayout from 'layouts/CoreLayout/CoreLayout'
function shallowRender (component) {
const renderer = TestUtils.createRenderer()
renderer.render(component)
return renderer.getRenderOutput()
}
function shallowRenderWithProps (props = {}) {
return shallowRender(<CoreLayout {...props} />)
}
describe('(Layout) Core', function () {
let _component
let _props
let _child
beforeEach(function () {
_child = <h1 className='child'>Child</h1>
_props = {
children : _child
}
_component = shallowRenderWithProps(_props)
})
it('Should render as a <div>.', function () {
expect(_component.type).to.equal('div')
})
})
|
components/summary.js
|
dvzrd/gatsby-utool.io
|
import React from 'react';
import { prune } from 'underscore.string';
import { fixLinks } from 'utils';
const style = {
summary: {
display: 'block',
position: 'relative',
margin: '0 auto',
color: '#555'
}
};
class Summary extends React.Component {
summary(body) {
const split = body.split('<hr>');
return split.length !== 0 && split[0].length < 200 ? split[0] : prune(body.replace(/<[^>]*>/g, ''), 200);
}
componentDidMount() {
fixLinks(this.refs.markdown, this.context.router);
}
render() {
return (
<p className="article summary" ref="markdown" style={style.summary} dangerouslySetInnerHTML={{__html: this.summary(this.props.body)}}/>
);
}
}
Summary.propTypes = {
body: React.PropTypes.string.isRequired
};
Summary.contextTypes = {
router: React.PropTypes.object.isRequired
};
export default Summary;
|
src/svg-icons/av/add-to-queue.js
|
nathanmarks/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvAddToQueue = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-7v2h-3v3h-2v-3H8v-2h3V7h2v3h3z"/>
</SvgIcon>
);
AvAddToQueue = pure(AvAddToQueue);
AvAddToQueue.displayName = 'AvAddToQueue';
AvAddToQueue.muiName = 'SvgIcon';
export default AvAddToQueue;
|
pages/api/toolbar.js
|
cherniavskii/material-ui
|
import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './toolbar.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
lib/Components/Current/Current.js
|
francylang/weathrly
|
import React from 'react';
import './Current.css';
const Current = (props) => {
return (
<div className={`mobileCard ${props.colors}`}>
<div className="topCard">
<h1 className="city">{props.weather.location}</h1>
<h2 className="currentTemp">
{props.weather.currentTemp}
<span className="deg">°</span>
</h2>
<h2 className="high-low">
HIGH {props.weather.dayHigh}
<span className="deg">°</span>
/ LOW {props.weather.dayLow}
<span className="deg">°</span>
</h2>
</div>
<div className="middleCard">
<i className={`wi wi-wu-${props.weather.currentIcon} currentIcon`}></i>
<h2 className="currentTime">{props.weather.day}</h2>
</div>
<div className="bottomCard">
<p className="weatherSummary">{props.weather.dailyDescrip}</p>
</div>
</div>
);
};
export default Current;
|
src/frontend/screens/Video/index.js
|
resummed/resummed
|
import React from 'react';
/**
* Video by pexels.com:
* https://videos.pexels.com/videos/birds-flying-over-industrial-area-569
*/
const Video = () => (
<div>
<video src={require('url-loader?limit=100000000!./video.mp4')} autoPlay loop />
</div>
);
export default Video;
|
js/react/workspace.js
|
CANTUS-Project/vitrail
|
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Program Name: vitrail
// Program Description: HTML/CSS/JavaScript user agent for the Cantus API.
//
// Filename: js/react/workspaces.js
// Purpose: The "Workspace" components for Vitrail.
//
// Copyright (C) 2016 Christopher Antila
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero 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 Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// -----------------------------------------------------------------------------------------------
import {Immutable} from 'nuclear-js';
import React from 'react';
import {Link, withRouter} from 'react-router';
import Button from 'react-bootstrap/lib/Button';
import ButtonGroup from 'react-bootstrap/lib/ButtonGroup';
import Col from 'react-bootstrap/lib/Col';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import Form from 'react-bootstrap/lib/Form';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import Grid from 'react-bootstrap/lib/Grid';
import Modal from 'react-bootstrap/lib/Modal';
import MenuItem from 'react-bootstrap/lib/MenuItem';
import Nav from 'react-bootstrap/lib/Nav';
import NavDropdown from 'react-bootstrap/lib/NavDropdown';
import PageHeader from 'react-bootstrap/lib/PageHeader';
import Panel from 'react-bootstrap/lib/Panel';
import Row from 'react-bootstrap/lib/Row';
import getters from '../nuclear/getters';
import reactor from '../nuclear/reactor';
import ResultList from './result_list';
import signals from '../nuclear/signals';
// for the "add to collection" and "remove from collection" buttons
const addToCollTooltip = 'Save Chant in a Collection';
const removeFromCollTooltip = 'Remove Chant from this Collection';
/** Displays existing collections, asking the user which collection a resource should be added to.
*
* NuclearJS State
* ---------------
* @param (ImmutableJS.Map) collections - The collections that exist.
*/
const AddToCollection = React.createClass({
propTypes: {
close: React.PropTypes.func.isRequired,
rid: React.PropTypes.string,
},
mixins: [reactor.ReactMixin],
getDataBindings() {
return {collections: getters.collections};
},
handleClick(event) {
const startOfSlice = 4; // after the "col-" part
signals.addToCollection(event.target.id.slice(startOfSlice), this.props.rid);
this.handleHide();
},
handleHide() {
this.props.close();
},
render() {
return (
<Modal show onHide={this.handleHide}>
<Modal.Header>
{`Add resource to which collection?`}
</Modal.Header>
<Modal.Body>
{this.state.collections.map((value, key) =>
<Button onClick={this.handleClick} id={`col-${key}`} key={key} block>
{value.get('name')}
</Button>
).toList()}
</Modal.Body>
<Modal.Footer>
<Button bsStyle="danger" onClick={this.handleHide}>{`Cancel`}</Button>
</Modal.Footer>
</Modal>
);
},
});
/** Produces a <ButtonGroup> with buttons for adding/removing a resource to a collection, as applicable.
*
* Props
* -----
* @param (string) rid - The resource ID to add or remove.
*
* State
* -----
* @param {bool} showAddToCollection - Whether to render the AddToCollection subcomponent.
* @param (bool) showingCollection - From the "showingCollection" getter.
*
* Note that a "remove" button will only be produced if "state.showingCollection" is not false.
* Otherwise, we don't know from which collection to remove the resource.
*
* The "add" button is always shown because you might want a resource to be in many collections.
*/
const AddRemoveCollection = React.createClass({
propTypes: {
rid: React.PropTypes.string.isRequired,
},
mixins: [reactor.ReactMixin],
getDataBindings() {
return {showingCollection: getters.showingCollection};
},
getInitialState() {
return {showAddToCollection: false};
},
handleRemove() {
signals.removeFromCollection(this.state.showingCollection, this.props.rid);
},
openAddToCollection() {
this.setState({showAddToCollection: true});
},
closeAddToCollection() {
this.setState({showAddToCollection: false});
},
render() {
let removeButton;
if (this.state.showingCollection) {
removeButton = (
<Button onClick={this.handleRemove} bsSize="small" title={removeFromCollTooltip}>
<Glyphicon glyph="minus"/>
<span className="sr-only">{removeFromCollTooltip}</span>
</Button>
);
}
let addToCollection;
if (this.state.showAddToCollection) {
addToCollection = <AddToCollection rid={this.props.rid} close={this.closeAddToCollection}/>;
}
return (
<ButtonGroup>
{addToCollection}
<Button onClick={this.openAddToCollection} bsSize="small" title={addToCollTooltip}>
<Glyphicon glyph="save"/>
<span className="sr-only">{addToCollTooltip}</span>
</Button>
{removeButton}
</ButtonGroup>
);
},
});
/** Sub-component of Collection that allows renaming.
*
* Props:
* ------
* @param (ImmutableJS.Map) collection - Optional. The collection corresponding to this Collection.
* If this is omitted, we assume this is for a new collection.
* @param (function) handleHide - This function is called to hide the component.
* @param (function) chooseName - This function is called with the newly-chosen name.
*
* State:
* ------
* @param (string) name - The new name for the collection, as it's typed.
*/
const CollectionRename = React.createClass({
propTypes: {
chooseName: React.PropTypes.func.isRequired,
collection: React.PropTypes.instanceOf(Immutable.Map),
handleHide: React.PropTypes.func.isRequired,
},
getInitialState() {
if (this.props.collection) {
return {name: this.props.collection.get('name')};
}
return {name: ''};
},
handleNameChange(event) {
this.setState({name: event.target.value});
},
handleRename() {
this.props.chooseName(this.state.name); this.props.handleHide();
},
render() {
let header;
if (this.props.collection) {
header = `Rename "${this.props.collection.get('name')}"`;
}
else {
header = 'New collection';
}
return (
<Modal show onHide={this.props.handleHide}>
<Modal.Header>
{header}
</Modal.Header>
<Modal.Body>
<Form onSubmit={this.handleRename}>
<FormGroup controlId="formControlsTextarea">
<ControlLabel>{`New name for the collection`}</ControlLabel>
<FormControl type="text" value={this.state.name} onChange={this.handleNameChange}/>
</FormGroup>
</Form>
</Modal.Body>
<Modal.Footer>
<Button bsStyle="danger" onClick={this.props.handleHide}>{`Cancel`}</Button>
<Button bsStyle="primary" onClick={this.handleRename}>{`Choose Name`}</Button>
</Modal.Footer>
</Modal>
);
},
});
/** A collection of database resources, as represented in the Shelf component.
*
* Props:
* ------
* @param (ImmutableJS.Map) collection - The collection corresponding to this Collection.
*
* State:
* ------
* @param (bool) showRenamer - Whether to show the <CollectionRename> component.
*/
const Collection = withRouter(React.createClass({
propTypes: {
collection: React.PropTypes.instanceOf(Immutable.Map).isRequired,
router: React.PropTypes.object.isRequired,
},
getInitialState() {
return {showRenamer: false};
},
handleDelete() {
signals.deleteCollection(this.props.collection.get('colid'));
},
handleShowRenamer() {
this.setState({showRenamer: !this.state.showRenamer});
},
submitRename(newName) {
signals.renameCollection(this.props.collection.get('colid'), newName);
},
render() {
const colid = this.props.collection.get('colid');
const linkToCollection = this.props.router.createHref(`/workspace/collection/${colid}`);
let renamer;
if (this.state.showRenamer) {
renamer = (
<CollectionRename
collection={this.props.collection}
handleHide={this.handleShowRenamer}
chooseName={this.submitRename}
/>
);
}
return (
<NavDropdown title={this.props.collection.get('name')} id={`coll-${colid}`}>
<MenuItem href={linkToCollection}>{`Open`}</MenuItem>
<MenuItem onClick={this.handleShowRenamer}>{`Rename`}</MenuItem>
<MenuItem onClick={this.handleDelete}>{`Delete`}</MenuItem>
{renamer}
</NavDropdown>
);
},
}));
/** The main workspace, where users can view a collection.
*
* State:
* ------
* @param (ImmutableJS.Map) collections - From NuclearJS, all of this user's Collections.
* @param (bool) showingCollection - From the "showingCollection" getter.
*/
const Desk = React.createClass({
mixins: [reactor.ReactMixin],
getDataBindings() {
return {
collections: getters.collections,
showingCollection: getters.showingCollection,
};
},
render() {
let header;
if (this.state.collections.has(this.state.showingCollection)) {
header = `Desk (viewing collection "${this.state.collections.get(this.state.showingCollection).get('name')}")`;
}
return (
<Col lg={10}>
<Panel header={header}>
<ResultList/>
</Panel>
</Col>
);
},
});
/** Confirm with the user that they want to reset the NuclearJS reactor.
*
* @param (function) handleHide - This function is called to hide the component.
*/
const ReactorResetter = React.createClass({
propTypes: {
handleHide: React.PropTypes.func.isRequired,
},
handleClear() {
signals.clearShelf();
this.props.handleHide();
},
render() {
return (
<Modal show onHide={this.props.handleHide}>
<Modal.Header>{`Really clear your shelf?`}</Modal.Header>
<Modal.Body>
{`When you clear your shelf:`}
<ul>
<li>{`all your collections are deleted,`}</li>
<li>{`all your saved collections are deleted, and`}</li>
<li>{`all your saved chants are deleted too.`}</li>
</ul>
{`This does not affect data on the server. Only your local data are affected.`}
<div className="alert alert-danger">
<strong>{`NOTE`}</strong>
{`: it does not fully work, so you have to refresh the page after you clear`}
</div>
</Modal.Body>
<Modal.Footer>
<Button bsStyle="danger" onClick={this.handleClear}>{`Clear`}</Button>
<Button bsStyle="success" onClick={this.props.handleHide}>{`Keep Shelf`}</Button>
</Modal.Footer>
</Modal>
);
},
});
/** TODO
*
* State:
* ------
* @param (ImmutableJS.Map) collections - From NuclearJS. The collections that exist.
* @param (bool) addingNewCollection - Whether we are currently adding a new collection, and the
* "CollectionRename" component should therefore be shown.
* @param (bool) showResetter - Whether we are currently asking the user whether they want to reset
* the NuclearJS Reactor, and should therefore show the "ReactorResetter" component.
*/
const Shelf = React.createClass({
mixins: [reactor.ReactMixin],
getDataBindings() {
return {collections: getters.collections};
},
getInitialState() {
return {addingNewCollection: false, showResetter: false};
},
toggleAddingCollection() {
this.setState({addingNewCollection: !this.state.addingNewCollection});
},
toggleShowResetter() {
this.setState({showResetter: !this.state.showResetter});
},
addCollection(newName) {
signals.newCollection(newName);
},
render() {
const collections =
this.state.collections.size > 0
?
this.state.collections.map((value) =>
<Collection key={value.get('colid')} collection={value}/>
).toArray()
:
<li>{'Choose '}<Glyphicon glyph="plus"/>{' below to make a collection.'}</li>
;
let renamer;
if (this.state.addingNewCollection) {
renamer = (
<CollectionRename
handleHide={this.toggleAddingCollection}
chooseName={this.addCollection}
/>
);
}
let resetter;
if (this.state.showResetter) {
resetter = <ReactorResetter handleHide={this.toggleShowResetter}/>;
}
return (
<Col lg={2}>
{renamer}
{resetter}
<Panel header="Shelf">
<Nav stacked>
{collections}
</Nav>
<hr/>
<ButtonGroup block vertical>
<Button bsStyle="primary" onClick={this.toggleAddingCollection}>
<Glyphicon glyph="plus"/>{` New Collection`}
</Button>
<Button bsStyle="primary" onClick={this.toggleShowResetter}>
<Glyphicon glyph="trash"/>{` Clear Shelf`}
</Button>
</ButtonGroup>
</Panel>
</Col>
);
},
});
/**
*
* NOTE: this component is responsible for setting the current collection ID
*
* Props:
* ------
* @param (str) params.colid - From react-router, the collection ID to display.
*/
const DeskAndShelf = React.createClass({
propTypes: {
children: React.PropTypes.element,
params: React.PropTypes.shape({
colid: React.PropTypes.string.isRequired,
}).isRequired,
},
componentWillMount() {
this.loadCollection(this.props.params.colid);
},
componentWillUpdate(nextProps) {
if (this.props.params.colid !== nextProps.params.colid) {
this.loadCollection(nextProps.params.colid);
}
},
componentWillUnmount() {
signals.setShowingCollection(false);
},
/** Load the data for the collection given by "colid."
*
* @param {str} colid - The collection ID to load.
*/
loadCollection(colid) {
if (colid) {
signals.setShowingCollection(colid);
signals.setPage(1);
signals.loadCollection(colid);
}
},
render() {
return (
<div>
<Desk/>
<Shelf/>
{this.props.children}
</div>
);
},
});
const JustShelf = React.createClass({
render() {
return (
<div>
<Col lg={10}>
<Panel header="Desk">
<p>
{`Choose a Collection from the Shelf to see its contents on the Desk.`}
</p>
</Panel>
</Col>
<Shelf/>
</div>
);
},
});
const WorkspaceHelp = React.createClass({
propTypes: {
handleHide: React.PropTypes.func,
},
render() {
return (
<Modal show onHide={this.props.handleHide} >
<Modal.Header>
<Modal.Title>{`About the Workspace`}</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
{`Use the Workspace to save "Collections" of chants to view offline. Your
collections are held on the "Shelf." Click or tap a collection on the Shelf
to open its chants on the "Desk."`}
</p>
<p>
{`You can name your collections and use them to keep track of search results
or any other group of chants you may want to view later. However, your
collections are only stored in your browser, so nobody else can see them.`}
</p>
<p>
{`When you add chants to a collection, they're automatically saved in your
browser. This means you can view the chants in your collections even if
you're not connected to the internet. Refer to our `}
<Link to="/offline">{`offline page `}</Link>{`for more information.`}
</p>
</Modal.Body>
<Modal.Footer>
<Button bsStyle="primary" onClick={this.props.handleHide}>{`Close`}</Button>
</Modal.Footer>
</Modal>
);
},
});
const Workspace = React.createClass({
propTypes: {
children: React.PropTypes.element,
},
getInitialState() {
return {showHelp: false};
},
handleHelp() {
this.setState({showHelp: !this.state.showHelp});
},
render() {
const help = this.state.showHelp ? <WorkspaceHelp handleHide={this.handleHelp}/> : undefined;
return (
<Grid id="vitrail-workspace" fluid>
{help}
<PageHeader>
{`Workspace\u2003`}
<small>
<i>{`Manage your personal collections.\u2003`}</i>
<Button bsStyle="info" className="help-icon" onClick={this.handleHelp}>
<Glyphicon glyph="question-sign"/>
</Button>
</small>
</PageHeader>
<Row>
{this.props.children}
</Row>
</Grid>
);
},
});
const moduleForTesting = {
Workspace: Workspace,
};
export {AddToCollection, AddRemoveCollection, DeskAndShelf, JustShelf, Workspace, moduleForTesting};
|
app/routes.js
|
FermORG/FermionJS
|
import React from 'react';
import { Switch, Route } from 'react-router';
import App from './containers/App';
import HomePage from './containers/HomePage';
import CorePage from './containers/CorePage';
export default () => (
<App>
<Switch>
<Route path="/core" component={CorePage} />
<Route path="/" component={HomePage} />
</Switch>
</App>
);
|
src/render-react.js
|
abramz/gulp-react-render
|
/*! Gulp Render React | MIT License */
import gutil from 'gulp-util';
import through from 'through2';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
/**
* Requires a file containing a React component and create an instance of it
* @param {String} filePath file path to the React component to render
* @param {Object} props properties to apply to the element
* @return {Element} the created React element
*/
function createElement(filePath, props) {
if (!filePath || typeof filePath !== 'string' || filePath.length === 0) {
throw new Error('Expected filePath to be a string');
}
// clear the require cache if we have already imported the file (if we are watching it)
if (require.cache[filePath]) {
delete require.cache[filePath];
}
const component = require(filePath); // eslint-disable-line global-require, import/no-dynamic-require
const element = React.createElement(component.default || component, props || {});
return element;
}
/**
* Uses ReactDOMServer.renderToString on a component at filePath. Will apply optional pro
* https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostring
*
* @param {String} filePath react component to render
* @param {Object} props properties to apply to the React component
* @return {Buffer} buffer of the component rendered to a string
*/
function renderToString(filePath, props) {
const element = createElement(filePath, props);
const elementString = ReactDOMServer.renderToString(element);
return new Buffer(elementString);
}
/**
* Uses ReactDOMServer.renderToStatic on a component at filePath. Will apply optional props
* https://facebook.github.io/react/docs/top-level-api.html#reactdomserver.rendertostaticmarkup
*
* @param {String} filePath react component to render
* @param {Object} props properties to apply to the React component
* @return {Buffer} buffer of the component rendered to a string
*/
function renderToStaticMarkup(filePath, props) {
const element = createElement(filePath, props);
const elementMarkup = ReactDOMServer.renderToStaticMarkup(element);
return new Buffer(elementMarkup);
}
module.exports = (options) => {
const opts = options || {};
if (!opts.type || (opts.type !== 'string' && opts.type !== 'markup')) {
throw new gutil.PluginError('gulp-render-react', '`type` required (`string` or `markup`)');
}
return through.obj(function process(file, enc, callback) {
try {
const newFile = file;
// temporary before we allow src extension in options
if (opts.type === 'string') {
newFile.contents = renderToString(file.path, opts.props ? opts.props : {});
} else if (opts.type === 'markup') {
newFile.contents = renderToStaticMarkup(file.path, opts.props ? opts.props : {});
}
// temporary before we allow dest extension in options
newFile.path = gutil.replaceExtension(file.path, '.html');
this.push(newFile);
} catch (err) {
this.emit('error', new gutil.PluginError('gulp-render-react', err, { fileName: file.path }));
}
callback();
});
};
|
test/containers/CounterPage.spc.js
|
tomv564/electron-git-buddy
|
import { expect } from 'chai';
import React from 'react';
import {
renderIntoDocument,
scryRenderedDOMComponentsWithTag,
findRenderedDOMComponentWithClass,
Simulate
} from 'react-addons-test-utils';
import { Provider } from 'react-redux';
import CounterPage from '../../app/containers/CounterPage';
import configureStore from '../../app/store/configureStore';
function setup(initialState) {
const store = configureStore(initialState);
const app = renderIntoDocument(
<Provider store={store}>
<CounterPage />
</Provider>
);
return {
app: app,
buttons: scryRenderedDOMComponentsWithTag(app, 'button').map(button => {
return button;
}),
p: findRenderedDOMComponentWithClass(app, 'counter')
};
}
describe('containers', () => {
describe('App', () => {
it('should display initial count', () => {
const { p } = setup();
expect(p.textContent).to.match(/^0$/);
});
it('should display updated count after increment button click', () => {
const { buttons, p } = setup();
Simulate.click(buttons[0]);
expect(p.textContent).to.match(/^1$/);
});
it('should display updated count after descrement button click', () => {
const { buttons, p } = setup();
Simulate.click(buttons[1]);
expect(p.textContent).to.match(/^-1$/);
});
it('shouldnt change if even and if odd button clicked', () => {
const { buttons, p } = setup();
Simulate.click(buttons[2]);
expect(p.textContent).to.match(/^0$/);
});
it('should change if odd and if odd button clicked', () => {
const { buttons, p } = setup({ counter: 1 });
Simulate.click(buttons[2]);
expect(p.textContent).to.match(/^2$/);
});
});
});
|
src/clincoded/static/libs/bootstrap/popover.js
|
ClinGen/clincoded
|
"use strict";
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
// Display a popover that shows descriptive text content until the user dismisses it.
// The typical format looks like:
//
// <PopOverComponent {...this.props}>
// // Render JSX...
// </PopOverComponent>
//
// This component has been written in similar way to the rewritten modal component.
//
// <PopOverComponent> usage details:
// See 'PopOverComponent.propTypes' for details
export default class PopOverComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
isPopOverOpen: false
};
this.handlePopOver = this.handlePopOver.bind(this);
this.closePopOver = this.closePopOver.bind(this);
}
componentDidMount() {
this.props.popOverRef(this);
}
componentWillUnmount() {
this.props.popOverRef(null);
}
// Called by the actuator (link/button to toggle the popover)
handlePopOver() {
this.setState({ isPopOverOpen: !this.state.isPopOverOpen });
}
// Called by the popover's own Close button defined in the "PopOver" component
closePopOver() {
this.setState({ isPopOverOpen: false });
}
render() {
return (
<div className={'popover-component ' + this.props.popOverWrapperClass}>
{this.props.actuatorTitle ?
<a className="popover-actuator" onClick={() => this.handlePopOver()}>{this.props.actuatorTitle}</a>
: null}
<PopOver isPopOverOpen={this.state.isPopOverOpen} closePopOver={this.closePopOver} popOverStyleClass={this.props.popOverStyleClass}>
{this.props.children}
</PopOver>
</div>
);
}
}
PopOverComponent.propTypes = {
popOverWrapperClass: PropTypes.string, // CSS class for popover DOM wrapper
popOverStyleClass: PropTypes.string, // CSS class for popover style (e.g. alert-info, alert-warning)
actuatorTitle: PropTypes.oneOfType([ // Text for link to invoke popover
PropTypes.object,
PropTypes.string
]),
children: PropTypes.node // JSX such as input field(s), dropdown(s), buttons, or text string
};
class PopOver extends React.Component {
render() {
if (this.props.isPopOverOpen === false) {
return null;
}
return (
<div className={'popover-wrapper ' + this.props.popOverStyleClass} style={{display: 'block'}}>
<a className="closePopOver" aria-label="Close" onClick={this.props.closePopOver}>
<span aria-hidden="true"><i className="icon icon-times"></i></span>
</a>
<div className="popover-content">
{this.props.children}
</div>
</div>
);
}
}
PopOver.propTypes = {
closePopOver: PropTypes.func,
isPopOverOpen: PropTypes.bool,
popOverStyleClass: PropTypes.string
};
|
8-css-inline/src/App.js
|
mariusz-malinowski/tutorial-react
|
import React, { Component } from 'react';
import initialState from './data';
import TodoList from './TodoList';
import TodoDetails from './TodoDetails';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from './reducer';
import createHistory from 'history/createBrowserHistory';
import { Router, Route } from 'react-router-dom';
const history = createHistory();
const store = createStore(reducer, initialState);
class App extends Component {
render() {
return (
<Provider store={store}>
<Router history={history}>
<div>
<Route exact path="/" component={TodoList} />
<Route path="/todoDetails" component={TodoDetails} />
</div>
</Router>
</Provider>
);
}
}
export default App;
|
app/setup.js
|
JohnKim/react-native-boilerplate
|
/**
*
* @flow
*/
import React, { Component } from 'react';
import { APP_ID, SERVER_URL } from 's5-env';
import { FacebookSDK } from 's5-util';
import Parse from 'parse/react-native';
import Relay from 'react-relay';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
/* Application */ import App from './components/app';
/* Application (for UI test) */ //import App from './AppPlayground';
function setup(): Component {
console.disableYellowBox = true;
Parse.initialize(APP_ID);
Parse.serverURL = `${SERVER_URL}/parse`;
FacebookSDK.init();
Parse.FacebookUtils.init();
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer(`${SERVER_URL}/graphql`, {
fetchTimeout: 30000,
retryDelays: [5000, 10000],
})
);
class Root extends Component {
state = {
isLoading: true,
store: configureStore(() => this.setState({isLoading: false})),
};
render() {
if (this.state.isLoading) {
return null;
}
/** 컴포넌트에 Store를 제공하는 Provider (최상위 컨포넌트) **/
return (
<Provider store={this.state.store}>
<App />
</Provider>
);
}
}
return Root;
}
global.LOG = (...args) => {
console.log('/------------------------------\\');
console.log(...args);
console.log('\\------------------------------/');
return args[args.length - 1];
};
module.exports = setup;
|
js/BaseComponents/InfoBlock.js
|
telldus/telldus-live-mobile-v3
|
/**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : 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.
*
* Telldus Live! app 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 Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*/
// @flow
'use strict';
import React from 'react';
import Text from './Text';
import View from './View';
import BlockIcon from './BlockIcon';
import Theme from '../App/Theme';
const InfoBlock = (props: Object): Object => {
const {
text,
appLayout,
infoIconStyle,
infoContainer,
textStyle,
} = props;
const {
infoContainerDef,
infoIconStyleDef,
textStyleDef,
blockIconContainerStyle,
} = getStyles(appLayout);
return (
<View
level={2}
style={[infoContainerDef, infoContainer]}>
<BlockIcon
icon={'info'}
iconLevel={36}
style={[infoIconStyleDef, infoIconStyle]}
containerStyle={blockIconContainerStyle}/>
<View style={{
flex: 1,
flexDirection: 'row',
flexWrap: 'wrap',
}}>
<Text
level={26}
style={[textStyleDef, textStyle]}>
{text}
</Text>
</View>
</View>
);
};
const getStyles = (appLayout: Object): Object => {
const { height, width } = appLayout;
const isPortrait = height > width;
const deviceWidth = isPortrait ? width : height;
const {
shadow,
paddingFactor,
fontSizeFactorTwelve,
} = Theme.Core;
const padding = deviceWidth * paddingFactor;
const fontSizeBody = deviceWidth * fontSizeFactorTwelve;
return {
infoContainerDef: {
flex: 1,
flexDirection: 'row',
marginBottom: padding / 2,
padding: padding,
...shadow,
alignItems: 'center',
justifyContent: 'space-between',
borderRadius: 2,
},
blockIconContainerStyle: {
backgroundColor: 'transparent',
},
infoIconStyleDef: {
fontSize: deviceWidth * 0.14,
},
textStyleDef: {
flex: 1,
fontSize: fontSizeBody,
flexWrap: 'wrap',
marginLeft: padding,
},
};
};
export default (React.memo<Object>(InfoBlock): Object);
|
src/app/client.js
|
lmcjt37/kulor-reactify
|
import 'react-toolbox/lib/commons.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('app'));
|
src/Flags/Nigeria.js
|
runjak/css-flags
|
// @flow
import React from 'react';
import LinearFlag from './LinearFlag';
import gradient from '../utils/gradient';
const green = '#008850';
const white = '#FFFFFF';
export default function Nigeria() {
return (
<LinearFlag
gradient={`to right, ${gradient([green, white, green])}`}
/>
);
}
|
src/components/Assets/Arrow.js
|
LifeSourceUA/lifesource.ua
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import svg from 'lib/svg';
@svg({
width: 8,
height: 14
})
export default class Arrow extends Component {
static propTypes = {
color: PropTypes.string.isRequired
};
render() {
const { color } = this.props;
return (
<path
fill={ color } d="M0.2,13.8L0.2,13.8c-0.3-0.3-0.3-0.8,0-1.1L6.2,7L0.2,1.3c-0.3-0.3-0.3-0.8,
0-1.1l0,0c0.3-0.3,0.8-0.3,1.1,0l6.5,6.3c0.3,0.3,0.3,0.8,0,1.1l-6.5,6.3C1,14.1,0.5,14.1,0.2,13.8z"
/>
);
}
}
|
popup/src/scripts/components/friends/LiveFriendVideoReplaysList.js
|
CaliAlec/ChromeIGStory
|
import React, { Component } from 'react';
import Toolbar from '@material-ui/core/Toolbar';
import Tooltip from '@material-ui/core/Tooltip';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import Avatar from '@material-ui/core/Avatar';
import MenuItem from '@material-ui/core/MenuItem';
import IconButton from '@material-ui/core/IconButton';
import ListSubheader from '@material-ui/core/ListSubheader';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import DownloadIcon from '@material-ui/icons/GetApp';
import ShareIcon from '@material-ui/icons/Share';
import VideoLibraryIcon from '@material-ui/icons/VideoLibrary';
import MusicLibraryIcon from '@material-ui/icons/LibraryMusic';
import LiveVideo from '../../../../../utils/LiveVideo';
import {getTimeElapsed} from '../../../../../utils/Utils';
import {setCurrentStoryObject} from '../../utils/PopupUtils';
import AnalyticsUtil from '../../../../../utils/AnalyticsUtil';
import LiveVideoReplayDownloadDialog from '../../../../../utils/LiveVideoReplayDownloadDialog';
class LiveFriendVideoReplaysList extends Component {
constructor(props){
super(props);
this.state = {
selectedIndex: -1,
downloadingIndex: -1,
isDownloadLiveVideoDialogOpen: false
}
}
handleRequestChange (event, index) {
var selectedStory = this.props.friendStories.post_live.post_live_items[index];
setCurrentStoryObject('LIVE_REPLAY', {post_live_item: selectedStory});
this.setState({
selectedIndex: index,
});
AnalyticsUtil.track("Story List Item Clicked", AnalyticsUtil.getStoryObject(selectedStory));
}
onDownloadStory(index) {
this.setState({
isDownloadLiveVideoDialogOpen: true,
downloadingIndex: index
});
}
onShareStory(index) {
var selectedStory = this.props.friendStories.post_live.post_live_items[index].broadcasts[0];
AnalyticsUtil.track("Share Story", AnalyticsUtil.getStoryObject(selectedStory));
window.open('https://watchmatcha.com/user/' + selectedStory.broadcast_owner.username);
}
renderListItem(index, liveVideoReplay) {
const styles = {
listItem: {
flex: 1,
background: 'transparent',
paddingLeft: '0px',
paddingRight: '0px',
minHeight: '48px'
},
listItemContent: {
display: 'flex',
flex: 1
},
listItemActions: {
textAlign: 'right'
}
}
const { selectedIndex } = this.state;
const isPrivate = liveVideoReplay.user.is_private;
const latestBroadcast = liveVideoReplay.broadcasts[liveVideoReplay.broadcasts.length - 1];
return (
<ListItem
key={index}
button
selected={selectedIndex === index}
onClick={event => this.handleRequestChange(event, index)}
>
<Toolbar style={styles.listItem}>
<div style={styles.listItemContent}>
<ListItemAvatar>
<Avatar src={liveVideoReplay.user.profile_pic_url} />
</ListItemAvatar>
<ListItemText
primary={liveVideoReplay.user.username}
secondary={getTimeElapsed(latestBroadcast.published_time)}
/>
</div>
<div style={styles.listItemActions}>
{/*
<Tooltip
title={(isPrivate) ? "Can't Share Private Story" : "Share"}
placement="bottom"
>
<IconButton
disabled={isPrivate}
onClick={() => this.onShareStory(index)}>
<ShareIcon />
</IconButton>
</Tooltip>
*/}
<Tooltip
title="Download"
placement="bottom"
>
<IconButton
onClick={() => this.onDownloadStory(index)}>
<DownloadIcon />
</IconButton>
</Tooltip>
</div>
</Toolbar>
</ListItem>
)
}
render() {
if(this.props.friendStories.post_live.post_live_items.length === 0) {
return (<div></div>);
}
const liveFriendVideoReplaysListData = this.props.friendStories.post_live.post_live_items.map((liveVideoReplay, key) => {
return this.renderListItem(key, liveVideoReplay);
});
return (
<div>
<List onChange={this.handleRequestChange.bind(this)}>
<ListSubheader disableSticky>Live Video Replays</ListSubheader>
{liveFriendVideoReplaysListData}
</List>
{this.state.isDownloadLiveVideoDialogOpen &&
<LiveVideoReplayDownloadDialog
isOpen={this.state.isDownloadLiveVideoDialogOpen}
liveVideoReplays={this.props.friendStories.post_live.post_live_items[this.state.downloadingIndex].broadcasts}
onRequestClose={() => this.setState({isDownloadLiveVideoDialogOpen: false})}
/>
}
</div>
)
}
}
export default LiveFriendVideoReplaysList;
|
app/components/widget-list.js
|
svtizg/svtizg.github.io
|
import React from 'react';
const WidgetList = React.createClass({
render: function() {
return (
<ul className="widget-list">
<li>Сообщение от пользователя 1</li>
<li>Сообщение от пользователя 2</li>
<li>Сообщение от пользователя 3</li>
</ul>
);
}
});
export default WidgetList;
|
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js
|
Ryanaka/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components';
import Overlay from 'react-overlays/lib/Overlay';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { supportsPassiveEvents } from 'detect-passive-events';
import { buildCustomEmojis, categoriesFromEmojis } from '../../emoji/emoji';
import { assetHost } from 'mastodon/utils/config';
const messages = defineMessages({
emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' },
emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' },
custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' },
recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' },
search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' },
people: { id: 'emoji_button.people', defaultMessage: 'People' },
nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' },
food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' },
activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' },
travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' },
objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' },
symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' },
flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' },
});
let EmojiPicker, Emoji; // load asynchronously
const listenerOptions = supportsPassiveEvents ? { passive: true } : false;
const backgroundImageFn = () => `${assetHost}/emoji/sheet_13.png`;
const notFoundFn = () => (
<div className='emoji-mart-no-results'>
<Emoji
emoji='sleuth_or_spy'
set='twitter'
size={32}
sheetSize={32}
backgroundImageFn={backgroundImageFn}
/>
<div className='emoji-mart-no-results-label'>
<FormattedMessage id='emoji_button.not_found' defaultMessage='No matching emojis found' />
</div>
</div>
);
class ModifierPickerMenu extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
};
handleClick = e => {
this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1);
}
componentWillReceiveProps (nextProps) {
if (nextProps.active) {
this.attachListeners();
} else {
this.removeListeners();
}
}
componentWillUnmount () {
this.removeListeners();
}
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
attachListeners () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
removeListeners () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
render () {
const { active } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}>
<button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button>
</div>
);
}
}
class ModifierPicker extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
modifier: PropTypes.number,
onChange: PropTypes.func,
onClose: PropTypes.func,
onOpen: PropTypes.func,
};
handleClick = () => {
if (this.props.active) {
this.props.onClose();
} else {
this.props.onOpen();
}
}
handleSelect = modifier => {
this.props.onChange(modifier);
this.props.onClose();
}
render () {
const { active, modifier } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers'>
<Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} />
<ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} />
</div>
);
}
}
@injectIntl
class EmojiPickerMenu extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
loading: PropTypes.bool,
onClose: PropTypes.func.isRequired,
onPick: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
intl: PropTypes.object.isRequired,
skinTone: PropTypes.number.isRequired,
onSkinTone: PropTypes.func.isRequired,
};
static defaultProps = {
style: {},
loading: true,
frequentlyUsedEmojis: [],
};
state = {
modifierOpen: false,
readyToFocus: false,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
// Because of https://github.com/react-bootstrap/react-bootstrap/issues/2614 we need
// to wait for a frame before focusing
requestAnimationFrame(() => {
this.setState({ readyToFocus: true });
if (this.node) {
const element = this.node.querySelector('input[type="search"]');
if (element) element.focus();
}
});
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
getI18n = () => {
const { intl } = this.props;
return {
search: intl.formatMessage(messages.emoji_search),
categories: {
search: intl.formatMessage(messages.search_results),
recent: intl.formatMessage(messages.recent),
people: intl.formatMessage(messages.people),
nature: intl.formatMessage(messages.nature),
foods: intl.formatMessage(messages.food),
activity: intl.formatMessage(messages.activity),
places: intl.formatMessage(messages.travel),
objects: intl.formatMessage(messages.objects),
symbols: intl.formatMessage(messages.symbols),
flags: intl.formatMessage(messages.flags),
custom: intl.formatMessage(messages.custom),
},
};
}
handleClick = (emoji, event) => {
if (!emoji.native) {
emoji.native = emoji.colons;
}
if (!(event.ctrlKey || event.metaKey)) {
this.props.onClose();
}
this.props.onPick(emoji);
}
handleModifierOpen = () => {
this.setState({ modifierOpen: true });
}
handleModifierClose = () => {
this.setState({ modifierOpen: false });
}
handleModifierChange = modifier => {
this.props.onSkinTone(modifier);
}
render () {
const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props;
if (loading) {
return <div style={{ width: 299 }} />;
}
const title = intl.formatMessage(messages.emoji);
const { modifierOpen } = this.state;
const categoriesSort = [
'recent',
'people',
'nature',
'foods',
'activity',
'places',
'objects',
'symbols',
'flags',
];
categoriesSort.splice(1, 0, ...Array.from(categoriesFromEmojis(custom_emojis)).sort());
return (
<div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}>
<EmojiPicker
perLine={8}
emojiSize={22}
sheetSize={32}
custom={buildCustomEmojis(custom_emojis)}
color=''
emoji=''
set='twitter'
title={title}
i18n={this.getI18n()}
onClick={this.handleClick}
include={categoriesSort}
recent={frequentlyUsedEmojis}
skin={skinTone}
showPreview={false}
showSkinTones={false}
backgroundImageFn={backgroundImageFn}
notFound={notFoundFn}
autoFocus={this.state.readyToFocus}
emojiTooltip
/>
<ModifierPicker
active={modifierOpen}
modifier={skinTone}
onOpen={this.handleModifierOpen}
onClose={this.handleModifierClose}
onChange={this.handleModifierChange}
/>
</div>
);
}
}
export default @injectIntl
class EmojiPickerDropdown extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
intl: PropTypes.object.isRequired,
onPickEmoji: PropTypes.func.isRequired,
onSkinTone: PropTypes.func.isRequired,
skinTone: PropTypes.number.isRequired,
button: PropTypes.node,
};
state = {
active: false,
loading: false,
placement: null,
};
setRef = (c) => {
this.dropdown = c;
}
onShowDropdown = ({ target }) => {
this.setState({ active: true });
if (!EmojiPicker) {
this.setState({ loading: true });
EmojiPickerAsync().then(EmojiMart => {
EmojiPicker = EmojiMart.Picker;
Emoji = EmojiMart.Emoji;
this.setState({ loading: false });
}).catch(() => {
this.setState({ loading: false, active: false });
});
}
const { top } = target.getBoundingClientRect();
this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' });
}
onHideDropdown = () => {
this.setState({ active: false });
}
onToggle = (e) => {
if (!this.state.loading && (!e.key || e.key === 'Enter')) {
if (this.state.active) {
this.onHideDropdown();
} else {
this.onShowDropdown(e);
}
}
}
handleKeyDown = e => {
if (e.key === 'Escape') {
this.onHideDropdown();
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
render () {
const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis, button } = this.props;
const title = intl.formatMessage(messages.emoji);
const { active, loading, placement } = this.state;
return (
<div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}>
<div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}>
{button || <img
className={classNames('emojione', { 'pulse-loading': active && loading })}
alt='🙂'
src={`${assetHost}/emoji/1f602.svg`}
/>}
</div>
<Overlay show={active} placement={placement} target={this.findTarget}>
<EmojiPickerMenu
custom_emojis={this.props.custom_emojis}
loading={loading}
onClose={this.onHideDropdown}
onPick={onPickEmoji}
onSkinTone={onSkinTone}
skinTone={skinTone}
frequentlyUsedEmojis={frequentlyUsedEmojis}
/>
</Overlay>
</div>
);
}
}
|
client/src/components/side_menu_button/SideMenuButton.js
|
thewizardplusplus/vk-group-stats
|
import React from 'react'
import IconicButton from '../iconic_button/IconicButton'
export default class SideMenuButton extends React.Component {
// this name required by the AppBar component for a correct styles processing
static muiName = 'IconButton'
static propTypes = {
iconStyle: React.PropTypes.object,
onClick: React.PropTypes.func,
}
render() {
return <IconicButton
icon="menu"
iconStyle={this.props.iconStyle}
onTouchTap={this.props.onClick} />
}
}
|
packages/enzyme-adapter-react-helper/src/ifReact.js
|
airbnb/enzyme
|
import React from 'react';
import { intersects } from 'semver';
export default function ifReact(range, yes, no) {
if (typeof yes !== 'function') { throw new TypeError('"yes" must be a function'); }
if (typeof no !== 'function') { throw new TypeError('"no" must be a function'); }
return intersects(range, React.version) ? yes : no;
}
|
index.android.js
|
wellnine/maelstorm
|
import "./bin/index";
// /**
// * Sample React Native App
// * https://github.com/facebook/react-native
// * @flow
// */
//
// import React, { Component } from 'react';
// import {
// AppRegistry,
// StyleSheet,
// Text,
// View
// } from 'react-native';
//
// export default class maelstorm extends Component {
// render() {
// return (
// <View style={styles.container}>
// <Text style={styles.welcome}>
// Welcome to React Native 1!
// </Text>
// <Text style={styles.instructions}>
// To get started, edit index.android.js
// </Text>
// <Text style={styles.instructions}>
// Double tap R on your keyboard to reload,{'\n'}
// Shake or press menu button for dev menu
// </Text>
// </View>
// );
// }
// }
//
// const styles = StyleSheet.create({
// container: {
// flex: 1,
// justifyContent: 'center',
// alignItems: 'center',
// backgroundColor: '#F5FCFF',
// },
// welcome: {
// fontSize: 20,
// textAlign: 'center',
// margin: 10,
// },
// instructions: {
// textAlign: 'center',
// color: '#333333',
// marginBottom: 5,
// },
// });
//
// AppRegistry.registerComponent('maelstorm', () => maelstorm);
|
src/svg-icons/action/settings-input-component.js
|
tan-jerene/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsInputComponent = (props) => (
<SvgIcon {...props}>
<path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v6h6V6H5V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2H9v2zm-8 0c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16v-2H1v2zM21 6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v6h6V6h-2zm-8-4c0-.55-.45-1-1-1s-1 .45-1 1v4H9v6h6V6h-2V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2h-6v2z"/>
</SvgIcon>
);
ActionSettingsInputComponent = pure(ActionSettingsInputComponent);
ActionSettingsInputComponent.displayName = 'ActionSettingsInputComponent';
ActionSettingsInputComponent.muiName = 'SvgIcon';
export default ActionSettingsInputComponent;
|
src/components/common/NavBarLeftButton.js
|
jinqiupeter/mtsr
|
import React from 'react';
import {StyleSheet, Platform, View, Text, TouchableOpacity} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import {COLOR} from '../../config';
export default ({icon, text, children, onPress, containerStyle, iconStyle, textStyle}) => {
if (children) {
return (
<TouchableOpacity onPress={onPress} style={[styles.container, containerStyle]}>
{children}
</TouchableOpacity>
);
} else {
return (
<TouchableOpacity onPress={onPress} style={styles.container}>
{icon ? <Icon name={icon} style={[styles.icon, iconStyle]} /> : null}
{text ? <Text style={[styles.text, textStyle]}>{text}</Text> : null}
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
container: {
position: 'absolute',
minWidth: 30,
...Platform.select({
ios: {
top: -6,
left: 3,
height: 50,
},
android: {
top: 12,
left: 3,
height: 34,
},
}),
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'center',
},
icon: {
fontSize: 14,
color: COLOR.textLightPrompt,
},
text: {
fontSize: 14,
color: COLOR.textLightPrompt,
},
});
|
src/chapters/04-porazdelitve-verjetnosti/01-funkcija-gostote/index.js
|
medja/ovs-prirocnik
|
import React from 'react';
import { createChapter } from 'components/chapter';
import Equation from 'components/equation';
const title = 'Funkcija gostote';
function Title(props) {
return (
<span>
{ props.title }{' '}
<Equation math="f(x)" />
</span>
);
}
function Chapter() {
return (
<div>
<p>
Funkcija gostote nam omogoča računanje verjetnosti slučajev
spremenljivke, <strong>če poznamo njeno porazdelitev</strong>.
Njeno vrednost lahko razberemo tudi s pomočjo verjetnostne
tabele, saj je njena vrednost za neki <Equation math="x" />{' '}
natanko vrednost v tabeli pod tem <Equation math="x" />-om,
torej <Equation math="p_x" />.
</p>
<p>
Ta funkcija nam zato pride prav, ko ne poznamo vnaprej
verjetnosti izidov oziroma kadar potrebujemo enačbo za izračun
le teh. Ker ta funkcija vrača relativno gostoto oziroma
verjetnost nekega izida pa seveda more biti omejena. Ker nič ne
more biti več kot <Equation math="100\%" /> mora biti vsota vseh
vrednosti te funkcije vedno enaka <Equation math="1" />.
</p>
</div>
);
}
export default createChapter(title, Chapter, [], { Title });
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.