path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
app/addons/config/layout.js | garrensmith/couchdb-fauxton | // 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 ConfigComponents from "./components.react";
import CORSComponents from "../cors/components.react";
import {Breadcrumbs} from '../components/header-breadcrumbs';
import {NotificationCenterButton} from '../fauxton/notifications/notifications.react';
import {ApiBarWrapper} from '../components/layouts';
export const ConfigHeader = ({node, crumbs, docURL, endpoint}) => {
return (
<header className="two-panel-header">
<div className="flex-layout flex-row">
<div id='breadcrumbs' className="faux__config-breadcrumbs">
<Breadcrumbs crumbs={crumbs}/>
</div>
<div className="right-header-wrapper flex-layout flex-row flex-body">
<div id="react-headerbar" className="flex-body"> </div>
<div id="right-header" className="flex-fill">
<ConfigComponents.AddOptionController node={node} />
</div>
<ApiBarWrapper docURL={docURL} endpoint={endpoint} />
<div id="notification-center-btn" className="flex-fill">
<NotificationCenterButton />
</div>
</div>
</div>
</header>
);
};
export const ConfigLayout = ({showCors, docURL, node, endpoint, crumbs}) => {
const sidebarItems = [
{
title: 'Main config',
link: '_config/' + node
},
{
title: 'CORS',
link: '_config/' + node + '/cors'
}
];
const selectedTab = showCors ? 'CORS' : 'Main config';
const content = showCors ? <CORSComponents.CORSController/> : <ConfigComponents.ConfigTableController node={node} />;
return (
<div id="dashboard" className="with-sidebar">
<ConfigHeader
docURL={docURL}
endpoint={endpoint}
node={node}
crumbs={crumbs}
/>
<div className="with-sidebar tabs-with-sidebar content-area">
<aside id="sidebar-content" className="scrollable">
<ConfigComponents.Tabs
sidebarItems={sidebarItems}
selectedTab={selectedTab}
/>
</aside>
<section id="dashboard-content" className="flex-layout flex-col">
<div id="dashboard-upper-content"></div>
<div id="dashboard-lower-content" className="flex-body">
{content}
</div>
<div id="footer"></div>
</section>
</div>
</div>
);
};
export default ConfigLayout;
|
src/index.js | mkoennecke/radieschenjs | import React from 'react';
import ReactDOM from 'react-dom';
import Radieschen from './Radieschen';
import './index.css';
ReactDOM.render(
<Radieschen />,
document.getElementById('root')
);
|
packages/mineral-ui-icons/src/IconStarBorder.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconStarBorder(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/>
</g>
</Icon>
);
}
IconStarBorder.displayName = 'IconStarBorder';
IconStarBorder.category = 'toggle';
|
shared/modules/utils/components/Loader.js | founderlab/fl-base-webapp | import React from 'react'
import PropTypes from 'prop-types'
export default function Loader(props) {
return (<div className="loader-wrapper"><div className="loader">loading...</div></div>)
}
|
modules/gui/src/widget/leaveAlert.js | openforis/sepal | import {compose} from 'compose'
import {connect} from 'store'
import React from 'react'
import _ from 'lodash'
export const withLeaveAlert = mapStateToLeaveAlert =>
WrappedComponent => {
class HigherOrderComponent extends React.Component {
constructor() {
super()
this.onClose = this.onClose.bind(this)
}
render() {
return React.createElement(WrappedComponent, this.props)
}
componentDidMount() {
window.addEventListener('beforeunload', this.onClose)
}
componentWillUnmount() {
window.removeEventListener('beforeunload', this.onClose)
}
onClose(e) {
const {leaveAlert} = this.props
if (leaveAlert) {
e.preventDefault()
e.returnValue = ''
return ''
}
}
}
const mapStateToProps = state => ({
leaveAlert: mapStateToLeaveAlert(state)
})
return compose(
HigherOrderComponent,
connect(mapStateToProps)
)
}
|
src/svg-icons/device/bluetooth-disabled.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBluetoothDisabled = (props) => (
<SvgIcon {...props}>
<path d="M13 5.83l1.88 1.88-1.6 1.6 1.41 1.41 3.02-3.02L12 2h-1v5.03l2 2v-3.2zM5.41 4L4 5.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l4.29-4.29 2.3 2.29L20 18.59 5.41 4zM13 18.17v-3.76l1.88 1.88L13 18.17z"/>
</SvgIcon>
);
DeviceBluetoothDisabled = pure(DeviceBluetoothDisabled);
DeviceBluetoothDisabled.displayName = 'DeviceBluetoothDisabled';
DeviceBluetoothDisabled.muiName = 'SvgIcon';
export default DeviceBluetoothDisabled;
|
src/containers/HomeSearch/index.js | kokengthecoder/github-user-search | import React, { Component } from 'react';
import SearchBar from './SearchBar';
import ListUser from './ListUser';
import { Grid } from 'semantic-ui-react';
class HomeSearch extends Component {
render() {
return (
<Grid centered>
<Grid.Row>
<h1>Github User Search</h1>
</Grid.Row>
<Grid.Row>
<SearchBar />
</Grid.Row>
<Grid.Row>
<ListUser />
</Grid.Row>
</Grid>
)
}
}
export default HomeSearch; |
internals/templates/homePage.js | ReelTalkers/reeltalk-web | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react'
export function HomePage() {
return (
<h1>This is the Homepage!</h1>
)
}
export default HomePage
|
packages/material-ui-icons/src/PermIdentity.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PermIdentity = props =>
<SvgIcon {...props}>
<path d="M12 5.9c1.16 0 2.1.94 2.1 2.1s-.94 2.1-2.1 2.1S9.9 9.16 9.9 8s.94-2.1 2.1-2.1m0 9c2.97 0 6.1 1.46 6.1 2.1v1.1H5.9V17c0-.64 3.13-2.1 6.1-2.1M12 4C9.79 4 8 5.79 8 8s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm0 9c-2.67 0-8 1.34-8 4v3h16v-3c0-2.66-5.33-4-8-4z" />
</SvgIcon>;
PermIdentity = pure(PermIdentity);
PermIdentity.muiName = 'SvgIcon';
export default PermIdentity;
|
lib/editor/components/editors/FinisherEditor.js | jirokun/survey-designer-js | import React, { Component } from 'react';
import { connect } from 'react-redux';
import cuid from 'cuid';
import { Col, FormGroup, ControlLabel, FormControl } from 'react-bootstrap';
import tinymce from 'tinymce';
import HtmlEditorPart from '../question_editors/parts/HtmlEditorPart';
import * as EditorActions from '../../actions';
import './../../../constants/tinymce_ja';
/** Finisherの編集画面 */
class FinisherEditor extends Component {
/** コンストラクタ */
constructor(props) {
super(props);
// tinymceがかぶらないようにするためにcuidを生成
this.cuid = cuid();
}
/** tinymceの値が変わったときの処理 */
handleHtmlChange(finisherId, html) {
const { changeFinisherAttribute } = this.props;
changeFinisherAttribute(finisherId, 'html', html);
}
/** tinymce以外のコントロールの値が変わったときの処理 */
handleChangeFinisherAttribute(finisherId, attribute, value) {
const { changeFinisherAttribute } = this.props;
changeFinisherAttribute(finisherId, attribute, value);
}
/** 描画 */
render() {
const { survey, finisher } = this.props;
const finisherId = finisher.getId();
const finisherNo = survey.calcFinisherNo(finisher.getId());
return (
<div className="form-horizontal">
<h4 className="enq-title enq-title__finisher">{finisherNo} 終了ページ設定</h4>
<FormGroup>
<Col componentClass={ControlLabel} md={2}>表示内容</Col>
<Col md={10}>
<HtmlEditorPart
key={`${finisherId}_html_editor`}
onChange={html => this.handleHtmlChange(finisherId, html)}
content={finisher.getHtml()}
/>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} md={2}>終了タイプ</Col>
<Col md={10}>
<FormControl componentClass="select" value={finisher.getFinishType()} onChange={e => this.handleChangeFinisherAttribute(finisherId, 'finishType', e.target.value)}>
<option value="COMPLETE">COMPLETE</option>
<option value="SCREEN">SCREEN</option>
</FormControl>
</Col>
</FormGroup>
</div>
);
}
}
const stateToProps = state => ({
survey: state.getSurvey(),
runtime: state.getRuntime(),
view: state.getViewSetting(),
});
const actionsToProps = dispatch => ({
changeFinisherAttribute: (finisherId, attribute, value) =>
dispatch(EditorActions.changeFinisherAttribute(finisherId, attribute, value)),
});
export default connect(
stateToProps,
actionsToProps,
)(FinisherEditor);
|
src/client/components/dialogs/Confirm.js | vanpaz/vbi | import React from 'react'
import Dialog from 'material-ui/lib/dialog'
import FlatButton from 'material-ui/lib/flat-button'
import bindMethods from '../../utils/bindMethods'
/**
* Usage:
*
* <Confirm ref="confirmDialog" />
*
* this.refs.confirmDialog.show({
* title: 'Sign in',
* description: <div>
* <p>
* To open, save, or delete scenarios you have to sign in first.
* </p>
* <p>
* Do you want to sign in now?
* </p>
* </div>
* })
* .then(ok => {
* console.log('ok?', ok) // ok is true or false
* })
*
* this.refs.confirmDialog.hide()
*
*/
export default class Confirm extends React.Component {
constructor (props) {
super (props)
bindMethods(this)
this.state = {
open: false,
title: null,
description: null,
handler: function () {}
}
}
render () {
const actions = [
<FlatButton
label="No"
secondary={true}
onTouchTap={this.hide}
/>,
<FlatButton
label="Yes"
primary={true}
keyboardFocused={true}
onTouchTap={this._handleOk}
/>
]
return <Dialog
title={this.state.title}
actions={actions}
modal={false}
open={this.state.open}
onRequestClose={this.hide} >
{this.state.description}
</Dialog>
}
show ({ title, description }) {
return new Promise((resolve, reject) => {
this.setState({
open: true,
title: title || 'Title',
description: description || 'Description',
handler: resolve
})
})
}
hide () {
this._handle(false)
}
_handleOk () {
this._handle(true)
}
_handle (ok) {
this.state.handler(ok)
this.setState({
open: false,
handler: function () {}
})
}
} |
app/components/clock.js | romankhrystynych/raspitron | // @flow
import moment from 'moment';
import React, { Component } from 'react';
import styles from './styles.css';
class Clock extends Component {
constructor(props) {
super(props);
this.state = {
time: ''
};
}
componentWillMount() {
this.setTime();
}
componentDidMount() {
this.loadInterval = setInterval(() => {
this.setTime();
}, 1000);
}
componentWillUnmount() {
clearInterval(this.loadInterval);
}
setTime() {
const date = moment().format('dddd MMM Do');
const time = moment().format('h:mm A');
this.setState({
date,
time
});
}
render() {
return (
<div className={styles.clock}>
<div className={styles.date}>{this.state.date}</div>
<div className={styles.time}>{this.state.time}</div>
</div>
);
}
}
export default Clock;
|
app/containers/FeaturePage/index.js | jdm85kor/sentbe | /*
* FeaturePage
*
* List all the features
*/
import React from 'react';
import Helmet from 'react-helmet';
import messages from './messages';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import List from './List';
import ListItem from './ListItem';
import ListItemTitle from './ListItemTitle';
export default class FeaturePage extends React.Component { // eslint-disable-line react/prefer-stateless-function
// Since state and props are static,
// there's no need to re-render this component
shouldComponentUpdate() {
return false;
}
render() {
return (
<div>
<Helmet
title="Feature Page"
meta={[
{ name: 'description', content: 'Feature page of React.js Boilerplate application' },
]}
/>
<H1>
<FormattedMessage {...messages.header} />
</H1>
<List>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.scaffoldingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.scaffoldingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.feedbackHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.feedbackMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.routingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.routingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.networkHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.networkMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.intlHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.intlMessage} />
</p>
</ListItem>
</List>
</div>
);
}
}
|
app/javascript/mastodon/features/account_timeline/containers/header_container.js | danhunsaker/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { makeGetAccount } from '../../../selectors';
import Header from '../components/header';
import {
followAccount,
unfollowAccount,
unblockAccount,
unmuteAccount,
pinAccount,
unpinAccount,
} from '../../../actions/accounts';
import {
mentionCompose,
directCompose,
} from '../../../actions/compose';
import { initMuteModal } from '../../../actions/mutes';
import { initBlockModal } from '../../../actions/blocks';
import { initReport } from '../../../actions/reports';
import { openModal } from '../../../actions/modal';
import { blockDomain, unblockDomain } from '../../../actions/domain_blocks';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { unfollowModal } from '../../../initial_state';
import { List as ImmutableList } from 'immutable';
const messages = defineMessages({
unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' },
blockDomainConfirm: { id: 'confirmations.domain_block.confirm', defaultMessage: 'Hide entire domain' },
});
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = (state, { accountId }) => ({
account: getAccount(state, accountId),
domain: state.getIn(['meta', 'domain']),
identity_proofs: state.getIn(['identity_proofs', accountId], ImmutableList()),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onFollow (account) {
if (account.getIn(['relationship', 'following']) || account.getIn(['relationship', 'requested'])) {
if (unfollowModal) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.unfollowConfirm),
onConfirm: () => dispatch(unfollowAccount(account.get('id'))),
}));
} else {
dispatch(unfollowAccount(account.get('id')));
}
} else {
dispatch(followAccount(account.get('id')));
}
},
onBlock (account) {
if (account.getIn(['relationship', 'blocking'])) {
dispatch(unblockAccount(account.get('id')));
} else {
dispatch(initBlockModal(account));
}
},
onMention (account, router) {
dispatch(mentionCompose(account, router));
},
onDirect (account, router) {
dispatch(directCompose(account, router));
},
onReblogToggle (account) {
if (account.getIn(['relationship', 'showing_reblogs'])) {
dispatch(followAccount(account.get('id'), { reblogs: false }));
} else {
dispatch(followAccount(account.get('id'), { reblogs: true }));
}
},
onEndorseToggle (account) {
if (account.getIn(['relationship', 'endorsed'])) {
dispatch(unpinAccount(account.get('id')));
} else {
dispatch(pinAccount(account.get('id')));
}
},
onNotifyToggle (account) {
if (account.getIn(['relationship', 'notifying'])) {
dispatch(followAccount(account.get('id'), { notify: false }));
} else {
dispatch(followAccount(account.get('id'), { notify: true }));
}
},
onReport (account) {
dispatch(initReport(account));
},
onMute (account) {
if (account.getIn(['relationship', 'muting'])) {
dispatch(unmuteAccount(account.get('id')));
} else {
dispatch(initMuteModal(account));
}
},
onBlockDomain (domain) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.domain_block.message' defaultMessage='Are you really, really sure you want to block the entire {domain}? In most cases a few targeted blocks or mutes are sufficient and preferable. You will not see content from that domain in any public timelines or your notifications. Your followers from that domain will be removed.' values={{ domain: <strong>{domain}</strong> }} />,
confirm: intl.formatMessage(messages.blockDomainConfirm),
onConfirm: () => dispatch(blockDomain(domain)),
}));
},
onUnblockDomain (domain) {
dispatch(unblockDomain(domain));
},
onAddToList(account){
dispatch(openModal('LIST_ADDER', {
accountId: account.get('id'),
}));
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Header));
|
javascript/components/VectorSource.js | bsudekum/react-native-mapbox-gl | import React from 'react';
import PropTypes from 'prop-types';
import {NativeModules, requireNativeComponent} from 'react-native';
import {cloneReactChildrenWithProps, viewPropTypes, isFunction} from '../utils';
const MapboxGL = NativeModules.MGLModule;
export const NATIVE_MODULE_NAME = 'RCTMGLVectorSource';
/**
* VectorSource is a map content source that supplies tiled vector data in Mapbox Vector Tile format to be shown on the map.
* The location of and metadata about the tiles are defined either by an option dictionary or by an external file that conforms to the TileJSON specification.
*/
class VectorSource extends React.Component {
static propTypes = {
...viewPropTypes,
/**
* A string that uniquely identifies the source.
*/
id: PropTypes.string,
/**
* A URL to a TileJSON configuration file describing the source’s contents and other metadata.
*/
url: PropTypes.string,
/**
* Source press listener, gets called when a user presses one of the children layers only
* if that layer has a higher z-index than another source layers
*/
onPress: PropTypes.func,
/**
* Overrides the default touch hitbox(44x44 pixels) for the source layers
*/
hitbox: PropTypes.shape({
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
}),
};
static defaultProps = {
id: MapboxGL.StyleSource.DefaultSourceID,
};
render() {
const props = {
id: this.props.id,
url: this.props.url,
hitbox: this.props.hitbox,
hasPressListener: isFunction(this.props.onPress),
onMapboxVectorSourcePress: this.props.onPress,
onPress: undefined,
};
return (
<RCTMGLVectorSource {...props}>
{cloneReactChildrenWithProps(this.props.children, {
sourceID: this.props.id,
})}
</RCTMGLVectorSource>
);
}
}
const RCTMGLVectorSource = requireNativeComponent(
NATIVE_MODULE_NAME,
VectorSource,
{
nativeOnly: {
hasPressListener: true,
onMapboxVectorSourcePress: true,
},
},
);
export default VectorSource;
|
scr-app/src/components/AutoComplete.js | tlatoza/SeeCodeRun | //Original: https://material-ui-next.com/demos/autocomplete/
import React from 'react';
import PropTypes from 'prop-types';
import Autosuggest from 'react-autosuggest';
import match from 'autosuggest-highlight/match';
import parse from 'autosuggest-highlight/parse';
import Paper from '@material-ui/core/Paper';
import MenuItem from '@material-ui/core/MenuItem';
import {withStyles} from '@material-ui/core/styles';
const renderSuggestionsContainer = options => {
const {containerProps, children} = options;
return (
<Paper {...containerProps} square>
{children}
</Paper>
);
};
const styles = (theme) => ({
container: {
flexGrow: 1,
position: 'relative',
maxWidth: 250,
maxHeight: 250,
height: 250,
width: 250,
overflow: 'visible',
marginLeft: theme.spacing(1),
marginRight: theme.spacing(1),
},
suggestionsContainerOpen: {
position: 'absolute',
zIndex: 1,
left: 0,
right: 0,
overflow: 'auto',
},
suggestion: {
display: 'block',
},
suggestionsList: {
margin: 0,
padding: 0,
listStyleType: 'none',
},
});
class AutoComplete extends React.Component {
state = {
suggestions: [],
isShowAll: true,
};
renderSuggestion = (suggestion, {query, isHighlighted}) => {
const {isShowAll} = this.state;
if (isShowAll) {
return (
<MenuItem selected={isHighlighted} component="div">
<div>
<span style={{fontWeight: 300}}>{suggestion.label}</span>
</div>
</MenuItem>
);
}
const matches = match(suggestion.label, query);
const parts = parse(suggestion.label, matches);
return (
<MenuItem selected={isHighlighted} component="div">
<div>
{parts.map((part, index) => {
return part.highlight ? (
<span key={String(index)} style={{fontWeight: 300}}>
{part.text}
</span>
) : (
<strong key={String(index)} style={{fontWeight: 500}}>
{part.text}
</strong>
);
})}
</div>
</MenuItem>
);
};
handleSuggestionsFetchRequested = ({value}) => {
const suggestionsResult = this.props.getSuggestions(value);
this.setState({
suggestions: suggestionsResult.suggestions,
isShowAll: suggestionsResult.isShowAll
});
};
handleSuggestionsClearRequested = () => {
const suggestionsResult = this.props.getSuggestions('');
this.setState({
suggestions: suggestionsResult.suggestions,
isShowAll: suggestionsResult.isShowAll
});
};
render() {
const {
classes,
renderInputComponent,
inputProps,
getSuggestionValue
} = this.props;
return (
<Autosuggest
theme={{
container: classes.container,
suggestionsContainerOpen: classes.suggestionsContainerOpen,
suggestionsList: classes.suggestionsList,
suggestion: classes.suggestion,
}}
renderInputComponent={renderInputComponent}
inputProps={inputProps}
suggestions={this.state.suggestions}
onSuggestionsFetchRequested={this.handleSuggestionsFetchRequested}
onSuggestionsClearRequested={this.handleSuggestionsClearRequested}
renderSuggestionsContainer={renderSuggestionsContainer}
getSuggestionValue={getSuggestionValue}
renderSuggestion={this.renderSuggestion}
/>
);
}
}
AutoComplete.propTypes = {
classes: PropTypes.object.isRequired,
renderInputComponent: PropTypes.func.isRequired,
inputProps: PropTypes.object.isRequired,
getSuggestions: PropTypes.func.isRequired,
getSuggestionValue: PropTypes.func.isRequired,
};
export default withStyles(styles)(AutoComplete);
|
demo/app/client/packages/users/index.js | jsdf/webpack_rails | import React from 'react'
import automountComponent from '../automountComponent'
console.log('a') |
public/src/components/input/input.js | rafaelfbs/rmodel | import React, { Component } from 'react';
import * as inputs from './inputs/index';
import { observer } from 'mobx-react';
export default class Input extends Component {
get type() {
const { model, name } = this.props;
return model.fields[name].inputType;
}
get component() {
const input = inputs[this.type];
if (!input) {
console.error(`Input for type "${this.type}" not found, using "text" as fallback.`);
return inputs['text'];
}
return input;
}
get input() {
return this.refs.inputComponent.input;
}
render() {
return <this.component ref="inputComponent" {...this.props} />;
}
}
|
data-browser-ui/public/app/components/tableComponents/columnOptionsComponent.js | CloudBoost/cloudboost | import React from 'react';
import { observer } from "mobx-react"
import {Checkbox,TextField} from 'material-ui'
import configObject from '../../config/app.js'
import {Popover, PopoverAnimationVertical} from 'material-ui/Popover'
@observer
class ColumnOptions extends React.Component {
constructor(){
super()
this.state = {
open: false,
unique:false,
required:false,
columnName:''
}
}
componentDidMount(){
this.state.unique = this.props.columnData.unique
this.state.required = this.props.columnData.required
this.setState(this.state)
}
hideShowColumn(name,e){
this.closeMenu()
this.props.tableStore.hideColumn(name)
}
sortColumns(columnName,what){
this.props.tableStore.sortColumnsData(what,columnName)
}
deleteColumn(columnName){
this.closeMenu()
this.props.tableStore.deleteColumn(columnName)
}
editColumn(columnName){
this.props.tableStore.editColumn(columnName,this.state.unique,this.state.required,this.state.columnName)
this.handleRequestClose()
}
closeMenu(){
this.props.handleRequestClose()
}
handleTouchTap(event){
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget
})
}
handleRequestClose(){
this.setState({
open: false
})
}
checkHandler(which,e,data){
this.state[which] = data
this.setState(this.state)
}
changeHandler(which,e){
this.state[which] = e.target.value
this.setState(this.state)
}
render() {
return (
<div>
<button
className={ ['Text','Email','Number','DateTime','Boolean'].indexOf(this.props.columnData.dataType) == -1 ? "hide" : "coloptbtn" }
onClick={ this.sortColumns.bind(this,this.props.columnData.name,'orderByAsc') }>
<i className="fa fa-sort-alpha-asc" aria-hidden="true"></i>
{' Sort Ascending'}
</button>
<button
className={ ['Text','Email','Number','DateTime','Boolean'].indexOf(this.props.columnData.dataType) == -1 ? "hide" : "coloptbtn" }
onClick={ this.sortColumns.bind(this,this.props.columnData.name,'orderByDesc') }>
<i className="fa fa-sort-alpha-desc" aria-hidden="true"></i>
{' Sort Descending'}
</button>
<button className="coloptbtn" onClick={ this.hideShowColumn.bind(this,this.props.columnData.name) }><i className="fa fa-eye-slash" aria-hidden="true"></i> Hide Column</button>
<button
className={ this.props.columnData.isDeletable ? "coloptbtn" : 'hide' }
onClick={ this.deleteColumn.bind(this,this.props.columnData.name) }>
<i className="fa fa-minus-circle" aria-hidden="true"></i>
{' Delete Column'}
</button>
<button
className={ this.props.columnData.isEditable ? "coloptbtn" : 'hide' }
onTouchTap={ this.handleTouchTap.bind(this) }>
<i className="fa fa-wrench" aria-hidden="true"></i>
{' Configure Column'}
</button>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin= {{"horizontal":"left","vertical":"bottom"}}
targetOrigin= {{"horizontal":"right","vertical":"top"}}
onRequestClose={this.handleRequestClose.bind(this)}
animated={false}
className="columnpop"
>
<TextField
floatingLabelText="New Column Name"
className="new-column-textField" floatingLabelStyle={{lineHeight:0}} onChange={this.changeHandler.bind(this,'columnName')}
/>
<Checkbox
label="Required"
className="checkeditcol"
checked={ this.state.required }
onCheck={ this.checkHandler.bind(this,'required') }
/>
<Checkbox
label="Unique"
className="checkeditcol"
checked={ this.state.unique }
onCheck={ this.checkHandler.bind(this,'unique') }
/>
<button className="savebtneditablecol" onClick={ this.editColumn.bind(this,this.props.columnData.name) }>Save</button>
</Popover>
</div>
);
}
}
export default ColumnOptions; |
app/index.js | w1nston/jwdotcom | import React from 'react';
import ReactDOM from 'react-dom';
import Main from './Main';
ReactDOM.render(
<Main />,
document.getElementById('root-content')
);
|
docs/src/app/components/pages/components/Toggle/Page.js | ichiohta/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import toggleReadmeText from './README';
import ToggleExampleSimple from './ExampleSimple';
import toggleExampleSimpleCode from '!raw!./ExampleSimple';
import toggleCode from '!raw!material-ui/Toggle/Toggle';
const description = 'The second example is selected by default using the `defaultToggled` property. The third ' +
'example is disabled using the `disabled` property. The final example uses the `labelPosition` property to ' +
'position the label on the right.';
const TogglePage = () => (
<div>
<Title render={(previousTitle) => `Toggle - ${previousTitle}`} />
<MarkdownElement text={toggleReadmeText} />
<CodeExample
title="Examples"
description={description}
code={toggleExampleSimpleCode}
>
<ToggleExampleSimple />
</CodeExample>
<PropTypeDescription code={toggleCode} />
</div>
);
export default TogglePage;
|
app/javascript/mastodon/features/picture_in_picture/index.js | tri-star/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Video from 'mastodon/features/video';
import Audio from 'mastodon/features/audio';
import { removePictureInPicture } from 'mastodon/actions/picture_in_picture';
import Header from './components/header';
import Footer from './components/footer';
const mapStateToProps = state => ({
...state.get('picture_in_picture'),
});
export default @connect(mapStateToProps)
class PictureInPicture extends React.Component {
static propTypes = {
statusId: PropTypes.string,
accountId: PropTypes.string,
type: PropTypes.string,
src: PropTypes.string,
muted: PropTypes.bool,
volume: PropTypes.number,
currentTime: PropTypes.number,
poster: PropTypes.string,
backgroundColor: PropTypes.string,
foregroundColor: PropTypes.string,
accentColor: PropTypes.string,
dispatch: PropTypes.func.isRequired,
};
handleClose = () => {
const { dispatch } = this.props;
dispatch(removePictureInPicture());
}
render () {
const { type, src, currentTime, accountId, statusId } = this.props;
if (!currentTime) {
return null;
}
let player;
if (type === 'video') {
player = (
<Video
src={src}
currentTime={this.props.currentTime}
volume={this.props.volume}
muted={this.props.muted}
autoPlay
inline
alwaysVisible
/>
);
} else if (type === 'audio') {
player = (
<Audio
src={src}
currentTime={this.props.currentTime}
volume={this.props.volume}
muted={this.props.muted}
poster={this.props.poster}
backgroundColor={this.props.backgroundColor}
foregroundColor={this.props.foregroundColor}
accentColor={this.props.accentColor}
autoPlay
/>
);
}
return (
<div className='picture-in-picture'>
<Header accountId={accountId} statusId={statusId} onClose={this.handleClose} />
{player}
<Footer statusId={statusId} />
</div>
);
}
}
|
client/Contests/components/MessageComponent.js | rystecher/senior-design | import React from 'react';
import { getTeamMessages, sendMessageToJudge } from '../ContestActions.js';
import { ChatFeed, Message } from './chat-ui/lib/index.js';
export default class MessageComponent extends React.Component {
constructor(props) {
super(props);
this.state = { messageObjs: [] };
}
componentDidMount() {
const { contestId, teamId } = this.props;
const intervalFunc = () => getTeamMessages(contestId, teamId).then((messages) => {
if (messages) {
const messageObjs = messages.map((message) => {
const type = 'Team' === message.from ? 0 : 1;
return new Message(type, message.message);
});
if (this.state.messageObjs.length < messageObjs.length) {
this.setState({ messageObjs });
this.child._scrollToBottom();
}
}
});
intervalFunc();
this.chatIntervId = setInterval(intervalFunc, 10000);
}
componentWillUnmount() {
clearInterval(this.chatIntervId);
}
sendMessage(event) {
const { contestId, teamId } = this.props;
if (event.keyCode === 13) {
sendMessageToJudge(contestId, teamId, event.target.value);
this.state.messageObjs.push(new Message(0, event.target.value));
event.target.value = '';
this.setState({ messageObjs: this.state.messageObjs });
setTimeout(() => this.child._scrollToBottom(), 250);
}
}
render() {
return (
<div className='chatbox'>
<ChatFeed
ref={instance => { this.child = instance; }}
messages={this.state.messageObjs}
bubblesCentered={false}
/>
<input
placeholder='Have a question for the judges...'
className='message-input'
onKeyDown={this.sendMessage.bind(this)}
type='text'
style={styles.inputField}
/>
</div>
);
}
}
const styles = {
inputField: {
display: 'inherit',
},
};
MessageComponent.propTypes = {
contestId: React.PropTypes.string.isRequired,
teamId: React.PropTypes.string.isRequired,
};
|
src/Game/UI/Row/Character.js | digijin/space-station-sim | //@flow
import {keys} from 'lodash'
import type Character from 'Game/Type/Character'
import Bar from 'Game/UI/Components/Bar'
import React from 'react'
import type {Skill} from 'Game/Data/Character/Skill'
type Props = {character:Character}
export default class CharacterRow extends React.Component {
props: Props
render() {
// let key = "char"+this.props.character.id;
let skills = []
if( this.props.character.type !== 'CUSTOMER'){
// FLOWHACK sigh more keys shit - TODO move this to datamap
Object.keys(this.props.character.skills).forEach((key:Skill) => {
let skill = this.props.character.skills[key];
// skills.push(<div>{key}-{skill}</div>);
skills.push(<Bar key={key} text={key} percent={skill} />)
})
}
return <div className="character row">
<div className="name">{this.props.character.toString()}</div>
<div className="type">{this.props.character.type}</div>
<div className="skills">
{skills}
</div>
</div>
}
}
|
test/js/AR/selectASurface.js | viromedia/viro | /**
* Copyright (c) 2017-present, Viro Media, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroScene,
ViroARScene,
ViroARPlane,
ViroBox,
ViroMaterials,
ViroNode,
ViroOrbitCamera,
ViroImage,
ViroVideo,
ViroSkyBox,
Viro360Video,
ViroText,
ViroQuad,
Viro3DObject
} from 'react-viro';
import TimerMixin from 'react-timer-mixin';
var createReactClass = require('create-react-class');
var position = [0,0,0];
var rotation = [0,0,0];
var width = 0;
var height = 0;
var boxStates = {}
for (var i = 0; i < 15; i++) {
boxStates["box" + i] = [.5,.5];
}
var testARScene = createReactClass({
mixins: [TimerMixin],
getInitialState: function() {
var initialState = {
text : "not tapped",
boxes: [],
count : 0,
width : .5,
selectedSurface : -1,
}
// amend the initial states with the boxStates
return Object.assign(initialState, boxStates);
},
render: function() {
return (
<ViroARScene ref="arscene" reticleEnabled={false} physicsWorld={{gravity:[0, -10,0], drawBounds : true}}>
{this._getARPlanes()}
{this._getBoxes()}
</ViroARScene>
);
},
/*
<ViroVideo
height={.2} width={.2} position={[0,.15,-.5]}
onClick={()=>{this._onTap(); this._addOneBox()}}
source={{"uri":"https://s3-us-west-2.amazonaws.com/viro/Climber1Top.mp4"}}
transformConstraints={"billboard"}
/>
<ViroText style={styles.welcome} position={[0, .5, -1]} text={this.state.text} />
*/
_getARPlanes() {
let prefix = "plane"
let planes = []
for (var i = 0; i < 15; i++) {
var color;
if (i%3 == 0) {
color = "blue"
} else if (i%3 == 1) {
color = "red"
} else {
color = "green"
}
planes.push((
<ViroARPlane key={prefix + i} onClick={this._addOneBox}
onAnchorFound={this._updateBoxState(i)} onAnchorUpdated={this._updateBoxState(i)}
visible={this.state.selectedSurface == -1 || this.state.selectedSurface == i}>
<ViroBox scale={[this.state["box" + i][0], .01, this.state["box" + i][1]]} position={[0,0,0]} rotation={[0,0,0]}
physicsBody={{
type:'static', restitution:0
}}
materials={color}
onClick={this._clickSurface(i)}/>
{this._getObject(i)}
</ViroARPlane>
));
}
return planes;
},
_clickSurface(planeNum) {
return () => {
this.setState({
selectedSurface : planeNum == this.state.selectedSurface ? -1 : planeNum
})
}
},
_getObject(planeNum) {
if (planeNum == this.state.selectedSurface) {
return (<Viro3DObject source={require('./res/aliengirl.obj')} scale={[.005,.005,.005]} type="OBJ"
materials={["aliengirl"]} onDrag={()=>{}} onClick={()=>{this.setState({showObj : false})}}/>)
}
},
_updateBoxState(boxNum) {
var boxKey = "box" + boxNum;
return (map)=>{
var newState = {};
newState[boxKey] = [map.width, map.height];
this.setState(newState);
}
},
_onComponentUpdated(map) {
console.log("------")
console.log(map.position);
console.log(map.rotation);
console.log(map.width);
console.log(map.width);
console.log("Diffs: ");
console.log([(map.position[0] - position[0]), (map.position[1] - position[1]), (map.position[2] - position[2])] )
console.log([(map.rotation[0] - rotation[0]), (map.rotation[1] - rotation[1]), (map.rotation[2] - rotation[2])] )
console.log(map.width - width);
console.log(map.height - height);
position = map.position;
rotation = map.rotation;
width = map.width;
height = map.height;
},
_getBoxes() {
let prefix = "box"
let boxes = [];
for (var i = 0; i < this.state.boxes.length; i++) {
boxes.push((<ViroBox key={prefix + i} position={this.state.boxes[i]} width={.1} height={.1} length={.1}
onDrag={()=>{}}
physicsBody={{
type:'dynamic',
mass:1
}} />));
}
return boxes;
},
_addOneBox() {
let position = this.refs["arscene"].getCameraPositionAsync().then((position) => {
this.state.boxes.push([position[0], 3, position[2] - .5])
this.setState({
boxes : this.state.boxes
})
});
},
_onTap() {
console.log("tapped video!!!!")
this.setState({
text : "tapped!"
})
this.setTimeout( () => {
this.setState({
text : "not tapped"
});
}, 1000);
},
_onLoadStart(component) {
return () => {
console.log("scene1 " + component + " load start");
}
},
_onLoadEnd(component) {
return () => {
console.log("scene1 " + component + " load end");
}
},
_onFinish(component) {
return () => {
console.log("scene1 " + component + " finished");
}
}
});
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFFFFF',
},
welcome: {
fontSize: 13,
textAlign: 'center',
color: '#ffffff',
margin: 2,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
ViroMaterials.createMaterials({
blue: {
shininess: 2.0,
lightingModel: "Constant",
diffuseColor: "#0000ff88"
},
green: {
shininess: 2.0,
lightingModel: "Constant",
diffuseColor: "#00ff0088"
},
red: {
shininess: 2.0,
lightingModel: "Constant",
diffuseColor: "#ff000088"
},
wework_title: {
shininess: 1.0,
lightingModel: "Constant",
diffuseTexture: {"uri": "https://s3-us-west-2.amazonaws.com/viro/guadalupe_360.jpg"},
diffuseTexture: require("../res/new_menu_screen.jpg"),
fresnelExponent: .5,
},
box_texture: {
diffuseTexture: require("../res/sun_2302.jpg"),
},
aliengirl: {
lightingModel: "Constant",
diffuseTexture: require('./res/aliengirl_diffuse.png'),
normalTexture: require('./res/aliengirl_normal.png'),
specularTexture: require('./res/aliengirl_specular.png')
},
});
module.exports = testARScene;
|
src/client/vendor/ReduxInfiniteScroll.js | busyorg/busy | import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
function topPosition(domElt) {
if (!domElt) {
return 0;
}
return domElt.offsetTop + topPosition(domElt.offsetParent);
}
function leftPosition(domElt) {
if (!domElt) {
return 0;
}
return domElt.offsetLeft + leftPosition(domElt.offsetParent);
}
export default class ReduxInfiniteScroll extends React.Component {
constructor(props) {
super(props);
this.scrollFunction = this.scrollListener.bind(this);
}
componentDidMount() {
this.attachScrollListener();
}
componentDidUpdate() {
this.attachScrollListener();
}
_findElement() {
return this.props.elementIsScrollable ? ReactDOM.findDOMNode(this) : window;
}
attachScrollListener() {
if (!this.props.hasMore || this.props.loadingMore) return;
let el = this._findElement();
el.addEventListener('scroll', this.scrollFunction, true);
el.addEventListener('resize', this.scrollFunction, true);
this.scrollListener();
}
_elScrollListener() {
let el = ReactDOM.findDOMNode(this);
if (this.props.horizontal) {
let leftScrollPos = el.scrollLeft;
let totalContainerWidth = el.scrollWidth;
let containerFixedWidth = el.offsetWidth;
let rightScrollPos = leftScrollPos + containerFixedWidth;
return totalContainerWidth - rightScrollPos;
}
let topScrollPos = el.scrollTop;
let totalContainerHeight = el.scrollHeight;
let containerFixedHeight = el.offsetHeight;
let bottomScrollPos = topScrollPos + containerFixedHeight;
return totalContainerHeight - bottomScrollPos;
}
_windowScrollListener() {
let el = ReactDOM.findDOMNode(this);
if (this.props.horizontal) {
let windowScrollLeft =
window.pageXOffset !== undefined
? window.pageXOffset
: (document.documentElement || document.body.parentNode || document.body).scrollLeft;
let elTotalWidth = leftPosition(el) + el.offsetWidth;
let currentRightPosition = elTotalWidth - windowScrollLeft - window.innerWidth;
return currentRightPosition;
}
let windowScrollTop =
window.pageYOffset !== undefined
? window.pageYOffset
: (document.documentElement || document.body.parentNode || document.body).scrollTop;
let elTotalHeight = topPosition(el) + el.offsetHeight;
let currentBottomPosition = elTotalHeight - windowScrollTop - window.innerHeight;
return currentBottomPosition;
}
scrollListener() {
// This is to prevent the upcoming logic from toggling a load more before
// any data has been passed to the component
if (this._totalItemsSize() <= 0) return;
let bottomPosition = this.props.elementIsScrollable
? this._elScrollListener()
: this._windowScrollListener();
if (bottomPosition < Number(this.props.threshold)) {
this.detachScrollListener();
this.props.loadMore();
}
}
detachScrollListener() {
let el = this._findElement();
el.removeEventListener('scroll', this.scrollFunction, true);
el.removeEventListener('resize', this.scrollFunction, true);
}
_renderOptions() {
const allItems = this.props.children.concat(this.props.items);
return allItems;
}
_totalItemsSize() {
let totalSize;
totalSize += this.props.children.size ? this.props.children.size : this.props.children.length;
totalSize += this.props.items.size ? this.props.items.size : this.props.items.length;
return totalSize;
}
componentWillUnmount() {
this.detachScrollListener();
}
renderLoader() {
return this.props.loadingMore && this.props.showLoader ? this.props.loader : undefined;
}
_assignHolderClass() {
let additionalClass;
additionalClass =
typeof this.props.className === 'function' ? this.props.className() : this.props.className;
return 'redux-infinite-scroll ' + additionalClass;
}
render() {
const Holder = this.props.holderType;
return (
<Holder className={this._assignHolderClass()} style={{ height: this.props.containerHeight }}>
{this._renderOptions()}
{this.renderLoader()}
</Holder>
);
}
}
ReduxInfiniteScroll.propTypes = {
elementIsScrollable: PropTypes.bool,
containerHeight: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
threshold: PropTypes.number,
horizontal: PropTypes.bool,
hasMore: PropTypes.bool,
loadingMore: PropTypes.bool,
loader: PropTypes.any,
showLoader: PropTypes.bool,
loadMore: PropTypes.func.isRequired,
items: PropTypes.node,
children: PropTypes.node,
holderType: PropTypes.string,
className: PropTypes.oneOfType([PropTypes.string, PropTypes.func]),
};
ReduxInfiniteScroll.defaultProps = {
className: '',
elementIsScrollable: true,
containerHeight: '100%',
threshold: 100,
horizontal: false,
hasMore: true,
loadingMore: false,
loader: <div style={{ textAlign: 'center' }}>Loading...</div>,
showLoader: true,
holderType: 'div',
children: [],
items: [],
};
|
src/svg-icons/content/drafts.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentDrafts = (props) => (
<SvgIcon {...props}>
<path d="M21.99 8c0-.72-.37-1.35-.94-1.7L12 1 2.95 6.3C2.38 6.65 2 7.28 2 8v10c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2l-.01-10zM12 13L3.74 7.84 12 3l8.26 4.84L12 13z"/>
</SvgIcon>
);
ContentDrafts = pure(ContentDrafts);
ContentDrafts.displayName = 'ContentDrafts';
ContentDrafts.muiName = 'SvgIcon';
export default ContentDrafts;
|
src/pagination/index.js | wisedu/bh-react | import React from 'react';
import RCPagination from 'rc-pagination';
import Select from 'rc-select';
require('rc-select/assets/index.css');
require('./bh-pagination.scss');
const prefixCls = 'bhr-pagination';
module.exports = React.createClass({
render: function() {
let className = this.props.className;
if (this.props.size === 'small') {
className += ' mini';
}
return <RCPagination selectComponentClass={Select}
{...this.props} prefixCls={prefixCls} className={className}/>;
}
});
|
src/components/Header.js | kjwatke/weather_app_updated_July-2017 | import React from 'react';
import Logo from './Logo';
const Header = () =>
(<div className="navbar-fixed">
<nav className="green darken-4">
<div className="nav-wrapper">
<Logo className="brand-logo" />
</div>
</nav>
</div>);
export default Header;
|
src/common/components/Error.js | nnnoel/graphql-apollo-resource-manager | import React from 'react';
import Box from 'grommet/components/Box';
import Anchor from 'grommet/components/Anchor';
import Article from 'grommet/components/Article';
import Status from 'grommet/components/icons/Status';
export default ({ message, onClick }) => (
<Article id="error-display" pad="none" full="vertical" direction="column">
<Box
flex={true}
full={false}
margin="small"
align="center"
justify="center"
>
<Status value="critical" size="medium" />{' '}
<Anchor onClick={onClick}>{message}</Anchor>
</Box>
</Article>
);
|
app/components/svg/index.js | ayrton/pinata | /* @flow */
import InlineSVG from 'svg-inline-react';
import React from 'react';
/**
* Svg component.
*/
export default function Svg(props: Object): ReactElement {
return (
<InlineSVG raw={true} {...props} />
);
}
|
frontend/src/Activity/Queue/QueueRowConnector.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { grabQueueItem, removeQueueItem } from 'Store/Actions/queueActions';
import createMovieSelector from 'Store/Selectors/createMovieSelector';
import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector';
import QueueRow from './QueueRow';
function createMapStateToProps() {
return createSelector(
createMovieSelector(),
createUISettingsSelector(),
(movie, uiSettings) => {
const result = {
showRelativeDates: uiSettings.showRelativeDates,
shortDateFormat: uiSettings.shortDateFormat,
timeFormat: uiSettings.timeFormat
};
result.movie = movie;
return result;
}
);
}
const mapDispatchToProps = {
grabQueueItem,
removeQueueItem
};
class QueueRowConnector extends Component {
//
// Listeners
onGrabPress = () => {
this.props.grabQueueItem({ id: this.props.id });
};
onRemoveQueueItemPress = (payload) => {
this.props.removeQueueItem({ id: this.props.id, ...payload });
};
//
// Render
render() {
return (
<QueueRow
{...this.props}
onGrabPress={this.onGrabPress}
onRemoveQueueItemPress={this.onRemoveQueueItemPress}
/>
);
}
}
QueueRowConnector.propTypes = {
id: PropTypes.number.isRequired,
movie: PropTypes.object,
grabQueueItem: PropTypes.func.isRequired,
removeQueueItem: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, mapDispatchToProps)(QueueRowConnector);
|
js/components/Form.react.js | mxstbr/login-flow | /**
* Form.react.js
*
* The form with a username and a password input field, both of which are
* controlled via the application state.
*
*/
import React, { Component } from 'react';
import { changeForm } from '../actions/AppActions';
import LoadingButton from './LoadingButton.react';
import ErrorMessage from './ErrorMessage.react';
// Object.assign is not yet fully supported in all browsers, so we fallback to
// a polyfill
const assign = Object.assign || require('object.assign');
class LoginForm extends Component {
render() {
return(
<form className="form" onSubmit={this._onSubmit.bind(this)}>
<ErrorMessage />
<div className="form__field-wrapper">
<input className="form__field-input" type="text" id="username" value={this.props.data.username} placeholder="frank.underwood" onChange={this._changeUsername.bind(this)} autoCorrect="off" autoCapitalize="off" spellCheck="false" />
<label className="form__field-label" htmlFor="username">Username</label>
</div>
<div className="form__field-wrapper">
<input className="form__field-input" id="password" type="password" value={this.props.data.password} placeholder="••••••••••" onChange={this._changePassword.bind(this)} />
<label className="form__field-label" htmlFor="password">Password</label>
</div>
<div className="form__submit-btn-wrapper">
{this.props.currentlySending ? (
<LoadingButton />
) : (
<button className="form__submit-btn" type="submit">{this.props.btnText}</button>
)}
</div>
</form>
);
}
// Change the username in the app state
_changeUsername(evt) {
var newState = this._mergeWithCurrentState({
username: evt.target.value
});
this._emitChange(newState);
}
// Change the password in the app state
_changePassword(evt) {
var newState = this._mergeWithCurrentState({
password: evt.target.value
});
this._emitChange(newState);
}
// Merges the current state with a change
_mergeWithCurrentState(change) {
return assign(this.props.data, change);
}
// Emits a change of the form state to the application state
_emitChange(newState) {
this.props.dispatch(changeForm(newState));
}
// onSubmit call the passed onSubmit function
_onSubmit(evt) {
evt.preventDefault();
this.props.onSubmit(this.props.data.username, this.props.data.password);
}
}
LoginForm.propTypes = {
onSubmit: React.PropTypes.func.isRequired,
btnText: React.PropTypes.string.isRequired,
data: React.PropTypes.object.isRequired
}
export default LoginForm;
|
src/parser/deathknight/unholy/modules/runicpower/RunicPowerDetails.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import Panel from 'interface/others/Panel';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import { formatPercentage } from 'common/format';
import Icon from 'common/Icon';
import ResourceBreakdown from 'parser/shared/modules/resourcetracker/ResourceBreakdown';
import RunicPowerTracker from './RunicPowerTracker';
class RunicPowerDetails extends Analyzer {
static dependencies = {
runicPowerTracker: RunicPowerTracker,
};
get wastedPercent(){
return this.runicPowerTracker.wasted / (this.runicPowerTracker.wasted + this.runicPowerTracker.generated) || 0;
}
get efficiencySuggestionThresholds() {
return {
actual: 1 - this.wastedPercent,
isLessThan: {
minor: 0.95,
average: 0.90,
major: .85,
},
style: 'percentage',
};
}
get suggestionThresholds() {
return {
actual: this.wastedPercent,
isGreaterThan: {
minor: 0.05,
average: 0.1,
major: .15,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(`You wasted ${formatPercentage(this.wastedPercent)}% of your Runic Power.`)
.icon('inv_sword_62')
.actual(`${formatPercentage(actual)}% wasted`)
.recommended(`<${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<Icon icon="inv_sword_62" />}
value={`${formatPercentage(this.wastedPercent)} %`}
label="Runic Power wasted"
tooltip={`${this.runicPowerTracker.wasted} out of ${this.runicPowerTracker.wasted + this.runicPowerTracker.generated} runic power wasted.`}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(2);
tab() {
return {
title: 'Runic Power usage',
url: 'runic-power-usage',
render: () => (
<Panel>
<ResourceBreakdown
tracker={this.runicPowerTracker}
showSpenders
/>
</Panel>
),
};
}
}
export default RunicPowerDetails;
|
src/ChallengeMeta4/index.js | christianalfoni/ducky-components | import React from 'react';
import PropTypes from 'prop-types';
import Typography from '../Typography';
import LabelSmall from '../LabelSmall';
import classNames from 'classnames';
import styles from './styles.css';
function ChallengeMeta4(props) {
let teamLabel = '';
if (props.yourTeam) {
teamLabel = props.yourTeamText;
}
return (
<div className={classNames(styles.wrapper, {
[props.className]: props.className
})}>
<Typography
className={classNames(styles.nameLightBackground, {
[styles.nameDarkBackground]: props.theme === 'dark'
})}
type="bodyTextStrong"
>
{props.name}
</Typography>
<div className={styles.statsWrapper}>
<LabelSmall
className={classNames(styles.membersLightBackground, {
[styles.membersDarkBackground]: props.theme === 'dark'
})}
content={props.members}
icon={'icon-people'}
type={"caption2Normal"}
/>
<Typography
className={classNames(styles.labelLightBackground, {
[styles.labelDarkBackground]: props.theme === 'dark'
})}
type="caption2Normal"
>
{teamLabel}
</Typography>
</div>
</div>
);
}
ChallengeMeta4.propTypes = {
className: PropTypes.string,
isLeader: PropTypes.bool,
members: PropTypes.number,
name: PropTypes.string,
theme: PropTypes.string,
yourTeam: PropTypes.bool,
yourTeamText: PropTypes.string
};
export default ChallengeMeta4;
|
src/js/components/pagination/pagination.js | rafaelfbs/realizejs | import React, { Component } from 'react';
import PropTypes from '../../prop_types';
import { mixin } from '../../utils/decorators';
import { CssClassMixin } from '../../mixins';
import { Input, PaginationItem } from '../../components';
@mixin(CssClassMixin)
export default class Pagination extends Component {
static propTypes = {
count: PropTypes.number,
page: PropTypes.number,
perPage: PropTypes.number,
window: PropTypes.number,
onPagination: PropTypes.func,
type: PropTypes.string
};
static defaultProps = {
themeClassKey: 'pagination',
page: 1,
perPage: 20,
window: 4,
onPagination: function(page) {
return true;
}
};
renderPaginationByType () {
if (this.props.type == 'default')
return (
<span>
{this.renderFirstButton()}
{this.renderPageButtons()}
{this.renderLastButton()}
</span>
);
else if (this.props.type == 'input')
return (
<span>{this.renderPageInput()}</span>
);
}
renderPreviousButton () {
var disabled = (this.props.page <= 1);
return (
<PaginationItem disabled={disabled} iconType="left" onClick={this.navigateToPrevious} />
);
}
renderFirstButton () {
if(this.firstWindowPage() <= 1) {
return '';
}
return (
<PaginationItem text="..." onClick={this.navigateTo.bind(this, 1)} />
);
}
renderNextButton () {
var disabled = (this.props.page >= this.lastPage());
return (
<PaginationItem disabled={disabled} iconType="right" onClick={this.navigateToNext} />
);
}
renderLastButton () {
var lastPage = this.lastPage();
if(this.lastWindowPage() >= lastPage) {
return '';
}
return (
<PaginationItem text="..." onClick={this.navigateTo.bind(this, lastPage)} />
);
}
renderPageButtons () {
var pageButtons = [];
for(var i = this.firstWindowPage(); i <= this.lastWindowPage(); i++) {
pageButtons.push(this.renderPageButton(i));
}
return pageButtons;
}
renderPageButton (page) {
var active = (this.props.page === page);
return (
<PaginationItem active={active} text={String(page)} onClick={this.navigateTo.bind(this, page)} key={"page_" + page} />
);
}
renderPageInput () {
var page = this.props.page;
return (
<Input value={page} clearTheme={true} className='form__input input-field col s3' />
)
}
render () {
return (
<ul className={this.className()}>
{this.renderPreviousButton()}
{this.renderPaginationByType()}
{this.renderNextButton()}
</ul>
);
}
lastPage () {
return Math.ceil(this.props.count / this.props.perPage);
}
firstWindowPage () {
return Math.max(1, this.props.page - this.props.window);
}
lastWindowPage () {
return Math.min(this.lastPage(), this.props.page + this.props.window);
}
navigateToPrevious = () => {
var pageToNavigate = Math.max(1, this.props.page - 1);
this.navigateTo(pageToNavigate);
}
navigateToNext = () => {
var pageToNavigate = Math.min(this.lastPage(), this.props.page + 1);
this.navigateTo(pageToNavigate);
}
navigateTo (page) {
this.props.onPagination(page);
}
}
|
jenkins-design-language/src/js/components/material-ui/svg-icons/notification/phone-paused.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const NotificationPhonePaused = (props) => (
<SvgIcon {...props}>
<path d="M17 3h-2v7h2V3zm3 12.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 3v7h2V3h-2z"/>
</SvgIcon>
);
NotificationPhonePaused.displayName = 'NotificationPhonePaused';
NotificationPhonePaused.muiName = 'SvgIcon';
export default NotificationPhonePaused;
|
src/svg-icons/action/invert-colors.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInvertColors = (props) => (
<SvgIcon {...props}>
<path d="M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58c2.05 0 4.1-.78 5.66-2.34 3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/>
</SvgIcon>
);
ActionInvertColors = pure(ActionInvertColors);
ActionInvertColors.displayName = 'ActionInvertColors';
ActionInvertColors.muiName = 'SvgIcon';
export default ActionInvertColors;
|
src/pages/index.js | victormoya/lavergeweb | import React from 'react';
import Helmet from 'react-helmet';
import PlayButton from '../components/playButton';
import Modal from 'react-modal';
import Template from '../layouts/template';
import '../../static/scss/all.scss';
const modalStyles = {
content: {
top: '50%',
left: '50%',
right: 'auto',
bottom: 'auto',
marginRight: '-50%',
transform: 'translate(-50%, -50%)',
backgroundColor: '#000',
border: 'none',
borderRadius: '0'
},
overlay: {
backgroundColor: 'rgba(0,0,0,0.71)'
}
};
class IndexPage extends React.Component {
constructor() {
super();
this.state = {
showModal: false
};
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
}
handleOpenModal() {
this.setState({ showModal: true });
}
handleCloseModal() {
this.setState({ showModal: false });
}
render() {
return (
<Template>
<div className="video-bg">
<Helmet
title="LAVERGE"
meta={[
{
name: 'description',
content: 'Laverge new sigle Sophisticated'
},
{
name: 'keywords',
content: 'laverge, rock, sophisticated'
},
{
name: 'viewport',
content:
'width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0'
}
]}
/>
<div onClick={this.handleOpenModal}>
<PlayButton />
</div>
<Modal
isOpen={this.state.showModal}
shouldCloseOnOverlayClick={true}
style={modalStyles}
>
<a onClick={this.handleCloseModal} className="close" />
<div className="video-wrapper">
<iframe
width="1280"
height="720"
frameBorder="0"
src="https://www.youtube.com/embed/e2-jyBp3QaM?controls=0&showinfo=0&rel=0&autoplay=1&loop=1"
/>
</div>
</Modal>
</div>
</Template>
);
}
}
export default IndexPage;
|
src/Router.js | allfix53/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import Router from 'react-routing/src/Router';
import http from './core/HttpClient';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import LoginPage from './components/LoginPage';
import RegisterPage from './components/RegisterPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
const router = new Router(on => {
on('*', async (state, next) => {
const component = await next();
return component && <App context={state.context}>{component}</App>;
});
on('/contact', async () => <ContactPage />);
on('/login', async () => <LoginPage />);
on('/register', async () => <RegisterPage />);
on('*', async (state) => {
const content = await http.get(`/api/content?path=${state.path}`);
return content && <ContentPage {...content} />;
});
on('error', (state, error) => state.statusCode === 404 ?
<App context={state.context} error={error}><NotFoundPage /></App> :
<App context={state.context} error={error}><ErrorPage /></App>
);
});
export default router;
|
react-router-tutorial/lessons/11-productionish-server/modules/Repo.js | zerotung/practices-and-notes | import React from 'react'
export default React.createClass({
render() {
return (
<div>
<h2>{this.props.params.repoName}</h2>
</div>
)
}
})
|
src/hoc/selectable-enhance.js | mikedklein/material-ui | import React from 'react';
import ThemeManager from '../styles/theme-manager';
import StylePropable from '../mixins/style-propable';
import ColorManipulator from '../utils/color-manipulator';
import DefaultRawTheme from '../styles/raw-themes/light-raw-theme';
export const SelectableContainerEnhance = (Component) => {
const composed = React.createClass({
displayName: `Selectable${Component.displayName}`,
propTypes: {
children: React.PropTypes.node,
selectedItemStyle: React.PropTypes.object,
valueLink: React.PropTypes.shape({
value: React.PropTypes.any,
requestChange: React.PropTypes.func,
}).isRequired,
},
contextTypes: {
muiTheme: React.PropTypes.object,
},
childContextTypes: {
muiTheme: React.PropTypes.object,
},
mixins: [
StylePropable,
],
getInitialState() {
return {
muiTheme: this.context.muiTheme ? this.context.muiTheme : ThemeManager.getMuiTheme(DefaultRawTheme),
};
},
getChildContext() {
return {
muiTheme: this.state.muiTheme,
};
},
componentWillReceiveProps(nextProps, nextContext) {
let newMuiTheme = nextContext.muiTheme ? nextContext.muiTheme : this.state.muiTheme;
this.setState({muiTheme: newMuiTheme});
},
getValueLink: function(props) {
return props.valueLink || {
value: props.value,
requestChange: props.onChange,
};
},
_extendChild(child, styles, selectedItemStyle) {
if (child && child.type && child.type.displayName === 'ListItem') {
let selected = this._isChildSelected(child, this.props);
let selectedChildrenStyles = {};
if (selected) {
selectedChildrenStyles = this.mergeStyles(styles, selectedItemStyle);
}
let mergedChildrenStyles = this.mergeStyles(child.props.style || {}, selectedChildrenStyles);
this._keyIndex += 1;
return React.cloneElement(child, {
onTouchTap: (e) => {
this._handleItemTouchTap(e, child);
if (child.props.onTouchTap) {
child.props.onTouchTap(e);
}
},
key: this._keyIndex,
style: mergedChildrenStyles,
nestedItems: child.props.nestedItems.map((child) => this._extendChild(child, styles, selectedItemStyle)),
});
} else {
return child;
}
},
_isChildSelected(child, props) {
let itemValue = this.getValueLink(props).value;
let childValue = child.props.value;
return (itemValue && itemValue === childValue);
},
_handleItemTouchTap(e, item) {
let valueLink = this.getValueLink(this.props);
let itemValue = item.props.value;
let menuValue = valueLink.value;
if ( itemValue !== menuValue) {
valueLink.requestChange(e, itemValue);
}
},
render() {
const {children, selectedItemStyle} = this.props;
this._keyIndex = 0;
let styles = {};
if (!selectedItemStyle) {
let textColor = this.state.muiTheme.rawTheme.palette.textColor;
let selectedColor = ColorManipulator.fade(textColor, 0.2);
styles = {
backgroundColor: selectedColor,
};
}
let newChildren = React.Children.map(children, (child) => this._extendChild(child, styles, selectedItemStyle));
return (
<Component {...this.props} {...this.state}>
{newChildren}
</Component>
);
},
});
return composed;
};
export default SelectableContainerEnhance;
|
client/src/dataProviders/sharedDataProviders.js | verejnedigital/verejne.digital | // @flow
import React from 'react'
import {receiveData} from '../actions/sharedActions'
import {setEntityDetails} from '../actions/publicActions'
import {ModalLoading} from '../components/Loading/Loading'
import type {Company, NewEntityDetail} from '../state'
import type {Dispatch} from '../types/reduxTypes'
import type {ObjectMap} from '../types/commonTypes'
const dispatchCompanyDetails = (eid: number) => (
ref: string,
data: Company,
dispatch: Dispatch
) => {
dispatch(receiveData(['companies'], {id: eid, eid, ...data}, ref))
}
const dispatchEntitySearch = (query: string) => (
ref: string,
data: Array<{eid: number}>,
dispatch: Dispatch
) => {
dispatch(receiveData(['entitySearch'], {id: query, query, eids: data.map(({eid}) => eid)}, ref))
}
const dispatchEntityDetails = () => (
ref: string,
data: ObjectMap<NewEntityDetail>,
dispatch: Dispatch
) => {
dispatch(setEntityDetails(data))
}
export const companyDetailProvider = (eid: number, needed: boolean = true) => {
return {
ref: `companyDetail-${eid}`,
getData: [
fetch,
`${process.env.REACT_APP_API_URL || ''}/api/v/getInfo?eid=${eid}`,
{
accept: 'application/json',
},
],
onData: [dispatchCompanyDetails, eid],
keepAliveFor: 60 * 60 * 1000,
needed,
}
}
export const entitySearchProvider = (
query: string,
modalLoading: boolean = false,
needed: boolean = true
) => ({
ref: `entitySearch-${query}`,
getData: [
fetch,
`${process.env.REACT_APP_API_URL || ''}/api/v/searchEntityByName?name=${query}`,
{
accept: 'application/json',
},
],
onData: [dispatchEntitySearch, query],
keepAliveFor: 60 * 60 * 1000,
loadingComponent: modalLoading ? <ModalLoading /> : undefined,
needed,
})
export const entityDetailProvider = (eid: number | number[], needed: boolean = true) => {
const requestPrefix = `${process.env.REACT_APP_API_URL || ''}`
return {
ref: `entityDetail-${eid.toString()}`,
getData: [
fetch,
`${requestPrefix}/api/v/getInfos?eids=${eid.toString()}`,
{
accept: 'application/json',
},
],
onData: [dispatchEntityDetails],
keepAliveFor: 60 * 60 * 1000,
loadingComponent: <ModalLoading />,
needed,
}
}
|
indico/web/client/js/jquery/widgets/jinja/datetime_widget.js | indico/indico | // This file is part of Indico.
// Copyright (C) 2002 - 2022 CERN
//
// Indico is free software; you can redistribute it and/or
// modify it under the terms of the MIT License; see the
// LICENSE file for more details.
import React from 'react';
import ReactDOM from 'react-dom';
import {WTFDateTimeField} from 'indico/react/components';
import {localeUses24HourTime} from 'indico/utils/date';
window.setupDateTimeWidget = function setupDateTimeWidget(options) {
options = $.extend(
true,
{
fieldId: null,
timezoneFieldId: null,
timezone: null,
defaultTime: null,
locale: null,
required: false,
disabled: false,
allowClear: false,
earliest: null,
latest: null,
linkedField: {
id: null,
notBefore: false,
notAfter: false,
},
},
options
);
// Make sure the results dropdown are displayed above the dialog.
const field = $(`#${options.fieldId}`);
field.closest('.ui-dialog-content').css('overflow', 'inherit');
field.closest('.exclusivePopup').css('overflow', 'inherit');
ReactDOM.render(
<WTFDateTimeField
timeId={`${options.fieldId}-timestorage`}
dateId={`${options.fieldId}-datestorage`}
timezoneFieldId={options.timezoneFieldId}
timezone={options.timezone}
uses24HourFormat={localeUses24HourTime(options.locale.replace('_', '-'))}
required={options.required}
disabled={options.disabled}
allowClear={options.allowClear}
earliest={options.earliest}
latest={options.latest}
defaultTime={options.defaultTime}
linkedField={options.linkedField}
/>,
document.getElementById(options.fieldId)
);
};
|
information/blendle-frontend-react-source/app/components/dialogues/Confirm.js | BramscoChill/BlendleParser | import React from 'react';
import PropTypes from 'prop-types';
import Dialogue from './Dialogue';
import Button from 'components/Button';
import classNames from 'classnames';
import { keyCode } from 'app-constants';
class Confirm extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
message: PropTypes.node.isRequired,
buttonText: PropTypes.string.isRequired,
onClose: PropTypes.func,
onConfirm: PropTypes.func.isRequired,
className: PropTypes.string,
children: PropTypes.any,
};
_onConfirm = (e) => {
this.confirmed = true;
this.props.onConfirm(e);
};
_onClose = () => {
this.props.onClose();
};
_onKeyDown = (e) => {
if (e.keyCode === keyCode.RETURN) {
this.props.onConfirm(e);
}
};
render() {
const { className, title, message, buttonText } = this.props;
const dialogClassName = classNames('v-confirm', 's-success', 'dialogue-content', className);
return (
<Dialogue {...this.props} onKeyDown={this._onKeyDown} className={dialogClassName}>
<h2 className="title">{title}</h2>
<p className="more">{message}</p>
<Button className="btn-fullwidth btn-confirm" onClick={() => this._onConfirm()}>
{buttonText}
</Button>
</Dialogue>
);
}
}
export default Confirm;
// WEBPACK FOOTER //
// ./src/js/app/components/dialogues/Confirm.js |
src/icons/AndroidRadioButtonOff.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidRadioButtonOff extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g id="Icon_20_">
<g>
<path d="M256,48C141.601,48,48,141.601,48,256s93.601,208,208,208s208-93.601,208-208S370.399,48,256,48z M256,422.399
c-91.518,0-166.399-74.882-166.399-166.399S164.482,89.6,256,89.6S422.4,164.482,422.4,256S347.518,422.399,256,422.399z"></path>
</g>
</g>
</g>;
} return <IconBase>
<g id="Icon_20_">
<g>
<path d="M256,48C141.601,48,48,141.601,48,256s93.601,208,208,208s208-93.601,208-208S370.399,48,256,48z M256,422.399
c-91.518,0-166.399-74.882-166.399-166.399S164.482,89.6,256,89.6S422.4,164.482,422.4,256S347.518,422.399,256,422.399z"></path>
</g>
</g>
</IconBase>;
}
};AndroidRadioButtonOff.defaultProps = {bare: false} |
src/routes.js | cessien/buzzer | // src/routes.js
import React from 'react'
import { Route, IndexRoute, browserHistory } from 'react-router'
import Base from './components/Base';
import IndexPage from './components/IndexPage';
import Login from './components/Login';
import Splash from './components/Splash';
import Register from './components/Register';
import SignUp from './components/SignUp';
import Thanks from './components/Thanks';
import Profile from './components/Profile';
import NotFoundPage from './components/NotFoundPage';
import ChooseTeam from './components/cSignUp/Team';
import PaymentPage from './components/cSignUp/Payment';
import requireAuth from './utils/authenticated';
const routes = (
<Route path="/" component={Base} history={browserHistory}>
<IndexRoute component={Splash} />
<Route path="/login" component={Login} />
<Route path="/register" component={Register} />
<Route path="/signup" component={SignUp} />
<Route path="/signup/teams" component={ChooseTeam} />
<Route path="/signup/payment" component={PaymentPage} />
<Route path="/thanks" component={Thanks} />
<Route path="/user/profile" component={Profile} onEnter={requireAuth} />
<Route path="/home" component={IndexPage} onEnter={requireAuth}/>
<Route path="*" component={NotFoundPage}/>
</Route>
);
export default routes;
|
src/containers/AppGame.js | jonishaso/nice-tdl | import React, { Component } from 'react';
import '../style/game.css';
const selectedCell = {
background: "white"
}
const randomCell = {
background: "green"
}
const crashCell = {
background: "orange"
}
let sytleShow = (self, randomString, currentString) => {
// isCurrent = selectedCell , isRandom = randonCell, isBoth = crashCell, Nothing =0
if (self === currentString && self === randomString) return crashCell
if (self !== currentString && self === randomString) return randomCell
if (self === currentString && self !== randomString) return selectedCell
if (self !== currentString && self !== randomString) return {}
}
class GameApp extends Component {
constructor() {
super();
this.state = {
X: 0,
Y: 0,
a: Math.floor(Math.random() * 4),
b: Math.floor(Math.random() * 4),
}
this.handleKeyPress = this.handleKeyPress.bind(this);
}
componentDidMount() {
window.addEventListener('keydown', this.handleKeyPress)
}
componentWillMount() {
window.removeEventListener('keydown', this.handleKeyPress)
}
handleKeyPress() {
switch (window.event.keyCode) {
case 37: {
if (this.state.Y !== 0) {
if ((this.state.Y - 1) === this.state.b && (this.state.X) === this.state.a) {
this.setState({
Y: (this.state.Y - 1),
a: Math.floor(Math.random() * 4),
b: Math.floor(Math.random() * 4),
})
}
else
this.setState({ Y: (this.state.Y - 1) })
}
break;
}
case 38: {
if (this.state.X !== 0) {
if ((this.state.X - 1) === this.state.a && (this.state.Y) === this.state.b) {
this.setState({
X: (this.state.X - 1),
a: Math.floor(Math.random() * 4),
b: Math.floor(Math.random() * 4),
})
}
else
this.setState({ X: (this.state.X - 1) })
}
break;
}
case 39: {
if (this.state.Y !== 4) {
if ((this.state.Y + 1) === this.state.b && (this.state.X) === this.state.a) {
this.setState({
Y: (this.state.Y + 1),
a: Math.floor(Math.random() * 4),
b: Math.floor(Math.random() * 4),
})
}
else
this.setState({ Y: (this.state.Y + 1) })
}
break;
}
case 40: {
if (this.state.X !== 4) {
if ((this.state.X + 1) === this.state.a && (this.state.Y) === this.state.b) {
this.setState({
X: (this.state.X + 1),
a: Math.floor(Math.random() * 4),
b: Math.floor(Math.random() * 4),
})
}
else
this.setState({ X: (this.state.X + 1) })
}
break;
}
default:
}
return
}
render() {
let currentPosition = this.state.X.toString() + '-' + this.state.Y.toString();
let randomPositio = this.state.a.toString() + '-' + this.state.b.toString();
return (
<div className="container-fluid" style={{ background: "#292b2c",height:'100%' }}>
<div className="row justify-content-center">
<p className="lead col-sm-5 my-1" style={{ color: "white" }}>
Try to catch the Green BoX, if the Box turn to organge, means you got it.
</p>
</div>
<div className="row justify-content-center">
<div className="col-sm-7 offset-sm-3 mb-1 mt-4">
<div className="grid-cell" style={sytleShow('0-0', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('0-1', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('0-2', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('0-3', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('0-4', randomPositio, currentPosition)} />
</div>
</div>
<div className="row justify-content-center">
<div className="col-sm-7 offset-sm-3 my-2">
<div className="grid-cell" style={sytleShow('1-0', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('1-1', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('1-2', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('1-3', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('1-4', randomPositio, currentPosition)} />
</div>
</div>
<div className="row justify-content-center">
<div className="col-sm-7 offset-sm-3 my-2">
<div className="grid-cell" style={sytleShow('2-0', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('2-1', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('2-2', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('2-3', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('2-4', randomPositio, currentPosition)} />
</div>
</div>
<div className="row justify-content-center">
<div className="col-sm-7 offset-sm-3 my-2">
<div className="grid-cell" style={sytleShow('3-0', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('3-1', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('3-2', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('3-3', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('3-4', randomPositio, currentPosition)} />
</div>
</div>
<div className="row justify-content-center">
<div className="col-sm-7 offset-sm-3 mb-5 mt-1">
<div className="grid-cell" style={sytleShow('4-0', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('4-1', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('4-2', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('4-3', randomPositio, currentPosition)} />
<div className="grid-cell" style={sytleShow('4-4', randomPositio, currentPosition)} />
</div>
</div>
</div>
)
}
}
export default GameApp;
|
src/templates/article.js | yen223/yens-blog | import React from 'react'
import Link from 'gatsby-link'
import Typography from 'typography'
export const Article = (props) => {
const article = props.data.markdownRemark
const html = {__html: article.html}
return (
<div>
<h1> {article.frontmatter.title} </h1>
<div dangerouslySetInnerHTML={html} />
</div>
)
}
export default Article
export const pageQuery = graphql`
query ArticleBySlug($slug: String!) {
markdownRemark(frontmatter: { slug: { eq: $slug } }) {
html
frontmatter {
title
date(formatString: "MMMM DD, YYYY")
}
}
}
`
|
packages/web/src/components/modal/ModalPortal.js | hwaterke/inab | import PropTypes from 'prop-types'
import React from 'react'
/**
* This is the basic presentation for a modal.
* It should never be used alone.
* The Modal component renders this in a modal div using a react portal
*/
export class ModalPortal extends React.Component {
static propTypes = {
children: PropTypes.node.isRequired,
onCloseRequested: PropTypes.func,
disableBackgroundClose: PropTypes.bool,
disableCloseButton: PropTypes.bool,
}
static defaultProps = {
onCloseRequested: null,
disableBackgroundClose: false,
disableCloseButton: false,
}
render() {
const {
children,
onCloseRequested,
disableBackgroundClose,
disableCloseButton,
} = this.props
return (
<div className="modal is-active">
<div
className="modal-background"
onClick={disableBackgroundClose ? null : onCloseRequested}
/>
<div className="modal-content">{children}</div>
{disableCloseButton || (
<button
onClick={onCloseRequested}
type="button"
className="modal-close is-large"
aria-label="close"
/>
)}
</div>
)
}
}
|
demo/input/index.js | hhhyaaon/chequer | import React from 'react';
import ReactDOM from 'react-dom';
import Container from '../../tpls/index';
import Input from '../../components/input';
import Icon from '../../components/icon';
import './index.scss';
export default class D_Input extends React.Component {
constructor(props) {
super(props);
}
render() {
const conf = {
};
return (
<div>
<fieldset>
<legend>普通输入框</legend>
<div>
<ul className="input-demo-1">
<li>
<div>姓名</div>
<Input value="hyaaon" />
</li>
<li>
<div>密码</div>
<Input type="password" value="123" />
</li>
<li>
<div>多行文本</div>
<Input type="textarea" value="hello world" />
</li>
</ul>
</div>
</fieldset>
<fieldset>
<legend>前缀/后缀</legend>
<div>
<ul className="input-demo-1">
<li>
<div>金额</div>
<Input
value="100"
prefix="$" />
</li>
<li>
<div>概率</div>
<Input
suffix="%"
value="50" />
</li>
<li>
<div>前后缀</div>
<Input
value="23"
prefix="第"
suffix="行" />
</li>
<li>
<div>图标</div>
<Input
value="正确"
prefix={<Icon type="tick-circle" />} />
</li>
</ul>
</div>
</fieldset>
<fieldset>
<legend>禁用输入框</legend>
<div>
<ul className="input-demo-1">
<li>
<div>姓名</div>
<Input
disabled={true} />
</li>
<li>
<div>密码</div>
<Input
type="password"
disabled={true} />
</li>
<li>
<div>多行文本</div>
<Input
type="textarea"
disabled={true} />
</li>
</ul>
</div>
</fieldset>
<fieldset>
<legend>只读输入框</legend>
<div>
<ul className="input-demo-1">
<li>
<div>姓名</div>
<Input
value='value'
readonly={true} />
</li>
<li>
<div>密码</div>
<Input
type="password"
value='value'
readonly={true} />
</li>
<li>
<div>多行文本</div>
<Input
type="textarea"
value='value'
readonly={true} />
</li>
</ul>
</div>
</fieldset>
<fieldset>
<legend>事件</legend>
<div>
<ul className="input-demo-1">
<li>
<div>姓名</div>
<Input
value='value'
onChange={(v) => { console.log(v); }} />
</li>
<li>
<div>多行文本</div>
<Input
type="textarea"
onChange={(v) => { console.log(v); }} />
</li>
</ul>
</div>
</fieldset>
</div>
);
}
}
ReactDOM.render(
<Container>
<D_Input />
</Container>,
document.getElementById('container')); |
static/src/containers/App/index.js | pfarnach/pulse | import React, { Component } from 'react';
import socket from '../../utils/socket';
import _ from 'lodash';
import MapContainer from '../MapContainer/mapContainer';
import './style.scss';
const sendPulse = _.debounce(() => socket.emit('client_pulse', {}), 500, { leading: true });
export class App extends Component {
render() {
return (
<div className="main-container">
<section className="content-container">
<div className="title-container">
<h1 className="title"><span className="title-1">LGBTQ</span><span className="title-2">Pulse</span></h1>
</div>
<MapContainer />
<button onClick={()=>sendPulse()}>CLICK</button>
<div className="info-container">
<div className="how">
<h3><span className="red"><</span> HOW TO <span className="red">></span></h3>
<h5><span className="red">>></span> Click the big button</h5>
<h5><span className="red">>></span> Watch your dot pop up on the map</h5>
</div>
<div className="about">
<h3><span className="red"><</span> ABOUT <span className="red">></span></h3>
<h5>This is a simple way to visualize support around the world for the LGBTQ community. Wherever you are, whenever you want, for as much time as you feel like, you can share your love and the rest of the world will see it.</h5>
<h5>No logins, no ads, just love.</h5>
</div>
</div>
</section>
</div>
);
}
}
|
src/TodoApp/TodoList/Todo.js | ksmithbaylor/react-todo-list | import React from 'react';
export default class Todo extends React.Component {
static propTypes = {
text: React.PropTypes.string.isRequired
}
state = {
completed: false
}
render() {
const style = {
textDecoration: this.state.completed ? 'line-through' : undefined,
marginTop: '0',
marginBottom: '0.2em'
};
return (
<p style={style} onClick={this.toggleCompleted}>
{this.props.text}
</p>
);
}
toggleCompleted = (event) => {
this.setState({ completed: !this.state.completed });
}
}
|
examples/counter/containers/App.js | ytiurin/redux | import React, { Component } from 'react';
import CounterApp from './CounterApp';
import { createRedux } from 'redux';
import { Provider } from 'redux/react';
import * as stores from '../stores';
const redux = createRedux(stores);
export default class App extends Component {
render() {
return (
<Provider redux={redux}>
{() => <CounterApp />}
</Provider>
);
}
}
|
src/react.js | ze-flo/redux | import React from 'react';
import createAll from './components/createAll';
export const { Provider, Connector, provide, connect } = createAll(React);
|
example/src/index.js | erikras/redux-form-material-ui | import React from 'react'
import ReactDOM from 'react-dom'
import injectTapEventPlugin from 'react-tap-event-plugin'
import { Provider } from 'react-redux'
import { createStore, combineReducers } from 'redux'
import { reducer as reduxFormReducer } from 'redux-form'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import { Code, Markdown, Values } from 'redux-form-website-template'
injectTapEventPlugin()
const dest = document.getElementById('content')
const reducer = combineReducers({
form: reduxFormReducer // mounted under "form"
})
const store = (window.devToolsExtension
? window.devToolsExtension()(createStore)
: createStore)(reducer)
const showResults = values =>
new Promise(resolve => {
setTimeout(() => {
// simulate server latency
window.alert(`You submitted:\n\n${JSON.stringify(values, null, 2)}`)
resolve()
}, 500)
})
let render = () => {
const Form = require('./Form').default
const readme = require('./Example.md')
const raw = require('!!raw-loader!./Form')
ReactDOM.render(
<Provider store={store}>
<MuiThemeProvider muiTheme={getMuiTheme()}>
<div>
<Markdown content={readme} />
<h2>Form</h2>
<Form onSubmit={showResults} />
<Values form="example" />
<h2>Code</h2>
<h4>Form.js</h4>
<Code source={raw} />
</div>
</MuiThemeProvider>
</Provider>,
dest
)
}
if (module.hot) {
// Support hot reloading of components
// and display an overlay for runtime errors
const renderApp = render
const renderError = error => {
console.error('ERROR:', error) // eslint-disable-line no-console
const RedBox = require('redbox-react')
ReactDOM.render(<RedBox error={error} className="redbox" />, dest)
}
render = () => {
try {
renderApp()
} catch (error) {
renderError(error)
}
}
const rerender = () => {
setTimeout(render)
}
module.hot.accept('./Form', rerender)
module.hot.accept('./Example.md', rerender)
module.hot.accept('!!raw-loader!./Form', rerender)
}
render()
|
src/containers/food.js | rosiene/growup-game | import React from 'react';
import Circle from './circle';
class Food extends React.Component {
render(){
return(
<Circle r={this.props.r} cx={this.props.cx} cy={this.props.cy} fill={this.props.fill} />
);
}
}
export default Food;
|
src/decorators/withViewport.js | neilhighley/fintechathon_svr | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
src/chromeApp/window.js | zalmoxisus/remotedev-app | import React from 'react';
import { render } from 'react-dom';
import App from '../app';
chrome.storage.local.get({
'monitor': 'InspectorMonitor',
'test-templates': null,
'test-templates-sel': null,
's:hostname': null,
's:port': null,
's:secure': null
}, options => {
render(
<App
selectMonitor={options.monitor}
testTemplates={options['test-templates']}
selectedTemplate={options['test-templates-sel']}
useCodemirror
socketOptions={
options['s:hostname'] && options['s:port'] ?
{
hostname: options['s:hostname'], port: options['s:port'], secure: options['s:secure']
} : undefined
}
/>,
document.getElementById('root')
);
});
|
app/javascript/src/components/packageBlocks/InserterForm.js | michelson/chaskiq | import React from 'react'
import FormDialog from '../../components/FormDialog'
import Button from '../../components/Button'
import ErrorBoundary from '../../components/ErrorBoundary'
import {
AppList,
} from './AppList'
export default function InserterForm({
isOpen,
closeHandler,
loading,
handleAdd,
packages,
app,
}){
return (
<div>
{isOpen && (
<FormDialog
open={isOpen}
handleClose={closeHandler}
titleContent={'Add apps to chat home'}
formComponent={
<div className="h-64 overflow-auto">
<ErrorBoundary>
<AppList
location={'home'}
loading={loading}
handleAdd={handleAdd}
packages={packages}
app={app}
/>
</ErrorBoundary>
</div>
}
dialogButtons={
<React.Fragment>
{/* <Button onClick={deleteHandler} className="ml-2" variant="danger">
{I18n.t('common.delete')}
</Button> */}
<Button onClick={closeHandler} variant="outlined">
{I18n.t('common.cancel')}
</Button>
</React.Fragment>
}
></FormDialog>
)}
</div>
)
} |
src/components/Link.js | lingxiao-Zhu/react-redux-demo | /**
* Created by larry on 2017/1/6.
*/
import React from 'react';
const Link = ({active,children,onClick}) => {
if(active){
return <span>{children}</span>
}
return(
<a
href="#"
onClick={e=>{
e.preventDefault();
onClick();
}}
>
{children}
</a>
)
}
export default Link
|
src/libs/popup/Popup/index.js | erhathaway/cellular_automata | import React from 'react';
import Component from './Component';
export default ({ show, ...props }) => {
if (show) return (<Component {...props} />);
return null;
};
|
actor-apps/app-web/src/app/components/modals/MyProfile.react.js | liuzwei/actor-platform | //import _ from 'lodash';
import React from 'react';
import { KeyCodes } from 'constants/ActorAppConstants';
import MyProfileActions from 'actions/MyProfileActions';
import MyProfileStore from 'stores/MyProfileStore';
import AvatarItem from 'components/common/AvatarItem.react';
import Modal from 'react-modal';
import { Styles, TextField, FlatButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
profile: MyProfileStore.getProfile(),
name: MyProfileStore.getName(),
isOpen: MyProfileStore.isModalOpen(),
isNameEditable: false
};
};
class MyProfile extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
this.unsubscribe = MyProfileStore.listen(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
},
textField: {
textColor: 'rgba(0,0,0,.87)',
focusColor: '#68a3e7',
backgroundColor: 'transparent',
borderColor: '#68a3e7',
disabledTextColor: 'rgba(0,0,0,.4)'
}
});
}
componentWillUnmount() {
this.unsubscribe();
document.removeEventListener('keydown', this.onKeyDown, false);
}
onClose = () => {
MyProfileActions.modalClose();
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onChange = () => {
this.setState(getStateFromStores());
};
onNameChange = event => {
this.setState({name: event.target.value});
};
onNameSave = () => {
MyProfileActions.setName(this.state.name);
this.onClose();
};
render() {
const isOpen = this.state.isOpen;
const profile = this.state.profile;
if (profile !== null && isOpen === true) {
return (
<Modal className="modal-new modal-new--profile"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 340}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person</a>
<h4 className="modal-new__header__title">Profile</h4>
<div className="pull-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onNameSave}
secondary={true}
style={{marginTop: -6}}/>
</div>
</header>
<div className="modal-new__body row">
<AvatarItem image={profile.bigAvatar}
placeholder={profile.placeholder}
size="big"
title={profile.name}/>
<div className="col-xs">
<div className="name">
<TextField className="login__form__input"
floatingLabelText="Username"
fullWidth
onChange={this.onNameChange}
type="text"
value={this.state.name}/>
</div>
<div className="phone">
<TextField className="login__form__input"
disabled
floatingLabelText="Phone number"
fullWidth
type="tel"
value={this.state.profile.phones[0].number}/>
</div>
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default MyProfile;
|
src/components/common/icons/Warning.js | WendellLiu/GoodJobShare | import React from 'react';
/* eslint-disable */
const Warning = (props) => (
<svg {...props} width="148" height="148" viewBox="0 0 148 148">
<g fillRule="evenodd" transform="translate(0 5)">
<ellipse cx="73.959" cy="111.077" rx="5.2" ry="5.205"/>
<path d="M69.3353998,53.0952988 L69.3353998,93.02983 C69.3353998,95.5839972 71.4030146,97.6559413 73.9592965,97.6559413 C76.5155783,97.6559413 78.5831932,95.5863045 78.5831932,93.02983 L78.5831932,53.0952988 C78.5831932,50.5411316 76.5155783,48.4668802 73.9592965,48.4668802 C71.4030146,48.4668802 69.3353998,50.5388243 69.3353998,53.0952988 L69.3353998,53.0952988 Z"/>
<path d="M146.982749,132.05529 L78.0392053,2.49648502 C76.4325972,-0.521446964 71.4836908,-0.521446964 69.8793877,2.49648502 L0.938148528,132.05529 C0.175182526,133.490423 0.218978158,135.220888 1.05570522,136.612183 C1.89012726,138.008091 3.39531396,138.861788 5.02036239,138.861788 L142.898231,138.861788 C144.523279,138.861788 146.026161,138.010399 146.865193,136.612183 C147.69731,135.220888 147.74341,133.490423 146.982749,132.05529 L146.982749,132.05529 Z M12.7214784,129.604951 L73.9592965,14.5151453 L135.19942,129.604951 L12.7214784,129.604951 L12.7214784,129.604951 Z"/>
</g>
</svg>
);
/* eslint-enable */
export default Warning;
|
src/svg-icons/communication/no-sim.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationNoSim = (props) => (
<SvgIcon {...props}>
<path d="M18.99 5c0-1.1-.89-2-1.99-2h-7L7.66 5.34 19 16.68 18.99 5zM3.65 3.88L2.38 5.15 5 7.77V19c0 1.1.9 2 2 2h10.01c.35 0 .67-.1.96-.26l1.88 1.88 1.27-1.27L3.65 3.88z"/>
</SvgIcon>
);
CommunicationNoSim = pure(CommunicationNoSim);
CommunicationNoSim.displayName = 'CommunicationNoSim';
CommunicationNoSim.muiName = 'SvgIcon';
export default CommunicationNoSim;
|
docs/app/Examples/views/Feed/Content/FeedExampleSummaryDateShorthand.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Feed } from 'semantic-ui-react'
const FeedExampleSummaryDate = () => (
<Feed>
<Feed.Event>
<Feed.Label image='http://semantic-ui.com/images/avatar/small/jenny.jpg' />
<Feed.Content>
<Feed.Summary
content='You added Jenny Hess to your coworker group.'
date='3 days ago'
/>
</Feed.Content>
</Feed.Event>
</Feed>
)
export default FeedExampleSummaryDate
|
examples/src/index.js | perminder-klair/react-sound | import React from 'react';
import Example from './Example';
React.render(<Example />, document.getElementById('app'));
|
pages/api/grid.js | cherniavskii/material-ui | import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './grid.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
app/components/Home.js | bopace/headrest | import React from 'react';
import Tappable from 'react-tappable';
import Habit from './Habit';
import '../css/home.css';
import HabitStore from '../stores/habit';
const Home = React.createClass({
displayName: 'Home',
login() {
this.props.loginAction();
},
render: function() {
return (
<div className='home'>
<img src="../../images/logo.png" />
<h1>Headrest</h1>
<Tappable className="signup-button">
Sign Up
</Tappable>
<Tappable className="login-button" onTap={this.login}>
Login
</Tappable>
</div>
);
}
});
module.exports = Home; |
src/components/popup/popup_header.js | n7best/react-weui | import React from 'react';
import PropTypes from 'prop-types';
import classNames from '../../utils/classnames';
/**
* Sample Popup header for Popup
*
*/
const PopupHeader = (props) => {
const { left, right, leftOnClick, rightOnClick, className } = props;
const cls = classNames('weui-popup__hd', className);
return (
<div className={cls}>
<a className="weui-popup__action" onClick={leftOnClick}>{left}</a>
<a className="weui-popup__action" onClick={rightOnClick}>{right}</a>
</div>
);
};
PopupHeader.propTypes = {
/**
* left button label
*
*/
left: PropTypes.string,
/**
* right button label
*
*/
right: PropTypes.string,
/**
* left button onclick
*
*/
leftOnClick: PropTypes.func,
/**
* right button onclick
*
*/
rightOnClick: PropTypes.func
};
PopupHeader.defaultProps = {
left: '',
right: ''
};
export default PopupHeader;
|
src/js/components/icons/base/TestDesktop.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-test-desktop`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'test-desktop');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M18.218,1 L23,1 L23,19 L1,19 L1,1 L6,1 M16.9999996,9.99999996 C13,6.99999996 11,13 7.00000002,9.99999996 M5,23 L19,23 L5,23 Z M10,1 L10,5.773 L5,12.955 L5,15 L19,15 L19,12.955 L14,5.773 L14,1 M8,1 L16,1 L8,1 Z M8,23 L16,23 L16,19 L8,19 L8,23 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'TestDesktop';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/Grid/components/__tests__/Header-test.js | jmcriffey/react-ui | import Mingus from 'mingus';
import React from 'react';
import fixtures from './fixtures';
import Header from '../Header';
Mingus.createTestCase('HeaderTest', {
testRender() {
const columnIndex = 0;
const column = fixtures.columns[columnIndex];
const rendered = this.renderComponent(
<Header
column={column}
columnIndex={columnIndex} />
);
const title = this.getChildren(rendered)[0];
this.assertIsType(rendered, 'th');
this.assertIsType(title, 'span');
this.assertEqual(title.props.title, 'This is the user id.');
},
testOnClick() {
const onHeaderClick = this.stub();
const columnIndex = 1;
const column = fixtures.columns[columnIndex];
const component = this.createComponent(
<Header
column={column}
columnIndex={columnIndex}
onHeaderClick={onHeaderClick} />
);
this.stub(component, 'setState');
component.onClick('mock evt');
this.assertEqual(onHeaderClick.callCount, 1);
this.assertEqual(component.setState.callCount, 1);
this.assertTrue(onHeaderClick.calledWith(
'mock evt',
column,
columnIndex,
undefined,
undefined,
1
));
this.assertTrue(component.setState.calledWith({numClicks: 1}));
},
testGetClassName() {
const columnIndex = 0;
const column = fixtures.columns[columnIndex];
const component = this.createComponent(
<Header
activeHeader={0}
column={column}
columnIndex={columnIndex} />
);
this.assertEqual(
component.getClassName(),
'react-ui-grid-header react-ui-grid-header-active'
);
}
});
|
app/components/IssueIcon/index.js | j921216063/chenya | import React from 'react';
function IssueIcon(props) {
return (
<svg
height="1em"
width="0.875em"
className={props.className}
>
<path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" />
</svg>
);
}
IssueIcon.propTypes = {
className: React.PropTypes.string,
};
export default IssueIcon;
|
src/data/warranties.js | aries-auto/ariesautomotive | import React from 'react';
module.exports = {
addressHtml: (
<div>
<p>ATTN: WARRANTY DEPT.</p>
<p></p>
<p>ARIES AUTOMOTIVE</p>
<p>2611 Regent Boulevard</p>
<p>Suite 300</p>
<p>DFW Airport, TX 75261 USA</p>
<p></p>
<p>Phone: (888) 635-9824</p>
<p></p>
<p>Fax: (972) 352-2617</p>
<p>Email: <a href="mailto:customerservice@ariesautomotive.com">customerservice@ariesautomotive.com</a></p>
</div>
),
registrationStickerHtml: (
<span>
<a href="https://www.curtmfg.com/assets/aries/warranty/bullbarregistrationsticker.jpg" target="blank">Bull Bar | </a>
<a href="https://www.curtmfg.com/assets/aries/warranty/grillguardregistrationsticker.jpg" target="blank">Grill Guard | </a>
<a href="https://www.curtmfg.com/assets/aries/warranty/sidebarregistrationsticker.jpg" target="blank">Side Bar</a>
</span>
),
};
module.exports.fields = [
{
type: 'text',
label: 'Enter your first name:',
placeholder: 'Enter your first name.',
name: 'firstName',
width: '6',
required: true,
},
{
type: 'text',
label: 'Enter your last name:',
placeholder: 'Enter your last name.',
name: 'lastName',
width: '6',
required: true,
},
{
type: 'text',
label: 'Enter your street address:',
placeholder: 'Enter your street address.',
name: 'address1',
width: '12',
required: true,
},
{
type: 'text',
label: 'Enter your city:',
placeholder: 'Enter your city.',
name: 'city',
width: '12',
required: true,
},
{
type: 'country',
label: 'Enter your country',
placeholder: 'Select Country',
name: 'country',
options: '',
width: '6',
required: true,
},
{
type: 'state',
label: 'Enter your state/province',
placeholder: 'Select State / Province',
name: 'state',
options: '',
width: '6',
required: true,
},
{
type: 'text',
label: 'Enter your postal code',
placeholder: 'Enter your postal code.',
name: 'postalCode',
width: '6',
required: true,
},
{
type: 'text',
label: 'Enter your phone number:',
placeholder: 'Enter your phone number.',
name: 'phone',
width: '6',
required: true,
},
{
type: 'email',
label: 'Enter your email address:',
placeholder: 'Enter your email address.',
name: 'email',
width: '12',
required: true,
},
];
module.exports.fields2 = [
{
type: 'text',
label: 'Part Number:',
placeholder: 'Enter a part number.',
name: 'partNumber',
width: '6',
required: true,
},
{
type: 'date',
label: 'Date',
name: 'date',
width: '6',
required: true,
},
{
type: 'text',
label: 'Serial Number:',
placeholder: 'Enter serial number.',
name: 'serialNumber',
width: '6',
required: true,
},
];
|
node_modules/react-router/es/Router.js | oiricaud/horizon-education | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import warning from 'warning';
import invariant from 'invariant';
import React from 'react';
import PropTypes from 'prop-types';
/**
* The public API for putting history on context.
*/
var Router = function (_React$Component) {
_inherits(Router, _React$Component);
function Router() {
var _temp, _this, _ret;
_classCallCheck(this, Router);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
match: _this.computeMatch(_this.props.history.location.pathname)
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Router.prototype.getChildContext = function getChildContext() {
return {
router: _extends({}, this.context.router, {
history: this.props.history,
route: {
location: this.props.history.location,
match: this.state.match
}
})
};
};
Router.prototype.computeMatch = function computeMatch(pathname) {
return {
path: '/',
url: '/',
params: {},
isExact: pathname === '/'
};
};
Router.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
var _props = this.props,
children = _props.children,
history = _props.history;
invariant(children == null || React.Children.count(children) === 1, 'A <Router> may have only one child element');
// Do this here so we can setState when a <Redirect> changes the
// location in componentWillMount. This happens e.g. when doing
// server rendering using a <StaticRouter>.
this.unlisten = history.listen(function () {
_this2.setState({
match: _this2.computeMatch(history.location.pathname)
});
});
};
Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
warning(this.props.history === nextProps.history, 'You cannot change <Router history>');
};
Router.prototype.componentWillUnmount = function componentWillUnmount() {
this.unlisten();
};
Router.prototype.render = function render() {
var children = this.props.children;
return children ? React.Children.only(children) : null;
};
return Router;
}(React.Component);
Router.propTypes = {
history: PropTypes.object.isRequired,
children: PropTypes.node
};
Router.contextTypes = {
router: PropTypes.object
};
Router.childContextTypes = {
router: PropTypes.object.isRequired
};
export default Router; |
submissions/arqex/src/components/AppContainer.js | enkidevs/flux-challenge | import React, { Component } from 'react';
import State from '../State';
import App from './App';
export default class AppContainer extends Component {
render() {
var state = State.get();
return (
<div className="app-container">
<App appState={ state } />
</div>
);
}
componentDidMount(){
State.on('update', () => this.forceUpdate() );
}
}
|
src/app/components/Summer.js | omarglz/rgvelite | import React from 'react';
export class Summer extends React.Component {
render() {
return (
<div className="summer-camp">
<div className="summer-camp-title bg-white">
<div className="summer-camp-title-overlay ph5-ns ph4 ph6-l pv4">
<h1 className="db f1-ns f2 lh-solid tc fw3 mt0 pa0 prim-text">Summer Camp 2020</h1>
<p className="f3-ns f4 fw3 prim-text tc">
In our twelve-week summer camp, we offer training sessions twice a day for any skill level. Have a look at all of our options below!
Contact us if you have any questions. There is limited enrollment.
</p>
</div>
</div>
<div className="summer-camp-weeks bg-near-white cf">
<div className="dt w-100 mw7 center pv4 ph2">
<div className="dtc">
<div className="dt center">
<h1 className="f5 f4-ns tl prim-text">Week 1: June 3 - 7</h1>
<h1 className="f5 f4-ns tl prim-text">Week 2: June 10 - 14</h1>
<h1 className="f5 f4-ns tl prim-text">Week 3: June 17 - 21</h1>
<h1 className="f5 f4-ns tl prim-text">Week 4: June 24 - 28</h1>
<h1 className="f5 f4-ns tl prim-text">Week 5: July 1 - 5</h1>
<h1 className="f5 f4-ns tl prim-text">Week 6: July 8 - 12</h1>
</div>
</div>
<div className="dtc">
<div className="dt center">
<h1 className="f5 f4-ns tl prim-text">Week 7: July 15 - 19</h1>
<h1 className="f5 f4-ns tl prim-text">Week 8: July 22 - 26</h1>
<h1 className="f5 f4-ns tl prim-text">Week 9: July 29 - Aug 2</h1>
<h1 className="f5 f4-ns tl prim-text">Week 10: Aug 5 - 9</h1>
<h1 className="f5 f4-ns tl prim-text">Week 11: Aug 12 - 16</h1>
<h1 className="f5 f4-ns tl prim-text">Week 12: Aug 19 - 23</h1>
</div>
</div>
</div>
</div>
<div className="summer-camp-beginner bg-white cf pb5">
<div className="beginner-title bg-beginners-orange pv3">
<h2 className="db f3 f2-l lh-solid tc fw3 mt0 pa0 white">Beginners / 10 and Under</h2>
</div>
<div className="summer-camp-beginner-overlay fl w-100">
<article className="cf">
<div className="pv2 ph4 mw6 mw7-ns center">
<div className="dtc center pt3">
<h1 className="f3 f2-l mv0 prim-text">Hours</h1>
</div>
<div className="dt w-100 mt1">
<div className="dtc center">
<h1 className="f3-ns f5 mv0 sec-text">Monday - Thursday:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Monday - Thursday:</h1>
</div>
<div className="dtc center">
<h1 className="f3-ns f5 mv0 tr sec-text">9:45am - 11:00am</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">7:15pm - 8:15pm</h1>
</div>
</div>
<div className="dtc center pt3">
<h1 className="f3 f2-l mv0 prim-text">Cost</h1>
</div>
<div className="dt w-100 mt1">
<div className="dtc center">
<h1 className="f3-ns f5 mv0 sec-text">Both sessions:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Morning session only:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Afternoon session only:</h1>
<h1 className="f3-ns f5 mv0 sec-text">3 days a week:</h1>
<h1 className="f3-ns f5 mv0 sec-text">2 days a week:</h1>
</div>
<div className="dtc center">
<h1 className="f3-ns f5 mv0 tr sec-text">$80 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$50 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$50 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$40 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$30 per week</h1>
</div>
</div>
</div>
</article>
</div>
</div>
<div className="summer-camp-challenger bg-near-white cf pb5">
<div className="challenger-title bg-challengers-pink pv3">
<h2 className="db f3 f2-l lh-solid tc fw3 mt0 pa0 white">Challenger</h2>
</div>
<div className="summer-camp-challenger-overlay fl w-100">
<article className="cf">
<div className="pv2 ph4 mw6 mw7-ns center">
<div className="dtc center pt3">
<h1 className="f3 f2-l mv0 prim-text">Hours</h1>
</div>
<div className="dt w-100 mt1">
<div className="dtc center">
<h1 className="f3-ns f5 mv0 sec-text">Monday - Friday:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Monday - Thursday:</h1>
</div>
<div className="dtc center">
<h1 className="f3-ns f5 mv0 tr sec-text">9:45am - 11:00am</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">7:15pm - 8:15pm</h1>
</div>
</div>
<div className="dtc center pt3">
<h1 className="f3 f2-l mv0 prim-text">Cost</h1>
</div>
<div className="dt w-100 mt1">
<div className="dtc center">
<h1 className="f3-ns f5 mv0 sec-text">Both sessions:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Morning session only:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Afternoon session only:</h1>
<h1 className="f3-ns f5 mv0 sec-text">3 days a week:</h1>
<h1 className="f3-ns f5 mv0 sec-text">2 days a week:</h1>
</div>
<div className="dtc center">
<h1 className="f3-ns f5 mv0 tr sec-text">$80 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$60 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$50 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$40 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$30 per week</h1>
</div>
</div>
</div>
</article>
</div>
</div>
<div className="summer-camp-elite bg-white cf pb5">
<div className="elite-title bg-elite-green pv3">
<h2 className="db f3 f2-l lh-solid tc fw3 mt0 pa0 white">Elite</h2>
</div>
<div className="summer-camp-elite-overlay fl w-100">
<article className="cf">
<div className="pv2 ph4 mw6 mw7-ns center">
<div className="dtc center pt3">
<h1 className="f3 f2-l mv0 prim-text">Hours</h1>
</div>
<div className="dt w-100 mt1">
<div className="dtc center">
<h1 className="f3-ns f5 mv0 sec-text">Monday - Friday:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Monday - Thursday:</h1>
</div>
<div className="dtc center">
<h1 className="f3-ns f5 mv0 tr sec-text">8:00am - 10:00am</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">5:45pm - 7:15pm</h1>
</div>
</div>
<div className="dtc center pt3">
<h1 className="f3 f2-l mv0 prim-text">Cost</h1>
</div>
<div className="dt w-100 mt1">
<div className="dtc center">
<h1 className="f3-ns f5 mv0 sec-text">Both sessions:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Morning session only:</h1>
<h1 className="f3-ns f5 mv0 sec-text">Afternoon session only:</h1>
</div>
<div className="dtc center">
<h1 className="f3-ns f5 mv0 tr sec-text">$160 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$100 per week</h1>
<h1 className="f3-ns f5 mv0 tr sec-text">$80 per week</h1>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
);
}
} |
docs/src/index.js | bokuweb/react-motion-menu | import React from 'react';
import { render } from 'react-dom';
import Example from './example';
render(<Example />, document.querySelector('.content'));
|
app/javascript/pawoo/containers/followers_you_follow_column.js | pixiv/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Avatar from '../../mastodon/components/avatar';
import Permalink from '../../mastodon/components/permalink';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { connect } from 'react-redux';
import { makeGetAccount } from '../../mastodon/selectors';
import ga from '../actions/ga';
const gaCategory = 'FollowersYouFollow';
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = (state, props) => ({
account: getAccount(state, props.accountId),
});
return mapStateToProps;
};
@connect(makeMapStateToProps)
export default class FollowersYouFollowColumn extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
};
handleAccountClick = () => {
const { account } = this.props;
ga.event({
eventCategory: gaCategory,
eventAction: 'ClickAccountIcon',
eventLabel: account.get('id'),
});
}
render() {
const { account } = this.props;
return (
<div className='multi-column' title={account.get('acct')}>
<Permalink key={account.get('id')} className='account__display-name' href={account.get('url')} to={`/accounts/${account.get('id')}`} onInterceptClick={this.handleAccountClick}>
<div className='account__avatar-wrapper'><Avatar account={account} size={40} /></div>
</Permalink>
</div>
);
}
}
|
examples/basic/src/containers/Home.js | calvinrbnspiess/react-static | import React from 'react'
import { getSiteProps } from 'react-static'
//
import logoImg from '../logo.png'
export default getSiteProps(() => (
<div>
<h1 style={{ textAlign: 'center' }}>Welcome to</h1>
<img src={logoImg} alt="" />
</div>
))
|
app/javascript/mastodon/features/notifications/components/filter_bar.js | 5thfloor/ichiji-social | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import Icon from 'mastodon/components/icon';
const tooltips = defineMessages({
mentions: { id: 'notifications.filter.mentions', defaultMessage: 'Mentions' },
favourites: { id: 'notifications.filter.favourites', defaultMessage: 'Favourites' },
boosts: { id: 'notifications.filter.boosts', defaultMessage: 'Boosts' },
polls: { id: 'notifications.filter.polls', defaultMessage: 'Poll results' },
follows: { id: 'notifications.filter.follows', defaultMessage: 'Follows' },
});
export default @injectIntl
class FilterBar extends React.PureComponent {
static propTypes = {
selectFilter: PropTypes.func.isRequired,
selectedFilter: PropTypes.string.isRequired,
advancedMode: PropTypes.bool.isRequired,
intl: PropTypes.object.isRequired,
};
onClick (notificationType) {
return () => this.props.selectFilter(notificationType);
}
render () {
const { selectedFilter, advancedMode, intl } = this.props;
const renderedElement = !advancedMode ? (
<div className='notification__filter-bar'>
<button
className={selectedFilter === 'all' ? 'active' : ''}
onClick={this.onClick('all')}
>
<FormattedMessage
id='notifications.filter.all'
defaultMessage='All'
/>
</button>
<button
className={selectedFilter === 'mention' ? 'active' : ''}
onClick={this.onClick('mention')}
>
<FormattedMessage
id='notifications.filter.mentions'
defaultMessage='Mentions'
/>
</button>
</div>
) : (
<div className='notification__filter-bar'>
<button
className={selectedFilter === 'all' ? 'active' : ''}
onClick={this.onClick('all')}
>
<FormattedMessage
id='notifications.filter.all'
defaultMessage='All'
/>
</button>
<button
className={selectedFilter === 'mention' ? 'active' : ''}
onClick={this.onClick('mention')}
title={intl.formatMessage(tooltips.mentions)}
>
<Icon id='reply-all' fixedWidth />
</button>
<button
className={selectedFilter === 'favourite' ? 'active' : ''}
onClick={this.onClick('favourite')}
title={intl.formatMessage(tooltips.favourites)}
>
<Icon id='star' fixedWidth />
</button>
<button
className={selectedFilter === 'reblog' ? 'active' : ''}
onClick={this.onClick('reblog')}
title={intl.formatMessage(tooltips.boosts)}
>
<Icon id='retweet' fixedWidth />
</button>
<button
className={selectedFilter === 'poll' ? 'active' : ''}
onClick={this.onClick('poll')}
title={intl.formatMessage(tooltips.polls)}
>
<Icon id='tasks' fixedWidth />
</button>
<button
className={selectedFilter === 'follow' ? 'active' : ''}
onClick={this.onClick('follow')}
title={intl.formatMessage(tooltips.follows)}
>
<Icon id='user-plus' fixedWidth />
</button>
</div>
);
return renderedElement;
}
}
|
app/containers/tutorial/fourth.js | DeividasK/my-future-ai | import React from 'react'
import SimpleList from 'components/lists/simple'
import { updateStep, updateHeading, updateActions } from '../../actions/TutorialActions'
import { FormattedMessage, defineMessages, injectIntl } from 'react-intl'
const content = defineMessages({
title: { id: 'app.tutorial.step4.title', defaultMessage: 'Reasons', }
})
class TutorialStep4 extends React.Component {
constructor (props) {
super(props)
this.state = {
filters: [
function(item) { return item.primary === false }
],
formItem: { type: 'textarea', value: 'reasons' }
}
}
componentWillMount () {
updateStep(4)
updateHeading(this.props.intl.formatMessage(content.title), "notebook")
updateActions(4)
}
render () {
return (
<div>
<p><FormattedMessage
id='app.tutorial.step4.introduction'
defaultMessage="Now write down why you absolutely will achieve your goals. Be clear and concise and positive. Tell yourself why you’re sure you can reach those outcomes, and why it’s important that you do."
/></p>
<SimpleList
items={ this.props.goals }
filters={ this.state.filters }
formItem={ this.state.formItem }
/>
</div>
)
}
}
export default injectIntl(TutorialStep4) |
src/components/label.js | selfcontained/labelr-react-ampersand-demo | import React from 'react';
import ampersandMixin from 'ampersand-react-mixin';
export default React.createClass({
displayName: 'Label',
mixins: [ampersandMixin],
getInitialState () {
const {name, color} = this.props.label;
return {
name: name,
color: color
};
},
onColorChange (event) {
this.setState({
color: event.target.value.slice(1)
});
},
onNameChange () {
this.setState({
name: event.target.value
});
},
onEditClick () {
this.props.label.editing = true;
},
onDeleteClick () {
console.log('wtf');
this.props.label.destroy();
},
onCancelClick () {
const {label} = this.props;
if(label.saved) {
label.editing = false;
this.setState(this.getInitialState());
}else {
label.collection.remove(label);
}
},
onSubmitForm (event) {
event.preventDefault();
const {label} = this.props;
if(label.saved) {
label.update(this.state);
}else {
label.save(this.state);
}
label.editing = false;
},
render () {
const {label} = this.props;
const {name, color} = this.state;
const cssColor = '#' + color;
let content;
if(label.editing) {
content = (
<form onSubmit={this.onSubmitForm} className='label'>
<span style={{backgroundColor: cssColor}} className='label-color avatar avatar-small avatar-rounded'> </span>
<input onChange={this.onNameChange} value={name} name='name'/>
<input onChange={this.onColorChange} value={'#' + color} name='color'/>
<button type='submit' className='button button-small'>Save</button>
<button onClick={this.onCancelClick} type='button' className='button button-small button-unstyled'>cancel</button>
</form>
);
}else {
content = (
<div className='label'>
<span style={{backgroundColor: cssColor}} className='label-color'> </span>
<span>{label.name}</span>
<span onClick={this.onEditClick} className='octicon octicon-pencil'></span>
<span onClick={this.onDeleteClick} className='octicon octicon-x'></span>
</div>
);
}
return <div>{content}</div>;
}
})
|
internal/reactgroup/storybook/demo/src/Profile.stories.js | agrc/Presentations | import React from 'react';
import Profile from './Profile';
import profileImage from './monkey.png'
export default {
title: 'Profile',
component: Profile,
};
const data = {
firstName: 'Story',
lastName: 'Book',
profileImage,
bio: 'enjoys foraging for food in the rain forest',
contact: '123-456-7890'
}
export const Empty = () => <Profile />;
export const Normal = () => <Profile {...data} />;
|
services/ui/src/components/RestoreButton/Prepare.js | amazeeio/lagoon | import React from 'react';
import gql from 'graphql-tag';
import { Mutation } from 'react-apollo';
import Button from 'components/Button';
const addRestore = gql`
mutation addRestore($input: AddRestoreInput!) {
addRestore(input: $input) {
id
}
}
`;
const Prepare = ({ backupId }) => (
<Mutation mutation={addRestore} variables={{ input: { backupId } }}>
{(addRestore, { loading, called, error, data }) => {
if (error) {
return (
<Button disabled>
Retrieve failed
</Button>
);
}
if (loading || called) {
return (
<Button disabled>
Retrieving ...
</Button>
);
}
return (
<Button action={addRestore}>
Retrieve
</Button>
);
}}
</Mutation>
);
export default Prepare;
|
src/interface/report/PlayerSelection/PlayerTile.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import SpecIcon from 'common/SpecIcon';
import { getClassName } from 'game/ROLES';
import getAverageItemLevel from 'game/getAverageItemLevel';
import Icon from 'common/Icon';
import SPECS from 'game/SPECS';
import { getCharacterById } from 'interface/selectors/characters';
import { fetchCharacter, SUPPORTED_REGIONS } from 'interface/actions/characters';
class PlayerTile extends React.PureComponent {
static propTypes = {
player: PropTypes.object.isRequired,
makeUrl: PropTypes.func.isRequired,
characterInfo: PropTypes.shape({
region: PropTypes.string.isRequired,
thumbnail: PropTypes.string.isRequired,
heartOfAzeroth: PropTypes.any,
}),
fetchCharacter: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
if (!this.props.characterInfo) {
// noinspection JSIgnoredPromiseFromCall
this.load();
}
}
async load() {
const { player, fetchCharacter } = this.props;
if (!SUPPORTED_REGIONS.includes(player.region)) {
return null;
}
try {
return await fetchCharacter(player.guid, player.region, player.server, player.name);
} catch (err) {
// No biggy, just show less info
console.error('An error occured fetching', player, '. The error:', err);
return null;
}
}
render() {
const { player, characterInfo, makeUrl } = this.props;
const avatar = characterInfo && characterInfo.thumbnail ? `https://render-${characterInfo.region}.worldofwarcraft.com/character/${characterInfo.thumbnail.replace('avatar', 'inset')}` : '/img/fallback-character.jpg';
const spec = SPECS[player.combatant.specID];
const analysisUrl = makeUrl(player.id);
const heartOfAzeroth = characterInfo && characterInfo.heartOfAzeroth ? characterInfo.heartOfAzeroth : null;
player.parsable = !player.combatant.error && spec;
if (!player.parsable) {
return (
<span
className="player"
onClick={() => {
alert(`This player can not be parsed. Warcraft Logs ran into an error parsing the log and is not giving us all the necessary information. Please update your Warcraft Logs Uploader and reupload your log to try again.`);
}}
>
<div className="role" />
<div className="card">
<div className="avatar" style={{ backgroundImage: `url(${avatar})` }} />
<div className="about">
<h1>{player.name}</h1>
</div>
</div>
</span>
);
}
return (
<Link
to={analysisUrl}
className={`player ${getClassName(spec.role)}`}
>
<div className="role" />
<div className="card">
<div className="avatar" style={{ backgroundImage: `url(${avatar})` }} />
<div className="about">
<h1
className={spec.className.replace(' ', '')}
// The name can't always fit so use a tooltip. We use title instead of the tooltip library for this because we don't want it to be distracting and the tooltip library would popup when hovering just to click an item, while this has a delay.
title={player.name}
>
{player.name}
</h1>
<small
title={`${spec.specName} ${spec.className}`}
>
<SpecIcon id={spec.id} /> {spec.specName} {spec.className}
</small>
<div className="flex text-muted text-small">
<div className="flex-main">
<Icon icon="inv_helmet_03" /> {Math.round(getAverageItemLevel(player.combatant.gear))}
</div>
{heartOfAzeroth && (
<div className="flex-main text-right">
<Icon icon={heartOfAzeroth.icon} /> {heartOfAzeroth.azeriteItemLevel}
</div>
)}
</div>
</div>
</div>
</Link>
);
}
}
const mapStateToProps = (state, { player }) => ({
characterInfo: getCharacterById(state, player.guid),
});
export default connect(
mapStateToProps,
{
fetchCharacter,
},
)(PlayerTile);
|
packages/terra-table/src/SelectableUtils.js | mschile/terra-core | import React from 'react';
/**
* Returns a validated max count for selection. Validates the max count prop, and if undefined
* returns a max of the count of children.
*/
const validatedMaxCountSelection = (rows, maxSelectionCount) => {
if (maxSelectionCount !== undefined) {
return maxSelectionCount;
}
return React.Children.count(rows);
};
/**
* Returns the index of the first selected row for SingleSelectableRows.
* To be used in the constructor, to set initial state.
*/
const initialSingleSelectRowIndex = (rows) => {
if (!rows || !rows.length) {
return null;
}
for (let i = 0; i < rows.length; i += 1) {
if (rows[i].props.isSelected) {
return i;
}
}
return -1;
};
/**
* Returns the indexes of the selected rows for MultiSelectableRows.
* To be used in the constructor, to set initial state.
*/
const initialMultiSelectRowIndexes = (rows, maxSelectionCount) => {
const childArray = React.Children.toArray(rows);
// Find the rows which are selected and are selectable
const selectedIndexes = [];
const validatedMaxSelectionCount = validatedMaxCountSelection(childArray, maxSelectionCount);
for (let i = 0; i < childArray.length; i += 1) {
if (childArray[i].props.isSelected) {
selectedIndexes.push(i);
if (selectedIndexes.length >= validatedMaxSelectionCount) {
break;
}
}
}
return selectedIndexes;
};
/**
* Returns a new array of the selected indexes, updated with the newIndex being added or removed
* from the existing.
*/
const updatedMultiSelectedIndexes = (currentIndexes, newIndex) => {
let newIndexes = [];
if (currentIndexes && currentIndexes.length) {
if (currentIndexes.indexOf(newIndex) >= 0) {
newIndexes = currentIndexes.slice();
newIndexes.splice(newIndexes.indexOf(newIndex), 1);
} else {
newIndexes = currentIndexes.concat([newIndex]);
}
} else {
newIndexes.push(newIndex);
}
return newIndexes;
};
/**
* Returns if the selected row index is already selected for SingleSelectableRows.
*/
const shouldHandleSingleSelectRowSelection = (currentIndex, newIndex) => currentIndex !== newIndex;
/**
* Returns whether not the new index can be added if it adheres to the maxSelectionCount.
* Or if the index is already present, and can be removed.
*/
const shouldHandleMultiSelectRowSelection = (children, maxSelectionCount, currentIndexes, newIndex) => {
if (currentIndexes.length < validatedMaxCountSelection(children, maxSelectionCount)) {
return true;
}
return currentIndexes.indexOf(newIndex) >= 0;
};
const SelectableUtils = {
validatedMaxCountSelection,
initialSingleSelectRowIndex,
initialMultiSelectRowIndexes,
updatedMultiSelectedIndexes,
shouldHandleSingleSelectRowSelection,
shouldHandleMultiSelectRowSelection,
};
export default SelectableUtils;
|
app/components/Common/PageError/index.js | VineRelay/VineRelayStore | import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
const Wrapper = styled.div`
`;
const PageError = ({ error }) => (
<Wrapper>
{error.message}
</Wrapper>
);
PageError.propTypes = {
error: PropTypes.object.isRequired,
};
export default PageError;
|
src/app.js | alexbonine/react-starter-kit | /*
* React.js Starter Kit
* Copyright (c) 2014 Konstantin Tarkus (@koistya), KriaSoft LLC.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
'use strict';
import 'babel/polyfill';
import React from 'react';
import emptyFunction from 'react/lib/emptyFunction';
import App from './components/App';
import Dispatcher from './core/Dispatcher';
import AppActions from './actions/AppActions';
import ActionTypes from './constants/ActionTypes';
import injectTapEventPlugin from 'react-tap-event-plugin';
var path = decodeURI(window.location.pathname);
var setMetaTag = (name, content) => {
// Remove and create a new <meta /> tag in order to make it work
// with bookmarks in Safari
var elements = document.getElementsByTagName('meta');
[].slice.call(elements).forEach((element) => {
if (element.getAttribute('name') === name) {
element.parentNode.removeChild(element);
}
});
var meta = document.createElement('meta');
meta.setAttribute('name', name);
meta.setAttribute('content', content);
document.getElementsByTagName('head')[0].appendChild(meta);
};
function run() {
// Render the top-level React component
var props = {
path: path,
onSetTitle: (title) => document.title = title,
onSetMeta: setMetaTag,
onPageNotFound: emptyFunction
};
var component = React.createElement(App, props);
var app = React.render(component, document.body);
// Update `Application.path` prop when `window.location` is changed
Dispatcher.register((payload) => {
if (payload.action.actionType === ActionTypes.CHANGE_LOCATION) {
app.setProps({path: decodeURI(payload.action.path)});
}
});
injectTapEventPlugin(); // required by material UI until React v1
}
// Run the application when both DOM is ready
// and page content is loaded
Promise.all([
new Promise((resolve) => {
if (window.addEventListener) {
window.addEventListener('DOMContentLoaded', resolve);
} else {
window.attachEvent('onload', resolve);
}
}),
new Promise((resolve) => {
AppActions.loadPage(path, resolve);
})
]).then(run);
|
frontend/src/index.js | kryptn/modulario | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import 'semantic-ui-css/semantic.min.css';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
client/components/DevTools.js | bbviana/alexandria-mern | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-w"
>
<LogMonitor />
</DockMonitor>
);
|
src/render.js | zab/jumpsuit | import React from 'react'
import { render } from 'react-dom'
//
import ConnectStore from './connectStore'
export default function (...params) {
// If passed a raw state object, combine/create/connect it to the component
const hasState = typeof params[0] === 'object' && typeof params[1] === 'object'
const states = hasState && params[0]
const userComponent = hasState ? params[1] : params[0]
const Comp = hasState ? ConnectStore(states, userComponent) : () => userComponent
// If we're in the dom, render to it
global.document && render(
<Comp />,
global.document.getElementById((hasState ? params[2] : params[1]) || 'root')
)
return Comp
}
|
pkg/users/delete-account-dialog.js | deryni/cockpit | /*
* This file is part of Cockpit.
*
* Copyright (C) 2020 Red Hat, Inc.
*
* Cockpit is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* Cockpit is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with Cockpit; If not, see <http://www.gnu.org/licenses/>.
*/
import cockpit from 'cockpit';
import React from 'react';
import { Checkbox } from '@patternfly/react-core';
import { show_modal_dialog } from "cockpit-components-dialog.jsx";
const _ = cockpit.gettext;
function DeleteAccountDialogBody({ state, change }) {
const { delete_files } = state;
return (
<Checkbox id="account-confirm-delete-files"
label={_("Delete files")}
isChecked={delete_files} onChange={checked => change("delete_files", checked)} />
);
}
export function delete_account_dialog(account) {
let dlg = null;
const state = {
delete_files: false
};
function change(field, value) {
state[field] = value;
update();
}
function update() {
const props = {
id: "account-confirm-delete-dialog",
title: cockpit.format(_("Delete $0"), account.name),
body: <DeleteAccountDialogBody state={state} change={change} />
};
const footer = {
actions: [
{
caption: _("Delete"),
style: "danger",
clicked: () => {
var prog = ["/usr/sbin/userdel"];
if (state.delete_files)
prog.push("-r");
prog.push(account.name);
return cockpit.spawn(prog, { superuser: "require", err: "message" })
.then(function () {
cockpit.location.go("/");
});
}
}
]
};
if (!dlg)
dlg = show_modal_dialog(props, footer);
else {
dlg.setProps(props);
dlg.setFooterProps(footer);
}
}
update();
}
|
src/js/components/icons/base/FormPrevious.js | odedre/grommet-final | /**
* @description FormPrevious SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-form-previous`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'form-previous');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polyline fill="none" stroke="#000" strokeWidth="2" points="9 6 15 12 9 18" transform="matrix(-1 0 0 1 24 0)"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'FormPrevious';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
monkey/monkey_island/cc/ui/src/components/pages/ReportPage.js | guardicore/monkey | import React from 'react';
import {Route} from 'react-router-dom';
import {Col, Nav} from 'react-bootstrap';
import AuthComponent from '../AuthComponent';
import MustRunMonkeyWarning from '../report-components/common/MustRunMonkeyWarning';
import AttackReport from '../report-components/AttackReport';
import SecurityReport from '../report-components/SecurityReport';
import ZeroTrustReport from '../report-components/ZeroTrustReport';
import RansomwareReport from '../report-components/RansomwareReport';
import {extractExecutionStatusFromServerResponse} from '../report-components/common/ExecutionStatus';
import MonkeysStillAliveWarning from '../report-components/common/MonkeysStillAliveWarning';
class ReportPageComponent extends AuthComponent {
constructor(props) {
super(props);
this.sections = ['security', 'zeroTrust', 'attack', 'ransomware'];
this.state = {
securityReport: {},
attackReport: {},
zeroTrustReport: {},
ransomwareReport: {},
allMonkeysAreDead: false,
runStarted: true,
selectedSection: ReportPageComponent.selectReport(this.sections),
orderedSections: [{key: 'security', title: 'Security report'},
{key: 'zeroTrust', title: 'Zero trust report'},
{key: 'attack', title: 'ATT&CK report'}]
};
}
static selectReport(reports) {
let url = window.location.href;
for (let report_name in reports) {
if (Object.prototype.hasOwnProperty.call(reports, report_name) && url.endsWith(reports[report_name])) {
return reports[report_name];
}
}
}
getReportFromServer(res) {
if (res['completed_steps']['run_monkey']) {
this.authFetch('/api/report/security')
.then(res => res.json())
.then(res => {
this.setState({
securityReport: res
});
});
this.authFetch('/api/report/attack')
.then(res => res.json())
.then(res => {
this.setState({
attackReport: res
});
});
this.getZeroTrustReportFromServer().then((ztReport) => {
this.setState({zeroTrustReport: ztReport})
});
this.authFetch('/api/report/ransomware')
.then(res => res.json())
.then(res => {
this.setState({
ransomwareReport: res
});
});
}
}
getZeroTrustReportFromServer = async () => {
let ztReport = {findings: {}, principles: {}, pillars: {}};
await this.authFetch('/api/report/zero-trust/findings')
.then(res => res.json())
.then(res => {
ztReport.findings = res;
});
await this.authFetch('/api/report/zero-trust/principles')
.then(res => res.json())
.then(res => {
ztReport.principles = res;
});
await this.authFetch('/api/report/zero-trust/pillars')
.then(res => res.json())
.then(res => {
ztReport.pillars = res;
});
return ztReport
};
componentWillUnmount() {
clearInterval(this.state.ztReportRefreshInterval);
}
updateMonkeysRunning = () => {
return this.authFetch('/api')
.then(res => res.json())
.then(res => {
this.setState(extractExecutionStatusFromServerResponse(res));
return res;
});
};
componentDidMount() {
const ztReportRefreshInterval = setInterval(this.updateZeroTrustReportFromServer, 8000);
this.setState({ztReportRefreshInterval: ztReportRefreshInterval});
this.updateMonkeysRunning().then(res => this.getReportFromServer(res));
}
setSelectedSection = (key) => {
this.setState({
selectedSection: key
});
};
renderNav = () => {
return (
<Route render={({history}) => (
<Nav variant='tabs'
fill
activeKey={this.state.selectedSection}
onSelect={(key) => {
this.setSelectedSection(key);
history.push(key)
}}
className={'report-nav'}>
{this.state.orderedSections.map(section => this.renderNavButton(section))}
</Nav>)}/>)
};
renderNavButton = (section) => {
return (
<Nav.Item key={section.key}>
<Nav.Link key={section.key}
eventKey={section.key}
onSelect={() => {
}}>
{section.title}
</Nav.Link>
</Nav.Item>)
};
getReportContent() {
switch (this.state.selectedSection) {
case 'security':
return (<SecurityReport report={this.state.securityReport}/>);
case 'attack':
return (<AttackReport report={this.state.attackReport}/>);
case 'zeroTrust':
return (<ZeroTrustReport report={this.state.zeroTrustReport}/>);
case 'ransomware':
return (
<RansomwareReport
report={this.state.ransomwareReport}
/>
);
}
}
addRansomwareTab() {
let ransomwareTab = {key: 'ransomware', title: 'Ransomware report'};
if(this.isRansomwareTabMissing(ransomwareTab)){
if (this.props.islandMode === 'ransomware') {
this.state.orderedSections.splice(0, 0, ransomwareTab);
}
else {
this.state.orderedSections.push(ransomwareTab);
}
}
}
isRansomwareTabMissing(ransomwareTab) {
return (
this.props.islandMode !== undefined &&
!this.state.orderedSections.some(tab =>
(tab.key === ransomwareTab.key
&& tab.title === ransomwareTab.title)
));
}
render() {
let content;
this.addRansomwareTab();
if (this.state.runStarted) {
content = this.getReportContent();
} else {
content = <MustRunMonkeyWarning/>;
}
return (
<Col sm={{offset: 3, span: 9}} md={{offset: 3, span: 9}}
lg={{offset: 3, span: 9}} xl={{offset: 2, span: 10}}
className={'report-wrapper'}>
<h1 className='page-title no-print'>3. Security Reports</h1>
{this.renderNav()}
<MonkeysStillAliveWarning allMonkeysAreDead={this.state.allMonkeysAreDead}/>
<div style={{'fontSize': '1.2em'}}>
{content}
</div>
</Col>
);
}
}
export default ReportPageComponent;
|
pkg/interface/chat/src/js/components/chat.js | ngzax/urbit | import React, { Component } from 'react';
import classnames from 'classnames';
import _ from 'lodash';
import moment from 'moment';
import { Route, Link } from "react-router-dom";
import { store } from "/store";
import { ResubscribeElement } from '/components/lib/resubscribe-element';
import { BacklogElement } from '/components/lib/backlog-element';
import { Message } from '/components/lib/message';
import { SidebarSwitcher } from '/components/lib/icons/icon-sidebar-switch.js';
import { ChatTabBar } from '/components/lib/chat-tabbar';
import { ChatInput } from '/components/lib/chat-input';
import { UnreadNotice } from '/components/lib/unread-notice';
import { deSig } from '/lib/util';
function getNumPending(props) {
const result = props.pendingMessages.has(props.station)
? props.pendingMessages.get(props.station).length
: 0;
return result;
}
const ACTIVITY_TIMEOUT = 60000; // a minute
const DEFAULT_BACKLOG_SIZE = 300;
function scrollIsAtTop(container) {
if ((navigator.userAgent.includes("Safari") &&
navigator.userAgent.includes("Chrome")) ||
navigator.userAgent.includes("Firefox")
) {
return container.scrollTop === 0;
} else if (navigator.userAgent.includes("Safari")) {
return container.scrollHeight + Math.round(container.scrollTop) <=
container.clientHeight + 10;
} else {
return false;
}
}
function scrollIsAtBottom(container) {
if ((navigator.userAgent.includes("Safari") &&
navigator.userAgent.includes("Chrome")) ||
navigator.userAgent.includes("Firefox")
) {
return container.scrollHeight - Math.round(container.scrollTop) <=
container.clientHeight + 10;
} else if (navigator.userAgent.includes("Safari")) {
return container.scrollTop === 0;
} else {
return false;
}
}
export class ChatScreen extends Component {
constructor(props) {
super(props);
this.state = {
numPages: 1,
scrollLocked: false,
read: props.read,
active: true,
// only for FF
lastScrollHeight: null,
};
this.hasAskedForMessages = false;
this.lastNumPending = 0;
this.scrollContainer = null;
this.onScroll = this.onScroll.bind(this);
this.unreadMarker = null;
this.scrolledToMarker = false;
this.setUnreadMarker = this.setUnreadMarker.bind(this);
this.activityTimeout = true;
this.handleActivity = this.handleActivity.bind(this);
this.setInactive = this.setInactive.bind(this);
moment.updateLocale('en', {
calendar: {
sameDay: '[Today]',
nextDay: '[Tomorrow]',
nextWeek: 'dddd',
lastDay: '[Yesterday]',
lastWeek: '[Last] dddd',
sameElse: 'DD/MM/YYYY'
}
});
}
componentDidMount() {
document.addEventListener("mousemove", this.handleActivity, false);
document.addEventListener("mousedown", this.handleActivity, false);
document.addEventListener("keypress", this.handleActivity, false);
document.addEventListener("touchmove", this.handleActivity, false);
this.activityTimeout = setTimeout(this.setInactive, ACTIVITY_TIMEOUT);
}
componentWillUnmount() {
document.removeEventListener("mousemove", this.handleActivity, false);
document.removeEventListener("mousedown", this.handleActivity, false);
document.removeEventListener("keypress", this.handleActivity, false);
document.removeEventListener("touchmove", this.handleActivity, false);
if(this.activityTimeout) {
clearTimeout(this.activityTimeout);
}
}
handleActivity() {
if(!this.state.active) {
this.setState({ active: true });
}
if(this.activityTimeout) {
clearTimeout(this.activityTimeout);
}
this.activityTimeout = setTimeout(this.setInactive, ACTIVITY_TIMEOUT);
}
setInactive() {
this.activityTimeout = null;
this.setState({ active: false, scrollLocked: true });
}
receivedNewChat() {
const { props } = this;
this.hasAskedForMessages = false;
this.unreadMarker = null;
this.scrolledToMarker = false;
this.setState({ read: props.read });
const unread = props.length - props.read;
const unreadUnloaded = unread - props.envelopes.length;
if(unreadUnloaded + 20 > DEFAULT_BACKLOG_SIZE) {
this.askForMessages(unreadUnloaded + 20);
} else {
this.askForMessages(DEFAULT_BACKLOG_SIZE);
}
if(props.read === props.length){
this.scrolledToMarker = true;
this.setState(
{
scrollLocked: false,
},
() => {
this.scrollToBottom();
}
);
} else {
this.setState({ scrollLocked: true, numPages: Math.ceil(unread/100) });
}
}
componentDidUpdate(prevProps, prevState) {
const { props, state } = this;
if (
prevProps.match.params.station !== props.match.params.station ||
prevProps.match.params.ship !== props.match.params.ship
) {
this.receivedNewChat();
} else if (props.chatInitialized &&
!(props.station in props.inbox) &&
(!!props.chatSynced && !(props.station in props.chatSynced))) {
props.history.push("/~chat");
} else if (
props.envelopes.length >= prevProps.envelopes.length + 10
) {
this.hasAskedForMessages = false;
} else if(props.length !== prevProps.length &&
prevProps.length === prevState.read &&
state.active
) {
this.setState({ read: props.length });
this.props.api.chat.read(this.props.station);
}
if(!prevProps.chatInitialized && props.chatInitialized) {
this.receivedNewChat();
}
if (
(props.length !== prevProps.length ||
props.envelopes.length !== prevProps.envelopes.length ||
getNumPending(props) !== this.lastNumPending ||
state.numPages !== prevState.numPages)
) {
this.scrollToBottom();
if(navigator.userAgent.includes("Firefox")) {
this.recalculateScrollTop();
}
this.lastNumPending = getNumPending(props);
}
}
askForMessages(size) {
const { props, state } = this;
if (
props.envelopes.length >= props.length ||
this.hasAskedForMessages ||
props.length <= 0
) {
return;
}
let start =
props.length - props.envelopes[props.envelopes.length - 1].number;
if (start > 0) {
const end = start + size < props.length ? start + size : props.length;
this.hasAskedForMessages = true;
props.subscription.fetchMessages(start + 1, end, props.station);
}
}
scrollToBottom() {
if (!this.state.scrollLocked && this.scrollElement) {
this.scrollElement.scrollIntoView();
}
}
// Restore chat position on FF when new messages come in
recalculateScrollTop() {
if(!this.scrollContainer) {
return;
}
const { lastScrollHeight } = this.state;
let target = this.scrollContainer;
let newScrollTop = this.scrollContainer.scrollHeight - lastScrollHeight;
if(target.scrollTop !== 0 || newScrollTop === target.scrollTop) {
return;
}
target.scrollTop = target.scrollHeight - lastScrollHeight;
}
onScroll(e) {
if(scrollIsAtTop(e.target)) {
// Save scroll position for FF
if (navigator.userAgent.includes('Firefox')) {
this.setState({
lastScrollHeight: e.target.scrollHeight
});
}
this.setState(
{
numPages: this.state.numPages + 1,
scrollLocked: true
},
() => {
this.askForMessages(DEFAULT_BACKLOG_SIZE);
}
);
} else if (scrollIsAtBottom(e.target)) {
this.dismissUnread();
this.setState({
numPages: 1,
scrollLocked: false
});
}
}
setUnreadMarker(ref) {
if(ref && !this.scrolledToMarker) {
this.setState({ scrollLocked: true }, () => {
ref.scrollIntoView({ block: 'center' });
if(ref.offsetParent &&
scrollIsAtBottom(ref.offsetParent)) {
this.dismissUnread();
this.setState({
numPages: 1,
scrollLocked: false
});
}
});
this.scrolledToMarker = true;
}
this.unreadMarker = ref;
}
dismissUnread() {
this.props.api.chat.read(this.props.station);
}
chatWindow(unread) {
// Replace with just the "not Firefox" implementation
// when Firefox #1042151 is patched.
const { props, state } = this;
let messages = props.envelopes.slice(0);
let lastMsgNum = messages.length > 0 ? messages.length : 0;
if (messages.length > 100 * state.numPages) {
messages = messages.slice(0, 100 * state.numPages);
}
let pendingMessages = props.pendingMessages.has(props.station)
? props.pendingMessages.get(props.station)
: [];
pendingMessages.map(function (value) {
return (value.pending = true);
});
messages = pendingMessages.concat(messages);
let messageElements = messages.map((msg, i) => {
// Render sigil if previous message is not by the same sender
let aut = ["author"];
let renderSigil =
_.get(messages[i + 1], aut) !==
_.get(msg, aut, msg.author);
let paddingTop = renderSigil;
let paddingBot =
_.get(messages[i - 1], aut) !==
_.get(msg, aut, msg.author);
let when = ['when'];
let dayBreak =
moment(_.get(messages[i+1], when)).format('YYYY.MM.DD') !==
moment(_.get(messages[i], when)).format('YYYY.MM.DD');
const messageElem = (
<Message
key={msg.uid}
msg={msg}
contacts={props.contacts}
renderSigil={renderSigil}
paddingTop={paddingTop}
paddingBot={paddingBot}
pending={!!msg.pending}
group={props.association}
/>
);
if(unread > 0 && i === unread - 1) {
return (
<>
{messageElem}
<div key={'unreads'+ msg.uid} ref={this.setUnreadMarker} className="mv2 green2 flex items-center f9">
<hr className="dn-s ma0 w2 b--green2 bt-0" />
<p className="mh4">
New messages below
</p>
<hr className="ma0 flex-grow-1 b--green2 bt-0" />
{ dayBreak && (
<p className="gray2 mh4">
{moment(_.get(messages[i], when)).calendar()}
</p>
)}
<hr style={{ width: 'calc(50% - 48px)' }} className="b--green2 ma0 bt-0"/>
</div>
</>
);
} else if(dayBreak) {
return (
<>
{messageElem}
<div key={'daybreak' + msg.uid} className="pv3 gray2 b--gray2 flex items-center justify-center f9 ">
<p>
{moment(_.get(messages[i], when)).calendar()}
</p>
</div>
</>
);
} else {
return messageElem;
}
});
if (navigator.userAgent.includes("Firefox")) {
return (
<div className="relative overflow-y-scroll h-100" onScroll={this.onScroll} ref={e => { this.scrollContainer = e; }}>
<div
className="bg-white bg-gray0-d pt3 pb2 flex flex-column-reverse"
style={{ resize: "vertical" }}
>
<div
ref={el => {
this.scrollElement = el;
}}></div>
{(props.chatInitialized &&
!(props.station in props.inbox)) && (
<BacklogElement />
)}
{(
props.chatSynced &&
!(props.station in props.chatSynced) &&
(messages.length > 0)
) ? (
<ResubscribeElement
api={props.api}
host={props.match.params.ship}
station={props.station} />
) : (<div />)
}
{messageElements}
</div>
</div>
)}
else {
return (
<div
className="overflow-y-scroll bg-white bg-gray0-d pt3 pb2 flex flex-column-reverse relative"
style={{ height: "100%", resize: "vertical" }}
onScroll={this.onScroll}
>
<div
ref={el => {
this.scrollElement = el;
}}></div>
{(props.chatInitialized &&
!(props.station in props.inbox)) && (
<BacklogElement />
)}
{(
props.chatSynced &&
!(props.station in props.chatSynced) &&
(messages.length > 0)
) ? (
<ResubscribeElement
api={props.api}
host={props.match.params.ship}
station={props.station} />
) : (<div />)
}
{messageElements}
</div>
)}
}
render() {
const { props, state } = this;
let messages = props.envelopes.slice(0);
let lastMsgNum = messages.length > 0 ? messages.length : 0;
let group = Array.from(props.permission.who.values());
const isinPopout = props.popout ? "popout/" : "";
let ownerContact = (window.ship in props.contacts)
? props.contacts[window.ship] : false;
let title = props.station.substr(1);
if (props.association && "metadata" in props.association) {
title =
props.association.metadata.title !== ""
? props.association.metadata.title
: props.station.substr(1);
}
const unread = props.length - state.read;
const unreadMsg = unread > 0 && messages[unread - 1];
const showUnreadNotice = props.length !== props.read && props.read === state.read;
return (
<div
key={props.station}
className="h-100 w-100 overflow-hidden flex flex-column relative">
<div
className="w-100 dn-m dn-l dn-xl inter pt4 pb6 pl3 f8"
style={{ height: "1rem" }}>
<Link to="/~chat/">{"⟵ All Chats"}</Link>
</div>
<div
className={"pl4 pt2 bb b--gray4 b--gray1-d bg-gray0-d flex relative" +
"overflow-x-scroll overflow-x-auto-l overflow-x-auto-xl flex-shrink-0"}
style={{ height: 48 }}>
<SidebarSwitcher
sidebarShown={this.props.sidebarShown}
popout={this.props.popout}
/>
<Link to={`/~chat/` + isinPopout + `room` + props.station}
className="pt2 white-d">
<h2
className={"dib f9 fw4 lh-solid v-top " +
((title === props.station.substr(1)) ? "mono" : "")}
style={{ width: "max-content" }}>
{title}
</h2>
</Link>
<ChatTabBar
{...props}
station={props.station}
numPeers={group.length}
isOwner={deSig(props.match.params.ship) === window.ship}
popout={this.props.popout}
api={props.api}
/>
</div>
{ !!unreadMsg && showUnreadNotice && (
<UnreadNotice
unread={unread}
unreadMsg={unreadMsg}
onRead={() => this.dismissUnread()}
/>
) }
{this.chatWindow(unread)}
<ChatInput
api={props.api}
numMsgs={lastMsgNum}
station={props.station}
owner={deSig(props.match.params.ship)}
ownerContact={ownerContact}
envelopes={props.envelopes}
contacts={props.contacts}
onEnter={() => this.setState({ scrollLocked: false })}
s3={props.s3}
placeholder="Message..."
/>
</div>
);
}
}
|
examples/with-atlaskit/components/ButtonComponent.js | JeromeFitz/next.js | import React from 'react'
import Button, { ButtonGroup } from '@atlaskit/button'
export default function ButtonComponent() {
return (
<React.Fragment>
<Button style={{ margin: 10 }}>Button</Button>
<Button style={{ margin: 10 }} appearance="primary">
Primary Button
</Button>
<Button style={{ margin: 10 }} appearance="danger">
Danger Button
</Button>
<Button style={{ margin: 10 }} appearance="warning">
Warning Button
</Button>
<Button style={{ margin: 10 }} appearance="link">
Link Button
</Button>
<Button style={{ margin: 10 }} isDisabled>
Disabled Button
</Button>
<ButtonGroup appearance="primary">
<Button>First Button</Button>
<Button>Second Button</Button>
<Button>Third Button</Button>
</ButtonGroup>
</React.Fragment>
)
}
|
src/App.js | lumio/waveblock | import React from 'react';
import styled from 'styled-components';
import WaveBlock from './components/WaveBlock';
import AudioData from './components/AudioData';
import Controls from './components/Controls';
const AppWrapper = styled.div`
width: 100vw;
height: 100vh;
display: flex;
justify-content: center;
align-items: center;
`;
export default class App extends React.Component {
static remapData( data, map ) {
if ( !map || !map.length ) {
return data;
}
return map.map( key => data[ key ] );
}
constructor() {
super();
this.state = {
data: [
.05, .05, .05,
.05, .05, .05,
.05, .05, .05,
],
// map: false,
map: [
3, 4, 5,
1, 0, 2,
6, 7, 3,
],
options: {
source: 'File',
mode: 'line',
color: '#fff',
},
};
}
updateData = ( data ) => {
this.setState( {
...this.state,
data: App.remapData( data, this.state.map ),
} );
}
updateOption = ( key, value ) => {
this.setState( {
...this.state,
options: {
...this.state.options,
[ key ]: value,
},
} );
};
render() {
return (
<AppWrapper>
<Controls
updateOption={ this.updateOption }
hideControls={ this.state.options.hideControls }
options={ this.state.options }
>
<AudioData
updateData={ this.updateData }
source={ this.state.options.source }
/>
</Controls>
<WaveBlock
data={ this.state.data }
mode={ this.state.options.mode }
color={ this.state.options.color }
/>
</AppWrapper>
);
}
}
|
src/pages/inndax.js | vitorbarbosa19/ziro-online | import React from 'react'
import BrandGallery from '../components/BrandGallery'
export default () => (
<BrandGallery brand='Inndax' />
)
|
stories/examples/ControlledChipInput.js | TeamWertarbyte/material-ui-chip-input | /* global alert */
import React from 'react'
import PropTypes from 'prop-types'
import ChipInput from '../../src/ChipInput'
class ControlledChipInput extends React.Component {
constructor (props) {
super(props)
this.state = {
chips: ['react']
}
}
onBeforeAdd (chip) {
return chip.length >= 3
}
handleAdd (chip) {
this.setState({
chips: [...this.state.chips, chip]
})
}
handleDelete (deletedChip) {
if (deletedChip !== 'react') {
this.setState({
chips: this.state.chips.filter((c) => c !== deletedChip)
})
} else {
alert('Why would you delete React?')
}
}
render () {
return <ChipInput
{...this.props}
value={this.state.chips}
onBeforeAdd={(chip) => this.onBeforeAdd(chip)}
onAdd={(chip) => this.handleAdd(chip)}
onDelete={(deletedChip) => this.handleDelete(deletedChip)}
onBlur={(event) => {
if (this.props.addOnBlur && event.target.value) {
this.handleAdd(event.target.value)
}
}}
fullWidth
label='Some chips with at least three characters'
/>
}
}
ControlledChipInput.propTypes = {
addOnBlur: PropTypes.bool
}
export default ControlledChipInput
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.