path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
demo/components/popup/PopupOptions.js
|
f0zze/rosemary-ui
|
import React from 'react';
import {Popup} from '../../../src';
import OptionsTable from '../../helper/OptionsTable';
export default () => {
let propDescription = {
attachment: {
values: `Mandatory, One Of:
top left,
top center,
top right,
middle left,
middle right,
bottom left,
bottom center,
bottom right`,
description: 'Popup attachment position'
},
on: {
values: 'One Of: hover, click',
description: 'Whether popup should be opened on click or on hover'
},
popupClassName: {
values: 'Variations: tooltip, popup, popup-blue-border',
description: 'Popup class name'
},
targetClassName: {
values: 'string',
description: 'Component to which popup is attached class name'
},
changeAttachmentDynamically: {
values: 'boolean',
description: 'Whether popup will change location on window resize'
},
modal: {
values: 'boolean',
description: 'Whether popup is modal'
},
animationBaseName: {
values: 'string',
description: 'Animation class name'
},
onOpen: {
values: 'function',
description: 'Callback when popup is opened'
}
};
return (
<div>
<OptionsTable component={Popup} propDescription={propDescription}/>
</div>
);
};
|
src/Parser/Druid/Restoration/Modules/NetherlightCrucibleTraits/NLCTraits.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import StatisticsListBox from 'Main/StatisticsListBox';
import CoreNLCTraits from "Parser/Core/Modules//NetherlightCrucibleTraits/NLCTraits";
import LightSpeed from "./LightSpeed";
import MasterOfShadows from "./MasterOfShadows";
class NLCTraits extends CoreNLCTraits {
static dependencies = {
...CoreNLCTraits.dependencies,
lightSpeed: LightSpeed,
masterOfShadows: MasterOfShadows,
};
statistic() {
return (
<StatisticsListBox
title="Netherlight Crucible"
tooltip="This provides an overview of the increased provide by the Netherlight Crucible traits."
>
{this.murderousIntent.active && this.murderousIntent.subStatistic()}
{this.shocklight.active && this.shocklight.subStatistic()}
{this.refractiveShell.active && this.refractiveShell.subStatistic()}
{this.secureInTheLight.active && this.secureInTheLight.subStatistic()}
{this.infusionOfLight.active && this.infusionOfLight.subStatistic()}
{this.lightsEmbrace.active && this.lightsEmbrace.subStatistic()}
{this.shadowbind.active && this.shadowbind.subStatistic()}
{this.chaoticDarkness.active && this.chaoticDarkness.subStatistic()}
{this.tormentTheWeak.active && this.tormentTheWeak.subStatistic()}
{this.darkSorrows.active && this.darkSorrows.subStatistic()}
{this.lightSpeed.active && this.lightSpeed.subStatistic()}
{this.masterOfShadows.active && this.masterOfShadows.subStatistic()}
</StatisticsListBox>
);
}
}
export default NLCTraits;
|
web/src/routes/ExampleIndexPage.js
|
ZhuPeng/trackupdates
|
import React from 'react';
import { connect } from 'dva';
import styles from './ExampleIndexPage.css';
function ExampleIndexPage() {
return (
<div className={styles.normal}>
<h1 className={styles.title}>Yay! Welcome to dva!</h1>
<div className={styles.welcome} />
<ul className={styles.list}>
<li>To get started, edit <code>src/index.js</code> and save to reload.</li>
<li><a href="https://github.com/dvajs/dva-docs/blob/master/v1/en-us/getting-started.md">Getting Started</a></li>
</ul>
</div>
);
}
ExampleIndexPage.propTypes = {
};
export default connect()(ExampleIndexPage);
|
src/Range/Range.js
|
nirhart/wix-style-react
|
import React from 'react';
import {children, optional, once} from '../Composite';
import Label from '../Label';
import Input from '../Input';
import RangeInputWithLabelComposite from '../Composite/RangeInputWithLabelComposite/RangeInputWithLabelComposite';
const Range = ({...props, children}) => (
<RangeInputWithLabelComposite {...props}>
{children}
</RangeInputWithLabelComposite>
);
Range.propTypes = {
children: children(optional(Label), once(Input), once(Input))
};
Range.displayName = 'Range';
export default Range;
|
src/svg-icons/maps/local-library.js
|
spiermar/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalLibrary = (props) => (
<SvgIcon {...props}>
<path d="M12 11.55C9.64 9.35 6.48 8 3 8v11c3.48 0 6.64 1.35 9 3.55 2.36-2.19 5.52-3.55 9-3.55V8c-3.48 0-6.64 1.35-9 3.55zM12 8c1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3 1.34 3 3 3z"/>
</SvgIcon>
);
MapsLocalLibrary = pure(MapsLocalLibrary);
MapsLocalLibrary.displayName = 'MapsLocalLibrary';
MapsLocalLibrary.muiName = 'SvgIcon';
export default MapsLocalLibrary;
|
index.ios.js
|
dddzg/app
|
/**
* 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 app extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake 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('app', () => app);
|
imports/api/administrativeAreas/administrativeAreas.js
|
howlround/worldtheatremap
|
// Meteor
import { Mongo } from 'meteor/mongo';
import React from 'react';
import ReactSelect from 'react-select';
import { FormattedMessage } from 'react-intl';
import t from 'tcomb-form';
class AdministrativeAreasCollection extends Mongo.Collection {
// insert(profile, callback) {
// }
// remove(selector, callback) {
// }
}
export const AdministrativeAreas = new AdministrativeAreasCollection('AdministrativeAreas');
// Deny all client-side updates since we will be using methods to manage this collection
AdministrativeAreas.deny({
insert() { return true; },
update() { return true; },
remove() { return true; },
});
AdministrativeAreas.publicFields = {
value: 1,
label: 1,
};
export const factory = () => {
// Administrative Area options
const ExistingAdministrativeAreas = AdministrativeAreas.find({}, { sort: { label: 1 } }).fetch();
// Administrative Area template
const existingAdministrativeAreasTags = t.form.Form.templates.select.clone({
renderSelect: (locals) => {
function onChange(options) {
const values = (options || []).map(({ value }) => value);
locals.onChange(values);
}
const placeholder = (
<FormattedMessage
id="forms.selectPlaceholder"
description="Select widget placeholder"
defaultMessage="Select..."
/>
);
return (
<ReactSelect
multi
autoBlur
options={ExistingAdministrativeAreas}
value={locals.value}
onChange={onChange}
className="administrative-area-select-edit"
placeholder={placeholder}
/>
);
},
});
// Administrative Area factory function
class ReactSelectExistingAdministrativeAreasFactory extends t.form.Component {
getTemplate() {
return existingAdministrativeAreasTags;
}
}
// Administrative Area transformer
ReactSelectExistingAdministrativeAreasFactory.transformer = t.form.List.transformer;
return ReactSelectExistingAdministrativeAreasFactory;
};
|
examples/src/components/examples/RightToLeft.js
|
rackt/react-tabs
|
import React from 'react';
import ExampleItem from '../ExampleItem';
const code = `const Component = (
<div dir="rtl">
<Tabs direction={'rtl'}>
<TabList>
<Tab>כותרת</Tab>
<Tab disabled>כותרת כבויה</Tab>
<Tab>כותרת שנייה</Tab>
<Tab>כותרת שלישית</Tab>
</TabList>
<TabPanel>
<p>
לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.
</p>
<p>
Source:{' '}
<a href="https://en.wikipedia.org/wiki/" target="_blank">
Wikipedia
</a>
</p>
</TabPanel>
<TabPanel>
<p>
לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.
</p>
<p>
Source:{' '}
<a href="https://en.wikipedia.org/wiki/" target="_blank">
Wikipedia
</a>
</p>
</TabPanel>
<TabPanel>
<p>
לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.
לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.
לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.
</p>
<p>
Source:{' '}
<a href="https://en.wikipedia.org/wiki/" target="_blank">
Wikipedia
</a>
</p>
</TabPanel>
<TabPanel>
<h4>תת כותרת</h4>
<p>
לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.
לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית לורם איפסום דולור סיט אמט, קונסקטורר אדיפיסינג אלית. סת אלמנקום ניסי נון ניבאה. דס איאקוליס וולופטה דיאם. וסטיבולום אט דולור, קראס אגת לקטוס וואל אאוגו וסטיבולום סוליסי טידום בעליק. קונדימנטום קורוס בליקרה, נונסטי קלובר בריקנה סטום, לפריקך תצטריק לרטי.
</p>
<p>
Source:{' '}
<a href="https://en.wikipedia.org/wiki/" target="_blank">
Wikipedia
</a>
</p>
</TabPanel>
</Tabs>
</div>
);
render(Component);`;
const hint =
'This is an example of a right to left option. Just pass the `direction` prop to the <Tabs /> element';
export default () => (
<ExampleItem
code={code}
direction="rtl"
hint={hint}
label="Right To Left Example"
/>
);
|
src/AppNavigator.js
|
mstmustisnt/wishlist
|
/*
*
* @providesModule AppNavigator
*
* */
import React from 'react';
import { observable, action } from 'mobx';
import { observer, Provider } from 'mobx-react';
import { StackNavigator } from 'react-navigation';
import { Root, Content } from 'native-base';
import appStyles from 'appStyles';
import ManageWishItemScreen from 'ManageWishItemScreen';
import ManageListScreen from 'ManageListScreen';
import ListsScreen from 'ListsScreen';
import WishItemsScreen from 'WishItemsScreen';
import Layout from './components/Layout';
import stores from './stores';
const navItems = [
{ title: 'Lists', component: ListsScreen, path: 'lists', },
{ title: 'New List', component: ManageListScreen, path: 'lists/create' },
{ title: 'Edit List', component: ManageListScreen, path: 'lists/:id/edit' },
{ title: 'New Wish', component: ManageWishItemScreen, path: 'wishes/create' },
{
title: 'Edit Wish',
component: ManageWishItemScreen,
path: 'lists/:listId/wishes/:id/edit'
},
{ title: 'Wishes', component: WishItemsScreen, path: 'lists/:id/wishes' },
];
const navOptions = {};
navItems.forEach((item) => {
const { component: Component, navigationOptions = {}, title } = item;
return navOptions[item.title] = {
screen(props) {
return (
<Layout {...props}>
<Component {...props}/>
</Layout>
);
},
path: item.path,
navigationOptions: Object.assign({ title }, navigationOptions)
};
});
const Navigator = StackNavigator(navOptions);
@observer
class AppNavigator extends React.Component {
render() {
return (
<Root>
<Provider {...stores}>
<Navigator style={appStyles.content}/>
</Provider>
</Root>
);
}
}
export default AppNavigator;
|
src/backward/Widgets/Title.js
|
sampsasaarela/NativeBase
|
import React from 'react';
import { Platform, View } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import { Text } from './Text';
import computeProps from '../../Utils/computeProps';
class Title extends NativeBaseComponent {
prepareRootProps() {
const type = {
fontFamily: this.getTheme().btnFontFamily,
fontWeight: (Platform.OS === 'ios') ? '500' : undefined,
alignSelf: (Platform.OS === 'ios') ? 'center' : 'flex-start',
};
const defaultProps = {
style: type,
};
return computeProps(this.props, defaultProps);
}
render() {
return (
<View style={{ justifyContent: 'center' }}><Text ref={c => this._root = c} {...this.prepareRootProps()} numberOfLines={1}>{this.props.children}</Text></View>
);
}
}
Title.propTypes = {
...Text.propTypes,
style: React.PropTypes.object,
};
const StyledTitle = connectStyle('NativeBase.Title', {}, mapPropsToStyleNames)(Title);
export {
StyledTitle as Title,
};
|
src/utils/createContextWrapper.js
|
tonylinyy/react-bootstrap
|
import React from 'react';
/**
* Creates new trigger class that injects context into overlay.
*/
export default function createContextWrapper(Trigger, propName) {
return function (contextTypes) {
class ContextWrapper extends React.Component {
getChildContext() {
return this.props.context;
}
render() {
// Strip injected props from below.
const {wrapped, context, ...props} = this.props;
return React.cloneElement(wrapped, props);
}
}
ContextWrapper.childContextTypes = contextTypes;
class TriggerWithContext {
render() {
const props = {...this.props};
props[propName] = this.getWrappedOverlay();
return (
<Trigger {...props}>
{this.props.children}
</Trigger>
);
}
getWrappedOverlay() {
return (
<ContextWrapper
context={this.context}
wrapped={this.props[propName]}
/>
);
}
}
TriggerWithContext.contextTypes = contextTypes;
return TriggerWithContext;
};
}
|
src/components/Navbar/Navbar/index.js
|
easingthemes/easingthemes.github.io
|
/**
*
* Navbar
*
*/
import React from 'react';
import styles from './styles.global.scss';
import Logo from 'components/navbar/Logo';
import Navigation from 'components/navbar/Navigation';
class Navbar extends React.Component {
//------------------------------------------------------------------------------------------------------------------
// React methods
//------------------------------------------------------------------------------------------------------------------
/**
*
* Set the initial state
*
* @private
*/
constructor(props) {
super(props);
this.state = {
pluginsInit: false
};
}
componentDidUpdate (nextProps, nextState) {
//console.log('nextState', nextState);
//console.log('Navbar did update: ', this.props.path);
this.initPlugins();
}
componentDidMount() {
//console.log('Navbar did mount: ', this.props.path);
}
initPlugins () {
/* --------------------------------------------
CLOSE COLLAPSE MENU ON MOBILE VIEW EXCEPT DROPDOWN
-------------------------------------------- */
$('.navbar-collapse ul li a:not(.dropdown-toggle)').on('click',function (event) {
$('.navbar-toggle:visible').click();
});
/* --------------------------------------------
STICKY SETTING
-------------------------------------------- */
if( $('.navbar-sticky').length > 0){
//$('.navbar-sticky').sticky({ topSpacing: 0 });
$('.navbar-sticky').css('z-index','100');
$('.navbar-sticky').addClass('bg-light');
$('.navbar-sticky').addClass('top-nav-collapse');
}
/* --------------------------------------------------------
NAVBAR FIXED TOP ON SCROLL
----------------------------------------------------------- */
const toggleNav = function() {
if ($('.navbar').offset().top > 10) {
$('.navbar-pasific-toggle').addClass('top-nav-collapse');
} else {
$('.navbar-pasific-toggle').removeClass('top-nav-collapse');
}
};
if (this.props.path !== '/' && this.props.path !== '/portfolio' && this.props.path !== '/contact') {
$('.navbar-pasific-toggle').addClass('top-nav-collapse');
$(window).off('scroll', toggleNav);
} else {
toggleNav();
//console.log('on');
$(window).on('scroll', toggleNav);
}
/* --------------------------------------------------------
NAVBAR-INVERSE FIXED TOP ON SCROLL
----------------------------------------------------------- */
if( $('.navbar-pasific-inverse').length > 0 ){
$(window).scroll(function() {
if ($('.navbar').offset().top > 10) {
$('.navbar-pasific').addClass('top-nav-collapse-inverse');
} else {
$('.navbar-pasific').removeClass('top-nav-collapse-inverse');
}
});
}
}
render() {
let navBg = '';
if (this.props.path !== '/' && this.props.path !== '/portfolio' && this.props.path !== '/contact') {
navBg = 'navbar-standart top-nav-collapse';
} else {
navBg = 'navbar-pasific-toggle';
}
//const path = this.props.path === '/' ? '' : 'navbar-standart'; //bg-white
const style = navBg + ' ';
//console.log('style', this.props.path);
return (
<nav className={style + ' navbar navbar-pasific navbar-fixed-top navbar-mp megamenu'}>
<div className="container-fluid">
<Logo />
<Navigation />
</div>
</nav>
);
}
}
export default Navbar;
|
src/server.js
|
montemishkin/mishkin_com
|
// third party imports
import express from 'express'
import compression from 'compression'
import logger from 'morgan'
import favicon from 'serve-favicon'
import serveStatic from 'serve-static'
import React from 'react'
import {renderToString} from 'react-dom/server'
import Helmet from 'react-helmet'
// local imports
import {
buildDir,
publicDir,
favicon as faviconPath,
} from 'config/projectPaths'
import Root from 'views/Root'
import renderTemplate from 'templates/index'
const server = express()
/* Server-wide Middleware */
// compress responses
server.use(compression())
// log requests
server.use(logger(process.env.NODE_ENV === 'production' ? 'combined' : 'dev'))
// serve favicon
server.use(favicon(faviconPath))
/* Routing */
// route static files to build and public dirs
server.use('/static', serveStatic(buildDir), serveStatic(publicDir))
// any url that hits this server
server.all('*', (req, res) => {
const renderedComponent = renderToString(<Root />)
// see: https://github.com/nfl/react-helmet#server-usage
const helmet = Helmet.rewind()
const html = renderTemplate({
renderedComponent,
title: helmet.title,
})
res.send(html)
})
export default server
|
blueocean-core-js/test/js/components/RunButton-spec.js
|
tfennelly/blueocean-plugin
|
/**
* Created by cmeyers on 9/16/16.
*/
import React from 'react';
import { assert } from 'chai';
import { shallow } from 'enzyme';
import utils from '../../../src/js/utils';
import { RunButton } from '../../../src/js/components/RunButton';
describe('RunButton', () => {
let pipeline;
beforeEach(() => {
pipeline = utils.clone(require('../data/pipeline-1.json'));
});
it('renders without errors when no props are specified', () => {
const wrapper = shallow(<RunButton />);
assert.isOk(wrapper);
});
describe('run button', () => {
describe('in non-running state', () => {
it('renders correctly when permissions are valid', () => {
pipeline.permissions.start = true;
const wrapper = shallow(<RunButton runnable={pipeline} latestRun={pipeline.latestRun} />);
assert.isOk(wrapper);
assert.equal(wrapper.find('.run-button-component').length, 1);
assert.equal(wrapper.find('.run-button').length, 1);
assert.equal(wrapper.find('.stop-button').length, 0);
});
it('does not render when permissions are invalid', () => {
pipeline.permissions.start = false;
const wrapper = shallow(<RunButton runnable={pipeline} latestRun={pipeline.latestRun} />);
assert.isOk(wrapper);
assert.equal(wrapper.find('.run-button-component').length, 0);
assert.equal(wrapper.find('.run-button').length, 0);
assert.equal(wrapper.find('.stop-button').length, 0);
});
});
describe('running state', () => {
beforeEach(() => {
pipeline.latestRun.state = 'RUNNING';
});
it('renders correctly when permissions are valid', () => {
pipeline.permissions.stop = true;
const wrapper = shallow(<RunButton runnable={pipeline} latestRun={pipeline.latestRun} />);
assert.isOk(wrapper);
assert.equal(wrapper.find('.run-button-component').length, 1);
assert.equal(wrapper.find('.run-button').length, 0);
assert.equal(wrapper.find('.stop-button').length, 1);
});
it('does not render when permissions are invalid', () => {
pipeline.permissions.stop = false;
const wrapper = shallow(<RunButton runnable={pipeline} latestRun={pipeline.latestRun} />);
assert.isOk(wrapper);
assert.equal(wrapper.find('.run-button-component').length, 0);
assert.equal(wrapper.find('.run-button').length, 0);
assert.equal(wrapper.find('.stop-button').length, 0);
});
});
});
});
|
src/App.js
|
tal87/operationcode_frontend
|
import React, { Component } from 'react';
import { Route, Router } from 'react-router';
import ReactGA from 'react-ga';
import createHistory from 'history/createBrowserHistory';
import ScrollToTop from 'shared/components/scrollToTop/scrollToTop';
import Home from './scenes/home/home';
const history = createHistory();
ReactGA.initialize('UA-75642413-1');
class App extends Component {
componentDidMount() {
if (process.env.NODE_ENV === 'production') {
// History listening doesn't catch first page load
ReactGA.set({ page: history.location.pathname });
ReactGA.pageview(history.location.pathname);
history.listen((location) => {
ReactGA.set({ page: location.pathname });
ReactGA.pageview(location.pathname);
});
}
}
render() {
return (
<Router history={history}>
<ScrollToTop>
<Route path="/" component={Home} />
</ScrollToTop>
</Router>
);
}
}
export default App;
|
src/view/private/index.js
|
coma/spotify
|
import React from 'react';
import style from './index.css';
import Top from './top';
import Nav from './nav';
class PrivateView extends React.Component {
render () {
return (
<div className={ style.main }>
<Top/>
<div className={ style.body }>
<Nav/>
<main className={ style.content }>{ this.props.children }</main>
</div>
</div>
);
}
}
export default PrivateView;
|
src/components/Footer/Footer.js
|
DaveSpringer/bmg-rap-sheets
|
import React from 'react'
import './style/Footer.scss'
class Footer extends React.Component {
render () {
return (
<div className='utility-belt-footer footer hidden-print'>
<p>© TM © DC Comics. WB SHIELD: TM; Warner Bros. Entertainment. Inc. (s17). Copyright © 2017 DC Comics.
All characters, their distinctive likenesses and related elements featured in this publication are trademarks of DC Comics.
Their stories, characters and incidents featured in this publication are entirely fictional.</p>
<p>Batman Miniature Game ©2008-2017 KNIGHT MODELS - All Rights Reserved.</p>
<p>Bruce's Utility Belt ©2017 David Springer</p>
</div>
)
}
}
export default Footer
|
src/components/pages/preferences/Images.js
|
DragonLegend/game
|
import React from 'react';
import ImagesForm from '../../preferences/ImagesForm';
export default () => (
<div>
<h2>Images</h2>
<ImagesForm />
</div>
);
|
writeExampleWebpack2Middleware/src/js/App.js
|
fengnovo/webpack-react
|
import React from 'react'
import Header from './containers/Header'
import Body from './containers/Body'
import Footer from './containers/Footer'
class App extends React.Component {
constructor (props) {
super(props)
}
render () {
return <div>
<Header />
<Body />
<Footer />
</div>
}
}
export default App
|
src/components/article/LeadingImage.js
|
garfieldduck/twreporter-react
|
/* eslint no-unused-vars:0 */
'use strict'
import React from 'react' // eslint-disable-line
import ReactDOM from 'react-dom'
import classNames from 'classnames'
import styles from './LeadingImage.scss'
import { getImageSrcSet, replaceStorageUrlPrefix } from '../../utils/'
// lodash
import get from 'lodash/get'
const _ = {
get
}
class LeadingImage extends React.Component {
constructor(props) {
super(props)
this.state = {
isMount: false
}
}
componentDidMount() {
this.setState({
isMount: true
})
}
render() {
const { size, image, id, description } = this.props
let leadingImgClass
if (!image) {
return null
}
switch (size) {
case 'normal':
leadingImgClass = 'leading-img'
break
case 'extend':
leadingImgClass = 'extended-leading-img'
break
case 'small':
leadingImgClass = 'small-leading-img'
break
default:
leadingImgClass = 'leading-img'
break
}
const defaultImgUrl = replaceStorageUrlPrefix(_.get(image, 'tiny.url'))
const imgJsx = this.state.isMount ? (
<img src={defaultImgUrl} alt={description} srcSet={getImageSrcSet(image)} />
) : (
<img src={defaultImgUrl} alt={description} className={styles['img-placeholder']} />
)
return (
<div className={styles[leadingImgClass]}>
{imgJsx}
</div>
)
}
}
LeadingImage.propTypes = {
size: React.PropTypes.string,
image: React.PropTypes.object,
description: React.PropTypes.string,
id: React.PropTypes.string
}
LeadingImage.defaultProps = {
size: 'normal',
image: null,
description: '',
id: ''
}
export { LeadingImage }
|
src/schema/test.dataSchema.js
|
RodgerLai/nodejs-nedb-excel
|
import React from 'react';
import {Icon} from 'antd';
// 定义某个表的dataSchema, 结构跟querySchema很相似, 见下面的例子
// 注意: 所有的key不能重复
// 这个配置不只决定了table的schema, 也包括用于新增/删除的表单的schema
module.exports = [
{
key: 'id', // 传递给后端的key
title: 'ID', // 前端显示的名字
// 其实dataType对前端的意义不大, 更重要的是生成后端接口时要用到, 所以要和DB中的类型一致
// 对java而言, int/float/varchar/datetime会映射为Long/Double/String/Date
dataType: 'int', // 数据类型, 目前可用的: int/float/varchar/datetime
// 这一列是否是主键?
// 如果不指定主键, 不能update/delete, 但可以insert
// 如果指定了主键, insert/update时不能填写主键的值;
// 只有int/varchar可以作为主键, 但是实际上主键一般都是自增id
primary: true,
// 可用的showType: normal/radio/select/checkbox/multiSelect/textarea/image/imageArray/file
// FIXME: image/imageArray/file类型暂未实现
showType: 'normal', // 默认是normal, 就是最普通的输入框
showInTable: true, // 这一列是否要在table中展示, 默认true
disabled: false, // 表单中这一列是否禁止编辑, 默认false
// 扩展接口, 决定了这一列渲染成什么样子
render: (text, record) => text,
},
{
key: 'name',
title: '用户名',
dataType: 'varchar', // 对于普通的input框, 可以设置addonBefore/addonAfter
placeholder: '请输入用户名',
addonBefore: (<Icon type="user"/>),
addonAfter: '切克闹',
defaultValue: 'foolbear', // 默认值, 只在insert时生效, update时不生效
},
{
key: 'weight',
title: '体重(千克)',
dataType: 'int',
min: 10,
defaultValue: 70, // 默认值
disabled: true,
showInForm: false, // 这一列是否要在表单中展示, 默认true. 这种列一般都是不需要用户输入的, DB就会给一个默认值那种
},
{
key: 'gender',
title: '性别',
dataType: 'int',
showType: 'radio',
options: [{key: '1', value: '男'}, {key: '2', value: '女'}],
defaultValue: '1',
disabled: true,
},
{
key: 'marriage',
title: '婚否',
dataType: 'varchar',
showType: 'select',
options: [{key: 'yes', value: '已婚'}, {key: 'no', value: '未婚'}],
// 对于dataSchema可以设置校验规则, querySchema不能设置
// 设置校验规则, 参考https://github.com/yiminghe/async-validator#rules
validator: [{type: 'string', required: true, message: '必须选择婚否!'}],
},
{
key: 'interest',
title: '兴趣爱好',
dataType: 'int',
showType: 'checkbox',
options: [{key: '1', value: '吃饭'}, {key: '2', value: '睡觉'}, {key: '3', value: '打豆豆'}],
defaultValue: ['1', '2'],
validator: [{type: 'array', required: true, message: '请至少选择一项兴趣'}],
},
{
key: 'good',
title: '优点',
dataType: 'varchar',
showType: 'multiSelect',
options: [{key: 'lan', value: '懒'}, {key: 'zhai', value: '宅'}],
validator: [{type: 'array', required: true, message: '请选择优点'}],
},
{
key: 'pic1',
title: '头像',
dataType: 'varchar',
showType: 'image', // 后端必须提供图片上传接口
showInTable: false,
},
{
key: 'pic2',
title: '自拍',
dataType: 'varchar',
showType: 'imageArray', // 上传多张图片
limit: 5, // 最多传几张图片
showInTable: false,
},
{
key: 'jianli',
title: '简历',
dataType: 'varchar',
showType: 'file', // 文件上传
url: 'xxx', // 要上传的地址
disabled: true,
showInTable: false,
},
{
key: 'desc',
title: '个人简介',
dataType: 'varchar',
showType: 'textarea', // 用于编辑大段的文本
showInTable: false,
defaultValue: '个人简介个人简介个人简介',
validator: [{type: 'string', max: 20, message: '最长20个字符'}],
},
{
key: 'score',
title: '分数',
dataType: 'int',
max: 99,
min: 9,
},
{
key: 'gpa',
title: 'GPA',
dataType: 'float',
max: 9.9,
placeholder: '哈哈',
},
{
key: 'birthday',
title: '生日',
// 对于日期类型要注意下, 在js端日期被表示为yyyy-MM-dd HH:mm:ss的字符串, 在java端日期被表示为java.util.Date对象
// fastjson反序列化时可以自动识别
// 序列化倒是不用特别配置, 看自己需求, fastjson会序列化为一个字符串, 前端原样展示
dataType: 'datetime',
// 对于datetime而言, 配置showType是无意义的
placeholder: 'happy!',
},
{
key: 'xxday',
title: 'xx日期',
dataType: 'datetime',
defaultValue: '2017-01-01 11:22:33',
showInTable: false,
showInForm: false, // 这个只是测试下...如果一列在table和form中都不出现, 那就不如直接去掉.
// 另外showInForm=false时, 很多针对form的字段都没意义了, 比如defaultValue/placeholder/validator等等
},
];
|
examples/counter/containers/Root.js
|
yz89/redux
|
import React, { Component } from 'react';
import { Provider } from 'react-redux';
import CounterApp from './CounterApp';
import configureStore from '../store/configureStore';
const store = configureStore();
export default class Root extends Component {
render() {
return (
<Provider store={store}>
{() => <CounterApp />}
</Provider>
);
}
}
|
lib/withData.js
|
wzalazar/spotify
|
import React from 'react'
import PropsTypes from 'prop-types'
import { Provider } from 'react-redux'
import initStore from './initStore'
import { get } from 'lodash'
import ip from 'ip'
export default (Component) => (
class extends React.Component {
static propTypes = {
initialState: PropsTypes.object,
}
static defaultProps = {
initialState: {},
}
static async getInitialProps(ctx) {
const headers = get(ctx, 'req.headers', {})
ctx.isServer = get(ctx, 'req', false)
const currentHost = get(ctx, 'req.headers.host', 'localhost')
const host = process.env.NODE_ENV === 'production' ? currentHost : ip.address()
const isProduction = process.env.NODE_ENV === 'production' ? true : false
const config = { host, isProduction }
if (ctx.isServer) {
ctx.config = { config }
}
const { store } = initStore()
ctx.store = store
const props = {
url: { ...ctx.query, pathname: ctx.pathname },
...await (Component.getInitialProps ? Component.getInitialProps(ctx) : {}),
}
const state = ctx.store.getState()
return {
initialState: {
...state,
config,
},
headers,
...props,
}
}
constructor(props) {
super(props)
const { store } = initStore(props.initialState)
this.store = store
}
render() {
return (
<Provider store={this.store}>
<Component {...this.props} />
</Provider>
)
}
}
)
|
packages/material-ui-icons/legacy/SignalCellularConnectedNoInternet3BarSharp.js
|
lgollut/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fillOpacity=".3" d="M22 8V2L2 22h16V8h4z" /><path d="M18 22V6L2 22h16zm2-12v8h2v-8h-2zm0 12h2v-2h-2v2z" /></React.Fragment>
, 'SignalCellularConnectedNoInternet3BarSharp');
|
examples/huge-apps/app.js
|
shunitoh/react-router
|
import React from 'react'
import { render } from 'react-dom'
import { Router, browserHistory } from 'react-router'
import withExampleBasename from '../withExampleBasename'
import './stubs/COURSES'
const rootRoute = {
childRoutes: [ {
path: '/',
component: require('./components/App'),
childRoutes: [
require('./routes/Calendar'),
require('./routes/Course'),
require('./routes/Grades'),
require('./routes/Messages'),
require('./routes/Profile')
]
} ]
}
render((
<Router
history={withExampleBasename(browserHistory, __dirname)}
routes={rootRoute}
/>
), document.getElementById('example'))
// I've unrolled the recursive directory loop that is happening above to get a
// better idea of just what this huge-apps Router looks like, or just look at the
// file system :)
//
// import { Route } from 'react-router'
// import App from './components/App'
// import Course from './routes/Course/components/Course'
// import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar'
// import Announcements from './routes/Course/routes/Announcements/components/Announcements'
// import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement'
// import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar'
// import Assignments from './routes/Course/routes/Assignments/components/Assignments'
// import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment'
// import CourseGrades from './routes/Course/routes/Grades/components/Grades'
// import Calendar from './routes/Calendar/components/Calendar'
// import Grades from './routes/Grades/components/Grades'
// import Messages from './routes/Messages/components/Messages'
// render(
// <Router>
// <Route path="/" component={App}>
// <Route path="calendar" component={Calendar} />
// <Route path="course/:courseId" component={Course}>
// <Route path="announcements" components={{
// sidebar: AnnouncementsSidebar,
// main: Announcements
// }}>
// <Route path=":announcementId" component={Announcement} />
// </Route>
// <Route path="assignments" components={{
// sidebar: AssignmentsSidebar,
// main: Assignments
// }}>
// <Route path=":assignmentId" component={Assignment} />
// </Route>
// <Route path="grades" component={CourseGrades} />
// </Route>
// <Route path="grades" component={Grades} />
// <Route path="messages" component={Messages} />
// <Route path="profile" component={Calendar} />
// </Route>
// </Router>,
// document.getElementById('example')
// )
|
app/App.js
|
mastermel/wwg_battle_tool
|
import React, { Component } from 'react';
import { createStore } from 'redux';
import { Provider, connect } from 'react-redux';
import { Router, Scene, ActionConst } from 'react-native-router-flux';
import { appReducer } from './Reducers/index';
import { navColor, font } from './Shared/Styles';
import Home from './Scenes/Home/index';
import Units from './Scenes/Units/index';
const store = createStore(appReducer);
const ConnectedRouter = connect()(Router);
export default class App extends Component {
render() {
return (
<Provider store={store}>
<ConnectedRouter>
<Scene key='root'
navigationBarStyle={styles.navigationBarStyle}
navBarButtonColor={font.color}
titleStyle={styles.titleStyle}
>
<Scene key='home'
initial
title='Home'
component={Home}
type={ActionConst.REPLACE}
/>
<Scene key='units'
title='Units'
component={Units}
/>
</Scene>
</ConnectedRouter>
</Provider>
);
}
}
const styles = {
navigationBarStyle: {
backgroundColor: navColor,
},
titleStyle: {
color: font.color,
},
};
|
docs/app/Examples/elements/Reveal/Content/index.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const RevealContentExamples = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Visible Content'
description='A reveal may contain content that is visible before interaction.'
examplePath='elements/Reveal/Content/RevealExampleVisible'
/>
<ComponentExample
title='Hidden Content'
description='A reveal may contain content that is hidden before user interaction.'
examplePath='elements/Reveal/Content/RevealExampleHidden'
/>
</ExampleSection>
)
export default RevealContentExamples
|
components/auth/Forget.js
|
digithun/jamplay-nap
|
import React from 'react'
import PropTypes from 'prop-types'
import { gql, graphql } from 'react-apollo'
import userProfile from '../userProfile.gql'
const Forget = ({ forget }) => {
const handleSubmit = e => {
e.preventDefault()
let email = e.target.elements.email.value
if (email === '') {
window.alert('Email fields are required.')
return false
}
forget(email)
}
return (
<form onSubmit={handleSubmit}>
<h1>Forget Password (GraphQL)</h1>
<input placeholder='email' name='email' defaultValue='katopz@gmail.com' />
<button type='submit'>Forget</button>
<style jsx>{`
form {
border-bottom: 1px solid #ececec;
padding-bottom: 20px;
margin-bottom: 20px;
}
h1 {
font-size: 20px;
}
input {
display: block;
margin-bottom: 10px;
}
`}</style>
</form>
)
}
const forget = gql`
mutation forget($email: String!) {
forget(email: $email) {
status
}
}
`
Forget.propTypes = () => ({
forget: PropTypes.func.isRequired
})
export default graphql(forget, {
props: ({ mutate }) => ({
forget: email =>
mutate({
variables: { email },
update: (proxy, { data }) => {
// Read the data from our cache for this query.
let cached = proxy.readQuery({ query: userProfile })
// User
cached.user = cached.user || {
_id: null,
name: null,
status: null,
isLinkedWithFacebook: null,
__typename: 'User'
}
cached.user.status = data.forget.status
// Write our data back to the cache.
proxy.writeQuery({ query: userProfile, data: cached })
}
}).catch(err => {
window.alert(err.message)
})
})
})(Forget)
|
src/gifPreview/index.js
|
SodhanaLibrary/react-examples
|
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './app';
render( <AppContainer><App/></AppContainer>, document.querySelector("#app"));
if (module.hot) {
module.hot.accept('./app.js', () => {
const App = require('./app.js').default;
render(
<AppContainer>
<App/>
</AppContainer>,
document.querySelector("#app")
);
});
}
|
src/main.js
|
ryanturner7/portfolio
|
import React from 'react'
import ReactDom from 'react-dom'
import {BrowserRouter, Route} from 'react-router-dom'
class App extends React.Component {
// constructor
constructor(props){
super(props)
this.state = {
content: '',
}
this.getApp = this.getApp.bind(this)
}
//hooks
componentDidUpdate(){
console.log('__STATE__', this.state)
}
//methods
getApp(){
return {
state: this.state,
setState: this.setState.bind(this)
}
}
//render
render(){
return (
<main className='app'>
<BrowserRouter>
<div>
</div>
</BrowserRouter>
</main>
)
}
}
ReactDom.render(<App title='' />, document.getElementById('root'))
|
app/utils.js
|
MichelHalmes/sankey
|
import React from 'react';
import request from 'superagent';
var MIN_LINK_VALUE = 50;
function loadData(path) {
request
.get(path)
.end((err, res) => {
if (err) { console.log(err); }
var links = res.body.links;
var nodes = res.body.nodes.map((node, i) => {
if (!node.node_id) { node.node_id = i; }
return node
});
this.setState({nodes, links});
});
}
function parseLevelData(level_nodes, level_links, split_level_1){
var node_map = parseLevelNodes(level_nodes, split_level_1);
var links = parseLevelLinks(level_links, node_map, split_level_1);
var nodes = Array.from(node_map.values())
.filter((node) => node.source_value>MIN_LINK_VALUE || node.target_value>MIN_LINK_VALUE)
// .filter((node, index, self) => index === self.findIndex((t) => (
// t.node_id === node.node_id && t.name === node.name
// ))
// );
return {nodes, links}
}
function parseLevelNodes(level_nodes, split_level_1) {
var node_map = new Map();
var node_count = -1;
var prev_level_1 = null;
level_nodes.sort((a,b) => a.level_1.localeCompare(b.level_1));
level_nodes.forEach(function(node) {
if(node.level_1 == split_level_1) {
node_count++;
node_map.set(node.level_0, {node_id: node_count, name: node.level_0, source_value: 0, target_value: 0, is_split: true});
} else {
if (node.level_1 != prev_level_1) {
node_count++;
prev_level_1 = node.level_1;
}
node_map.set(node.level_0, {node_id: node_count, name: node.level_1, source_value: 0, target_value: 0});
}
});
return node_map;
}
function parseLevelLinks(level_links, node_map, split_level_1) {
level_links = level_links.map(function(link) {
var source = node_map.get(link.source_0);
if (!source){
console.log(`The link '${link}'' has the source '${link.source_0}' unspecified in the nodes`);
return {delete: true}; // Will be filtered
}
var target = node_map.get(link.target_0);
if (!target){
console.log(`The link '${link}'' has the target '${link.target_0}' unspecified in the nodes`);
return {delete: true}; // Will be filtered
}
if (!split_level_1 || source.is_split || target.is_split) {
source.source_value+= link.value;
target.target_value+= link.value;
return {source: source, target: target, value : link.value}
} else {
return {delete: true}; // Will be filtered
}
});
level_links = level_links.filter((link) => (
!link.delete && link.source.node_id != link.target.node_id
&& link.value > MIN_LINK_VALUE
&& (link.value > 0.2*link.source.source_value || link.value > 0.2*link.target.target_value)
))
.map((link) => ({source: link.source.node_id, target: link.target.node_id, value: link.value}) )
.sort((a, b) => a.source - b.source || a.target - b.target);
var links = level_links.reduce(function (acc, curr, idx) {
var prev = level_links[idx-1] || {source: -1, target: -1};
if (curr.source == prev.source && curr.target == prev.target) {
acc[acc.length - 1].value += curr.value;
} else {
acc.push(curr);
}
return acc;
}, []);
return links;
}
export { loadData, parseLevelData }
|
test/ModalSpec.js
|
natlownes/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Modal from '../src/Modal';
import { render, shouldWarn } from './helpers';
describe('Modal', function () {
let mountPoint;
beforeEach(() => {
mountPoint = document.createElement('div');
document.body.appendChild(mountPoint);
});
afterEach(function () {
React.unmountComponentAtNode(mountPoint);
document.body.removeChild(mountPoint);
});
it('Should render the modal content', function() {
let noOp = function () {};
let instance = render(
<Modal show onHide={noOp} animation={false}>
<strong>Message</strong>
</Modal>
, mountPoint);
assert.ok(
ReactTestUtils.findRenderedDOMComponentWithTag(instance.refs.modal, 'strong'));
});
it('Should add modal-open class to the modal container while open', function(done) {
let Container = React.createClass({
getInitialState() {
return { modalOpen: true };
},
handleCloseModal() {
this.setState({ modalOpen: false });
},
render() {
return (
<div>
<Modal
animation={false}
show={this.state.modalOpen}
onHide={this.handleCloseModal}
container={this}
>
<strong>Message</strong>
</Modal>
</div>
);
}
});
let instance = render(
<Container />
, mountPoint);
let modal = ReactTestUtils.findRenderedComponentWithType(instance, Modal);
assert.ok(React.findDOMNode(instance).className.match(/\bmodal-open\b/));
let backdrop = React.findDOMNode(modal.refs.backdrop);
ReactTestUtils.Simulate.click(backdrop);
setTimeout(function() {
assert.equal(React.findDOMNode(instance).className.length, 0);
done();
}, 0);
});
it('Should close the modal when the backdrop is clicked', function (done) {
let doneOp = function () { done(); };
let instance = render(
<Modal show onHide={doneOp} animation={false}>
<strong>Message</strong>
</Modal>
, mountPoint);
let backdrop = React.findDOMNode(instance.refs.backdrop);
ReactTestUtils.Simulate.click(backdrop);
});
it('Should close the modal when the modal dialog is clicked', function (done) {
let doneOp = function () { done(); };
let instance = render(
<Modal show onHide={doneOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = React.findDOMNode(instance.refs.dialog);
ReactTestUtils.Simulate.click(dialog);
});
it('Should not close the modal when the "static" backdrop is clicked', function () {
let onHideSpy = sinon.spy();
let instance = render(
<Modal show onHide={onHideSpy} backdrop='static'>
<strong>Message</strong>
</Modal>
, mountPoint);
let backdrop = React.findDOMNode(instance.refs.backdrop);
ReactTestUtils.Simulate.click(backdrop);
expect(onHideSpy).to.not.have.been.called;
});
it('Should close the modal when the modal close button is clicked', function (done) {
let doneOp = function () { done(); };
let instance = render(
<Modal show onHide={doneOp}>
<Modal.Header closeButton />
<strong>Message</strong>
</Modal>
, mountPoint);
let button = React.findDOMNode(instance.refs.modal)
.getElementsByClassName('close')[0];
ReactTestUtils.Simulate.click(button);
});
it('Should pass className to the dialog', function () {
let noOp = function () {};
let instance = render(
<Modal show className='mymodal' onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = React.findDOMNode(instance.refs.dialog);
assert.ok(dialog.className.match(/\bmymodal\b/));
});
it('Should use bsClass on the dialog', function () {
let noOp = function () {};
let instance = render(
<Modal show bsClass='mymodal' onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = React.findDOMNode(instance.refs.dialog);
let backdrop = React.findDOMNode(instance.refs.backdrop);
assert.ok(dialog.className.match(/\bmymodal\b/));
assert.ok(dialog.children[0].className.match(/\bmymodal-dialog\b/));
assert.ok(dialog.children[0].children[0].className.match(/\bmymodal-content\b/));
assert.ok(backdrop.className.match(/\bmymodal-backdrop\b/));
shouldWarn("Invalid prop 'bsClass' of value 'mymodal'");
});
it('Should pass bsSize to the dialog', function () {
let noOp = function () {};
let instance = render(
<Modal show bsSize='small' onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = React.findDOMNode(instance.refs.modal).getElementsByClassName('modal-dialog')[0];
assert.ok(dialog.className.match(/\bmodal-sm\b/));
});
it('Should pass dialogClassName to the dialog', function () {
let noOp = function () {};
let instance = render(
<Modal show dialogClassName="testCss" onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
let dialog = ReactTestUtils.findRenderedDOMComponentWithClass(instance.refs.modal, 'modal-dialog');
assert.match(dialog.props.className, /\btestCss\b/);
});
it('Should assign refs correctly when no backdrop', function () {
let test = () => render(
<Modal show backdrop={false} onHide={function () {}}>
<strong>Message</strong>
</Modal>
, mountPoint);
expect(test).not.to.throw();
});
it('Should use dialogComponent', function () {
let noOp = function () {};
class CustomDialog {
render() { return <div {...this.props}/>; }
}
let instance = render(
<Modal show dialogComponent={CustomDialog} onHide={noOp}>
<strong>Message</strong>
</Modal>
, mountPoint);
assert.ok(instance.refs.dialog instanceof CustomDialog);
});
it('Should pass transition callbacks to Transition', function (done) {
let count = 0;
let increment = ()=> count++;
let instance = render(
<Modal show
onHide={() => {}}
onExit={increment}
onExiting={increment}
onExited={()=> {
increment();
expect(count).to.equal(6);
done();
}}
onEnter={increment}
onEntering={increment}
onEntered={()=> {
increment();
instance.setProps({ show: false });
}}
>
<strong>Message</strong>
</Modal>
, mountPoint);
});
it('Should unbind listeners when unmounted', function() {
render(
<div>
<Modal show onHide={() => null} animation={false}>
<strong>Foo bar</strong>
</Modal>
</div>
, mountPoint);
assert.include(document.body.className, 'modal-open');
render(<div />, mountPoint);
assert.notInclude(document.body.className, 'modal-open');
});
describe('Focused state', function () {
let focusableContainer = null;
beforeEach(() => {
focusableContainer = document.createElement('div');
focusableContainer.tabIndex = 0;
document.body.appendChild(focusableContainer);
focusableContainer.focus();
});
afterEach(function () {
React.unmountComponentAtNode(focusableContainer);
document.body.removeChild(focusableContainer);
});
it('Should focus on the Modal when it is opened', function () {
document.activeElement.should.equal(focusableContainer);
let instance = render(
<Modal show onHide={() => {}} animation={false}>
<strong>Message</strong>
</Modal>
, focusableContainer);
document.activeElement.className.should.contain('modal');
instance.renderWithProps({ show: false });
document.activeElement.should.equal(focusableContainer);
});
it('Should not focus on the Modal when autoFocus is false', function () {
render(
<Modal show autoFocus={false} onHide={() => {}} animation={false}>
<strong>Message</strong>
</Modal>
, focusableContainer);
document.activeElement.should.equal(focusableContainer);
});
it('Should not focus Modal when child has focus', function () {
document.activeElement.should.equal(focusableContainer);
render(
<Modal show onHide={() => {}} animation={false}>
<input autoFocus />
</Modal>
, focusableContainer);
let input = document.getElementsByTagName('input')[0];
document.activeElement.should.equal(input);
});
});
});
|
src/fields/InputField.ios.js
|
MichaelCereda/react-native-form-generator
|
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import ReactNative from 'react-native';
import {InputComponent} from '../lib/InputComponent';
const {StyleSheet} = ReactNative;
export class InputField extends React.Component{
handleValidation(isValid, validationErrors){
this.valid = isValid;
this.validationErrors = validationErrors;
}
setValue(value){
this.refs.fieldComponent.setValue(value)
}
focus(){
this.refs.fieldComponent.focus()
}
render(){
return(<InputComponent
{...this.props}
ref='fieldComponent'
onValidation={this.handleValidation.bind(this)}
labelStyle={[formStyles.fieldText, this.props.labelStyle]}
inputStyle={[formStyles.input,
(this.props.multiline)?formStyles.multiline:{},
(this.props.label)?formStyles.textRight:{},
this.props.style
]}
containerStyle={[formStyles.fieldContainer,
formStyles.horizontalContainer,
this.props.containerStyle,
]}
/>
)
}
}
InputField.propTypes = {
multiline: PropTypes.bool,
placeholder:PropTypes.string,
}
let fieldStyles =StyleSheet.create({
input:{
paddingLeft: 10,
paddingRight: 10,
},
});
let formStyles = StyleSheet.create({
form:{
},
alignRight:{
marginTop: 7, position:'absolute', right: 10
},
textRight:{
textAlign: 'right'
},
multiline:{
lineHeight: 32,
fontSize: 34/2,
paddingBottom:10
},
separatorContainer:{
// borderTopColor: '#C8C7CC',
// borderTopWidth: 1,
paddingTop: 35,
borderBottomColor: '#C8C7CC',
borderBottomWidth: 1,
},
fieldsWrapper:{
// borderTopColor: '#afafaf',
// borderTopWidth: 1,
},
horizontalContainer:{
flexDirection: 'row',
justifyContent: 'flex-start'
},
fieldContainer:{
borderBottomWidth: 1,
borderBottomColor: '#C8C7CC',
backgroundColor: 'white',
justifyContent: 'center',
},
fieldText:{
fontSize: 34/2,
paddingLeft: 10,
paddingRight: 10,
justifyContent: 'center',
lineHeight: 32,
},
input:{
paddingLeft: 10,
paddingRight: 10,
},
helpTextContainer:{
marginTop:9,
marginBottom: 25,
paddingLeft: 20,
paddingRight: 20,
},
helpText:{
color: '#7a7a7a'
}
});
{/*<View
onLayout={this.handleLayoutChange.bind(this)}>
{(this.props.iconLeft)
? this.props.iconLeft
: null
}
{(this.props.label)
?
<Text style={formStyles.fieldText}
onLayout={this.handleLabelLayoutChange.bind(this)}
onPress={this.handleFieldPress.bind(this)}
>{this.props.label}</Text>
: null
}
<TextInput
{...this.props}
ref='inputBox'
keyboardType = {this.props.keyboardType}
style={[formStyles.input,
(this.props.multiline)?formStyles.multiline:{},
(this.props.label)?formStyles.textRight:{},
this.props.style,
{height: this.state.inputHeight}
]}
onChange={this.handleChange.bind(this)}
onFocus={this._scrollToInput.bind(this)}
placeholder={this.props.placeholder}
value={this.state.value}
width={this.state.width-this.state.labelWidth
-((this.props.iconRight)?this.props.iconRight.props.size:0)
-((this.props.iconLeft)?this.props.iconLeft.props.size:0)
}
/>
{(this.props.iconRight)
? this.props.iconRight
: null
}
</View>*/}
|
node_modules/react-bootstrap/es/Pagination.js
|
premcool/getmydeal
|
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import PaginationButton from './PaginationButton';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
activePage: React.PropTypes.number,
items: React.PropTypes.number,
maxButtons: React.PropTypes.number,
/**
* When `true`, will display the first and the last button page when
* displaying ellipsis.
*/
boundaryLinks: React.PropTypes.bool,
/**
* When `true`, will display the default node value ('…').
* Otherwise, will display provided node (when specified).
*/
ellipsis: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]),
/**
* When `true`, will display the default node value ('«').
* Otherwise, will display provided node (when specified).
*/
first: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]),
/**
* When `true`, will display the default node value ('»').
* Otherwise, will display provided node (when specified).
*/
last: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]),
/**
* When `true`, will display the default node value ('‹').
* Otherwise, will display provided node (when specified).
*/
prev: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]),
/**
* When `true`, will display the default node value ('›').
* Otherwise, will display provided node (when specified).
*/
next: React.PropTypes.oneOfType([React.PropTypes.bool, React.PropTypes.node]),
onSelect: React.PropTypes.func,
/**
* You can use a custom element for the buttons
*/
buttonComponentClass: elementType
};
var defaultProps = {
activePage: 1,
items: 1,
maxButtons: 0,
first: false,
last: false,
prev: false,
next: false,
ellipsis: true,
boundaryLinks: false
};
var Pagination = function (_React$Component) {
_inherits(Pagination, _React$Component);
function Pagination() {
_classCallCheck(this, Pagination);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Pagination.prototype.renderPageButtons = function renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps) {
var pageButtons = [];
var startPage = void 0;
var endPage = void 0;
if (maxButtons && maxButtons < items) {
startPage = Math.max(Math.min(activePage - Math.floor(maxButtons / 2, 10), items - maxButtons + 1), 1);
endPage = startPage + maxButtons - 1;
} else {
startPage = 1;
endPage = items;
}
for (var page = startPage; page <= endPage; ++page) {
pageButtons.push(React.createElement(
PaginationButton,
_extends({}, buttonProps, {
key: page,
eventKey: page,
active: page === activePage
}),
page
));
}
if (ellipsis && boundaryLinks && startPage > 1) {
if (startPage > 2) {
pageButtons.unshift(React.createElement(
PaginationButton,
{
key: 'ellipsisFirst',
disabled: true,
componentClass: buttonProps.componentClass
},
React.createElement(
'span',
{ 'aria-label': 'More' },
ellipsis === true ? '\u2026' : ellipsis
)
));
}
pageButtons.unshift(React.createElement(
PaginationButton,
_extends({}, buttonProps, {
key: 1,
eventKey: 1,
active: false
}),
'1'
));
}
if (ellipsis && endPage < items) {
if (!boundaryLinks || endPage < items - 1) {
pageButtons.push(React.createElement(
PaginationButton,
{
key: 'ellipsis',
disabled: true,
componentClass: buttonProps.componentClass
},
React.createElement(
'span',
{ 'aria-label': 'More' },
ellipsis === true ? '\u2026' : ellipsis
)
));
}
if (boundaryLinks) {
pageButtons.push(React.createElement(
PaginationButton,
_extends({}, buttonProps, {
key: items,
eventKey: items,
active: false
}),
items
));
}
}
return pageButtons;
};
Pagination.prototype.render = function render() {
var _props = this.props,
activePage = _props.activePage,
items = _props.items,
maxButtons = _props.maxButtons,
boundaryLinks = _props.boundaryLinks,
ellipsis = _props.ellipsis,
first = _props.first,
last = _props.last,
prev = _props.prev,
next = _props.next,
onSelect = _props.onSelect,
buttonComponentClass = _props.buttonComponentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['activePage', 'items', 'maxButtons', 'boundaryLinks', 'ellipsis', 'first', 'last', 'prev', 'next', 'onSelect', 'buttonComponentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
var buttonProps = {
onSelect: onSelect,
componentClass: buttonComponentClass
};
return React.createElement(
'ul',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
first && React.createElement(
PaginationButton,
_extends({}, buttonProps, {
eventKey: 1,
disabled: activePage === 1
}),
React.createElement(
'span',
{ 'aria-label': 'First' },
first === true ? '\xAB' : first
)
),
prev && React.createElement(
PaginationButton,
_extends({}, buttonProps, {
eventKey: activePage - 1,
disabled: activePage === 1
}),
React.createElement(
'span',
{ 'aria-label': 'Previous' },
prev === true ? '\u2039' : prev
)
),
this.renderPageButtons(activePage, items, maxButtons, boundaryLinks, ellipsis, buttonProps),
next && React.createElement(
PaginationButton,
_extends({}, buttonProps, {
eventKey: activePage + 1,
disabled: activePage >= items
}),
React.createElement(
'span',
{ 'aria-label': 'Next' },
next === true ? '\u203A' : next
)
),
last && React.createElement(
PaginationButton,
_extends({}, buttonProps, {
eventKey: items,
disabled: activePage >= items
}),
React.createElement(
'span',
{ 'aria-label': 'Last' },
last === true ? '\xBB' : last
)
)
);
};
return Pagination;
}(React.Component);
Pagination.propTypes = propTypes;
Pagination.defaultProps = defaultProps;
export default bsClass('pagination', Pagination);
|
app/src/components/Synth/PianoKeyNote.js
|
civa86/web-synth
|
import React from 'react';
const PianoKeyNote = (props) => {
const {
note,
semiNote,
playNoteHandler,
stopNoteHandler,
playingVoices,
octave
} = props;
function getClassName (color, key) {
const voiceLabel = key + '-' + octave;
let result = 'key-' + color + ' no-select';
if (playingVoices && playingVoices.indexOf(voiceLabel) !== -1) {
result += ' playing';
}
return result;
}
function semiNoteKey () {
if (semiNote) {
return (
<div className={getClassName('black', semiNote.key)}
onMouseDown={(e) => playNoteHandler(e, semiNote.key)}
onTouchStart={(e) => playNoteHandler(e, semiNote.key)}
onMouseOut={() => stopNoteHandler(null, semiNote.key)}
onMouseUp={(e) => stopNoteHandler(e, semiNote.key)}
onTouchEnd={(e) => stopNoteHandler(e, semiNote.key)}><span>{semiNote.label}</span>
</div>
);
} else {
return '';
}
}
return (
<div className={getClassName('white', note.key)}
onMouseDown={(e) => playNoteHandler(e, note.key)}
onTouchStart={(e) => playNoteHandler(e, note.key)}
onMouseOut={() => stopNoteHandler(null, note.key)}
onMouseUp={(e) => stopNoteHandler(e, note.key)}
onTouchEnd={(e) => stopNoteHandler(e, note.key)}><span>{note.label}</span>
{semiNoteKey()}
</div>
);
};
export default PianoKeyNote;
|
client/About/Social.js
|
PicDrop/PicDrop
|
import React from 'react';
import Github from './Github';
import LinkedIn from './LinkedIn';
class Social extends React.Component {
render() {
return (
<div>
<LinkedIn linkedIn={this.props.linkedIn}/>
<Github github={this.props.github}/>
</div>
);
}
}
export default Social;
|
src/GridList/GridTile.spec.js
|
ArcanisCz/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import GridTile from './GridTile';
import getMuiTheme from '../styles/getMuiTheme';
describe('<GridTile />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const tileData = {
img: 'images/grid-list/00-52-29-429_640.jpg',
title: 'Breakfast',
author: 'jill111',
};
describe('prop: children', () => {
it('should renders children by default', () => {
const testChildren = <img src={tileData.img} />;
const wrapper = shallowWithContext(
<GridTile>{testChildren}</GridTile>
);
assert.strictEqual(wrapper.containsMatchingElement(testChildren), true,
'should contain the children');
});
});
describe('prop: className', () => {
it('should renders className', () => {
const wrapper = shallowWithContext(
<GridTile className="foo" />
);
assert.strictEqual(wrapper.hasClass('foo'), true,
'should contain the className');
});
});
describe('prop: title', () => {
it('should renders title', () => {
const wrapper = shallowWithContext(
<GridTile title={tileData.title} />
);
assert.strictEqual(wrapper.children('div').text(), tileData.title,
'should contain the title');
});
});
describe('prop: titleStyle', () => {
it('should overwrite styles', () => {
const titleStyle = {
fontSize: 20,
};
const wrapper = shallowWithContext(
<GridTile title="foo" titleStyle={titleStyle} />
);
assert.strictEqual(wrapper.find('div > div > div > div').props().style.fontSize,
titleStyle.fontSize, 'should overwrite title fontSize');
});
});
});
|
node_modules/expo/src/Modal/ModalHost.js
|
RahulDesai92/PHR
|
/* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { View, StyleSheet } from 'react-native';
import PureContainer from './PureContainer';
type Layout = {
width: number,
height: number,
};
type LayoutEvent = {
nativeEvent: {
layout: Layout,
},
};
type Renderer = (layout: Layout, key: number) => any;
type Props = {
children?: any,
};
type State = {
modals: Array<{ key: number, renderer: Renderer }>,
layout: {
measured: boolean,
} & Layout,
};
export const channel = '__$expo_modal_host';
export default class ModalHost extends Component<Props, State> {
static childContextTypes = {
[channel]: PropTypes.object,
};
state = {
modals: [],
layout: {
height: 0,
width: 0,
measured: false,
},
};
getChildContext() {
return {
[channel]: {
register: this._register,
},
};
}
_currentKey = 0;
_register = (renderer: Renderer) => {
const key = this._currentKey;
this._currentKey++;
this.setState(state => ({
modals: [...state.modals, { key, renderer }],
}));
const update = (r: Renderer) =>
this.setState(state => ({
modals: state.modals.map(
m => (m.key === key ? { key, renderer: r } : m)
),
}));
const remove = () =>
this.setState(state => ({
modals: state.modals.filter(m => m.key !== key),
}));
return {
update,
remove,
};
};
_handleLayout = (e: LayoutEvent) => {
const { layout } = e.nativeEvent;
if (
layout.height !== this.state.layout.height ||
layout.width !== this.state.layout.width
) {
this.setState({ layout: { ...e.nativeEvent.layout, measured: true } });
}
};
render() {
return (
<View style={styles.host} onLayout={this._handleLayout}>
<PureContainer {...this.props}>
{this.props.children}
</PureContainer>
{this.state.layout.measured
? this.state.modals.map(({ key, renderer }) => {
return renderer(this.state.layout, key);
})
: null}
</View>
);
}
}
const styles = StyleSheet.create({
host: {
flex: 1,
},
});
|
src/index.js
|
bkkeye/redux_carouse
|
/**
* Created by u on 2017/5/20.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import {createStore,applyMiddleware} from 'redux';
import {Provider} from "react-redux";
import thunk from 'redux-thunk';
import Carousel from "./components/Carousel.jsx";
import reducer from "./reducers";
const store = createStore(reducer,applyMiddleware(thunk));
ReactDOM.render(
<Provider store={store}>
<Carousel/>
</Provider>,
document.getElementById('root')
)
|
src/components/SplitIt/SplitDashboard.js
|
tfrankie88/splitzi_react
|
import React, { Component } from 'react';
import NavigationSplitIt from '../Navigation/NavigationSplitIt';
import RestaurantSearch from './RestaurantSearch';
import MenuList from './MenuList';
class SplitDashboard extends Component {
constructor() {
super();
this.state = {
menu: [],
cart: 0
};
}
componentWillMount() {
if (localStorage.getItem('token')) {
window.localStorage.removeItem('token');
}
if(localStorage.getItem('restuarant')) {
window.localStorage.removeItem('restaurant');
}
}
searchRestaurant(term) {
fetch(`https://splitzi-api.herokuapp.com/restaurant/name/${term}`)
.then(r => r.json())
.then((data) => {
console.log('this is data from first fetch', data);
this.setState({ menuItems: data.search })
console.log('this is data.id', data.id)
fetch(`https://splitzi-api.herokuapp.com/menu/${data.id}/menu`)
.then(r => r.json())
.then((menuData) => {
console.log(menuData);
this.setState({ menu: menuData });
console.log('this is state menu state', this.state.menuItems[0]);
})
})
.catch(err => console.log('ERROR', err));
}
addToCart(){
this.setState({cart: this.state.cart + 1}, () => {
// console.log("this is the cart", this.state.cart);
});
}
render() {
return(
<div>
<NavigationSplitIt />
<div className="content-container">
<h1 className="search-items-title">where did you <span>eat?</span></h1>
<div>
<RestaurantSearch
searchRestaurant={this.searchRestaurant.bind(this)}
/>
</div>
<div className="item-cards-container">
<MenuList
menu={this.state.menu}
addToCart={this.addToCart.bind(this)}
/>
</div>
</div>
</div>
);
}
}
export default SplitDashboard;
|
js/example-work.js
|
sithadmin/my-portfolio
|
import React from 'react';
import ExampleWorkModal from './example-work-modal';
class ExampleWork extends React.Component {
constructor(props) {
super(props);
this.state = {
'modalOpen': false,
'selectedExample': this.props.work[0]
};
this.openModal = this.openModal.bind(this);
this.closeModal = this.closeModal.bind(this);
}
openModal(evt, example) {
this.setState({
'modalOpen': true,
'selectedExample': example
});
}
closeModal(evt) {
this.setState({
'modalOpen': false
});
}
render() {
return (
<span>
<section className="section section--alignCentered section--description">
{ this.props.work.map( (example, idx) => {
return (
<ExampleWorkBubble example={example} key={idx}
openModal={this.openModal} />
)
})
}
</section>
<ExampleWorkModal example={this.state.selectedExample}
open={this.state.modalOpen} closeModal={this.closeModal} />
</span>
)
}
}
class ExampleWorkBubble extends React.Component {
render() {
let example = this.props.example;
return (
<div className="section__exampleWrapper"
onClick={(evt) => this.props.openModal(evt, example) }>
<div className="section__example">
<img alt="{example.image.desc}"
className="section__exampleImage"
src={example.image.src}/>
<dl className="color--cloud">
<dt className="section__exampleTitle section__text--centered">
{example.title}
</dt>
<dd></dd>
</dl>
</div>
</div>
)
}
}
export default ExampleWork;
export { ExampleWorkBubble };
|
src/withControl.js
|
andrewkshim/react-animatronics
|
// @flow
/**
* @module withControl
*/
import React from 'react'
import hoistNonReactStatics from 'hoist-non-react-statics'
import type { ComponentType } from 'react'
import ContextTypes from './internal/context-types'
import Control from './Control'
import { IS_PRODUCTION } from './internal/constants'
import {
getDisplayName,
isStatelessComponent,
isReactComponent,
makeError,
} from './internal/utils'
type Props = {
innerRef: Function,
};
const withControl = (name: string) => (BaseComponent: ComponentType<{}>) => {
if (!IS_PRODUCTION) {
if (!isReactComponent(BaseComponent)) {
throw makeError(
`The withControl() higher-order component must be used to wrap a`,
`valid React component.`
);
}
}
class ControlledComponent extends React.Component<Props> {
static contextTypes: Object = ContextTypes
render() {
const { innerRef, ...props } = this.props;
return (
<Control name={ name }>{ ({ animatronicStyles, ref }) =>
<BaseComponent
{ ...this.props }
animatronicStyles={ animatronicStyles }
ref={ isStatelessComponent(BaseComponent) ? null : element => {
innerRef && innerRef(element);
ref(element);
} }
/>
}</Control>
);
}
}
ControlledComponent.displayName = `withControl(${ getDisplayName(BaseComponent) })`;
return hoistNonReactStatics(ControlledComponent, BaseComponent);
}
export default withControl;
|
examples/universal/client/index.js
|
keyanzhang/redux
|
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import configureStore from '../common/store/configureStore'
import App from '../common/containers/App'
const initialState = window.__INITIAL_STATE__
const store = configureStore(initialState)
const rootElement = document.getElementById('app')
render(
<Provider store={store}>
<App/>
</Provider>,
rootElement
)
|
app/javascript/mastodon/components/modal_root.js
|
anon5r/mastonon
|
import React from 'react';
import PropTypes from 'prop-types';
export default class ModalRoot extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
onClose: PropTypes.func.isRequired,
};
state = {
revealed: !!this.props.children,
};
activeElement = this.state.revealed ? document.activeElement : null;
handleKeyUp = (e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!this.props.children) {
this.props.onClose();
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
}
componentWillReceiveProps (nextProps) {
if (!!nextProps.children && !this.props.children) {
this.activeElement = document.activeElement;
this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
} else if (!nextProps.children) {
this.setState({ revealed: false });
}
}
componentDidUpdate (prevProps) {
if (!this.props.children && !!prevProps.children) {
this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
this.activeElement.focus();
this.activeElement = null;
}
if (this.props.children) {
requestAnimationFrame(() => {
this.setState({ revealed: true });
});
}
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
}
getSiblings = () => {
return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
}
setRef = ref => {
this.node = ref;
}
render () {
const { children, onClose } = this.props;
const { revealed } = this.state;
const visible = !!children;
if (!visible) {
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
);
}
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: revealed ? 1 : 0 }}>
<div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
<div role='presentation' className='modal-root__overlay' onClick={onClose} />
<div role='dialog' className='modal-root__container'>{children}</div>
</div>
</div>
);
}
}
|
app/javascript/mastodon/features/ui/components/embed_modal.js
|
tootsuite/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, FormattedMessage, injectIntl } from 'react-intl';
import api from 'mastodon/api';
import IconButton from 'mastodon/components/icon_button';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
});
export default @injectIntl
class EmbedModal extends ImmutablePureComponent {
static propTypes = {
url: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
onError: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
}
state = {
loading: false,
oembed: null,
};
componentDidMount () {
const { url } = this.props;
this.setState({ loading: true });
api().post('/api/web/embed', { url }).then(res => {
this.setState({ loading: false, oembed: res.data });
const iframeDocument = this.iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(res.data.html);
iframeDocument.close();
iframeDocument.body.style.margin = 0;
this.iframe.width = iframeDocument.body.scrollWidth;
this.iframe.height = iframeDocument.body.scrollHeight;
}).catch(error => {
this.props.onError(error);
});
}
setIframeRef = c => {
this.iframe = c;
}
handleTextareaClick = (e) => {
e.target.select();
}
render () {
const { intl, onClose } = this.props;
const { oembed } = this.state;
return (
<div className='modal-root__modal report-modal embed-modal'>
<div className='report-modal__target'>
<IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} />
<FormattedMessage id='status.embed' defaultMessage='Embed' />
</div>
<div className='report-modal__container embed-modal__container' style={{ display: 'block' }}>
<p className='hint'>
<FormattedMessage id='embed.instructions' defaultMessage='Embed this status on your website by copying the code below.' />
</p>
<input
type='text'
className='embed-modal__html'
readOnly
value={oembed && oembed.html || ''}
onClick={this.handleTextareaClick}
/>
<p className='hint'>
<FormattedMessage id='embed.preview' defaultMessage='Here is what it will look like:' />
</p>
<iframe
className='embed-modal__iframe'
frameBorder='0'
ref={this.setIframeRef}
sandbox='allow-same-origin'
title='preview'
/>
</div>
</div>
);
}
}
|
docs/app/Examples/collections/Breadcrumb/Variations/BreadcrumbExampleMassiveSize.js
|
clemensw/stardust
|
import React from 'react'
import { Breadcrumb } from 'semantic-ui-react'
const BreadcrumbExampleMassiveSize = () => (
<Breadcrumb size='massive'>
<Breadcrumb.Section link>Home</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section link>Registration</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section active>Personal Information</Breadcrumb.Section>
</Breadcrumb>
)
export default BreadcrumbExampleMassiveSize
|
src/shared/components/idme/idme.js
|
tal87/operationcode_frontend
|
import React, { Component } from 'react';
import config from 'config/environment';
import troopImage from 'images/Troop.png';
import styles from './idme.css';
class Idme extends Component {
idMe = () => {
window.open(`${config.idmeOAuthUrl}?client_id=${config.idmeClientId}&redirect_uri=${config.host}/profile/verify&response_type=token&scope=military&display=popup', '', 'scrollbars=yes,menubar=no,status=no,location=no,toolbar=no,width=750,height=780,top=200,left=200`);
};
render() {
return (
<div className={styles.wrapper}>
<span className={styles.authbtn} role="link" onClick={this.idMe} tabIndex={0}>
<img className={styles.authImage} src={troopImage} alt="Verify your status with Id.Me" />
</span>
</div>
);
}
}
export default Idme;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/maps/pin-drop.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsPinDrop = (props) => (
<SvgIcon {...props}>
<path d="M18 8c0-3.31-2.69-6-6-6S6 4.69 6 8c0 4.5 6 11 6 11s6-6.5 6-11zm-8 0c0-1.1.9-2 2-2s2 .9 2 2-.89 2-2 2c-1.1 0-2-.9-2-2zM5 20v2h14v-2H5z"/>
</SvgIcon>
);
MapsPinDrop.displayName = 'MapsPinDrop';
MapsPinDrop.muiName = 'SvgIcon';
export default MapsPinDrop;
|
actor-apps/app-web/src/app/components/activity/UserProfileContactInfo.react.js
|
Jaeandroid/actor-platform
|
import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
const {addons: { PureRenderMixin }} = addons;
@ReactMixin.decorate(PureRenderMixin)
class UserProfileContactInfo extends React.Component {
static propTypes = {
phones: React.PropTypes.array
};
constructor(props) {
super(props);
}
render() {
let phones = this.props.phones;
let contactPhones = _.map(phones, (phone, i) => {
return (
<li className="profile__list__item row" key={i}>
<i className="material-icons">call</i>
<div className="col-xs">
<span className="contact">+{phone.number}</span>
<span className="title">{phone.title}</span>
</div>
</li>
);
});
return (
<ul className="profile__list profile__list--contacts">
{contactPhones}
</ul>
);
}
}
export default UserProfileContactInfo;
|
src/Interpolate.js
|
Firfi/meteor-react-bootstrap
|
// https://www.npmjs.org/package/react-interpolate-component
// TODO: Drop this in favor of es6 string interpolation
import React from 'react';
import ValidComponentChildren from './utils/ValidComponentChildren';
const REGEXP = /\%\((.+?)\)s/;
const Interpolate = React.createClass({
displayName: 'Interpolate',
propTypes: {
format: React.PropTypes.string
},
getDefaultProps() {
return { component: 'span' };
},
render() {
let format = (ValidComponentChildren.hasValidComponent(this.props.children) ||
(typeof this.props.children === 'string')) ?
this.props.children : this.props.format;
let parent = this.props.component;
let unsafe = this.props.unsafe === true;
let props = {...this.props};
delete props.children;
delete props.format;
delete props.component;
delete props.unsafe;
if (unsafe) {
let content = format.split(REGEXP).reduce(function(memo, match, index) {
let html;
if (index % 2 === 0) {
html = match;
} else {
html = props[match];
delete props[match];
}
if (React.isValidElement(html)) {
throw new Error('cannot interpolate a React component into unsafe text');
}
memo += html;
return memo;
}, '');
props.dangerouslySetInnerHTML = { __html: content };
return React.createElement(parent, props);
} else {
let kids = format.split(REGEXP).reduce(function(memo, match, index) {
let child;
if (index % 2 === 0) {
if (match.length === 0) {
return memo;
}
child = match;
} else {
child = props[match];
delete props[match];
}
memo.push(child);
return memo;
}, []);
return React.createElement(parent, props, kids);
}
}
});
export default Interpolate;
|
js/jqwidgets/demos/react/app/datatable/serverpaging/app.js
|
luissancheza/sice
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js';
class App extends React.Component {
render() {
let source =
{
dataType: 'json',
dataFields: [
{ name: 'ShipCountry', type: 'string' },
{ name: 'ShipCity', type: 'string' },
{ name: 'ShipAddress', type: 'string' },
{ name: 'ShipName', type: 'string' },
{ name: 'Freight', type: 'number' },
{ name: 'ShippedDate', type: 'date' }
],
root: 'value',
url: 'http://services.odata.org/V3/Northwind/Northwind.svc/Orders?$format=json&$callback=?'
};
let dataAdapter = new $.jqx.dataAdapter(source,
{
formatData: (data) => {
// update the $skip and $top params of the OData service.
// data.pagenum - page number starting from 0.
// data.pagesize - page size
data.$skip = data.pagenum * data.pagesize;
data.$top = data.pagesize;
data.$inlinecount = 'allpages';
return data;
},
downloadComplete: (data, status, xhr) => {
if (!source.totalRecords) {
source.totalRecords = parseInt(data['odata.count']);
}
},
loadError: (xhr, status, error) => {
throw new Error('http://services.odata.org: ' + error.toString());
}
}
);
let columns =
[
{ text: 'Ship Name', dataField: 'ShipName', width: 300 },
{ text: 'Ship Country', hidden: true, dataField: 'ShipCountry', width: 250 },
{ text: 'Ship City', dataField: 'ShipCity', width: 150 },
{ text: 'Ship Address', dataField: 'ShipAddress' }
];
return (
<div>
<h3 style={{ fontSize: 16, fontFamily: 'Verdana' }}>Data Source: 'http://services.odata.org'</h3>
<JqxDataTable
width={850} source={dataAdapter} altRows={true}
pageable={true} columnsResize={true} serverProcessing={true}
columns={columns} pagerButtonsCount={10}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/containers/Asians/TabControls/PreliminaryRounds/EnterRoundResults/Ballots/Instance/InstanceTabs.js
|
westoncolemanl/tabbr-web
|
import React from 'react'
import { connect } from 'react-redux'
import Tabs, { Tab } from 'material-ui/Tabs'
import AppBar from 'material-ui/AppBar'
import withStyles from 'material-ui/styles/withStyles'
const styles = theme => ({
indicator: {
backgroundColor: '#ffffff'
}
})
export default connect(mapStateToProps)(withStyles(styles)(({
room,
value,
adjudicatorsById,
onChange,
classes
}) =>
<AppBar
position={'static'}
elevation={0}
>
<Tabs
className={'w-100'}
value={value}
onChange={(e, v) => onChange(v)}
scrollable
scrollButtons={'auto'}
classes={{
indicator: classes.indicator
}}
>
<Tab
label={'Room'}
value={'room'}
/>
<Tab
label={`${adjudicatorsById[room.chair].firstName} ${adjudicatorsById[room.chair].lastName}`}
value={'chair'}
/>
{room.panels.map(panel =>
<Tab
key={panel}
label={`${adjudicatorsById[panel].firstName} ${adjudicatorsById[panel].lastName}`}
value={panel}
/>
)}
</Tabs>
</AppBar>
))
function mapStateToProps (state, ownProps) {
return {
adjudicatorsById: state.adjudicators.data
}
}
|
frontend/src/layouts/CoreLayout/CoreLayout.js
|
qurben/mopidy-jukebox
|
import React from 'react'
import Header from '../../components/Header'
import classes from './CoreLayout.scss'
import '../../styles/core.scss'
export const CoreLayout = ({ children }) => (
<div className='container text-center'>
<Header/>
<div className={classes.mainContainer}>
{children}
</div>
</div>
)
CoreLayout.propTypes = {
children: React.PropTypes.element.isRequired
}
export default CoreLayout
|
src/pages/about/index.js
|
joefraley/ratticusscript
|
'use strict'
import Helmet from 'react-helmet'
import React from 'react'
const ratPictures = require.context('./assets', true, /rat/)
export const Thumbnail = ({ alt, link, source }) => <a href={ link } target="_">
<img src={ require(`./${source}`) } alt={ alt }></img>
</a>
export const AboutPage = props => <section>
<Helmet
title="About | RatticusScript"
meta={[{
content: 'Some stuff you can pretend to like if you need to make conversation with me.',
name: 'description'
}]}
/>
<h1>About Me</h1>
<p>I studied analytic philosophy at the University of Colorado, Boulder, and also at Western Washington University. I see everything through a Socratic lens, and it makes me lame at parties. Please reach out to chat about anything you like - I'm always excited to meet new people. Otherwise I wouldn't have a personal website 😘</p>
<p>If you'd like to talk, but aren't sure about what, here are some things that have influenced me:</p>
<ul>
<h2>Philosophy</h2>
<div>
<Thumbnail link="https://www.overdrive.com/media/1223521/countdown" source="assets/cover-countdown.jpg" alt="Countdown book cover."/>
<Thumbnail link="https://www.overdrive.com/media/515281/the-world-without-us" source="assets/cover-world-without-us.jpg" alt="The World Without Us book cover."/>
<Thumbnail link="https://www.overdrive.com/media/265875/eating-animals" source="assets/cover-eating-animals.jpg" alt="Eating animals book cover."/>
<Thumbnail link="https://www.overdrive.com/media/511535/dominion" source="assets/cover-dominion.jpg" alt="Dominion book cover."/>
<Thumbnail link="https://www.overdrive.com/media/1263597/slaughterhouse" source="assets/cover-slaughterhouse.jpg" alt="Slaughterhouse book cover."/>
<Thumbnail link="https://www.overdrive.com/media/585585/the-best-of-all-possible-worlds" source="assets/cover-best-of-all-worlds.jpg" alt="Best of All Possible Worlds book cover."/>
<Thumbnail link="http://www.physics.princeton.edu/ph115/LQ.pdf" source="assets/cover-the-last-question.jpg" alt="The Last Question book cover."/>
<Thumbnail link="http://www.tandon-books.com/Humanities/PL2064%20-%20Ethics%20and%20Technology/(PL2143)%20Elements%20of%20Moral%20Philosophy.pdf" source="assets/cover-elements-of-moral-philosophy.jpg" alt="Elements of Moral Philosophy book cover." />
</div>
<li>John Stuart Mill, Jeremy Bentham, Peter Singer, and several other important consquentialists have inspired me. Early on I thought that consquentialism was clearly the craziest possible world view. You can read up on it around here:
<ul>
<li><a href="http://www.utilitarianism.com/mill1.htm" target="_"><em>Utilitarianism</em> - John Stuart Mill</a></li>
<li><a href="http://utilitarianism.com/jeremy-bentham/index.html" target="_"><em>An Introduction to the Principles of Morals and Legislation</em> - Jeremy Bentham</a></li>
<li><a href="https://nwveg.org/files/Singer_The_Animal_Liberation_Movement.pdf" target="_"><em>Animal Liberation</em> - Peter Singer</a></li>
</ul>
</li>
<li>There is a deep and yet mysterious connection between the words we use, the concepts they represent, and the material states-of-affairs they pick out. Very little has been written directly on this subject, but good starting points are important figures in the philosophy of language like Bertrand Russel and Saul Kripke. <em>On Denoting</em> is a great place to start.
<ul>
<li><a href="http://philo.ruc.edu.cn/logic/reading/On%20sense%20and%20reference.pdf" target="_"><em>On Sense and Reference</em> - Gottlob Frege</a></li>
<li><a href="http://www.theotodman.com/Kripke_Naming.pdf" target="_"><em>Naming and Necessity</em> - Saul Kripke</a></li>
<li><a href="http://www.uvm.edu/~lderosse/courses/lang/Russell(1905).pdf" target="_"><em>On Denoting</em> - Bertrand Russel</a></li>
</ul>
</li>
<li>Many people have written about the problem of evil for traditional Christianity. The best thing you can read about it is probably:
<ul>
<li><a href="https://www.overdrive.com/media/585585/the-best-of-all-possible-worlds" target="_"><em>The Best of All Possible Worlds: A Story of Philosophers, God, and Evil in the Age of Reason</em> - Steven Nadler</a></li>
</ul>
</li>
<li>The problem of induction is irresolvable. There is no plausible way to salvage it. Accepting that commits you to a leaky world view that empirical evidence alone can't seal. David Hume defined the problem once and for all in his <em>Enquiry Concerning Human Understanding</em>.
<ul>
<li><a href="http://www.earlymoderntexts.com/assets/pdfs/hume1748.pdf" target="_"><em>Enquiry Concerning Human Understanding</em> - David Hume</a></li>
</ul>
</li>
<li>Perhaps no book has had a larger impact on me than <em>Countdown: Our Last, Best Hope for a Future on Earth?</em> This book changed the entire direction of my life - it is the reason I learned to program in pursuit of a longer lever of influence, and it has shaped more of my personal decisions than anything else I can think of since. I recommend you read it next to its companion <em>The World Witout Us</em>
<ul>
<li><a href="https://www.overdrive.com/media/515281/the-world-without-us" target="_"><em>The World Without Us</em> - Alan Weisman</a></li>
<li><a href="https://www.overdrive.com/media/1223521/countdown" target="_"><em>Countdown: Our Last, Best Hope for a Future on Earth?</em> - Alan Weisman</a></li>
</ul>
</li>
<li>There are many, many people that helped to open my eyes to the intrinsic worth of non-human animals, and the tyranical cruelty with which we treat them. Here's a short list:
<ul>
<li><a href="https://www.overdrive.com/media/265875/eating-animals" target="_"><em>Eating Animals</em> - Jonath Safran Foer</a></li>
<li><a href="https://www.overdrive.com/media/114394/charlottes-web" target="_"><em>Charlotte's Web</em> - E.B. White</a></li>
<li><a href="http://www.authorama.com/a-dogs-tale-1.html" target="_"><em>A Dog's Tale</em> - Mark Twain</a></li>
<li><a href="http://www.playr.org/play/pokemon_red/420" target="_">Pokémon Red</a></li>
<li><a href="https://en.wikipedia.org/wiki/Avatar:_The_Last_Airbender" target="_">Avatar: the Last Airbender</a></li>
</ul>
</li>
<h2>Fiction</h2>
<div>
<Thumbnail link="https://en.wikipedia.org/wiki/Eternal_Sunshine_of_the_Spotless_Mind" source="assets/movie-eternal-sunshine.jpg" alt="Eternal Sunshine on the Spotless Mind movie poster."/>
<Thumbnail link="https://en.wikipedia.org/wiki/Once_(film)" source="assets/movie-once.jpg" alt="Once movie poster" />
<Thumbnail link="https://www.overdrive.com/media/1866841/shining" source="assets/cover-the-shining.jpg" alt="The Shining bespoke cartoon book cover"/>
<Thumbnail link="http://www.adultswim.com/videos/rick-and-morty/" source="assets/movie-rick-and-morty.jpg" alt="Rick using a terrified Morty as a human shield"/>
<Thumbnail link="https://www.overdrive.com/media/2678033/the-sandman-volume-1" source="assets/comics-sandman.jpg" alt="Sandman Vol.2 book cover"/>
<Thumbnail link="https://www.overdrive.com/media/2504933/the-gunslinger" source="assets/cover-dark-tower.jpg" alt="Wizard and Glass, Dark Tower Vol. 4 book cover"/>
<Thumbnail link="https://www.overdrive.com/media/2677748/all-star-superman" source="assets/comics-superman.jpg" alt="A benevelont superman holds the word in his hands. Image by Frank Quietly."/>
<Thumbnail link="http://www.avclub.com/tv/batman-the-animated-series/" source="assets/comics-batman.jpg" alt="Batman in the shadows, circa Batman: the animated series."/>
</div>
<li>Some stories that have strongly influenced my views about love and <strong>The Point of Life™</strong> include <em>Eternal Sunshine on the Spotless Mind</em>, <em>Once</em>, <em>The Wonder Years</em>, <em>500 Days of Summer</em>, <em>The Shining</em>, and <em>Adventure Time</em>. They are all beautiful works of fiction.</li>
<li>Many works of science-fiction have inspired me, especially time-travel stories generally. Reading The Dark Tower series fundamentally changed the way I think about stories and endings. Sandman, too.</li>
<li>Superhero mythology has profoundly influenced me. Superman, Batman, Judge Dredd, and Hellboy especially resonate at my frequency - as well as many others. Brilliant people have said much in their voices. See especially:
<ul>
<li><a href="http://www.avclub.com/tv/batman-the-animated-series/"><em>Batman: the Animated Series</em></a></li>
<li><a href="https://www.overdrive.com/media/2677748/all-star-superman">Grant Morrison's <em>All-Star Superman</em></a></li>
</ul>
</li>
<li><a href="http://comicsalliance.com/author/chris-sims/">Comicsalliance writer and batmanologist Chris Sims</a> has shaped much of the way I approach fiction. <a href="http://moviebob.blogspot.com/">Bob Chipman</a>, formerly of <a href="http://www.escapistmagazine.com/videos/view/escape-to-the-movies">Escape to the Movies on the Escapist</a> has had a similar impact on my approach to film.</li>
<h2>Music</h2>
<div>
<Thumbnail link="https://www.youtube.com/watch?v=IluRBvnYMoY&list=PLDGvrCyjfEatTU8RGi1lNZ5KB75bq6KRV" source="assets/music-daft-punk.jpg" alt="Random Access Memories album cover" />
<Thumbnail link="https://www.youtube.com/watch?v=9NLZCLKppZs&list=PLxfOxxV02Em24f9rdvz8t1OfGAf1TI1I6" source="assets/music-john-mayer-2.jpg" alt="Where the Light Is album cover" />
<Thumbnail link="https://www.youtube.com/watch?v=GeCClzNCfcA&list=PL4y_nGkVeFwslrc5Gw6UKEkxjVdozI0-e" source="assets/music-john-mayer-3.jpg" alt="Battle Studies album cover" />
<Thumbnail link="https://www.youtube.com/watch?v=ktQxEpr_emU&list=PLBAHmVTbbf92bwrFZMlWbSD8Dpm_vYq8a" source="assets/music-justin-timberlake.jpg" alt="Future Sex Love Sounds album cover"/>
</div>
<li>No musician has influenced me more than John Mayer. He taught me to seek sinceriety in all things, and to value heart above all else in art and expression. One day Daft Punk will go on a US tour again...</li>
<h2>Programming and Technology</h2>
<div>
<Thumbnail link="https://github.com/funjs/book-source" source="assets/cover-functional-javascript.jpg" alt="Functional JavaScript book cover"/>
<Thumbnail link="https://github.com/getify/You-Dont-Know-JS" source="assets/cover-you-dont-know-js.jpg" alt="You Don't Know JS: Async and Performance book cover"/>
<Thumbnail link="http://eloquentjavascript.net" source="assets/cover-eloquent-javascript.jpg" alt="Eloquent JavaScript: 2nd Edition book cover" />
<Thumbnail link="http://craphound.com/news/2014/12/10/information-doesnt-want-to-be-free-audiobook" source="assets/cover-information-doesnt-want-to-be-free.jpg" alt="Inofrmation Doesn't Want to Be Free book cover"/>
</div>
<li>I have lots of opinions about the fabric of technology in our lives, especially the internet. It's hard to name particular works that have strongly influenced me, since there are so many little things happening all the time that nudge me this way or that. A great book on the subject is <a href="http://craphound.com/news/2014/12/10/information-doesnt-want-to-be-free-audiobook/">Information Doesn't Want to Be Free</a>.</li>
<li>On the subject of programming, <a href="https://github.com/funjs/book-source">Michael Fogus's Functional Javascript</a> forever altered my perspective on the language, as has Kyle Simpson's work, especially <a href="https://github.com/getify/You-Dont-Know-JS">You Don't Know JS</a>.</li>
<li>I strongly identify with declarative programming styles, and frameworks like <a href="https://facebook.github.io/react/">React</a> and <a href="http://elm-lang.org/">the Elm architecture</a> have shaped that perspective. Both enjoy positive, intelligent communities full of clever, diverse people.</li>
<h2>Rats</h2>
<div>
{ ratPictures.keys().map((file, index) => {
const picture = ratPictures(file)
return <img key={ index } src={ picture } alt="My rats: Clementine, Jalino, and Pandora"></img>
}) }
</div>
<li>If you've never met rats, you should. They are the model of innocence in this world.</li>
</ul>
<p>You can also check out <a href="/reading">my reading journal here on this site</a>. I've written about <a href="/posts/2016-09-23">the general architecture for this website here</a>.</p>
</section>
|
src/app/components/DevTools/index.js
|
omrilitov/react-universal
|
import React from 'react';
import {createDevTools} from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'
>
<LogMonitor />
</DockMonitor>
);
|
assets/javascripts/kitten/components/structure/cards/horizontal-project-card/index.js
|
KissKissBankBank/kitten
|
import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import styled from 'styled-components'
import { pxToRem } from '../../../../helpers/utils/typography'
import COLORS from '../../../../constants/colors-config'
import { ScreenConfig } from '../../../../constants/screen-config'
import { Progress } from '../../../feedback/progress'
import { Text } from '../../../typography/text'
const StyledCard = styled.a`
border: var(--border-width) solid transparent;
background-color: ${COLORS.background1};
box-sizing: border-box;
height: ${pxToRem(70)};
width: 100%;
padding: ${pxToRem(4)};
display: grid;
gap: ${pxToRem(5)} ${pxToRem(10)};
grid-template-columns: ${pxToRem(100)} ${pxToRem(110)} 1fr;
grid-template-rows: auto repeat(2, 1fr);
text-decoration: none;
color: ${COLORS.font1};
/* Border Radius should Image border radius (4) plus padding plus border. */
border-radius: calc(${pxToRem(4 + 4)} + var(--border-width));
transition: background-color 0.2s ease, border-color 0.2s ease;
&[href]:hover {
border-color: var(--color-grey-400);
background-color: ${COLORS.background2};
}
&[href]:active {
border-color: var(--color-grey-500);
background-color: ${COLORS.background3};
}
&[href]:focus-visible {
outline: auto;
}
.k-HorizontalProjectCard__imageWrapper {
grid-column: 1 / span 1;
grid-row: 1 / span 3;
img {
width: ${pxToRem(100)};
height: ${pxToRem(60)};
object-fit: cover;
object-position: center;
border-radius: var(--border-radius-xs);
}
}
.k-HorizontalProjectCard__title {
grid-column: 2 / span 2;
grid-row: 1 / 2;
margin: 0;
line-height: 1.2;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.k-HorizontalProjectCard__description {
grid-column: 2 / span 2;
grid-row: 2 / 3;
margin: 0;
line-height: 1;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
.k-HorizontalProjectCard__info {
grid-column: 2 / span 1;
grid-row: 3 / 4;
}
.k-HorizontalProjectCard__progress {
grid-column: 3 / span 1;
grid-row: 3 / 4;
place-self: center stretch;
display: flex;
gap: ${pxToRem(5)};
align-items: center;
.k-HorizontalProjectCard__progress__ramp {
flex: 1 0 calc(100% - ${pxToRem(5 + 46)});
}
.k-HorizontalProjectCard__progress__value {
flex: 0 0 ${pxToRem(46)};
width: ${pxToRem(46)};
}
@media (max-width: ${pxToRem(ScreenConfig.XXS.max)}) {
display: none;
}
}
@media (max-width: ${pxToRem(ScreenConfig.XS.max)}) {
&.k-HorizontalProjectCard--noProgressOnMobile {
.k-HorizontalProjectCard__progress {
display: none;
}
.k-HorizontalProjectCard__info {
grid-column: 2 / span 2;
}
}
}
`
export const HorizontalProjectCard = ({
href = '#',
imageProps = {
src: '',
alt: '',
},
title = '',
titleTag = 'h3',
description = '',
info = null,
progress = 0,
progressColor = COLORS.primary1,
className,
noProgressOnMobile = false,
noProgress = false,
progressLabel = 'progression',
...props
}) => {
return (
<StyledCard
href={href}
className={classNames('k-HorizontalProjectCard', className, {
'k-HorizontalProjectCard--noProgressOnMobile': noProgressOnMobile,
})}
{...props}
>
<div className="k-HorizontalProjectCard__imageWrapper">
<img {...imageProps} alt={imageProps.alt || ''} />
</div>
<Text
weight="regular"
size="small"
as={titleTag}
className="k-HorizontalProjectCard__title"
>
{title}
</Text>
<Text
as="p"
weight="light"
size="micro"
className="k-HorizontalProjectCard__description"
>
{description}
</Text>
<div className="k-HorizontalProjectCard__info">{info}</div>
{!noProgress && (
<div className="k-HorizontalProjectCard__progress">
<Progress
aria-label={progressLabel}
value={progress}
color={progressColor}
rampProps={{ style: { height: 4 } }}
className="k-HorizontalProjectCard__progress__ramp"
/>
<Text
weight="light"
size="micro"
className="k-HorizontalProjectCard__progress__value"
>
{progress} %
</Text>
</div>
)}
</StyledCard>
)
}
HorizontalProjectCard.propTypes = {
href: PropTypes.string,
imageProps: PropTypes.object,
title: PropTypes.string,
titleTag: PropTypes.string,
description: PropTypes.string,
info: PropTypes.node,
progress: PropTypes.number,
progressColor: PropTypes.string,
progressLabel: PropTypes.string,
noProgress: PropTypes.bool,
noProgressOnMobile: PropTypes.bool,
}
|
node_modules/react-bootstrap/es/ModalBody.js
|
geng890518/editor-ui
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'div'
};
var ModalBody = function (_React$Component) {
_inherits(ModalBody, _React$Component);
function ModalBody() {
_classCallCheck(this, ModalBody);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalBody.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ModalBody;
}(React.Component);
ModalBody.propTypes = propTypes;
ModalBody.defaultProps = defaultProps;
export default bsClass('modal-body', ModalBody);
|
app/routes.js
|
yaolei/Node-Clound
|
import React from 'react';
import ReactDOM from 'react-dom';
import {
HashRouter,
Route,
Link
} from 'react-router-dom';
import Navbar from './components/Navbar';
import App from './components/App';
import Home from './components/Home';
import FooterBar from './components/Footer';
import ChatBar from './components/Chat';
import TableBar from './components/Table';
import JsonBar from './components/reJson';
//<FooterBar />
if(typeof window !== 'undefined') {
ReactDOM.render((
<HashRouter>
<div>
<Navbar />
<Route exact path="/" component={Home} />
<Route exact path="/app" component={App} />
<Route exact path="/chat" component={ChatBar} />
<Route exact path="/table" component={TableBar} />
<Route exact path="/json" component={JsonBar} />
</div>
</HashRouter >
), document.getElementById('root'))
}
|
client/pages/__tests__/LogoutPage-test.js
|
freakimkaefig/melodicsimilarity
|
import React from 'react';
import { mount } from 'enzyme';
import sinon from 'sinon';
import LogoutPage from '../LogoutPage';
import DocumentTitle from 'react-document-title';
import { APP_NAME } from '../../constants/AppConstants';
jest.mock('../../services/AuthService');
describe('<LogoutPage/>', () => {
var wrapper;
beforeEach(() => {
jest.resetModules();
wrapper = mount(<LogoutPage/>);
});
it('should render <DocumentTitle/>', () => {
expect(wrapper.find(DocumentTitle).length).toBe(1);
expect(wrapper.find(DocumentTitle).props().title).toEqual('Logout // ' + APP_NAME);
});
it('should logout when mounting', () => {
sinon.spy(LogoutPage.prototype, 'componentDidMount');
jest.resetModules();
wrapper = mount(<LogoutPage/>);
expect(LogoutPage.prototype.componentDidMount.callCount).toBe(1);
LogoutPage.prototype.componentDidMount.restore();
});
});
|
src/.stories/index.js
|
clauderic/react-infinite-calendar
|
/* eslint-disable sort-keys */
import React from 'react';
import {addDecorator, storiesOf} from '@kadira/storybook';
import InfiniteCalendar, {
Calendar,
defaultMultipleDateInterpolation,
withDateSelection,
withKeyboardSupport,
withMultipleDates,
withRange,
} from '../';
import styles from './stories.scss';
// Date manipulation utils
import addDays from 'date-fns/add_days';
import addMonths from 'date-fns/add_months';
import endOfMonth from 'date-fns/end_of_month';
import format from 'date-fns/format';
import isBefore from 'date-fns/is_before';
import subMonths from 'date-fns/sub_months';
const CenterDecorator = story => <div className={styles.center}>{story()}</div>;
addDecorator(CenterDecorator);
const today = new Date();
storiesOf('Basic settings', module)
.add('Default Configuration', () => <InfiniteCalendar />)
.add('Initially Selected Date', () => <InfiniteCalendar selected={addDays(today, 5)} />)
.add('Blank Initial State', () => <InfiniteCalendar selected={null} />)
.add('Min Date', () => (
<InfiniteCalendar
min={subMonths(today, 1)} // Minimum month to render
minDate={addDays(today, 1)} // Minimum selectable date
selected={addDays(today, 5)}
/>
))
.add('Max Date', () => (
<InfiniteCalendar
max={endOfMonth(addMonths(today, 1))} // Maximum rendered month
maxDate={today} // Maximum selectable date
/>
))
.add('Disable Specific Dates', () => (
<InfiniteCalendar
disabledDates={[-10, -5, -6, 5, 6, 7, 2].map(amount =>
addDays(today, amount)
)}
/>
))
.add('Disable Specific Weekdays', () => (
<InfiniteCalendar disabledDays={[0, 6]} />
));
storiesOf('Higher Order Components', module)
.add('Range selection', () => (
<InfiniteCalendar
selected={{
start: addDays(new Date(), 2),
end: addDays(new Date(), 17),
}}
locale={{
headerFormat: 'MMM Do',
}}
Component={withRange(withKeyboardSupport(Calendar))}
/>
))
.add('Multiple date selection', () => {
return (
<InfiniteCalendar
selected={[addDays(today, -600), addDays(today, -200), today, addDays(today, 50), addDays(today, 400)]}
interpolateSelection={defaultMultipleDateInterpolation}
Component={withMultipleDates(withKeyboardSupport(Calendar))}
/>
);
})
.add('Keyboard Support', () => {
return <InfiniteCalendar Component={withDateSelection(withKeyboardSupport(Calendar))} />;
});
storiesOf('Internationalization', module)
.add('Locale', () => (
<InfiniteCalendar
locale={{
blank: 'Aucune date sélectionnée',
headerFormat: 'dddd, D MMM',
locale: require('date-fns/locale/fr'),
todayLabel: {
long: "Aujourd'hui",
short: 'Auj.',
},
weekdays: ['Dim', 'Lun', 'Mar', 'Mer', 'Jeu', 'Ven', 'Sam'],
}}
/>
))
.add('First Day of the Week', () => (
<InfiniteCalendar
locale={{
weekStartsOn: 1,
}}
/>
));
storiesOf('Customization', module)
.add('Theming', () => (
<InfiniteCalendar
theme={{
floatingNav: {
background: 'rgba(105, 74, 228, 0.91)',
chevron: '#FFA726',
color: '#FFF',
},
headerColor: 'rgb(127, 95, 251)',
selectionColor: 'rgb(146, 118, 255)',
textColor: {
active: '#FFF',
default: '#333',
},
weekdayColor: 'rgb(146, 118, 255)',
}}
/>
))
.add('Flexible Size', () => (
<InfiniteCalendar
width={'94%'}
height={window.innerHeight - 147}
rowHeight={70}
/>
))
.add('Select Year First', () => (
<InfiniteCalendar display={'years'} selected={null} />
))
.add('Dynamic Selection Color', () => (
<InfiniteCalendar
selected={addDays(today, -1)}
theme={{
selectionColor: date => {
return isBefore(date, today) ? '#EC6150' : '#559FFF';
},
}}
/>
));
storiesOf('Display Options', module)
.add('Landscape Layout', () => (
<InfiniteCalendar
displayOptions={{
layout: 'landscape',
}}
width={600}
height={350}
/>
))
.add('Disable Header', () => (
<InfiniteCalendar
displayOptions={{
showHeader: false,
}}
/>
))
.add('Disable Header Animation', () => (
<InfiniteCalendar
displayOptions={{
shouldHeaderAnimate: false,
}}
/>
))
.add('Disable Month Overlay', () => (
<InfiniteCalendar
displayOptions={{
showOverlay: false,
}}
/>
))
.add('Disable Floating Today Helper', () => (
<InfiniteCalendar
displayOptions={{
showTodayHelper: false,
}}
/>
))
.add('Hide Months in Year Selection', () => (
<InfiniteCalendar
display={'years'}
displayOptions={{
showMonthsForYears: false,
}}
/>
))
.add('Hide Weekdays Helper', () => (
<InfiniteCalendar
displayOptions={{
showWeekdays: false,
}}
/>
));
storiesOf('Events', module)
.add('On Select', () => (
<InfiniteCalendar
onSelect={date =>
alert(`You selected: ${format(date, 'ddd, MMM Do YYYY')}`)}
/>
))
.add('On Scroll', () => [
<label key="label">Check your console logs.</label>,
<InfiniteCalendar
key="calendar"
onScroll={scrollTop =>
console.info('onScroll() – Scroll top:', scrollTop)}
/>,
]);
|
src/components/App.js
|
TorinoMeteo/tm-realtime-map
|
import React from 'react'
import { browserHistory, Router } from 'react-router'
import { Provider } from 'react-redux'
import PropTypes from 'prop-types'
class App extends React.Component {
static propTypes = {
store: PropTypes.object.isRequired,
routes: PropTypes.array.isRequired
}
shouldComponentUpdate () {
return false
}
render () {
return (
<Provider store={this.props.store}>
<div style={{ height: '100%' }}>
<Router history={browserHistory} children={this.props.routes} />
</div>
</Provider>
)
}
}
export default App
|
packages/react-dom/src/server/ReactPartialRenderer.js
|
syranide/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 type {
ReactProvider,
ReactConsumer,
ReactContext,
} from 'shared/ReactTypes';
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 lowPriorityWarning from 'shared/lowPriorityWarning';
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 {warnAboutDeprecatedLifecycles} from 'shared/ReactFeatureFlags';
import {
REACT_FRAGMENT_TYPE,
REACT_STRICT_MODE_TYPE,
REACT_ASYNC_MODE_TYPE,
REACT_CALL_TYPE,
REACT_RETURN_TYPE,
REACT_PORTAL_TYPE,
REACT_PROVIDER_TYPE,
REACT_CONTEXT_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;
const toArray = ((React.Children.toArray: any): toArrayType);
let currentDebugStack;
let currentDebugElementStack;
let getStackAddendum = emptyFunction.thatReturns('');
let describeStackFrame = emptyFunction.thatReturns('');
let validatePropertiesInDevelopment = (type, props) => {};
let setCurrentDebugStack = (stack: Array<Frame>) => {};
let pushElementToDebugStack = (element: ReactElement) => {};
let resetCurrentDebugStack = () => {};
if (__DEV__) {
validatePropertiesInDevelopment = function(type, props) {
validateARIAProperties(type, props);
validateInputProperties(type, props);
validateUnknownProperties(type, props, /* canUseEventSystem */ false);
};
describeStackFrame = function(element): string {
const source = element._source;
const type = element.type;
const name = getComponentName(type);
const ownerName = null;
return describeComponentFrame(name, source, ownerName);
};
currentDebugStack = null;
currentDebugElementStack = null;
setCurrentDebugStack = function(stack: Array<Frame>) {
const 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;
};
pushElementToDebugStack = function(element: ReactElement) {
if (currentDebugElementStack !== null) {
currentDebugElementStack.push(element);
}
};
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;
};
}
let didWarnDefaultInputValue = false;
let didWarnDefaultChecked = false;
let didWarnDefaultSelectValue = false;
let didWarnDefaultTextareaValue = false;
let didWarnInvalidOptionChildren = false;
const didWarnAboutNoopUpdateForComponent = {};
const didWarnAboutBadClass = {};
const didWarnAboutDeprecatedWillMount = {};
const didWarnAboutUndefinedDerivedState = {};
const didWarnAboutUninitializedState = {};
const valuePropNames = ['value', 'defaultValue'];
const 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
const VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
const validatedTagCache = {};
function validateDangerousTag(tag) {
if (!validatedTagCache.hasOwnProperty(tag)) {
invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag);
validatedTagCache[tag] = true;
}
}
const processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
function createMarkupForStyles(styles): string | null {
let serialized = '';
let delimiter = '';
for (const styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
const isCustomProperty = styleName.indexOf('--') === 0;
const 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__) {
const 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) {
const innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
const 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 {
let 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) {
const contextTypes = type.contextTypes;
if (!contextTypes) {
return emptyObject;
}
const maskedContext = {};
for (const 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) {
const maskedContext = maskContext(type, context);
if (__DEV__) {
if (type.contextTypes) {
checkContextTypes(type.contextTypes, maskedContext, 'context');
}
}
return maskedContext;
}
const STYLE = 'style';
const 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 {
let ret = '<' + tagVerbatim;
for (const propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
let propValue = props[propKey];
if (propValue == null) {
continue;
}
if (propKey === STYLE) {
propValue = createMarkupForStyles(propValue);
}
let 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,
|} {
let element: ReactElement;
let Component;
let publicContext;
let inst, queue, replace;
let updater;
let initialState;
let oldQueue, oldReplace;
let nextState, dontMutate;
let partial, partialState;
let childContext;
let childContextTypes, contextKey;
while (React.isValidElement(child)) {
// Safe because we just checked it's an element.
element = ((child: any): ReactElement);
if (__DEV__) {
pushElementToDebugStack(element);
}
Component = element.type;
if (typeof Component !== 'function') {
break;
}
publicContext = processContext(Component, context);
queue = [];
replace = false;
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, currentPartialState) {
if (queue === null) {
warnNoop(publicInstance, 'setState');
return null;
}
queue.push(currentPartialState);
},
};
if (shouldConstruct(Component)) {
inst = new Component(element.props, publicContext, updater);
if (typeof Component.getDerivedStateFromProps === 'function') {
if (__DEV__) {
if (inst.state === null || inst.state === undefined) {
const componentName = getComponentName(Component) || 'Unknown';
if (!didWarnAboutUninitializedState[componentName]) {
warning(
false,
'%s: Did not properly initialize state during construction. ' +
'Expected state to be an object, but it was %s.',
componentName,
inst.state === null ? 'null' : 'undefined',
);
didWarnAboutUninitializedState[componentName] = true;
}
}
}
partialState = Component.getDerivedStateFromProps.call(
null,
element.props,
inst.state,
);
if (__DEV__) {
if (partialState === undefined) {
const componentName = getComponentName(Component) || 'Unknown';
if (!didWarnAboutUndefinedDerivedState[componentName]) {
warning(
false,
'%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' +
'You have returned undefined.',
componentName,
);
didWarnAboutUndefinedDerivedState[componentName] = true;
}
}
}
if (partialState != null) {
inst.state = Object.assign({}, inst.state, partialState);
}
}
} else {
if (__DEV__) {
if (
Component.prototype &&
typeof Component.prototype.render === 'function'
) {
const componentName = getComponentName(Component) || 'Unknown';
if (!didWarnAboutBadClass[componentName]) {
warning(
false,
"The <%s /> component appears to have a render method, but doesn't extend React.Component. " +
'This is likely to cause errors. Change %s to extend React.Component instead.',
componentName,
componentName,
);
didWarnAboutBadClass[componentName] = true;
}
}
}
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;
initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
if (
typeof inst.UNSAFE_componentWillMount === 'function' ||
typeof inst.componentWillMount === 'function'
) {
if (typeof inst.componentWillMount === 'function') {
if (__DEV__) {
if (
warnAboutDeprecatedLifecycles &&
inst.componentWillMount.__suppressDeprecationWarning !== true
) {
const componentName = getComponentName(Component) || 'Unknown';
if (!didWarnAboutDeprecatedWillMount[componentName]) {
lowPriorityWarning(
false,
'%s: componentWillMount() is deprecated and will be ' +
'removed in the next major version. Read about the motivations ' +
'behind this change: ' +
'https://fb.me/react-async-component-lifecycle-hooks' +
'\n\n' +
'As a temporary workaround, you can rename to ' +
'UNSAFE_componentWillMount instead.',
componentName,
);
didWarnAboutDeprecatedWillMount[componentName] = true;
}
}
}
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for any component with the new gDSFP.
if (typeof Component.getDerivedStateFromProps !== 'function') {
inst.componentWillMount();
}
}
if (
typeof inst.UNSAFE_componentWillMount === 'function' &&
typeof Component.getDerivedStateFromProps !== 'function'
) {
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for any component with the new gDSFP.
inst.UNSAFE_componentWillMount();
}
if (queue.length) {
oldQueue = queue;
oldReplace = replace;
queue = null;
replace = false;
if (oldReplace && oldQueue.length === 1) {
inst.state = oldQueue[0];
} else {
nextState = oldReplace ? oldQueue[0] : inst.state;
dontMutate = true;
for (let i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
partial = oldQueue[i];
partialState =
typeof partial === 'function'
? partial.call(inst, nextState, element.props, publicContext)
: partial;
if (partialState != null) {
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);
if (typeof inst.getChildContext === 'function') {
childContextTypes = Component.childContextTypes;
if (typeof childContextTypes === 'object') {
childContext = inst.getChildContext();
for (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 = {
type: mixed,
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;
providerStack: Array<?ReactProvider<any>>;
providerIndex: number;
constructor(children: mixed, makeStaticMarkup: boolean) {
const flatChildren = flattenTopLevelChildren(children);
const topFrame: Frame = {
type: null,
// 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;
// Context (new API)
this.providerStack = []; // Stack of provider objects
this.providerIndex = -1;
}
pushProvider<T>(provider: ReactProvider<T>): void {
this.providerIndex += 1;
this.providerStack[this.providerIndex] = provider;
const context: ReactContext<any> = provider.type.context;
context.currentValue = provider.props.value;
}
popProvider<T>(provider: ReactProvider<T>): void {
if (__DEV__) {
warning(
this.providerIndex > -1 &&
provider === this.providerStack[this.providerIndex],
'Unexpected pop.',
);
}
this.providerStack[this.providerIndex] = null;
this.providerIndex -= 1;
const context: ReactContext<any> = provider.type.context;
if (this.providerIndex < 0) {
context.currentValue = context.defaultValue;
} else {
// We assume this type is correct because of the index check above.
const previousProvider: ReactProvider<any> = (this.providerStack[
this.providerIndex
]: any);
context.currentValue = previousProvider.props.value;
}
}
read(bytes: number): string | null {
if (this.exhausted) {
return null;
}
let out = '';
while (out.length < bytes) {
if (this.stack.length === 0) {
this.exhausted = true;
break;
}
const frame: Frame = this.stack[this.stack.length - 1];
if (frame.childIndex >= frame.children.length) {
const footer = frame.footer;
out += footer;
if (footer !== '') {
this.previousWasTextNode = false;
}
this.stack.pop();
if (frame.type === 'select') {
this.currentSelectValue = null;
} else if (
frame.type != null &&
frame.type.type != null &&
frame.type.type.$$typeof === REACT_PROVIDER_TYPE
) {
const provider: ReactProvider<any> = (frame.type: any);
this.popProvider(provider);
}
continue;
}
const 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') {
const text = '' + child;
if (text === '') {
return '';
}
if (this.makeStaticMarkup) {
return escapeTextForBrowser(text);
}
if (this.previousWasTextNode) {
return '<!-- -->' + escapeTextForBrowser(text);
}
this.previousWasTextNode = true;
return escapeTextForBrowser(text);
} else {
let 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.',
);
// 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 = {
type: null,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
}
// Safe because we just checked it's an element.
const nextElement = ((nextChild: any): ReactElement);
const elementType = nextElement.type;
if (typeof elementType === 'string') {
return this.renderDOM(nextElement, context, parentNamespace);
}
switch (elementType) {
case REACT_STRICT_MODE_TYPE:
case REACT_ASYNC_MODE_TYPE:
case REACT_FRAGMENT_TYPE: {
const nextChildren = toArray(
((nextChild: any): ReactElement).props.children,
);
const frame: Frame = {
type: null,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
}
case REACT_CALL_TYPE:
case REACT_RETURN_TYPE:
invariant(
false,
'The experimental Call and Return types are not currently ' +
'supported by the server renderer.',
);
// eslint-disable-next-line-no-fallthrough
default:
break;
}
if (typeof elementType === 'object' && elementType !== null) {
switch (elementType.$$typeof) {
case REACT_PROVIDER_TYPE: {
const provider: ReactProvider<any> = (nextChild: any);
const nextProps = provider.props;
const nextChildren = toArray(nextProps.children);
const frame: Frame = {
type: provider,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.pushProvider(provider);
this.stack.push(frame);
return '';
}
case REACT_CONTEXT_TYPE: {
const consumer: ReactConsumer<any> = (nextChild: any);
const nextProps: any = consumer.props;
const nextValue = consumer.type.currentValue;
const nextChildren = toArray(nextProps.children(nextValue));
const frame: Frame = {
type: nextChild,
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
}
default:
break;
}
}
let info = '';
if (__DEV__) {
const owner = nextElement._owner;
if (
elementType === undefined ||
(typeof elementType === 'object' &&
elementType !== null &&
Object.keys(elementType).length === 0)
) {
info +=
' You likely forgot to export your component from the file ' +
"it's defined in, or you might have mixed up default and " +
'named imports.';
}
const ownerName = owner ? getComponentName(owner) : null;
if (ownerName) {
info += '\n\nCheck the render method of `' + ownerName + '`.';
}
}
invariant(
false,
'Element type is invalid: expected a string (for built-in ' +
'components) or a class/function (for composite components) ' +
'but got: %s.%s',
elementType == null ? elementType : typeof elementType,
info,
);
}
}
renderDOM(
element: ReactElement,
context: Object,
parentNamespace: string,
): string {
const 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);
let 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;
}
}
let initialValue = props.value;
if (initialValue == null) {
let defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
let 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 (let i = 0; i < valuePropNames.length; i++) {
const propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
const 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') {
let selected = null;
const selectValue = this.currentSelectValue;
const optionChildren = flattenOptionChildren(props.children);
if (selectValue != null) {
let value;
if (props.value != null) {
value = props.value + '';
} else {
value = optionChildren;
}
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (let 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);
let out = createOpenTagMarkup(
element.type,
tag,
props,
namespace,
this.makeStaticMarkup,
this.stack.length === 1,
);
let footer = '';
if (omittedCloseTags.hasOwnProperty(tag)) {
out += '/>';
} else {
out += '>';
footer = '</' + element.type + '>';
}
let children;
const 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);
}
const frame = {
domNamespace: getChildNamespace(parentNamespace, element.type),
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;
|
packages/bonde-admin/src/pages/app.js
|
ourcities/rebu-client
|
import React from 'react'
import { BrowserRouter as Router, Route, Switch } from 'react-router-dom'
import DevTools from '@/components/dev-tools'
import '@/styles/main.scss'
import { TechnicalIssues } from '@/components/error/index'
import { ZendeskWidget } from '@/components/external-services'
import { GoogleFontsLoader } from '@/components/fonts'
import NotificationSystem from '@/components/notification-system'
import AccountRegisterPage from './public/account-register'
import SubscriptionEditPage from './public/subscription-edit'
import LoggedRoute from './admin'
const AuthExample = () => (
<div>
<Router>
<Switch>
<Route exact path='/register' component={AccountRegisterPage} />
<Route exact path='/subscriptions/:id/edit' component={SubscriptionEditPage} />
<Route path='/' component={LoggedRoute} />
<Route component={TechnicalIssues} />
</Switch>
</Router>
{process.env.NODE_ENV !== 'production' ? <DevTools /> : <div></div>}
<ZendeskWidget />
<NotificationSystem />
<GoogleFontsLoader fonts='Source Sans Pro' />
</div>
)
export default AuthExample
|
src/WorkWeek.js
|
intljusticemission/react-big-calendar
|
import PropTypes from 'prop-types'
import React from 'react'
import Week from './Week'
import TimeGrid from './TimeGrid'
function workWeekRange(date, options) {
return Week.range(date, options).filter(
d => [6, 0].indexOf(d.getDay()) === -1
)
}
class WorkWeek extends React.Component {
render() {
let { date, ...props } = this.props
let range = workWeekRange(date, this.props)
return <TimeGrid {...props} range={range} eventOffset={15} />
}
}
WorkWeek.propTypes = {
date: PropTypes.instanceOf(Date).isRequired,
}
WorkWeek.defaultProps = TimeGrid.defaultProps
WorkWeek.range = workWeekRange
WorkWeek.navigate = Week.navigate
WorkWeek.title = (date, { localizer }) => {
let [start, ...rest] = workWeekRange(date, { localizer })
return localizer.format({ start, end: rest.pop() }, 'dayRangeHeaderFormat')
}
export default WorkWeek
|
project-setup/libs/react-router/src/index.js
|
kasiriveni/practice
|
import React from 'react';
import {render} from 'react-dom';
import { BrowserRouter as Router, Route, Link } from "react-router-dom";
import Hello from './components/welcome';
import {Home,About,Topics} from './components/menu';
const root =document.getElementById("root");
render(
<Router>
<div>
<ul>
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/about">About</Link>
</li>
<li>
<Link to="/topics">Topics</Link>
</li>
</ul>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Route path="/topics" component={Topics} />
<Hello/>
</div>
</Router>,
root
)
|
docs/src/app/components/pages/discover-more/Community.js
|
frnk94/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import MarkdownElement from '../../MarkdownElement';
import communityText from './community.md';
const Community = () => (
<div>
<Title render={(previousTitle) => `Community - ${previousTitle}`} />
<MarkdownElement text={communityText} />
</div>
);
export default Community;
|
test/specs/collections/Form/FormFieldTextArea-test.js
|
mohammed88/Semantic-UI-React
|
import React from 'react'
import FormTextArea from 'src/collections/Form/FormTextArea'
import TextArea from 'src/addons/TextArea/TextArea'
import * as common from 'test/specs/commonTests'
describe('FormTextArea', () => {
common.isConformant(FormTextArea)
it('renders a FormField with a TextArea control', () => {
shallow(<FormTextArea />)
.find('FormField')
.should.have.prop('control', TextArea)
})
})
|
src/routes/bbs/Category/index.js
|
pmg1989/dva-admin
|
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'dva'
import { checkPower } from 'utils'
import { ADD, UPDATE, DELETE } from 'constants/options'
import CategoryList from './List'
import CategorySearch from './Search'
import CategoryModal from './ModalForm'
function Category ({ location, curPowers, dispatch, bbsCategory, modal, loading }) {
const addPower = checkPower(ADD, curPowers)
const updatePower = checkPower(UPDATE, curPowers)
const deletePower = checkPower(DELETE, curPowers)
const { field, keyword } = location.query
const searchProps = {
field,
keyword,
addPower,
onSearch (fieldsValue) {
dispatch({
type: 'bbsCategory/query',
payload: {
current: 1,
// pageSize: 10,
...fieldsValue,
},
})
},
onAdd () {
dispatch({
type: 'modal/showModal',
payload: {
type: 'create',
},
})
},
}
const listProps = {
bbsCategory,
loading,
updatePower,
deletePower,
onPageChange (fieldsValue) {
dispatch({
type: 'bbsCategory/query',
payload: { ...fieldsValue },
})
},
onDeleteItem (id) {
dispatch({ type: 'bbsCategory/delete', payload: { id } })
},
onEditItem (item) {
dispatch({
type: 'modal/showModal',
payload: {
type: 'update',
curItem: item,
},
})
},
}
const modalProps = {
modal,
loading,
onOk (data) {
dispatch({
type: data.cid
? 'bbsCategory/update'
: 'bbsCategory/create',
payload: {
curItem: data,
},
})
},
onCancel () {
dispatch({ type: 'modal/hideModal' })
},
}
return (
<div className="content-inner">
<CategorySearch {...searchProps} />
<CategoryList {...listProps} />
<CategoryModal {...modalProps} />
</div>
)
}
Category.propTypes = {
bbsCategory: PropTypes.object.isRequired,
location: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
curPowers: PropTypes.array.isRequired,
modal: PropTypes.object.isRequired,
loading: PropTypes.bool.isRequired,
}
function mapStateToProps ({ bbsCategory, modal, loading }) {
return { bbsCategory, modal, loading: loading.models.bbsCategory }
}
export default connect(mapStateToProps)(Category)
|
src/views/hr-view/components/ul.js
|
vynogradskyi/resume
|
import React from 'react';
import styles from 'css-modules/hr-view/ul.scss';
import {li_types as types} from "appConstants";
import classnames from 'classnames';
//components
import Li from './li';
export default ({points, type, className}) => {
return (
<ul className={classnames(styles.ul, className || '')}>
{points.map((point, i) => {
let customLi = getCusomLi(type);
return (
<Li text={point} key={i} customLi={customLi && customLi(point)}/>
)
})
}
</ul>
)
}
const getCusomLi = type => {
switch (type) {
case types.coding:
return codingLi;
case types.social:
return socialLi;
default:
return null;
}
};
const socialLi = point => {
let aParam = {};
if(!point.nohref){
aParam.href = point.url;
}
if(!point.noTarget){
aParam.target = '_blank';
}
return (
<a {...aParam}>
<span className={classnames(styles.site, 'text-grey')}>{`${point.site} / `}</span>
{point.value}
</a>
)
};
const codingLi = point => {
return (
<span>
{point.title}
<span className={classnames(styles.level, 'text-grey')}>{` (${point.level})`}</span>
</span>
)
}
|
src/js/sections/Title1.js
|
BavoG/onesupportdocu
|
import React from 'react';
import classnames from 'classnames';
import Headline from 'grommet/components/Headline';
import Box from 'grommet/components/Box';
import InfographicSection from '../components/InfographicSection';
import PlatformAndroid from 'grommet/components/icons/base/PlatformAndroid';
import Anchor from 'grommet/components/Anchor';
const CLASS_ROOT = "title-section";
export default function Title1 () {
const classes = classnames([
CLASS_ROOT,
`${CLASS_ROOT}--left-align`,
`${CLASS_ROOT}--column-reverse`
]);
return (
<InfographicSection className={classes} direction="row" colorIndex="accent-1">
<Box className={`${CLASS_ROOT}__col-2`} direction="column" alignContent="start">
<Headline className={`${CLASS_ROOT}__title`} size="medium">
Visit the <Anchor href="https://play.google.com/store/apps/details?id=com.hpeit.mobile.support&hl=en" target="_blank">play store</Anchor> and install.
That is all folks!
</Headline>
<Headline className={`${CLASS_ROOT}__desc`} size="small">
p.s. you can click the little android to take you there
</Headline>
</Box>
<Box pad={{vertical: "medium", between: "medium"}} direction="column"
className={`${CLASS_ROOT}__col-1`}justify="center">
<Anchor href="https://play.google.com/store/apps/details?id=com.hpeit.mobile.support&hl=en" target="_blank">
<PlatformAndroid size="huge" colorIndex="grey-1" />
</Anchor>
</Box>
</InfographicSection>
);
};
|
client/src/react/journal/Journal.js
|
charlesj/Apollo
|
import React from 'react'
import { connect, } from 'react-redux'
import MarkdownRenderer from 'react-markdown-renderer'
import PropTypes from 'prop-types'
import { journalActions, } from '../../redux/actions'
import { journalSelectors, } from '../../redux/selectors'
import { NotifySuccess, } from '../../services/notifier'
import { Page, LoadMoreButton, Tag, AddButton, } from '../_controls'
import JournalEntryForm from './JournalEntryForm'
import './logs.css'
function EntryDisplay(props) {
const { entry, } = props
return (
<div className="note">
<div className="createdTime">{entry.createdAtDisplay}</div>
<div className="content">
<MarkdownRenderer markdown={entry.note} />
</div>
<div className="tags">
{entry.tags &&
entry.tags.map((t, i) => {
return <Tag key={i} name={t} />
})}
</div>
</div>
)
}
EntryDisplay.propTypes = {
entry: PropTypes.object.isRequired,
}
function EntryListDisplay(props) {
return (
<div>
{props.entries.map((entry) => {
return <EntryDisplay entry={entry} key={entry.id} />
})}
</div>
)
}
EntryListDisplay.propTypes = {
entries: PropTypes.array.isRequired,
}
class Journal extends React.Component {
constructor(props) {
super(props)
this.state = { addNote: true, }
}
componentDidMount() {
const { loadEntries, entries, } = this.props
loadEntries(entries.length)
}
handleNewEntry(formResult) {
const { saveEntry, } = this.props
saveEntry({
note: formResult.note,
tags: formResult.unifiedTags.split(','),
})
NotifySuccess('Added note')
this.setState({ addNote: false, })
}
render() {
const { entries, loadEntries, total, } = this.props
const { addNote, } = this.state
return (
<Page>
{!addNote && (
<AddButton
onClick={() => this.setState({ addNote: !addNote, })}
noun="Entry"
/>
)}
{addNote && (
<JournalEntryForm
onCancel={() => this.setState({ addNote: !addNote, })}
onSubmit={formResult => this.handleNewEntry(formResult)}
/>
)}
<EntryListDisplay entries={entries} />
<div>
{total} Total Entries {entries.length} Loaded
</div>
<LoadMoreButton onClick={() => loadEntries(entries.length)} />
</Page>
)
}
}
Journal.propTypes = {
entries: PropTypes.array.isRequired,
total: PropTypes.number.isRequired,
loadEntries: PropTypes.func.isRequired,
saveEntry: PropTypes.func.isRequired,
}
function mapStateToProps(state) {
const entries = journalSelectors.all(state)
return {
entries,
total: state.journal.total,
}
}
function mapDispatchToProps(dispatch) {
return {
loadEntries: start => dispatch(journalActions.load({ start, })),
saveEntry: entry => dispatch(journalActions.save(entry)),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Journal)
|
src/containers/DevToolsWindow.js
|
fforres/coworks_client_side
|
import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
export default createDevTools(
<LogMonitor />
);
|
src/svg-icons/maps/local-cafe.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalCafe = (props) => (
<SvgIcon {...props}>
<path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.89 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM2 21h18v-2H2v2z"/>
</SvgIcon>
);
MapsLocalCafe = pure(MapsLocalCafe);
MapsLocalCafe.displayName = 'MapsLocalCafe';
export default MapsLocalCafe;
|
setup/src/universal/features/user/auth/components/ResetPasswordForm/index.js
|
ch-apptitude/goomi
|
/**
*
* ResetPasswordForm
*
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Form } from 'react-form';
import { Row, Col } from 'react-flexbox-grid';
import Theme from 'assets/theme';
import Box from 'features/common_ui/components/Box';
import { GreenButton } from 'features/common_ui/components/Button';
import Field from 'features/common_ui/form/Field';
import validate from './validate';
import messages from './messages';
class ResetPasswordForm extends Component {
renderForm = ({ submitForm }) => {
return (
<form onSubmit={submitForm} name="ResetPasswordForm">
<Box>
<Field type="password" field="password" label={messages.password} autoFocus />
<Field type="password" field="repassword" label={messages.repassword} />
</Box>
<Box smallHeight borderTop>
<Row middle="xs">
<Col xs={12}>
<GreenButton type="submit" message={messages.save} fitWidth />
</Col>
</Row>
</Box>
</form>
);
};
render() {
const { onSubmit, onChange } = this.props;
return (
<Form onSubmit={onSubmit} validate={validate} onChange={onChange}>
{this.renderForm}
</Form>
);
}
}
ResetPasswordForm.defaultProps = {
onChange: () => {},
onSubmit: () => {},
};
ResetPasswordForm.propTypes = {
onSubmit: PropTypes.func,
onChange: PropTypes.func,
};
export default ResetPasswordForm;
|
examples/todomvc/index.js
|
wong2/redux
|
import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import App from './containers/App';
import configureStore from './store/configureStore';
import 'todomvc-app-css/index.css';
const store = configureStore();
React.render(
<Provider store={store}>
{() => <App />}
</Provider>,
document.getElementById('root')
);
|
src/renderer/components/TitleBarShim.js
|
digidem/ecuador-map-editor
|
import React from 'react'
import { remote } from 'electron'
import styled from 'styled-components'
const TitleBarArea = styled.div`
position: relative;
height: 22px;
`
// Create a space for MacOS title bar buttons on a frameless Window
const TitleBarShim = () => {
const win = remote.getCurrentWindow()
const titleBarSize = win.getSize()[1] - win.getContentSize()[1]
if (titleBarSize > 0) return null
return <TitleBarArea />
}
export default TitleBarShim
|
src/components/preview/preview-input.js
|
sergeyruskov/sergeyruskov.github.io
|
//@flow
import React from 'react';
import type {Card, UpdateCard} from "../../types/cards";
import type {Action} from "../../types/index";
/**
* Предпросмотр и настройка добавленного пользователем контрола Input
**/
export default function PreviewInput({updateCard, card, id}: {
updateCard: UpdateCard => Action,
card: Card,
id: number
}) {
const {title, required} = card;
return <div className="preview__item--without-hover">
<label className="preview__label">
Имя поля: <br/>
<input placeholder="Введите имя поля" className="preview__label-input" value={title} required={required} type="text" onChange={(e) => updateCard({id, 'title': e.target.value})} />
</label>
<label className="preview__label">
Обязательное поле:
<input
type="checkbox"
checked={required}
onChange={(e) => updateCard({id, 'required': e.target.checked})}
/>
</label>
</div>
}
|
src/Grid.js
|
tannewt/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import CustomPropTypes from './utils/CustomPropTypes';
const Grid = React.createClass({
propTypes: {
/**
* Turn any fixed-width grid layout into a full-width layout by this property.
*
* Adds `container-fluid` class.
*/
fluid: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
let className = this.props.fluid ? 'container-fluid' : 'container';
return (
<ComponentClass
{...this.props}
className={classNames(this.props.className, className)}>
{this.props.children}
</ComponentClass>
);
}
});
export default Grid;
|
twitter-ui-react/src/index.js
|
leemurray100/twitter
|
/* eslint-disable import/default */
import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import configureStore from './store/configureStore';
require('./favicon.ico'); // Tell webpack to load favicon.ico
import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import { syncHistoryWithStore } from 'react-router-redux';
const store = configureStore();
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>, document.getElementById('app')
);
|
techCurriculum/ui/solutions/2.1/src/components/Title.js
|
jennybkim/engineeringessentials
|
/**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
function Title() {
return (
<div>
<h1>Cards</h1>
<h2>Share your ideas</h2>
</div>
);
}
export default Title;
|
static/src/entry.js
|
smit1625/gospotchess
|
import React from 'react';
import ReactDOM from 'react-dom';
// import Routes from './components/Routes';
import ChessGame from './components/ChessGame';
ReactDOM.render(
<ChessGame url="/api/moves" pollInterval={2000} />,
document.getElementById('gsc-chess'));
|
src/components/organisms/FileDetailMenu/index.js
|
SIB-Colombia/biodiversity_catalogue_v2_frontend
|
import React from 'react';
import styled from 'styled-components';
import Carousel from 'react-slick';
import {Grid, Row, Col} from 'react-flexbox-grid';
import RaisedButton from 'material-ui/RaisedButton';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import Menu from 'material-ui/svg-icons/navigation/menu';
import ArrowBack from 'material-ui/svg-icons/hardware/keyboard-arrow-left';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import Chip from 'material-ui/Chip';
import {List, ListItem} from 'material-ui/List';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import Subheader from 'material-ui/Subheader';
import {Link} from 'components';
import {size, palette} from 'styled-theme';
import Scrollchor from 'react-scrollchor';
const Wrapper = styled.div `
float: left;
left: -32px;
position: relative;
width: 35px;
@media ${size('sm')}{
position: absolute;
left: 0;
top:0;
button{
width: 30px !important;
}
}
.index{
color: #555;
font-weight: 600;
font-size: 20px;
text-align: center;
padding: 15px 5px 15px 5px;
border-bottom: 1px solid #e8e8e8;
}
.nav-link{
span{
font-weight: 400 !important;
font-size: 13px !important;
}
}
.style-btn{
box-shadow: none !important;
/*margin-top: 3.5px;*/
button{
background-color: ${palette('primary', 0)} !important;
height: 64px !important;
border-radius: 0 !important;
svg{
}
}
}
`
class FileDetailMenu extends React.Component {
constructor(props) {
super(props)
this.state = {
open: false,
sections: []
}
}
componentWillMount() {
let sections = [];
for (var property in this.props.complete) {
if(property.indexOf('InUse') > -1){
sections[property] = true;
}
}
this.setState({sections :sections});
}
handleToggleMenu = () => this.setState({
open: !this.state.open
});
render() {
return (
<Wrapper>
<div className="btnFilters animated fadeInLeft">
<FloatingActionButton onTouchTap={this.handleToggleMenu} className="style-btn">
<Menu/>
</FloatingActionButton>
</div>
<Drawer open={this.state.open} containerClassName="drawer">
<div className="index">Índice de ficha</div>
{Object.keys(this.state.sections).map((section,i) => (
<Scrollchor key={i} to={`#${section}`} animate={{offset: -80, duration: 600}} className="nav-link"><MenuItem>{section}</MenuItem></Scrollchor>
))}
</Drawer>
</Wrapper>
)
}
}
export default FileDetailMenu;
|
src/components/parallax-scroll.component.js
|
gitpoint/git-point
|
import React, { Component } from 'react';
import { View, Dimensions, Platform, TouchableOpacity } from 'react-native';
import ParallaxScrollView from 'react-native-parallax-scroll-view';
import { Icon } from 'react-native-elements';
import styled from 'styled-components';
import { colors, normalize, fonts } from 'config';
const STICKY_HEADER_HEIGHT = 44;
type Props = {
renderContent: any,
stickyTitle: string,
navigateBack?: boolean,
showMenu?: boolean,
menuAction?: Function,
menuIcon?: string,
navigation: Object,
children?: React.Element<*>,
refreshControl?: React.Element<*>,
};
type State = {
parallaxHeaderHeight: number,
};
const Background = styled.View`
position: absolute;
top: 0;
background-color: ${colors.primaryDark};
height: ${props => props.height};
`;
const StickySection = styled.View`
height: ${STICKY_HEADER_HEIGHT};
background-color: ${colors.primaryDark};
align-items: center;
justify-content: flex-end;
`;
const StickySectionText = styled.Text`
color: ${colors.white};
font-size: ${normalize(16)};
margin: 10px;
${fonts.fontPrimaryBold};
`;
const FixedSectionLeft = styled.View`
position: absolute;
bottom: 0;
`;
const FixedSectionRight = styled.View`
position: absolute;
bottom: 10;
right: 10;
`;
export class ParallaxScroll extends Component {
props: Props;
state: State;
constructor(props) {
super(props);
this.state = {
parallaxHeaderHeight: this.getParallaxHeaderHeight(),
};
}
componentDidMount() {
Dimensions.addEventListener('change', this.dimensionsDidChange);
}
getParallaxHeaderHeight = (window = Dimensions.get('window')) => {
let divider = 2;
if (window.width > window.height) {
divider = Platform.OS === 'ios' ? 1.2 : 1.4;
}
return window.height / divider;
};
dimensionsDidChange = ({ window }) => {
this.setState({
parallaxHeaderHeight: this.getParallaxHeaderHeight(window),
});
};
render() {
const {
renderContent,
stickyTitle,
navigateBack,
showMenu,
menuIcon,
menuAction,
navigation,
children,
refreshControl,
} = this.props;
return (
<ParallaxScrollView
backgroundColor={colors.primaryDark}
stickyHeaderHeight={STICKY_HEADER_HEIGHT}
parallaxHeaderHeight={this.state.parallaxHeaderHeight}
backgroundSpeed={10}
renderBackground={() => (
<View key="background">
<Background height={this.state.parallaxHeaderHeight} />
</View>
)}
renderForeground={renderContent}
renderStickyHeader={() => (
<StickySection key="sticky-header">
<StickySectionText>{stickyTitle}</StickySectionText>
</StickySection>
)}
renderFixedHeader={() => (
<View key="fixed-header">
{navigateBack && (
<FixedSectionLeft>
<TouchableOpacity onPress={() => navigation.goBack()}>
<Icon
name="chevron-left"
size={42}
color={colors.white}
underlayColor="transparent"
/>
</TouchableOpacity>
</FixedSectionLeft>
)}
{showMenu && (
<FixedSectionRight>
<TouchableOpacity onPress={menuAction}>
<Icon
name={menuIcon}
type="font-awesome"
color={colors.white}
underlayColor="transparent"
/>
</TouchableOpacity>
</FixedSectionRight>
)}
</View>
)}
refreshControl={refreshControl}
>
{children}
</ParallaxScrollView>
);
}
}
ParallaxScroll.defaultProps = {
navigateBack: false,
showMenu: false,
menuIcon: 'ellipsis-h',
menuAction: undefined,
children: null,
refreshControl: null,
};
|
tests/views/HomeView.spec.js
|
juanda99/react-redux-material-ui
|
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import { bindActionCreators } from 'redux'
import { HomeView } from 'views/HomeView/HomeView'
import { mount } from 'enzyme'
function shallowRender (component) {
const renderer = TestUtils.createRenderer()
renderer.render(component)
return renderer.getRenderOutput()
}
function renderWithProps (props = {}) {
return TestUtils.renderIntoDocument(<HomeView {...props} />)
}
function shallowRenderWithProps (props = {}) {
return shallowRender(<HomeView {...props} />)
}
describe('(View) Home', function () {
let _component, _rendered, _props, _spies
beforeEach(function () {
_spies = {}
_props = {
counter: 0,
...bindActionCreators({
doubleAsync: (_spies.doubleAsync = sinon.spy()),
increment: (_spies.increment = sinon.spy())
}, _spies.dispatch = sinon.spy())
}
_component = shallowRenderWithProps(_props)
_rendered = renderWithProps(_props)
})
it('Should render as a <div>.', function () {
expect(_component.type).to.equal('div')
})
it('Should include an <h1> with welcome text.', function () {
const h1 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h1')
expect(h1).to.exist
expect(h1.textContent).to.match(/Welcome to the React Redux Starter Kit/)
})
it('Should render with an <h2> that includes Sample Counter text.', function () {
const h2 = TestUtils.findRenderedDOMComponentWithTag(_rendered, 'h2')
expect(h2).to.exist
expect(h2.textContent).to.match(/Sample Counter/)
})
it('Should render props.counter at the end of the sample counter <h2>.', function () {
const h2 = TestUtils.findRenderedDOMComponentWithTag(
renderWithProps({ ..._props, counter: 5 }), 'h2'
)
expect(h2).to.exist
expect(h2.textContent).to.match(/5$/)
})
it('Should render exactly two buttons.', function () {
const wrapper = mount(<HomeView {..._props} />)
expect(wrapper).to.have.descendants('.btn')
})
describe('An increment button...', function () {
let _btn
beforeEach(() => {
_btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button')
.filter((a) => /Increment/.test(a.textContent))[0]
})
it('should be rendered.', function () {
expect(_btn).to.exist
})
it('should dispatch an action when clicked.', function () {
_spies.dispatch.should.have.not.been.called
TestUtils.Simulate.click(_btn)
_spies.dispatch.should.have.been.called
})
})
describe('A Double (Async) button...', function () {
let _btn
beforeEach(() => {
_btn = TestUtils.scryRenderedDOMComponentsWithTag(_rendered, 'button')
.filter((a) => /Double/.test(a.textContent))[0]
})
it('should be rendered.', function () {
expect(_btn).to.exist
})
it('should dispatch an action when clicked.', function () {
_spies.dispatch.should.have.not.been.called
TestUtils.Simulate.click(_btn)
_spies.dispatch.should.have.been.called
})
})
})
|
src/main/server/utils/renderComponent.js
|
FrederikS/react-isomorphic-example
|
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { RouterContext } from 'react-router';
import ContextProvider from '../../common/container/ContextProvider';
import Layout from '../Layout';
import fetchComponentData from './fetchComponentData';
import dehydrate from './dehydrate';
export default function (store, renderProps) {
return new Promise((resolve, reject) => {
fetchComponentData(store, renderProps.components)
.then(() => {
const css = new Set();
const content = ReactDOMServer.renderToString(
/* eslint-disable no-underscore-dangle */
<ContextProvider
context={{
store,
insertCss: styles => css.add(styles._getCss())
}}
>
{/* eslint-enable */}
<RouterContext {...renderProps} />
</ContextProvider>
);
resolve(Layout.render({
content,
css: Array.from(css).join(''),
state: dehydrate({ store })
}));
}).catch(error => reject(error));
});
}
|
extensions/genericdata/client-admin.js
|
axax/lunuc
|
import React from 'react'
import Hook from 'util/hook'
import Async from 'client/components/Async'
import {
SimpleSwitch,
SimpleButton
} from 'ui/admin'
import Util from '../../client/util'
import {CAPABILITY_MANAGE_CMS_TEMPLATE} from '../cms/constants'
import {client} from 'client/middleware/graphql'
import config from 'gen/config-client'
import {_t, registerTrs} from '../../util/i18n'
import {performFieldProjection} from '../../util/project'
import {translations} from './translations/admin'
import {setPropertyByPath} from "../../client/util/json";
import {openWindow} from '../../client/util/window'
import {deepMergeToFirst} from '../../util/deepMerge'
import {parseStyles} from '../../client/util/style'
registerTrs(translations, 'GenericData')
const GenericForm = (props) => <Async {...props}
load={import(/* webpackChunkName: "admin" */ '../../client/components/GenericForm')}/>
const Typography = (props) => <Async {...props} expose="Typography"
load={import(/* webpackChunkName: "admin" */ '../../gensrc/ui/admin')}/>
const findField = (definition, key) => {
if (definition && definition.structure && definition.structure.fields) {
if (key.startsWith('data.')) {
key = key.substring(5)
}
return definition.structure.fields.find(f => f.name === key)
}
}
export default () => {
/*
TypesContainer: gets called before the table is rendered
add some extra data to the table
*/
Hook.on('TypeTable', ({type, dataSource, data, container}) => {
if (type === 'GenericData' && data.results.length > 0) {
dataSource.forEach((row, i) => {
const item = data.results[i],
structure = item.definition ? item.definition.structure : {}
if (structure) {
if(structure.rowStyle){
const styleString = Util.replacePlaceholders(structure.rowStyle, {Util, ...item})
if(styleString) {
row.style = parseStyles(styleString)
}
}
if (structure.titleTemplate) {
row.data = Util.replacePlaceholders(structure.titleTemplate, {Util, ...item})
if (structure.titleIsHtml) {
row.data = <div dangerouslySetInnerHTML={{
__html: row.data
}}/>
}
} else {
let pickerFields
if (structure.pickerField) {
// can be a String or an Array
pickerFields = structure.pickerField
} else if (item.data.title) {
// take title attribute if available
pickerFields = 'title'
} else {
// take the fist attribute of the object if none is specified
const keys = Object.keys(item.data)
if (keys.length > 0) {
pickerFields = keys[0]
}
}
if (pickerFields) {
if (pickerFields.constructor !== Array) {
pickerFields = [pickerFields]
}
row.data = ''
pickerFields.forEach(picker => {
if (item.data[picker]) {
let value
if (item.data[picker].constructor === Object) {
//TODO it is not save to assume that it is a localized value
value = item.data[picker][_app_.lang]
} else {
value = item.data[picker]
}
if (value) {
if (row.data) {
row.data += ' | '
}
row.data += value
}
}
})
if (row.data.length > 83) {
row.data = row.data.substring(0, 80) + '...'
}
}
}
}
})
}
})
Hook.on('TypeCreateEdit', ({type, props, meta, formFields, dataToEdit, parentRef}) => {
if (type === 'GenericData') {
if (!dataToEdit) {
// create empty object
dataToEdit = {}
const data = meta.TypeContainer.state.data
if (data.meta) {
dataToEdit.definition = JSON.parse(data.meta)
}
const {baseFilter} = Util.extractQueryParams(window.location.search.substring(1))
// if there is a base filter set try to use its value to set as default when creating a new object
if (baseFilter) {
const query = Util.extractQueryParams(baseFilter.replace(/==/g, '='))
Object.keys(query).forEach(key => {
let value = query[key]
if (value) {
const field = findField(dataToEdit.definition, key)
if (field) {
if (field.type === 'Boolean') {
value = value === 'true' ? true : false
}
}
setPropertyByPath(value, key, dataToEdit)
}
})
}
}
if (!dataToEdit.definition && meta.TypeContainer.pageParams.meta) {
dataToEdit.definition = meta.TypeContainer.pageParams.meta
}
if (dataToEdit.definition && (dataToEdit.definition.structure || dataToEdit.definition.constructor === String)) {
if (!dataToEdit.definition.structure) {
client.query({
query: `query genericDataDefinitions($filter:String){genericDataDefinitions(filter:$filter){results{_id name structure}}}`,
variables: {
filter: `_id=${dataToEdit.definition} || name==${dataToEdit.definition}`
}
}).then(response => {
if (response.data.genericDataDefinitions.results) {
const definition = response.data.genericDataDefinitions.results[0]
let newDataToEdit = Object.assign({}, dataToEdit, {
definition: Object.assign({}, definition, {structure: JSON.parse(definition.structure)}),
createdBy: _app_.user
})
parentRef.setState({dataToEdit: newDataToEdit})
}
}).catch(error => {
console.error(error.message)
})
props.children = <React.Fragment>
loading structure...
</React.Fragment>
} else {
const structure = dataToEdit.definition.structure,
dataObject = dataToEdit.data || {}
const newFields = Object.assign({}, formFields)
const newDataToEdit = Object.assign({}, dataToEdit)
delete newFields.data
delete newDataToEdit.data
newFields.definition.readOnly = true
let overrideTranslations = false, translateTimeout = 0
const userHasCapa = Util.hasCapability({userData: _app_.user}, CAPABILITY_MANAGE_CMS_TEMPLATE)
const actions = structure.actions
if (actions) {
props.actions.unshift(...structure.actions)
}
props.title = <React.Fragment>
{structure.title || newDataToEdit.definition.name}{newDataToEdit._id && userHasCapa ? ' (' + newDataToEdit._id + ')' : ''}
<div
style={{float: 'right', textAlign: 'right'}}>{userHasCapa && [<SimpleButton
key="showJson" size="small" variant="contained"
color="primary"
onClick={() => {
const a = document.createElement('a'),
blob = new Blob([JSON.stringify(dataObject, null, 2)], {'type': 'text/plain'})
a.href = window.URL.createObjectURL(blob)
// a.download = 'json.txt'
a.target = '_blank'
a.click()
}}>Show JSON</SimpleButton>,
<SimpleButton key="autoTranslate" size="small" variant="contained"
color="primary"
onClick={() => {
structure.fields.forEach(field => {
if (field.localized) {
const name = field.name
if (!dataObject[name]) {
dataObject[name] = newFields[name]
}
if (dataObject[name] && dataObject[name].constructor === String) {
dataObject[name] = {[config.DEFAULT_LANGUAGE]: dataObject[name]}
}
const obj = dataObject[name]
if (obj) {
config.LANGUAGES.forEach(lang => {
if ((overrideTranslations || !obj[lang]) && lang !== config.DEFAULT_LANGUAGE) {
const text = obj[config.DEFAULT_LANGUAGE].replace(/\\n/g, '\n').replace(/%(\w+)%/g, '@_$1_')
client.query({
fetchPolicy: 'no-cache',
query: 'query translate($text: String!, $toIso: String!){translate(text: $text, toIso: $toIso){text toIso}}',
variables: {
text,
toIso: lang,
fromIso: config.DEFAULT_LANGUAGE
},
}).then((res) => {
const resLang = res.data.translate.toIso
const newText = res.data.translate.text.replace(/@_(\w+)_/g, '%$1%').replace(/\\/g, '') //.replace(/"/g,'\\"')
dataObject[name][resLang] = newText
clearTimeout(translateTimeout)
translateTimeout = setTimeout(() => {
parentRef.setState({
forceSave: true,
dataToEdit: {
...dataToEdit,
data: dataObject
}
})
}, 1000)
})
}
})
}
}
})
}}>Autotranslate
</SimpleButton>,
<SimpleSwitch key="overrideTranslations" label="Override Translations"
name="overrideTranslations"
onChange={(e) => {
overrideTranslations = e.target.checked
}}/>
]}
</div>
</React.Fragment>
structure.fields.forEach((field) => {
const oriName = field.name, newName = 'data_' + oriName
newFields[newName] = Object.assign({}, field, {name: newName})
if (field.localized) {
newDataToEdit[newName] = dataObject[oriName]
} else {
newDataToEdit[newName] = dataObject[oriName] && dataObject[oriName].constructor === Object ? JSON.stringify(dataObject[oriName]) : dataObject[oriName]
}
if (field.defaultValue && !newDataToEdit[newName]) {
try {
newDataToEdit[newName] = eval(field.defaultValue)
} catch (e) {
newDataToEdit[newName] = field.defaultValue
}
}
})
if (structure.extendFields) {
deepMergeToFirst(newFields, structure.extendFields)
}
// override default
props.children = <GenericForm autoFocus
onRef={ref => {
if(ref) {
parentRef.createEditForm = ref
}
}}
onBlur={event => {
}}
onChange={field => {
}}
primaryButton={false}
fields={newFields}
trigger={structure.trigger}
values={newDataToEdit}/>
}
} else {
const newFields = Object.assign({}, formFields)
newFields.definition.readOnly = false
delete newFields.data
delete dataToEdit.definition
// override default
props.children = <React.Fragment>
<Typography key="GenericDataLabel" variant="subtitle1"
gutterBottom>{_t('GenericData.createNewHint')}</Typography>
<GenericForm key="genericForm" autoFocus onRef={ref => {
if(ref) {
parentRef.createEditForm = ref
}
}} onBlur={event => {
Hook.call('TypeCreateEditBlur', {type, event})
}} onChange={field => {
}} primaryButton={false} fields={newFields} values={dataToEdit}/>
</React.Fragment>
}
}
})
Hook.on('TypeCreateEditBeforeSave', function ({type, editedData, optimisticData, formFields}) {
if (type === 'GenericData' && editedData && editedData.definition) {
const definition = editedData.definition.constructor === Array ? editedData.definition[0] : editedData.definition,
dataObject = {},
optimisticDataObject = {}
if (definition.structure.constructor === String) {
definition.structure = JSON.parse(definition.structure)
}
// Combine data attributes to the data object
definition.structure.fields.forEach(field => {
if (field.genericType) {
// only keep reference _id
const fieldData = editedData['data_' + field.name]
if (fieldData && fieldData.constructor === Array && fieldData.length > 0 && fieldData[0]._id) {
if (field.metaFields) {
dataObject[field.name] = fieldData.map(e => ({_id: e._id, metaValues: e.metaValues}))
} else {
dataObject[field.name] = fieldData.map(e => e._id)
}
} else if (fieldData && fieldData._id) {
if (field.metaFields) {
dataObject[field.name] = {_id: fieldData._id, metaValues: fieldData.metaValues}
} else {
dataObject[field.name] = fieldData._id
}
} else {
dataObject[field.name] = editedData['data_' + field.name]
}
// we keep resolved values for the optimisticDataObject
optimisticDataObject[field.name] = editedData['data_' + field.name]
} else {
let currentDataAttr
if (field.type === 'Object' && !(editedData['data_' + field.name] instanceof Object)) {
try {
currentDataAttr = JSON.parse(editedData['data_' + field.name])
} catch (e) {
console.log(e, field.name + ' -> ' + editedData['data_' + field.name])
}
} else {
currentDataAttr = editedData['data_' + field.name]
}
dataObject[field.name] = optimisticDataObject[field.name] = currentDataAttr
}
// delete data attribute
delete editedData['data_' + field.name]
delete optimisticData['data_' + field.name]
})
editedData.data = JSON.stringify(dataObject)
optimisticData.data = optimisticDataObject
}
})
/*
Send the name of the generic type as meta data
*/
Hook.on('TypeTableBeforeEdit', function ({type, data, variables, fieldsToLoad}) {
if (type === 'GenericData' && data.definition) {
variables.meta = data.definition.name
if (data.definition.structure && fieldsToLoad.indexOf('data') < 0) {
if (data.definition.structure.fields.some(f => f.vagueLookup === false)) {
fieldsToLoad.push('data')
}
}
}
})
// add some extra data to the table
Hook.on('TypeTableAction', function ({type, actions, pageParams}) {
if (type === 'GenericData') {
const filterdActions = actions.filter(f => f.key === 'export_csv')
if (filterdActions.length > 0) {
// replace cvs export function
filterdActions[0].onClick = () => {
const items = []
this.state.data.results.forEach(res => {
items.push({date: Util.formattedDatetimeFromObjectId(res._id), ...res.data})
})
const header = Object.keys(items[0])
let csv = items.map(row => header.map(fieldName => {
let value = row[fieldName]
if (value) {
if (value.constructor === Array) {
value = value.map(item => {
return item._id
})
} else if (value.constructor === Object) {
value = JSON.stringify(value)
}
} else {
value = ''
}
return '"' + Util.escapeForJson(value) + '"'
}).join(','))
csv.unshift(header.join(','))
csv = csv.join('\r\n')
const a = document.createElement('a'),
blob = new Blob([csv], {'type': 'text/comma-separated-values'})
a.href = window.URL.createObjectURL(blob)
a.download = (pageParams.title || 'export') + '.csv'
a.target = '_blank'
a.click()
}
}
}
})
/*
TypePicker: This gets called after the user picks items in a new window
filter the object with only the attributes that are specified as pickerFields
*/
Hook.on('TypePickerBeforeHandlePick', function ({type, fieldsToProject, rawValue}) {
if (type === 'GenericData') {
let dataFieldsToProject
if (fieldsToProject.length === 0 && rawValue.definition && rawValue.definition.structure) {
dataFieldsToProject = rawValue.definition.structure.pickerField
if (dataFieldsToProject && dataFieldsToProject.constructor !== Array) {
dataFieldsToProject = [dataFieldsToProject]
}
} else {
dataFieldsToProject = fieldsToProject.slice(0)
}
if (dataFieldsToProject && dataFieldsToProject.length > 0) {
// project data
try {
const newData = performFieldProjection(dataFieldsToProject, rawValue.data)
rawValue.data = newData
delete rawValue.definition
} catch (e) {
console.log('Error in TypePickerBeforeHandlePick', e)
}
fieldsToProject.splice(0, fieldsToProject.length)
fieldsToProject.push('_id')
fieldsToProject.push('data')
}
}
})
/*
TypePicker: This gets called before the query string is built
*/
Hook.on('TypePickerBeforeQueryString', function ({type, finalFields}) {
if (type === 'GenericData') {
finalFields.splice(0, finalFields.length)
finalFields.push('data')
}
})
/*
TypePicker: This gets called after the user types in the picker field and before data are loaded
*/
Hook.on('TypePickerBeforeHandleChange', function ({value, searchFields, type}) {
if (type === 'GenericData') {
if (searchFields) {
for (let i = 0; i < searchFields.length; i++) {
if (!searchFields[i].startsWith('data.')) {
searchFields[i] = 'data.' + searchFields[i]
}
}
}
}
})
/*
TypesContainer: This gets called before the filter dialog is shown
*/
Hook.on('TypesContainerBeforeFilterDialog', function ({type, filterFields}) {
if (type === 'GenericData') {
if (this.state.data.meta) {
const definition = JSON.parse(this.state.data.meta)
if (definition.structure) {
delete filterFields.definition
definition.structure.fields.forEach(field => {
if (field.searchable) {
filterFields['data.' + field.name] = Object.assign({}, field, {
tab: null,
required: false,
fullWidth: true
})
if (field.uitype === 'datetime') {
filterFields['data.' + field.name].fullWidth = false
filterFields['data.' + field.name].twoThirdWidth = true
filterFields['__operator.data.' + field.name] = {
label: 'Vergleichsoperator',
enum: [
{
value: '==',
name: 'ist gleich'
},
{
value: '>',
name: 'ist grösser'
},
{
value: '<',
name: 'ist kleiner'
}
],
tab: null,
required: false,
thirdWidth: true
}
}
}
})
}
}
}
})
/*
TypesContainer: This gets called before the filter dialog is shown
*/
Hook.on('TypesContainerBeforeFilterLabel', function ({type, payload}) {
if (type === 'GenericData') {
if (this.state.data && this.state.data.meta) {
const definition = JSON.parse(this.state.data.meta)
if (definition.structure) {
const newPrettyFilter = {}
if(payload.prettyFilter.createdBy){
newPrettyFilter['Kunde'] = payload.prettyFilter.createdBy
}
definition.structure.fields.forEach(field => {
let value = payload.prettyFilter['data.'+field.name]
if(value){
if(field.enum){
const tmp = field.enum.find(f=>f.value===value)
if(tmp){
value = tmp.name
}
}else if (field.uitype === 'datetime') {
value = new Date(value)
}
const key = field.label || field.name
newPrettyFilter['__operator.'+key] = payload.prettyFilter['__operator.data.'+field.name]
newPrettyFilter[key] = value
}
})
payload.prettyFilter = newPrettyFilter
}
}
}
})
/*
TypesContainer: This gets called before the filter dialog is shown
*/
Hook.on('typeDataToLabel', function (context) {
if (context.item.__typename === 'GenericData') {
const definition = context.item.definition
try {
if (typeof context.item.data === 'object') {
context.item = context.item.data
} else {
context.item = JSON.parse(context.item.data)
}
} catch (e) {
console.log(e)
}
if (!context.pickerField) {
if (definition) {
try {
context.pickerField = definition.structure.pickerField
} catch (e) {
console.log(e)
}
}
}
}
})
Hook.on('TypeCreateEditAction', ({type, action, dataToEdit}) => {
if (type === 'GenericData' && action.url) {
try {
const actionStr = new Function('const data=this.data,Util=this.Util;return `' + JSON.stringify(action) + '`').call({
data: dataToEdit.data,
_id: dataToEdit._id,
Util
})
const newAction = JSON.parse(actionStr)
openWindow(newAction)
} catch (e) {
console.log('Error in actions', e)
}
}
})
}
|
src/components/constellations.js
|
cosmowiki/cosmowiki
|
import React from 'react';
import {ConstellationNotes} from './notes';
import {Summary} from './chunks/summary';
const ConstellationsComponent = ({constellations}) => {
return (
<main role="main" className="pure-u-1">
<div id="siteTitle" className="constellations pure-u-1 center">
<div id="siteTitleContainer">
<h1>Sternbilder</h1>
<h3>Figuren am Firmament</h3>
</div>
</div>
<div id="todo" className="pure-u-1">
<p>@wolfram: pls make the filter work with FilterRows as in stars-site</p>
</div>
<Summary>
<p className="summary-text">
<em>Orion</em>, <em>Kassiopeia</em> oder die beiden <em>Zwillinge</em> <em>Castor</em> und <em>Pollux</em> -
wir alle kennen mindestens ein Sternbild und können es aus dem Stehgreif
am Nachthimmel finden. Diese Figuren weisen seit Jahrhunderten Reisenden
den Weg.
</p>
<div className="summary-img size-lg">
<a href="/img/constellations/Ursa_Major_(Bode).jpg" title="Großer Bär, Kupferstich aus dem Sternatlas von Johann Elert Bode - Großansicht">
<img src="/img/constellations/Ursa_Major_(Bode).jpg" alt="Großer Bär, Kupferstich aus dem Sternatlas von Johann Elert Bode" />
</a>
<p className="summary-img-text">
Großer Bär, Johann Elert Bode
</p>
</div>
<p className="summary-text">
Auf der Nordhalbkugel helfen <em>Großer Wagen</em> und <em>Kleiner Wagen</em> den
Polarstern zu finden, wobei der Große Wagen als Asterismus kein eigenes
Sternbild ist, sondern nur ein Teil des <em>Großen Bären</em>. Auch
die <em>Kassiopeia</em>, das "Himmels-W" zieht nach Norden hin geöffnet
am Firmament entlang.
</p>
<div className="summary-img size-lg">
<a href="/img/constellations/Dunhuang_star_map_lg.jpg" title="Sternenkarte von Dunhuang, China - Großansicht">
<img src="/img/constellations/Dunhuang_star_map_sm.jpg" alt="Sternenkarte von Dunhuang, China" />
</a>
<p className="summary-img-text">
Dunhuang Sternenkarte
</p>
</div>
<p className="summary-text">
Die Bewohner der südlichen Hemisphäre orientieren sich am <em>Kreuz des
Südens</em>, dessen Name von christlichen Seefahrern geprägt wurde.
Schon <em>Amerigo Vespucci</em>, nach dem die Neue Welt ihren Namen Amerika
erhielt, nutzte das Kreuz des Südens Anfang des 16. Jahrhunderts zur Orientierung
auf seinen Reisen entlang der Ostküste Südamerikas.
</p>
<p className="summary-text">
Sternbilder dürften schon in vielen frühgeschichtlichen Kulturen bekannt
gewesen sein. Die heute verwendeten Konstellationen haben ihren Ursprung
in den 12 Tierkreiszeichen aus Babylonien und dem Ägypten des Altertums.
Mitte des 2. Jahrhunderts n. Chr. erstellte <em>Claudius Ptolemäus</em> dann
mit dem <em>Almagest</em> eines der größten Werke der antiken Astronomie.
Dieses für die folgenden 1500 Jahre prägende Lehrbuch enthielt auch einen
Sternenkatalog mit Angaben zu 1025 Sternen in 48 Sternbildern.
</p>
<div className="summary-img">
<a href="/img/constellations/Planisphaerium_Coeleste_lg.jpg" title="Planisphaerium Coeleste von Georg Christoph Eimmart, 1705 - Großansicht">
<img src="/img/constellations/Planisphaerium_Coeleste_sm.jpg" alt="Planisphaerium Coeleste von Georg Christoph Eimmart, 1705" />
</a>
<p className="summary-img-text">
Planisphaerium Coeleste,<br />
Georg Christoph Eimmart
</p>
</div>
<p className="summary-text">
<em>Johann Bayer</em> übernahm dann 1603 in seiner <em>Uranometria</em> einige
Konstellationen aus Himmelsgloben des <em>Petrus Plancius</em>, die auf
die niederländischen Navigatoren <em>Pieter Dirkszoon Keyser</em> und <em>Frederick
de Houtman</em> zurückgingen. Die Astronomen <em>Johannes
Hevelius</em> und <em>Nicolas-Louis de Lacaille</em> fügten weitere hinzu.
</p>
<p className="summary-text">
Religiöse Motive führten zur Umbenennung und Ersetzung heidnischer Sternbilder.
Zu Ehren zeitgenössischer Herrscher oder aus astronomischer Notwendigkeit
heraus wurde der Kanon immer wieder reformiert und erweitert. Durch die
Erfindung des Teleskopes war die Zahl der bekannten Sterne schnell gewachsen
und die Kreativität bei der "Erfindung" neuer Konstellationen wuchs mit
dem Zwang nach Zuordnung.
</p>
<div className="summary-img size-sm">
<a href="/img/constellations/Papua_New_Guinea_lg.png" title="Flagge von Papua Neuguinea - Großansicht">
<img src="/img/constellations/Papua_New_Guinea_sm.png" alt="Flagge von Papua Neuguinea" />
</a>
<p className="summary-img-text">
Papua-Neuguinea
</p>
</div>
<p className="summary-text">
Nach einem Vorschlag des amerikanischen Astronomen <em>Henry Norris Russell</em> legte
dann 1922 die <em>Internationale Astronomische Union</em> (IAU) auf ihrer ersten
Generalversammlung 88 Sternbilder fest, deren Grenzen sechs Jahre später
exakt definiert wurden.
</p>
<p className="summary-text">
Weltweit am bekanntesten dürfte das Kreuz des Südens sein, das auf vielen
Flaggen abgebildet ist und auch das Logo der <em>Europäischen
Südsternwarte</em> (ESO) ziert. Der Große Wagen prangt gemeinsam mit dem
Polarstern auf der Flagge des US-Bundesstaates Alaska.
</p>
<h4>Wussten Sie schon?</h4>
<ul className="summary-list">
<li>
Durch die <em>Präzessionsbewegung der Erde</em> war das Kreuz des Südens in
der Antike auch im Mittelmeerraum sichtbar.
</li>
<li>
Das Kreuz des Südens ist auf den Staatsflaggen von Australien, Brasilien,
Neuseeland, Papua-Neuguinea und Samoa zu sehen.
</li>
<li>
Die Namen von Sternbildern wie <em>Chemischer Ofen</em> oder <em>Luftpumpe</em> symbolisieren
den technischen Fortschritt des 18. Jahrhunderts.
</li>
</ul>
</Summary>
<div id="dataArea" className="constellations module pure-u-1">
<div id="controlArea" className="constellations pure-u-1">
<div id="controllers" className="pure-u-1">
<div id="sort" className="constellations pure-u-1-2 left">
<a href="#" className="toggle-sort" name="toggle-sort">Sortieren</a>
<div id="sortArea">
<form id="sortConstellations" className="sort-form">
<select name="sortConstellations" defaultValue="sortConstellationsName">
<option value="sortConstellationsName">Name</option>
<option value="sortConstellationsSquaredegrees">Fläche</option>
</select>
</form>
<div id="toggleAscDesc">
<label>
<input className="switch" type="checkbox" />
<span className="slider"></span>
<span className="text"></span>
</label>
</div>
</div>
</div>
<div id="filter" className="constellations pure-u-1-2 right">
<a href="#" className="toggle-filter" name="toggle-filter">Filtern</a>
<div id="filterArea">
<form id="filterConstellationsByVisibility" className="filter-form">
<label>Sichtbarkeit:</label>
<select name="constellationsVisibilities" defaultValue="showAllConstellations">
<option value="showAllConstellations">alle</option>
<option value="showConstellationsNorth">nur nördlich</option>
<option value="showConstellationsNorthsouth">nördlich, teils südlich</option>
<option value="showConstellationsMid">mittig</option>
<option value="showConstellationsSouthnorth">südlich, teils nördlich</option>
<option value="showConstellationsSouth">nur südlich</option>
</select>
</form>
</div>
</div>
</div>
</div>
<div id="constellationsTable">
{constellations.map((constellation, idx) => <ConstellationComponent constellation={constellation} key={idx}/>)}
</div>
</div>
<ConstellationNotes />
</main>
);
};
export default ConstellationsComponent;
const ConstellationComponent = ({constellation:item}) => {
return (
<div className="constellation-row data-row pure-u-1">
<div className="constellation-img pure-u-1 pure-u-sm-1-2 pure-u-md-1-3 center">
<a href={item.imageLargeUrl} title={item.name}><img src={item.imageSmallUrl} alt={item.name} /></a>
<small>
Bild: {item.imageSrc}<br />
<a href={item.imageLicenceUrl}>{item.imageLicence}</a>
</small>
</div>
<div className="constellation-info pure-u-1 pure-u-sm-1-2 pure-u-md-2-3 center">
<div className="constellation-name pure-u-1 pure-u-md-1-2">
<p className="constellation-name"><a href={item.wikipediaUrl} title={item.name}>{item.name}</a></p>
<p className="constellation-latin-name">({item.latinName})</p>
</div>
<div className="constellation-data pure-u-1 pure-u-md-1-2">
<p className="constellation-data1">sichtbar von {item.visibleFrom} bis {item.visibleTo}</p>
<p className="constellation-data2">Fläche: {item.squareDegrees} deg²</p>
<p className="constellation-data3">hellster Stern:<br />{item.brightestStarUrl ? <a href={item.brightestStarUrl} title={item.brightestStar}>{item.brightestStar}</a> : item.brightestStar} ({item.highestBrightness} mag)</p>
<p className="constellation-data4">benannt {item.namedYear} von <a href={item.astronomerUrl} title={item.astronomer}>{item.astronomer}</a></p>
</div>
</div>
</div>
);
};
|
example/examples/DraggableMarkers.js
|
pjamrozowicz/react-native-maps
|
import React from 'react';
import {
StyleSheet,
View,
Dimensions,
} from 'react-native';
import MapView from 'react-native-maps';
import PriceMarker from './PriceMarker';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const SPACE = 0.01;
function log(eventName, e) {
console.log(eventName, e.nativeEvent);
}
class MarkerTypes extends React.Component {
constructor(props) {
super(props);
this.state = {
a: {
latitude: LATITUDE + SPACE,
longitude: LONGITUDE + SPACE,
},
b: {
latitude: LATITUDE - SPACE,
longitude: LONGITUDE - SPACE,
},
};
}
render() {
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
initialRegion={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
>
<MapView.Marker
coordinate={this.state.a}
onSelect={(e) => log('onSelect', e)}
onDrag={(e) => log('onDrag', e)}
onDragStart={(e) => log('onDragStart', e)}
onDragEnd={(e) => log('onDragEnd', e)}
onPress={(e) => log('onPress', e)}
draggable
>
<PriceMarker amount={99} />
</MapView.Marker>
<MapView.Marker
coordinate={this.state.b}
onSelect={(e) => log('onSelect', e)}
onDrag={(e) => log('onDrag', e)}
onDragStart={(e) => log('onDragStart', e)}
onDragEnd={(e) => log('onDragEnd', e)}
onPress={(e) => log('onPress', e)}
draggable
/>
</MapView>
</View>
);
}
}
MarkerTypes.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
});
module.exports = MarkerTypes;
|
src/App.js
|
SwordSoul/swordsoul.github.com
|
import React, { Component } from 'react';
import {Route, Router, browserHistory} from 'react-router';
import Page from './Page.js';
import Contents from './Contents.js';
export default class App extends Component {
render() {
return (
<Router history={browserHistory}>
<Route name="contents" path="/" component = {Contents}/>
<Route
name = "Page"
path = "/:name"
component = {Page}
/>
</Router>
);
}
}
|
packages/icons/src/external.js
|
yldio/joyent-portal
|
import React from 'react';
import Rotate from './rotate';
import calcFill from './fill';
export default ({
fill = null,
light = false,
disabled = false,
direction = 'down',
colors = {},
style = {},
...rest
}) => (
<Rotate direction={direction}>
{({ style: rotateStyle }) => (
<svg
xmlns="http://www.w3.org/2000/svg"
width="17"
height="17"
viewBox="0 0 17 17"
style={{ ...style, ...rotateStyle }}
{...rest}
>
<path
fill={calcFill({ fill, disabled, light, colors })}
d="M14,9v5a1,1,0,0,1-1,1H3a1,1,0,0,1-1-1V4A1,1,0,0,1,3,3H8V1H3C1,1,0,2,0,4V14c0,2,1,3,3,3H13c2,0,3-1,3-3V9ZM11,0h6V6H15V2.7L7.38,10.32l-.7-.7L14.29,2H11Z"
/>
</svg>
)}
</Rotate>
);
|
blueocean-material-icons/src/js/components/svg-icons/content/undo.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ContentUndo = (props) => (
<SvgIcon {...props}>
<path d="M12.5 8c-2.65 0-5.05.99-6.9 2.6L2 7v9h9l-3.62-3.62c1.39-1.16 3.16-1.88 5.12-1.88 3.54 0 6.55 2.31 7.6 5.5l2.37-.78C21.08 11.03 17.15 8 12.5 8z"/>
</SvgIcon>
);
ContentUndo.displayName = 'ContentUndo';
ContentUndo.muiName = 'SvgIcon';
export default ContentUndo;
|
Screens/Settings/Lists.js
|
Datasilk/Dedicate
|
import React from 'react';
import { View, StyleSheet, BackHandler, Alert } from 'react-native';
import Text from 'text/Text';
import Body from 'ui/Body';
import DbLists from 'db/DbLists';
import ListPicker from 'fields/ListPicker';
import Textbox from 'fields/Textbox';
import Button from 'buttons/Button';
export default class ListsScreen extends React.Component {
constructor(props){
super(props);
this.state = {
lists:[],
listsList:null,
newlist:'',
refresh:1
}
//bind events
this.hardwareBackPress = this.hardwareBackPress.bind(this);
this.loadToolbar = this.loadToolbar.bind(this);
this.loadContent = this.loadContent.bind(this);
this.loadLists = this.loadLists.bind(this);
this.onPressAddList = this.onPressAddList.bind(this);
this.onChangeNewListNameText = this.onChangeNewListNameText.bind(this);
this.onPressCreateNewList = this.onPressCreateNewList.bind(this);
this.onUpdateListState = this.onUpdateListState.bind(this);
this.onAddListItem = this.onAddListItem.bind(this);
this.removedList = this.removedList.bind(this);
}
componentWillMount() {
BackHandler.addEventListener('hardwareBackPress', this.hardwareBackPress);
this.loadToolbar();
this.loadContent();
}
componentWillUnmount(){
BackHandler.removeEventListener('hardwareBackPress', this.hardwareBackPress);
}
hardwareBackPress() {
global.navigate(this, 'Settings');
return true;
}
loadContent(){
this.loadLists();
}
// Load Toolbar ////////////////////////////////////////////////////////////////////////////////////////////////////
loadToolbar(){
global.updateToolbar({
...this.props,
screen:'Lists',
buttonAdd:true,
buttonRecord:false,
bottomFade:true,
hasTasks:false,
hasRecords:false,
footerMessage: '',
onAdd:this.onPressAddList
});
}
// Get Lists ////////////////////////////////////////////////////////////////////////////////////////////////////
loadLists(){
const dbLists = new DbLists();
const lists = dbLists.GetLists();
this.setState({lists:lists, listsList:lists.map(list => {
return (
<ListPicker key={list.id}
name={list.name}
selectedText={list.name}
listId={list.id}
editable={true}
view="list"
refresh={this.state.refresh}
onUpdateListState={(state) => this.onUpdateListState(list.id, state)}
onAddListItem={this.onAddListItem}
onRemoveList={this.removedList}
></ListPicker>
);
})});
}
//Add List ////////////////////////////////////////////////////////////////////////////////////////////////////
onPressAddList(){
global.Modal.setContent('Create New List', (
<View style={[this.styles.modalContainer]}>
<Text style={this.styles.fieldTitle}>List Name</Text>
<Textbox
defaultValue={this.state.newlist}
style={this.styles.inputField}
placeholder="My List"
returnKeyType={'done'}
onChangeText={this.onChangeNewListNameText}
/>
<View style={this.styles.createNewListButton}>
<Button text="Create" onPress={this.onPressCreateNewList}/>
</View>
</View>
));
global.Modal.show();
}
onChangeNewListNameText(value){
this.setState({newlist:value});
}
onPressCreateNewList(){
const dbLists = new DbLists();
dbLists.CreateList(this.state.newlist);
this.setState({newlist:''}, () => {
this.loadLists();
global.Modal.hide();
});
}
// Update List Item ///////////////////////////////////////////////////////////////////////////////////////////////
onUpdateListState(listId, state){
const dbLists = new DbLists();
dbLists.UpdateListState(listId, state);
}
onAddListItem(){
this.setState({refresh:this.state.refresh+1}, () => {
this.loadLists();
})
}
// Removed List ////////////////////////////////////////////////////////////////////////////////////////////////////
removedList(id){
this.setState({lists:[], refresh:this.state.refresh+1}, () => {
this.loadLists();
});
}
render() {
return (
<Body {...this.props} style={this.styles.body} title="Lists" backButton={this.hardwareBackPress}>
<View style={this.styles.container}>
{this.state.lists.length > 0 ? this.state.listsList :
<Text style={this.styles.nolists}>You haven't created any lists yet</Text>
}
</View>
</Body>
)
}
styles = StyleSheet.create({
body:{position:'absolute', top:0, bottom:0, left:0, right:0},
nolists:{textAlign:'center', width:'100%', paddingTop:50},
container:{paddingBottom:AppStyles.paddingFooterSpace},
inputField: {fontSize:AppStyles.titleFontSize},
modalContainer:{backgroundColor:AppStyles.backgroundColor, minWidth:'50%', padding:AppStyles.paddingLarge},
createNewListButton:{marginTop:AppStyles.padding, alignSelf:'center'},
fieldTitle: {fontSize:AppStyles.fieldFontSize, fontWeight:'bold'},
});
}
|
examples/js/column-filter/select-filter.js
|
dana2208/react-bootstrap-table
|
/* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
const qualityType = {
0: 'good',
1: 'bad',
2: 'unknown'
};
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
quality: i % 3
});
}
}
addProducts(5);
function enumFormatter(cell, row, enumObject) {
return enumObject[cell];
}
export default class SelectFilter extends React.Component {
render() {
return (
<BootstrapTable data={ products }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='quality' dataFormat={ enumFormatter } formatExtraData={ qualityType }
filter={ { type: 'SelectFilter', options: qualityType } }>Product Quality</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/svg-icons/image/linked-camera.js
|
jacklam718/react-svg-iconx
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLinkedCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="14" r="3.2"/><path d="M16 3.33c2.58 0 4.67 2.09 4.67 4.67H22c0-3.31-2.69-6-6-6v1.33M16 6c1.11 0 2 .89 2 2h1.33c0-1.84-1.49-3.33-3.33-3.33V6"/><path d="M17 9c0-1.11-.89-2-2-2V4H9L7.17 6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9h-5zm-5 10c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImageLinkedCamera = pure(ImageLinkedCamera);
ImageLinkedCamera.displayName = 'ImageLinkedCamera';
ImageLinkedCamera.muiName = 'SvgIcon';
export default ImageLinkedCamera;
|
src/components/Html.js
|
LeraSavchenko/Maysternia
|
import React from 'react';
import PropTypes from 'prop-types';
import serialize from 'serialize-javascript';
import config from '../config';
class Html extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
styles: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
cssText: PropTypes.string.isRequired,
}).isRequired),
scripts: PropTypes.arrayOf(PropTypes.string.isRequired),
app: PropTypes.object.isRequired,
children: PropTypes.string.isRequired,
};
static defaultProps = {
styles: [],
scripts: [],
};
render() {
const { title, description, styles, scripts, app, children } = this.props;
return (
<html className="no-js" lang={app.lang}>
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<title>{title}</title>
<meta name="description" content={description} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="apple-touch-icon" href="apple-touch-icon.png" />
<link href="https://fonts.googleapis.com/css?family=Lora|Open+Sans|Roboto" rel="stylesheet" />
{styles.map(style => (
<style
key={style.id}
id={style.id}
dangerouslySetInnerHTML={{ __html: style.cssText }}
/>
))}
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{ __html: children }} />
<script dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }} />
{scripts.map(script => <script key={script} src={script} />)}
{config.analytics.googleTrackingId &&
<script
dangerouslySetInnerHTML={{ __html:
'window.ga=function(){ga.q.push(arguments)};ga.q=[];ga.l=+new Date;' +
`ga('create','${config.analytics.googleTrackingId}','auto');ga('send','pageview')` }}
/>
}
{config.analytics.googleTrackingId &&
<script src="https://www.google-analytics.com/analytics.js" async defer />
}
</body>
</html>
);
}
}
export default Html;
|
examples/04 Sortable/Simple/index.js
|
globexdesigns/react-dnd
|
import React, { Component } from 'react';
import Container from './Container';
export default class SortableSimple extends Component {
render() {
return (
<div>
<p>
<b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/04%20Sortable/Simple'>Browse the Source</a></b>
</p>
<p>
It is easy to implement a sortable interface with React DnD. Just make the same component both a drag source and a drop target, and reorder the data in the <code>hover</code> handler.
</p>
<Container />
</div>
);
}
}
|
src/encoded/static/components/donor.js
|
T2DREAM/t2dream-portal
|
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import url from 'url';
import { Panel, PanelBody, PanelHeading } from '../libs/bootstrap/panel';
import { auditDecor } from './audit';
import { ExperimentTable } from './dataset';
import { DbxrefList } from './dbxref';
import { DocumentsPanel, DocumentsSubpanels } from './doc';
import { GeneticModificationSummary } from './genetic_modification';
import * as globals from './globals';
import { RelatedItems } from './item';
import { Breadcrumbs } from './navigation';
import { requestObjects, AlternateAccession } from './objectutils';
import pubReferenceList from './reference';
import { PickerActions } from './search';
import { SortTablePanel, SortTable } from './sorttable';
import StatusLabel from './statuslabel';
import { BiosampleTable } from './typeutils';
const HumanDonor = (props) => {
const { context, biosample } = props;
const references = pubReferenceList(context.references);
// Render tags badges
let tagBadges;
if (context.internal_tags && context.internal_tags.length) {
tagBadges = context.internal_tags.map(tag => <img key={tag} src={`/static/img/tag-${tag}.png`} alt={`${tag} tag`} />);
}
return (
<div>
<Panel>
<PanelHeading>
<h4>Donor information</h4>
</PanelHeading>
<PanelBody>
<dl className="key-value">
<div data-test="accession">
<dt>Accession</dt>
<dd>{biosample ? <a href={context['@id']}>{context.accession}</a> : context.accession}</dd>
</div>
{context.aliases.length ?
<div data-test="aliases">
<dt>Aliases</dt>
<dd>{context.aliases.join(', ')}</dd>
</div>
: null}
{context.external_ids && context.external_ids.length ?
<div data-test="externalid">
<dt>Donor external identifiers</dt>
<dd><DbxrefList context={context} dbxrefs={context.external_ids} /></dd>
</div>
: null}
{context.organism.scientific_name ?
<div data-test="species">
<dt>Species</dt>
<dd className="sentence-case"><em>{context.organism.scientific_name}</em></dd>
</div>
: null}
{context.life_stage ?
<div data-test="life-stage">
<dt>Life stage</dt>
<dd className="sentence-case">{context.life_stage}</dd>
</div>
: null}
{context.age ?
<div data-test="age">
<dt>Age</dt>
<dd className="sentence-case">{context.age}{context.age_units ? ` ${context.age_units}` : null}</dd>
</div>
: null}
{context.sex ?
<div data-test="sex">
<dt>Sex</dt>
<dd className="sentence-case">{context.sex}</dd>
</div>
: null}
{context.health_status ?
<div data-test="health-status">
<dt>Health status</dt>
<dd className="sentence-case">{context.health_status}</dd>
</div>
: null}
{context.ethnicity ?
<div data-test="ethnicity">
<dt>Ethnicity</dt>
<dd className="sentence-case">{context.ethnicity}</dd>
</div>
: null}
{context.dbxrefs && context.dbxrefs.length ?
<div data-test="external-resources">
<dt>External resources</dt>
<dd><DbxrefList context={context} dbxrefs={context.dbxrefs} /></dd>
</div>
: null}
{references ?
<div data-test="references">
<dt>References</dt>
<dd>{references}</dd>
</div>
: null}
{context.submitter_comment ?
<div data-test="submittercomment">
<dt>Submitter comment</dt>
<dd>{context.submitter_comment}</dd>
</div>
: null}
{tagBadges ?
<div className="tag-badges" data-test="tags">
<dt>Tags</dt>
<dd>{tagBadges}</dd>
</div>
: null}
</dl>
</PanelBody>
</Panel>
</div>
);
};
HumanDonor.propTypes = {
context: PropTypes.object.isRequired, // Donor being displayed
biosample: PropTypes.object, // Biosample this donor is associated with
};
HumanDonor.defaultProps = {
biosample: null,
};
globals.panelViews.register(HumanDonor, 'HumanDonor');
/**
* Display a table of donors. Mostly useful for arrays of donors related to the one being
* displayed.
*/
const donorTableColumns = {
accession: {
title: 'Accession',
display: donor => <a href={donor['@id']}>{donor.accession}</a>,
},
age_display: {
title: 'Age',
display: (donor) => {
if (donor.age) {
return (
<span>
{donor.age}
{donor.age_units ? ` ${donor.age_units}` : null}
</span>
);
}
return null;
},
},
health_status: { title: 'Health status' },
life_stage: { title: 'Life stage' },
sex: { title: 'Sex' },
status: {
title: 'Status',
display: donor => <div className="characterization-meta-data"><StatusLabel status={donor.status} /></div>,
},
};
const DonorTable = (props) => {
const { title, donors } = props;
return (
<SortTablePanel title={title}>
<SortTable list={donors} columns={donorTableColumns} />
</SortTablePanel>
);
};
DonorTable.propTypes = {
title: PropTypes.string, // Title to display in the title bar of the donor table
donors: PropTypes.array, // Array of donors to display in the table
};
DonorTable.defaultProps = {
title: '',
donors: '',
};
const MouseDonor = (props) => {
const { context, biosample } = props;
let donorUrlDomain;
// Get the domain name of the donor URL.
if (biosample && biosample.donor && biosample.donor.url) {
const donorUrl = url.parse(biosample.donor.url);
donorUrlDomain = donorUrl.hostname || '';
}
// Render tags badges.
let tagBadges;
if (context.internal_tags && context.internal_tags.length) {
tagBadges = context.internal_tags.map(tag => <img key={tag} src={`/static/img/tag-${tag}.png`} alt={`${tag} tag`} />);
}
return (
<div>
<Panel>
<PanelHeading>
<h4>Strain information</h4>
</PanelHeading>
<PanelBody>
<dl className="key-value">
<div data-test="accession">
<dt>Accession</dt>
<dd>{biosample ? <a href={context['@id']}>{context.accession}</a> : context.accession}</dd>
</div>
{context.aliases.length ?
<div data-test="aliases">
<dt>Aliases</dt>
<dd>{context.aliases.join(', ')}</dd>
</div>
: null}
{context.external_ids && context.external_ids.length ?
<div data-test="externalid">
<dt>Donor external identifiers</dt>
<dd><DbxrefList context={context} dbxrefs={context.external_ids} /></dd>
</div>
: null}
{context.organism.scientific_name ?
<div data-test="organism">
<dt>Species</dt>
<dd className="sentence-case"><em>{context.organism.scientific_name}</em></dd>
</div>
: null}
{context.genotype ?
<div data-test="genotype">
<dt>Genotype</dt>
<dd>{context.genotype}</dd>
</div>
: null}
{context.mutated_gene && biosample && biosample.donor && biosample.donor.mutated_gene && biosample.donor.mutated_gene.label ?
<div data-test="mutatedgene">
<dt>Mutated gene</dt>
<dd><a href={context.mutated_gene}>{biosample.donor.mutated_gene.label}</a></dd>
</div>
: null}
{biosample && biosample.sex ?
<div data-test="sex">
<dt>Sex</dt>
<dd className="sentence-case">{biosample.sex}</dd>
</div>
: null}
{biosample && biosample.health_status ?
<div data-test="health-status">
<dt>Health status</dt>
<dd className="sentence-case">{biosample.health_status}</dd>
</div>
: null}
{donorUrlDomain ?
<div data-test="mutatedgene">
<dt>Strain reference</dt>
<dd><a href={biosample.donor.url}>{donorUrlDomain}</a></dd>
</div>
: null}
{context.strain_background ?
<div data-test="strain-background">
<dt>Strain background</dt>
<dd className="sentence-case">{context.strain_background}</dd>
</div>
: null}
{context.strain_name ?
<div data-test="strain-name">
<dt>Strain name</dt>
<dd>{context.strain_name}</dd>
</div>
: null}
{context.dbxrefs && context.dbxrefs.length ?
<div data-test="external-resources">
<dt>External resources</dt>
<dd><DbxrefList context={context} dbxrefs={context.dbxrefs} /></dd>
</div>
: null}
{context.references && context.references.length ?
<div data-test="references">
<dt>References</dt>
<dd>{pubReferenceList(context.references)}</dd>
</div>
: null}
{tagBadges ?
<div className="tag-badges" data-test="tags">
<dt>Tags</dt>
<dd>{tagBadges}</dd>
</div>
: null}
{context.submitter_comment ?
<div data-test="submittercomment">
<dt>Submitter comment</dt>
<dd>{context.submitter_comment}</dd>
</div>
: null}
</dl>
{biosample && biosample.donor.characterizations && biosample.donor.characterizations.length ?
<div>
<hr />
<h4>Characterizations</h4>
<PanelBody addClasses="panel-body-doc-interior">
<DocumentsSubpanels documentSpec={{ documents: biosample.donor.characterizations }} />
</PanelBody>
</div>
: null}
</PanelBody>
</Panel>
</div>
);
};
MouseDonor.propTypes = {
context: PropTypes.object, // Mouse donor object being rendered
biosample: PropTypes.object, // Biosample object this donor belongs to
};
globals.panelViews.register(MouseDonor, 'MouseDonor');
const FlyWormDonor = (props) => {
const { context, biosample } = props;
let donorUrlDomain;
// Render tags badges.
let tagBadges;
if (context.internal_tags && context.internal_tags.length) {
tagBadges = context.internal_tags.map(tag => <img key={tag} src={`/static/img/tag-${tag}.png`} alt={`${tag} tag`} />);
}
return (
<div>
<Panel>
<PanelHeading>
<h4>Strain information</h4>
</PanelHeading>
<PanelBody>
<dl className="key-value">
<div data-test="accession">
<dt>Accession</dt>
<dd>{biosample ? <a href={context['@id']}>{context.accession}</a> : context.accession}</dd>
</div>
{context.aliases.length ?
<div data-test="aliases">
<dt>Aliases</dt>
<dd>{context.aliases.join(', ')}</dd>
</div>
: null}
{context.external_ids && context.external_ids.length ?
<div data-test="externalid">
<dt>Donor external identifiers</dt>
<dd><DbxrefList context={context} dbxrefs={context.external_ids} /></dd>
</div>
: null}
{context.organism.scientific_name ?
<div data-test="species">
<dt>Species</dt>
<dd className="sentence-case"><em>{context.organism.scientific_name}</em></dd>
</div>
: null}
{context.genotype ?
<div data-test="genotype">
<dt>Genotype</dt>
<dd>{context.genotype}</dd>
</div>
: null}
{context.mutated_gene && biosample && biosample.donor && biosample.donor.mutated_gene && biosample.donor.mutated_gene.label ?
<div data-test="mutatedgene">
<dt>Mutated gene</dt>
<dd><a href={context.mutated_gene['@id']}>{biosample.donor.mutated_gene.label}</a></dd>
</div>
: null}
{biosample && biosample.sex ?
<div data-test="sex">
<dt>Sex</dt>
<dd className="sentence-case">{biosample.sex}</dd>
</div>
: null}
{biosample && biosample.health_status ?
<div data-test="health-status">
<dt>Health status</dt>
<dd className="sentence-case">{biosample.health_status}</dd>
</div>
: null}
{donorUrlDomain ?
<div data-test="mutatedgene">
<dt>Strain reference</dt>
<dd><a href={biosample.donor.url}>{donorUrlDomain}</a></dd>
</div>
: null}
{context.strain_background ?
<div data-test="strain-background">
<dt>Strain background</dt>
<dd className="sentence-case">{context.strain_background}</dd>
</div>
: null}
{context.strain_name ?
<div data-test="strain-name">
<dt>Strain name</dt>
<dd>{context.strain_name}</dd>
</div>
: null}
{context.dbxrefs && context.dbxrefs.length ?
<div data-test="external-resources">
<dt>External resources</dt>
<dd><DbxrefList context={context} dbxrefs={context.dbxrefs} /></dd>
</div>
: null}
{context.submitter_comment ?
<div data-test="submittercomment">
<dt>Submitter comment</dt>
<dd>{context.submitter_comment}</dd>
</div>
: null}
{tagBadges ?
<div className="tag-badges" data-test="tags">
<dt>Tags</dt>
<dd>{tagBadges}</dd>
</div>
: null}
</dl>
</PanelBody>
</Panel>
</div>
);
};
FlyWormDonor.propTypes = {
context: PropTypes.object, // Mouse donor object being rendered
biosample: PropTypes.object, // Biosample object this donor belongs to
};
globals.panelViews.register(FlyWormDonor, 'FlyDonor');
globals.panelViews.register(FlyWormDonor, 'WormDonor');
// This component activates for any donors that aren't any of the above registered types.
class Donor extends React.Component {
constructor() {
super();
this.state = {
parentDonors: [],
childDOnors: [],
};
// Bind `this` to non-React methods.
this.requestRelations = this.requestRelations.bind(this);
}
componentDidMount() {
// Humans need to do a couple requests to get the parents and children of the donor.
if (this.props.context['@type'][0] === 'HumanDonor') {
// Now that the component has mounted, we can do a GET request of the donor's children and
// parents so we can display them once the results come back.
this.requestRelations();
// In case the logged-in state changes, we have to keep track of the old logged-in state.
this.loggedIn = !!(this.context.session && this.context.session['auth.userid']);
}
}
componentWillReceiveProps() {
// Humans need to do a couple requests to get the parents and children of the donor.
if (this.props.context['@type'][0] === 'HumanDonor') {
// If the logged-in state has changed since the last time we rendered, request files again
// in case logging in changes the list of dependent files.
const currLoggedIn = !!(this.context.session && this.context.session['auth.userid']);
if (this.loggedIn !== currLoggedIn) {
this.requestRelations();
this.loggedIn = currLoggedIn;
}
}
}
requestRelations() {
// donor.parents and donor.children aren't embedded in the human donor object -- they're
// just arrays of human_donor @ids. This function does a database search to retrieve all
// donor.parent and donor.children objects.
const donor = this.props.context;
const parentAtids = donor.parents && donor.parents.length ? donor.parents : [];
const childrenAtids = donor.children && donor.children.length ? donor.children : [];
// Do both the donor.parent and donor.children as a combined search, and sort the results
// out after they get retrieved.
const atIds = parentAtids.concat(childrenAtids);
// atIds now has an array of human_donor parents and children @ids. Send a GET request to
// perform a search.
if (atIds.length) {
requestObjects(atIds, '/search/?type=HumanDonor&limit=all&status!=deleted&status!=revoked&status!=replaced').then((parentChildDonors) => {
// Got search results with all human_donor parents and children as one search
// result array. Sort them into parents and children based on their locations in
// the donor.
const relations = _(parentChildDonors).groupBy((parentChildDonor) => {
// Any results that have a matching @id in the array of parents in the donor
// get put into the 'parents' key in the `relations` object as an array. Any
// with a matching @id in the array of children get put into the 'children' key
// as an array.
if (parentAtids.indexOf(parentChildDonor['@id']) !== -1) {
return 'parents';
}
if (childrenAtids.indexOf(parentChildDonor['@id']) !== -1) {
return 'children';
}
// This should *never* happen.
return 'unknown';
});
// Rerender the page with the parents and children tables.
this.setState({
parentDonors: relations.parents || [],
childDonors: relations.children || [],
});
});
}
}
render() {
const { context } = this.props;
const itemClass = globals.itemClass(context, 'view-item');
const PanelView = globals.panelViews.lookup(context);
let characterizationDocuments = [];
let donorDocuments = [];
// Collect the characterization documents.
if (context.characterizations && context.characterizations.length) {
characterizationDocuments = context.characterizations;
}
// Collect the donor documents.
if (context.documents && context.documents.length) {
donorDocuments = context.documents;
}
// Combine characterization and donor documents.
const combinedDocuments = [].concat(characterizationDocuments, donorDocuments);
// Set up breadcrumbs.
const crumbs = [
{ id: 'Donors' },
{ id: <i>{context.organism.scientific_name}</i> },
];
return (
<div className={itemClass}>
<header className="row">
<div className="col-sm-12">
<Breadcrumbs crumbs={crumbs} />
<h2>{context.accession}</h2>
<AlternateAccession altAcc={context.alternate_accessions} />
<div className="status-line">
<div className="characterization-status-labels">
<StatusLabel title="Status" status={context.status} />
</div>
</div>
</div>
</header>
<PanelView key={context.uuid} {...this.props} />
{context.genetic_modifications && context.genetic_modifications.length ?
<GeneticModificationSummary geneticModifications={context.genetic_modifications} />
: null}
<RelatedItems
title={`Biosamples from this ${context.organism.name === 'human' ? 'donor' : 'strain'}`}
url={`/search/?type=Biosample&donor.uuid=${context.uuid}`}
Component={BiosampleTable}
/>
{context['@type'][0] === 'HumanDonor' && this.state.childDonors && this.state.childDonors.length ?
<DonorTable title="Children of this donor" donors={this.state.childDonors} />
: null}
{context['@type'][0] === 'HumanDonor' && this.state.parentDonors && this.state.parentDonors.length ?
<DonorTable title="Parents of this donor" donors={this.state.parentDonors} />
: null}
<RelatedItems
title={`Experiments from this ${context.organism.name === 'human' ? 'donor' : 'strain'}`}
url={`/search/?type=Experiment&replicates.library.biosample.donor.uuid=${context.uuid}`}
Component={ExperimentTable}
/>
{combinedDocuments.length ?
<DocumentsPanel documentSpecs={[{ documents: combinedDocuments }]} />
: null}
</div>
);
}
}
Donor.propTypes = {
context: PropTypes.object, // Donor being rendered
};
Donor.contextTypes = {
session: PropTypes.object, // Login information
};
globals.contentViews.register(Donor, 'Donor');
const DonorListingComponent = (props, reactContext) => {
const { organismTitle } = props;
const result = props.context;
// Make array of extra info for display in the search results link with a join. The `Boolean`
// constructor in the filter cleverly filters out falsy values from the array. See:
// https://stackoverflow.com/questions/32906887/remove-all-falsy-values-from-an-array#answer-32906951
const details = [
result.strain_name,
result.strain_background ? (result.strain_background !== 'unknown' ? result.strain_background : 'unknown strain background') : null,
result.sex ? (result.sex !== 'unknown' ? result.sex : 'unknown sex') : null,
result.life_stage ? (result.life_stage !== 'unknown' ? result.life_stage : 'unknown life stage') : null,
result.age ? (result.age !== 'unknown' ? `${result.age} ${result.age_units}` : 'unknown age') : null,
].filter(Boolean);
return (
<li>
<div className="clearfix">
<PickerActions {...props} />
<div className="pull-right search-meta">
<p className="type meta-title">{organismTitle}</p>
<p className="type">{` ${result.accession}`}</p>
<p className="type meta-status">{` ${result.status}`}</p>
{props.auditIndicators(result.audit, result['@id'], { session: reactContext.session, search: true })}
</div>
<div className="accession">
<a href={result['@id']}>
<i>{result.organism.scientific_name}</i>
{details.length ? ` (${details.join(', ')})` : null}
</a>
</div>
<div className="data-row">
{result.lab ? <div><strong>Lab: </strong>{result.lab.title}</div> : null}
{result.external_ids && result.external_ids.length ?
<div>
<strong>External resources: </strong>
<DbxrefList context={result} dbxrefs={result.external_ids} />
</div>
: null}
</div>
</div>
{props.auditDetail(result.audit, result['@id'], { session: reactContext.session, except: result['@id'], forcedEditLink: true })}
</li>
);
};
DonorListingComponent.propTypes = {
context: PropTypes.object.isRequired, // Search results object
organismTitle: PropTypes.string.isRequired, // Title to display on the right for each kind of organism
auditDetail: PropTypes.func.isRequired, // Audit HOC function to show audit details
auditIndicators: PropTypes.func.isRequired, // Audit HOC function to display audit indicators
};
DonorListingComponent.contextTypes = {
session: PropTypes.object, // Login information from <App>
};
const DonorListing = auditDecor(DonorListingComponent);
const HumanListing = props => (
<DonorListing {...props} organismTitle="Human donor" />
);
const MouseListing = props => (
<DonorListing {...props} organismTitle="Mouse donor" />
);
const WormListing = props => (
<DonorListing {...props} organismTitle="Worm donor" />
);
const FlyListing = props => (
<DonorListing {...props} organismTitle="Fly donor" />
);
globals.listingViews.register(HumanListing, 'HumanDonor');
globals.listingViews.register(MouseListing, 'MouseDonor');
globals.listingViews.register(WormListing, 'WormDonor');
globals.listingViews.register(FlyListing, 'FlyDonor');
|
app/chaos/chaos.js
|
enotsimon/home
|
import ReactDOM from 'react-dom'
import React from 'react'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import Util from 'common/util'
import Agent from 'chaos/agent'
import App from 'chaos/components/app'
import root_reducer from 'chaos/reducers'
import * as actions from 'chaos/actions'
class Chaos {
constructor() {
// constants
this.x_size = 20
this.y_size = 20
this.symbols = [
'✕', '✖', '✙', '✚', '✛', '✜', '✠', '✡', '✢', '✣', '✤', '✥', '✦', '✧', '✩', '✪', '✫', '✬', '✭',
'✮', '✯', '✰', '✱', '✲', '✳', '✴', '✵', '✶', '✷', '✸', '✹', '✺', '✻', '✽', '✾', '✿', '❀', '❁',
'❂', '❃', '❄', '❅', '❆', '❇', '❈', '❉', '❊', '❋', '❖'
]
this.symbol_min_weight = 8
this.symbol_max_weight = 16
this.symbol_classes_min_length = 15
this.symbol_classes_max_length = 20
this.symbol_classes_count = 2
this.init()
}
init() {
let symbols_arr = []
this.symbols.forEach(symbol => {
const symbol_weight = Util.rand(this.symbol_min_weight, this.symbol_max_weight)
symbols_arr = symbols_arr.concat((new Array(symbol_weight)).fill(symbol))
})
this.symbol_classes = Array.from(Array(this.symbol_classes_count), () => {
const length = Util.rand(this.symbol_classes_min_length, this.symbol_classes_max_length)
// should symbol classes contain only uniq elements or not?
return Array.from(Array(length), () => Util.rand_element(this.symbols))
})
this.data = Array.from(Array(this.y_size).keys(), y => {
return Array.from(Array(this.x_size).keys(), x => {
return this.init_agent(x, y)
})
})
this.store = createStore(root_reducer)
this.tick_delay = 2000
}
run(count) {
if (count < 0) {
return
}
this.flush_exchange_flags()
this.advance_symbol_classes()
this.exchange_symbols()
this.store.dispatch(actions.tick())
// eslint-disable-next-line
setTimeout(() => this.run(--count), this.tick_delay)
}
//
// private
//
init_agent(x, y) {
const agent = new Agent(x, y)
this.symbol_classes.forEach((symbol_class, i) => {
agent.add_symbol_class(`sc${i}`, symbol_class, Util.rand(0, symbol_class.length))
})
return agent
}
for_all_agents(func) {
this.data.forEach(line => {
line.forEach(agent => {
func(agent)
})
})
}
advance_symbol_classes() {
this.for_all_agents(agent => agent.advance_symbol_classes())
this.store.dispatch(actions.advance_symbols_complete())
}
get_neighbors(agent) {
// von neimann
const base = [[agent.x - 1, agent.y], [agent.x + 1, agent.y], [agent.x, agent.y - 1], [agent.x, agent.y + 1]]
const ret = []
base.forEach(([x, y]) => {
if (this.data[y] && this.data[y][x]) {
ret.push(this.data[y][x])
}
})
return ret
}
flush_exchange_flags() {
this.for_all_agents(agent => {
agent.for_all_symbol_classes((symbols, prop) => {
agent.set_exchange_flag(prop, false)
})
})
}
//
// hellish omg part
//
exchange_symbols() {
this.for_all_agents(agent => {
agent.for_all_symbol_classes((symbols, prop) => {
// valuable symbol on top, we aint gonna give it away
if (!agent.are_you_gonna_exchange(prop)) {
return
}
// all our neighbors our potential exchange partners
let partners = this.get_neighbors(agent)
// its quite stupid to exchange symbol to just the same symbol
partners = partners.filter(p => p.get_current_symbol(prop) !== agent.get_current_symbol(prop))
// when we gonna know that they are willing to exchange something
partners = partners.filter(p => p.are_you_gonna_exchange(prop))
if (!partners.length) {
return
}
// first of all we gonna exchange some trash on some sweety
// but if we failed, let us exchange our trash on even some other trash
const first_class_partners = partners.filter(p => agent.is_valuable_symbol(p.get_current_symbol(prop), prop))
if (first_class_partners.length) {
partners = first_class_partners
}
// finally we are to choose one partner from all possible
const partner = Util.rand_element(partners)
// and finally -- technical details
const our = agent.get_current_symbol(prop)
const their = partner.get_current_symbol(prop)
agent.exchange_symbol(prop, their)
partner.exchange_symbol(prop, our)
// console.log('exchange done', prop, our, 'to', their, agent, partner);
})
})
this.store.dispatch(actions.exchange_symbols_complete())
}
}
const chaos = new Chaos()
export default chaos
chaos.run(5)
document.addEventListener('DOMContentLoaded', () => {
ReactDOM.render(
<Provider store={chaos.store}>
<App />
</Provider>,
document.querySelector('#app')
)
})
|
geonode/contrib/monitoring/frontend/src/pages/software-performance/index.js
|
timlinux/geonode
|
import React from 'react';
import Header from '../../components/organisms/header';
import GeonodeAnalytics from '../../components/organisms/geonode-analytics';
import GeonodeLayersAnalytics from '../../components/organisms/geonode-layers-analytics';
import WSAnalytics from '../../components/organisms/ws-analytics';
import WSLayersAnalytics from '../../components/organisms/ws-layers-analytics';
import styles from './styles';
class SWPerf extends React.Component {
render() {
return (
<div style={styles.root}>
<Header back="/" />
<div style={styles.analytics}>
<GeonodeAnalytics />
<WSAnalytics />
</div>
<div style={styles.analytics}>
<GeonodeLayersAnalytics />
<WSLayersAnalytics />
</div>
</div>
);
}
}
export default SWPerf;
|
www/pages/components/home/ValueProps2.js
|
andrewlinfoot/keystone
|
import React, { Component } from 'react';
import Container from '../../../components/Container';
import { Col, Row } from '../../../components/Grid';
import theme from '../../../theme';
import { compose } from 'glamor';
import { EntypoTools, EntypoCloud, EntypoRocket } from 'react-entypo';
import { rhythm } from 'utils/typography';
const ValueProp = ({ icon, text, title, text2, marginTop }) => {
return (
<div {...compose(styles.base, { marginTop })}>
<i {...compose(styles.icon)}>{icon}</i>
<div {...compose(styles.content)}>
<h3 {...compose(styles.title)}>{title}</h3>
<p {...compose(styles.text)}>{text}</p>
{text2
? <p {...compose(styles.text)}>{text2}</p>
: null}
</div>
</div>
);
};
ValueProp.defaultProps = {
marginTop: '4em',
};
export default class ValueProps extends Component {
render () {
return (
<div className={compose(styles.wrapper)}>
<EntypoCloud style={{ width: '200px', height: '170px', color: theme.color.blue, marginTop: '-100px', position: 'absolute', right: '8%' }} />
<EntypoRocket style={{ width: '137px', height: '140px', color: theme.color.blue, marginTop: '-220px', position: 'absolute', left: '8%' }} />
<Container>
<div className={compose(styles.intro)}>
<h2 className={compose(styles.heading)}>What you build is up to you.</h2>
<p className={compose(styles.subheading)}>There are a lot of frameworks that make decisions for you, and many that take decisions away. Keystone doesn't do that. Use the features that suit you, and replace the ones that don't.</p>
<EntypoTools style={{ width: '90px', height: '90px' }} />
</div>
<Row small="1" medium="1/2" large="1/4">
<Col>
<ValueProp
title="Built on Express"
text="Keystone can configure Express for you, or you can take over and treat Keystone like any other Express middleware."
text2="You can also easily integrate it into an existing Express app."
marginTop="1em"
/>
</Col>
<Col>
<ValueProp
title="Powered by MongoDB"
text="Keystone uses Mongoose, the leading ODM for node.js and MongoDB, and gives you a single place for your schema, validation rules and logic."
text2="So anything you can build with MongoDB, you can build with Keystone."
marginTop="1em"
/>
</Col>
<Col>
<ValueProp
title="Lightweight and flexible"
text="Keystone is designed to be as light as you want - you can pick and choose the features you want to include."
text2="\nCreate your own routes, your own database schema, and use any template language you like."
marginTop="1em"
/>
</Col>
<Col>
<ValueProp
title="Extendable"
text="One of the greatest things about node.js is the vast number of quality packages available."
text2="Keystone is designed to let you use any of them, without losing the benefits it provides."
marginTop="1em"
/>
</Col>
</Row>
</Container>
</div>
);
}
};
const styles = {
wrapper: {
backgroundColor: theme.color.blue,
color: 'white',
paddingBottom: '5em',
},
intro: {
paddingBottom: rhythm(2),
paddingTop: rhythm(2),
textAlign: 'center',
},
heading: {
fontSize: '2.6em',
color: 'white',
},
subheading: {
paddingTop: '1em',
fontSize: '1.8em',
lineHeight: '1.2em',
paddingBottom: '1em',
},
base: {
display: 'flex',
},
content: {
flexGrow: 1,
},
icon: {
marginRight: '1em',
},
title: {
color: 'inherit',
fontWeight: '400',
marginTop: '0.2em',
},
text: {
paddingTop: '1em',
fontWeight: '300',
},
};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.