path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/svg-icons/image/camera-front.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCameraFront = (props) => (
<SvgIcon {...props}>
<path d="M10 20H5v2h5v2l3-3-3-3v2zm4 0v2h5v-2h-5zM12 8c1.1 0 2-.9 2-2s-.9-2-2-2-1.99.9-1.99 2S10.9 8 12 8zm5-8H7C5.9 0 5 .9 5 2v14c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V2c0-1.1-.9-2-2-2zM7 2h10v10.5c0-1.67-3.33-2.5-5-2.5s-5 .83-5 2.5V2z"/>
</SvgIcon>
);
ImageCameraFront = pure(ImageCameraFront);
ImageCameraFront.displayName = 'ImageCameraFront';
ImageCameraFront.muiName = 'SvgIcon';
export default ImageCameraFront;
|
imports/ui/components/Navigation/Navigation.js | jamiebones/Journal_Publication | import React from 'react';
import PropTypes from 'prop-types';
import { Navbar , Nav, NavItem } from 'react-bootstrap';
import { Link } from 'react-router-dom';
import { LinkContainer } from 'react-router-bootstrap';
import Icon from '../../components/Icon/Icon';
import PublicNavigation from '../PublicNavigation/PublicNavigation';
import AuthenticatedNavigation from '../AuthenticatedNavigation/AuthenticatedNavigation';
import './Navigation.scss';
const Navigation = props => (
<div className="appNav">
<Navbar fluid>
<Navbar.Header>
<Navbar.Brand>
<Link to="" className="navbar-brand">
<img src="/image/elogo.png" alt="Erudite Scholars"/>
</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<LinkContainer exact to="/">
<NavItem href="/">Home</NavItem>
</LinkContainer>
</Nav>
<Nav>
<LinkContainer to="/search_published_paper">
<NavItem eventKey={2} href="/search_published_paper">Search For Papers</NavItem>
</LinkContainer>
</Nav>
<PublicNavigation {...props} />
</Navbar.Collapse>
</Navbar>
</div>
);
Navigation.defaultProps = {
name: '',
};
Navigation.propTypes = {
authenticated: PropTypes.bool.isRequired,
};
export default Navigation;
|
styleguide.js | mazzcris/sortello | import {render} from 'react-dom'
import React from 'react'
import StyleguideApp from './StyleguideApp.jsx'
import Bootstrap from 'bootstrap/dist/css/bootstrap.min.css'
import "./css/style.css";
import "./css/animate-sortello.css";
import "./css/buttons.css";
import "./css/api-key.css";
import "./css/board-column__selection.css";
import "./css/choices.css";
import "./css/responsive/board-column-selection__responsive.css";
import "./css/responsive/choices__responsive.css";
import "./css/logout-button.css";
import "./css/responsive/logout-button__responsive.css";
import "./css/footer.css";
import "./css/responsive/footer__responsive.css";
import "./css/responsive/api-key__responsive.css";
import "./css/responsive/disclaimer__responsive.css";
import "./css/disclaimer.css";
import "./css/send-ordered.css";
import "./css/send-success.css";
import "./css/responsive/send-success__responsive.css";
import "./css/responsive/send-ordered__responsive.css";
import "./css/recap.css";
import "./css/responsive/recap__responsive.css";
import "./css/prioritization-end.css";
import "./css/responsive/prioritization-end__responsive.css";
import "./css/no-access-message.css";
const containerEl = document.getElementById("container")
render(<StyleguideApp/>, containerEl)
|
docs/src/examples/elements/Reveal/States/RevealExampleDisabled.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Image, Reveal } from 'semantic-ui-react'
const RevealExampleDisabled = () => (
<Reveal animated='move' disabled>
<Reveal.Content visible>
<Image src='/images/wireframe/square-image.png' size='small' />
</Reveal.Content>
<Reveal.Content hidden>
<Image src='/images/avatar/large/chris.jpg' size='small' />
</Reveal.Content>
</Reveal>
)
export default RevealExampleDisabled
|
modules/useRouterRestoreScroll.js | jshin49/react-router-restore-scroll | import React from 'react'
import RestoreWindowScroll from './RestoreWindowScroll'
const useRouterRestoreScroll = () => ({
renderRouterContext: (child, props) => (
<RestoreWindowScroll
restoreWindow={props.router.restoreScroll.restoreWindow}
location={props.location}
children={child}
/>
)
})
export default useRouterRestoreScroll
|
examples/real-world/index.js | nickhudkins/redux | import 'babel-core/polyfill';
import React from 'react';
import Root from './containers/Root';
import BrowserHistory from 'react-router/lib/BrowserHistory';
React.render(
<Root history={new BrowserHistory()} />,
document.getElementById('root')
);
|
app/components/PointList/index.js | GuiaLa/guiala-web-app | /**
*
* PointList
*
*/
import React from 'react';
import PointListItem from 'PointListItem'
import styles from './styles.css';
class PointList extends React.Component {
render() {
const { items, params } = this.props;
return (
<div className={ styles.wrapper }>
{ items.map((item, key) => <PointListItem key={key} {...item} place={params.placeSlug} /> )}
</div>
);
}
}
export default PointList;
|
tests/react_native_tests/test_data/native_code/ToolbarAndroid/app/components/Mobile/index.js | ibhubs/sketch-components | /**
* @flow
*/
import React from 'react'
import PropTypes from 'prop-types'
import { observer } from 'mobx-react/native'
import styles from './styles'
import Mobile from './component'
@observer
class MobileWrapper extends React.Component {
render() {
return (
<Mobile
{...this.props}
></Mobile>
);
}
}
export default MobileWrapper |
src/rodal.js | chenjiahan/rodal | /* ===============================
* Rodal v1.8.2 https://chenjiahan.github.com/rodal
* =============================== */
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
// env
const IN_BROWSER = typeof window !== 'undefined';
const UA = IN_BROWSER && window.navigator.userAgent.toLowerCase();
const IS_IE_9 = UA && UA.indexOf('msie 9.0') > 0;
const Dialog = props => {
const animation =
(props.animationType === 'enter'
? props.enterAnimation
: props.leaveAnimation) || props.animation;
const className = `rodal-dialog rodal-${animation}-${props.animationType}`;
const CloseButton = props.showCloseButton ? (
<span
className="rodal-close"
onClick={props.onClose}
onKeyPress={event => {
if (props.onClose && event.which === 13) {
props.onClose(event);
}
}}
tabIndex={0}
/>
) : null;
const { width, height, measure, duration, customStyles, id } = props;
const style = {
width: width + measure,
height: height + measure,
animationDuration: duration + 'ms',
WebkitAnimationDuration: duration + 'ms'
};
const mergedStyles = { ...style, ...customStyles };
return (
<div style={mergedStyles} className={className} id={id}>
{props.children}
{CloseButton}
</div>
);
};
class Rodal extends React.Component {
static propTypes = {
width: PropTypes.number,
height: PropTypes.number,
measure: PropTypes.string,
visible: PropTypes.bool,
showMask: PropTypes.bool,
closeOnEsc: PropTypes.bool,
closeMaskOnClick: PropTypes.bool,
showCloseButton: PropTypes.bool,
animation: PropTypes.string,
enterAnimation: PropTypes.string,
leaveAnimation: PropTypes.string,
duration: PropTypes.number,
className: PropTypes.string,
customStyles: PropTypes.object,
customMaskStyles: PropTypes.object,
onClose: PropTypes.func.isRequired,
onAnimationEnd: PropTypes.func,
id:PropTypes.string
};
static defaultProps = {
width: 400,
height: 240,
measure: 'px',
visible: false,
showMask: true,
closeOnEsc: false,
closeMaskOnClick: true,
showCloseButton: true,
animation: 'zoom',
enterAnimation: '',
leaveAnimation: '',
duration: 300,
className: '',
customStyles: {},
customMaskStyles: {}
};
state = {
isShow: false,
animationType: 'leave'
};
componentDidMount() {
if (this.props.visible) {
this.enter();
}
}
componentDidUpdate(prevProps) {
if (this.props.visible && !prevProps.visible) {
this.enter();
}
if (!this.props.visible && prevProps.visible) {
this.leave();
}
}
enter() {
this.setState({ isShow: true, animationType: 'enter' });
}
leave() {
this.setState(IS_IE_9 ? { isShow: false } : { animationType: 'leave' });
}
onKeyUp = event => {
if (!this.props.closeOnEsc || event.keyCode !== 27) {
return;
}
this.props.onClose(event);
};
animationEnd = event => {
const { animationType } = this.state;
const { closeOnEsc, onAnimationEnd } = this.props;
if (animationType === 'leave') {
this.setState({ isShow: false });
} else if (closeOnEsc) {
this.el.focus();
}
if (event.target === this.el && onAnimationEnd) {
onAnimationEnd();
}
};
render() {
const {
closeMaskOnClick,
onClose,
customMaskStyles,
showMask,
duration,
className,
children
} = this.props;
const { isShow, animationType } = this.state;
const Mask = showMask ? (
<div
className="rodal-mask"
style={customMaskStyles}
onClick={closeMaskOnClick ? onClose : void 0}
/>
) : null;
const style = {
display: isShow ? '' : 'none',
animationDuration: duration + 'ms',
WebkitAnimationDuration: duration + 'ms'
};
return (
<div
style={style}
className={cx('rodal', `rodal-fade-${animationType}`, className)}
onAnimationEnd={this.animationEnd}
tabIndex="-1"
ref={el => {
this.el = el;
}}
onKeyUp={this.onKeyUp}
>
{Mask}
<Dialog {...this.props} animationType={animationType}>
{children}
</Dialog>
</div>
);
}
}
export default Rodal;
|
notebook/experience/web/webpack4-upgrade-log/simple-webpack-config/src/components/confirm.js | JMwill/wiki | import React from 'react'
import modal from './modal'
/**
* 弹出确认窗
* @param {[type]} options.message 消息
* @param {[type]} options.ok 确认的回调函数
* @param {String} okLabel 确认按钮标签
* @param {[type]} cancel 取消的回调函数
* @param {String} cancelLabel 取消按钮标签
* @return {[type]} 销毁函数
*/
function withConfirm({
message,
ok = function() { },
okLabel = '确定',
cancel = function() {},
cancelLabel = '取消',
}) {
return function({close}) {
return (
<div className='pepe-modal-table'>
<div className='bd'>{message}</div>
<div className='ft'>
<button
className='btn btn-primary'
onClick={() => {
ok()
close()
}}
>
{okLabel}
</button>
<button
className='btn btn-default'
onClick={() => {
cancel()
close()
}}
>
{cancelLabel}
</button>
</div>
</div>
)
}
}
export default function confirm(props) {
return modal({
component: withConfirm(props),
header: (props.title != null),
title: props.title,
size: 'sm',
})
}
|
src/routes/register/index.js | rameshrr/dicomviewer | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Register from './Register';
const title = 'New User Registration';
function action() {
return {
chunks: ['register'],
title,
component: (
<Layout>
<Register title={title} />
</Layout>
),
};
}
export default action;
|
tom-binary-tree/src/Button.js | slorber/scalable-frontend-with-elm-or-redux | import React from 'react'
// EVENTS
class Toggle {
update(model) {
return { model: !model }
}
}
// APP
export default {
init() {
return { model: true }
},
update(model, event) {
return event.update(model)
},
view(model, dispatch) {
const onClick = () => dispatch(new Toggle())
const style = { backgroundColor: model ? 'green' : 'red' }
return <button onClick={onClick} style={style}>Click</button>
}
} |
react/features/device-selection/components/DeviceSelector.js | parisjulien/arkadin-jitsimeet | import AKDropdownMenu from '@atlaskit/dropdown-menu';
import ExpandIcon from '@atlaskit/icon/glyph/expand';
import React, { Component } from 'react';
import { translate } from '../../base/i18n';
const EXPAND_ICON = <ExpandIcon label = 'expand' />;
/**
* React component for selecting a device from a select element. Wraps
* AKDropdownMenu with device selection specific logic.
*
* @extends Component
*/
class DeviceSelector extends Component {
/**
* DeviceSelector component's property types.
*
* @static
*/
static propTypes = {
/**
* MediaDeviceInfos used for display in the select element.
*/
devices: React.PropTypes.array,
/**
* If false, will return a selector with no selection options.
*/
hasPermission: React.PropTypes.bool,
/**
* CSS class for the icon to the left of the dropdown trigger.
*/
icon: React.PropTypes.string,
/**
* If true, will render the selector disabled with a default selection.
*/
isDisabled: React.PropTypes.bool,
/**
* The translation key to display as a menu label.
*/
label: React.PropTypes.string,
/**
* The callback to invoke when a selection is made.
*/
onSelect: React.PropTypes.func,
/**
* The default device to display as selected.
*/
selectedDeviceId: React.PropTypes.string,
/**
* Invoked to obtain translated strings.
*/
t: React.PropTypes.func
};
/**
* Initializes a new DeviceSelector instance.
*
* @param {Object} props - The read-only React Component props with which
* the new instance is to be initialized.
*/
constructor(props) {
super(props);
this._onSelect = this._onSelect.bind(this);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
if (!this.props.hasPermission) {
return this._renderNoPermission();
}
if (!this.props.devices.length) {
return this._renderNoDevices();
}
const items = this.props.devices.map(this._createDropdownItem);
const defaultSelected = items.find(item =>
item.value === this.props.selectedDeviceId
);
return this._createDropdown({
defaultSelected,
isDisabled: this.props.isDisabled,
items,
placeholder: this.props.t('deviceSelection.selectADevice')
});
}
/**
* Creates a React Element for displaying the passed in text surrounded by
* two icons. The left icon is the icon class passed in through props and
* the right icon is AtlasKit ExpandIcon.
*
* @param {string} triggerText - The text to display within the element.
* @private
* @returns {ReactElement}
*/
_createDropdownTrigger(triggerText) {
return (
<div className = 'device-selector-trigger'>
<span
className = { `device-selector-icon ${this.props.icon}` } />
<span className = 'device-selector-trigger-text'>
{ triggerText }
</span>
{ EXPAND_ICON }
</div>
);
}
/**
* Creates an object in the format expected by AKDropdownMenu for an option.
*
* @param {MediaDeviceInfo} device - An object with a label and a deviceId.
* @private
* @returns {Object} The passed in media device description converted to a
* format recognized as a valid AKDropdownMenu item.
*/
_createDropdownItem(device) {
return {
content: device.label,
value: device.deviceId
};
}
/**
* Creates a AKDropdownMenu Component using passed in props and options. If
* the dropdown needs to be disabled, then only the AKDropdownMenu trigger
* element is returned to simulate a disabled state.
*
* @param {Object} options - Additional configuration for display.
* @param {Object} options.defaultSelected - The option that should be set
* as currently chosen.
* @param {boolean} options.isDisabled - If true, only the AKDropdownMenu
* trigger component will be returned to simulate a disabled dropdown.
* @param {Array} options.items - All the selectable options to display.
* @param {string} options.placeholder - The translation key to display when
* no selection has been made.
* @private
* @returns {ReactElement}
*/
_createDropdown(options) {
const triggerText
= (options.defaultSelected && options.defaultSelected.content)
|| options.placeholder;
const trigger = this._createDropdownTrigger(triggerText);
if (options.isDisabled) {
return (
<div className = 'device-selector-trigger-disabled'>
{ trigger }
</div>
);
}
return (
<AKDropdownMenu
items = { [ { items: options.items || [] } ] }
onItemActivated = { this._onSelect }
shouldFitContainer = { true }>
{ trigger }
</AKDropdownMenu>
);
}
/**
* Invokes the passed in callback to notify of selection changes.
*
* @param {Object} selection - Event from choosing a AKDropdownMenu option.
* @private
* @returns {void}
*/
_onSelect(selection) {
const newDeviceId = selection.item.value;
if (this.props.selectedDeviceId !== newDeviceId) {
this.props.onSelect(selection.item.value);
}
}
/**
* Creates a Select Component that is disabled and has a placeholder
* indicating there are no devices to select.
*
* @private
* @returns {ReactElement}
*/
_renderNoDevices() {
return this._createDropdown({
isDisabled: true,
placeholder: this.props.t('settings.noDevice')
});
}
/**
* Creates a AKDropdownMenu Component that is disabled and has a placeholder
* stating there is no permission to display the devices.
*
* @private
* @returns {ReactElement}
*/
_renderNoPermission() {
return this._createDropdown({
isDisabled: true,
placeholder: this.props.t('deviceSelection.noPermission')
});
}
}
export default translate(DeviceSelector);
|
src/packages/recompose/__tests__/types/test_withStateHandlers.js | acdlite/recompose | /* eslint-disable no-unused-vars, no-unused-expressions */
/* @flow */
import React from 'react'
import { compose, withProps, withStateHandlers } from '../..'
import type { HOC } from '../..'
type EnhancedCompProps = {
initialCounter: number,
}
const enhancer: HOC<*, EnhancedCompProps> = compose(
withStateHandlers(
{ value: 'Hello', letIt: 'be', obj: ({}: { [key: string]: string }) },
{
// we need to set argument type so inference will work good
setValue: (state, props) => (value: string) => ({
value,
}),
changeValue: (state, props) => (
{ i, j }: { i: number, j: string },
k: number
) => ({
value: `world again ${i} ${j}`,
}),
inform: state => () => {},
}
),
// here props itself will not be infered without explicit handler args types
withProps(props => ({
hi: (props.value: string),
ic: (props.initialCounter: number),
cc: (props.obj.a: string),
// $ExpectError value not a number or any
ehi: (props.value: number),
// $ExpectError not a number
cn: (props.obj.a: number),
// $ExpectError property not found (to detect that props is not any)
err: props.iMNotExists,
// $ExpectError initialCounter not any nor string
icErr: (props.initialCounter: string),
}))
)
const enhancerFuncInit: HOC<*, EnhancedCompProps> = compose(
withStateHandlers(
props => ({
counter: props.initialCounter,
}),
{
// it's better to set argument type with named props, easier to find an error
// if you call it with wrong arguments
incCounter: ({ counter }) => ({ value }: { value: number }) => ({
counter: counter + value,
}),
}
),
withProps(props => ({
// check that result is void
iVal: (props.incCounter({ value: 1 }): void),
// $ExpectError check that incCounter is not any
iVal2: (props.incCounter({ value: 1 }): number),
// $ExpectError property not found
err: props.iMNotExists,
}))
)
const BaseComponent = ({ hi, changeValue, setValue }) =>
<div
onClick={() => {
// check that supports few arguments
const x = changeValue({ i: 1, j: '1' }, 1)
setValue('ww')
// Check that result is void
;(x: void)
// $ExpectError check that x is not any
;(x: {})
// Check hi
;(hi: string)
// $ExpectError check that hi is not any
;(hi: number)
}}
>
{hi}
</div>
const EnhancedComponent = enhancer(BaseComponent)
;<EnhancedComponent initialCounter={0} />
// Without $Exact<State> this will cause error
const enhancer3: HOC<*, EnhancedCompProps> = compose(
withStateHandlers(
({
mapA2B: {},
}: { mapA2B: { [key: string]: string } }),
{}
),
withProps(props => ({
// check that result is void
iVal: props.mapA2B.c,
}))
)
|
src/components/TopNav.js | one-stop-team/ripta-app | import React from 'react'
import * as bs from 'react-bootstrap'
import logo from '../images/ripta_logo.png'
const LinkContainer = ({children}) => (
<span>{children}</span>
)
export default class TopNav extends React.Component {
render() {
return (
<bs.Navbar fixedTop fluid>
<bs.Navbar.Header>
<bs.Navbar.Brand>
<img src={logo} alt="RIPTA" />
</bs.Navbar.Brand>
<bs.Navbar.Toggle />
</bs.Navbar.Header>
<bs.Navbar.Collapse>
<bs.Nav>
<bs.NavItem>Home</bs.NavItem>
<bs.NavItem>Schedules</bs.NavItem>
<bs.NavItem>Alerts</bs.NavItem>
</bs.Nav>
</bs.Navbar.Collapse>
</bs.Navbar>
)
}
}
|
src/modules/Hemmo.js | futurice/PelaryHemmo | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
StyleSheet,
Modal,
AppState,
Text,
View,
Platform,
TouchableOpacity,
} from 'react-native';
import { getSizeByWidth, getFontSize } from '../services/graphics';
import AudioPlayerViewContainer from './AudioPlayerViewContainer';
import { toggleMute, setText, setAudio } from '../state/HemmoState';
import AppButton from '../components/AppButton';
const styles = StyleSheet.create({
container: {
position: 'absolute',
right: 0,
},
hemmo: {
alignSelf: 'flex-end',
right: getFontSize(1),
top: getFontSize(1.5),
...Platform.select({
ios: {
top: getFontSize(2.8),
},
}),
},
bubbleContainer: {
flex: 1,
flexDirection: 'column',
zIndex: 10000,
backgroundColor: 'rgba(255,255,255,0.8)',
alignItems: 'center',
},
bubble: {
position: 'absolute',
top: getFontSize(4),
right: getFontSize(5),
marginTop: getFontSize(5),
},
toggleVolumeButton: {
position: 'absolute',
left: 0,
bottom: 0,
padding: getFontSize(2),
},
text: {
padding: 70,
textAlign: 'center',
alignSelf: 'center',
fontSize: getFontSize(1.8),
color: '#000',
fontFamily: 'ComicNeue-Bold',
},
});
const phrases = require('../data/phrases.json');
const mapStateToProps = state => ({
text: state.getIn(['hemmo', 'text']),
audio: state.getIn(['hemmo', 'audio']),
muted: state.getIn(['hemmo', 'muted']),
activeRoute: state.getIn([
'navigatorState',
'routes',
state.getIn(['navigatorState', 'index']),
'routeName',
]),
routes: state.getIn(['navigatorState', 'routes']),
});
const mapDispatchToProps = dispatch => ({
toggleMute: () => dispatch(toggleMute()),
setText: text => dispatch(setText(text)),
setAudio: audio => dispatch(setAudio(audio)),
});
@connect(mapStateToProps, mapDispatchToProps)
export default class Hemmo extends Component {
static propTypes = {
activeRoute: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
audio: PropTypes.string.isRequired,
setText: PropTypes.func.isRequired,
setAudio: PropTypes.func.isRequired,
toggleMute: PropTypes.func.isRequired,
muted: PropTypes.bool.isRequired,
};
state = {
currentAppState: AppState.currentState,
showBubble: false,
mutePressed: false,
};
componentDidMount() {
AppState.addEventListener('change', this.handleAppStateChange);
}
async componentDidUpdate(prevProps) {
if (
prevProps.activeRoute !== this.props.activeRoute &&
this.props.routes.size > prevProps.routes.size
) {
if (this.props.activeRoute === 'Ending') {
setTimeout(this.showBubble, 3000);
} else {
await this.showBubble();
}
}
if (this.props.routes.size < prevProps.routes.size) {
await this.setEmptyText();
}
}
componentWillUnmount() {
AppState.removeEventListener('change', this.handleAppStateChange);
}
onEnd = () => {
setTimeout(this.hideBubble, 500);
};
setDefaultText = async () => {
const routeName = this.props.activeRoute;
if (!phrases[routeName]) return;
await this.props.setText(phrases[routeName].text);
await this.props.setAudio(phrases[routeName].audio);
};
setEmptyText = async () => {
await this.props.setText('');
await this.props.setAudio('');
};
showBubble = async () => {
if (!this.props.text || !this.props.audio) {
await this.setDefaultText();
}
if (
this.state.currentAppState === 'active' &&
this.props.text &&
this.props.audio
) {
this.setState({ showBubble: true });
}
};
hideBubble = async () => {
this.setState({ showBubble: false, mutePressed: false });
await this.setEmptyText();
};
toggleMute = async () => {
if (this.props.muted) {
await this.props.setAudio(phrases.unmute.audio);
await this.props.setText(phrases.unmute.text);
} else {
this.setState({ mutePressed: true });
await this.props.setAudio(phrases.mute.audio);
await this.props.setText(phrases.mute.text);
}
await this.props.toggleMute();
};
handleAppStateChange = async currentAppState => {
if (currentAppState !== 'active') {
await this.hideBubble();
}
this.setState({ currentAppState });
};
renderBubble = () =>
this.state.showBubble
? <Modal
animationType={'fade'}
transparent
visible={this.state.showBubble}
onRequestClose={this.hideBubble}
supportedOrientations={['portrait', 'landscape']}
>
<TouchableOpacity
style={styles.bubbleContainer}
onPress={this.hideBubble}
>
{this.renderHemmoButton()}
{this.renderBubbleButton()}
{this.renderMuteButton()}
</TouchableOpacity>
</Modal>
: null;
renderAudio = () => {
if (
this.state.currentAppState === 'active' &&
this.props.audio &&
(!this.props.muted || this.state.mutePressed)
) {
return (
<AudioPlayerViewContainer
onEnd={this.onEnd}
audioTrack={this.props.audio}
/>
);
}
return null;
};
renderMuteButton = () =>
<View style={styles.toggleVolumeButton}>
<AppButton
background={this.props.muted ? 'volume_is_off' : 'volume_is_on'}
onPress={this.toggleMute}
width={getSizeByWidth('volume_is_off', 0.23).width}
shadow
/>
</View>;
renderBubbleButton = () =>
<View style={styles.bubble}>
<AppButton
background="up_big"
onPress={this.hideBubble}
width={getSizeByWidth('up_big', 0.8).width}
shadow
>
<Text style={styles.text}>
{this.props.text}
</Text>
</AppButton>
</View>;
renderHemmoButton = () =>
<View style={styles.hemmo}>
<AppButton
background="hemmo"
onPress={this.state.showBubble ? this.hideBubble : this.showBubble}
width={getSizeByWidth('hemmo', 0.12).width}
shadow
/>
</View>;
render() {
if (
this.props.activeRoute === 'Login' ||
this.props.activeRoute === 'Settings'
) {
return null;
}
return (
<View style={styles.container}>
{this.renderBubble()}
{this.renderAudio()}
{phrases[this.props.activeRoute] ? this.renderHemmoButton() : null}
</View>
);
}
}
|
examples/with-clerk/pages/index.js | azukaru/next.js | import React from 'react'
import Head from 'next/head'
import Link from 'next/link'
import styles from '../styles/Home.module.css'
import { SignedIn, SignedOut } from '@clerk/nextjs'
const ClerkFeatures = () => (
<Link href="/user">
<a className={styles.cardContent}>
<img src="/icons/layout.svg" />
<div>
<h3>Explore features provided by Clerk</h3>
<p>
Interact with the user button, user profile, and more to preview what
your users will see
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/arrow-right.svg" />
</div>
</a>
</Link>
)
const SignupLink = () => (
<Link href="/sign-up">
<a className={styles.cardContent}>
<img src="/icons/user-plus.svg" />
<div>
<h3>Sign up for an account</h3>
<p>
Sign up and sign in to explore all the features provided by Clerk
out-of-the-box
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/arrow-right.svg" />
</div>
</a>
</Link>
)
const apiSample = `import { withSession } from '@clerk/nextjs/api'
export default withSession((req, res) => {
res.statusCode = 200
if (req.session) {
res.json({ id: req.session.userId })
} else {
res.json({ id: null })
}
})`
// Main component using <SignedIn> & <SignedOut>.
//
// The SignedIn and SignedOut components are used to control rendering depending
// on whether or not a visitor is signed in.
//
// https://docs.clerk.dev/frontend/react/signedin-and-signedout
const Main = () => (
<main className={styles.main}>
<h1 className={styles.title}>Welcome to your new app</h1>
<p className={styles.description}>Sign up for an account to get started</p>
<div className={styles.cards}>
<div className={styles.card}>
<SignedIn>
<ClerkFeatures />
</SignedIn>
<SignedOut>
<SignupLink />
</SignedOut>
</div>
<div className={styles.card}>
<Link href="https://dashboard.clerk.dev">
<a target="_blank" rel="noreferrer" className={styles.cardContent}>
<img src="/icons/settings.svg" />
<div>
<h3>Configure settings for your app</h3>
<p>
Visit Clerk to manage instances and configure settings for user
management, theme, and more
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/arrow-right.svg" />
</div>
</a>
</Link>
</div>
</div>
<APIRequest />
<div className={styles.links}>
<Link href="https://docs.clerk.dev">
<a target="_blank" rel="noreferrer" className={styles.link}>
<span className={styles.linkText}>Read Clerk documentation</span>
</a>
</Link>
<Link href="https://nextjs.org/docs">
<a target="_blank" rel="noreferrer" className={styles.link}>
<span className={styles.linkText}>Read NextJS documentation</span>
</a>
</Link>
</div>
</main>
)
const APIRequest = () => {
React.useEffect(() => {
if (window.Prism) {
window.Prism.highlightAll()
}
})
const [response, setResponse] = React.useState(
'// Click above to run the request'
)
const makeRequest = async () => {
setResponse('// Loading...')
try {
const res = await fetch('/api/getAuthenticatedUserId')
const body = await res.json()
setResponse(JSON.stringify(body, null, ' '))
} catch (e) {
setResponse(
'// There was an error with the request. Please contact [email protected]'
)
}
}
return (
<div className={styles.backend}>
<h2>API request example</h2>
<div className={styles.card}>
<button
target="_blank"
rel="noreferrer"
className={styles.cardContent}
onClick={() => makeRequest()}
>
<img src="/icons/server.svg" />
<div>
<h3>fetch('/api/getAuthenticatedUserId')</h3>
<p>
Retrieve the user ID of the signed in user, or null if there is no
user
</p>
</div>
<div className={styles.arrow}>
<img src="/icons/download.svg" />
</div>
</button>
</div>
<h4>
Response
<em>
<SignedIn>
You are signed in, so the request will return your user ID
</SignedIn>
<SignedOut>
You are signed out, so the request will return null
</SignedOut>
</em>
</h4>
<pre>
<code className="language-js">{response}</code>
</pre>
<h4>pages/api/getAuthenticatedUserId.js</h4>
<pre>
<code className="language-js">{apiSample}</code>
</pre>
</div>
)
}
// Footer component
const Footer = () => (
<footer className={styles.footer}>
Powered by{' '}
<a href="https://clerk.dev" target="_blank" rel="noopener noreferrer">
<img src="/clerk.svg" alt="Clerk.dev" className={styles.logo} />
</a>
+
<a href="https://nextjs.org/" target="_blank" rel="noopener noreferrer">
<img src="/nextjs.svg" alt="Next.js" className={styles.logo} />
</a>
</footer>
)
const Home = () => (
<div className={styles.container}>
<Head>
<title>Create Next App</title>
<link rel="icon" href="/favicon.ico" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
></meta>
</Head>
<Main />
<Footer />
</div>
)
export default Home
|
src/components/ProgressBar/ProgressBar.js | vonZ/rc-vvz | import React from 'react';
import PropTypes from 'prop-types';
class ProgressBar extends React.Component {
getColor = (percent) => {
if (this.props.percent === 100) return 'green';
return this.props.percent > 50 ? 'lightgreen' : 'red';
}
getWidthAsPercentOfTotalWidth = () => {
return parseInt(this.props.width * (this.props.percent / 100), 10);
}
render() {
const {percent, width, height} = this.props;
return (
<div style={{border: 'solid 1px lightgray', width: width}}>
<div style={{
width: this.getWidthAsPercentOfTotalWidth(),
height,
backgroundColor: this.getColor(percent)
}} />
</div>
);
}
}
ProgressBar.propTypes = {
/** Percent of progress completed */
percent: PropTypes.number.isRequired,
/** Bar width */
width: PropTypes.number.isRequired,
/** Bar height */
height: PropTypes.number
};
ProgressBar.defaultProps = {
height: 5
};
export default ProgressBar;
|
src/containers/HomeContainer.js | hoppispace/hoppi-space-web-app | import React from 'react';
import { URL_FACEBOOK, URL_INSTAGRAM, URL_TWITTER } from "../constants";
import SearchForm from '../components/Search/SearchForm';
const HomePage = () => {
return (
<main id="home-container">
<div className="container-fluid">
<div className="row">
<div id="lead" className="col-lg-12 align-center">
<div id="social-media-links">
<a href={URL_FACEBOOK}><img src={require("../assets/icons/socialmedia/icons8-facebook.svg")}/></a>
<a href={URL_INSTAGRAM}><img src={require("../assets/icons/socialmedia/icons8-instagram.svg")}/></a>
<a href={URL_TWITTER}><img src={require("../assets/icons/socialmedia/icons8-twitter.svg")}/></a>
</div>
<h1 className="hoppiSpaceBrandName">hoppi space</h1>
<h4>Connecting the artist within to the space you are without</h4>
<SearchForm/>
</div>
</div>
<div className="row">
<div id="how-it-works" className="col-lg-12">
<h2>How It Works</h2>
<h3>Browse, Book, Pay</h3>
<hr/>
<p className="lead">We are your new favorite local coffee shop community board. Browse hundreds
of available workshops in your area or worldwide using our fast and efficient search engine.
We optimize results with your craft needs, tools, and budget in mind.
When you've found "the one", our effortless booking system will relay your request to our
owners for confirmation, and utilizing our secure Braintree-based payment system, make your
payment. <span className="font-weight-bold font-italic">Welcome home!</span></p>
</div>
</div>
</div>
</main>
);
};
export default HomePage;
|
code/web/node_modules/react-bootstrap/es/Label.js | zyxcambridge/RecordExistence | import _Object$values from 'babel-runtime/core-js/object/values';
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, bsStyles, getClassSet, splitBsProps } from './utils/bootstrapUtils';
import { State, Style } from './utils/StyleConfig';
var Label = function (_React$Component) {
_inherits(Label, _React$Component);
function Label() {
_classCallCheck(this, Label);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Label.prototype.hasContent = function hasContent(children) {
var result = false;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (child || child === 0) {
result = true;
}
});
return result;
};
Label.prototype.render = function render() {
var _props = this.props;
var className = _props.className;
var children = _props.children;
var props = _objectWithoutProperties(_props, ['className', 'children']);
var _splitBsProps = splitBsProps(props);
var bsProps = _splitBsProps[0];
var elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), {
// Hack for collapsing on IE8.
hidden: !this.hasContent(children)
});
return React.createElement(
'span',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
children
);
};
return Label;
}(React.Component);
export default bsClass('label', bsStyles([].concat(_Object$values(State), [Style.DEFAULT, Style.PRIMARY]), Style.DEFAULT, Label)); |
packages/ringcentral-widgets/components/CallListV2/index.js | ringcentral/ringcentral-js-widget | import React from 'react';
import PropTypes from 'prop-types';
import { List } from 'react-virtualized';
import CallItem from '../CallItem';
import NoCalls from '../NoCalls';
export default class CallListV2 extends React.PureComponent {
constructor(props) {
super(props);
this.state = {
extendedIndex: null,
};
this._list = React.createRef();
}
componentWillReceiveProps(nextProps) {
const { extendedIndex } = this.state;
if (
extendedIndex !== null &&
this.props.calls[extendedIndex] !== nextProps.calls[extendedIndex]
) {
this._setExtendedIndex(null);
}
}
_setExtendedIndex = (extendedIndex) => {
this.setState(
{
extendedIndex,
},
() => {
if (this._list && this._list.current) {
this._list.current.recomputeRowHeights(0);
}
},
);
};
_onSizeChanged = (index) => {
if (this.state.extendedIndex === index) {
this._setExtendedIndex(null);
} else {
this._setExtendedIndex(index);
}
};
_renderRowHeight = ({ index }) => {
// If we don't add extra height for the last item
// the toggle button will be cut off
const margin = index === this.props.calls.length - 1 ? 15 : 0;
const rowHeight =
index === this.state.extendedIndex
? this.props.extendedRowHeight
: this.props.rowHeight;
return rowHeight + margin;
};
_rowRender = ({ index, key, style }) => {
const {
className,
brand,
currentLocale,
calls,
areaCode,
countryCode,
onViewContact,
onCreateContact,
createEntityTypes,
onLogCall,
onClickToDial,
onClickToSms,
isLoggedContact,
disableLinks,
disableCallButton,
disableClickToDial,
outboundSmsPermission,
internalSmsPermission,
active,
dateTimeFormatter,
loggingMap,
webphoneAnswer,
webphoneReject,
webphoneHangup,
webphoneResume,
enableContactFallback,
autoLog,
showContactDisplayPlaceholder,
sourceIcons,
phoneTypeRenderer,
phoneSourceNameRenderer,
renderContactName,
renderExtraButton,
contactDisplayStyle,
externalViewEntity,
externalHasEntity,
readTextPermission,
} = this.props;
let content;
if (index >= calls.length) {
content = (
<div className={className}>
<NoCalls currentLocale={currentLocale} active={active} />
</div>
);
} else {
const call = calls[index];
content = (
<CallItem
key={call.id}
renderIndex={index}
extended={this.state.extendedIndex === index}
style={style}
call={call}
currentLocale={currentLocale}
brand={brand}
areaCode={areaCode}
countryCode={countryCode}
onViewContact={onViewContact}
onCreateContact={onCreateContact}
createEntityTypes={createEntityTypes}
onLogCall={onLogCall}
onClickToDial={onClickToDial}
onClickToSms={onClickToSms}
isLoggedContact={isLoggedContact}
disableLinks={disableLinks}
disableCallButton={disableCallButton}
disableClickToDial={disableClickToDial}
outboundSmsPermission={outboundSmsPermission}
internalSmsPermission={internalSmsPermission}
active={active}
dateTimeFormatter={dateTimeFormatter}
isLogging={!!loggingMap[call.sessionId]}
webphoneAnswer={webphoneAnswer}
webphoneReject={webphoneReject}
webphoneHangup={webphoneHangup}
webphoneResume={webphoneResume}
enableContactFallback={enableContactFallback}
autoLog={autoLog}
showContactDisplayPlaceholder={showContactDisplayPlaceholder}
sourceIcons={sourceIcons}
phoneTypeRenderer={phoneTypeRenderer}
phoneSourceNameRenderer={phoneSourceNameRenderer}
renderContactName={renderContactName}
renderExtraButton={renderExtraButton}
contactDisplayStyle={contactDisplayStyle}
externalViewEntity={externalViewEntity}
externalHasEntity={externalHasEntity}
readTextPermission={readTextPermission}
onSizeChanged={this._onSizeChanged}
// disable animation when rendered with react-virtualized
withAnimation={false}
/>
);
}
return (
<div key={key} style={style}>
{content}
</div>
);
};
noRowsRender = () => {
const { currentLocale, active } = this.props;
return <NoCalls currentLocale={currentLocale} active={active} />;
};
render() {
const { width, height, calls, className } = this.props;
return (
<div>
<List
style={{ outline: 'none', overflowY: 'auto' }}
containerStyle={{ overflow: 'visible' }}
ref={this._list}
width={width}
height={height}
overscanRowCount={15}
className={className}
rowCount={calls.length}
rowHeight={this._renderRowHeight}
rowRenderer={this._rowRender}
noRowsRenderer={this.noRowsRender}
/>
</div>
);
}
}
CallListV2.propTypes = {
className: PropTypes.string,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
brand: PropTypes.string.isRequired,
currentLocale: PropTypes.string.isRequired,
calls: PropTypes.arrayOf(CallItem.propTypes.call).isRequired,
active: PropTypes.bool,
areaCode: PropTypes.string.isRequired,
countryCode: PropTypes.string.isRequired,
onViewContact: PropTypes.func,
onCreateContact: PropTypes.func,
createEntityTypes: PropTypes.array,
onLogCall: PropTypes.func,
onClickToDial: PropTypes.func,
onClickToSms: PropTypes.func,
isLoggedContact: PropTypes.func,
loggingMap: PropTypes.object,
disableLinks: PropTypes.bool,
disableCallButton: PropTypes.bool,
disableClickToDial: PropTypes.bool,
outboundSmsPermission: PropTypes.bool,
internalSmsPermission: PropTypes.bool,
dateTimeFormatter: PropTypes.func.isRequired,
webphoneAnswer: PropTypes.func,
webphoneReject: PropTypes.func,
webphoneHangup: PropTypes.func,
webphoneResume: PropTypes.func,
enableContactFallback: PropTypes.bool,
autoLog: PropTypes.bool,
showContactDisplayPlaceholder: PropTypes.bool,
sourceIcons: PropTypes.object,
phoneTypeRenderer: PropTypes.func,
phoneSourceNameRenderer: PropTypes.func,
renderContactName: PropTypes.func,
renderExtraButton: PropTypes.func,
contactDisplayStyle: PropTypes.string,
externalViewEntity: PropTypes.func,
externalHasEntity: PropTypes.func,
readTextPermission: PropTypes.bool,
rowHeight: PropTypes.number,
extendedRowHeight: PropTypes.number,
};
CallListV2.defaultProps = {
className: null,
active: false,
disableLinks: false,
disableCallButton: false,
disableClickToDial: false,
outboundSmsPermission: false,
internalSmsPermission: false,
onViewContact: undefined,
onCreateContact: undefined,
createEntityTypes: undefined,
onLogCall: undefined,
isLoggedContact: undefined,
onClickToDial: undefined,
onClickToSms: undefined,
loggingMap: {},
webphoneAnswer: undefined,
webphoneReject: undefined,
webphoneHangup: undefined,
webphoneResume: undefined,
enableContactFallback: undefined,
showContactDisplayPlaceholder: true,
autoLog: false,
sourceIcons: undefined,
phoneTypeRenderer: undefined,
phoneSourceNameRenderer: undefined,
renderContactName: undefined,
renderExtraButton: undefined,
contactDisplayStyle: undefined,
externalViewEntity: undefined,
externalHasEntity: undefined,
readTextPermission: true,
rowHeight: 65,
extendedRowHeight: 130,
};
|
src/svg-icons/av/fiber-new.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvFiberNew = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zM8.5 15H7.3l-2.55-3.5V15H3.5V9h1.25l2.5 3.5V9H8.5v6zm5-4.74H11v1.12h2.5v1.26H11v1.11h2.5V15h-4V9h4v1.26zm7 3.74c0 .55-.45 1-1 1h-4c-.55 0-1-.45-1-1V9h1.25v4.51h1.13V9.99h1.25v3.51h1.12V9h1.25v5z"/>
</SvgIcon>
);
AvFiberNew = pure(AvFiberNew);
AvFiberNew.displayName = 'AvFiberNew';
AvFiberNew.muiName = 'SvgIcon';
export default AvFiberNew;
|
examples/todomvc/containers/TodoApp.js | rt2zz/redux | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Connector } from 'redux/react';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/TodoActions';
export default class TodoApp extends Component {
render() {
return (
<Connector select={state => ({ todos: state.todos })}>
{this.renderChild}
</Connector>
);
}
renderChild({ todos, dispatch }) {
const actions = bindActionCreators(TodoActions, dispatch);
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
|
src/svg-icons/action/perm-device-information.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermDeviceInformation = (props) => (
<SvgIcon {...props}>
<path d="M13 7h-2v2h2V7zm0 4h-2v6h2v-6zm4-9.99L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
ActionPermDeviceInformation = pure(ActionPermDeviceInformation);
ActionPermDeviceInformation.displayName = 'ActionPermDeviceInformation';
ActionPermDeviceInformation.muiName = 'SvgIcon';
export default ActionPermDeviceInformation;
|
node_modules/react-router/es6/IndexRedirect.js | wojtczat/WeatherApp | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import Redirect from './Redirect';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes;
var string = _React$PropTypes.string;
var object = _React$PropTypes.object;
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
var IndexRedirect = React.createClass({
displayName: 'IndexRedirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = Redirect.createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRedirect; |
frontend/src/Settings/ImportLists/ImportLists/ImportLists.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Card from 'Components/Card';
import FieldSet from 'Components/FieldSet';
import Icon from 'Components/Icon';
import PageSectionContent from 'Components/Page/PageSectionContent';
import { icons } from 'Helpers/Props';
import AddImportListModal from './AddImportListModal';
import EditImportListModalConnector from './EditImportListModalConnector';
import ImportList from './ImportList';
import styles from './ImportLists.css';
class ImportLists extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
isAddImportListModalOpen: false,
isEditImportListModalOpen: false
};
}
//
// Listeners
onAddImportListPress = () => {
this.setState({ isAddImportListModalOpen: true });
}
onAddImportListModalClose = ({ listSelected = false } = {}) => {
this.setState({
isAddImportListModalOpen: false,
isEditImportListModalOpen: listSelected
});
}
onEditImportListModalClose = () => {
this.setState({ isEditImportListModalOpen: false });
}
//
// Render
render() {
const {
items,
onConfirmDeleteImportList,
...otherProps
} = this.props;
const {
isAddImportListModalOpen,
isEditImportListModalOpen
} = this.state;
return (
<FieldSet
legend="Import Lists"
>
<PageSectionContent
errorMessage="Unable to load Lists"
{...otherProps}
>
<div className={styles.lists}>
{
items.map((item) => {
return (
<ImportList
key={item.id}
{...item}
onConfirmDeleteImportList={onConfirmDeleteImportList}
/>
);
})
}
<Card
className={styles.addList}
onPress={this.onAddImportListPress}
>
<div className={styles.center}>
<Icon
name={icons.ADD}
size={45}
/>
</div>
</Card>
</div>
<AddImportListModal
isOpen={isAddImportListModalOpen}
onModalClose={this.onAddImportListModalClose}
/>
<EditImportListModalConnector
isOpen={isEditImportListModalOpen}
onModalClose={this.onEditImportListModalClose}
/>
</PageSectionContent>
</FieldSet>
);
}
}
ImportLists.propTypes = {
isFetching: PropTypes.bool.isRequired,
error: PropTypes.object,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
onConfirmDeleteImportList: PropTypes.func.isRequired
};
export default ImportLists;
|
screens/PersonDetail.js | FindEarth/app | import React from 'react'
import PropTypes from 'prop-types'
import Colors from '../constants/Colors'
import Styles from '../styles/PersonDetail'
import HeaderTitle from '../components/HeaderTitle'
import PersonDetailView from '../components/PersonDetailView'
import { Share } from 'react-native'
import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import * as allActions from '../actions'
const rightIcon = {
ios: 'ios-share-outline',
android: 'md-share',
onPress: personShare,
}
const shareOptions = {
url: 'https://find.earth/',
name: 'personas perdidas',
}
function personShare() {
Share.share({
message: `Ayudanos a encontrar a ${shareOptions.name}`,
url: shareOptions.url,
title: `Compartir ${shareOptions.name}`,
}, {
dialogTitle: 'Compartir',
}
)
.then((result) => {
if (result.action === Share.sharedAction) {
if (result.activityType) {
console.log('Shared with an activityType: ', result.activityType)
} else {
console.log('Shared')
}
} else if (result.action === Share.dismissedAction) {
console.log('Dismissed')
}
})
.catch((error) => console.log(error.message))
}
class PersonDetail extends React.Component {
static propTypes = {
personSelected: PropTypes.object.isRequired,
refreshingPerson: PropTypes.bool.isRequired,
errorRefreshingPerson: PropTypes.bool.isRequired,
refreshPersonDetail: PropTypes.func.isRequired,
}
static route = {
navigationBar: {
title: 'Descripción',
backgroundColor: Colors.white,
borderBottomWidth: 1,
tintColor: Colors.tintColor,
renderTitle: (route) => (
<HeaderTitle
title={route.params.person.name}
rightIcon={rightIcon}
/>
),
},
}
componentWillMount() {
this.updateHeaderName()
}
componentWillReceiveProps() {
this.updateHeaderName()
}
updateHeaderName = () => {
const person = this.props.personSelected
if (person) {
this.props.route.params.person.name = person.name
shareOptions.name = person.name
shareOptions.url = `https://find.earth/person/${person._slug}`
}
}
onRefreshPerson = () => {
this.props.refreshPersonDetail()
}
render() {
return (
<PersonDetailView
styles={Styles}
person={this.props.personSelected}
refreshingPerson={this.props.refreshingPerson}
errorRefreshingPerson={this.props.errorRefreshingPerson}
onRefreshPerson={this.onRefreshPerson}
/>
)
}
}
function mapStateToProps (state) {
return {
personSelected: state.personDetail.personSelected,
refreshingPerson: state.personDetail.refreshingPerson,
errorRefreshingPerson: state.personDetail.errorRefreshingPerson,
}
}
function mapDispatchToProps (dispatch) {
const actions = bindActionCreators(allActions, dispatch)
return {
refreshPersonDetail: actions.refreshPersonDetail,
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(PersonDetail)
|
src/mongostick/frontend/src/screens/Collections.js | RockingRolli/mongostick | import React from 'react'
import { Col, Row, Table } from 'antd'
import { connect } from 'react-redux'
import { formatBytes } from '../lib/mongodb'
class Collections extends React.Component {
getColumns = () => {
return [
{
title: 'Name',
dataIndex: 'ns',
key: 'ns',
},
{
title: 'storageSize',
dataIndex: 'storageSize',
key:'storageSize',
render: text => formatBytes(text),
sorter: (a, b) => a.storageSize - b.storageSize,
},
{
title:'Size',
dataIndex: 'size',
key:'size',
render: text => formatBytes(text),
sorter: (a, b) => a.size - b.size,
},
{
title:'count',
dataIndex: 'count',
key:'count',
render: text => text.toLocaleString(),
sorter: (a, b) => a.count - b.count,
},
{
title:'totalIndexSize',
dataIndex: 'totalIndexSize',
key:'totalIndexSize',
render: text => formatBytes(text),
sorter: (a, b) => a.totalIndexSize - b.totalIndexSize,
},
{
title:'nindexes',
dataIndex: 'nindexes',
key:'nindexes',
sorter: (a, b) => a.nindexes - b.nindexes,
},
{
title:'avgObjSize',
dataIndex: 'avgObjSize',
key:'avgObjSize',
render: text => formatBytes(text),
sorter: (a, b) => a.avgObjSize - b.avgObjSize,
},
{
title:'capped',
dataIndex: 'capped',
key:'capped',
render: text => text.toString(),
},
]
}
getDataSource = () => {
const { databases } = this.props
const { db_name } = this.props.match.params
const database = databases[db_name]
if (database === undefined) {
return []
}
return Object.keys(database.collections).map((index) => database.collections[index])
}
render() {
return (
<div>
{this.props.children}
<Row style={{ background: '#fff' }}>
<Col span={24}>
<Table
dataSource={this.getDataSource()}
columns={this.getColumns()}
rowKey={record => record.ns}
/>
</Col>
</Row>
</div>
)
}
}
const mapStateToProps = store => {
return {
databases: store.databases,
}
}
export default connect(mapStateToProps)(Collections)
|
app/javascript/mastodon/features/status/components/action_bar.js | Arukas/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import IconButton from '../../../components/icon_button';
import ImmutablePropTypes from 'react-immutable-proptypes';
import DropdownMenuContainer from '../../../containers/dropdown_menu_container';
import { defineMessages, injectIntl } from 'react-intl';
import { me } from '../../../initial_state';
const messages = defineMessages({
delete: { id: 'status.delete', defaultMessage: 'Delete' },
mention: { id: 'status.mention', defaultMessage: 'Mention @{name}' },
reply: { id: 'status.reply', defaultMessage: 'Reply' },
reblog: { id: 'status.reblog', defaultMessage: 'Boost' },
cannot_reblog: { id: 'status.cannot_reblog', defaultMessage: 'This post cannot be boosted' },
favourite: { id: 'status.favourite', defaultMessage: 'Favourite' },
mute: { id: 'status.mute', defaultMessage: 'Mute @{name}' },
muteConversation: { id: 'status.mute_conversation', defaultMessage: 'Mute conversation' },
unmuteConversation: { id: 'status.unmute_conversation', defaultMessage: 'Unmute conversation' },
block: { id: 'status.block', defaultMessage: 'Block @{name}' },
report: { id: 'status.report', defaultMessage: 'Report @{name}' },
share: { id: 'status.share', defaultMessage: 'Share' },
pin: { id: 'status.pin', defaultMessage: 'Pin on profile' },
unpin: { id: 'status.unpin', defaultMessage: 'Unpin from profile' },
embed: { id: 'status.embed', defaultMessage: 'Embed' },
});
@injectIntl
export default class ActionBar extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
onReply: PropTypes.func.isRequired,
onReblog: PropTypes.func.isRequired,
onFavourite: PropTypes.func.isRequired,
onDelete: PropTypes.func.isRequired,
onMention: PropTypes.func.isRequired,
onMute: PropTypes.func,
onMuteConversation: PropTypes.func,
onBlock: PropTypes.func,
onReport: PropTypes.func,
onPin: PropTypes.func,
onEmbed: PropTypes.func,
intl: PropTypes.object.isRequired,
};
handleReplyClick = () => {
this.props.onReply(this.props.status);
}
handleReblogClick = (e) => {
this.props.onReblog(this.props.status, e);
}
handleFavouriteClick = () => {
this.props.onFavourite(this.props.status);
}
handleDeleteClick = () => {
this.props.onDelete(this.props.status);
}
handleMentionClick = () => {
this.props.onMention(this.props.status.get('account'), this.context.router.history);
}
handleMuteClick = () => {
this.props.onMute(this.props.status.get('account'));
}
handleConversationMuteClick = () => {
this.props.onMuteConversation(this.props.status);
}
handleBlockClick = () => {
this.props.onBlock(this.props.status.get('account'));
}
handleReport = () => {
this.props.onReport(this.props.status);
}
handlePinClick = () => {
this.props.onPin(this.props.status);
}
handleShare = () => {
navigator.share({
text: this.props.status.get('search_index'),
url: this.props.status.get('url'),
});
}
handleEmbed = () => {
this.props.onEmbed(this.props.status);
}
render () {
const { status, intl } = this.props;
const publicStatus = ['public', 'unlisted'].includes(status.get('visibility'));
const mutingConversation = status.get('muted');
let menu = [];
if (publicStatus) {
menu.push({ text: intl.formatMessage(messages.embed), action: this.handleEmbed });
}
if (me === status.getIn(['account', 'id'])) {
if (publicStatus) {
menu.push({ text: intl.formatMessage(status.get('pinned') ? messages.unpin : messages.pin), action: this.handlePinClick });
}
menu.push(null);
menu.push({ text: intl.formatMessage(mutingConversation ? messages.unmuteConversation : messages.muteConversation), action: this.handleConversationMuteClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.delete), action: this.handleDeleteClick });
} else {
menu.push({ text: intl.formatMessage(messages.mention, { name: status.getIn(['account', 'username']) }), action: this.handleMentionClick });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mute, { name: status.getIn(['account', 'username']) }), action: this.handleMuteClick });
menu.push({ text: intl.formatMessage(messages.block, { name: status.getIn(['account', 'username']) }), action: this.handleBlockClick });
menu.push({ text: intl.formatMessage(messages.report, { name: status.getIn(['account', 'username']) }), action: this.handleReport });
}
const shareButton = ('share' in navigator) && status.get('visibility') === 'public' && (
<div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.share)} icon='share-alt' onClick={this.handleShare} /></div>
);
let reblogIcon = 'retweet';
if (status.get('visibility') === 'direct') reblogIcon = 'envelope';
else if (status.get('visibility') === 'private') reblogIcon = 'lock';
let reblog_disabled = (status.get('visibility') === 'direct' || status.get('visibility') === 'private');
return (
<div className='detailed-status__action-bar'>
<div className='detailed-status__button'><IconButton title={intl.formatMessage(messages.reply)} icon={status.get('in_reply_to_id', null) === null ? 'reply' : 'reply-all'} onClick={this.handleReplyClick} /></div>
<div className='detailed-status__button'><IconButton disabled={reblog_disabled} active={status.get('reblogged')} title={reblog_disabled ? intl.formatMessage(messages.cannot_reblog) : intl.formatMessage(messages.reblog)} icon={reblogIcon} onClick={this.handleReblogClick} /></div>
<div className='detailed-status__button'><IconButton animate active={status.get('favourited')} title={intl.formatMessage(messages.favourite)} icon='star' onClick={this.handleFavouriteClick} activeStyle={{ color: '#ca8f04' }} /></div>
{shareButton}
<div className='detailed-status__action-bar-dropdown'>
<DropdownMenuContainer size={18} icon='ellipsis-h' items={menu} direction='left' title='More' />
</div>
</div>
);
}
}
|
packages/reactor-kitchensink/src/examples/D3/Hierarchy/ConfigurablePivotTreeMap/ConfigurablePivotTreeMap.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Toolbar, Button, Spacer } from '@extjs/ext-react';
import { PivotD3Container } from '@extjs/ext-react-pivot-d3';
import createData from './createData';
import './styles.css';
const regions = {
"Belgium": 'Europe',
"Netherlands": 'Europe',
"United Kingdom": 'Europe',
"Canada": 'North America',
"United States": 'North America',
"Australia": 'Australia'
};
Ext.require(['Ext.pivot.d3.TreeMap']);
export default class ConfigurablePivotTreeMap extends Component {
store = Ext.create('Ext.data.TreeStore', {
fields: [
{name: 'id', type: 'string'},
{name: 'company', type: 'string'},
{name: 'country', type: 'string'},
{name: 'person', type: 'string'},
{name: 'date', type: 'date', dateFormat: 'c'},
{name: 'value', type: 'float'},
{name: 'quantity', type: 'float'},
{
name: 'year',
calculate: function(data){
return parseInt(Ext.Date.format(data.date, "Y"), 10);
}
},{
name: 'month',
calculate: function(data){
return parseInt(Ext.Date.format(data.date, "m"), 10) - 1;
}
},{
name: 'continent',
calculate: function(data){
return regions[data.country];
}
}
],
data: createData()
})
showConfigurator = () => this.refs.mainCtn.showConfigurator()
onShowConfigPanel = panel => {
panel.getLeftAxisHeader().getTitle().setText('Tree labels');
panel.setTopAxisContainerVisible(false);
}
onBeforeAddConfigField = (panel, config) => {
const dest = config.toContainer,
store = dest.getStore();
if (dest.getFieldType() !== 'all' && store.getCount() >= 1) {
// this will force single fields on both axis and aggregate
store.removeAll();
}
}
onShowFieldSettings = (panel, config) => {
const align = config.container.down('[name=align]');
// hide the alignment field in settings since it's useless
if(align) {
align.hide();
}
}
render() {
return (
<PivotD3Container
shadow
ref="mainCtn"
onShowConfigPanel={this.onShowConfigPanel}
onBeforeMoveConfigField={this.onBeforeAddConfigField}
onShowConfigFieldSettings={this.onShowFieldSettings}
matrix={{
store: this.store,
aggregate: [{
dataIndex: 'value',
header: 'Value',
aggregator: 'sum'
}],
leftAxis: [{
dataIndex: 'person',
header: 'Person'
}]
}}
drawing={{xtype: 'pivottreemap'}}
configurator={{
// It is possible to configure a list of fields that can be used to configure the pivot matrix
// If no fields list is supplied then all fields from the Store model are fetched automatically
fields: [{
dataIndex: 'quantity',
header: 'Qty',
// You can even provide a default aggregator function to be used when this field is dropped
// on the agg dimensions
aggregator: 'sum',
formatter: 'number("0")',
settings: {
// Define here in which areas this field could be used
allowed: ['aggregate'],
// Set a custom style for this field to inform the user that it can be dragged only to "Values"
style: {
fontWeight: 'bold'
},
// Define here custom formatters that ca be used on this dimension
formatters: {
'0': 'number("0")',
'0%': 'number("0%")'
}
}
}, {
dataIndex: 'value',
header: 'Value',
settings: {
// Define here in which areas this field could be used
allowed: 'aggregate',
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: ['sum', 'avg', 'count'],
// Set a custom style for this field to inform the user that it can be dragged only to "Values"
style: {
fontWeight: 'bold'
},
// Define here custom formatters that ca be used on this dimension
formatters: {
'0': 'number("0")',
'0.00': 'number("0.00")',
'0,000.00': 'number("0,000.00")',
'0%': 'number("0%")',
'0.00%': 'number("0.00%")'
}
}
}, {
dataIndex: 'company',
header: 'Company',
settings: {
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: ['count']
}
}, {
dataIndex: 'country',
header: 'Country',
settings: {
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: ['count']
}
}, {
dataIndex: 'person',
header: 'Person',
settings: {
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: 'count'
}
}, {
dataIndex: 'year',
header: 'Year',
settings: {
// Define here in which areas this field could be used
allowed: ['leftAxis', 'topAxis']
}
}, {
dataIndex: 'month',
header: 'Month',
labelRenderer: 'monthLabelRenderer',
settings: {
// Define here in which areas this field could be used
allowed: ['leftAxis', 'topAxis']
}
}]
}}
>
<Toolbar docked="top">
<Spacer/>
<Button text="Show configurator" handler={this.showConfigurator}/>
</Toolbar>
</PivotD3Container>
)
}
} |
src/svg-icons/hardware/keyboard-return.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardReturn = (props) => (
<SvgIcon {...props}>
<path d="M19 7v4H5.83l3.58-3.59L8 6l-6 6 6 6 1.41-1.41L5.83 13H21V7z"/>
</SvgIcon>
);
HardwareKeyboardReturn = pure(HardwareKeyboardReturn);
HardwareKeyboardReturn.displayName = 'HardwareKeyboardReturn';
HardwareKeyboardReturn.muiName = 'SvgIcon';
export default HardwareKeyboardReturn;
|
app/components/DrawerHeader/DrawerHeader.js | danielzy95/oaa-chat | import React from 'react'
import { observer } from 'mobx-react'
import IconButton from 'material-ui/IconButton'
import styles from './DrawerHeader.css'
const DrawerHeader = ({ title, backgroundColor, color, close }) => (
<div class={styles.root} style={{ backgroundColor: backgroundColor || '#493553' }}>
<IconButton iconClassName="material-icons"
iconStyle={{color: color || '#7B85AD'}}
style={{ top: '42%' }}
onClick={close}>
arrow_back
</IconButton>
<span class={styles.title}>{title}</span>
</div>
)
export default observer(DrawerHeader) |
src/app.js | williambryan777/react-blog-with-es6 | import React, { Component } from 'react';
import { BlogBox } from './components';
import $ from 'jquery';
class App extends Component {
constructor(props) {
super(props);
this.state = {
blogList: [],
};
}
componentDidMount() {
const postUrl = '/Social/Home/GetHotMicroBlogs';
const queryParams = {
rcount: 0,
startId: 0,
pageIndex: 1,
time: 24,
pageSize: 15,
};
$.post(postUrl, queryParams, (response) => {
const listItems = response.list.Items;
this.setState({
blogList: listItems,
});
});
}
render() {
return (
<div>
<BlogBox blogList={this.state.blogList} />
</div>
);
}
}
export default App;
|
app/javascript/mastodon/features/ui/components/bundle_modal_error.js | cobodo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import IconButton from '../../../components/icon_button';
const messages = defineMessages({
error: { id: 'bundle_modal_error.message', defaultMessage: 'Something went wrong while loading this component.' },
retry: { id: 'bundle_modal_error.retry', defaultMessage: 'Try again' },
close: { id: 'bundle_modal_error.close', defaultMessage: 'Close' },
});
class BundleModalError extends React.PureComponent {
static propTypes = {
onRetry: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
}
handleRetry = () => {
this.props.onRetry();
}
render () {
const { onClose, intl: { formatMessage } } = this.props;
// Keep the markup in sync with <ModalLoading />
// (make sure they have the same dimensions)
return (
<div className='modal-root__modal error-modal'>
<div className='error-modal__body'>
<IconButton title={formatMessage(messages.retry)} icon='refresh' onClick={this.handleRetry} size={64} />
{formatMessage(messages.error)}
</div>
<div className='error-modal__footer'>
<div>
<button
onClick={onClose}
className='error-modal__nav onboarding-modal__skip'
>
{formatMessage(messages.close)}
</button>
</div>
</div>
</div>
);
}
}
export default injectIntl(BundleModalError);
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SvgInclusion.js | gutenye/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import logo from './assets/logo.svg';
export default () => <img id="feature-svg-inclusion" src={logo} alt="logo" />;
|
analysis/shamanelemental/src/modules/features/Overload.js | yajinni/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import { SpellIcon } from 'interface';
import Analyzer from 'parser/core/Analyzer';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import StatisticBox, { STATISTIC_ORDER } from 'parser/ui/StatisticBox';
import Events from 'parser/core/Events';
class Overload extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
spells = [];
statisticOrder = STATISTIC_ORDER.OPTIONAL();
constructor(...args) {
super(...args);
this.active = true;
this.getAbility = spellId => this.abilityTracker.getAbility(spellId);
this.hasIcefury = this.selectedCombatant.hasTalent(SPELLS.ICEFURY_TALENT.id);
this.hasElementalBlast = this.selectedCombatant.hasTalent(SPELLS.ELEMENTAL_BLAST_TALENT.id);
this.spells = [
this.getHits(SPELLS.LAVA_BURST_OVERLOAD_DAMAGE.id, SPELLS.LAVA_BURST_DAMAGE.id),
this.getHits(SPELLS.LIGHTNING_BOLT_OVERLOAD_HIT.id, SPELLS.LIGHTNING_BOLT.id),
this.getHits(SPELLS.CHAIN_LIGHTNING_OVERLOAD.id, SPELLS.CHAIN_LIGHTNING.id),
this.hasElementalBlast && this.getHits(SPELLS.ELEMENTAL_BLAST_OVERLOAD.id, SPELLS.ELEMENTAL_BLAST_TALENT.id),
this.hasIcefury && this.getHits(SPELLS.ICEFURY_OVERLOAD.id, SPELLS.ICEFURY_TALENT.id),
];
this.addEventListener(Events.fightend, this.onFightend);
}
getHits(overloadSpellId, normalSpellId) {
const overloadSpell = this.getAbility(overloadSpellId);
const normalSpell = this.getAbility(normalSpellId);
const normal = !normalSpell.ability ? 0 : normalSpell.damageHits;
const overloads = !overloadSpell.ability ? 0 : overloadSpell.damageHits;
return {
id: overloadSpellId,
name: !normalSpell.ability ? 'a spell' : normalSpell.ability.name,
normal,
overloads,
percent: overloads / normal,
};
}
onFightend() {
this.spells = [
this.getHits(SPELLS.LAVA_BURST_OVERLOAD_DAMAGE.id, SPELLS.LAVA_BURST_DAMAGE.id),
this.getHits(SPELLS.LIGHTNING_BOLT_OVERLOAD_HIT.id, SPELLS.LIGHTNING_BOLT.id),
this.getHits(SPELLS.CHAIN_LIGHTNING_OVERLOAD.id, SPELLS.CHAIN_LIGHTNING.id),
this.hasElementalBlast && this.getHits(SPELLS.ELEMENTAL_BLAST_OVERLOAD.id, SPELLS.ELEMENTAL_BLAST_TALENT.id),
this.hasIcefury && this.getHits(SPELLS.ICEFURY_OVERLOAD.id, SPELLS.ICEFURY_TALENT.id),
];
}
renderOverloads(spell) {
if (!spell) {
return null;
}
return (
<li key={spell.id}>
<SpellIcon
id={spell.id}
style={{
height: '1.3em',
marginTop: '-.1em',
}}
/>
<span style={{ display: 'inline-block', textAlign: 'left', marginLeft: '0.5em' }}>
{spell.overloads} / {spell.normal}
</span>
</li>
);
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.ELEMENTAL_MASTERY.id} />}
value={(
<ul style={{ listStyle: 'none', paddingLeft: 0 }}>
{this.spells.map(spell => this.renderOverloads(spell))}
</ul>
)}
label="Overload procs"
tooltip={`${this.spells[0].overloads} / ${this.spells[0].normal} means you hit the target ${this.spells[0].normal} times with ${this.spells[0].name} and got ${this.spells[0].overloads} extra overload hits.`}
/>
);
}
}
export default Overload;
|
docs-ui/components/alertLink.stories.js | beeftornado/sentry | import React from 'react';
import {withInfo} from '@storybook/addon-info';
import AlertLink from 'app/components/alertLink';
import {IconDocs, IconGeneric, IconMail, IconStack, IconStar} from 'app/icons';
export default {
title: 'Core/Alerts/AlertLink',
};
export const Default = withInfo(
'A way to loudly link between different parts of the application'
)(() => [
<AlertLink to="/settings/account/notifications" key="1">
Check out the notifications settings panel.
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="error" key="2">
Do not forget to read the docs ya dum dum!
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="info" key="3">
Install this thing or else!
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="success" key="4">
Gj you did it. Now go here.
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="muted" key="5">
I am saying nothing, ok?
</AlertLink>,
]);
Default.story = {
name: 'default',
};
export const WithAnIcon = withInfo('You can optionally pass an icon src')(() => [
<AlertLink to="/settings/account/notifications" icon={<IconMail />} key="1">
Gumbo beet greens corn soko endive gumbo gourd. Parsley shallot courgette tatsoi pea
sprouts fava bean collard greens dandelion okra wakame tomato. Dandelion cucumber
earthnut pea peanut soko zucchini.
</AlertLink>,
<AlertLink
to="/settings/account/notifications"
icon={<IconDocs />}
priority="error"
key="2"
>
Do not forget to read the docs ya dum dum!
</AlertLink>,
<AlertLink
to="/settings/account/notifications"
icon={<IconStack />}
priority="info"
key="3"
>
Install this thing or else!
</AlertLink>,
<AlertLink
to="/settings/account/notifications"
icon={<IconStar />}
priority="success"
key="4"
>
Gj you did it. Now go here.
</AlertLink>,
<AlertLink
to="/settings/account/notifications"
icon={<IconGeneric />}
priority="muted"
key="5"
>
I am saying nothing, ok?
</AlertLink>,
]);
WithAnIcon.story = {
name: 'with an icon',
};
export const Small = withInfo('You can optionally pass an icon src')(() => [
<AlertLink to="/settings/account/notifications" size="small" key="1">
Check out the notifications settings panel.
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="error" size="small" key="2">
Do not forget to read the docs ya dum dum!
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="info" size="small" key="3">
Install this thing or else!
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="success" size="small" key="4">
Gj you did it. Now go here.
</AlertLink>,
<AlertLink to="/settings/account/notifications" priority="muted" size="small" key="5">
I am saying nothing, ok?
</AlertLink>,
]);
Small.story = {
name: 'small',
};
|
app/components/CollectionHeader.js | jackokerman/react-discogs-dj | import React from 'react';
import HeaderColumn from './HeaderColumn.js';
const columns = [
{ column: 'artist', display: 'Artist' },
{ column: 'title', display: 'Title' },
{ column: 'year', display: 'Year' },
{ column: 'added', display: 'Added' },
];
const CollectionHeader = props => (
<tr>
{columns.map((column, i) => {
if (props.sortColumn === column.column) {
return (
<HeaderColumn
key={i}
handleSort={props.handleSort}
column={column.column}
sort={props.sortOrder}
>
{column.display}
</HeaderColumn>
);
}
return (
<HeaderColumn
key={i}
handleSort={props.handleSort}
column={column.column}
>
{column.display}
</HeaderColumn>
);
})}
</tr>
);
CollectionHeader.propTypes = {
sortColumn: React.PropTypes.string.isRequired,
sortOrder: React.PropTypes.string.isRequired,
handleSort: React.PropTypes.func.isRequired,
};
export default CollectionHeader;
|
src/components/Hello/index.js | lijinfengworm/ant-design-reactjs | import React from 'react';
import './index.less';
/**
* 测试用
*/
class Hello extends React.PureComponent {
render() {
return <div><h1 className="testStyle">Hello, React!</h1></div>;
}
}
export default Hello;
|
app/components/welcome0.js | nyc-bobolinks-2016/TemoApp | import React, { Component } from 'react';
import {
Navigator,
StyleSheet,
Text,
TextInput,
TouchableOpacity,
View
} from 'react-native';
import SendBird from 'sendbird'
import NavMenu from './navMenu';
export default class Signup extends Component {
constructor() {
super();
console.disableYellowBox = true;
global.lastRoute = ""
this.state = {
username: '',
phone: ''
}
}
handleChangeUsername(value) {
this.setState({username: value})
global.currentUser = value
}
handleChangePhone(value) {
this.setState({phone: value})
global.currentPhone = value
}
handleSignup() {
sb = new SendBird({
appId: '6042A607-C497-460C-B8E8-9934DF5D8529'
})
var _self = this
sb.connect(_self.state.phone, function (user, error) {});
sb.updateCurrentUserInfo(this.state.username, '', function(response, error) {
});
fetch('https://temo-api.herokuapp.com/users', {
method: 'post',
headers: { 'Accept': 'application/json','Content-Type': 'application/json'},
body: JSON.stringify({
username: this.state.username,
phone: this.state.phone
})
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.created_at != null) {
console.log(responseJson)
this.props.navigator.push({name: 'conversations'})
} else {
console.log("no invalid phone number")
}
})
}
handleLogin() {
sb = new SendBird({
appId: '6042A607-C497-460C-B8E8-9934DF5D8529'
})
var _self = this
sb.connect(_self.state.phone, function (user, error) {});
sb.updateCurrentUserInfo(this.state.username, '', function(response, error) {
});
fetch('https://temo-api.herokuapp.com/users/login', {
method: 'post',
headers: { 'Accept': 'application/json','Content-Type': 'application/json'},
body: JSON.stringify({
username: this.state.username,
phone: this.state.phone
})
})
.then((response) => response.json())
.then((responseJson) => {
if (responseJson.created_at) {
console.log(responseJson)
this.props.navigator.push({name: 'conversations'})
} else {
console.log("no invalid phone number")
}
})
}
render() {
return (
<View style={styles.container}>
<Text style={styles.header}>
Temo
</Text>
<TextInput
style={styles.textInput}
placeholder={'Username'}
onChangeText={this.handleChangeUsername.bind(this)}
value={this.state.username}
/>
<TextInput
style={styles.textInput}
placeholder={'Password'}
onChangeText={this.handleChangePhone.bind(this)}
value={this.state.phone}
/>
<TouchableOpacity onPress={this.handleLogin.bind(this)}>
<Text style={styles.button}>Login</Text>
</TouchableOpacity>
<TouchableOpacity onPress={this.handleSignup.bind(this)}>
<Text style={styles.button}>Sign up</Text>
</TouchableOpacity>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
backgroundColor: '#e0e0e0',
margin: 10,
},
header: {
fontSize: 100,
color: '#00b0ff',
margin: 60,
fontFamily: 'SnellRoundhand-Bold',
marginBottom: 40,
},
button: {
fontSize: 30,
color: '#00b0ff',
fontWeight: "100",
fontFamily: 'AppleSDGothicNeo-Thin',
margin: 5,
},
textInput: {
padding: 5,
alignItems: 'center',
justifyContent: 'center',
width: 240,
height: 40,
borderWidth: 1,
borderColor: '#757575',
marginLeft: 67,
marginBottom: 3,
borderRadius: 5,
backgroundColor: '#e3f2fd'
}
});
|
examples/Box.js | casesandberg/workbench | import React from 'react'
import _ from 'lodash'
import ReactCSS from 'reactcss'
const build = (element, property, obj, toApply) => {
return toApply ? _.mapValues(obj, (value) => {
return { [element]: { [property]: value } }
}) : {}
}
const justifyContent = {
left: 'flex-start',
center: 'center',
right: 'flex-end',
spread: 'space-between',
}
const alignItems = {
top: 'flex-start',
center: 'center',
bottom: 'flex-end',
}
const flexbox = {
// direction
row: {
// alignment: flexbox
align: 'justifyContent',
verticalAlign: 'alignItems'
},
column: {
align: 'alignItems',
verticalAlign: 'justifyContent'
}
}
export class Box extends React.Component {
classes = () => ({
'default': {
box: {
}
},
'row': {
box: {
display: 'flex',
width: '100%',
height: '100%',
}
},
'column': {
box: {
display: 'flex',
flexDirection: 'column',
width: '100%',
height: '100%',
}
},
// ...build('box', 'justifyContent', _.mapKeys(align, (v, k) => (`align-${ k }`)), this.props.row),
// ...build('box', 'alignItems', _.mapKeys(verticalAlign, (v, k) => (`align-${ k }`)), this.props.column),
// ...build('box', 'alignItems', _.mapKeys(align, (v, k) => (`verticalAlign-${ k }`)), this.props.row),
// ...build('box', 'justifyContent', _.mapKeys(verticalAlign, (v, k) => (`verticalAlign-${ k }`)), this.props.column)
})
render() {
console.log(this.styles().box)
return (
<div style={ this.styles().box }>{ this.props.children }</div>
)
}
}
export default ReactCSS(Box)
|
src/app.js | jeiker26/react | import React from 'react';
import ReactDom from 'react-dom';
import SearchGot from './components/search';
ReactDom.render(<SearchGot />, document.getElementById('app'));
|
app/components/mapMarker/mapMarkerView.js | UsabilitySoft/Proximater | import React, { Component } from 'react';
import { AppRegistry, Text, View, Image, Button } from 'react-native';
import { styles } from './styles';
const images = require('../images');
export class MapMarkerView extends Component {
render() {
return (
<View style={styles.container}>
<Image
source={images.iconMapMarker}
style={styles.icon}/>
</View>
);
}
} |
client/index.js | gigavinyl/pern-starter | 'use-strict';
import { configureStore } from '../shared/redux/store/configureStore';
import { Provider } from 'react-redux';
import postReducer from '../shared/redux/reducers/reducer';
import { render } from 'react-dom';
import React from 'react';
import App from '../shared/container/App';
import PostListView from '../shared/container/PostListView/PostListView';
import PostDetailView from '../shared/container/PostDetailView/PostDetailView';
import { Router, browserHistory } from 'react-router';
import routes from '../shared/routes';
const store = configureStore(window.__INITIAL_STATE__);
const history = browserHistory;
render((
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
)
, document.getElementById('root'));
|
demo/components/navbar/NavBarOptions.js | f0zze/rosemary-ui | import React from 'react';
import {NavItem, NavHrefItem} from '../../../src';
import OptionsTable from '../../helper/OptionsTable';
export default () => {
let commonPropDesc = {
active: {
values: 'boolean',
description: 'Set link to be active'
},
right: {
values: 'boolean',
description: 'Set link to float right'
},
withHoverEffect: {
values: 'boolean',
description: 'on hover will show underline'
}
};
let navItemPropDesc = {
...commonPropDesc,
onClick: {
values: 'function',
description: 'Is called when btn is clicked'
}
};
let navHrefItemPropDesc = {
...commonPropDesc
};
return (
<div>
NavItem:
<OptionsTable component={NavItem} propDescription={navItemPropDesc} />
NavHrefItem:
<OptionsTable component={NavHrefItem} propDescription={navHrefItemPropDesc} />
</div>
);
};
|
lib/components/App.js | sanack/atom-jq | /** @babel */
import React from 'react'
import InputBottomView from './InputBottomView'
import { Provider } from 'react-redux'
export const App = (store) => (
<Provider store={store}>
<InputBottomView />
</Provider>
)
|
definitions/npm/radium_v0.19.x/test_radium-v0.19.x.js | mkscrg/flow-typed | // @flow
import React from 'react';
import Radium from 'radium';
import type { FunctionComponent } from 'radium'
type Props1 = {
a: number,
b: string
};
const C1: FunctionComponent<Props1, void> = (props: Props1) => <div>{props.a} {props.b}</div>
type Props2 = {
a: number,
b: string,
};
class C2 extends React.Component<void, Props2, void> {
render () {
return <div>{this.props.a} {this.props.b}</div>
}
}
Radium(<div/>);
Radium(<Radium.StyleRoot/>);
Radium.keyframes({});
// $ExpectError
Radium.keyframes(); // missing object
Radium.getState({}, 'ref', ':hover');
// $ExpectError
Radium.getState({}, 'ref', ':visible') // invalid property
const RC1 = Radium(C1);
<RC1 a={1} b="s" />;
// $ExpectError
<RC1 />; // missing a, b
// $ExpectError
<RC1 a={1} />; // missing b
// $ExpectError
<RC1 a="s" b="s" />; // wrong a type
const RC2 = Radium(C2);
<RC2 a={1} b="s" />;
// $ExpectError
<RC2 />; // missing a, b
// $ExpectError
<RC2 a={1} />; // missing b
// $ExpectError
<RC2 a="s" b="s" />; // wrong a type
const ConfiguredRadium = Radium({ userAgent: 'foo' })
const CRC1 = ConfiguredRadium(C1);
<CRC1 a={1} b="s" />;
// $ExpectError
<CRC1 />; // missing a, b
// $ExpectError
<CRC1 a={1} />; // missing b
// $ExpectError
<CRC1 a="s" b="s" />; // wrong a type
const CRC2 = ConfiguredRadium(C2);
<CRC2 a={1} b="s" />;
// $ExpectError
<CRC2 />; // missing a, b
// $ExpectError
<CRC2 a={1} />; // missing b
// $ExpectError
<CRC2 a="s" b="s" />; // wrong a type |
src/components/attributes/scatter-plot/local-attributes/GridLines.js | eveafeline/D3-ID3-Naomi | import React, { Component } from 'react';
class GridLines extends Component {
constructor(props) {
super(props)
this.state = {
checkbox: false
}
this.handleCheckbox = this.handleCheckbox.bind(this);
this.onSubmit = this.onSubmit.bind(this);
}
onSubmit(event) {
event.preventDefault();
}
handleCheckbox(event) {
this.setState({
checkbox: !this.state.checkbox
});
}
render() {
let gridLineDisplay = <div className="attr-display"></div>
const width = <div className="input-container">
<label>
width
<input type="number" className="form-control"></input>
</label>
</div>
const color = <div className="input-container">
<label>
color
<input type="text" className="form-control"></input>
</label>
</div>
if (this.state.checkbox) {
gridLineDisplay = <div className="attr-display">
<h6 className="panel-subheaders">X-GridLines</h6>
<div className="input-group">
{width}
{color}
</div>
<h6 className="panel-subheaders">Y-Gridlines</h6>
<div className="input-group">
{width}
{color}
</div>
</div>
}
return(
<div className="attr-container">
{/* <header className="toolbar toolbar-header attr-header">
<div className="checkbox">
<form onSubmit={this.onSubmit}>
<label>
<input type="checkbox" onChange={this.handleCheckbox} checked={this.state.checkbox}/>
Grid Lines
</label>
</form>
</div>
</header> */}
<div onClick={this.handleCheckbox} checked={this.state.checkbox}>
<h5 className="panel-headers">Grid Lines</h5>
</div>
{gridLineDisplay}
</div>
);
}
}
export default GridLines;
|
modules/dreamview/frontend/src/components/PNCMonitor/ControlMonitor.js | jinghaomiao/apollo | import React from 'react';
import { inject, observer } from 'mobx-react';
import SETTING from 'store/config/ControlGraph.yml';
import ScatterGraph, { generateScatterGraph } from 'components/PNCMonitor/ScatterGraph';
@inject('store') @observer
export default class ControlMonitor extends React.Component {
render() {
const { lastUpdatedTime, data } = this.props.store.controlData;
if (!lastUpdatedTime) {
return null;
}
return (
<div>
{generateScatterGraph(SETTING.trajectoryGraph, data.trajectoryGraph, {
pose: data.pose,
})}
{generateScatterGraph(SETTING.speedGraph, data.speedGraph)}
{generateScatterGraph(SETTING.accelerationGraph, data.accelerationGraph)}
{generateScatterGraph(SETTING.curvatureGraph, data.curvatureGraph)}
{generateScatterGraph(SETTING.stationErrorGraph, data.stationErrorGraph)}
{generateScatterGraph(SETTING.lateralErrorGraph, data.lateralErrorGraph)}
{generateScatterGraph(SETTING.headingErrorGraph, data.headingErrorGraph)}
</div>
);
}
}
|
src/js/container/ScrollSpy.js | tpucci/jobads-webapp | import React from 'react';
let latestKnownScrollY;
let raf;
let ticking;
let waiting;
let endScrollHandle;
export default class ScrollSpy extends React.Component {
constructor(props) {
super(props);
this.state = {
top: 0,
inertia: 0,
isAtTop: true
};
}
componentDidMount() {
raf = window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
latestKnownScrollY = window.scrollY;
ticking = false;
window.addEventListener('scroll', this._handleScroll, false);
}
componentWillUnmount() {
window.removeEventListener('scroll', this._handleScroll);
}
_handleScroll = () => {
latestKnownScrollY = window.scrollY;
this._requestTick();
}
_requestTick = () => {
if(!ticking) {
raf(this._requestCalculate);
}
ticking = true;
}
_requestCalculate = () => {
if (waiting) {
return;
}
waiting = true;
// clear previous scheduled endScrollHandle
clearTimeout(endScrollHandle);
this._calculate();
setTimeout( () => {
waiting = false;
}, 200);
// schedule an extra execution of scroll() after 400ms
// in case the scrolling stops in next 200ms
endScrollHandle = setTimeout( () => {
this._calculate();
}, 400);
}
_calculate = () => {
ticking = false;
let top = latestKnownScrollY;
let isAtTop = (top == 0);
let inertia = this.state.top - top;
this.setState({
top,
inertia,
isAtTop
});
}
render () {
const childrenWithProps = React.Children.map(this.props.children,
(child) => React.cloneElement(child, {
top: this.state.top,
isAtTop: this.state.isAtTop,
inertia: this.state.inertia,
})
);
return (
<div>
{childrenWithProps}
</div>
);
}
} |
sub-packs/themes/zealder-default-theme/src/components/Html.js | Zealder/zealder-cms | // @flow
// this is the most generic content component that only export content as html
import React from 'react';
export default class Html extends React.Component {
componentDidMount() {
if ($(".as-html form").length) {
// since there is form on page, add recaptcha
grecaptcha.ready(function() {
grecaptcha.execute(reCAPTCHAkey, {action: 'html_form'}).then((token) => {
var input = $("<input>").attr("type", "hidden").attr("name", "recaptcha").val(token);
$('.as-html form').append($(input));
});
});
}
}
render() {
// default value when content hasn't been added
let content = {__html: "This content is not available"};
const {html} = this.props.content.scContent;
if (html) {
content = {__html: html}
}
return (
<div dangerouslySetInnerHTML={content} className="as-html" />
);
}
}
|
src/components/Contact/Contact.js | notaurologist/jasonlemoine.com | import React from 'react';
import styles from './contact.css';
const Contact = () => (
<main className={ styles.contact }>
<form action="https://formspree.io/[email protected]" method="POST">
<input type="hidden" name="_next" value="http://www.jasonlemoine.com/contact/thanks" />
<input type="text" name="_gotcha" style={ {display:'none'} } />
<input type="text" role="textbox" aria-label="name" name="name" placeholder="Name" tabIndex="1" required />
<input type="email" role="textbox" aria-label="_replyto" name="_replyto" placeholder="Email" tabIndex="2" required />
<textarea aria-label="message" role="textbox" aria-multiline="true" name="message" placeholder="Message" tabIndex="3" required></textarea>
<button tabIndex="4">Send</button>
</form>
</main>
);
export default Contact;
|
src/containers/community/InvitationList.js | Hylozoic/hylo-redux | import React from 'react'
import { humanDate } from '../../util/text'
import A from '../../components/A'
import Avatar from '../../components/Avatar'
import {
fetchInvitations, sendCommunityInvitation, notify,
resendAllCommunityInvitations
} from '../../actions'
import { FETCH_INVITATIONS } from '../../actions/constants'
import cx from 'classnames'
import { get, uniqBy } from 'lodash/fp'
import { connect } from 'react-redux'
const InvitationList = connect((state, { id }) => ({
invitationEditor: get('invitationEditor', state),
invitations: state.invitations[id],
total: state.totalInvitations[id],
pending: state.pending[FETCH_INVITATIONS]
}))(props => {
const { invitations, pending, total, dispatch, id, invitationEditor } = props
const offset = get('length', invitations) || 0
const loadMore = () =>
!pending && offset < total && dispatch(fetchInvitations(id, offset))
const countText = offset < total
? `showing ${invitations.length} of ${total} invitations, ${invitations.filter(i => i.user).length} used`
: `${total} invitations sent, ${invitations.filter(i => i.user).length} used`
const { subject, message, moderator } = invitationEditor
const resendAll = () =>
dispatch(resendAllCommunityInvitations(id, {subject, message}))
.then(({ error }) => {
if (error) {
dispatch(notify('There was a problem sending these invitations; please try again later.', {type: 'error'}))
} else {
dispatch(notify('Your invitations have been queued and will be sent shortly.'))
}
})
const sendInvitation = email =>
dispatch(sendCommunityInvitation(id, {subject, message, emails: [email], moderator}))
.then(({ error }) => {
if (error) {
dispatch(notify('There was a problem sending this invitation; please try again later.', {type: 'error'}))
} else {
dispatch(notify(`Invitation sent to ${email}.`))
}
})
return <div className='invitations'>
<div className='invitations-header'>
<label>Pending Invitations</label>
<p className='count'>{countText}</p>
<p className='summary'>These are people you have already sent invitations to.</p>
<a className='resend-all' onClick={resendAll}>Resend All</a>
</div>
<div className='person-table'>
<table>
<thead>
<tr>
<th>Recipient</th>
<th>Used by</th>
<th>Time sent</th>
<th></th>
</tr>
</thead>
<tbody>
{uniqBy('email', (invitations || [])).map((invitation, index) => {
let person = invitation.user
return <tr key={invitation.id} className={cx({even: index % 2 === 0})}>
<td>{invitation.email}</td>
{person
? <td className='person'>
<Avatar person={person} />
<A to={`/u/${person.id}`}>{person.name}</A>
</td>
: <td className='unused'>unused</td>}
<td>{humanDate(invitation.created_at)}</td>
{person
? <td />
: <td><a className='table-button' onClick={() => sendInvitation(invitation.email)}>
Resend
</a></td>
}
</tr>
})}
{offset < total && <tr><td /><td /><td />
<td>
<button onClick={loadMore}>Load More</button>
</td>
</tr>}
</tbody>
</table>
</div>
</div>
})
export default InvitationList
|
test/fixtures/webpack-message-formatting/src/AppAliasUnknownExport.js | timlogemann/create-react-app | import React, { Component } from 'react';
import { bar as bar2 } from './AppUnknownExport';
class App extends Component {
componentDidMount() {
bar2();
}
render() {
return <div />;
}
}
export default App;
|
app/javascript/mastodon/features/ui/components/columns_area.js | WitchesTown/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import { Link } from 'react-router-dom';
import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import DrawerLoading from './drawer_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, FavouritedStatuses, ListTimeline } from '../../ui/util/async-components';
import detectPassiveEvents from 'detect-passive-events';
import { scrollRight } from '../../../scroll';
const componentMap = {
'COMPOSE': Compose,
'HOME': HomeTimeline,
'NOTIFICATIONS': Notifications,
'PUBLIC': PublicTimeline,
'COMMUNITY': CommunityTimeline,
'HASHTAG': HashtagTimeline,
'FAVOURITES': FavouritedStatuses,
'LIST': ListTimeline,
};
const shouldHideFAB = path => path.match(/^\/statuses\//);
@component => injectIntl(component, { withRef: true })
export default class ColumnsArea extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
columns: ImmutablePropTypes.list.isRequired,
isModalOpen: PropTypes.bool.isRequired,
singleColumn: PropTypes.bool,
children: PropTypes.node,
};
state = {
shouldAnimate: false,
}
componentWillReceiveProps() {
this.setState({ shouldAnimate: false });
}
componentDidMount() {
if (!this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl');
this.setState({ shouldAnimate: true });
}
componentWillUpdate(nextProps) {
if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
componentDidUpdate(prevProps) {
if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, detectPassiveEvents.hasSupport ? { passive: true } : false);
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
}
componentWillUnmount () {
if (!this.props.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
handleChildrenContentChange() {
if (!this.props.singleColumn) {
const modifier = this.isRtlLayout ? -1 : 1;
this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier);
}
}
handleSwipe = (index) => {
this.pendingIndex = index;
const nextLinkTranslationId = links[index].props['data-preview-title-id'];
const currentLinkSelector = '.tabs-bar__link.active';
const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;
// HACK: Remove the active class from the current link and set it to the next one
// React-router does this for us, but too late, feeling laggy.
document.querySelector(currentLinkSelector).classList.remove('active');
document.querySelector(nextLinkSelector).classList.add('active');
}
handleAnimationEnd = () => {
if (typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = (node) => {
this.node = node;
}
renderView = (link, index) => {
const columnIndex = getIndex(this.context.router.history.location.pathname);
const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
const icon = link.props['data-preview-icon'];
const view = (index === columnIndex) ?
React.cloneElement(this.props.children) :
<ColumnLoading title={title} icon={icon} />;
return (
<div className='columns-area' key={index}>
{view}
</div>
);
}
renderLoading = columnId => () => {
return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { columns, children, singleColumn, isModalOpen } = this.props;
const { shouldAnimate } = this.state;
const columnIndex = getIndex(this.context.router.history.location.pathname);
this.pendingIndex = null;
if (singleColumn) {
const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/statuses/new' className='floating-action-button'><i className='fa fa-pencil' /></Link>;
return columnIndex !== -1 ? [
<ReactSwipeableViews key='content' index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
{links.map(this.renderView)}
</ReactSwipeableViews>,
floatingActionButton,
] : [
<div className='columns-area'>{children}</div>,
floatingActionButton,
];
}
return (
<div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}>
{columns.map(column => {
const params = column.get('params', null) === null ? null : column.get('params').toJS();
return (
<BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}>
{SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn />}
</BundleContainer>
);
})}
{React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}
</div>
);
}
}
|
modules/IndexLink.js | upraised/react-router | import React from 'react'
import Link from './Link'
const IndexLink = React.createClass({
render() {
return <Link {...this.props} onlyActiveOnIndex={true} />
}
})
export default IndexLink
|
src/js/components/icons/base/Power.js | odedre/grommet-final | /**
* @description Power SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M16,4 C19.3637732,5.43018182 22,8.98935065 22,13 C22,18.6008831 17.5273457,23 12,23 C6.47265429,23 2,18.6008831 2,13 C2,8.98935065 4.63622679,5.43018182 8,4 M12,1 L12,11"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-power`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'power');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M16,4 C19.3637732,5.43018182 22,8.98935065 22,13 C22,18.6008831 17.5273457,23 12,23 C6.47265429,23 2,18.6008831 2,13 C2,8.98935065 4.63622679,5.43018182 8,4 M12,1 L12,11"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Power';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/Transition.js | cesarandreu/react-overlays | import React from 'react';
import transitionInfo from 'dom-helpers/transition/properties';
import addEventListener from 'dom-helpers/events/on';
import classnames from 'classnames';
let transitionEndEvent = transitionInfo.end;
export const UNMOUNTED = 0;
export const EXITED = 1;
export const ENTERING = 2;
export const ENTERED = 3;
export const EXITING = 4;
/**
* The Transition component lets you define and run css transitions with a simple declarative api.
* It works similar to React's own [CSSTransitionGroup](http://facebook.github.io/react/docs/animation.html#high-level-api-reactcsstransitiongroup)
* but is specifically optimized for transitioning a single child "in" or "out".
*
* You don't even need to use class based css transitions if you don't want to (but it is easiest).
* The extensive set of lifecyle callbacks means you have control over
* the transitioning now at each step of the way.
*/
class Transition extends React.Component {
constructor(props, context) {
super(props, context);
let initialStatus;
if (props.in) {
// Start enter transition in componentDidMount.
initialStatus = props.transitionAppear ? EXITED : ENTERED;
} else {
initialStatus = props.unmountOnExit ? UNMOUNTED : EXITED;
}
this.state = {status: initialStatus};
this.nextCallback = null;
}
componentDidMount() {
if (this.props.transitionAppear && this.props.in) {
this.performEnter(this.props);
}
}
componentWillReceiveProps(nextProps) {
const status = this.state.status;
if (nextProps.in) {
if (status === EXITING) {
this.performEnter(nextProps);
} else if (this.props.unmountOnExit) {
if (status === UNMOUNTED) {
// Start enter transition in componentDidUpdate.
this.setState({status: EXITED});
}
} else if (status === EXITED) {
this.performEnter(nextProps);
}
// Otherwise we're already entering or entered.
} else {
if (status === ENTERING || status === ENTERED) {
this.performExit(nextProps);
}
// Otherwise we're already exited or exiting.
}
}
componentDidUpdate() {
if (this.props.unmountOnExit && this.state.status === EXITED) {
// EXITED is always a transitional state to either ENTERING or UNMOUNTED
// when using unmountOnExit.
if (this.props.in) {
this.performEnter(this.props);
} else {
this.setState({status: UNMOUNTED});
}
}
}
componentWillUnmount() {
this.cancelNextCallback();
}
performEnter(props) {
this.cancelNextCallback();
const node = React.findDOMNode(this);
// Not this.props, because we might be about to receive new props.
props.onEnter(node);
this.safeSetState({status: ENTERING}, () => {
this.props.onEntering(node);
this.onTransitionEnd(node, () => {
this.safeSetState({status: ENTERED}, () => {
this.props.onEntered(node);
});
});
});
}
performExit(props) {
this.cancelNextCallback();
const node = React.findDOMNode(this);
// Not this.props, because we might be about to receive new props.
props.onExit(node);
this.safeSetState({status: EXITING}, () => {
this.props.onExiting(node);
this.onTransitionEnd(node, () => {
this.safeSetState({status: EXITED}, () => {
this.props.onExited(node);
});
});
});
}
cancelNextCallback() {
if (this.nextCallback !== null) {
this.nextCallback.cancel();
this.nextCallback = null;
}
}
safeSetState(nextState, callback) {
// This shouldn't be necessary, but there are weird race conditions with
// setState callbacks and unmounting in testing, so always make sure that
// we can cancel any pending setState callbacks after we unmount.
this.setState(nextState, this.setNextCallback(callback));
}
setNextCallback(callback) {
let active = true;
this.nextCallback = (event) => {
if (active) {
active = false;
this.nextCallback = null;
callback(event);
}
};
this.nextCallback.cancel = () => {
active = false;
};
return this.nextCallback;
}
onTransitionEnd(node, handler) {
this.setNextCallback(handler);
if (node) {
addEventListener(node, transitionEndEvent, this.nextCallback);
setTimeout(this.nextCallback, this.props.timeout);
} else {
setTimeout(this.nextCallback, 0);
}
}
render() {
const status = this.state.status;
if (status === UNMOUNTED) {
return null;
}
const {children, className, ...childProps} = this.props;
Object.keys(Transition.propTypes).forEach(key => delete childProps[key]);
let transitionClassName;
if (status === EXITED) {
transitionClassName = this.props.exitedClassName;
} else if (status === ENTERING) {
transitionClassName = this.props.enteringClassName;
} else if (status === ENTERED) {
transitionClassName = this.props.enteredClassName;
} else if (status === EXITING) {
transitionClassName = this.props.exitingClassName;
}
const child = React.Children.only(children);
return React.cloneElement(
child,
{
...childProps,
className: classnames(
child.props.className,
className,
transitionClassName
)
}
);
}
}
Transition.propTypes = {
/**
* Show the component; triggers the enter or exit animation
*/
in: React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is not shown
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the enter animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* A Timeout for the animation, in milliseconds, to ensure that a node doesn't
* transition indefinately if the browser transitionEnd events are
* canceled or interrupted.
*
* By default this is set to a high number (5 seconds) as a failsafe. You should consider
* setting this to the duration of your animation (or a bit above it).
*/
timeout: React.PropTypes.number,
/**
* CSS class or classes applied when the component is exited
*/
exitedClassName: React.PropTypes.string,
/**
* CSS class or classes applied while the component is exiting
*/
exitingClassName: React.PropTypes.string,
/**
* CSS class or classes applied when the component is entered
*/
enteredClassName: React.PropTypes.string,
/**
* CSS class or classes applied while the component is entering
*/
enteringClassName: React.PropTypes.string,
/**
* Callback fired before the "entering" classes are applied
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the "entering" classes are applied
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the "enter" classes are applied
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the "exiting" classes are applied
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the "exiting" classes are applied
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the "exited" classes are applied
*/
onExited: React.PropTypes.func
};
// Name the function so it is clearer in the documentation
function noop() {}
Transition.displayName = 'Transition';
Transition.defaultProps = {
in: false,
unmountOnExit: false,
transitionAppear: false,
timeout: 5000,
onEnter: noop,
onEntering: noop,
onEntered: noop,
onExit: noop,
onExiting: noop,
onExited: noop
};
export default Transition;
|
src/svg-icons/hardware/laptop-windows.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareLaptopWindows = (props) => (
<SvgIcon {...props}>
<path d="M20 18v-1c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2v1H0v2h24v-2h-4zM4 5h16v10H4V5z"/>
</SvgIcon>
);
HardwareLaptopWindows = pure(HardwareLaptopWindows);
HardwareLaptopWindows.displayName = 'HardwareLaptopWindows';
export default HardwareLaptopWindows;
|
actor-apps/app-web/src/app/components/sidebar/ContactsSectionItem.react.js | voidException/actor-platform | import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
import DialogActionCreators from 'actions/DialogActionCreators';
import AvatarItem from 'components/common/AvatarItem.react';
const {addons: { PureRenderMixin }} = addons;
@ReactMixin.decorate(PureRenderMixin)
class ContactsSectionItem extends React.Component {
static propTypes = {
contact: React.PropTypes.object
};
constructor(props) {
super(props);
}
openNewPrivateCoversation = () => {
DialogActionCreators.selectDialogPeerUser(this.props.contact.uid);
}
render() {
const contact = this.props.contact;
return (
<li className="sidebar__list__item row" onClick={this.openNewPrivateCoversation}>
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
</li>
);
}
}
export default ContactsSectionItem;
|
src/cms/preview-templates/page-preview.js | wall3/wall3.github.io | // @flow strict
import React from 'react';
import type { Entry, WidgetFor } from '../../types';
type Props = {
entry: Entry,
widgetFor: WidgetFor
};
const PagePreview = ({ entry, widgetFor }: Props) => {
const body = widgetFor('body');
const title = entry.getIn(['data', 'title']);
return (
<div className="page">
<h1 className="page__title">{title}</h1>
<div className="page__body">{ body }</div>
</div>
);
};
export default PagePreview;
|
core/src/plugins/gui.ajax/res/js/ui/Workspaces/search/components/FileSizePanel.js | huzergackl/pydio-core | /*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
import React from 'react';
const {PydioContextConsumer} = require('pydio').requireLib('boot')
import {TextField} from 'material-ui';
class SearchFileSizePanel extends React.Component {
constructor(props) {
super(props)
this.state = {
from:false,
to: null
}
}
onChange() {
this.setState({
from: this.refs.from.getValue() || 0,
to: this.refs.to.getValue() || 1099511627776
})
}
componentWillUpdate(nextProps, nextState) {
if (nextState === this.state) return
const {from, to} = nextState
this.props.onChange({
ajxp_bytesize: (from && to) ? '['+from+' TO '+to+']' : null
})
}
render() {
const {inputStyle, getMessage, ...props} = this.props
return (
<div>
<TextField
ref="from"
style={inputStyle}
hintText={getMessage(504)}
floatingLabelFixed={true}
floatingLabelText={getMessage(613)}
onChange={this.onChange.bind(this)}
/>
<TextField
ref="to"
style={inputStyle}
hintText={getMessage(504)}
floatingLabelFixed={true}
floatingLabelText={getMessage(614)}
onChange={this.onChange.bind(this)}
/>
</div>
);
}
}
SearchFileSizePanel = PydioContextConsumer(SearchFileSizePanel)
export default SearchFileSizePanel |
cm19/ReactJS/your-first-react-app-exercises-master/exercise-11/complete/App.js | Brandon-J-Campbell/codemash | import React, { Component } from 'react';
import Exercise from './Exercise';
import styles from './App.css';
import classNames from 'classnames';
class App extends Component {
render() {
return (
<div className={styles.app}>
<header className={styles.appHeader}>
<h1 className={styles.appTitle}>Exercise 11</h1>
<h2 className={classNames(styles.subTitle, styles.emphasize)}>CSS Modules</h2>
</header>
<div className={styles.exercise}>
<Exercise />
</div>
</div>
);
}
}
export default App; |
examples/react-native/index.ios.js | natew/rxdb | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import {
AppRegistry,
} from 'react-native';
import React, { Component } from 'react';
import App from './src'
AppRegistry.registerComponent('reactNative', () => App);
|
app/components/ProgressBar.js | AngelGallegosE/Osiris | import React from 'react';
class ProgressBar extends React.Component {
render() {
return (
<div id="MainProgressBarContainer">
<progress id="progressBar" value={this.props.value} max="100" className={this.props.value===0?'hidden':''}></progress>
</div>
);
}
}
ProgressBar.propTypes = {
value: React.PropTypes.number
};
export default ProgressBar; |
src/server.js | brecht/react-redux-universal-hot-example | import Express from 'express';
import React from 'react';
import Location from 'react-router/lib/Location';
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 api from './api/api';
import ApiClient from './ApiClient';
import universalRouter from './universalRouter';
import Html from './Html';
import PrettyError from 'pretty-error';
const pretty = new PrettyError();
const app = new Express();
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
let webpackStats;
if (!__DEVELOPMENT__) {
webpackStats = require('../webpack-stats.json');
}
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
webpackStats = require('../webpack-stats.json');
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
delete require.cache[require.resolve('../webpack-stats.json')];
}
const client = new ApiClient(req);
const store = createStore(client);
const location = new Location(req.path, req.query);
if (__DISABLE_SSR__) {
res.send('<!doctype html>\n' +
React.renderToString(<Html webpackStats={webpackStats} component={<div/>} store={store}/>));
} else {
universalRouter(location, undefined, store)
.then(({component, transition, isRedirect}) => {
if (isRedirect) {
res.redirect(transition.redirectInfo.pathname);
return;
}
res.send('<!doctype html>\n' +
React.renderToString(<Html webpackStats={webpackStats} component={component} store={store}/>));
})
.catch((error) => {
console.error('ROUTER ERROR:', pretty.render(error));
res.status(500).send({error: error.stack});
});
}
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) {
console.error(err);
} else {
api().then(() => {
console.info('==> ✅ Server is listening');
console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort);
console.info('----------\n==> 💻 Open http://localhost:%s in a browser to view the app.', config.port);
});
}
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
test/integration/image-component/default/pages/style-inheritance.js | azukaru/next.js | import React from 'react'
import Image from 'next/image'
import style from '../style.module.css'
const Page = () => {
return (
<div id="main-container" className={style.mainContainer}>
<h1>Image Style Inheritance</h1>
<Image
id="img-fixed"
layout="fixed"
src="/test.jpg"
width="400"
height="400"
/>
<Image
id="img-intrinsic"
layout="intrinsic"
src="/test.jpg"
width="400"
height="400"
/>
<div style={{ position: 'relative', width: '200px', height: '200px' }}>
<Image id="img-fill" layout="fill" src="/test.jpg" objectFit="cover" />
</div>
<Image
id="img-responsive"
layout="responsive"
src="/test.jpg"
width="400"
height="400"
/>
<footer>Footer</footer>
</div>
)
}
export default Page
|
frontend/src/components/dir-view-mode/dir-column-view.js | miurahr/seahub | import React from 'react';
import PropTypes from 'prop-types';
import DirColumnNav from './dir-column-nav';
import DirColumnFile from './dir-column-file';
import DirListView from './dir-list-view';
const propTypes = {
path: PropTypes.string.isRequired,
repoID: PropTypes.string.isRequired,
// repoinfo
currentRepoInfo: PropTypes.object.isRequired,
repoPermission: PropTypes.bool.isRequired,
enableDirPrivateShare: PropTypes.bool.isRequired,
userPerm: PropTypes.string,
isGroupOwnedRepo: PropTypes.bool.isRequired,
// tree
isTreeDataLoading: PropTypes.bool.isRequired,
treeData: PropTypes.object.isRequired,
currentNode: PropTypes.object,
onNodeClick: PropTypes.func.isRequired,
onNodeCollapse: PropTypes.func.isRequired,
onNodeExpanded: PropTypes.func.isRequired,
onRenameNode: PropTypes.func.isRequired,
onDeleteNode: PropTypes.func.isRequired,
onAddFileNode: PropTypes.func.isRequired,
onAddFolderNode: PropTypes.func.isRequired,
// file
isViewFile: PropTypes.bool.isRequired,
isFileLoading: PropTypes.bool.isRequired,
isFileLoadedErr: PropTypes.bool.isRequired,
hash: PropTypes.string,
isDraft: PropTypes.bool.isRequired,
hasDraft: PropTypes.bool.isRequired,
goDraftPage: PropTypes.func.isRequired,
filePermission: PropTypes.string,
content: PropTypes.string,
lastModified: PropTypes.string,
latestContributor: PropTypes.string,
onLinkClick: PropTypes.func.isRequired,
// repo content
isRepoInfoBarShow: PropTypes.bool.isRequired,
draftCounts: PropTypes.number.isRequired,
usedRepoTags: PropTypes.array.isRequired,
readmeMarkdown: PropTypes.object,
updateUsedRepoTags: PropTypes.func.isRequired,
// list
isDirentListLoading: PropTypes.bool.isRequired,
direntList: PropTypes.array.isRequired,
sortBy: PropTypes.string.isRequired,
sortOrder: PropTypes.string.isRequired,
sortItems: PropTypes.func.isRequired,
onAddFolder: PropTypes.func.isRequired,
onAddFile: PropTypes.func.isRequired,
updateDirent: PropTypes.func.isRequired,
onItemClick: PropTypes.func.isRequired,
onItemSelected: PropTypes.func.isRequired,
onItemDelete: PropTypes.func.isRequired,
onItemRename: PropTypes.func.isRequired,
onItemMove: PropTypes.func.isRequired,
onItemCopy: PropTypes.func.isRequired,
onDirentClick: PropTypes.func.isRequired,
isAllItemSelected: PropTypes.bool.isRequired,
onAllItemSelected: PropTypes.func.isRequired,
selectedDirentList: PropTypes.array.isRequired,
onItemsMove: PropTypes.func.isRequired,
onItemsCopy: PropTypes.func.isRequired,
onItemsDelete: PropTypes.func.isRequired,
onFileTagChanged: PropTypes.func,
showDirentDetail: PropTypes.func.isRequired,
};
class DirColumnView extends React.Component {
constructor(props) {
super(props);
this.state = {
inResizing: false,
navRate: 0.25,
};
this.containerWidth = null;
}
onResizeMouseUp = () => {
if (this.state.inResizing) {
this.setState({
inResizing: false
});
}
this.setCookie('navRate', this.state.navRate);
}
onResizeMouseDown = () => {
this.containerWidth = this.refs.viewModeContainer.clientWidth;
this.setState({
inResizing: true
});
};
onResizeMouseMove = (e) => {
let sizeNavWidth = this.containerWidth / 0.78 * 0.22 + 3;
let rate = (e.nativeEvent.clientX - sizeNavWidth) / this.containerWidth;
if (rate < 0.1) {
this.setState({
inResizing: false,
navRate: 0.12,
});
}
else if (rate > 0.4) {
this.setState({
inResizing: false,
navRate: 0.38,
});
}
else {
this.setState({
navRate: rate
});
}
};
setCookie = (name, value) => {
let cookie = name + '=' + value + ';';
document.cookie = cookie;
}
getCookie = (cookiename) => {
let name = cookiename + '=';
let cookie = document.cookie.split(';');
for (let i = 0, len = cookie.length; i < len; i++) {
let c = cookie[i].trim();
if (c.indexOf(name) == 0) {
return c.substring(name.length, c.length) * 1;
}
}
return '';
}
componentWillMount() {
let rate = this.getCookie('navRate');
if (rate) {
this.setState({
navRate: rate,
});
}
}
render() {
const onResizeMove = this.state.inResizing ? this.onResizeMouseMove : null;
const select = this.state.inResizing ? 'none' : '';
const mainFlex = '1 0 ' + (1 - this.state.navRate - 0.05) * 100 + '%';
return (
<div className="dir-colunm-view" onMouseMove={onResizeMove} onMouseUp={this.onResizeMouseUp} ref="viewModeContainer">
<DirColumnNav
currentPath={this.props.path}
repoPermission={this.props.repoPermission}
isTreeDataLoading={this.props.isTreeDataLoading}
treeData={this.props.treeData}
currentNode={this.props.currentNode}
onNodeClick={this.props.onNodeClick}
onNodeCollapse={this.props.onNodeCollapse}
onNodeExpanded={this.props.onNodeExpanded}
onAddFolderNode={this.props.onAddFolderNode}
onAddFileNode={this.props.onAddFileNode}
onRenameNode={this.props.onRenameNode}
onDeleteNode={this.props.onDeleteNode}
repoID={this.props.repoID}
navRate={this.state.navRate}
inResizing={this.state.inResizing}
currentRepoInfo={this.props.currentRepoInfo}
onItemMove={this.props.onItemMove}
onItemCopy={this.props.onItemCopy}
selectedDirentList={this.props.selectedDirentList}
onItemsMove={this.props.onItemsMove}
/>
<div className="dir-content-resize" onMouseDown={this.onResizeMouseDown}></div>
<div className="dir-content-main" style={{userSelect: select, flex: mainFlex}}>
{this.props.isViewFile ? (
<DirColumnFile
path={this.props.path}
repoID={this.props.repoID}
hash={this.props.hash}
isDraft={this.props.isDraft}
hasDraft={this.props.hasDraft}
goDraftPage={this.props.goDraftPage}
isFileLoading={this.props.isFileLoading}
isFileLoadedErr={this.props.isFileLoadedErr}
filePermission={this.props.filePermission}
content={this.props.content}
lastModified={this.props.lastModified}
latestContributor={this.props.latestContributor}
onLinkClick={this.props.onLinkClick}
/>
) : (
<DirListView
path={this.props.path}
repoID={this.props.repoID}
currentRepoInfo={this.props.currentRepoInfo}
isGroupOwnedRepo={this.props.isGroupOwnedRepo}
userPerm={this.props.userPerm}
enableDirPrivateShare={this.props.enableDirPrivateShare}
isRepoInfoBarShow={this.props.isRepoInfoBarShow}
usedRepoTags={this.props.usedRepoTags}
readmeMarkdown={this.props.readmeMarkdown}
draftCounts={this.props.draftCounts}
updateUsedRepoTags={this.props.updateUsedRepoTags}
isDirentListLoading={this.props.isDirentListLoading}
direntList={this.props.direntList}
sortBy={this.props.sortBy}
sortOrder={this.props.sortOrder}
sortItems={this.props.sortItems}
onAddFolder={this.props.onAddFolder}
onAddFile={this.props.onAddFile}
onItemClick={this.props.onItemClick}
onItemSelected={this.props.onItemSelected}
onItemDelete={this.props.onItemDelete}
onItemRename={this.props.onItemRename}
onItemMove={this.props.onItemMove}
onItemCopy={this.props.onItemCopy}
onDirentClick={this.props.onDirentClick}
updateDirent={this.props.updateDirent}
isAllItemSelected={this.props.isAllItemSelected}
onAllItemSelected={this.props.onAllItemSelected}
selectedDirentList={this.props.selectedDirentList}
onItemsMove={this.props.onItemsMove}
onItemsCopy={this.props.onItemsCopy}
onItemsDelete={this.props.onItemsDelete}
onFileTagChanged={this.props.onFileTagChanged}
showDirentDetail={this.props.showDirentDetail}
/>
)}
</div>
</div>
);
}
}
DirColumnView.propTypes = propTypes;
export default DirColumnView;
|
app/javascript/mastodon/features/account_timeline/index.js | sylph-sin-tyaku/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { fetchAccount } from '../../actions/accounts';
import { expandAccountFeaturedTimeline, expandAccountTimeline } from '../../actions/timelines';
import StatusList from '../../components/status_list';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import HeaderContainer from './containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import { List as ImmutableList } from 'immutable';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import { fetchAccountIdentityProofs } from '../../actions/identity_proofs';
import MissingIndicator from 'mastodon/components/missing_indicator';
const emptyList = ImmutableList();
const mapStateToProps = (state, { params: { accountId }, withReplies = false }) => {
const path = withReplies ? `${accountId}:with_replies` : accountId;
return {
isAccount: !!state.getIn(['accounts', accountId]),
statusIds: state.getIn(['timelines', `account:${path}`, 'items'], emptyList),
featuredStatusIds: withReplies ? ImmutableList() : state.getIn(['timelines', `account:${accountId}:pinned`, 'items'], emptyList),
isLoading: state.getIn(['timelines', `account:${path}`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${path}`, 'hasMore']),
blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false),
};
};
export default @connect(mapStateToProps)
class AccountTimeline extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
statusIds: ImmutablePropTypes.list,
featuredStatusIds: ImmutablePropTypes.list,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
withReplies: PropTypes.bool,
blockedBy: PropTypes.bool,
isAccount: PropTypes.bool,
multiColumn: PropTypes.bool,
};
componentWillMount () {
const { params: { accountId }, withReplies } = this.props;
this.props.dispatch(fetchAccount(accountId));
this.props.dispatch(fetchAccountIdentityProofs(accountId));
if (!withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(accountId));
}
this.props.dispatch(expandAccountTimeline(accountId, { withReplies }));
}
componentWillReceiveProps (nextProps) {
if ((nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) || nextProps.withReplies !== this.props.withReplies) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(fetchAccountIdentityProofs(nextProps.params.accountId));
if (!nextProps.withReplies) {
this.props.dispatch(expandAccountFeaturedTimeline(nextProps.params.accountId));
}
this.props.dispatch(expandAccountTimeline(nextProps.params.accountId, { withReplies: nextProps.params.withReplies }));
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountTimeline(this.props.params.accountId, { maxId, withReplies: this.props.withReplies }));
}
render () {
const { shouldUpdateScroll, statusIds, featuredStatusIds, isLoading, hasMore, blockedBy, isAccount, multiColumn } = this.props;
if (!isAccount) {
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<MissingIndicator />
</Column>
);
}
if (!statusIds && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = blockedBy ? <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' /> : <FormattedMessage id='empty_column.account_timeline' defaultMessage='No toots here!' />;
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<StatusList
prepend={<HeaderContainer accountId={this.props.params.accountId} />}
alwaysPrepend
scrollKey='account_timeline'
statusIds={blockedBy ? emptyList : statusIds}
featuredStatusIds={featuredStatusIds}
isLoading={isLoading}
hasMore={hasMore}
onLoadMore={this.handleLoadMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
src/web/solutions/SolveError/SolutionForm.js | whybug/whybug-server | import React from 'react';
export var SolutionForm = React.createClass({
propTypes: {
solution: React.PropTypes.object,
onChange: React.PropTypes.func,
onSave: React.PropTypes.func
},
render() {
var solution = this.props.solution || {};
return form({},
div({className: 'w-row'},
div({className: 'w-col w-col-9'},
MarkdownTextarea({
id: 'description',
onSave: this.props.onSave,
saving: this.props.saving,
//spinner: Spinner,
rows: 6,
required: "required",
className: "w-input field textarea markdown-body",
placeholder: 'How to solve this error?',
autoFocus: true,
buttonText: 'Create'
}),
this.props.error ? div({}, "Unable to save solution. ", this.props.error.message) : ""
),
div({className: 'w-col w-col-3'},
TextInput({
text: 'Level',
name: 'level',
onChange: this.props.onChange('level'),
values: solution
}),
TextInput({
text: 'Language',
name: 'programminglanguage',
onChange: this.props.onChange('programminglanguage'),
values: solution
}),
TextInput({
text: 'Language version',
name: 'programminglanguage_version',
onChange: this.props.onChange('programminglanguage_version'),
values: solution
}),
TextInput({
text: 'Operating system',
name: 'os',
onChange: this.props.onChange('os'),
values: solution
})
)
)
);
}
});
|
test/regressions/site/src/tests/Divider/InsetDivider.js | und3fined/material-ui | // @flow weak
import React from 'react';
import Divider from 'material-ui/Divider';
export default function InsetDivider() {
return (
<div style={{ padding: 2, width: 100 }}>
<Divider inset />
</div>
);
}
|
shared/components/Comment.js | AndrewGibson27/react-webpack-express-isomorphic-boilerplate | import React, { Component } from 'react';
const Comment = ({ body }) => (
<p>{body}</p>
);
export default Comment;
|
src/parser/warrior/arms/modules/core/Execute/MortalStrike.js | sMteX/WoWAnalyzer | import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import Abilities from 'parser/core/modules/Abilities';
import calculateMaxCasts from 'parser/core/calculateMaxCasts';
import Events from 'parser/core/Events';
import ExecuteRange from './ExecuteRange';
class MortalStrikeAnalyzer extends Analyzer {
static dependencies = {
abilities: Abilities,
executeRange: ExecuteRange,
};
mortalStrikesOutsideExecuteRange = 0;
mortalStrikesInExecuteRange = 0;
constructor(...args) {
super(...args);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.MORTAL_STRIKE), this._onMortalStrikeCast);
}
_onMortalStrikeCast(event) {
if (this.executeRange.isTargetInExecuteRange(event)) {
this.mortalStrikesInExecuteRange += 1;
event.meta = event.meta || {};
event.meta.isInefficientCast = true;
event.meta.inefficientCastReason = 'This Mortal Strike was used on a target in Execute range.';
} else {
this.mortalStrikesOutsideExecuteRange += 1;
}
}
get goodMortalStrikeThresholds() {
const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
const max = calculateMaxCasts(cd, this.owner.fightDuration - this.executeRange.executionPhaseDuration());
const maxCast = this.mortalStrikesOutsideExecuteRange / max > 1 ? this.mortalStrikesOutsideExecuteRange : max;
return {
actual: this.mortalStrikesOutsideExecuteRange / maxCast,
isLessThan: {
minor: 0.9,
average: 0.8,
major: 0.7,
},
style: 'percentage',
};
}
get badMortalStrikeThresholds() {
const cd = this.abilities.getAbility(SPELLS.MORTAL_STRIKE.id).cooldown;
const max = calculateMaxCasts(cd, this.executeRange.executionPhaseDuration());
const maxCast = this.mortalStrikesInExecuteRange / max > 1 ? this.mortalStrikesInExecuteRange : max;
return {
actual: this.mortalStrikesInExecuteRange / maxCast,
isGreaterThan: {
minor: 0,
average: 0.05,
major: 0.1,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.badMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<>Try to avoid using <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> on a target in <SpellLink id={SPELLS.EXECUTE.id} icon /> range, as <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> is less rage efficient than <SpellLink id={SPELLS.EXECUTE.id} />.</>)
.icon(SPELLS.MORTAL_STRIKE.icon)
.actual(`Mortal Strike was cast ${this.mortalStrikesInExecuteRange} times accounting for ${formatPercentage(actual)}% of the total possible casts of Mortal Strike during a time a target was in execute range.`)
.recommended(`${formatPercentage(recommended)}% is recommended`);
});
when(this.goodMortalStrikeThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<>Try to cast <SpellLink id={SPELLS.MORTAL_STRIKE.id} icon /> more often when the target is outside execute range.</>)
.icon(SPELLS.MORTAL_STRIKE.icon)
.actual(`Mortal Strike was used ${formatPercentage(actual)}% of the time on a target outside execute range.`)
.recommended(`${formatPercentage(recommended)}% is recommended`);
});
}
}
export default MortalStrikeAnalyzer;
|
packages/icons/src/md/maps/Navigation.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdNavigation(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<polygon points="24 5 9 41.59 10.41 43 24 37 37.59 43 39 41.59" />
</IconBase>
);
}
export default MdNavigation;
|
RNApp/node_modules/react-native/local-cli/generator/templates/index.android.js | abhaytalreja/react-native-telescope | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class <%= name %> extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('<%= name %>', () => <%= name %>);
|
src/main.js | daveham/ilgmrdx | import React from 'react';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { useRouterHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import createStore from 'store/createStore';
import Root from 'containers/Root';
// Browser History Setup
const browserHistory = useRouterHistory(createBrowserHistory)({
basename : __BASENAME__
});
// Store and History Instantiation
// Create redux store and sync with react-router-redux. We have installed the
// react-router-redux reducer under the routerKey "router" in src/routes/index.js,
// so we need to provide a custom `selectLocationState` to inform
// react-router-redux of its location.
const initialState = window.___INITIAL_STATE__;
const store = createStore(initialState, browserHistory);
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState : (state) => state.router
});
// Render Setup
const MOUNT_NODE = document.getElementById('root');
let render = () => {
const routes = require('./routes/index').default(store);
ReactDOM.render(
<Root
store={store}
history={history}
routes={routes}
/>,
MOUNT_NODE
);
};
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render;
const renderError = (error) => {
const RedBox = require('redbox-react').default;
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE);
};
// Wrap render in try/catch
render = () => {
try {
renderApp();
} catch (error) {
renderError(error);
}
};
// Setup hot module replacement
module.hot.accept('./routes/index', () => {
setTimeout(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render();
});
});
}
}
render();
|
analysis/deathknightblood/src/CONFIG.js | anom0ly/WoWAnalyzer | import SPELLS from 'common/SPELLS';
import { Yajinni, joshinator } from 'CONTRIBUTORS';
import SPECS from 'game/SPECS';
import { SpellLink } from 'interface';
import React from 'react';
import CHANGELOG from './CHANGELOG';
export default {
// The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
contributors: [Yajinni, joshinator],
// The WoW client patch this spec was last updated.
patchCompatibility: '9.0.5',
isPartial: false,
// Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
// If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
description: (
<>
Blood depends a lot on using his runes and how they're used in order to perform well.
<br />
Overusing <SpellLink id={SPELLS.MARROWREND.id} /> for example reduces the amount of runic
power you can generate, directly affecting the amount of{' '}
<SpellLink id={SPELLS.DEATH_STRIKE.id} />
's.
<br />
<br />
Not only the amount of <SpellLink id={SPELLS.DEATH_STRIKE.id} />
's are important, timing is aswell. Make sure to check them in the 'Death Strike Timing'-tab
below.
<br />
The rest of this analyzer focuses a lot on maximizing your damage output, buff uptimes,
cooldown usage and more or less usefull statistics.
<br />
Your best defensive rotation is also your best offensive one, so optimizing your output means
you'll optimize your survivability aswell.
<br />
<br />
If you find any issues or have something you'd like to see added, open an issue on{' '}
<a href="https://github.com/WoWAnalyzer/WoWAnalyzer/issues/new">GitHub</a>, contact us on{' '}
<a href="https://discord.gg/AxphPxU">Discord</a> or DM us on Discord.
<br />
<br />
Make sure to check out the <a href="https://goo.gl/qjTtNY">Death Knight Class Discord</a> if
you need more specific advice or a more detailed guide than the ones available on{' '}
<a href="https://www.icy-veins.com/wow/blood-death-knight-pve-tank-guide">Icy-Veins</a> and{' '}
<a href="http://www.wowhead.com/blood-death-knight-guide">wowhead</a>.
</>
),
// A recent example report to see interesting parts of the spec. Will be shown on the homepage.
exampleReport: "/report/mx1BaMV7PyL4FnKz/10-Mythic+Artificer+Xy'mox+-+Kill+(5:53)/Tombo/standard",
// Don't change anything below this line;
// The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
spec: SPECS.BLOOD_DEATH_KNIGHT,
// The contents of your changelog.
changelog: CHANGELOG,
// The CombatLogParser class for your spec.
parser: () =>
import('./CombatLogParser' /* webpackChunkName: "BloodDeathKnight" */).then(
(exports) => exports.default,
),
// The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
path: __dirname,
};
|
packages/example-universal-react-app/src/index.js | raymondsze/create-react-scripts | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
packages/components/src/List/Toolbar/ItemsNumber/ItemsNumber.component.js | Talend/ui | import React from 'react';
import PropTypes from 'prop-types';
import getDefaultT from '../../../translate';
function ItemsNumber({ id, totalItems, selected, label, labelSelected, t }) {
return (
<div className="tc-items-number" id={id}>
{selected
? labelSelected ||
t('LIST_TOOLBAR_NUMBER_OF_SELECTED_ITEMS', {
defaultValue: '{{count}}/{{total}} items',
count: selected,
total: totalItems,
})
: label ||
t('LIST_TOOLBAR_TOTAL_NUMBER_OF_ITEMS', {
defaultValue: '{{count}} items',
count: totalItems,
})}
</div>
);
}
ItemsNumber.propTypes = {
id: PropTypes.string,
selected: PropTypes.number,
totalItems: PropTypes.number,
label: PropTypes.string,
labelSelected: PropTypes.string,
t: PropTypes.func,
};
ItemsNumber.defaultProps = {
t: getDefaultT(),
};
export default ItemsNumber;
|
src/components/relativeLink/index.js | LiskHQ/lisk-nano | import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import buttonStyle from 'react-toolbox/lib/button/theme.css';
import offlineStyle from '../offlineWrapper/offlineWrapper.css';
import dialogs from '../dialog/dialogs';
const RelativeLink = ({
location, to, children, className, raised, neutral, primary, flat, disableWhenOffline,
}) => {
let style = '';
if (raised !== undefined) style += `${buttonStyle.raised} `;
if (neutral !== undefined) style += `${buttonStyle.neutral} `;
if (flat !== undefined) style += `${buttonStyle.flat} `;
if (primary !== undefined) style += `${buttonStyle.primary} `;
if (disableWhenOffline !== undefined) style += `${offlineStyle.disableWhenOffline} `;
if (style !== '') style += ` ${buttonStyle.button}`;
const dialogNames = Object.keys(dialogs());
let pathname = location.pathname;
dialogNames.forEach((dialog) => {
pathname = pathname.replace(`/${dialog}`, '');
});
const path = `${pathname}/${to}`.replace('//', '/');
return (
<Link className={`${className} ${style}`} to={path}>{ children }</Link>
);
};
const mapStateToProps = state => ({
dialog: state.dialog,
});
export default withRouter(connect(mapStateToProps)(RelativeLink));
|
client/src/components/StreamField/blocks/FieldBlock.js | torchbox/wagtail | /* global $ */
import { escapeHtml as h } from '../../../utils/text';
import ReactDOM from 'react-dom';
import React from 'react';
import Icon from '../../Icon/Icon';
export class FieldBlock {
constructor(
blockDef,
placeholder,
prefix,
initialState,
initialError,
parentCapabilities,
) {
this.blockDef = blockDef;
this.type = blockDef.name;
const dom = $(`
<div class="${h(this.blockDef.meta.classname)}">
<div class="field-content">
<div class="input">
<div data-streamfield-widget></div>
<span></span>
</div>
</div>
</div>
`);
$(placeholder).replaceWith(dom);
const widgetElement = dom.find('[data-streamfield-widget]').get(0);
this.element = dom[0];
this.parentCapabilities = parentCapabilities || new Map();
this.prefix = prefix;
try {
this.widget = this.blockDef.widget.render(
widgetElement,
prefix,
prefix,
initialState,
this.parentCapabilities,
);
} catch (e) {
// eslint-disable-next-line no-console
console.error(e);
this.setError([
{
messages: [
'This widget failed to render, please check the console for details',
],
},
]);
return;
}
this.idForLabel = this.widget.idForLabel;
if (this.blockDef.meta.helpText) {
const helpElement = document.createElement('p');
helpElement.classList.add('help');
helpElement.innerHTML = this.blockDef.meta.helpText; // unescaped, as per Django conventions
this.element.querySelector('.field-content').appendChild(helpElement);
}
if (window.comments && this.blockDef.meta.showAddCommentButton) {
const fieldCommentControlElement = document.createElement('div');
fieldCommentControlElement.classList.add('field-comment-control');
this.element.appendChild(fieldCommentControlElement);
const addCommentButtonElement = document.createElement('button');
addCommentButtonElement.type = 'button';
addCommentButtonElement.setAttribute(
'aria-label',
blockDef.meta.strings.ADD_COMMENT,
);
addCommentButtonElement.setAttribute('data-comment-add', '');
addCommentButtonElement.classList.add('button');
addCommentButtonElement.classList.add('button-secondary');
addCommentButtonElement.classList.add('button-small');
addCommentButtonElement.classList.add('u-hidden');
ReactDOM.render(
<>
<Icon name="comment-add" className="icon-default" />
<Icon name="comment-add-reversed" className="icon-reversed" />
</>,
addCommentButtonElement,
);
fieldCommentControlElement.appendChild(addCommentButtonElement);
window.comments.initAddCommentButton(addCommentButtonElement);
}
if (initialError) {
this.setError(initialError);
}
}
setCapabilityOptions(capability, options) {
Object.assign(this.parentCapabilities.get(capability), options);
if (this.widget && this.widget.setCapabilityOptions) {
this.widget.setCapabilityOptions(capability, options);
}
}
setState(state) {
if (this.widget) {
this.widget.setState(state);
}
}
setError(errorList) {
this.element
.querySelectorAll(':scope > .field-content > .error-message')
.forEach((element) => element.remove());
if (errorList) {
this.element.classList.add('error');
const errorElement = document.createElement('p');
errorElement.classList.add('error-message');
errorElement.innerHTML = errorList
.map((error) => `<span>${h(error.messages[0])}</span>`)
.join('');
this.element.querySelector('.field-content').appendChild(errorElement);
} else {
this.element.classList.remove('error');
}
}
getState() {
return this.widget.getState();
}
getValue() {
return this.widget.getValue();
}
getTextLabel(opts) {
if (this.widget.getTextLabel) {
return this.widget.getTextLabel(opts);
}
return null;
}
focus(opts) {
if (this.widget) {
this.widget.focus(opts);
}
}
}
export class FieldBlockDefinition {
constructor(name, widget, meta) {
this.name = name;
this.widget = widget;
this.meta = meta;
}
render(placeholder, prefix, initialState, initialError, parentCapabilities) {
return new FieldBlock(
this,
placeholder,
prefix,
initialState,
initialError,
parentCapabilities,
);
}
}
|
server/prerenderer.js | firegoby/react-ecosystem-aurora | import React from 'react'
import Router from 'react-router'
import Flux from '../app/flux.js'
import routes from '../app/routes.js'
import performRouteHandlerStaticMethod from '../app/shared/performRouteHandlerStaticMethod'
export default function (req, res) {
const flux = new Flux()
// let's just assume `npm run build` has been run at least once
const hash = require('../public/build/stats.json').hash
const router = Router.create({
routes: routes,
location: req.url,
onError: error => {
throw error
},
onAbort: abortReason => {
const error = new Error()
if (abortReason.constructor.name === 'Redirect') {
console.log('redirect causing abort')
const { to, params, query } = abortReason
console.log(to, params, query)
const url = router.makePath(to, params, query)
error.redirect = url
}
throw error
}
})
router.run(function (Handler, state) {
async function run() {
await performRouteHandlerStaticMethod(state.routes, 'routerWillRunOnServer', state, flux)
React.withContext(
{ flux },
() => {
let appString = React.renderToString(<Handler />)
res.render('index', { production: true, appString: appString, hash: hash })
}
)
}
run().catch(error => {
throw error
})
})
}
|
modules/IndexLink.js | littlefoot32/react-router | import React from 'react'
import Link from './Link'
var IndexLink = React.createClass({
render() {
return <Link {...this.props} onlyActiveOnIndex={true} />
}
})
export default IndexLink
|
src/parser/monk/brewmaster/modules/core/MasteryValue.js | sMteX/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import Analyzer from 'parser/core/Analyzer';
import StatTracker from 'parser/shared/modules/StatTracker';
import LazyLoadStatisticBox from 'interface/others/LazyLoadStatisticBox';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import OneVariableBinomialChart from 'interface/others/charts/OneVariableBinomialChart';
import DamageTaken from './DamageTaken';
import GiftOfTheOx from '../spells/GiftOfTheOx';
// coefficients to calculate dodge chance from agility
const MONK_DODGE_COEFFS = {
base_dodge: 3,
base_agi: 1468,
// names of individual coefficients are taken from ancient lore, err,
// formulae
P: 452.27,
D: 80,
v: 0.01,
h: 1.06382978723,
};
function _clampProb(prob) {
if (prob > 1.0) {
return 1.0;
} else if (prob < 0.0) {
return 0.0;
} else {
return prob;
}
}
/**
* This class represents the Markov Chain with which the Mastery stacks
* are modeled. The transition probabilities are defined by two
* potential operations:
*
* 1. Guaranteed Addition: from using an ability that generates a stack
* 100% of the time (e.g. BoS, BoF). The probability of having i stacks
* afterward is equal to the probability of having i-1 stacks before
* (the probability of having 0 stacks afterward is 0).
*
* 2. Attack: The probability of having i > 0 stacks afterward is equal to
* the probability of being hit with i - 1 stacks. The probability of
* having 0 stacks afterward is the sum of the probabilities of dodging
* with each number of stacks. Note that there is a natural cap on the
* number of stacks you can reach, since after that point every hit will
* be a dodge.
*
* The expected number of stacks you have is just the sum of the indices
* weighted by the values.
*/
class StackMarkovChain {
_stackProbs = [1.0];
_assertSum() {
const sum = this._stackProbs.reduce((sum, p) => p + sum, 0);
if (Math.abs(sum - 1.0) > 1e-6) {
const err = new Error('probabilities do not sum to 1 in StackMarkovChain');
err.data = {
sum: sum,
probs: this._stackProbs,
};
console.log(err.data);
throw err;
}
}
// add a stack with guaranteed probability
guaranteeStack() {
this._stackProbs.unshift(0.0);
this._assertSum();
}
processAttack(baseDodgeProb, masteryValue) {
this._stackProbs.push(0);
const n = this._stackProbs.length - 1;
// probability of ending at 0 stacks. initial
let zeroProb = 0;
// didn't dodge, gain a stack
for (let stacks = n - 1; stacks >= 0; stacks--) {
const prob = _clampProb(baseDodgeProb + masteryValue * stacks);
zeroProb += prob * this._stackProbs[stacks]; // dodge -> go to 0
const hitProb = 1 - prob;
this._stackProbs[stacks + 1] = hitProb * this._stackProbs[stacks]; // hit -> go to stacks + 1
}
// did dodge, reset stacks
this._stackProbs[0] = zeroProb;
this._assertSum();
}
get expected() {
return this._stackProbs.reduce((sum, prob, index) => sum + prob * index, 0);
}
}
export function baseDodge(agility, dodge_rating = 0) {
const base = MONK_DODGE_COEFFS.base_dodge + MONK_DODGE_COEFFS.base_agi / MONK_DODGE_COEFFS.P;
const chance = (agility - MONK_DODGE_COEFFS.base_agi) / MONK_DODGE_COEFFS.P + dodge_rating / MONK_DODGE_COEFFS.D;
// the x / (x + k) formula is commonly used by the wow team to
// implement diminishing returns
return (base + chance / (chance * MONK_DODGE_COEFFS.v + MONK_DODGE_COEFFS.h)) / 100;
}
/**
* Estimate the expected value of mastery on this fight. The *actual*
* estimated value is subject to greater variance.
* On the other hand, the expected value averages over all
* possible outcomes and gives a better sense of how valuable mastery is
* if you were to do this fight again. This values more stable over
* repeated attempts or kills and reflects the value of mastery (and the
* execution of the rotation) more closely than how well-favored you
* were on this particular attempt.
*
* We calculate the expected value by applying the Markov Chain above to
* the timeline to calculate the expected number of stacks at each
* dodgeable event. This is then combined with information about the
* expected damage of each dodged hit (dodge events have amount: 0,
* absorbed: 0, etc.) to provide a best-guess estimate of the damage
* you'll mitigate on average. The actual estimate (shown in the
* tooltip) may be over or under this, but is unlikely to be far from
* it.
*
* This madness was authored by emallson. If you need further explanation of
* the theory behind it, find me on discord.
*/
class MasteryValue extends Analyzer {
static dependencies = {
dmg: DamageTaken,
stats: StatTracker,
gotox: GiftOfTheOx,
};
_loaded = false;
_dodgeableSpells = {};
_timeline = [];
_hitCounts = {};
_dodgeCounts = {};
dodgePenalty(_source) {
return 0.045; // 1.5% per level, bosses are three levels over players. not sure how to get trash levels yet -- may not matter
}
// returns the current chance to dodge a damage event assuming the
// event is dodgeable
dodgeChance(masteryStacks, masteryRating, agility, sourceID, timestamp = null) {
const masteryPercentage = this.stats.masteryPercentage(masteryRating, true);
return _clampProb(masteryPercentage * masteryStacks + baseDodge(agility) - this.dodgePenalty(sourceID));
}
on_byPlayer_cast(event) {
if (this._stacksApplied(event) > 0) {
this._timeline.push(event);
}
}
on_toPlayer_damage(event) {
event._masteryRating = this.stats.currentMasteryRating;
event._agility = this.stats.currentAgilityRating;
if (event.hitType === HIT_TYPES.DODGE) {
this._addDodge(event);
} else {
this._addHit(event);
}
}
_addDodge(event) {
const spellId = event.ability.guid;
this._dodgeableSpells[spellId] = true;
if (this._dodgeCounts[spellId] === undefined) {
this._dodgeCounts[spellId] = 0;
}
this._dodgeCounts[spellId] += 1;
this._timeline.push(event);
}
_addHit(event) {
const spellId = event.ability.guid;
if (this._hitCounts[spellId] === undefined) {
this._hitCounts[spellId] = 0;
}
this._hitCounts[spellId] += 1;
this._timeline.push(event);
}
// returns true of the event represents a cast that applies a stack of
// mastery
_stacksApplied(event) {
if(event.ability.guid !== SPELLS.BLACKOUT_STRIKE.id) {
return 0;
}
let stacks = 1;
// account for elusive footwork
if(this.selectedCombatant.hasTrait(SPELLS.ELUSIVE_FOOTWORK.id) && event.hitType === HIT_TYPES.CRIT) {
stacks += 1;
}
return stacks;
}
meanHitByAbility(spellId) {
if (this._hitCounts[spellId] !== undefined) {
return (this.dmg.byAbility(spellId).effective + this.dmg.staggeredByAbility(spellId)) / this._hitCounts[spellId];
}
return 0;
}
// events that either (a) add a stack or (b) can be dodged according
// to the data we have
get relevantTimeline() {
return this._timeline.filter(event => event.type === 'cast' || this._dodgeableSpells[event.ability.guid]);
}
_expectedValues = {
expectedDamageMitigated: 0,
estimatedDamageMitigated: 0,
meanExpectedDodge: 0,
noMasteryExpectedDamageMitigated: 0,
noMasteryMeanExpectedDodge: 0,
noAgiExpectedDamageMitigated: 0,
};
_calculateExpectedValues() {
// expected damage mitigated according to the markov chain
let expectedDamageMitigated = 0;
let noMasteryExpectedDamageMitigated = 0;
let noAgiExpectedDamageMitigated = 0;
// estimate of the damage that was actually dodged in this log
let estimatedDamageMitigated = 0;
// average dodge % across each event that could be dodged
let meanExpectedDodge = 0;
let noMasteryMeanExpectedDodge = 0;
let dodgeableEvents = 0;
const stacks = new StackMarkovChain(); // mutating a const object irks me to no end
const noMasteryStacks = new StackMarkovChain();
const noAgiStacks = new StackMarkovChain();
// timeline replay is expensive, compute several things here and
// provide individual getters for each of the values
this.relevantTimeline.forEach(event => {
if (event.type === 'cast') {
const eventStacks = this._stacksApplied(event);
for(let i = 0; i < eventStacks; i++) {
stacks.guaranteeStack();
noMasteryStacks.guaranteeStack();
noAgiStacks.guaranteeStack();
}
} else if (event.type === 'damage') {
const noMasteryDodgeChance = this.dodgeChance(noMasteryStacks.expected, 0, event._agility, event.sourceID, event.timestamp);
const noAgiDodgeChance = this.dodgeChance(noAgiStacks.expected, event._masteryRating,
MONK_DODGE_COEFFS.base_agi, event.sourceID, event.timestamp);
const expectedDodgeChance = this.dodgeChance(stacks.expected, event._masteryRating, event._agility, event.sourceID, event.timestamp);
const baseDodgeChance = this.dodgeChance(0, 0, event._agility, event.sourceID, event.timestamp);
const noAgiBaseDodgeChance = this.dodgeChance(0, 0, MONK_DODGE_COEFFS.base_agi, event.sourceID, event.timestamp);
const damage = (event.amount + event.absorbed) || this.meanHitByAbility(event.ability.guid);
expectedDamageMitigated += expectedDodgeChance * damage;
noMasteryExpectedDamageMitigated += noMasteryDodgeChance * damage;
noAgiExpectedDamageMitigated += noAgiDodgeChance * damage;
estimatedDamageMitigated += (event.hitType === HIT_TYPES.DODGE) * damage;
meanExpectedDodge += expectedDodgeChance;
noMasteryMeanExpectedDodge += noMasteryDodgeChance;
dodgeableEvents += 1;
stacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(event._masteryRating, true));
noAgiStacks.processAttack(noAgiBaseDodgeChance, this.stats.masteryPercentage(event._masteryRating, true));
noMasteryStacks.processAttack(baseDodgeChance, this.stats.masteryPercentage(0, true));
}
});
meanExpectedDodge /= dodgeableEvents;
noMasteryMeanExpectedDodge /= dodgeableEvents;
return {
expectedDamageMitigated,
estimatedDamageMitigated,
meanExpectedDodge,
noMasteryExpectedDamageMitigated,
noMasteryMeanExpectedDodge,
noAgiExpectedDamageMitigated,
};
}
get expectedMitigation() {
return this._expectedValues.expectedDamageMitigated;
}
get expectedMeanDodge() {
return this._expectedValues.meanExpectedDodge;
}
get noMasteryExpectedMeanDodge() {
return this._expectedValues.noMasteryMeanExpectedDodge;
}
get totalDodges() {
return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + this._dodgeCounts[spellId], 0);
}
get totalDodgeableHits() {
return Object.keys(this._dodgeableSpells).reduce((sum, spellId) => sum + (this._hitCounts[spellId] || 0), 0)
+ this.totalDodges;
}
get actualDodgeRate() {
return this.totalDodges / this.totalDodgeableHits;
}
get estimatedActualMitigation() {
return this._expectedValues.estimatedDamageMitigated;
}
get averageMasteryRating() {
return this.relevantTimeline.reduce((sum, event) => {
if (event.type === 'damage') {
return event._masteryRating + sum;
} else {
return sum;
}
}, 0) / this.relevantTimeline.filter(event => event.type === 'damage').length;
}
get noMasteryExpectedMitigation() {
return this._expectedValues.noMasteryExpectedDamageMitigated;
}
get noAgiExpectedDamageMitigated() {
return this._expectedValues.noAgiExpectedDamageMitigated;
}
get expectedMitigationPerSecond() {
return this.expectedMitigation / this.owner.fightDuration * 1000;
}
get noMasteryExpectedMitigationPerSecond() {
return this.noMasteryExpectedMitigation / this.owner.fightDuration * 1000;
}
get totalMasteryHealing() {
return this.gotox.masteryBonusHealing;
}
get plot() {
// not the most efficient, but close enough and pretty safe
function binom(n, k) {
if(k > n) {
return null;
}
if(k === 0) {
return 1;
}
return n / k * binom(n-1, k-1);
}
// pmf of the binomial distribution with n = totalDodgeableHits and
// p = expectedMeanDodge
const dodge_prob = (i) => binom(this.totalDodgeableHits, i) * Math.pow(this.expectedMeanDodge, i) * Math.pow(1 - this.expectedMeanDodge, this.totalDodgeableHits - i);
// probability of having dodge exactly k of the n incoming hits
// assuming the expected mean dodge % is the true mean dodge %
const dodge_probs = Array.from({length: this.totalDodgeableHits}, (_x, i) => {
return { x: i, y: dodge_prob(i) };
});
const actualDodge = {
x: this.totalDodges,
y: dodge_prob(this.totalDodges),
};
return (
<OneVariableBinomialChart
probabilities={dodge_probs}
actualEvent={actualDodge}
yDomain={[0, 0.4]}
xAxis={{
title: 'Dodge %',
tickFormat: (value) => `${formatPercentage(value / this.totalDodgeableHits, 0)}%`,
}}
tooltip={(point) => `Actual Dodge: ${formatPercentage(point.x / this.totalDodgeableHits, 2)}%`}
/>
);
}
load() {
this._loaded = true;
this._expectedValues = this._calculateExpectedValues();
return Promise.resolve(this._expectedValues);
}
statistic() {
return (
<LazyLoadStatisticBox
loader={this.load.bind(this)}
icon={<SpellIcon id={SPELLS.MASTERY_ELUSIVE_BRAWLER.id} />}
value={`${formatNumber(this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond)} DTPS`}
label="Expected Mitigation by Mastery"
tooltip={this._loaded ? (
<>
On average, you would dodge about <strong>{formatNumber(this.expectedMitigation)}</strong> damage on this fight. This value was increased by about <strong>{formatNumber(this.expectedMitigation - this.noMasteryExpectedMitigation)}</strong> due to Mastery.
You had an average expected dodge chance of <strong>{formatPercentage(this.expectedMeanDodge)}%</strong> and actually dodged about <strong>{formatNumber(this.estimatedActualMitigation)}</strong> damage with an overall rate of <strong>{formatPercentage(this.actualDodgeRate)}%</strong>.
This amounts to an expected reduction of <strong>{formatNumber((this.expectedMitigationPerSecond - this.noMasteryExpectedMitigationPerSecond) / this.averageMasteryRating)} DTPS per 1 Mastery</strong> <em>on this fight</em>.<br /><br />
<em>Technical Information:</em><br />
<strong>Estimated Actual Damage</strong> is calculated by calculating the average damage per hit of an ability, then multiplying that by the number of times you dodged each ability.<br />
<strong>Expected</strong> values are calculated by computing the expected number of mastery stacks each time you <em>could</em> dodge an ability.<br />
An ability is considered <strong>dodgeable</strong> if you dodged it at least once.
</>
) : null}
>
<div style={{padding: '8px'}}>
{this._loaded ? this.plot : null}
<p>Likelihood of dodging <em>exactly</em> as much as you did with your level of Mastery.</p>
</div>
</LazyLoadStatisticBox>
);
}
}
export default MasteryValue;
|
src/js/components/AccordionPanel.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Header from './Header';
import Button from './Button';
import ListItem from './ListItem';
import CaretNextIcon from './icons/base/CaretNext';
import Collapsible from './Collapsible';
import CSSClassnames from '../utils/CSSClassnames';
import Intl from '../utils/Intl';
const CLASS_ROOT = CSSClassnames.ACCORDION_PANEL;
export default class AccordionPanel extends Component {
constructor() {
super();
this._onClickTab = this._onClickTab.bind(this);
}
_onClickTab (event) {
const { onChange } = this.props;
if (event) {
event.preventDefault();
}
onChange();
}
render () {
const {
a11yTitle, active, animate, className, children, heading, pad
} = this.props;
const { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
className,
{
[`${CLASS_ROOT}--active`]: active
}
);
const tabContentTitle = Intl.getMessage(intl, 'Tab Contents', {
activeTitle: a11yTitle || heading
});
return (
<div>
<ListItem className={classes} direction='column' pad='none'
aria-expanded={active} aria-selected={active} role='tab'
aria-label={a11yTitle || heading}>
<Button fill={true} plain={true} onClick={this._onClickTab}>
<Header pad={pad} direction='row'
justify='between' align='center' responsive={false}
className={`${CLASS_ROOT}__header`}>
{heading}
<CaretNextIcon
className={`${CLASS_ROOT}__control`} />
</Header>
</Button>
</ListItem>
<Collapsible aria-label={tabContentTitle} role='tabpanel'
active={active} animate={animate} pad={pad}>
{children}
</Collapsible>
</div>
);
}
}
AccordionPanel.propTypes = {
a11yTitle: PropTypes.string,
active: PropTypes.bool, // set by Accordion
animate: PropTypes.bool,
heading: PropTypes.node.isRequired,
onChange: PropTypes.func,
pad: Header.propTypes.pad
};
AccordionPanel.contextTypes = {
intl: PropTypes.object
};
|
local-cli/templates/HelloNavigation/components/ListItem.js | makadaw/react-native | 'use strict';
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
TouchableHighlight,
TouchableNativeFeedback,
View,
} from 'react-native';
/**
* Renders the right type of Touchable for the list item, based on platform.
*/
const Touchable = ({onPress, children}) => {
const child = React.Children.only(children);
if (Platform.OS === 'android') {
return (
<TouchableNativeFeedback onPress={onPress}>
{child}
</TouchableNativeFeedback>
);
} else {
return (
<TouchableHighlight onPress={onPress} underlayColor="#ddd">
{child}
</TouchableHighlight>
);
}
}
const ListItem = ({label, onPress}) => (
<Touchable onPress={onPress}>
<View style={styles.item}>
<Text style={styles.label}>{label}</Text>
</View>
</Touchable>
);
const styles = StyleSheet.create({
item: {
height: 48,
justifyContent: 'center',
paddingLeft: 12,
borderBottomWidth: StyleSheet.hairlineWidth,
borderBottomColor: '#ddd',
},
label: {
fontSize: 16,
}
});
export default ListItem;
|
packages/starter-scripts/fixtures/kitchensink/src/features/webpack/ScssModulesInclusion.js | chungchiehlun/create-starter-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import styles from './assets/scss-styles.module.scss';
import indexStyles from './assets/index.module.scss';
export default () => (
<div>
<p className={styles.scssModulesInclusion}>SCSS Modules are working!</p>
<p className={indexStyles.scssModulesIndexInclusion}>
SCSS Modules with index are working!
</p>
</div>
);
|
components/navbar/DropDownMenu.js | telemark/portalen | import React from 'react'
import { Icon } from '../styles'
export default class extends React.Component {
constructor (props) {
super(props)
this.state = {
isOpen: false
}
this.handleOutsideClick = this.handleOutsideClick.bind(this)
this.handleClick = this.handleClick.bind(this)
}
handleClick () {
this.state.isOpen
? document.removeEventListener('click', this.handleOutsideClick, false)
: document.addEventListener('click', this.handleOutsideClick, false)
this.setState(prevState => ({ isOpen: !prevState.isOpen }))
}
handleOutsideClick (e) {
if (this.node.contains(e.target)) {
return
}
this.handleClick()
}
render () {
return (
<div className='menu' ref={node => { this.node = node }}>
<a onClick={this.handleClick}><Icon name='more_vert' /></a>
{
this.state.isOpen &&
<div className='menu-content'>
{this.props.children}
</div>
}
<style jsx>
{`
.menu {
position: relative;
cursor: pointer;
}
.menu-content {
display: inline-block;
position: absolute;
background-color: #f9f9f9;
min-width: 130px;
box-shadow: 0px 8px 16px 0px rgba(0,0,0,0.2);
z-index: 1;
right: 0;
line-height: 30px;
top: 40px;
text-align: center;
border-radius: 2px;
}
`}
</style>
</div>
)
}
}
|
src/files/explore-form/FilesExploreForm.stories.js | ipfs/webui | import React from 'react'
import { storiesOf } from '@storybook/react'
import { action } from '@storybook/addon-actions'
import { checkA11y } from '@storybook/addon-a11y'
import i18n from '../../i18n-decorator'
import FilesExploreForm from './FilesExploreForm'
storiesOf('Files', module)
.addDecorator(checkA11y)
.addDecorator(i18n)
.add('Explore Form', () => (
<div className='ma3 pa3 bg-snow-muted mw6'>
<FilesExploreForm onBrowse={action('Browse')} onInspect={action('Inspect')} />
</div>
))
|
src/svg-icons/av/high-quality.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvHighQuality = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.11 0-2 .9-2 2v12c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 11H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm7-1c0 .55-.45 1-1 1h-.75v1.5h-1.5V15H14c-.55 0-1-.45-1-1v-4c0-.55.45-1 1-1h3c.55 0 1 .45 1 1v4zm-3.5-.5h2v-3h-2v3z"/>
</SvgIcon>
);
AvHighQuality = pure(AvHighQuality);
AvHighQuality.displayName = 'AvHighQuality';
AvHighQuality.muiName = 'SvgIcon';
export default AvHighQuality;
|
client/components/ReactHotLoader.js | KCPSoftware/KCPS-React-Starterkit | /* eslint-disable global-require */
/* eslint-disable import/no-extraneous-dependencies */
import React from 'react';
// We create this wrapper so that we only import react-hot-loader for a
// development build. Small savings. :)
const ReactHotLoader = process.env.NODE_ENV === 'development'
? require('react-hot-loader').AppContainer
: ({ children }) => React.Children.only(children);
export default ReactHotLoader;
|
src/icons/IosListOutline.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class IosListOutline extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<g>
<path d="M432,80v352H80V80H432 M448,64H64v384h384V64L448,64z"></path>
<g>
<rect x="192" y="152" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="248" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="344" width="192" height="16"></rect>
</g>
</g>
<circle cx="144" cy="160" r="16"></circle>
<circle cx="144" cy="256" r="16"></circle>
<circle cx="144" cy="352" r="16"></circle>
</g>
</g>;
} return <IconBase>
<g>
<g>
<path d="M432,80v352H80V80H432 M448,64H64v384h384V64L448,64z"></path>
<g>
<rect x="192" y="152" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="248" width="192" height="16"></rect>
</g>
<g>
<rect x="192" y="344" width="192" height="16"></rect>
</g>
</g>
<circle cx="144" cy="160" r="16"></circle>
<circle cx="144" cy="256" r="16"></circle>
<circle cx="144" cy="352" r="16"></circle>
</g>
</IconBase>;
}
};IosListOutline.defaultProps = {bare: false} |
src/elements/List/ListHeader.js | aabustamante/Semantic-UI-React | import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A list item can contain a header.
*/
function ListHeader(props) {
const { children, className, content } = props
const classes = cx('header', className)
const rest = getUnhandledProps(ListHeader, props)
const ElementType = getElementType(ListHeader, props)
return (
<ElementType {...rest} className={classes}>
{_.isNil(children) ? content : children}
</ElementType>
)
}
ListHeader._meta = {
name: 'ListHeader',
parent: 'List',
type: META.TYPES.ELEMENT,
}
ListHeader.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
}
ListHeader.create = createShorthandFactory(ListHeader, content => ({ content }))
export default ListHeader
|
src/routes.js | Rosita13/react-redux | /* eslint-disable */
import React from 'react';
import { IndexRoute, Route } from 'react-router';
import { routerActions } from 'react-router-redux';
import { UserAuthWrapper } from 'redux-auth-wrapper';
import { App, Home, NotFound } from 'containers';
import getRoutesUtils from 'utils/routes';
// eslint-disable-next-line import/no-dynamic-require
if (typeof System.import === 'undefined') System.import = module => Promise.resolve(require(module));
export default store => {
const {
injectReducerAndRender,
permissionsComponent
} = getRoutesUtils(store);
/* Permissions */
const isAuthenticated = UserAuthWrapper({
authSelector: state => state.auth.user,
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsAuthenticated'
});
const isNotAuthenticated = UserAuthWrapper({
authSelector: state => state.auth.user,
redirectAction: routerActions.replace,
wrapperDisplayName: 'UserIsNotAuthenticated',
predicate: user => !user,
failureRedirectPath: '/',
allowRedirectBack: false
});
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
{/* Home (main) route */}
<IndexRoute component={Home} />
{/* Routes requiring login */}
{/*
You can also protect a route like this:
<Route path="protected-route" {...permissionsComponent(isAuthenticated)(Component)}>
*/}
<Route {...permissionsComponent(isAuthenticated)() }>
<Route path="loginSuccess" getComponent={() => System.import('./containers/LoginSuccess/LoginSuccess')} />
<Route
path="chatFeathers"
getComponent={() => injectReducerAndRender(
{ chat: System.import('./redux/modules/chat') },
System.import('./containers/ChatFeathers/ChatFeathers')
)}
/>
/>
</Route>
{/* Routes disallow login */}
<Route {...permissionsComponent(isNotAuthenticated)() }>
<Route path="register" getComponent={() => System.import('./containers/Register/Register')} />
</Route>
{/* Routes */}
{/*<Route path="login" getComponent={() => System.import('./containers/Login/Login')} /> */}
<Route path="about" getComponent={() => System.import('./containers/About/About')} />
<Route path="profile" getComponent={() => System.import('./containers/profile/profile')} />
<Route path="cooperations" getComponent={() => System.import('./containers/Cooperations/Cooperations')} />
<Route path="cooperation/:slug" getComponent={() => System.import('./containers/Cooperation/Cooperation')} />
<Route
path="cooperation/:slug/edit"
getComponent={() => System.import('./containers/CooperationEdit/CooperationEdit')} />
<Route
path="cooperation-create"
getComponent={() => System.import('./containers/CooperationCreate/CooperationCreate')} />
<Route path="cooperation" getComponent={() => System.import('./containers/Cooperation/Cooperation')} />
<Route
path="survey"
getComponent={() => injectReducerAndRender(
{ survey: System.import('./redux/modules/survey') },
System.import('./containers/Survey/Survey')
)}
/>
/>
<Route
path="widgets"
getComponent={() => injectReducerAndRender(
{ widgets: System.import('./redux/modules/widgets') },
System.import('./containers/Widgets/Widgets')
)}
/>
/>
<Route path="chat" getComponent={() => System.import('./containers/Chat/Chat')} />
{/* Catch all route */}
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
app/javascript/components/FieldShape/FieldShape.js | SumOfUs/Champaign | import React, { Component } from 'react';
import { map, pick } from 'lodash';
import SweetInput from '../SweetInput/SweetInput';
import SelectCountry from '../SelectCountry/SelectCountry';
import SweetSelect from '../SweetSelect/SweetSelect';
import Checkbox from '../Checkbox/Checkbox';
export default class FieldShape extends Component {
checkboxToggle(event) {
const checked = event.currentTarget.checked;
this.props.onChange && this.props.onChange(checked ? '1' : '0');
}
fieldProps() {
const { field, value } = this.props;
return {
name: field.name,
label: field.label,
disabled: field.disabled,
required: field.required,
value: value,
errorMessage: this.props.errorMessage,
onChange: this.props.onChange,
};
}
errorMessage(fieldProps) {
if (fieldProps.errorMessage)
return <span className="error-msg">{fieldProps.errorMessage}</span>;
}
renderParagraph(fieldProps) {
return (
<div>
<textarea
name={fieldProps.name}
value={fieldProps.value}
placeholder={fieldProps.label}
onChange={e =>
fieldProps.onChange && fieldProps.onChange(e.currentTarget.value)
}
className={fieldProps.errorMessage ? 'has-error' : ''}
maxLength="9999"
/>
{this.errorMessage(fieldProps)}
</div>
);
}
renderCheckbox(fieldProps) {
fieldProps.value = (fieldProps.value || '0').toString();
const checked =
fieldProps.value === '1' ||
fieldProps.value === 'checked' ||
fieldProps.value === 'true';
return (
<div>
<Checkbox checked={checked} onChange={this.checkboxToggle.bind(this)}>
{fieldProps.label}
</Checkbox>
{this.errorMessage(fieldProps)}
</div>
);
}
renderChoice(fieldProps) {
const { field } = this.props;
return (
<div className="radio-container">
<div className="form__instruction">{fieldProps.label}</div>
{field.choices &&
field.choices.map(choice => (
<label key={choice.id} htmlFor={choice.id}>
<input
id={choice.id}
name={fieldProps.name}
type="radio"
value={choice.value}
checked={choice.value === fieldProps.value}
onChange={event =>
this.props.onChange &&
this.props.onChange(event.currentTarget.value)
}
/>
{choice.label}
</label>
))}
{this.errorMessage(fieldProps)}
</div>
);
}
renderField(type) {
const fieldProps = this.fieldProps();
const {
field: { default_value, name, choices },
} = this.props;
switch (type) {
case 'email':
return <SweetInput type="email" {...fieldProps} />;
case 'phone':
case 'numeric':
return <SweetInput type="tel" {...fieldProps} />;
case 'country':
return <SelectCountry {...fieldProps} />;
case 'dropdown':
case 'select':
return (
<SweetSelect
{...fieldProps}
options={map(choices, c => pick(c, 'value', 'label'))}
/>
);
case 'hidden':
return <input type="hidden" name={name} value={default_value} />;
case 'checkbox':
return this.renderCheckbox(fieldProps);
case 'choice':
return this.renderChoice(fieldProps);
case 'instruction':
return <div className="form__instruction">{fieldProps.label}</div>;
case 'paragraph':
return this.renderParagraph(fieldProps);
case 'text':
case 'postal':
default:
return <SweetInput type="text" {...fieldProps} />;
}
}
render() {
return (
<div
key={this.props.field.name}
className={`MemberDetailsForm-field form__group action-form__field-container ${this
.props.className || ''}`}
>
{this.renderField(this.props.field.data_type)}
</div>
);
}
}
|
client/app/containers/LocaleToggle/index.js | KamillaKhabibrakhmanova/postcardsforchange-api | /*
*
* LanguageToggle
*
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import Toggle from 'components/Toggle';
import Wrapper from './Wrapper';
import messages from './messages';
import { appLocales } from '../../i18n';
import { changeLocale } from '../LanguageProvider/actions';
import { makeSelectLocale } from '../LanguageProvider/selectors';
export class LocaleToggle extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<Wrapper>
<Toggle value={this.props.locale} values={appLocales} messages={messages} onToggle={this.props.onLocaleToggle} />
</Wrapper>
);
}
}
LocaleToggle.propTypes = {
onLocaleToggle: React.PropTypes.func,
locale: React.PropTypes.string,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
export function mapDispatchToProps(dispatch) {
return {
onLocaleToggle: (evt) => dispatch(changeLocale(evt.target.value)),
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LocaleToggle);
|
src/components/table/TableQuickInput.js | metasfresh/metasfresh-webui-frontend | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import cx from 'classnames';
import { getLayout, patchRequest } from '../../api';
import { addNotification } from '../../actions/AppActions';
import { completeRequest, createInstance } from '../../actions/GenericActions';
import { parseToDisplay } from '../../utils/documentListHelper';
import RawWidget from '../widget/RawWidget';
class TableQuickInput extends Component {
// promise with patching for queuing form submission after patch is done
patchPromise;
constructor(props) {
super(props);
this.state = {
layout: null,
data: null,
id: null,
editedField: 0,
inProgress: false,
};
}
componentDidMount() {
this.initQuickInput();
}
componentDidUpdate() {
const { data, layout, editedField } = this.state;
if (data && layout) {
for (let i = 0; i < layout.length; i++) {
const item = layout[i].fields.map((elem) => data[elem.field] || -1);
if (!item[0].value) {
if (editedField !== i) {
this.setState(
{
editedField: i,
},
() => {
if (this.rawWidgets) {
let curWidget = this.rawWidgets[i];
if (curWidget && curWidget.focus) {
curWidget.focus();
}
}
}
);
}
break;
}
}
}
}
initQuickInput = () => {
const { dispatch, docType, docId, tabId, closeBatchEntry } = this.props;
const { layout } = this.state;
this.setState(
{
data: null,
},
() => {
createInstance('window', docType, docId, tabId, 'quickInput')
.then((instance) => {
this.setState({
data: parseToDisplay(instance.data.fieldsByName),
id: instance.data.id,
editedField: 0,
});
})
.catch((err) => {
if (err.response.status === 404) {
dispatch(
addNotification(
'Batch entry error',
'Batch entry is not available.',
5000,
'error'
)
);
closeBatchEntry();
}
});
!layout &&
getLayout('window', docType, tabId, 'quickInput', docId).then(
(layout) => {
this.setState({
layout: layout.data.elements,
});
}
);
}
);
};
handleChange = (field, value) => {
this.setState((prevState) => ({
data: Object.assign({}, prevState.data, {
[field]: Object.assign({}, prevState.data[field], {
value,
}),
}),
}));
};
handlePatch = (prop, value, callback) => {
const { docType, docId, tabId } = this.props;
const { id } = this.state;
this.setState(
{
inProgress: true,
},
() => {
this.patchPromise = new Promise((resolve) => {
patchRequest({
entity: 'window',
docType,
docId,
tabId,
property: prop,
value,
subentity: 'quickInput',
subentityId: id,
}).then((response) => {
const fields = response.data[0] && response.data[0].fieldsByName;
fields &&
Object.keys(fields).map((fieldName) => {
this.setState(
(prevState) => ({
data: Object.assign({}, prevState.data, {
[fieldName]: Object.assign(
{},
prevState.data[fieldName],
fields[fieldName]
),
}),
inProgress: false,
}),
() => {
if (callback) {
callback();
}
resolve();
}
);
});
});
});
}
);
};
renderFields = (layout, data, dataId, attributeType, quickInputId) => {
const { tabId, docType, forceHeight } = this.props;
const { inProgress } = this.state;
this.rawWidgets = [];
const layoutFieldsAmt = layout ? layout.length : 2;
const stylingLayout = [
{
formGroup: cx(`col-12`, {
'col-lg-5': layoutFieldsAmt === 2,
'col-xl-6': layoutFieldsAmt === 2,
'col-lg-4': layoutFieldsAmt === 3,
'col-xl-5': layoutFieldsAmt === 3,
}),
label: `col-12 col-lg-3 quickInput-label`,
field: `col-12 col-lg-9`,
},
{
formGroup: `col-12 col-lg-3 col-xl-3`,
label: `col-12 col-sm-4 col-lg-5 col-xl-4`,
field: `col-12 col-sm-8 col-lg-7 col-xl-8`,
},
{
formGroup: `col-12 col-lg-3 col-xl-2`,
label: `col-12 col-sm-9 col-lg-7`,
field: `col-12 col-sm-3 col-lg-5`,
},
];
if (data && layout) {
return layout.map((item, idx) => {
const widgetData = item.fields.map((elem) => data[elem.field] || -1);
const lastFormField = idx === layout.length - 1;
return (
<RawWidget
ref={(c) => {
if (c) {
this.rawWidgets.push(c);
}
}}
fieldFormGroupClass={stylingLayout[idx].formGroup}
fieldLabelClass={stylingLayout[idx].label}
fieldInputClass={stylingLayout[idx].field}
inProgress={inProgress}
entity={attributeType}
subentity="quickInput"
subentityId={quickInputId}
tabId={tabId}
windowType={docType}
widgetType={item.widgetType}
fields={item.fields}
dataId={dataId}
widgetData={widgetData}
gridAlign={item.gridAlign}
forceFullWidth={widgetData.length > 1}
forceHeight={forceHeight}
key={idx}
lastFormField={lastFormField}
caption={item.caption}
handlePatch={this.handlePatch}
handleChange={this.handleChange}
type="secondary"
autoFocus={idx === 0}
initialFocus={idx === 0}
/>
);
});
}
};
onSubmit = (e) => {
const { dispatch, docType, docId, tabId } = this.props;
const { id, data } = this.state;
e.preventDefault();
document.activeElement.blur();
if (!this.validateForm(data)) {
return dispatch(
addNotification(
'Error',
'Mandatory fields are not filled!',
5000,
'error'
)
);
}
return this.patchPromise
.then(() => {
return completeRequest(
'window',
docType,
docId,
tabId,
null,
'quickInput',
id
);
})
.then(() => {
this.initQuickInput();
});
};
validateForm = (data) => {
return !Object.keys(data).filter(
(key) => data[key].mandatory && !data[key].value
).length;
};
render() {
const { docId } = this.props;
const { data, layout, id } = this.state;
return (
<form
onSubmit={this.onSubmit}
className="row quick-input-container"
ref={(c) => (this.form = c)}
>
{this.renderFields(layout, data, docId, 'window', id)}
<div className="col-sm-12 col-md-3 col-lg-2 hint">
{`(Press 'Enter' to add)`}
</div>
<button type="submit" className="hidden-up" />
</form>
);
}
}
TableQuickInput.propTypes = {
dispatch: PropTypes.func.isRequired,
closeBatchEntry: PropTypes.func,
forceHeight: PropTypes.number,
docType: PropTypes.any,
docId: PropTypes.string,
tabId: PropTypes.string,
};
export default connect()(TableQuickInput);
|
client/modules/App/__tests__/Components/Header.spec.js | GTDev87/stylizer | import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { FormattedMessage } from 'react-intl';
import { Header } from '../../components/Header/Header';
import { intl } from '../../../../util/react-intl-test-helper';
const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] };
test('renders the header properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.truthy(wrapper.find('Link').first().containsMatchingElement(<FormattedMessage id="siteTitle" />));
t.is(wrapper.find('a').length, 1);
});
test('doesn\'t add post in pages other than home', t => {
const router = {
isActive: sinon.stub().returns(false),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.is(wrapper.find('a').length, 0);
});
test('toggleAddPost called properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const toggleAddPost = sinon.spy();
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={toggleAddPost} />,
{
context: {
router,
intl,
},
}
);
wrapper.find('a').first().simulate('click');
t.truthy(toggleAddPost.calledOnce);
});
|
src/svg-icons/action/settings-overscan.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsOverscan = (props) => (
<SvgIcon {...props}>
<path d="M12.01 5.5L10 8h4l-1.99-2.5zM18 10v4l2.5-1.99L18 10zM6 10l-2.5 2.01L6 14v-4zm8 6h-4l2.01 2.5L14 16zm7-13H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16.01H3V4.99h18v14.02z"/>
</SvgIcon>
);
ActionSettingsOverscan = pure(ActionSettingsOverscan);
ActionSettingsOverscan.displayName = 'ActionSettingsOverscan';
ActionSettingsOverscan.muiName = 'SvgIcon';
export default ActionSettingsOverscan;
|
src/index.js | erdgabios/react-youtube-search | import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail';
// Put here your youtube-api-search key
const API_KEY = '';
class App extends Component {
constructor(props){
super(props);
this.state = {
videos: [],
selectedVideo: null
};
this.videoSearch('surfboards');
}
videoSearch(term) {
YTSearch({key: API_KEY, term: term}, (videos) => {
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render() {
const videoSearch = _.debounce((term) => { this.videoSearch(term) }, 300);
return (
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({selectedVideo}) }
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container'));
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.