path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
frontend/src/components/username-history/root.js | 1905410/Misago | import React from 'react';
import ListEmpty from 'misago/components/username-history/list-empty'; // jshint ignore:line
import ListReady from 'misago/components/username-history/list-ready'; // jshint ignore:line
import ListPreview from 'misago/components/username-history/list-preview'; // jshint ignore:line
export default class extends React.Component {
render() {
if (this.props.isLoaded) {
if (this.props.changes.length) {
/* jshint ignore:start */
return <ListReady changes={this.props.changes} />;
/* jshint ignore:end */
} else {
/* jshint ignore:start */
return <ListEmpty emptyMessage={this.props.emptyMessage} />;
/* jshint ignore:end */
}
} else {
/* jshint ignore:start */
return <ListPreview />;
/* jshint ignore:end */
}
}
} |
examples/CardSimple.js | 15lyfromsaturn/react-materialize | import React from 'react';
import Card from '../src/Card';
import Col from '../src/Col';
export default
<Col m={6} s={12}>
<Card className='blue-grey darken-1' textClassName='white-text' title='Card title' actions={[<a href='#'>This is a link</a>]}>
I am a very simple card.
</Card>
</Col>;
|
src/svg-icons/action/hourglass-full.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHourglassFull = (props) => (
<SvgIcon {...props}>
<path d="M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6z"/>
</SvgIcon>
);
ActionHourglassFull = pure(ActionHourglassFull);
ActionHourglassFull.displayName = 'ActionHourglassFull';
ActionHourglassFull.muiName = 'SvgIcon';
export default ActionHourglassFull;
|
frontend/src/Settings/Metadata/Metadata/Metadata.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Card from 'Components/Card';
import Label from 'Components/Label';
import { kinds } from 'Helpers/Props';
import EditMetadataModalConnector from './EditMetadataModalConnector';
import styles from './Metadata.css';
class Metadata extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
isEditMetadataModalOpen: false
};
}
//
// Listeners
onEditMetadataPress = () => {
this.setState({ isEditMetadataModalOpen: true });
}
onEditMetadataModalClose = () => {
this.setState({ isEditMetadataModalOpen: false });
}
//
// Render
render() {
const {
id,
name,
enable,
fields
} = this.props;
const metadataFields = [];
const imageFields = [];
fields.forEach((field) => {
if (field.section === 'metadata') {
metadataFields.push(field);
} else {
imageFields.push(field);
}
});
return (
<Card
className={styles.metadata}
overlayContent={true}
onPress={this.onEditMetadataPress}
>
<div className={styles.name}>
{name}
</div>
<div>
{
enable ?
<Label kind={kinds.SUCCESS}>
Enabled
</Label> :
<Label
kind={kinds.DISABLED}
outline={true}
>
Disabled
</Label>
}
</div>
{
enable && !!metadataFields.length &&
<div>
<div className={styles.section}>
Metadata
</div>
{
metadataFields.map((field) => {
if (!field.value) {
return null;
}
return (
<Label
key={field.label}
kind={kinds.SUCCESS}
>
{field.label}
</Label>
);
})
}
</div>
}
{
enable && !!imageFields.length &&
<div>
<div className={styles.section}>
Images
</div>
{
imageFields.map((field) => {
if (!field.value) {
return null;
}
return (
<Label
key={field.label}
kind={kinds.SUCCESS}
>
{field.label}
</Label>
);
})
}
</div>
}
<EditMetadataModalConnector
id={id}
isOpen={this.state.isEditMetadataModalOpen}
onModalClose={this.onEditMetadataModalClose}
/>
</Card>
);
}
}
Metadata.propTypes = {
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
enable: PropTypes.bool.isRequired,
fields: PropTypes.arrayOf(PropTypes.object).isRequired
};
export default Metadata;
|
src/icons/ConnectionBars.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class ConnectionBars extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<rect x="80" y="352" width="64" height="64"></rect>
<rect x="176" y="288" width="64" height="128"></rect>
<rect x="272" y="192" width="64" height="224"></rect>
<rect x="368" y="96" width="64" height="320"></rect>
</g>
</g>;
} return <IconBase>
<g>
<rect x="80" y="352" width="64" height="64"></rect>
<rect x="176" y="288" width="64" height="128"></rect>
<rect x="272" y="192" width="64" height="224"></rect>
<rect x="368" y="96" width="64" height="320"></rect>
</g>
</IconBase>;
}
};ConnectionBars.defaultProps = {bare: false} |
client/components/popover/AdminCreateBasisForm.js | slantz/slasti-od-ua | import React from 'react'
import { Field, reduxForm } from 'redux-form'
import {connect} from 'react-redux'
import * as InputWithValidation from '../elements/InputWithValidation'
import * as UTIL from '../../util/util'
import { RaisedButton } from "material-ui";
import { ru_RU } from "../../constants/Translations";
let AdminCreateBasisForm = (props) => {
const { handleSubmit } = props;
return (
<form onSubmit={handleSubmit}>
<fieldset>
<Field name="type"
component={InputWithValidation.renderField}
type="text"
label={ru_RU['COMPONENT.POPOVER.ADMIN_CREATE_BASIS_FORM.TYPE']}
placeholder={ru_RU['COMPONENT.POPOVER.ADMIN_CREATE_BASIS_FORM.TYPE']}
placeholderAccusative={ru_RU['COMPONENT.POPOVER.ADMIN_CREATE_BASIS_FORM.TYPE_ACCUSATIVE']}/>
<Field name="composition"
component={InputWithValidation.renderField}
type="text"
label={ru_RU['COMPONENT.POPOVER.ADMIN_CREATE_BASIS_FORM.COMPOSITION']}
placeholder={ru_RU['COMPONENT.POPOVER.ADMIN_CREATE_BASIS_FORM.COMPOSITION']}
placeholderAccusative={ru_RU['COMPONENT.POPOVER.ADMIN_CREATE_BASIS_FORM.COMPOSITION_ACCUSATIVE']}/>
</fieldset>
<fieldset>
<RaisedButton primary={true} label={ru_RU['COMPONENT.POPOVER.ADMIN_CREATE_BASIS_FORM.SUBMIT']} type="submit" />
</fieldset>
</form>
)
};
AdminCreateBasisForm = reduxForm({
form: 'admin-create-basis',
enableReinitialize: true,
validate: InputWithValidation.validateBasis,
warn: InputWithValidation.warn
})(AdminCreateBasisForm);
AdminCreateBasisForm = connect(
state => ({
initialValues: UTIL.getFirstInitialValue(state.admin.basis.currentBasis, 'type')
})
)(AdminCreateBasisForm);
export default AdminCreateBasisForm
|
src/svg-icons/action/perm-media.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermMedia = (props) => (
<SvgIcon {...props}>
<path d="M2 6H0v5h.01L0 20c0 1.1.9 2 2 2h18v-2H2V6zm20-2h-8l-2-2H6c-1.1 0-1.99.9-1.99 2L4 16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zM7 15l4.5-6 3.5 4.51 2.5-3.01L21 15H7z"/>
</SvgIcon>
);
ActionPermMedia = pure(ActionPermMedia);
ActionPermMedia.displayName = 'ActionPermMedia';
ActionPermMedia.muiName = 'SvgIcon';
export default ActionPermMedia;
|
example1/toilet/ios_views/read/category.js | anchoretics/ztf-work-app | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
ScrollView,
Image,
TouchableOpacity
} from 'react-native';
import Util from './../util';
import List from './list';
class Category extends Component{
constructor(props){
super(props);
this.state = {
data: this.props.data
};
}
render(){
let data = this.props.data;
var first = [];
let second = [];
for(var i in data){
let Item = (
<TouchableOpacity style={[styles.categoryTopic]} key={i} onPress={this._showList.bind(this, data[i].text)}>
<Text style={[styles.title, styles.fontFFF]}>{data[i].text}</Text>
</TouchableOpacity>
);
if(i < 2){
first.push(Item);
}else{
second.push(Item);
}
}
return(
<View style={{marginRight:10}}>
<View>
<Text style={[styles.bigText, {marginLeft:10}]}>分类</Text>
</View>
<View style={[styles.row, {marginTop:10}]}>
{first}
</View>
<View style={[styles.row, {marginTop:10}]}>
{second}
</View>
</View>
);
}
_showList(keywords){
var type = 'it';
switch (keywords){
case '互联网':
type = 'it';
break;
case '散文':
type = 'sanwen';
break;
case '笑话':
type = 'cookies';
break;
case '管理':
type = 'manager';
break;
default :
type = 'it';
break;
}
this.props.navigator.push({
component: List,
barTintColor: '#fff',
title: keywords,
passProps:{
type: type
}
});
}
}
const styles = StyleSheet.create({
bigText:{
fontSize:17,
fontWeight: '300',
marginBottom: 5
},
row:{
flexDirection: 'row'
},
categoryTopic:{
height: 70,
borderWidth: Util.pixel,
borderColor: '#ccc',
justifyContent: 'center',
alignItems: 'center',
flex:1,
borderRadius: 3,
marginLeft:10
},
title:{
fontSize:17,
fontWeight:'300'
},
fontFFF:{
//color:'#fff'
}
});
module.exports = Category; |
src/svg-icons/device/devices.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceDevices = (props) => (
<SvgIcon {...props}>
<path d="M4 6h18V4H4c-1.1 0-2 .9-2 2v11H0v3h14v-3H4V6zm19 2h-6c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1zm-1 9h-4v-7h4v7z"/>
</SvgIcon>
);
DeviceDevices = pure(DeviceDevices);
DeviceDevices.displayName = 'DeviceDevices';
DeviceDevices.muiName = 'SvgIcon';
export default DeviceDevices;
|
src/dumb/block_graph/ReadonlyBlockGraph.js | jeckhummer/wf-constructor | import React from 'react';
import {WORKFLOW_GRID} from "../../styles";
import {ReadonlyArrowBlock} from "./ReadonlyArrowBlock";
import {Grid} from '../common/Grid';
import * as _ from "lodash";
import {ReadonlyTaskBlock} from "./ReadonlyTaskBlock";
import {EmptyBlockStub} from "./EmptyBlockStub";
export const ReadonlyBlockGraph = ({ matrix }) => {
let content;
if (matrix.length > 0) {
content = matrix.map(
(row, key) => {
const blocks = [
_.flatten(row.map(
(item, i) =>
[<ReadonlyTaskBlock {...item} />].concat([
i !== row.length - 1
? <ReadonlyArrowBlock interceptable={false}/>
: null
])
)
)
];
return (
<div
style={{paddingBottom: key === matrix.length -1 ? '0px' : WORKFLOW_GRID.PADDING}}
key={key}>
<Grid borderless matrix={blocks}/>
</div>
);
}
);
} else {
content = <EmptyBlockStub/>;
}
return (
<div style={{ padding: WORKFLOW_GRID.PADDING }}>
{content}
</div>
);
}; |
templates/rubix/rubix-bootstrap/src/Alert.js | jeffthemaximum/jeffline | import React from 'react';
import BAlert from 'react-bootstrap/lib/Alert';
export default class Alert extends React.Component {
static propTypes = {
success: React.PropTypes.bool,
info: React.PropTypes.bool,
warning: React.PropTypes.bool,
danger: React.PropTypes.bool,
dismissible: React.PropTypes.bool,
};
constructor(...args) {
super(...args);
this.state = { alertVisible: true };
}
handleAlertDismiss() {
this.setState({alertVisible: false});
}
render() {
let props = { ...this.props };
if (props.success) {
props.bsStyle = 'success';
delete props.success;
}
if (props.info) {
props.bsStyle = 'info';
delete props.info;
}
if (props.warning) {
props.bsStyle = 'warning';
delete props.warning;
}
if (props.danger) {
props.bsStyle = 'danger';
delete props.danger;
}
if (!props.dismissible) {
delete props.dismissible;
return <BAlert {...props} />;
}
if (this.state.alertVisible) {
delete props.dismissible;
return <BAlert {...props} onDismiss={::this.handleAlertDismiss} />;
}
return null;
}
}
|
src/CrudRoute.js | RestUI/rest-ui | import React from 'react';
import { IndexRoute, Route } from 'react-router';
import { createRoutesFromReactChildren } from 'react-router/lib/RouteUtils';
import pure from 'recompose/pure';
const CrudRoute = () => <div><CrudRoute> elements are for configuration only and should not be rendered</div>;
CrudRoute.createRouteFromReactElement = (element, parentRoute) => {
const { path, list, create, edit, show, remove, options, onEnter = () => null } = element.props;
// dynamically add crud routes
const crudRoute = createRoutesFromReactChildren(
<Route path={path}>
{list && <IndexRoute component={list} onEnter={onEnter({ resource: path, route: 'list' })} />}
{create && <Route path="create" component={create} onEnter={onEnter({ resource: path, route: 'create' })} />}
{edit && <Route path=":id" component={edit} onEnter={onEnter({ resource: path, route: 'edit', scrollToTop: true })} />}
{show && <Route path=":id/show" component={show} onEnter={onEnter({ resource: path, route: 'show', scrollToTop: true })} />}
{remove && <Route path=":id/delete" component={remove} onEnter={onEnter({ resource: path, route: 'delete' })} />}
</Route>,
parentRoute,
)[0];
// higher-order component to pass path as resource to components
crudRoute.component = pure(({ children }) => (
<div>
{React.Children.map(children, child => React.cloneElement(child, {
resource: path,
options,
hasList: !!list,
hasEdit: !!edit,
hasShow: !!show,
hasCreate: !!create,
hasDelete: !!remove,
}))}
</div>
));
return crudRoute;
};
export default CrudRoute;
|
app/javascript/mastodon/features/ui/components/column_loading.js | tri-star/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Column from '../../../components/column';
import ColumnHeader from '../../../components/column_header';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class ColumnLoading extends ImmutablePureComponent {
static propTypes = {
title: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
icon: PropTypes.string,
};
static defaultProps = {
title: '',
icon: '',
};
render() {
let { title, icon } = this.props;
return (
<Column>
<ColumnHeader icon={icon} title={title} multiColumn={false} focusable={false} placeholder />
<div className='scrollable' />
</Column>
);
}
}
|
classic/src/scenes/wbui/TooltipSectionListItem.js | wavebox/waveboxapp | import React from 'react'
import shallowCompare from 'react-addons-shallow-compare'
import { withStyles } from '@material-ui/core/styles'
import classNames from 'classnames'
import { ListItem } from '@material-ui/core'
import ThemeTools from 'wbui/Themes/ThemeTools'
const styles = (theme) => ({
root: {
paddingTop: 2,
paddingBottom: 2,
paddingLeft: 8,
paddingRight: 8,
color: ThemeTools.getValue(theme, 'wavebox.popover.section.listItem.color'),
backgroundColor: ThemeTools.getValue(theme, 'wavebox.popover.section.listItem.backgroundColor')
},
rootButton: {
color: ThemeTools.getStateValue(theme, 'wavebox.popover.section.listItem.button.color', 'default'),
backgroundColor: ThemeTools.getStateValue(theme, 'wavebox.popover.section.listItem.button.backgroundColor', 'default'),
'&:hover': {
color: ThemeTools.getStateValue(theme, 'wavebox.popover.section.listItem.button.color', 'hover'),
backgroundColor: ThemeTools.getStateValue(theme, 'wavebox.popover.section.listItem.button.backgroundColor', 'hover')
}
}
})
@withStyles(styles, { withTheme: true })
class TooltipSectionListItem extends React.Component {
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const {
classes,
className,
theme,
children,
button,
...passProps
} = this.props
return (
<ListItem
disableGutters
className={classNames(classes.root, button ? classes.rootButton : undefined, className)}
button={button}
{...passProps}>
{children}
</ListItem>
)
}
}
export default TooltipSectionListItem
|
app/components/component.js | mac10688/react-webpack-cookbook | import './MyComponent.css';
import './LessComponent.less';
import React from 'react';
export default class Hello extends React.Component {
render() {
return (
<div className="MyComponent-wrapper box">
<h1>Hello world!!</h1>
</div>
)
}
} |
src/js/components/text.js | frig-js/frigging-bootstrap | import React from 'react'
import cx from 'classnames'
import InputErrorList from './input_error_list'
import Saved from './saved'
import Label from './label'
import { sizeClassNames, formGroupCx } from '../util.js'
import defaultProps from '../default_props.js'
import defaultPropTypes from '../default_prop_types.js'
export default class Text extends React.Component {
static displayName = 'FriggingBootstrap.Text'
static defaultProps = defaultProps
static propTypes = Object.assign({},
defaultPropTypes, {
rows: React.PropTypes.number,
}
)
_inputHtml() {
return Object.assign({}, this.props.inputHtml, {
className: cx(this.props.className, 'form-control'),
value: this.props.value || '',
onChange: this.props.onChange,
rows: this.props.rows,
})
}
render() {
return (
<div className={cx(sizeClassNames(this.props))}>
<div className={formGroupCx(this.props)}>
<Label {...this.props} />
<div className="controls">
<textarea {...this._inputHtml()} />
</div>
<Saved saved={this.props.saved} />
<InputErrorList errors={this.props.errors} />
</div>
</div>
)
}
}
|
pootle/static/js/editor/components/SuggestionFeedbackForm.js | phlax/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import _ from 'underscore';
import React from 'react';
import assign from 'object-assign';
import FormElement from 'components/FormElement';
const SuggestionFeedBackForm = React.createClass({
propTypes: {
suggId: React.PropTypes.number.isRequired,
initialSuggestionValues: React.PropTypes.array.isRequired,
onAcceptSuggestion: React.PropTypes.func.isRequired,
onRejectSuggestion: React.PropTypes.func.isRequired,
onChange: React.PropTypes.func.isRequired,
editorComponent: React.PropTypes.func.isRequired,
isDisabled: React.PropTypes.bool.isRequired,
sourceValues: React.PropTypes.array.isRequired,
currentLocaleCode: React.PropTypes.string.isRequired,
currentLocaleDir: React.PropTypes.string.isRequired,
targetNplurals: React.PropTypes.number,
},
/* Lifecycle */
getInitialState() {
this.initialData = {
comment: '',
translations: this.props.initialSuggestionValues,
};
return {
formData: this.initialData,
};
},
/* Handlers */
handleAccept(e) {
const suggestionChanged = (
this.state.formData.translations !== this.props.initialSuggestionValues
);
e.preventDefault();
this.props.onAcceptSuggestion(
this.props.suggId,
{
requestData: this.state.formData,
isSuggestionChanged: suggestionChanged,
}
);
},
handleReject(e) {
e.preventDefault();
this.props.onRejectSuggestion(this.props.suggId, { requestData: this.state.formData });
},
handleChange(values) {
const isDirty = !_.isEqual(values, this.initialData);
const formData = assign(this.state.formData, { translations: values });
this.setState({ isDirty, formData });
this.props.onChange(isDirty);
},
handleCommentChange(name, comment) {
const isDirty = comment !== '';
const formData = assign(this.state.formData, { comment });
this.setState({ isDirty, formData });
this.props.onChange(isDirty);
},
/* Layout */
render() {
const { formData } = this.state;
return (
<form
id="suggestion-feedback-form"
>
<div className="fields">
<div className="field-wrapper suggestion-editor">
<label htmlFor="suggestion-editor">
{gettext('Edit the suggestion before accepting, if necessary')}
</label>
<this.props.editorComponent
currentLocaleCode={this.props.currentLocaleCode}
currentLocaleDir={this.props.currentLocaleDir}
initialValues={formData.translations}
onChange={this.handleChange}
sourceValues={this.props.sourceValues}
targetNplurals={this.props.targetNplurals}
isDisabled={this.props.isDisabled}
/>
</div>
<FormElement
type="textarea"
label={gettext('Provide optional comment (will be publicly visible)')}
placeholder=""
name="comment"
handleChange={this.handleCommentChange}
value={formData.comment}
className="comment"
/>
</div>
<p className="buttons">
<button
className="btn btn-success"
onClick={this.handleAccept}
><i className="icon-accept-white"></i>{gettext('Accept')}</button>
<button
className="btn btn-danger"
onClick={this.handleReject}
><i className="icon-reject-white"></i>{gettext('Reject')}</button>
</p>
<div className="clear" />
</form>
);
},
});
export default SuggestionFeedBackForm;
|
pages/contact.js | peterqiu1997/irc | import React, { Component } from 'react';
import Helmet from 'react-helmet';
import { config } from 'config';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers';
import FontAwesome from 'react-fontawesome';
export default class Contact extends Component {
render () {
return (
<div className="page page--contact">
<Helmet
title={config.siteTitle}
/>
<div className="contact--center">
<div className="contact--title">
Contact
</div>
<a href="#" target="_blank">
<FontAwesome
className="media--icon fb"
name="facebook"
/>
</a>
<a href="#" target="_blank">
<FontAwesome
className="media--icon mail"
name="envelope"
/>
</a>
</div>
</div>
);
}
}
|
src/route.js | CRwming/cnode-webapp | /**
* Created by ming on 2017/3/24
*/
import React from 'react';
import {Route, IndexRoute} from 'react-router';
import App from './App';
/*
* 代码分拆
* */
const homeScreen = (location, cb) => {
require.ensure([], require => {
cb(null, require('./containers/HomePage').default);
}, 'HomeScreen');
};
const loginScreen = (location, cb) => {
require.ensure([], require => {
cb(null, require('./containers/Login').default);
}, 'Index');
};
const articleScreen = (location, cb) => {
require.ensure([], require => {
cb(null, require('./containers/Article').default);
}, 'Index');
};
const aboutScreen = (location, cb) => {
require.ensure([], require => {
cb(null, require('./components/About').default);
}, 'Index');
};
const newScreen = (location, cb) => {
require.ensure([], require => {
cb(null, require('./containers/NewTopics').default);
}, 'Index');
};
const isLogin = (nextState, replace) => {
const info = JSON.parse(window.localStorage.getItem("userAcc"));
if (!info) {
replace('/')
}
};
const route = (
<Route path="/" components={App}>
<IndexRoute getComponent={homeScreen}/>
<Route path="login" getComponent={loginScreen}/>
<Route path="article/:id" getComponent={articleScreen}/>
<Route path="/:tab" getComponent={homeScreen}/>
<Route path="/about/me" getComponent={aboutScreen}/>
<Route path="/new/topics" getComponent={newScreen} onEnter={isLogin}/>
</Route>
);
export default route;
|
src/svg-icons/image/crop-landscape.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropLandscape = (props) => (
<SvgIcon {...props}>
<path d="M19 5H5c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 12H5V7h14v10z"/>
</SvgIcon>
);
ImageCropLandscape = pure(ImageCropLandscape);
ImageCropLandscape.displayName = 'ImageCropLandscape';
ImageCropLandscape.muiName = 'SvgIcon';
export default ImageCropLandscape;
|
packages/react-dom/src/server/ReactPartialRenderer.js | silvestrijonathan/react | /**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {ReactElement} from 'shared/ReactElementType';
import React from 'react';
import emptyFunction from 'fbjs/lib/emptyFunction';
import emptyObject from 'fbjs/lib/emptyObject';
import hyphenateStyleName from 'fbjs/lib/hyphenateStyleName';
import invariant from 'fbjs/lib/invariant';
import memoizeStringOnly from 'fbjs/lib/memoizeStringOnly';
import warning from 'fbjs/lib/warning';
import checkPropTypes from 'prop-types/checkPropTypes';
import describeComponentFrame from 'shared/describeComponentFrame';
import {ReactDebugCurrentFrame} from 'shared/ReactGlobalSharedState';
import DOMMarkupOperations from './DOMMarkupOperations';
import {
Namespaces,
getIntrinsicNamespace,
getChildNamespace,
} from '../shared/DOMNamespaces';
import ReactControlledValuePropTypes
from '../shared/ReactControlledValuePropTypes';
import assertValidProps from '../shared/assertValidProps';
import dangerousStyleValue from '../shared/dangerousStyleValue';
import escapeTextContentForBrowser from '../shared/escapeTextContentForBrowser';
import isCustomComponent from '../shared/isCustomComponent';
import omittedCloseTags from '../shared/omittedCloseTags';
import warnValidStyle from '../shared/warnValidStyle';
import {
validateProperties as validateARIAProperties,
} from '../shared/ReactDOMInvalidARIAHook';
import {
validateProperties as validateInputProperties,
} from '../shared/ReactDOMNullInputValuePropHook';
import {
validateProperties as validateUnknownProperties,
} from '../shared/ReactDOMUnknownPropertyHook';
var REACT_FRAGMENT_TYPE =
(typeof Symbol === 'function' &&
Symbol.for &&
Symbol.for('react.fragment')) ||
0xeacb;
// Based on reading the React.Children implementation. TODO: type this somewhere?
type ReactNode = string | number | ReactElement;
type FlatReactChildren = Array<null | ReactNode>;
type toArrayType = (children: mixed) => FlatReactChildren;
var toArray = ((React.Children.toArray: any): toArrayType);
var getStackAddendum = emptyFunction.thatReturns('');
if (__DEV__) {
var validatePropertiesInDevelopment = function(type, props) {
validateARIAProperties(type, props);
validateInputProperties(type, props);
validateUnknownProperties(type, props);
};
var describeStackFrame = function(element): string {
var source = element._source;
var type = element.type;
var name = getComponentName(type);
var ownerName = null;
return describeComponentFrame(name, source, ownerName);
};
var currentDebugStack = null;
var currentDebugElementStack = null;
var setCurrentDebugStack = function(stack: Array<Frame>) {
var frame: Frame = stack[stack.length - 1];
currentDebugElementStack = ((frame: any): FrameDev).debugElementStack;
// We are about to enter a new composite stack, reset the array.
currentDebugElementStack.length = 0;
currentDebugStack = stack;
ReactDebugCurrentFrame.getCurrentStack = getStackAddendum;
};
var pushElementToDebugStack = function(element: ReactElement) {
if (currentDebugElementStack !== null) {
currentDebugElementStack.push(element);
}
};
var resetCurrentDebugStack = function() {
currentDebugElementStack = null;
currentDebugStack = null;
ReactDebugCurrentFrame.getCurrentStack = null;
};
getStackAddendum = function(): null | string {
if (currentDebugStack === null) {
return '';
}
let stack = '';
let debugStack = currentDebugStack;
for (let i = debugStack.length - 1; i >= 0; i--) {
const frame: Frame = debugStack[i];
let debugElementStack = ((frame: any): FrameDev).debugElementStack;
for (let ii = debugElementStack.length - 1; ii >= 0; ii--) {
stack += describeStackFrame(debugElementStack[ii]);
}
}
return stack;
};
}
var didWarnDefaultInputValue = false;
var didWarnDefaultChecked = false;
var didWarnDefaultSelectValue = false;
var didWarnDefaultTextareaValue = false;
var didWarnInvalidOptionChildren = false;
var didWarnAboutNoopUpdateForComponent = {};
var valuePropNames = ['value', 'defaultValue'];
var newlineEatingTags = {
listing: true,
pre: true,
textarea: true,
};
function getComponentName(type) {
return typeof type === 'string'
? type
: typeof type === 'function' ? type.displayName || type.name : null;
}
// We accept any tag to be rendered but since this gets injected into arbitrary
// HTML, we want to make sure that it's a safe tag.
// http://www.w3.org/TR/REC-xml/#NT-Name
var VALID_TAG_REGEX = /^[a-zA-Z][a-zA-Z:_\.\-\d]*$/; // Simplified subset
var validatedTagCache = {};
function validateDangerousTag(tag) {
if (!validatedTagCache.hasOwnProperty(tag)) {
invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag);
validatedTagCache[tag] = true;
}
}
var processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
function createMarkupForStyles(styles): string | null {
var serialized = '';
var delimiter = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
var isCustomProperty = styleName.indexOf('--') === 0;
var styleValue = styles[styleName];
if (__DEV__) {
if (!isCustomProperty) {
warnValidStyle(styleName, styleValue, getStackAddendum);
}
}
if (styleValue != null) {
serialized += delimiter + processStyleName(styleName) + ':';
serialized += dangerousStyleValue(
styleName,
styleValue,
isCustomProperty,
);
delimiter = ';';
}
}
return serialized || null;
}
function warnNoop(
publicInstance: React$Component<any, any>,
callerName: string,
) {
if (__DEV__) {
var constructor = publicInstance.constructor;
const componentName =
(constructor && getComponentName(constructor)) || 'ReactClass';
const warningKey = `${componentName}.${callerName}`;
if (didWarnAboutNoopUpdateForComponent[warningKey]) {
return;
}
warning(
false,
'%s(...): Can only update a mounting component. ' +
'This usually means you called %s() outside componentWillMount() on the server. ' +
'This is a no-op.\n\nPlease check the code for the %s component.',
callerName,
callerName,
componentName,
);
didWarnAboutNoopUpdateForComponent[warningKey] = true;
}
}
function shouldConstruct(Component) {
return Component.prototype && Component.prototype.isReactComponent;
}
function getNonChildrenInnerMarkup(props) {
var innerHTML = props.dangerouslySetInnerHTML;
if (innerHTML != null) {
if (innerHTML.__html != null) {
return innerHTML.__html;
}
} else {
var content = props.children;
if (typeof content === 'string' || typeof content === 'number') {
return escapeTextContentForBrowser(content);
}
}
return null;
}
function flattenTopLevelChildren(children: mixed): FlatReactChildren {
if (!React.isValidElement(children)) {
return toArray(children);
}
const element = ((children: any): ReactElement);
if (element.type !== REACT_FRAGMENT_TYPE) {
return [element];
}
const fragmentChildren = element.props.children;
if (!React.isValidElement(fragmentChildren)) {
return toArray(fragmentChildren);
}
const fragmentChildElement = ((fragmentChildren: any): ReactElement);
return [fragmentChildElement];
}
function flattenOptionChildren(children: mixed): string {
var content = '';
// Flatten children and warn if they aren't strings or numbers;
// invalid types are ignored.
React.Children.forEach(children, function(child) {
if (child == null) {
return;
}
if (typeof child === 'string' || typeof child === 'number') {
content += child;
} else {
if (__DEV__) {
if (!didWarnInvalidOptionChildren) {
didWarnInvalidOptionChildren = true;
warning(
false,
'Only strings and numbers are supported as <option> children.',
);
}
}
}
});
return content;
}
function maskContext(type, context) {
var contextTypes = type.contextTypes;
if (!contextTypes) {
return emptyObject;
}
var maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
return maskedContext;
}
function checkContextTypes(typeSpecs, values, location: string) {
if (__DEV__) {
checkPropTypes(typeSpecs, values, location, 'Component', getStackAddendum);
}
}
function processContext(type, context) {
var maskedContext = maskContext(type, context);
if (__DEV__) {
if (type.contextTypes) {
checkContextTypes(type.contextTypes, maskedContext, 'context');
}
}
return maskedContext;
}
var STYLE = 'style';
var RESERVED_PROPS = {
children: null,
dangerouslySetInnerHTML: null,
suppressContentEditableWarning: null,
suppressHydrationWarning: null,
};
function createOpenTagMarkup(
tagVerbatim: string,
tagLowercase: string,
props: Object,
namespace: string,
makeStaticMarkup: boolean,
isRootElement: boolean,
): string {
var ret = '<' + tagVerbatim;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (propKey === STYLE) {
propValue = createMarkupForStyles(propValue);
}
var markup = null;
if (isCustomComponent(tagLowercase, props)) {
if (!RESERVED_PROPS.hasOwnProperty(propKey)) {
markup = DOMMarkupOperations.createMarkupForCustomAttribute(
propKey,
propValue,
);
}
} else {
markup = DOMMarkupOperations.createMarkupForProperty(propKey, propValue);
}
if (markup) {
ret += ' ' + markup;
}
}
// For static pages, no need to put React ID and checksum. Saves lots of
// bytes.
if (makeStaticMarkup) {
return ret;
}
if (isRootElement) {
ret += ' ' + DOMMarkupOperations.createMarkupForRoot();
}
return ret;
}
function validateRenderResult(child, type) {
if (child === undefined) {
invariant(
false,
'%s(...): Nothing was returned from render. This usually means a ' +
'return statement is missing. Or, to render nothing, ' +
'return null.',
getComponentName(type) || 'Component',
);
}
}
function resolve(
child: mixed,
context: Object,
): {|
child: mixed,
context: Object,
|} {
while (React.isValidElement(child)) {
// Safe because we just checked it's an element.
var element: ReactElement = ((child: any): ReactElement);
if (__DEV__) {
pushElementToDebugStack(element);
}
var Component = element.type;
if (typeof Component !== 'function') {
break;
}
var publicContext = processContext(Component, context);
var inst;
var queue = [];
var replace = false;
var updater = {
isMounted: function(publicInstance) {
return false;
},
enqueueForceUpdate: function(publicInstance) {
if (queue === null) {
warnNoop(publicInstance, 'forceUpdate');
return null;
}
},
enqueueReplaceState: function(publicInstance, completeState) {
replace = true;
queue = [completeState];
},
enqueueSetState: function(publicInstance, partialState) {
if (queue === null) {
warnNoop(publicInstance, 'setState');
return null;
}
queue.push(partialState);
},
};
if (shouldConstruct(Component)) {
inst = new Component(element.props, publicContext, updater);
} else {
inst = Component(element.props, publicContext, updater);
if (inst == null || inst.render == null) {
child = inst;
validateRenderResult(child, Component);
continue;
}
}
inst.props = element.props;
inst.context = publicContext;
inst.updater = updater;
var initialState = inst.state;
if (initialState === undefined) {
inst.state = initialState = null;
}
if (inst.componentWillMount) {
inst.componentWillMount();
if (queue.length) {
var oldQueue = queue;
var oldReplace = replace;
queue = null;
replace = false;
if (oldReplace && oldQueue.length === 1) {
inst.state = oldQueue[0];
} else {
var nextState = oldReplace ? oldQueue[0] : inst.state;
var dontMutate = true;
for (var i = oldReplace ? 1 : 0; i < oldQueue.length; i++) {
var partial = oldQueue[i];
var partialState = typeof partial === 'function'
? partial.call(inst, nextState, element.props, publicContext)
: partial;
if (partialState) {
if (dontMutate) {
dontMutate = false;
nextState = Object.assign({}, nextState, partialState);
} else {
Object.assign(nextState, partialState);
}
}
}
inst.state = nextState;
}
} else {
queue = null;
}
}
child = inst.render();
if (__DEV__) {
if (child === undefined && inst.render._isMockFunction) {
// This is probably bad practice. Consider warning here and
// deprecating this convenience.
child = null;
}
}
validateRenderResult(child, Component);
var childContext;
if (typeof inst.getChildContext === 'function') {
var childContextTypes = Component.childContextTypes;
invariant(
typeof childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
getComponentName(Component) || 'Unknown',
);
childContext = inst.getChildContext();
for (let contextKey in childContext) {
invariant(
contextKey in childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
getComponentName(Component) || 'Unknown',
contextKey,
);
}
}
if (childContext) {
context = Object.assign({}, context, childContext);
}
}
return {child, context};
}
type Frame = {
domNamespace: string,
children: FlatReactChildren,
childIndex: number,
context: Object,
footer: string,
};
type FrameDev = Frame & {
debugElementStack: Array<ReactElement>,
};
class ReactDOMServerRenderer {
stack: Array<Frame>;
exhausted: boolean;
// TODO: type this more strictly:
currentSelectValue: any;
previousWasTextNode: boolean;
makeStaticMarkup: boolean;
constructor(children: mixed, makeStaticMarkup: boolean) {
const flatChildren = flattenTopLevelChildren(children);
var topFrame: Frame = {
// Assume all trees start in the HTML namespace (not totally true, but
// this is what we did historically)
domNamespace: Namespaces.html,
children: flatChildren,
childIndex: 0,
context: emptyObject,
footer: '',
};
if (__DEV__) {
((topFrame: any): FrameDev).debugElementStack = [];
}
this.stack = [topFrame];
this.exhausted = false;
this.currentSelectValue = null;
this.previousWasTextNode = false;
this.makeStaticMarkup = makeStaticMarkup;
}
read(bytes: number): string | null {
if (this.exhausted) {
return null;
}
var out = '';
while (out.length < bytes) {
if (this.stack.length === 0) {
this.exhausted = true;
break;
}
var frame: Frame = this.stack[this.stack.length - 1];
if (frame.childIndex >= frame.children.length) {
var footer = frame.footer;
out += footer;
if (footer !== '') {
this.previousWasTextNode = false;
}
this.stack.pop();
if (frame.tag === 'select') {
this.currentSelectValue = null;
}
continue;
}
var child = frame.children[frame.childIndex++];
if (__DEV__) {
setCurrentDebugStack(this.stack);
}
out += this.render(child, frame.context, frame.domNamespace);
if (__DEV__) {
// TODO: Handle reentrant server render calls. This doesn't.
resetCurrentDebugStack();
}
}
return out;
}
render(
child: ReactNode | null,
context: Object,
parentNamespace: string,
): string {
if (typeof child === 'string' || typeof child === 'number') {
var text = '' + child;
if (text === '') {
return '';
}
if (this.makeStaticMarkup) {
return escapeTextContentForBrowser(text);
}
if (this.previousWasTextNode) {
return '<!-- -->' + escapeTextContentForBrowser(text);
}
this.previousWasTextNode = true;
return escapeTextContentForBrowser(text);
} else {
var nextChild;
({child: nextChild, context} = resolve(child, context));
if (nextChild === null || nextChild === false) {
return '';
} else if (!React.isValidElement(nextChild)) {
const nextChildren = toArray(nextChild);
const frame: Frame = {
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
} else if (
((nextChild: any): ReactElement).type === REACT_FRAGMENT_TYPE
) {
const nextChildren = toArray(
((nextChild: any): ReactElement).props.children,
);
const frame: Frame = {
domNamespace: parentNamespace,
children: nextChildren,
childIndex: 0,
context: context,
footer: '',
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
return '';
} else {
// Safe because we just checked it's an element.
var nextElement = ((nextChild: any): ReactElement);
return this.renderDOM(nextElement, context, parentNamespace);
}
}
}
renderDOM(
element: ReactElement,
context: Object,
parentNamespace: string,
): string {
var tag = element.type.toLowerCase();
let namespace = parentNamespace;
if (parentNamespace === Namespaces.html) {
namespace = getIntrinsicNamespace(tag);
}
if (__DEV__) {
if (namespace === Namespaces.html) {
// Should this check be gated by parent namespace? Not sure we want to
// allow <SVG> or <mATH>.
warning(
tag === element.type,
'<%s /> is using uppercase HTML. Always use lowercase HTML tags ' +
'in React.',
element.type,
);
}
}
validateDangerousTag(tag);
var props = element.props;
if (tag === 'input') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'input',
props,
getStackAddendum,
);
if (
props.checked !== undefined &&
props.defaultChecked !== undefined &&
!didWarnDefaultChecked
) {
warning(
false,
'%s contains an input of type %s with both checked and defaultChecked props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the checked prop, or the defaultChecked prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
'A component',
props.type,
);
didWarnDefaultChecked = true;
}
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultInputValue
) {
warning(
false,
'%s contains an input of type %s with both value and defaultValue props. ' +
'Input elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled input ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
'A component',
props.type,
);
didWarnDefaultInputValue = true;
}
}
props = Object.assign(
{
type: undefined,
},
props,
{
defaultChecked: undefined,
defaultValue: undefined,
value: props.value != null ? props.value : props.defaultValue,
checked: props.checked != null ? props.checked : props.defaultChecked,
},
);
} else if (tag === 'textarea') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'textarea',
props,
getStackAddendum,
);
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultTextareaValue
) {
warning(
false,
'Textarea elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled textarea ' +
'and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
didWarnDefaultTextareaValue = true;
}
}
var initialValue = props.value;
if (initialValue == null) {
var defaultValue = props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var textareaChildren = props.children;
if (textareaChildren != null) {
if (__DEV__) {
warning(
false,
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.',
);
}
invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.',
);
if (Array.isArray(textareaChildren)) {
invariant(
textareaChildren.length <= 1,
'<textarea> can only have at most one child.',
);
textareaChildren = textareaChildren[0];
}
defaultValue = '' + textareaChildren;
}
if (defaultValue == null) {
defaultValue = '';
}
initialValue = defaultValue;
}
props = Object.assign({}, props, {
value: undefined,
children: '' + initialValue,
});
} else if (tag === 'select') {
if (__DEV__) {
ReactControlledValuePropTypes.checkPropTypes(
'select',
props,
getStackAddendum,
);
for (var i = 0; i < valuePropNames.length; i++) {
var propName = valuePropNames[i];
if (props[propName] == null) {
continue;
}
var isArray = Array.isArray(props[propName]);
if (props.multiple && !isArray) {
warning(
false,
'The `%s` prop supplied to <select> must be an array if ' +
'`multiple` is true.%s',
propName,
'', // getDeclarationErrorAddendum(),
);
} else if (!props.multiple && isArray) {
warning(
false,
'The `%s` prop supplied to <select> must be a scalar ' +
'value if `multiple` is false.%s',
propName,
'', // getDeclarationErrorAddendum(),
);
}
}
if (
props.value !== undefined &&
props.defaultValue !== undefined &&
!didWarnDefaultSelectValue
) {
warning(
false,
'Select elements must be either controlled or uncontrolled ' +
'(specify either the value prop, or the defaultValue prop, but not ' +
'both). Decide between using a controlled or uncontrolled select ' +
'element and remove one of these props. More info: ' +
'https://fb.me/react-controlled-components',
);
didWarnDefaultSelectValue = true;
}
}
this.currentSelectValue = props.value != null
? props.value
: props.defaultValue;
props = Object.assign({}, props, {
value: undefined,
});
} else if (tag === 'option') {
var selected = null;
var selectValue = this.currentSelectValue;
var optionChildren = flattenOptionChildren(props.children);
if (selectValue != null) {
var value;
if (props.value != null) {
value = props.value + '';
} else {
value = optionChildren;
}
selected = false;
if (Array.isArray(selectValue)) {
// multiple
for (var j = 0; j < selectValue.length; j++) {
if ('' + selectValue[j] === value) {
selected = true;
break;
}
}
} else {
selected = '' + selectValue === value;
}
props = Object.assign(
{
selected: undefined,
children: undefined,
},
props,
{
selected: selected,
children: optionChildren,
},
);
}
}
if (__DEV__) {
validatePropertiesInDevelopment(tag, props);
}
assertValidProps(tag, props, getStackAddendum);
var out = createOpenTagMarkup(
element.type,
tag,
props,
namespace,
this.makeStaticMarkup,
this.stack.length === 1,
);
var footer = '';
if (omittedCloseTags.hasOwnProperty(tag)) {
out += '/>';
} else {
out += '>';
footer = '</' + element.type + '>';
}
var children;
var innerMarkup = getNonChildrenInnerMarkup(props);
if (innerMarkup != null) {
children = [];
if (newlineEatingTags[tag] && innerMarkup.charAt(0) === '\n') {
// text/html ignores the first character in these tags if it's a newline
// Prefer to break application/xml over text/html (for now) by adding
// a newline specifically to get eaten by the parser. (Alternately for
// textareas, replacing "^\n" with "\r\n" doesn't get eaten, and the first
// \r is normalized out by HTMLTextAreaElement#value.)
// See: <http://www.w3.org/TR/html-polyglot/#newlines-in-textarea-and-pre>
// See: <http://www.w3.org/TR/html5/syntax.html#element-restrictions>
// See: <http://www.w3.org/TR/html5/syntax.html#newlines>
// See: Parsing of "textarea" "listing" and "pre" elements
// from <http://www.w3.org/TR/html5/syntax.html#parsing-main-inbody>
out += '\n';
}
out += innerMarkup;
} else {
children = toArray(props.children);
}
var frame = {
domNamespace: getChildNamespace(parentNamespace, element.type),
tag,
children,
childIndex: 0,
context: context,
footer: footer,
};
if (__DEV__) {
((frame: any): FrameDev).debugElementStack = [];
}
this.stack.push(frame);
this.previousWasTextNode = false;
return out;
}
}
export default ReactDOMServerRenderer;
|
src/decorators/withViewport.js | piscis/react-starter-kit | /*! 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', 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});
}
};
}
export default withViewport;
|
node_modules/semantic-ui-react/dist/es/collections/Form/FormGroup.js | mowbell/clickdelivery-fed-test | import _toConsumableArray from 'babel-runtime/helpers/toConsumableArray';
import _extends from 'babel-runtime/helpers/extends';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META, SUI, useKeyOnly, useWidthProp } from '../../lib';
/**
* A set of fields can appear grouped together.
* @see Form
*/
function FormGroup(props) {
var children = props.children,
className = props.className,
grouped = props.grouped,
inline = props.inline,
widths = props.widths;
var classes = cx(useKeyOnly(grouped, 'grouped'), useKeyOnly(inline, 'inline'), useWidthProp(widths, null, true), 'fields', className);
var rest = getUnhandledProps(FormGroup, props);
var ElementType = getElementType(FormGroup, props);
return React.createElement(
ElementType,
_extends({}, rest, { className: classes }),
children
);
}
FormGroup.handledProps = ['as', 'children', 'className', 'grouped', 'inline', 'widths'];
FormGroup._meta = {
name: 'FormGroup',
parent: 'Form',
type: META.TYPES.COLLECTION
};
process.env.NODE_ENV !== "production" ? FormGroup.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Fields can show related choices. */
grouped: customPropTypes.every([customPropTypes.disallow(['inline']), PropTypes.bool]),
/** Multiple fields may be inline in a row. */
inline: customPropTypes.every([customPropTypes.disallow(['grouped']), PropTypes.bool]),
/** Fields Groups can specify their width in grid columns or automatically divide fields to be equal width. */
widths: PropTypes.oneOf([].concat(_toConsumableArray(SUI.WIDTHS), ['equal']))
} : void 0;
export default FormGroup; |
assets/jqwidgets/demos/react/app/grid/everpresentrowwithcustomwidgets/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js';
import JqxDateTimeInput from '../../../jqwidgets-react/react_jqxdatetimeinput.js';
import JqxDropDownList from '../../../jqwidgets-react/react_jqxdropdownlist.js';
import JqxInput from '../../../jqwidgets-react/react_jqxinput.js';
import JqxNumberInput from '../../../jqwidgets-react/react_jqxnumberinput.js';
import JqxRadioButton from '../../../jqwidgets-react/react_jqxradiobutton.js';
class App extends React.Component {
componentDidMount() {
this.refs.top.on('checked', () => {
this.refs.myGrid.everpresentrowactions('add reset');
});
this.refs.bottom.on('checked', () => {
this.refs.myGrid.everpresentrowactions('addBottom reset');
});
}
render() {
let source =
{
localdata: generatedata(10),
datafields:
[
{ name: 'name', type: 'string' },
{ name: 'productname', type: 'string' },
{ name: 'available', type: 'bool' },
{ name: 'date', type: 'date' },
{ name: 'quantity', type: 'number' }
],
datatype: 'array'
};
let dataAdapter = new $.jqx.dataAdapter(source);
let getSourceAdapter = (name) => {
let source =
{
localdata: generatedata(10),
datafields:
[
{ name: 'name', type: 'string' },
{ name: 'productname', type: 'string' }
],
datatype: 'array'
};
let fields = new Array();
fields.push(name);
let dataAdapter = new $.jqx.dataAdapter(source, { autoBind: true, autoSort: true, uniqueDataFields: fields, autoSortField: name });
return dataAdapter.records;
}
let input, dropDownList, DateTimeInput, NumberInput;
let columns =
[
{
text: 'Name', columntype: 'textbox', filtertype: 'input', datafield: 'name', width: 215,
createEverPresentRowWidget: (datafield, htmlElement, popup, addCallback) => {
let container = document.createElement('div');
htmlElement[0].appendChild(container);
input = ReactDOM.render(
<JqxInput style={{ border: 'none' }}
width={'100%'} height={30} source={getSourceAdapter('name')}
popupZIndex={999999} placeHolder={'Enter Name: '} displayMember={'name'}
/>, container);
return container;
},
initEverPresentRowWidget: (datafield, htmlElement) => {
},
getEverPresentRowWidgetValue: (datafield, htmlElement, validate) => {
let value = input.val();
return value;
},
resetEverPresentRowWidgetValue: (datafield, htmlElement) => {
input.val('');
}
},
{
text: 'Product', filtertype: 'checkedlist', datafield: 'productname', width: 220,
createEverPresentRowWidget: (datafield, htmlElement, popup, addCallback) => {
let container = document.createElement('div');
htmlElement[0].appendChild(container);
dropDownList = ReactDOM.render(
<JqxDropDownList style={{ border: 'none' }}
width={'100%'} height={30} source={getSourceAdapter('productname')}
popupZIndex={999999} placeHolder={'Enter Product: '} displayMember={'productname'}
/>, container);
return container;
},
getEverPresentRowWidgetValue: (datafield, htmlElement, validate) => {
let selectedItem = dropDownList.getSelectedItem();
if (!selectedItem)
return '';
let value = selectedItem.label;
return value;
},
resetEverPresentRowWidgetValue: (datafield, htmlElement) => {
dropDownList.clearSelection();
}
},
{
text: 'Ship Date', datafield: 'date', filtertype: 'range', width: 210, cellsalign: 'right', cellsformat: 'd',
createEverPresentRowWidget: (datafield, htmlElement, popup, addCallback) => {
let container = document.createElement('div');
htmlElement[0].appendChild(container);
DateTimeInput = ReactDOM.render(
<JqxDateTimeInput style={{ border: 'none' }}
width={'100%'} height={30} value={null}
popupZIndex={999999} placeHolder={'Enter Date: '}
/>, container);
return container;
},
initEverPresentRowWidget: (datafield, htmlElement) => {
},
getEverPresentRowWidgetValue: (datafield, htmlElement, validate) => {
let value = DateTimeInput.val();
return value;
},
resetEverPresentRowWidgetValue: (datafield, htmlElement) => {
DateTimeInput.val(null);
}
},
{
text: 'Qty.', datafield: 'quantity', filtertype: 'number', cellsalign: 'right',
createEverPresentRowWidget: (datafield, htmlElement, popup, addCallback) => {
let container = document.createElement('div');
htmlElement[0].appendChild(container);
NumberInput = ReactDOM.render(
<JqxNumberInput style={{ border: 'none' }}
width={'100%'} height={30} decimalDigits={0} inputMode={'simple'}
/>, container);
return container;
},
initEverPresentRowWidget: (datafield, htmlElement) => {
},
getEverPresentRowWidgetValue: (datafield, htmlElement, validate) => {
let value = NumberInput.val();
if (value == '') value = 0;
return parseInt(value);
},
resetEverPresentRowWidgetValue: (datafield, htmlElement) => {
NumberInput.val('');
}
},
{ text: '', datafield: 'addButtonColumn', width: 50 },
{ text: '', datafield: 'resetButtonColumn', width: 50 }
];
return (
<div>
<JqxGrid ref='myGrid'
width={850} source={dataAdapter} filterable={true}
showeverpresentrow={true} everpresentrowposition={'top'}
editable={true} columns={columns} everpresentrowactionsmode={'columns'}
selectionmode={'multiplecellsadvanced'}
/>
<br />
<JqxRadioButton ref='top' checked={true}>Add New Row to Top</JqxRadioButton>
<JqxRadioButton ref='bottom'>Add New Row to Bottom</JqxRadioButton>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/buttons/Button.js | edu-affiliates/promo_calculators | 'use strict';
import React from 'react';
import {connect} from 'react-redux'
import generalOptions from '../../config/generalOptions'
class Button extends React.Component {
constructor(props) {
super(props);
}
redirectTo() {
const {type, service, serviceId, levelId, deadlineId, serviceName} = this.props;
let srvcId;
if (this.props.service !== undefined) {
for (const i in this.props.serviceName) {
if (this.props.serviceName[i].name.toLowerCase() == this.props.service.toLowerCase()) {
srvcId = this.props.serviceName[i].id;
}
}
}
let redirectTo = generalOptions.siteMyUrl
+ `/${type}?cli=` + levelId
+ '&cdi=' + deadlineId
+ '&ccu=' + 1;
if (generalOptions.rid) {
redirectTo += `&rid=${generalOptions.rid}`
}
if (generalOptions.dsc) {
redirectTo += `&dsc=${generalOptions.dsc}`
}
if (this.props.service === undefined || this.props.service == '') {
redirectTo += `&csi=${serviceId}`
} else {
redirectTo += `&csi=${srvcId}`
}
if (type != 'dashboard') {
location.href = redirectTo;
} else {
location.href = generalOptions.siteMyUrl + `/${type}`;
}
}
render() {
return (
<div onClick={() => this.redirectTo()} className={this.props.class}>{this.props.name}</div>
)
}
}
//container to match redux state to component props and dispatch redux actions to callback props
const mapStateToProps = state => {
return {
serviceId: state.serviceId,
levelId: state.levelId,
deadlineId: state.deadlineId,
serviceName: state.allServices
}
};
const mapDispatchToProps = dispatch => {
return {}
};
export default connect(mapStateToProps, mapDispatchToProps)(Button); |
app/javascript/mastodon/components/poll.js | im-in-space/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import Motion from 'mastodon/features/ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import escapeTextContentForBrowser from 'escape-html';
import emojify from 'mastodon/features/emoji/emoji';
import RelativeTimestamp from './relative_timestamp';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
closed: {
id: 'poll.closed',
defaultMessage: 'Closed',
},
voted: {
id: 'poll.voted',
defaultMessage: 'You voted for this answer',
},
votes: {
id: 'poll.votes',
defaultMessage: '{votes, plural, one {# vote} other {# votes}}',
},
});
const makeEmojiMap = record => record.get('emojis').reduce((obj, emoji) => {
obj[`:${emoji.get('shortcode')}:`] = emoji.toJS();
return obj;
}, {});
export default @injectIntl
class Poll extends ImmutablePureComponent {
static propTypes = {
poll: ImmutablePropTypes.map,
intl: PropTypes.object.isRequired,
disabled: PropTypes.bool,
refresh: PropTypes.func,
onVote: PropTypes.func,
};
state = {
selected: {},
expired: null,
};
static getDerivedStateFromProps (props, state) {
const { poll, intl } = props;
const expires_at = poll.get('expires_at');
const expired = poll.get('expired') || expires_at !== null && (new Date(expires_at)).getTime() < intl.now();
return (expired === state.expired) ? null : { expired };
}
componentDidMount () {
this._setupTimer();
}
componentDidUpdate () {
this._setupTimer();
}
componentWillUnmount () {
clearTimeout(this._timer);
}
_setupTimer () {
const { poll, intl } = this.props;
clearTimeout(this._timer);
if (!this.state.expired) {
const delay = (new Date(poll.get('expires_at'))).getTime() - intl.now();
this._timer = setTimeout(() => {
this.setState({ expired: true });
}, delay);
}
}
_toggleOption = value => {
if (this.props.poll.get('multiple')) {
const tmp = { ...this.state.selected };
if (tmp[value]) {
delete tmp[value];
} else {
tmp[value] = true;
}
this.setState({ selected: tmp });
} else {
const tmp = {};
tmp[value] = true;
this.setState({ selected: tmp });
}
}
handleOptionChange = ({ target: { value } }) => {
this._toggleOption(value);
};
handleOptionKeyPress = (e) => {
if (e.key === 'Enter' || e.key === ' ') {
this._toggleOption(e.target.getAttribute('data-index'));
e.stopPropagation();
e.preventDefault();
}
}
handleVote = () => {
if (this.props.disabled) {
return;
}
this.props.onVote(Object.keys(this.state.selected));
};
handleRefresh = () => {
if (this.props.disabled) {
return;
}
this.props.refresh();
};
renderOption (option, optionIndex, showResults) {
const { poll, disabled, intl } = this.props;
const pollVotesCount = poll.get('voters_count') || poll.get('votes_count');
const percent = pollVotesCount === 0 ? 0 : (option.get('votes_count') / pollVotesCount) * 100;
const leading = poll.get('options').filterNot(other => other.get('title') === option.get('title')).every(other => option.get('votes_count') >= other.get('votes_count'));
const active = !!this.state.selected[`${optionIndex}`];
const voted = option.get('voted') || (poll.get('own_votes') && poll.get('own_votes').includes(optionIndex));
let titleEmojified = option.get('title_emojified');
if (!titleEmojified) {
const emojiMap = makeEmojiMap(poll);
titleEmojified = emojify(escapeTextContentForBrowser(option.get('title')), emojiMap);
}
return (
<li key={option.get('title')}>
<label className={classNames('poll__option', { selectable: !showResults })}>
<input
name='vote-options'
type={poll.get('multiple') ? 'checkbox' : 'radio'}
value={optionIndex}
checked={active}
onChange={this.handleOptionChange}
disabled={disabled}
/>
{!showResults && (
<span
className={classNames('poll__input', { checkbox: poll.get('multiple'), active })}
tabIndex='0'
role={poll.get('multiple') ? 'checkbox' : 'radio'}
onKeyPress={this.handleOptionKeyPress}
aria-checked={active}
aria-label={option.get('title')}
data-index={optionIndex}
/>
)}
{showResults && (
<span
className='poll__number'
title={intl.formatMessage(messages.votes, {
votes: option.get('votes_count'),
})}
>
{Math.round(percent)}%
</span>
)}
<span
className='poll__option__text translate'
dangerouslySetInnerHTML={{ __html: titleEmojified }}
/>
{!!voted && <span className='poll__voted'>
<Icon id='check' className='poll__voted__mark' title={intl.formatMessage(messages.voted)} />
</span>}
</label>
{showResults && (
<Motion defaultStyle={{ width: 0 }} style={{ width: spring(percent, { stiffness: 180, damping: 12 }) }}>
{({ width }) =>
<span className={classNames('poll__chart', { leading })} style={{ width: `${width}%` }} />
}
</Motion>
)}
</li>
);
}
render () {
const { poll, intl } = this.props;
const { expired } = this.state;
if (!poll) {
return null;
}
const timeRemaining = expired ? intl.formatMessage(messages.closed) : <RelativeTimestamp timestamp={poll.get('expires_at')} futureDate />;
const showResults = poll.get('voted') || expired;
const disabled = this.props.disabled || Object.entries(this.state.selected).every(item => !item);
let votesCount = null;
if (poll.get('voters_count') !== null && poll.get('voters_count') !== undefined) {
votesCount = <FormattedMessage id='poll.total_people' defaultMessage='{count, plural, one {# person} other {# people}}' values={{ count: poll.get('voters_count') }} />;
} else {
votesCount = <FormattedMessage id='poll.total_votes' defaultMessage='{count, plural, one {# vote} other {# votes}}' values={{ count: poll.get('votes_count') }} />;
}
return (
<div className='poll'>
<ul>
{poll.get('options').map((option, i) => this.renderOption(option, i, showResults))}
</ul>
<div className='poll__footer'>
{!showResults && <button className='button button-secondary' disabled={disabled} onClick={this.handleVote}><FormattedMessage id='poll.vote' defaultMessage='Vote' /></button>}
{showResults && !this.props.disabled && <span><button className='poll__link' onClick={this.handleRefresh}><FormattedMessage id='poll.refresh' defaultMessage='Refresh' /></button> · </span>}
{votesCount}
{poll.get('expires_at') && <span> · {timeRemaining}</span>}
</div>
</div>
);
}
}
|
test/integration/image-component/default/pages/layout-fill.js | azukaru/next.js | import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<p>Layout Fill</p>
<div style={{ position: 'relative', width: '600px', height: '350px' }}>
<Image id="fill1" src="/wide.png" layout="fill" />
</div>
<p>Layout Fill</p>
<div style={{ position: 'relative', width: '100vw', height: '100vh' }}>
<Image
id="fill2"
src="/wide.png"
layout="fill"
objectFit="cover"
objectPosition="left center"
/>
</div>
<p>Layout Fill</p>
<div style={{ position: 'relative', width: '50vw', height: '50vh' }}>
<Image
id="fill3"
src="/wide.png"
layout="fill"
objectFit="cover"
objectPosition="left center"
sizes="(min-width: 1200px) 90vw,
(min-width: 800px) 30vw,
100vw"
/>
</div>
<p>Layout Fill</p>
<div style={{ position: 'relative', width: '50vw', height: '50vh' }}>
<Image
id="fill4"
src="/wide.png"
layout="fill"
objectFit="cover"
objectPosition="left center"
sizes="500px"
/>
</div>
</div>
)
}
export default Page
|
modules/frontend/src/js/components/containers/Application.js | fleximaps/fleximaps | import styles from './Application.css';
import Header from '../widgets/Header';
import CSSModules from 'react-css-modules';
import React from 'react';
export default CSSModules(class Application extends React.Component {
render() {
return (
<div styleName='application'>
<Header/>
{this.props.children}
</div>
);
}
}, styles); |
frontend/component/Footer.js | ghkk/node_dataguru | import React from 'react';
const footerStyle = {
marginTop: 50,
padding: 20,
};
export default class Footer extends React.Component {
render() {
return (
<div className="text-center" style={footerStyle}>
© CopyRight Node.js hank guo
</div>
);
}
} |
src/Splicer.js | chenzihui/react-splicer | 'use strict';
import React from 'react';
import SplicerList from './SplicerList';
const KEYS = {
ENTER: 13,
ESC: 27,
DOWN: 40,
UP: 38
};
class Splicer extends React.Component {
constructor(props) {
super(props);
this.state = { selectables: [], selectedIndex: 0 };
this._insertSelected = this._insertSelected.bind(this);
this._handleEnterKey = this._handleEnterKey.bind(this);
this._resetState = this._resetState.bind(this);
this._handleKeyDown = this._handleKeyDown.bind(this);
this._handleKeyUp = this._handleKeyUp.bind(this);
}
render() {
return (
<div className="splicer">
<div
ref="userInput"
className="splicer__user-input"
contentEditable="true"
onKeyDown={this._handleKeyDown}
onKeyUp={this._handleKeyUp}></div>
<SplicerList
selectedIdx={this.state.selectedIndex}
data={this.state.selectables}
insertFn={this._insertSelected} />
</div>
);
}
_handleKeyDown(evt) {
if (evt.which === KEYS.ENTER) {
evt.preventDefault();
}
if (evt.which === KEYS.DOWN || evt.which === KEYS.UP) {
if (this.state.selectables.length !== 0) {
evt.preventDefault();
}
}
}
_handleKeyUp(evt) {
if (evt.which === KEYS.ENTER) {
return this._handleEnterKey(evt);
}
if (evt.which === KEYS.ESC) {
return this._resetState();
}
if (evt.which === KEYS.UP || evt.which === KEYS.DOWN) {
return this._setSelectedItem(evt.which);
}
this._setSearchTerm();
}
_handleEnterKey(evt) {
if (this.state.selectables.length > 0) {
return this._insertSelected(
this.state.selectables[this.state.selectedIndex]);
} else {
return this._fireCallback(evt.target.textContent);
}
}
_fireCallback(textContent) {
if (textContent.trim()) {
return this.props.callback(textContent);
}
}
_setSelectedItem(keyCode) {
let selectedIdx;
if (keyCode === KEYS.UP) {
selectedIdx = this.state.selectedIndex === 0
? this.state.selectables.length - 1
: this.state.selectedIndex - 1;
} else if (keyCode === KEYS.DOWN) {
selectedIdx = this.state.selectedIndex === this.state.selectables.length - 1
? 0
: this.state.selectedIndex + 1;
}
this.setState({ selectedIndex: selectedIdx });
}
_setSearchTerm() {
let selection = window.getSelection(),
range = selection.getRangeAt(0),
userInput = React.findDOMNode(this.refs.userInput),
content, searchTerm, selectables;
range.collapse(true);
range.setStart(userInput, 0);
content = range.toString().split(' ');
searchTerm = content[content.length - 1];
if (searchTerm.length >= this.props.charCount) {
selectables = this.props.data.filter((item) => {
return item.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1;
});
this.setState({ selectables: selectables });
} else {
this.setState({ selectables: [] });
}
}
_insertSelected(data) {
let result = this.props.transformFn(data),
sel = window.getSelection(),
range = sel.getRangeAt(0),
input = React.findDOMNode(this.refs.userInput),
nodes, startNode, words, lastWord, wordStart, wordEnd, el, space;
input.normalize();
range.collapse(true);
range.setStart(input, 0);
nodes = Array.prototype.filter.call(input.childNodes, (node) => {
return node.nodeType === 3;
});
nodes = nodes.reverse();
Array.prototype.forEach.call(nodes, (node) => {
if (node.nodeValue.trim()) {
startNode = node;
}
});
words = range.toString().split(' ');
lastWord = words[words.length - 1];
wordStart = range.toString().lastIndexOf(lastWord);
wordEnd = wordStart + lastWord.length;
range.setStart(startNode, wordStart);
range.setEnd(startNode, wordEnd);
range.deleteContents();
if (typeof(result) === 'string') {
el = document.createTextNode(result);
} else {
el = result;
}
range.insertNode(el);
range.setStartAfter(el);
space = document.createTextNode('\u00a0');
range.insertNode(space);
range.setStartAfter(space);
range.collapse(false);
sel.removeAllRanges();
sel.addRange(range);
this._resetState();
}
_resetState() {
this.setState({ selectables: [], selectedIndex: 0 });
}
};
export default Splicer;
|
packages/ringcentral-widgets-docs/src/app/pages/Components/CallCtrlPanel/Demo.js | u9520107/ringcentral-js-widget | import React from 'react';
// eslint-disable-next-line
import CallCtrlPanel from 'ringcentral-widgets/components/CallCtrlPanel';
const props = {};
props.nameMatches = [];
props.fallBackName = 'test string';
props.currentLocale = 'en-US';
props.recordStatus = 'test string';
props.onMute = () => null;
props.onUnmute = () => null;
props.onHold = () => null;
props.onUnhold = () => null;
props.onRecord = () => null;
props.onStopRecord = () => null;
props.onAdd = () => null;
props.onHangup = () => null;
props.onFlip = () => null;
props.onPark = () => null;
props.onTransfer = () => null;
props.onBackButtonClick = () => null;
props.onKeyPadChange = () => null;
props.formatPhone = () => null;
props.areaCode = '650';
props.countryCode = 'US';
props.selectedMatcherIndex = 0;
props.onSelectMatcherName = () => null;
props.calls = [{}, {}];
props.searchContactList = [];
props.searchContact = () => null;
/**
* A example of `CallCtrlPanel`
*/
const CallCtrlPanelDemo = () => (
<div style={{
position: 'relative',
height: '500px',
width: '300px',
border: '1px solid #f3f3f3',
}}>
<CallCtrlPanel
{...props}
/>
</div>
);
export default CallCtrlPanelDemo;
|
src/store.js | batazor/labelMap | import React from 'react'
import { createStore, combineReducers, compose, applyMiddleware } from 'redux'
import * as reducers from './reducers'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
import { routerReducer, routerMiddleware } from 'react-router-redux'
export const DevTools = createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q">
<LogMonitor theme="tomorrow" preserveScrollTop={false} />
</DockMonitor>
)
export function configureStore(history, initialState) {
const reducer = combineReducers({
...reducers,
routing: routerReducer
})
let devTools = []
if (typeof document !== 'undefined') {
devTools = [ DevTools.instrument() ]
}
const store = createStore(
reducer,
initialState,
compose(
applyMiddleware(
routerMiddleware(history)
),
...devTools
)
)
return store
}
|
example/WithSize.js | wuct/react-dom-utils | import React from 'react'
import throttle from 'raf-throttle'
import withSize from '../src/withSize'
const style = {
width: '100%',
height: 100,
backgroundColor: '#7E94C7',
}
const component = ({ DOMSize }) =>
(<div style={style}>
<span>
{JSON.stringify(DOMSize)}
</span>
</div>)
export default withSize(throttle)(component)
|
app/ListScene.js | dalmago/thatThing |
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
ScrollView,
ActivityIndicator,
Alert,
TouchableOpacity,
} from 'react-native'
import Icon from 'react-native-vector-icons/FontAwesome';
export class ListScene extends Component {
constructor(props){
super(props);
this.state = {loading: true, thingsList: []};
this.getThingsList();
}
render() {
var thingGroup = this.state.thingsList.map((thingCat, i) => {
var things = thingCat.map((thing, j) => {
return (
<View key={j}>
<TouchableOpacity
onPress={() => {
this.props.navigator.push({sceneIndex: 4, thing: thing, sessionId: this.props.route.sessionId});
}}
activeOpacity={75 / 100}>
<Text style={styles.content}>{thing.name}</Text>
</TouchableOpacity>
<Text style={{fontSize: 5}}>{'\n'}</Text>
</View>
);}, this);
return (
<View key={i}>
<Text style={styles.titles}>{ thingCat[0].defName }</Text>
<Text style={{fontSize: 5}}>{'\n'}</Text>
{ things }
</View>
);}, this);
var blankSpace = <Text style={{fontSize: 5}}>{'\n'}</Text>;
return (
<View
style={{
flex: 1,
justifyContent: "flex-start",
alignItems: "stretch",
backgroundColor: "rgba(35,109,197,1)",
}}>
{<Text>{''}</Text>}
<View
style={{
flex: 1,
flexDirection: 'row',
}}>
<View
style={{
flex: 1,
justifyContent: "space-around",
alignItems: "center",
}}>
<Text
style={{
color: 'black',
fontSize: 20,
fontWeight: "bold",
textAlign: 'center',
}}>
{(this.props.route.portal === 'dw')?
'Device Wise' : ''
}
</Text>
</View>
<View
style={{
flex: 1,
justifyContent: "space-around",
alignItems: "center",
}}>
<Image
style={{
width: 90,
height: 90,
}}
resizeMode={"contain"}
source={require('./static/img/devicewise.png')}
/>
</View>
<View
style={{
flex: 1,
justifyContent: "center",
alignItems: "center",
}}>
<Icon.Button name="refresh" size={50} color="rgba(40,40,40,1)" backgroundColor="rgba(35,109,197,1)" onPress={() => {
this.setState({loading: true});
this.getThingsList();
}}/>
</View>
</View>
<View
style={{
flex: 10,
justifyContent: "center",
alignItems: "center",
backgroundColor: "rgb(74,144,226)",
}}>
{(this.state.loading)?
<ActivityIndicator
animating={this.state.loading}
size={'large'}
color={'black'}
/> :
<ScrollView
horizontal={false}>
{blankSpace}
<View
style={{
flex: 1,
alignItems: "center",
}}>
<Icon.Button name="search" size={50} color="rgba(42,42,42,1)" backgroundColor="rgb(74,144,226)"
onPress={() => {this.props.navigator.push({sceneIndex: 3, thingsList: this.state.thingsList, sessionId: this.props.route.sessionId})}}
/>
<Icon.Button name="map" size={50} color="rgba(42,42,42,1)" backgroundColor="rgb(74,144,226)"
onPress={() => {this.props.navigator.push({sceneIndex: 2, thingsList: this.state.thingsList})}} />
</View>
{blankSpace}
{ thingGroup }
</ScrollView>}
</View>
</View>
);
}
getThingsList(){
switch(this.props.route.portal){
case 'dw':
this.getThingsDW();
break;
default:
Alert.alert('Portal ainda não implementado');
this.setState({loading: false});
}
}
getThingsDW(){
var server = "https://api.devicewise.com/api";
var sessionId = this.props.route.sessionId;
var js = {
"auth":{"sessionId": sessionId},
"1": {
"command": "thing.list",
"params" : {
"limit": 10,
"sort": "+defName"
}
}
}
fetch(server, {
method: 'POST',
body: JSON.stringify(js)
}).then((res) => res.json()).then((res) => {
if (__DEV__ === true)
console.log('getThingsList: ', res);
if (res[1].success === true){
this.updateThingsList(res[1].params.result);
} else{
Alert.alert('Erro obtendo dados', 'Tente fazer login novamente');
}
this.setState({loading: false});
}).catch((err) => {
if (__DEV__ === true)
console.log('getThingsList err:', err);
Alert.alert('Erro obtendo dados', 'Você está conectado?');
});
}
updateThingsList(list){
var lastDefName = list[0].defName;
var defGroup = []
var thingsList = []
for (i=0; i<list.length; i++){
if (list[i].defName == lastDefName){
defGroup = defGroup.concat(list[i]);
} else{
thingsList = thingsList.concat([defGroup]);
defGroup = [list[i]];
lastDefName = list[i].defName;
}
}
thingsList = thingsList.concat([defGroup]);
this.setState({thingsList: thingsList});
}
}
const styles = StyleSheet.create({
titles: {
color: 'black',
fontSize: 24,
fontWeight: "bold",
textAlign: "center",
},
content: {
color: 'black',
fontSize: 20,
fontWeight: "normal",
textAlign: "center",
},
});
|
docs/src/IntroductionPage.js | RichardLitt/react-bootstrap | import React from 'react';
import CodeExample from './CodeExample';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
const IntroductionPage = React.createClass({
render() {
return (
<div>
<NavMain activePage="introduction" />
<PageHeader
title="Introduction"
subTitle="The most popular front-end framework, rebuilt for React."/>
<div className="container bs-docs-container">
<div className="row">
<div className="col-md-9" role="main">
<div className="bs-docs-section">
<p className="lead">
React-Bootstrap is a library of reuseable front-end components.
You'll get the look-and-feel of Twitter Bootstrap,
but with much cleaner code, via Facebook's React.js framework.
</p>
<p>
Let's say you want a small button that says "Something",
to trigger the function someCallback.
If you were writing a native application,
you might write something like:
</p>
<div className="highlight">
<CodeExample
mode="javascript"
codeText={
`button(size=SMALL, color=GREEN, text="Something", onClick=someCallback)`
}
/>
</div>
<p>
With the most popular web front-end framework,
Twitter Bootstrap, you'd write this in your HTML:
</p>
<div className="highlight">
<CodeExample
mode="htmlmixed"
codeText={
`<button id="something-btn" type="button" class="btn btn-success btn-sm">
Something
</button>`
}
/>
</div>
<p>
And something like
<code className="js">
$('#something-btn').click(someCallback);
</code>
in your Javascript.
</p>
<p>
By web standards this is quite nice,
but it's still quite nasty.
React-Bootstrap lets you write this:
</p>
<div className="highlight">
<CodeExample
mode="javascript"
codeText={
`<Button bsStyle="success" bsSize="small" onClick={someCallback}>
Something
</Button>`
}
/>
</div>
<p>
The HTML/CSS implementation details are abstracted away,
leaving you with an interface that more closely resembles
what you would expect to write in other programming languages.
</p>
<h2>A better Bootstrap API using React.js</h2>
<p>
The Bootstrap code is so repetitive because HTML and CSS
do not support the abstractions necessary for a nice library
of components. That's why we have to write <code>btn</code>
three times, within an element called <code>button</code>.
</p>
<p>
<strong>
The React.js solution is to write directly in Javascript.
</strong> React takes over the page-rendering entirely.
You just give it a tree of Javascript objects,
and tell it how state is transmitted between them.
</p>
<p>
For instance, we might tell React to render a page displaying
a single button, styled using the handy Bootstrap CSS:
</p>
<div className="highlight">
<CodeExample
mode="javascript"
codeText={
`var button = React.DOM.button({
className: "btn btn-lg btn-success",
children: "Register"
});
React.render(button, mountNode);`
}
/>
</div>
<p>
But now that we're in Javascript, we can wrap the HTML/CSS,
and provide a much better API:
</p>
<div className="highlight">
<CodeExample
mode="javascript"
codeText={
`var button = ReactBootstrap.Button({
bsStyle: "success",
bsSize: "large",
children: "Register"
});
React.render(button, mountNode);`
}
/>
</div>
<p>
React-Bootstrap is a library of such components,
which you can also easily extend and enhance
with your own functionality.
</p>
<h3>JSX Syntax</h3>
<p>
While each React component is really just a Javascript object,
writing tree-structures that way gets tedious.
React encourages the use of a syntactic-sugar called JSX,
which lets you write the tree in an HTML-like syntax:
</p>
<div className="highlight">
<CodeExample
mode="javascript"
codeText={
`var buttonGroupInstance = (
<ButtonGroup>
<DropdownButton bsStyle="success" title="Dropdown">
<MenuItem key="1">Dropdown link</MenuItem>
<MenuItem key="2">Dropdown link</MenuItem>
</DropdownButton>
<Button bsStyle="info">Middle</Button>
<Button bsStyle="info">Right</Button>
</ButtonGroup>
);
React.render(buttonGroupInstance, mountNode);`
}
/>
</div>
<p>
Some people's first impression of React.js is that it seems
messy to mix Javascript and HTML in this way.
However, compare the code required to add
a dropdown button in the example above to the <a
href="http://getbootstrap.com/javascript/#dropdowns">
Bootstrap Javascript</a> and <a
href="http://getbootstrap.com/components/#btn-dropdowns">
Components</a> documentation for creating a dropdown button.
The documentation is split in two because
you have to implement the component in two places
in your code: first you must add the HTML/CSS elements,
and then you must call some Javascript setup
code to wire the component together.
</p>
<p>
The React-Bootstrap component library tries to follow
the React.js philosophy that a single piece of functionality
should be defined in a single place.
View the current React-Bootstrap library on the <a
href="/components.html">components page</a>.
</p>
</div>
</div>
</div>
</div>
<PageFooter />
</div>
);
}
});
export default IntroductionPage;
|
packages/netlify-cms-editor-component-image/src/index.js | netlify/netlify-cms | import React from 'react';
const image = {
label: 'Image',
id: 'image',
fromBlock: match =>
match && {
image: match[2],
alt: match[1],
title: match[4],
},
toBlock: ({ alt, image, title }) =>
`}"` : ''})`,
// eslint-disable-next-line react/display-name
toPreview: ({ alt, image, title }, getAsset, fields) => {
const imageField = fields?.find(f => f.get('widget') === 'image');
const src = getAsset(image, imageField);
return <img src={src || ''} alt={alt || ''} title={title || ''} />;
},
pattern: /^!\[(.*)\]\((.*?)(\s"(.*)")?\)$/,
fields: [
{
label: 'Image',
name: 'image',
widget: 'image',
media_library: {
allow_multiple: false,
},
},
{
label: 'Alt Text',
name: 'alt',
},
{
label: 'Title',
name: 'title',
},
],
};
export const NetlifyCmsEditorComponentImage = image;
export default image;
|
app/javascript/mastodon/components/dropdown_menu.js | anon5r/mastonon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import IconButton from './icon_button';
import Overlay from 'react-overlays/lib/Overlay';
import Motion from '../features/ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import detectPassiveEvents from 'detect-passive-events';
const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false;
let id = 0;
class DropdownMenu extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
items: PropTypes.array.isRequired,
onClose: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
};
static defaultProps = {
style: {},
placement: 'bottom',
};
state = {
mounted: false,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
if (this.focusedItem) this.focusedItem.focus();
this.setState({ mounted: true });
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
setFocusRef = c => {
this.focusedItem = c;
}
handleKeyDown = e => {
const items = Array.from(this.node.getElementsByTagName('a'));
const index = items.indexOf(e.currentTarget);
let element;
switch(e.key) {
case 'Enter':
this.handleClick(e);
break;
case 'ArrowDown':
element = items[index+1];
if (element) {
element.focus();
}
break;
case 'ArrowUp':
element = items[index-1];
if (element) {
element.focus();
}
break;
case 'Home':
element = items[0];
if (element) {
element.focus();
}
break;
case 'End':
element = items[items.length-1];
if (element) {
element.focus();
}
break;
}
}
handleClick = e => {
const i = Number(e.currentTarget.getAttribute('data-index'));
const { action, to } = this.props.items[i];
this.props.onClose();
if (typeof action === 'function') {
e.preventDefault();
action(e);
} else if (to) {
e.preventDefault();
this.context.router.history.push(to);
}
}
renderItem (option, i) {
if (option === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { text, href = '#' } = option;
return (
<li className='dropdown-menu__item' key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyDown={this.handleKeyDown} data-index={i}>
{text}
</a>
</li>
);
}
render () {
const { items, style, placement, arrowOffsetLeft, arrowOffsetTop } = this.props;
const { mounted } = this.state;
return (
<Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
{({ opacity, scaleX, scaleY }) => (
// It should not be transformed when mounting because the resulting
// size will be used to determine the coordinate of the menu by
// react-overlays
<div className='dropdown-menu' style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}>
<div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} />
<ul>
{items.map((option, i) => this.renderItem(option, i))}
</ul>
</div>
)}
</Motion>
);
}
}
export default class Dropdown extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
icon: PropTypes.string.isRequired,
items: PropTypes.array.isRequired,
size: PropTypes.number.isRequired,
title: PropTypes.string,
disabled: PropTypes.bool,
status: ImmutablePropTypes.map,
isUserTouching: PropTypes.func,
isModalOpen: PropTypes.bool.isRequired,
onOpen: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
dropdownPlacement: PropTypes.string,
openDropdownId: PropTypes.number,
};
static defaultProps = {
title: 'Menu',
};
state = {
id: id++,
};
handleClick = ({ target }) => {
if (this.state.id === this.props.openDropdownId) {
this.handleClose();
} else {
const { top } = target.getBoundingClientRect();
const placement = top * 2 < innerHeight ? 'bottom' : 'top';
this.props.onOpen(this.state.id, this.handleItemClick, placement);
}
}
handleClose = () => {
this.props.onClose(this.state.id);
}
handleKeyDown = e => {
switch(e.key) {
case 'Escape':
this.handleClose();
break;
}
}
handleItemClick = e => {
const i = Number(e.currentTarget.getAttribute('data-index'));
const { action, to } = this.props.items[i];
this.handleClose();
if (typeof action === 'function') {
e.preventDefault();
action();
} else if (to) {
e.preventDefault();
this.context.router.history.push(to);
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
render () {
const { icon, items, size, title, disabled, dropdownPlacement, openDropdownId } = this.props;
const open = this.state.id === openDropdownId;
return (
<div onKeyDown={this.handleKeyDown}>
<IconButton
icon={icon}
title={title}
active={open}
disabled={disabled}
size={size}
ref={this.setTargetRef}
onClick={this.handleClick}
/>
<Overlay show={open} placement={dropdownPlacement} target={this.findTarget}>
<DropdownMenu items={items} onClose={this.handleClose} />
</Overlay>
</div>
);
}
}
|
app/javascript/mastodon/components/status_list.js | Craftodon/Craftodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import StatusContainer from '../containers/status_container';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ScrollableList from './scrollable_list';
export default class StatusList extends ImmutablePureComponent {
static propTypes = {
scrollKey: PropTypes.string.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
onScrollToBottom: PropTypes.func,
onScrollToTop: PropTypes.func,
onScroll: PropTypes.func,
trackScroll: PropTypes.bool,
shouldUpdateScroll: PropTypes.func,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
prepend: PropTypes.node,
emptyMessage: PropTypes.node,
};
static defaultProps = {
trackScroll: true,
};
handleMoveUp = id => {
const elementIndex = this.props.statusIds.indexOf(id) - 1;
this._selectChild(elementIndex);
}
handleMoveDown = id => {
const elementIndex = this.props.statusIds.indexOf(id) + 1;
this._selectChild(elementIndex);
}
_selectChild (index) {
const element = this.node.node.querySelector(`article:nth-of-type(${index + 1}) .focusable`);
if (element) {
element.focus();
}
}
setRef = c => {
this.node = c;
}
render () {
const { statusIds, ...other } = this.props;
const { isLoading } = other;
const scrollableContent = (isLoading || statusIds.size > 0) ? (
statusIds.map((statusId) => (
<StatusContainer
key={statusId}
id={statusId}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
/>
))
) : null;
return (
<ScrollableList {...other} ref={this.setRef}>
{scrollableContent}
</ScrollableList>
);
}
}
|
assets/javascripts/kitten/karl/pages/pre-deposit/components/triptych/solutions-triptych.js | KissKissBankBank/kitten | import React from 'react'
import { Container, Grid, GridCol, Title, Triptych, COLORS } from 'kitten'
import { CardWithButton } from './card-with-button'
const SolutionsTriptych = () => (
<div className="k-u-margin-top-octuple k-u-margin-top-decuple@l-up">
<Container>
<Grid>
<GridCol
col-l="10"
offset-l="1"
col-m="12"
offset-m="0"
col-s="10"
offset-s="1"
>
<Triptych
title={
<Title
tag="h2"
modifier="secondary"
margin={false}
style={{ color: COLORS.font1 }}
>
3 solutions pour collecter des fonds et financer mon projet
</Title>
}
item1={
<CardWithButton
title="Le don en échange de contreparties"
paragraph="Adapté à tous les types de projets, laissez parler votre créativité pour remercier vos contributeurs."
imageProps={{
src: 'http://via.placeholder.com/350x350/19b4fa/19b4fa',
alt: '',
}}
horizontalStroke={false}
marginBetweenImgAndBody="3"
/>
}
item2={
<CardWithButton
title="La prévente"
paragraph="Recommandée pour lancer vos créations, votre marque, vos produits ou pour tester un prototype. Fonctionne aussi très bien pour gérer la billetterie de vos événements."
imageProps={{
src: 'http://via.placeholder.com/350x350/19b4fa/19b4fa',
alt: '',
}}
horizontalStroke={false}
marginBetweenImgAndBody="3"
/>
}
item3={
<CardWithButton
title="Le don libre"
paragraph="Idéal pour les projets associatifs, philanthropiques, de défense de l’environnement, éducatifs, patrimoniaux, de mécénat, personnels…"
imageProps={{
src: 'http://via.placeholder.com/350x350/19b4fa/19b4fa',
alt: '',
}}
horizontalStroke={false}
marginBetweenImgAndBody="3"
/>
}
/>
</GridCol>
</Grid>
</Container>
</div>
)
export default SolutionsTriptych
|
src/shared/components/Shared/HeartToggle.js | Grace951/ReactAU | import React from 'react';
class HeartToggle extends React.Component{
constructor(props) {
super(props);
this.state ={
select: props.init
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(evt){
let nSelect = !this.state.select;
this.setState((state, props) => { return { select: nSelect };});
this.props.selectIt && this.props.selectIt(nSelect);
}
render(){
let r = 'fa fa-heart';
if(!this.state.select){
r += '-o';
}
return (
<i onClick={this.handleClick} className={r} style={{color: "#CC3300"}}/>
);
}
}
HeartToggle.propTypes = {
init: React.PropTypes.bool,
selectIt: React.PropTypes.func,
};
HeartToggle.defaultProps = {
init: false,
};
export default HeartToggle;
|
web/src/components/IndexLayout.js | ZhuPeng/trackupdates | import React from 'react';
import style from './IndexLayout.css';
import * as jobitem from '../services/item';
import ItemList from './ItemList';
import { Layout, Menu, Icon, Select, BackTop } from 'antd';
const { Header, Sider, Content, Footer } = Layout;
const Option = Select.Option;
class IndexLayout extends React.Component {
constructor(props) {
super(props);
this.state = {
collapsed: false,
data: '',
loading: true,
selectedKey: '',
formatStyle: 'markdown',
};
this.initStatus()
}
initStatus() {
var self = this;
jobitem.queryApiIndex().then(function(res) {
var selectedKey = '';
for (var i in res.data.items) {
selectedKey = i
break
}
console.log(res.data)
self.setState({
data: res.data,
selectedKey: selectedKey,
loading: false,
})
})
}
toggle = () => {
console.log(this.props)
this.setState({
collapsed: !this.state.collapsed,
});
}
handleClick = (e) => {
console.log('click: ', e.key);
this.setState({
selectedKey: e.key,
});
}
handleChange(value) {
console.log(`selected ${value}`);
this.setState({formatStyle: value})
}
render() {
var {collapsed, data, loading, selectedKey, formatStyle} = this.state;
var menuItem = []
if (!loading) {
for (var i in data.items) {
menuItem.push(<Menu.Item key={i}><span>{data.items[i].name}</span></Menu.Item>)
}
}
return (
<Layout>
<Sider trigger={null} collapsible collapsed={collapsed}>
<div className={style["logo"]} key="logo">
<h1 className={style['h1']}>TrackUpdates</h1>
</div>
<Menu theme="dark" onClick={this.handleClick} selectedKeys={[selectedKey]}>
{menuItem}
</Menu>
<BackTop> <div className={style["ant-back-top-inner"]}>UP</div> </BackTop>
</Sider>
<Layout>
<Header style={{ background: '#fff', padding: 0 }}>
<Icon className={style["trigger"]} type={collapsed ? 'menu-unfold' : 'menu-fold'} onClick={this.toggle} />
<Select defaultValue={formatStyle} style={{ width: 160, float: 'right', 'padding': '15px' }} onChange={this.handleChange.bind(this)}>
<Option value="html">HTML</Option>
<Option value="markdown">Markdown</Option>
<Option value="json">表格</Option>
</Select>
</Header>
<Content style={{ margin: '24px 16px', padding: 24, background: '#fff', minHeight: 280 }}>
<ItemList selectedKey={selectedKey} formatStyle={formatStyle}/>
</Content>
<Footer style={{ textAlign: 'center' }}>
GitHub: <a href='https://github.com/ZhuPeng/trackupdates'>TrackUpdates</a> ©2018 Created by Peng ZHU
</Footer>
</Layout>
</Layout>
);
}
}
export default IndexLayout;
|
src/containers/Home/index.js | DiscipleD/react-redux-antd-starter | /**
* Created by jack on 16-9-6.
*/
import React from 'react';
import {push} from 'react-router-redux';
import {connect} from 'react-redux';
import {createSelector} from 'reselect';
import HeaderNav from 'components/HeaderNav';
import menuActions from 'actions/menu';
@connect(
state => ({
...state.menu,
currentPath: createSelector(
state => state.menu.list,
state => state.routing.locationBeforeTransitions.pathname,
(list = [], pathname) => list.length === 0 ? '' : list.filter(item => item.path === pathname).length > 0 ? pathname : list[0].path
)(state)
}), {
goHome: () => push('/'),
queryMenuList: menuActions.queryMenuList
})
class Home extends React.Component {
componentWillMount() {
this.props.queryMenuList();
}
render() {
const menuList = this.props.list;
return (
<section>
<HeaderNav
navList={menuList}
path={this.props.currentPath}
onlogoClickFn={this.props.goHome}
/>
{this.props.children}
</section>
)
}
}
export default Home;
|
src/components/Main.js | Looooper/openclass-gallery | require('normalize.css/normalize.css');
require('styles/App.scss');
import React from 'react';
import ReactDOM from 'react-dom';
import ControllerUnit from './ControllerUnit';
import ImgFigure from './ImgFigure';
// 获取图片相关数据
let imageDatas = require('../data/imageData.json');
// 利用自执行函数,讲图片名称转换成路径信息
imageDatas = (function generateImgURL(imgDataArr){
for (var i = 0;i<imgDataArr.length;i++) {
let singleImageData = imgDataArr[i];
singleImageData.imgURL = require('../images/'+singleImageData.fileName);
imgDataArr[i] = singleImageData;
}
return imgDataArr;
})(imageDatas);
/*
* 获取区间内的一个随机值
*/
function getRangeRandom(low, high) {
return Math.ceil(Math.random() * (high - low) + low);
}
/*
* 获取 0~30° 之间的一个任意正负值
*/
function get30DegRandom() {
return ((Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30));
}
// 整个React应用的根组件
class AppComponent extends React.Component {
constructor(props){
super(props);
this.state = {
imgsArrangeArr: [
/*{
pos: {
left: '0',
top: '0'
},
rotate: 0, // 旋转角度
isInverse: false, // 图片正反面
isCenter: false, // 图片是否居中
}*/
]
};
this.Constant = {
centerPos: {
left: 0,
right: 0
},
hPosRange: { // 水平方向的取值范围
leftSecX: [0, 0],
rightSecX: [0, 0],
y: [0, 0]
},
vPosRange: { // 垂直方向的取值范围
x: [0, 0],
topY: [0, 0]
}
};
}
/*
* 翻转图片
* @param index 传入当前被执行inverse操作的图片对应的图片信息数组的index值
* @returns {Function} 这是一个闭包函数, 其内return一个真正待被执行的函数
*/
inverse(index) {
return function () {
var imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
this.setState({
imgsArrangeArr: imgsArrangeArr
});
}.bind(this);
}
/*
* 重新布局所有图片
* @param centerIndex 指定居中排布哪个图片
*/
rearrange(centerIndex) {
var imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgsArrangeTopArr = [],
topImgNum = Math.floor(Math.random() * 2), // 取一个或者不取
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);
// 首先居中 centerIndex 的图片, 居中的 centerIndex 的图片不需要旋转
imgsArrangeCenterArr[0] = {
pos: centerPos,
rotate: 0,
isCenter: true
};
// 取出要布局上侧的图片的状态信息
topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);
// 布局位于上侧的图片
imgsArrangeTopArr.forEach(function (value, index) {
imgsArrangeTopArr[index] = {
pos: {
top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
},
rotate: get30DegRandom(),
isCenter: false
};
});
// 布局左右两侧的图片
for (var i = 0, j = imgsArrangeArr.length, k = j / 2; i < j; i++) {
var hPosRangeLORX = null;
// 前半部分布局左边, 右半部分布局右边
if (i < k) {
hPosRangeLORX = hPosRangeLeftSecX;
} else {
hPosRangeLORX = hPosRangeRightSecX;
}
imgsArrangeArr[i] = {
pos: {
top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
},
rotate: get30DegRandom(),
isCenter: false
};
}
if (imgsArrangeTopArr && imgsArrangeTopArr[0]) {
imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
}
imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);
this.setState({
imgsArrangeArr: imgsArrangeArr
});
}
/*
* 利用arrange函数, 居中对应index的图片
* @param index, 需要被居中的图片对应的图片信息数组的index值
* @returns {Function}
*/
center(index) {
return function () {
this.rearrange(index);
}.bind(this);
}
// 组件加载以后, 为每张图片计算其位置的范围
componentDidMount() {
// 首先拿到舞台的大小
var stageDOM = ReactDOM.findDOMNode(this.refs.stage),
stageW = stageDOM.scrollWidth,
stageH = stageDOM.scrollHeight,
halfStageW = Math.ceil(stageW / 2),
halfStageH = Math.ceil(stageH / 2);
// 拿到一个imageFigure的大小
var imgFigureDOM = ReactDOM.findDOMNode(this.refs.imgFigure0),
imgW = imgFigureDOM.scrollWidth,
imgH = imgFigureDOM.scrollHeight,
halfImgW = Math.ceil(imgW / 2),
halfImgH = Math.ceil(imgH / 2);
// 计算中心图片的位置点
this.Constant.centerPos = {
left: halfStageW - halfImgW,
top: halfStageH - halfImgH
};
// 计算左侧,右侧区域图片排布位置的取值范围
this.Constant.hPosRange.leftSecX[0] = -halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageH - halfImgH;
// 计算上侧区域图片排布位置的取值范围
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.Constant.vPosRange.x[0] = halfStageW - imgW;
this.Constant.vPosRange.x[1] = halfStageW;
this.rearrange(0);
}
render() {
var controllerUnits = [],
imgFigures = [];
imageDatas.forEach(function (value, index) {
if (!this.state.imgsArrangeArr[index]) {
this.state.imgsArrangeArr[index] = {
pos: {
left: 0,
top: 0
},
rotate: 0,
isInverse: false,
isCenter: false
};
}
imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
}.bind(this));
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgFigures}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
|
src/containers/app/index.js | eNdiD/wl_test_frontend | import React, { Component } from 'react';
import { Route, Switch, withRouter } from 'react-router';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import * as filmsListActions from '../../actions/films';
import * as actorsListActions from '../../actions/actors';
import 'bootstrap/dist/css/bootstrap.css';
import 'bootstrap/dist/css/bootstrap-theme.css';
import './style.css';
import Header from '../../components/header';
import Loading from '../../components/loading';
import FilmsList from '../../components/films-list';
import FilmItem from '../../components/film-item';
import AddFilm from '../../components/add-film';
import EditFilm from '../../components/edit-film';
class App extends Component {
componentDidMount() {
this.props.filmsListActions.getFilmsList();
this.props.actorsListActions.getActorsList();
}
// shouldComponentUpdate(nextProps) {
// return true;
// }
render() {
const { filmsList, actorsList, filmsListActions, actorsListActions } = this.props;
return (
<div>
<Header/>
{
filmsList.status ?
<div className='container'>
<p className='bg-danger status-text'>{ filmsList.status }</p>
</div> :
''
}
{
filmsList.fetching ?
<Loading/> :
<Switch>
<Route
exact={ true }
path='/'
render={ () =>
<FilmsList
films={ filmsList.films }
actors={ actorsList.actors }
order_by={ filmsList.order_by }
order={ filmsList.order }
changeOrder={ filmsListActions.changeOrder }
addFilmItem={ filmsListActions.addFilmItem }
deleteFilmItem={ filmsListActions.deleteFilmItem }
addActorItem={ actorsListActions.addActorItem }
showStatus={ filmsListActions.showStatus }/>
}/>
<Route
exact={ true }
path='/film/:pk'
render={ () =>
<FilmItem
films={ filmsList.films }
actors={ actorsList.actors }
deleteFilmItem={ filmsListActions.deleteFilmItem }
showStatus={ filmsListActions.showStatus }/>
}/>
<Route
exact={ true }
path='/add'
render={ () =>
<AddFilm
actors={ actorsList.actors }
films={ filmsList.films }
addFilmItem={ filmsListActions.addFilmItem }
showStatus={ filmsListActions.showStatus }
addActorItem={ actorsListActions.addActorItem }
deleteActorItem={ actorsListActions.deleteActorItem }/>
}/>
<Route
exact={ true }
path='/edit/:pk'
render={ () =>
<EditFilm
actors={ actorsList.actors }
films={ filmsList.films }
editFilmItem={ filmsListActions.editFilmItem }
showStatus={ filmsListActions.showStatus }
addActorItem={ actorsListActions.addActorItem }
deleteActorItem={ actorsListActions.deleteActorItem }/>
}/>
</Switch>
}
</div>
);
}
}
function mapStateToProps(state) {
return {
filmsList: state.filmsList,
actorsList: state.actorsList
}
}
function mapDispatchToProps(dispatch) {
return {
filmsListActions: bindActionCreators(filmsListActions, dispatch),
actorsListActions: bindActionCreators(actorsListActions, dispatch)
}
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(App));
|
app/javascript/mastodon/features/following/index.js | gol-cha/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import {
lookupAccount,
fetchAccount,
fetchFollowing,
expandFollowing,
} from '../../actions/accounts';
import { FormattedMessage } from 'react-intl';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import ScrollableList from '../../components/scrollable_list';
import MissingIndicator from 'mastodon/components/missing_indicator';
import TimelineHint from 'mastodon/components/timeline_hint';
const mapStateToProps = (state, { params: { acct, id } }) => {
const accountId = id || state.getIn(['accounts_map', acct]);
if (!accountId) {
return {
isLoading: true,
};
}
return {
accountId,
remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])),
remoteUrl: state.getIn(['accounts', accountId, 'url']),
isAccount: !!state.getIn(['accounts', accountId]),
accountIds: state.getIn(['user_lists', 'following', accountId, 'items']),
hasMore: !!state.getIn(['user_lists', 'following', accountId, 'next']),
isLoading: state.getIn(['user_lists', 'following', accountId, 'isLoading'], true),
blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false),
};
};
const RemoteHint = ({ url }) => (
<TimelineHint url={url} resource={<FormattedMessage id='timeline_hint.resources.follows' defaultMessage='Follows' />} />
);
RemoteHint.propTypes = {
url: PropTypes.string.isRequired,
};
export default @connect(mapStateToProps)
class Following extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.shape({
acct: PropTypes.string,
id: PropTypes.string,
}).isRequired,
accountId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
blockedBy: PropTypes.bool,
isAccount: PropTypes.bool,
remote: PropTypes.bool,
remoteUrl: PropTypes.string,
multiColumn: PropTypes.bool,
};
_load () {
const { accountId, isAccount, dispatch } = this.props;
if (!isAccount) dispatch(fetchAccount(accountId));
dispatch(fetchFollowing(accountId));
}
componentDidMount () {
const { params: { acct }, accountId, dispatch } = this.props;
if (accountId) {
this._load();
} else {
dispatch(lookupAccount(acct));
}
}
componentDidUpdate (prevProps) {
const { params: { acct }, accountId, dispatch } = this.props;
if (prevProps.accountId !== accountId && accountId) {
this._load();
} else if (prevProps.params.acct !== acct) {
dispatch(lookupAccount(acct));
}
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFollowing(this.props.accountId));
}, 300, { leading: true });
render () {
const { accountIds, hasMore, blockedBy, isAccount, multiColumn, isLoading, remote, remoteUrl } = this.props;
if (!isAccount) {
return (
<Column>
<MissingIndicator />
</Column>
);
}
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
let emptyMessage;
if (blockedBy) {
emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />;
} else if (remote && accountIds.isEmpty()) {
emptyMessage = <RemoteHint url={remoteUrl} />;
} else {
emptyMessage = <FormattedMessage id='account.follows.empty' defaultMessage="This user doesn't follow anyone yet." />;
}
const remoteMessage = remote ? <RemoteHint url={remoteUrl} /> : null;
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<ScrollableList
scrollKey='following'
hasMore={hasMore}
isLoading={isLoading}
onLoadMore={this.handleLoadMore}
prepend={<HeaderContainer accountId={this.props.accountId} hideTabs />}
alwaysPrepend
append={remoteMessage}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{blockedBy ? [] : accountIds.map(id =>
<AccountContainer key={id} id={id} withNote={false} />,
)}
</ScrollableList>
</Column>
);
}
}
|
javascript/canopy-listing/GridHeader.js | AppStateESS/carousel | 'use strict'
import React from 'react'
import PropTypes from 'prop-types'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faCaretUp, faCaretDown} from '@fortawesome/free-solid-svg-icons'
const GridHeader = ({columns, sortFunction, sortIconTrack}) => {
const th = columns.map((value, key) => {
let icon
let className = []
let handle = null
if (value.sort === true) {
className.push('pointer')
handle = sortFunction.bind(null, value.column)
if (sortIconTrack[value.column] === 1) {
icon = <FontAwesomeIcon icon={faCaretUp} transform="up-4" />
} else if (sortIconTrack[value.column] === 2) {
icon = <FontAwesomeIcon icon={faCaretDown} transform="down-4" />
} else {
icon = (
<span className="fa-layers fa-fw">
<FontAwesomeIcon icon={faCaretUp} transform="up-4" />
<FontAwesomeIcon icon={faCaretDown} transform="down-4" />
</span>
)
}
}
if (value.className) {
className.push(value.className)
}
let style
if (value.style && typeof value.style === 'object') {
style = value.style
}
return (
<th style={style} className={className} key={`th${key}`} onClick={handle}>
{value.label} {icon}
</th>
)
})
return <tr>{th}</tr>
}
GridHeader.propTypes = {
columns: PropTypes.array,
sortFunction: PropTypes.func,
sortIconTrack: PropTypes.object
}
export default GridHeader
|
src/components_back20170707/components/message-box/index.js | MeteDesign/MeteDesign | import React from 'react';
import ReactDOM from 'react-dom';
import MessageBox from './MessageBox';
function alert(message, title, props) {
if (typeof title === 'object') {
props = title;
}
props = Object.assign({ title, message,
modal: 'alert',
closeOnPressEscape: false,
closeOnClickModal: false
}, props);
return next(props);
}
function confirm(message, title, props) {
if (typeof title === 'object') {
props = title;
}
props = Object.assign({ title, message,
modal: 'confirm',
showCancelButton: true
}, props);
return next(props);
}
function prompt(message, title, props) {
if (typeof title === 'object') {
props = title;
}
props = Object.assign({ title, message,
modal: 'prompt',
showCancelButton: true,
showInput: true
}, props);
return next(props);
}
function msgbox(props) {
return next(props);
}
function next(props) {
return new Promise((resolve, reject) => {
const div = document.createElement('div');
document.body.appendChild(div);
if (props.lockScroll != false) {
document.body.style.setProperty('overflow', 'hidden');
}
const component = React.createElement(MessageBox, Object.assign({}, props, {
promise: { resolve, reject },
onClose: () => {
ReactDOM.unmountComponentAtNode(div);
document.body.removeChild(div);
document.body.style.removeProperty('overflow');
if (props.onClose instanceof Function) {
props.onClose();
}
}
}));
ReactDOM.render(component, div);
});
}
export default {
alert,
confirm,
prompt,
msgbox
}
|
src/routes/Post/components/Post.js | oliveirafabio/wut-blog | import React from 'react'
import { Field } from 'redux-form'
import RaisedButton from 'material-ui/RaisedButton'
import TextField from 'material-ui/TextField'
import classes from './Post.scss'
export const Post = (props) => {
const { handleSubmit, post } = props
return (
<div className={classes['Post']}>
<form onSubmit={handleSubmit(post)}>
<div>
<Field name="title"
component={({ input }) => {
return <TextField {...input}
hintText="Title"
fullWidth={true}/>
}} />
</div>
<div>
<Field name="content"
component={({ input }) => {
return <TextField {...input}
floatingLabelText="Content"
multiLine={true}
rows={20}
fullWidth={true}/>
}} />
</div>
<RaisedButton label="cancel"
className={classes['button']}
secondary={true}/>
<RaisedButton type="submit"
label="save"
className={classes['button']}
primary={true}/>
</form>
</div>
)
}
export default Post
|
webapp/src/app/about/screen/About.js | cpollet/itinerants | import React from 'react';
class About extends React.Component {
render() {
return (
<div>
<a href="https://github.com/cpollet/itinerants">Fork me on github</a>
</div>
);
}
}
export default About;
|
src/containers/NhtsaApp/NhtsaApp.js | Zoomdata/nhtsa-dashboard-2.2 | import styles from './NhtsaApp.css';
import React from 'react';
import { connect } from 'react-redux';
import Overlay from '../../components/Overlay/Overlay';
import Dashboard from '../../components/Dashboard/Dashboard';
import { ButtonContainerContainer } from '../../containers/ButtonContainer/ButtonContainer';
import { verticalScrollThreshold } from '../../config/app-constants';
// Which props do we want to inject, given the global state?
// Note: use https://github.com/faassen/reselect for better performance.
const mapStateToProps = (state) => {
return {
browser: state.browser,
dashboardDimensions: state.layout.dashboardDimensions
}
}
const NhtsaApp = ({
browser,
dashboardDimensions
}) => {
let newBackgroundX = (dashboardDimensions.offsetLeft + dashboardDimensions.width) - 465;
let newBackgroundY;
let newOverflowY = 'hidden';
if (window.innerHeight < verticalScrollThreshold) {
newBackgroundY = verticalScrollThreshold - 323;
} else {
newBackgroundY = window.innerHeight - 323;
}
if (browser.height < verticalScrollThreshold) {
newOverflowY = 'visible';
}
const nhtsaAppStyle = {
backgroundPositionX: newBackgroundX,
backgroundPositionY: newBackgroundY,
overflowY: newOverflowY
};
return (
<div
className={styles.root}
style={nhtsaAppStyle}
>
<Overlay />
<Dashboard />
<footer>
© 2014 <a href="http://www.zoomdata.com/">Zoomdata</a>, Inc. <a href="http://www.zoomdata.com/contact">Contact</a> <a href="http://www.zoomdata.com/terms">Legal</a>
</footer>
<ButtonContainerContainer />
</div>
)
}
// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps)(NhtsaApp) |
src/scenes/dashboard/messages/index.js | PowerlineApp/powerline-rn | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Content, Text, List, ListItem, Left, Body, Right, Thumbnail, Button, Icon } from 'native-base';
import {
TouchableOpacity,
View
} from 'react-native';
import ContentPlaceholder from '../../../components/ContentPlaceholder';
class Messages extends Component {
state = {
messages: []
}
render() {
return (
<ContentPlaceholder
empty={this.state.messages.length === 0}
title="The only announcement right now is that there are no announcements."
>
<List style={{ backgroundColor: 'white' }}>
</List>
</ContentPlaceholder>
);
}
}
export default connect()(Messages); |
analysis/druidferal/src/modules/spells/FerociousBiteEnergy.js | anom0ly/WoWAnalyzer | import { t } from '@lingui/macro';
import { formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import HIT_TYPES from 'game/HIT_TYPES';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import { SpellLink } from 'interface';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import { ThresholdStyle } from 'parser/core/ParseResults';
import React from 'react';
import {
BERSERK_ENERGY_COST_MULTIPLIER,
ENERGY_FOR_FULL_DAMAGE_BITE,
MAX_BITE_DAMAGE_BONUS_FROM_ENERGY,
} from '../../constants';
import SpellEnergyCost from '../features/SpellEnergyCost';
const debug = false;
const LEEWAY_BETWEEN_CAST_AND_DAMAGE = 500; // in ms
const HIT_TYPES_TO_IGNORE = [HIT_TYPES.MISS, HIT_TYPES.DODGE, HIT_TYPES.PARRY];
/**
* Although Ferocious Bite costs 25 energy it does extra damage with more energy available, up to double with a full 25 extra energy. This is among the most efficient uses of energy so it's recommended that feral druids wait for 50+ energy before using Bite.
* Ferocious Bite consumes energy in an unusual way: the cast will consume 25 energy followed by a drain event consuming up to 25 more.
* Berserk or Incarnation reduces energy costs by 40%. It reduces Bite's base cost correctly to 15 but reduces the drain effect to 13 (I expect a bug from when it used to reduce costs by 50%). So a player only needs to have 28 (or 30 if the bug is fixed) energy to get full damage from Ferocious Bite during Berserk rather than the usual 50. This module ignores the bug (the effect is very minor) and calculates everything as if the drain effect is correctly reduced to 15 rather than 13.
*/
class FerociousBiteEnergy extends Analyzer {
get _dpsLostFromLowEnergyBites() {
return (this.lostDamageTotal / this.owner.fightDuration) * 1000;
}
get _averageBonusEnergyFraction() {
return this.biteCount > 0 ? this.sumBonusEnergyFraction / this.biteCount : 1.0;
}
get suggestionThresholds() {
return {
actual: this._averageBonusEnergyFraction,
isLessThan: {
minor: 1.0,
average: 0.95,
major: 0.8,
},
style: ThresholdStyle.PERCENTAGE,
};
}
static dependencies = {
spellEnergyCost: SpellEnergyCost,
};
biteCount = 0;
lostDamageTotal = 0;
sumBonusEnergyFraction = 0;
lastBiteCast = {
timestamp: 0,
event: undefined,
energyForFullDamage: 50,
energyUsedByCast: 25,
energyAvailable: 100,
isPaired: true,
};
constructor(...args) {
super(...args);
this.addEventListener(
Events.cast.by(SELECTED_PLAYER).spell(SPELLS.FEROCIOUS_BITE),
this._onBiteCast,
);
this.addEventListener(
Events.damage.by(SELECTED_PLAYER).spell(SPELLS.FEROCIOUS_BITE),
this._onBiteDamage,
);
}
_onBiteCast(event) {
this.lastBiteCast = {
timestamp: event.timestamp,
event: event,
energyForFullDamage:
ENERGY_FOR_FULL_DAMAGE_BITE *
(this._hasBerserkAtTime(event.timestamp) ? BERSERK_ENERGY_COST_MULTIPLIER : 1),
energyUsedByCast: this._energyUsedByCast(event),
energyAvailable: this._energyAvailable(event),
isPaired: false,
};
}
_onBiteDamage(event) {
if (
this.lastBiteCast.isPaired ||
event.timestamp > this.lastBiteCast.timestamp + LEEWAY_BETWEEN_CAST_AND_DAMAGE
) {
debug &&
this.warn(
`Ferocious Bite damage event couldn't find a matching cast event. Last Ferocious Bite cast event was at ${
this.lastBiteCast.timestamp
}${this.lastBiteCast.isPaired ? ' but has already been paired' : ''}.`,
);
return;
}
if (HIT_TYPES_TO_IGNORE.includes(event.hitType)) {
// ignore parry/dodge/miss events as they'll refund energy anyway
return;
}
if (this.lastBiteCast.energyAvailable < this.lastBiteCast.energyForFullDamage) {
const actualDamage = event.amount + event.absorbed;
const lostDamage =
this._calcPotentialBiteDamage(actualDamage, this.lastBiteCast) - actualDamage;
this.lostDamageTotal += lostDamage;
this.sumBonusEnergyFraction += this._bonusEnergyFraction(this.lastBiteCast);
const castEvent = this.lastBiteCast.event;
castEvent.meta = event.meta || {};
castEvent.meta.isInefficientCast = true;
castEvent.meta.inefficientCastReason = `Used with low energy only gaining ${(
this._bonusEnergyFraction(this.lastBiteCast) * 100
).toFixed(1)}% of the potential bonus from extra energy, missing out on ${formatNumber(
lostDamage,
)} damage.`;
} else {
this.sumBonusEnergyFraction += 1;
}
this.biteCount += 1;
this.lastBiteCast.isPaired = true;
}
_hasBerserkAtTime(timestamp) {
return (
this.selectedCombatant.hasBuff(SPELLS.BERSERK.id, timestamp) ||
this.selectedCombatant.hasBuff(SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id, timestamp)
);
}
_energyAvailable(event) {
const resource =
event.classResources &&
event.classResources.find(
(classResources) => classResources.type === RESOURCE_TYPES.ENERGY.id,
);
if (!resource || !resource.amount) {
debug && this.warn('Unable to get energy available from cast event.');
return 100;
}
return resource.amount;
}
_energyUsedByCast(event) {
if (!event.resourceCost || event.resourceCost[RESOURCE_TYPES.ENERGY.id] === undefined) {
debug && this.warn('Unable to get energy cost from cast event.');
return 0;
}
return event.resourceCost[RESOURCE_TYPES.ENERGY.id];
}
_bonusEnergyFraction(biteCast) {
return Math.min(
1,
(biteCast.energyAvailable - biteCast.energyUsedByCast) /
(biteCast.energyForFullDamage - biteCast.energyUsedByCast),
);
}
/**
* Calculate what damage a bite could have done if it'd been given the maximum bonus energy
* @param {number} actualDamage Observed damage of the Bite
* @param {number} energy Energy available when Bite was cast
*/
_calcPotentialBiteDamage(actualDamage, biteCast) {
if (biteCast.energyAvailable >= biteCast.energyForFullDamage) {
// Bite was already doing its maximum damage
return actualDamage;
}
// the ideal multiplier would be 2, but because this bite didn't have enough energy the actual multiplier will be lower
const actualMultiplier =
1 + MAX_BITE_DAMAGE_BONUS_FROM_ENERGY * this._bonusEnergyFraction(biteCast);
const damageBeforeMultiplier = actualDamage / actualMultiplier;
return damageBeforeMultiplier * (1 + MAX_BITE_DAMAGE_BONUS_FROM_ENERGY);
}
suggestions(when) {
const berserkOrIncarnationId = this.selectedCombatant.hasTalent(
SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id,
)
? SPELLS.INCARNATION_KING_OF_THE_JUNGLE_TALENT.id
: SPELLS.BERSERK.id;
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) =>
suggest(
<>
You didn't always give <SpellLink id={SPELLS.FEROCIOUS_BITE.id} /> enough energy to get
the full damage bonus. You should aim to have {ENERGY_FOR_FULL_DAMAGE_BITE} energy before
using Ferocious Bite, or{' '}
{(ENERGY_FOR_FULL_DAMAGE_BITE * BERSERK_ENERGY_COST_MULTIPLIER).toFixed(0)} during{' '}
<SpellLink id={berserkOrIncarnationId} />. Your Ferocious Bite damage was reduced by{' '}
{formatNumber(this._dpsLostFromLowEnergyBites)} DPS due to lack of energy.
</>,
)
.icon(SPELLS.FEROCIOUS_BITE.icon)
.actual(
t({
id: 'druid.feral.suggestions.ferociousBite.efficiency',
message: `${(actual * 100).toFixed(
1,
)}% average damage bonus from energy on Ferocious Bite.`,
}),
)
.recommended(`${(recommended * 100).toFixed(1)}% is recommended.`),
);
}
}
export default FerociousBiteEnergy;
|
react/features/base/media/components/native/VideoTransform.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import { PanResponder, PixelRatio, View } from 'react-native';
import { type Dispatch } from 'redux';
import { connect } from '../../../redux';
import { storeVideoTransform } from '../../actions';
import styles from './styles';
/**
* The default/initial transform (= no transform).
*/
const DEFAULT_TRANSFORM = {
scale: 1,
translateX: 0,
translateY: 0
};
/**
* The minimum scale (magnification) multiplier. 1 is equal to objectFit
* = 'contain'.
*/
const MIN_SCALE = 1;
/*
* The max distance from the edge of the screen where we let the user move the
* view to. This is large enough now to let the user drag the view to a position
* where no other displayed components cover it (such as filmstrip). If a
* ViewPort (hint) support is added to the LargeVideo component then this
* constant will not be necessary anymore.
*/
const MAX_OFFSET = 100;
/**
* The max allowed scale (magnification) multiplier.
*/
const MAX_SCALE = 5;
/**
* The threshold to allow the fingers move before we consider a gesture a
* move instead of a touch.
*/
const MOVE_THRESHOLD_DISMISSES_TOUCH = 5;
/**
* A tap timeout after which we consider a gesture a long tap and will not
* trigger onPress (unless long tap gesture support is added in the future).
*/
const TAP_TIMEOUT_MS = 400;
/**
* Type of a transform object this component is capable of handling.
*/
type Transform = {
scale: number,
translateX: number,
translateY: number
};
type Props = {
/**
* The children components of this view.
*/
children: Object,
/**
* Transformation is only enabled when this flag is true.
*/
enabled: boolean,
/**
* Function to invoke when a press event is detected.
*/
onPress?: Function,
/**
* The id of the current stream that is displayed.
*/
streamId: string,
/**
* Style of the top level transformable view.
*/
style: Object,
/**
* The stored transforms retrieved from Redux to be initially applied
* to different streams.
*/
_transforms: Object,
/**
* Action to dispatch when the component is unmounted.
*/
_onUnmount: Function
};
type State = {
/**
* The current (non-transformed) layout of the View.
*/
layout: ?Object,
/**
* The current transform that is applied.
*/
transform: Transform
};
/**
* An container that captures gestures such as pinch&zoom, touch or move.
*/
class VideoTransform extends Component<Props, State> {
/**
* The gesture handler object.
*/
gestureHandlers: Object;
/**
* The initial distance of the fingers on pinch start.
*/
initialDistance: ?number;
/**
* The initial position of the finger on touch start.
*/
initialPosition: {
x: number,
y: number
};
/**
* The actual move threshold that is calculated for this device/screen.
*/
moveThreshold: number;
/**
* Time of the last tap.
*/
lastTap: number;
/**
* Constructor of the component.
*
* @inheritdoc
*/
constructor(props: Props) {
super(props);
this.state = {
layout: null,
transform:
this._getSavedTransform(props.streamId) || DEFAULT_TRANSFORM
};
this._didMove = this._didMove.bind(this);
this._getTransformStyle = this._getTransformStyle.bind(this);
this._onGesture = this._onGesture.bind(this);
this._onLayout = this._onLayout.bind(this);
this._onMoveShouldSetPanResponder
= this._onMoveShouldSetPanResponder.bind(this);
this._onPanResponderGrant = this._onPanResponderGrant.bind(this);
this._onPanResponderMove = this._onPanResponderMove.bind(this);
this._onPanResponderRelease = this._onPanResponderRelease.bind(this);
this._onStartShouldSetPanResponder
= this._onStartShouldSetPanResponder.bind(this);
// The move threshold should be adaptive to the pixel ratio of the
// screen to avoid making it too sensitive or difficult to handle on
// different pixel ratio screens.
this.moveThreshold
= PixelRatio.get() * MOVE_THRESHOLD_DISMISSES_TOUCH;
this.gestureHandlers = PanResponder.create({
onPanResponderGrant: this._onPanResponderGrant,
onPanResponderMove: this._onPanResponderMove,
onPanResponderRelease: this._onPanResponderRelease,
onPanResponderTerminationRequest: () => true,
onMoveShouldSetPanResponder: this._onMoveShouldSetPanResponder,
onShouldBlockNativeResponder: () => false,
onStartShouldSetPanResponder: this._onStartShouldSetPanResponder
});
}
/**
* Implements React Component's componentDidUpdate.
*
* @inheritdoc
*/
componentDidUpdate(prevProps: Props, prevState: State) {
if (prevProps.streamId !== this.props.streamId) {
this._storeTransform(prevProps.streamId, prevState.transform);
this._restoreTransform(this.props.streamId);
}
}
/**
* Implements React Component's componentWillUnmount.
*
* @inheritdoc
*/
componentWillUnmount() {
this._storeTransform(this.props.streamId, this.state.transform);
}
/**
* Renders the empty component that captures the gestures.
*
* @inheritdoc
*/
render() {
const { children, style } = this.props;
return (
<View
onLayout = { this._onLayout }
pointerEvents = 'box-only'
style = { [
styles.videoTransformedViewContainer,
style
] }
{ ...this.gestureHandlers.panHandlers }>
<View
style = { [
styles.videoTranformedView,
this._getTransformStyle()
] }>
{ children }
</View>
</View>
);
}
/**
* Calculates the new transformation to be applied by merging the current
* transform values with the newly received incremental values.
*
* @param {Transform} transform - The new transform object.
* @private
* @returns {Transform}
*/
_calculateTransformIncrement(transform: Transform) {
let {
scale,
translateX,
translateY
} = this.state.transform;
const {
scale: newScale,
translateX: newTranslateX,
translateY: newTranslateY
} = transform;
// Note: We don't limit MIN_SCALE here yet, as we need to detect a scale
// down gesture even if the scale is already at MIN_SCALE to let the
// user return the screen to center with that gesture. Scale is limited
// to MIN_SCALE right before it gets applied.
scale = Math.min(scale * (newScale || 1), MAX_SCALE);
translateX = translateX + ((newTranslateX || 0) / scale);
translateY = translateY + ((newTranslateY || 0) / scale);
return {
scale,
translateX,
translateY
};
}
_didMove: Object => boolean;
/**
* Determines if there was large enough movement to be handled.
*
* @param {Object} gestureState - The gesture state.
* @returns {boolean}
*/
_didMove({ dx, dy }) {
return Math.abs(dx) > this.moveThreshold
|| Math.abs(dy) > this.moveThreshold;
}
/**
* Returns the stored transform a stream should display with initially.
*
* @param {string} streamId - The id of the stream to match with a stored
* transform.
* @private
* @returns {Object | null}
*/
_getSavedTransform(streamId) {
const { enabled, _transforms } = this.props;
return (enabled && _transforms[streamId]) || null;
}
_getTouchDistance: Object => number;
/**
* Calculates the touch distance on a pinch event.
*
* @param {Object} evt - The touch event.
* @private
* @returns {number}
*/
_getTouchDistance({ nativeEvent: { touches } }) {
const dx = Math.abs(touches[0].pageX - touches[1].pageX);
const dy = Math.abs(touches[0].pageY - touches[1].pageY);
return Math.sqrt(Math.pow(dx, 2) + Math.pow(dy, 2));
}
_getTouchPosition: Object => Object;
/**
* Calculates the position of the touch event.
*
* @param {Object} evt - The touch event.
* @private
* @returns {Object}
*/
_getTouchPosition({ nativeEvent: { touches } }) {
return {
x: touches[0].pageX,
y: touches[0].pageY
};
}
_getTransformStyle: () => Object;
/**
* Generates a transform style object to be used on the component.
*
* @returns {{string: Array<{string: number}>}}
*/
_getTransformStyle() {
const { enabled } = this.props;
if (!enabled) {
return null;
}
const {
scale,
translateX,
translateY
} = this.state.transform;
return {
transform: [
{ scale },
{ translateX },
{ translateY }
]
};
}
/**
* Limits the move matrix and then applies the transformation to the
* component (updates state).
*
* Note: Points A (top-left) and D (bottom-right) are opposite points of
* the View rectangle.
*
* @param {Transform} transform - The transformation object.
* @private
* @returns {void}
*/
_limitAndApplyTransformation(transform: Transform) {
const { layout } = this.state;
if (layout) {
const { scale } = this.state.transform;
const { scale: newScaleUnlimited } = transform;
let {
translateX: newTranslateX,
translateY: newTranslateY
} = transform;
// Scale is only limited to MIN_SCALE here to detect downscale
// gesture later.
const newScale = Math.max(newScaleUnlimited, MIN_SCALE);
// The A and D points of the original View (before transform).
const originalLayout = {
a: {
x: layout.x,
y: layout.y
},
d: {
x: layout.x + layout.width,
y: layout.y + layout.height
}
};
// The center point (midpoint) of the transformed View.
const transformedCenterPoint = {
x: ((layout.x + layout.width) / 2) + (newTranslateX * newScale),
y: ((layout.y + layout.height) / 2) + (newTranslateY * newScale)
};
// The size of the transformed View.
const transformedSize = {
height: layout.height * newScale,
width: layout.width * newScale
};
// The A and D points of the transformed View.
const transformedLayout = {
a: {
x: transformedCenterPoint.x - (transformedSize.width / 2),
y: transformedCenterPoint.y - (transformedSize.height / 2)
},
d: {
x: transformedCenterPoint.x + (transformedSize.width / 2),
y: transformedCenterPoint.y + (transformedSize.height / 2)
}
};
let _MAX_OFFSET = MAX_OFFSET;
if (newScaleUnlimited < scale) {
// This is a negative scale event so we dynamycally reduce the
// MAX_OFFSET to get the screen back to the center on
// downscaling.
_MAX_OFFSET = Math.min(MAX_OFFSET, MAX_OFFSET * (newScale - 1));
}
// Correct move matrix if it goes out of the view
// too much (_MAX_OFFSET).
newTranslateX
-= Math.max(
transformedLayout.a.x - originalLayout.a.x - _MAX_OFFSET,
0);
newTranslateX
+= Math.max(
originalLayout.d.x - transformedLayout.d.x - _MAX_OFFSET,
0);
newTranslateY
-= Math.max(
transformedLayout.a.y - originalLayout.a.y - _MAX_OFFSET,
0);
newTranslateY
+= Math.max(
originalLayout.d.y - transformedLayout.d.y - _MAX_OFFSET,
0);
this.setState({
transform: {
scale: newScale,
translateX: Math.round(newTranslateX),
translateY: Math.round(newTranslateY)
}
});
}
}
_onGesture: (string, ?Object | number) => void;
/**
* Handles gestures and converts them to transforms.
*
* Currently supported gestures:
* - scale (punch&zoom-type scale).
* - move
* - press.
*
* Note: This component supports onPress solely to overcome the problem of
* not being able to register gestures via the PanResponder due to the fact
* that the entire Conference component was a single touch responder
* component in the past (see base/react/.../Container with an onPress
* event) - and stock touch responder components seem to have exclusive
* priority in handling touches in React.
*
* @param {string} type - The type of the gesture.
* @param {?Object | number} value - The value of the gesture, if any.
* @returns {void}
*/
_onGesture(type, value) {
let transform;
switch (type) {
case 'move':
transform = {
...DEFAULT_TRANSFORM,
translateX: value.x,
translateY: value.y
};
break;
case 'scale':
transform = {
...DEFAULT_TRANSFORM,
scale: value
};
break;
case 'press': {
const { onPress } = this.props;
typeof onPress === 'function' && onPress();
break;
}
}
if (transform) {
this._limitAndApplyTransformation(
this._calculateTransformIncrement(transform));
}
this.lastTap = 0;
}
_onLayout: Object => void;
/**
* Callback for the onLayout of the component.
*
* @param {Object} event - The native props of the onLayout event.
* @private
* @returns {void}
*/
_onLayout({ nativeEvent: { layout: { x, y, width, height } } }) {
this.setState({
layout: {
x,
y,
width,
height
}
});
}
_onMoveShouldSetPanResponder: (Object, Object) => boolean;
/**
* Function to decide whether the responder should respond to a move event.
*
* @param {Object} evt - The event.
* @param {Object} gestureState - Gesture state.
* @private
* @returns {boolean}
*/
_onMoveShouldSetPanResponder(evt, gestureState) {
return this.props.enabled
&& (this._didMove(gestureState)
|| gestureState.numberActiveTouches === 2);
}
_onPanResponderGrant: (Object, Object) => void;
/**
* Calculates the initial touch distance.
*
* @param {Object} evt - Touch event.
* @param {Object} gestureState - Gesture state.
* @private
* @returns {void}
*/
_onPanResponderGrant(evt, { numberActiveTouches }) {
if (numberActiveTouches === 1) {
this.initialPosition = this._getTouchPosition(evt);
this.lastTap = Date.now();
} else if (numberActiveTouches === 2) {
this.initialDistance = this._getTouchDistance(evt);
}
}
_onPanResponderMove: (Object, Object) => void;
/**
* Handles the PanResponder move (touch move) event.
*
* @param {Object} evt - Touch event.
* @param {Object} gestureState - Gesture state.
* @private
* @returns {void}
*/
_onPanResponderMove(evt, gestureState) {
if (gestureState.numberActiveTouches === 2) {
// this is a zoom event
if (
this.initialDistance === undefined
|| isNaN(this.initialDistance)
) {
// there is no initial distance because the user started
// with only one finger. We calculate it now.
this.initialDistance = this._getTouchDistance(evt);
} else {
const distance = this._getTouchDistance(evt);
const scale = distance / (this.initialDistance || 1);
this.initialDistance = distance;
this._onGesture('scale', scale);
}
} else if (gestureState.numberActiveTouches === 1
&& isNaN(this.initialDistance)
&& this._didMove(gestureState)) {
// this is a move event
const position = this._getTouchPosition(evt);
const move = {
x: position.x - this.initialPosition.x,
y: position.y - this.initialPosition.y
};
this.initialPosition = position;
this._onGesture('move', move);
}
}
_onPanResponderRelease: () => void;
/**
* Handles the PanResponder gesture end event.
*
* @private
* @returns {void}
*/
_onPanResponderRelease() {
if (this.lastTap && Date.now() - this.lastTap < TAP_TIMEOUT_MS) {
this._onGesture('press');
}
delete this.initialDistance;
this.initialPosition = {
x: 0,
y: 0
};
}
_onStartShouldSetPanResponder: () => boolean;
/**
* Function to decide whether the responder should respond to a start
* (thouch) event.
*
* @private
* @returns {boolean}
*/
_onStartShouldSetPanResponder() {
return typeof this.props.onPress === 'function';
}
/**
* Restores the last applied transform when the component is mounted, or
* a new stream is about to be rendered.
*
* @param {string} streamId - The stream id to restore transform for.
* @private
* @returns {void}
*/
_restoreTransform(streamId) {
const savedTransform = this._getSavedTransform(streamId);
if (savedTransform) {
this.setState({
transform: savedTransform
});
}
}
/**
* Stores/saves the a transform when the component is destroyed, or a
* new stream is about to be rendered.
*
* @param {string} streamId - The stream id associated with the transform.
* @param {Object} transform - The {@Transform} to save.
* @private
* @returns {void}
*/
_storeTransform(streamId, transform) {
const { _onUnmount, enabled } = this.props;
if (enabled) {
_onUnmount(streamId, transform);
}
}
}
/**
* Maps dispatching of some action to React component props.
*
* @param {Function} dispatch - Redux action dispatcher.
* @private
* @returns {{
* _onUnmount: Function
* }}
*/
function _mapDispatchToProps(dispatch: Dispatch<any>) {
return {
/**
* Dispatches actions to store the last applied transform to a video.
*
* @param {string} streamId - The ID of the stream.
* @param {Transform} transform - The last applied transform.
* @private
* @returns {void}
*/
_onUnmount(streamId, transform) {
dispatch(storeVideoTransform(streamId, transform));
}
};
}
/**
* Maps (parts of) the redux state to the component's props.
*
* @param {Object} state - The redux state.
* @private
* @returns {{
* _transforms: Object
* }}
*/
function _mapStateToProps(state) {
return {
/**
* The stored transforms retrieved from Redux to be initially applied to
* different streams.
*
* @private
* @type {Object}
*/
_transforms: state['features/base/media'].video.transforms
};
}
export default connect(_mapStateToProps, _mapDispatchToProps)(VideoTransform);
|
src/svg-icons/hardware/keyboard.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboard = (props) => (
<SvgIcon {...props}>
<path d="M20 5H4c-1.1 0-1.99.9-1.99 2L2 17c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-9 3h2v2h-2V8zm0 3h2v2h-2v-2zM8 8h2v2H8V8zm0 3h2v2H8v-2zm-1 2H5v-2h2v2zm0-3H5V8h2v2zm9 7H8v-2h8v2zm0-4h-2v-2h2v2zm0-3h-2V8h2v2zm3 3h-2v-2h2v2zm0-3h-2V8h2v2z"/>
</SvgIcon>
);
HardwareKeyboard = pure(HardwareKeyboard);
HardwareKeyboard.displayName = 'HardwareKeyboard';
export default HardwareKeyboard;
|
shared/components/Main/Payment/Payment.js | KCPSoftware/KCPS-React-Starterkit | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getPayment } from '../../../actions/orderActions';
import { Redirect } from 'react-router';
import { paymentStatus } from '../../../utils/enums/paymentStatus';
import Loading from '../../SubComponents/Loading';
import { updateMeeting } from '../../../actions/calenderActions';
import Link from 'react-router-dom/Link';
const queryString = require('query-string');
import { changeTaxRulingState } from "../../../actions/userActions";
import { taxRulingState } from "../../../utils/enums/taxRulingState";
@connect(store => ({
isLoading: store.payment.isLoading,
paymentStatus: store.payment.paymentStatus,
email: store.user.data.email,
}))
class Payment extends Component {
constructor(props) {
super(props);
this.state = { payment: true }
}
componentDidMount() {
const parsed = queryString.parse(this.props.location.search);
if (parsed.package) {
this.setState({
package: parsed.package
})
this.props.dispatch(getPayment(true));
} else {
if (localStorage.getItem('paymentId') !== null) {
this.props.dispatch(getPayment());
} else {
this.setState({
payment: false
})
}
}
}
updateEvent() {
this.props.dispatch(updateMeeting(localStorage.getItem('formValues')));
}
getPaymentStatus() {
let status;
if (this.state.package) {
status = this.state.package;
} else {
status = this.props.paymentStatus;
}
switch (status) {
case 'taxAdvice':
this.updateEvent();
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Dear Client, <br />
Thank you for the payment. Via an e-mail you will receive a confirmation of the meeting and further details regarding the tax filing process.
You can start with the tax questionnaire via the button below.</span></p>
{this.props.email ? <Link to="/taxReturn">RETURN TO ACTION BAR</Link> : <a href="http://www.ttmtax.nl">RETURN TO WEBSITE</a>}</div>
)
case 'taxReturnWithAppointment':
this.updateEvent();
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Thank you for your payment. Your appointment is booked and you can continue with your questionnaire.
You will receive an e-mail shortly with the details of your appointment, you can also view your upcoming appointments on the overview page.</span></p>
<Link to="/taxReturn">RETURN TO QUESTIONNAIRE</Link></div>)
case 'taxReturnWithoutAppointment':
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Thank you for your payment. We will review your questionnaire and give feedback if necessary.</span></p>
<Link to="/taxReturn">RETURN TO ACTION BAR</Link></div>)
case 'taxRuling':
this.props.dispatch(changeTaxRulingState(taxRulingState.readyToReview))
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Thank you for your payment. We will review your questionnaire and give feedback if necessary.</span></p>
<Link to="/">Return to overview</Link></div>)
case 'taxReturnPlusPartnerWithAppointment':
this.updateEvent();
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Thank you for your payment. Your appointment is booked and you can continue with your questionnaire.
You will receive an e-mail shortly with the details of your appointment, you can also view your upcoming appointments on the overview page.</span></p>
<Link to="/taxReturn">RETURN TO QUESTIONNAIRE</Link></div>)
case 'taxReturnPlusPartnerWithoutAppointment':
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Thank you for your payment. We will review your questionnaire and give feedback if necessary.</span></p>
<Link to="/taxReturn">RETURN TO ACTION BAR</Link></div>)
case 'taxReturnProvisionalWithAppointment':
this.updateEvent();
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Thank you for your payment. Your appointment is booked and you can continue with your questionnaire.
You will receive an e-mail shortly with the details of your appointment, you can also view your upcoming appointments on the overview page.</span></p>
<Link to="/taxReturn">RETURN TO QUESTIONNAIRE</Link></div>)
case 'taxReturnProvisionalWithoutAppointment':
return (<div>
<p className="title">Payment Accepted</p>
<i className="fa fa-check-circle-o" aria-hidden="true"></i>
<p className="payment-text"> <span>Thank you for your payment. We will review your questionnaire and give feedback if necessary.</span></p>
<Link to="/taxReturn">RETURN TO ACTION BAR</Link></div>)
case 'expired':
return (<div>
<p className="title">Payment expired</p>
<i className="fa fa-times" aria-hidden="true"></i>
<p className="payment-text"> <span>Your payment has expired. Your appointment/tax-return has not been created. Please retry to complete your payment</span></p>
<Link to="/taxReturn">RETURN TO ACTION BAR</Link></div>)
case 'cancelled':
return (<div>
<p className="title">Payment cancelled</p>
<i className="fa fa-times" aria-hidden="true"></i>
<p className="payment-text"> <span>Your payment has been cancelled. Your appointment/tax-return has not been created. Please retry to complete your payment</span></p>
<Link to="/taxReturn">RETURN TO ACTION BAR</Link></div>)
case 'open':
return (<div>
<p className="title">Payment not complete</p>
<i className="fa fa-times" aria-hidden="true"></i>
<p className="payment-text"> <span>Your appointment/tax-return has not been created. Please retry to complete your payment</span></p>
<Link to="/taxReturn">RETURN TO ACTION BAR</Link></div>)
default:
return (<div>
<p className="title">Payment not complete</p>
<i className="fa fa-times" aria-hidden="true"></i>
<p className="payment-text"> <span>Your appointment/tax-return has not been created. Please retry to complete your payment</span></p>
<Link to="/taxReturn">RETURN TO ACTION BAR</Link></div>)
}
}
render() {
if (this.props.isLoading) {
if (!this.state.payment) {
return <div className="payment-information-container">
<p className="title">Payment not complete</p>
<i className="fa fa-times" aria-hidden="true"></i>
<p> <span>Please try again via the client portal.</span></p>
<Link to="/taxReturn">Return to questionnaire</Link></div>;
}
return <Loading />;
}
return (
<div className="payment-information-container">
{this.getPaymentStatus()}
</div>
);
}
}
export default Payment;
|
fields/types/select/SelectColumn.js | michaelerobertsjr/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var SelectColumn = React.createClass({
displayName: 'SelectColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
const option = this.props.col.field.ops.filter(i => i.value === value)[0];
return option ? option.label : null;
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = SelectColumn;
|
frontend/src/Components/Form/CaptchaInputConnector.js | geogolem/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { getCaptchaCookie, refreshCaptcha, resetCaptcha } from 'Store/Actions/captchaActions';
import CaptchaInput from './CaptchaInput';
function createMapStateToProps() {
return createSelector(
(state) => state.captcha,
(captcha) => {
return captcha;
}
);
}
const mapDispatchToProps = {
refreshCaptcha,
getCaptchaCookie,
resetCaptcha
};
class CaptchaInputConnector extends Component {
//
// Lifecycle
componentDidUpdate(prevProps) {
const {
name,
token,
onChange
} = this.props;
if (token && token !== prevProps.token) {
onChange({ name, value: token });
}
}
componentWillUnmount = () => {
this.props.resetCaptcha();
}
//
// Listeners
onRefreshPress = () => {
const {
provider,
providerData
} = this.props;
this.props.refreshCaptcha({ provider, providerData });
}
onCaptchaChange = (captchaResponse) => {
// If the captcha has expired `captchaResponse` will be null.
// In the event it's null don't try to get the captchaCookie.
// TODO: Should we clear the cookie? or reset the captcha?
if (!captchaResponse) {
return;
}
const {
provider,
providerData
} = this.props;
this.props.getCaptchaCookie({ provider, providerData, captchaResponse });
}
//
// Render
render() {
return (
<CaptchaInput
{...this.props}
onRefreshPress={this.onRefreshPress}
onCaptchaChange={this.onCaptchaChange}
/>
);
}
}
CaptchaInputConnector.propTypes = {
provider: PropTypes.string.isRequired,
providerData: PropTypes.object.isRequired,
name: PropTypes.string.isRequired,
token: PropTypes.string,
onChange: PropTypes.func.isRequired,
refreshCaptcha: PropTypes.func.isRequired,
getCaptchaCookie: PropTypes.func.isRequired,
resetCaptcha: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, mapDispatchToProps)(CaptchaInputConnector);
|
src/containers/TeamAbout/index.js | JohnPaulHarold/ReactExample | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import {
getTeamRequested
} from '../../logic/actions/';
import {TeamCrest} from '../../components/';
class TeamAbout extends Component {
componentWillMount() {
const {
match: {
params: {
id,
},
},
getTeamById,
} = this.props;
getTeamById(id);
}
render() {
const {
teamAbout: {
crestUrl: url,
code,
name,
squadMarketValue,
},
} = this.props;
const crestUrl = url !== '' ? url : '';
return (
<div>
<h2>Team About</h2>
<TeamCrest crest={crestUrl} teamName={name}/>
<p>{code}</p>
<p>{name}</p>
<p>{squadMarketValue}</p>
</div>
);
}
}
export const mapStateToProps = (state) => {
return {
teamAbout: state.teamAbout,
};
};
export const mapDispatchToProps = (dispatch) => {
return {
getTeamById: (id) => {
return dispatch(getTeamRequested(id));
}
};
};
TeamAbout.propTypes = {
teamAbout: PropTypes.object,
dispatch: PropTypes.func,
params: PropTypes.object,
getTeamById: PropTypes.func,
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(TeamAbout);
|
src/components/common/stat/HoverBar.js | tidepool-org/viz | import PropTypes from 'prop-types';
import React from 'react';
import { Bar, Rect } from 'victory';
import _ from 'lodash';
import colors from '../../../styles/colors.css';
export const HoverBar = props => {
const {
barSpacing,
barWidth,
chartLabelWidth,
cornerRadius,
domain,
index,
scale = {
x: _.noop,
y: _.noop,
},
width,
y,
} = props;
const barGridWidth = barWidth / 6;
const barGridRadius = _.get(cornerRadius, 'top', 2);
const widthCorrection = (width - chartLabelWidth) / width;
return (
<g className="HoverBar">
<g className="HoverBarTarget" pointerEvents="all">
<Rect
{...props}
x={0}
y={scale.x(index + 1) - (barWidth / 2) - (barSpacing / 2)}
rx={barGridRadius}
ry={barGridRadius}
width={scale.y(domain.x[1])}
height={barWidth + barSpacing}
style={{
stroke: 'transparent',
fill: 'transparent',
}}
/>
</g>
<g className="barBg" pointerEvents="none">
<Rect
{...props}
x={0}
y={scale.x(index + 1) - (barGridWidth / 2)}
rx={barGridRadius}
ry={barGridRadius}
width={scale.y(domain.x[1]) - chartLabelWidth}
height={barGridWidth}
style={{
stroke: 'transparent',
fill: colors.axis,
}}
/>
</g>
<g pointerEvents="none">
<Bar
{...props}
width={scale.y(domain.x[1]) - chartLabelWidth}
y={y * widthCorrection}
/>
</g>
</g>
);
};
HoverBar.propTypes = {
chartLabelWidth: PropTypes.number,
domain: PropTypes.object.isRequired,
scale: PropTypes.object,
y: PropTypes.number,
};
HoverBar.displayName = 'HoverBar';
export default HoverBar;
|
components/Form/Star/Star.story.js | rdjpalmer/bloom | import React from 'react';
import { storiesOf } from '@storybook/react';
import { withKnobs, boolean } from '@storybook/addon-knobs';
import Star from './Star';
const stories = storiesOf('FormComponents', module);
stories.addDecorator(withKnobs);
stories.add('Star', () => (
<Star checked={ boolean('Checked', false) } />
));
|
docs/src/app/components/pages/components/Divider/ExampleForm.js | spiermar/material-ui | import React from 'react';
import Divider from 'material-ui/Divider';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
const style = {
marginLeft: 20,
};
const DividerExampleForm = () => (
<Paper zDepth={2}>
<TextField hintText="First name" style={style} underlineShow={false} />
<Divider />
<TextField hintText="Middle name" style={style} underlineShow={false} />
<Divider />
<TextField hintText="Last name" style={style} underlineShow={false} />
<Divider />
<TextField hintText="Email address" style={style} underlineShow={false} />
<Divider />
</Paper>
);
export default DividerExampleForm;
|
app/js/index.js | mattiaslundberg/typer | import '../style/main.scss'
import React from 'react'
import ReactDOM from 'react-dom'
import App from './app'
ReactDOM.render(<App />, document.getElementById('root'))
|
docs/src/app/components/pages/components/FloatingActionButton/Page.js | spiermar/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 floatingButtonReadmeText from './README';
import floatingButtonExampleSimpleCode from '!raw!./ExampleSimple';
import FloatingButtonExampleSimple from './ExampleSimple';
import floatingButtonCode from '!raw!material-ui/FloatingActionButton/FloatingActionButton';
const descriptions = {
simple: 'Default size and `mini` FABs, in primary (default), `secondary` and `disabled` colors.',
};
const FloatingActionButtonPage = () => (
<div>
<Title render={(previousTitle) => `Floating Action Button - ${previousTitle}`} />
<MarkdownElement text={floatingButtonReadmeText} />
<CodeExample description={descriptions.simple} code={floatingButtonExampleSimpleCode}>
<FloatingButtonExampleSimple />
</CodeExample>
<PropTypeDescription code={floatingButtonCode} />
</div>
);
export default FloatingActionButtonPage;
|
src/components/DevTool/index.js | urfonline/frontend | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
const DevTools = createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q"
defaultIsVisible={false}
>
<LogMonitor theme="tomorrow" />
</DockMonitor>,
);
export default DevTools;
|
src/@ui/Chip/Chip.stories.js | NewSpring/Apollos | import React from 'react';
import { storiesOf } from '@storybook/react-native';
import FlexedView from '@ui/FlexedView';
import Chip from './';
storiesOf('Chip', module)
.add('default', () => (
<FlexedView style={{ flexWrap: 'wrap', flexDirection: 'row' }}>
<Chip
onPress={() => {}}
title="I'm just a poor chip"
/>
<Chip
onPress={() => {}}
icon="close"
title="I need no sympathy"
/>
<Chip
onPress={() => {}}
selected
title="Easy come"
/>
<Chip
onPress={() => {}}
icon="close"
selected
title="Easy go"
/>
<Chip
onPress={() => {}}
icon="arrow-up"
title="Litte high"
/>
<Chip
onPress={() => {}}
type="secondary"
icon="arrow-down"
title="Litte low"
/>
<Chip
title="📍💨?"
/>
<Chip
selected
title="¯\_(ツ)_/¯"
/>
</FlexedView>
));
|
assets/javascripts/kitten/components/form/checkbox-set/index.js | KissKissBankBank/kitten | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import classNames from 'classnames'
import { Checkbox } from '../../form/checkbox'
import { pxToRem } from '../../../helpers/utils/typography'
import { Label } from '../../form/label'
const StyledCheckboxSet = styled.fieldset`
margin: 0;
padding: 0;
border: 0;
display: flex;
flex-direction: column;
line-height: 1.3rem;
& > legend {
padding: 0;
}
.k-Form-CheckboxSet__label {
margin-bottom: ${pxToRem(10)};
}
.k-Form-CheckboxSet__checkbox {
margin: ${pxToRem(5)} 0;
&:first-of-type {
margin-top: 0;
}
&:last-of-type {
margin-bottom: 0;
}
}
`
export const CheckboxSet = ({
items,
disabled,
className,
name,
error,
label,
children,
...props
}) => (
<StyledCheckboxSet
className={classNames('k-Form-CheckboxSet', className)}
disabled={disabled}
{...props}
>
{label && (
<Label tag="legend" className="k-Form-CheckboxSet__label">
{label}
</Label>
)}
{children && !label && <legend>{children}</legend>}
{items.map(({ id, className, ...itemProps }) => (
<Checkbox
id={id}
error={error}
name={name}
key={id}
{...itemProps}
className={classNames('k-Form-CheckboxSet__checkbox', className)}
/>
))}
</StyledCheckboxSet>
)
CheckboxSet.propTypes = {
name: PropTypes.string.isRequired,
error: PropTypes.bool,
label: PropTypes.string,
items: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string,
id: PropTypes.string.isRequired,
defaultChecked: PropTypes.bool,
children: PropTypes.node,
}),
),
disabled: PropTypes.bool,
}
CheckboxSet.defaultProps = {
name: 'checkboxSet',
error: false,
label: null,
items: [
{
label: null,
children: null,
defaultChecked: true,
id: 'myCheckbox', // Replace by a real value
},
],
disabled: false,
}
|
app/javascript/mastodon/features/followers/index.js | corzntin/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import {
fetchAccount,
fetchFollowers,
expandFollowers,
} from '../../actions/accounts';
import { ScrollContainer } from 'react-router-scroll';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import HeaderContainer from '../account_timeline/containers/header_container';
import LoadMore from '../../components/load_more';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'followers', Number(props.params.accountId), 'items']),
hasMore: !!state.getIn(['user_lists', 'followers', Number(props.params.accountId), 'next']),
});
@connect(mapStateToProps)
export default class Followers extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchAccount(Number(this.props.params.accountId)));
this.props.dispatch(fetchFollowers(Number(this.props.params.accountId)));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(Number(nextProps.params.accountId)));
this.props.dispatch(fetchFollowers(Number(nextProps.params.accountId)));
}
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) {
this.props.dispatch(expandFollowers(Number(this.props.params.accountId)));
}
}
handleLoadMore = (e) => {
e.preventDefault();
this.props.dispatch(expandFollowers(Number(this.props.params.accountId)));
}
render () {
const { accountIds, hasMore } = this.props;
let loadMore = null;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
if (hasMore) {
loadMore = <LoadMore onClick={this.handleLoadMore} />;
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='followers'>
<div className='scrollable' onScroll={this.handleScroll}>
<div className='followers'>
<HeaderContainer accountId={this.props.params.accountId} />
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
{loadMore}
</div>
</div>
</ScrollContainer>
</Column>
);
}
}
|
src/js/components/icons/base/AccessAd.js | odedre/grommet-final | /**
* @description AccessAd SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M12.3018676,10.102852 C13.6209278,10.102852 14.6837926,11.172641 14.6837926,12.484777 C14.6837926,13.8003751 13.6209278,14.8701641 12.3018676,14.8701641 L11.6786896,14.8701641 L11.6786896,10.102852 L12.3018676,10.102852 L12.3018676,10.102852 Z M12.5442146,16.9543484 C15.0126921,16.9543484 17.0207102,14.9497924 17.0207102,12.484777 C17.0207102,10.0093753 15.0334647,8.0082814 12.5649872,8.0082814 L12.5372904,8.0082814 L9.79876912,8.0082814 L9.79876912,16.9578105 L12.5442146,16.9578105 L12.5442146,16.9543484 Z M8.87336291,16.9595283 L6.91381417,16.9595283 L6.91381417,15.7754901 L3.63174315,15.7754901 L2.8770053,16.9595283 L0,16.9595283 L6.42565804,8.00653714 L8.87336291,8.00653714 L8.87336291,16.9595283 L8.87336291,16.9595283 Z M6.92591824,13.9098051 L4.8625065,13.9098051 L6.92591824,10.7039002 L6.92591824,13.9098051 L6.92591824,13.9098051 Z M22.2620257,8 L21.9781335,8 L21.44497,8 L21.1610778,8 C22.4039718,9.23596978 23.1206265,10.9289368 23.1206265,12.6876837 C23.1206265,14.2490909 22.5597663,15.7412561 21.5661435,16.9252944 L21.8500358,16.9252944 L22.3347298,16.9252944 L22.6220841,16.9252944 C23.5049197,15.7100972 24,14.2213941 24,12.6876837 C24,10.9600957 23.3698978,9.29828759 22.2620257,8 M20.0102192,8 L19.726327,8 L19.1931635,8 L18.9092713,8 C20.1521653,9.23596978 20.86882,10.9289368 20.86882,12.6876837 C20.86882,14.2490909 20.3079598,15.7412561 19.314337,16.9252944 L19.5982293,16.9252944 L20.0829233,16.9252944 L20.3633534,16.9252944 C21.2531132,15.7100972 21.7481935,14.2213941 21.7481935,12.6876837 C21.7481935,10.9600957 21.1180913,9.29828759 20.0102192,8 M17.7584421,8 L17.4745499,8 L16.9344623,8 L16.6574942,8 C17.9003882,9.23596978 18.6101188,10.9289368 18.6101188,12.6876837 C18.6101188,14.2490909 18.0492585,15.7412561 17.06256,16.9252944 L17.3464522,16.9252944 L17.8276841,16.9252944 L18.1115763,16.9252944 C19.0013361,15.7100972 19.4894922,14.2213941 19.4894922,12.6876837 C19.4894922,10.9600957 18.8663142,9.29828759 17.7584421,8"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-access-ad`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'access-ad');
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 fillRule="evenodd" d="M12.3018676,10.102852 C13.6209278,10.102852 14.6837926,11.172641 14.6837926,12.484777 C14.6837926,13.8003751 13.6209278,14.8701641 12.3018676,14.8701641 L11.6786896,14.8701641 L11.6786896,10.102852 L12.3018676,10.102852 L12.3018676,10.102852 Z M12.5442146,16.9543484 C15.0126921,16.9543484 17.0207102,14.9497924 17.0207102,12.484777 C17.0207102,10.0093753 15.0334647,8.0082814 12.5649872,8.0082814 L12.5372904,8.0082814 L9.79876912,8.0082814 L9.79876912,16.9578105 L12.5442146,16.9578105 L12.5442146,16.9543484 Z M8.87336291,16.9595283 L6.91381417,16.9595283 L6.91381417,15.7754901 L3.63174315,15.7754901 L2.8770053,16.9595283 L0,16.9595283 L6.42565804,8.00653714 L8.87336291,8.00653714 L8.87336291,16.9595283 L8.87336291,16.9595283 Z M6.92591824,13.9098051 L4.8625065,13.9098051 L6.92591824,10.7039002 L6.92591824,13.9098051 L6.92591824,13.9098051 Z M22.2620257,8 L21.9781335,8 L21.44497,8 L21.1610778,8 C22.4039718,9.23596978 23.1206265,10.9289368 23.1206265,12.6876837 C23.1206265,14.2490909 22.5597663,15.7412561 21.5661435,16.9252944 L21.8500358,16.9252944 L22.3347298,16.9252944 L22.6220841,16.9252944 C23.5049197,15.7100972 24,14.2213941 24,12.6876837 C24,10.9600957 23.3698978,9.29828759 22.2620257,8 M20.0102192,8 L19.726327,8 L19.1931635,8 L18.9092713,8 C20.1521653,9.23596978 20.86882,10.9289368 20.86882,12.6876837 C20.86882,14.2490909 20.3079598,15.7412561 19.314337,16.9252944 L19.5982293,16.9252944 L20.0829233,16.9252944 L20.3633534,16.9252944 C21.2531132,15.7100972 21.7481935,14.2213941 21.7481935,12.6876837 C21.7481935,10.9600957 21.1180913,9.29828759 20.0102192,8 M17.7584421,8 L17.4745499,8 L16.9344623,8 L16.6574942,8 C17.9003882,9.23596978 18.6101188,10.9289368 18.6101188,12.6876837 C18.6101188,14.2490909 18.0492585,15.7412561 17.06256,16.9252944 L17.3464522,16.9252944 L17.8276841,16.9252944 L18.1115763,16.9252944 C19.0013361,15.7100972 19.4894922,14.2213941 19.4894922,12.6876837 C19.4894922,10.9600957 18.8663142,9.29828759 17.7584421,8"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'AccessAd';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
docs/src/pages/styles/basics/NestedStylesHook.js | lgollut/material-ui | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
const useStyles = makeStyles({
root: {
color: 'red',
'& p': {
margin: 0,
color: 'green',
'& span': {
color: 'blue',
},
},
},
});
export default function NestedStylesHook() {
const classes = useStyles();
return (
<div className={classes.root}>
This is red since it is inside the root.
<p>
This is green since it is inside the paragraph{' '}
<span>and this is blue since it is inside the span</span>
</p>
</div>
);
}
|
src/components/NotFound/NotFound.js | outlandishideas/kasia-boilerplate | /**
* # Not Found Container
*/
import React from 'react'
import { Link } from 'react-router'
import Helmet from 'react-helmet'
import styles from './NotFound.scss'
export default function NotFound () {
return (
<div className={styles.NotFound}>
<Helmet title='Not Found' />
<h2>Not Found</h2>
<p>The page you have requested was not found.</p>
<p>
<Link to='/'>Go to the Homepage.</Link>
</p>
</div>
)
}
|
src/components/Box/Overlay.js | falmar/react-adm-lte | import React from 'react'
const Overlay = () => {
return (
<div className='overlay'>
<i className='fa fa-refresh fa-spin' />
</div>
)
}
export default Overlay
|
src/components/overview.js | prexsa/m3specs | import React from 'react';
import { Card, Grid, Header, List } from 'semantic-ui-react';
import CarOption from './caroption';
const Overview = (props) => {
const options = props.equipment;
if(!options) {
return <div>Loading...</div>;
}
const equipment = options;
const modelName = equipment.name;
const cityMPG = equipment.MPG.city;
const hwyMPG = equipment.MPG.highway;
const horsepower = equipment.engine.horsepower;
const horsepowerRPM = equipment.engine.rpm.horsepower;
const torque = equipment.engine.torque;
const torqueRPM = equipment.engine.rpm.torque;
const optionsList = (equipment) => {
let optionsItem;
return optionsItem = equipment.options[0].options.map((carOption) => {
return <CarOption key={carOption.id} option={carOption.name} />;
})
}
return (
<div className='margins striped-background-color'>
<div className='container-width'>
<Header id='overview' className='header-spacing' as='h1' size='huge' color='black' textAlign='center' dividing={true}>OVERVIEW</Header>
<Grid columns={2} padded='horizontally'>
<Grid.Row>
<Grid.Column>
<Header as='h4' textAlign='center'>Specs</Header>
<List className='overview-positioning overview-specs' size='large'>
<List.Item><Header as='h3'>E46 M3</Header></List.Item>
<List.Item>{cityMPG} City / {hwyMPG} HWY</List.Item>
<List.Item>{modelName}</List.Item>
<List.Item>{horsepower} horsepower @ {horsepowerRPM}</List.Item>
<List.Item>{torque} lbs of torque @ {torqueRPM}</List.Item>
</List>
</Grid.Column>
<Grid.Column>
<Header as='h4' textAlign='center'>Features and Options</Header>
<List className='overview-positioning overview-fontsize'>
{optionsList(equipment)}
</List>
</Grid.Column>
</Grid.Row>
</Grid>
</div>
</div>
)
}
export default Overview; |
packages/react-error-overlay/src/components/ErrorOverlay.js | viankakrisna/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React, { Component } from 'react';
import { black } from '../styles';
import type { Node as ReactNode } from 'react';
const overlayStyle = {
position: 'relative',
display: 'inline-flex',
flexDirection: 'column',
height: '100%',
width: '1024px',
maxWidth: '100%',
overflowX: 'hidden',
overflowY: 'auto',
padding: '0.5rem',
boxSizing: 'border-box',
textAlign: 'left',
fontFamily: 'Consolas, Menlo, monospace',
fontSize: '11px',
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
lineHeight: 1.5,
color: black,
};
type Props = {|
children: ReactNode,
shortcutHandler?: (eventKey: string) => void,
|};
type State = {|
collapsed: boolean,
|};
class ErrorOverlay extends Component<Props, State> {
iframeWindow: window = null;
getIframeWindow = (element: ?HTMLDivElement) => {
if (element) {
const document = element.ownerDocument;
this.iframeWindow = document.defaultView;
}
};
onKeyDown = (e: KeyboardEvent) => {
const { shortcutHandler } = this.props;
if (shortcutHandler) {
shortcutHandler(e.key);
}
};
componentDidMount() {
window.addEventListener('keydown', this.onKeyDown);
if (this.iframeWindow) {
this.iframeWindow.addEventListener('keydown', this.onKeyDown);
}
}
componentWillUnmount() {
window.removeEventListener('keydown', this.onKeyDown);
if (this.iframeWindow) {
this.iframeWindow.removeEventListener('keydown', this.onKeyDown);
}
}
render() {
return (
<div style={overlayStyle} ref={this.getIframeWindow}>
{this.props.children}
</div>
);
}
}
export default ErrorOverlay;
|
src/react.js | aaronjensen/redux | import React from 'react';
import createAll from './components/createAll';
export const { Provider, Connector, provide, connect } = createAll(React);
|
src/svg-icons/av/playlist-add.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvPlaylistAdd = (props) => (
<SvgIcon {...props}>
<path d="M14 10H2v2h12v-2zm0-4H2v2h12V6zm4 8v-4h-2v4h-4v2h4v4h2v-4h4v-2h-4zM2 16h8v-2H2v2z"/>
</SvgIcon>
);
AvPlaylistAdd = pure(AvPlaylistAdd);
AvPlaylistAdd.displayName = 'AvPlaylistAdd';
AvPlaylistAdd.muiName = 'SvgIcon';
export default AvPlaylistAdd;
|
app/components/listItem/App.js | Artur93gev/React-lists | import React from 'react';
import styles from './sass/app.scss';
import { connect } from 'react-redux';
import { addToList } from '../../actions/add';
import { removeFromList } from '../../actions/remove';
import { updateListItemValue } from '../../actions/update';
import { ITEMTYPES as itemTypes } from './constants/index';
import { DragSource } from 'react-dnd';
// dragndrop functionality
const ListItemSource = {
beginDrag(props) {
return {
type: props.type,
data: props.item
};
}
};
function collect(connectDrag, monitor) {
return {
connectDragSource: connectDrag.dragSource(),
isDragging: monitor.isDragging()
};
}
class ListItem extends React.Component {
changeDetect(event) {
const selector = this.props.type;
const index = this.props.index;
if (this.props.isLast && event.target.value) {
this.add(selector);
}
if (event.target.value || (!event.target.value && index === 0)) {
this.update(index, selector, event);
}
if (!event.target.value && (index !== 0 || (index === 0 && !this.props.isLast))) {
this.remove(index, selector);
}
setTimeout(() => {
this.textInput.focus();
}, 0);
}
add(selector) {
const message = {
selector: selector,
};
this.props.addToList(message);
}
remove(index, selector) {
const message = {
index: index,
selector: selector,
};
this.props.removeFromList(message);
}
update(index, selector, event) {
const message = {
text: event.target.value,
index: index,
selector: selector,
};
this.props.updateListItemValue(message);
}
render() {
const { connectDragSource } = this.props;
return connectDragSource(
<li key={this.props.item.id}>
<input type="text" ref={(input) => { this.textInput = input; }} value={this.props.item.value} className={styles.input} onChange={(event) => { this.changeDetect(event); }} />
</li>
);
}
}
ListItem.defaultProps = {
item: {},
};
const mapStateToProps = (state, props) => ({
item: state.items[props.type].filter(data => data.id === props.item.id)[0],
index: state.items[props.type].map(data => data.id).indexOf(props.item.id),
isLast: state.items[props.type][state.items[props.type].length - 1].id === props.item.id
});
ListItem.propTypes = {
type: React.PropTypes.string.isRequired,
item: React.PropTypes.object.isRequired,
index: React.PropTypes.number.isRequired,
isLast: React.PropTypes.bool.isRequired,
removeFromList: React.PropTypes.func.isRequired,
addToList: React.PropTypes.func.isRequired,
updateListItemValue: React.PropTypes.func.isRequired,
connectDragSource: React.PropTypes.func.isRequired,
isDragging: React.PropTypes.bool.isRequired
};
ListItem = DragSource(itemTypes.listItem, ListItemSource, collect)(ListItem);
export default connect(mapStateToProps, { addToList, removeFromList, updateListItemValue })(ListItem);
|
js/barber/HaircutDetails.js | BarberHour/barber-hour | import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
StatusBar,
Image,
ScrollView,
TouchableNativeFeedback,
Alert,
Platform,
ActivityIndicator
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { connect } from 'react-redux';
import Button from '../common/Button';
import Toolbar from '../common/Toolbar';
import BarberIcon from '../common/BarberIcon';
import AppointmentCanceled from './AppointmentCanceled';
import formStyle from '../forms/style';
import { cancelAppointment, finishAppointment, getAppointment, setEditMode } from '../actions/appointments';
class HaircutDetails extends Component {
componentDidMount() {
if (this.props.edit) {
this.props.dispatch(setEditMode());
}
if (!this.props.appointment) {
this.props.dispatch(getAppointment('barber', this.props.appointmentId));
}
}
componentDidUpdate() {
if (this.props.form.success) {
this.props.navigator.replace({
component: AppointmentCanceled
});
}
}
_cancelSchedule() {
this.props.dispatch(cancelAppointment('barber', this.props.appointment.id));
}
_finishSchedule() {
this.props.dispatch(finishAppointment(this.props.appointment.id));
}
_confirmCancelSchedule() {
Alert.alert(
'Cancelar horário',
'Tem certeza que deseja cancelar esse horário?',
[
{text: 'Sim, cancelar horário', onPress: () => {this._cancelSchedule()} },
{text: 'Voltar', style: 'cancel'},
]
);
}
_confirmFinishSchedule() {
Alert.alert(
'Finalizar horário',
'Tem certeza que deseja finalizar esse horário?',
[
{text: 'Sim, finalizar horário', onPress: () => {this._finishSchedule()} },
{text: 'Voltar', style: 'cancel'},
]
);
}
_iconForStatus(status) {
switch (status) {
case 'finished':
return 'alarm-on';
case 'canceled':
return 'alarm-off';
case 'scheduled':
return 'alarm';
}
}
render() {
var { appointment, navigator, form } = this.props;
var loadingContent;
if (form.isLoading) {
loadingContent = <View style={styles.loading}><ActivityIndicator /></View>;
}
var content;
if (appointment) {
const { schedule, customer, appointment_services } = appointment;
const cancelButtonLabel = this.props.form.isLoading ? 'Cancelando...' : 'Cancelar';
const finishButtonLabel = this.props.form.isFinishing ? 'Finalizando...' : 'Finalizar';
var errorMessage;
if (this.props.form.error) {
errorMessage = <Text style={formStyle.errorBlock}>{this.props.form.error}</Text>;
}
content = (
<View>
<View style={styles.innerContainer}>
<Text style={styles.title} numberOfLines={1}>{customer.name}</Text>
<View style={styles.infoContainer}>
<Icon name='local-phone' size={24} color='#003459' style={styles.icon} />
<Text style={styles.info}>{customer.phone}</Text>
</View>
<View style={styles.infoContainer}>
<Text style={styles.info} numberOfLines={1}>{schedule.day_number} de {schedule.month_name} às {schedule.hour}</Text>
</View>
</View>
<View style={styles.infoContainer}>
<View style={styles.statusContainer}>
<Icon name={this._iconForStatus(appointment.status)} size={24} color='#003459' style={styles.icon} />
<Text>{appointment.translated_status}</Text>
</View>
</View>
<View style={styles.infoContainer}>
<Text style={[styles.info, styles.code]}>Código: #{appointment.id}</Text>
</View>
<View style={styles.separator} />
<View style={styles.innerContainer}>
{appointment_services.map((appointmentService) => {
const icon = appointmentService.service_name === 'Corte de Cabelo' ? 'scissor-4' : 'razor';
return(
<View key={appointmentService.id} style={styles.serviceContainer}>
<BarberIcon name={icon} size={24} color='#003459' style={styles.serviceIcon} />
<Text style={styles.price}>{appointmentService.service_name}: {appointmentService.service_price}</Text>
</View>
)
})}
</View>
{appointment.status === 'scheduled' ? (
<View>
<View style={styles.separator} />
<View style={styles.innerContainer}>
{errorMessage}
<Button
containerStyle={styles.button}
disabled={this.props.form.isLoading || this.props.form.isFinishing}
text={finishButtonLabel}
onPress={this._confirmFinishSchedule.bind(this)} />
<Button
outline
containerStyle={styles.button}
disabled={this.props.form.isLoading || this.props.form.isFinishing}
text={cancelButtonLabel}
onPress={this._confirmCancelSchedule.bind(this)} />
</View>
</View>
) : (<View />)}
</View>
);
}
return(
<View style={styles.container}>
<StatusBar backgroundColor='#C5C5C5' networkActivityIndicatorVisible={this.props.form.isLoading || this.props.form.isFinishing} />
<Toolbar backIcon border navigator={navigator} />
{loadingContent}
{content}
</View>
);
}
}
function select(store, ownProps) {
return {
form: store.appointments,
appointment: ownProps.appointment || store.appointments.appointments.find(a => a.id === ownProps.appointmentId)
};
}
export default connect(select)(HaircutDetails);
var styles = StyleSheet.create({
container: {
flex: 1,
flexDirection: 'column',
backgroundColor: 'white',
marginTop: Platform.OS === 'ios' ? 60 : 0
},
innerContainer: {
paddingTop: 10,
paddingBottom: 10,
paddingLeft: 20,
paddingRight: 20,
},
title: {
fontSize: 24,
textAlign: 'center',
color: '#111111'
},
info: {
fontSize: 16,
textAlign: 'center'
},
button: {
marginTop: 10,
marginBottom: 10,
},
separator: {
backgroundColor: '#DCDCDC',
height: 1,
},
infoContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
serviceIcon: {
marginRight: 20
},
icon: {
marginRight: 10
},
serviceContainer: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'center'
},
statusContainer: {
flexDirection: 'row',
marginTop: 5,
marginBottom: 10,
alignItems: 'center'
},
code: {
marginBottom: 10
},
loading: {
marginTop: 10
}
});
|
js/Login.js | mk007sg/threeSeaShells | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
AsyncStorage,
} from 'react-native';
//import {GoogleSignin, GoogleSigninButton} from 'react-native-google-signin';
import { Container, Content, Button, List, ListItem, InputGroup, Input, Icon } from 'native-base';
import {Actions} from 'react-native-router-flux';
export default class LoginComponent extends Component {
constructor(props) {
super(props);
console.log("Saving shit");
this.goFuckYourself();
console.log("Saved shit!");
}
async goFuckYourself() {
try {
await AsyncStorage.setItem("gerhard", "1");
await AsyncStorage.setItem("gareth", "1");
await AsyncStorage.setItem("michael", "2");
await AsyncStorage.setItem("anton", "3");
await AsyncStorage.setItem("gesa", "2");
await AsyncStorage.setItem("uwe", "2");
await AsyncStorage.setItem("marcin", "3");
await AsyncStorage.setItem("adrian", "2");
} catch (error) {
console.log("Be sadface.");
}
}
async buttonPress() {
var userState = await AsyncStorage.getItem(this.state.inputName);
if(userState == null) {
userState = '3';
}
Actions.nextDate(userState);
}
render() {
return (
<View style={styles.container}>
<Container>
<Content>
<InputGroup style={styles.input}>
<Icon name='ios-person' />
<Input
placeholder='NAME'
onChangeText={(txt) => this.setState({inputName: txt})}/>
</InputGroup>
<Button
style={styles.button}
onPress={this.buttonPress.bind(this)}> Enter </Button>
</Content>
</Container>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 2,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
paddingTop: 150
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
input: {
width: 250
},
button: {
flex: 1,
marginTop: 5
}
});
|
chat/chat/YOChat.js | wph1129/react-native-chat | import React from 'react';
import {
Animated,
InteractionManager,
Platform,
StyleSheet,
View,
Text,
} from 'react-native';
import DismissKeyboard from 'react-native-dismiss-keyboard';
import moment from 'moment';
import Actions from './Actions';
import Avatar from './Avatar';
import Bubble from './Bubble';
import MessageImage from './MessageImage';
import MessageText from './MessageText';
import Composer from './Composer';
import Day from './Day';
import InputToolbar from './InputToolbar';
import Message from './Message';
import MessageContainer from './MessageContainer';
import Send from './Send';
import Time from './Time';
// Min and max heights of ToolbarInput and Composer
// Needed for Composer auto grow and ScrollView animation
// TODO move these values to Constants.js (also with used colors #b2b2b2)
const MIN_COMPOSER_HEIGHT = Platform.select({
ios: 33,
android: 41,
});
const MAX_COMPOSER_HEIGHT = 100;
const MIN_INPUT_TOOLBAR_HEIGHT = 44;
class YOChat extends React.Component {
constructor(props) {
super(props);
// default values
this._isMounted = false;
this._keyboardHeight = 0;
this._bottomOffset = 0;
this._maxHeight = null;
this._touchStarted = false;
this._isFirstLayout = true;
this._isTypingDisabled = false;
this._locale = 'en';
this._messages = [];
this.state = {
isInitialized: false, // initialization will calculate maxHeight before rendering the chat
};
this.onTouchStart = this.onTouchStart.bind(this);
this.onTouchMove = this.onTouchMove.bind(this);
this.onTouchEnd = this.onTouchEnd.bind(this);
this.onKeyboardWillShow = this.onKeyboardWillShow.bind(this);
this.onKeyboardWillHide = this.onKeyboardWillHide.bind(this);
this.onKeyboardDidShow = this.onKeyboardDidShow.bind(this);
this.onKeyboardDidHide = this.onKeyboardDidHide.bind(this);
this.onType = this.onType.bind(this);
this.onSend = this.onSend.bind(this);
this.getLocale = this.getLocale.bind(this);
this.invertibleScrollViewProps = {
inverted: true,
keyboardShouldPersistTaps: true,
onTouchStart: this.onTouchStart,
onTouchMove: this.onTouchMove,
onTouchEnd: this.onTouchEnd,
onKeyboardWillShow: this.onKeyboardWillShow,
onKeyboardWillHide: this.onKeyboardWillHide,
onKeyboardDidShow: this.onKeyboardDidShow,
onKeyboardDidHide: this.onKeyboardDidHide,
};
}
static append(currentMessages = [], messages) {
if (!Array.isArray(messages)) {
messages = [messages];
}
return messages.concat(currentMessages);
}
static prepend(currentMessages = [], messages) {
if (!Array.isArray(messages)) {
messages = [messages];
}
return currentMessages.concat(messages);
}
getChildContext() {
return {
actionSheet: () => this._actionSheetRef,
getLocale: this.getLocale,
};
}
componentWillMount() {
this.setIsMounted(true);
this.initLocale();
this.initMessages(this.props.messages);
}
componentWillUnmount() {
this.setIsMounted(false);
}
componentWillReceiveProps(nextProps = {}) {
this.initMessages(nextProps.messages);
}
initLocale() {
if (this.props.locale === null || moment.locales().indexOf(this.props.locale) === -1) {
this.setLocale('en');
} else {
this.setLocale(this.props.locale);
}
}
initMessages(messages = []) {
this.setMessages(messages);
}
setLocale(locale) {
this._locale = locale;
}
getLocale() {
return this._locale;
}
setMessages(messages) {
this._messages = messages;
}
getMessages() {
return this._messages;
}
setMaxHeight(height) {
this._maxHeight = height;
}
getMaxHeight() {
return this._maxHeight;
}
setKeyboardHeight(height) {
this._keyboardHeight = height;
}
getKeyboardHeight() {
return this._keyboardHeight;
}
setBottomOffset(value) {
this._bottomOffset = value;
}
getBottomOffset() {
return this._bottomOffset;
}
setIsFirstLayout(value) {
this._isFirstLayout = value;
}
getIsFirstLayout() {
return this._isFirstLayout;
}
setIsTypingDisabled(value) {
this._isTypingDisabled = value;
}
getIsTypingDisabled() {
return this._isTypingDisabled;
}
setIsMounted(value) {
this._isMounted = value;
}
getIsMounted() {
return this._isMounted;
}
// TODO
// setMinInputToolbarHeight
getMinInputToolbarHeight() {
if (this.props.renderAccessory) {
return MIN_INPUT_TOOLBAR_HEIGHT * 2;
}
return MIN_INPUT_TOOLBAR_HEIGHT;
}
prepareMessagesContainerHeight(value) {
if (this.props.isAnimated === true) {
return new Animated.Value(value);
}
return value;
}
onKeyboardWillShow(e) {
this.setIsTypingDisabled(true);
this.setKeyboardHeight(e.endCoordinates ? e.endCoordinates.height : e.end.height);
this.setBottomOffset(this.props.bottomOffset);
const newMessagesContainerHeight = (this.getMaxHeight() - (this.state.composerHeight + (this.getMinInputToolbarHeight() - MIN_COMPOSER_HEIGHT))) - this.getKeyboardHeight() + this.getBottomOffset();
if (this.props.isAnimated === true) {
Animated.timing(this.state.messagesContainerHeight, {
toValue: newMessagesContainerHeight,
duration: 210,
}).start();
} else {
this.setState((previousState) => {
return {
messagesContainerHeight: newMessagesContainerHeight,
};
});
}
}
onKeyboardWillHide() {
this.setIsTypingDisabled(true);
this.setKeyboardHeight(0);
this.setBottomOffset(0);
const newMessagesContainerHeight = this.getMaxHeight() - (this.state.composerHeight + (this.getMinInputToolbarHeight() - MIN_COMPOSER_HEIGHT));
if (this.props.isAnimated === true) {
Animated.timing(this.state.messagesContainerHeight, {
toValue: newMessagesContainerHeight,
duration: 210,
}).start();
} else {
this.setState((previousState) => {
return {
messagesContainerHeight: newMessagesContainerHeight,
};
});
}
}
onKeyboardDidShow(e) {
if (Platform.OS === 'android') {
this.onKeyboardWillShow(e);
}
this.setIsTypingDisabled(false);
}
onKeyboardDidHide(e) {
if (Platform.OS === 'android') {
this.onKeyboardWillHide(e);
}
this.setIsTypingDisabled(false);
}
scrollToBottom(animated = true) {
this._messageContainerRef.scrollTo({
y: 0,
animated,
});
}
onTouchStart() {
this._touchStarted = true;
}
onTouchMove() {
this._touchStarted = false;
}
// handle Tap event to dismiss keyboard
onTouchEnd() {
if (this._touchStarted === true) {
DismissKeyboard();
}
this._touchStarted = false;
}
renderMessages() {
const AnimatedView = this.props.isAnimated === true ? Animated.View : View;
return (
<AnimatedView style={{
height: this.state.messagesContainerHeight,
}}>
<MessageContainer
{...this.props}
invertibleScrollViewProps={this.invertibleScrollViewProps}
messages={this.getMessages()}
ref={component => this._messageContainerRef = component}
/>
{this.renderChatFooter()}
</AnimatedView>
);
}
onSend(messages = [], shouldResetInputToolbar = false) {
if (!Array.isArray(messages)) {
messages = [messages];
}
messages = messages.map((message) => {
return {
...message,
user: this.props.user,
createdAt: new Date(),
_id: 'temp-id-' + Math.round(Math.random() * 1000000),
};
});
if (shouldResetInputToolbar === true) {
this.setIsTypingDisabled(true);
this.resetInputToolbar();
}
this.props.onSend(messages);
this.scrollToBottom();
if (shouldResetInputToolbar === true) {
setTimeout(() => {
if (this.getIsMounted() === true) {
this.setIsTypingDisabled(false);
}
}, 200);
}
}
resetInputToolbar() {
this.setState((previousState) => {
return {
text: '',
composerHeight: MIN_COMPOSER_HEIGHT,
messagesContainerHeight: this.prepareMessagesContainerHeight(this.getMaxHeight() - this.getMinInputToolbarHeight() - this.getKeyboardHeight() + this.getBottomOffset()),
};
});
}
calculateInputToolbarHeight(newComposerHeight) {
return newComposerHeight + (this.getMinInputToolbarHeight() - MIN_COMPOSER_HEIGHT);
}
onType(e) {
if (this.getIsTypingDisabled() === true) {
return;
}
let newComposerHeight = null;
if (e.nativeEvent && e.nativeEvent.contentSize) {
newComposerHeight = Math.max(MIN_COMPOSER_HEIGHT, Math.min(MAX_COMPOSER_HEIGHT, e.nativeEvent.contentSize.height));
} else {
newComposerHeight = MIN_COMPOSER_HEIGHT;
}
const newMessagesContainerHeight = this.getMaxHeight() - this.calculateInputToolbarHeight(newComposerHeight) - this.getKeyboardHeight() + this.getBottomOffset();
const newText = e.nativeEvent.text;
this.setState((previousState) => {
return {
text: newText,
composerHeight: newComposerHeight,
messagesContainerHeight: this.prepareMessagesContainerHeight(newMessagesContainerHeight),
};
});
}
renderInputToolbar() {
const inputToolbarProps = {
...this.props,
text: this.state.text,
composerHeight: Math.max(MIN_COMPOSER_HEIGHT, this.state.composerHeight),
onChange: this.onType,
onSend: this.onSend,
};
if (this.props.renderInputToolbar) {
return this.props.renderInputToolbar(inputToolbarProps);
}
return (
<InputToolbar
{...inputToolbarProps}
/>
);
}
renderChatFooter() {
if (this.props.renderChatFooter) {
const footerProps = {
...this.props,
};
return this.props.renderChatFooter(footerProps);
}
return null;
}
renderLoading() {
if (this.props.renderLoading) {
return this.props.renderLoading();
}
return null;
}
render() {
if (this.state.isInitialized === true) {
return (
<View>
<View
style={styles.container}
onLayout={(e) => {
if (Platform.OS === 'android') {
// fix an issue when keyboard is dismissing during the initialization
const layout = e.nativeEvent.layout;
if (this.getMaxHeight() !== layout.height && this.getIsFirstLayout() === true) {
this.setMaxHeight(layout.height);
this.setState({
messagesContainerHeight: this.prepareMessagesContainerHeight(this.getMaxHeight() - this.getMinInputToolbarHeight()),
});
}
}
if (this.getIsFirstLayout() === true) {
this.setIsFirstLayout(false);
}
}}
>
{this.renderMessages()}
{this.renderInputToolbar()}
</View>
</View>
);
}
return (
<View
style={styles.container}
onLayout={(e) => {
const layout = e.nativeEvent.layout;
this.setMaxHeight(layout.height);
InteractionManager.runAfterInteractions(() => {
this.setState({
isInitialized: true,
text: '',
composerHeight: MIN_COMPOSER_HEIGHT,
messagesContainerHeight: this.prepareMessagesContainerHeight(this.getMaxHeight() - this.getMinInputToolbarHeight()),
});
});
}}
>
{this.renderLoading()}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
YOChat.childContextTypes = {
actionSheet: React.PropTypes.func,
getLocale: React.PropTypes.func,
};
YOChat.defaultProps = {
messages: [],
onSend: () => {
},
locale: null,
isAnimated: Platform.select({
ios: true,
android: false,
}),
renderAccessory: null,
renderActions: null,
renderAvatar: null,
renderBubble: null,
renderFooter: null,
renderChatFooter: null,
renderMessageText: null,
renderMessageImage: null,
renderComposer: null,
renderCustomView: null,
renderDay: null,
renderInputToolbar: null,
renderLoading: null,
renderMessage: null,
renderSend: null,
renderTime: null,
user: {},
bottomOffset: 0,
};
YOChat.propTypes = {
messages: React.PropTypes.array,
onSend: React.PropTypes.func,
locale: React.PropTypes.string,
isAnimated: React.PropTypes.bool,
renderAccessory: React.PropTypes.func,
renderActions: React.PropTypes.func,
renderAvatar: React.PropTypes.func,
renderBubble: React.PropTypes.func,
renderFooter: React.PropTypes.func,
renderChatFooter: React.PropTypes.func,
renderMessageText: React.PropTypes.func,
renderMessageImage: React.PropTypes.func,
renderComposer: React.PropTypes.func,
renderCustomView: React.PropTypes.func,
renderDay: React.PropTypes.func,
renderInputToolbar: React.PropTypes.func,
renderLoading: React.PropTypes.func,
renderMessage: React.PropTypes.func,
renderSend: React.PropTypes.func,
renderTime: React.PropTypes.func,
user: React.PropTypes.object,
bottomOffset: React.PropTypes.number,
};
module.exports = {
YOChat,
Actions,
Avatar,
Bubble,
MessageImage,
MessageText,
Composer,
Day,
InputToolbar,
Message,
Send,
Time,
}; |
.history/src/instacelebs_20171001003039.js | oded-soffrin/gkm_viewer |
import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './store/configureStore';
require('./favicon.ico'); // Tell webpack to load favicon.ico
import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import InstaCelebs from './components/InstaCelebs/index'
import { getStats } from './actions/instaActions'
const store = configureStore();
store.dispatch(getStats())
render(
<Provider store={store}>
<InstaCelebs/>
</Provider>, document.getElementById('app')
);
|
src/package/plugins/slate-grid-plugin/GridButton.js | abobwhite/slate-editor | import React from 'react'
import FontAwesome from 'react-fontawesome'
import classnames from 'classnames'
import { Button} from '../../components/button'
import { appendGrid, hasGrid } from './GridUtils'
const GridButton = ({ state, onChange, className, style, type }) => (
<Button
style={style}
type={type}
onClick={e => onChange(appendGrid(state.change()))}
className={classnames(
'slate-grid-plugin--button',
{ active: hasGrid(state) },
className,
)}
>
<FontAwesome name="th" />
</Button>
)
export default GridButton
|
src/components/common/svg-icons/communication/call-end.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationCallEnd = (props) => (
<SvgIcon {...props}>
<path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"/>
</SvgIcon>
);
CommunicationCallEnd = pure(CommunicationCallEnd);
CommunicationCallEnd.displayName = 'CommunicationCallEnd';
CommunicationCallEnd.muiName = 'SvgIcon';
export default CommunicationCallEnd;
|
bear-api-koa/client/src/libs/component/index.js | thoughtbit/node-web-starter | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
class Component extends React.Component {
classNames(...args) {
return classnames(args);
}
className(...args) {
return this.classNames.apply(this, args.concat([this.props.className]));
}
style(args) {
return Object.assign({}, args, this.props.style);
}
}
Component.propTypes = {
className: PropTypes.string,
style: PropTypes.object
};
export default Component;
|
actor-apps/app-web/src/app/components/sidebar/RecentSection.react.js | yangchaogit/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import DialogActionCreators from 'actions/DialogActionCreators';
import DialogStore from 'stores/DialogStore';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import RecentSectionItem from './RecentSectionItem.react';
import CreateGroupModal from 'components/modals/CreateGroup.react';
import CreateGroupStore from 'stores/CreateGroupStore';
const ThemeManager = new Styles.ThemeManager();
const LoadDialogsScrollBottom = 100;
const getStateFromStore = () => {
return {
isCreateGroupModalOpen: CreateGroupStore.isModalOpen(),
dialogs: DialogStore.getAll()
};
};
class RecentSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStore();
DialogStore.addChangeListener(this.onChange);
CreateGroupStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
componentWillUnmount() {
DialogStore.removeChangeListener(this.onChange);
CreateGroupStore.removeChangeListener(this.onChange);
}
onChange = () => {
this.setState(getStateFromStore());
};
openCreateGroup = () => {
CreateGroupActionCreators.openModal();
};
onScroll = event => {
if (event.target.scrollHeight - event.target.scrollTop - event.target.clientHeight <= LoadDialogsScrollBottom) {
DialogActionCreators.onDialogsEnd();
}
};
render() {
let dialogs = _.map(this.state.dialogs, (dialog, index) => {
return (
<RecentSectionItem dialog={dialog} key={index}/>
);
}, this);
let createGroupModal;
if (this.state.isCreateGroupModalOpen) {
createGroupModal = <CreateGroupModal/>;
}
return (
<section className="sidebar__recent">
<ul className="sidebar__list sidebar__list--recent" onScroll={this.onScroll}>
{dialogs}
</ul>
<footer>
<RaisedButton label="Create group" onClick={this.openCreateGroup} style={{width: '100%'}}/>
{createGroupModal}
</footer>
</section>
);
}
}
export default RecentSection;
|
app/containers/NotFoundPage/index.js | gihrig/react-boilerplate-logic | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import messages from './messages';
export default function NotFound() {
return (
<article>
<H1>
<FormattedMessage {...messages.header} />
</H1>
</article>
);
}
|
admin/client/components/FooterBar.js | Tangcuyu/keystone | import React from 'react';
import blacklist from 'blacklist';
var FooterBar = React.createClass({
propTypes: {
style: React.PropTypes.object,
},
getDefaultProps () {
return {
style: {},
};
},
getInitialState () {
return {
position: 'relative',
width: 'auto',
height: 'auto',
top: 0,
};
},
componentDidMount () {
// Bail in IE8 because React doesn't support the onScroll event in that browser
// Conveniently (!) IE8 doesn't have window.getComputedStyle which we also use here
if (!window.getComputedStyle) return;
var footer = this.refs.footer;
this.windowSize = this.getWindowSize();
var footerStyle = window.getComputedStyle(footer);
this.footerSize = {
x: footer.offsetWidth,
y: footer.offsetHeight + parseInt(footerStyle.marginTop || '0'),
};
window.addEventListener('scroll', this.recalcPosition, false);
window.addEventListener('resize', this.recalcPosition, false);
this.recalcPosition();
},
getWindowSize () {
return {
x: window.innerWidth,
y: window.innerHeight,
};
},
recalcPosition () {
var wrapper = this.refs.wrapper;
this.footerSize.x = wrapper.offsetWidth;
var offsetTop = 0;
var offsetEl = wrapper;
while (offsetEl) {
offsetTop += offsetEl.offsetTop;
offsetEl = offsetEl.offsetParent;
}
var maxY = offsetTop + this.footerSize.y;
var viewY = window.scrollY + window.innerHeight;
var newSize = this.getWindowSize();
var sizeChanged = (newSize.x !== this.windowSize.x || newSize.y !== this.windowSize.y);
this.windowSize = newSize;
var newState = {
width: this.footerSize.x,
height: this.footerSize.y,
};
if (viewY > maxY && (sizeChanged || this.mode !== 'inline')) {
this.mode = 'inline';
newState.top = 0;
newState.position = 'absolute';
this.setState(newState);
} else if (viewY <= maxY && (sizeChanged || this.mode !== 'fixed')) {
this.mode = 'fixed';
newState.top = window.innerHeight - this.footerSize.y;
newState.position = 'fixed';
this.setState(newState);
}
},
render () {
var wrapperStyle = {
height: this.state.height,
marginTop: 60,
position: 'relative',
};
var footerProps = blacklist(this.props, 'children', 'style');
var footerStyle = Object.assign({}, this.props.style, {
position: this.state.position,
top: this.state.top,
width: this.state.width,
height: this.state.height,
});
return (
<div ref="wrapper" style={wrapperStyle}>
<div ref="footer" style={footerStyle} {...footerProps}>{this.props.children}</div>
</div>
);
},
});
module.exports = FooterBar;
|
frontend/jqwidgets/jqwidgets-react/react_jqxknob.js | yevgeny-sergeyev/nexl-js | /*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxKnob extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['allowValueChangeOnClick','allowValueChangeOnDrag','allowValueChangeOnMouseWheel','changing','dragEndAngle','dragStartAngle','disabled','dial','endAngle','height','labels','marks','min','max','progressBar','pointer','pointerGrabAction','rotation','startAngle','spinner','style','step','snapToStep','value','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxKnob(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxKnob('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxKnob(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
allowValueChangeOnClick(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('allowValueChangeOnClick', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('allowValueChangeOnClick');
}
};
allowValueChangeOnDrag(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('allowValueChangeOnDrag', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('allowValueChangeOnDrag');
}
};
allowValueChangeOnMouseWheel(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('allowValueChangeOnMouseWheel', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('allowValueChangeOnMouseWheel');
}
};
changing(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('changing', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('changing');
}
};
dragEndAngle(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('dragEndAngle', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('dragEndAngle');
}
};
dragStartAngle(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('dragStartAngle', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('dragStartAngle');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('disabled');
}
};
dial(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('dial', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('dial');
}
};
endAngle(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('endAngle', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('endAngle');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('height', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('height');
}
};
labels(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('labels', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('labels');
}
};
marks(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('marks', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('marks');
}
};
min(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('min', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('min');
}
};
max(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('max', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('max');
}
};
progressBar(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('progressBar', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('progressBar');
}
};
pointer(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('pointer', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('pointer');
}
};
pointerGrabAction(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('pointerGrabAction', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('pointerGrabAction');
}
};
rotation(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('rotation', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('rotation');
}
};
startAngle(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('startAngle', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('startAngle');
}
};
spinner(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('spinner', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('spinner');
}
};
style(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('style', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('style');
}
};
step(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('step', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('step');
}
};
snapToStep(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('snapToStep', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('snapToStep');
}
};
value(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('value', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('value');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxKnob('width', arg)
} else {
return JQXLite(this.componentSelector).jqxKnob('width');
}
};
destroy() {
JQXLite(this.componentSelector).jqxKnob('destroy');
};
val(value) {
if (value !== undefined) {
JQXLite(this.componentSelector).jqxKnob('val', value)
} else {
return JQXLite(this.componentSelector).jqxKnob('val');
}
};
render() {
let id = 'jqxKnob' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
src/index.js | jackiechoi/redux_weather_app | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import ReduxPromise from 'redux-promise';
import App from './components/app';
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(ReduxPromise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<App />
</Provider>
, document.querySelector('.container')); |
src/svg-icons/action/feedback.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFeedback = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-7 12h-2v-2h2v2zm0-4h-2V6h2v4z"/>
</SvgIcon>
);
ActionFeedback = pure(ActionFeedback);
ActionFeedback.displayName = 'ActionFeedback';
export default ActionFeedback;
|
Veo/index.android.js | JGMorgan/Veo | 'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Dimensions,
StyleSheet,
Text,
Vibration,
TouchableHighlight,
View
} from 'react-native';
import Camera from 'react-native-camera';
var pattern = [0, 500, 200, 500];
class Veo extends Component {
render() {
return (
<View style={styles.container}>
<Camera
captureTarget={Camera.constants.CaptureTarget.memory}
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}>
<Text style={styles.capture} onPress={this.takePicture.bind(this)}>[CAPTURE]</Text>
</Camera>
</View>
);
}
takePicture() {
this.camera.capture().then((data) => {
console.log(data);
/*app.models.predict(Clarifai.GENERAL_MODEL, {base64: data['data']}).then(
function(response) {
console.log(response);
},
function(err) {
// there was an error
}
);*/
return fetch('http://45.33.5.10:5000/', {
method: 'POST',
headers: {
'Accept': '*/*',
'Content-Type': 'application/json',
},
body: JSON.stringify({
Image: data['data'],
})
})
}).then((response) => {
console.log(JSON.stringify(response).includes('"content-length":["4"]'));
/*real hackathon code who coding*/
if (JSON.stringify(response).includes('"content-length":["4"]')) {
for (var i = 0; i < 5; i++) {
Vibration.vibrate(pattern);
}
}
})
.catch((error) => {console.log(error); return error});
};
};
const styles = StyleSheet.create({
container: {
flex: 1
},
preview: {
flex: 1,
justifyContent: 'flex-end',
alignItems: 'center',
height: Dimensions.get('window').height,
width: Dimensions.get('window').width
},
capture: {
flex: 0,
backgroundColor: '#fff',
borderRadius: 5,
color: '#000',
padding: 10,
margin: 40
}
});
AppRegistry.registerComponent('Veo', () => Veo);
|
node_modules/react-native/local-cli/server/middleware/heapCapture/src/heapCapture.js | hpdmitriy/Bjj4All | /**
* Copyright (c) 2016-present, Facebook, 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.
*/
'use strict';
/*eslint no-console-disallow: "off"*/
/*global preLoadedCapture:true*/
import ReactDOM from 'react-dom';
import React from 'react';
import {
Aggrow,
AggrowData,
AggrowTable,
StringInterner,
StackRegistry,
} from './index.js';
function RefVisitor(refs, id) {
this.refs = refs;
this.id = id;
}
RefVisitor.prototype = {
moveToEdge: function moveToEdge(name) {
const ref = this.refs[this.id];
if (ref && ref.edges) {
const edges = ref.edges;
for (const edgeId in edges) {
if (edges[edgeId] === name) {
this.id = edgeId;
return this;
}
}
}
this.id = undefined;
return this;
},
moveToFirst: function moveToFirst(callback) {
const ref = this.refs[this.id];
if (ref && ref.edges) {
const edges = ref.edges;
for (const edgeId in edges) {
this.id = edgeId;
if (callback(edges[edgeId], this)) {
return this;
}
}
}
this.id = undefined;
return this;
},
forEachEdge: function forEachEdge(callback) {
const ref = this.refs[this.id];
if (ref && ref.edges) {
const edges = ref.edges;
const visitor = new RefVisitor(this.refs, undefined);
for (const edgeId in edges) {
visitor.id = edgeId;
callback(edges[edgeId], visitor);
}
}
},
getType: function getType() {
const ref = this.refs[this.id];
if (ref) {
return ref.type;
}
return undefined;
},
getRef: function getRef() {
return this.refs[this.id];
},
clone: function clone() {
return new RefVisitor(this.refs, this.id);
},
isDefined: function isDefined() {
return !!this.id;
},
getValue: function getValue() {
const ref = this.refs[this.id];
if (ref) {
if (ref.type === 'string') {
if (ref.value) {
return ref.value;
} else {
const rope = [];
this.forEachEdge((name, visitor) => {
if (name && name.startsWith('[') && name.endsWith(']')) {
const index = parseInt(name.substring(1, name.length - 1), 10);
rope[index] = visitor.getValue();
}
});
return rope.join('');
}
} else if (ref.type === 'ScriptExecutable'
|| ref.type === 'EvalExecutable'
|| ref.type === 'ProgramExecutable') {
return ref.value.url + ':' + ref.value.line + ':' + ref.value.col;
} else if (ref.type === 'FunctionExecutable') {
return ref.value.name + '@' + ref.value.url + ':' + ref.value.line + ':' + ref.value.col;
} else if (ref.type === 'NativeExecutable') {
return ref.value.function + ' ' + ref.value.constructor + ' ' + ref.value.name;
} else if (ref.type === 'Function') {
const executable = this.clone().moveToEdge('@Executable');
if (executable.id) {
return executable.getRef().type + ' ' + executable.getValue();
}
}
}
return '#none';
}
};
function forEachRef(refs, callback) {
const visitor = new RefVisitor(refs, undefined);
for (const id in refs) {
visitor.id = id;
callback(visitor);
}
}
function firstRef(refs, callback) {
for (const id in refs) {
const ref = refs[id];
if (callback(id, ref)) {
return new RefVisitor(refs, id);
}
}
return new RefVisitor(refs, undefined);
}
function getInternalInstanceName(visitor) {
const type = visitor.clone().moveToEdge('_currentElement').moveToEdge('type');
if (type.getType() === 'string') { // element.type is string
return type.getValue();
} else if (type.getType() === 'Function') { // element.type is function
const displayName = type.clone().moveToEdge('displayName');
if (displayName.isDefined()) {
return displayName.getValue(); // element.type.displayName
}
const name = type.clone().moveToEdge('name');
if (name.isDefined()) {
return name.getValue(); // element.type.name
}
type.moveToEdge('@Executable');
if (type.getType() === 'FunctionExecutable') {
return type.getRef().value.name; // element.type symbolicated name
}
}
return '#unknown';
}
function buildReactComponentTree(visitor, registry, strings) {
const ref = visitor.getRef();
if (ref.reactTree || ref.reactParent === undefined) {
return; // has one or doesn't need one
}
const parentVisitor = ref.reactParent;
if (parentVisitor === null) {
ref.reactTree = registry.insert(registry.root, strings.intern(getInternalInstanceName(visitor)));
} else if (parentVisitor) {
const parentRef = parentVisitor.getRef();
buildReactComponentTree(parentVisitor, registry, strings);
let relativeName = getInternalInstanceName(visitor);
if (ref.reactKey) {
relativeName = ref.reactKey + ': ' + relativeName;
}
ref.reactTree = registry.insert(parentRef.reactTree, strings.intern(relativeName));
} else {
throw 'non react instance parent of react instance';
}
}
function markReactComponentTree(refs, registry, strings) {
// annotate all refs that are react internal instances with their parent and name
// ref.reactParent = visitor that points to parent instance,
// null if we know it's an instance, but don't have a parent yet
// ref.reactKey = if a key is used to distinguish siblings
forEachRef(refs, (visitor) => {
const visitorClone = visitor.clone(); // visitor will get stomped on next iteration
const ref = visitor.getRef();
visitor.forEachEdge((edgeName, edgeVisitor) => {
const edgeRef = edgeVisitor.getRef();
if (edgeRef) {
if (edgeName === '_renderedChildren') {
if (ref.reactParent === undefined) {
// ref is react component, even if we don't have a parent yet
ref.reactParent = null;
}
edgeVisitor.forEachEdge((childName, childVisitor) => {
const childRef = childVisitor.getRef();
if (childRef && childName.startsWith('.')) {
childRef.reactParent = visitorClone;
childRef.reactKey = childName;
}
});
} else if (edgeName === '_renderedComponent') {
if (ref.reactParent === undefined) {
ref.reactParent = null;
}
edgeRef.reactParent = visitorClone;
}
}
});
});
// build tree of react internal instances (since that's what has the structure)
// fill in ref.reactTree = path registry node
forEachRef(refs, (visitor) => {
buildReactComponentTree(visitor, registry, strings);
});
// hook in components by looking at their _reactInternalInstance fields
forEachRef(refs, (visitor) => {
const ref = visitor.getRef();
const instanceRef = visitor.moveToEdge('_reactInternalInstance').getRef();
if (instanceRef) {
ref.reactTree = instanceRef.reactTree;
}
});
}
function functionUrlFileName(visitor) {
const executable = visitor.clone().moveToEdge('@Executable');
const ref = executable.getRef();
if (ref && ref.value && ref.value.url) {
const url = ref.value.url;
let file = url.substring(url.lastIndexOf('/') + 1);
if (file.endsWith('.js')) {
file = file.substring(0, file.length - 3);
}
return file;
}
return undefined;
}
function markModules(refs) {
const modules = firstRef(refs, (id, ref) => ref.type === 'CallbackGlobalObject');
modules.moveToEdge('require');
modules.moveToFirst((name, visitor) => visitor.getType() === 'JSActivation');
modules.moveToEdge('modules');
modules.forEachEdge((name, visitor) => {
const ref = visitor.getRef();
visitor.moveToEdge('exports');
if (visitor.getType() === 'Object') {
visitor.moveToFirst((memberName, member) => member.getType() === 'Function');
if (visitor.isDefined()) {
ref.module = functionUrlFileName(visitor);
}
} else if (visitor.getType() === 'Function') {
const displayName = visitor.clone().moveToEdge('displayName');
if (displayName.isDefined()) {
ref.module = displayName.getValue();
}
ref.module = functionUrlFileName(visitor);
}
if (ref && !ref.module) {
ref.module = '#unknown ' + name;
}
});
}
function registerPathToRootBFS(breadth, registry, strings) {
while (breadth.length > 0) {
const nextBreadth = [];
for (let i = 0; i < breadth.length; i++) {
const visitor = breadth[i];
const ref = visitor.getRef();
visitor.forEachEdge((edgeName, edgeVisitor) => {
const edgeRef = edgeVisitor.getRef();
if (edgeRef && edgeRef.rootPath === undefined) {
let pathName = edgeRef.type;
if (edgeName) {
pathName = edgeName + ': ' + pathName;
}
edgeRef.rootPath = registry.insert(ref.rootPath, strings.intern(pathName));
nextBreadth.push(edgeVisitor.clone());
// copy module and react tree forward
if (edgeRef.module === undefined) {
edgeRef.module = ref.module;
}
if (edgeRef.reactTree === undefined) {
edgeRef.reactTree = ref.reactTree;
}
}
});
}
breadth = nextBreadth;
}
}
function registerPathToRoot(capture, registry, strings) {
const refs = capture.refs;
const roots = capture.roots;
markReactComponentTree(refs, registry, strings);
markModules(refs);
let breadth = [];
// BFS from global objects first
forEachRef(refs, (visitor) => {
const ref = visitor.getRef();
if (ref.type === 'CallbackGlobalObject') {
ref.rootPath = registry.insert(registry.root, strings.intern(ref.type));
breadth.push(visitor.clone());
}
});
registerPathToRootBFS(breadth, registry, strings);
breadth = [];
// lower priority, BFS from other roots
for (const id of roots) {
const visitor = new RefVisitor(refs, id);
const ref = visitor.getRef();
if (ref.rootPath === undefined) {
ref.rootPath = registry.insert(registry.root, strings.intern(`root ${id}: ${ref.type}`));
breadth.push(visitor.clone());
}
}
registerPathToRootBFS(breadth, registry, strings);
}
function registerCapture(data, captureId, capture, stacks, strings) {
// NB: capture.refs is potentially VERY large, so we try to avoid making
// copies, even if iteration is a bit more annoying.
let rowCount = 0;
for (const id in capture.refs) { // eslint-disable-line no-unused-vars
rowCount++;
}
for (const id in capture.markedBlocks) { // eslint-disable-line no-unused-vars
rowCount++;
}
const inserter = data.rowInserter(rowCount);
registerPathToRoot(capture, stacks, strings);
const noneString = strings.intern('#none');
const noneStack = stacks.insert(stacks.root, noneString);
forEachRef(capture.refs, (visitor) => {
// want to data.append(value, value, value), not IDs
const ref = visitor.getRef();
const id = visitor.id;
inserter.insertRow(
parseInt(id, 16),
ref.type,
ref.size,
ref.cellSize,
captureId,
ref.rootPath === undefined ? noneStack : ref.rootPath,
ref.reactTree === undefined ? noneStack : ref.reactTree,
visitor.getValue(),
ref.module === undefined ? '#none' : ref.module,
);
});
for (const id in capture.markedBlocks) {
const block = capture.markedBlocks[id];
inserter.insertRow(
parseInt(id, 16),
'Marked Block Overhead',
block.capacity - block.size,
0,
captureId,
noneStack,
noneStack,
'capacity: ' + block.capacity + ', size: ' + block.size + ', granularity: ' + block.cellSize,
'#none',
);
}
inserter.done();
}
if (preLoadedCapture) {
const strings = new StringInterner();
const stacks = new StackRegistry();
const columns = [
{ name: 'id', type: 'int' },
{ name: 'type', type: 'string', strings: strings },
{ name: 'size', type: 'int' },
{ name: 'cell', type: 'int' },
{ name: 'trace', type: 'string', strings: strings },
{ name: 'path', type: 'stack', stacks: stacks, getter: x => strings.get(x), formatter: x => x },
{ name: 'react', type: 'stack', stacks: stacks, getter: x => strings.get(x), formatter: x => x },
{ name: 'value', type: 'string', strings: strings },
{ name: 'module', type: 'string', strings: strings },
];
const data = new AggrowData(columns);
registerCapture(data, 'trace', preLoadedCapture, stacks, strings);
preLoadedCapture = undefined; // let GG clean up the capture
const aggrow = new Aggrow(data);
aggrow.addPointerExpander('Id', 'id');
const typeExpander = aggrow.addStringExpander('Type', 'type');
aggrow.addNumberExpander('Size', 'size');
aggrow.addStringExpander('Trace', 'trace');
const pathExpander = aggrow.addStackExpander('Path', 'path');
const reactExpander = aggrow.addStackExpander('React Tree', 'react');
const valueExpander = aggrow.addStringExpander('Value', 'value');
const moduleExpander = aggrow.addStringExpander('Module', 'module');
aggrow.expander.setActiveExpanders([
pathExpander,
reactExpander,
moduleExpander,
typeExpander,
valueExpander,
]);
const sizeAggregator = aggrow.addSumAggregator('Size', 'size');
const cellAggregator = aggrow.addSumAggregator('Cell Size', 'cell');
const countAggregator = aggrow.addCountAggregator('Count');
aggrow.expander.setActiveAggregators([
cellAggregator,
sizeAggregator,
countAggregator,
]);
ReactDOM.render(<AggrowTable aggrow={aggrow} />, document.body);
}
|
TestDemos/examples/BookExamples/XA-2-1.js | AzenXu/ReactNativeTest | /**
* Created by Azen on 16/8/31.
* 《RN跨平台移动应用开发代码2-1》
* 知识点:
* 1. 'use strict'
* 2. PixelRatio(记录逻辑像素的密度) 和 scale(记录缩放比例) 好像没啥区别
* 3. chrome调试 - console.log(打印普通的log信息) console.warn 打印醒目的console信息
*/
'use strict';
import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
let Dimensions = require('Dimensions');
let PixelRatio = require('PixelRatio');
let {width, height, scale} = Dimensions.get('window'); // 想用这种方法获取height 和 width ,就不能自定义变量名
let totalWidth = Dimensions.get('window').width;
let totalHeight = Dimensions.get('window').height;
let pixelRatio = PixelRatio.get();
class Project19 extends Component {
render() {
let aValue;
console.log('render has been executed.');
console.log('totalHeight is:' + totalHeight);
console.log('aValue is:' + aValue);
console.warn('the type of aValue is:' + typeof(aValue));
return (
<View style = {styles.container}>
<Text style = {styles.welcome}>PixelRatio = {pixelRatio}</Text>
<Text style= {styles.welcome}>Scal = {scale}</Text>
<Text style = {styles.instructions}>totalHeight = {totalHeight}</Text>
<Text style = {styles.instructions}>height = {height}</Text>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF'
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5
}
});
module.exports = Project19; |
src/interface/common/Expandable.js | FaideWW/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import ReactTooltip from 'react-tooltip';
class Expandable extends React.PureComponent {
static propTypes = {
header: PropTypes.node.isRequired,
children: PropTypes.node.isRequired,
};
constructor() {
super();
this.state = {
expanded: false,
};
this.handleToggle = this.handleToggle.bind(this);
}
handleToggle() {
this.setState({
expanded: !this.state.expanded,
});
}
componentDidUpdate() {
ReactTooltip.rebuild();
}
render() {
const { header, children } = this.props;
return (
<div className={`expandable ${this.state.expanded ? 'expanded' : ''}`}>
<div className="meta" onClick={this.handleToggle}>
{header}
</div>
{this.state.expanded && (
<div className="details">
{children}
</div>
)}
</div>
);
}
}
export default Expandable;
|
src/ButtonInput.js | Firfi/meteor-react-bootstrap | import React from 'react';
import Button from './Button';
import FormGroup from './FormGroup';
import InputBase from './InputBase';
import childrenValueValidation from './utils/childrenValueInputValidation';
class ButtonInput extends InputBase {
renderFormGroup(children) {
let {bsStyle, value, ...other} = this.props; // eslint-disable-line object-shorthand
return <FormGroup {...other}>{children}</FormGroup>;
}
renderInput() {
let {children, value, ...other} = this.props; // eslint-disable-line object-shorthand
let val = children ? children : value;
return <Button {...other} componentClass="input" ref="input" key="input" value={val} />;
}
}
ButtonInput.types = ['button', 'reset', 'submit'];
ButtonInput.defaultProps = {
type: 'button'
};
ButtonInput.propTypes = {
type: React.PropTypes.oneOf(ButtonInput.types),
bsStyle(props) {
//defer to Button propTypes of bsStyle
return null;
},
children: childrenValueValidation,
value: childrenValueValidation
};
export default ButtonInput;
|
frontend/src/cms/components/shared/CustomDatePicker/index.js | tsurupin/portfolio | import React, { Component } from 'react';
import DatePicker from 'material-ui/DatePicker';
export default class CustomDatePicker extends Component {
constructor(props) {
super(props);
}
onChange(e, date) {
if (this.props.onChange) {
this.props.onChange(date);
}
}
render() {
let props;
if (this.props.value) {
props = {...this.props, value: new Date(this.props.value)}
} else {
props = this.props
}
return <DatePicker {...props} onChange={this.onChange.bind(this)} />
}
} |
src/svg-icons/communication/stay-current-landscape.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStayCurrentLandscape = (props) => (
<SvgIcon {...props}>
<path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/>
</SvgIcon>
);
CommunicationStayCurrentLandscape = pure(CommunicationStayCurrentLandscape);
CommunicationStayCurrentLandscape.displayName = 'CommunicationStayCurrentLandscape';
CommunicationStayCurrentLandscape.muiName = 'SvgIcon';
export default CommunicationStayCurrentLandscape;
|
tools/browser-runtime/src/component/Tile/Tile.js | kevoree/kevoree-js | import React from 'react';
import { Icon } from 'semantic-ui-react';
import './Tile.css';
export default class Tile extends React.Component {
changeState() {
if (this.props.instance.started) {
this.props.instance.submitScript(`stop ${this.props.instance.nodeName}.${this.props.instance.name}`);
} else {
this.props.instance.submitScript(`start ${this.props.instance.nodeName}.${this.props.instance.name}`);
}
}
close() {
this.props.instance.submitScript(`remove ${this.props.instance.nodeName}.${this.props.instance.name}`);
}
componentWillUnmount() {
console.log('Tile unmount:', this.props.instance.path);
}
render() {
const name = this.props.instance.name;
const tdef = this.props.instance.getModelEntity().typeDefinition;
return (
<div className='Tile' ref={(elem) => this.tile = elem}>
<div className='Tile-header'>
<h3 className='Tile-name'>{name + ': ' + tdef.name + '/' + tdef.version}</h3>
<div className='Tile-actions'>
<span className='Tile-action' onClick={() => this.changeState()}>
<Icon name={this.props.instance.started ? 'stop circle':'play circle'} />
</span>
<span className='Tile-action' onClick={() => this.close()}>
<Icon name='window close' />
</span>
</div>
</div>
<div className='Tile-content'>
{!this.props.instance.started && (
<div className='Tile-stopped-overlay'>
<p>STOPPED</p>
</div>
)}
<div className='Tile-overlay' style={this.props.instance._showOverlay ? {display: 'block'}:{display: 'none'}} />
<iframe
title={this.props.instance.getPath()}
src={'tile.html?path=' + encodeURI(this.props.instance.getPath())}
frameBorder='0'
marginHeight='0'
marginWidth='0'>
</iframe>
</div>
</div>
);
}
}
|
main.js | RickFrom1987/rickfrom1987.com | import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './core/store';
import router from './core/router';
import history from './core/history';
let routes = require('./routes.json'); // Loaded with utils/routes-loader.js
const container = document.getElementById('root');
function renderComponent(component) {
ReactDOM.render(<Provider store={store}>{component}</Provider>, container);
window.scrollTo(0,0);
}
// Find and render a web page matching the current URL path,
// if such page is not found then render an error page (see routes.json, core/router.js)
function render(location) {
router.resolve(routes, location)
.then(renderComponent)
.catch(error => router.resolve(routes, { ...location, error }).then(renderComponent));
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/ReactJSTraining/history/tree/master/docs#readme
history.listen(render);
render(history.getCurrentLocation());
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./routes.json', () => {
routes = require('./routes.json'); // eslint-disable-line global-require
render(history.getCurrentLocation());
});
}
|
components/Form/RadioGroup/RadioGroup.story.js | NGMarmaduke/bloom | import React from 'react';
import { storiesOf, action } from '@storybook/react';
import { withKnobs, number } from '@storybook/addon-knobs';
import RadioGroup from './RadioGroup';
const stories = storiesOf('FormComponents', module);
stories.addDecorator(withKnobs);
stories.add('RadioGroup', () => (
<RadioGroup
value={ number('Value', 1) }
onChange={ action('checked') }
>
{ radio => (
<span>
{ radio({ value: 1, label: 'One' }) }
{ radio({ value: 2, label: 'Two' }) }
{ radio({ value: 3, label: 'Three' }) }
{ radio({ value: 4, label: 'Four' }) }
{ radio({ value: 5, label: 'Five' }) }
</span>
) }
</RadioGroup>
));
|
src/Table.js | 15lyfromsaturn/react-materialize | import React from 'react';
import cx from 'classnames';
class Table extends React.Component {
render() {
let classes = {
centered: this.props.centered,
highlight: this.props.hoverable,
'responsive-table': this.props.responsive,
stripped: this.props.stripped,
bordered: this.props.bordered
};
let {className, children, ...props} = this.props;
return (
<table className={cx(classes, className)} {...this.props}>
{children}
</table>
);
}
}
Table.propTypes = {
/**
* Center align all the text in the table
* @default false
*/
centered: React.PropTypes.bool,
/**
* Highlight the row that's hovered
* @default false
*/
hoverable: React.PropTypes.bool,
/**
* Enable response to make the table horizontally scrollable on smaller screens
* @default false
*/
responsive: React.PropTypes.bool,
/**
* Stripped style
* @default false
*/
stripped: React.PropTypes.bool,
/**
* Add border to each row
* @default false
*/
bordered: React.PropTypes.bool
};
export default Table;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.