path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
docs/src/PropTable.js | insionng/react-bootstrap | import merge from 'lodash/object/merge';
import React from 'react';
import Label from '../../src/Label';
import Table from '../../src/Table';
let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, '');
function getPropsData(componentData, metadata){
let props = componentData.props || {};
if (componentData.composes) {
componentData.composes.forEach( other => {
props = merge({}, getPropsData(metadata[other] || {}, metadata), props);
});
}
if (componentData.mixins) {
componentData.mixins.forEach( other => {
if ( componentData.composes.indexOf(other) === -1) {
props = merge({}, getPropsData(metadata[other] || {}, metadata), props);
}
});
}
return props;
}
const PropTable = React.createClass({
contextTypes: {
metadata: React.PropTypes.object
},
componentWillMount(){
let componentData = this.context.metadata[this.props.component] || {};
this.propsData = getPropsData(componentData, this.context.metadata);
},
render(){
let propsData = this.propsData;
if ( !Object.keys(propsData).length){
return <span/>;
}
return (
<Table bordered striped className="prop-table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{ this._renderRows(propsData) }
</tbody>
</Table>
);
},
_renderRows(propsData){
return Object.keys(propsData)
.sort()
.filter(propName => propsData[propName].type && !propsData[propName].doclets.private )
.map(propName => {
let propData = propsData[propName];
return (
<tr key={propName} className='prop-table-row'>
<td>
{propName} {this.renderRequiredLabel(propData)}
</td>
<td>
<div>{this.getType(propData)}</div>
</td>
<td>{propData.defaultValue}</td>
<td>
{ propData.doclets.deprecated
&& <div><strong className='text-danger'>{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong></div>
}
<div dangerouslySetInnerHTML={{__html: propData.descHtml }} />
</td>
</tr>
);
});
},
renderRequiredLabel(prop) {
if (!prop.required) {
return null;
}
return (
<Label>required</Label>
);
},
getType(prop) {
let type = prop.type || {};
let name = this.getDisplayTypeName(type.name);
let doclets = prop.doclets || {};
switch (name) {
case 'object':
return name;
case 'union':
return type.value.reduce((current, val, i, list) => {
let item = this.getType({ type: val });
if (React.isValidElement(item)) {
item = React.cloneElement(item, {key: i});
}
current = current.concat(item);
return i === (list.length - 1) ? current : current.concat(' | ');
}, []);
case 'array':
let child = this.getType({ type: type.value });
return <span>{'array<'}{ child }{'>'}</span>;
case 'enum':
return this.renderEnum(type);
case 'custom':
return cleanDocletValue(doclets.type || name);
default:
return name;
}
},
getDisplayTypeName(typeName) {
if (typeName === 'func') {
return 'function';
} else if (typeName === 'bool') {
return 'boolean';
} else {
return typeName;
}
},
renderEnum(enumType) {
const enumValues = enumType.value || [];
const renderedEnumValues = [];
enumValues.forEach(function renderEnumValue(enumValue, i) {
if (i > 0) {
renderedEnumValues.push(
<span key={`${i}c`}>, </span>
);
}
renderedEnumValues.push(
<code key={i}>{enumValue}</code>
);
});
return (
<span>one of: {renderedEnumValues}</span>
);
}
});
export default PropTable;
|
blueocean-material-icons/src/js/components/svg-icons/social/people.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const SocialPeople = (props) => (
<SvgIcon {...props}>
<path d="M16 11c1.66 0 2.99-1.34 2.99-3S17.66 5 16 5c-1.66 0-3 1.34-3 3s1.34 3 3 3zm-8 0c1.66 0 2.99-1.34 2.99-3S9.66 5 8 5C6.34 5 5 6.34 5 8s1.34 3 3 3zm0 2c-2.33 0-7 1.17-7 3.5V19h14v-2.5c0-2.33-4.67-3.5-7-3.5zm8 0c-.29 0-.62.02-.97.05 1.16.84 1.97 1.97 1.97 3.45V19h6v-2.5c0-2.33-4.67-3.5-7-3.5z"/>
</SvgIcon>
);
SocialPeople.displayName = 'SocialPeople';
SocialPeople.muiName = 'SvgIcon';
export default SocialPeople;
|
src/components/LoadingScreen.js | robertkirsz/magic-cards-manager | import React from 'react'
import { Spinner } from 'components'
import { AbsoluteCenter } from 'styled'
const LoadingScreen = () => (
<AbsoluteCenter background="white">
<Spinner />
</AbsoluteCenter>
)
export default LoadingScreen
|
src/give/Funds/FundDetails.js | NewSpring/Apollos | import React from 'react';
import { Platform, ScrollView } from 'react-native';
import { compose, mapProps } from 'recompose';
import withFinancialAccounts from '@data/withFinancialAccounts';
import styled from '@ui/styled';
import Header from '@ui/Header';
import BackgroundView from '@ui/BackgroundView';
import SideBySideView, { Left, Right } from '@ui/SideBySideView';
import MediaQuery from '@ui/MediaQuery';
import Hero, { BackgroundImage } from '@ui/Hero';
import HTMLView from '@ui/HTMLView';
import PaddedView from '@ui/PaddedView';
import { ContributionForm } from '@ui/forms';
import ConnectedImage from '@ui/ConnectedImage';
import { H2 } from '@ui/typography';
const enhance = compose(
withFinancialAccounts,
mapProps(({ accounts = [], match: { params: { id } }, ...otherProps }) => ({
...otherProps,
fund: accounts.find(account => `${account.id}` === `${id}`),
})),
);
const FlexedSideBySideView = styled({ flex: 1 })(SideBySideView);
const FlexedLeft = styled({ flex: 1 })(Left);
const StyledImage = styled({
width: '100%',
aspectRatio: 2,
...Platform.select({
web: {
height: 0,
paddingTop: '50%',
},
}),
})(ConnectedImage);
const FundDetails = enhance(({
fund: {
name,
id,
images,
description,
} = {},
}) => (
<BackgroundView>
<FlexedSideBySideView>
<FlexedLeft>
<Header
titleText={name}
backButton
webEnabled
/>
<ScrollView>
<MediaQuery maxWidth="md">
<StyledImage source={images} />
</MediaQuery>
<PaddedView>
<MediaQuery maxWidth="md">
<H2>{name}</H2>
</MediaQuery>
<HTMLView>
{description}
</HTMLView>
</PaddedView>
<ContributionForm
onComplete={({ history, savedPaymentMethods } = {}) => {
const userHasPaymentMethods = savedPaymentMethods.length > 0;
if (userHasPaymentMethods) {
return history.push('/give/checkout/confirm');
}
return history.push('/give/checkout');
}}
preselection={{ id, name }}
/>
</ScrollView>
</FlexedLeft>
<MediaQuery minWidth="md">
<Right>
<Hero background={<BackgroundImage source={images} />} />
</Right>
</MediaQuery>
</FlexedSideBySideView>
</BackgroundView>
));
export default FundDetails;
|
react-demos/drag_and_drop/src/index.js | konvajs/site | import React, { Component } from 'react';
import { createRoot } from 'react-dom/client';
import { Stage, Layer, Text } from 'react-konva';
class App extends Component {
state = {
isDragging: false,
x: 50,
y: 50,
};
render() {
return (
<Stage width={window.innerWidth} height={window.innerHeight}>
<Layer>
<Text
text="Draggable Text"
x={this.state.x}
y={this.state.y}
draggable
fill={this.state.isDragging ? 'green' : 'black'}
onDragStart={() => {
this.setState({
isDragging: true,
});
}}
onDragEnd={(e) => {
this.setState({
isDragging: false,
x: e.target.x(),
y: e.target.y(),
});
}}
/>
</Layer>
</Stage>
);
}
}
const container = document.getElementById('root');
const root = createRoot(container);
root.render(<App />);
|
src/layouts/CoreLayout/CoreLayout.js | colindcampbell/word-weaver | import React from 'react'
import PropTypes from 'prop-types'
import Header from '../../components/Header'
import 'styles/core.scss'
export const CoreLayout = ({ children }) => (
<div className='container text-center'>
<Header />
<div className='core-layout__viewport'>
{children}
</div>
</div>
)
CoreLayout.propTypes = {
children : PropTypes.element.isRequired
}
export default CoreLayout
|
zhihu/src/js/zhihuReact2/index.js | fengnovo/webpack-react | import React from 'react'
import { render } from 'react-dom'
import { BrowserRouter as Router, Route } from 'react-router-dom'
import App from './App'
import Detail from './Detail'
import Comment from './Comment'
var rootElement = document.getElementById('app')
render(
<Router>
<div>
<Route exact path="/" render={() => {
console.log(cacheData);
return <App cacheData={cacheData} updateData={updateData} pushData={pushData}/>}
} />
<Route path="/detail/:id" component={Detail} />
<Route path="/comment/:id" component={Comment} />
</div>
</Router>,
rootElement
) |
fields/types/date/DateColumn.js | stunjiturner/keystone | import React from 'react';
import moment from 'moment';
import ItemsTableCell from '../../../admin/client/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTableValue';
var DateColumn = React.createClass({
displayName: 'DateColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
let value = this.props.data.fields[this.props.col.path];
if (!value) return null;
let format = (this.props.col.path === 'dateTime') ? 'MMMM Do YYYY, h:mm:ss a' : 'MMMM Do YYYY';
let formattedValue = moment(value).format(format);
return (
<ItemsTableValue title={formattedValue} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
}
});
module.exports = DateColumn;
|
packages/material-ui/src/Tabs/TabScrollButton.js | cherniavskii/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import KeyboardArrowLeft from '../internal/svg-icons/KeyboardArrowLeft';
import KeyboardArrowRight from '../internal/svg-icons/KeyboardArrowRight';
import withStyles from '../styles/withStyles';
import ButtonBase from '../ButtonBase';
export const styles = theme => ({
root: {
color: 'inherit',
flex: `0 0 ${theme.spacing.unit * 7}px`,
},
});
/**
* @ignore - internal component.
*/
function TabScrollButton(props) {
const { classes, className: classNameProp, direction, onClick, visible, ...other } = props;
const className = classNames(classes.root, classNameProp);
if (!visible) {
return <div className={className} />;
}
return (
<ButtonBase className={className} onClick={onClick} tabIndex={-1} {...other}>
{direction === 'left' ? <KeyboardArrowLeft /> : <KeyboardArrowRight />}
</ButtonBase>
);
}
TabScrollButton.propTypes = {
/**
* Useful to extend the style applied to components.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* Which direction should the button indicate?
*/
direction: PropTypes.oneOf(['left', 'right']),
/**
* Callback to execute for button press.
*/
onClick: PropTypes.func,
/**
* Should the button be present or just consume space.
*/
visible: PropTypes.bool,
};
TabScrollButton.defaultProps = {
visible: true,
};
export default withStyles(styles, { name: 'MuiTabScrollButton' })(TabScrollButton);
|
examples/async/containers/Root.js | AVert/redux | import React, { Component } from 'react';
import { Provider } from 'react-redux';
import configureStore from '../store/configureStore';
import AsyncApp from './AsyncApp';
const store = configureStore();
export default class Root extends Component {
render() {
return (
<Provider store={store}>
{() => <AsyncApp />}
</Provider>
);
}
}
|
src/components/form/controls/combobox/FormsCombobox.js | TechyFatih/Nuzlog | import React from 'react';
import icons from 'img/icons';
import defaultIcon from 'img/defaultIcon.png';
import pokedex from 'data/pokedex';
import normalize from 'utilities/normalize';
import Combobox from './Combobox';
const getForms = pokemon => {
let forms = ['Normal'];
if (pokemon) {
const entry = pokedex.get(normalize(pokemon.species));
if (entry && Array.isArray(entry.forms)) {
forms = forms.concat(entry.forms)
}
}
const species = pokemon ? normalize(pokemon.species) : '';
return forms.map((form, index) => {
let _form = '';
if (index != 0) _form = '-' + normalize(form);
let icon = icons[species + _form];
if (!icon) icon = icons[species];
if (!icon) icon = defaultIcon;
return (
<span value={form} key={index} style={{whiteSpace: 'nowrap'}}>
<img src={icon} /> {form}
</span>
)
});
}
export default class FormsCombobox extends React.Component {
constructor(props) {
super(props);
this.state = {forms: getForms(props.pokemon)};
}
componentWillReceiveProps(nextProps) {
this.setState({forms: getForms(nextProps.pokemon)});
}
render() {
return (
<Combobox id={this.props.id}
placeholder={this.props.placeholder}
value={this.props.value}
focus={this.props.focus}
onChange={this.props.onChange}
onFocus={this.props.onFocus}
onBlur={this.props.onBlur}
rowHeight={40}>
{this.state.forms}
</Combobox>
)
}
} |
node_modules/react-bootstrap/es/SplitButton.js | lucketta/got-quote-generator | import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import PropTypes from 'prop-types';
import Button from './Button';
import Dropdown from './Dropdown';
import SplitToggle from './SplitToggle';
import splitComponentProps from './utils/splitComponentProps';
var propTypes = _extends({}, Dropdown.propTypes, {
// Toggle props.
bsStyle: PropTypes.string,
bsSize: PropTypes.string,
href: PropTypes.string,
onClick: PropTypes.func,
/**
* The content of the split button.
*/
title: PropTypes.node.isRequired,
/**
* Accessible label for the toggle; the value of `title` if not specified.
*/
toggleLabel: PropTypes.string,
// Override generated docs from <Dropdown>.
/**
* @private
*/
children: PropTypes.node
});
var SplitButton = function (_React$Component) {
_inherits(SplitButton, _React$Component);
function SplitButton() {
_classCallCheck(this, SplitButton);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
SplitButton.prototype.render = function render() {
var _props = this.props,
bsSize = _props.bsSize,
bsStyle = _props.bsStyle,
title = _props.title,
toggleLabel = _props.toggleLabel,
children = _props.children,
props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'toggleLabel', 'children']);
var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent),
dropdownProps = _splitComponentProps[0],
buttonProps = _splitComponentProps[1];
return React.createElement(
Dropdown,
_extends({}, dropdownProps, {
bsSize: bsSize,
bsStyle: bsStyle
}),
React.createElement(
Button,
_extends({}, buttonProps, {
disabled: props.disabled,
bsSize: bsSize,
bsStyle: bsStyle
}),
title
),
React.createElement(SplitToggle, {
'aria-label': toggleLabel || title,
bsSize: bsSize,
bsStyle: bsStyle
}),
React.createElement(
Dropdown.Menu,
null,
children
)
);
};
return SplitButton;
}(React.Component);
SplitButton.propTypes = propTypes;
SplitButton.Toggle = SplitToggle;
export default SplitButton; |
src/Portal.js | sthawali/react-overlays | import React from 'react';
import mountable from 'react-prop-types/lib/mountable';
import ownerDocument from './utils/ownerDocument';
import getContainer from './utils/getContainer';
/**
* The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy.
* You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`.
* The children of `<Portal/>` component will be appended to the `container` specified.
*/
let Portal = React.createClass({
displayName: 'Portal',
propTypes: {
/**
* A Node, Component instance, or function that returns either. The `container` will have the Portal children
* appended to it.
*/
container: React.PropTypes.oneOfType([
mountable,
React.PropTypes.func
])
},
componentDidMount() {
this._renderOverlay();
},
componentDidUpdate() {
this._renderOverlay();
},
componentWillUnmount() {
this._unrenderOverlay();
this._unmountOverlayTarget();
},
_mountOverlayTarget() {
if (!this._overlayTarget) {
this._overlayTarget = document.createElement('div');
this.getContainerDOMNode()
.appendChild(this._overlayTarget);
}
},
_unmountOverlayTarget() {
if (this._overlayTarget) {
this.getContainerDOMNode()
.removeChild(this._overlayTarget);
this._overlayTarget = null;
}
},
_renderOverlay() {
let overlay = !this.props.children
? null
: React.Children.only(this.props.children);
// Save reference for future access.
if (overlay !== null) {
this._mountOverlayTarget();
this._overlayInstance = React.render(overlay, this._overlayTarget);
} else {
// Unrender if the component is null for transitions to null
this._unrenderOverlay();
this._unmountOverlayTarget();
}
},
_unrenderOverlay() {
if (this._overlayTarget) {
React.unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
}
},
render() {
return null;
},
getMountNode(){
return this._overlayTarget;
},
getOverlayDOMNode() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this._overlayInstance) {
if (this._overlayInstance.getWrappedDOMNode) {
return this._overlayInstance.getWrappedDOMNode();
} else {
return React.findDOMNode(this._overlayInstance);
}
}
return null;
},
getContainerDOMNode() {
return getContainer(this.props.container, ownerDocument(this).body);
}
});
export default Portal;
|
src/containers/App/index.js | raptiq/fire-emblem-optimizer | import React, { Component } from 'react';
/* global styles for app */
import './styles/app.scss';
/* application components */
import { Header } from 'components/Header';
import { Footer } from 'components/Footer';
export class App extends Component {
static propTypes = {
children: React.PropTypes.any,
};
render() {
return (
<section>
{this.props.children}
<Footer />
</section>
);
}
}
|
ui/src/components/GatewayForm.js | jcampanell-cablelabs/lora-app-server | import React, { Component } from 'react';
import { Link } from 'react-router';
import { Map, Marker, TileLayer } from 'react-leaflet';
import Select from "react-select";
import SessionStore from "../stores/SessionStore";
import LocationStore from "../stores/LocationStore";
import GatewayStore from "../stores/GatewayStore";
import NetworkServerStore from "../stores/NetworkServerStore";
class GatewayForm extends Component {
static contextTypes = {
router: React.PropTypes.object.isRequired
};
constructor() {
super();
this.state = {
gateway: {},
mapZoom: 15,
update: false,
channelConfigurations: [],
networkServers: [],
};
this.handleSubmit = this.handleSubmit.bind(this);
this.updatePosition = this.updatePosition.bind(this);
this.updateZoom = this.updateZoom.bind(this);
this.setToCurrentPosition = this.setToCurrentPosition.bind(this);
this.handleSetToCurrentPosition = this.handleSetToCurrentPosition.bind(this);
}
onSelectChange(field, val) {
let gateway = this.state.gateway;
if (val != null) {
gateway[field] = val.value;
} else {
gateway[field] = null;
}
if (field === "networkServerID" && gateway.networkServerID !== null) {
GatewayStore.getAllChannelConfigurations(gateway.networkServerID, (configurations) => {
this.setState({
channelConfigurations: configurations,
});
});
}
this.setState({
gateway: gateway,
});
}
onChange(field, e) {
let gateway = this.state.gateway;
if (e.target.type === "number") {
gateway[field] = parseFloat(e.target.value);
} else if (e.target.type === "checkbox") {
gateway[field] = e.target.checked;
} else {
gateway[field] = e.target.value;
}
this.setState({
gateway: gateway,
});
}
updatePosition() {
const position = this.refs.marker.leafletElement.getLatLng();
let gateway = this.state.gateway;
gateway.latitude = position.lat;
gateway.longitude = position.lng;
this.setState({
gateway: gateway,
});
}
updateZoom(e) {
this.setState({
mapZoom: e.target.getZoom(),
});
}
componentDidMount() {
this.setState({
gateway: this.props.gateway,
isGlobalAdmin: SessionStore.isAdmin(),
});
if (!this.props.update) {
this.setToCurrentPosition(false);
}
NetworkServerStore.getAllForOrganizationID(this.props.organizationID, 9999, 0, (totalCount, networkServers) => {
this.setState({
networkServers: networkServers,
});
});
if (typeof(this.props.gateway.networkServerID) !== "undefined") {
GatewayStore.getAllChannelConfigurations(this.props.gateway.networkServerID, (configurations) => {
this.setState({
channelConfigurations: configurations,
});
});
}
}
setToCurrentPosition(overwrite) {
LocationStore.getLocation((position) => {
if (overwrite === true || typeof(this.state.gateway.latitude) === "undefined" || typeof(this.state.gateway.longitude) === "undefined" || this.state.gateway.latitude === 0 || this.state.gateway.longitude === 0) {
let gateway = this.state.gateway;
gateway.latitude = position.coords.latitude;
gateway.longitude = position.coords.longitude;
this.setState({
gateway: gateway,
});
}
});
}
componentWillReceiveProps(nextProps) {
this.setState({
gateway: nextProps.gateway,
update: typeof nextProps.gateway.mac !== "undefined",
});
GatewayStore.getAllChannelConfigurations(nextProps.gateway.networkServerID, (configurations) => {
this.setState({
channelConfigurations: configurations,
});
});
}
handleSubmit(e) {
e.preventDefault();
this.props.onSubmit(this.state.gateway);
}
handleSetToCurrentPosition(e) {
e.preventDefault();
this.setToCurrentPosition(true);
}
render() {
const mapStyle = {
height: "400px",
};
let position = [];
if (typeof(this.state.gateway.latitude) !== "undefined" || typeof(this.state.gateway.longitude) !== "undefined") {
position = [this.state.gateway.latitude, this.state.gateway.longitude];
} else {
position = [0,0];
}
const channelConfigurations = this.state.channelConfigurations.map((c, i) => {
return {
value: c.id,
label: c.name,
};
});
const networkServerOptions = this.state.networkServers.map((n, i) => {
return {
value: n.id,
label: n.name,
};
});
return(
<div>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label className="control-label" htmlFor="name">Gateway name</label>
<input className="form-control" id="name" type="text" placeholder="e.g. 'rooftop-gateway'" required value={this.state.gateway.name || ''} pattern="[\w-]+" onChange={this.onChange.bind(this, 'name')} />
<p className="help-block">
The name may only contain words, numbers and dashes.
</p>
</div>
<div className="form-group">
<label className="control-label" htmlFor="name">Gateway description</label>
<input className="form-control" id="description" type="text" placeholder="a short description of your gateway" required value={this.state.gateway.description || ''} onChange={this.onChange.bind(this, 'description')} />
</div>
<div className="form-group">
<label className="control-label" htmlFor="mac">MAC address</label>
<input className="form-control" id="mac" type="text" placeholder="0000000000000000" pattern="[A-Fa-f0-9]{16}" required disabled={this.state.update} value={this.state.gateway.mac || ''} onChange={this.onChange.bind(this, 'mac')} />
<p className="help-block">
Enter the gateway MAC address as configured in the packet-forwarder configuration on the gateway.
</p>
</div>
<div className="form-group">
<label className="control-label" htmlFor="networkServerID">Network-server</label>
<Select
name="networkServerID"
options={networkServerOptions}
value={this.state.gateway.networkServerID}
onChange={this.onSelectChange.bind(this, "networkServerID")}
disabled={this.state.update}
/>
<p className="help-block">
Select the network-server to which the gateway will connect. When no network-servers are available in the dropdown, make sure a service-profile exists for this organization.
</p>
</div>
<div className="form-group">
<label className="control-label" htmlFor="channelConfigurationID">Channel-configuration</label>
<Select
name="channelConfigurationID"
options={channelConfigurations}
value={this.state.gateway.channelConfigurationID}
onChange={this.onSelectChange.bind(this, "channelConfigurationID")}
/>
<p className="help-block">An optional channel-configuration can be assigned to a gateway. This configuration can be used to automatically re-configure the gateway (in the future).</p>
</div>
<div className="form-group">
<label className="control-label" htmlFor="ping">
<input type="checkbox" name="ping" id="ping" checked={this.state.gateway.ping} onChange={this.onChange.bind(this, 'ping')} /> Discovery enabled
</label>
<p className="help-block">When enabled (and LoRa App Server is configured with the gateway discover feature enabled), the gateway will send out periodical pings to test its coverage by other gateways in the same network.</p>
</div>
<div className="form-group">
<label className="control-label" htmlFor="altitude">Gateway altitude (meters)</label>
<input className="form-control" id="altitude" type="number" value={this.state.gateway.altitude || 0} onChange={this.onChange.bind(this, 'altitude')} />
<p className="help-block">When the gateway has an on-board GPS, this value will be set automatically when the network received statistics from the gateway.</p>
</div>
<div className="form-group">
<label className="control-label">Gateway location (<Link onClick={this.handleSetToCurrentPosition} href="#">set to current location</Link>)</label>
<Map
zoom={this.state.mapZoom}
center={position}
style={mapStyle}
animate={true}
onZoomend={this.updateZoom}
scrollWheelZoom={false}
>
<TileLayer
url='//{s}.tile.openstreetmap.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
<Marker position={position} draggable={true} onDragend={this.updatePosition} ref="marker" />
</Map>
<p className="help-block">Drag the marker to the location of the gateway. When the gateway has an on-board GPS, this value will be set automatically when the network receives statistics from the gateway.</p>
</div>
<hr />
<div className="btn-toolbar pull-right">
<a className="btn btn-default" onClick={this.context.router.goBack}>Go back</a>
<button type="submit" className="btn btn-primary">Submit</button>
</div>
</form>
</div>
);
}
}
export default GatewayForm;
|
frontend/src/admin/branchManagement/memberView/MemberListTable.js | rabblerouser/core | import React from 'react';
import moment from 'moment';
import { connect } from 'react-redux';
import { EditButton, DeleteButton } from '../../common';
import { SortedTable } from '../../common/tables';
import { editMember, memberRemoveRequested } from './actions';
const columnsWithAddress = [
{ type: 'name', field: 'memberName', label: 'Member name' },
{ type: 'name', field: 'contactNumber', label: 'Contact information' },
{ type: 'name', field: 'address', label: 'Address' },
{ type: 'name', field: 'memberSince', label: 'Member since' },
{ type: 'actions' },
];
const columnsWithoutAddress = [
{ type: 'name', field: 'memberName', label: 'Member name' },
{ type: 'name', field: 'contactNumber', label: 'Contact information' },
{ type: 'name', field: 'memberSince', label: 'Member since' },
{ type: 'actions' },
];
const mapFields = ({ name, phoneNumber, email, memberSince, address },
addressEnabled) => {
const memberNameField = name;
const contactNumberField = `${phoneNumber || ''} ${email || ''}`;
const memberSinceField = moment(memberSince).format('YYYY/MM/DD');
let addressField;
if (address) {
addressField =
`${address.address || ''}, ${address.suburb || ''}, ${address.state || ''}, ` +
`${address.postcode || ''}, ${address.country || ''}`;
} else {
addressField = '-';
}
let fields;
if (addressEnabled) {
fields = {
memberName: memberNameField,
contactNumber: contactNumberField,
address: addressField,
memberSince: memberSinceField,
};
} else {
fields = {
memberName: memberNameField,
contactNumber: contactNumberField,
memberSince: memberSinceField,
};
}
return fields;
};
const mapActions = (edit, remove, memberId) => [
<EditButton key={`${memberId}-edit`} onClick={() => { edit(memberId); }} />,
<DeleteButton
key={`${memberId}-delete`}
confirmMessage="Are you sure you want to delete the selected member?"
title="Delete member"
onDelete={() => remove(memberId)}
/>,
];
export const MemberListTable = ({
edit,
remove,
members,
addressEnabled = customisation.addressEnabled,
}) => {
const columns = addressEnabled ? columnsWithAddress : columnsWithoutAddress;
return (<SortedTable
columns={columns}
data={members.map(member => (
{
...mapFields(member, addressEnabled),
actions: mapActions(edit, remove, member.id),
}
))}
sortOn="memberName"
/>);
};
export default connect(() => ({}), { edit: editMember, remove: memberRemoveRequested })(MemberListTable);
|
13. ReactJS Fundamentals - Feb 2019/03. Events and Forms/Fog-App/src/Games/GameGridList.js | zrusev/SoftwareUniversity2016 | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import GridList from '@material-ui/core/GridList';
import GridListTile from '@material-ui/core/GridListTile';
import GridListTileBar from '@material-ui/core/GridListTileBar';
import IconButton from '@material-ui/core/IconButton';
import StarBorderIcon from '@material-ui/icons/StarBorder';
const styles = theme => ({
root: {
display: 'flex',
flexWrap: 'wrap',
justifyContent: 'space-around',
overflow: 'hidden',
},
gridList: {
width: 500,
height: 450,
// Promote the list into his own layer on Chrome. This cost memory but helps keeping high FPS.
transform: 'translateZ(0)',
},
titleBar: {
background:
'linear-gradient(to bottom, rgba(0,0,0,0.7) 0%, ' +
'rgba(0,0,0,0.3) 70%, rgba(0,0,0,0) 100%)',
},
icon: {
color: 'white',
},
});
function GameGridList(props) {
const { classes } = props;
return (
<div className={classes.root}>
<GridList cellHeight={200} spacing={1} className={classes.gridList}>
{props.games.map(game => (
<GridListTile key={game.imageUrl} cols={game.description ? 2 : 1} rows={game.description ? 2 : 1}>
<img src={game.imageUrl} alt={game.title} />
<GridListTileBar
title={game.title}
titlePosition="top"
actionPosition="left"
className={classes.titleBar}
/>
</GridListTile>
))}
</GridList>
</div>
);
}
GameGridList.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(GameGridList); |
app/javascript/mastodon/components/button.js | corzntin/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class Button extends React.PureComponent {
static propTypes = {
text: PropTypes.node,
onClick: PropTypes.func,
disabled: PropTypes.bool,
block: PropTypes.bool,
secondary: PropTypes.bool,
size: PropTypes.number,
className: PropTypes.string,
style: PropTypes.object,
children: PropTypes.node,
};
static defaultProps = {
size: 36,
};
handleClick = (e) => {
if (!this.props.disabled) {
this.props.onClick(e);
}
}
setRef = (c) => {
this.node = c;
}
focus() {
this.node.focus();
}
render () {
const style = {
padding: `0 ${this.props.size / 2.25}px`,
height: `${this.props.size}px`,
lineHeight: `${this.props.size}px`,
...this.props.style,
};
const className = classNames('button', this.props.className, {
'button-secondary': this.props.secondary,
'button--block': this.props.block,
});
return (
<button
className={className}
disabled={this.props.disabled}
onClick={this.handleClick}
ref={this.setRef}
style={style}
>
{this.props.text || this.props.children}
</button>
);
}
}
|
js/src/dapps/dappreg/ModalUpdate/modalUpdate.js | BSDStudios/parity | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component } from 'react';
import { observer } from 'mobx-react';
import DappsStore from '../dappsStore';
import ModalStore from '../modalStore';
import Button from '../Button';
import Modal from '../Modal';
import styles from '../Modal/modal.css';
const HEADERS = [
'Error During Update',
'Confirm Application Update',
'Waiting for Signer Confirmation',
'Waiting for Transaction Receipt',
'Update Completed'
];
const STEP_ERROR = 0;
const STEP_CONFIRM = 1;
const STEP_SIGNER = 2;
const STEP_TXRECEIPT = 3;
const STEP_DONE = 4;
@observer
export default class ModalUpdate extends Component {
dappsStore = DappsStore.instance();
modalStore = ModalStore.instance();
render () {
if (!this.modalStore.showingUpdate) {
return null;
}
return (
<Modal
buttons={ this.renderButtons() }
error={ this.modalStore.errorUpdate }
header={ HEADERS[this.modalStore.stepUpdate] }
>
{ this.renderStep() }
</Modal>
);
}
renderButtons () {
switch (this.modalStore.stepUpdate) {
case STEP_ERROR:
case STEP_DONE:
return [
<Button
key='close'
label='Close'
onClick={ this.onClickClose }
/>
];
case STEP_CONFIRM:
return [
<Button
key='cancel'
label='No, Cancel'
onClick={ this.onClickClose }
/>,
<Button
key='delete'
label='Yes, Update'
warning
onClick={ this.onClickYes }
/>
];
default:
return null;
}
}
renderStep () {
switch (this.modalStore.stepUpdate) {
case STEP_CONFIRM:
return this.renderStepConfirm();
case STEP_SIGNER:
return this.renderStepWait('Waiting for transaction confirmation in the Parity secure signer');
case STEP_TXRECEIPT:
return this.renderStepWait('Waiting for the transaction receipt from the network');
case STEP_DONE:
return this.renderStepCompleted();
default:
return null;
}
}
renderStepCompleted () {
return (
<div>
<div className={ styles.section }>
Your application metadata has been updated in the registry.
</div>
</div>
);
}
renderStepConfirm () {
return (
<div>
<div className={ styles.section }>
You are about to update the application details in the registry, the details of these updates are given below. Please note that each update will generate a seperate transaction.
</div>
<div className={ styles.section }>
<div className={ styles.heading }>
Application identifier
</div>
<div>
{ this.dappsStore.wipApp.id }
</div>
</div>
{ this.renderChanges() }
</div>
);
}
renderChanges () {
return ['content', 'image', 'manifest']
.filter((type) => this.dappsStore.wipApp[`${type}Changed`])
.map((type) => {
return (
<div className={ styles.section } key={ `${type}Update` }>
<div className={ styles.heading }>
Updates to { type } hash
</div>
<div>
<div>{ this.dappsStore.wipApp[`${type}Hash`] || '(removed)' }</div>
<div className={ styles.hint }>
{ this.dappsStore.wipApp[`${type}Url`] || 'current url to be removed from registry' }
</div>
</div>
</div>
);
});
}
renderStepWait (waitingFor) {
return (
<div>
<div className={ styles.section }>
{ waitingFor }
</div>
</div>
);
}
onClickClose = () => {
this.modalStore.hideUpdate();
}
onClickYes = () => {
this.modalStore.doUpdate();
}
}
|
modules/RouteContext.js | nottombrown/react-router | import React from 'react'
const { object } = React.PropTypes
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
const RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext() {
return {
route: this.props.route
}
}
}
export default RouteContext
|
dashboard/client/src/js/components/modules/ExperimentDetails.js | jigarjain/sieve | import React from 'react';
import Helpers from '../../utils/helpers';
export default function (props) {
const items = [
{
name: 'Experiment Id',
value: props.experiment.id
},
{
name: 'Version',
value: props.experiment.version
},
{
name: 'Exposure',
value: props.experiment.exposure
},
{
name: 'Created On',
value: Helpers.formatDate(props.experiment.createTime)
}
];
if (props.experiment.updateTime) {
items.push({
name: 'Last Updated On',
value: Helpers.formatDate(props.experiment.updateTime)
});
}
return (
<section className="experiment-details">
{
items.map((item, i) => {
return (
<div
key={i}
className="item"
>
<div className="item__name">{item.name}</div>
<div className="item__value">{item.value}</div>
</div>
);
})
}
</section>
);
}
|
src/svg-icons/image/looks.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLooks = (props) => (
<SvgIcon {...props}>
<path d="M12 10c-3.86 0-7 3.14-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.86-3.14-7-7-7zm0-4C5.93 6 1 10.93 1 17h2c0-4.96 4.04-9 9-9s9 4.04 9 9h2c0-6.07-4.93-11-11-11z"/>
</SvgIcon>
);
ImageLooks = pure(ImageLooks);
ImageLooks.displayName = 'ImageLooks';
export default ImageLooks;
|
views/pages/questsAll/questsAll.js | MozalovPavel/team5 | import React from 'react';
import ReactDOM from 'react-dom';
import Search from '../../blocks/Search/search';
ReactDOM.render(
<div>
<h2 className="page__title">Все квесты</h2>
<Search />
</div>,
document.getElementById('root')
);
|
src/components/Profile.js | vkarpov15/shidoshi | 'use strict';
import ArticleList from './ArticleList';
import React from 'react';
import { Link } from 'react-router';
import agent from '../agent';
import { connect } from 'react-redux';
const EditProfileSettings = props => {
if (props.isUser) {
return (
<Link
to="settings"
className="btn btn-sm btn-outline-secondary action-btn">
<i className="ion-gear-a"></i> Edit Profile Settings
</Link>
);
}
return null;
};
const FollowUserButton = props => {
if (props.isUser) {
return null;
}
let classes = 'btn btn-sm action-btn';
if (props.user.following) {
classes += ' btn-secondary';
} else {
classes += ' btn-outline-secondary';
}
const handleClick = ev => {
ev.preventDefault();
if (props.user.following) {
props.unfollow(props.user.username)
} else {
props.follow(props.user.username)
}
};
return (
<button
className={classes}
onClick={handleClick}>
<i className="ion-plus-round"></i>
{props.user.following ? 'Unfollow' : 'Follow'} {props.user.username}
</button>
);
};
const mapStateToProps = state => ({
...state.articleList,
currentUser: state.common.currentUser,
profile: state.profile
});
const mapDispatchToProps = dispatch => ({
onFollow: username => dispatch({
type: 'FOLLOW_USER',
payload: agent.Profile.follow(username)
}),
onLoad: payload => dispatch({ type: 'PROFILE_PAGE_LOADED', payload }),
onSetPage: (page, payload) => dispatch({ type: 'SET_PAGE', page, payload }),
onUnfollow: username => dispatch({
type: 'UNFOLLOW_USER',
payload: agent.Profile.unfollow(username)
}),
onUnload: () => dispatch({ type: 'PROFILE_PAGE_UNLOADED' })
});
class Profile extends React.Component {
componentWillMount() {
this.props.onLoad(Promise.all([
agent.Profile.get(this.props.params.username),
agent.Articles.byAuthor(this.props.params.username)
]));
}
componentWillUnmount() {
this.props.onUnload();
}
renderTabs() {
return (
<ul className="nav nav-pills outline-active">
<li className="nav-item">
<Link
className="nav-link active"
to={`@${this.props.profile.username}`}>
My Articles
</Link>
</li>
<li className="nav-item">
<Link
className="nav-link"
to={`@${this.props.profile.username}/favorites`}>
Favorited Articles
</Link>
</li>
</ul>
);
}
onSetPage(page) {
const promise = agent.Articles.byAuthor(this.props.profile.username, page);
this.props.onSetPage(page, promise);
}
render() {
const profile = this.props.profile;
if (!profile) {e
return null;
}
const isUser = this.props.currentUser &&
this.props.profile.username === this.props.currentUser.username;
const onSetPage = page => this.onSetPage(page)
return (
<div className="profile-page">
<div className="user-info">
<div className="container">
<div className="row">
<div className="col-xs-12 col-md-10 offset-md-1">
<img src={profile.image} className="user-img" />
<h4>{profile.username}</h4>
<p>{profile.bio}</p>
<EditProfileSettings isUser={isUser} />
<FollowUserButton
isUser={isUser}
user={profile}
follow={this.props.onFollow}
unfollow={this.props.onUnfollow}
/>
</div>
</div>
</div>
</div>
<div className="container">
<div className="row">
<div className="col-xs-12 col-md-10 offset-md-1">
<div className="articles-toggle">
{this.renderTabs()}
</div>
<ArticleList
articles={this.props.articles}
articlesCount={this.props.articlesCount}
currentPage={this.props.currentPage}
onSetPage={onSetPage} />
</div>
</div>
</div>
</div>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(Profile);
export { Profile as Profile, mapStateToProps as mapStateToProps };
|
src/layouts/index.js | sarahatwork/gatsby-poc | import React from 'react';
import PropTypes from 'prop-types';
import Link from 'gatsby-link';
import Helmet from 'react-helmet';
import './reset.css';
const TemplateWrapper = ({children}) => (
<div>
<Helmet title="Gatsby POC" />
{children()}
</div>
);
TemplateWrapper.propTypes = {
children: PropTypes.func
};
export default TemplateWrapper;
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-v3-text-button.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import {BaseMixin, ElementaryMixin, Tools} from './../common/common.js';
import InputWrapper from './internal/input-wrapper.js';
import TextInput from './internal/text-input.js';
import TextInputMixin from './mixins/text-input-mixin.js'
import ItemList from './internal/item-list.js';
import Backdrop from './../bricks/backdrop.js';
import './text-button.less';
export const TextButton = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin,
TextInputMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Forms.TextButton',
classNames: {
main: 'uu5-forms-text-button'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
value: React.PropTypes.string,
buttons: React.PropTypes.arrayOf(React.PropTypes.shape({
glyphicon: React.PropTypes.string,
onClick: React.PropTypes.func,
colorSchema: React.PropTypes.string
})
)
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps () {
return {
value: '',
buttons: null
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
componentWillMount(){
if (this.props.onValidate && typeof this.props.onValidate === 'function') {
this._validateOnChange({value: this.state.value, event: null, component: this})
}
return this;
},
componentWillReceiveProps(nextProps) {
if (this.props.controlled) {
this.setFeedback(nextProps.feedback, nextProps.message, nextProps.value)
}
return this;
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
//@@viewOff:interface
//@@viewOn:overridingMethods
// TODO: tohle je ještě otázka - je potřeba nastavit hodnotu z jiné komponenty (musí být validace) a z onChange (neměla by být validace)
setValue_(value, setStateCallback){
if (this._checkRequired({value: value})) {
if (typeof this.props.onValidate === 'function') {
this._validateOnChange({value: value, event: null, component: this})
} else {
this.props.required ? this.setSuccess(null, value, setStateCallback) : this.setInitial(null, value, setStateCallback);
}
}
return this;
},
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_validateOnChange(opt){
let result = typeof this.props.onValidate === 'function' ? this.props.onValidate(opt) : null;
if (result) {
if (typeof result === 'object') {
if (result.feedback) {
this.setFeedback(result.feedback, result.message, result.value);
} else {
this.setState({value: opt.value});
}
} else {
this.showError('validateError', null, {context: {event: e, func: this.props.onValidate, result: result}});
}
}
return this;
},
_getFeedbackIcon(){
let icon = this.props.required ? this.props.successGlyphicon : null;
switch (this.getFeedback()) {
case 'success':
icon = this.props.successGlyphicon;
break;
case 'warning':
icon = this.props.warningGlyphicon;
break;
case 'error':
icon = this.props.errorGlyphicon;
break;
}
return icon;
},
_getButtons(){
let result = [];
if (!this.isReadOnly()) {
this.props.buttons && this.props.buttons.map((button, key)=> {
let newButton = Tools.merge({}, button);
if (typeof button.onClick === 'function') {
newButton.onClick = ()=> button.onClick({value: this.state.value, component: this});
}
if (this.isDisabled()) {
newButton.disabled = true;
}
result.push(newButton);
});
}
return result;
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render () {
let inputId = this.getId() + '-input';
return (
<div {...this._getInputAttrs()}>
{this.getLabel(inputId)}
{this.getInputWrapper([
<TextInput
id={inputId}
name={this.props.name || inputId}
value={this.state.value}
placeholder={this.props.placeholder}
type='text'
onChange={this.onChange}
onBlur={this.onBlur}
onFocus={this.onFocus}
mainAttrs={this.props.inputAttrs}
disabled={this.isDisabled() || this.isLoading()}
readonly={this.isReadOnly()}
glyphicon={this._getFeedbackIcon()}
loading={this.isLoading()}
/>,
this.state.autocompleteItems && <ItemList {...this._getItemListProps()}>
{this._getChildren()}
</ItemList>,
this.state.autocompleteItems && <Backdrop {...this._getBackdropProps()} />],
this._getButtons())}
</div>
);
}
//@@viewOn:render
});
export default TextButton;
|
src/pages/404.js | pixelstew/pixelstew-gatsby | import React from 'react'
const NotFoundPage = () => (
<div>
<h1>NOT FOUND</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</div>
)
export default NotFoundPage
|
docs/server.js | bbc/react-bootstrap | /* eslint no-console: 0 */
import 'colors';
import React from 'react';
import express from 'express';
import path from 'path';
import Router from 'react-router';
import routes from './src/Routes';
import httpProxy from 'http-proxy';
import metadata from './generate-metadata';
import ip from 'ip';
const development = process.env.NODE_ENV !== 'production';
const port = process.env.PORT || 4000;
let app = express();
if (development) {
let proxy = httpProxy.createProxyServer();
let webpackPort = process.env.WEBPACK_DEV_PORT;
let target = `http://${ip.address()}:${webpackPort}`;
app.get('/assets/*', (req, res) => {
proxy.web(req, res, { target });
});
proxy.on('error', e => {
console.log('Could not connect to webpack proxy'.red);
console.log(e.toString().red);
});
console.log('Prop data generation started:'.green);
metadata().then( props => {
console.log('Prop data generation finished:'.green);
app.use(function renderApp(req, res) {
res.header('Access-Control-Allow-Origin', target);
res.header('Access-Control-Allow-Headers', 'X-Requested-With');
Router.run(routes, req.url, Handler => {
let html = React.renderToString(<Handler assetBaseUrl={target} propData={props}/>);
res.send('<!doctype html>' + html);
});
});
});
} else {
app.use(express.static(path.join(__dirname, '../docs-built')));
}
app.listen(port, () => {
console.log(`Server started at:`);
console.log(`- http://localhost:${port}`);
console.log(`- http://${ip.address()}:${port}`);
});
|
react/features/base/dialog/components/DialogContent.js | gpolitis/jitsi-meet | // @flow
import React, { Component } from 'react';
import { Container, Text } from '../../react';
import { type StyleType } from '../../styles';
import styles from './styles';
type Props = {
/**
* Children of the component.
*/
children: string | React$Node,
style: ?StyleType
};
/**
* Generic dialog content container to provide the same styling for all custom
* dialogs.
*/
export default class DialogContent extends Component<Props> {
/**
* Implements {@code Component#render}.
*
* @inheritdoc
*/
render() {
const { children, style } = this.props;
const childrenComponent = typeof children === 'string'
? <Text style = { style }>{ children }</Text>
: children;
return (
<Container style = { styles.dialogContainer }>
{ childrenComponent }
</Container>
);
}
}
|
DateField/index.js | derniercri/react-components | import React from 'react'
import {
View,
DatePickerIOS,
Platform,
} from 'react-native'
import moment from 'moment'
import 'moment/locale/fr'
import DatePickerAndroid from './DatePickerAndroid'
moment.locale('fr')
const formatDateValue = rawDate => {
const dateValue = typeof rawDate === 'number'
? parseFloat(rawDate) * 1000
: rawDate
return dateValue ? new Date(dateValue) : new Date()
}
const Picker = Platform.OS === 'ios' ? DatePickerIOS : DatePickerAndroid
const getMonthName = monthIndex => {
const month = [
'janv.',
'févr.',
'mars.',
'avr.',
'mai.',
'juin.',
'juil.',
'août.',
'sept.',
'oct.',
'nov.',
'déc.',
]
return month[monthIndex]
}
class DateInput extends React.Component {
componentDidMount () {
const {
onValueChange,
selectedValue,
} = this.props
onValueChange(formatDateValue(selectedValue))
}
render () {
const {
selectedValue,
androidStyles,
mode,
onValueChange,
minDate,
maxDate,
} = this.props
return (
<View style={androidStyles.pickerHolder}>
<Picker
initDate={formatDateValue(selectedValue)}
date={formatDateValue(selectedValue)}
minimumDate={minDate}
maximumDate={maxDate}
mode={mode}
androidStyles={androidStyles}
formatDay={i => i.length < 2 ? `0${i}` : i}
formatMonth={(i, date) => getMonthName(i)}
onDateChange={date => onValueChange(date)}
/>
</View>
)
}
}
DateInput.propTypes = {
androidStyles: React.PropTypes.object,
selectedValue: React.PropTypes.oneOfType([React.PropTypes.instanceOf(Date), React.PropTypes.number, React.PropTypes.string]),
mode: React.PropTypes.string,
minDate: React.PropTypes.instanceOf(Date),
maxDate: React.PropTypes.instanceOf(Date),
onValueChange: React.PropTypes.func.isRequired,
}
DateInput.defaultProps = {
selectedValue: new Date(),
mode: 'datetime',
androidStyles: {},
}
export default DateInput
|
src/addons/dragAndDrop/DraggableEventWrapper.js | martynasj/react-big-calendar | import PropTypes from 'prop-types';
import React from 'react'
import { DragSource } from 'react-dnd';
import cn from 'classnames';
import BigCalendar from '../../index';
/* drag sources */
let eventSource = {
beginDrag(props) {
return props.event;
}
}
function collectSource(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
}
const propTypes = {
connectDragSource: PropTypes.func.isRequired,
isDragging: PropTypes.bool.isRequired,
event: PropTypes.object.isRequired,
}
class DraggableEventWrapper extends React.Component {
render() {
let { connectDragSource, isDragging, children, event } = this.props;
let EventWrapper = BigCalendar.components.eventWrapper;
children = React.cloneElement(children, {
className: cn(
children.props.className,
isDragging && 'rbc-addons-dnd-dragging'
)
})
return (
<EventWrapper event={event}>
{connectDragSource(children)}
</EventWrapper>
);
}
}
DraggableEventWrapper.propTypes = propTypes;
export default DragSource('event', eventSource, collectSource)(DraggableEventWrapper);
|
src/index.js | peterjam28/ReduxSimpleStarter | import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/app'
ReactDOM.render(<App />, document.querySelector('.container'))
|
actor-apps/app-web/src/app/components/sidebar/ContactsSection.react.js | zomeelee/actor-platform | import _ from 'lodash';
import React from 'react';
import { Styles, RaisedButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ContactStore from 'stores/ContactStore';
import ContactActionCreators from 'actions/ContactActionCreators';
import AddContactStore from 'stores/AddContactStore';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import ContactsSectionItem from './ContactsSectionItem.react';
import AddContactModal from 'components/modals/AddContact.react.js';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isAddContactModalOpen: AddContactStore.isModalOpen(),
contacts: ContactStore.getContacts()
};
};
class ContactsSection extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
ContactActionCreators.hideContactList();
ContactStore.removeChangeListener(this.onChange);
AddContactStore.removeChangeListener(this.onChange);
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ContactActionCreators.showContactList();
ContactStore.addChangeListener(this.onChange);
AddContactStore.addChangeListener(this.onChange);
ThemeManager.setTheme(ActorTheme);
}
onChange = () => {
this.setState(getStateFromStores());
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
render() {
let contacts = this.state.contacts;
let contactList = _.map(contacts, (contact, i) => {
return (
<ContactsSectionItem contact={contact} key={i}/>
);
});
let addContactModal;
if (this.state.isAddContactModalOpen) {
addContactModal = <AddContactModal/>;
}
return (
<section className="sidebar__contacts">
<ul className="sidebar__list sidebar__list--contacts">
{contactList}
</ul>
<footer>
<RaisedButton label="Add contact" onClick={this.openAddContactModal} style={{width: '100%'}}/>
{addContactModal}
</footer>
</section>
);
}
}
export default ContactsSection;
|
docs/src/NotFoundPage.js | nickuraltsev/react-bootstrap | import React from 'react';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
const NotFoundPage = React.createClass({
render() {
return (
<div>
<NavMain activePage="" />
<PageHeader
title="404"
subTitle="Hmmm this is awkward." />
<PageFooter />
</div>
);
}
});
export default NotFoundPage;
|
src/svg-icons/alert/add-alert.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AlertAddAlert = (props) => (
<SvgIcon {...props}>
<path d="M10.01 21.01c0 1.1.89 1.99 1.99 1.99s1.99-.89 1.99-1.99h-3.98zm8.87-4.19V11c0-3.25-2.25-5.97-5.29-6.69v-.72C13.59 2.71 12.88 2 12 2s-1.59.71-1.59 1.59v.72C7.37 5.03 5.12 7.75 5.12 11v5.82L3 18.94V20h18v-1.06l-2.12-2.12zM16 13.01h-3v3h-2v-3H8V11h3V8h2v3h3v2.01z"/>
</SvgIcon>
);
AlertAddAlert = pure(AlertAddAlert);
AlertAddAlert.displayName = 'AlertAddAlert';
AlertAddAlert.muiName = 'SvgIcon';
export default AlertAddAlert;
|
src/svg-icons/device/signal-cellular-0-bar.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellular0Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M2 22h20V2z"/>
</SvgIcon>
);
DeviceSignalCellular0Bar = pure(DeviceSignalCellular0Bar);
DeviceSignalCellular0Bar.displayName = 'DeviceSignalCellular0Bar';
DeviceSignalCellular0Bar.muiName = 'SvgIcon';
export default DeviceSignalCellular0Bar;
|
src/js/components/Posts.js | slavapavlutin/pavlutin-node | import { chunk, reduce } from 'lodash';
import React from 'react';
import PostPreview from './PostPreview';
function Posts({ posts, tag }) {
if (posts.length === 0) {
return <p>No posts found.</p>;
}
return (
<section className="posts">
<ul className="nav-list">
{mapPostsToRows(posts, tag)}
</ul>
</section>
);
}
function mapPostsToRows(posts, tag) {
return chunk(posts, 3).map((ch) => {
const id = reduce(ch, (sum, n) => `${sum}#${n.id}`, '');
return (
<div key={id} className="posts__row">
{ch.map(mapPostToListItem(tag))}
</div>
);
});
}
function mapPostToListItem(tag) {
return function mapPostToListItemWithTag(p) {
return (
<li key={p.id} className="posts__post">
<PostPreview post={p} activeTag={tag} />
</li>
);
};
}
export default Posts;
|
assets/javascripts/kitten/karl/pages/news-list/index.js | KissKissBankBank/kitten | import React from 'react'
import NewsCard from './news-card'
import styled, { css } from 'styled-components'
import {
ArrowIcon,
ScreenConfig,
HorizontalStroke,
Title,
Paragraph,
Text,
Container,
Button,
InstrumentTagIcon,
pxToRem,
COLORS,
} from 'kitten'
const Head = styled.div`
background-color: ${COLORS.primary5};
margin-bottom: ${pxToRem(100)};
`
const HeadContainer = styled(Container)`
height: 100px;
display: flex;
justify-content: space-between;
align-items: center;
`
const AnchorLink = styled(Text)`
padding: ${pxToRem(15)} ${pxToRem(30)};
${props =>
props.selected &&
css`
color: ${COLORS.background1};
background-color: ${COLORS.primary1};
border-radius: var(--border-radius-xs);
`}
`
const BackLink = styled(Text)`
display: flex;
align-items: center;
`
const LeftArrowIcon = styled(ArrowIcon)`
fill: ${COLORS.primary1};
margin-right: ${pxToRem(5)};
`
const NewsContainer = styled.div`
padding: 0 ${pxToRem(20)};
@media (min-width: ${pxToRem(ScreenConfig.M.min)}) {
padding: 0 ${pxToRem(100)};
}
@media (min-width: ${pxToRem(ScreenConfig.L.min)}) {
padding: 0 ${pxToRem(160)};
}
`
const BlockTitle = styled(Title)`
margin-top: ${pxToRem(100)};
`
const NewsList = () => {
return (
<>
<Head className="k-u-hidden@s-down">
<HeadContainer>
<BackLink
weight="bold"
size="small"
color="primary1"
tag="a"
href="#"
>
<LeftArrowIcon direction="left" /> Retour au projet
</BackLink>
<div>
<AnchorLink
weight="bold"
size="small"
color="font1"
tag="a"
href="#"
selected
>
Brouillons
</AnchorLink>
<AnchorLink
weight="bold"
size="small"
color="font1"
tag="a"
href="#"
>
Programmées
</AnchorLink>
<AnchorLink
weight="bold"
size="small"
color="font1"
tag="a"
href="#"
>
Publiées
</AnchorLink>
</div>
<Button modifier="beryllium">
<InstrumentTagIcon width="14" />
<span>Créer une nouvelle actu</span>
</Button>
</HeadContainer>
</Head>
<Container>
<NewsContainer>
<Button size="large" fit="fluid" modifier="helium">
<InstrumentTagIcon width="14" />
<span>Créer une nouvelle actu</span>
</Button>
<BlockTitle tag="h2" modifier="secondary" margin={false}>
Mes Brouillons
</BlockTitle>
<HorizontalStroke
size="large"
className="k-u-margin-top-double k-u-margin-bottom-quadruple"
/>
<Paragraph modifier="secondary">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Cum sociis natoque penatibus et magnis
dis parturient montes.
</Paragraph>
<NewsCard title="My Actu #1">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus…
</NewsCard>
<NewsCard title="My Actu #2">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus…
</NewsCard>
<BlockTitle tag="h2" modifier="secondary" margin={false}>
Programmées
</BlockTitle>
<HorizontalStroke
size="large"
className="k-u-margin-top-double k-u-margin-bottom-quadruple"
/>
<Paragraph modifier="secondary">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Cum sociis natoque penatibus et magnis
dis parturient montes.
</Paragraph>
<NewsCard title="My Actu #3" publishedAt={Date.now()}>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus…
</NewsCard>
<NewsCard title="My Actu #4" publishedAt={Date.now()}>
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean
commodo ligula eget dolor. Aenean massa. Cum sociis natoque
penatibus et magnis dis parturient montes, nascetur ridiculus mus…
</NewsCard>
</NewsContainer>
</Container>
</>
)
}
export default NewsList
|
src/components/icons/SmsIcon.js | austinknight/ui-components | import React from 'react';
const SmsIcon = props => (
<svg
{...props.size || { width: "24px", height: "24px" }}
{...props}
viewBox="0 0 24 24"
>
{props.title && <title>{props.title}</title>}
<defs>
<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-2zM9 11H7V9h2v2zm4 0h-2V9h2v2zm4 0h-2V9h2v2z"
id="sms-path-1"
/>
</defs>
<g
stroke="none"
strokeWidth="1"
fillRule="evenodd"
>
<mask id="sms-mask-2" fill="white">
<use xlinkHref="#sms-path-1" />
</mask>
<use id="Sms-Combined-Shape" xlinkHref="#sms-path-1" />
</g>
</svg>
);
export default SmsIcon;
|
lib/component.js | AlmirKadric/hyperterm | import React from 'react';
import {StyleSheet, css} from 'aphrodite-simple';
import {shouldComponentUpdate} from 'react-addons-pure-render-mixin';
export default class Component extends React.Component {
constructor() {
super();
this.styles_ = this.createStyleSheet();
this.cssHelper = this.cssHelper.bind(this);
if (!this.shouldComponentUpdate) {
this.shouldComponentUpdate = shouldComponentUpdate.bind(this);
}
}
createStyleSheet() {
if (!this.styles) {
return {};
}
const styles = this.styles();
if (typeof styles !== 'object') {
throw new TypeError('Component `styles` returns a non-object');
}
return StyleSheet.create(this.styles());
}
// wrap aphrodite's css helper for two reasons:
// - we can give the element an unaltered global classname
// that can be used to introduce global css side effects
// for example, through the configuration, web inspector
// or user agent extensions
// - the user doesn't need to keep track of both `css`
// and `style`, and we make that whole ordeal easier
cssHelper(...args) {
const classes = args
.map(c => {
if (c) {
// we compute the global name from the given
// css class and we prepend the component name
//
// it's important classes never get mangled by
// uglifiers so that we can avoid collisions
const component = this.constructor.name
.toString()
.toLowerCase();
const globalName = `${component}_${c}`;
return [globalName, css(this.styles_[c])];
}
return null;
})
// skip nulls
.filter(v => Boolean(v))
// flatten
.reduce((a, b) => a.concat(b));
return classes.length ? classes.join(' ') : null;
}
render() {
// convert static objects from `babel-plugin-transform-jsx`
// to `React.Element`.
if (!this.template) {
throw new TypeError('Component doesn\'t define `template`');
}
// invoke the template creator passing our css helper
return this.template(this.cssHelper);
}
}
|
docs/src/components/templates/dashboard/Menu.js | HsuTing/cat-components | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import radium, {StyleRoot} from 'radium';
import {Route} from 'react-router-dom';
import Img from 'cat-components/lib/img';
import Link from 'cat-components/lib/link';
import * as style from './style/menu';
import pages from './../temp/dashboard';
@radium
export default class Menu extends React.Component {
static propTypes = {
img: PropTypes.string.isRequired,
email: PropTypes.string.isRequired,
style: PropTypes.object,
hide: PropTypes.func
}
static defaultProps = {
hide: () => {}
}
render() {
const {style: propsStyle, img, email, hide} = this.props;
return (
<StyleRoot style={[style.root, propsStyle]}>
<div style={style.header}>
<div />
<div style={style.imgBackground}>
<Img style={[style.imgBackground, style.img]}
src={img}
type='div'
/>
</div>
<p style={style.email}
>{email}</p>
</div>
<div style={style.linkRoot}>
{pages.map(({title, path}, index) => (
<Route key={index}
path={path}
exact
>
{({match}) => (
<Link style={style.link(match)}
to={path}
onClick={() => hide()}
>{title}</Link>
)}
</Route>
))}
</div>
</StyleRoot>
);
}
}
|
node_modules/react-bootstrap/es/CarouselItem.js | NathanBWaters/jb_club | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import ReactDOM from 'react-dom';
import TransitionEvents from './utils/TransitionEvents';
// TODO: This should use a timeout instead of TransitionEvents, or else just
// not wait until transition end to trigger continuing animations.
var propTypes = {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
index: React.PropTypes.number
};
var defaultProps = {
active: false,
animateIn: false,
animateOut: false
};
var CarouselItem = function (_React$Component) {
_inherits(CarouselItem, _React$Component);
function CarouselItem(props, context) {
_classCallCheck(this, CarouselItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleAnimateOutEnd = _this.handleAnimateOutEnd.bind(_this);
_this.state = {
direction: null
};
_this.isUnmounted = false;
return _this;
}
CarouselItem.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({ direction: null });
}
};
CarouselItem.prototype.componentDidUpdate = function componentDidUpdate(prevProps) {
var _this2 = this;
var active = this.props.active;
var prevActive = prevProps.active;
if (!active && prevActive) {
TransitionEvents.addEndEventListener(ReactDOM.findDOMNode(this), this.handleAnimateOutEnd);
}
if (active !== prevActive) {
setTimeout(function () {
return _this2.startAnimation();
}, 20);
}
};
CarouselItem.prototype.componentWillUnmount = function componentWillUnmount() {
this.isUnmounted = true;
};
CarouselItem.prototype.handleAnimateOutEnd = function handleAnimateOutEnd() {
if (this.isUnmounted) {
return;
}
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd(this.props.index);
}
};
CarouselItem.prototype.startAnimation = function startAnimation() {
if (this.isUnmounted) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ? 'right' : 'left'
});
};
CarouselItem.prototype.render = function render() {
var _props = this.props,
direction = _props.direction,
active = _props.active,
animateIn = _props.animateIn,
animateOut = _props.animateOut,
className = _props.className,
props = _objectWithoutProperties(_props, ['direction', 'active', 'animateIn', 'animateOut', 'className']);
delete props.onAnimateOutEnd;
delete props.index;
var classes = {
item: true,
active: active && !animateIn || animateOut
};
if (direction && active && animateIn) {
classes[direction] = true;
}
if (this.state.direction && (animateIn || animateOut)) {
classes[this.state.direction] = true;
}
return React.createElement('div', _extends({}, props, {
className: classNames(className, classes)
}));
};
return CarouselItem;
}(React.Component);
CarouselItem.propTypes = propTypes;
CarouselItem.defaultProps = defaultProps;
export default CarouselItem; |
packages/material-ui-icons/src/LocationOn.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M12 2C8.13 2 5 5.13 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.87-3.13-7-7-7zm0 9.5c-1.38 0-2.5-1.12-2.5-2.5s1.12-2.5 2.5-2.5 2.5 1.12 2.5 2.5-1.12 2.5-2.5 2.5z" /></g>
, 'LocationOn');
|
app/components/HomePageComponents/index.js | rapicastillo/beautifulrising-client | /**
*
* HomePageComponents
*
*/
import React from 'react';
import styled from 'styled-components';
import { CommonLeftHeader } from 'components/CommonComponents';
import SmallSectionHeader from 'components/SmallSectionHeader';
function HomePageComponents() {
return (
<div>
</div>
);
}
HomePageComponents.propTypes = {
};
export const LeftHeader = styled(SmallSectionHeader)`
text-align: center;
`;
export const LeftContainer = styled.div`
padding-bottom: 10px;
border-bottom: 2px solid black;
margin-bottom: 50px;
padding-top: 10px;
`;
export default HomePageComponents;
|
website/src/pages/index.js | scalapb/ScalaPB | import React from 'react';
import clsx from 'clsx';
import Layout from '@theme/Layout';
import Link from '@docusaurus/Link';
import useDocusaurusContext from '@docusaurus/useDocusaurusContext';
import useBaseUrl from '@docusaurus/useBaseUrl';
import styles from './styles.module.css';
const features = [
{
title: <>Easy to Use</>,
description: (
<>
ScalaPB translates Protocol Buffers to Scala case classes.
The generated API is easy to use!
</>
),
},
{
title: <>Supports proto2 and proto3</>,
description: (
<>
ScalaPB is built as a protoc plugin and has perfect compatibility
with the protobuf language specification.
</>
),
},
{
title: <>Nested updates</>,
description: (
<>
Updating immutable nested structure is made easy by an optional
lenses support. <a href="docs/generated-code#updating-messages">Learn more.</a>
</>
),
},
{
title: <>Interoperate with Java</>,
description: (
<>
Scala Protocol Buffers can be converted to Java and vice versa. Scala and
Java protobufs can co-exist in the same project to make it easier to gradually
migrate, or interact with legacy Java APIs.
</>
),
},
{
title: <>Scala.js support</>,
description: (
<>
ScalaPB fully supports Scala.js so you can write Scala programs that use your
domain-specific Protocol Buffers in the browser! <a href="docs/scala.js">Learn more.</a>
</>
),
},
{
title: <>gRPC</>,
description: (
<>
Build gRPC servers and clients with ScalaPB. ScalaPB ships with its
own wrapper around the official gRPC Java implementation. There are gRPC
libraries for ZIO, Cats Effect and Akka. <a href="docs/grpc"></a>
</>
),
},
];
const sponsors = [{
name: <>MOIA</>,
profileUrl: 'https://moia.io'
}];
function Feature({imageUrl, title, description}) {
const imgUrl = useBaseUrl(imageUrl);
return (
<div className={clsx('col col--4', styles.feature)}>
{imgUrl && (
<div className="text--center">
<img className={styles.featureImage} src={imgUrl} alt={title} />
</div>
)}
<h3>{title}</h3>
<p>{description}</p>
</div>
);
}
function Sponsor({name, profileUrl}) {
return (
<div className={clsx('col col--4', styles.sponsor)}>
<a href={profileUrl}>{name}</a>
</div>
);
}
function Home() {
const context = useDocusaurusContext();
const {siteConfig = {}} = context;
const img = useBaseUrl('img/ScalaPB.png');
return (
<Layout
title="ScalaPB: Protocol Buffer Compiler for Scala"
description="ScalaPB compiles protocol buffers into Scala case classes.">
<header className={clsx('hero hero--primary', styles.heroBanner)}>
<div className="container">
<img src={img} width="80%"/>
<p className="hero__subtitle">{siteConfig.tagline}</p>
<div className={styles.buttons}>
<Link
className={clsx(
// 'button button--outline button--secondary button--lg',
styles.indexCtasGetStartedButton,
)}
to={useBaseUrl('docs/')}>
Get Started
</Link>
</div>
</div>
</header>
<main>
{features && features.length > 0 && (
<section className={styles.features}>
<div className="container">
<div className="row">
{features.map((props, idx) => (
<Feature key={idx} {...props} />
))}
</div>
</div>
</section>
)}
<section className={styles.sponsors}>
<div className="container">
<h3>Sponsors</h3>
{sponsors.map((props, idx) => (
<Sponsor key={idx} {...props} />
))}
<a href="https://github.com/sponsors/thesamet">Become a sponsor.</a>
</div>
</section>
</main>
</Layout>
);
}
export default Home;
|
packages/material-ui-icons/tpl/SvgIcon.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '{{{ muiRequireStmt }}}';
let {{className}} = props =>
<SvgIcon {...props}>
{{{paths}}}
</SvgIcon>;
{{className}} = pure({{className}});
{{className}}.muiName = 'SvgIcon';
export default {{className}};
|
docs/app/Examples/elements/Loader/Variations/LoaderExampleInline.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Loader } from 'semantic-ui-react'
const LoaderExampleInline = () => (
<Loader active inline />
)
export default LoaderExampleInline
|
src/components/posts_show.js | richgurney/ReduxBlogBoilerPlate | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { fetchPost, deletePost } from '../actions';
import MarkdownRenderer from 'react-markdown-renderer';
import Parser from 'html-react-parser';
import { Link } from 'react-router-dom';
import DateFormat from 'dateformat';
class PostsShow extends Component {
componentDidMount() {
const { id } = this.props.match.params;
this.props.fetchPost(id);
}
onDeleteClick() {
const { id } = this.props.match.params;
this.props.deletePost(id, () => {
this.props.history.push('/');
});
}
renderMarkdown(body) {
return (
<div>
{Parser(body)}
</div>
)
}
formatStartDate(date) {
return DateFormat(date, "dddd - mmmm dS - yyyy, h:MM TT");
}
render() {
const { post } = this.props;
if (!post) {
return <div>Loading...</div>
}
return (
<div className="blogContainer">
<div className="blog-title">
<h1>{post.title}</h1>
</div>
<div className="blog-details">
RICHARD GURNEY
</div>
<div className="blog-details">
{this.formatStartDate(post.createdAt)}
</div>
<div className="card-body">
<div className="card-text">
{this.renderMarkdown(post.body)}
</div>
<div className="card-subtitle mb-2 text-muted">
RG- <Link to="/">Back</Link>
</div>
</div>
<button
type="button"
className="btn btn-danger"
onClick={this.onDeleteClick.bind(this)}
> Delete
</button>
</div>
)
}
}
function mapStateToProps({ posts }, ownProps) {
return { post: posts[ownProps.match.params.id] }
}
export default connect(mapStateToProps, { fetchPost, deletePost })(PostsShow);
|
src/index.js | DarklyLabs/LaserWeb4 | import React from 'react'
import { render } from 'react-dom'
import { compose, applyMiddleware, createStore } from 'redux';
import { Provider } from 'react-redux';
import logger from 'redux-logger';
import persistState, {mergePersistedState} from 'redux-localstorage'
import adapter from 'redux-localstorage/lib/adapters/localStorage';
import filter from 'redux-localstorage-filter';
export const LOCALSTORAGE_KEY = 'LaserWeb';
const hot = (state, action) => {
return require('./reducers').default(state, action);
};
const reducer = compose(
mergePersistedState((initialState, persistedState) => {
let state = { ...initialState, ...persistedState };
state.camera = require('./reducers/camera').resetCamera(null, state.settings);
return hot(state, { type: 'LOADED' });
})
)(hot);
const storage = compose(
filter(['settings','machineProfiles','splitters','materialDatabase'])
)(adapter(window.localStorage));
// adds getState() to any action to get the global Store :slick:
const globalstoreMiddleWare = store => next => action => {
next({ ...action, getState: store.getState });
};
const middleware = compose(
applyMiddleware(
logger({ collapsed: true }),
globalstoreMiddleWare
),
persistState(storage, LOCALSTORAGE_KEY),
);
const store = createStore(reducer, middleware);
// Bad bad bad
export function GlobalStore()
{
return store;
}
function Hot(props) {
const LaserWeb = require('./components/laserweb').default;
return <LaserWeb />;
}
function renderHot() {
render((
<Provider store={store}>
<Hot />
</Provider>
), document.getElementById('laserweb'));
}
renderHot();
if (module.hot) {
module.hot.accept('./reducers', renderHot);
module.hot.accept('./components/laserweb', renderHot);
}
|
src/routes.js | idealgardens/codeword | import React from 'react' // eslint-disable-line
import { Route, IndexRoute, Router, browserHistory } from 'react-router'
import {
App,
Home,
Account,
Login,
Signup,
NotFound,
Locations,
Location
} from './containers'
export default (store) => (
<Router history={browserHistory} store={store}>
<Route path='/' component={App}>
<IndexRoute component={Home} />
<Route path='login' component={Login} />
<Route path='signup' component={Signup} />
<Route path='account' component={Account} />
<Route path='locations' component={Locations} />
<Route path='locations/:locationName' component={Location} />
<Route path='*' component={NotFound} />
</Route>
</Router>
)
|
src/Mememe.js | amysimmons/mememe | import Instruction from './Instruction';
import Container from './Container';
import Share from './Share';
import React from 'react';
import request from 'superagent';
var Mememe = React.createClass({
getInitialState (){
var memesGenerated = false;
return{
memesGenerated: memesGenerated
};
},
generateMemes (descriptions){
for(var key in descriptions) {
var VALUE = descriptions[key];
var YOUR_API_KEY = "xxx";
var YOUR_CSE_ID = "yyy";
var searchQuery = `https://www.googleapis.com/customsearch/v1?key=${YOUR_API_KEY}&cx=${YOUR_CSE_ID}&q=${VALUE}&searchType=image&fileType=jpg&imgSize=small&alt=json`
request
.get(searchQuery)
.end((err, results) => {
debugger
})
debugger
}
var memesGenerated = true;
this.setState({memesGenerated: memesGenerated});
},
render (){
var generateMemes = this.generateMemes;
var memesGenerated = this.state.memesGenerated;
return (
<div className="mememe">
<Instruction/>
<Container
memesGenerated={memesGenerated}
generateMemes={generateMemes}/>
<Share/>
</div>
)
}
});
module.exports = Mememe; |
src/app/components/auth/groups/groupItem.js | rokbar/vivdchat | import React from 'react';
import { Link } from 'react-router';
import {
TableRow,
TableRowColumn
} from 'material-ui/Table';
import IconButton from 'material-ui/IconButton';
import AcceptIcon from 'material-ui/svg-icons/action/check-circle';
import CancelIcon from 'material-ui/svg-icons/navigation/cancel';
import ChatIcon from 'material-ui/svg-icons/communication/chat';
import LeaveIcon from 'material-ui/svg-icons/content/remove-circle';
import InviteIcon from 'material-ui/svg-icons/social/person-add';
import enumState from './enumState';
import { map } from 'lodash';
const GroupItem = (props) => {
const handleAccept = (e) => {
e.preventDefault();
props.handleSubmit(props.id, props.acceptInvitation);
}
const handleDecline = (e) => {
e.preventDefault();
props.handleSubmit(props.id, props.declineInvitation);
}
const handleLeave = (e) => {
e.preventDefault();
props.handleSubmit(props.id, props.leaveGroup);
}
const leaderActionButtons = () => {
return (
<div style={{ display: 'inline-flex' }}>
<IconButton containerElement={<Link to={`/chat/${props.id}`} />} tooltip="Join chat" tooltipPosition="left">
<ChatIcon />
</IconButton>
<IconButton onClick={() => props.handleOpenInviteUser(props.id)} tooltip="Invite user" tooltipPosition="left">
<InviteIcon />
</IconButton>
</div>
)
};
const actionButtons = (state) => {
switch (state) {
case 0:
return (
<div style={{ display: 'inline-flex' }}>
<form method="post" onSubmit={(e) => handleAccept(e)}>
<IconButton type="submit" tooltip="Accept invitation" tooltipPosition="left">
<AcceptIcon />
</IconButton>
</form>
<form method="post" onSubmit={(e) => handleDecline(e)}>
<IconButton type="submit" tooltip="Decline invitation" tooltipPosition="left">
<CancelIcon />
</IconButton>
</form>
</div>
);
case 1:
return (
<div style={{ display: 'inline-flex' }}>
<IconButton containerElement={<Link to={`/chat/${props.id}`} />} tooltip="Join chat" tooltipPosition="right">
<ChatIcon />
</IconButton>
<form method="post" onSubmit={(e) => handleLeave(e)}>
<IconButton type="submit" tooltip="Leave group" tooltipPosition="left">
<LeaveIcon />
</IconButton>
</form>
</div>
);
case 2:
return (
<div>
<span>No actions</span>
</div>
);
case 3:
return (
<div>
<span>No actions</span>
</div>
);
}
};
return (
<TableRow>
<TableRowColumn style={{ textAlign: 'center' }}>{props.name}</TableRowColumn>
<TableRowColumn style={{ textAlign: 'center' }}>
{props.user.id === props.leader ? <div>You are group leader</div> : enumState[props.user.state] }
</TableRowColumn>
<TableRowColumn style={{ textAlign: 'center' }}>
{props.user.id === props.leader ? leaderActionButtons() : actionButtons(props.user.state)}
</TableRowColumn>
</TableRow>
);
}
export default GroupItem;
|
src/common/components/Landing.js | ThinkingInReact/ThinkingInReact | import React, { Component } from 'react';
class Landing extends Component {
render() {
return (
<div className="Landing">
You have reached the top secret landing page!
</div>
);
}
}
export default Landing;
|
src/Main/SelectorBase.js | enragednuke/WoWAnalyzer | import React from 'react';
import ReactTooltip from 'react-tooltip';
class SelectorBase extends React.PureComponent {
static propTypes = {
};
constructor(props) {
super(props);
this.state = {
show: false,
};
this.handleClick = this.handleClick.bind(this);
this.handleDocumentClick = this.handleDocumentClick.bind(this);
this.setRef = this.setRef.bind(this);
}
componentDidMount() {
document.body.addEventListener('click', this.handleDocumentClick);
document.body.addEventListener('touchend', this.handleDocumentClick);
}
componentWillUnmount() {
document.body.removeEventListener('click', this.handleDocumentClick);
document.body.removeEventListener('touchend', this.handleDocumentClick);
ReactTooltip.hide();
}
handleClick(event) {
this.setState({ show: !this.state.show });
}
handleDocumentClick(event) {
if (this.ref && !this.ref.contains(event.target)) {
this.setState({ show: false });
}
}
setRef(node) {
this.ref = node;
}
}
export default SelectorBase;
|
src/js/client/app.js | juancjara/bettson-notifier-chrome-extension | import React from 'react';
import Main from './Main.jsx';
import db from '../background/db';
React.render(<Main />,
document.getElementById('app'));
|
src/components/DesignerProjects.js | computer-lab/salon94design.com | import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import styled from 'emotion/react'
import cx from 'classnames'
import {
sansfont,
baseUl,
childLink,
Header2,
Header3,
SimpleLinkList,
SimpleLinkListItem,
SimpleLinkListSection,
} from '../layouts/emotion-base'
import { projectLink } from '../util'
const Container = styled.section`
margin-top: 20px;
`
const DesignerProjects = ({ projects }) => {
if (!projects || projects.length === 0) {
return null
}
// XXX: Projects with missing or invalid dates will not be displayed
projects = projects
.map(p => {
const start_date = p.start_date ? new Date(p.start_date) : null
const end_date = p.end_date ? new Date(p.end_date) : null
return !isNaN(start_date.getTime()) ? { ...p, start_date, end_date } : null
})
.filter(p => p != null)
// Sort by reverse-date
projects.sort((a, b) => b.start_date.getTime() - a.start_date.getTime())
// Group by year
const projectsByYear = projects.reduce((acc, project) => {
const year = project.start_date.getFullYear()
if (!acc[year]) {
acc[year] = [project]
}
else {
acc[year].push(project)
}
return acc
}, {})
const descendingYears = Object.keys(projectsByYear).sort().reverse()
return (
<Container>
<Header2>Exhibitions</Header2>
{descendingYears.map(year => (
<SimpleLinkListSection key={year}>
<Header3>{year}</Header3>
<SimpleLinkList>
{projectsByYear[year].map(item => (
<SimpleLinkListItem key={item.slug}>
<Link to={projectLink(item)}>{item.title}</Link>
</SimpleLinkListItem>
))}
</SimpleLinkList>
</SimpleLinkListSection>
))}
</Container>
)
}
DesignerProjects.propTypes = {
projects: PropTypes.array.isRequired,
}
export default DesignerProjects
|
SQL/client/src/components/dumb/FormBlock/index.js | thebillkidy/MERGE-Stack | import React from 'react';
import Input from '../Input';
import Button from '../Button';
import Radio from '../Radio';
import Label from '../Label';
// import './FormBlock.css';
export default class FormBlock extends React.Component {
static propTypes = {
isHideLabel: React.PropTypes.bool
}
getElement() {
// Pull own propTypes from props and put remaining one in other variable
// Also possible: const { isHideLabel, ...elProps } = this.props;, but returns unused variable
// More info: https://facebook.github.io/react/warnings/unknown-prop.html
const elProps = Object.assign({}, this.props);
delete elProps.isHideLabel;
if (this.props.type === 'button' || this.props.type === 'submit') {
return <Button className="Button" {...elProps} />;
} else if (this.props.type === 'radio') {
return <Radio className="form-field" {...elProps} />;
} else {
return <Input className="form-field" {...elProps} />;
}
}
render() {
const isHideLabel = this.props.isHideLabel;
return (
<div className={this.props.className || 'form-block'}>
{!isHideLabel && <Label className="form-label">{this.props.label}</Label>}
{this.getElement()}
</div>
);
}
}
|
js/components/addItem/index.js | bsusta/NativeBase-KitchenSink |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Input, Picker, Item, Footer, FooterTab, Container, Header, Title, Content, Button, Icon, Text, Left, Right, Body, List, ListItem, View } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { openDrawer, closeDrawer } from '../../actions/drawer';
import styles from './styles';
const {
pushRoute,
} = actions;
const datas = [
];
class AddItem extends Component {
static propTypes = {
openDrawer: React.PropTypes.func,
pushRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
pushRoute(route) {
this.props.pushRoute({ key: route, index: 1 }, this.props.navigation.key);
}
constructor(props) {
super(props);
this.state = {
selectedItem: undefined,
selected1: 'key0',
results: {
items: []
},
};
}
onValueChange(value: string) {
this.setState({
selected1: value
});
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Add/Edit item</Title>
</Body>
</Header>
<Content style={{ padding: 15 }}>
<Text note>Name</Text>
<View style={{ borderColor: '#CCCCCC', borderWidth: 0.5, marginBottom: 15 }}>
<Input />
</View>
<Text note>Price/unit</Text>
<View style={{ borderColor: '#CCCCCC', borderWidth: 0.5, marginBottom: 15 }}>
<Input />
</View>
<Text note>Unit</Text>
<View style={{ borderColor: '#CCCCCC', borderWidth: 0.5, marginBottom: 15 }}>
<Picker
supportedOrientations={['portrait', 'landscape']}
iosHeader="Select one"
mode="dropdown"
selectedValue={this.state.selected1}
onValueChange={this.onValueChange.bind(this)}>
<Item label="ks" value="key0" />
<Item label="th" value="key1" />
</Picker>
</View>
<Text note>Quantity</Text>
<View style={{ borderColor: '#CCCCCC', borderWidth: 0.5, marginBottom: 15 }}>
<Input />
</View>
</Content>
<Footer>
<FooterTab>
<Button onPress={Actions.addUser} iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }}>
<Icon active style={{ color: 'white' }} name="trash" />
<Text style={{ color: 'white' }} >Delete</Text>
</Button>
</FooterTab>
<FooterTab>
<Button onPress={Actions.addUser} iconLeft style={{ flexDirection: 'row', borderColor: 'white', borderWidth: 0.5 }}>
<Icon active style={{ color: 'white' }} name="add" />
<Text style={{ color: 'white' }} >Save</Text>
</Button>
</FooterTab>
</Footer>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
closeDrawer: () => dispatch(closeDrawer()),
pushRoute: (route, key) => dispatch(pushRoute(route, key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(AddItem);
|
common/components/ide/panels/TestAuthoringPanel.js | ebertmi/webbox | import React from 'react';
import Editor from '../../Editor';
import optionManager from '../../../models/options';
import { Button } from '../../bootstrap';
export default class TestAuthoringPanel extends React.Component {
constructor(props) {
super(props);
this.onChangeOption = this.onChangeOption.bind(this);
this.onChange = this.onChange.bind(this);
this.onSave = this.onSave.bind(this);
// Initial state
this.state = {
options: optionManager.getEditorOptions()
};
}
componentDidMount() {
this.editor.focus();
this.props.item.on('change', this.onChange);
optionManager.on('change', this.onChangeOption);
this.onChangeOption();
}
componentWillUnmount() {
this.props.item.removeListener('change', this.onChange);
optionManager.removeListener('change', this.onChangeOption);
}
onChange() {
}
onChangeOption() {
this.setState({
options: optionManager.getEditorOptions()
});
}
onSave(e) {
e.preventDefault();
this.props.item.saveTests();
}
render() {
let file = this.props.item.getTestCode();
if (file == null) {
file = this.props.item.createTestCode();
}
return (
<div className="tests-panel" onSubmit={e => e.preventDefault()}>
<h3>Tests</h3>
<div>
<p className="text-muted">Hier können Sie die Unit-Tests bearbeiten. Bitte benutzen Sie das jeweilige Template für die Programmiersprache.</p>
<Button bsStyle="success" className="form-group" onClick={this.onSave}>Speichern</Button>
</div>
<hr />
<Editor
options={this.state.options}
file={file}
ref={editor => {this.editor = editor;}}
/>
</div>
);
}
}
|
src/svg-icons/device/signal-cellular-connected-no-internet-0-bar.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet0Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 22h2v-2h-2v2zm0-12v8h2v-8h-2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet0Bar = pure(DeviceSignalCellularConnectedNoInternet0Bar);
DeviceSignalCellularConnectedNoInternet0Bar.displayName = 'DeviceSignalCellularConnectedNoInternet0Bar';
DeviceSignalCellularConnectedNoInternet0Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet0Bar;
|
dapp/src/shared/dao/token/components/main.js | airalab/DAO-IPCI | import React from 'react'
import { Link } from 'react-router'
import { translate } from 'react-i18next'
import { Layout } from '../../main/components'
import Form from '../containers/formFunc'
const Main = (props) => {
const { address, name, totalSupply, balance, t } = props
const menu = (<div className="btn-group" style={{ marginBottom: 10 }}>
<Link to={'/dao/token/transfer/' + address} className="btn btn-default">{t('menuSend')}</Link>
<Link to={'/dao/token/approve/' + address} className="btn btn-default">{t('menuApprove')}</Link>
<Link to={'/dao/token/emission/' + address} className="btn btn-default">{t('menuEmission')}</Link>
</div>)
return (<Layout title={t('titlePrefix') + ' ' + name} address={address} menu={menu}>
<p><b>{t('allTokens')}</b>: {totalSupply}</p>
<p><b>{t('myBalance')}</b>: {balance}</p>
<div className="panel panel-default">
<div className="panel-heading">{t('Balance')}</div>
<div className="panel-body">
<Form address={address} action="balanceOf" />
</div>
</div>
</Layout>)
}
export default translate(['token'])(Main)
|
app/javascript/mastodon/features/ui/components/embed_modal.js | cobodo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, FormattedMessage, injectIntl } from 'react-intl';
import api from 'mastodon/api';
import IconButton from 'mastodon/components/icon_button';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
});
export default @injectIntl
class EmbedModal extends ImmutablePureComponent {
static propTypes = {
url: PropTypes.string.isRequired,
onClose: PropTypes.func.isRequired,
onError: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
}
state = {
loading: false,
oembed: null,
};
componentDidMount () {
const { url } = this.props;
this.setState({ loading: true });
api().post('/api/web/embed', { url }).then(res => {
this.setState({ loading: false, oembed: res.data });
const iframeDocument = this.iframe.contentWindow.document;
iframeDocument.open();
iframeDocument.write(res.data.html);
iframeDocument.close();
iframeDocument.body.style.margin = 0;
this.iframe.width = iframeDocument.body.scrollWidth;
this.iframe.height = iframeDocument.body.scrollHeight;
}).catch(error => {
this.props.onError(error);
});
}
setIframeRef = c => {
this.iframe = c;
}
handleTextareaClick = (e) => {
e.target.select();
}
render () {
const { intl, onClose } = this.props;
const { oembed } = this.state;
return (
<div className='modal-root__modal report-modal embed-modal'>
<div className='report-modal__target'>
<IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={16} />
<FormattedMessage id='status.embed' defaultMessage='Embed' />
</div>
<div className='report-modal__container embed-modal__container' style={{ display: 'block' }}>
<p className='hint'>
<FormattedMessage id='embed.instructions' defaultMessage='Embed this status on your website by copying the code below.' />
</p>
<input
type='text'
className='embed-modal__html'
readOnly
value={oembed && oembed.html || ''}
onClick={this.handleTextareaClick}
/>
<p className='hint'>
<FormattedMessage id='embed.preview' defaultMessage='Here is what it will look like:' />
</p>
<iframe
className='embed-modal__iframe'
frameBorder='0'
ref={this.setIframeRef}
sandbox='allow-same-origin'
title='preview'
/>
</div>
</div>
);
}
}
|
client/views/omnichannel/appearance/AppearanceForm.stories.js | VoiSmart/Rocket.Chat | import React from 'react';
import AppearanceForm from './AppearanceForm';
export default {
title: 'omnichannel/AppearanceForm',
component: AppearanceForm,
};
export const Default = () => <AppearanceForm />;
|
src/components/Header/Header.js | neilhighley/maybeconsulting | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react';
import styles from './Header.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
import Navigation from '../Navigation';
@withStyles(styles)
class Header extends Component {
render() {
return (
<div className="Header">
<div className="Header-container">
<a className="Header-brand" href="/" onClick={Link.handleClick}>
<img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" />
<span className="Header-brandTxt">Your Company</span>
</a>
<Navigation className="Header-nav" />
<div className="Header-banner">
<h1 className="Header-bannerTitle">React</h1>
<p className="Header-bannerDesc">Complex web apps made easy</p>
</div>
</div>
</div>
);
}
}
export default Header;
|
client/components/Nav/MobileDrawer.js | ncrmro/ango | import React from 'react'
import Navigation from 'react-mdc-web/lib/Drawer/Navigation'
import Drawer from 'react-mdc-web/lib/Drawer/Drawer'
import DrawerHeader from 'react-mdc-web/lib/Drawer/DrawerHeader'
import DrawerHeaderContent from 'react-mdc-web/lib/Drawer/DrawerHeaderContent'
import DrawerContent from 'react-mdc-web/lib/Drawer/DrawerContent'
import { HomeLink } from './Nav'
type MobileDrawerProps = {
title: string,
}
const MobileDrawer = (props: MobileDrawerProps) =>
<Drawer
{...props}
>
<DrawerHeader>
<DrawerHeaderContent>
<HomeLink className='button_home-link' title={props.title} />
</DrawerHeaderContent>
</DrawerHeader>
<DrawerContent>
<Navigation>
{props.children}
</Navigation>
</DrawerContent>
</Drawer>
export default MobileDrawer |
src/HelpDialog.js | BenjaminCosman/alchemistsSolver | import React from 'react'
import Modal from 'antd/lib/modal'
function showHelpDialog() {
Modal.info({
title: 'Usage',
content: <>
<h3>Overview</h3>
<br/>
This app takes in things you learn during the game (primarily
experimental results), and helps you figure out what to publish, what
further experiments to do, etc. (We assume you already know
the <a href="http://czechgames.com/en/alchemists/downloads/">rules of
Alchemists</a>.)
<br/>
<br/>
<h3>Data Input (top of screen)</h3>
<br/>
<h4>Two-Ingredient Facts:</h4>
When you mix a potion, enter the results as a Two-Ingredient Fact.
Select all potions that you might have made, e.g. if you try to sell a
Red- to the adventurer and get the "wrong sign" result, select all three
plus potions. You can also use this to enter the results of
Master-Variant debunking.
<br/>
<br/>
<h4>One-Ingredient Facts:</h4>
A One-Ingredient Fact says the given ingredient has at least
one of the given aspects. This is useful when you observe one ingredient
of a potion using Periscope, or for Apprentice-Variant debunking. For
example, if an opponent mixes a "red or green plus" potion for the
adventurer and you Periscope an ingredient, check off both red+ and
green+.
<h5>Bayes Mode</h5>
In normal mode, a fact simply treats worlds as possible or
impossible. However sometimes you can infer more: for example, if you
learn by Periscope that the Fern was used to make an unknown Plus
potion, the only alchemical that you can outright eliminate is the
triple-Minus, but it is more likely that the Fern is the triple-Plus
than anything else. Check the Bayes Mode box if you want this extra
information taken into account.
<br/>
<br/>
<h4>Rival Publications:</h4>
When an opponent publishes a theory, you can enter it here.
The numbers you enter are an (8-way) odds ratio, so only the ratio
between them matters; scaling by a
constant factor (e.g. changing them from all 1s to all 10s) makes no
difference. Your chart will be updated in accordance with the odds you
choose - if you only want to record the publication without affecting
your deduction grid, leave the odds ratio at the "Completely Guessing"
default of all equal values. Try to enter
odds only based on what you know of your opponent's situation
and personality, and NOT based on your own experiments: the
probability calculator is already taking your experiments into account for
you and you should not double-count that evidence.
{/* COMING SOON:
Entering publications here will also allow you to filter them out of the
Experiment Optimizer in case you only want to publish something new, not
endorse. */}
<br/>
<br/>
<h4>(Expansion only) Other Facts:</h4>
Library, Golem Test, and Golem Animation Facts work similarly to the
above.
<br/>
<br/>
<h3>Publishing Tab</h3>
<br/>
<h4>Remaining Worlds:</h4>
Your world is described by the true mapping between ingredients and
alchemicals. At the beginning of the game any mapping is possible, so
there are 8 factorial (40320) worlds you
could be in. This counter tracks how many are still possible. You can
click Explore to look at the worlds one at a time (not recommended until
there are very few left!)
<br/>
<br/>
<h4>The Table:</h4>
Each cell tells you the probability its ingredient maps to its
alchemical (rounded to the nearest percentage point). This is simply the
fraction of remaining worlds that have that mapping (possibly weighted
by Bayes Mode facts).
<br/>
<br/>
<h4>(Expansion only) Encyclopedia:</h4>
Each cell tells you the probability its ingredient has its aspect, e.g.
a 10% in the upper left means there is a 10% chance the mushroom has
a red plus (and thus 90% chance it has a red minus).
<br/>
<br/>
<h4>(Expansion only) Golem:</h4>
Similar to the previous tables.
<br/>
<br/>
<h3>Experiment Optimizer Tab</h3>
<br/>
<h4>Ingredients to mix</h4>
A list of all pairs of ingredients you can mix into potions. You can
use the filter to include e.g. only the ones in your hand
at the moment.
<br/>
<br/>
<h4>Starred Theory Chance</h4>
The chance (as a percentage) that after performing this experiment you
can uniquely identify at least one new ingredient's alchemical.
<br/>
<br/>
<h4>Total Theory Chance</h4>
The chance that after performing this experiment you
can identify one new ingredient's alchemical to within two options that
differ in only one aspect (so you can safely publish a hedged theory).
Does NOT include the chance that a formerly-hedgable theory becomes
certain.
<br/>
<br/>
<h4>Shannon Entropy</h4>
Higher is better - roughly, if an experiment scores x bits of entropy
you can expect it to cut the number of possible worlds by a factor of
2^x. (E.g. your first experiment of the game will cut by a factor of
2^2.8 = 7). In particular, entropy of 0 means you will learn nothing
from the experiment. Note that you can usually get the most raw information
by testing ingredients you've never used before, yet to publish quickly
this may not be the best strategy.
<br/>
<br/>
<h4>Mix success</h4>
The chance that you will make one of the potions you want to make
(select them in its filter menu). Most useful for the Sell Potion action.
<br/>
<br/>
<h4>(Expansion only) Animate success</h4>
The chance that this pair would animate the golem.
</>
})
}
export {showHelpDialog}
|
src/main.js | slaweet/lisk-nano | import React from 'react';
import ReactDOM from 'react-dom';
import { HashRouter as Router } from 'react-router-dom';
import { Provider } from 'react-redux';
import { I18nextProvider } from 'react-i18next';
import App from './components/app';
// import history from './history';
import store from './store';
import i18n from './i18n'; // initialized i18next instance
import proxyLogin from './utils/proxyLogin';
import externalLinks from './utils/externalLinks';
import env from './constants/env';
import ipcLocale from './utils/ipcLocale';
if (env.production) {
proxyLogin.init();
ipcLocale.init(i18n);
externalLinks.init();
}
const rootElement = document.getElementById('app');
const renderWithRouter = Component =>
<Provider store={store}>
<Router>
<I18nextProvider i18n={ i18n }>
<Component />
</I18nextProvider>
</Router>
</Provider>;
ReactDOM.render(renderWithRouter(App), rootElement);
if (module.hot) {
module.hot.accept('./components/app', () => {
const NextRootContainer = require('./components/app').default;
ReactDOM.render(renderWithRouter(NextRootContainer), rootElement);
});
}
|
pages/blog/test-article-two.js | al6mina/jsCom | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import React, { Component } from 'react';
export default class extends Component {
render() {
return (
<div>
<h1>Test Article 2</h1>
<p>Coming soon.</p>
</div>
);
}
}
|
src/components/Home/PortfolioPreview.js | franciskim722/crypy | import React from 'react';
import PropTypes from 'prop-types';
import { VictoryPie } from 'victory';
export default class PortfolioPreview extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
};
}
render(){
const {balanceData} = this.props;
return (
<div className="pt-card pt-elevation-1 crypy-home-portfolio-preview">
<div className="crypy-home-portfolio-feed-container">
<h5>Portfolio Feed:</h5>
<div className="crypy-home-portfolio-feed">
{balanceData.map((balance, i) => {
return (
<div key={i} className="pt-card pt-elevation-2 pt-interactive crypy-home-feed-item" >
{`${balance.Currency}: ${balance.Balance}`}
</div>
);
})}
</div>
</div>
<div className="crypy-home-portfolio-viz">
<VictoryPie
height={400}
width={400}
data={balanceData}
x="Currency"
y="Balance"
colorScale={["tomato", "orange", "gold", "cyan", "navy" ]}
/>
</div>
</div>
);
}
}
PortfolioPreview.propTypes ={
balanceData: PropTypes.array
};
PortfolioPreview.contextTypes = {
router: PropTypes.object
};
|
src/routes/request/index.js | 102010cncger/antd-admin | import React from 'react'
import Mock from 'mockjs'
import { request, config } from 'utils'
import {
Row,
Col,
Card,
Select,
Input,
Button,
} from 'antd'
import styles from './index.less'
const { api } = config
const { dashboard, users, userLogin, user, v1test, v2test } = api
const requestOptions = [
{
url: user.replace('/:id', ''),
desc: 'intercept request by mock.js',
},
{
url: dashboard,
desc: 'intercept request by mock.js',
},
{
url: userLogin,
method: 'post',
data: {
username: 'guest',
password: 'guest',
},
desc: 'intercept request by mock.js',
},
{
url: users,
desc: 'intercept request by mock.js',
},
{
url: user,
desc: 'intercept request by mock.js',
data: Mock.mock({
id: '@id',
}),
},
{
url: user.replace('/:id', ''),
desc: 'intercept request by mock.js',
method: 'post',
data: Mock.mock({
name: '@cname',
nickName: '@last',
phone: /^1[34578]\d{9}$/,
'age|11-99': 1,
address: '@county(true)',
isMale: '@boolean',
email: '@email',
avatar () {
return Mock.Random.image('100x100', Mock.Random.color(), '#757575', 'png', this.nickName.substr(0, 1))
},
}),
},
{
url: user,
desc: 'intercept request by mock.js',
method: 'patch',
data: Mock.mock({
id: '@id',
name: '@cname',
}),
},
{
url: user,
desc: 'intercept request by mock.js',
method: 'delete',
data: Mock.mock({
id: '@id',
}),
},
{
url: v1test,
desc: 'intercept request by mock.js',
method: 'get',
},
{
url: v2test,
desc: 'intercept request by mock.js',
method: 'get',
},
{
url: 'http://api.asilu.com/weather/',
desc: 'cross-domain request, but match config.baseURL(./src/utils/config.js)',
},
{
url: 'http://www.zuimeitianqi.com/zuimei/queryWeather',
data: {
cityCode: '01010101',
},
desc: 'cross-domain request by yahoo\'s yql',
}]
export default class RequestPage extends React.Component {
constructor (props) {
super(props)
this.state = {
currntRequest: requestOptions[0],
method: 'get',
result: '',
}
}
componentDidMount () {
this.handleRequest()
}
handleRequest = () => {
const { currntRequest } = this.state
const { desc, ...requestParams } = currntRequest
this.setState({
...this.state,
result: <div key="sending">
请求中<br />
url:{currntRequest.url}<br />
method:{currntRequest.method}<br />
params:{currntRequest.data ? JSON.stringify(currntRequest.data) : 'null'}<br />
</div>,
})
request({ ...requestParams }).then((data) => {
const state = this.state
state.result = [this.state.result, <div key="complete"><div>请求完成</div>{JSON.stringify(data)}</div>]
this.setState(state)
})
}
handeleURLChange = (value) => {
const state = this.state
const curretUrl = value.split('?')[0]
const curretMethod = value.split('?')[1]
const currntItem = requestOptions.filter((item) => {
const { method = 'get' } = item
return curretUrl === item.url && curretMethod === method
})
state.currntRequest = currntItem[0]
this.setState(state)
}
render () {
const colProps = {
lg: 12,
md: 24,
}
const { result, currntRequest } = this.state
const { method = 'get' } = currntRequest
return (
<div className="content-inner">
<Row gutter={32}>
<Col {...colProps}>
<Card title="Request"
style={{
overflow: 'visible',
}}
>
<div className={styles.option}>
<Select
style={{
width: '100%',
flex: 1,
}}
defaultValue={`${method.toLocaleUpperCase()} ${requestOptions[0].url}`}
size="large"
onChange={this.handeleURLChange}
>
{requestOptions.map((item, index) => {
const m = item.method || 'get'
return (<Select.Option key={index} value={`${item.url}?${m}`}>
{`${m.toLocaleUpperCase()} `}{item.url}
</Select.Option>)
})}
</Select>
<Button type="primary" style={{ width: 100, marginLeft: 16 }} onClick={this.handleRequest}>发送</Button>
</div>
<div className={styles.params}>
<div className={styles.label}>Params:</div>
<Input disabled value={currntRequest.data ? JSON.stringify(currntRequest.data) : 'null'} size="large" style={{ width: 200 }} placeholder="null" />
<div style={{ flex: 1, marginLeft: 16 }}>{currntRequest.desc}</div>
</div>
<div className={styles.result}>
{result}
</div>
</Card>
</Col>
</Row>
</div>
)
}
}
|
src/components/Profile/Profile.js | RegOpz/RegOpzWebApp | import React, { Component } from 'react';
import ProfileLeftPane from './ProfileLeft';
import ProfileRightPane from './ProfileRight';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { actionFetchUsers, actionUpdateUser } from './../../actions/UsersAction';
class Profile extends Component {
constructor(props) {
super(props);
console.log(props);
this.state = {
user: this.props.login.user,
userDetails: []
};
this.saveEditedData = this.saveEditedData.bind(this);
this.resetChanges = this.resetChanges.bind(this);
}
componentWillMount() {
this.props.fetchUserDetails(this.state.user,undefined,true);
}
componentWillReceiveProps(nextProps) {
console.log(nextProps);
if (nextProps.userDetails.message === 'Data Updated') {
this.props.fetchUserDetails(this.state.user,undefined,true);
return;
}
if (nextProps.userDetails.error !== undefined) {
this.setState({
userDetails: nextProps.userDetails.error, //userDetails,
user: nextProps.login.user
});
}
else
this.setState({ user: nextProps.login.user });
}
saveEditedData(userData) {
console.log("update request....",userData);
this.props.updateUserDetails(userData);
}
resetChanges() {
this.props.fetchUserDetails(this.state.user,undefined,true);
}
render() {
return (
<div className="row form-container">
<div className="col-xs-12">
<div className="x_panel">
<div className="x_title">
<h2>User Profile<small> manage profile</small></h2>
<ul className="nav navbar-right panel_toolbox">
<li>
<a className="close-link" href="#/dashboard" title="Close"><i className="fa fa-close"></i></a>
</li>
</ul>
<div className="clearfix">
</div>
</div>
<div className="x_content">
<ProfileLeftPane
image="images/user.png"
username={this.state.user}
userData={this.state.userDetails}
saveEditedData={this.saveEditedData}
toInitialise={true}
/>
<ProfileRightPane />
</div>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
userDetails: state.user_details,
login: state.login_store
};
}
const matchDispatchToProps = (dispatch) => {
return {
fetchUserDetails: (user,userCheck,labelList) => {
dispatch(actionFetchUsers(user,userCheck,labelList));
},
updateUserDetails: (data) => {
dispatch(actionUpdateUser(data));
}
};
};
export default connect(mapStateToProps, matchDispatchToProps)(Profile);
|
app/javascript/mastodon/features/ui/components/zoomable_image.js | gol-cha/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import IconButton from 'mastodon/components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
compress: { id: 'lightbox.compress', defaultMessage: 'Compress image view box' },
expand: { id: 'lightbox.expand', defaultMessage: 'Expand image view box' },
});
const MIN_SCALE = 1;
const MAX_SCALE = 4;
const NAV_BAR_HEIGHT = 66;
const getMidpoint = (p1, p2) => ({
x: (p1.clientX + p2.clientX) / 2,
y: (p1.clientY + p2.clientY) / 2,
});
const getDistance = (p1, p2) =>
Math.sqrt(Math.pow(p1.clientX - p2.clientX, 2) + Math.pow(p1.clientY - p2.clientY, 2));
const clamp = (min, max, value) => Math.min(max, Math.max(min, value));
// Normalizing mousewheel speed across browsers
// copy from: https://github.com/facebookarchive/fixed-data-table/blob/master/src/vendor_upstream/dom/normalizeWheel.js
const normalizeWheel = event => {
// Reasonable defaults
const PIXEL_STEP = 10;
const LINE_HEIGHT = 40;
const PAGE_HEIGHT = 800;
let sX = 0,
sY = 0, // spinX, spinY
pX = 0,
pY = 0; // pixelX, pixelY
// Legacy
if ('detail' in event) {
sY = event.detail;
}
if ('wheelDelta' in event) {
sY = -event.wheelDelta / 120;
}
if ('wheelDeltaY' in event) {
sY = -event.wheelDeltaY / 120;
}
if ('wheelDeltaX' in event) {
sX = -event.wheelDeltaX / 120;
}
// side scrolling on FF with DOMMouseScroll
if ('axis' in event && event.axis === event.HORIZONTAL_AXIS) {
sX = sY;
sY = 0;
}
pX = sX * PIXEL_STEP;
pY = sY * PIXEL_STEP;
if ('deltaY' in event) {
pY = event.deltaY;
}
if ('deltaX' in event) {
pX = event.deltaX;
}
if ((pX || pY) && event.deltaMode) {
if (event.deltaMode === 1) { // delta in LINE units
pX *= LINE_HEIGHT;
pY *= LINE_HEIGHT;
} else { // delta in PAGE units
pX *= PAGE_HEIGHT;
pY *= PAGE_HEIGHT;
}
}
// Fall-back if spin cannot be determined
if (pX && !sX) {
sX = (pX < 1) ? -1 : 1;
}
if (pY && !sY) {
sY = (pY < 1) ? -1 : 1;
}
return {
spinX: sX,
spinY: sY,
pixelX: pX,
pixelY: pY,
};
};
export default @injectIntl
class ZoomableImage extends React.PureComponent {
static propTypes = {
alt: PropTypes.string,
src: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
onClick: PropTypes.func,
zoomButtonHidden: PropTypes.bool,
intl: PropTypes.object.isRequired,
}
static defaultProps = {
alt: '',
width: null,
height: null,
};
state = {
scale: MIN_SCALE,
zoomMatrix: {
type: null, // 'width' 'height'
fullScreen: null, // bool
rate: null, // full screen scale rate
clientWidth: null,
clientHeight: null,
offsetWidth: null,
offsetHeight: null,
clientHeightFixed: null,
scrollTop: null,
scrollLeft: null,
translateX: null,
translateY: null,
},
zoomState: 'expand', // 'expand' 'compress'
navigationHidden: false,
dragPosition: { top: 0, left: 0, x: 0, y: 0 },
dragged: false,
lockScroll: { x: 0, y: 0 },
lockTranslate: { x: 0, y: 0 },
}
removers = [];
container = null;
image = null;
lastTouchEndTime = 0;
lastDistance = 0;
componentDidMount () {
let handler = this.handleTouchStart;
this.container.addEventListener('touchstart', handler);
this.removers.push(() => this.container.removeEventListener('touchstart', handler));
handler = this.handleTouchMove;
// on Chrome 56+, touch event listeners will default to passive
// https://www.chromestatus.com/features/5093566007214080
this.container.addEventListener('touchmove', handler, { passive: false });
this.removers.push(() => this.container.removeEventListener('touchend', handler));
handler = this.mouseDownHandler;
this.container.addEventListener('mousedown', handler);
this.removers.push(() => this.container.removeEventListener('mousedown', handler));
handler = this.mouseWheelHandler;
this.container.addEventListener('wheel', handler);
this.removers.push(() => this.container.removeEventListener('wheel', handler));
// Old Chrome
this.container.addEventListener('mousewheel', handler);
this.removers.push(() => this.container.removeEventListener('mousewheel', handler));
// Old Firefox
this.container.addEventListener('DOMMouseScroll', handler);
this.removers.push(() => this.container.removeEventListener('DOMMouseScroll', handler));
this.initZoomMatrix();
}
componentWillUnmount () {
this.removeEventListeners();
}
componentDidUpdate () {
this.setState({ zoomState: this.state.scale >= this.state.zoomMatrix.rate ? 'compress' : 'expand' });
if (this.state.scale === MIN_SCALE) {
this.container.style.removeProperty('cursor');
}
}
UNSAFE_componentWillReceiveProps () {
// reset when slide to next image
if (this.props.zoomButtonHidden) {
this.setState({
scale: MIN_SCALE,
lockTranslate: { x: 0, y: 0 },
}, () => {
this.container.scrollLeft = 0;
this.container.scrollTop = 0;
});
}
}
removeEventListeners () {
this.removers.forEach(listeners => listeners());
this.removers = [];
}
mouseWheelHandler = e => {
e.preventDefault();
const event = normalizeWheel(e);
if (this.state.zoomMatrix.type === 'width') {
// full width, scroll vertical
this.container.scrollTop = Math.max(this.container.scrollTop + event.pixelY, this.state.lockScroll.y);
} else {
// full height, scroll horizontal
this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelY, this.state.lockScroll.x);
}
// lock horizontal scroll
this.container.scrollLeft = Math.max(this.container.scrollLeft + event.pixelX, this.state.lockScroll.x);
}
mouseDownHandler = e => {
this.container.style.cursor = 'grabbing';
this.container.style.userSelect = 'none';
this.setState({ dragPosition: {
left: this.container.scrollLeft,
top: this.container.scrollTop,
// Get the current mouse position
x: e.clientX,
y: e.clientY,
} });
this.image.addEventListener('mousemove', this.mouseMoveHandler);
this.image.addEventListener('mouseup', this.mouseUpHandler);
}
mouseMoveHandler = e => {
const dx = e.clientX - this.state.dragPosition.x;
const dy = e.clientY - this.state.dragPosition.y;
this.container.scrollLeft = Math.max(this.state.dragPosition.left - dx, this.state.lockScroll.x);
this.container.scrollTop = Math.max(this.state.dragPosition.top - dy, this.state.lockScroll.y);
this.setState({ dragged: true });
}
mouseUpHandler = () => {
this.container.style.cursor = 'grab';
this.container.style.removeProperty('user-select');
this.image.removeEventListener('mousemove', this.mouseMoveHandler);
this.image.removeEventListener('mouseup', this.mouseUpHandler);
}
handleTouchStart = e => {
if (e.touches.length !== 2) return;
this.lastDistance = getDistance(...e.touches);
}
handleTouchMove = e => {
const { scrollTop, scrollHeight, clientHeight } = this.container;
if (e.touches.length === 1 && scrollTop !== scrollHeight - clientHeight) {
// prevent propagating event to MediaModal
e.stopPropagation();
return;
}
if (e.touches.length !== 2) return;
e.preventDefault();
e.stopPropagation();
const distance = getDistance(...e.touches);
const midpoint = getMidpoint(...e.touches);
const _MAX_SCALE = Math.max(MAX_SCALE, this.state.zoomMatrix.rate);
const scale = clamp(MIN_SCALE, _MAX_SCALE, this.state.scale * distance / this.lastDistance);
this.zoom(scale, midpoint);
this.lastMidpoint = midpoint;
this.lastDistance = distance;
}
zoom(nextScale, midpoint) {
const { scale, zoomMatrix } = this.state;
const { scrollLeft, scrollTop } = this.container;
// math memo:
// x = (scrollLeft + midpoint.x) / scrollWidth
// x' = (nextScrollLeft + midpoint.x) / nextScrollWidth
// scrollWidth = clientWidth * scale
// scrollWidth' = clientWidth * nextScale
// Solve x = x' for nextScrollLeft
const nextScrollLeft = (scrollLeft + midpoint.x) * nextScale / scale - midpoint.x;
const nextScrollTop = (scrollTop + midpoint.y) * nextScale / scale - midpoint.y;
this.setState({ scale: nextScale }, () => {
this.container.scrollLeft = nextScrollLeft;
this.container.scrollTop = nextScrollTop;
// reset the translateX/Y constantly
if (nextScale < zoomMatrix.rate) {
this.setState({
lockTranslate: {
x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY * ((nextScale - MIN_SCALE) / (zoomMatrix.rate - MIN_SCALE)),
},
});
}
});
}
handleClick = e => {
// don't propagate event to MediaModal
e.stopPropagation();
const dragged = this.state.dragged;
this.setState({ dragged: false });
if (dragged) return;
const handler = this.props.onClick;
if (handler) handler();
this.setState({ navigationHidden: !this.state.navigationHidden });
}
handleMouseDown = e => {
e.preventDefault();
}
initZoomMatrix = () => {
const { width, height } = this.props;
const { clientWidth, clientHeight } = this.container;
const { offsetWidth, offsetHeight } = this.image;
const clientHeightFixed = clientHeight - NAV_BAR_HEIGHT;
const type = width / height < clientWidth / clientHeightFixed ? 'width' : 'height';
const fullScreen = type === 'width' ? width > clientWidth : height > clientHeightFixed;
const rate = type === 'width' ? Math.min(clientWidth, width) / offsetWidth : Math.min(clientHeightFixed, height) / offsetHeight;
const scrollTop = type === 'width' ? (clientHeight - offsetHeight) / 2 - NAV_BAR_HEIGHT : (clientHeightFixed - offsetHeight) / 2;
const scrollLeft = (clientWidth - offsetWidth) / 2;
const translateX = type === 'width' ? (width - offsetWidth) / (2 * rate) : 0;
const translateY = type === 'height' ? (height - offsetHeight) / (2 * rate) : 0;
this.setState({
zoomMatrix: {
type: type,
fullScreen: fullScreen,
rate: rate,
clientWidth: clientWidth,
clientHeight: clientHeight,
offsetWidth: offsetWidth,
offsetHeight: offsetHeight,
clientHeightFixed: clientHeightFixed,
scrollTop: scrollTop,
scrollLeft: scrollLeft,
translateX: translateX,
translateY: translateY,
},
});
}
handleZoomClick = e => {
e.preventDefault();
e.stopPropagation();
const { scale, zoomMatrix } = this.state;
if ( scale >= zoomMatrix.rate ) {
this.setState({
scale: MIN_SCALE,
lockScroll: {
x: 0,
y: 0,
},
lockTranslate: {
x: 0,
y: 0,
},
}, () => {
this.container.scrollLeft = 0;
this.container.scrollTop = 0;
});
} else {
this.setState({
scale: zoomMatrix.rate,
lockScroll: {
x: zoomMatrix.scrollLeft,
y: zoomMatrix.scrollTop,
},
lockTranslate: {
x: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateX,
y: zoomMatrix.fullScreen ? 0 : zoomMatrix.translateY,
},
}, () => {
this.container.scrollLeft = zoomMatrix.scrollLeft;
this.container.scrollTop = zoomMatrix.scrollTop;
});
}
this.container.style.cursor = 'grab';
this.container.style.removeProperty('user-select');
}
setContainerRef = c => {
this.container = c;
}
setImageRef = c => {
this.image = c;
}
render () {
const { alt, src, width, height, intl } = this.props;
const { scale, lockTranslate } = this.state;
const overflow = scale === MIN_SCALE ? 'hidden' : 'scroll';
const zoomButtonShouldHide = this.state.navigationHidden || this.props.zoomButtonHidden || this.state.zoomMatrix.rate <= MIN_SCALE ? 'media-modal__zoom-button--hidden' : '';
const zoomButtonTitle = this.state.zoomState === 'compress' ? intl.formatMessage(messages.compress) : intl.formatMessage(messages.expand);
return (
<React.Fragment>
<IconButton
className={`media-modal__zoom-button ${zoomButtonShouldHide}`}
title={zoomButtonTitle}
icon={this.state.zoomState}
onClick={this.handleZoomClick}
size={40}
style={{
fontSize: '30px', /* Fontawesome's fa-compress fa-expand is larger than fa-close */
}}
/>
<div
className='zoomable-image'
ref={this.setContainerRef}
style={{ overflow }}
>
<img
role='presentation'
ref={this.setImageRef}
alt={alt}
title={alt}
src={src}
width={width}
height={height}
style={{
transform: `scale(${scale}) translate(-${lockTranslate.x}px, -${lockTranslate.y}px)`,
transformOrigin: '0 0',
}}
draggable={false}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
/>
</div>
</React.Fragment>
);
}
}
|
actor-apps/app-web/src/app/components/DialogSection.react.js | tsdl2013/actor-platform | import _ from 'lodash';
import React from 'react';
import { PeerTypes } from 'constants/ActorAppConstants';
import MessagesSection from 'components/dialog/MessagesSection.react';
import TypingSection from 'components/dialog/TypingSection.react';
import ComposeSection from 'components/dialog/ComposeSection.react';
import DialogStore from 'stores/DialogStore';
import MessageStore from 'stores/MessageStore';
import GroupStore from 'stores/GroupStore';
import DialogActionCreators from 'actions/DialogActionCreators';
// On which scrollTop value start loading older messages
const LoadMessagesScrollTop = 100;
const initialRenderMessagesCount = 20;
const renderMessagesStep = 20;
let renderMessagesCount = initialRenderMessagesCount;
let lastPeer = null;
let lastScrolledFromBottom = 0;
const getStateFromStores = () => {
const messages = MessageStore.getAll();
let messagesToRender;
if (messages.length > renderMessagesCount) {
messagesToRender = messages.slice(messages.length - renderMessagesCount);
} else {
messagesToRender = messages;
}
return {
peer: DialogStore.getSelectedDialogPeer(),
messages: messages,
messagesToRender: messagesToRender
};
};
class DialogSection extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
DialogStore.addSelectListener(this.onSelectedDialogChange);
MessageStore.addChangeListener(this.onMessagesChange);
}
componentWillUnmount() {
DialogStore.removeSelectListener(this.onSelectedDialogChange);
MessageStore.removeChangeListener(this.onMessagesChange);
}
componentDidUpdate() {
this.fixScroll();
this.loadMessagesByScroll();
}
render() {
const peer = this.state.peer;
if (peer) {
let isMember = true;
let memberArea;
if (peer.type === PeerTypes.GROUP) {
const group = GroupStore.getGroup(peer.id);
isMember = DialogStore.isGroupMember(group);
}
if (isMember) {
memberArea = (
<div>
<TypingSection/>
<ComposeSection peer={this.state.peer}/>
</div>
);
} else {
memberArea = (
<section className="compose compose--disabled row center-xs middle-xs">
<h3>You are not member</h3>
</section>
);
}
return (
<section className="dialog" onScroll={this.loadMessagesByScroll}>
<MessagesSection messages={this.state.messagesToRender}
peer={this.state.peer}
ref="MessagesSection"/>
{memberArea}
</section>
);
} else {
return (
<section className="dialog dialog--empty row middle-xs center-xs">
Select dialog or start a new one.
</section>
);
}
}
fixScroll = () => {
if (lastPeer !== null ) {
let node = React.findDOMNode(this.refs.MessagesSection);
node.scrollTop = node.scrollHeight - lastScrolledFromBottom;
}
}
onSelectedDialogChange = () => {
renderMessagesCount = initialRenderMessagesCount;
if (lastPeer != null) {
DialogActionCreators.onConversationClosed(lastPeer);
}
lastPeer = DialogStore.getSelectedDialogPeer();
DialogActionCreators.onConversationOpen(lastPeer);
}
onMessagesChange = _.debounce(() => {
this.setState(getStateFromStores());
}, 10, {maxWait: 50, leading: true});
loadMessagesByScroll = _.debounce(() => {
if (lastPeer !== null ) {
let node = React.findDOMNode(this.refs.MessagesSection);
let scrollTop = node.scrollTop;
lastScrolledFromBottom = node.scrollHeight - scrollTop;
if (node.scrollTop < LoadMessagesScrollTop) {
DialogActionCreators.onChatEnd(this.state.peer);
if (this.state.messages.length > this.state.messagesToRender.length) {
renderMessagesCount += renderMessagesStep;
if (renderMessagesCount > this.state.messages.length) {
renderMessagesCount = this.state.messages.length;
}
this.setState(getStateFromStores());
}
}
}
}, 5, {maxWait: 30});
}
export default DialogSection;
|
webapp/app/components/Notifications/Form/index.js | EIP-SAM/SAM-Solution-Node-js | //
// Component notifications form
//
import React from 'react';
import Title from 'containers/Notifications/Form/Title';
import Description from 'containers/Notifications/Form/Description';
import Persistence from 'containers/Notifications/Form/Persistence';
import Users from 'containers/Notifications/Form/Users';
import Buttons from 'containers/Notifications/Form/Buttons';
import LinkContainerButton from 'components/Button';
/* eslint-disable react/prefer-stateless-function */
export default class NotificationsForm extends React.Component {
render() {
return (
<form>
<Title />
<Description />
<Persistence />
<LinkContainerButton buttonType="submit" buttonBsStyle="info" buttonText="Select by groups" link="/notifications/groups" />
<Users />
<Buttons />
</form>
);
}
}
|
docs/app/Examples/elements/Reveal/index.js | ben174/Semantic-UI-React | import React from 'react'
import Types from './Types'
import Content from './Content'
import States from './States'
import Variations from './Variations'
const RevealExamples = () => (
<div>
<Types />
<Content />
<States />
<Variations />
</div>
)
export default RevealExamples
|
src/Loadable.js | jonjomckay/stividor | import React, { Component } from 'react';
import Spinner from 'react-spinkit';
export default class Loadable extends Component {
render() {
let content;
if (this.props.isLoading) {
content = (
<div style={{ width: '100%', height: '100%', position: 'absolute', background: 'rgba(255, 255, 255, 0.7)' }}>
<Spinner fadeIn="none" name="wave" style={{ position: 'absolute', left: '50%', marginTop: '7px' }} />
</div>
);
}
return (
<div style={{ position: 'relative' }}>
{ content }
{ this.props.children }
</div>
);
}
} |
src/components/TableAgreement.js | aurigadl/EnvReactAsk | import React from 'react'
import {makeRequest as mReq} from '../utils/mrequest';
import {Table, Card, Col, Row, Button, Icon} from 'antd';
const columns = [{
title: 'No del contrato',
dataIndex: 'no_agreement',
key: 'no_agreement',
render: text => <Button type="primary" shape="circle" icon="download"/>,
}, {
title: 'Fecha de creación',
dataIndex: 'created_at',
key: 'created_at',
}, {
title: 'Creado Por',
dataIndex: 'created_by',
key: 'created_by',
}, {
title: 'Fecha Inicial',
dataIndex: 'init_date',
key: 'init_date',
}, {
title: 'Fecha Final',
dataIndex: 'last_date',
key: 'last_date',
}, {
title: 'No del viaje',
dataIndex: 'no_trip',
key: 'no_trip',
}, {
title: 'Contratante',
dataIndex: 'person',
key: 'person',
}];
var TableAgreement = React.createClass({
getInitialState: function () {
return {
dataValue: [],
filetoload: ''
};
},
getRemoteData: function (parreq, cb_success, cb_error) {
mReq(parreq)
.then(function (response) {
cb_success(response)
}.bind(this))
.catch(function (err) {
cb_error(err);
console.log('TableAgreement, there was an error!', err.statusText);
});
},
componentDidMount: function () {
var parreq = {
method: 'GET',
url: 'apiFuec/fullAllAgreement'
};
this.getRemoteData(parreq,
this.successLoadData,
this.errorLoadData
);
},
successLoadData: function (data) {
this.setState({
dataValue: data.result
});
},
errorLoadData: function (err) {
},
handleGetFile: function (record, index) {
var params = {
'agreement': record.no_agreement
};
var parreq = {
method: 'GET',
url: 'apiFuec/fileAgreement',
params: params
};
this.getRemoteData(parreq,
this.successLoadFile,
this.errorLoadFile
);
},
successLoadFile: function (remoteData) {
this.setState({
filetoload: remoteData.result
});
},
errorLoadFile: function () {
},
render: function () {
var pdf;
var showClass = this.state.filetoload ? '' : 'is-hidden';
if(this.state.filetoload != ""){
pdf = "data:application/pdf;base64," + this.state.filetoload;
}
return (
<Card title="Listado de contratos" bordered={false}>
<Table rowKey="id" onRowClick={this.handleGetFile} dataSource={this.state.dataValue} columns={columns} />
<iframe
src={pdf}
className={showClass}
width="100%"
height="500px"
alt="pdf"
type="application/pdf"
/>
</Card>
)
}
});
export default TableAgreement;
|
src/components/Dashboard/UsageChart.js | kennylbj/kiwi-blog | import React from 'react'
import color from '../../constants/color.js'
import { AreaChart, Area, XAxis, YAxis, CartesianGrid, Legend, Tooltip, ResponsiveContainer } from 'recharts'
const UsageChart = ({ data }) => {
return (
<div >
<div style={{marginLeft: '32px', marginBottom: '32px', fontSize: '16px'}}>CPU / Memory Usage</div>
<ResponsiveContainer minHeight={360}>
<AreaChart data={data} >
<XAxis dataKey="name" axisLine={{ stroke: color.borderBase, strokeWidth: 1 }} tickLine={false} />
<YAxis axisLine={false} tickLine={false} />
<CartesianGrid vertical={false} stroke={color.borderBase} strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Area type="monotone" dataKey="cpu" stroke={color.sky} fill={color.sky} />
<Area type="monotone" dataKey="memory" stroke={color.grass} fill={color.grass} />
</AreaChart>
</ResponsiveContainer>
</div>
)
}
export default UsageChart
|
js/app.js | cansin/jspm-react-es6-hello-world | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
<b>world!</b>,
document.getElementById('world')
);
|
packages/ndla-icons/src/editor/FocalPoint.js | netliferesearch/frontend-packages | /**
* Copyright (c) 2017-present, NDLA.
*
* This source code is licensed under the GPLv3 license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// N.B! AUTOGENERATED FILE. DO NOT EDIT
import React from 'react';
import Icon from '../Icon';
const FocalPoint = props => (
<Icon
viewBox="0 0 24 24"
data-license="Apache License 2.0"
data-source="Material Design"
{...props}>
<g>
<path d="M0 0h24v24H0z" fill="none" />
<path d="M12 8c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4zm-7 7H3v4c0 1.1.9 2 2 2h4v-2H5v-4zM5 5h4V3H5c-1.1 0-2 .9-2 2v4h2V5zm14-2h-4v2h4v4h2V5c0-1.1-.9-2-2-2zm0 16h-4v2h4c1.1 0 2-.9 2-2v-4h-2v4z" />
</g>
</Icon>
);
export default FocalPoint;
|
src/svg-icons/places/child-care.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesChildCare = (props) => (
<SvgIcon {...props}>
<circle cx="14.5" cy="10.5" r="1.25"/><circle cx="9.5" cy="10.5" r="1.25"/><path d="M22.94 12.66c.04-.21.06-.43.06-.66s-.02-.45-.06-.66c-.25-1.51-1.36-2.74-2.81-3.17-.53-1.12-1.28-2.1-2.19-2.91C16.36 3.85 14.28 3 12 3s-4.36.85-5.94 2.26c-.92.81-1.67 1.8-2.19 2.91-1.45.43-2.56 1.65-2.81 3.17-.04.21-.06.43-.06.66s.02.45.06.66c.25 1.51 1.36 2.74 2.81 3.17.52 1.11 1.27 2.09 2.17 2.89C7.62 20.14 9.71 21 12 21s4.38-.86 5.97-2.28c.9-.8 1.65-1.79 2.17-2.89 1.44-.43 2.55-1.65 2.8-3.17zM19 14c-.1 0-.19-.02-.29-.03-.2.67-.49 1.29-.86 1.86C16.6 17.74 14.45 19 12 19s-4.6-1.26-5.85-3.17c-.37-.57-.66-1.19-.86-1.86-.1.01-.19.03-.29.03-1.1 0-2-.9-2-2s.9-2 2-2c.1 0 .19.02.29.03.2-.67.49-1.29.86-1.86C7.4 6.26 9.55 5 12 5s4.6 1.26 5.85 3.17c.37.57.66 1.19.86 1.86.1-.01.19-.03.29-.03 1.1 0 2 .9 2 2s-.9 2-2 2zM7.5 14c.76 1.77 2.49 3 4.5 3s3.74-1.23 4.5-3h-9z"/>
</SvgIcon>
);
PlacesChildCare = pure(PlacesChildCare);
PlacesChildCare.displayName = 'PlacesChildCare';
PlacesChildCare.muiName = 'SvgIcon';
export default PlacesChildCare;
|
src/svg-icons/action/settings-remote.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsRemote = (props) => (
<SvgIcon {...props}>
<path d="M15 9H9c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h6c.55 0 1-.45 1-1V10c0-.55-.45-1-1-1zm-3 6c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zM7.05 6.05l1.41 1.41C9.37 6.56 10.62 6 12 6s2.63.56 3.54 1.46l1.41-1.41C15.68 4.78 13.93 4 12 4s-3.68.78-4.95 2.05zM12 0C8.96 0 6.21 1.23 4.22 3.22l1.41 1.41C7.26 3.01 9.51 2 12 2s4.74 1.01 6.36 2.64l1.41-1.41C17.79 1.23 15.04 0 12 0z"/>
</SvgIcon>
);
ActionSettingsRemote = pure(ActionSettingsRemote);
ActionSettingsRemote.displayName = 'ActionSettingsRemote';
export default ActionSettingsRemote;
|
packages/showcase/axes/static-crosshair.js | uber-common/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import {
XYPlot,
XAxis,
YAxis,
VerticalGridLines,
HorizontalGridLines,
LineSeries,
Crosshair
} from 'react-vis';
export default function Example() {
return (
<XYPlot width={300} height={300}>
<VerticalGridLines />
<HorizontalGridLines />
<XAxis />
<YAxis />
<LineSeries
data={[
{x: 1, y: 10},
{x: 2, y: 7},
{x: 3, y: 15}
]}
/>
<LineSeries
data={[
{x: 1, y: 20},
{x: 2, y: 5},
{x: 3, y: 15}
]}
/>
<Crosshair
values={[
{x: 2, y: 5},
{x: 2, y: 7}
]}
/>
</XYPlot>
);
}
|
src/components/Headline/Headline.js | resendefreitas/avidade | import React from 'react';
import './Headline.less';
class Headline extends React.Component {
render() {
return (
<div className="Headline container">
<div>
<h1 className="Headline__text text-center">
A Vida de Quem?
</h1>
<h4 className="Headline__text text-center">
O seu meme escrito da sua forma sobre a sua vida.
</h4>
</div>
</div>
);
};
}
export default Headline;
|
src/components/ControlPanel/SelectorPanel.js | bocasfx/Q | import React from 'react';
import Panel from '../UI/Tabs/Panel';
import { connect } from 'react-redux';
import ListItem from './ListItem';
import { bindActionCreators } from 'redux';
import { deleteStream, selectStream, setStreamDisabledStatus, deselectStreams } from '../../actions/Streams';
import { deleteNode, selectNode, setNodeDisabledStatus, deselectNodes, stopNode, unlinkNode } from '../../actions/Nodes';
import { setSelection } from '../../actions/Selection';
import './SelectorPanel.css';
import PropTypes from 'prop-types';
class SelectorPanel extends React.Component {
static propTypes = {
stopNode: PropTypes.func,
deleteStream: PropTypes.func,
unlinkNode: PropTypes.func,
deleteNode: PropTypes.func,
setNodeDisabledStatus: PropTypes.func,
setStreamDisabledStatus: PropTypes.func,
deselectNodes: PropTypes.func,
selectNode: PropTypes.func,
setSelection: PropTypes.func,
deselectStreams: PropTypes.func,
selectStream: PropTypes.func,
nodes: PropTypes.array,
streams: PropTypes.array,
}
constructor(props) {
super(props);
this.renderStreams = this.renderStreams.bind(this);
}
onDeleteStream(id, event) {
event.preventDefault();
this.props.nodes.forEach((node) => {
this.props.stopNode(node.id);
});
this.props.deleteStream(id);
event.stopPropagation();
}
onDeleteNode(id, event) {
event.preventDefault();
this.props.stopNode(id);
this.props.unlinkNode(id);
this.props.deleteNode(id);
event.stopPropagation();
}
onToggleNode(node, event) {
event.preventDefault();
this.props.setNodeDisabledStatus(node.id, !node.disabled);
event.stopPropagation();
}
onToggleStream(stream, event) {
event.preventDefault();
this.props.setStreamDisabledStatus(stream.id, !stream.disabled);
event.stopPropagation();
}
onClickNode(node, event) {
event.preventDefault();
if (!event.metaKey) {
this.props.deselectNodes();
}
this.props.selectNode(node.id);
this.props.setSelection('nodes');
this.props.deselectStreams();
}
onClickStream(stream, event) {
event.preventDefault();
this.props.selectStream(stream.id);
this.props.deselectNodes();
this.props.setSelection('streams');
}
renderStreams() {
if (!this.props.streams.length) {
return null;
}
return this.props.streams.map((stream, idx) => {
return <ListItem
key={idx}
item={stream}
idx={idx}
onToggle={this.onToggleStream.bind(this, stream)}
onDelete={this.onDeleteStream.bind(this, stream.id)}
onClick={this.onClickStream.bind(this, stream)}/>;
});
}
renderNodes() {
if (!this.props.nodes.length) {
return null;
}
return this.props.nodes.map((node, idx) => {
return <ListItem
key={idx}
item={node}
idx={idx}
onToggle={this.onToggleNode.bind(this, node)}
onDelete={this.onDeleteNode.bind(this, node.id)}
onClick={this.onClickNode.bind(this, node)}/>;
});
}
render() {
return (
<div className="selector-panel-container">
<Panel label="Nodes">
{this.renderStreams()}
{this.renderNodes()}
</Panel>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
streams: state.streams,
nodes: state.nodes,
};
};
const mapDispatchToProps = (dispatch) => {
return {
deleteStream: bindActionCreators(deleteStream, dispatch),
selectStream: bindActionCreators(selectStream, dispatch),
deleteNode: bindActionCreators(deleteNode, dispatch),
deselectNodes: bindActionCreators(deselectNodes, dispatch),
selectNode: bindActionCreators(selectNode, dispatch),
setNodeDisabledStatus: bindActionCreators(setNodeDisabledStatus, dispatch),
setStreamDisabledStatus: bindActionCreators(setStreamDisabledStatus, dispatch),
stopNode: bindActionCreators(stopNode, dispatch),
unlinkNode: bindActionCreators(unlinkNode, dispatch),
deselectStreams: bindActionCreators(deselectStreams, dispatch),
setSelection: bindActionCreators(setSelection, dispatch),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(SelectorPanel);
|
src/client/assets/javascripts/app/index.js | yougothack/hyperbowl | import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { AppContainer } from 'react-hot-loader';
import Redbox from 'redbox-react';
import Root from './Root';
import configureStore from './store/configure-store';
import 'styles/styles.scss';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
// Get the DOM Element that will host our React application
const rootEl = document.getElementById('app');
// Render the React application to the DOM
render(
<AppContainer errorReporter={Redbox}>
<Root store={store} history={history} />
</AppContainer>,
rootEl
);
if (module.hot) {
/**
* Warning from React Router, caused by react-hot-loader.
* The warning can be safely ignored, so filter it from the console.
* Otherwise you'll see it every time something changes.
* See https://github.com/gaearon/react-hot-loader/issues/298
*/
const orgError = console.error; // eslint-disable-line no-console
console.error = (message) => { // eslint-disable-line no-console
if (message && message.indexOf('You cannot change <Router routes>;') === -1) {
// Log the error as normally
orgError.apply(console, [message]);
}
};
module.hot.accept('./Root', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./Root').default;
render(
<AppContainer errorReporter={Redbox}>
<NextApp store={store} history={history} />
</AppContainer>,
rootEl
);
});
}
|
src/Glyphicon.js | pieter-lazzaro/react-bootstrap | import React from 'react';
import classNames from 'classnames';
const Glyphicon = React.createClass({
propTypes: {
/**
* bootstrap className
* @private
*/
bsClass: React.PropTypes.string,
/**
* An icon name. See e.g. http://getbootstrap.com/components/#glyphicons
*/
glyph: React.PropTypes.string.isRequired,
/**
* Adds 'form-control-feedback' class
* @private
*/
formControlFeedback: React.PropTypes.bool
},
getDefaultProps() {
return {
bsClass: 'glyphicon',
formControlFeedback: false
};
},
render() {
let className = classNames(this.props.className, {
[this.props.bsClass]: true,
['glyphicon-' + this.props.glyph]: true,
['form-control-feedback']: this.props.formControlFeedback
});
return (
<span {...this.props} className={className}>
{this.props.children}
</span>
);
}
});
export default Glyphicon;
|
src/components/commons/Spinner.js | leapfrogtechnology/chill-dashboard | import React from 'react';
const Spinner = () => (
<div className="loader">Loading...</div>
);
export default Spinner;
|
src/modules/App/components/Footer.js | prjctrft/mantenuto | import React from 'react';
const Footer = () => {
const styles = require('./Footer.scss');
return (
<footer className={styles.footer}>
<span>©2017 by Project Refit</span>
<button><a href="https://www.projectrefit.us/">Home site</a></button>
<button><a href="/sponsors">Our sponsors</a></button>
</footer>
)
}
export default Footer
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/CssInclusion.js | iamdoron/create-react-app | /**
* Copyright (c) 2015-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.
*/
import React from 'react';
import './assets/style.css';
export default () => <p id="feature-css-inclusion">We love useless text.</p>;
|
src/interface/report/handleApiError.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import { Trans, t } from '@lingui/macro';
import { ApiDownError, CorruptResponseError, JsonParseError, LogNotFoundError } from 'common/fetchWclApi';
import { i18n } from 'interface/RootLocalizationProvider';
import FullscreenError from 'interface/FullscreenError';
import ApiDownBackground from 'interface/common/images/api-down-background.gif';
import ThunderSoundEffect from 'interface/audio/Thunder Sound effect.mp3';
import { EventsParseError } from 'interface/report/EventParser';
export default function handleApiError(error, onBack) {
console.error(error);
if (error instanceof LogNotFoundError) {
return (
<FullscreenError
error={i18n._(t`Report not found.`)}
details={i18n._(t`Either you entered a wrong report, or it is private.`)}
background="https://media.giphy.com/media/DAgxA6qRfa5La/giphy.gif"
>
<div className="text-muted">
<Trans>Private reports can not be used, if your guild has private reports you will have to <a href="https://www.warcraftlogs.com/help/start/">upload your own logs</a> or change the existing reports to the <i>unlisted</i> privacy option instead.</Trans>
</div>
<div>
<button
type="button"
className="btn btn-primary"
onClick={onBack}
>
< <Trans>Back</Trans>
</button>
</div>
</FullscreenError>
);
} else if (error instanceof ApiDownError) {
return (
<FullscreenError
error={i18n._(t`The API is down.`)}
details={i18n._(t`This is usually because we're leveling up with another patch.`)}
background={ApiDownBackground}
>
<div className="text-muted">
<Trans>Aside from the great news that you'll be the first to experience something new that is probably going to pretty amazing, you'll probably also enjoy knowing that our updates usually only take less than 10 seconds. So just <a href={window.location.href}>give it another try</a>.</Trans>
</div>
{/* I couldn't resist */}
<audio autoPlay>
<source src={ThunderSoundEffect} />
</audio>
</FullscreenError>
);
} else if (error instanceof CorruptResponseError) {
return (
<FullscreenError
error={i18n._(t`Corrupt Warcraft Logs API response`)}
details={i18n._(t`Corrupt Warcraft Logs API response received, this report can not be processed.`)}
background="https://media.giphy.com/media/m4TbeLYX5MaZy/giphy.gif"
>
<div>
<button
type="button"
className="btn btn-primary"
onClick={onBack}
>
< <Trans>Back</Trans>
</button>
</div>
</FullscreenError>
);
} else if (error instanceof JsonParseError) {
return (
<FullscreenError
error={i18n._(t`Failed to parse API response`)}
details={i18n._(t`JSON parse error, the API response is probably corrupt. Let us know on Discord and we may be able to fix it for you.`)}
background="https://media.giphy.com/media/m4TbeLYX5MaZy/giphy.gif"
>
<div>
<button
type="button"
className="btn btn-primary"
onClick={onBack}
>
< <Trans>Back</Trans>
</button>
</div>
</FullscreenError>
);
} else if (error instanceof EventsParseError) {
return (
<FullscreenError
error={i18n._(t`An error occured during analysis`)}
details={i18n._(t`We fucked up and our code broke like the motherfucker that it is. Please let us know on Discord and we will fix it for you.`)}
background="https://media.giphy.com/media/2sdHZ0iBuI45s6fqc9/giphy.gif"
>
<div>
<button
type="button"
className="btn btn-primary"
onClick={onBack}
>
< <Trans>Back</Trans>
</button>
</div>
</FullscreenError>
);
} else {
// Some kind of network error, internet may be down.
return (
<FullscreenError
error={i18n._(t`A connection error occured.`)}
details={i18n._(t`Something went wrong talking to our servers, please try again.`)}
background="https://media.giphy.com/media/m4TbeLYX5MaZy/giphy.gif"
>
<div className="text-muted">
{error.message}
</div>
<div>
<a className="btn btn-primary" href={window.location.href}><Trans>Refresh</Trans></a>
</div>
</FullscreenError>
);
}
}
|
src/components/form/agreement.js | woshisbb43/coinMessageWechat | import React from 'react';
import classNames from '../../utils/classnames';
/**
* Agreement style checkbox
*
*/
const Agreement = (props) => {
const { className, children, id, ...others } = props;
const cls = classNames({
'weui-agree': true,
[className]: className
});
return (
<label className={cls} htmlFor={id}>
<input id={id} type="checkbox" className="weui-agree__checkbox" {...others}/>
<span className="weui-agree__text">
{children}
</span>
</label>
);
};
export default Agreement; |
docs/src/app/components/pages/components/Paper/ExampleRounded.js | matthewoates/material-ui | import React from 'react';
import Paper from 'material-ui/Paper';
const style = {
height: 100,
width: 100,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
const PaperExampleRounded = () => (
<div>
<Paper style={style} zDepth={1} rounded={false} />
<Paper style={style} zDepth={2} rounded={false} />
<Paper style={style} zDepth={3} rounded={false} />
<Paper style={style} zDepth={4} rounded={false} />
<Paper style={style} zDepth={5} rounded={false} />
</div>
);
export default PaperExampleRounded;
|
src/components/Panel.js | ericyd/gdrive-copy | /**
* Information message container
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import Alert from './Alert';
export default function Panel(props) {
return (
<Alert label={props.label} className="alert--neutral">
{props.children}
</Alert>
);
}
Panel.propTypes = {
label: PropTypes.string
};
|
frontend/src/components/Post/PostList.js | romerorocha/readable | import React from 'react';
import PostItem from './PostItem';
import { Item, Container } from 'semantic-ui-react';
import OrderByButtons from './OrderByButtons';
const PostList = ({ posts, voteAction }) => {
return posts.length > 0 ? (
<Container fluid>
<OrderByButtons />
<Item.Group divided>
{posts.map(post => (
<PostItem key={post.id} post={post} voteAction={voteAction} />
))}
</Item.Group>
</Container>
) : (
'ZERO posts at the moment :('
);
};
export default PostList;
|
src/Pagination.js | mengmenglv/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import PaginationButton from './PaginationButton';
import CustomPropTypes from './utils/CustomPropTypes';
import SafeAnchor from './SafeAnchor';
const Pagination = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
activePage: React.PropTypes.number,
items: React.PropTypes.number,
maxButtons: React.PropTypes.number,
ellipsis: React.PropTypes.bool,
first: React.PropTypes.bool,
last: React.PropTypes.bool,
prev: React.PropTypes.bool,
next: React.PropTypes.bool,
onSelect: React.PropTypes.func,
/**
* You can use a custom element for the buttons
*/
buttonComponentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
activePage: 1,
items: 1,
maxButtons: 0,
first: false,
last: false,
prev: false,
next: false,
ellipsis: true,
buttonComponentClass: SafeAnchor,
bsClass: 'pagination'
};
},
renderPageButtons() {
let pageButtons = [];
let startPage, endPage, hasHiddenPagesAfter;
let {
maxButtons,
activePage,
items,
onSelect,
ellipsis,
buttonComponentClass
} = this.props;
if (maxButtons) {
let hiddenPagesBefore = activePage - parseInt(maxButtons / 2, 10);
startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1;
hasHiddenPagesAfter = startPage + maxButtons <= items;
if (!hasHiddenPagesAfter) {
endPage = items;
startPage = items - maxButtons + 1;
if (startPage < 1) {
startPage = 1;
}
} else {
endPage = startPage + maxButtons - 1;
}
} else {
startPage = 1;
endPage = items;
}
for (let pagenumber = startPage; pagenumber <= endPage; pagenumber++) {
pageButtons.push(
<PaginationButton
key={pagenumber}
eventKey={pagenumber}
active={pagenumber === activePage}
onSelect={onSelect}
buttonComponentClass={buttonComponentClass}>
{pagenumber}
</PaginationButton>
);
}
if (maxButtons && hasHiddenPagesAfter && ellipsis) {
pageButtons.push(
<PaginationButton
key="ellipsis"
disabled
buttonComponentClass={buttonComponentClass}>
<span aria-label="More">...</span>
</PaginationButton>
);
}
return pageButtons;
},
renderPrev() {
if (!this.props.prev) {
return null;
}
return (
<PaginationButton
key="prev"
eventKey={this.props.activePage - 1}
disabled={this.props.activePage === 1}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="Previous">‹</span>
</PaginationButton>
);
},
renderNext() {
if (!this.props.next) {
return null;
}
return (
<PaginationButton
key="next"
eventKey={this.props.activePage + 1}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="Next">›</span>
</PaginationButton>
);
},
renderFirst() {
if (!this.props.first) {
return null;
}
return (
<PaginationButton
key="first"
eventKey={1}
disabled={this.props.activePage === 1 }
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="First">«</span>
</PaginationButton>
);
},
renderLast() {
if (!this.props.last) {
return null;
}
return (
<PaginationButton
key="last"
eventKey={this.props.items}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="Last">»</span>
</PaginationButton>
);
},
render() {
return (
<ul
{...this.props}
className={classNames(this.props.className, this.getBsClassSet())}>
{this.renderFirst()}
{this.renderPrev()}
{this.renderPageButtons()}
{this.renderNext()}
{this.renderLast()}
</ul>
);
}
});
export default Pagination;
|
src/client.js | bofa/react-education | import './client.less';
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute } from 'react-router';
import store from './store';
import { Provider } from 'react-redux';
import TodoApp from './components/smart/TodoAppContainer';
import IndexPage from './components/smart/IndexPageContainer';
import TodoPage from './components/smart/TodoPageContainer';
// import todos from './todos'
// console.log('todos', todos.toJS());
const app = (
<Provider store={store}>
<Router>
<Route path="/" component={TodoApp}>
<IndexRoute component={IndexPage} />
<Route path="todo/:uuid" component={TodoPage} />
</Route>
</Router>
</Provider>
)
ReactDOM.render(
app,
document.getElementById('app')
)
|
app/demos/rendering.js | asantebuil/room-reservation | import React from 'react';
import BigCalendar from 'react-big-calendar';
import events from '../events';
function Event({ event }) {
return (
<span>
<strong>
{event.title}
</strong>
{ event.desc && (': ' + event.desc)}
</span>
)
}
function EventAgenda({ event }) {
return <span>
<em style={{ color: 'magenta'}}>{event.title}</em>
<p>{ event.desc }</p>
</span>
}
let Rendering = React.createClass({
render(){
return (
<div {...this.props}>
<BigCalendar
events={events}
defaultDate={new Date(2015, 3, 1)}
defaultView='agenda'
components={{
event: Event,
agenda: {
event: EventAgenda
}
}}
/>
</div>
)
}
})
export default Rendering;
|
app/app.js | bartoszkrawczyk2/react-redux-canvas | import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import Circles from './containers/circles';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducer from './reducers/circles';
render(
<Provider store={createStore(reducer, window.devToolsExtension && window.devToolsExtension())}>
<Circles />
</Provider>,
document.getElementById('app')
); |
src/index.js | csepulv/electron-with-create-react-app | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.