path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
---|---|---|
src/docs/examples/TextInputBEM/TextExample.js | choudlet/ps-react-choudlet | import React from 'react';
import TextInputBEM from 'ps-react/TextInputBEM';
/** Required TextBox with error */
export default class ExampleError extends React.Component {
render() {
return (
<TextInputBEM
htmlId="example-optional"
label="First Name"
name="firstname"
onChange={() => {}}
required
error="First name is required."
/>
)
}
} |
app/packs/src/components/AnalysisEditor.js | ComPlat/chemotion_ELN | import React from 'react';
import PropTypes from 'prop-types';
import { OverlayTrigger, Popover } from 'react-bootstrap';
import Delta from 'quill-delta';
import { formatAnalysisContent } from './utils/ElementUtils';
import TextTemplateStore from './stores/TextTemplateStore';
import TextTemplateActions from './actions/TextTemplateActions';
import DynamicToolbarEditor from './react_quill/DynamicToolbarEditor';
import ToolbarIcon from './react_quill/ToolbarIcon';
import BaseToolbar from './react_quill/BaseToolbar';
import TextTemplateToolbar from './text_template_toolbar/TextTemplateToolbar';
import ToolbarTemplateCreator from './text_template_toolbar/ToolbarTemplateCreator';
const toolbarOptions = [
'bold', 'italic', 'underline',
'header', 'script',
'list', 'bullet',
];
export default class AnalysisEditor extends React.Component {
constructor(props) {
super(props);
this.reactQuillRef = React.createRef();
const templateStore = TextTemplateStore.getState();
const { predefinedTemplateNames, fetchedPredefinedTemplates } = templateStore;
const fetchedTemplates = fetchedPredefinedTemplates && fetchedPredefinedTemplates.toJS();
this.state = {
fetchedNames: Object.keys(fetchedTemplates),
predefinedTemplateNames: predefinedTemplateNames && predefinedTemplateNames.toJS(),
fetchedPredefinedTemplates,
updateTemplate: false
};
this.fetchPredefinedTemplates = this.fetchPredefinedTemplates.bind(this);
this.onChangeTemplateStore = this.onChangeTemplateStore.bind(this);
this.onChangeContent = this.onChangeContent.bind(this);
this.autoFormatContent = this.autoFormatContent.bind(this);
this.applyTemplate = this.applyTemplate.bind(this);
this.updateTextTemplates = this.updateTextTemplates.bind(this);
this.quillOnChange = this.quillOnChange.bind(this);
}
componentDidMount() {
TextTemplateStore.listen(this.onChangeTemplateStore);
TextTemplateActions.fetchPredefinedTemplateNames();
const { template } = this.props;
const namesToFetch = Object.values(template).flat();
this.fetchPredefinedTemplates(namesToFetch);
}
componentDidUpdate(prevProps) {
const { template } = this.props;
const namesToFetch = Object.values(template).flat();
if (!this.state.updateTemplate && Object.keys(template).length !== 0) {
// this.fetchPredefinedTemplates(namesToFetch);
TextTemplateActions.fetchPredefinedTemplateByNames(namesToFetch);
// eslint-disable-next-line react/no-did-update-set-state
this.setState({
updateTemplate: true
});
} else if (this.props.template !== prevProps.template && this.state.updateTemplate) {
const prevnamesToFetch = Object.values(prevProps.template).flat();
if (prevnamesToFetch.length !== namesToFetch.length) {
// this.fetchPredefinedTemplates(namesToFetch);
TextTemplateActions.fetchPredefinedTemplateByNames(namesToFetch);
}
}
}
componentWillUnmount() {
TextTemplateStore.unlisten(this.onChangeTemplateStore);
}
onChangeTemplateStore(state) {
const { predefinedTemplateNames, fetchedPredefinedTemplates } = state;
const { fetchedNames } = this.state;
const fetchedTemplates = (fetchedPredefinedTemplates && fetchedPredefinedTemplates.toJS()) || Map();
const templateStoreFetched = Object.keys(fetchedTemplates);
const fetched = [...new Set(fetchedNames.concat(templateStoreFetched))];
this.setState({
fetchedNames: fetched,
predefinedTemplateNames: predefinedTemplateNames && predefinedTemplateNames.toJS(),
fetchedPredefinedTemplates: fetchedTemplates
});
}
onChangeContent(quillEditor) {
const { onChangeContent } = this.props;
if (onChangeContent) {
onChangeContent(quillEditor.getContents());
}
}
fetchPredefinedTemplates(names) {
if (!names || names.length === 0) return;
const { fetchedNames } = this.state;
const namesToFetch = names.filter(n => !fetchedNames.includes(n));
if (namesToFetch.length === 0) return;
const fetched = [...new Set(fetchedNames.concat(names))];
this.setState({ fetchedNames: fetched }, () => {
TextTemplateActions.fetchPredefinedTemplateByNames(namesToFetch);
});
}
autoFormatContent() {
if (this.reactQuillRef.current == null) {
return;
}
const { analysis } = this.props;
let value = analysis.extended_metadata.content || {};
value = formatAnalysisContent(analysis);
const quill = this.reactQuillRef.current.getEditor();
quill.setContents(value);
this.onChangeContent(quill);
}
quillOnChange(content, delta, source, editor) {
if (this.reactQuillRef.current == null) {
return;
}
this.onChangeContent(editor);
}
applyTemplate(macro) {
const check = ('ops' in macro) && Array.isArray(macro.ops);
if (!check) return;
if (this.reactQuillRef.current == null) {
return;
}
const quill = this.reactQuillRef.current.getEditor();
const range = quill.getSelection();
if (!range) return;
let contents = quill.getContents();
let elementOps = macro.ops;
const insertDelta = new Delta(elementOps);
if (range.index > 0) {
elementOps = [{ retain: range.index }].concat(elementOps);
}
const macroDelta = new Delta(elementOps);
contents = contents.compose(macroDelta);
quill.setContents(contents);
range.length = 0;
range.index += insertDelta.length();
quill.setSelection(range);
this.onChangeContent(quill);
}
updateTextTemplates(template) {
const { updateTextTemplates } = this.props;
updateTextTemplates(template);
}
render() {
const { predefinedTemplateNames, fetchedPredefinedTemplates } = this.state;
const { template, analysis, readOnly } = this.props;
const value = analysis.extended_metadata.content || {};
const autoFormatIcon = <span className="fa fa-magic" />;
const templateCreatorPopover = (
<Popover
id="popover-positioned-top"
title="Custom toolbar"
className="analyses-template-creator"
>
<ToolbarTemplateCreator
template={template}
templateOptions={predefinedTemplateNames}
updateTextTemplates={this.updateTextTemplates}
/>
</Popover>
);
return (
<DynamicToolbarEditor
theme="snow"
formats={toolbarOptions}
style={{ height: '120px' }}
ref={this.reactQuillRef}
onChange={this.quillOnChange}
value={value}
readOnly={readOnly}
>
<BaseToolbar />
<ToolbarIcon
icon={autoFormatIcon}
onClick={this.autoFormatContent}
/>
<TextTemplateToolbar
template={template}
predefinedTemplates={fetchedPredefinedTemplates}
applyTemplate={this.applyTemplate}
/>
<OverlayTrigger
trigger="click"
placement="top"
rootClose
overlay={templateCreatorPopover}
onHide={this.onCloseTemplateCreator}
>
<span className="ql-formats">
<button>
<span className="fa fa-cog" />
</button>
</span>
</OverlayTrigger>
</DynamicToolbarEditor>
);
}
}
AnalysisEditor.propTypes = {
/* eslint-disable react/forbid-prop-types */
template: PropTypes.object,
analysis: PropTypes.object,
/* eslint-enable react/forbid-prop-types */
readOnly: PropTypes.bool,
onChangeContent: PropTypes.func,
updateTextTemplates: PropTypes.func,
};
AnalysisEditor.defaultProps = {
readOnly: false,
template: {},
analysis: {},
onChangeContent: null,
updateTextTemplates: null
};
|
admin/client/Signin/components/Brand.js | alobodig/keystone | /**
* Renders a logo, defaulting to the Keystone logo if no brand is specified in
* the configuration
*/
import React from 'react';
const Brand = function (props) {
// Default to the KeystoneJS logo
let logo = { src: `${Keystone.adminPath}/images/logo.png`, width: 205, height: 68 };
if (props.logo) {
// If the logo is set to a string, it's a direct link
logo = typeof props.logo === 'string' ? { src: props.logo } : props.logo;
// Optionally one can specify the logo as an array, also stating the
// wanted width and height of the logo
// TODO: Deprecate this
if (Array.isArray(logo)) {
logo = { src: logo[0], width: logo[1], height: logo[2] };
}
}
return (
<div className="auth-box__col">
<div className="auth-box__brand">
<a href="/" className="auth-box__brand__logo">
<img
src={logo.src}
width={logo.width ? logo.width : null}
height={logo.height ? logo.height : null}
alt={props.brand}
/>
</a>
</div>
</div>
);
};
module.exports = Brand;
|
components/ImageList/ImageItem/ImageActionBar/index.js | samuelngs/px |
import React, { Component } from 'react';
import { View, Image, Text, StyleSheet } from 'react-native';
import Touchable from 'px/components/Touchable';
import ListItemLike from 'px/assets/icons/list_item_like.png';
import ListItemCollection from 'px/assets/icons/list_item_collection.png';
import ListItemShare from 'px/assets/icons/list_item_share.png';
export default class ImageActionBar extends Component {
static defaultProps = {
src: { },
}
static propTypes = {
src: React.PropTypes.object,
}
render() {
const { src: { likes } } = this.props;
return <View style={styles.base}>
<Touchable style={styles.button}>
<View style={styles.horizontal}>
<Image style={styles.icon} source={ListItemLike} />
<Text style={styles.text}>{ likes } likes</Text>
</View>
</Touchable>
<Touchable style={styles.button}>
<View style={styles.horizontal}>
<Image style={styles.icon} source={ListItemCollection} />
<Text style={styles.text}>Collection</Text>
</View>
</Touchable>
<View style={styles.fill} />
<Touchable style={styles.button}>
<View style={styles.horizontal}>
<Image style={styles.icon} source={ListItemShare} />
<Text style={styles.text}>Share</Text>
</View>
</Touchable>
</View>
}
}
const styles = StyleSheet.create({
base: {
height: 38,
flexDirection: 'row',
backgroundColor: '#fff',
alignItems: 'flex-end',
},
fill: {
flex: 1,
},
horizontal: {
flexDirection: 'row',
alignItems: 'center',
},
button: {
paddingLeft: 10,
paddingRight: 10,
height: 38,
justifyContent: 'center',
},
icon: {
width: 12,
height: 12,
marginRight: 6,
},
text: {
fontSize: 12,
fontWeight: '500',
color: '#9ca0a9',
},
});
|
src/svg-icons/action/toll.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionToll = (props) => (
<SvgIcon {...props}>
<path d="M15 4c-4.42 0-8 3.58-8 8s3.58 8 8 8 8-3.58 8-8-3.58-8-8-8zm0 14c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zM3 12c0-2.61 1.67-4.83 4-5.65V4.26C3.55 5.15 1 8.27 1 12s2.55 6.85 6 7.74v-2.09c-2.33-.82-4-3.04-4-5.65z"/>
</SvgIcon>
);
ActionToll = pure(ActionToll);
ActionToll.displayName = 'ActionToll';
ActionToll.muiName = 'SvgIcon';
export default ActionToll;
|
docs/app/Examples/modules/Dropdown/Usage/DropdownExampleTriggerImage.js | shengnian/shengnian-ui-react | import faker from 'faker'
import React from 'react'
import { Dropdown, Image } from 'shengnian-ui-react'
const trigger = (
<span>
<Image avatar src={faker.internet.avatar()} /> {faker.name.findName()}
</span>
)
const options = [
{ key: 'user', text: 'Account', icon: 'user' },
{ key: 'settings', text: 'Settings', icon: 'settings' },
{ key: 'sign-out', text: 'Sign Out', icon: 'sign out' },
]
const DropdownImageTriggerExample = () => (
<Dropdown trigger={trigger} options={options} pointing='top left' icon={null} />
)
export default DropdownImageTriggerExample
|
src/svg-icons/navigation/fullscreen-exit.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationFullscreenExit = (props) => (
<SvgIcon {...props}>
<path d="M5 16h3v3h2v-5H5v2zm3-8H5v2h5V5H8v3zm6 11h2v-3h3v-2h-5v5zm2-11V5h-2v5h5V8h-3z"/>
</SvgIcon>
);
NavigationFullscreenExit = pure(NavigationFullscreenExit);
NavigationFullscreenExit.displayName = 'NavigationFullscreenExit';
NavigationFullscreenExit.muiName = 'SvgIcon';
export default NavigationFullscreenExit;
|
system/src/routes/PurchaseOrder/containers/PurchaseOrderListViewContainer/index.js | axmatthew/react | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import purchaseOrderModule from '../../../../modules/purchase-orders';
import PurchaseOrderListView from '../../components/PurchaseOrderListView';
import { baseMapStateToProps } from '../../../../common/container-helpers';
class PurchaseOrderListViewContainer extends Component {
static propTypes = Object.assign({}, PurchaseOrderListView.propTypes, {
fetchAll: React.PropTypes.func.isRequired
});
// FIXME: duplicate code with EnquiryListViewContainer
componentDidMount() {
// fetchAll if no entities, and do not unlisten on unmount
if (this.props.data.get('entities').size === 0) {
this.props.fetchAll();
}
}
// FIXME: duplicate code with EnquiryListViewContainer
componentWillReceiveProps(nextProps) {
// fetch data after login
if (this.props.user !== nextProps.user) {
if (this.props.data.get('entities').size === 0) {
this.props.fetchAll();
}
}
}
render() {
return React.createElement(PurchaseOrderListView,
Object.assign({}, this.props, { fetchAll: undefined }));
}
}
export default connect(baseMapStateToProps.bind(null, purchaseOrderModule.entityUrl, 'listView'), {
fetchAll: purchaseOrderModule.fetchAll,
// Transfer to presentation component
push,
listSearch: purchaseOrderModule.listSearch,
setListFilter: purchaseOrderModule.setListFilter,
setPage: purchaseOrderModule.setPage,
toggleClosedDone: purchaseOrderModule.toggleClosedDone,
showContextMenu: purchaseOrderModule.showContextMenu,
remove: purchaseOrderModule.remove
})(PurchaseOrderListViewContainer);
|
docs/app/Examples/elements/Step/Content/StepExampleDescriptions.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Step } from 'semantic-ui-react'
const StepExampleDescriptions = () => (
<div>
<Step.Group>
<Step>
<Step.Title>Shipping</Step.Title>
<Step.Description>Choose your shipping options</Step.Description>
</Step>
</Step.Group>
<br />
<Step.Group>
<Step>
<Step.Title title='Shipping' />
<Step.Description description='Choose your shipping options' />
</Step>
</Step.Group>
<br />
<Step.Group>
<Step title='Shipping' description='Choose your shipping options' />
</Step.Group>
</div>
)
export default StepExampleDescriptions
|
src/components/framework/head.js | nextstrain/auspice | import React from 'react';
import { connect } from "react-redux";
import { Helmet } from "react-helmet";
import { hasExtension, getExtension } from "../../util/extensions";
const Head = ({metadata}) => {
let pageTitle = "auspice";
if (hasExtension("browserTitle")) {
pageTitle = getExtension("browserTitle");
}
const displayedDataset = window.location.pathname
.replace(/^\//g, '')
.replace(/\/$/g, '')
.replace(/\//g, ' / ')
.replace(/:/g, ' : ');
if (displayedDataset) {
pageTitle = pageTitle + " / " + displayedDataset;
}
return (
<Helmet>
<title>
{pageTitle}
</title>
{metadata && metadata.title ?
<meta name="description" content={metadata.title} /> :
null}
</Helmet>
);
};
/* we want this component to rerun each time the pathname changes, which we keep a copy
of in state. This allows us to detect changes such as redirects such as /flu/avian ->
/flu/avian/h5n1/ha. Similarly when the metadata changes. */
export default connect(
(state) => ({
pathname: state.general.pathname,
metadata: state.metadata,
general: state.general
})
)(Head);
|
src-example/components/organisms/Hero/index.js | SIB-Colombia/biodiversity_catalogue_v2_frontend | import React from 'react'
import styled from 'styled-components'
import { palette } from 'styled-theme'
import { Block, Paragraph, IconLink, IconButton, LogoImage, Tooltip } from 'components'
const Wrapper = styled(Block)`
display: flex;
flex-direction: column;
align-items: center;
height: calc(100vh - 3.75rem);
max-height: 700px;
padding: 2rem 6rem;
box-sizing: border-box;
text-align: center;
@media screen and (max-width: 640px) {
padding: 1rem;
}
`
const Text = styled(Paragraph)`
color: ${palette('grayscale', 3)}
margin: 3rem auto;
max-width: 800px;
font-weight: 300;
font-size: 1.35rem;
line-height: 1.35em;
letter-spacing: 0.07em;
@media screen and (max-width: 640px) {
font-size: 1rem;
}
`
const Logo = styled(LogoImage)`
flex: 1;
width: 100%;
min-height: 1px;
`
const StyledIconButton = styled(IconButton)`
flex: none;
`
const Hero = (props) => {
return (
<Wrapper opaque reverse {...props}>
<Logo />
<Text>
<strong>ARc</strong> is a <IconLink reverse icon="react" href="https://facebook.github.io/react/">React</IconLink> starter kit based on the <IconLink reverse icon="atomic-design" href="http://bradfrost.com/blog/post/atomic-web-design/">Atomic Design</IconLink> methodology. It's <strong>progressive</strong>, which means that you can start with the basic boilerplate and try the other features when you are comfortable.
</Text>
<Tooltip data-title="Just a fancy tooltip 😊" reverse>
<StyledIconButton
icon="github"
href="https://github.com/diegohaz/arc"
height={50}
transparent
reverse
>
View on GitHub
</StyledIconButton>
</Tooltip>
</Wrapper>
)
}
export default Hero
|
examples/basic/components/array.js | jas-chen/react-render-loader | import React from 'react';
import Hello from './class.js';
const array = [
<Hello name="Array1" />,
<Hello name="Array2" />,
<Hello name="Array3" />,
[
<Hello name="Sub array1" />,
<Hello name="Sub array2" />,
<Hello name="Sub array3" />
]
];
export default array;
|
src/decorators/withViewport.js | panli-com/MyApp | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
src/Type/AbstractType.js | reactmob/dos-filter | import React from 'react';
import PropTypes from 'prop-types';
export default class AbstractType extends React.Component {
static propTypes = {
onOperatorChange: PropTypes.func,
onValueChange: PropTypes.func,
operator: PropTypes.string,
doRenderValueInput: PropTypes.func,
doRenderOperatorList: PropTypes.func,
doRenderDoubleInput: PropTypes.func,
};
static defaultProps = {
value: '',
onOperatorChange: (value) => {
console.warn(value)
},
onValueChange: (value) => {
console.warn(value)
},
};
constructor(props) {
super(props);
if (props.doRenderDoubleInput) {
this.doRenderDoubleInput = props.doRenderDoubleInput.bind(this);
}
if (props.doRenderValueInput) {
this.doRenderValueInput = props.doRenderValueInput.bind(this);
}
if (props.doRenderOperatorList) {
this.doRenderOperatorList = props.doRenderOperatorList.bind(this);
}
this.state = {
value: props.value,
operator: props.operator,
};
}
componentWillReceiveProps(nextProps) {
if (this.state.value !== nextProps.value) {
this.setState({ value: nextProps.value });
}
if (this.state.operator !== nextProps.operator) {
this.setState({ operator: nextProps.operator });
}
}
onValueChange = (val) => {
const value = this.validate(val);
this.setState({ value });
this.props.onValueChange(value);
};
onOperatorChange = (operator) => {
this.setState({ operator });
this.props.onOperatorChange(operator);
};
/**
* @abstract
*/
getOperators() {
return {};
}
/**
* @param {String} operator
*
* @return {boolean}
*/
isSingleValue(operator) {
return true;
}
/**
* @param value
*
* @return {*}
*/
validate(value) {
return value;
}
/**
* @return {*}
*/
getValueInput() {
const { value } = this.state;
switch (false) {
case this.isSingleValue(this.state.operator):
const [aValue, bValue] = Array.isArray(value) ? value : [value, ''];
return this.doRenderDoubleInput(
this.doRenderValueInput(aValue, (value) => this.onValueChange([value, bValue])),
this.doRenderValueInput(bValue, (value) => this.onValueChange([aValue, value]))
);
default:
return this.doRenderValueInput(value, this.onValueChange);
}
}
/**
* @abstract
*/
doRenderValueInput(value, onChange) {
return null;
}
/**
* @abstract
*/
doRenderDoubleInput(aInput, bInput) {
return (
<div className="dos-filter__type--input--double">
{aInput} <span>and</span> {bInput}
</div>
);
}
/**
* @abstract
*/
doRenderOperatorList(selected, operators, onOperatorChange) {
return (
<select value={selected} onChange={(e) => onOperatorChange(e.target.value)}>
{Object.keys(operators).map((operator) => {
return <option key={operator} value={operator}>{operators[operator]}</option>;
})}
</select>
);
}
render() {
const { operator } = this.state;
const operators = this.getOperators();
const operatorList = this.doRenderOperatorList(operator, operators, this.onOperatorChange);
return (
<div className="dos-filter__type">
{operatorList &&
<div className="dos-filter__type--operator">
{operatorList}
</div>}
<div className="dos-filter__type--input">
{this.getValueInput()}
</div>
</div>
);
}
}
|
src/main/MainTabs.js | kunall17/zulip-mobile | /* @TODO flow */
import React from 'react';
import { TabNavigator, TabBarBottom } from 'react-navigation';
import tabsOptions from '../styles/tabs';
import StreamTabsCard from '../nav/StreamTabsCard';
import ConversationsContainer from '../conversations/ConversationsContainer';
import SettingsCard from '../settings/SettingsCard';
import { IconStream, IconSettings } from '../common/Icons';
import IconUnreadConversations from '../nav/IconUnreadConversations';
export default TabNavigator(
{
streams: {
screen: props => <StreamTabsCard {...props.screenProps} />,
navigationOptions: {
tabBarLabel: 'Streams',
tabBarIcon: ({ tintColor }) => <IconStream size={24} color={tintColor} />,
},
},
conversations: {
screen: props => <ConversationsContainer {...props.screenProps} />,
navigationOptions: {
tabBarLabel: 'Conversations',
tabBarIcon: ({ tintColor }) => <IconUnreadConversations color={tintColor} />,
},
},
settings: {
screen: SettingsCard,
navigationOptions: {
tabBarLabel: 'Settings',
tabBarIcon: ({ tintColor }) => <IconSettings size={24} color={tintColor} />,
},
},
},
tabsOptions(TabBarBottom, 'bottom', false),
);
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | johncorderox/Socialize | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
docs/src/app/components/pages/components/SvgIcon/ExampleSimple.js | kasra-co/material-ui | import React from 'react';
import {blue500, red500, greenA200} from 'material-ui/styles/colors';
import SvgIcon from 'material-ui/SvgIcon';
const iconStyles = {
marginRight: 24,
};
const HomeIcon = (props) => (
<SvgIcon {...props}>
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
</SvgIcon>
);
const SvgIconExampleSimple = () => (
<div>
<HomeIcon style={iconStyles} />
<HomeIcon style={iconStyles} color={blue500} />
<HomeIcon style={iconStyles} color={red500} hoverColor={greenA200} />
</div>
);
export default SvgIconExampleSimple;
|
node_modules/react-router/es/IndexRoute.js | firdiansyah/crud-req | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { component, components, falsy } from './InternalPropTypes';
var func = React.PropTypes.func;
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
/* eslint-disable react/require-render-return */
var IndexRoute = React.createClass({
displayName: 'IndexRoute',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = _createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
path: falsy,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRoute; |
demo/badge/badge.js | eferte/react-mdl-1 | import React from 'react';
import Icon from '../../src/Icon';
import Badge from '../../src/Badge';
class Demo extends React.Component {
render() {
return (
<div>
<p>Number badge on icon</p>
<Badge text="1">
<Icon name="account_box" />
</Badge>
<p>Icon badge on icon</p>
<Badge text="♥">
<Icon name="account_box" />
</Badge>
<p>Number badge</p>
<Badge text="4">Inbox</Badge>
<p>Icon badge</p>
<Badge text="♥">Mood</Badge>
</div>
);
}
}
React.render(<Demo />, document.getElementById('app'));
|
src/routes/Home/index.js | Raphael67/react-restify-mysql | import React from 'react'
import DefaultLayout from '../../layouts/Default'
export default class Home extends React.Component {
render() {
return (
<DefaultLayout currentPage='home'>
<div>This is the home page!</div>
</DefaultLayout>
)
}
} |
src/components/run.js | nfrigus/react-webpack | import React from 'react';
import ReactDOM from 'react-dom';
import App from './Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/action/pageview.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPageview = (props) => (
<SvgIcon {...props}>
<path d="M11.5 9C10.12 9 9 10.12 9 11.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5S12.88 9 11.5 9zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-3.21 14.21l-2.91-2.91c-.69.44-1.51.7-2.39.7C9.01 16 7 13.99 7 11.5S9.01 7 11.5 7 16 9.01 16 11.5c0 .88-.26 1.69-.7 2.39l2.91 2.9-1.42 1.42z"/>
</SvgIcon>
);
ActionPageview = pure(ActionPageview);
ActionPageview.displayName = 'ActionPageview';
export default ActionPageview;
|
client/components/media_by_day.js | jaischeema/panorma | import React from 'react';
import MediaByInterval from './media_by_interval';
import moment from 'moment';
export default class MediaByDay extends MediaByInterval {
fetchParams(props) {
return {
year: props.params.year,
month: props.params.month,
day: props.params.day
}
}
titleElements() {
let titleDate = moment({
month: this.props.params.month - 1,
year: this.props.params.year,
day: this.props.params.day
})
return <span>{titleDate.format('Do MMMM YYYY')}</span>
}
}
|
index.ios.js | gfogle/multi-platform-react | 'use strict';
// it is important to import the react package before anything else
import React from 'react';
import {
AppRegistry
} from 'react-native';
import Root from './src/components/root/root';
AppRegistry.registerComponent('MultiPlatformReact', () => Root);
|
src/common/components/Routes.js | aretheyrobots/prove-it | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './App';
import LoginPage from '../../pages/login/page';
import ViewPage from '../../pages/view/page';
import SpikePage from '../../pages/spike/page';
export default (
<Route path="/" component={App}>
<IndexRoute component={LoginPage} />
<Route path="spike/:id" component={SpikePage} />
<Route path="view/:id" component={ViewPage} />
</Route>
);
|
src/index.js | jonjomckay/stividor | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
app/routes/notFound/__tests__/notFound.component.spec.js | wojciech-panek/study-group-7-ssr | import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import Helmet from 'react-helmet';
import { NotFound } from '../notFound.component';
describe('NotFound: Component', () => {
const component = (props) => (
<NotFound {...props} />
);
it('should not render not-found root', () => {
const wrapper = shallow(component({}));
expect(wrapper.find('.not-found')).to.have.length(1);
});
it('should render <Helmet/>', () => {
const wrapper = shallow(component({}));
expect(wrapper.find(Helmet)).to.have.length(1);
});
it('should pass title prop to <Helmet/>', () => {
const wrapper = shallow(component({}));
const helmetProps = wrapper.find(Helmet).props();
expect(helmetProps.title).to.be.a('string');
});
});
|
src/Problem.js | CISC475-Group2/parsons-ui | import React, { Component } from 'react';
import { DragSource, DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import Block from './Block';
import BlockList from './BlockList';
import AvailableBlocksSpace from './AvailableBlocksSpace'
class Problem extends Component {
render() {
return (
<div className="problem col-lg-12">
<div className="page-header">
<h1>Problem 4</h1>
</div>
<pre className="code-space">{this.props.baseBlockString}</pre>
<pre>
<Block block={this.props.baseBlock}
onMoveBlock={this.props.onMoveBlock}
onSwapBlocks={this.props.onSwapBlocks} />
<AvailableBlocksSpace onMoveBlock={this.props.onMoveBlock}>
<BlockList blocks={this.props.blocks}
onMoveBlock={this.props.onMoveBlock}
onSwapBlocks={this.props.onSwapBlocks} />
</AvailableBlocksSpace>
</pre>
<div className="btn-group" role="group" aria-label="...">
<button type="button" className="btn btn-default" onClick={this.props.onReset.bind(this)}>Reset</button>
<button type="button" className="btn btn-default" >Submit</button>
</div>
</div>
);
}
};
export default DragDropContext(HTML5Backend)(Problem);
|
src/statics/UserNotFound.js | Sekhmet/busy | import React from 'react';
import { FormattedMessage } from 'react-intl';
const UserNotFound = () =>
<div className="text-center my-5">
<h3>
<FormattedMessage id="user_not_found" defaultMessage="User not found" />
</h3>
</div>;
export default UserNotFound;
|
src/templates/blogPost.js | asunny72/IdeaNation | import React from 'react'
import Helmet from 'react-helmet'
import { DiscussionEmbed } from "disqus-react"
import { graphql } from "gatsby"
import Layout from '../components/layout'
import HeaderGeneric from '../components/HeaderGeneric'
class BlogPost extends React.Component {
constructor(data) {
super();
this.data = data;
}
render() {
const data = this.data.data;
if (!data || !(data.markdownRemark || data.contentfulBlogPost)) {
return;
}
const post = data.markdownRemark? extractPostFromLocalBlogs(data) : extractPostFromContenfulBlogs(data);
const disqusShortname = "ideanation";
const disqusConfig = {
identifier: post.id,
title: post.title,
};
return (
<Layout>
<Helmet title="BlogPost" />
<HeaderGeneric />
<div id="main" className="main">
<section id="content" className="main">
<h1>{post.title}</h1>
<div white-space="pre-wrap" dangerouslySetInnerHTML={{ __html: post.html }} />
</section>
<section id="content" className="main">
<DiscussionEmbed shortname={disqusShortname} config={disqusConfig} />
</section>
</div>
</Layout>
)
}
}
const extractPostFromLocalBlogs = data => {
const entry = data.markdownRemark;
return {
id: entry.id,
title: entry.frontmatter.title,
html: entry.html
};
};
const extractPostFromContenfulBlogs = data => {
const entry = data.contentfulBlogPost;
return {
id: entry.id,
title: entry.title,
html: entry.childContentfulBlogPostBodyTextNode.childMarkdownRemark.html
};
};
export default BlogPost
export const query = graphql`
query($slug: String!) {
markdownRemark(fields: { slug: { eq: $slug } }) {
html
frontmatter {
title
}
}
contentfulBlogPost(slug: { eq: $slug }) {
id
title
childContentfulBlogPostBodyTextNode {
childMarkdownRemark {
html
}
}
}
}
` |
src/scripts/app.js | lixmal/keepass4web | import jQuery from 'jquery'
import Css from '../style/app.css'
import React from 'react'
import ReactDOM from 'react-dom'
import Router from 'react-router/lib/Router'
import Route from 'react-router/lib/Route'
import useRouterHistory from 'react-router/lib/useRouterHistory'
import withRouter from 'react-router/lib/withRouter'
import { createHashHistory } from 'history'
import Viewport from './Viewport'
import UserLogin from './UserLogin'
import BackendLogin from './BackendLogin'
import DBLogin from './DBLogin'
const View = withRouter(Viewport)
const UserForm = withRouter(UserLogin)
const BackendForm = withRouter(BackendLogin)
const DBForm = withRouter(DBLogin)
const appHistory = useRouterHistory(createHashHistory)()
// global namespace
window.KeePass4Web = {}
KeePass4Web.checkAuth = function (nextState, replace, callback) {
return KeePass4Web.ajax('authenticated', {
error: function (r, s, e) {
var auth
if (r.status == 401 && r.responseJSON)
auth = r.responseJSON.message
else
KeePass4Web.error(r, s, e)
if (!auth) return
var state = nextState && nextState.location.state
// route to proper login page if unauthenticated
// in that order
if (!auth.user) {
KeePass4Web.clearStorage()
replace({
state: state,
pathname: '/user_login'
})
}
else if (!auth.backend) {
var template = KeePass4Web.getSettings().template
if (template.type === 'redirect') {
window.location = template.url
// stopping javascript execution to prevent redirect loop
throw 'Redirecting'
}
else if (template.type === 'mask')
replace({
state: state,
pathname: '/backend_login'
})
}
else if (!auth.db) {
replace({
state: state,
pathname: '/db_login'
})
}
}.bind(this),
complete: callback,
})
}
// simple wrapper for ajax calls, in case implementation changes
KeePass4Web.ajax = function (url, conf) {
conf.url = url
// set defaults
conf.method = typeof conf.method === 'undefined' ? 'POST' : conf.method
conf.dataType = typeof conf.dataType === 'undefined' ? 'json' : conf.dataType
if (typeof conf.headers === 'undefined') {
conf.headers = {}
}
conf.headers['X-CSRF-Token'] = KeePass4Web.getCSRFToken()
KeePass4Web.restartTimer(true)
return jQuery.ajax(conf)
}
// leave room for implementation changes
KeePass4Web.clearStorage = function () {
localStorage.removeItem('settings')
localStorage.removeItem('CSRFToken')
}
KeePass4Web.setCSRFToken = function (CSRFToken) {
localStorage.setItem('CSRFToken', CSRFToken || '')
}
KeePass4Web.getCSRFToken = function () {
return localStorage.getItem('CSRFToken') || null
}
KeePass4Web.setSettings = function (settings) {
var stored = KeePass4Web.getSettings()
for (var k in settings) {
stored[k] = settings[k]
}
localStorage.setItem('settings', JSON.stringify(stored))
}
KeePass4Web.getSettings = function () {
var settings = localStorage.getItem('settings')
if (settings)
return JSON.parse(settings)
return {}
}
KeePass4Web.timer = false
KeePass4Web.restartTimer = function (val) {
if (typeof val !== 'undefined' ) KeePass4Web.timer = val
return KeePass4Web.timer
}
KeePass4Web.error = function (r, s, e) {
// ignore aborted requests
if (e === 'abort')
return
if (r.status == 401) {
if (this.props && this.props.router) {
// redirect first, to hide sensitive data
this.props.router.replace('/db_login')
this.props.router.replace({
state: { info: 'Session expired' },
pathname: '/'
})
}
else {
alert('Your session expired')
location.reload()
}
}
else {
let error = e
if (r.responseJSON)
error = r.responseJSON.message
// disable remaining loading masks
if (this.state) {
this.setState({
groupMask: false,
nodeMask: false,
})
}
alert(error)
}
}
ReactDOM.render(
<Router history={appHistory}>
<Route path="/" component={View} onEnter={KeePass4Web.checkAuth} />
<Route path="/user_login" component={UserForm} />
<Route path="/backend_login" component={BackendForm} />
<Route path="/db_login" component={DBForm} />
</Router>,
document.getElementById('app-content')
)
|
docs/pages/api-docs/table-pagination.js | lgollut/material-ui | import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'api/table-pagination';
const requireRaw = require.context('!raw-loader!./', false, /\/table-pagination\.md$/);
export default function Page({ docs }) {
return <MarkdownDocs docs={docs} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
docs/src/pages/faq.js | Gisto/Gisto | import React from 'react';
import {Helmet} from "react-helmet";
import Header from 'components/header';
import Footer from 'components/footer';
const Faq = () => (
<React.Fragment>
<Helmet>
<title>F.A.Q.</title>
</Helmet>
<Header/>
<h1>F.A.Q.</h1>
<section className="whiter boxes page-faq inner">
<div className="w-container content-container">
<div className="w-row">
<div className="w-col w-col-3 w-clearfix side-container">
<h2>QUESTIONS</h2>
<nav>
<ul>
<li><a className="innsite" href="#what-is-gisto">What is Gisto?</a>
</li>
<li><a className="innsite" href="#auth">Authentication</a></li>
<li><a className="innsite" href="#do-you-use-server">Do you use
backend server?
</a>
</li>
<li><a className="innsite" href="#who-can-see-my-gists">Who can see
my
gists?
</a>
</li>
<li><a className="innsite" href="#run-as-portable">Use gisto as
portable application in windows.
</a>
</li>
<li><a className="innsite" href="#do-you-plan-to-add-feature">Do you
plan to support / add support for
[future-name-here]?
</a>
</li>
<li><a className="innsite" href="#issues-bugs-features">Issues, bug
reporting, pull and feature requests
</a>
</li>
<li><a className="innsite" href="#how-to-contact">How to contact
us
</a>
</li>
</ul>
</nav>
</div>
<div className="w-col w-col-9 w-clearfix">
<h2 id="what-is-gisto">What is Gisto?</h2>
<p>Gisto is a code snippet manager that runs on GitHub Gists and adds
additional features
such as searching, tagging and sharing gists while including a rich code
editor.
</p>
<p>Gisto is cross platform and is in constant sync with GitHub so you can
view
and edit
your Gists via both Gisto and GitHub.
</p>
<h2 id="auth">Authentication</h2>
<p>Gisto authenticates to GitHub by using basic authentication over SSL and
retrieving an oAuth2 token
thus the need for your GitHub user and password.
</p>
<p>Gisto only saves the oAuth2 token received after authenticating and
nothing
else.
If you would rather to supply your own access token without providing
Gisto your login details you
may manually create an access token from the account settings at GitHub
and login using the
generated token.
</p>
<p>This token will be saved permanently until you log out.</p>
<h2 id="do-you-use-server">Do you use backend server?</h2>
<p>Gisto is using GitHub gist API and communicates directly with Github, no
3rd party server or database
involved in gist management.
</p>
<p>However we do use a backend server for "notifications and sharing
service",
the only data stored is username
and gist ID and this is to allow Gisto to notify user if there are Gists
shared with him.
</p>
<p>You also have the option of running your own notification server so you
can
be sure your data is secure.
</p>
<h2 id="who-can-see-my-gists">Who can see my Gists?</h2>
<p>As per GitHub Guidelines Gists are not private and are available to the
public.
</p>
<p>The difference between secret and public Gists is that public Gists are
listed on GitHub website for
public viewing and searching while secret Gists are not
</p>
<h2 id="run-as-portable">Use gisto as portable application on windows?</h2>
<blockquote>
Please note this instructions refers to legacy version (up to v0.3.2)
</blockquote>
<p>For a non-installer version of Gisto, you can:</p>
<ul className="fa-ul">
<li className="icons-li"><i
className="fa fa-chevron-circle-right" /> Download a ZIP file of
Windows Version from Gisto "Nightly" builds: <a
href="http://build.gistoapp.com">build.gistoapp.com
</a> and
extract it to some directory of your choosing.
</li>
<li className="icons-li"><i
className="fa fa-chevron-circle-right" /> Create a empty file in
directory you've extracted Gisto ZIP named <em>gisto.bat</em>
</li>
<li className="icons-li"><i
className="fa fa-chevron-circle-right" /> Edit <em>gisto.bat</em> file
and add the following content: <code>gisto.exe
--data-path="./gistoData"
</code>
</li>
<li className="icons-li"><i
className="fa fa-chevron-circle-right" /> Start Gisto by
double-click the <em>gisto.bat</em> file.
</li>
</ul>
<p>You have now your portable version of Gisto and all data will be saved in
directory named <em>gistoData</em>, relative to path where you are
running
Gisto from.
</p>
<p>In order to update portable Gisto - just download new version ZIP and
extract it by overwriting the existing files.
</p>
<h2 id="do-you-plan-to-add-feature">Do you plan to support / add support for
[<i>future-name-here</i>]?
</h2>
<p>Please open a feature request in our <a
href="https://github.com/Gisto/Gisto/issues">issue tracker
</a>, we
appreciate and strive for
suggestions on how to improve Gisto.
</p>
<h2 id="issues-bugs-features">Issues, bug reporting, pull and feature
requests
</h2>
<p>Please feel free to add a bug / feature request / suggestions to the <a
href="https://github.com/Gisto/Gisto/issues">issue tracker
</a>.
Pull requests are also very welcome as well.
</p>
<h2 id="how-to-contact">How to contact us</h2>
<p>Twitter: <a href="https://twitter.com/gistoapp">@gistoapp</a></p>
<p>Email: contact@gistoapp.com</p>
<p>Issue tracker: <a href="https://github.com/Gisto/Gisto/issues">Issue
tracker at GitHub
</a>
</p>
</div>
</div>
</div>
</section>
<Footer/>
</React.Fragment>
);
export default Faq;
|
actor-apps/app-web/src/app/components/modals/InviteUser.react.js | WangCrystal/actor-platform | import _ from 'lodash';
import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ActorClient from 'utils/ActorClient';
import { KeyCodes } from 'constants/ActorAppConstants';
import InviteUserActions from 'actions/InviteUserActions';
import InviteUserByLinkActions from 'actions/InviteUserByLinkActions';
import ContactStore from 'stores/ContactStore';
import InviteUserStore from 'stores/InviteUserStore';
import ContactItem from './invite-user/ContactItem.react';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return ({
contacts: ContactStore.getContacts(),
group: InviteUserStore.getGroup(),
isOpen: InviteUserStore.isModalOpen()
});
};
const hasMember = (group, userId) =>
undefined !== _.find(group.members, (c) => c.peerInfo.peer.id === userId);
@ReactMixin.decorate(IntlMixin)
class InviteUser extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = _.assign({
search: ''
}, getStateFromStores());
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
InviteUserStore.addChangeListener(this.onChange);
ContactStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
InviteUserStore.removeChangeListener(this.onChange);
ContactStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
InviteUserActions.hide();
};
onContactSelect = (contact) => {
const { group } = this.state;
InviteUserActions.inviteUser(group.id, contact.uid);
};
onInviteUrlByClick = () => {
InviteUserByLinkActions.show(this.state.group);
InviteUserActions.hide();
};
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onSearchChange = (event) => {
this.setState({search: event.target.value});
};
render() {
const { contacts, group, search, isOpen } = this.state;
let contactList = [];
if (isOpen) {
_.forEach(contacts, (contact, i) => {
const name = contact.name.toLowerCase();
if (name.includes(search.toLowerCase())) {
if (!hasMember(group, contact.uid)) {
contactList.push(
<ContactItem contact={contact} key={i} onSelect={this.onContactSelect}/>
);
} else {
contactList.push(
<ContactItem contact={contact} key={i} isMember/>
);
}
}
}, this);
}
if (contactList.length === 0) {
contactList.push(
<li className="contacts__list__item contacts__list__item--empty text-center">
<FormattedMessage message={this.getIntlMessage('inviteModalNotFound')}/>
</li>
);
}
return (
<Modal className="modal-new modal-new--invite contacts"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 400}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person_add</a>
<h4 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('inviteModalTitle')}/>
</h4>
<div className="pull-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</header>
<div className="modal-new__body">
<div className="modal-new__search">
<i className="material-icons">search</i>
<input className="input input--search"
onChange={this.onSearchChange}
placeholder={this.getIntlMessage('inviteModalSearch')}
type="search"
value={this.state.search}/>
</div>
<a className="link link--blue" onClick={this.onInviteUrlByClick}>
<i className="material-icons">link</i>
{this.getIntlMessage('inviteByLink')}
</a>
</div>
<div className="contacts__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
}
}
export default InviteUser;
|
src/components/Bookmark.js | Jalissa/rss-feed-client | import React from 'react';
const Bookmark = (props) => {
let style = { color: '#ccc'};
if(props.markBookmarkFlag){
style.color = '#000';
}
const onClick = (evt) => {
evt.stopPropagation();
const element = evt.target;
props.boundActions.toggleBookmark(element, props.feed);
};
return (
<span
onClick={onClick}
style={style}
className="glyphicon glyphicon-bookmark"
aria-hidden="true"/>
);
};
export default Bookmark;
|
client/trello/src/app/routes/home/Home.spec.js | Madmous/Trello-Clone | import { shallow, mount } from 'enzyme';
import { Provider } from 'react-redux';
import { expect } from 'chai';
import sinon from 'sinon';
import React from 'react';
import configureMockStore from 'redux-mock-store';
import thunk from 'redux-thunk';
import nock from 'nock';
import HomeContainer from './HomeContainer';
import Home from './Home';
const setupShallow = () => {
const props = {
errorMessages: [],
homeActions: {}
}
return shallow(<Home {...props} />)
}
const setupMount = () => {
const initialState = {
app: {
errorMessage: '',
fullName: 'Mous',
isFetching: true,
isFetchingUser: false,
isFetchingUserSuccessful: true,
userId: '1'
},
starredBoard: {
starredBoards: []
},
organization: {
organizations: []
},
board: {
boards: []
},
boardsMenu: {
isFocusOnBoardsMenu: false,
isBoardsMenuOpen: false,
userInput: ''
},
modals: {
isCreateOrganizationModalOpen: false,
isCreateBoardModalOpen: false,
isFocusOnModal: false,
isModalOpen: false
},
notification: {
errorMessages: [],
isPopOverOpen: false
},
homeActions: {}
};
const middlewares = [ thunk ];
const mockStore = configureMockStore(middlewares);
const store = mockStore(initialState);
return mount(
<Provider store={ store }>
<HomeContainer />
</Provider>);
};
describe('<Home />', () => {
it('should call componentDidMount', () => {
let spy = sinon.spy(Home.prototype, 'componentDidMount');
const wrapper = setupMount();
expect(spy.calledOnce).to.equal(true);
spy.restore();
nock.cleanAll();
})
})
describe('<Boards />', () => {
it('should render Boards', () => {
const wrapper = setupShallow();
expect(wrapper.find('Connect(Boards)')).to.have.length(1);
expect(wrapper.find('Notification')).to.have.length(0);
})
})
describe('<Notification />', () => {
it('should render Notification', () => {
const wrapper = setupShallow();
expect(wrapper.find('Notification')).to.have.length(0);
wrapper.setProps({ errorMessages: ['There is an error'] });
expect(wrapper.find('Notification')).to.have.length(1);
})
}) |
src/server.js | BlackAngus/BVPHackathon | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
import bodyParser from 'body-parser';
import twilio from 'twilio';
import Firebase from 'firebase';
// Twilio Setup.
const accountSid = 'ACa54c5209e1735c0762bdb2d3da27d7ce';
const authToken = '82fc0731876d1c9022d3963bca07f2ff';
const client = twilio(accountSid, authToken);
// Firebase Setup.
const myRootRef = new Firebase('https://bvphackathon.firebaseio.com/');
const server = global.server = express();
server.set('port', (process.env.PORT || 5000));
server.use(express.static(path.join(__dirname, 'public')));
server.use(bodyParser.json());
server.post('/getHelp', async (req, res, next) => {
var Workers = myRootRef.child('Workers');
Workers.once('value', function(data){
console.log("Data from Firebase: ", data.val());
var memberArray = [];
// Push the mmebers into an array.
for(var worker in data.val()) memberArray.push(data.val()[worker]);
// This will be random for now but a proper algorithm will help.
// Random number generator 0 - 1.
var randomWorker = memberArray[Math.floor((Math.random() * memberArray.length))];
console.log("Contacting: ", randomWorker);
client.messages.create({
body: [
randomWorker.name,
"Your help is need in 5 mintues at",
"Job Site: DNA Pizza",
"Address: 375 11th St, San Francisco, CA 94103",
"Phone: (415) 626-0166",
"Description: The job is 2hrs long and you will make $40 for your services."
].join("\n"),
to: randomWorker.phone,
from: "+19782212765"
}, function(err, message) {
console.log(req.body);
if(err) return res.status(200).send("<response>false</response>");
console.log(message.sid);
return res.status(200).send("<response>true</response>");
});
});
});
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '' };
const css = [];
const context = {
onInsertCss: value => css.push(value),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(server.get('port'), () => {
/* eslint-disable no-console */
console.log('The server is running at http://0.0.0.0:' + server.get('port'));
if (process.send) {
process.send('online');
}
});
|
app/javascript/flavours/glitch/features/ui/components/column_loading.js | Kirishima21/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Column from 'flavours/glitch/components/column';
import ColumnHeader from 'flavours/glitch/components/column_header';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class ColumnLoading extends ImmutablePureComponent {
static propTypes = {
title: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
icon: PropTypes.string,
};
static defaultProps = {
title: '',
icon: '',
};
render() {
let { title, icon } = this.props;
return (
<Column>
<ColumnHeader icon={icon} title={title} multiColumn={false} focusable={false} placeholder />
<div className='scrollable' />
</Column>
);
}
}
|
tests/layouts/CoreLayout.spec.js | ZeusTheTrueGod/WindsurfingNetwork-client | import React from 'react';
import TestUtils from 'react-addons-test-utils';
import CoreLayout from 'layouts/CoreLayout/CoreLayout';
function shallowRender (component) {
const renderer = TestUtils.createRenderer();
renderer.render(component);
return renderer.getRenderOutput();
}
function shallowRenderWithProps (props = {}) {
return shallowRender(<CoreLayout {...props} />);
}
describe('(Layout) Core', function () {
let _component;
let _props;
let _child;
beforeEach(function () {
_child = <h1 className='child'>Child</h1>;
_props = {
children : _child,
};
_component = shallowRenderWithProps(_props);
});
it('Should render as a <div>.', function () {
expect(_component.type).to.equal('div');
});
});
|
client/src/components/search/searchPage/NoResults.js | BhaveshSGupta/FreeCodeCamp | import React from 'react';
import PropTypes from 'prop-types';
const propTypes = {
query: PropTypes.string
};
function NoResults({ query }) {
return (
<div className='no-results-wrapper'>
<p>
We could not find anything relating to <em>{query}</em>
</p>
</div>
);
}
NoResults.displayName = 'NoResults';
NoResults.propTypes = propTypes;
export default NoResults;
|
examples/react-redux/src/store/routes.js | rangle/redux-segment | import React from 'react';
import { IndexRoute, Route } from 'react-router';
import App from '../containers/App';
import AboutPage from '../containers/AboutPage';
import CounterPage from '../containers/CounterPage';
export default (
<Route path="/" component={ App }>
<IndexRoute component={ CounterPage }/>
<Route path="about" component={ AboutPage }/>
</Route>
);
|
packages/lightning-components/Select/index.js | DaReaper/lightning-app | import React from 'react'
import reactCSS, { hover } from 'reactcss'
import _ from 'lodash'
import { colors, css, fonts } from '../helpers'
export const Media = (props) => {
const styles = reactCSS({
'default': {
select: {
background: 'transparent',
border: 'none',
height: 30,
boxShadow: 'inset 0 0 0 1px #ccc',
borderRadius: 2,
textTransform: 'uppercase',
color: '#aaa',
cursor: 'pointer',
outline: 'none',
fontSize: fonts.sizes.medium,
transition: 'box-shadow 200ms ease-out, color 200ms ease-out',
},
},
'hover': {
select: {
boxShadow: 'inset 0 0 0 1px #888',
color: '#777',
},
},
'bare': {
select: {
boxShadow: 'none',
padding: 0,
},
},
...css.build('media', 'color', colors),
}, props)
return (
<select style={ styles.select } value={ props.value } onChange={ props.onChange }>
{ _.map(props.options, (option) => {
return <option key={ option.value } value={ option.value }>{ option.label }</option>
}) }
</select>
)
}
export default hover(Media)
|
app/actions/entryActions.js | JasonEtco/flintcms | import React from 'react'
import { push } from 'react-router-redux'
import graphFetcher from 'utils/graphFetcher'
import formatFields from 'utils/formatFields'
import { getSlugFromId } from 'utils/helpers'
import { newToast, errorToasts } from './uiActions'
export const REQUEST_ENTRIES = 'REQUEST_ENTRIES'
export const RECEIVE_ENTRIES = 'RECEIVE_ENTRIES'
export const NEW_ENTRY = 'NEW_ENTRY'
export const UPDATE_ENTRY = 'UPDATE_ENTRY'
export const DELETE_ENTRY = 'DELETE_ENTRY'
export const ENTRY_DETAILS = 'ENTRY_DETAILS'
/**
* Creates a new Entry
* @param {string} title
* @param {string} section
* @param {string} status
* @param {string} dateCreated
* @param {object} rawOptions
*/
export function newEntry (title, section, status, dateCreated, rawOptions) {
return async (dispatch, getState) => {
const { fields, sections, user } = getState()
const options = await formatFields(rawOptions, fields.fields)
const query = `mutation ($data: EntriesInput!) {
addEntry(data: $data) {
_id
title
slug
status
fields {
fieldId
handle
value
}
section
author {
username
}
dateCreated
}
}`
const variables = {
data: {
title,
section,
status,
dateCreated,
fields: options,
author: user._id
}
}
return graphFetcher(query, variables)
.then((json) => {
const { addEntry } = json.data.data
dispatch({ type: NEW_ENTRY, addEntry })
dispatch(newToast({
message: <span><b>{addEntry.title}</b> has been created!</span>,
style: 'success'
}))
const sectionSlug = getSlugFromId(sections.sections, addEntry.section)
dispatch(push(`/entries/${sectionSlug}/${addEntry._id}`))
})
.catch(errorToasts)
}
}
/**
* Saves updates of an existing Entry
* @param {string} _id
* @param {object} data
*/
export function updateEntry (_id, data) {
return async (dispatch, getState) => {
const state = getState()
const { title, status, dateCreated, ...fields } = data
const options = await formatFields(fields, state.fields.fields)
const query = `mutation ($_id: ID!, $data: EntriesInput!) {
updateEntry(_id: $_id, data: $data) {
_id
title
status
fields {
fieldId
handle
value
}
}
}`
const variables = {
_id,
data: {
title,
status,
dateCreated,
fields: options
}
}
return graphFetcher(query, variables)
.then((json) => {
const updatedEntry = json.data.data.updateEntry
dispatch({ type: UPDATE_ENTRY, updateEntry: updatedEntry })
dispatch(newToast({
message: <span><b>{updatedEntry.title}</b> has been updated!</span>,
style: 'success'
}))
})
.catch(errorToasts)
}
}
/**
* Posts to GraphQL to delete an Entry
* @param {string} _id
* @param {boolean} [redirect=false] - Redirect to the entries page after deleting the entry
*/
export function deleteEntry (_id, redirect = false) {
return (dispatch) => {
const query = `mutation ($_id:ID!) {
removeEntry(_id: $_id) {
_id
title
}
}`
return graphFetcher(query, { _id })
.then((json) => {
const { removeEntry } = json.data.data
if (redirect) dispatch(push('/entries'))
dispatch({ type: DELETE_ENTRY, id: removeEntry._id })
dispatch(newToast({
message: <span><b>{removeEntry.title}</b> has been deleted.</span>,
style: 'success'
}))
})
.catch(errorToasts)
}
}
/**
* Gets the details (fields object) of an Entry
* @param {string} _id - Mongo ID of Entry.
*/
export function entryDetails (_id) {
return (dispatch) => {
const query = `query ($_id:ID!) {
entry (_id: $_id) {
fields {
fieldId
handle
value
}
}
}`
return graphFetcher(query, { _id })
.then((json) => {
const { entry } = json.data.data
dispatch({ type: UPDATE_ENTRY, updateEntry: { _id, ...entry } })
})
.catch(errorToasts)
}
}
|
stories/components/quoteBanner/index.js | tskuse/operationcode_frontend | import React from 'react';
import { storiesOf } from '@storybook/react';
import QuoteBanner from 'shared/components/quoteBanner/quoteBanner';
storiesOf('shared/components/quoteBanner', module)
.add('Default', () => (
<QuoteBanner
author="James bond"
quote="I always enjoyed learning a new tongue"
/>
));
|
web/themes/custom/proyectofinal/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | kevinmora94/proyectoDrupal | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
app/app.js | lishengzxc/random | import './app.scss';
import styles from './views/Page/Page.scss';
import React from 'react';
import SideBar from './views/SideBar/SideBar';
import Header from './views/Header/Header';
import TeamList from './views/TeamList/TeamList';
import AddTeamButton from './views/AddTeamButton/AddTeamButton';
import EditTeamButton from './views/EditTeamButton/EditTeamButton';
import AddTeamList from './views/AddTeamList/AddTeamList';
import Setup from './views/Setup/Setup';
import MessageBox from './views/MessageBox/MessageBox';
import RandomPage from './views/RandomPage/RandomPage';
import cx from 'classnames';
import Router from 'react-router';
import RandomStore from './stores/random-store';
var Route = Router.Route;
var RouteHandler = Router.RouteHandler;
var getPageState = () => ({ pageState: RandomStore.getPageState() });
var App = React.createClass({
getInitialState: function () {
return getPageState();
},
onSlide: function () {
this.setState(getPageState());
},
componentDidMount: function () {
RandomStore.addChangeListener(this.onSlide);
},
componentWillUnmount: function () {
RandomStore.removeChangeListener(this.onSlide);
},
render: function () {
var classList = this.state.pageState ? [styles.page, styles.slide] : [styles.page];
return (
<div className={styles.div}>
<SideBar />
<Header />
<div className={cx(classList)}>
<div className={cx(styles.wrapper)}>
<RouteHandler />
</div>
</div>
<AddTeamButton visibility={
window.location.hash.substr(1) === '/addTeam' ||
window.location.hash.substr(1) === '/setup' ||
window.location.hash.substr(1) === '/randomPage' ||
window.location.hash.substr(1) === '/editTeam'}
/>
<EditTeamButton visibility={
window.location.hash.substr(1) === '/randomPage'}
/>
</div>
)
}
});
var routes = (
<Route handler={App}>
<Route path="/" handler={TeamList} />
<Route path="addTeam" handler={AddTeamList} />
<Route path="setup" handler={Setup} />
<Route path="randomPage" handler={RandomPage} />
<Route path="editTeam" handler={AddTeamList} />
</Route>
);
Router.run(routes, Router.HashLocation, (Root) => {
React.render(<Root />, document.body);
});
|
app/javascript/mastodon/features/ui/util/react_router_helpers.js | SerCom-KC/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';
import ColumnLoading from '../components/column_loading';
import BundleColumnError from '../components/bundle_column_error';
import BundleContainer from '../containers/bundle_container';
// Small wrapper to pass multiColumn to the route components
export class WrappedSwitch extends React.PureComponent {
render () {
const { multiColumn, children } = this.props;
return (
<Switch>
{React.Children.map(children, child => React.cloneElement(child, { multiColumn }))}
</Switch>
);
}
}
WrappedSwitch.propTypes = {
multiColumn: PropTypes.bool,
children: PropTypes.node,
};
// Small Wrapper to extract the params from the route and pass
// them to the rendered component, together with the content to
// be rendered inside (the children)
export class WrappedRoute extends React.Component {
static propTypes = {
component: PropTypes.func.isRequired,
content: PropTypes.node,
multiColumn: PropTypes.bool,
componentParams: PropTypes.object,
};
static defaultProps = {
componentParams: {},
};
renderComponent = ({ match }) => {
const { component, content, multiColumn, componentParams } = this.props;
return (
<BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}>
{Component => <Component params={match.params} multiColumn={multiColumn} {...componentParams}>{content}</Component>}
</BundleContainer>
);
}
renderLoading = () => {
return <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { component: Component, content, ...rest } = this.props;
return <Route {...rest} render={this.renderComponent} />;
}
}
|
blueocean-material-icons/src/js/components/svg-icons/action/settings-power.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionSettingsPower = (props) => (
<SvgIcon {...props}>
<path d="M7 24h2v-2H7v2zm4 0h2v-2h-2v2zm2-22h-2v10h2V2zm3.56 2.44l-1.45 1.45C16.84 6.94 18 8.83 18 11c0 3.31-2.69 6-6 6s-6-2.69-6-6c0-2.17 1.16-4.06 2.88-5.12L7.44 4.44C5.36 5.88 4 8.28 4 11c0 4.42 3.58 8 8 8s8-3.58 8-8c0-2.72-1.36-5.12-3.44-6.56zM15 24h2v-2h-2v2z"/>
</SvgIcon>
);
ActionSettingsPower.displayName = 'ActionSettingsPower';
ActionSettingsPower.muiName = 'SvgIcon';
export default ActionSettingsPower;
|
src/App.js | shihlinlu/tesla-range-calculator | import React, { Component } from 'react';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import TeslaCarContainer from './containers/TeslaCarContainer';
import TeslaStatsContainer from './containers/TeslaStatsContainer';
import TeslaSpeedCounterContainer from './containers/TeslaSpeedCounterContainer';
import TeslaTempCounterContainer from './containers/TeslaTempCounterContainer';
import TeslaClimateContainer from './containers/TeslaClimateContainer';
import TeslaWheelsContainer from './containers/TeslaWheelsContainer';
import TeslaNotice from './components/TeslaNotice/TeslaNotice';
import './App.css';
import Header from './components/Header/Header';
import appReducer from './reducers/teslaRangeApp';
const store = createStore(appReducer, window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
/**
* Top-level component of entire app
*/
class App extends Component {
render() {
return (
<Provider store={store}>
<div>
<Header />
<div className="wrapper">
<form className="tesla-battery">
<h1>Range Per Charge</h1>
<TeslaCarContainer />
<TeslaStatsContainer />
<div className="tesla-controls cf">
<TeslaSpeedCounterContainer />
<div className="tesla-climate-container cf">
<TeslaTempCounterContainer />
<TeslaClimateContainer />
</div>
<TeslaWheelsContainer />
</div>
<TeslaNotice />
</form>
</div>
</div>
</Provider>
);
}
}
export default App;
|
src/Dialog/Dialog.spec.js | manchesergit/material-ui | /* eslint-env mocha */
import React from 'react';
import Dialog from './Dialog';
import {spy} from 'sinon';
import {mount} from 'enzyme';
import {assert} from 'chai';
import TestUtils from 'react-dom/test-utils';
import getMuiTheme from '../styles/getMuiTheme';
describe('<Dialog />', () => {
const muiTheme = getMuiTheme();
const mountWithContext = (node) => mount(node, {context: {muiTheme}});
it('appends a dialog to the document body', () => {
const testClass = 'test-dialog-class';
mountWithContext(
<Dialog
open={true}
contentClassName={testClass}
/>
);
const dialogEl = document.getElementsByClassName(testClass)[0];
assert.ok(dialogEl);
});
it('registers events on dialog actions', () => {
const clickSpy = spy();
const testClass = 'dialog-action';
mountWithContext(
<Dialog
open={true}
actions={[
<button
key="a"
onClick={clickSpy}
className={testClass}
>
test
</button>,
]}
/>
);
const actionEl = document.getElementsByClassName(testClass)[0];
assert.ok(actionEl);
TestUtils.Simulate.click(actionEl);
assert.ok(clickSpy.called);
});
it('should render a inner content container with sharp corners', () => {
const testClass = 'test-dialog-paper-rounded-class';
mountWithContext(
<Dialog
open={true}
paperClassName={testClass}
paperProps={{rounded: false}}
/>
);
const testEl = document.getElementsByClassName(testClass)[0];
assert.strictEqual(testEl.style.borderRadius, '0px');
});
describe('should render a custom className', () => {
const testTitle = 'test-dialog-title';
const testAction = <button>test</button>;
const testClasses = {
root: 'test-dialog-root-class',
overlay: 'test-dialog-overlay-class',
body: 'test-dialog-body-class',
content: 'test-dialog-content-class',
innerContent: 'test-dialog-paper-class',
titleContainer: 'test-dialog-title-container-class',
actionsContainer: 'test-dialog-actions-container-class',
};
mountWithContext(
<Dialog
open={true}
title={testTitle}
actionsContainerClassName={testClasses.actionsContainer}
bodyClassName={testClasses.body}
className={testClasses.root}
contentClassName={testClasses.content}
paperClassName={testClasses.innerContent}
overlayClassName={testClasses.overlay}
titleClassName={testClasses.titleContainer}
actions={testAction}
/>
);
for (const key in testClasses) {
if (testClasses.hasOwnProperty(key)) {
const testClass = testClasses[key];
it(testClass, () => {
assert.ok(document.getElementsByClassName(testClass)[0]);
});
}
}
});
describe('ID handeling and generation', () => {
it('should use the supplied id without overriding', () => {
const id = '12345';
const wrapper = mountWithContext(
<Dialog id={id} open={true} />
);
assert.strictEqual(wrapper.prop('id'), id, 'should use provided id');
});
// there should be a test to make sure that the ID's are auto generated
// but I can't work out how to get deep enough into the tree to get at the data
// I'm stuck at RenderToLayer
});
});
|
src/svg-icons/action/settings-cell.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsCell = (props) => (
<SvgIcon {...props}>
<path d="M7 24h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM16 .01L8 0C6.9 0 6 .9 6 2v16c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V2c0-1.1-.9-1.99-2-1.99zM16 16H8V4h8v12z"/>
</SvgIcon>
);
ActionSettingsCell = pure(ActionSettingsCell);
ActionSettingsCell.displayName = 'ActionSettingsCell';
ActionSettingsCell.muiName = 'SvgIcon';
export default ActionSettingsCell;
|
ContosoUniversity.Spa.React/ClientApp/src/components/common/Footer.js | alimon808/contoso-university | import React from 'react';
export default function () {
return (
<footer className="container">
<p>© 2018 - Contoso University</p>
</footer>
);
} |
desktop-application/test/components/Counter.spec.js | santosh-surya/pcb-cnc-machine | /* eslint no-unused-expressions: 0 */
import { expect } from 'chai';
import { spy } from 'sinon';
import React from 'react';
import {
renderIntoDocument,
scryRenderedDOMComponentsWithTag,
findRenderedDOMComponentWithClass,
Simulate
} from 'react-addons-test-utils';
import Counter from '../../app/components/Counter';
function setup() {
const actions = {
increment: spy(),
incrementIfOdd: spy(),
incrementAsync: spy(),
decrement: spy()
};
const component = renderIntoDocument(<Counter counter={1} {...actions} />);
return {
component,
actions,
buttons: scryRenderedDOMComponentsWithTag(component, 'button').map(button => button),
p: findRenderedDOMComponentWithClass(component, 'counter')
};
}
describe('Counter component', () => {
it('should display count', () => {
const { p } = setup();
expect(p.textContent).to.match(/^1$/);
});
it('first button should call increment', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[0]);
expect(actions.increment.called).to.be.true;
});
it('second button should call decrement', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[1]);
expect(actions.decrement.called).to.be.true;
});
it('third button should call incrementIfOdd', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[2]);
expect(actions.incrementIfOdd.called).to.be.true;
});
it('fourth button should call incrementAsync', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[3]);
expect(actions.incrementAsync.called).to.be.true;
});
});
|
packages/material-ui-icons/src/BorderInner.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let BorderInner = props =>
<SvgIcon {...props}>
<path d="M3 21h2v-2H3v2zm4 0h2v-2H7v2zM5 7H3v2h2V7zM3 17h2v-2H3v2zM9 3H7v2h2V3zM5 3H3v2h2V3zm12 0h-2v2h2V3zm2 6h2V7h-2v2zm0-6v2h2V3h-2zm-4 18h2v-2h-2v2zM13 3h-2v8H3v2h8v8h2v-8h8v-2h-8V3zm6 18h2v-2h-2v2zm0-4h2v-2h-2v2z" />
</SvgIcon>;
BorderInner = pure(BorderInner);
BorderInner.muiName = 'SvgIcon';
export default BorderInner;
|
docs-ui/components/confirm.stories.js | beeftornado/sentry | import React from 'react';
import {withInfo} from '@storybook/addon-info';
import {action} from '@storybook/addon-actions';
import Confirm from 'app/components/confirm';
import Button from 'app/components/button';
export default {
title: 'Core/Buttons/Confirm',
};
export const _Confirm = withInfo({
text:
'Component whose child is rendered as the "action" component that when clicked opens the "Confirm Modal"',
propTablesExclude: [Button],
})(() => (
<div>
<Confirm onConfirm={action('confirmed')} message="Are you sure you want to do this?">
<Button priority="primary">Confirm on Button click</Button>
</Confirm>
</div>
));
|
src/Thumbnail.js | aparticka/react-bootstrap | import React from 'react';
import classSet from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import SafeAnchor from './SafeAnchor';
const Thumbnail = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
alt: React.PropTypes.string,
href: React.PropTypes.string,
src: React.PropTypes.string
},
getDefaultProps() {
return {
bsClass: 'thumbnail'
};
},
render() {
let classes = this.getBsClassSet();
if(this.props.href) {
return (
<SafeAnchor {...this.props} href={this.props.href} className={classSet(this.props.className, classes)}>
<img src={this.props.src} alt={this.props.alt} />
</SafeAnchor>
);
}
else {
if(this.props.children) {
return (
<div {...this.props} className={classSet(this.props.className, classes)}>
<img src={this.props.src} alt={this.props.alt} />
<div className="caption">
{this.props.children}
</div>
</div>
);
}
else {
return (
<div {...this.props} className={classSet(this.props.className, classes)}>
<img src={this.props.src} alt={this.props.alt} />
</div>
);
}
}
}
});
export default Thumbnail;
|
0020-flowtype/app/src/index.js | davidwparker/programmingtil-react | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
tests/Formsy-spec.js | christianalfoni/formsy-react | import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Formsy from './..';
import TestInput from './utils/TestInput';
import TestInputHoc from './utils/TestInputHoc';
import immediate from './utils/immediate';
import sinon from 'sinon';
export default {
'Setting up a form': {
'should expose the users DOM node through an innerRef prop': function (test) {
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInputHoc name="name" innerRef={(c) => { this.name = c; }} />
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = form.name;
test.equal(input.methodOnWrappedInstance('foo'), 'foo');
test.done();
},
'should render a form into the document': function (test) {
const form = TestUtils.renderIntoDocument(<Formsy.Form></Formsy.Form>);
test.equal(ReactDOM.findDOMNode(form).tagName, 'FORM');
test.done();
},
'should set a class name if passed': function (test) {
const form = TestUtils.renderIntoDocument( <Formsy.Form className="foo"></Formsy.Form>);
test.equal(ReactDOM.findDOMNode(form).className, 'foo');
test.done();
},
'should allow for null/undefined children': function (test) {
let model = null;
const TestForm = React.createClass({
render() {
return (
<Formsy.Form onSubmit={(formModel) => (model = formModel)}>
<h1>Test</h1>
{ null }
{ undefined }
<TestInput name="name" value={ 'foo' } />
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
immediate(() => {
TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
test.deepEqual(model, {name: 'foo'});
test.done();
});
},
'should allow for inputs being added dynamically': function (test) {
const inputs = [];
let forceUpdate = null;
let model = null;
const TestForm = React.createClass({
componentWillMount() {
forceUpdate = this.forceUpdate.bind(this);
},
render() {
return (
<Formsy.Form onSubmit={(formModel) => (model = formModel)}>
{inputs}
</Formsy.Form>);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
// Wait before adding the input
setTimeout(() => {
inputs.push(<TestInput name="test" value="" key={inputs.length}/>);
forceUpdate(() => {
// Wait for next event loop, as that does the form
immediate(() => {
TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
test.ok('test' in model);
test.done();
});
});
}, 10);
},
'should allow dynamically added inputs to update the form-model': function (test) {
const inputs = [];
let forceUpdate = null;
let model = null;
const TestForm = React.createClass({
componentWillMount() {
forceUpdate = this.forceUpdate.bind(this);
},
render() {
return (
<Formsy.Form onSubmit={(formModel) => (model = formModel)}>
{inputs}
</Formsy.Form>);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
// Wait before adding the input
immediate(() => {
inputs.push(<TestInput name="test" key={inputs.length}/>);
forceUpdate(() => {
// Wait for next event loop, as that does the form
immediate(() => {
TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'foo'}});
TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
test.equal(model.test, 'foo');
test.done();
});
});
});
},
'should allow a dynamically updated input to update the form-model': function (test) {
let forceUpdate = null;
let model = null;
const TestForm = React.createClass({
componentWillMount() {
forceUpdate = this.forceUpdate.bind(this);
},
render() {
const input = <TestInput name="test" value={this.props.value} />;
return (
<Formsy.Form onSubmit={(formModel) => (model = formModel)}>
{input}
</Formsy.Form>);
}
});
let form = TestUtils.renderIntoDocument(<TestForm value="foo"/>);
// Wait before changing the input
immediate(() => {
form = TestUtils.renderIntoDocument(<TestForm value="bar"/>);
forceUpdate(() => {
// Wait for next event loop, as that does the form
immediate(() => {
TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
test.equal(model.test, 'bar');
test.done();
});
});
});
}
},
'validations': {
'should run when the input changes': function (test) {
const runRule = sinon.spy();
const notRunRule = sinon.spy();
Formsy.addValidationRule('runRule', runRule);
Formsy.addValidationRule('notRunRule', notRunRule);
const form = TestUtils.renderIntoDocument(
<Formsy.Form>
<TestInput name="one" validations="runRule" value="foo"/>
</Formsy.Form>
);
const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
test.equal(runRule.calledWith({one: 'bar'}, 'bar', true), true);
test.equal(notRunRule.called, false);
test.done();
},
'should allow the validation to be changed': function (test) {
const ruleA = sinon.spy();
const ruleB = sinon.spy();
Formsy.addValidationRule('ruleA', ruleA);
Formsy.addValidationRule('ruleB', ruleB);
class TestForm extends React.Component {
constructor(props) {
super(props);
this.state = {rule: 'ruleA'};
}
changeRule() {
this.setState({
rule: 'ruleB'
});
}
render() {
return (
<Formsy.Form>
<TestInput name="one" validations={this.state.rule} value="foo"/>
</Formsy.Form>
);
}
}
const form = TestUtils.renderIntoDocument(<TestForm/>);
form.changeRule();
const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true);
test.done();
},
'should invalidate a form if dynamically inserted input is invalid': function (test) {
const isInValidSpy = sinon.spy();
class TestForm extends React.Component {
constructor(props) {
super(props);
this.state = {showSecondInput: false};
}
addInput() {
this.setState({
showSecondInput: true
});
}
render() {
return (
<Formsy.Form ref="formsy" onInvalid={isInValidSpy}>
<TestInput name="one" validations="isEmail" value="foo@bar.com"/>
{
this.state.showSecondInput ?
<TestInput name="two" validations="isEmail" value="foo@bar"/>
:
null
}
</Formsy.Form>
);
}
}
const form = TestUtils.renderIntoDocument(<TestForm/>);
test.equal(form.refs.formsy.state.isValid, true);
form.addInput();
immediate(() => {
test.equal(isInValidSpy.called, true);
test.done();
});
},
'should validate a form when removing an invalid input': function (test) {
const isValidSpy = sinon.spy();
class TestForm extends React.Component {
constructor(props) {
super(props);
this.state = {showSecondInput: true};
}
removeInput() {
this.setState({
showSecondInput: false
});
}
render() {
return (
<Formsy.Form ref="formsy" onValid={isValidSpy}>
<TestInput name="one" validations="isEmail" value="foo@bar.com"/>
{
this.state.showSecondInput ?
<TestInput name="two" validations="isEmail" value="foo@bar"/>
:
null
}
</Formsy.Form>
);
}
}
const form = TestUtils.renderIntoDocument(<TestForm/>);
test.equal(form.refs.formsy.state.isValid, false);
form.removeInput();
immediate(() => {
test.equal(isValidSpy.called, true);
test.done();
});
},
'runs multiple validations': function (test) {
const ruleA = sinon.spy();
const ruleB = sinon.spy();
Formsy.addValidationRule('ruleA', ruleA);
Formsy.addValidationRule('ruleB', ruleB);
const form = TestUtils.renderIntoDocument(
<Formsy.Form>
<TestInput name="one" validations="ruleA,ruleB" value="foo" />
</Formsy.Form>
);
const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
test.equal(ruleA.calledWith({one: 'bar'}, 'bar', true), true);
test.equal(ruleB.calledWith({one: 'bar'}, 'bar', true), true);
test.done();
}
},
'should not trigger onChange when form is mounted': function (test) {
const hasChanged = sinon.spy();
const TestForm = React.createClass({
render() {
return <Formsy.Form onChange={hasChanged}></Formsy.Form>;
}
});
TestUtils.renderIntoDocument(<TestForm/>);
test.equal(hasChanged.called, false);
test.done();
},
'should trigger onChange once when form element is changed': function (test) {
const hasChanged = sinon.spy();
const form = TestUtils.renderIntoDocument(
<Formsy.Form onChange={hasChanged}>
<TestInput name="foo"/>
</Formsy.Form>
);
TestUtils.Simulate.change(TestUtils.findRenderedDOMComponentWithTag(form, 'INPUT'), {target: {value: 'bar'}});
test.equal(hasChanged.calledOnce, true);
test.done();
},
'should trigger onChange once when new input is added to form': function (test) {
const hasChanged = sinon.spy();
const TestForm = React.createClass({
getInitialState() {
return {
showInput: false
};
},
addInput() {
this.setState({
showInput: true
})
},
render() {
return (
<Formsy.Form onChange={hasChanged}>
{
this.state.showInput ?
<TestInput name="test"/>
:
null
}
</Formsy.Form>);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
form.addInput();
immediate(() => {
test.equal(hasChanged.calledOnce, true);
test.done();
});
},
'Update a form': {
'should allow elements to check if the form is disabled': function (test) {
const TestForm = React.createClass({
getInitialState() { return { disabled: true }; },
enableForm() { this.setState({ disabled: false }); },
render() {
return (
<Formsy.Form disabled={this.state.disabled}>
<TestInput name="foo"/>
</Formsy.Form>);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(input.isFormDisabled(), true);
form.enableForm();
immediate(() => {
test.equal(input.isFormDisabled(), false);
test.done();
});
},
'should be possible to pass error state of elements by changing an errors attribute': function (test) {
const TestForm = React.createClass({
getInitialState() { return { validationErrors: { foo: 'bar' } }; },
onChange(values) {
this.setState(values.foo ? { validationErrors: {} } : { validationErrors: {foo: 'bar'} });
},
render() {
return (
<Formsy.Form onChange={this.onChange} validationErrors={this.state.validationErrors}>
<TestInput name="foo"/>
</Formsy.Form>);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
// Wait for update
immediate(() => {
const input = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(input.getErrorMessage(), 'bar');
input.setValue('gotValue');
// Wait for update
immediate(() => {
test.equal(input.getErrorMessage(), null);
test.done();
});
});
},
'should trigger an onValidSubmit when submitting a valid form': function (test) {
let isCalled = sinon.spy();
const TestForm = React.createClass({
render() {
return (
<Formsy.Form onValidSubmit={isCalled}>
<TestInput name="foo" validations="isEmail" value="foo@bar.com"/>
</Formsy.Form>);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm);
TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm));
test.equal(isCalled.called,true);
test.done();
},
'should trigger an onInvalidSubmit when submitting an invalid form': function (test) {
let isCalled = sinon.spy();
const TestForm = React.createClass({
render() {
return (
<Formsy.Form onInvalidSubmit={isCalled}>
<TestInput name="foo" validations="isEmail" value="foo@bar"/>
</Formsy.Form>);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const FoundForm = TestUtils.findRenderedComponentWithType(form, TestForm);
TestUtils.Simulate.submit(ReactDOM.findDOMNode(FoundForm));
test.equal(isCalled.called, true);
test.done();
}
},
'value === false': {
'should call onSubmit correctly': function (test) {
const onSubmit = sinon.spy();
const TestForm = React.createClass({
render() {
return (
<Formsy.Form onSubmit={onSubmit}>
<TestInput name="foo" value={false} type="checkbox" />
<button type="submit">Save</button>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
test.equal(onSubmit.calledWith({foo: false}), true);
test.done();
},
'should allow dynamic changes to false': function (test) {
const onSubmit = sinon.spy();
const TestForm = React.createClass({
getInitialState() {
return {
value: true
};
},
changeValue() {
this.setState({
value: false
});
},
render() {
return (
<Formsy.Form onSubmit={onSubmit}>
<TestInput name="foo" value={this.state.value} type="checkbox" />
<button type="submit">Save</button>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
form.changeValue();
TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
test.equal(onSubmit.calledWith({foo: false}), true);
test.done();
},
'should say the form is submitted': function (test) {
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInput name="foo" value={true} type="checkbox" />
<button type="submit">Save</button>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = TestUtils.findRenderedComponentWithType(form, TestInput);
test.equal(input.isFormSubmitted(), false);
TestUtils.Simulate.submit(ReactDOM.findDOMNode(form));
test.equal(input.isFormSubmitted(), true);
test.done();
},
'should be able to reset the form to its pristine state': function (test) {
const TestForm = React.createClass({
getInitialState() {
return {
value: true
};
},
changeValue() {
this.setState({
value: false
});
},
render() {
return (
<Formsy.Form>
<TestInput name="foo" value={this.state.value} type="checkbox" />
<button type="submit">Save</button>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = TestUtils.findRenderedComponentWithType(form, TestInput);
const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form);
test.equal(input.getValue(), true);
form.changeValue();
test.equal(input.getValue(), false);
formsyForm.reset();
test.equal(input.getValue(), true);
test.done();
},
'should be able to reset the form using custom data': function (test) {
const TestForm = React.createClass({
getInitialState() {
return {
value: true
};
},
changeValue() {
this.setState({
value: false
});
},
render() {
return (
<Formsy.Form>
<TestInput name="foo" value={this.state.value} type="checkbox" />
<button type="submit">Save</button>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = TestUtils.findRenderedComponentWithType(form, TestInput);
const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form);
test.equal(input.getValue(), true);
form.changeValue();
test.equal(input.getValue(), false);
formsyForm.reset({
foo: 'bar'
});
test.equal(input.getValue(), 'bar');
test.done();
}
},
'should be able to reset the form to empty values': function (test) {
const TestForm = React.createClass({
render() {
return (
<Formsy.Form>
<TestInput name="foo" value="42" type="checkbox" />
<button type="submit">Save</button>
</Formsy.Form>
);
}
});
const form = TestUtils.renderIntoDocument(<TestForm/>);
const input = TestUtils.findRenderedComponentWithType(form, TestInput);
const formsyForm = TestUtils.findRenderedComponentWithType(form, Formsy.Form);
formsyForm.reset({
foo: ''
});
test.equal(input.getValue(), '');
test.done();
},
'.isChanged()': {
'initially returns false': function (test) {
const hasOnChanged = sinon.spy();
const form = TestUtils.renderIntoDocument(
<Formsy.Form onChange={hasOnChanged}>
<TestInput name="one" value="foo" />
</Formsy.Form>
);
test.equal(form.isChanged(), false);
test.equal(hasOnChanged.called, false);
test.done();
},
'returns true when changed': function (test) {
const hasOnChanged = sinon.spy();
const form = TestUtils.renderIntoDocument(
<Formsy.Form onChange={hasOnChanged}>
<TestInput name="one" value="foo" />
</Formsy.Form>
);
const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
test.equal(form.isChanged(), true);
test.equal(hasOnChanged.calledWith({one: 'bar'}), true);
test.done();
},
'returns false if changes are undone': function (test) {
const hasOnChanged = sinon.spy();
const form = TestUtils.renderIntoDocument(
<Formsy.Form onChange={hasOnChanged}>
<TestInput name="one" value="foo" />
</Formsy.Form>
);
const input = TestUtils.findRenderedDOMComponentWithTag(form, 'input');
TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'bar'}});
test.equal(hasOnChanged.calledWith({one: 'bar'}, true), true);
TestUtils.Simulate.change(ReactDOM.findDOMNode(input), {target: {value: 'foo'}});
test.equal(form.isChanged(), false);
test.equal(hasOnChanged.calledWith({one: 'foo'}, false), true);
test.done();
}
}
};
|
packages/material-ui-icons/src/People.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z" /></g>
, 'People');
|
src/TabPane.js | jontewks/react-bootstrap | import React from 'react';
import deprecationWarning from './utils/deprecationWarning';
import Tab from './Tab';
const TabPane = React.createClass({
componentWillMount() {
deprecationWarning(
'TabPane', 'Tab',
'https://github.com/react-bootstrap/react-bootstrap/pull/1091'
);
},
render() {
return (
<Tab {...this.props} />
);
}
});
export default TabPane;
|
src/server.js | lolilukia/Personal-gallery | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
const server = global.server = express();
server.set('port', (process.env.PORT || 5000));
server.use(express.static(path.join(__dirname, 'public')));
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '' };
const css = [];
const context = {
onInsertCss: value => css.push(value),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(server.get('port'), () => {
/* eslint-disable no-console */
console.log('The server is running at http://localhost:' + server.get('port'));
if (process.send) {
process.send('online');
}
});
|
packages/wix-style-react/src/MessageBox/docs/AlertExamples/Scrollable.js | wix/wix-style-react | /* eslint-disable react/prop-types */
import React from 'react';
import { MessageBoxFunctionalLayout } from 'wix-style-react';
export default () => (
<MessageBoxFunctionalLayout
title="Interruption Message"
confirmText="Action"
maxHeight="200px"
theme="blue"
dataHook="alert-scrollable"
>
<div>
This is a generic message. No harm done, but really needed to interrupt
you.
</div>
<div>It has multiple lines and limited max height</div>
<div>and some are rows hidden</div>
<div>and some are rows hidden</div>
<div>and some are rows hidden</div>
<div>and some are rows hidden</div>
<div>and some are rows hidden</div>
<div>and some are rows hidden</div>
<div>and some are rows hidden</div>
</MessageBoxFunctionalLayout>
);
|
src/main/script/EntryList.js | krujos/willitconnect | import PropTypes from 'prop-types';
import React from 'react';
import StatefulEntry from './Entry';
const EntryList = (props) => {
const entryNodes = props.data.map(entry => {
return (
<StatefulEntry
key={entry.id}
onSubmit={props.onSubmit}
onChange={props.onChange}
{...entry}
/>
);
}).reverse();
return (
<div className="entryList">
{entryNodes}
</div>
);
};
export default EntryList;
EntryList.propTypes = {
data: PropTypes.array.isRequired,
onChange: PropTypes.func,
onSubmit: PropTypes.func,
};
EntryList.defaultProps = {
data: [],
}; |
js/App/Components/Schedule/SubViews/TextRowWrapper.js | telldus/telldus-live-mobile-v3 | /**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Telldus Live! app is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*/
// @flow
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import { View } from '../../../../BaseComponents';
type Props = {
children: string,
style?: Object,
appLayout: Object,
};
export default class TextRowWrapper extends View<null, Props, null> {
static propTypes = {
children: PropTypes.node.isRequired,
style: PropTypes.object,
};
render(): React$Element<any> {
const { children, style, appLayout } = this.props;
const defaultStyle = this._getDefaultStyle(appLayout);
return (
<View style={[defaultStyle, style]}>
{children}
</View>
);
}
_getDefaultStyle = (appLayout: Object): Object => {
const { height, width } = appLayout;
const isPortrait = height > width;
const deviceWidth = isPortrait ? width : height;
return {
justifyContent: 'center',
backgroundColor: 'transparent',
alignItems: 'flex-start',
width: deviceWidth * 0.586666667,
paddingLeft: deviceWidth * 0.101333333,
paddingRight: 10,
paddingVertical: 5,
};
};
}
|
client/containers/shell.js | vidi-insights/vidi-dashboard | 'use strict'
import React from 'react'
import {connect} from 'react-redux'
import {Header, Footer} from '../components/index'
export const Shell = React.createClass({
render () {
const handleToggle = this.handleToggle
const {children, isLoggedIn} = this.props
return (
<div className="shell">
<Header showMenu={isLoggedIn}/>
<div className={'page-wrapper'}>{children}</div>
<Footer />
</div>
)
}
})
export default connect((state) => {
return {
isLoggedIn: state.auth.isLoggedIn
}
})(Shell)
|
docs/app/Examples/elements/Button/GroupVariations/ButtonGroupEqualWidthExample.js | jcarbo/stardust | import React from 'react'
import { Button, Divider } from 'stardust'
const ButtonGroupEqualWidthExample = () => (
<div>
<Button.Group widths='5'>
<Button>Overview</Button>
<Button>Specs</Button>
<Button>Warranty</Button>
<Button>Reviews</Button>
<Button>Support</Button>
</Button.Group>
<Divider />
<Button.Group widths='3'>
<Button>Overview</Button>
<Button>Specs</Button>
<Button>Support</Button>
</Button.Group>
</div>
)
export default ButtonGroupEqualWidthExample
|
docs/app/Examples/modules/Embed/States/index.js | mohammed88/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const EmbedStatesExamples = () => (
<ExampleSection title='States'>
<ComponentExample
title='Active'
description='An embed can be active.'
examplePath='modules/Embed/States/EmbedExampleActive'
/>
</ExampleSection>
)
export default EmbedStatesExamples
|
ui/src/js/selfPlantOverview/SelfPlantOverviewPage.js | Dica-Developer/weplantaforest | import axios from 'axios';
import counterpart from 'counterpart';
import React, { Component } from 'react';
import { Map, Marker, TileLayer, useMap } from 'react-leaflet';
import { browserHistory } from 'react-router';
import NotificationSystem from 'react-notification-system';
import Notification from '../common/components/Notification';
import DateField from '../common/components/DateField';
import IconButton from '../common/components/IconButton';
import FileChooser from '../common/components/FileChooser';
import { getTextForSelectedLanguage } from '../common/language/LanguageHelper';
require('./selfPlantOverview.less');
export default class SelfPlantOverviewPage extends Component {
constructor() {
super();
this.state = {
edit: false,
showEditMap: true,
selfPlantData: {
latitude: 0,
longitude: 0,
plantedOn: new Date().getTime(),
description: '',
amount: 1,
imageName: '',
treeTypeId: 1,
treeTypeName: '',
},
imageFile: null,
treeTypes: [],
treePosition: [51.499807, 11.956521],
trees: [],
myTree: { latitude: 0, longitude: 0 },
treeId: null,
allowEdit: localStorage.getItem('isAdmin') === 'true',
};
}
componentDidMount() {
var that = this;
// this is a little hack to assure both leaflet maps(for edit and non-edit) are rendered correctly
// on initial rendering both maps have to be displayed so that leaflet can render the correct tiles
// surprisingly 1ms is enough...
setTimeout(() => {
that.setState({showEditMap: false});
}, 1);
axios
.get('http://localhost:8081/treeTypes')
.then(function (response) {
var result = response.data;
result.splice(result.length - 1, 0, result.splice(0, 1)[0]);
that.setState({ treeTypes: result });
})
.catch(function (response) {
if (response instanceof Error) {
console.error('Error', response.message);
} else {
console.error(response.data);
console.error(response.status);
console.error(response.headers);
console.error(response.config);
}
});
axios
.get('http://localhost:8081/trees/selfPlanted')
.then(function (response) {
var result = response.data;
that.setState({ trees: result });
})
.catch(function (error) {
that.refs.notification.handleError(error);
});
that.getMyTree();
}
getMyTree() {
var that = this;
axios
.get('http://localhost:8081/tree/' + this.props.params.treeId)
.then(function (response) {
var result = response.data;
that.setState({
myTree: {
latitude: result.latitude,
longitude: result.longitude,
},
selfPlantData: {
latitude: result.latitude,
longitude: result.longitude,
plantedOn: result.plantedOn,
description: result.description,
amount: result.amount,
imageName: result.imagePath,
treeTypeId: result.treeType.id,
treeTypeName: result.treeType.name,
},
treeId: result.id,
allowEdit: that.state.allowEdit || localStorage.getItem('username') === result.owner.name,
treeOwner: result.owner.name,
});
that.refs.description.value = result.description;
})
.catch(function (error) {
that.refs.notification.handleError(error);
});
}
updatePlantedOn(value) {
this.state.selfPlantData.plantedOn = value;
this.forceUpdate();
}
updateAmount(event) {
this.state.selfPlantData.amount = event.target.value;
this.forceUpdate();
}
updateImage(imageName, file) {
this.state.selfPlantData.imageName = imageName;
this.state.imageFile = file;
this.forceUpdate();
}
updateTreeType(event) {
this.state.selfPlantData.treeTypeId = event.target.value;
this.forceUpdate();
}
sendSelfPlantedTree() {
if (localStorage.getItem('jwt') == null || localStorage.getItem('jwt') == '') {
this.refs.notification.addNotification(counterpart.translate('NO_AUTH_USER_TITLE'), counterpart.translate('NO_AUTH_USER_TEXT'), 'error');
} else {
var that = this;
var config = {
headers: {
'X-AUTH-TOKEN': localStorage.getItem('jwt'),
},
};
this.state.selfPlantData.description = this.refs.description.value;
axios
.put('http://localhost:8081/plantSelf?id=' + this.state.treeId, this.state.selfPlantData, config)
.then(function (response) {
if (that.state.imageFile != null) {
var data = new FormData();
data.append('treeId', response.data);
data.append('file', that.state.imageFile);
axios
.post('http://localhost:8081/plantSelf/upload', data, config)
.then(function (response) {
that.refs.notification.addNotification(counterpart.translate('PLANTING_CREATED'), '', 'success');
that.setState({ edit: false, showEditMap: false });
that.forceUpdate();
location.reload();
})
.catch(function (response) {
if (response instanceof Error) {
console.error('Error', response.message);
} else {
console.error(response.data);
console.error(response.status);
console.error(response.headers);
console.error(response.config);
}
that.setState({ edit: false, showEditMap: false });
});
} else {
that.refs.notification.addNotification(counterpart.translate('PLANTING_CREATED'), '', 'success');
that.setState({ edit: false, showEditMap: false });
location.reload();
}
})
.catch(function (response) {
that.refs.notification.addNotification(counterpart.translate('ERROR'), counterpart.translate('TRY_AGAIN'), 'error');
if (response instanceof Error) {
console.error('Error', response.message);
} else {
console.error(response.data);
console.error(response.status);
console.error(response.headers);
console.error(response.config);
}
that.setState({ edit: false });
});
}
}
startEdit() {
this.setState({ edit: true, showEditMap: true });
}
updateTreePositionFromMapClick(event) {
if (this.state.edit) {
this.state.selfPlantData.latitude = parseFloat(event.latlng.lat);
this.state.selfPlantData.longitude = parseFloat(event.latlng.lng);
this.state.myTree.latitude = parseFloat(event.latlng.lat);
this.state.myTree.longitude = parseFloat(event.latlng.lng);
this.refs.marker.leafletElement._latlng.lat = event.latlng.lat;
this.refs.marker.leafletElement._latlng.lng = event.latlng.lng;
this.forceUpdate();
}
}
updateTreePositionFromMarkerDrag() {
if (this.state.edit) {
this.state.selfPlantData.latitude = parseFloat(this.refs.marker.leafletElement._latlng.lat);
this.state.selfPlantData.longitude = parseFloat(this.refs.marker.leafletElement._latlng.lng);
this.state.myTree.latitude = parseFloat(this.refs.marker.leafletElement._latlng.lat);
this.state.myTree.longitude = parseFloat(this.refs.marker.leafletElement._latlng.lng);
this.forceUpdate();
}
}
openDeleteConfirmation() {
this.refs.notificationSystem.addNotification({
title: counterpart.translate('WARNING') + '!',
position: 'tc',
autoDismiss: 0,
message: counterpart.translate('DELETE_SELFPLANTING_CONFIRMATION_TEXT'),
level: 'warning',
children: (
<div className="delete-confirmation align-center">
<button>{counterpart.translate('ABORT')}</button>
<button
onClick={() => {
this.deleteTree();
}}
>
OK
</button>
</div>
),
});
}
deleteTree() {
var config = {
headers: {
'X-AUTH-TOKEN': localStorage.getItem('jwt'),
},
};
var that = this;
axios
.delete('http://localhost:8081/plantSelf?treeId=' + this.state.treeId, config)
.then(function (response) {
browserHistory.push('/user/' + encodeURIComponent(that.state.treeOwner));
})
.catch(function (error) {
that.refs.notification.handleError(error);
});
}
render() {
let that = this;
let myIcon = L.divIcon({ className: 'glyphicon glyphicon-tree-deciduous' });
let myTreeIcon = L.divIcon({ className: 'glyphicon glyphicon-tree-deciduous my-tree' });
var confirmBoxStyle = {
Containers: {
DefaultStyle: {
zIndex: 11000,
},
tc: {
top: '50%',
bottom: 'auto',
margin: '0 auto',
left: '50%',
},
},
};
return (
<div className="container paddingTopBottom15 selfPlantOverview">
<div className="row">
<div className="col-md-12">
<h1>
{counterpart.translate('COMMUNITY_TREE')}
<div className={this.state.allowEdit ? 'delete-btn ' : 'no-display '}>
<IconButton glyphIcon="glyphicon-trash" text="" onClick={this.openDeleteConfirmation.bind(this)} />
</div>
<div className={this.state.allowEdit && !this.state.edit ? '' : 'no-display '}>
<IconButton glyphIcon="glyphicon-pencil" text="" onClick={this.startEdit.bind(this)} />
</div>
</h1>
</div>
</div>
<div className={'row ' + (this.state.edit ? '' : 'no-display')}>
<div className="form-group col-md-4">
<label htmlFor="when">{counterpart.translate('DATE')}:</label>
<DateField id="when" date={this.state.selfPlantData.plantedOn} updateDateValue={this.updatePlantedOn.bind(this)} noFuture="true" />
</div>
<div className="form-group col-md-8">
<label htmlFor="howmuch">
{counterpart.translate('NUMBER')}: {this.state.selfPlantData.amount}
</label>
<input
className="tree-slider"
type="range"
min="1"
max={localStorage.getItem('isAdmin') === 'true' ? 10000 : 10}
value={this.state.selfPlantData.amount}
step="1"
onChange={this.updateAmount.bind(this)}
/>
<br />
<span>{counterpart.translate('HOW_MANY_HINT')}</span>
</div>
</div>
<div className={'row ' + (this.state.edit ? '' : 'no-display')}>
<div className="form-group col-md-4">
<label htmlFor="photo">{counterpart.translate('FOTO')}:</label>
<FileChooser id="photo" updateFile={this.updateImage.bind(this)} />
</div>
<div className="form-group col-md-8">
<label htmlFor="treeType">{counterpart.translate('TREETYPE')}:</label>
<select id="treeType" className="form-control" onChange={this.updateTreeType.bind(this)} ref="select">
{this.state.treeTypes.map(function (treeType, i) {
if (treeType.name != 'Default') {
if (treeType.id === that.state.selfPlantData.treeTypeId) {
return (
<option value={treeType.id} key={i} selected="selected">
{getTextForSelectedLanguage(treeType.name)}
</option>
);
} else {
return (
<option value={treeType.id} key={i}>
{getTextForSelectedLanguage(treeType.name)}
</option>
);
}
} else {
if (treeType.id === that.state.selfPlantData.treeTypeId) {
return (
<option value={treeType.id} key={i} selected="selected">
{counterpart.translate('OTHER')}
</option>
);
} else {
return (
<option value={treeType.id} key={i}>
{counterpart.translate('OTHER')}
</option>
);
}
}
})}
</select>
</div>
</div>
<div className={'row ' + (this.state.showEditMap ? '' : 'no-display')}>
<div className="form-group col-md-4">
<label htmlFor="description">{counterpart.translate('SHORT_DESCRIPTION')}:</label>
<div>
<textarea rows="4" cols="50" ref="description" />
</div>
</div>
<div className="col-md-8">
<label htmlFor="all-self-planted-edit-map">{counterpart.translate('TREE_LOCATION')}:</label>
<Map id="all-self-planted-edit-map" center={[this.state.myTree.latitude, this.state.myTree.longitude]} zoom={10} onClick={this.updateTreePositionFromMapClick.bind(this)} >
<TileLayer url="https://{s}.tile.osm.org/{z}/{x}/{y}.png" attribution='© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' />
<Marker
position={[this.state.myTree.latitude, this.state.myTree.longitude]}
ref="marker"
draggable={this.state.edit}
icon={myTreeIcon}
onDragEnd={this.updateTreePositionFromMarkerDrag.bind(this)}
/>
{this.state.trees.map(function (tree, i) {
if (tree.latitude && tree.longitude) {
if (tree.id != that.props.params.treeId) {
return <Marker key={i} position={[tree.latitude, tree.longitude]} ref={'marker-' + i} icon={myIcon} />;
}
} else {
return '';
}
})}
</Map>
</div>
</div>
<div className={'row ' + (this.state.edit ? '' : 'no-display')}>
<div className="col-md-12 align-left">
<IconButton text="Planzung aktualisieren" glyphIcon="glyphicon-tree-deciduous" onClick={this.sendSelfPlantedTree.bind(this)} />
</div>
</div>
<div className={'row ' + (this.state.edit ? 'no-display' : '')}>
<div className="col-md-4">
<div className={'row ' + (this.state.edit ? 'no-display' : 'no-padding')}>
<div className="col-md-12 center">
<img height="150px" src={'http://localhost:8081/tree/image/' + encodeURIComponent(this.state.selfPlantData.imageName) + '/935/935'} />
</div>
<div className="col-md-12 tree-description"><i>{this.state.selfPlantData.description}</i></div>
<div className="col-md-12"><b>{counterpart.translate('DATE')}: </b> {new Date(this.state.selfPlantData.plantedOn).toLocaleDateString()}</div>
<div className="col-md-12"><b>{counterpart.translate('NUMBER')}: </b>{this.state.selfPlantData.amount}</div>
<div className="col-md-12"><b>{counterpart.translate('TREETYPE')}: </b>{getTextForSelectedLanguage(this.state.selfPlantData.treeTypeName)}</div>
</div>
</div>
<div className="col-md-8">
<Map id="all-self-planted-map" center={[this.state.myTree.latitude, this.state.myTree.longitude]} zoom={10} onClick={this.updateTreePositionFromMapClick.bind(this)} >
<TileLayer url="https://{s}.tile.osm.org/{z}/{x}/{y}.png" attribution='© <a href="https://osm.org/copyright">OpenStreetMap</a> contributors' />
<Marker
position={[this.state.myTree.latitude, this.state.myTree.longitude]}
ref="marker"
draggable={this.state.edit}
icon={myTreeIcon}
onDragEnd={this.updateTreePositionFromMarkerDrag.bind(this)}
/>
{this.state.trees.map(function (tree, i) {
if (tree.latitude && tree.longitude) {
if (tree.id != that.props.params.treeId) {
return <Marker key={i} position={[tree.latitude, tree.longitude]} ref={'marker-' + i} icon={myIcon} />;
}
} else {
return '';
}
})}
</Map>
</div>
</div>
<Notification ref="notification" />
<NotificationSystem ref="notificationSystem" style={confirmBoxStyle} />
</div>
);
}
}
/* vim: set softtabstop=2:shiftwidth=2:expandtab */
|
fields/types/email/EmailField.js | everisARQ/keystone | import Field from '../Field';
import React from 'react';
import { FormInput } from 'elemental';
/*
TODO:
- gravatar
- validate email address
*/
module.exports = Field.create({
displayName: 'EmailField',
renderField () {
return (
<FormInput
name={this.props.path}
ref="focusTarget"
value={this.props.value}
onChange={this.valueChanged}
autoComplete="off"
type="email"
/>
);
},
renderValue () {
return this.props.value ? (
<FormInput noedit href={'mailto:' + this.props.value}>{this.props.value}</FormInput>
) : (
<FormInput noedit>(not set)</FormInput>
);
},
});
|
Examples/TabsExample/src/routes.js | Wolox/react-native-renavigate | import React from 'react';
import { Text, TouchableOpacity } from 'react-native';
import { actionCreators as navigationActions } from 'react-native-renavigate';
import PostDetailContainer from './PostDetailContainer';
import PostListContainer from './PostListContainer';
import EmptyView from './EmptyView';
const navButtonStyle = { padding: 5, color: 'blue' };
const titleStyle = { fontWeight: 'bold' };
export default {
DETAIL: (params) => ({
component: PostDetailContainer,
params,
leftButton: (dispatch) => {
const goBack = () => {
dispatch(navigationActions.pop());
};
return (
<TouchableOpacity onPress={goBack}>
<Text style={navButtonStyle}>Back</Text>
</TouchableOpacity>
);
},
rightButton: () => {
return <Text style={navButtonStyle}>FAV</Text>;
},
title: () => {
return <Text style={[navButtonStyle, titleStyle]}>{ params.title }</Text>;
}
}),
LIST: (params) => ({
component: PostListContainer,
params,
title: () => {
return <Text style={[titleStyle, navButtonStyle]}>YOUR POSTS</Text>;
}
}),
EMPTY_VIEW: (params) => ({
component: EmptyView,
params,
title: () => {
return <Text style={[titleStyle, navButtonStyle]}>EMPTY VIEW</Text>;
}
})
};
|
src/client/components/list/button/FollowButton.js | DBCDK/content-first | import React from 'react';
import {connect} from 'react-redux';
import {getListByIdSelector, CUSTOM_LIST} from '../../../redux/list.reducer';
import {OPEN_MODAL} from '../../../redux/modal.reducer';
import Button from '../../base/Button';
import Icon from '../../base/Icon';
import T from '../../base/T';
import {withFollow} from '../../hoc/Follow';
const getListById = getListByIdSelector();
export const FollowButton = ({
disabled = false,
allowFollow,
isLoggedIn,
isFollowing,
follow,
unFollow,
requireLogin,
className,
style
}) => {
if (!allowFollow) {
return null;
}
return (
<Button
className={className}
disabled={disabled}
type="link2"
style={{
color: isFollowing ? 'var(--de-york)' : 'var(--petroleum)',
textDecoration: 'none',
...style
}}
onClick={() => {
if (!isLoggedIn) {
return requireLogin();
}
if (isFollowing) {
return unFollow();
}
return follow();
}}
data-cy="follow-btn"
>
<span className="align-middle">
<Icon name="playlist_add" className="mr-1 align-middle" />
<T
component="list"
name={isFollowing ? 'followingList' : 'followList'}
/>
</span>
</Button>
);
};
const mapStateToProps = (state, ownProps) => {
const list = getListById(state, {_id: ownProps._id});
return {
allowFollow: list.type === CUSTOM_LIST,
isLoggedIn: state.userReducer.isLoggedIn
};
};
export const mapDispatchToProps = dispatch => ({
requireLogin: () => {
dispatch({
type: OPEN_MODAL,
modal: 'login',
context: {
title: <T component="list" name={'followList'} />,
reason: <T component="list" name={'loginFollowModalDescription'} />
}
});
}
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(withFollow(FollowButton));
|
src/icons/image.js | markdyousef/zen-editor | import React from 'react';
export default ({ ...props }) => {
return (
<svg {...props} width="16" height="16" viewBox="0 0 16 16">
<g>
<path
d="M14.39,2.31H1.61c-0.83,0-1.5,0.68-1.5,1.5v8.41c0,0.83,0.67,1.5,1.5,1.5h12.78c0.49,0,0.93-0.23,1.19-0.6
c0.08-0.09,0.14-0.19,0.18-0.3c0.09-0.18,0.13-0.39,0.13-0.6V3.81C15.89,2.99,15.22,2.31,14.39,2.31z M1.11,3.81
c0-0.27,0.22-0.5,0.5-0.5h12.78c0.28,0,0.5,0.23,0.5,0.5v7.96l-4.01-4.02c-0.14-0.14-0.36-0.15-0.51-0.02L7.96,9.77L5.25,7.08
C5.12,6.95,4.91,6.93,4.76,7.04L1.11,9.8V3.81z M1.61,12.72c-0.28,0-0.5-0.23-0.5-0.5v-1.47l3.84-2.91l2.7,2.68l2.21,2.2H1.61z
M14.39,12.72h-3.46L8.49,10.3l2.1-1.78l4.09,4.1C14.6,12.68,14.5,12.72,14.39,12.72z"
/>
</g>
<g>
<path d="M15.76,12.82c0,0.09-0.03,0.18-0.1,0.25c-0.02,0.02-0.05,0.04-0.08,0.05C15.66,13.03,15.72,12.93,15.76,12.82z" />
</g>
<g>
<path
d="M12.718,7.153c-0.872,0-1.582-0.71-1.582-1.583c0-0.873,0.71-1.583,1.582-1.583c0.873,0,1.583,0.71,1.583,1.583
C14.301,6.443,13.591,7.153,12.718,7.153z M12.718,4.738c-0.459,0-0.832,0.374-0.832,0.833c0,0.459,0.373,0.833,0.832,0.833
s0.833-0.374,0.833-0.833C13.551,5.111,13.177,4.738,12.718,4.738z"
/>
</g>
</svg>
);
};
|
actor-apps/app-web/src/app/components/ActivitySection.react.js | liqk2014/actor-platform | import React from 'react';
import classNames from 'classnames';
import { ActivityTypes } from 'constants/ActorAppConstants';
//import ActivityActionCreators from 'actions/ActivityActionCreators';
import ActivityStore from 'stores/ActivityStore';
import UserProfile from 'components/activity/UserProfile.react';
import GroupProfile from 'components/activity/GroupProfile.react';
const getStateFromStores = () => {
return {
activity: ActivityStore.getActivity(),
isOpen: ActivityStore.isOpen()
};
};
class ActivitySection extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
ActivityStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
ActivityStore.removeChangeListener(this.onChange);
}
render() {
const activity = this.state.activity;
if (activity !== null) {
const activityClassName = classNames('activity', {
'activity--shown': this.state.isOpen
});
let activityBody;
switch (activity.type) {
case ActivityTypes.USER_PROFILE:
activityBody = <UserProfile user={activity.user}/>;
break;
case ActivityTypes.GROUP_PROFILE:
activityBody = <GroupProfile group={activity.group}/>;
break;
default:
}
return (
<section className={activityClassName}>
{activityBody}
</section>
);
} else {
return null;
}
}
onChange = () => {
this.setState(getStateFromStores());
};
}
export default ActivitySection;
|
src/components/Team.js | ccoode/timer | import React from 'react'
import classNames from 'classnames'
import Meta from './Meta'
import Control from './Control'
import Clock from './Clock'
function Team(props) {
const divClass = classNames({
team: true,
hide: props.hide,
})
return (
<div className={divClass}>
<Meta
right={props.right}
teamName={props.name}
thought={props.thought}
hide={props.hideAll}
/>
<Clock timeout={props.timeout} />
<Control controlFns={props.controlFns} running={props.running} end={props.end} />
</div>
)
}
export default Team
|
client/src/app/components/ribbon/SmallBreadcrumbs.js | zraees/sms-project | import React from 'react'
import {connect} from 'react-redux'
import Msg from '../i18n/Msg'
class SmallBreadcrumbs extends React.Component {
render() {
return (
<ol className="breadcrumb">
{
this.props.items.map((it, idx)=> (
<li key={it + idx}><Msg phrase={it}/></li>
))
}
</ol>
)
}
}
const mapStateToProps = (state, ownProps) => {
const {navigation, routing}= state;
const route = routing.locationBeforeTransitions.pathname;
const titleReducer = (chain, it)=> {
if (it.route == route) {
chain.push(it.title)
} else if (it.items) {
it.items.reduce(titleReducer, chain);
}
return chain
};
const items = navigation.items.reduce(titleReducer, ['Home']);
return {items}
};
export default connect(mapStateToProps)(SmallBreadcrumbs) |
front/app/app/rh-components/rh-Panel.js | nudoru/React-Starter-2-app | import React from 'react';
const Panel = (props) => {
let panelClass = ['rh-panel'],
header, footer;
if (props.title || props.icon || props.utilityButtons) {
header = <PanelHeader {...props}/>;
}
if (props.footerNote || props.actionButtons) {
footer = <PanelFooter {...props}/>;
}
return (<section className={panelClass.join(' ')}>
{header}
<div className="rh-panel-content">
{props.children}
</div>
{footer}
</section>);
};
export default Panel;
export const PanelHeader = ({title, icon, utilityButtons}) => {
let headerIcon = icon ?
<div className="rh-panel-header-icon"><i className={'fa fa-' + icon}/>
</div> : null;
// TODO apply key to utility buttons
return (<div className="rh-panel-header">
{headerIcon}
<div className="rh-panel-header-label">
<h1>{title}</h1>
</div>
<div className="rh-panel-header-buttons">
{utilityButtons ? utilityButtons.map(b => b) : null}
</div>
</div>);
};
export const PanelFooter = ({footerNote, actionButtons}) => {
// TODO apply key to action buttons
return (<div className="rh-panel-footer">
<h1>{footerNote}</h1>
<div className="rh-panel-footer-buttons">
{actionButtons ? actionButtons.map(b => b) : null}
</div>
</div>);
}; |
components/selectionBlock/selectionBlock.js | Travix-International/travix-ui-kit | import classnames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { getDataAttributes } from '../_helpers';
const SelectionBlock = (props) => {
const {
align = 'center',
children,
className,
dataAttrs = {},
icon,
logo,
logoLabel,
subtitle,
title,
type = 'horizontal',
} = props;
const logoSection = !logo ? null : (
<div className="ui-selection-block__logo">
<span className="ui-selection-block__logo-label">
{logoLabel}
</span>
{logo}
</div>
);
const iconSection = !icon ? null : (
<div className="ui-selection-block__icon">
{icon}
</div>
);
const classes = classnames(className, 'ui-selection-block', {
'ui-selection-block_vertical': type === 'vertical',
[`ui-selection-block_align-${align}`]: true,
});
return (
<div
className={classes}
{...getDataAttributes(dataAttrs)}
>
<div className="ui-selection-block__section">
<header className="ui-selection-block__header">
<div className="ui-selection-block__titles">
{iconSection}
<h2 className="ui-selection-block__title">
{title}
</h2>
<h5 className="ui-selection-block__subtitle">
{subtitle}
</h5>
</div>
{logoSection}
</header>
<div className="ui-selection-block__body">
{children}
</div>
</div>
{logoSection}
</div>
);
};
SelectionBlock.propTypes = {
/**
* The title section align.
*/
align: PropTypes.oneOf(['start', 'center', 'end']),
/**
* Content that will be wrapped by SelectionBlock
*/
children: PropTypes.node,
/**
* Specify a CSS class
*/
className: PropTypes.string,
/**
* Data attribute. You can use it to set up any custom data-* attribute.
*/
dataAttrs: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.object,
]),
/**
* The icon for title section.
*/
icon: PropTypes.node,
/**
* The selection block logo.
*/
logo: PropTypes.node,
/**
* The logo label.
*/
logoLabel: PropTypes.string,
/**
* The selection block subtitle.
*/
subtitle: PropTypes.string,
/**
* The selection block title.
*/
title: PropTypes.string,
/**
* The selection block type.
*/
type: PropTypes.oneOf(['vertical', 'horizontal']),
};
export default SelectionBlock;
|
client/src/components/dashboard/profile/utils/trash-look-three.js | mikelearning91/seeme-starter | import React, { Component } from 'react';
import Modal from 'react-modal';
import MdDelete from 'react-icons/lib/md/delete';
const cookie = require('react-cookie')
const axios = require('axios');
class TrashLookThree extends React.Component {
constructor(props) {
super(props);
this.trashLook = this.trashLook.bind(this);
}
trashLook() {
const user = cookie.load('user');
const emailQuery = user.email;
const lookId = user.looks[2]._id;
console.log(lookId)
axios.put('https://seemedate.herokuapp.com/api/see/delete-look', {
emailQuery: emailQuery,
lookId: lookId
},
{ headers: { Authorization: cookie.load('token') } })
.then((response) => {
cookie.save('token', response.data.token, { path: '/' });
cookie.save('user', response.data.user, { path: '/' });
this.props.remove();
// window.location.reload()
})
.catch((error) => {
console.log(error);
});
}
render() {
return (
<div>
<button className="trash-look" onClick={this.trashLook}><MdDelete /></button>
</div>
);
}
}
export default TrashLookThree; |
src/routes.js | RockingChewee/react-redux-building-applications | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './components/App';
import HomePage from './components/home/HomePage';
import AboutPage from './components/about/AboutPage';
import CoursesPage from './components/course/CoursesPage';
// Linting warning is thrown here due to the fact that ManageCoursePage is exported as a default export (for app) and as a named export (for testing).
import ManageCoursePage from './components/course/ManageCoursePage'; //eslint-disable-line import/no-named-as-default
export default (
/* Always load the App component and then pass the nested items as "children" to the App based on the routing. */
<Route path="/" component={App}>
{/* If someone goes to /, we will load the HomePage. */}
<IndexRoute component={HomePage} />
<Route path="courses" component={CoursesPage} />
<Route path="course" component={ManageCoursePage} />
<Route path="course/:id" component={ManageCoursePage} />
<Route path="about" component={AboutPage} />
</Route>
);
|
src/views/HomeView/HomeView.js | oldsaratov/postcards-spa | import _ from 'lodash';
import React from 'react';
import { connect } from 'react-redux';
import postcardsActions from 'redux/modules/postcards/actions';
import PostcardBox from 'components/PostcardBox/PostcardBox';
const mapStateToProps = (state) => ({
postcards: state.postcards
});
export class HomeView extends React.Component {
constructor (props) {
super(props);
}
componentDidMount () {
const { dispatch } = this.props;
dispatch(postcardsActions.fetch());
}
render () {
let { postcards } = this.props;
return (
<div className='container text-center'>
<div className='row'>
<div className='col-xs-2 col-xs-offset-5'>
{ _.map(postcards.items, postcard => <PostcardBox key={postcard.id} postcard={postcard} />) }
</div>
</div>
</div>
);
}
}
HomeView.propTypes = {
dispatch: React.PropTypes.func.isRequired,
postcards: React.PropTypes.object.isRequired
};
export default connect(mapStateToProps)(HomeView);
|
src/i18n/translate.spec.js | matteolc/admin-on-rest | import assert from 'assert';
import React from 'react';
import translate from './translate';
describe('translate HOC', () => {
it('should conserve base component default props', () => {
const Component = () => <div />;
Component.defaultProps = { foo: 'bar' };
const TranslatedComponent = translate(Component);
assert.deepEqual(TranslatedComponent.defaultProps, { foo: 'bar' });
});
});
|
monkey/monkey_island/cc/ui/src/components/report-components/zerotrust/EventsModal.js | guardicore/monkey | import React from 'react';
import {Modal} from 'react-bootstrap';
import EventsTimeline from './EventsTimeline';
import * as PropTypes from 'prop-types';
import saveJsonToFile from '../../utils/SaveJsonToFile';
import EventsModalButtons from './EventsModalButtons';
import AuthComponent from '../../AuthComponent';
import Pluralize from 'pluralize';
import SkippedEventsTimeline from './SkippedEventsTimeline';
const FINDING_EVENTS_URL = '/api/zero-trust/finding-event/';
export default class EventsModal extends AuthComponent {
constructor(props) {
super(props);
}
render() {
return (
<div>
<Modal show={this.props.showEvents} onHide={() => this.props.hideCallback()}>
<Modal.Body>
<h3>
<div className="text-center">Events</div>
</h3>
<hr/>
<p>
There {Pluralize('is', this.props.event_count)} {
<div className={'badge badge-primary'}>{this.props.event_count}</div>
} {Pluralize('event', this.props.event_count)} associated with this finding. {
<div className={'badge badge-primary'}>
{this.props.latest_events.length + this.props.oldest_events.length}
</div>
} {Pluralize('is', this.props.event_count)} displayed below. All events can be exported using the Export button.
</p>
{this.props.event_count > 5 ? this.renderButtons() : null}
<EventsTimeline events={this.props.oldest_events}/>
{this.props.event_count > this.props.latest_events.length+this.props.oldest_events.length ?
this.renderSkippedEventsTimeline() : null}
<EventsTimeline events={this.props.latest_events}/>
{this.renderButtons()}
</Modal.Body>
</Modal>
</div>
);
}
renderSkippedEventsTimeline(){
return <div className={'skipped-events-timeline'}>
<SkippedEventsTimeline
skipped_count={this.props.event_count -
this.props.latest_events.length + this.props.oldest_events.length}/>
</div>
}
renderButtons() {
return <EventsModalButtons
onClickClose={() => this.props.hideCallback()}
onClickExport={() => {
let full_url = FINDING_EVENTS_URL + this.props.finding_id;
this.authFetch(full_url).then(res => res.json()).then(res => {
const dataToSave = res.events_json;
const filename = this.props.exportFilename;
saveJsonToFile(dataToSave, filename);
});
}}/>;
}
}
EventsModal.propTypes = {
showEvents: PropTypes.bool,
events: PropTypes.array,
hideCallback: PropTypes.func
};
|
node_modules/antd/es/transfer/list.js | prodigalyijun/demo-by-antd | import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import { findDOMNode } from 'react-dom';
import classNames from 'classnames';
import Animate from 'rc-animate';
import PureRenderMixin from 'rc-util/es/PureRenderMixin';
import assign from 'object-assign';
import Checkbox from '../checkbox';
import Search from './search';
import Item from './item';
import triggerEvent from '../_util/triggerEvent';
function noop() {}
function isRenderResultPlainObject(result) {
return result && !React.isValidElement(result) && Object.prototype.toString.call(result) === '[object Object]';
}
var TransferList = function (_React$Component) {
_inherits(TransferList, _React$Component);
function TransferList(props) {
_classCallCheck(this, TransferList);
var _this = _possibleConstructorReturn(this, (TransferList.__proto__ || Object.getPrototypeOf(TransferList)).call(this, props));
_this.handleSelect = function (selectedItem) {
var checkedKeys = _this.props.checkedKeys;
var result = checkedKeys.some(function (key) {
return key === selectedItem.key;
});
_this.props.handleSelect(selectedItem, !result);
};
_this.handleFilter = function (e) {
_this.props.handleFilter(e);
if (!e.target.value) {
return;
}
// Manually trigger scroll event for lazy search bug
// https://github.com/ant-design/ant-design/issues/5631
_this.triggerScrollTimer = setTimeout(function () {
var listNode = findDOMNode(_this).querySelectorAll('.ant-transfer-list-content')[0];
if (listNode) {
triggerEvent(listNode, 'scroll');
}
}, 0);
};
_this.handleClear = function () {
_this.props.handleClear();
};
_this.matchFilter = function (text, item) {
var _this$props = _this.props,
filter = _this$props.filter,
filterOption = _this$props.filterOption;
if (filterOption) {
return filterOption(filter, item);
}
return text.indexOf(filter) >= 0;
};
_this.renderItem = function (item) {
var _this$props$render = _this.props.render,
render = _this$props$render === undefined ? noop : _this$props$render;
var renderResult = render(item);
var isRenderResultPlain = isRenderResultPlainObject(renderResult);
return {
renderedText: isRenderResultPlain ? renderResult.value : renderResult,
renderedEl: isRenderResultPlain ? renderResult.label : renderResult
};
};
_this.state = {
mounted: false
};
return _this;
}
_createClass(TransferList, [{
key: 'componentDidMount',
value: function componentDidMount() {
var _this2 = this;
this.timer = setTimeout(function () {
_this2.setState({
mounted: true
});
}, 0);
}
}, {
key: 'componentWillUnmount',
value: function componentWillUnmount() {
clearTimeout(this.timer);
clearTimeout(this.triggerScrollTimer);
}
}, {
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return PureRenderMixin.shouldComponentUpdate.apply(this, args);
}
}, {
key: 'getCheckStatus',
value: function getCheckStatus(filteredDataSource) {
var checkedKeys = this.props.checkedKeys;
if (checkedKeys.length === 0) {
return 'none';
} else if (filteredDataSource.every(function (item) {
return checkedKeys.indexOf(item.key) >= 0;
})) {
return 'all';
}
return 'part';
}
}, {
key: 'render',
value: function render() {
var _this3 = this;
var _props = this.props,
prefixCls = _props.prefixCls,
dataSource = _props.dataSource,
titleText = _props.titleText,
checkedKeys = _props.checkedKeys,
lazy = _props.lazy,
_props$body = _props.body,
body = _props$body === undefined ? noop : _props$body,
_props$footer = _props.footer,
footer = _props$footer === undefined ? noop : _props$footer,
showSearch = _props.showSearch,
style = _props.style,
filter = _props.filter,
searchPlaceholder = _props.searchPlaceholder,
notFoundContent = _props.notFoundContent,
itemUnit = _props.itemUnit,
itemsUnit = _props.itemsUnit,
onScroll = _props.onScroll;
// Custom Layout
var footerDom = footer(assign({}, this.props));
var bodyDom = body(assign({}, this.props));
var listCls = classNames(prefixCls, _defineProperty({}, prefixCls + '-with-footer', !!footerDom));
var filteredDataSource = [];
var totalDataSource = [];
var showItems = dataSource.map(function (item) {
var _renderItem = _this3.renderItem(item),
renderedText = _renderItem.renderedText,
renderedEl = _renderItem.renderedEl;
if (filter && filter.trim() && !_this3.matchFilter(renderedText, item)) {
return null;
}
// all show items
totalDataSource.push(item);
if (!item.disabled) {
// response to checkAll items
filteredDataSource.push(item);
}
var checked = checkedKeys.indexOf(item.key) >= 0;
return React.createElement(Item, { key: item.key, item: item, lazy: lazy, renderedText: renderedText, renderedEl: renderedEl, checked: checked, prefixCls: prefixCls, onClick: _this3.handleSelect });
});
var unit = dataSource.length > 1 ? itemsUnit : itemUnit;
var search = showSearch ? React.createElement(
'div',
{ className: prefixCls + '-body-search-wrapper' },
React.createElement(Search, { prefixCls: prefixCls + '-search', onChange: this.handleFilter, handleClear: this.handleClear, placeholder: searchPlaceholder, value: filter })
) : null;
var listBody = bodyDom || React.createElement(
'div',
{ className: showSearch ? prefixCls + '-body ' + prefixCls + '-body-with-search' : prefixCls + '-body' },
search,
React.createElement(
Animate,
{ component: 'ul', componentProps: { onScroll: onScroll }, className: prefixCls + '-content', transitionName: this.state.mounted ? prefixCls + '-content-item-highlight' : '', transitionLeave: false },
showItems
),
React.createElement(
'div',
{ className: prefixCls + '-body-not-found' },
notFoundContent
)
);
var listFooter = footerDom ? React.createElement(
'div',
{ className: prefixCls + '-footer' },
footerDom
) : null;
var checkStatus = this.getCheckStatus(filteredDataSource);
var checkedAll = checkStatus === 'all';
var checkAllCheckbox = React.createElement(Checkbox, { ref: 'checkbox', checked: checkedAll, indeterminate: checkStatus === 'part', onChange: function onChange() {
return _this3.props.handleSelectAll(filteredDataSource, checkedAll);
} });
return React.createElement(
'div',
{ className: listCls, style: style },
React.createElement(
'div',
{ className: prefixCls + '-header' },
checkAllCheckbox,
React.createElement(
'span',
{ className: prefixCls + '-header-selected' },
React.createElement(
'span',
null,
(checkedKeys.length > 0 ? checkedKeys.length + '/' : '') + totalDataSource.length,
' ',
unit
),
React.createElement(
'span',
{ className: prefixCls + '-header-title' },
titleText
)
)
),
listBody,
listFooter
);
}
}]);
return TransferList;
}(React.Component);
export default TransferList;
TransferList.defaultProps = {
dataSource: [],
titleText: '',
showSearch: false,
render: noop,
lazy: {}
}; |
client/routes.js | AlexFrazer/site | import React from 'react';
import {Route, IndexRoute} from 'react-router';
import App from './containers/App';
import Home from './containers/HomePage';
import Users from './containers/Users';
import AddUser from './containers/AddUser';
import NotFound from './containers/NotFound';
export default (
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/users" component={Users} />
<Route path="/create/user" component={AddUser} />
<Route path="*" component={NotFound} />
</Route>
)
|
src/routes/notFound/NotFound.js | kinshuk-jain/TB-Dfront | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './NotFound.css';
class NotFound extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{this.props.title}</h1>
<p>Sorry, the page you were trying to view does not exist.</p>
</div>
</div>
);
}
}
export default withStyles(s)(NotFound);
|
pages/logout.js | 1uphealth/1upwebapp | import React from 'react';
import Header from '../components/Header.js';
export default class Logout extends React.Component {
static async getInitialProps({ req }) {
const user = req ? req.user : null;
return { user };
}
componentDidMount() {
if (this.props.user) {
try {
window.localStorage.setItem('user', this.props.user);
} catch (err) {}
} else if (typeof this.props.user !== 'undefined') {
window.localStorage.removeItem('user');
}
}
render() {
return (
<div>
<Header />
<h1>Logged out!</h1>
</div>
);
}
}
|
docs/index.js | rsuite/rsuite-tag | // 解决 IE 11 兼容性问题
import 'babel-polyfill';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Markdown } from 'react-markdown-reader';
import CodeView from 'react-code-view';
import { PageContainer } from 'rsuite-docs';
import './less/index.less';
import Tag, { TagGroup } from '../src';
import randomText from './util/randomText';
const tags = (() => {
const common = Array.from(new Array(5)).map(() => `标签${randomText()}`);
const custom = [
{
text: `标签${randomText()}`,
color: Tag.Color.PRIMARY,
},
{
text: `标签${randomText()}`,
color: Tag.Color.SUCCESS,
closable: true
}
];
return [...custom, ...new Set(common)];
})();
class App extends Component {
render() {
return (
<PageContainer
activeKey="Autocomplete"
githubURL="https://github.com/rsuite/rsuite-autocomplete"
>
<Markdown>{require('../README.md')}</Markdown>
<CodeView
dependencies={{
React,
Tag,
randomText
}}
>
{require('./md/basic.md')}
</CodeView>
<CodeView
dependencies={{
React,
Tag,
TagGroup,
randomText,
tags
}}
>
{require('./md/tagGroup.md')}
</CodeView>
<CodeView
dependencies={{
React,
Tag,
TagGroup,
randomText,
tags
}}
babelTransformOptions={{
presets: [
'es2015',
'react',
'stage-1'
]
}}
>
{require('./md/tagGroupCustomized.md')}
</CodeView>
<Markdown>{require('./md/tagProps.md')}</Markdown>
<Markdown>{require('./md/tagGroupProps.md')}</Markdown>
</PageContainer>
);
}
}
ReactDOM.render(<App />,
document.getElementById('app')
);
|
app/components/side_bar.js | uglymugs/JustNUM | import React from 'react';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import { white } from 'material-ui/styles/colors';
import AssignmentLate from 'material-ui/svg-icons/action/assignment-late';
import Work from 'material-ui/svg-icons/action/work';
import NoteAdd from 'material-ui/svg-icons/action/note-add';
import Divider from 'material-ui/Divider';
import { Link } from 'react-router';
const style = {
paper: {
position: 'fixed',
top: 0,
left: 0,
zIndex: 100,
height: '100%',
width: '224px',
backgroundColor: '#5E7B8D',
},
rightIcon: {
textAlign: 'center',
lineHeight: '24px',
},
header: {
display: 'flex',
marginLeft: '10px',
marginBottom: '5px',
},
headerImg: {
marginTop: '5px',
width: '54px',
height: '54px',
},
headerText: {
color: 'white',
marginLeft: '8px',
fontSize: '1.6em',
},
};
const menuItemStyles = {
color: 'white',
};
const SideBar = () =>
<Paper style={style.paper}>
<div style={style.header}>
<img src="logo_sml.png" role="presentation" style={style.headerImg} />
<h1 style={style.headerText}>JustNUM</h1>
</div>
<Menu>
<MenuItem
primaryText="Tasks"
style={menuItemStyles}
leftIcon={<AssignmentLate color={white} />}
containerElement={<Link to="/authenticated/tasks" />}
/>
<MenuItem
primaryText="Cases"
style={menuItemStyles}
leftIcon={<Work color={white} />}
containerElement={<Link to="/authenticated/cases" />}
/>
<Divider />
<MenuItem
primaryText="Add Case"
style={menuItemStyles}
leftIcon={<NoteAdd color={white} />}
containerElement={<Link to="/authenticated/cases/new" />}
/>
<Divider />
</Menu>
</Paper>;
export default SideBar;
|
src/pages/i-need-your-help.js | theanxy/wojtekzajac.com | import React from 'react';
import Helmet from 'react-helmet';
import Link from 'gatsby-link';
import styled from 'styled-components';
import Kenya from '../img/swahilibox/swahilibox.jpg';
const SwahiliboxPage = styled.div`
line-height: 1.8;
@media (min-width: 650px) {
margin: 0 2.5em;
}
@media (min-width: 850px) {
margin: 0 5em;
p {
margin-right: 20%;
}
}
.caption {
display: block;
margin: -35px 10px 20px;
text-align: right;
color: rgba(0, 0, 0, 0.4);
}
p,
ul {
font-size: 14px;
strong {
font-weight: 600;
}
}
li {
margin-bottom: 0.2em;
}
.intro {
font-size: 18px;
margin-right: 0;
}
`;
class Swahilibox extends React.Component {
render() {
return (
<SwahiliboxPage>
<Helmet
title="I need your help — Wojtek Zając"
meta={[
{
name: 'description',
content: 'A perfect opportunity to support a thriving technical community in Mombasa.'
}
]}
/>
<h1>I need your help! (Apologies for the clickbait 😉)</h1>
<img src={Kenya} alt="Wojtek in Kenya" />
<small className="caption">Last week, assisting students in Mombasa</small>
<p className="intro">Hello friend,</p>
<p className="intro">
It's Wednesday, September 11th. I'm reaching out to you personally as I consider you someone who has inspired
me in the past or just someone I genuinely look up to.
</p>
<p>
<strong>
I’m currently in Mombasa, Kenya during the 4th and final week of volunteering at a local NGO, SwahiliBox.
</strong>{' '}
For the past month, along with 2 colleagues of mine, we've been running various technical workshops.
</p>
<p>
<strong>Yesterday</strong>, I've announced that I can run one more workshop this week, asking about the topic
they would like me to cover.
</p>
<p>
To my excitement, they've mentioned that{' '}
<strong>they'd love to cover entrepreneurship and soft skills</strong>. I couldn't be happier about that!
However, I then realized that after 3 weeks spent with them, distributing this process could both produce
better results in terms of diversifying ideas, but also have a bigger impact that should hopefully push them
to act more boldly :)
</p>
<h2>The idea</h2>
<p style={{ fontSize: 16 }}>
<strong>
I'd like to create a compilation of short videos encouraging Swahilibox members to take action while keeping
focused on their goals and thinking big.
</strong>
</p>
<p>
Ideally, a video should include at least one tip connected to:{' '}
<strong>
community leadership, networking, being searchable, understanding how to self-direct their growth, improving
soft skills, validating business ideas, not being afraid to fail, etc.
</strong>{' '}
(Anything that would boost their careers other than technical skills, really.)
</p>
<h2>Rules</h2>
<ul>
<li>start with "hello swahilibox!"</li>
<li>please don't mention me at all</li>
<li>
feel free to refer to your past experiences (explain how TAKING ACTION resulted in a very tangible and
positive outcome)
</li>
<li>as for the duration, anything between 5 seconds and 5 minutes works</li>
<li>horizontal orientation is strongly preferred, but not required</li>
<li>feel free to forward to your friends if they'd like to contribute as well!</li>
</ul>
<h2>Target group</h2>
<p>
SwahiliBox currently consists of about 15 talented developers, mostly between 18-26 years old. Some are good
with IoT, others already published native mobile apps, but the biggest group is eager to keep getting better
at web development.
</p>
<p>
Below are some of the members who stand out from the crowd, I think by referencing them personally we could
have a bigger impact.
</p>
<ul>
<li>
<strong>Maria</strong>: an extremely dedicated person working long hours
</li>
<li>
<strong>Isaac Nyakoi (Python Dev Entrepreneur)</strong>: He has been very dedicated in how he keeps coming
to the space and loves to help others. He has started doing workshops when asked around Python and has even
been teaching python in a bootcamp style learning environment. He also has his own startup which is in
development stage.
</li>
<li>
<strong>Abdallah</strong>:
</li>
<li>
<strong>Dennis onkangi (IOT and Web Dev)</strong> has created Impact innovations to help communities
including a very recent addition called TeleTap targeting Pregnant mothers during their pregnancy period.
Since we all know miscarriages happen alot in africa due to long response times from medical personel. Thus
they are making a small gadget that will allow for faster communication to health workers when a pregnant
mother is in need of medical help.
</li>
<li>
<strong>Abae Akili (Web and graphics Dev)</strong> Very dedicated to the community Runs workshops at
SwahiliBox and does alot to help within SwahiliBox itself. He has a startup that looks at engaging people
with emergency services closing the gap between the two entities.
</li>
<li>
<strong>Muzammil Khan - (IOT Dev)</strong> A very energetic young highschool individual that has been
instrumental in keeping the fire of IOT learning Alive at SwahiliBox he is doing his A-Levels and juggles
full time education with being a vibrant community member.
</li>
<li>… TBD</li>
</ul>
<h2>Deadline</h2>
<p>
Our final session takes place on Friday, so{' '}
<strong>I will need to receive all videos by Thursday, EOD</strong>. Afterwards, I'd like to screen it in
front of the entire group.
</p>
<p>
As soon as this project ends, you will get a link to the finished video. Every help counts and this is a
chance for you to really influence the lives of these students. Any questions, just let me know!
</p>
<p className="intro">
Please send recorded videos until Thursday, EOD via email / dropbox / google drive / youtube to:{' '}
<a href="mailto:kenya@wojtekzajac.com">kenya@wojtekzajac.com</a>
</p>
</SwahiliboxPage>
);
}
}
export default Swahilibox;
|
src/components/SideBarList.js | jamescchu/jameschu-v5 | import React from 'react'
import Link from 'gatsby-link'
import styled from 'styled-components'
import { rhythm } from '../utils/typography'
import { media } from '../utils/media'
import PropTypes from 'prop-types'
import StyledLink from './Link'
const Content = styled.section`width: 100%;`
const SideContainer = styled.ul`
list-style: none;
margin: 0;
position: fixed;
${media.desktop`
display: none;
`};
${media.giant`
display: block;
`};
`
const SideItem = styled.li`margin: 0;`
const SideHeader = styled.span`
font-size: ${rhythm(1 / 2)};
text-transform: uppercase;
color: rgba(0, 0, 0, 0.5);
`
const SideLink = StyledLink.withComponent(`a`)
const SideBar = ({ sections }) =>
<SideContainer>
<SideHeader>Contents</SideHeader>
{sections &&
sections.split(', ').map((section, array) =>
<SideItem>
<SideLink href={`#${section}`}>
{section.replace(/-/g, ' ')}
</SideLink>
</SideItem>
)}
</SideContainer>
SideBar.propTypes = {
sections: PropTypes.string,
}
export default SideBar
|
src/components/MonsterManualItem.js | kristyjy/battleplan | import React from 'react';
import { ListGroupItem, Collapse, Button} from 'reactstrap';
import NPCStatBlock from './NPCStatBlock';
import classNames from 'classnames';
class MonsterManualItem extends React.Component {
constructor(props, context) {
super(props, context);
this.toggle = this.toggle.bind(this);
this.state = { collapse: false };
this.addToInitiative = this.addToInitiative.bind(this);
}
toggle() {
this.setState({ collapse: !this.state.collapse });
}
addToInitiative(item) {
this.props.actions.addCombatant({
...item,
'initiative': 0,
'isKO': false,
'isDead': false
});
this.props.actions.sortCombatants();
}
render() {
const {item} = this.props;
const listItemClasses = classNames({
'monster-manual-list__item': true,
'monster-manual-list__item--open': this.state.collapse,
'justify-content-between': true
});
return (
<div>
<ListGroupItem className={listItemClasses} >
<Button size="sm" onClick={() => { this.toggle(); }}>Details</Button>
{item.name}
<Button size="sm" onClick={() => { this.addToInitiative(item); }}>+</Button>
</ListGroupItem>
<Collapse isOpen={this.state.collapse}>
<NPCStatBlock item={item} />
</Collapse>
</div>
);
}
}
MonsterManualItem.propTypes = {
item : React.PropTypes.object.isRequired,
actions : React.PropTypes.object.isRequired
};
export default MonsterManualItem;
|
src/client.js | kayluhb/tbmaga | /**
* THIS IS THE ENTRY POINT FOR THE CLIENT.
*/
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
// import useScroll from 'scroll-behavior/lib/useStandardScroll';
import withScroll from 'scroll-behavior';
import { browserHistory as _browserHistory, Router, RouterContext } from 'react-router';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
import createStore from './redux/create';
import routes from './routes';
import { menuClose, placeCloseMedia } from './redux/modules/actions';
const browserHistory = withScroll(_browserHistory);
const content = document.getElementById('content');
const store = createStore(browserHistory, window.initialState);
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
const inProduction = process.env.NODE_ENV === 'production';
const component = (
<Router
history={history}
render={(props) =>
<RouterContext {...props} />
}
>
{routes()}
</Router>
);
ReactDOM.render(
<Provider store={store} key="provider">
{component}
</Provider>,
content
);
if (!inProduction) {
if (!content || !content.firstChild || !content.firstChild.attributes ||
!content.firstChild.attributes['data-react-checksum']) {
console.error(
`Server-side React render was discarded. Make sure that your `
`initial render does not contain any client-side code.`
);
}
} else {
/* eslint-disable */
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;
i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();
a=s.createElement(o), m=s.getElementsByTagName(o)[0];
a.async=1;
a.src=g;
m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js', 'ga');
ga('create', 'UA-592045-7', 'auto');
ga('send', 'pageview');
/* eslint-enable */
}
function onHistoryChange() {
const state = store.getState();
if (state.menu.open) {
store.dispatch(menuClose());
}
if (state.place.mediaOpen) {
store.dispatch(placeCloseMedia());
}
if (inProduction) {
window.ga('send', 'pageview');
}
}
history.listen(onHistoryChange);
if (__DEVTOOLS__ && !window.devToolsExtension) {
const DevTools = require('./containers/DevTools/DevTools');
ReactDOM.render(
<Provider store={store} key="provider">
<div>
{component}
<DevTools />
</div>
</Provider>,
content
);
}
|
client/component/schema/filter/types/member.js | johngodley/search-regex | /**
* External dependencies
*/
import React from 'react';
import { translate as __ } from 'i18n-calypso';
import { useSelector, useDispatch } from 'react-redux';
/**
* Internal dependencies
*/
import Logic from '../logic';
import { DropdownText, MultiOptionDropdown } from 'wp-plugin-components';
import SearchFlags from 'component/search-flags';
import { setLabel } from 'state/search/action';
import { getLabel } from 'state/search/selector';
function setValues( values, changed, all ) {
if ( changed === '' ) {
return values.indexOf( '' ) === -1 ? [] : all;
}
return values.filter( ( item ) => item !== '' );
}
function getValues( values, allLength ) {
if ( values.length === allLength ) {
return [ '' ].concat( values );
}
return values;
}
function getOptions( options ) {
return [
{
value: '',
label: __( 'All' ),
},
].concat( options );
}
function FilterMember( props ) {
const { disabled, item, onChange, schema, fetchData } = props;
const { logic = 'include', values = [], flags = [ 'case' ] } = item;
const remote = schema.options === 'api' ? fetchData : false;
const { labels } = useSelector( ( state ) => state.search );
const dispatch = useDispatch();
const logicComponent = (
<Logic
type="member"
value={ logic }
disabled={ disabled }
onChange={ ( value ) => onChange( { logic: value, values: [] } ) }
/>
);
if ( logic === 'contains' || logic === 'notcontains' ) {
return (
<>
{ logicComponent }
<DropdownText
value={ values.length === 0 ? '' : values[ 0 ] }
disabled={ disabled }
onChange={ ( newValue ) => onChange( { values: [ newValue ] } ) }
/>
<SearchFlags
flags={ flags }
disabled={ disabled }
onChange={ ( value ) => onChange( { flags: value } ) }
allowRegex={ false }
allowMultiline={ false }
/>
</>
);
}
if ( remote ) {
return (
<>
{ logicComponent }
<DropdownText
value={ values }
disabled={ disabled }
onChange={ ( newValue ) => onChange( { values: newValue } ) }
fetchData={ remote }
loadOnFocus={ schema.preload }
maxChoices={ 20 }
onlyChoices
setLabel={ ( labelId, labelValue ) =>
dispatch( setLabel( schema.column + '_' + labelId, labelValue ) )
}
getLabel={ ( labelId ) => getLabel( labels, schema.column + '_' + labelId ) }
/>
</>
);
}
return (
<>
{ logicComponent }
{ ! remote && (
<MultiOptionDropdown
options={ getOptions( schema.options ) }
selected={ getValues( values, schema.options.length ) }
onApply={ ( newValue, changed ) =>
onChange( {
values: setValues( newValue, changed, schema.options.map( ( item ) => item.value ) ),
} )
}
multiple={ schema.multiple ?? true }
disabled={ disabled }
hideTitle
title={ schema.title }
badges
customBadge={ ( selected ) => ( selected.length >= schema.options.length ? [ '' ] : selected ) }
/>
) }
</>
);
}
export default FilterMember;
|
src/server.js | vincentbello/isomorphic-networker | import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
import {ReduxRouter} from 'redux-router';
import createHistory from 'history/lib/createMemoryHistory';
import {reduxReactRouter, match} from 'redux-router/server';
import {Provider} from 'react-redux';
import qs from 'query-string';
import getRoutes from './routes';
import getStatusFromRoutes from './helpers/getStatusFromRoutes';
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
const proxy = httpProxy.createProxyServer({
target: 'http://' + config.apiHost + ':' + config.apiPort,
ws: true
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
let json;
if (error.code !== 'ECONNRESET') {
console.error('proxy error', error);
}
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = {error: 'proxy_error', reason: error.message};
res.end(JSON.stringify(json));
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
webpackIsomorphicTools.refresh();
}
const client = new ApiClient(req);
const store = createStore(reduxReactRouter, getRoutes, createHistory, client);
function hydrateOnClient() {
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>));
}
if (__DISABLE_SSR__) {
hydrateOnClient();
return;
}
store.dispatch(match(req.originalUrl, (error, redirectLocation, routerState) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
console.error('ROUTER ERROR:', pretty.render(error));
res.status(500);
hydrateOnClient();
} else if (!routerState) {
res.status(500);
hydrateOnClient();
} else {
// Workaround redux-router query string issue:
// https://github.com/rackt/redux-router/issues/106
if (routerState.location.search && !routerState.location.query) {
routerState.location.query = qs.parse(routerState.location.search);
}
store.getState().router.then(() => {
const component = (
<Provider store={store} key="provider">
<ReduxRouter/>
</Provider>
);
const status = getStatusFromRoutes(routerState.routes);
if (status) {
res.status(status);
}
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
}).catch((err) => {
console.error('DATA FETCHING ERROR:', pretty.render(err));
res.status(500);
hydrateOnClient();
});
}
}));
});
if (config.port) {
if (config.isProduction) {
const io = new SocketIo(server);
io.path('/api/ws');
}
server.listen(config.port, (err) => {
if (err) {
console.error(err);
}
console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort);
console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port);
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
app/containers/Mt2Mobile/index.js | Blacksage959/Michael.McCann | /*
*
* Mt2Mobile
*
*/
import React from 'react';
import Helmet from 'react-helmet';
export default class Mt2Mobile extends React.PureComponent {
render() {
return (
<div>
<Helmet title="Mt2Mobile" meta={[ { name: 'description', content: 'Description of Mt2Mobile' }]}/>
//Remove this line and you can start writing your code here.
</div>
);
}
}
|
src/FormsyRadioGroup/FormsyRadioGroup.spec.js | maccuaa/formsy-mui | import 'jsdom-global/register';
import React from 'react';
import PropTypes from 'prop-types';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {Form} from 'formsy-react-2';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import test from 'tape';
import Sinon from 'sinon';
import RadioButtonGroup from 'material-ui/RadioButton/RadioButtonGroup';
import FormsyRadio from '../FormsyRadio';
import FormsyRadioGroup from './FormsyRadioGroup';
Enzyme.configure({ adapter: new Adapter() });
const muiTheme = getMuiTheme();
const mountWithContext = (node) => mount(node, {
context: {muiTheme},
childContextTypes: {muiTheme: PropTypes.object.isRequired}
});
test('FormsyRadioGroup renders a material-ui RadioButtonGroup', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyRadioGroup name='test' />
</Form>
);
assert.equals(wrapper.find(RadioButtonGroup).length, 1);
assert.end();
});
test('FormsyRadioGroup sends value to Formsy Form', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyRadioGroup name='test' valueSelected='foo'>
<FormsyRadio value='foo' />
</FormsyRadioGroup>
</Form>
);
const expected = 'foo';
const formsyForm = wrapper.find(Form).instance();
const input = wrapper.find('input').instance();
// Make sure the Formsy Form component has the right value
assert.equals(formsyForm.getCurrentValues().test, expected);
// Make sure the DOM has the right value
assert.true(input.checked);
assert.end();
});
test('FormsyRadioGroup resetValue sets value back to original value', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyRadioGroup name='test' valueSelected='foo'>
<FormsyRadio value='foo' />
<FormsyRadio value='bar' />
</FormsyRadioGroup>
</Form>
);
const formsyRadioGroup = wrapper.find(FormsyRadioGroup).instance();
const fooInput = wrapper.find({value: 'foo'}).last();
const barInput = wrapper.find({value: 'bar'}).last();
assert.false(barInput.instance().checked);
assert.true(fooInput.instance().checked);
assert.equals(formsyRadioGroup.getValue(), 'foo');
barInput.instance().checked = true;
barInput.simulate('change');
assert.equals(formsyRadioGroup.getValue(), 'bar');
assert.true(barInput.instance().checked);
assert.false(fooInput.instance().checked);
formsyRadioGroup.resetValue();
assert.equals(formsyRadioGroup.getValue(), 'foo');
assert.false(barInput.instance().checked);
assert.true(fooInput.instance().checked);
assert.end();
});
test('FormsyRadioGroup onChange prop is called', (assert) => {
const onChangeSpy = Sinon.spy();
const wrapper = mountWithContext(
<Form>
<FormsyRadioGroup name='test' onChange={onChangeSpy}>
<FormsyRadio value='foo' />
</FormsyRadioGroup>
</Form>
);
wrapper.find({value: 'foo'}).last().simulate('change');
assert.true(onChangeSpy.calledOnce);
assert.end();
});
test('FormsyRadioGroup falsey valueSelected values are correctly set', (assert) => {
const zero = 0;
const notTrue = false;
const nill = null;
const notdefined = undefined;
const wrapper = mountWithContext(
<Form>
<FormsyRadioGroup name='zero' valueSelected={zero}>
<FormsyRadio value={zero} />
</FormsyRadioGroup>
<FormsyRadioGroup name='notTrue' valueSelected={notTrue}>
<FormsyRadio value={notTrue} />
</FormsyRadioGroup>
<FormsyRadioGroup name='nill' valueSelected={nill}>
<FormsyRadio value={nill} />
</FormsyRadioGroup>
<FormsyRadioGroup name='notdefined' valueSelected={notdefined}>
<FormsyRadio value={notdefined} />
</FormsyRadioGroup>
</Form>
);
const formsyForm = wrapper.find(Form).instance();
const formValues = formsyForm.getCurrentValues();
assert.equals(formValues.zero, zero);
assert.equals(formValues.notTrue, notTrue);
assert.equals(formValues.nill, nill);
assert.equals(formValues.notdefined, notdefined);
assert.end();
});
test('FormsyRadioGroup falsey defaultSelected values are correctly set', (assert) => {
const zero = 0;
const notTrue = false;
const nill = null;
const notdefined = undefined;
const wrapper = mountWithContext(
<Form>
<FormsyRadioGroup name='zero' defaultSelected={zero}>
<FormsyRadio value={zero} />
</FormsyRadioGroup>
<FormsyRadioGroup name='notTrue' defaultSelected={notTrue}>
<FormsyRadio value={notTrue} />
</FormsyRadioGroup>
<FormsyRadioGroup name='nill' defaultSelected={nill}>
<FormsyRadio value={nill} />
</FormsyRadioGroup>
<FormsyRadioGroup name='notdefined' defaultSelected={notdefined}>
<FormsyRadio value={notdefined} />
</FormsyRadioGroup>
</Form>
);
const formsyForm = wrapper.find(Form).instance();
const formValues = formsyForm.getCurrentValues();
assert.equals(formValues.zero, zero);
assert.equals(formValues.notTrue, notTrue);
assert.equals(formValues.nill, nill);
assert.equals(formValues.notdefined, notdefined);
assert.end();
});
test('FormsyRadioGroup updates value as a controlled component', (assert) => {
class MyComponent extends React.PureComponent {
constructor (props) {
super(props);
this.state = {
value: 'foo'
};
}
changeValue () {
this.setState({value: 'bar'});
}
render () {
return (
<Form>
<FormsyRadioGroup name='test' valueSelected={this.state.value}>
<FormsyRadio value='foo' />
<FormsyRadio value='bar' />
</FormsyRadioGroup>
</Form>
);
}
}
const wrapper = mountWithContext(<MyComponent />);
const formsyForm = wrapper.find(Form).instance();
const myComponent = wrapper.find(MyComponent).instance();
const formsyRadioGroup = wrapper.find(FormsyRadioGroup).instance();
const radioButtonGroup = wrapper.find(RadioButtonGroup).instance();
const fooInput = wrapper.find({value: 'foo'}).last();
const barInput = wrapper.find({value: 'bar'}).last();
assert.equals(formsyForm.getCurrentValues().test, 'foo');
assert.false(barInput.instance().checked);
assert.true(fooInput.instance().checked);
assert.equals(formsyRadioGroup.getValue(), 'foo');
assert.equals(radioButtonGroup.getSelectedValue(), 'foo');
myComponent.changeValue();
assert.equals(formsyForm.getCurrentValues().test, 'bar');
assert.true(barInput.instance().checked);
assert.false(fooInput.instance().checked);
assert.equals(formsyRadioGroup.getValue(), 'bar');
assert.equals(radioButtonGroup.getSelectedValue(), 'bar');
assert.end();
});
|
actor-apps/app-web/src/app/components/modals/MyProfile.react.js | gaolichuang/actor-platform | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import React, { Component } from 'react';
import { Container } from 'flux/utils';
import Modal from 'react-modal';
import ActorClient from 'utils/ActorClient';
import { KeyCodes } from 'constants/ActorAppConstants';
import MyProfileActions from 'actions/MyProfileActionCreators';
import CropAvatarActionCreators from 'actions/CropAvatarActionCreators';
import MyProfileStore from 'stores/MyProfileStore';
import CropAvatarStore from 'stores/CropAvatarStore';
import AvatarItem from 'components/common/AvatarItem.react';
import CropAvatarModal from './CropAvatar.react.js';
import { Styles, TextField } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
class MyProfile extends Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
static getStores = () => [MyProfileStore, CropAvatarStore];
static calculateState() {
return {
profile: MyProfileStore.getProfile(),
name: MyProfileStore.getName(),
nick: MyProfileStore.getNick(),
about: MyProfileStore.getAbout(),
isOpen: MyProfileStore.isModalOpen(),
isCropModalOpen: CropAvatarStore.isOpen()
};
}
componentWillMount() {
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7',
disabledTextColor: 'rgba(0,0,0,.4)'
}
});
}
componentWillUpdate(nextProps, nextState) {
if ((nextState.isOpen && !this.state.isOpen) || (this.state.isOpen && !nextState.isCropModalOpen)) {
document.addEventListener('keydown', this.onKeyDown, false);
} else if ((!nextState.isOpen && this.state.isOpen) || (this.state.isOpen && nextState.isCropModalOpen)) {
document.removeEventListener('keydown', this.onKeyDown, false);
}
}
onClose = () => MyProfileActions.hide();
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onNameChange = event => this.setState({name: event.target.value});
onNicknameChange = event => this.setState({nick: event.target.value});
onAboutChange = event => this.setState({about: event.target.value});
onSave = () => {
const { nick, name, about } = this.state;
MyProfileActions.saveName(name);
MyProfileActions.saveNickname(nick);
MyProfileActions.editMyAbout(about);
this.onClose();
};
onProfilePictureInputChange = () => {
const imageInput = React.findDOMNode(this.refs.imageInput);
const imageForm = React.findDOMNode(this.refs.imageForm);
const file = imageInput.files[0];
let reader = new FileReader();
reader.onload = (event) => {
CropAvatarActionCreators.show(event.target.result);
imageForm.reset();
};
reader.readAsDataURL(file);
};
onChangeAvatarClick = () => {
const imageInput = React.findDOMNode(this.refs.imageInput);
imageInput.click()
};
onProfilePictureRemove = () => MyProfileActions.removeMyAvatar();
changeMyAvatar = (croppedImage) => MyProfileActions.changeMyAvatar(croppedImage);
render() {
const { isOpen, isCropModalOpen, profile, nick, name, about } = this.state;
const cropAvatar = isCropModalOpen ? <CropAvatarModal onCropFinish={this.changeMyAvatar}/> : null;
if (profile !== null && isOpen) {
return (
<Modal className="modal-new modal-new--profile"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 440}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person</a>
<h4 className="modal-new__header__title">Profile</h4>
<div className="pull-right">
<button className="button button--lightblue" onClick={this.onSave}>Done</button>
</div>
</header>
<div className="modal-new__body row">
<div className="col-xs">
<div className="name">
<TextField className="login__form__input"
floatingLabelText="Full name"
fullWidth
onChange={this.onNameChange}
type="text"
value={name}/>
</div>
<div className="nick">
<TextField className="login__form__input"
floatingLabelText="Nickname"
fullWidth
onChange={this.onNicknameChange}
type="text"
value={nick}/>
</div>
<div className="phone">
<TextField className="login__form__input"
disabled
floatingLabelText="Phone number"
fullWidth
type="tel"
value={(profile.phones[0] || {}).number}/>
</div>
<div className="about">
<label htmlFor="about">About</label>
<textarea className="textarea"
id="about"
onChange={this.onAboutChange}
placeholder="Few words about you"
value={about}/>
</div>
</div>
<div className="profile-picture text-center">
<div className="profile-picture__changer">
<AvatarItem image={profile.bigAvatar}
placeholder={profile.placeholder}
size="big"
title={profile.name}/>
<a onClick={this.onChangeAvatarClick}>
<span>Change</span>
<span>avatar</span>
</a>
</div>
<div className="profile-picture__controls">
<a onClick={this.onProfilePictureRemove}>Remove</a>
</div>
<form className="hide" ref="imageForm">
<input onChange={this.onProfilePictureInputChange} ref="imageInput" type="file"/>
</form>
</div>
</div>
{cropAvatar}
</Modal>
);
} else {
return null;
}
}
}
export default Container.create(MyProfile, {pure: false});
|
src/svg-icons/action/swap-vertical-circle.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSwapVerticalCircle = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM6.5 9L10 5.5 13.5 9H11v4H9V9H6.5zm11 6L14 18.5 10.5 15H13v-4h2v4h2.5z"/>
</SvgIcon>
);
ActionSwapVerticalCircle = pure(ActionSwapVerticalCircle);
ActionSwapVerticalCircle.displayName = 'ActionSwapVerticalCircle';
ActionSwapVerticalCircle.muiName = 'SvgIcon';
export default ActionSwapVerticalCircle;
|
client/modules/User/pages/UserBasePage.js | vwtan/FinancialTracker | import React from 'react';
import { Link } from 'react-router';
import styles from '../styles/User.scss';
import Sidebar from '../components/Sidebar';
/* eslint react/prop-types: 0 */
export function UserBasePage(props) {
return (
<div className={styles.bg}>
<Sidebar />
{ props.children }
</div>
);
}
export default UserBasePage;
|
src-example/components/molecules/Blockquote/index.js | SIB-Colombia/biodiversity_catalogue_v2_frontend | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { font, palette } from 'styled-theme'
const StyledBlockquote = styled.blockquote`
position: relative;
font-family: ${font('quote')};
font-style: italic;
font-size: 1.2rem;
line-height: 2rem;
box-sizing: border-box;
color: ${palette('grayscale', 1)};
border-left: 5px solid ${palette('grayscale', 2, true)};
margin: 1rem 0;
padding: 0.5rem 0 0.5rem 1.5rem;
`
const Cite = styled.cite`
display: block;
font-family: ${font('primary')};
font-weight: 300;
font-style: normal;
margin-top: 0.4rem;
`
const Blockquote = ({ cite, children, ...props }) => {
return (
<StyledBlockquote {...props}>
<div>{children}</div>
{cite && <Cite>{cite}</Cite>}
</StyledBlockquote>
)
}
Blockquote.propTypes = {
cite: PropTypes.string,
children: PropTypes.node,
reverse: PropTypes.bool,
}
export default Blockquote
|