path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
---|---|---|
website/irulez/src/components/admin_menu/Dashboard.js | deklungel/iRulez | import React, { Component } from 'react';
import './Dashboard.css';
class Admin extends Component {
constructor(props) {
super(props);
this.props.Collapse('dashboard');
}
render() {
return (
<div className='Admin'>
<div className='App-header'>
<h2>Welcome Admin</h2>
</div>
</div>
);
}
}
export default Admin;
|
src/Parser/HolyPaladin/Modules/Items/Tier20_4set.js | mwwscott0/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatNumber } from 'common/format';
import Module from 'Parser/Core/Module';
import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing';
import Combatants from 'Parser/Core/Modules/Combatants';
import { BEACON_TYPES, BASE_BEACON_TRANSFER, BEACON_OF_FAITH_TRANSFER_REDUCTION } from '../../Constants';
import LightOfDawn from '../PaladinCore/LightOfDawn';
const LIGHTS_EMBRACE_BEACON_HEAL_INCREASE = 0.4;
/**
* 4 pieces (Holy) : For 5 sec after casting Light of Dawn, your healing spells will transfer an additional 40% to your Beacon of Light target.
*/
class Tier20_4set extends Module {
static dependencies = {
combatants: Combatants,
lightOfDawn: LightOfDawn,
};
healing = 0;
totalBeaconHealingDuringLightsEmbrace = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.HOLY_PALADIN_T20_4SET_BONUS_BUFF.id);
}
on_beacon_heal(beaconTransferEvent, healEvent) {
const baseBeaconTransferFactor = this.getBaseBeaconTransferFactor(healEvent);
const lightsEmbraceBeaconTransferFactor = this.getLightsEmbraceBeaconTransferFactor(healEvent);
if (lightsEmbraceBeaconTransferFactor === 0) {
return;
}
const totalBeaconTransferFactor = baseBeaconTransferFactor + lightsEmbraceBeaconTransferFactor;
const lightsEmbraceBeaconTransferHealingIncrease = lightsEmbraceBeaconTransferFactor / totalBeaconTransferFactor;
const effectiveHealing = calculateEffectiveHealing(beaconTransferEvent, lightsEmbraceBeaconTransferHealingIncrease);
this.healing += effectiveHealing;
this.totalBeaconHealingDuringLightsEmbrace += beaconTransferEvent.amount + (beaconTransferEvent.absorbed || 0) + (beaconTransferEvent.overheal || 0);
}
getBaseBeaconTransferFactor(healEvent) {
let beaconFactor = BASE_BEACON_TRANSFER;
if (this.beaconType === BEACON_TYPES.BEACON_OF_FATH) {
beaconFactor *= (1 - BEACON_OF_FAITH_TRANSFER_REDUCTION);
}
return beaconFactor;
}
getLightsEmbraceBeaconTransferFactor(healEvent) {
let beaconTransferFactor = 0;
// What happens here are 2 situations:
// - Light of Dawn applies Light's Embrace, it acts a bit weird though since the FIRST heal from the cast does NOT get the increased beacon transfer, while all sebsequent heals do (even when the combatlog has't fired the Light's Embrace applybuff event yet). The first part checks for that. The combatlog looks different when the first heal is a self heal vs they're all on other people, but in both cases it always doesn't apply to the first LoD heal and does for all subsequent ones.
// - If a FoL or something else is cast right before the LoD, the beacon transfer may be delayed until after the Light's Embrace is applied. This beacon transfer does not appear to benefit. My hypothesis is that the server does healing and buffs async and there's a small lag between the processes, and I think 100ms should be about the time required.
const hasLightsEmbrace = (healEvent.ability.guid === SPELLS.LIGHT_OF_DAWN_HEAL.id && healEvent.lightOfDawnHealIndex > 0) || this.combatants.selected.hasBuff(SPELLS.LIGHTS_EMBRACE_BUFF.id, null, 0, 100);
if (hasLightsEmbrace) {
beaconTransferFactor += LIGHTS_EMBRACE_BEACON_HEAL_INCREASE;
}
if (this.beaconType === BEACON_TYPES.BEACON_OF_FATH) {
beaconTransferFactor *= (1 - BEACON_OF_FAITH_TRANSFER_REDUCTION);
}
// console.log(hasLightsEmbrace, healEvent.ability.name, healEvent, '-', (healEvent.timestamp - this.owner.fight.start_time) / 1000, 'seconds into the fight');
return beaconTransferFactor;
}
item() {
return {
id: `spell-${SPELLS.HOLY_PALADIN_T20_4SET_BONUS_BUFF.id}`,
icon: <SpellIcon id={SPELLS.HOLY_PALADIN_T20_4SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.HOLY_PALADIN_T20_4SET_BONUS_BUFF.id} />,
result: (
<dfn data-tip={`The actual effective healing contributed by the tier 20 4 set bonus. A total of ${formatNumber(this.totalBeaconHealingDuringLightsEmbrace)} <span style="color:orange">raw</span> healing was done on beacons during the Light's Embrace buff.`}>
{this.owner.formatItemHealingDone(this.healing)}
</dfn>
),
};
}
}
export default Tier20_4set;
|
src/components/UI/NewEntry/NewEntry.js | wanchopen/vida | import React, { Component } from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './NewEntry.css';
import Dialog from 'material-ui/Dialog';
import {grey400, cyan500} from 'material-ui/styles/colors';
import IconButton from 'material-ui/IconButton';
import EditorBorderColor from 'material-ui/svg-icons/editor/border-color';
import EditorPublish from 'material-ui/svg-icons/editor/publish';
import ContentDrafts from 'material-ui/svg-icons/content/drafts';
import TextField from 'material-ui/TextField';
const styles = {
iconSize: {
width: 21,
height: 21,
}
};
class NewEntry extends Component {
state = {
open: false,
};
handleOpen = () => {
this.setState({open: true});
};
handleClose = () => {
this.setState({open: false});
};
render() {
const actions = [
<IconButton tooltip="Publish"
tooltipPosition="bottom-center"
onTouchTap={this.handleClose}>
<EditorPublish color={cyan500} className={s.actionIcon}/>
</IconButton>,
<IconButton tooltip="Save as a draft"
tooltipPosition="bottom-center"
onTouchTap={this.handleClose}>
<ContentDrafts color={grey400} className={s.actionIcon}/>
</IconButton>
];
return (
<div>
<IconButton tooltip="Write an Entry"
tooltipPosition="bottom-right"
iconStyle={styles.iconSize}
onTouchTap={this.handleOpen}>
<EditorBorderColor color={grey400} className={s.viewsIcon}/>
</IconButton>
<Dialog
title="Create new entry"
modal={false}
open={this.state.open}
actions={actions}
autoScrollBodyContent={true}
autoDetectWindowHeight={true}
actionsContainerClassName={s.actionsContainer}
onRequestClose={this.handleClose}
className={s.dialogWindow}
>
<div className={s.entryFormContainer}>
<TextField
hintText="Enter title for your entry"
floatingLabelText="Title"
/>
<TextField
hintText="Enter text for your entry"
floatingLabelText="Text"
multiLine={true}
rows={2}
/>
</div>
</Dialog>
</div>
);
}
}
export default withStyles(s)(NewEntry); |
frontend/react-stack/web/src/Header.js | wesleyegberto/courses-projects | import React from 'react';
function Header(props) {
return <h1>{ props.title }</h1>;
}
export default Header;
|
client/layout/guided-tours/main-tour.js | tinkertinker/wp-calypso | import React from 'react';
import { translate } from 'i18n-calypso';
import { overEvery as and } from 'lodash';
import {
makeTour,
Tour,
Step,
Next,
Quit,
Continue,
Link,
} from 'layout/guided-tours/config-elements';
import {
isNewUser,
isEnabled,
selectedSiteIsPreviewable,
selectedSiteIsCustomizable,
previewIsNotShowing,
previewIsShowing,
} from 'state/ui/guided-tours/contexts';
import Gridicon from 'components/gridicon';
export const MainTour = makeTour(
<Tour name="main" version="20160601" path="/" when={ and( isNewUser, isEnabled( 'guided-tours/main' ) ) }>
<Step name="init" placement="right" next="my-sites" className="guided-tours__step-first">
<p className="guided-tours__step-text">
{
translate( "{{strong}}Need a hand?{{/strong}} We'd love to show you around the place," +
'and give you some ideas for what to do next.',
{
components: {
strong: <strong />,
}
} )
}
</p>
<div className="guided-tours__choice-button-row">
<Next step="my-sites">{ translate( "Let's go!" ) }</Next>
<Quit>{ translate( 'No thanks.' ) }</Quit>
</div>
</Step>
<Step name="my-sites"
target="my-sites"
placement="below"
arrow="top-left"
next="sidebar"
>
<p className="guided-tours__step-text">
{
translate( "{{strong}}First things first.{{/strong}} Up here, you'll find tools for managing " +
"your site's content and design.",
{
components: {
strong: <strong />,
}
} )
}
</p>
<p className="guided-tours__actionstep-instructions">
<Continue icon="my-sites" target="my-sites" step="sidebar" click>
{
translate( 'Click the {{GridIcon/}} to continue.', {
components: {
GridIcon: <Gridicon icon="my-sites" size={ 24 } />,
}
} )
}
</Continue>
</p>
</Step>
<Step name="sidebar"
target="sidebar"
arrow="left-middle"
placement="beside"
next="click-preview"
>
<p className="guided-tours__step-text">
{ translate( 'This menu lets you navigate around, and will adapt to give you the tools you need when you need them.' ) }
</p>
<div className="guided-tours__choice-button-row">
<Next step="click-preview" />
<Quit />
</div>
</Step>
<Step name="click-preview"
className="guided-tours__step-action"
target="site-card-preview"
arrow="top-left"
placement="below"
when={ selectedSiteIsPreviewable }
scrollContainer=".sidebar__region"
next="in-preview"
>
<p className="guided-tours__step-text">
{
translate( "This shows your currently {{strong}}selected site{{/strong}}'s name and address.", {
components: {
strong: <strong />,
}
} )
}
</p>
<p className="guided-tours__actionstep-instructions">
<Continue step="in-preview" target="site-card-preview" click>
{
translate( "Click {{strong}}your site's name{{/strong}} to continue.", {
components: {
strong: <strong/>,
},
} )
}
</Continue>
</p>
</Step>
<Step name="in-preview"
placement="center"
when={ selectedSiteIsPreviewable }
next="close-preview"
>
<p className="guided-tours__step-text">
{
translate( "This is your site's {{strong}}Preview{{/strong}}. From here you can see how your site looks to others.", {
components: {
strong: <strong />,
}
} )
}
</p>
<div className="guided-tours__choice-button-row">
<Next step="close-preview" />
<Quit />
<Continue step="close-preview" when={ previewIsNotShowing } hidden />
</div>
</Step>
<Step name="close-preview"
className="guided-tours__step-action"
target="web-preview__close"
arrow="left-top"
placement="beside"
when={ and( selectedSiteIsPreviewable, previewIsShowing ) }
next="themes"
>
<p className="guided-tours__step-text">
{ translate( 'Take a look at your site — and then close the site preview. You can come back here anytime.' ) }
</p>
<p className="guided-tours__actionstep-instructions">
<Continue step="themes" target="web-preview__close" when={ previewIsNotShowing }>
{
translate( 'Click the {{GridIcon/}} to continue.', {
components: {
GridIcon: <Gridicon icon="cross-small" size={ 24 } />,
}
} )
}
</Continue>
</p>
</Step>
<Step name="themes"
target="themes"
arrow="top-left"
placement="below"
when={ selectedSiteIsCustomizable }
scrollContainer=".sidebar__region"
next="finish"
>
<p className="guided-tours__step-text">
{
translate( 'Change your {{strong}}Theme{{/strong}} to choose a new layout, or {{strong}}Customize{{/strong}} ' +
"your theme's colors, fonts, and more.",
{
components: {
strong: <strong />,
}
} )
}
</p>
<div className="guided-tours__choice-button-row">
<Next step="finish" />
<Quit />
</div>
</Step>
<Step name="finish"
placement="center"
className="guided-tours__step-finish"
>
<p className="guided-tours__step-text">
{
translate( "{{strong}}That's it!{{/strong}} Now that you know a few of the basics, feel free to wander around.", {
components: {
strong: <strong />,
}
} )
}
</p>
<div className="guided-tours__single-button-row">
<Quit primary>{ translate( "We're all done!" ) }</Quit>
</div>
<Link href="https://lean.wordpress.com">
{ translate( 'Learn more about WordPress.com' ) }
</Link>
</Step>
</Tour>
);
|
client/index.prod.js | BitTigerInst/ElasticSearch | import React from 'react';
import routes from '../shared/routes';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { configureStore } from '../shared/redux/store/configureStore';
const store = configureStore(window.__INITIAL_STATE__);
const history = browserHistory;
const dest = document.getElementById('root');
render(<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>, dest);
|
src/views/Card/CardDescription.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
SUI,
useTextAlignProp,
} from '../../lib'
/**
* A card can contain a description with one or more paragraphs.
*/
function CardDescription(props) {
const { children, className, content, textAlign } = props
const classes = cx(
useTextAlignProp(textAlign),
'description',
className,
)
const rest = getUnhandledProps(CardDescription, props)
const ElementType = getElementType(CardDescription, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
CardDescription._meta = {
name: 'CardDescription',
parent: 'Card',
type: META.TYPES.VIEW,
}
CardDescription.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,
/** A card content can adjust its text alignment. */
textAlign: PropTypes.oneOf(_.without(SUI.TEXT_ALIGNMENTS, 'justified')),
}
export default CardDescription
|
packages/es-components/src/components/patterns/callToAction/getCallToActionChildren.js | TWExchangeSolutions/es-components | import React from 'react';
export function getCallToActionChildren(children, type = 'default') {
const allChildren = React.Children.toArray(children);
const actions = allChildren
.filter(child => child.type.name === 'Action')
.map(action => {
if (type === 'light') {
const styleType = action.props.isPrimary ? 'primary' : 'darkDefault';
return React.cloneElement(action, { styleType });
}
const styleType = action.props.isPrimary ? 'primary' : 'default';
return React.cloneElement(action, { styleType });
});
const nonActions = allChildren.filter(child => child.type.name !== 'Action');
return {
actions,
nonActions
};
}
|
course/example_2/src/routes/Home/components/HomeView.js | FMCalisto/redux-get-started | import React from 'react'
import DuckImage from '../assets/Duck.jpg'
import './HomeView.scss'
export const HomeView = () => (
<div>
<h4>Welcome!</h4>
<img alt='This is a duck, because Redux!' className='duck' src={DuckImage} />
</div>
)
export default HomeView
|
app/javascript/mastodon/features/bookmarked_statuses/index.js | imas/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchBookmarkedStatuses, expandBookmarkedStatuses } from '../../actions/bookmarks';
import Column from '../ui/components/column';
import ColumnHeader from '../../components/column_header';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import StatusList from '../../components/status_list';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { debounce } from 'lodash';
const messages = defineMessages({
heading: { id: 'column.bookmarks', defaultMessage: 'Bookmarks' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'bookmarks', 'items']),
isLoading: state.getIn(['status_lists', 'bookmarks', 'isLoading'], true),
hasMore: !!state.getIn(['status_lists', 'bookmarks', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Bookmarks extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchBookmarkedStatuses());
}
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('BOOKMARKS', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandBookmarkedStatuses());
}, 300, { leading: true })
render () {
const { intl, shouldUpdateScroll, statusIds, columnId, multiColumn, hasMore, isLoading } = this.props;
const pinned = !!columnId;
const emptyMessage = <FormattedMessage id='empty_column.bookmarked_statuses' defaultMessage="You don't have any bookmarked toots yet. When you bookmark one, it will show up here." />;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.heading)}>
<ColumnHeader
icon='bookmark'
title={intl.formatMessage(messages.heading)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
/>
<StatusList
trackScroll={!pinned}
statusIds={statusIds}
scrollKey={`bookmarked_statuses-${columnId}`}
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
ext/lib/site/home-forum/component.js | DemocraciaEnRed/vicentelopez | import React from 'react'
import HomeProyectos from '../home-proyectos/component'
import HomePropuestas from '../home-propuestas/component'
const HomeForum = (props) => {
const { params: { forum } } = props
switch (forum) {
case 'propuestas':
return <HomePropuestas {...props} />
default:
return <HomeProyectos {...props} />
}
}
export default HomeForum
|
src/views/ReviewSettings/DetailBox.js | halo-design/halo-optimus | import React from 'react'
import { connect } from 'react-redux'
import { Table } from 'antd'
@connect(
state => ({
detail: state.pages.reviewSettings.strategyDetail
})
)
export default class DetailBoxView extends React.Component {
render () {
const { info, detail } = this.props
const columns = [{
title: '策略编号',
dataIndex: 'authId',
key: 'authId'
}, {
title: '策略名称',
dataIndex: 'alias',
key: 'alias'
}, {
title: '授权方式',
dataIndex: 'authType',
key: 'authType',
render: (text, record) => {
return text === '0' || text === 0 ? <span>无序</span> : <span>有序</span>
}
}, {
title: '授权定义',
children: [{
title: '一级',
dataIndex: 'add1',
key: 'add1'
}, {
title: '二级',
dataIndex: 'add2',
key: 'add2'
}, {
title: '三级',
dataIndex: 'add3',
key: 'ad3'
}, {
title: '四级',
dataIndex: 'add4',
key: 'add4'
}, {
title: '五级',
dataIndex: 'add5',
key: 'add5'
}]
}]
let dataSource = []
if (detail.alias) {
dataSource.push({
...detail,
key: 1
})
}
return (
<div className='detailBox'>
<h4 style={{ paddingBottom: '15px' }}>交易名称:{info.bsnName}</h4>
<div className='app-narrow-table'>
<Table
bordered
columns={columns}
dataSource={dataSource}
pagination={false}
/>
</div>
</div>
)
}
}
|
src/app/containers/Support.js | pingwing/travel-guide-las-palmas | import React from 'react';
import {Component} from 'react';
export default class Support extends Component {
askUltimateQuestion() {
alert('the answer is 42');
}
render() {
return (
<form onSubmit={this.askUltimateQuestion}>
<input type="text" className="support" placeholder="ask us anything" />
</form>
)
}}
|
pyxis/components/PButton/index.js | gtkatakura/furb-desenvolvimento-plataformas-moveis | import React from 'react';
import { View, Button, StyleSheet } from 'react-native';
const styles = StyleSheet.create({
button: {
marginBottom: 8,
marginLeft: 40,
marginRight: 40,
}
});
const PButton = ({ title, onPress}) => {
return (
<View style={styles.button}>
<Button title={title} onPress={onPress}></Button>
</View>
)
};
export default PButton; |
docs/src/app/components/pages/components/FloatingActionButton/ExampleSimple.js | pancho111203/material-ui | import React from 'react';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import ContentAdd from 'material-ui/svg-icons/content/add';
const style = {
marginRight: 20,
};
/**
* Default size and `mini` FABs, in primary (default), `secondary` and `disabled` colors.
*/
const FloatingActionButtonExampleSimple = () => (
<div>
<FloatingActionButton style={style}>
<ContentAdd />
</FloatingActionButton>
<FloatingActionButton mini={true} style={style}>
<ContentAdd />
</FloatingActionButton>
<FloatingActionButton secondary={true} style={style}>
<ContentAdd />
</FloatingActionButton>
<FloatingActionButton mini={true} secondary={true} style={style}>
<ContentAdd />
</FloatingActionButton>
<FloatingActionButton disabled={true} style={style}>
<ContentAdd />
</FloatingActionButton>
<FloatingActionButton mini={true} disabled={true} style={style}>
<ContentAdd />
</FloatingActionButton>
</div>
);
export default FloatingActionButtonExampleSimple;
|
src/client/components/hoc/Permissions/withPermissions.hoc.js | DBCDK/content-first | import React from 'react';
import {useDispatch, useSelector} from 'react-redux';
import {get} from 'lodash';
import Kiosk from '../../base/Kiosk/Kiosk';
import {loadKiosk} from '../../../redux/kiosk.thunk';
import {OPEN_MODAL, CLOSE_MODAL} from '../../../redux/modal.reducer';
import permissions from './permissions.json';
import T from '../../base/T';
import Button from '../../base/Button';
function getUserRoles(roles) {
return roles.map(role => role.machineName);
}
const defaultPremiumContext = {
title: 'Du har desværre ikke adgang',
reason: 'Indholdet er ikke tilgængeligt for dit bibliotek'
};
const defaultLoginContext = {
title: 'Login',
reason:
'Log ind for at finde ud af, om dit bibliotek abonnerer på Læsekompas.dk – og dermed giver mulighed for at bestille bøger til biblioteket.'
};
/**
Permissions.hoc usage example:
export default withPermissions(YourComponent, Options);
Options parameters
@param {string} name {required}
@param {obj} context premium + login modal context (same context for both)
@param {obj} modals individual modal context settings
Options example:
{
name: 'YourComponentName',
-- set context like this --
context: {
title: 'all prompted modals will have this title',
reason: 'all prompted modals will have this description'
},
-- or this --
modals: {
login: {
context: {title: 'only login modal will have this title', reason: '...'}
},
premium: {
context: {title: '...', reason: '....'}
}
}
}
Set permissions for your component in the /permissions.json file
Permissions object in permissions.json example:
"YourComponentName": {
"free": false,
"premium": true,
"kiosk": false,
"role": {
"contentFirstAdmin": false,
"contentFirstEditor": false
}
}
**/
export default (WrappedComponent, ComponentOptions) => props => {
/* Get the name of the wrapped component, this name is used to
get the component options from the permissions.json object. */
const name = get(ComponentOptions, 'name', false) || props.name;
/* If user is denied acces to a premium functionality,
they will be prompted with a modal. content of the
modal is given by the premium context */
const premiumContext =
get(ComponentOptions, 'context', false) ||
get(ComponentOptions, 'modals.premium.context', false) ||
get(props, 'premium.context', false);
/* If user is denied acces to a logged-in-user functionality,
they will be prompted with a modal. content of the
modal is given by the login context */
const loginContext =
get(ComponentOptions, 'context', false) ||
get(ComponentOptions, 'modals.login.context', false) ||
get(props, 'login.context', false);
const dispatch = useDispatch();
// Kiosk
const kioskState = useSelector(state => get(state, 'kiosk', false));
// Premium
const isPremium = useSelector(state =>
get(state, 'userReducer.isPremium', false)
);
const isLoggedIn = useSelector(state =>
get(state, 'userReducer.isLoggedIn', false)
);
// Roles
const roles = useSelector(state => get(state, 'userReducer.roles', []));
const isAdmin = getUserRoles(roles).includes('contentFirstAdmin');
const isEditor = getUserRoles(roles).includes('contentFirstEditor');
// Get component Permissions
const p = permissions[name];
// If no name or settings is found for the wrapped component
if (!p) {
return <WrappedComponent {...props} />;
}
// If Kioskmode is enabled and allowed - return component without further checks.
if (kioskState.enabled) {
// const agency = get(kiosk, 'configuration.agencyId', false);
// const branch = get(kiosk, 'configuration.branch', false);
// Get kiosk configuration if not loaded
if (!kioskState.loaded) {
dispatch(loadKiosk({}));
}
// Return
if (p.kiosk) {
// if (p.kiosk && agency && branch) {
// return <WrappedComponent {...props} />;
return (
<Kiosk
render={({kiosk}) => <WrappedComponent kiosk={kiosk} {...props} />}
/>
);
}
}
// If permission is allowed on a free plan.
if (p.free) {
return <WrappedComponent {...props} />;
}
// Checks, which is only available if user is logged in
if (isLoggedIn) {
// If user has a paying library (Premium access)
if (p.premium && isPremium) {
return <WrappedComponent {...props} />;
}
// if user has a editor role
if (p.role.contentFirstEditor && isEditor) {
return <WrappedComponent {...props} />;
}
// if user has an admin role
if (p.role.contentFirstAdmin && isAdmin) {
return <WrappedComponent {...props} />;
}
// If component has premium options set
if (premiumContext) {
// Promt the user with a premium-only order book modal
if (ComponentOptions.name === 'OrderButton') {
return (
<WrappedComponent
{...props}
onClick={e => {
e.preventDefault();
e.stopPropagation();
dispatch({
type: OPEN_MODAL,
modal: 'confirm',
context: {
...defaultPremiumContext,
...premiumContext,
className: 'premium-modal',
hideCancel: true,
hideConfirm: false,
onConfirm: () => {
dispatch({
type: CLOSE_MODAL,
modal: 'confirm'
});
},
reason: (
<React.Fragment>
<p>{premiumContext.reason}</p>
<Button
type="link"
size="medium"
href="https://bibliotek.dk/"
style={{paddingLeft: '0'}}
>
<T component="order" name="findOnBibliotekDK" />
</Button>
<p style={{marginTop: '1rem'}}>
<T component="order" name="orderButtonModalText" />
</p>
</React.Fragment>
)
}
});
}}
/>
);
}
// Promt the user with a premium-only modal (for non-order buttons)
return (
<WrappedComponent
{...props}
onClick={e => {
e.preventDefault();
e.stopPropagation();
dispatch({
hideCancel: true,
hideConfirm: true,
type: OPEN_MODAL,
modal: 'confirm',
context: {
...defaultPremiumContext,
...premiumContext,
className: 'premium-modal'
}
});
}}
/>
);
}
}
if (!isLoggedIn && p.premium) {
return (
<WrappedComponent
{...props}
onClick={e => {
e.preventDefault();
e.stopPropagation();
dispatch({
type: OPEN_MODAL,
modal: 'login',
context: {
...defaultLoginContext,
...loginContext
}
});
}}
/>
);
}
return null;
};
|
src/main/app/components/system/host/Host.js | reactor/reactor-pylon | /*
* Copyright (c) 2011-2016 Pivotal Software Inc, All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Nvd3 from './../../core/chart/Nvd3';
import { Link } from 'react-router'
class Host extends React.Component {
constructor(props) {
super(props);
}
render() {
var name = <div className="host-label">
<Link to={`/pylon/system/host/${this.props.host.id}`}>
{this.props.host.name}: <strong>{this.props.host.ip}</strong>
</Link>
</div>;
var info = <ul>
<li>OS: <strong>Debian OS</strong></li>
<li>Version: <strong>12.1</strong></li>
<li>Status: <strong>pending</strong></li>
<li>Memory: <strong>2Go / 20Go</strong></li>
<li>CPU: <strong>Intel Core 4Q</strong></li>
</ul>;
var result = null;
if (this.props.mode == 0) {
result = (
<div className="host">
<div className="host-container">
{name}
<div className="row host-general">
<div className="gr-4">
<div className="donut-chart">
{
React.createElement(Nvd3, {
id: "toto2",
type:'pieChart',
datum: this.getDummy2(),
showLegend: false,
showLabels: false,
margin: {top:0,left:10,right:0,bottom:0},
duration: 1,
x:"key",
y:"y",
donut: true,
donutRatio: 0.6
})
}
<div className="label">CPU usage</div>
<div className="percent">80%</div>
</div>
</div>
<div className="gr-8">
<div className="host-infos">
<img src="/assets/images/host/linux.png" width="60px" />
{info}
</div>
</div>
</div>
<div>
{
React.createElement(Nvd3, {
type:'lineChart',
id: "toto1",
datum: this.getDummy(),
margin: {left: 20, bottom: 20, right: 10, top:0},
useInteractiveGuideline: true,
showYAxis: true,
showXAxis: true,
forceY: [0,100],
duration: 1
})
}
</div>
</div>
</div>
)
} else {
result = <div className="host-small">
<div className="left">
{name}
{info}
</div>
<div className="right">
<div className="progress"><div style={{width:'40%'}} className="value green"></div></div>
<div className="progress"><div style={{width:'66%'}} className="value blue"></div></div>
<div className="progress"><div style={{width:'32%'}} className="value red"></div></div>
</div>
</div>
}
return result
}
getDummy() {
var c1 = [],c2 = [], c3 = [];
for (var i = 0; i < 60; i++) {
c1.push({x: i, y: Math.round(Math.random() * 0.9 * 100)});
c2.push({x: i, y: Math.round(Math.random() * 0.5 * 100)});
c3.push({x: i, y: Math.round(Math.random() * 0.2 * 100)});
}
return [
{ values: c1, key: 'CPU', color: '#60b124' },
{ values: c2, key: 'Memory', color: '#40a7ff' },
{ values: c3, key: 'In flight', color: '#ff5240' }
];
}
getDummy2() {
return [
{key: "One", y: 80, color: "#60b124"},
{key: "Two", y: 20, color: "#e5e5e5"},
];
}
}
export default Host;
|
frontend/app_v2/src/components/DictionaryDetail/DictionaryDetailPresentation.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router-dom'
import { Disclosure } from '@headlessui/react'
// FPCC
import { getMediaUrl } from 'common/urlHelpers'
import useIcon from 'common/useIcon'
import useVisibilityIcon from 'common/useVisibilityIcon'
import { makePlural } from 'common/urlHelpers'
import AudioMinimal from 'components/AudioMinimal'
import ActionsMenu from 'components/ActionsMenu'
import ImageWithLightbox from 'components/ImageWithLightbox'
import SanitizedHtml from 'components/SanitizedHtml'
function DictionaryDetailPresentation({ actions, moreActions, entry, sitename }) {
const lableStyling = 'text-left font-medium text-lg uppercase text-fv-charcoal'
const contentStyling = 'text-fv-charcoal sm:mt-0 sm:ml-6 sm:col-span-2'
const noMedia = entry?.pictures?.length > 0 || entry?.videos?.length > 0 ? false : true
const shortTitle = entry?.title.length < 20
return (
<div
className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 mt-4 md:mt-10 bg-white"
data-testid="DictionaryDetailPresentation"
>
<div className="grid grid-cols-8 gap-4">
<div id="WordDetails" className={`col-span-8 md:col-span-5 ${noMedia ? 'md:col-start-3' : ''}`}>
<section className="lg:mb-3">
<div className="py-2 md:p-3 md:flex items-top">
<span className={`font-bold ${shortTitle ? 'text-2xl md:text-5xl' : 'text-xl md:text-2xl'}`}>
{entry.title}
</span>
<div className="mt-4 md:mt-1 md:ml-4">
<ActionsMenu.Presentation
docId={entry.id}
docTitle={entry.title}
docType={entry.type}
docVisibility={entry?.visibility}
actions={actions}
moreActions={moreActions}
iconStyling={'w-6 h-6'}
withLabels
withConfirmation
/>
</div>
{entry?.visibility === 'public' || !entry?.visibility ? (
''
) : (
<div className="mt-4 md:mt-1 md:ml-4 flex items-top text-secondary-dark">
{useVisibilityIcon(entry?.visibility, 'fill-current inline-flex h-6 w-6 mr-2')}
</div>
)}
</div>
{/* Translations/Definitions */}
{entry?.translations?.length > 0 && (
<div className="py-2 md:p-3">
<ol
className={`${entry?.translations?.length === 1 ? 'list-none' : 'list-decimal'} list-inside text-lg ${
shortTitle ? 'md:text-2xl' : 'md:text-xl'
}`}
>
{entry?.translations?.map((translation, index) => (
<li key={index} className="p-0.5">
{translation.translation}
</li>
))}
</ol>
</div>
)}
{/* Audio */}
{entry?.audio?.length > 0 && (
<div className="py-2 md:p-3">
{entry?.audio?.map((audioFile, index) => (
<AudioMinimal.Container
key={`${audioFile.uid}_${index}`}
icons={{
Play: useIcon('Audio', `fill-current h-6 w-6 ${audioFile?.speaker?.length > 0 ? 'mr-2' : ''}`),
Stop: useIcon('Stop', `fill-current h-6 w-6 ${audioFile?.speaker?.length > 0 ? 'mr-2' : ''}`),
}}
buttonStyling="bg-secondary hover:bg-secondary-dark text-white text-sm rounded-lg inline-flex items-center py-1.5 px-2 mr-2"
label={audioFile?.speaker}
src={getMediaUrl({ type: 'audio', id: audioFile.uid })}
/>
))}
</div>
)}
</section>
<section>
{/* Categories */}
{entry?.categories?.length > 0 && (
<div className="py-2 md:p-4">
<h4 className={lableStyling}>Categories</h4>
{entry?.categories?.map((category) => (
<Link
key={category.uid}
to={`/${sitename}/categories/${category.uid}`}
className="p-1.5 inline-flex text-sm font-medium rounded-lg bg-tertiaryB hover:bg-tertiaryB-dark text-white mr-1 mb-1"
>
{category['dc:title']}
<span className="sr-only">, </span>
</Link>
))}
</div>
)}
{/* Related Content */}
{entry?.relatedAssets?.length > 0 && (
<div className="py-2 md:p-4">
<table className="w-full">
<thead>
<tr>
<th colSpan="2" className={`${lableStyling}pb-2`}>
Related Content
</th>
</tr>
<tr>
<th className="hidden">Title</th>
<th className="hidden">Definitions</th>
</tr>
</thead>
<tbody className="py-2 px-10">
{/* Related Content */}
{entry?.relatedAssets?.map((asset, index) => {
const zebraStripe = index % 2 === 1 ? '' : 'bg-gray-100'
return (
<tr key={index} className={zebraStripe}>
<td className="p-2 flex items-center">
<Link to={`/${sitename}/${makePlural(asset?.type)}/${asset.uid}`}>{asset['dc:title']}</Link>
{asset?.related_audio?.map((audioId, i) => (
<AudioMinimal.Container
key={`${audioId}_${i}`}
icons={{
Play: useIcon('Audio', 'fill-current h-8 w-8 ml-2'),
Stop: useIcon('StopCircle', 'fill-current h-8 w-8 ml-2'),
}}
src={getMediaUrl({ type: 'audio', id: audioId })}
/>
))}
</td>
<td className="p-2">
<span>{asset?.['fv:definitions']?.[0]?.translation}</span>
</td>
</tr>
)
})}
</tbody>
</table>
</div>
)}
</section>
{/* Other Information */}
<section>
{(entry?.acknowledgement || entry?.reference || entry?.sources?.length > 0) && (
<div className="py-2 md:p-4">
<h4 className={lableStyling}>Acknowledgement</h4>
<ul className="list-none md:list-disc space-y-1">
{entry?.acknowledgement && <li className={contentStyling}>{entry?.acknowledgement}</li>}
{entry?.reference && <li className={contentStyling}>Reference: {entry?.reference}</li>}
{entry?.sources?.length > 0 &&
entry?.sources?.map((source) => (
<li key={source.uid} className={contentStyling}>
Source: {source?.['dc:title']}
</li>
))}
</ul>
</div>
)}
{entry?.culturalNotes?.length > 0 || entry?.generalNote || entry?.literalTranslations?.length > 0 ? (
<div className="py-2 md:p-4">
<h4 className={lableStyling}>Notes</h4>
<ul className="list-none md:list-disc space-y-1">
{entry?.culturalNotes?.map((note, i) => (
<li key={i} className={contentStyling}>
Cultural note: {note}
</li>
))}
{entry?.generalNote && (
<SanitizedHtml className={contentStyling} tagName="li" text={entry?.generalNote} />
)}
{/* Literal Translations - WORD ONLY */}
{entry?.literalTranslations?.map((translation, index) => (
<li key={index} className={contentStyling}>
Literal translation: {translation.translation}
</li>
))}
</ul>
</div>
) : null}
{entry?.partOfSpeech && (
<div className="py-2 md:p-4">
<h4 className={lableStyling}>Part of Speech</h4>
<div className={contentStyling}>{entry?.partOfSpeech}</div>
</div>
)}
{entry?.pronunciation && (
<div className="py-2 md:p-4">
<h4 className={lableStyling}>Pronunciation</h4>
<div className={contentStyling}>{entry?.pronunciation}</div>
</div>
)}
</section>
</div>
{/* Pictures and Video */}
{noMedia ? null : (
<div id="WordMedia" className="col-span-8 md:col-span-3 py-2 md:p-5 md:mt-5">
<ul>
{entry?.pictures
? entry?.pictures?.map((picture, index) => (
<li key={`${picture.uid}_${index}`} className="my-2">
<div className="inline-flex rounded-lg overflow-hidden relative ">
<div className="relative">
<div className="inline-flex rounded-lg overflow-hidden">
<ImageWithLightbox.Presentation maxWidth={1000} image={picture} />
</div>
</div>
</div>
</li>
))
: null}
{entry?.videos
? entry?.videos?.map((video, index) => (
<li key={`${video.uid}_${index}`} className="my-2">
<Disclosure>
<Disclosure.Button>
<div className="inline-flex rounded-lg overflow-hidden">
<video
className="shrink-0 w-full h-auto"
src={getMediaUrl({ type: 'video', id: video.uid, viewName: 'Small' })}
controls
>
Your browser does not support the video tag.
</video>
</div>
</Disclosure.Button>
<Disclosure.Panel>
<div className="text-fv-charcoal">
{video?.['dc:title']} - {video?.['dc:description']}
</div>
<div className="text-fv-charcoal">
<span className="font-medium">Acknowledgement:</span> {video?.speaker}
</div>
</Disclosure.Panel>
</Disclosure>
</li>
))
: null}
</ul>
</div>
)}
</div>
</div>
)
}
// PROPTYPES
const { array, object, string } = PropTypes
DictionaryDetailPresentation.propTypes = {
actions: array,
entry: object,
moreActions: array,
sitename: string,
}
export default DictionaryDetailPresentation
|
lib/src/detailcard.js | SerendpityZOEY/Fixr-RelevantCodeSearch | /**
* Created by yue on 2/9/17.
*/
import React from 'react';
import {List, ListItem, NestedList} from 'material-ui/List';
import {BarChart, Bar, XAxis, YAxis, CartesianGrid, Tooltip, Legend} from 'recharts';
import FlatButton from 'material-ui/FlatButton';
import FontIcon from 'material-ui/FontIcon';
import Lines from './linesofcode.js';
const styles = {
headline: {
fontSize: 14,
},
item1: {
fontSize:14,
fontWeight: 800,
},
customWidth: {
paddingLeft: 9,
},
codeSnippet:{
fontFamily:"Fira Mono",
fontSize:14
},
methodSnippet:{
fontFamily:"Fira Mono",
fontSize:14,
backgroundColor:'#f5f5f5',
paddingLeft: 50,
paddingRight: 50
},
buttonStyle:{
fontSize:12,
fontWeight:450,
paddingLeft:5,
paddingBottom:10
}
};
class DetailCard extends React.Component{
parseData(commit,field,token) {
var rest = commit[field].toString().split(token);
var restCommits=rest[0];
for(var i=1;i<rest.length;i++){
//TODO: parent imports contains the added/removed line
restCommits += rest[i]+'\n';
}
return restCommits;
}
render(){
var commit = this.props.commit;
var importEntered = this.props.importEntered; //input imposts
var callsiteEntered = this.props.methodEntered; //input callsites
var fileName=commit.name_sni;
var browseFile = 'https://github.com/'+commit.repo_sni+'/issues/';
var method = [];
var add = 0;
var remove = 0;
commit.c_patch_t[0].split("\n").forEach( function (line, index) {
if (line.length > 0) {
//patch.push(line.substring(1))
}
if (line.match(/^\+/)) {
add++;
}
if (line.match(/^\-/)) {
remove++;
}
});
//parse whole content
if(callsiteEntered!=''){
commit.c_patch_t[0].split("\n").forEach( function (line, index){
if(line.length>0){
for(var item=0;item<callsiteEntered.length;item++){
//avoid method name in comment being highlighted
var customizeMethod = '.'+callsiteEntered[item]+'(';
if(line.includes(customizeMethod)){
for(var i=index-4;i<index+4;i++){
if(i==index){
method.push(highlightWord(line,callsiteEntered[item]))
}else{
method.push(commit.c_patch_t[0].split("\n")[i])
}
}
method.push('=================================');
}
}
}
})
method = method.join('\n')
}else{
method = "Please specify a method first!"
}
function highlightWord(line, word){
//console.log('word',line.substring(line.indexOf(word), line.indexOf(word)+word.length))
line = line.substring(0,line.indexOf(word))+'<mark>'+line.substring(line.indexOf(word), line.indexOf(word)+word.length)+'</mark>'+
line.substring(line.indexOf(word)+word.length)
//console.log('new line', line)
return line
}
var temp = <Lines diffcontent={commit.c_patch_t[0]} content={commit.c_contents_t[0]}
callsiteEntered={callsiteEntered} importEntered={importEntered}
onAddBtnClick={this.props.onAddBtnClick.bind(this)}
newCode={this.props.newCode}
/>
return(<div>
<ListItem
primaryText={'File Name:'+fileName}
rightIconButton={
<FlatButton
label="See Issues"
href={browseFile}
target="_blank"
default={true}
icon={<FontIcon className="fa fa-github fa-lg" />}
/>
}
style={styles.item1}
/>
<ListItem
primaryText={["Expand to view where method gets called",
]}
nestedItems={[
<pre style={{marginTop:0,marginBottom:0}}><code dangerouslySetInnerHTML={{__html: method}}></code></pre>
]}
nestedListStyle={styles.methodSnippet}
style={styles.headline}
/>
{temp}
</div>)
}
}
export default DetailCard; |
packages/veritone-react-common/src/components/NavigationSideBar/SectionTree.js | veritone/veritone-sdk | import React from 'react';
import cx from 'classnames';
import { noop, initial, get, map, kebabCase } from 'lodash';
import {
string,
arrayOf,
shape,
func,
element,
bool,
objectOf,
any
} from 'prop-types';
import Button from '@material-ui/core/Button';
import ArrowBackIcon from '@material-ui/icons/ArrowBack';
import ChevronRightIcon from '@material-ui/icons/ChevronRight';
import { makeStyles } from '@material-ui/styles';
import { intersperse } from 'helpers/fp';
import styles from './styles/sectiontree';
const nodeShape = {
label: string,
icon: element,
iconClassName: string
};
nodeShape.children = objectOf(shape(nodeShape));
export const sectionsShape = shape(nodeShape);
const useStyles = makeStyles(styles);
export default function SectionTree({
sections,
activePath,
onNavigate,
selectedItemClasses,
classes
}) {
const muiClasses = useStyles();
const getDeepestMatchedPath = () => {
// find the deepest section we can match in the tree by dropping pieces
// from the activePath until we find one that works.
// this can probably be done more cleanly.
return activePath.reduce(
result => {
const tryPath = intersperse(result, 'children');
const maybeSection = get(sections.children, tryPath);
return maybeSection ? result : initial(result);
},
[...activePath]
);
};
const getNavigationRelativePath = () => {
const deepestMatchingPath = getDeepestMatchedPath();
const showingPartialPath = deepestMatchingPath !== activePath;
return showingPartialPath ? deepestMatchingPath : activePath;
};
const handleNavigateForward = (path) => {
onNavigate([...getNavigationRelativePath(), path]);
};
const handleNavigateBack = () => {
onNavigate(initial(getNavigationRelativePath()));
};
const handleNavigateSibling = (path) => {
onNavigate([...initial(getNavigationRelativePath()), path]);
};
const deepestMatchedPath = getDeepestMatchedPath();
const deepestMatchedPathParent = initial(deepestMatchedPath);
const currentVisibleSection =
activePath.length === 0
? sections // root visible by default
: get(
sections.children, // skip root when navigating
intersperse(deepestMatchedPath, 'children')
);
const currentVisibleSectionParent = get(
sections.children,
intersperse(deepestMatchedPathParent, 'children'),
sections
);
const parentIsRoot = currentVisibleSectionParent === sections;
const selectedItemHasChildren = !!currentVisibleSection.children;
const rootItemSelected = parentIsRoot && !selectedItemHasChildren;
return (
<div className={muiClasses.tabsContainer}>
{!rootItemSelected &&
activePath.length > 0 && (
<SectionTreeTab
selectedClasses={selectedItemClasses}
classes={classes}
selected
label={currentVisibleSection.label}
leftIcon={<ArrowBackIcon />}
// eslint-disable-next-line react/jsx-no-bind
onClick={handleNavigateBack}
data-testtarget="back-button"
btnActionTrackName={currentVisibleSection.btnActionTrackName}
/>
)}
{map(
// render the parent (w/ current section highlighted + its siblings)
// when we're at a leaf path
currentVisibleSection.children
? currentVisibleSection.children
: currentVisibleSectionParent.children,
({ label, formComponentId, children, icon, iconClassName, btnActionTrackName }, path) => (
<SectionTreeTab
selectedClasses={selectedItemClasses}
classes={classes}
selected={label === currentVisibleSection.label}
label={label}
leftIcon={
iconClassName ? <span className={iconClassName} /> : icon
}
rightIcon={
children && Object.keys(children).length && <ChevronRightIcon />
}
key={`${label}-${path}`}
id={path}
onClick={
currentVisibleSection.children
? handleNavigateForward
: handleNavigateSibling
}
btnActionTrackName={btnActionTrackName}
/>
)
)}
</div>
);
};
SectionTree.propTypes = {
sections: sectionsShape.isRequired,
activePath: arrayOf(string).isRequired,
onNavigate: func.isRequired,
selectedItemClasses: shape({
leftIcon: string
}),
classes: shape({
leftIcon: string
})
};
export const SectionTreeTab = ({
label = '',
id,
leftIcon,
rightIcon,
selected,
selectedClasses = {},
classes = {},
onClick = noop,
btnActionTrackName
}) => {
const muiClasses = useStyles();
return (
/* eslint-disable react/jsx-no-bind */
<Button
classes={{
root: cx(muiClasses.sectionTreeTab, { [muiClasses.selected]: selected }),
label: muiClasses.muiButtonLabelOverride
}}
onClick={() => onClick(id)}
data-veritone-element={btnActionTrackName || `sidebar-${kebabCase(label.toLowerCase())}-button`}
>
<span
className={cx(muiClasses.leftIcon, classes.leftIcon, {
[selectedClasses.leftIcon]: selected
})}
>
{leftIcon}
</span>
<span className={muiClasses.label}>{label}</span>
<span className={muiClasses.rightIcon}>{rightIcon}</span>
</Button>
)};
SectionTreeTab.propTypes = {
label: string,
id: string,
leftIcon: element,
rightIcon: element,
selected: bool,
onClick: func,
classes: objectOf(any),
selectedClasses: objectOf(any),
btnActionTrackName: string
};
|
src/common/components/Heading.js | chad099/react-native-boilerplate | // @flow
import type { TextProps } from './Text';
import type { Theme } from '../themes/types';
import Text from './Text';
import React from 'react';
type HeadingContext = {
theme: Theme,
};
const Heading = (props: TextProps, { theme }: HeadingContext) => {
const {
bold = true,
fontFamily = theme.heading.fontFamily,
marginBottom = theme.heading.marginBottom,
...restProps
} = props;
return (
<Text
bold={bold}
fontFamily={fontFamily}
marginBottom={marginBottom}
{...restProps}
/>
);
};
Heading.contextTypes = {
theme: React.PropTypes.object,
};
export default Heading;
|
sb-admin-seed-react/src/vendor/recharts/demo/component/AreaChart.js | Gigasz/tropical-bears | import React from 'react';
import { changeNumberOfData } from './utils';
import { AreaChart, Area, XAxis, YAxis, Tooltip, CartesianGrid, Brush,
ReferenceArea, ReferenceLine, ReferenceDot, ResponsiveContainer } from 'recharts';
const data = [
{ name: 'Page A', uv: 4000, pv: 2400, amt: 2400 },
{ name: 'Page B', uv: 3000, pv: 1398, amt: 2210 },
{ name: 'Page C', uv: 2000, pv: 9800, amt: 2290 },
{ name: 'Page D', uv: 2780, pv: 3908, amt: 2000 },
{ name: 'Page E', uv: 2500, pv: 4800, amt: 2181 },
{ name: 'Page F', uv: 1220, pv: 3800, amt: 2500 },
{ name: 'Page G', uv: 2300, pv: 4300, amt: 2100 },
];
const data01 = [
{ day: '05-01', weather: 'sunny' },
{ day: '05-02', weather: 'sunny' },
{ day: '05-03', weather: 'cloudy' },
{ day: '05-04', weather: 'rain' },
{ day: '05-05', weather: 'rain' },
{ day: '05-06', weather: 'cloudy' },
{ day: '05-07', weather: 'cloudy' },
{ day: '05-08', weather: 'sunny' },
{ day: '05-09', weather: 'sunny' },
];
const data02 = [
{ name: 'Page A', uv: 4000, pv: 2400, amt: 2400 },
{ name: 'Page B', uv: 3000, pv: 1398, amt: 2210 },
{ name: 'Page C', uv: 2000, pv: 9800, amt: 2290 },
{ name: 'Page D', uv: 2780, pv: 3908, amt: 2000 },
{ name: 'Page E', uv: 1890, pv: 4800, amt: 2181 },
];
const initilaState = { data, data01, data02 };
const CustomTooltip = React.createClass({
render() {
const { active, payload, external, label } = this.props;
if (active) {
const style = {
padding: 6,
backgroundColor: '#fff',
border: '1px solid #ccc',
};
const currData = external.filter(entry => (entry.name === label))[0];
return (
<div className="area-chart-tooltip" style={style}>
<p>{payload[0].name + ' : '}<em>{payload[0].value}</em></p>
<p>{'uv : '}<em>{currData.uv}</em></p>
</div>
);
}
return null;
},
});
const renderCustomizedActiveDot = (props) => {
const { cx, cy, stroke, index, dataKey } = props;
return <path d={`M${cx - 2},${cy - 2}h4v4h-4Z`} fill={stroke} key={`dot-${dataKey}`}/>;
};
const renderLabel = (props) => {
const { x, y, textAnchor, value, index } = props;
return <text x={x} y={y} dy={-10} textAnchor={textAnchor} key={`label-${index}`}>{value[1]}</text>
};
const RenderRect = (props) => {
return <rect x={20} y={20} width={100} height={20} stroke="#000"/>;
};
function CustomizedAxisTick(props) {
const { x, y, stroke, payload } = props;
return (
<g transform={`translate(${x},${y})`}>
<text x={0} y={0} dy={-12} textAnchor="end" fill="#999" fontSize="12">{payload.value}</text>
</g>
);
}
export default React.createClass({
displayName: 'AreaChartDemo',
getInitialState() {
return initilaState;
},
handleChangeData() {
this.setState(() => _.mapValues(initilaState, changeNumberOfData));
},
render() {
const { data, data01, data02 } = this.state;
return (
<div className="area-charts">
<a
href="javascript: void(0);"
className="btn update"
onClick={this.handleChangeData}
>
change data
</a>
<br/>
<p>Stacked AreaChart</p>
<div className="area-chart-wrapper">
<AreaChart width={800} height={400} data={this.state.data}
margin={{ top: 20, right: 80, left: 20, bottom: 5 }}
syncId="test"
>
<XAxis dataKey="name" label="province"/>
<YAxis />
<Tooltip />
<Area
stackId="0"
type="monotone"
dataKey="uv"
stroke="#ff7300"
fill="#ff7300"
dot
activeDot={renderCustomizedActiveDot}
/>
<Area
stackId="0"
type="monotone"
dataKey="amt"
stroke="#82ca9d"
fill="#82ca9d"
dot
activeDot={renderCustomizedActiveDot}
/>
<Area
stackId="0"
type="monotone"
dataKey="pv"
stroke="#387908"
fill="#387908"
animationBegin={1300}
label={renderLabel}
dot
activeDot={renderCustomizedActiveDot}
/>
</AreaChart>
</div>
<p>Stacked AreaChart | Stack Offset Expand</p>
<div className="area-chart-wrapper">
<AreaChart width={400} height={300} data={this.state.data}
margin={{ top: 20, right: 80, left: 20, bottom: 5 }}
stackOffset="expand"
syncId="test"
>
<XAxis />
<YAxis />
<Tooltip />
<Area stackId="0"
type="monotone"
dataKey="uv"
stroke="#ff7300"
fill="#ff7300"
dot
activeDot={renderCustomizedActiveDot}
/>
<Area stackId="0"
type="monotone"
dataKey="pv"
stroke="#387908"
fill="#387908"
animationBegin={1300}
label={renderLabel}
dot
activeDot={renderCustomizedActiveDot}
/>
</AreaChart>
</div>
<p>Stacked AreaChart | Stack Offset Silhouette</p>
<div className="area-chart-wrapper">
<AreaChart width={800} height={400} data={this.state.data}
margin={{ top: 20, right: 80, left: 20, bottom: 5 }}
stackOffset="silhouette"
>
<XAxis dataKey="name" label="province" />
<YAxis />
<Tooltip />
<Area stackId="0"
type="monotone"
dataKey="uv"
stroke="#ff7300"
fill="#ff7300"
dot
activeDot={renderCustomizedActiveDot}
/>
<Area stackId="0"
type="monotone"
dataKey="pv"
stroke="#387908"
fill="#387908"
animationBegin={1300}
label={renderLabel}
dot
activeDot={renderCustomizedActiveDot}
/>
</AreaChart>
</div>
<p>Tiny AreaChart</p>
<div className="area-chart-wrapper">
<AreaChart width={100}
height={50}
data={data.slice(0, 1)}
margin={{ top: 5, right: 0, left: 0, bottom: 5 }}
>
<Area type="monotone" dataKey="uv" stroke="#ff7300" fill="#ff7300" />
</AreaChart>
</div>
<p>AreaChart with three y-axes</p>
<div className="area-chart-wrapper">
<AreaChart width={600}
height={400}
data={data}
margin={{ top: 20, right: 30, left: 20, bottom: 5 }}
>
<YAxis label="uv" type="number" yAxisId={0} stroke="#ff7300" />
<YAxis label="pv" type="number" orientation="right" yAxisId={1} stroke="#387908" />
<YAxis label="amt"
type="number"
orientation="right"
yAxisId={2}
stroke="#38abc8"
/>
<XAxis dataKey="name" interval={0}/>
<Area dataKey="uv" stroke="#ff7300" fill="#ff7300" strokeWidth={2} yAxisId={0} />
<Area dataKey="pv" stroke="#387908" fill="#387908" strokeWidth={2} yAxisId={1} />
<Area dataKey="amt" stroke="#38abc8" fill="#38abc8" strokeWidth={2} yAxisId={2} />
</AreaChart>
</div>
<p>AreaChart of vertical layout </p>
<div className="area-chart-wrapper" style={{ margin: 40 }}>
<AreaChart width={400} height={400} data={data} layout="vertical"
margin={{ top: 5, right: 30, bottom: 5, left: 5 }}
>
<YAxis type="category" dataKey="name" />
<XAxis type="number" xAxisId={0} orientation="top" />
<XAxis type="number" xAxisId={1} orientation="bottom" />
<Area dataKey="uv"
type="monotone"
stroke="#ff7300"
fill="#ff7300"
strokeWidth={2}
xAxisId={0}
/>
<Area dataKey="pv"
type="monotone"
stroke="#387908"
fill="#387908"
strokeWidth={2}
xAxisId={1}
/>
<Tooltip />
</AreaChart>
</div>
<p>AreaChart with custom tooltip</p>
<div className="area-chart-wrapper">
<AreaChart width={900}
height={250}
data={data}
margin={{ top: 10, right: 30, bottom: 10, left: 10 }}
>
<XAxis dataKey="name" hasTick />
<YAxis tickCount={7} hasTick />
<Tooltip content={<CustomTooltip external={data} />} />
<CartesianGrid stroke="#f5f5f5" />
<ReferenceArea x1="Page A" x2="Page E" />
<ReferenceLine y={7500} stroke="#387908"/>
<ReferenceDot x="Page C" y={1398} r={10} fill="#387908" isFront/>
<Area type="monotone"
dataKey="pv"
stroke="#ff7300"
fill="#ff7300"
fillOpacity={0.9}
/>
</AreaChart>
</div>
<p>AreaChart filled with linear gradient</p>
<div>
<AreaChart width={800} height={400} data={this.state.data}
margin={{ top: 20, right: 80, left: 20, bottom: 5 }}
>
<defs>
<linearGradient id="MyGradient" x1="0" y1="0" x2="0" y2="1">
<stop offset="5%" stopColor="rgba(0, 136, 254, 0.8)" />
<stop offset="95%" stopColor="rgba(0, 136, 254, 0)" />
</linearGradient>
</defs>
<XAxis dataKey="name" label="province" />
<YAxis />
<Tooltip />
<Area
type="monotone"
dataKey="uv"
stroke="#0088FE"
strokeWidth="2"
fillOpacity="1"
fill="url(#MyGradient)"
dot
/>
</AreaChart>
</div>
<p>AreaChart of discrete values</p>
<div className="area-chart-wrapper">
<AreaChart
width={400} height={400} data={data01}
margin={{ top: 20, right: 20, bottom: 20, left: 20 }}>
<XAxis dataKey="day" />
<YAxis type="category" />
<Tooltip />
<Area type="stepAfter" dataKey="weather" stroke="#0088FE" />
</AreaChart>
</div>
</div>
);
},
});
|
src/components/icons/OutlinedFlagIcon.js | InsideSalesOfficial/insidesales-components | import React from 'react';
const OutlinedFlagIcon = props => (
<svg {...props.size || { width: '24px', height: '24px' }} {...props} viewBox="0 0 24 24">
{props.title && <title>{props.title}</title>}
<path d="M14 6l-1-2H5v17h2v-7h5l1 2h7V6h-6zm4 8h-4l-1-2H7V6h5l1 2h5v6z" />
<path fill="none" d="M0 0h24v24H0z" />
</svg>
);
export default OutlinedFlagIcon;
|
examples/withReactRouterReduxIntl/client/containers/index.js | Canner/coren | import React from 'react';
import ReactDOM from 'react-dom';
import Index from '../components/index';
ReactDOM.render(
<Index/>
, document.getElementById('root'));
if(module.hot) {
module.hot.accept();
}
|
packages/react-router-native/__tests__/index.ios.js | goblortikus/react-router | import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
client/src/app/admin/panel/settings/admin-panel-system-preferences.js | ivandiazwm/opensupports | import React from 'react';
import _ from 'lodash';
import store from 'app/store';
import ConfigActions from 'actions/config-actions';
import API from 'lib-app/api-call';
import i18n from 'lib-app/i18n';
import LanguageSelector from 'app-components/language-selector';
import ToggleButton from 'app-components/toggle-button';
import languageList from 'data/language-list';
import Form from 'core-components/form';
import FormField from 'core-components/form-field';
import Header from 'core-components/header';
import SubmitButton from 'core-components/submit-button';
import Button from 'core-components/button';
import Message from 'core-components/message';
import InfoTooltip from 'core-components/info-tooltip';
const languageKeys = Object.keys(languageList);
class AdminPanelSystemPreferences extends React.Component {
state = {
loading: true,
message: null,
values: {
maintenance: false,
}
};
componentDidMount() {
this.recoverSettings();
}
render() {
return (
<div className="admin-panel-system-preferences">
<Header title={i18n('SYSTEM_PREFERENCES')} description={i18n('SYSTEM_PREFERENCES_DESCRIPTION')}/>
<Form values={this.state.values} onChange={this.onFormChange.bind(this)} onSubmit={this.onSubmit.bind(this)} loading={this.state.loading}>
<div className="row">
<div className="col-md-12">
<div className="admin-panel-system-preferences__maintenance">
<span>{i18n('MAINTENANCE_MODE')} <InfoTooltip text={i18n('MAINTENANCE_MODE_INFO')} /></span>
<FormField className="admin-panel-system-preferences__maintenance-field" name="maintenance-mode" decorator={ToggleButton}/>
</div>
</div>
</div>
<div className="row">
<div className="col-md-12">
<span className="separator" />
</div>
</div>
<div className="row">
<div className="col-md-6">
<FormField label={i18n('SUPPORT_CENTER_URL')} fieldProps={{size: 'large'}} name="url" validation="URL" required/>
<FormField label={i18n('SUPPORT_CENTER_LAYOUT')} fieldProps={{size: 'large', items: [{content: i18n('BOXED')}, {content: i18n('FULL_WIDTH')}]}} field="select" name="layout" />
</div>
<div className="col-md-6">
<FormField label={i18n('SUPPORT_CENTER_TITLE')} fieldProps={{size: 'large'}} name="title" validation="TITLE" required/>
<FormField label={i18n('DEFAULT_TIMEZONE')} fieldProps={{size: 'large'}} name="time-zone"/>
</div>
</div>
<div className="row">
<div className="col-md-12">
<span className="separator" />
</div>
<div className="col-md-6">
<div className="row admin-panel-system-preferences__languages">
<div className="col-md-6 admin-panel-system-preferences__languages-allowed">
<div>{i18n('ALLOWED_LANGUAGES')} <InfoTooltip text={i18n('ALLOWED_LANGUAGES_INFO')} /></div>
<FormField name="allowedLanguages" field="checkbox-group" fieldProps={{items: this.getLanguageList()}} validation="LIST" required/>
</div>
<div className="col-md-6 admin-panel-system-preferences__languages-supported">
<div>{i18n('SUPPORTED_LANGUAGES')} <InfoTooltip text={i18n('SUPPORTED_LANGUAGES_INFO')} /></div>
<FormField name="supportedLanguages" field="checkbox-group" fieldProps={{items: this.getLanguageList()}} validation="LIST" required/>
</div>
</div>
</div>
<div className="col-md-6">
<FormField className="admin-panel-system-preferences__default-language-field" name="language" label={i18n('DEFAULT_LANGUAGE')} decorator={LanguageSelector} fieldProps={{
type: 'custom',
customList: (this.state.values.supportedLanguages && this.state.values.supportedLanguages.length) ? this.state.values.supportedLanguages.map(index => languageKeys[index]) : undefined
}} />
<FormField label={i18n('RECAPTCHA_PUBLIC_KEY')} fieldProps={{size: 'large'}} name="reCaptchaKey"/>
<FormField label={i18n('RECAPTCHA_PRIVATE_KEY')} fieldProps={{size: 'large'}} name="reCaptchaPrivate"/>
<div className="admin-panel-system-preferences__file-attachments">
<span>{i18n('ALLOW_FILE_ATTACHMENTS')}</span>
<FormField className="admin-panel-system-preferences__file-attachments-field" name="allow-attachments" decorator={ToggleButton}/>
</div>
<div className="admin-panel-system-preferences__max-size">
<span>{i18n('MAX_SIZE_MB')}</span>
<FormField className="admin-panel-system-preferences__max-size-field" fieldProps={{size: 'small'}} name="max-size"/>
</div>
</div>
</div>
<div className="row">
<div className="col-md-12">
<span className="separator" />
</div>
</div>
<div className="row">
<div className="col-md-4 col-md-offset-2">
<SubmitButton type="secondary">{i18n('UPDATE_SETTINGS')}</SubmitButton>
</div>
<div className="col-md-4">
<Button onClick={this.onDiscardChangesSubmit.bind(this)}>{i18n('DISCARD_CHANGES')}</Button>
</div>
</div>
</Form>
{this.renderMessage()}
</div>
);
}
renderMessage() {
switch (this.state.message) {
case 'success':
return <Message className="admin-panel-system-preferences__message" type="success">{i18n('SETTINGS_UPDATED')}</Message>;
case 'fail':
return <Message className="admin-panel-system-preferences__message" type="error">{i18n('ERROR_UPDATING_SETTINGS')}</Message>;
default:
return null;
}
}
onFormChange(form) {
const { language, supportedLanguages, allowedLanguages } = form;
const languageIndex = _.indexOf(languageKeys, language);
this.setState({
values: _.extend({}, form, {
language: _.includes(supportedLanguages, languageIndex) ? language : languageKeys[supportedLanguages[0]],
supportedLanguages: _.filter(supportedLanguages, (supportedIndex) => _.includes(allowedLanguages, supportedIndex))
}),
message: null
});
}
onSubmit(form) {
this.setState({loading: true});
API.call({
path: '/system/edit-settings',
data: {
'language': form.language,
'recaptcha-public': form.reCaptchaKey,
'recaptcha-private': form.reCaptchaPrivate,
'url': form['url'],
'title': form['title'],
'layout': form['layout'] ? 'full-width' : 'boxed',
'time-zone': form['time-zone'],
'maintenance-mode': form['maintenance-mode'] * 1,
'allow-attachments': form['allow-attachments'] * 1,
'max-size': form['max-size'],
'allowedLanguages': JSON.stringify(form.allowedLanguages.map(index => languageKeys[index])),
'supportedLanguages': JSON.stringify(form.supportedLanguages.map(index => languageKeys[index]))
}
}).then(this.onSubmitSuccess.bind(this)).catch(() => this.setState({loading: false, message: 'fail'}));
}
onSubmitSuccess() {
this.recoverSettings();
this.setState({
message: 'success',
loading: false
});
}
getLanguageList() {
return Object.keys(languageList).map(key => languageList[key].name);
}
recoverSettings() {
API.call({
path: '/system/get-settings',
data: {
allSettings: true
}
}).then(this.onRecoverSettingsSuccess.bind(this)).catch(this.onRecoverSettingsFail.bind(this));
}
onRecoverSettingsSuccess(result) {
this.setState({
loading: false,
values: {
'language': result.data.language,
'reCaptchaKey': result.data.reCaptchaKey,
'reCaptchaPrivate': result.data.reCaptchaPrivate,
'url': result.data['url'],
'title': result.data['title'],
'layout': (result.data['layout'] == 'full-width') ? 1 : 0,
'time-zone': result.data['time-zone'],
'maintenance-mode': !!(result.data['maintenance-mode'] * 1),
'allow-attachments': !!(result.data['allow-attachments'] * 1),
'max-size': result.data['max-size'],
'allowedLanguages': result.data.allowedLanguages.map(lang => (_.indexOf(languageKeys, lang))),
'supportedLanguages': result.data.supportedLanguages.map(lang => (_.indexOf(languageKeys, lang)))
}
});
store.dispatch(ConfigActions.updateData());
}
onRecoverSettingsFail() {
this.setState({
message: 'error'
});
}
onDiscardChangesSubmit(event) {
event.preventDefault();
this.setState({loading: true});
this.recoverSettings();
}
}
export default AdminPanelSystemPreferences;
|
src/SparklinesSpots.js | Jonekee/react-sparklines | import React from 'react';
export default class SparklinesSpots extends React.Component {
static propTypes = {
size: React.PropTypes.number,
style: React.PropTypes.object,
spotColors: React.PropTypes.object
};
static defaultProps = {
size: 2,
spotColors: {
'-1': 'red',
'0': 'black',
'1': 'green'
}
};
lastDirection(points) {
Math.sign = Math.sign || function(x) { return x > 0 ? 1 : -1; }
return points.length < 2
? 0
: Math.sign(points[points.length - 2].y - points[points.length - 1].y);
}
render() {
const { points, width, height, size, style, spotColors } = this.props;
const startSpot = <circle
cx={points[0].x}
cy={points[0].y}
r={size}
style={style} />
const endSpot = <circle
cx={points[points.length - 1].x}
cy={points[points.length - 1].y}
r={size}
style={style || { fill: spotColors[this.lastDirection(points)] }} />
return (
<g>
{style && startSpot}
{endSpot}
</g>
)
}
}
|
cms/react-static/src/containers/Post.js | fishjar/gabe-study-notes | import React from 'react'
import { withRouteData, Link } from 'react-static'
//
export default withRouteData(({ post }) => (
<div>
<Link to="/blog/">{'<'} Back</Link>
<br />
<h3>{post.title}</h3>
<p>{post.body}</p>
</div>
))
|
app/components/Hello.js | designjockey/reactor | import React from 'react';
class Hello extends React.Component {
render() {
return (
<h1 ref={(node) => { this.heading = node; }}>Hello World</h1>
);
}
}
export default Hello;
|
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js | xiaotaijun/actor-platform | import _ from 'lodash';
import React from 'react';
import mixpanel from 'utils/Mixpanel';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import MyProfileActions from 'actions/MyProfileActions';
import LoginActionCreators from 'actions/LoginActionCreators';
import HelpActionCreators from 'actions/HelpActionCreators';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import AvatarItem from 'components/common/AvatarItem.react';
import MyProfileModal from 'components/modals/MyProfile.react';
import ActorClient from 'utils/ActorClient';
import AddContactModal from 'components/modals/AddContact.react';
import PreferencesModal from '../modals/Preferences.react';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
var getStateFromStores = () => {
return {
dialogInfo: null
};
};
@ReactMixin.decorate(IntlMixin)
class HeaderSection extends React.Component {
constructor(props) {
super(props);
this.state = _.assign({
isOpened: false
}, getStateFromStores());
}
componentDidMount() {
ActorClient.bindUser(ActorClient.getUid(), this.setUser);
}
componentWillUnmount() {
ActorClient.unbindUser(ActorClient.getUid(), this.setUser);
}
setUser = (user) => {
this.setState({user: user});
};
setLogout = () => {
LoginActionCreators.setLoggedOut();
};
openMyProfile = () => {
MyProfileActions.modalOpen();
mixpanel.track('My profile open');
};
openHelpDialog = () => {
HelpActionCreators.open();
mixpanel.track('Click on HELP');
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
onSettingsOpen = () => {
PreferencesActionCreators.show();
};
toggleHeaderMenu = () => {
const isOpened = this.state.isOpened;
if (!isOpened) {
this.setState({isOpened: true});
mixpanel.track('Open sidebar menu');
document.addEventListener('click', this.closeHeaderMenu, false);
} else {
this.closeHeaderMenu();
}
};
closeHeaderMenu = () => {
this.setState({isOpened: false});
document.removeEventListener('click', this.closeHeaderMenu, false);
};
render() {
const user = this.state.user;
if (user) {
let headerClass = classNames('sidebar__header', 'sidebar__header--clickable', {
'sidebar__header--opened': this.state.isOpened
});
let menuClass = classNames('dropdown', {
'dropdown--opened': this.state.isOpened
});
return (
<header className={headerClass}>
<div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}>
<AvatarItem image={user.avatar}
placeholder={user.placeholder}
size="tiny"
title={user.name} />
<span className="sidebar__header__user__name col-xs">{user.name}</span>
<div className={menuClass}>
<span className="dropdown__button">
<i className="material-icons">arrow_drop_down</i>
</span>
<ul className="dropdown__menu dropdown__menu--right">
<li className="dropdown__menu__item hide">
<i className="material-icons">photo_camera</i>
<FormattedMessage message={this.getIntlMessage('setProfilePhoto')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openMyProfile}>
<i className="material-icons">edit</i>
<FormattedMessage message={this.getIntlMessage('editProfile')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openAddContactModal}>
<i className="material-icons">person_add</i>
Add contact
</li>
<li className="dropdown__menu__separator"></li>
<li className="dropdown__menu__item hide">
<svg className="icon icon--dropdown"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/>
<FormattedMessage message={this.getIntlMessage('configureIntegrations')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openHelpDialog}>
<i className="material-icons">help</i>
<FormattedMessage message={this.getIntlMessage('helpAndFeedback')}/>
</li>
<li className="dropdown__menu__item hide" onClick={this.onSettingsOpen}>
<i className="material-icons">settings</i>
<FormattedMessage message={this.getIntlMessage('preferences')}/>
</li>
<li className="dropdown__menu__item dropdown__menu__item--light" onClick={this.setLogout}>
<FormattedMessage message={this.getIntlMessage('signOut')}/>
</li>
</ul>
</div>
</div>
<MyProfileModal/>
<AddContactModal/>
<PreferencesModal/>
</header>
);
} else {
return null;
}
}
}
export default HeaderSection;
|
app/components/RollPage.js | mzanini/DeeMemory | import React from 'react'
import Roll from './Roll'
const RollPage = () => (
<Roll/>
)
export default RollPage
|
src/js/pages/PricingTable.js | hadnazzar/ModernBusinessBootstrap-ReactComponent | import React from 'react';
import {Link} from "react-router";
import Subheading from '../components/Subheading';
export default class Layout extends React.Component {
constructor() {
super();
this.state = {
title:"Welcome to Momoware!",
};
}
changeTitle(title){
this.setState({title});
}
navigate() {
console.log(this.props);
}
render() {
return(
<div>
<Subheading title="Pricing Table"/>
<div class="container">
<div class="row">
<div class="col-md-4">
<div class="panel panel-default text-center">
<div class="panel-heading">
<h3 class="panel-title">Basic</h3>
</div>
<div class="panel-body">
<span class="price"><sup>$</sup>19<sup>99</sup></span>
<span class="period">per month</span>
</div>
<ul class="list-group">
<li class="list-group-item"><strong>1</strong> User</li>
<li class="list-group-item"><strong>5</strong> Projects</li>
<li class="list-group-item"><strong>Unlimited</strong> Email Accounts</li>
<li class="list-group-item"><strong>10GB</strong> Disk Space</li>
<li class="list-group-item"><strong>100GB</strong> Monthly Bandwidth</li>
<li class="list-group-item"><a href="#" class="btn btn-primary">Sign Up!</a>
</li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-primary text-center">
<div class="panel-heading">
<h3 class="panel-title">Plus <span class="label label-success">Best Value</span></h3>
</div>
<div class="panel-body">
<span class="price"><sup>$</sup>39<sup>99</sup></span>
<span class="period">per month</span>
</div>
<ul class="list-group">
<li class="list-group-item"><strong>10</strong> User</li>
<li class="list-group-item"><strong>500</strong> Projects</li>
<li class="list-group-item"><strong>Unlimited</strong> Email Accounts</li>
<li class="list-group-item"><strong>1000GB</strong> Disk Space</li>
<li class="list-group-item"><strong>10000GB</strong> Monthly Bandwidth</li>
<li class="list-group-item"><a href="#" class="btn btn-primary">Sign Up!</a>
</li>
</ul>
</div>
</div>
<div class="col-md-4">
<div class="panel panel-default text-center">
<div class="panel-heading">
<h3 class="panel-title">Ultra</h3>
</div>
<div class="panel-body">
<span class="price"><sup>$</sup>159<sup>99</sup></span>
<span class="period">per month</span>
</div>
<ul class="list-group">
<li class="list-group-item"><strong>Unlimted</strong> Users</li>
<li class="list-group-item"><strong>Unlimited</strong> Projects</li>
<li class="list-group-item"><strong>Unlimited</strong> Email Accounts</li>
<li class="list-group-item"><strong>10000GB</strong> Disk Space</li>
<li class="list-group-item"><strong>Unlimited</strong> Monthly Bandwidth</li>
<li class="list-group-item"><a href="#" class="btn btn-primary">Sign Up!</a>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
);
}
}
|
app/m_components/Copyright.js | kongchun/BigData-Web | import React from 'react';
import {
Link
} from 'react-router';
class Copyright extends React.Component {
render() {
return (
<div className="copyright">
<div className="container">
<div className="row">
<div className="col-sm-12">
<span>Copyright © <a href="http://www.limaodata.com/">苏州猫耳网络科技有限公司</a></span> |
<span><a href="http://www.miibeian.gov.cn/" target="_blank">苏ICP备14030752号</a></span>
</div>
</div>
</div>
</div>
);
}
}
export default Copyright; |
app/javascript/mastodon/features/followers/index.js | mhffdq/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import {
fetchAccount,
fetchFollowers,
expandFollowers,
} from '../../actions/accounts';
import { ScrollContainer } from 'react-router-scroll-4';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import LoadMore from '../../components/load_more';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'followers', props.params.accountId, 'items']),
hasMore: !!state.getIn(['user_lists', 'followers', props.params.accountId, 'next']),
});
@connect(mapStateToProps)
export default class Followers extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchAccount(this.props.params.accountId));
this.props.dispatch(fetchFollowers(this.props.params.accountId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(fetchFollowers(nextProps.params.accountId));
}
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) {
this.props.dispatch(expandFollowers(this.props.params.accountId));
}
}
handleLoadMore = (e) => {
e.preventDefault();
this.props.dispatch(expandFollowers(this.props.params.accountId));
}
render () {
const { accountIds, hasMore } = this.props;
let loadMore = null;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
if (hasMore) {
loadMore = <LoadMore onClick={this.handleLoadMore} />;
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='followers'>
<div className='scrollable' onScroll={this.handleScroll}>
<div className='followers'>
<HeaderContainer accountId={this.props.params.accountId} hideTabs />
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
{loadMore}
</div>
</div>
</ScrollContainer>
</Column>
);
}
}
|
app/react-icons/fa/pie-chart.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaPieChart extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m17.6 19.9l12.2 12.2q-2.3 2.4-5.5 3.7t-6.7 1.3q-4.6 0-8.6-2.3t-6.2-6.2-2.3-8.6 2.3-8.6 6.2-6.2 8.6-2.3v17z m4.2 0.1h17.3q0 3.5-1.4 6.7t-3.7 5.5z m15.8-2.9h-17.1v-17.1q4.7 0 8.6 2.3t6.2 6.2 2.3 8.6z"/></g>
</IconBase>
);
}
}
|
src/server.js | labreaks/ep-web-app | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
const server = global.server = express();
const port = process.env.PORT || 5000;
server.set('port', port);
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '' };
const css = [];
const context = {
onInsertCss: value => css.push(value),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
/* eslint-disable no-console */
console.log(`The server is running at http://localhost:${port}/`);
});
|
src/components/Races/SelectYearComponent.js | chiefwhitecloud/running-man-frontend | import React from 'react';
import PropTypes from 'prop-types';
const SelectYearComponent = ({years}) => {
return <div>
{years.map(function(year){
return <div>{year}</div>
})}
</div>;
};
SelectYearComponent.propTypes = { years: PropTypes.array };
export default SelectYearComponent;
|
src/components/Rating/index.js | xenotime-india/CV | import React from 'react'
class Rating extends React.Component {
render() {
const { skillName, rating } = this.props
const userRating = []
for (let i = 0; i < rating; i++) {
userRating.push(
<i className="fa fa-circle fa-2x" aria-hidden="true" key={i} />
)
}
while (userRating.length < 5) {
userRating.push(
<i
className="fa fa-circle-thin fa-2x"
aria-hidden="true"
key={userRating.length}
/>
)
}
return (
<div className="skill-col">
<div>{skillName}</div>
<div className="col-group rating">{userRating}</div>
</div>
)
}
}
export default Rating
|
src/mui-themeable.js | tyfoo/material-ui | import React from 'react';
import DefaultRawTheme from './styles/raw-themes/light-raw-theme';
import ThemeManager from './styles/theme-manager';
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export default function muiThemeable(WrappedComponent) {
const MuiComponent = (props, {muiTheme = ThemeManager.getMuiTheme(DefaultRawTheme)}) => {
return <WrappedComponent {...props} muiTheme={muiTheme} />;
};
MuiComponent.displayName = getDisplayName(WrappedComponent);
MuiComponent.contextTypes = {
muiTheme: React.PropTypes.object,
};
MuiComponent.childContextTypes = {
muiTheme: React.PropTypes.object,
};
return MuiComponent;
}
|
src/index.js | Ibrasau/socketChatExample | import React, { Component } from 'react';
import { render } from 'react-dom';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import Chat from './components/Chat.js';
import reducer from './reducers/rootReducer';
const store = createStore(reducer);
render(
<Provider store={store}>
<Chat />
</Provider>,
document.querySelector('main')
);
if (module.hot.accept) module.hot.accept();
|
modules/__tests__/transitionHooks-test.js | arasmussen/react-router | /*eslint-env mocha */
/*eslint react/prop-types: 0*/
import expect, { spyOn } from 'expect'
import React from 'react'
import createHistory from 'history/lib/createMemoryHistory'
import execSteps from './execSteps'
import Router from '../Router'
describe('When a router enters a branch', function () {
let node, Dashboard, NewsFeed, Inbox, DashboardRoute, NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute, routes
beforeEach(function () {
node = document.createElement('div')
Dashboard = React.createClass({
render() {
return (
<div className="Dashboard">
<h1>The Dashboard</h1>
{this.props.children}
</div>
)
}
})
NewsFeed = React.createClass({
render() {
return <div>News</div>
}
})
Inbox = React.createClass({
render() {
return <div>Inbox</div>
}
})
NewsFeedRoute = {
path: 'news',
component: NewsFeed,
onEnter(nextState, replaceState) {
expect(this).toBe(NewsFeedRoute)
expect(nextState.routes).toContain(NewsFeedRoute)
expect(replaceState).toBeA('function')
},
onLeave() {
expect(this).toBe(NewsFeedRoute)
}
}
InboxRoute = {
path: 'inbox',
component: Inbox,
onEnter(nextState, replaceState) {
expect(this).toBe(InboxRoute)
expect(nextState.routes).toContain(InboxRoute)
expect(replaceState).toBeA('function')
},
onLeave() {
expect(this).toBe(InboxRoute)
}
}
RedirectToInboxRoute = {
path: 'redirect-to-inbox',
onEnter(nextState, replaceState) {
expect(this).toBe(RedirectToInboxRoute)
expect(nextState.routes).toContain(RedirectToInboxRoute)
expect(replaceState).toBeA('function')
replaceState(null, '/inbox')
},
onLeave() {
expect(this).toBe(RedirectToInboxRoute)
}
}
MessageRoute = {
path: 'messages/:messageID',
onEnter(nextState, replaceState) {
expect(this).toBe(MessageRoute)
expect(nextState.routes).toContain(MessageRoute)
expect(replaceState).toBeA('function')
},
onLeave() {
expect(this).toBe(MessageRoute)
}
}
DashboardRoute = {
component: Dashboard,
onEnter(nextState, replaceState) {
expect(this).toBe(DashboardRoute)
expect(nextState.routes).toContain(DashboardRoute)
expect(replaceState).toBeA('function')
},
onLeave() {
expect(this).toBe(DashboardRoute)
},
childRoutes: [ NewsFeedRoute, InboxRoute, RedirectToInboxRoute, MessageRoute ]
}
routes = [
DashboardRoute
]
})
afterEach(function () {
React.unmountComponentAtNode(node)
})
it('calls the onEnter hooks of all routes in that branch', function (done) {
const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough()
const newsFeedRouteEnterSpy = spyOn(NewsFeedRoute, 'onEnter').andCallThrough()
React.render(<Router history={createHistory('/news')} routes={routes}/>, node, function () {
expect(dashboardRouteEnterSpy).toHaveBeenCalled()
expect(newsFeedRouteEnterSpy).toHaveBeenCalled()
done()
})
})
describe('and one of the transition hooks navigates to another route', function () {
it('immediately transitions to the new route', function (done) {
const redirectRouteEnterSpy = spyOn(RedirectToInboxRoute, 'onEnter').andCallThrough()
const redirectRouteLeaveSpy = spyOn(RedirectToInboxRoute, 'onLeave').andCallThrough()
const inboxEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough()
React.render(<Router history={createHistory('/redirect-to-inbox')} routes={routes}/>, node, function () {
expect(this.state.location.pathname).toEqual('/inbox')
expect(redirectRouteEnterSpy).toHaveBeenCalled()
expect(redirectRouteLeaveSpy.calls.length).toEqual(0)
expect(inboxEnterSpy).toHaveBeenCalled()
done()
})
})
})
describe('and then navigates to another branch', function () {
it('calls the onLeave hooks of all routes in the previous branch that are not in the next branch', function (done) {
const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough()
const inboxRouteEnterSpy = spyOn(InboxRoute, 'onEnter').andCallThrough()
const inboxRouteLeaveSpy = spyOn(InboxRoute, 'onLeave').andCallThrough()
const steps = [
function () {
expect(inboxRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called')
this.history.pushState(null, '/news')
},
function () {
expect(inboxRouteLeaveSpy).toHaveBeenCalled('InboxRoute.onLeave was not called')
expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called')
}
]
const execNextStep = execSteps(steps, done)
React.render(
<Router history={createHistory('/inbox')}
routes={routes}
onUpdate={execNextStep}
/>, node, execNextStep)
})
})
describe('and then navigates to the same branch, but with different params', function () {
it('calls the onLeave and onEnter hooks of all routes whose params have changed', function (done) {
const dashboardRouteLeaveSpy = spyOn(DashboardRoute, 'onLeave').andCallThrough()
const dashboardRouteEnterSpy = spyOn(DashboardRoute, 'onEnter').andCallThrough()
const messageRouteLeaveSpy = spyOn(MessageRoute, 'onLeave').andCallThrough()
const messageRouteEnterSpy = spyOn(MessageRoute, 'onEnter').andCallThrough()
const steps = [
function () {
expect(dashboardRouteEnterSpy).toHaveBeenCalled('DashboardRoute.onEnter was not called')
expect(messageRouteEnterSpy).toHaveBeenCalled('InboxRoute.onEnter was not called')
this.history.pushState(null, '/messages/456')
},
function () {
expect(messageRouteLeaveSpy).toHaveBeenCalled('MessageRoute.onLeave was not called')
expect(messageRouteEnterSpy).toHaveBeenCalled('MessageRoute.onEnter was not called')
expect(dashboardRouteLeaveSpy.calls.length).toEqual(0, 'DashboardRoute.onLeave was called')
}
]
const execNextStep = execSteps(steps, done)
React.render(
<Router history={createHistory('/messages/123')}
routes={routes}
onUpdate={execNextStep}
/>, node, execNextStep)
})
})
})
|
src/components/tabBar.js | Seeingu/borrow-book | /*
底部栏
*/
import React from 'react';
import {
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
} from 'react-native';
import FontAwesomeIcon from 'react-native-vector-icons/FontAwesome';
import Icon from 'react-native-vector-icons/Ionicons';
import { ComponentStyles, CommonStyles } from '../assets/styles';
import ToastUtil from '../utils/ToastUtils';
import ViewPage from '../components/view';
import { color } from '../assets/styles/color';
import * as RouterSceneConfig from '../utils/RouterScene';
const styles = StyleSheet.create({
tab: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
paddingBottom: 5,
},
tabs: {
height: 60,
flexDirection: 'row',
paddingTop: 5,
borderWidth: 1,
borderTopWidth: 0,
borderLeftWidth: 0,
borderRightWidth: 0,
borderBottomColor: 'rgba(0,0,0,0.05)',
},
});
const FacebookTabBar = React.createClass({
tabIcons: [],
propTypes: {
goToPage: React.PropTypes.func,
activeTab: React.PropTypes.number,
tabs: React.PropTypes.array,
},
// componentDidMount() {
// this._listener = this.props.scrollValue.addListener(this.setAnimationValue);
// },
// setAnimationValue({ value }) {
// this.tabIcons.forEach((icon, i) => {
// const progress = Math.min(1, Math.abs(value - i));
// icon.setNativeProps({
// style: {
// color: this.iconColor(progress),
// },
// });
// });
// },
// color between rgb(59,89,152) and rgb(204,204,204)
// iconColor(progress) {
// const red = 59 + (204 - 59) * progress;
// const green = 89 + (204 - 89) * progress;
// const blue = 152 + (204 - 152) * progress;
// return `rgb(${red}, ${green}, ${blue})`;
// },
render() {
const { router } = this.props;
const tabNames = ['借书', '还书', '+', '我的', '捐书'];
return (<View style={[styles.tabs, this.props.style,]}>
{this.props.tabs.map((tab, i) => (
(i === 2) ?
<TouchableOpacity
key={tab}
style={styles.tab}
onPress={() => router.push(ViewPage.search(), {
router,
sceneConfig: RouterSceneConfig.customFloatFromBottom,
})}
>
<View
style={{
marginTop: 5,
alignItems: 'center',
justifyContent: 'center',
paddingTop: 5,
borderRadius: 20,
width: 40,
height: 40,
backgroundColor: color.yellow }}
>
<Icon
name={tab}
size={20}
style={{ marginBottom: 5 }}
color={'white'}
ref={(icon) => { this.tabIcons[i] = icon; }}
/>
</View>
</TouchableOpacity>
: <TouchableOpacity key={tab} onPress={() => this.props.goToPage(i)} style={styles.tab}>
<View style={[CommonStyles.flexColumn]}>
{i === 4 ?
<Image
source={require('../assets/images/icon-public-benefit.png')}
style={{
width: 30,
height: 30,
}}
>
<View
style={{
backgroundColor: this.props.activeTab === i ? 'rgba(255,255,255,0)' : 'rgba(255,255,255,0.7)',
width: 40,
height: 40,
}}
/>
</Image>
: <Icon
name={tab}
size={30}
color={this.props.activeTab === i ? '#323232' : 'rgb(204,204,204)'}
ref={(icon) => { this.tabIcons[i] = icon; }}
/>
}
<Text
style={[CommonStyles.font_ms, this.props.activeTab === i ? { color: '#323232' } : { color: 'rgb(204,204,204)' }]}
>
{tabNames[i]}
</Text>
</View>
</TouchableOpacity>
))}
</View>);
},
});
export default FacebookTabBar;
|
app/components/Keywords.js | alexindigo/ndash | import React, { Component } from 'react';
import { Text, View } from 'react-native';
import { combine } from '../helpers/styles';
export default class Keywords extends Component {
renderKeywords() {
if (!this.props.keywords) {
return null;
}
return React.Children.toArray(this.props.keywords).map((word, i) => {
return (
<Text
key={'keyword_' + i}
style={this.props.wordStyle}
>{word}</Text>
);
});
}
render() {
return (
<View
style={this.props.style}
>
{ this.renderKeywords() }
</View>
);
}
}
|
docs/src/components/nav.js | mcanthony/nuclear-js | import React from 'react'
import { BASE_URL } from '../globals'
function urlize(uri) {
return BASE_URL + uri
}
export default React.createClass({
render() {
const logo = this.props.includeLogo
? <a href={BASE_URL} className="brand-logo">NuclearJS</a>
: null
const homeLink = this.props.includeLogo
? <li className="hide-on-large-only"><a href={urlize("")}>Home</a></li>
: null
return <div className="navbar-fixed">
<nav className="nav">
<div className="hide-on-large-only">
<ul className="right">
{homeLink}
<li><a href={urlize("docs/01-getting-started.html")}>Docs</a></li>
<li><a href={urlize("docs/07-api.html")}>API</a></li>
<li><a href="https://github.com/optimizely/nuclear-js">Github</a></li>
</ul>
</div>
<div className="nav-wrapper hide-on-med-and-down">
{logo}
<ul className="right">
<li><a href={urlize("docs/01-getting-started.html")}>Docs</a></li>
<li><a href={urlize("docs/07-api.html")}>API</a></li>
<li><a href="https://github.com/optimizely/nuclear-js">Github</a></li>
</ul>
</div>
</nav>
</div>
}
})
|
app/javascript/mastodon/features/account_gallery/index.js | masarakki/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 { expandAccountMediaTimeline } from '../../actions/timelines';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { getAccountGallery } from '../../selectors';
import MediaItem from './components/media_item';
import HeaderContainer from '../account_timeline/containers/header_container';
import { ScrollContainer } from 'react-router-scroll-4';
import LoadMore from '../../components/load_more';
const mapStateToProps = (state, props) => ({
medias: getAccountGallery(state, props.params.accountId),
isLoading: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'hasMore']),
});
class LoadMoreMedia extends ImmutablePureComponent {
static propTypes = {
shouldUpdateScroll: PropTypes.func,
maxId: PropTypes.string,
onLoadMore: PropTypes.func.isRequired,
};
handleLoadMore = () => {
this.props.onLoadMore(this.props.maxId);
}
render () {
return (
<LoadMore
disabled={this.props.disabled}
onLoadMore={this.handleLoadMore}
/>
);
}
}
export default @connect(mapStateToProps)
class AccountGallery extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
medias: ImmutablePropTypes.list.isRequired,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
};
componentDidMount () {
this.props.dispatch(fetchAccount(this.props.params.accountId));
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId));
}
}
handleScrollToBottom = () => {
if (this.props.hasMore) {
this.handleLoadMore(this.props.medias.last().getIn(['status', 'id']));
}
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
const offset = scrollHeight - scrollTop - clientHeight;
if (150 > offset && !this.props.isLoading) {
this.handleScrollToBottom();
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId, { maxId }));
};
handleLoadOlder = (e) => {
e.preventDefault();
this.handleScrollToBottom();
}
render () {
const { medias, shouldUpdateScroll, isLoading, hasMore } = this.props;
let loadOlder = null;
if (!medias && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
if (!isLoading && medias.size > 0 && hasMore) {
loadOlder = <LoadMore onClick={this.handleLoadOlder} />;
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='account_gallery' shouldUpdateScroll={shouldUpdateScroll}>
<div className='scrollable' onScroll={this.handleScroll}>
<HeaderContainer accountId={this.props.params.accountId} />
<div className='account-gallery__container'>
{medias.map((media, index) => media === null ? (
<LoadMoreMedia
key={'more:' + medias.getIn(index + 1, 'id')}
maxId={index > 0 ? medias.getIn(index - 1, 'id') : null}
/>
) : (
<MediaItem
key={media.get('id')}
media={media}
/>
))}
{loadOlder}
</div>
</div>
</ScrollContainer>
</Column>
);
}
}
|
src/svg-icons/action/settings-remote.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsRemote = (props) => (
<SvgIcon {...props}>
<path d="M15 9H9c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V10c0-.55-.45-1-1-1zm-3 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM7.05 6.05l1.41 1.41C9.37 6.56 10.62 6 12 6s2.63.56 3.54 1.46l1.41-1.41C15.68 4.78 13.93 4 12 4s-3.68.78-4.95 2.05zM12 0C8.96 0 6.21 1.23 4.22 3.22l1.41 1.41C7.26 3.01 9.51 2 12 2s4.74 1.01 6.36 2.64l1.41-1.41C17.79 1.23 15.04 0 12 0z"/>
</SvgIcon>
);
ActionSettingsRemote = pure(ActionSettingsRemote);
ActionSettingsRemote.displayName = 'ActionSettingsRemote';
ActionSettingsRemote.muiName = 'SvgIcon';
export default ActionSettingsRemote;
|
src/components/Code.js | doug2k1/webpack-generator | // @flow
/* eslint react/no-danger: "off" */
import React from 'react'
import { js_beautify as beautify } from 'js-beautify/js/lib/beautify'
// import only highlight.js core and javascript language for smaller bundle size
import hljs from 'highlight.js/lib/highlight'
import hljsJS from 'highlight.js/lib/languages/javascript'
import { ConfigData } from '../types/ConfigData.type'
import '../../node_modules/highlight.js/styles/github.css'
hljs.registerLanguage('javascript', hljsJS)
type Props = {
data: ConfigData
}
type State = {
code: string,
modules: string[],
babelConfig: ?string
}
class Code extends React.Component<Props, State> {
state = this.stateFromProps()
componentWillReceiveProps(nextProps: Props) {
if (nextProps.data !== this.props.data) {
this.setState(this.stateFromProps(nextProps))
}
}
codeFromProps(props = this.props) {
const rules = []
const { data } = props
if (data.loaders.es6) {
rules.push({
test: `/\\.js$/`,
use: `'babel-loader'`
})
}
if (data.loaders.style === 'css') {
rules.push({
test: `/\\.css$/`,
use: data.plugins.extract
? `ExtractTextPlugin.extract({fallback: 'style-loader', use: ['css-loader']})`
: `['style-loader', 'css-loader']`
})
} else if (data.loaders.style === 'sass') {
rules.push({
test: `/\\.scss$/`,
use: data.plugins.extract
? `ExtractTextPlugin.extract({fallback: 'style-loader', use: ['css-loader', 'sass-loader']})`
: `['style-loader', 'css-loader', 'sass-loader']`
})
}
const plugins = []
if (data.plugins.extract) {
plugins.push({
importer: `const ExtractTextPlugin = require('extract-text-webpack-plugin');`,
init: `new ExtractTextPlugin('${data.plugins.extractFile}')`
})
}
let code = `const path = require('path');
${plugins.map(plugin => `${plugin.importer}\n`).join('')}
module.exports = {
entry: '${data.entry}',
output: {
path: path.resolve('${data.output.path}'),
filename: '${data.output.filename}'
}`
if (rules.length > 0) {
code += `,
module: {
rules: [${rules
.map(rule => `{ test: ${rule.test}, use: ${rule.use} }`)
.join(',\n\n')}]
}`
}
if (plugins.length > 0) {
code += `,
plugins: [
${plugins.map(plugin => plugin.init).join(',\n')}
]`
}
code += `};`
code = beautify(code, {
indent_size: 2
})
return hljs.highlight('javascript', code).value
}
modulesFromProps(props = this.props) {
const { data } = props
const modules = {
webpack: true,
'babel-core': data.loaders.es6,
'babel-loader': data.loaders.es6,
'babel-preset-env': data.loaders.es6,
'babel-preset-react': data.loaders.react,
'css-loader': data.loaders.style !== null,
'style-loader': data.loaders.style !== null,
'node-sass': data.loaders.style === 'sass',
'sass-loader': data.loaders.style === 'sass',
'extract-text-webpack-plugin': data.plugins.extract
}
return Object.keys(modules).filter(key => modules[key])
}
babelConfigFromProps(props = this.props) {
const { data } = props
const presets = {
env: data.loaders.es6,
react: data.loaders.react
}
const usingPresets = Object.keys(presets).filter(key => presets[key])
if (usingPresets.length > 0) {
return `{
"presets": [ "${usingPresets.join('", "')}" ]
}`
}
return null
}
stateFromProps(props = this.props) {
return {
code: this.codeFromProps(props),
modules: this.modulesFromProps(props),
babelConfig: this.babelConfigFromProps(props)
}
}
render() {
return (
<div>
<section>
<h3 className="section-title">Webpack config</h3>
<p className="section-subtitle">webpack.config.js</p>
<div>
<pre>
<code
className="hljs javascript"
dangerouslySetInnerHTML={{ __html: this.state.code }}
/>
</pre>
</div>
</section>
<section>
<div className="modules">
<h3 className="section-title">Modules</h3>
<p className="section-subtitle">Install with npm</p>
<p
dangerouslySetInnerHTML={{
__html: this.state.modules
.map(
mod =>
`<a href="https://www.npmjs.com/package/${
mod
}" target="_blank" rel="noopener noreferrer">${mod}</a>`
)
.join(', ')
}}
/>
<pre>
<code className="hljs">
npm i -D {this.state.modules.join(' ')}
</code>
</pre>
</div>
</section>
{this.state.babelConfig && (
<section>
<h3 className="section-title">Babel config</h3>
<p className="section-subtitle">.babelrc</p>
<pre>
<code className="hljs">{this.state.babelConfig}</code>
</pre>
</section>
)}
</div>
)
}
}
export default Code
|
src/svg-icons/action/eject.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionEject = (props) => (
<SvgIcon {...props}>
<path d="M5 17h14v2H5zm7-12L5.33 15h13.34z"/>
</SvgIcon>
);
ActionEject = pure(ActionEject);
ActionEject.displayName = 'ActionEject';
ActionEject.muiName = 'SvgIcon';
export default ActionEject;
|
wegas-app/src/main/node/wegas-react-form/src/Script/singleStatement.js | Heigvd/Wegas | import PropTypes from 'prop-types';
import React from 'react';
import { types } from 'recast';
/**
* HOC single statement builder
*/
function singleStatement(Comp) {
/**
* Component
* @param {{code:Object[], onChange:(AST:Object[])=>void}} props Component's props
*/
function SingleStatement(props) {
const { code, onChange } = props;
const stmt = code[0] || types.builders.emptyStatement();
return (
<Comp
{...props}
node={stmt}
onChange={v => onChange([types.builders.expressionStatement(v)])}
/>
);
}
SingleStatement.propTypes = {
code: PropTypes.array,
onChange: PropTypes.func
};
return SingleStatement;
}
export default singleStatement;
|
imports/ui/pages/ViewResources.js | lizihan021/SAA-Website | import React from 'react';
import NotFound from './NotFound';
import PropTypes from 'prop-types';
export default class ViewResources extends React.Component {
render() {
return (
<div className="ViewResources">
<h2 className="page-header">{this.props.params.id}</h2>
<embed src={ `/files/${this.props.params.id}.pdf` } type="application/pdf" ></embed>
</div>
);
}
};
|
index.js | Prashant31/redux-blog | import React from 'react'
import { render } from 'react-dom'
import {initialize} from './utils/Root'
var {provider} = initialize();
render(provider, document.getElementById('root'));
|
src/TreeSelect/TreeSelect.stories.js | ctco/rosemary-ui | import React from 'react';
import { storiesOf, action } from '@storybook/react';
import noop from 'lodash/noop';
import { TreeSelect, SingleTreeSelect, TreeWithInactiveSwitch } from './TreeSelect';
let nextId = 0;
const makeOption = (displayString, treeNodeHash, leaf, active = true, id = null) => {
nextId++;
return {
id: id === null ? nextId : id,
displayString,
treeNodeHash,
leaf,
active
};
};
const options = [
makeOption('A Test 1', '1'),
makeOption('B Test 11', '11', true, false),
makeOption('C Test 12', '12', false),
makeOption('D Test 121', '121', true),
makeOption('X Test 13', '3', true, false, -1),
makeOption('E Test 2', '2'),
makeOption('F Test 21', '21', true)
];
storiesOf('TreeSelect', module)
.add('basic', () => <TreeSelect hashLength={1} options={options} onChange={noop} />)
.add('showActive', () => <TreeWithInactiveSwitch hashLength={1} options={options} value={[4]} />)
.add('single select', () => (
<div style={{ textAlign: 'center' }}>
<SingleTreeSelect
hashLength={1}
options={options}
onChange={action('onChange')}
label="+ Add Org. Unit"
sort={(a, b) => {
if (a.id === -1) {
return -1;
}
if (b.id === 1) {
return 1;
}
return a.displayString.localeCompare(b.displayString);
}}
/>
</div>
));
|
src/components/Select/__tests__/select.spec.js | StepanYurtsiv/kep-e-campus | import React from 'react';
import Select from '../index';
import { renderToJson } from '../../../lib/utils/testing';
describe('Select component', () => {
it('should render Select component with options', () => {
const options = [{
_id: 123,
text: 'Option 1',
}, {
_id: 456,
text: 'Option 2',
}, {
_id: 678,
text: 'Option 3',
}];
expect(
renderToJson(
<Select
inputLabel="Awesome select"
options={options}
value={options[0]._id}
onChange={() => {}}
textKey="text"
/>,
),
).toMatchSnapshot();
});
});
|
src/components/App/index.js | LamouchiMS/adintel | import React from 'react';
import injectTapEventPlugin from 'react-tap-event-plugin';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {fade} from 'material-ui/utils/colorManipulator';
import {
cyan700,
grey600,
yellowA100,
yellowA200,
yellowA400,
white,
fullWhite
} from 'material-ui/styles/colors';
import styles from './App.css';
import First from '../First';
import Header from '../Header';
import Footer from '../Footer';
injectTapEventPlugin();
const muiTheme = getMuiTheme({
palette: {
primary1Color: '#303030',
primary2Color: cyan700,
primary3Color: grey600,
accent1Color: yellowA200,
accent2Color: yellowA400,
accent3Color: yellowA100,
textColor: fullWhite,
secondaryTextColor: fade(fullWhite, 0.7),
alternateTextColor: white,
canvasColor: '#303030',
borderColor: fade(fullWhite, 0.3),
disabledColor: fade(fullWhite, 0.3),
pickerHeaderColor: fade(fullWhite, 0.12),
clockCircleColor: fade(fullWhite, 0.12)
}
});
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
msg: 'Hello world'
}
}
render() {
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div className={styles.app}>
<Header/>
<First/>
<Footer/>
</div>
</MuiThemeProvider>
);
}
}
export default App;
|
src/BottomNavigation/BottomNavigation.js | AndriusBil/material-ui | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
export const styles = (theme: Object) => ({
root: {
display: 'flex',
justifyContent: 'center',
height: 56,
backgroundColor: theme.palette.background.paper,
},
});
function BottomNavigation(props) {
const {
children: childrenProp,
classes,
className: classNameProp,
onChange,
showLabels,
value,
...other
} = props;
const className = classNames(classes.root, classNameProp);
const children = React.Children.map(childrenProp, (child, childIndex) => {
const childValue = child.props.value || childIndex;
return React.cloneElement(child, {
selected: childValue === value,
showLabel: child.props.showLabel !== undefined ? child.props.showLabel : showLabels,
value: childValue,
onChange,
});
});
return (
<div className={className} {...other}>
{children}
</div>
);
}
BottomNavigation.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node.isRequired,
/**
* Useful to extend the style applied to components.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Callback fired when the value changes.
*
* @param {object} event The event source of the callback
* @param {any} value We default to the index of the child
*/
onChange: PropTypes.func,
/**
* If `true`, all `BottomNavigationButton`s will show their labels.
* By default only the selected `BottomNavigationButton` will show its label.
*/
showLabels: PropTypes.bool,
/**
* The value of the currently selected `BottomNavigationButton`.
*/
value: PropTypes.any.isRequired,
};
BottomNavigation.defaultProps = {
showLabels: false,
};
export default withStyles(styles, { name: 'MuiBottomNavigation' })(BottomNavigation);
|
src/components/Title.js | mirego/mirego-open-web | import React from 'react';
import styled from '@emotion/styled';
const Content = styled.div`
padding: 0 10px;
margin: 0 0 30px;
text-align: center;
color: #666;
@media (prefers-color-scheme: dark) {
& {
color: #aaa;
}
}
`;
const Title = styled.h2`
margin: 0 0 5px;
text-align: center;
font-size: 26px;
font-weight: bold;
color: #444;
@media (prefers-color-scheme: dark) {
& {
color: #ccc;
}
}
`;
export default ({title, children}) => (
<Content>
<Title dangerouslySetInnerHTML={{__html: title}} />
{children}
</Content>
);
|
app/components/DropdownFontSelectorMenu.js | googlefonts/korean | import React, { Component } from 'react';
import { FONTS } from '../constants/defaults';
import { connect } from 'react-redux';
import { changeDescFontDropdownOpened, changeCurrentDescFont } from '../actions';
import onClickOutside from "react-onclickoutside";
import _ from 'lodash';
const Fragment = React.Fragment;
class DropDownFontSelectorMenu extends Component {
handleCurrentDescFont(fontData, e){
e.stopPropagation();
let { currentDescFontSelected } = this.props;
let newCurrentDescFont = {
...this.props.currentDescFont
};
if (currentDescFontSelected == "all") {
newCurrentDescFont["title"] = fontData.id;
newCurrentDescFont["paragraph"] = fontData.id;
} else {
newCurrentDescFont[currentDescFontSelected] = fontData.id;
}
this.props.dispatch(changeCurrentDescFont(newCurrentDescFont));
this.props.dispatch(changeDescFontDropdownOpened(false));
}
handleClickOutside(evt){
evt.stopPropagation();
_.delay(() => {
this.props.dispatch(changeDescFontDropdownOpened(false));
}, 100);
}
render() {
let { currentDescFontSelected, locale } = this.props;
let currentDescFont = _.find(FONTS, fontData => { return this.props.currentDescFont[currentDescFontSelected] == fontData.id });
return (
<div className="dropdown-font-selector__menu">
{
_.map(FONTS, fontData => {
return (
<a className="dropdown-font-selector__list" onClick={this.handleCurrentDescFont.bind(this, fontData)} key={fontData.id} href="javascript:void(0);">
{
locale == "ko" ?
<Fragment>
<div className="dropdown-font-selector__list__label-ko-black">
{
fontData.nameKo
}
</div>
<div className="dropdown-font-selector__list__label-en-regular">
{
fontData.nameEn
}
</div>
</Fragment> :
<Fragment>
<div className="dropdown-font-selector__list__label-en-black">
{
fontData.nameEn
}
</div>
<div className="dropdown-font-selector__list__label-ko-regular">
{
fontData.nameKo
}
</div>
</Fragment>
}
</a>
);
})
}
</div>
);
}
}
let mapStateToProps = state => {
return {
currentDescFont: state.currentDescFont,
locale: state.locale,
currentDescFontSelected: state.currentDescFontSelected
}
}
export default connect(mapStateToProps)(onClickOutside(DropDownFontSelectorMenu)); |
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch03/03_02/finish/src/components/SkiDayCount.js | yevheniyc/Autodidact | import React from 'react'
import '../stylesheets/ui.scss'
export const SkiDayCount = React.createClass({
render() {
return (
<div className="ski-day-count">
<div className="total-days">
<span>5 days</span>
</div>
<div className="powder-days">
<span>2 days</span>
</div>
<div className="backcountry-days">
<span>1 hiking day</span>
</div>
</div>
)
}
}) |
test/react/ModalBody.spec.js | onap-sdc/sdc-ui | import React from 'react';
import ModalBody from '../../src/react/ModalBody.js';
import renderer from 'react-test-renderer';
describe('ModalBody', () => {
test('basic test', () => {
const header = renderer.create(<ModalBody/>).toJSON();
expect(header).toMatchSnapshot();
});
}); |
docs/app/Examples/collections/Grid/ResponsiveVariations/GridExampleDeviceVisibility.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Grid, Segment } from 'semantic-ui-react'
const GridExampleDeviceVisibility = () => (
<Grid>
<Grid.Row columns={2} only='large screen'>
<Grid.Column>
<Segment>Large Screen</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Large Screen</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={2} only='widescreen'>
<Grid.Column>
<Segment>Widescreen</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Widescreen</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={2} only='mobile'>
<Grid.Column>
<Segment>Mobile</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Mobile</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={3}>
<Grid.Column only='computer'>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column only='tablet mobile'>
<Segment>Tablet and Mobile</Segment>
</Grid.Column>
<Grid.Column>
<Segment>All Sizes</Segment>
</Grid.Column>
<Grid.Column>
<Segment>All Sizes</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row columns={4} only='computer'>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Computer</Segment>
</Grid.Column>
</Grid.Row>
<Grid.Row only='tablet'>
<Grid.Column>
<Segment>Tablet</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Tablet</Segment>
</Grid.Column>
<Grid.Column>
<Segment>Tablet</Segment>
</Grid.Column>
</Grid.Row>
</Grid>
)
export default GridExampleDeviceVisibility
|
examples/tree-view/src/containers/Node.js | roth1002/redux | import React from 'react'
import { Component } from 'react'
import { connect } from 'react-redux'
import * as actions from '../actions'
export class Node extends Component {
handleIncrementClick = () => {
const { increment, id } = this.props
increment(id)
}
handleAddChildClick = e => {
e.preventDefault()
const { addChild, createNode, id } = this.props
const childId = createNode().nodeId
addChild(id, childId)
}
handleRemoveClick = e => {
e.preventDefault()
const { removeChild, deleteNode, parentId, id } = this.props
removeChild(parentId, id)
deleteNode(id)
}
renderChild = childId => {
const { id } = this.props
return (
<li key={childId}>
<ConnectedNode id={childId} parentId={id} />
</li>
)
}
render() {
const { counter, parentId, childIds } = this.props
return (
<div>
Counter: {counter}
{' '}
<button onClick={this.handleIncrementClick}>
+
</button>
{' '}
{typeof parentId !== 'undefined' &&
<a href="#" onClick={this.handleRemoveClick} // eslint-disable-line jsx-a11y/href-no-hash
style={{ color: 'lightgray', textDecoration: 'none' }}>
×
</a>
}
<ul>
{childIds.map(this.renderChild)}
<li key="add">
<a href="#" // eslint-disable-line jsx-a11y/href-no-hash
onClick={this.handleAddChildClick}
>
Add child
</a>
</li>
</ul>
</div>
)
}
}
function mapStateToProps(state, ownProps) {
return state[ownProps.id]
}
const ConnectedNode = connect(mapStateToProps, actions)(Node)
export default ConnectedNode
|
actor-apps/app-web/src/app/components/activity/UserProfile.react.js | jamesbond12/actor-platform | /*
* Copyright (C) 2015 Actor LLC. <https://actor.im>
*/
import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classnames from 'classnames';
import ActorClient from 'utils/ActorClient';
import confirm from 'utils/confirm'
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import AvatarItem from 'components/common/AvatarItem.react';
import Fold from 'components/common/Fold.React';
const getStateFromStores = (userId) => {
const thisPeer = PeerStore.getUserPeer(userId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer)
};
};
@ReactMixin.decorate(IntlMixin) class UserProfile extends React.Component {
static propTypes = {
user: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = _.assign({
isActionsDropdownOpen: false
}, getStateFromStores(props.user.id));
DialogStore.addNotificationsListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.user.id));
}
addToContacts = () => {
ContactActionCreators.addContact(this.props.user.id);
};
removeFromContacts = () => {
const { user } = this.props;
const confirmText = 'You really want to remove ' + user.name + ' from your contacts?';
confirm(confirmText).then(
() => ContactActionCreators.removeContact(user.id)
);
};
onNotificationChange = (event) => {
const { thisPeer } = this.state;
DialogActionCreators.changeNotificationsEnabled(thisPeer, event.target.checked);
};
onChange = () => {
const { user } = this.props;
this.setState(getStateFromStores(user.id));
};
toggleActionsDropdown = () => {
const { isActionsDropdownOpen } = this.state;
if (!isActionsDropdownOpen) {
this.setState({isActionsDropdownOpen: true});
document.addEventListener('click', this.closeActionsDropdown, false);
} else {
this.closeActionsDropdown();
}
};
closeActionsDropdown = () => {
this.setState({isActionsDropdownOpen: false});
document.removeEventListener('click', this.closeActionsDropdown, false);
};
clearChat = (uid) => {
confirm('Do you really want to delete this conversation?').then(
() => {
const peer = ActorClient.getUserPeer(uid);
DialogActionCreators.clearChat(peer);
},
() => {
}
);
};
deleteChat = (uid) => {
confirm('Do you really want to delete this conversation?').then(
() => {
const peer = ActorClient.getUserPeer(uid);
DialogActionCreators.deleteChat(peer);
},
() => {
}
);
};
render() {
const { user } = this.props;
const { isNotificationsEnabled, isActionsDropdownOpen } = this.state;
const actions = (user.isContact === false) ? (
<li className="dropdown__menu__item" onClick={this.addToContacts}>
<FormattedMessage message={this.getIntlMessage('addToContacts')}/>
</li>
) : (
<li className="dropdown__menu__item" onClick={this.removeFromContacts}>
<FormattedMessage message={this.getIntlMessage('removeFromContacts')}/>
</li>
);
const dropdownClassNames = classnames('dropdown pull-left', {
'dropdown--opened': isActionsDropdownOpen
});
const about = user.about ? (
<div className="user_profile__meta__about">
{user.about}
</div>
) : null;
const nickname = user.nick ? (
<li>
<svg className="icon icon--pink"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#username"/>'}}/>
<span className="title">{user.nick}</span>
<span className="description">nickname</span>
</li>
) : null;
const email = user.email ? (
<li className="hide">
<i className="material-icons icon icon--blue">mail</i>
<span className="title">{user.email}</span>
<span className="description">email</span>
</li>
) : null;
const phone = user.phones[0] ? (
<li>
<i className="material-icons icon icon--green">call</i>
<span className="title">{'+' + user.phones[0].number}</span>
<span className="description">mobile</span>
</li>
) : null;
return (
<div className="activity__body user_profile">
<ul className="profile__list">
<li className="profile__list__item user_profile__meta">
<header>
<AvatarItem image={user.bigAvatar}
placeholder={user.placeholder}
size="large"
title={user.name}/>
<h3 className="user_profile__meta__title">{user.name}</h3>
<div className="user_profile__meta__presence">{user.presence}</div>
</header>
{about}
<footer>
<div className={dropdownClassNames}>
<button className="dropdown__button button button--flat" onClick={this.toggleActionsDropdown}>
<i className="material-icons">more_horiz</i>
<FormattedMessage message={this.getIntlMessage('actions')}/>
</button>
<ul className="dropdown__menu dropdown__menu--left">
{actions}
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={() => this.clearChat(user.id)}>
<FormattedMessage message={this.getIntlMessage('clearConversation')}/>
</li>
<li className="dropdown__menu__item dropdown__menu__item--light"
onClick={() => this.deleteChat(user.id)}>
<FormattedMessage message={this.getIntlMessage('deleteConversation')}/>
</li>
</ul>
</div>
</footer>
</li>
<li className="profile__list__item user_profile__contact_info no-p">
<ul className="user_profile__contact_info__list">
{nickname}
{phone}
{email}
</ul>
</li>
<li className="profile__list__item user_profile__media no-p hide">
<Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}>
<ul>
<li><a>230 Shared Photos and Videos</a></li>
<li><a>49 Shared Links</a></li>
<li><a>49 Shared Files</a></li>
</ul>
</Fold>
</li>
<li className="profile__list__item user_profile__notifications no-p">
<label htmlFor="notifications">
<i className="material-icons icon icon--squash">notifications_none</i>
<FormattedMessage message={this.getIntlMessage('notifications')}/>
<div className="switch pull-right">
<input checked={isNotificationsEnabled}
id="notifications"
onChange={this.onNotificationChange}
type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</label>
</li>
</ul>
</div>
);
}
}
export default UserProfile;
|
src/components/AdminSidebar.js | PickaxeCMS/pickaxecms | import React, { Component } from 'react';
import { connect } from 'react-redux'
import MediaQuery from 'react-responsive';
import { Sidebar, Menu, Image, Dropdown, Icon, Segment, Form, Button, Input, Header } from 'semantic-ui-react'
class AdminSidebar extends Component {
constructor(props) {
super(props);
this.handleEditingButton = this.handleEditingButton.bind(this);
this.handleSaveButton = this.handleSaveButton.bind(this);
this.handleNewDivisionButton = this.handleNewDivisionButton.bind(this);
this.handleNewPageButton = this.handleNewPageButton.bind(this);
this.handleAddNavButton = this.handleAddNavButton.bind(this);
this.handleRemoveNavButton = this.handleRemoveNavButton.bind(this);
this.handlesDeletePageClick = this.handlesDeletePageClick.bind(this);
this.state = {
userToken: null,
activePage: false,
isEditing: props.isEditing,
navItems:[]
};
}
handleEditingButton(event) {
event.preventDefault();
this.setState({isEditing: !this.state.isEditing})
this.props.handleEditingButton();
}
handleNewDivisionButton(event) {
event.preventDefault();
this.props.handleNewDivisionButton();
}
handleNewPageButton(event) {
event.preventDefault();
this.props.handleNewPageButton();
}
handleSaveButton(event) {
event.preventDefault();
this.setState({isEditing: !this.state.isEditing})
this.props.handleSaveButton();
}
handleAddNavButton(event) {
event.preventDefault();
this.props.handleAddNavButton();
}
handleRemoveNavButton(event) {
event.preventDefault();
this.props.handleRemoveNavButton();
}
handlesDeletePageClick(event) {
event.preventDefault();
this.props.handlesDeletePageClick();
}
componentWillMount(){
this.setState({navItems:this.props.divisionsBypage['site_plan'].navItems})
if(this.state.navItems[this.props.selectedPage] !== undefined){
this.setState({activePage: true})
}
else{
this.setState({activePage: false})
}
this.forceUpdate()
}
componentWillReceiveProps(nextProps){
this.setState({navItems:nextProps.divisionsBypage['site_plan'].navItems})
if(this.state.navItems[nextProps.selectedPage] !== undefined){
this.setState({activePage: true})
}
else{
this.setState({activePage: false})
}
this.forceUpdate()
}
render() {
return (
<Sidebar.Pushable as={Segment} style={{height:'100vh'}}>
<Sidebar as={Menu} animation='scale down' width='wide' visible={true} vertical inverted={process.env.REACT_APP_INVERTED}>
<Menu.Item style={{textAlign:'center'}}>
<h3 style={{marginTop: '0px', marginLeft:5, cursor:'pointer'}}>Site Configuration</h3>
</Menu.Item>
{
!this.state.editName
?
<Menu.Item name='app_name'>
<Form.Field inline>
<label style={{marginRight:10}}>App Name:</label>
<Input placeholder='App Name' defaultValue={process.env.REACT_APP_NAME} />
</Form.Field>
<div style={{textAlign:'center', marginTop:10}}>
<Button style={{display:'inline', width:'40%'}}>Cancel</Button>
<Button color='teal' style={{display:'inline', width:'40%'}}>Save</Button>
</div>
</Menu.Item>
:
<Menu.Item name='app_name'>
<Icon name='edit' />
<b style={{marginRight:10}}>Change App Name: </b> {process.env.REACT_APP_NAME}
</Menu.Item>
}
<Menu.Item name='app_logo'>
<Icon name='edit' />
<b style={{marginRight:10}}>Change App Logo:</b> <Image src={process.env.REACT_APP_LOGO} style={{width:20, display:'inline'}} />
</Menu.Item>
<Menu.Item name='app_font'>
<Icon name='edit' />
<b style={{marginRight:10}}>Change App Font:</b> current_app_font || Default
</Menu.Item>
{
!this.state.editName
?
<Menu.Item name='app_name'>
<div style={{textAlign:'center', marginTop:10}}>
<Button style={{display:'inline', width:'40%'}} onClick={()=> process.env.REACT_APP_INVERTED = true} color="black">Dark</Button>
<Button style={{display:'inline', width:'40%'}} onClick={()=> process.env.REACT_APP_INVERTED = false}>Light</Button>
</div>
</Menu.Item>
:
<Menu.Item name='app_font'>
<Icon name='edit' />
<b style={{marginRight:10}}>Invert App Theme:</b> current_app_theme || dark vs light
</Menu.Item>
}
</Sidebar>
<Sidebar.Pusher>
<Segment basic>
<Header as='h3'>Application Content</Header>
<Image src='/assets/images/wireframe/paragraph.png' />
</Segment>
</Sidebar.Pusher>
</Sidebar.Pushable>
);
}
}
const mapStateToProps = state => {
const { selectedPage, divisionsBypage } = state
return {
selectedPage,
divisionsBypage
}
}
export default connect(mapStateToProps)(AdminSidebar);
|
app/javascript/mastodon/features/ui/components/column.js | verniy6462/mastodon | import React from 'react';
import ColumnHeader from './column_header';
import PropTypes from 'prop-types';
import { debounce } from 'lodash';
import { scrollTop } from '../../../scroll';
import { isMobile } from '../../../is_mobile';
export default class Column extends React.PureComponent {
static propTypes = {
heading: PropTypes.string,
icon: PropTypes.string,
children: PropTypes.node,
active: PropTypes.bool,
hideHeadingOnMobile: PropTypes.bool,
};
handleHeaderClick = () => {
const scrollable = this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
handleScroll = debounce(() => {
if (typeof this._interruptScrollAnimation !== 'undefined') {
this._interruptScrollAnimation();
}
}, 200)
setRef = (c) => {
this.node = c;
}
render () {
const { heading, icon, children, active, hideHeadingOnMobile } = this.props;
const showHeading = heading && (!hideHeadingOnMobile || (hideHeadingOnMobile && !isMobile(window.innerWidth)));
const columnHeaderId = showHeading && heading.replace(/ /g, '-');
const header = showHeading && (
<ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} columnHeaderId={columnHeaderId} />
);
return (
<div
ref={this.setRef}
role='region'
aria-labelledby={columnHeaderId}
className='column'
onScroll={this.handleScroll}
>
{header}
{children}
</div>
);
}
}
|
addons/info/src/components/types/ObjectOf.js | rhalff/storybook | import React from 'react';
import PrettyPropType from './PrettyPropType';
import { TypeInfo, getPropTypes } from './proptypes';
const ObjectOf = ({ propType }) => (
<span>
{'{[<key>]: '}
<PrettyPropType propType={getPropTypes(propType)} />
{'}'}
</span>
);
ObjectOf.propTypes = {
propType: TypeInfo.isRequired,
};
export default ObjectOf;
|
src/applications/financial-status-report/pages/income/spouse/spouseInfo.js | department-of-veterans-affairs/vets-website | import React from 'react';
import AdditionalInfo from '@department-of-veterans-affairs/component-library/AdditionalInfo';
const MaritalStatusInfo = (
<AdditionalInfo triggerText="Why does my marital status matter?">
<p>
We want to make sure we understand your household’s financial situation.
</p>
<p>
If you’re married, we also need to understand your spouse’s financial
situation. This allows us to make a more informed decision regarding your
request.
</p>
</AdditionalInfo>
);
export const uiSchema = {
'ui:title': 'Your spouse information',
questions: {
isMarried: {
'ui:title': 'Are you married?',
'ui:widget': 'yesNo',
'ui:required': () => true,
'ui:errorMessages': {
required: 'Please select your marital status.',
},
},
},
'view:components': {
'view:maritalStatus': {
'ui:description': MaritalStatusInfo,
},
},
};
export const schema = {
type: 'object',
properties: {
questions: {
type: 'object',
properties: {
isMarried: {
type: 'boolean',
},
},
},
'view:components': {
type: 'object',
properties: {
'view:maritalStatus': {
type: 'object',
properties: {},
},
},
},
},
};
|
modules/gui/src/widget/form/input.js | openforis/sepal | import {Input, Textarea} from 'widget/input'
import {Subject, debounceTime, distinctUntilChanged} from 'rxjs'
import {compose} from 'compose'
import {getErrorMessage} from 'widget/form/error'
import {withFormContext} from 'widget/form/context'
import PropTypes from 'prop-types'
import React from 'react'
import withSubscriptions from 'subscription'
const DEBOUNCE_TIME_MS = 750
class _FormInput extends React.Component {
constructor(props) {
super(props)
const {addSubscription, onChangeDebounced} = props
this.change$ = new Subject()
addSubscription(
this.change$.pipe(
debounceTime(DEBOUNCE_TIME_MS),
distinctUntilChanged()
).subscribe(
value => onChangeDebounced && onChangeDebounced(value)
)
)
}
render() {
const {textArea} = this.props
return textArea ? this.renderTextArea() : this.renderInput()
}
renderInput() {
const {form, className, input, errorMessage, busyMessage, type, validate, tabIndex, onChange, onBlur, additionalButtons, ...props} = this.props
return (
<Input
{...props}
className={className}
type={type}
name={input && input.name}
value={typeof input.value === 'number' || typeof input.value === 'boolean' || input.value
? input.value
: ''
}
errorMessage={getErrorMessage(form, errorMessage === true ? input : errorMessage)}
busyMessage={busyMessage}
tabIndex={tabIndex}
additionalButtons={additionalButtons}
onChange={e => {
input.handleChange(e)
this.change$.next(e.target.value)
onChange && onChange(e)
validate === 'onChange' && input.validate()
}}
onBlur={e => {
onBlur && onBlur(e)
validate === 'onBlur' && input.validate()
}}
/>
)
}
renderTextArea() {
const {form, className, input, errorMessage, busyMessage, minRows, maxRows, validate, tabIndex, onChange, onBlur, ...props} = this.props
return (
<Textarea
{...props}
className={className}
name={input.name}
value={input.value || ''}
errorMessage={getErrorMessage(form, errorMessage === true ? input : errorMessage)}
busyMessage={busyMessage}
tabIndex={tabIndex}
minRows={minRows}
maxRows={maxRows}
onChange={e => {
input && input.handleChange(e)
onChange && onChange(e)
input && validate === 'onChange' && input.validate()
}}
onBlur={e => {
onBlur && onBlur(e)
input && validate === 'onBlur' && input.validate()
}}
/>
)
}
}
export const FormInput = compose(
_FormInput,
withFormContext(),
withSubscriptions()
)
FormInput.propTypes = {
input: PropTypes.object.isRequired,
additionalButtons: PropTypes.arrayOf(PropTypes.node),
autoCapitalize: PropTypes.any,
autoComplete: PropTypes.any,
autoCorrect: PropTypes.any,
autoFocus: PropTypes.any,
busyMessage: PropTypes.any,
className: PropTypes.string,
errorMessage: PropTypes.any,
inputTooltip: PropTypes.any,
inputTooltipPlacement: PropTypes.string,
label: PropTypes.string,
maxRows: PropTypes.number,
minRows: PropTypes.number,
placeholder: PropTypes.any,
spellCheck: PropTypes.any,
tabIndex: PropTypes.number,
textArea: PropTypes.any,
tooltip: PropTypes.any,
tooltipPlacement: PropTypes.string,
tooltipTrigger: PropTypes.string,
type: PropTypes.string,
validate: PropTypes.oneOf(['onChange', 'onBlur']),
onBlur: PropTypes.func,
onChange: PropTypes.func,
onChangeDebounced: PropTypes.func
}
FormInput.defaultProps = {
validate: 'onBlur'
}
|
samples/06.recomposing-ui/d.plain-ui/src/CardActionButton.js | billba/botchat | import React from 'react';
import ImBackButton from './ImBackButton';
import MessageBackButton from './MessageBackButton';
import PostBackButton from './PostBackButton';
// "cardAction" could be either, "imBack", "messageBack", or "postBack".
export default ({ cardAction }) => {
switch (cardAction.type) {
case 'messageBack':
return <MessageBackButton cardAction={cardAction} />;
case 'postBack':
return <PostBackButton cardAction={cardAction} />;
default:
return <ImBackButton cardAction={cardAction} />;
}
};
|
src/svg-icons/image/crop-original.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropOriginal = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14zm-5.04-6.71l-2.75 3.54-1.96-2.36L6.5 17h11l-3.54-4.71z"/>
</SvgIcon>
);
ImageCropOriginal = pure(ImageCropOriginal);
ImageCropOriginal.displayName = 'ImageCropOriginal';
ImageCropOriginal.muiName = 'SvgIcon';
export default ImageCropOriginal;
|
example/pages/searchbar/index.js | woshisbb43/coinMessageWechat | import React from 'react';
import Page from '../../component/page';
import SampleData from './nameDB';
import {
//main component
SearchBar,
//for display data
Panel,
PanelHeader,
PanelBody,
PanelFooter,
MediaBox,
MediaBoxHeader,
MediaBoxBody,
MediaBoxTitle,
MediaBoxDescription,
Cell,
CellBody,
CellFooter
} from '../../../build/packages';
const appMsgIcon = <img src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAHgAAAB4CAMAAAAOusbgAAAAeFBMVEUAwAD///+U5ZTc9twOww7G8MYwzDCH4YcfyR9x23Hw+/DY9dhm2WZG0kbT9NP0/PTL8sux7LFe115T1VM+zz7i+OIXxhes6qxr2mvA8MCe6J6M4oz6/frr+us5zjn2/fa67rqB4IF13XWn6ad83nxa1loqyirn+eccHxx4AAAC/klEQVRo3u2W2ZKiQBBF8wpCNSCyLwri7v//4bRIFVXoTBBB+DAReV5sG6lTXDITiGEYhmEYhmEYhmEYhmEY5v9i5fsZGRx9PyGDne8f6K9cfd+mKXe1yNG/0CcqYE86AkBMBh66f20deBc7wA/1WFiTwvSEpBMA2JJOBsSLxe/4QEEaJRrASP8EVF8Q74GbmevKg0saa0B8QbwBdjRyADYxIhqxAZ++IKYtciPXLQVG+imw+oo4Bu56rjEJ4GYsvPmKOAB+xlz7L5aevqUXuePWVhvWJ4eWiwUQ67mK51qPj4dFDMlRLBZTqF3SDvmr4BwtkECu5gHWPkmDfQh02WLxXuvbvC8ku8F57GsI5e0CmUwLz1kq3kD17R1In5816rGvQ5VMk5FEtIiWislTffuDpl/k/PzscdQsv8r9qWq4LRWX6tQYtTxvI3XyrwdyQxChXioOngH3dLgOFjk0all56XRi/wDFQrGQU3Os5t0wJu1GNtNKHdPqYaGYQuRDfbfDf26AGLYSyGS3ZAK4S8XuoAlxGSdYMKwqZKM9XJMtyqXi7HX/CiAZS6d8bSVUz5J36mEMFDTlAFQzxOT1dzLRljjB6+++ejFqka+mXIe6F59mw22OuOw1F4T6lg/9VjL1rLDoI9Xzl1MSYDNHnPQnt3D1EE7PrXjye/3pVpr1Z45hMUdcACc5NVQI0bOdS1WA0wuz73e7/5TNqBPhQXPEFGJNV2zNqWI7QKBd2Gn6AiBko02zuAOXeWIXjV0jNqdKegaE/kJQ6Bfs4aju04lMLkA2T5wBSYPKDGF3RKhFYEa6A1L1LG2yacmsaZ6YPOSAMKNsO+N5dNTfkc5Aqe26uxHpx7ZirvgCwJpWq/lmX1hA7LyabQ34tt5RiJKXSwQ+0KU0V5xg+hZrd4Bn1n4EID+WkQdgLfRNtvil9SPfwy+WQ7PFBWQz6dGWZBLkeJFXZGCfLUjCgGgqXo5TuSu3cugdcTv/HjqnBTEMwzAMwzAMwzAMwzAMw/zf/AFbXiOA6frlMAAAAABJRU5ErkJggg==" />
const CellMore = () => (
<Cell access link>
<CellBody>More</CellBody>
<CellFooter />
</Cell>
)
export default class SearchBarDemo extends React.Component {
state={
searchText: 'a',
results: []
};
handleChange(text, e){
let keywords = [text];
let results = SampleData.filter(/./.test.bind(new RegExp(keywords.join('|'),'i')));
if(results.length > 3) results = results.slice(0,3);
this.setState({
results,
searchText:text,
});
}
render() {
return (
<Page className="searchbar" title="SearchBar" subTitle="搜索栏">
<SearchBar
onChange={this.handleChange.bind(this)}
defaultValue={this.state.searchText}
placeholder="Female Name Search"
lang={{
cancel: 'Cancel'
}}
/>
<Panel style={{display: this.state.searchText ? null: 'none', marginTop: 0}}>
<PanelHeader>
Female Name Search
</PanelHeader>
<PanelBody>
{
this.state.results.length > 0 ?
this.state.results.map((item,i)=>{
return (
<MediaBox key={i} type="appmsg" href="javascript:void(0);">
<MediaBoxHeader>{appMsgIcon}</MediaBoxHeader>
<MediaBoxBody>
<MediaBoxTitle>{item}</MediaBoxTitle>
<MediaBoxDescription>
You may like this name.
</MediaBoxDescription>
</MediaBoxBody>
</MediaBox>
)
})
: <MediaBox>Can't find any!</MediaBox>
}
</PanelBody>
<PanelFooter href="javascript:void(0);">
<CellMore />
</PanelFooter>
</Panel>
</Page>
);
}
};
|
frontend/app_v2/src/common/icons/ForwardArrow.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
/**
* @summary ForwardArrow
* @component
*
* @param {object} props
*
* @returns {node} jsx markup
*/
function ForwardArrow({ styling }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className={styling}>
<title>ForwardArrow</title>
<g transform="translate(50 50) scale(-0.69 0.69) rotate(0) translate(-50 -50)">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className={styling}>
<g>
<g>
<path d="M5273.1,2400.1v-2c0-2.8-5-4-9.7-4s-9.7,1.3-9.7,4v2c0,1.8,0.7,3.6,2,4.9l5,4.9c0.3,0.3,0.4,0.6,0.4,1v6.4 c0,0.4,0.2,0.7,0.6,0.8l2.9,0.9c0.5,0.1,1-0.2,1-0.8v-7.2c0-0.4,0.2-0.7,0.4-1l5.1-5C5272.4,2403.7,5273.1,2401.9,5273.1,2400.1z M5263.4,2400c-4.8,0-7.4-1.3-7.5-1.8v0c0.1-0.5,2.7-1.8,7.5-1.8c4.8,0,7.3,1.3,7.5,1.8C5270.7,2398.7,5268.2,2400,5263.4,2400z" />
<path d="M5268.4,2410.3c-0.6,0-1,0.4-1,1c0,0.6,0.4,1,1,1h4.3c0.6,0,1-0.4,1-1c0-0.6-0.4-1-1-1H5268.4z" />
<path d="M5272.7,2413.7h-4.3c-0.6,0-1,0.4-1,1c0,0.6,0.4,1,1,1h4.3c0.6,0,1-0.4,1-1C5273.7,2414.1,5273.3,2413.7,5272.7,2413.7z" />
<path d="M5272.7,2417h-4.3c-0.6,0-1,0.4-1,1c0,0.6,0.4,1,1,1h4.3c0.6,0,1-0.4,1-1C5273.7,2417.5,5273.3,2417,5272.7,2417z" />
</g>
<path d="M97.5,88.7c0-22.6-21.8-53.7-49.4-58.8V11.3L2.5,45.1l45.6,33.8V60C67.4,62,84.6,71.2,97.5,88.7z" />
</g>
</svg>
</g>
</svg>
)
}
// PROPTYPES
const { string } = PropTypes
ForwardArrow.propTypes = {
styling: string,
}
export default ForwardArrow
|
cerberus-dashboard/src/components/LoginUserForm/LoginUserForm.js | Nike-Inc/cerberus | /*
* Copyright (c) 2020 Nike, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { reduxForm } from 'redux-form';
import { loginUser } from '../../actions/authenticationActions';
const formName = 'login-user-form';
/**
* Component used to authenticate users before to the dashboard.
*/
export const fields = ['username', 'password'];
const isValidEmailRegex = /^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i;
// define our client side form validation rules
const validate = values => {
const errors = {};
if (!values.username) {
errors.username = 'Required';
} else if (!isValidEmailRegex.test(values.username)) {
errors.username = 'Invalid email address';
}
if (!values.password) {
errors.password = 'Required';
}
return errors;
};
class LoginUserForm extends Component {
static propTypes = {
fields: PropTypes.object.isRequired,
handleSubmit: PropTypes.func.isRequired,
isAuthenticating: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired,
};
render() {
const { fields: { username, password }, handleSubmit, isAuthenticating, dispatch } = this.props;
return (
<form id={formName} onSubmit={handleSubmit(data => {
dispatch(loginUser(data.username, data.password));
})}>
<div id='email-div' className='ncss-form-group'>
<div className={((username.touched && username.error) ? 'ncss-input-container error' : 'ncss-input-container')}>
<label className='ncss-label'>Email</label>
<input type='text'
className='ncss-input pt2-sm pr4-sm pb2-sm pl4-sm'
placeholder='Please enter your email address'
{...username} />
{username.touched && username.error && <div className='ncss-error-msg'>{username.error}</div>}
</div>
</div>
<div id='pass-div' className='ncss-form-group'>
<div className={((password.touched && password.error) ? 'ncss-input-container error' : 'ncss-input-container')}>
<label className='ncss-label'>Password</label>
<input type='password'
className='ncss-input pt2-sm pr4-sm pb2-sm pl4-sm r'
placeholder='Please enter your password'
{...password} />
{password.touched && password.error && <div className='ncss-error-msg'>{password.error}</div>}
</div>
</div>
<div id='login-form-submit-container'>
<div id='fountainG' className={isAuthenticating ? 'show-me' : 'hide-me'}>
<div id='fountainG_1' className='fountainG'></div>
<div id='fountainG_2' className='fountainG'></div>
<div id='fountainG_3' className='fountainG'></div>
<div id='fountainG_4' className='fountainG'></div>
<div id='fountainG_5' className='fountainG'></div>
<div id='fountainG_6' className='fountainG'></div>
<div id='fountainG_7' className='fountainG'></div>
<div id='fountainG_8' className='fountainG'></div>
</div>
<div id="login-help">
<a target="_blank" href="/dashboard/help/index.html">Need help?</a>
</div>
<button id='login-btn'
className='ncss-btn-offwhite ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
disabled={isAuthenticating}>Login</button>
</div>
</form>
);
}
}
const mapStateToProps = state => ({
isAuthenticating: state.auth.isAuthenticating,
statusText: state.auth.statusText,
initialValues: {
redirectTo: state.router.location.query.next || '/'
}
});
const form = reduxForm(
{
form: formName,
fields: fields,
validate
}
)(LoginUserForm);
export default connect(mapStateToProps)(form); |
src/pages/User/components/PullRequests/UserShare.js | jenkoian/hacktoberfest-checker | import React from 'react';
const UserShare = () => {
Tw();
Fb();
return <div id="fb-root"></div>;
};
function Tw() {
window.twttr = (function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0],
t = window.twttr || {};
if (d.getElementById(id)) return t;
js = d.createElement(s);
js.id = id;
js.src = 'https://platform.twitter.com/widgets.js';
fjs.parentNode.insertBefore(js, fjs);
t._e = [];
t.ready = function (f) {
t._e.push(f);
};
return t;
})(document, 'script', 'twitter-wjs');
}
function Fb() {
(function (d, s, id) {
var js,
fjs = d.getElementsByTagName(s)[0];
if (d.getElementById(id)) return;
js = d.createElement(s);
js.id = id;
js.src = '//connect.facebook.net/en_US/sdk.js#xfbml=1&version=v2.10';
fjs.parentNode.insertBefore(js, fjs);
})(document, 'script', 'facebook-jssdk');
}
export default UserShare;
|
src/components/list_items.js | blanck-space/reacTube | import React from 'react';
const VListItem = (props) => {
return(
<li onClick={()=>props.onItemClick(props.video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={props.video.snippet.thumbnails.default.url} />
</div>
<div className="media-body">
<div className = "media-heading">{props.video.snippet.title}</div>
</div>
</div>
</li>
);
};
export default VListItem;
|
app/static/index.js | Murdius/GW2Snapshot | import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware, compose } from 'redux';
import { Provider } from 'react-redux';
import App from './components/App.jsx';
import createLogger from 'redux-logger';
import thunkMiddleware from 'redux-thunk';
import reducer from './reducers';
const loggerMiddleware = createLogger()
const composeEnhancers = window.__REDUX_DEVTOOLS_EXTENSION_COMPOSE__ || compose;
const store = createStore(reducer, composeEnhancers(
applyMiddleware(thunkMiddleware, loggerMiddleware)
));
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('form')
)
|
packages/metadata-react/src/TabularSection/TabularSection.js | oknosoft/metadata.js | import React from 'react';
import PropTypes from 'prop-types';
import MComponent from '../common/MComponent';
import TabularSectionToolbar from './TabularSectionToolbar';
import SchemeSettingsTabs from '../SchemeSettings/SchemeSettingsTabs';
import LoadingMessage from '../DumbLoader/LoadingMessage';
import ReactDataGrid from 'metadata-external/react-data-grid.min';
import AutoSizer from 'react-virtualized/dist/es/AutoSizer';
const cmpType = PropTypes.oneOfType([PropTypes.object, PropTypes.array]);
export default class TabularSection extends MComponent {
static propTypes = {
_obj: PropTypes.object.isRequired,
_tabular: PropTypes.string.isRequired,
_meta: PropTypes.object,
scheme: PropTypes.object, // Вариант настроек
read_only: PropTypes.bool, // Элемент только для чтения
hideToolbar: PropTypes.bool, // Указывает не выводить toolbar
denyAddDel: PropTypes.bool, // Запрет добавления и удаления строк (скрывает кнопки в панели, отключает обработчики)
denyReorder: PropTypes.bool, // Запрет изменения порядка строк
minHeight: PropTypes.number,
btns: cmpType, // дополнительные кнопки
menu_items: cmpType, // дополнительные пункты меню
handleValueChange: PropTypes.func, // Обработчик изменения значения в ячейке
handleRowChange: PropTypes.func, // При окончании редактирования строки
handleCustom: PropTypes.func, // Внешний дополнительный подключаемый обработчик
rowSelection: PropTypes.object, // Настройка пометок строк
selectedIds: PropTypes.array,
onCellSelected: PropTypes.func,
onRowUpdated: PropTypes.func,
};
static defaultProps = {
denyAddDel: false,
read_only: false,
minHeight: 220,
};
constructor(props, context) {
super(props, context);
this.handleObjChange(props, true);
}
shouldComponentUpdate(props, {_tabular}){
if(_tabular._owner != props._obj){
this.handleObjChange(props);
return false;
}
return true;
}
handleObjChange(props, init) {
const {_obj, _tabular} = props;
const state = {
_meta: props._meta || _obj._metadata(_tabular),
_tabular: _obj[_tabular],
_columns: [],
selectedIds: props.rowSelection ? props.rowSelection.selectBy.keys.values : [],
settings_open: false,
};
if(init){
this.state = state;
}
else{
this.setState(state);
}
if(props.scheme) {
this.handleSchemeChange(props.scheme)
}
else {
$p.cat.scheme_settings.get_scheme(_obj._manager.class_name + '.' + _tabular).then(this.handleSchemeChange);
}
}
getRows() {
const {scheme, _tabular} = this.state;
return scheme ? scheme.filter(_tabular) : [];
}
rowsCount() {
return this.getRows().length;
}
rowGetter = (i) => {
return this.getRows()[i];
};
handleRemove = () => {
const {state: {_tabular}, _grid: {state}} = this;
const {selected} = state;
if(selected && selected.hasOwnProperty('rowIdx')) {
_tabular.del(selected.rowIdx);
this.forceUpdate();
}
};
handleClear = () => {
const {_tabular} = this.state;
if(_tabular) {
_tabular.clear();
this.forceUpdate();
}
};
handleAdd = () => {
const {_tabular} = this.state;
if(_tabular) {
_tabular.add();
this.forceUpdate();
}
};
handleUp = () => {
const {state: {_tabular}, _grid: {state}} = this;
const {selected} = state;
if(selected && selected.hasOwnProperty('rowIdx') && selected.rowIdx > 0) {
_tabular.swap(selected.rowIdx, selected.rowIdx - 1);
selected.rowIdx = selected.rowIdx - 1;
this.forceUpdate();
}
};
handleDown = () => {
const {state: {_tabular}, _grid: {state}} = this;
const {selected} = state;
if(selected && selected.hasOwnProperty('rowIdx') && selected.rowIdx < _tabular.count() - 1) {
_tabular.swap(selected.rowIdx, selected.rowIdx + 1);
selected.rowIdx = selected.rowIdx + 1;
this.forceUpdate();
}
};
handleRowUpdated = (e) => {
//merge updated row with current row and rerender by setting state
const row = this.rowGetter(e.rowIdx);
if(row){
if(this.props.onRowUpdated){
if(this.props.onRowUpdated(e, row) === false){
return;
}
}
Object.assign(row._row || row, e.updated);
}
}
handleSettingsOpen = () => {
this.setState({settings_open: true});
};
handleSettingsClose = () => {
this.setState({settings_open: false});
};
// обработчик при изменении настроек компоновки
handleSchemeChange = (scheme) => {
const {props, state} = this;
const _columns = scheme.rx_columns({
mode: 'ts',
fields: state._meta.fields,
_obj: props._obj
});
if(this._mounted) {
this.setState({scheme, _columns});
}
else {
Object.assign(state, {scheme, _columns});
}
};
onRowsSelected = (rows) => {
const {props, state} = this;
const {keys} = props.rowSelection.selectBy;
this.setState({
selectedIds: state.selectedIds.concat(
rows.map(r => {
if(keys.markKey) {
r.row[keys.markKey] = true;
}
return r.row[keys.rowKey];
}))
});
};
onRowsDeselected = (rows) => {
const {keys} = this.props.rowSelection.selectBy;
let rowIds = rows.map(r => {
if(keys.markKey) {
r.row[keys.markKey] = false;
}
return r.row[keys.rowKey];
});
this.setState({
selectedIds: this.state.selectedIds.filter(i => rowIds.indexOf(i) === -1)
});
};
render() {
const {props, state, rowGetter, onRowsSelected, onRowsDeselected, handleRowUpdated} = this;
const {_meta, _tabular, _columns, scheme, selectedIds, settings_open} = state;
const {_obj, rowSelection, minHeight, hideToolbar, onCellSelected, classes, denyAddDel, denyReorder, btns, end_btns, menu_items} = props;
const Toolbar = props.Toolbar || TabularSectionToolbar;
if(!_columns || !_columns.length) {
if(!scheme) {
return <LoadingMessage text="Чтение настроек компоновки..."/>;
}
return <LoadingMessage text="Ошибка настроек компоновки..."/>;
}
if(rowSelection) {
rowSelection.onRowsSelected = onRowsSelected;
rowSelection.onRowsDeselected = onRowsDeselected;
rowSelection.selectBy.keys.values = selectedIds;
}
return (
<AutoSizer>
{({width, height}) => {
const show_grid = !settings_open || Math.max(minHeight, height) > 372;
return [
!hideToolbar && <Toolbar
key="toolbar"
width={width}
_obj={_obj}
_tabular={_tabular}
_columns={_columns}
scheme={scheme}
settings_open={settings_open}
denyAddDel={denyAddDel}
denyReorder={denyReorder}
btns={btns}
end_btns={end_btns}
menu_items={menu_items}
handleSettingsOpen={this.handleSettingsOpen}
handleSettingsClose={this.handleSettingsClose}
handleSchemeChange={this.handleSchemeChange}
handleAdd={this.handleAdd}
handleRemove={this.handleRemove}
handleClear={this.handleClear}
handleUp={this.handleUp}
handleDown={this.handleDown}
handleCustom={props.handleCustom}
/>,
settings_open && <SchemeSettingsTabs
key="schemesettings"
height={show_grid ? 272 : Math.max(minHeight, height)}
scheme={scheme}
handleSchemeChange={this.handleSchemeChange}
/>,
<ReactDataGrid
key="grid"
minWidth={width}
minHeight={Math.max(minHeight, height) - (hideToolbar ? 2 : 52) - (settings_open ? 320 : 0)}
rowHeight={33}
ref={(el) => this._grid = el}
columns={_columns}
enableCellSelect={true}
rowGetter={rowGetter}
rowsCount={this.rowsCount()}
rowSelection={rowSelection}
onRowUpdated={handleRowUpdated}
onCellSelected={onCellSelected}
/>
];
}}
</AutoSizer>
);
}
}
|
packages/material-ui-icons/src/DoNotDisturbAlt.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M12 2C6.5 2 2 6.5 2 12s4.5 10 10 10 10-4.5 10-10S17.5 2 12 2zM4 12c0-4.4 3.6-8 8-8 1.8 0 3.5.6 4.9 1.7L5.7 16.9C4.6 15.5 4 13.8 4 12zm8 8c-1.8 0-3.5-.6-4.9-1.7L18.3 7.1C19.4 8.5 20 10.2 20 12c0 4.4-3.6 8-8 8z" /></g>
, 'DoNotDisturbAlt');
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestParameters.js | ro-savage/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load({ id = 0, ...rest }) {
return [
{ id: id + 1, name: '1' },
{ id: id + 2, name: '2' },
{ id: id + 3, name: '3' },
rest.user,
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load({ id: 0, user: { id: 42, name: '42' } });
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-rest-parameters">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
src/svg-icons/image/straighten.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageStraighten = (props) => (
<SvgIcon {...props}>
<path d="M21 6H3c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2zm0 10H3V8h2v4h2V8h2v4h2V8h2v4h2V8h2v4h2V8h2v8z"/>
</SvgIcon>
);
ImageStraighten = pure(ImageStraighten);
ImageStraighten.displayName = 'ImageStraighten';
ImageStraighten.muiName = 'SvgIcon';
export default ImageStraighten;
|
app/admin/actions/AddSkill.js | in42/internship-portal | import React, { Component } from 'react';
import axios from 'axios';
import { Form, Button, Divider } from 'semantic-ui-react';
import PropTypes from 'prop-types';
import Auth from '../../auth/modules/Auth';
const addSkill = skill => axios.post('/api/admin/add-skills', skill, {
headers: {
Authorization: `bearer ${Auth.getToken()}`,
},
})
.then(res => res);
class AddSkill extends Component {
constructor() {
super();
this.state = { newSkill: '' };
this.handleAdd = () => {
console.log('new skill', this.state.newSkill);
const temp = { name: this.state.newSkill };
addSkill(temp)
.then((res) => {
console.log(res);
this.props.refreshSkillList();
this.setState({ newSkill: '' });
})
.catch(console.error());
};
this.handleChange = (e, { name, value }) => this.setState({ [name]: value });
}
render() {
return (
<div className="addSkillBar" >
<Form>
<Divider />
<Form.Group>
<Form.Input name="newSkill" value={this.state.newSkill} onChange={this.handleChange} width={16} placeholder="Add new skill here eg: Software Development" />
<Form.Button onClick={this.handleAdd} floated="right" content="Add" />
</Form.Group>
<Divider />
</Form>
</div>
);
}
}
AddSkill.prototypes = {
refreshSkillList: PropTypes.func.isRequired,
};
export default AddSkill;
|
src/index.js | RUTH2013/gallery-by-react | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/device/add-alarm.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceAddAlarm = (props) => (
<SvgIcon {...props}>
<path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/>
</SvgIcon>
);
DeviceAddAlarm = pure(DeviceAddAlarm);
DeviceAddAlarm.displayName = 'DeviceAddAlarm';
DeviceAddAlarm.muiName = 'SvgIcon';
export default DeviceAddAlarm;
|
test/dialog-spec.js | tomrosier/material-ui | import React from 'react';
import Dialog from 'dialog';
import {spy} from 'sinon';
import TestUtils from 'react-addons-test-utils';
describe('Dialog', () => {
it('appends a dialog to the document body', () => {
const testClass = 'test-dialog-class';
TestUtils.renderIntoDocument(
<Dialog
open={true}
contentClassName={testClass}
/>
);
const dialogEl = document.getElementsByClassName(testClass)[0];
expect(dialogEl).to.be.ok;
});
it('registers events on dialog actions', () => {
const clickSpy = spy();
const testClass = 'dialog-action';
TestUtils.renderIntoDocument(
<Dialog
open={true}
actions={[
<button
key="a"
onClick={clickSpy}
className={testClass}
>
test
</button>,
]}
/>
);
const actionEl = document.getElementsByClassName(testClass)[0];
expect(actionEl).to.be.ok;
TestUtils.Simulate.click(actionEl);
expect(clickSpy.called).to.be.ok;
});
});
|
frontend/src/login.js | rarellano/socializa | import React from 'react';
import { hashHistory, Link } from 'react-router'
import $ from 'jquery';
import API from './api';
import { login } from './auth';
import { translate, Interpolate } from 'react-i18next';
import i18n from './i18n';
class Login extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {
var self = this;
var q = this.getQueryParams();
if (q.token) {
self.authWithToken(q.token, q.email);
} else {
API.oauth2apps()
.then(function(resp) {
self.setState({
gapp: resp.google,
fapp: resp.facebook,
tapp: resp.twitter
});
});
}
}
getQueryParams = () => {
var qs = document.location.search;
qs = qs.split('+').join(' ');
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
return params;
}
authWithToken(token, email) {
login(email, token, 'token');
hashHistory.push('/map');
document.location.search = '';
}
emailChange = (e) => {
this.setState({email: e.target.value});
}
passChange = (e) => {
this.setState({password: e.target.value});
}
state = {
email: '', password: '',
gapp: null, tapp: null, fapp: null
}
login = (e) => {
var email = this.state.email;
var password = this.state.password;
return API.login(email, password)
.then(function(resp) {
login(email, resp.token, 'token');
hashHistory.push('/map');
}).catch(function(error) {
alert(error);
});
}
googleAuth = (e) => {
var self = this;
var redirect = encodeURIComponent('https://socializa.wadobo.com/oauth2callback/');
var gapp = this.state.gapp;
var guri = 'https://accounts.google.com/o/oauth2/v2/auth?scope=email%20profile&response_type=token&client_id='+gapp;
guri += '&redirect_uri='+redirect;
guri += '&state='+location.href;
if (window.HOST != '') {
this.win = window.open(guri, '_blank', 'location=no');
} else {
location.href = guri;
}
function loadCallBack(ev) {
var qs = ev.url;
qs = qs.split('+').join(' ');
if (!qs.includes('oauth2redirect')) {
return;
}
var params = {},
tokens,
re = /[?&]?([^=]+)=([^&]*)/g;
while (tokens = re.exec(qs)) {
params[decodeURIComponent(tokens[1])] = decodeURIComponent(tokens[2]);
}
if (params.token) {
self.authWithToken(params.token, params.email);
}
self.win.close();
}
if (this.win) {
this.win.addEventListener('loadstart', loadCallBack);
}
}
render() {
const { t } = this.props;
return (
<div id="login" className="container">
<div className="header text-center">
<img src="app/images/icon.png" className="logo" alt="logo"/><br/>
<h1>Socializa</h1>
</div>
<form className="form">
<input className="form-control" type="email" id="email" name="email" placeholder={t('login:email')} value={ this.state.email } onChange={ this.emailChange }/>
<input className="form-control" type="password" id="password" name="password" placeholder={t('login:password')} value={ this.state.password } onChange={ this.passChange }/>
</form>
<Link to="/register">{t('login:New account')}</Link>
<hr/>
<div className="social row text-center">
<div className="col-xs-4">
<a href="#" className="btn btn-primary btn-circle">
<i className="fa fa-facebook" aria-hidden="true"></i>
</a>
</div>
<div className="col-xs-4">
<a href="#" className="btn btn-info btn-circle">
<i className="fa fa-twitter" aria-hidden="true"></i>
</a>
</div>
<div className="col-xs-4">
{ this.state.gapp ? (
<a onClick={ this.googleAuth } className="btn btn-danger btn-circle">
<i className="fa fa-google-plus" aria-hidden="true"></i>
</a> )
: (<span></span>) }
</div>
</div>
<hr/>
<button className="btn btn-fixed-bottom btn-success" onClick={ this.login }>{t('login:Login')}</button>
</div>
);
}
}
export default translate(['login'], { wait: true })(Login);
|
client/modules/App/components/Footer/Footer.js | ArthurGerbelot/keystamp-mern | import React from 'react';
import { FormattedMessage } from 'react-intl';
// Import Style
import styles from './Footer.css';
// Import Images
import bg from '../../header-bk.png';
export function Footer() {
return (
<div style={{ background: `#FFF url(${bg}) center` }} className={styles.footer}>
<p>© 2016 · Hashnode · LinearBytes Inc.</p>
<p><FormattedMessage id="twitterMessage" /> : <a href="https://twitter.com/@mern_io" target="_Blank">@mern_io</a></p>
</div>
);
}
export default Footer;
|
docs/app/Examples/elements/Header/Variations/HeaderBlockExample.js | jamiehill/stardust | import React from 'react'
import { Header } from 'stardust'
const HeaderBlockExample = () => (
<Header as='h3' block>
Block Header
</Header>
)
export default HeaderBlockExample
|
analysis/rogueassassination/src/modules/features/Checklist/Module.js | yajinni/WoWAnalyzer | import { ComboPointDetails, EnergyCapTracker, EnergyDetails } from '@wowanalyzer/rogue';
import React from 'react';
import BaseChecklist from 'parser/shared/modules/features/Checklist/Module';
import CastEfficiency from 'parser/shared/modules/CastEfficiency';
import Combatants from 'parser/shared/modules/Combatants';
import PreparationRuleAnalyzer from 'parser/shared/modules/features/Checklist/PreparationRuleAnalyzer';
import GarroteUptime from '../../spells/GarroteUptime';
import RuptureUptime from '../../spells/RuptureUptime';
import EarlyDotRefresh from '../../spells/EarlyDotRefresh';
import Blindside from '../../talents/Blindside';
import Subterfuge from '../../talents/Subterfuge';
import Component from './Component';
import GarroteSnapshot from '../GarroteSnapshot';
import RuptureSnapshot from '../RuptureSnapshot';
import Nightstalker from '../../talents/Nightstalker';
import MasterAssassin from '../../talents/MasterAssassin';
class Checklist extends BaseChecklist {
static dependencies = {
combatants: Combatants,
castEfficiency: CastEfficiency,
preparationRuleAnalyzer: PreparationRuleAnalyzer,
garroteUptime: GarroteUptime,
ruptureUptime: RuptureUptime,
earlyDotRefresh: EarlyDotRefresh,
blindside: Blindside,
energyDetails: EnergyDetails,
energyCapTracker: EnergyCapTracker,
comboPointDetails: ComboPointDetails,
subterfuge: Subterfuge,
nightstalker: Nightstalker,
masterAssassin: MasterAssassin,
garroteSnapshot: GarroteSnapshot,
ruptureSnapshot: RuptureSnapshot,
};
render() {
return (
<Component
combatant={this.combatants.selected}
castEfficiency={this.castEfficiency}
thresholds={{
...this.preparationRuleAnalyzer.thresholds,
garroteUptime: this.garroteUptime.suggestionThresholds,
ruptureUptime: this.ruptureUptime.suggestionThresholds,
garroteEfficiency: this.earlyDotRefresh.suggestionThresholdsGarroteEfficiency,
ruptureEfficiency: this.earlyDotRefresh.suggestionThresholdsRuptureEfficiency,
blindsideEfficiency: this.blindside.suggestionThresholds,
energyEfficiency: this.energyDetails.suggestionThresholds,
energyCapEfficiency: this.energyCapTracker.suggestionThresholds,
comboPointEfficiency: this.comboPointDetails.suggestionThresholds,
subterfugeEfficiency: this.subterfuge.suggestionThresholds,
nightstalkerEfficiency: this.nightstalker.suggestionThresholds,
nightstalkerOpenerEfficiency: this.nightstalker.suggestionThresholdsOpener,
masterAssassinEfficiency: this.masterAssassin.suggestionThresholds,
ruptureSnapshotEfficiency: this.ruptureSnapshot.suggestionThresholds,
garroteSnapshotEfficiency: this.garroteSnapshot.suggestionThresholds,
}}
/>
);
}
}
export default Checklist;
|
client/src/pages/Product.js | ccwukong/lfcommerce-react | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Breadcrumb, BreadcrumbItem, Button, Row, Col } from 'reactstrap';
import { withRouter } from 'react-router-dom';
import jwt from 'jsonwebtoken';
import { FormattedMessage } from 'react-intl';
import ProductForm from './product/ProductForm';
import { FormContext } from './contexts';
import config from '../config';
class Product extends Component {
render() {
const {
history,
match: {
path,
params: { id },
},
} = this.props;
const {
data: { storeId },
} = jwt.decode(localStorage.getItem(config.accessTokenKey));
return (
<FormContext.Provider value={{ storeId, id }}>
<div className="page-navbar">
<div className="page-name">
<FormattedMessage id="sys.product" />
</div>
<Breadcrumb>
<BreadcrumbItem>
<Button color="link" onClick={() => history.push('/dashboard')}>
<FormattedMessage id="sys.dashboard" />
</Button>
</BreadcrumbItem>
<BreadcrumbItem>
<Button color="link" onClick={() => history.push('/products')}>
<FormattedMessage id="sys.products" />
</Button>
</BreadcrumbItem>
<BreadcrumbItem active>
<FormattedMessage id="sys.product" />
</BreadcrumbItem>
</Breadcrumb>
</div>
<div className="content-body">
<Row>
<Col md={12}>
<ProductForm mode={path === '/new-product' ? 'new' : 'update'} />
</Col>
</Row>
</div>
</FormContext.Provider>
);
}
}
Product.propTypes = {
history: PropTypes.object.isRequired,
match: PropTypes.object.isRequired,
};
export default withRouter(Product);
|
src/views/auth/index.js | foysalit/react-mcq | import React, { Component } from 'react';
import AuthSignin from './signin';
import AuthSignup from './signup';
import AuthStore from '../../stores/auth';
import AppActions from '../../actions/app';
import { Paper } from 'material-ui';
export class Auth extends Component {
constructor(props) {
super(props);
}
_authChanged () {
const { location, history } = this.props
// console.log(AuthStore.isLoggedIn());
if (!AuthStore.isLoggedIn())
return;
if (location.state && location.state.nextPathname) {
history.replaceState(null, location.state.nextPathname);
} else {
history.replaceState(null, '/exams');
}
}
componentDidMount() {
AuthStore.addChangeListener(this._authChanged.bind(this));
}
componentWillUnmount() {
AuthStore.removeChangeListener(this._authChanged.bind(this));
}
render() {
const style = {
width: '30%',
margin: '0 auto'
};
return (
<Paper style={style}>
{ this.props.children }
</Paper>
);
}
}
export {Auth, AuthSignin, AuthSignup};
|
client/routes.js | jozecarlos/bloodonors | /* eslint-disable global-require */
import React from 'react';
import { Route } from 'react-router';
import Container from './modules/home/';
// require.ensure polyfill for node
if (typeof require.ensure !== 'function') {
require.ensure = function requireModule(deps, callback) {
callback(require);
};
}
/* Workaround for async react routes to work with react-hot-reloader till
https://github.com/reactjs/react-router/issues/2182 and
https://github.com/gaearon/react-hot-loader/issues/288 is fixed.
*/
if (process.env.NODE_ENV !== 'production') {
// Require async routes only in development for react-hot-reloader to work.
// require('./modules/Post/pages/PostListPage/PostListPage');
// require('./modules/Post/pages/PostDetailPage/PostDetailPage');
}
// react-router setup with code-splitting
// More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/
export default (
<Route exact path="/" component={Container} />
);
|
app/javascript/mastodon/components/load_more.js | mosaxiv/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
export default class LoadMore extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
disabled: PropTypes.bool,
visible: PropTypes.bool,
}
static defaultProps = {
visible: true,
}
render() {
const { disabled, visible } = this.props;
return (
<button className='load-more' disabled={disabled || !visible} style={{ visibility: visible ? 'visible' : 'hidden' }} onClick={this.props.onClick}>
<FormattedMessage id='status.load_more' defaultMessage='Load more' />
</button>
);
}
}
|
src/svg-icons/image/wb-auto.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageWbAuto = (props) => (
<SvgIcon {...props}>
<path d="M6.85 12.65h2.3L8 9l-1.15 3.65zM22 7l-1.2 6.29L19.3 7h-1.6l-1.49 6.29L15 7h-.76C12.77 5.17 10.53 4 8 4c-4.42 0-8 3.58-8 8s3.58 8 8 8c3.13 0 5.84-1.81 7.15-4.43l.1.43H17l1.5-6.1L20 16h1.75l2.05-9H22zm-11.7 9l-.7-2H6.4l-.7 2H3.8L7 7h2l3.2 9h-1.9z"/>
</SvgIcon>
);
ImageWbAuto = pure(ImageWbAuto);
ImageWbAuto.displayName = 'ImageWbAuto';
ImageWbAuto.muiName = 'SvgIcon';
export default ImageWbAuto;
|
src/parser/monk/windwalker/modules/talents/Serenity.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import Statistic from 'interface/statistics/Statistic';
import { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import SpellIcon from 'common/SpellIcon';
import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText/index';
import SPELLS from 'common/SPELLS';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import { ABILITIES_AFFECTED_BY_DAMAGE_INCREASES } from 'parser/monk/windwalker/constants';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import { formatNumber, formatPercentage } from 'common/format';
const DAMAGE_MULTIPLIER = 0.2;
class Serenity extends Analyzer {
static dependencies = {
spellUsable: SpellUsable,
};
damageGain = 0;
effectiveRisingSunKickReductionMs = 0;
effectiveFistsOfFuryReductionMs = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SERENITY_TALENT.id);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.RISING_SUN_KICK), this.onRSK);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.FISTS_OF_FURY_CAST), this.onFoF);
this.addEventListener(Events.applybuff.by(SELECTED_PLAYER).spell(SPELLS.SERENITY_TALENT), this.onSerenityStart);
this.addEventListener(Events.removebuff.by(SELECTED_PLAYER).spell(SPELLS.SERENITY_TALENT), this.onSerenityEnd);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(ABILITIES_AFFECTED_BY_DAMAGE_INCREASES), this.onAffectedDamage);
}
_reduceRSK() {
if (this.spellUsable.isOnCooldown(SPELLS.RISING_SUN_KICK.id)) {
const cooldownReduction = (this.spellUsable.cooldownRemaining(SPELLS.RISING_SUN_KICK.id)) * 0.5;
this.spellUsable.reduceCooldown(SPELLS.RISING_SUN_KICK.id, cooldownReduction);
this.effectiveRisingSunKickReductionMs += cooldownReduction;
}
}
_reduceFoF() {
if (this.spellUsable.isOnCooldown(SPELLS.FISTS_OF_FURY_CAST.id)) {
const cooldownReduction = (this.spellUsable.cooldownRemaining(SPELLS.FISTS_OF_FURY_CAST.id)) * 0.5;
this.spellUsable.reduceCooldown(SPELLS.FISTS_OF_FURY_CAST.id, cooldownReduction);
this.effectiveFistsOfFuryReductionMs += cooldownReduction;
}
}
onRSK() {
if (this.selectedCombatant.hasBuff(SPELLS.SERENITY_TALENT.id)){
this._reduceRSK();
}
}
onFoF() {
if (this.selectedCombatant.hasBuff(SPELLS.SERENITY_TALENT.id)){
this._reduceFoF();
}
}
onSerenityStart() {
this._reduceRSK();
this._reduceFoF();
}
onSerenityEnd() {
if (this.spellUsable.isOnCooldown(SPELLS.RISING_SUN_KICK.id)) {
const cooldownExtension = (this.spellUsable.cooldownRemaining(SPELLS.RISING_SUN_KICK.id));
this.spellUsable.extendCooldown(SPELLS.RISING_SUN_KICK.id, cooldownExtension);
this.effectiveRisingSunKickReductionMs -= cooldownExtension;
}
if (this.spellUsable.isOnCooldown(SPELLS.FISTS_OF_FURY_CAST.id)) {
const cooldownExtension = (this.spellUsable.cooldownRemaining(SPELLS.FISTS_OF_FURY_CAST.id));
this.spellUsable.extendCooldown(SPELLS.FISTS_OF_FURY_CAST.id, cooldownExtension);
this.effectiveFistsOfFuryReductionMs -= cooldownExtension;
}
}
onAffectedDamage(event) {
if (!this.selectedCombatant.hasBuff(SPELLS.SERENITY_TALENT.id)) {
return;
}
this.damageGain += calculateEffectiveDamage(event, DAMAGE_MULTIPLIER);
}
get dps() {
return this.damageGain / this.owner.fightDuration * 1000;
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.CORE(3)}
size="flexible"
tooltip={(
<>
Total damage increase: {formatNumber(this.damageGain)}.
<br />
The damage increase is calculated from the {formatPercentage(DAMAGE_MULTIPLIER)}% damage bonus and doesn't count raw damage from extra casts gained from cooldown reduction.
</>
)}
>
<BoringSpellValueText spell={SPELLS.SERENITY_TALENT}>
<img
src="/img/sword.png"
alt="Damage"
className="icon"
/> {formatNumber(this.dps)} DPS <small>{formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.damageGain))} % of total</small>
<span style={{ fontsize: '75%' }}>
<SpellIcon
id={SPELLS.RISING_SUN_KICK.id}
style={{
height: '1.3em',
marginTop: '-1.em',
}}
/> {(this.effectiveRisingSunKickReductionMs / 1000).toFixed(1)} <small>Seconds reduced</small>
<br />
<SpellIcon
id={SPELLS.FISTS_OF_FURY_CAST.id}
style={{
height: '1.3em',
marginTop: '-1.em',
}}
/> {(this.effectiveFistsOfFuryReductionMs / 1000).toFixed(1)} <small>Seconds reduced</small>
</span>
</BoringSpellValueText>
</Statistic>
);
}
}
export default Serenity;
|
node_modules/react-native-maps/lib/components/MapPolygon.js | RahulDesai92/PHR | import PropTypes from 'prop-types';
import React from 'react';
import {
ViewPropTypes,
} from 'react-native';
import decorateMapComponent, {
USES_DEFAULT_IMPLEMENTATION,
SUPPORTED,
} from './decorateMapComponent';
const propTypes = {
...ViewPropTypes,
/**
* An array of coordinates to describe the polygon
*/
coordinates: PropTypes.arrayOf(PropTypes.shape({
/**
* Latitude/Longitude coordinates
*/
latitude: PropTypes.number.isRequired,
longitude: PropTypes.number.isRequired,
})),
/**
* An array of array of coordinates to describe the polygon holes
*/
holes: PropTypes.arrayOf(PropTypes.arrayOf(PropTypes.shape({
/**
* Latitude/Longitude coordinates
*/
latitude: PropTypes.number.isRequired,
longitude: PropTypes.number.isRequired,
}))),
/**
* Callback that is called when the user presses on the polygon
*/
onPress: PropTypes.func,
/**
* Boolean to allow a polygon to be tappable and use the
* onPress function
*/
tappable: PropTypes.bool,
/**
* The stroke width to use for the path.
*/
strokeWidth: PropTypes.number,
/**
* The stroke color to use for the path.
*/
strokeColor: PropTypes.string,
/**
* The fill color to use for the path.
*/
fillColor: PropTypes.string,
/**
* The order in which this tile overlay is drawn with respect to other overlays. An overlay
* with a larger z-index is drawn over overlays with smaller z-indices. The order of overlays
* with the same z-index is arbitrary. The default zIndex is 0.
*
* @platform android
*/
zIndex: PropTypes.number,
/**
* The line cap style to apply to the open ends of the path.
* The default style is `round`.
*
* @platform ios
*/
lineCap: PropTypes.oneOf([
'butt',
'round',
'square',
]),
/**
* The line join style to apply to corners of the path.
* The default style is `round`.
*
* @platform ios
*/
lineJoin: PropTypes.oneOf([
'miter',
'round',
'bevel',
]),
/**
* The limiting value that helps avoid spikes at junctions between connected line segments.
* The miter limit helps you avoid spikes in paths that use the `miter` `lineJoin` style. If
* the ratio of the miter length—that is, the diagonal length of the miter join—to the line
* thickness exceeds the miter limit, the joint is converted to a bevel join. The default
* miter limit is 10, which results in the conversion of miters whose angle at the joint
* is less than 11 degrees.
*
* @platform ios
*/
miterLimit: PropTypes.number,
/**
* Boolean to indicate whether to draw each segment of the line as a geodesic as opposed to
* straight lines on the Mercator projection. A geodesic is the shortest path between two
* points on the Earth's surface. The geodesic curve is constructed assuming the Earth is
* a sphere.
*
*/
geodesic: PropTypes.bool,
/**
* The offset (in points) at which to start drawing the dash pattern.
*
* Use this property to start drawing a dashed line partway through a segment or gap. For
* example, a phase value of 6 for the patter 5-2-3-2 would cause drawing to begin in the
* middle of the first gap.
*
* The default value of this property is 0.
*
* @platform ios
*/
lineDashPhase: PropTypes.number,
/**
* An array of numbers specifying the dash pattern to use for the path.
*
* The array contains one or more numbers that indicate the lengths (measured in points) of the
* line segments and gaps in the pattern. The values in the array alternate, starting with the
* first line segment length, followed by the first gap length, followed by the second line
* segment length, and so on.
*
* This property is set to `null` by default, which indicates no line dash pattern.
*
* @platform ios
*/
lineDashPattern: PropTypes.arrayOf(PropTypes.number),
};
const defaultProps = {
strokeColor: '#000',
strokeWidth: 1,
};
class MapPolygon extends React.Component {
setNativeProps(props) {
this.polygon.setNativeProps(props);
}
render() {
const AIRMapPolygon = this.getAirComponent();
return (
<AIRMapPolygon {...this.props} ref={ref => { this.polygon = ref; }} />
);
}
}
MapPolygon.propTypes = propTypes;
MapPolygon.defaultProps = defaultProps;
module.exports = decorateMapComponent(MapPolygon, {
componentType: 'Polygon',
providers: {
google: {
ios: SUPPORTED,
android: USES_DEFAULT_IMPLEMENTATION,
},
},
});
|
client/extensions/woocommerce/app/products/product-create.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { head, isNumber } from 'lodash';
import { localize } from 'i18n-calypso';
import page from 'page';
/**
* Internal dependencies
*/
import Main from 'components/main';
import { ProtectFormGuard } from 'lib/protect-form';
import { getSelectedSiteWithFallback } from 'woocommerce/state/sites/selectors';
import { successNotice, errorNotice } from 'state/notices/actions';
import {
clearProductEdits,
editProduct,
editProductAttribute,
createProductActionList,
} from 'woocommerce/state/ui/products/actions';
import {
clearProductCategoryEdits,
editProductCategory,
} from 'woocommerce/state/ui/product-categories/actions';
import { getActionList } from 'woocommerce/state/action-list/selectors';
import {
getCurrentlyEditingId,
getProductWithLocalEdits,
getProductEdits,
} from 'woocommerce/state/ui/products/selectors';
import { getFinishedInitialSetup } from 'woocommerce/state/sites/setup-choices/selectors';
import { getProductVariationsWithLocalEdits } from 'woocommerce/state/ui/products/variations/selectors';
import { fetchProductCategories } from 'woocommerce/state/sites/product-categories/actions';
import {
clearProductVariationEdits,
editProductVariation,
} from 'woocommerce/state/ui/products/variations/actions';
import { getProductCategoriesWithLocalEdits } from 'woocommerce/state/ui/product-categories/selectors';
import ProductForm from './product-form';
import ProductHeader from './product-header';
import { getLink } from 'woocommerce/lib/nav-utils';
import { withAnalytics, recordTracksEvent } from 'state/analytics/actions';
import { getSaveErrorMessage } from './save-error-message';
class ProductCreate extends React.Component {
static propTypes = {
className: PropTypes.string,
site: PropTypes.shape( {
ID: PropTypes.number,
slug: PropTypes.string,
} ),
product: PropTypes.shape( {
id: PropTypes.isRequired,
} ),
fetchProductCategories: PropTypes.func.isRequired,
editProduct: PropTypes.func.isRequired,
editProductCategory: PropTypes.func.isRequired,
editProductAttribute: PropTypes.func.isRequired,
editProductVariation: PropTypes.func.isRequired,
};
state = {
isUploading: [],
};
componentDidMount() {
const { site } = this.props;
if ( site && site.ID ) {
this.props.editProduct( site.ID, null, {} );
this.props.fetchProductCategories( site.ID, { offset: 0 } );
}
}
UNSAFE_componentWillReceiveProps( newProps ) {
const { site } = this.props;
const newSiteId = ( newProps.site && newProps.site.ID ) || null;
const oldSiteId = ( site && site.ID ) || null;
if ( oldSiteId !== newSiteId ) {
this.props.editProduct( newSiteId, null, {} );
this.props.fetchProductCategories( newSiteId, { offset: 0 } );
}
}
componentWillUnmount() {
const { site } = this.props;
if ( site ) {
this.props.clearProductEdits( site.ID );
this.props.clearProductCategoryEdits( site.ID );
this.props.clearProductVariationEdits( site.ID );
}
}
onUploadStart = () => {
this.setState( prevState => ( {
isUploading: [ ...prevState.isUploading, [ true ] ],
} ) );
};
onUploadFinish = () => {
this.setState( prevState => ( {
isUploading: prevState.isUploading.slice( 1 ),
} ) );
};
onSave = () => {
const { site, product, finishedInitialSetup, translate } = this.props;
const getSuccessNotice = newProduct => {
if ( ! finishedInitialSetup ) {
return successNotice(
translate( '%(product)s successfully created. {{productLink}}View{{/productLink}}', {
args: {
product: newProduct.name,
},
components: {
productLink: (
<a href={ newProduct.permalink } target="_blank" rel="noopener noreferrer" />
),
},
} ),
{
displayOnNextPage: true,
showDismiss: false,
button: translate( 'Back to dashboard' ),
href: getLink( '/store/:site', site ),
}
);
}
return successNotice(
translate( '%(product)s successfully created.', {
args: { product: product.name },
} ),
{
displayOnNextPage: true,
duration: 8000,
button: translate( 'View' ),
onClick: () => {
window.open( newProduct.permalink );
},
}
);
};
const successAction = products => {
const newProduct = head( products );
page.redirect( getLink( '/store/products/:site', site ) );
return getSuccessNotice( newProduct );
};
const failureAction = error => {
const errorSlug = ( error && error.error ) || undefined;
return errorNotice( getSaveErrorMessage( errorSlug, product.name, translate ), {
duration: 8000,
} );
};
if ( ! product.type ) {
// Product type was never switched, so set it before we save.
this.props.editProduct( site.ID, product, { type: 'simple' } );
}
if ( ! product.regular_price ) {
this.props.editProduct( site.ID, product, { regular_price: '0' } );
}
this.props.createProductActionList( successAction, failureAction );
};
isProductValid( product = this.props.product ) {
return product && product.name && product.name.length > 0;
}
render() {
const {
site,
product,
hasEdits,
className,
variations,
productCategories,
actionList,
} = this.props;
const isValid = 'undefined' !== site && this.isProductValid();
const isBusy = Boolean( actionList ); // If there's an action list present, we're trying to save.
const saveEnabled = isValid && ! isBusy && 0 === this.state.isUploading.length;
if ( ! product || isNumber( product.id ) ) {
return null;
}
return (
<Main className={ className } wideLayout>
<ProductHeader
site={ site }
product={ product }
onSave={ saveEnabled ? this.onSave : false }
isBusy={ isBusy }
/>
<ProtectFormGuard isChanged={ hasEdits } />
<ProductForm
siteId={ site && site.ID }
product={ product || { type: 'simple' } }
variations={ variations }
productCategories={ productCategories }
editProduct={ this.props.editProduct }
editProductCategory={ this.props.editProductCategory }
editProductAttribute={ this.props.editProductAttribute }
editProductVariation={ this.props.editProductVariation }
onUploadStart={ this.onUploadStart }
onUploadFinish={ this.onUploadFinish }
/>
</Main>
);
}
}
function mapStateToProps( state ) {
const site = getSelectedSiteWithFallback( state );
const productId = getCurrentlyEditingId( state );
const combinedProduct = getProductWithLocalEdits( state, productId );
const product = combinedProduct || ( productId && { id: productId } );
const hasEdits = Boolean( getProductEdits( state, productId ) );
const variations = product && getProductVariationsWithLocalEdits( state, product.id );
const productCategories = getProductCategoriesWithLocalEdits( state );
const actionList = getActionList( state );
const finishedInitialSetup = getFinishedInitialSetup( state );
return {
site,
product,
hasEdits,
variations,
productCategories,
actionList,
finishedInitialSetup,
};
}
function mapDispatchToProps( dispatch ) {
return bindActionCreators(
{
createProductActionList: ( ...args ) =>
withAnalytics(
recordTracksEvent( 'calypso_woocommerce_ui_product_create' ),
createProductActionList( ...args )
),
editProduct,
editProductCategory,
editProductAttribute,
editProductVariation,
fetchProductCategories,
clearProductEdits,
clearProductCategoryEdits,
clearProductVariationEdits,
},
dispatch
);
}
export default connect(
mapStateToProps,
mapDispatchToProps
)( localize( ProductCreate ) );
|
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/expected.js | Maxwelloff/react-football | import _transformLib from 'transform-lib';
const _components = {
Foo: {
displayName: 'Foo'
}
};
const _transformLib2 = _transformLib({
filename: '%FIXTURE_PATH%',
components: _components,
locals: [],
imports: []
});
function _wrapComponent(id) {
return function (Component) {
return _transformLib2(Component, id);
};
}
import React, { Component } from 'react';
const Foo = _wrapComponent('Foo')(class Foo extends Component {
render() {}
});
|
resources/js/components/Team/MemberComponent.js | Stasgar/BugWall_Visual_Bugtracker | import React, { Component } from 'react';
import Ability from './AbilityComponent';
class Member extends React.Component {
constructor(props) {
super(props);
this.props = props;
this.api = props.api;
}
render() {
return (
<tr><td>
<a href={this.props.member.profile_url}>
<span>@</span>{this.props.member.name}
<img className="user-profile-image" src={this.props.member.profile_image_url} alt="" width="20px"/>
{" "}
</a>
<span>
<MemberControlPanel
key={this.props.member.name}
api={this.api}
member={this.props.member}
canDelete={this.props.canDelete}
canManage={this.props.canManage}
detach={this.props.links.detach+'/'+this.props.member.name}
detachUser={this.props.detachUser.bind(this)}
updateMembers={this.props.updateMembers.bind(this)}/>
</span>
</td></tr>
)
}
}
class MemberControlPanel extends React.Component {
constructor(props) {
super(props);
}
roles() {
let roles = [];
if (this.props.member.abilities['create'] === true) {
roles.push(<CreatorBadge key={'creator_badge_'+this.props.member.name} />);
}
if (this.props.member.abilities['manage'] === true) {
roles.push(<ManagerBadge key={'manager_badge_'+this.props.member.name} />);
}
return roles;
}
render() {
return (
<span className="controls">
<span>
{(this.props.canManage || this.props.canDelete) &&
<DeleteButton key={'delete_button_'+this.props.member.name}
detach={this.props.detach}
detachUser={this.props.detachUser.bind(this)} />
}
</span>
{(this.props.canDelete) &&
<Ability key={'ability_'+this.props.member.name}
api={this.props.api}
member={this.props.member}
abilities={this.props.member.abilities}
updateMembers={this.props.updateMembers.bind(this)} />
}
{this.roles()}
</span>
)
}
}
function DeleteButton(props) {
return (
<a href={props.detach}
className="member-delete-form btn btn-danger btn-xs glyphicon glyphicon-remove"
onClick={props.detachUser}></a>
);
}
function CreatorBadge(props) {
return (
<span className="small creator-badge ability-badge member-control-element">creator</span>
);
}
function ManagerBadge(props) {
return (
<span className="small manager-badge ability-badge member-control-element">manager</span>
);
}
export default Member;
|
packages/components/src/ResourceList/Toolbar/StateFilter/StateFilter.component.js | Talend/ui | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { withTranslation } from 'react-i18next';
import ActionIconToggle from '../../../Actions/ActionIconToggle';
import I18N_DOMAIN_COMPONENTS from '../../../constants';
import getDefaultT from '../../../translate';
import theme from './StateFilter.scss';
export const TYPES = {
SELECTION: 'selection',
FAVORITES: 'favorites',
CERTIFIED: 'certified',
};
function StateFilter({ t, types, onChange, selection, favorites, certified }) {
return (
!!types.length && (
<div
className={classNames(
'tc-resource-picker-state-filters',
theme['tc-resource-picker-state-filters'],
)}
>
<span className={classNames(theme['option-label'])}>
{t('FILTER', { defaultValue: 'Filter:' })}
</span>
{types.includes(TYPES.SELECTION) && (
<ActionIconToggle
icon="talend-check-circle"
label={t('SELECTION', { defaultValue: 'Selected' })}
active={selection}
onClick={() => onChange(TYPES.SELECTION, !selection)}
className={classNames(theme['tc-resource-picker-selection-filter'])}
/>
)}
{types.includes(TYPES.CERTIFIED) && (
<ActionIconToggle
icon="talend-badge"
label={t('CERTIFIED', { defaultValue: 'Certified' })}
active={certified}
onClick={() => onChange(TYPES.CERTIFIED, !certified)}
className={classNames(theme['tc-resource-picker-certified-filter'])}
/>
)}
{types.includes(TYPES.FAVORITES) && (
<ActionIconToggle
icon="talend-star"
label={t('FAVORITES', { defaultValue: 'Favorites' })}
active={favorites}
onClick={() => onChange(TYPES.FAVORITES, !favorites)}
className={classNames(theme['tc-resource-picker-favorite-filter'])}
/>
)}
</div>
)
);
}
StateFilter.propTypes = {
t: PropTypes.func,
selection: PropTypes.bool,
favorites: PropTypes.bool,
certified: PropTypes.bool,
onChange: PropTypes.func,
types: PropTypes.array,
};
StateFilter.defaultProps = {
t: getDefaultT(),
types: [TYPES.SELECTION, TYPES.FAVORITES, TYPES.CERTIFIED],
};
export default withTranslation(I18N_DOMAIN_COMPONENTS)(StateFilter);
|
script/js/react/material-ui/src/demo/hello/hello.js | joshuazhan/arsenal4j | import React from 'react';
import {render} from 'react-dom';
render(
<h1>Hello, world!</h1>,
document.getElementById('content')
); |
carbon-page/stories/task/index.js | ShotaOd/dabunt | import React, { Component } from 'react';
import { storiesOf, action } from '@kadira/storybook';
import cardStory from './card'
const story = storiesOf('Task', module);
cardStory(story); |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.