path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
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;
|
test/specs/collections/Form/FormField-test.js
|
koenvg/Semantic-UI-React
|
import faker from 'faker'
import React from 'react'
import Radio from 'src/addons/Radio/Radio'
import FormField from 'src/collections/Form/FormField'
import { SUI } from 'src/lib'
import Checkbox from 'src/modules/Checkbox/Checkbox'
import * as common from 'test/specs/commonTests'
describe('FormField', () => {
common.isConformant(FormField)
common.rendersChildren(FormField)
common.implementsHTMLLabelProp(FormField)
common.implementsWidthProp(FormField, SUI.WIDTHS, {
canEqual: false,
propKey: 'width',
})
common.propKeyOnlyToClassName(FormField, 'disabled')
common.propKeyOnlyToClassName(FormField, 'error')
common.propKeyOnlyToClassName(FormField, 'inline')
common.propKeyOnlyToClassName(FormField, 'required', {
requiredProps: { label: '' },
})
describe('control', () => {
it('adds an HTML element child of the same type', () => {
const controls = ['button', 'input', 'select', 'textarea']
controls.forEach(control => {
shallow(<FormField control={control} />)
.should.have.descendants(control)
})
})
})
describe('label', () => {
it('wraps html checkbox inputs', () => {
const text = faker.hacker.phrase()
const label = shallow(<FormField control='input' label={text} type='checkbox' />)
.find('label')
label.childAt(0).should.have.tagName('input')
label.should.contain.text(text)
})
it('wraps html radio inputs', () => {
const text = faker.hacker.phrase()
const label = shallow(<FormField control='input' label={text} type='radio' />)
.find('label')
label.childAt(0).should.have.tagName('input')
label.should.contain.text(text)
})
it('is passed to Checkbox controls', () => {
const text = faker.hacker.phrase()
shallow(<FormField control={Checkbox} label={text} />)
.find('Checkbox')
.should.have.prop('label', text)
})
it('is passed to Radio controls', () => {
const text = faker.hacker.phrase()
shallow(<FormField control={Radio} label={text} />)
.find('Radio')
.should.have.prop('label', text)
})
it('is sibling to text inputs', () => {
const text = faker.hacker.phrase()
const wrapper = shallow(<FormField control='input' label={text} type='text' />)
wrapper.childAt(0).should.have.tagName('label')
wrapper.childAt(0).should.contain.text(text)
wrapper.childAt(1).should.have.tagName('input')
})
})
describe('required', () => {
it('is passed to the control', () => {
const wrapper = shallow(<FormField control='input' required />)
const input = wrapper.find('input')
wrapper.should.have.exactly(1).descendants('input')
input.should.have.prop('required', true)
})
})
})
|
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
|
test/TooltipSpec.js
|
Sipree/react-bootstrap
|
import _ from 'lodash-compat';
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Tooltip from '../src/Tooltip';
describe('Tooltip', () => {
it('Should output a tooltip with content', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Tooltip positionTop={10} positionLeft={20}>
<strong>Tooltip Content</strong>
</Tooltip>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
const tooltip = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tooltip');
expect(_.pick(tooltip.style, ['top', 'left']))
.to.eql({top: '10px', left: '20px'});
});
describe('When a style property is provided', () => {
it('Should render a tooltip with merged styles', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Tooltip style={{opacity: 0.9}} positionTop={10} positionLeft={20}>
<strong>Tooltip Content</strong>
</Tooltip>
);
const tooltip = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tooltip');
expect(_.pick(tooltip.style, ['opacity', 'top', 'left']))
.to.eql({opacity: '0.9', top: '10px', left: '20px'});
});
});
});
|
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;
|
20161211/RN-Learn/__tests__/index.android.js
|
fengnovo/react-native
|
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
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;
|
ui/src/main/js/components/__tests__/Diff-test.js
|
apache/aurora
|
import React from 'react';
import { shallow } from 'enzyme';
import Diff from '../Diff';
import { TaskConfigBuilder } from 'test-utils/TaskBuilders';
describe('Diff', () => {
it('Should not add change classes to diff viewer when objects are same', () => {
const el = shallow(<Diff left={{test: true}} right={{test: true}} />);
expect(el.find('span.removed').length).toBe(0);
expect(el.find('span.added').length).toBe(0);
});
it('Should add change classes to diff viewer when configs are not the same', () => {
const el = shallow(<Diff left={{test: true}} right={{test: false}} />);
expect(el.find('span.removed').length).toBe(1);
expect(el.find('span.added').length).toBe(1);
});
it('Should render a finer grained diff when Thermos executor is used', () => {
const left = TaskConfigBuilder.executorConfig({
name: 'AuroraExecutor',
data: JSON.stringify({
one: 1,
two: 2,
three: 3,
nested: {
okay: true
}
})
}).build();
const right = TaskConfigBuilder.executorConfig({
name: 'AuroraExecutor',
data: JSON.stringify({
one: 'one',
two: 2,
three: 3,
nested: {
okay: false
}
})
}).build();
const el = shallow(<Diff left={left} right={right} />);
expect(el.find('span.removed').length).toBe(2);
expect(el.find('span.added').length).toBe(2);
});
it('Just treats executor config as a string for custom executors', () => {
const left = TaskConfigBuilder.executorConfig({
name: 'MyExecutor',
data: JSON.stringify({
one: 1,
two: 2,
three: 3,
nested: {
okay: true
}
})
}).build();
const right = TaskConfigBuilder.executorConfig({
name: 'MyExecutor',
data: JSON.stringify({
one: 'one',
two: 2,
three: 3,
nested: {
okay: false
}
})
}).build();
const el = shallow(<Diff left={left} right={right} />);
expect(el.find('span.removed').length).toBe(1);
expect(el.find('span.added').length).toBe(1);
});
});
|
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')
);
|
frontend/src/components/eois/modals/addClarificationAnswer/addClarificationAnswerForm.js
|
unicef/un-partner-portal
|
import React from 'react';
import { connect } from 'react-redux';
import { reduxForm, clearSubmitErrors } from 'redux-form';
import PropTypes from 'prop-types';
import Snackbar from 'material-ui/Snackbar';
import GridColumn from '../../../common/grid/gridColumn';
import TextFieldForm from '../../../forms/textFieldForm';
import FileForm from '../../../forms/fileForm';
const messages = {
labels: {
comment: 'Title',
commentPlaceholder: 'Enter title of file',
document: 'Document',
},
};
const AddClarificationAnswerForm = (props) => {
const { handleSubmit, error, clearError, form } = props;
return (
<form onSubmit={handleSubmit}>
<GridColumn >
<TextFieldForm
fieldName="title"
textFieldProps={{
multiline: true,
InputProps: {
inputProps: {
maxLength: '5000',
},
},
}}
label={messages.labels.comment}
placeholder={messages.labels.commentPlaceholder}
/>
<FileForm
fieldName="file"
label={messages.labels.document}
formName={form}
/>
<Snackbar
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
open={error}
message={error}
autoHideDuration={6e3}
onClose={clearError}
/>
</GridColumn>
</form >
);
};
AddClarificationAnswerForm.propTypes = {
/**
* callback for form submit
*/
handleSubmit: PropTypes.func.isRequired,
clearError: PropTypes.func,
error: PropTypes.string,
form: PropTypes.string,
};
const formAddClarificationAnswerForm = reduxForm({
enableReinitialize: true,
})(AddClarificationAnswerForm);
const mapDispatchToProps = dispatch => ({
clearError: () => dispatch(clearSubmitErrors('addClarificationAnswerForm')),
});
export default connect(
null,
mapDispatchToProps,
)(formAddClarificationAnswerForm);
|
src/components/Sections/SectionTable.js
|
demisto/sane-reports
|
import './SectionTable.less';
import React from 'react';
import PropTypes from 'prop-types';
import { getDefaultMaxLength, TABLE_CELL_TYPE } from '../../constants/Constants';
import { isEmpty, isString, isArray, truncate, isObjectLike, map } from 'lodash';
import WidgetEmptyState from './WidgetEmptyState';
import SectionTitle from './SectionTitle';
function getExtraPropsForColumn(key, columnsMetaDataMap, headerStyle) {
const extraProps = {};
const metaData = columnsMetaDataMap.get(key);
if (metaData) {
extraProps.width = metaData.width;
}
if (headerStyle) {
extraProps.style = headerStyle;
}
return extraProps;
}
const SectionTable = ({ columns, readableHeaders, data, classes, style, title, titleStyle, emptyString,
maxColumns, forceRangeMessage, headerStyle }) => {
let tableData = data || [];
if (isString(data)) {
try {
tableData = JSON.parse(data);
} catch (ignored) {
return <div>Error parsing table</div>;
}
}
if (!isArray(tableData) && isObjectLike(tableData)) {
tableData = tableData.data || tableData.iocs || tableData.messages || [];
}
let readyColumns = columns;
if (isEmpty(columns) && isArray(tableData)) {
const headerKeys = {};
tableData.forEach((val, i) => {
for (const key in tableData[i]) { // eslint-disable-line no-restricted-syntax
if (headerKeys[key] !== key) {
headerKeys[key] = key;
}
}
});
readyColumns = Object.keys(headerKeys);
}
const columnsMetaDataMap = new Map();
if (columns && isArray(columns)) {
columns.forEach(mData => columnsMetaDataMap.set(mData.key, mData));
}
let tableBody;
const defaultMaxLength = getDefaultMaxLength();
if (isArray(readyColumns)) {
readyColumns = maxColumns > 0 ? readyColumns.slice(0, maxColumns) : readyColumns;
tableBody = tableData.length > 0 ? (
<table className={'ui compact table unstackable section-table ' + classes} style={{ tableLayout: 'fixed' }}>
<thead>
<tr>
{readyColumns.map((col) => {
const key = col.key || col;
const extraProps = getExtraPropsForColumn(key, columnsMetaDataMap, headerStyle);
return (
<th key={key} {...extraProps}>
{!col.hidden && ((readableHeaders && readableHeaders[key]) || key)}
</th>
);
})}
</tr>
</thead>
<tbody>
{tableData.map((row, i) =>
<tr key={i}>
{readyColumns.map((col, j) =>
(() => {
const key = col.key || col;
let cell = row[key];
if (cell === undefined || cell === null) {
cell = readableHeaders && row[readableHeaders[key]];
}
let cellToRender = '';
if (cell || cell === 0) {
switch (cell.type) {
case TABLE_CELL_TYPE.image:
cellToRender = (
<img
src={cell.data}
alt={cell.alt}
className={'ui image ' + cell.classes}
style={cell.style}
/>
);
break;
default:
cellToRender = truncate(cell, { length: defaultMaxLength });
}
}
return (
<td key={j} style={{ wordBreak: 'break-word', whiteSpace: 'pre-line' }}>
{cellToRender}
</td>
);
})()
)}
</tr>)
}
</tbody>
</table>
) : (
<div>
<table className={'ui compact table unstackable ' + classes} style={{ tableLayout: 'fixed' }}>
<thead>
<tr>
{readyColumns.map((col) => {
const key = col.key || col;
const extraProps = getExtraPropsForColumn(key, columnsMetaDataMap, headerStyle);
return (
<th
{...extraProps}
key={key}
{...(headerStyle ? { style: headerStyle } : {})}
>
{!col.hidden && ((readableHeaders && readableHeaders[key]) || key)}
</th>
);
})}
</tr>
</thead>
</table>
<WidgetEmptyState emptyString={emptyString} />
</div>);
} else {
tableBody = (
<table className={'ui compact table unstackable ' + classes}>
<tbody>
{map(tableData, (val, key) => (
<tr key={key}>
<td style={{ background: 'rgb(249, 250, 251)', width: '20%', whiteSpace: 'nowrap' }}>
{key}
</td>
<td>{truncate(val, { length: defaultMaxLength })}</td>
</tr>
))}
</tbody>
</table>
);
}
return (
<div className="section-table" style={style}>
<SectionTitle title={title} titleStyle={titleStyle} subTitle={forceRangeMessage} />
{tableBody}
</div>
);
};
SectionTable.propTypes = {
columns: PropTypes.array,
readableHeaders: PropTypes.object,
data: PropTypes.oneOfType([
PropTypes.array,
PropTypes.object,
PropTypes.string
]),
classes: PropTypes.string,
style: PropTypes.object,
title: PropTypes.string,
maxColumns: PropTypes.number,
titleStyle: PropTypes.object,
emptyString: PropTypes.string,
forceRangeMessage: PropTypes.string,
headerStyle: PropTypes.object
};
export default SectionTable;
|
src/index.js
|
budiantotan/book-store
|
import 'babel-polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css';
import configureStore from './store/configureStore';
import * as bookActions from './actions/bookActions';
const store = configureStore();
store.dispatch(bookActions.fetchBooks());
render(
<Provider store={store}>
<Router routes={routes} history={browserHistory} />
</Provider>,
document.getElementById('app')
);
|
src/js/components/icons/base/VmMaintenance.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-vm-maintenance`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'vm-maintenance');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M19,9.9999 L19,1.9999 L7,1.9999 L7,13.9999 L14,13.9999 L14,6.9999 L2,6.9999 L2,18.9999 L10,18.9999 M14,23 L20,17 M21,14 C19.8954305,14 19,14.8954305 19,16 C19,17.1045695 19.8954305,18 21,18 C22.1045695,18 23,17.1045695 23,16"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'VmMaintenance';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
imports/old/signup/confirm.js
|
jiyuu-llc/jiyuu
|
import React from 'react';
const Confirm = () => ({
confirmNext(){
const firstName = Session.get("fname");
const lastName = Session.get("lname");
const username = Session.get('username');
const email = Session.get('contact');
const dob =Session.get('dob');
const password = Session.get('password');
const accountType = Session.get('aType');
const theme = "jiyuu";
const interests = Session.get("interests") || [];
var user = {email:email,password:password,username:username,theme:theme,type:accountType,firstName:firstName,lastName:lastName,avatar:'/images/users.png',cover:'/images/cover.png',dob:dob, interests: interests};
Accounts.createUser(user,function(error){
if(error){
alert("Sorry something went wrong.")
} else{
Meteor.call('addConnectionGroup', 'Friends', (err, res)=>{
if (!err){
Meteor.call('addConnectionGroup', 'Following', (err, res)=>{
if (!err){
Meteor.call('addConnectionGroup', 'Blocked');
if (interests.indexOf('news') != -1){
// adds the anti media
Meteor.call('addConnectionToGroup', 'Following', 'TheAntiMedia');
}
if (interests.indexOf('technology') != -1){
// adds futurism
Meteor.call('addConnectionToGroup', 'Following', 'Futurism');
}
if (interests.indexOf('hippie') != -1){
// adds the mind unleashed
Meteor.call('addConnectionToGroup', 'Following', 'TheMindUnleashed');
}
}
});
}
});
FlowRouter.go('/register/10');
}
});
},
render() {
return (
<div id="jiyuu">
<h2 className="question">We have sent you a confirmation code.</h2>
<div id="question-card" className="form-group">
<div id="questionInputContain">
<input id="questionInput" type="text" tabindex="1" placeholder="Confirmation Code" className="form-control"/>
</div>
<div className="qnext" onClick={this.confirmNext.bind(this)}>
<i className="fa fa-caret-right" aria-hidden="true"/>
</div>
</div>
</div>
);
}
});
export default Confirm;
|
packages/frontend/tests/components/common/RadioButton/index.spec.js
|
ks888/LambStatus
|
import React from 'react'
import RadioButton from 'components/common/RadioButton'
import { mount } from 'enzyme'
describe('RadioButton', () => {
const generateProps = () => {
return {
onChange: sinon.spy(),
label: 'radio label',
groupName: 'radio group',
checked: false
}
}
it('should render the radio button', () => {
const props = generateProps()
const radioButton = mount(<RadioButton {...props} />)
assert(radioButton.find('label').prop('htmlFor') === props.label)
assert(radioButton.find('input').prop('name') === props.groupName)
assert(radioButton.find('input').getDOMNode().checked === false)
})
it('should click the radio button if specified by checked props', () => {
const props = generateProps()
props.checked = true
const radioButton = mount(<RadioButton {...props} />)
assert(radioButton.find('input').getDOMNode().checked === true)
})
})
|
examples/js/app.js
|
prajapati-parth/react-bootstrap-table
|
import React from 'react';
import ReactDOM from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { IndexRoute, Router, Route, hashHistory } from 'react-router';
import App from './components/App';
import Home from './components/Home';
import GettingStarted from './components/GettingStarted';
import PageNotFound from './components/PageNotFound';
import Basic from './basic/demo';
import Column from './column/demo';
import Sort from './sort/demo';
import ColumnFormat from './column-format/demo';
import ColumnFilter from './column-filter/demo';
import Selection from './selection/demo';
import Pagination from './pagination/demo';
import Manipulation from './manipulation/demo';
import CellEdit from './cell-edit/demo';
import Style from './style/demo';
import Advance from './advance/demo';
import Other from './others/demo';
import Complex from './complex/demo';
import Remote from './remote/demo';
import Expand from './expandRow/demo';
import Custom from './custom/demo';
import Span from './column-header-span/demo';
import KeyBoardNav from './keyboard-nav/demo';
import FooterTable from './footer/demo';
const renderApp = () => {
ReactDOM.render(
<AppContainer>
<Router history={ hashHistory }>
<Route path='/' component={ App }>
<IndexRoute component={ Home } />
<Route path='getting-started' component={ GettingStarted }/>
<Route path='examples'>
<Route path='basic' component={ Basic } />
<Route path='column' component={ Column } />
<Route path='sort' component={ Sort } />
<Route path='column-format' component={ ColumnFormat } />
<Route path='column-filter' component={ ColumnFilter } />
<Route path='column-header-span' component={ Span } />
<Route path='selection' component={ Selection } />
<Route path='pagination' component={ Pagination } />
<Route path='manipulation' component={ Manipulation } />
<Route path='cell-edit' component={ CellEdit } />
<Route path='style' component={ Style } />
<Route path='advance' component={ Advance } />
<Route path='others' component={ Other } />
<Route path='complex' component={ Complex } />
<Route path='remote' component={ Remote } />
<Route path='custom' component={ Custom } />
<Route path='expandRow' component={ Expand } />
<Route path='keyboard-nav' component={ KeyBoardNav } />
<Route path='footer' component={ FooterTable } />
</Route>
<Route path='*' component={ PageNotFound }/>
</Route>
</Router>
</AppContainer>, document.querySelector('#root'));
};
if (module.hot) {
module.hot.accept('./app', renderApp);
}
renderApp();
|
frontend/components/TwoColumn.js
|
datoszs/czech-lawyers
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from './TwoColumn.less';
const TwoColumn = ({children}) => <div className={styles.main}>{children}</div>;
TwoColumn.propTypes = {
children: PropTypes.node,
};
TwoColumn.defaultProps = {
children: null,
};
export default TwoColumn;
|
docs/app/Examples/elements/Reveal/Types/RevealExampleMoveDown.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Image, Reveal } from 'semantic-ui-react'
const RevealExampleMoveDown = () => (
<Reveal animated='move down'>
<Reveal.Content visible>
<Image src='/assets/images/wireframe/square-image.png' size='small' />
</Reveal.Content>
<Reveal.Content hidden>
<Image src='/assets/images/avatar/large/nan.jpg' size='small' />
</Reveal.Content>
</Reveal>
)
export default RevealExampleMoveDown
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js
|
nicksiyer/nicksiyer.github.io
|
import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
index.android.js
|
quickresolve/CycleTheBay
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class CycleTheBay extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('CycleTheBay', () => CycleTheBay);
|
src/icons/ArrowForwardIcon.js
|
kiloe/ui
|
import React from 'react';
import Icon from '../Icon';
export default class ArrowForwardIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M24 8l-2.83 2.83L32.34 22H8v4h24.34L21.17 37.17 24 40l16-16z"/></svg>;}
};
|
fixtures/nesting/src/modern/index.js
|
billfeller/react
|
import React from 'react';
import {StrictMode} from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import App from './App';
import {store} from '../store';
ReactDOM.render(
<StrictMode>
<Provider store={store}>
<App />
</Provider>
</StrictMode>,
document.getElementById('root')
);
|
webpack/scenes/Subscriptions/components/SubscriptionsTable/SubscriptionsTable.js
|
snagoor/katello
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { cloneDeep, findIndex, isEqual } from 'lodash';
import { translate as __ } from 'foremanReact/common/I18n';
import { LoadingState } from '../../../../components/LoadingState';
import { recordsValid } from '../../SubscriptionValidations';
import { buildTableRows, groupSubscriptionsByProductId } from './SubscriptionsTableHelpers';
import Table from './components/Table';
import Dialogs from './components/Dialogs';
class SubscriptionsTable extends Component {
constructor(props) {
super(props);
this.state = {
rows: undefined,
subscriptions: undefined,
groupedSubscriptions: undefined,
updatedQuantity: {},
editing: false,
showUpdateConfirmDialog: false,
showCancelConfirmDialog: false,
showErrorDialog: false,
};
}
static getDerivedStateFromProps(nextProps, prevState) {
if (
nextProps.subscriptions !== undefined &&
!isEqual(nextProps.subscriptions, prevState.subscriptions)
) {
const groupedSubscriptions = groupSubscriptionsByProductId(
nextProps.subscriptions,
prevState.groupedSubscriptions,
);
const rows = buildTableRows(
groupedSubscriptions,
nextProps.subscriptions.availableQuantities,
prevState.updatedQuantity,
);
return { rows, groupedSubscriptions, subscriptions: nextProps.subscriptions };
}
return null;
}
getInlineEditController = () => ({
isEditing: ({ rowData }) =>
(this.state.editing && rowData.available >= 0 && rowData.upstream_pool_id),
hasChanged: ({ rowData }) => {
const editedValue = this.state.updatedQuantity[rowData.id];
return this.hasQuantityChanged(rowData, editedValue);
},
onActivate: () => this.enableEditing(true),
onConfirm: () => {
if (recordsValid(this.state.rows)) {
this.showUpdateConfirm(true);
} else {
this.showErrorDialog(true);
}
},
onCancel: () => {
this.showCancelConfirm(true);
},
onChange: (value, { rowData }) => {
const updatedQuantity = cloneDeep(this.state.updatedQuantity);
if (this.hasQuantityChanged(rowData, value)) {
updatedQuantity[rowData.id] = value;
} else {
delete updatedQuantity[rowData.id];
}
this.updateRows(updatedQuantity);
},
});
getSelectionController = () => {
const allSubscriptionResults = this.props.subscriptions.results;
const checkAllRowsSelected = () =>
allSubscriptionResults.length === this.props.selectedRows.length;
return ({
allRowsSelected: () => checkAllRowsSelected(),
selectAllRows: () => {
if (checkAllRowsSelected()) {
this.props.onSelectedRowsChange([]);
this.props.toggleDeleteButton(false);
} else {
this.props.onSelectedRowsChange(allSubscriptionResults.map(row => row.id));
this.props.toggleDeleteButton(true);
}
},
selectRow: ({ rowData }) => {
let { selectedRows } = this.props;
if (selectedRows.includes(rowData.id)) {
selectedRows = selectedRows.filter(e => e !== rowData.id);
} else {
selectedRows = selectedRows.concat(rowData.id);
}
this.props.onSelectedRowsChange(selectedRows);
this.props.toggleDeleteButton(selectedRows.length > 0);
},
isSelected: ({ rowData }) => this.props.selectedRows.includes(rowData.id),
});
};
getTableProps = () => {
const {
subscriptions,
emptyState,
tableColumns,
loadSubscriptions,
selectionEnabled,
} = this.props;
const { groupedSubscriptions, rows, editing } = this.state;
return {
emptyState,
editing,
groupedSubscriptions,
loadSubscriptions,
rows,
subscriptions,
selectionEnabled,
tableColumns,
toggleSubscriptionGroup: this.toggleSubscriptionGroup,
inlineEditController: this.getInlineEditController(),
selectionController: this.getSelectionController(),
};
};
getUpdateDialogProps = () => {
const { showUpdateConfirmDialog: show, updatedQuantity } = this.state;
const {
updateQuantity,
} = this.props;
return {
show,
updatedQuantity,
updateQuantity,
enableEditing: this.enableEditing,
showUpdateConfirm: this.showUpdateConfirm,
};
};
getUnsavedChangesDialogProps = () => {
const { showCancelConfirmDialog: show } = this.state;
return {
show,
cancelEdit: this.cancelEdit,
showCancelConfirm: this.showCancelConfirm,
};
};
getInputsErrorsDialogProps = () => {
const { showErrorDialog: show } = this.state;
return {
show,
showErrorDialog: this.showErrorDialog,
};
};
getDeleteDialogProps = () => {
const {
subscriptionDeleteModalOpen: show,
onDeleteSubscriptions,
onSubscriptionDeleteModalClose,
} = this.props;
const { selectedRows } = this.props;
return {
show,
selectedRows,
onSubscriptionDeleteModalClose,
onDeleteSubscriptions,
};
};
getLoadingStateProps = () => {
const { subscriptions: { loading } } = this.props;
return {
loading,
loadingText: __('Loading'),
};
};
getDialogsProps = () => ({
updateDialog: this.getUpdateDialogProps(),
unsavedChangesDialog: this.getUnsavedChangesDialogProps(),
inputsErrorsDialog: this.getInputsErrorsDialogProps(),
deleteDialog: this.getDeleteDialogProps(),
});
toggleSubscriptionGroup = (groupId) => {
this.setState((prevState) => {
const { subscriptions } = this.props;
const { groupedSubscriptions, updatedQuantity } = prevState;
const { open } = groupedSubscriptions[groupId];
groupedSubscriptions[groupId].open = !open;
const rows = buildTableRows(
groupedSubscriptions,
subscriptions.availableQuantities,
updatedQuantity,
);
return { rows, groupedSubscriptions };
});
};
enableEditing = (editingState) => {
this.setState({
updatedQuantity: {},
editing: editingState,
});
};
updateRows = (updatedQuantity) => {
this.setState((prevState) => {
const { groupedSubscriptions } = prevState;
const { subscriptions } = this.props;
const rows = buildTableRows(
groupedSubscriptions,
subscriptions.availableQuantities,
updatedQuantity,
);
return { rows, updatedQuantity };
});
};
showUpdateConfirm = (show) => {
this.setState({
showUpdateConfirmDialog: show,
});
};
showCancelConfirm = (show) => {
this.setState({
showCancelConfirmDialog: show,
});
};
showErrorDialog = (show) => {
this.setState({
showErrorDialog: show,
});
};
cancelEdit = () => {
this.showCancelConfirm(false);
this.enableEditing(false);
this.updateRows({});
};
hasQuantityChanged = (rowData, editedValue) => {
if (editedValue !== undefined) {
const originalRows = this.props.subscriptions.results;
const index = findIndex(originalRows, row => (row.id === rowData.id));
const currentValue = originalRows[index].quantity;
return (`${editedValue}` !== `${currentValue}`);
}
return false;
};
render() {
return (
<LoadingState {...this.getLoadingStateProps()}>
<Table {...this.getTableProps()} />
<Dialogs {...this.getDialogsProps()} />
</LoadingState>
);
}
}
SubscriptionsTable.propTypes = {
tableColumns: PropTypes.arrayOf(PropTypes.string).isRequired,
loadSubscriptions: PropTypes.func.isRequired,
updateQuantity: PropTypes.func.isRequired,
emptyState: PropTypes.shape({}).isRequired,
subscriptions: PropTypes.shape({
loading: PropTypes.bool,
availableQuantities: PropTypes.shape({}),
// Disabling rule as existing code failed due to an eslint-plugin-react update
// eslint-disable-next-line react/forbid-prop-types
results: PropTypes.array,
}).isRequired,
subscriptionDeleteModalOpen: PropTypes.bool.isRequired,
onDeleteSubscriptions: PropTypes.func.isRequired,
onSubscriptionDeleteModalClose: PropTypes.func.isRequired,
toggleDeleteButton: PropTypes.func.isRequired,
selectedRows: PropTypes.instanceOf(Array).isRequired,
onSelectedRowsChange: PropTypes.func.isRequired,
selectionEnabled: PropTypes.bool,
};
SubscriptionsTable.defaultProps = {
selectionEnabled: false,
};
export default SubscriptionsTable;
|
node_modules/react-bootstrap/es/PaginationButton.js
|
ivanhristov92/bookingCalendar
|
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 elementType from 'react-prop-types/lib/elementType';
import SafeAnchor from './SafeAnchor';
import createChainedFunction from './utils/createChainedFunction';
// TODO: This should be `<Pagination.Item>`.
// TODO: This should use `componentClass` like other components.
var propTypes = {
componentClass: elementType,
className: React.PropTypes.string,
eventKey: React.PropTypes.any,
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool,
active: React.PropTypes.bool,
onClick: React.PropTypes.func
};
var defaultProps = {
componentClass: SafeAnchor,
active: false,
disabled: false
};
var PaginationButton = function (_React$Component) {
_inherits(PaginationButton, _React$Component);
function PaginationButton(props, context) {
_classCallCheck(this, PaginationButton);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
PaginationButton.prototype.handleClick = function handleClick(event) {
var _props = this.props,
disabled = _props.disabled,
onSelect = _props.onSelect,
eventKey = _props.eventKey;
if (disabled) {
return;
}
if (onSelect) {
onSelect(eventKey, event);
}
};
PaginationButton.prototype.render = function render() {
var _props2 = this.props,
Component = _props2.componentClass,
active = _props2.active,
disabled = _props2.disabled,
onClick = _props2.onClick,
className = _props2.className,
style = _props2.style,
props = _objectWithoutProperties(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']);
if (Component === SafeAnchor) {
// Assume that custom components want `eventKey`.
delete props.eventKey;
}
delete props.onSelect;
return React.createElement(
'li',
{
className: classNames(className, { active: active, disabled: disabled }),
style: style
},
React.createElement(Component, _extends({}, props, {
disabled: disabled,
onClick: createChainedFunction(onClick, this.handleClick)
}))
);
};
return PaginationButton;
}(React.Component);
PaginationButton.propTypes = propTypes;
PaginationButton.defaultProps = defaultProps;
export default PaginationButton;
|
src/icons/ArrowUpC.js
|
fbfeix/react-icons
|
import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class ArrowUpC extends React.Component {
render() {
if(this.props.bare) {
return <g>
<path d="M128.4,189.3L233.4,89c5.8-6,13.7-9,22.4-9c8.7,0,16.5,3,22.4,9l105.4,100.3c12.5,11.9,12.5,31.3,0,43.2
c-12.5,11.9-32.7,11.9-45.2,0L288,184.4v217c0,16.9-14.3,30.6-32,30.6c-17.7,0-32-13.7-32-30.6v-217l-50.4,48.2
c-12.5,11.9-32.7,11.9-45.2,0C115.9,220.6,115.9,201.3,128.4,189.3z"></path>
</g>;
} return <IconBase>
<path d="M128.4,189.3L233.4,89c5.8-6,13.7-9,22.4-9c8.7,0,16.5,3,22.4,9l105.4,100.3c12.5,11.9,12.5,31.3,0,43.2
c-12.5,11.9-32.7,11.9-45.2,0L288,184.4v217c0,16.9-14.3,30.6-32,30.6c-17.7,0-32-13.7-32-30.6v-217l-50.4,48.2
c-12.5,11.9-32.7,11.9-45.2,0C115.9,220.6,115.9,201.3,128.4,189.3z"></path>
</IconBase>;
}
};ArrowUpC.defaultProps = {bare: false}
|
src/components/Card.js
|
ciaoben/ListView
|
import React from 'react';
var Card = React.createClass({
getDefaultProps: function() {
return {
onPaginate: function() {},
status: 'loading',
per: 25,
page: 1,
filter: null
};
},
render: function() {
return (<div className='card'>
<div className='header'>
<span className='status'>Status: Active</span>
{this.props.title}
</div>
<div className='body'>
<span className='info'>45 email accounts</span>
<span className='separator'></span>
<span className='info'>3.5GB spazio occupato</span>
<span className='separator'></span>
<span className='info'>attivo dal 13 agosto 2015</span>
</div>
</div>);
}
});
module.exports = Card;
|
src/containers/Simple/Simple.js
|
hungtruongquoc/shipper_front
|
import React, { Component } from 'react';
class Simple extends Component {
render() {
return (
<div className="app flex-row align-items-center">
{this.props.children}
</div>
);
}
}
export default Simple;
|
examples/AwesomeApp/__tests__/index.android.js
|
QianmiOpen/iflux2
|
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
demo/universal-routed-flux-demo/components/AppContainer.react.js
|
waterbolik/prestudy
|
import React from 'react';
import {Link} from 'react-router';
export default class AppContainer extends React.Component{
constructor(props) {
super(props);
}
render(){
var nav = <div>
<p>
<Link to="/todo">Todo list without logs</Link><br/>
<Link to="/todo/logs">Todo list with logs</Link>
</p>
</div>;
return (
<div>
{this.props.children || nav}
</div>
);
}
}
|
src/TabPane.js
|
IveWong/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const TabPane = React.createClass({
propTypes: {
active: React.PropTypes.bool,
animation: React.PropTypes.bool,
onAnimateOutEnd: React.PropTypes.func,
disabled: React.PropTypes.bool
},
getDefaultProps() {
return {
animation: true
};
},
getInitialState() {
return {
animateIn: false,
animateOut: false
};
},
componentWillReceiveProps(nextProps) {
if (this.props.animation) {
if (!this.state.animateIn && nextProps.active && !this.props.active) {
this.setState({
animateIn: true
});
} else if (!this.state.animateOut && !nextProps.active && this.props.active) {
this.setState({
animateOut: true
});
}
}
},
componentDidUpdate() {
if (this.state.animateIn) {
setTimeout(this.startAnimateIn, 0);
}
if (this.state.animateOut) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.stopAnimateOut
);
}
},
startAnimateIn() {
if (this.isMounted()) {
this.setState({
animateIn: false
});
}
},
stopAnimateOut() {
if (this.isMounted()) {
this.setState({
animateOut: false
});
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd();
}
}
},
render() {
let classes = {
'tab-pane': true,
'fade': true,
'active': this.props.active || this.state.animateOut,
'in': this.props.active && !this.state.animateIn
};
return (
<div {...this.props}
role='tabpanel'
aria-hidden={!this.props.active}
className={classNames(this.props.className, classes)}
>
{this.props.children}
</div>
);
}
});
export default TabPane;
|
src/svg-icons/content/filter-list.js
|
kasra-co/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentFilterList = (props) => (
<SvgIcon {...props}>
<path d="M10 18h4v-2h-4v2zM3 6v2h18V6H3zm3 7h12v-2H6v2z"/>
</SvgIcon>
);
ContentFilterList = pure(ContentFilterList);
ContentFilterList.displayName = 'ContentFilterList';
ContentFilterList.muiName = 'SvgIcon';
export default ContentFilterList;
|
app/javascript/mastodon/features/notifications/components/notification.js
|
hyuki0000/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import StatusContainer from '../../../containers/status_container';
import AccountContainer from '../../../containers/account_container';
import { FormattedMessage } from 'react-intl';
import Permalink from '../../../components/permalink';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class Notification extends ImmutablePureComponent {
static propTypes = {
notification: ImmutablePropTypes.map.isRequired,
hidden: PropTypes.bool,
};
renderFollow (account, link) {
return (
<div className='notification notification-follow'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-user-plus' />
</div>
<FormattedMessage id='notification.follow' defaultMessage='{name} followed you' values={{ name: link }} />
</div>
<AccountContainer id={account.get('id')} withNote={false} hidden={this.props.hidden} />
</div>
);
}
renderMention (notification) {
return <StatusContainer id={notification.get('status')} withDismiss hidden={this.props.hidden} />;
}
renderFavourite (notification, link) {
return (
<div className='notification notification-favourite'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-star star-icon' />
</div>
<FormattedMessage id='notification.favourite' defaultMessage='{name} favourited your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={!!this.props.hidden} />
</div>
);
}
renderReblog (notification, link) {
return (
<div className='notification notification-reblog'>
<div className='notification__message'>
<div className='notification__favourite-icon-wrapper'>
<i className='fa fa-fw fa-retweet' />
</div>
<FormattedMessage id='notification.reblog' defaultMessage='{name} boosted your status' values={{ name: link }} />
</div>
<StatusContainer id={notification.get('status')} account={notification.get('account')} muted withDismiss hidden={this.props.hidden} />
</div>
);
}
render () {
const { notification } = this.props;
const account = notification.get('account');
const displayNameHtml = { __html: account.get('display_name_html') };
const link = <Permalink className='notification__display-name' href={account.get('url')} title={account.get('acct')} to={`/accounts/${account.get('id')}`} dangerouslySetInnerHTML={displayNameHtml} />;
switch(notification.get('type')) {
case 'follow':
return this.renderFollow(account, link);
case 'mention':
return this.renderMention(notification);
case 'favourite':
return this.renderFavourite(notification, link);
case 'reblog':
return this.renderReblog(notification, link);
}
return null;
}
}
|
lib/components/map/__tests__/isochrone.js
|
conveyal/scenario-editor
|
// @flow
import React from 'react'
import {Map} from 'react-leaflet'
import renderer from 'react-test-renderer'
import Isochrone from '../isochrone'
describe('Components > Map > Isochrone', () => {
it('renders correctly', () => {
const props = {
comparisonInProgress: false,
comparisonIsochrone: null,
isDestinationTravelTimeDistributionComponentOnMap: false,
isFetchingIsochrone: false,
isochrone: null,
isochroneCutoff: 10,
isochroneLonLat: { lat: 38.898, lon: -77.015 },
isochroneIsStale: false,
variantIndex: 1,
// actions
addDestinationTravelTimeDistributionComponentToMap: jest.fn(),
fetchTravelTimeSurface: jest.fn(),
remove: jest.fn(),
removeDestinationTravelTimeDistributionComponentFromMap: jest.fn(),
setDestination: jest.fn(),
setIsochroneLonLat: jest.fn()
}
const tree = renderer.create(
<Map>
<Isochrone {...props} />
</Map>
)
expect(tree).toMatchSnapshot()
// expect isochrone marker to be added to map by intercepting call to Leaflet
// expect(Leaflet.marker.mock.calls[0][0]).toMatchSnapshot()
})
})
|
App/src/features/projects/ProjectsList.js
|
DupK/dashboard-epitech
|
import React, { Component } from 'react';
import moment from 'moment';
import { observer } from 'mobx-react/native';
import {
Text,
View,
TouchableOpacity,
Platform,
ScrollView,
ListView,
} from 'react-native';
import ProgressBar from './ProgressBar';
import { Actions } from 'react-native-router-flux';
import _ from 'lodash';
import IconFA from 'react-native-vector-icons/FontAwesome';
import IconIO from 'react-native-vector-icons/Ionicons';
import styles from './styles.js';
@observer
export default class ProjectsList extends Component {
constructor(props) {
super(props);
this.renderProject = this.renderProject.bind(this);
this.renderHeader = this.renderHeader.bind(this);
this.ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
}
renderProject(project) {
const { uiStore } = this.props;
const parsedStart = moment(project.begin_acti, 'YYYY-MM-DD, HH:mm:ss');
const parsedEnd = moment(project.end_acti, 'YYYY-MM-DD, HH:mm:ss');
const projectDuration = parsedEnd.diff(parsedStart, 'days');
const durationSoFar = moment().diff(parsedStart, 'days');
const progress = Math.max(1, Math.min((durationSoFar / projectDuration) * 100, 100));
return (
<View style={{ padding: 15, borderBottomWidth: 1, borderBottomColor: 'rgba(0, 0, 0, 0.2)'}}>
<TouchableOpacity onPress={() => uiStore.isConnected && Actions.projectDetails({ progress: progress, project: project, title: project.acti_title }) }>
<View style={{ flex: 1, flexDirection: 'row', backgroundColor: '#fafafa',}}>
<View style={{ flex: 100,}}>
<View style={{flex: 1, flexDirection: 'column',}}>
<View style={{ flexDirection: 'row' }}>
<Text style={{ fontSize: 12, fontWeight: 'bold', color: '#233445',}}>{ project.acti_title }</Text>
<Text style={{fontSize: 12, color: '#233445',}}> / { project.title_module }</Text>
</View>
<View style={{ marginTop: 2 }}>
<View style={{flexDirection: 'row', justifyContent: 'space-between',}}>
<Text style={{color: '#233445', fontSize: 10, marginTop: 5,}}>{ parsedStart.fromNow() }</Text>
<Text style={{color: '#233445', fontSize: 10, margin: 5,}}>{ parsedEnd.fromNow() }</Text>
</View>
<ProgressBar completePercentage={progress}/>
</View>
</View>
</View>
<View style={{flex: 15, justifyContent: 'center', alignItems: 'flex-end',}}>
<IconIO name="ios-arrow-forward-outline" style={{fontSize: 14, color: '#233445',}}/>
</View>
</View>
</TouchableOpacity>
</View>
);
}
renderHeader(title, icon) {
return (
<View key={title} style={Platform.OS === 'ios' ? styles.headerContainerIOS : styles.headerContainerAndroid}>
<IconFA style={styles.headerIcon} name={ icon } />
<Text style={styles.headerText}>{ title }</Text>
</View>
)
}
renderAerProjects(projects) {
return [
this.renderHeader('AER projects', 'life-bouy'),
<ListView
key="aer"
dataSource={this.ds.cloneWithRows(projects)}
renderRow={this.renderProject}>
</ListView>
];
}
renderCurrentProjects(projects) {
return [
this.renderHeader('Currents projects', 'hourglass-half'),
<ListView
key="current"
dataSource={this.ds.cloneWithRows(projects)}
renderRow={this.renderProject}>
</ListView>
];
}
renderCommingProjects(projects) {
return [
this.renderHeader('Incoming projects', 'hourglass-start'),
<ListView
key="comming"
dataSource={this.ds.cloneWithRows(projects)}
renderRow={this.renderProject}>
</ListView>
];
}
render() {
const { projectsStore } = this.props;
const projects = projectsStore.projects.slice();
const currentProjects = _.filter(projects, (project) => (
moment(project.begin_acti, 'YYYY-MM-DD, HH:mm:ss').isBefore(moment()) && project.rights.includes('student')
));
const comingsProjects = _.filter(projects, (project) => (
moment(project.begin_acti, 'YYYY-MM-DD, HH:mm:ss').isAfter(moment()) && project.rights.includes('student')
));
const aerProjects = _.filter(projects, (project) => (
project.rights.includes('assistant')
));
return (
<View style={{ flex: 1 }}>
{projects.length > 0 ?
<ScrollView style={{ flex: 1, backgroundColor: '#FAFAFA' }}>
{ currentProjects.length !== 0 && this.renderCurrentProjects(currentProjects)}
{ comingsProjects.length !== 0 && this.renderCommingProjects(comingsProjects)}
{ aerProjects.length !== 0 && this.renderAerProjects(aerProjects) }
</ScrollView>
:
<View style={{ flex: 1, backgroundColor: '#2c3e50', flexDirection: 'column', justifyContent: 'center' }}>
<IconIO
name="ios-cafe-outline"
size={100}
style={{ color: '#203040', alignSelf: 'center' }}
/>
<Text style={{ marginTop: 10, color:'#203040', alignSelf: 'center', fontSize: 15 }}>
You're not registered to any future project
</Text>
</View>
}
</View>
);
}
}
ProjectsList.propTypes = {
projectsStore: React.PropTypes.object.isRequired,
uiStore: React.PropTypes.object.isRequired,
};
|
src/components/GithubButton/GithubButton.js
|
paschcua/erikras
|
import React from 'react';
const GithubButton = (props) => {
const {user, repo, type, width, height, count, large} = props;
let src = `https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=${type}`;
if (count) src += '&count=true';
if (large) src += '&size=large';
return (
<iframe
src={src}
frameBorder="0"
allowTransparency="true"
scrolling="0"
width={width}
height={height}
style={{border: 'none', width: width, height: height}}></iframe>
);
};
GithubButton.propTypes = {
user: React.PropTypes.string.isRequired,
repo: React.PropTypes.string.isRequired,
type: React.PropTypes.oneOf(['star', 'watch', 'fork', 'follow']).isRequired,
width: React.PropTypes.number.isRequired,
height: React.PropTypes.number.isRequired,
count: React.PropTypes.bool,
large: React.PropTypes.bool
};
export default GithubButton;
|
src/svg-icons/maps/layers-clear.js
|
hai-cea/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLayersClear = (props) => (
<SvgIcon {...props}>
<path d="M19.81 14.99l1.19-.92-1.43-1.43-1.19.92 1.43 1.43zm-.45-4.72L21 9l-9-7-2.91 2.27 7.87 7.88 2.4-1.88zM3.27 1L2 2.27l4.22 4.22L3 9l1.63 1.27L12 16l2.1-1.63 1.43 1.43L12 18.54l-7.37-5.73L3 14.07l9 7 4.95-3.85L20.73 21 22 19.73 3.27 1z"/>
</SvgIcon>
);
MapsLayersClear = pure(MapsLayersClear);
MapsLayersClear.displayName = 'MapsLayersClear';
MapsLayersClear.muiName = 'SvgIcon';
export default MapsLayersClear;
|
src/rows-toolbar.js
|
Uber5/u5-datatable
|
import React from 'react'
import IconMenu from 'material-ui/IconMenu'
import IconButton from 'material-ui/IconButton'
import NavigationExpandMoreIcon from 'material-ui/svg-icons/navigation/expand-more'
import MenuItem from 'material-ui/MenuItem'
import DropDownMenu from 'material-ui/DropDownMenu'
import FlatButton from 'material-ui/FlatButton'
import RaisedButton from 'material-ui/RaisedButton'
import {
Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle
} from 'material-ui/Toolbar';
import BackIcon from 'material-ui/svg-icons/navigation/arrow-back'
import * as R from 'ramda'
import { saveAs } from 'file-saver'
export default class ToolbarExamplesSimple extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 3,
};
}
handleChange = (event, index, value) => this.setState({value});
downloadRows = () => {
const { selected, config } = this.props
const escape = s => s.replace(/["]/g, "\\$&") // escape '"' only
const headers = R.keys(config.columns)
.filter(colName => config.columns[colName].skipExport !== true)
.map(colName => config.columns[colName].label || colName)
.map(label => `"${ escape(label) }"`).join(',')
const lines = selected.map(row => {
const line = R.keys(config.columns)
.filter(colName => config.columns[colName].skipExport !== true)
.map(colName => {
const value = R.path(colName.split('.'), row)
const spec = config.columns[colName]
const formatted = spec.format ? spec.format(row) : value
const escaped = formatted ? escape(formatted.toString()) : ''
return `"${ escaped }"`
}).join(',')
return line
})
const asCsv = R.concat([ headers ], lines ).join('\n')
const blob = new Blob([ asCsv ], { type: "text/csv;charset=utf-8" })
saveAs(blob, "data.csv")
}
render() {
const { selected, clearSelected } = this.props
return (
<Toolbar>
<ToolbarGroup firstChild={true}>
<FlatButton
label="Back"
icon={<BackIcon />}
onClick={clearSelected}
/>
</ToolbarGroup>
<ToolbarGroup>
<ToolbarTitle text={`${ selected.length } selected`} />
<ToolbarSeparator />
<RaisedButton label="Download" primary={true}
onClick={this.downloadRows}
/>
</ToolbarGroup>
</Toolbar>
);
}
}
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/src/app/components/Apis/Create/Swagger/ApiCreateSwagger.js
|
lakmali/carbon-apimgt
|
/*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import SingleInput from '../FormComponents/SingleInput';
import CheckboxOrRadioGroup from '../FormComponents/CheckboxOrRadioGroup';
import API from '../../../../data/api.js'
import { toast } from 'react-toastify';
import 'react-toastify/dist/ReactToastify.min.css';
import './ApiCreateSwagger.css'
import Dropzone from 'react-dropzone'
import {ScopeValidation, resourceMethod, resourcePath} from '../../../../data/ScopeValidation'
import { Form, Icon, Input, Button, message, Upload, Radio } from 'antd';
const FormItem = Form.Item;
const RadioButton = Radio.Button;
const RadioGroup = Radio.Group;
class SwaggerForm extends React.Component {
constructor(props) {
super(props);
this.state = {uploadMethod:'file',file:{}}
}
createAPICallback = (response) => {
let uuid = JSON.parse(response.data).id;
let redirect_url = "/apis/" + uuid + "/overview";
this.props.history.push(redirect_url);
};
/**
* Do create API from either swagger URL or swagger file upload.In case of URL pre fetch the swagger file and make a blob
* and the send it over REST API.
* @param e {Event}
*/
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
if (!err) {
console.log('Received values of form: ', values);
let input_type = this.state.uploadMethod;
if (input_type === "url") {
let url = values.url;
let data = {};
data.url = url;
data.type = 'swagger-url';
let new_api = new API('');
new_api.create(data)
.then(this.createAPICallback)
.catch(
function (error_response) {
let error_data = JSON.parse(error_response.data);
let messageTxt = "Error[" + error_data.code + "]: " + error_data.description + " | " + error_data.message + ".";
message.error(messageTxt);
console.debug(error_response);
});
} else if (input_type === "file") {
let swagger = this.state.file.originFileObj;
let new_api = new API('');
new_api.create(swagger)
.then(this.createAPICallback)
.catch(
function (error_response) {
let error_data;
let messageTxt;
if (error_response.obj) {
error_data = error_response.obj;
messageTxt = "Error[" + error_data.code + "]: " + error_data.description + " | " + error_data.message + ".";
} else {
error_data = error_response.data;
messageTxt = "Error: " + error_data + ".";
}
message.error(messageTxt);
console.debug(error_response);
});
}
} else {
}
});
};
normFile = (e) => {
console.log('Upload event:', e);
if (Array.isArray(e)) {
return e;
}
return e && e.fileList;
};
handleUploadMethodChange = (e) => {
this.setState({uploadMethod:e.target.value});
};
toggleSwaggerType = (containerType) => {
return this.state.uploadMethod === containerType ? '' : 'hidden';
};
handleUploadFile = (info) => {
const status = info.file.status;
if (status !== 'uploading') {
console.log(info.file, info.fileList);
}
if (status === 'done') {
message.success(`${info.file.name} file uploaded successfully.`);
this.setState({file:info.file})
} else if (status === 'error') {
message.error(`${info.file.name} file upload failed.`);
}
}
render(){
const { getFieldDecorator } = this.props.form;
const props = {
name: 'file',
multiple: false,
showUploadList: true,
action: '//jsonplaceholder.typicode.com/posts/'
};
return(
<Form onSubmit={this.handleSubmit} className="login-form">
<FormItem>
{getFieldDecorator('radio-button')(
<RadioGroup initialValue="file" onChange={this.handleUploadMethodChange}>
<RadioButton value="file">Swagger File</RadioButton>
<RadioButton value="url">Swagger URL</RadioButton>
</RadioGroup>
)}
</FormItem>
<FormItem className={this.toggleSwaggerType("file")}>
<div className="dropbox">
{getFieldDecorator('dragger', {
valuePropName: 'fileList',
getValueFromEvent: this.normFile,
})(
<Upload.Dragger {...props} onChange={this.handleUploadFile}>
<p className="ant-upload-drag-icon">
<Icon type="inbox" />
</p>
<p className="ant-upload-text">Click or drag file to this area to upload</p>
<p className="ant-upload-hint">Support for a single or bulk upload. Strictly prohibit from uploading company data or other band files</p>
</Upload.Dragger>
)}
</div>
</FormItem>
<FormItem className={this.toggleSwaggerType("url")}>
{getFieldDecorator('userName', {
rules: [{ required: false, message: 'Please input your username!' }],
})(
<Input name="url" prefix={<Icon type="user" style={{ fontSize: 13 }} />} placeholder="Username" />
)}
</FormItem>
<FormItem >
<ScopeValidation resourceMethod={resourceMethod.POST} resourcePath={resourcePath.APIS}>
<Button type="primary" htmlType="submit">
Create
</Button>
</ScopeValidation>
<Button type="default" htmlType="button" onClick={() => this.props.history.push("/api/create/home")}>
Cancel
</Button>
</FormItem>
</Form>
);
}
}
const SwaggerFormGenerated = Form.create()(SwaggerForm);
class ApiCreateSwagger extends React.Component {
constructor(props) {
super(props);
}
render = () => {return <SwaggerFormGenerated history={this.props.history} /> }
}
export default ApiCreateSwagger;
|
app/javascript/mastodon/features/standalone/hashtag_timeline/index.js
|
cobodo/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { expandHashtagTimeline } from 'mastodon/actions/timelines';
import Masonry from 'react-masonry-infinite';
import { List as ImmutableList } from 'immutable';
import DetailedStatusContainer from 'mastodon/features/status/containers/detailed_status_container';
import { debounce } from 'lodash';
import LoadingIndicator from 'mastodon/components/loading_indicator';
const mapStateToProps = (state, { hashtag }) => ({
statusIds: state.getIn(['timelines', `hashtag:${hashtag}`, 'items'], ImmutableList()),
isLoading: state.getIn(['timelines', `hashtag:${hashtag}`, 'isLoading'], false),
hasMore: state.getIn(['timelines', `hashtag:${hashtag}`, 'hasMore'], false),
});
export default @connect(mapStateToProps)
class HashtagTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
isLoading: PropTypes.bool.isRequired,
hasMore: PropTypes.bool.isRequired,
hashtag: PropTypes.string.isRequired,
local: PropTypes.bool.isRequired,
};
static defaultProps = {
local: false,
};
componentDidMount () {
const { dispatch, hashtag, local } = this.props;
dispatch(expandHashtagTimeline(hashtag, { local }));
}
handleLoadMore = () => {
const { dispatch, hashtag, local, statusIds } = this.props;
const maxId = statusIds.last();
if (maxId) {
dispatch(expandHashtagTimeline(hashtag, { maxId, local }));
}
}
setRef = c => {
this.masonry = c;
}
handleHeightChange = debounce(() => {
if (!this.masonry) {
return;
}
this.masonry.forcePack();
}, 50)
render () {
const { statusIds, hasMore, isLoading } = this.props;
const sizes = [
{ columns: 1, gutter: 0 },
{ mq: '415px', columns: 1, gutter: 10 },
{ mq: '640px', columns: 2, gutter: 10 },
{ mq: '960px', columns: 3, gutter: 10 },
{ mq: '1255px', columns: 3, gutter: 10 },
];
const loader = (isLoading && statusIds.isEmpty()) ? <LoadingIndicator key={0} /> : undefined;
return (
<Masonry ref={this.setRef} className='statuses-grid' hasMore={hasMore} loadMore={this.handleLoadMore} sizes={sizes} loader={loader}>
{statusIds.map(statusId => (
<div className='statuses-grid__item' key={statusId}>
<DetailedStatusContainer
id={statusId}
compact
measureHeight
onHeightChange={this.handleHeightChange}
/>
</div>
)).toArray()}
</Masonry>
);
}
}
|
src/shared/components/imageListItem/imageListItem.js
|
tal87/operationcode_frontend
|
import React from 'react';
import PropTypes from 'prop-types';
import styles from './imageListItem.css';
const ImageListItem = props => (
<div className={styles.imageListItem}>
<img className={styles.cardImage} src={props.image} alt={props.title} />
<div className={styles.cardText}>
<h3 className={styles.cardTitle}>{props.title}</h3>
<p>{props.cardText}</p>
</div>
</div>
);
ImageListItem.propTypes = {
image: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
cardText: PropTypes.string.isRequired
};
export default ImageListItem;
|
app/components/results-Child/Player.js
|
mohamekasem/reactstart
|
import React from 'react';
import PropTypes from 'prop-types';
import PlayerPreview from '../Battle-Child/Player-Preview';
const Profile = (props)=>{
let info = props.info;
return (
<PlayerPreview username={info.login} avatar={info.avatar_url}>
<ul className='space-list-items'>
{info.name && <li>{info.name}</li>}
{info.location && <li>{info.location}</li>}
{info.company && <li>{info.company}</li>}
<li>Followers: {info.followers}</li>
<li>Following: {info.following}</li>
<li>Public Repos: {info.public_repos}</li>
{info.blog && <li><a href={info.blog}>{info.blog}</a></li>}
</ul>
</PlayerPreview>
)
}
Profile.PropTypes = {
info: PropTypes.object.isRquired
}
const Player = (props)=> {
return (
<div>
<h1>{props.label}</h1>
<h3 style={{textAlign: 'centr'}}>Score: {props.score}</h3>
<Profile
info={props.profile}
/>
</div>
)
}
Player.propTypes = {
label: PropTypes.string.isRequired,
score: PropTypes.number.isRequired,
profile: PropTypes.object.isRequired,
}
export default Player;
|
src/components/dashboard/feed/item.js
|
cosminseceleanu/react-sb-admin-bootstrap4
|
import React from 'react';
import Comment from "./comment";
import ItemActions from "./item-actions";
import {
Card,
CardImg,
CardBody,
CardFooter,
CardTitle,
CardText
} from 'reactstrap';
const Item = ({item}) => {
return (
<Card className="mb-3">
<CardImg top width="100%" src={item.photo}/>
<CardBody>
<CardTitle><a href="/">{item.user}</a></CardTitle>
<CardText className="small">
{item.description}
{renderHashTags(item.tags)}
</CardText>
</CardBody>
<hr className="my-0"/>
<ItemActions/>
<hr className="my-0"/>
<CardBody className="small bg-faded">
{renderComments(item.comments)}
</CardBody>
<CardFooter className="small text-muted">{item.date}</CardFooter>
</Card>
)
};
const renderHashTags = tags => {
return tags.map((tag, index) => {
return (
<a key={index} href="/"> {tag}</a>
)
})
};
const renderComments = comments => {
return comments.map((comment, index) => {
const reply = comment.reply ? renderComment(comment.reply, null) : null;
return renderComment(comment, reply, index);
})
};
const renderComment = (comment, reply = null, index) => {
return (
<Comment key={reply !== null ? `reply-${index}` : index} {...comment}>{reply}</Comment>
)
};
export default Item;
|
src/Nav/Nav.js
|
brz0/folio-v11
|
import React from 'react';
import Modal from 'react-modal';
import {Link} from 'react-router';
import LogoLight from '../img/logo-light.svg';
import LogoDark from '../img/logo-dark.svg';
import MenuBtn from '../img/menu-btn.svg';
import MenuBtnDark from '../img/menu-btn-dark.svg';
import MenuClose from '../img/menuClose.svg';
const customStyles = {
content: {
top: 'auto',
left: 'auto',
right: '0px',
bottom: 'auto',
transform: 'none',
width: '300px',
height: '100%',
position: 'fixed',
marginRight: '0px',
backgroundColor: '#F21F40',
border: 'none',
borderRadius: '0px',
zIndex: 4,
padding: '0px',
},
overlay: {
backgroundColor: 'transparent',
zIndex: 4,
}
};
function setStyle( objId, propertyObject ) {
var elem = document.getElementById(objId);
for (var property in propertyObject)
elem.style[property] = propertyObject[property];
}
var scrollObject = {};
function getScrollPosition(){
scrollObject = {
x: window.pageXOffset,
y: window.pageYOffset
}
if(scrollObject.y > window.innerHeight - 50) {
setStyle('nav', {'background': '#F8F5F9', 'transition': '1s'});
setStyle('logoLight', {'display': 'none', 'transition': '1s'});
setStyle('logoDark', {'display': 'inline-block', 'transition': '1s'});
setStyle('menuLight', {'display': 'none', 'transition': '1s'});
setStyle('menuDark', {'display': 'block', 'transition': '1s'});
document.activeElement.blur();
} else {
setStyle('nav', {'background': 'transparent', 'transition': '1s'});
setStyle('logoLight', {'display': 'inline-block', 'transition': '1s'});
setStyle('logoDark', {'display': 'none', 'transition': '1s'});
setStyle('menuLight', {'display': 'block', 'transition': '1s'});
setStyle('menuDark', {'display': 'none', 'transition': '1s'});
}
}
window.onscroll = getScrollPosition;
export default class Nav extends React.Component {
constructor() {
super();
this.state = {
modalIsOpen: false
};
this.openModal = this.openModal.bind(this);
this.afterOpenModal = this.afterOpenModal.bind(this);
this.closeModal = this.closeModal.bind(this);
}
openModal() {
this.setState({modalIsOpen: true});
}
afterOpenModal() {}
closeModal() {
this.setState({modalIsOpen: false});
}
render() {
return (
<div>
<div className="navWrap" id="nav">
<Link to="/"><img src={LogoLight} className="logoNav" id="logoLight" alt="Justin Brazeau" /></Link>
<Link to="/"><img src={LogoDark} className="logoNav" id="logoDark" alt="Justin Brazeau" /></Link>
<img src={MenuBtn} className="menuBtn" id="menuLight" alt="Menu" onClick={this.openModal} />
<img src={MenuBtnDark} className="menuBtn" id="menuDark" alt="Menu" onClick={this.openModal} />
</div>
<Modal
isOpen={this.state.modalIsOpen} onAfterOpen={this.afterOpenModal}
onRequestClose={this.closeModal} style={customStyles}
contentLabel="Example Modal" >
<button onClick={this.closeModal} className="modalBtnClose">
<img src={MenuClose} className="modalBtnCloseImg" />
</button>
<div className="menuList">
<h2>Projects</h2>
<ul>
<Link to="chart-suite"><li><span>Chart Suite</span></li></Link>
<Link to="terminal-ui"><li><span>Terminal UI</span></li></Link>
<Link to="homes-from-the-future"><li><span>Future Homes</span></li></Link>
<Link to="odd-scenes"><li><span>Odd Scenes</span></li></Link>
<Link to="walltagged"><li><span>WallTagged</span></li></Link>
<Link to="gold-tooth"><li><span>Gold Tooth</span></li></Link>
</ul>
</div>
<div className="bottonMenuWrap">
<div className="buttonMenu">
<a href="http://be.net/justinbrazeau">
<div className="buttonMenuInner btnMenuLeft">
<i className="fa fa-behance" aria-hidden="true"></i>
<span>behance</span>
</div>
</a>
</div>
<div className="buttonMenu">
<a href="http://codepen.io/brz0">
<div className="buttonMenuInner btnMenuRight">
<i className="fa fa-codepen" aria-hidden="true"></i>
<span>codepen</span>
</div>
</a>
</div>
<div className="buttonMenu">
<a href="http://twitter.com/justinbrazeau">
<div className="buttonMenuInner btnMenuLeft buttonMenuInnerBottom">
<i className="fa fa-twitter" aria-hidden="true"></i>
<span>twitter</span>
</div>
</a>
</div>
<div className="buttonMenu">
<a href="http://github.com/brz0">
<div className="buttonMenuInner btnMenuRight buttonMenuInnerBottom">
<i className="fa fa-github" aria-hidden="true"></i>
<span>github</span>
</div>
</a>
</div>
</div>
</Modal>
</div>
)
}
}
|
app/react-icons/fa/hand-peace-o.js
|
scampersand/sonos-front
|
import React from 'react';
import IconBase from 'react-icon-base';
export default class FaHandPeaceO extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m31.8 14.4q1.3 0 2.3 0.6 3.2 1.4 3.2 5v3.9q0 2.2-0.5 4.2l-1.9 7.6q-0.5 1.9-2 3.1t-3.6 1.2h-14.9q-2.3 0-4-1.7t-1.7-4v-9l-5.3-14q-0.4-1-0.4-2 0-2.4 1.7-4.1t4-1.6q1.8 0 3.3 1t2 2.7l0.4 0.9v-2.5q0-2.4 1.7-4t4-1.7 4.1 1.7 1.7 4v5.8q0.6-0.1 1-0.1 1.6 0 2.9 0.8t1.9 2.2z m-4.9-0.1q-0.7 0-1.3 0.4t-0.9 1.1l-1.7 3.6-1.6 3.5h1.2q1.2 0 2.1 0.7t1.1 1.8l3.4-7.6q0.2-0.4 0.2-1 0-1-0.7-1.8t-1.8-0.7z m5 3q-0.5 0-0.9 0.2t-0.7 0.3-0.5 0.7-0.4 0.7-0.4 0.8l-2.9 6.5q-0.2 0.4-0.2 1 0 1 0.7 1.8t1.8 0.7q0.7 0 1.3-0.4t0.9-1.1l3.6-7.8q0.2-0.4 0.2-0.9 0-1.1-0.7-1.8t-1.8-0.7z m-26-8q0 0.5 0.1 1l5.6 14.5v1.6l2.2-2.5q1-1 2.4-1h4.4l2.4-5.2v-12q0-1.2-0.8-2t-2.1-0.8-2 0.8-0.8 2v14.3h-1.4l-4.5-11.7q-0.3-0.9-1.1-1.4t-1.6-0.5q-1.2 0-2 0.9t-0.8 2z m23.4 27.8q1 0 1.8-0.6t1-1.5l1.9-7.6q0.4-1.6 0.4-3.5v-2l-3.1 6.9q-0.4 0.9-1.2 1.4t-1.7 0.5q-1.2 0-2.1-0.8t-1.1-1.9q-1 1.3-2.6 1.3h-4.6v-0.7h4.6q1.1 0 1.8-0.8t0.8-1.7-0.7-1.8-1.7-0.7h-6.6q-1.1 0-1.8 0.8l-2.8 3v6.9q0 1.2 0.8 2t2 0.8h14.9z"/></g>
</IconBase>
);
}
}
|
src/scripts/components/app.js
|
k-takam/simple-text-translator
|
import React, { Component } from 'react';
import Header from './header';
import Footer from './footer';
import MenuContainer from '../containers/menu-container';
import InputTextContainer from '../containers/input-text-container';
import OutputTextContainer from '../containers/output-text-container';
import ModalContainer from '../containers/modal-container';
export default class App extends Component {
render() {
return (
<div className="wrapper">
<Header />
<section className="section">
<div className="container">
<div className="columns is-multiline">
<div className="column is-half">
<p>テキストを日本語から英語へ翻訳します。</p>
</div>
<MenuContainer />
<InputTextContainer />
<OutputTextContainer />
</div>
</div>
<ModalContainer />
</section>
<Footer />
</div>
);
}
}
|
app/components/Vesting/CancelPowerDownPrompt.js
|
aaroncox/vessel
|
// @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Message, Modal, Segment } from 'semantic-ui-react';
import { Form } from 'formsy-semantic-ui-react'
import * as KeysActions from '../../actions/keys';
class CancelPowerDownPrompt extends Component {
handleConfirm = (e: SyntheticEvent) => {
const account = this.props.targetAccount;
const permissions = this.props.keys.permissions;
// console.log('cancelWithdrawVesting', { account }, permissions[account]);
this.props.actions.useKey('cancelWithdrawVesting', { account }, permissions[account]);
e.preventDefault();
}
handleOnChange = (value) => {
const vests = parseFloat(value).toFixed(6);
const props = this.props.hive.props;
const totalVestsHive = parseFloat(props.total_vesting_fund_steem.split(" ")[0])
const totalVests = parseFloat(props.total_vesting_shares.split(" ")[0])
const sp = totalVestsHive * vests / totalVests;
const perWeek = Math.round(sp / 13 * 1000) / 1000;
this.setState({ vests, sp, perWeek });
}
handleOnChangeComplete = (value) => {
const vests = parseFloat(value).toFixed(6);
const props = this.props.hive.props;
const totalVestsHive = parseFloat(props.total_vesting_fund_steem.split(" ")[0])
const totalVests = parseFloat(props.total_vesting_shares.split(" ")[0])
const sp = totalVestsHive * vests / totalVests;
const perWeek = Math.round(sp / 13 * 1000) / 1000;
this.setState({ vests, sp, perWeek });
}
render() {
const {
account_vesting_withdraw_error,
account_vesting_withdraw_pending,
account_vesting_withdraw_resolved
} = this.props.processing;
return (
<Modal
size="small"
open
header="Cancel - Power Down"
content={
<Form
error={account_vesting_withdraw_error}
loading={account_vesting_withdraw_pending}
>
<Segment
padded
basic
>
<p>
Cancelling this power down cannot be reversed. Any progress
on your current week's credit will be reset, and if you power
down again, you'll have to wait another 7 days for it to begin.
</p>
<Message
error
header="Operation Error"
content={account_vesting_withdraw_error}
/>
</Segment>
</Form>
}
actions={[
{
key: 'no',
content: 'Cancel Operation',
floated: 'left',
color: 'red',
onClick: this.props.handleCancel,
disabled: account_vesting_withdraw_pending
},
{
key: 'yes',
type: 'submit',
content: 'Cancel Power Down',
color: 'blue',
onClick: this.handleConfirm,
disabled: account_vesting_withdraw_pending
}
]}
/>
);
}
}
function mapStateToProps(state) {
return {
account: state.account,
keys: state.keys,
hive: state.hive
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({
...KeysActions
}, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CancelPowerDownPrompt);
|
src/prop-types.js
|
narendrashetty/react-geosuggest
|
import React from 'react';
/**
* Default values
*/
export default {
fixtures: React.PropTypes.array,
initialValue: React.PropTypes.string,
placeholder: React.PropTypes.string,
disabled: React.PropTypes.bool,
className: React.PropTypes.string,
inputClassName: React.PropTypes.string,
suggestsHiddenClassName: React.PropTypes.string,
suggestItemActiveClassName: React.PropTypes.string,
location: React.PropTypes.object,
radius: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
bounds: React.PropTypes.object,
country: React.PropTypes.string,
types: React.PropTypes.array,
queryDelay: React.PropTypes.number,
googleMaps: React.PropTypes.object,
onSuggestSelect: React.PropTypes.func,
onFocus: React.PropTypes.func,
onBlur: React.PropTypes.func,
onChange: React.PropTypes.func,
onKeyPress: React.PropTypes.func,
skipSuggest: React.PropTypes.func,
getSuggestLabel: React.PropTypes.func,
autoActivateFirstSuggest: React.PropTypes.bool,
style: React.PropTypes.shape({
input: React.PropTypes.object,
suggests: React.PropTypes.object,
suggestItem: React.PropTypes.object
}),
ignoreTab: React.PropTypes.bool,
label: React.PropTypes.string
};
|
app/templates/src/createRoutes.js
|
chentsulin/generator-redux-app
|
import React from 'react';
import { Route } from 'react-router';
import App from './containers/App';
import * as containers from './containers';
const {
CounterPage,
AnotherPage,
NotFoundPage,
} = containers;
/**
* /
* /another
**/
const createRoutes = store => ( // eslint-disable-line no-unused-vars
<Route component={App}>
<Route path="/" component={CounterPage} />
<Route path="/another" component={AnotherPage} />
<Route path="*" component={NotFoundPage} />
</Route>
);
export default createRoutes;
|
src/Popover.js
|
JimiHFord/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
const Popover = React.createClass({
mixins: [ BootstrapMixin ],
propTypes: {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: CustomPropTypes.isRequiredForA11y(
React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
),
/**
* Sets the direction the Popover is positioned towards.
*/
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "left" position value for the Popover.
*/
positionLeft: React.PropTypes.number,
/**
* The "top" position value for the Popover.
*/
positionTop: React.PropTypes.number,
/**
* The "left" position value for the Popover arrow.
*/
arrowOffsetLeft: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
]),
/**
* The "top" position value for the Popover arrow.
*/
arrowOffsetTop: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
]),
/**
* Title text
*/
title: React.PropTypes.node
},
getDefaultProps() {
return {
placement: 'right'
};
},
render() {
const classes = {
'popover': true,
[this.props.placement]: true
};
const style = {
'left': this.props.positionLeft,
'top': this.props.positionTop,
'display': 'block',
// we don't want to expose the `style` property
...this.props.style // eslint-disable-line react/prop-types
};
const arrowStyle = {
'left': this.props.arrowOffsetLeft,
'top': this.props.arrowOffsetTop
};
return (
<div role="tooltip" {...this.props} className={classNames(this.props.className, classes)} style={style} title={null}>
<div className="arrow" style={arrowStyle} />
{this.props.title ? this.renderTitle() : null}
<div className="popover-content">
{this.props.children}
</div>
</div>
);
},
renderTitle() {
return (
<h3 className="popover-title">{this.props.title}</h3>
);
}
});
export default Popover;
|
src/routes.js
|
kunwardeep/react-redux-store
|
import React from 'react';
import {Route,IndexRoute} from 'react-router';
import HomePage from './components/home/HomePage';
import App from './components/App';
import AboutPage from './components/about/AboutPage';
import CoursesPage from './components/course/CoursesPage';
import PracticePage from './components/practice/PracticePage';
import ManageCoursePage from './components/course/ManageCoursePage';
export default(
<Route path="/" component={App}>
<IndexRoute component={HomePage}/>
<Route path="about" component={AboutPage}/>
<Route path="courses" component={CoursesPage}/>
<Route path="course/:id" component={ManageCoursePage}/>
<Route path="course" component={ManageCoursePage}/>
<Route path="practice" component={PracticePage}/>
</Route>
);
|
docs/build.js
|
leozdgao/react-bootstrap
|
import React from 'react';
import path from 'path';
import Router from 'react-router';
import routes from './src/Routes';
import Root from './src/Root';
import fsp from 'fs-promise';
import { copy } from '../tools/fs-utils';
import { exec } from '../tools/exec';
import metadata from './generate-metadata';
const repoRoot = path.resolve(__dirname, '../');
const docsBuilt = path.join(repoRoot, 'docs-built');
const license = path.join(repoRoot, 'LICENSE');
const readmeSrc = path.join(__dirname, 'README.docs.md');
const readmeDest = path.join(docsBuilt, 'README.md');
/**
* Generates HTML code for `fileName` page.
*
* @param {string} fileName Path for Router.Route
* @return {Promise} promise
* @internal
*/
function generateHTML(fileName, propData) {
return new Promise((resolve, reject) => {
const urlSlug = fileName === 'index.html' ? '/' : `/${fileName}`;
Router.run(routes, urlSlug, Handler => {
let html = React.renderToString(React.createElement(Handler, { propData }));
html = '<!doctype html>' + html;
let write = fsp.writeFile(path.join(docsBuilt, fileName), html);
resolve(write);
});
});
}
export default function BuildDocs({ dev }) {
console.log('Building: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : ''));
return exec(`rimraf ${docsBuilt}`)
.then(() => fsp.mkdir(docsBuilt))
.then(metadata)
.then(propData => {
let pagesGenerators = Root.getPages().map( page => generateHTML(page, propData));
return Promise.all(pagesGenerators.concat([
exec(`webpack --config webpack.docs.js ${dev ? '' : '-p '}--bail`),
copy(license, docsBuilt),
copy(readmeSrc, readmeDest)
]));
})
.then(() => console.log('Built: '.cyan + 'docs'.green + (dev ? ' [DEV]'.grey : '')));
}
|
actor-apps/app-web/src/app/components/ActivitySection.react.js
|
shaunstanislaus/actor-platform
|
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import ActivityActionCreators from 'actions/ActivityActionCreators';
import ActorAppConstants from 'constants/ActorAppConstants';
import ActivityStore from 'stores/ActivityStore';
import UserProfile from 'components/activity/UserProfile.react';
import GroupProfile from 'components/activity/GroupProfile.react';
import classNames from 'classnames';
const ActivityTypes = ActorAppConstants.ActivityTypes;
var getStateFromStores = function() {
return {
activity: ActivityStore.getActivity()
};
};
class ActivitySection extends React.Component {
constructor() {
super();
this.setActivityClosed = this.setActivityClosed.bind(this);
this.onChange = this.onChange.bind(this);
this.state = getStateFromStores();
}
componentDidMount() {
ActivityStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
ActivityStore.removeChangeListener(this.onChange);
}
render() {
let activity = this.state.activity;
if (activity !== null) {
let activityTitle;
let activityBody;
let activityClassName = classNames('activity', {
'activity--shown': true
});
switch (activity.type) {
case ActivityTypes.USER_PROFILE:
activityTitle = 'User information';
activityBody = <UserProfile user={activity.user}/>;
break;
case ActivityTypes.GROUP_PROFILE:
activityTitle = 'Group information';
activityBody = <GroupProfile group={activity.group}/>;
break;
default:
}
return (
<section className={activityClassName}>
<ActivitySection.Header close={this.setActivityClosed} title={activityTitle}/>
{activityBody}
</section>
);
} else {
return (null);
}
}
setActivityClosed() {
ActivityActionCreators.hide();
}
onChange() {
this.setState(getStateFromStores());
}
}
ActivitySection.Header = React.createClass({
propTypes: {
close: React.PropTypes.func,
title: React.PropTypes.string
},
mixins: [PureRenderMixin],
render() {
let title = this.props.title;
let close = this.props.close;
var headerTitle;
if (typeof title !== 'undefined') {
headerTitle = <span className="activity__header__title">{title}</span>;
}
return (
<header className="activity__header toolbar">
<a className="activity__header__close material-icons" onClick={close}>clear</a>
{headerTitle}
</header>
);
}
});
export default ActivitySection;
|
src/components/gradients/h-gradient.js
|
mapbox/react-colorpickr
|
import React from 'react';
import PropTypes from 'prop-types';
import themeable from 'react-themeable';
import { autokey } from '../../autokey';
function HGradient({ theme, active, hueBackground }) {
const themer = autokey(themeable(theme));
if (!active) return <noscript />;
return (
<>
<div {...themer('gradient')} style={{ backgroundColor: hueBackground }} />
<div {...themer('gradient', 'gradientHue')} />
</>
);
}
HGradient.propTypes = {
theme: PropTypes.object.isRequired,
active: PropTypes.bool.isRequired,
hueBackground: PropTypes.string.isRequired
};
export { HGradient };
|
packages/react/components/fab-buttons.js
|
AdrianV/Framework7
|
import React from 'react';
import Utils from '../utils/utils';
import Mixins from '../utils/mixins';
import __reactComponentSlots from '../runtime-helpers/react-component-slots.js';
import __reactComponentSetProps from '../runtime-helpers/react-component-set-props.js';
class F7FabButtons extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const props = this.props;
const {
className,
id,
style,
position
} = props;
const classes = Utils.classNames(className, 'fab-buttons', `fab-buttons-${position}`, Mixins.colorClasses(props));
return React.createElement('div', {
id: id,
style: style,
className: classes
}, this.slots['default']);
}
get slots() {
return __reactComponentSlots(this.props);
}
}
__reactComponentSetProps(F7FabButtons, Object.assign({
id: [String, Number],
position: {
type: String,
default: 'top'
}
}, Mixins.colorProps));
F7FabButtons.displayName = 'f7-fab-buttons';
export default F7FabButtons;
|
src/react/connect.js
|
krasimir/stent
|
import React from 'react';
import connect from '../helpers/connect';
export default function(Component) {
const withFunc = (...names) => {
const mapFunc = (done, once, silent) => {
const mapping = once ? "mapOnce" : silent ? "mapSilent" : "map";
return class StentConnect extends React.Component {
constructor(props) {
super(props);
this.initialStateHasBeenSet = false;
this.state = {};
this.disconnect = connect({
meta: { component: Component.name }
})
.with(...names)
[mapping]((...deps) => {
const nextState = done ? done(...deps) : {};
if (
this.initialStateHasBeenSet === false &&
mapping !== 'mapSilent'
) {
this.state = nextState;
this.initialStateHasBeenSet = true;
return;
}
this.setState(function () {
return nextState;
});
});
}
componentWillUnmount() {
if (this.disconnect) {
this.disconnect();
}
}
render() {
return <Component {...this.state} {...this.props} />;
}
}
}
return {
'map': mapFunc,
'mapOnce': done => mapFunc(done, true),
'mapSilent': done => mapFunc(done, false, true),
}
}
return { 'with': withFunc };
}
|
site/demos/ecommerce/src/index.js
|
appbaseio/reactivesearch
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('app'));
|
assets/js/components/SignInModal.js
|
basarevych/webfm
|
import React from 'react';
import PropTypes from 'prop-types';
import { Map } from 'immutable';
import { Button, Modal, ModalHeader, ModalBody, ModalFooter } from 'reactstrap';
import { Form, FormGroup, Label, Col, Input } from 'reactstrap';
import RequiredFieldLabel from './RequiredFieldLabel';
import FormMessages from './FormMessages';
import FieldErrors from './FieldErrors';
class SignInModal extends React.Component {
static propTypes = {
isOpen: PropTypes.bool.isRequired,
isLocked: PropTypes.bool.isRequired,
values: PropTypes.instanceOf(Map).isRequired,
messages: PropTypes.instanceOf(Map).isRequired,
errors: PropTypes.instanceOf(Map).isRequired,
onToggle: PropTypes.func.isRequired,
onInput: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
isOpen: props.isOpen,
isLocked: props.isLocked,
ignoreBlur: true,
nextFocus: null,
};
this.loginInput = React.createRef();
this.passwordInput = React.createRef();
this.handleInput = this.handleInput.bind(this);
this.handleKeyPress = this.handleKeyPress.bind(this);
this.handleFocus = this.handleFocus.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
}
static getDerivedStateFromProps(nextProps, prevState) {
let state = {};
if (nextProps.isOpen !== prevState.isOpen)
state.isOpen = nextProps.isOpen;
if (nextProps.isLocked !== prevState.isLocked)
state.isLocked = nextProps.isLocked;
if (state.isOpen === true) {
state.nextFocus = 'login';
} else if (state.isLocked === false) {
if (nextProps.errors.has('login'))
state.nextFocus = 'login';
else if (nextProps.errors.has('password'))
state.nextFocus = 'password';
}
return _.keys(state).length ? state : null;
}
handleInput(event) {
if (this.props.isLocked)
return;
this.props.onInput({ [event.target.name]: event.target.value });
}
handleKeyPress(event) {
if (this.props.isLocked || event.charCode !== 13) // enter
return;
switch (event.target.name) {
case 'login':
if (this.passwordInput.current)
setTimeout(() => this.passwordInput.current.focus(), 0);
break;
case 'password':
this.handleSubmit();
break;
}
}
handleFocus() {
if (this.props.isLocked)
return;
this.setState({ ignoreBlur: false });
}
handleBlur(event) {
if (this.props.isLocked || this.state.ignoreBlur)
return;
let submittedAt = Date.now();
let field = event.target.name;
setTimeout(
() => {
if (this.props.isLocked || this.state.ignoreBlur)
return;
this.props.onSubmit(submittedAt, field);
},
250
);
}
handleSubmit() {
if (this.props.isLocked)
return;
this.setState({ ignoreBlur: true });
this.props.onSubmit(Date.now());
}
componentDidUpdate() {
if (this.state.nextFocus) {
let field = this.state.nextFocus;
this.setState({ nextFocus: null }, () => {
switch (field) {
case 'login':
if (this.loginInput.current)
setTimeout(() => this.loginInput.current.focus(), 0);
break;
case 'password':
if (this.passwordInput.current)
setTimeout(() => this.passwordInput.current.focus(), 0);
break;
}
});
}
}
render() {
return (
<Modal
isOpen={this.props.isOpen}
toggle={this.props.onToggle}
backdrop="static"
fade
centered
>
<ModalHeader toggle={this.props.onToggle}>{__('sign_in_title')}</ModalHeader>
<ModalBody>
<Form>
<FormMessages messages={this.props.messages} />
<FormGroup row>
<Label for="signInLogin" sm={4} className="text-sm-right">
{__('login_label')}
<RequiredFieldLabel />
</Label>
<Col sm={8}>
<Input
type="text"
name="login"
id="signInLogin"
disabled={this.props.isLocked}
invalid={this.props.errors.has('login')}
value={this.props.values.get('login')}
onChange={this.handleInput}
onKeyPress={this.handleKeyPress}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
innerRef={this.loginInput}
/>
<FieldErrors errors={this.props.errors.get('login')} />
</Col>
</FormGroup>
<FormGroup row>
<Label for="signInPassword" sm={4} className="text-sm-right">
{__('password_label')}
<RequiredFieldLabel />
</Label>
<Col sm={8}>
<Input
type="password"
name="password"
id="signInPassword"
disabled={this.props.isLocked}
invalid={this.props.errors.has('password')}
value={this.props.values.get('password')}
onChange={this.handleInput}
onKeyPress={this.handleKeyPress}
onFocus={this.handleFocus}
onBlur={this.handleBlur}
innerRef={this.passwordInput}
/>
<FieldErrors errors={this.props.errors.get('password')} />
</Col>
</FormGroup>
</Form>
</ModalBody>
<ModalFooter>
<Button color="secondary" disabled={this.props.isLocked} onClick={this.props.onToggle}>
{__('cancel_button')}
</Button>
<Button color="primary" disabled={this.props.isLocked} onClick={this.handleSubmit}>
{__('submit_button')}
</Button>
</ModalFooter>
</Modal>
);
}
}
export default SignInModal;
|
src/core/UserProfileStructure/ProfileImage/component.js
|
dlennox24/ricro-app-template
|
import { Collapse } from '@material-ui/core';
import Button from '@material-ui/core/Button';
import withStyles from '@material-ui/core/styles/withStyles';
import Typography from '@material-ui/core/Typography';
import classNames from 'classnames';
import _ from 'lodash';
import IconPencil from 'mdi-material-ui/Pencil';
import PropTypes from 'prop-types';
import React from 'react';
import userDefaultProfileImg from '../../../assets/img/default-profile.svg';
import { userShape } from '../../../assets/propTypes';
import FileDropzone from '../../../component/FileDropzone';
import FileDropzoneList from '../../../component/FileDropzoneList';
import styles from './styles';
class ProfileImage extends React.Component {
state = {
dropzoneFunc: {},
files: [],
};
handleUpdateFiles = files => {
this.setState({ files });
};
handleLoadDropzoneFunc = funcs => {
this.setState({ dropzoneFunc: funcs });
};
handleUploadSuccess = apiResp => {
this.props.handleReduxUpdateProfileImage(apiResp.data.result.newPath);
};
createHelpText = () => {
const { classes } = this.props;
const { dropzoneFunc, files } = this.state;
return (
<React.Fragment>
{!_.isEmpty(dropzoneFunc) && (
<Collapse className={classes.fileListContainer} in={files.length > 0}>
<FileDropzoneList files={files} onRemoveFile={dropzoneFunc.handleRemove} />
<Button
variant="contained"
color="primary"
fullWidth
onClick={dropzoneFunc.handleUpload}
>
Update Profile Image
</Button>
</Collapse>
)}
<Collapse in={files.length < 1}>
<Typography className={classes.uploadInstructions} variant="caption">
Click the image above or drag and drop an image file to change the profile image. Images
must be square and of the type <code>.jpg</code>.
</Typography>
</Collapse>
</React.Fragment>
);
};
render() {
const { api, classes, loggedInUserId, user } = this.props;
const { files } = this.state;
const image = (
<img
className={classes.profileImage}
src={user.profileImage ? api.host + user.profileImage : userDefaultProfileImg}
alt={user.displayName}
/>
);
return user.csuId !== loggedInUserId ? (
image
) : (
<React.Fragment>
<FileDropzone
axiosData={{ csuId: user.csuId }}
axiosPath={api.editProfileImagePath}
dragRootClassName={classes.dragRoot}
dropzoneProps={{
accept: 'image/jpeg',
multiple: false,
onClick: null,
}}
maxFiles={1}
onFilesChange={this.handleUpdateFiles}
onLoadFunc={this.handleLoadDropzoneFunc}
onUploadSuccessFunc={this.handleUploadSuccess}
>
{() => (
<div className={classNames(files.length < 1 && classes.editImageContainer)}>
{files.length < 1 && (
<div className={classes.profileImageEdit}>
<Typography color="inherit" component="div" className={classes.dragIconContainer}>
<IconPencil />
</Typography>
<Typography color="inherit" component="div" variant="h6">
Edit Image
</Typography>
</div>
)}
<div className={classes.profileImageCover}>{image}</div>
</div>
)}
</FileDropzone>
{this.createHelpText()}
</React.Fragment>
);
}
}
ProfileImage.propTypes = {
api: PropTypes.object.isRequired, // redux state
classes: PropTypes.object.isRequired, // MUI withStyles()
handleReduxUpdateProfileImage: PropTypes.func.isRequired, // redux dispatch
loggedInUserId: PropTypes.number.isRequired, // redux state
user: userShape.isRequired,
};
export default withStyles(styles)(ProfileImage);
|
src/svg-icons/image/crop-3-2.js
|
kasra-co/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCrop32 = (props) => (
<SvgIcon {...props}>
<path d="M19 4H5c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 14H5V6h14v12z"/>
</SvgIcon>
);
ImageCrop32 = pure(ImageCrop32);
ImageCrop32.displayName = 'ImageCrop32';
ImageCrop32.muiName = 'SvgIcon';
export default ImageCrop32;
|
client/src/components/Draftail/Tooltip/Tooltip.js
|
jnns/wagtail
|
import PropTypes from 'prop-types';
import React from 'react';
const TOP = 'top';
const LEFT = 'left';
const TOP_LEFT = 'top-left';
const getTooltipStyles = (target, direction) => {
const top = window.pageYOffset + target.top;
const left = window.pageXOffset + target.left;
switch (direction) {
case TOP:
return {
top: top + target.height,
left: left + target.width / 2,
};
case LEFT:
return {
top: top + target.height / 2,
left: left + target.width,
};
case TOP_LEFT:
default:
return {
top: top + target.height,
left: left,
};
}
};
/**
* A tooltip, with arbitrary content.
*/
const Tooltip = ({ target, children, direction }) => (
<div
style={getTooltipStyles(target, direction)}
className={`Tooltip Tooltip--${direction}`}
role="tooltip"
>
{children}
</div>
);
Tooltip.propTypes = {
target: PropTypes.shape({
top: PropTypes.number.isRequired,
left: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
}).isRequired,
direction: PropTypes.oneOf([TOP, LEFT, TOP_LEFT]).isRequired,
children: PropTypes.node.isRequired,
};
export default Tooltip;
|
src/js/components/icons/base/Detach.js
|
odedre/grommet-final
|
/**
* @description Detach SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M4,4 L20,20 M22,12 C22,12 16.7200572,17.2799437 16.7200572,17.2799437 M15,19 C15,19 13.7932491,20.2067517 13.0000004,21.0000004 C6.99999996,27.0000004 -2.00000007,18.0000004 3.99999994,12.0000004 C4.88551518,11.1144851 6,10 6,10 M8,8 C8,8 10.1615592,5.83844087 13,3.00000008 C17,-0.999999955 23,4.99999994 19,9.00000005 C16.9873313,11.0126688 14,14 14,14 M12,16 C12,16 10.6478339,17.3521667 9.99999995,18.0000004 C7.99999952,20 5,17 6.99999995,15.0000004 C7.50049504,14.4995054 9,13 9,13 M11,11 C10.7388543,11.261146 16,6 16,6"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-detach`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'detach');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M4,4 L20,20 M22,12 C22,12 16.7200572,17.2799437 16.7200572,17.2799437 M15,19 C15,19 13.7932491,20.2067517 13.0000004,21.0000004 C6.99999996,27.0000004 -2.00000007,18.0000004 3.99999994,12.0000004 C4.88551518,11.1144851 6,10 6,10 M8,8 C8,8 10.1615592,5.83844087 13,3.00000008 C17,-0.999999955 23,4.99999994 19,9.00000005 C16.9873313,11.0126688 14,14 14,14 M12,16 C12,16 10.6478339,17.3521667 9.99999995,18.0000004 C7.99999952,20 5,17 6.99999995,15.0000004 C7.50049504,14.4995054 9,13 9,13 M11,11 C10.7388543,11.261146 16,6 16,6"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Detach';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
app/containers/Root.js
|
pamler/electron-mario
|
// @flow
import React from 'react';
import { Provider } from 'react-redux';
import { ConnectedRouter } from 'react-router-redux';
import Routes from '../routes';
type RootType = {
store: {},
history: {}
};
export default function Root({ store, history }: RootType) {
return (
<Provider store={store}>
<ConnectedRouter history={history}>
<Routes />
</ConnectedRouter>
</Provider>
);
}
|
src/components/repository-section-title.component.js
|
Antoine38660/git-point
|
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { StateBadge } from 'components';
import { colors, fonts } from 'config';
type Props = {
text: string,
openCount: number,
closedCount: number,
loading: boolean,
};
const styles = StyleSheet.create({
title: {
flexDirection: 'row',
},
titleText: {
color: colors.black,
...fonts.fontPrimaryBold,
},
badgeContainer: {
flexDirection: 'row',
marginTop: -7,
},
badge: {
marginLeft: 10,
},
});
export const RepositorySectionTitle = ({
text,
loading,
openCount,
closedCount,
}: Props) => {
return (
<View style={styles.title}>
<Text style={styles.titleText}>{text}</Text>
{!loading && (
<View style={styles.badgeContainer}>
<StateBadge type="open" text={openCount} style={styles.badge} />
<StateBadge type="closed" text={closedCount} style={styles.badge} />
</View>
)}
</View>
);
};
|
app/containers/CodingPage/index.js
|
andresol/homepage
|
import React from 'react';
import Nav from 'components/Nav';
import StravaSection from 'components/Strava/Section';
const Coding = () => (
<div className="page-wrap">
<Nav index={3} />
<section id="main">
<StravaSection note={'Coding'} action={false} />
<section id="athlets">
<div>
<p>Vær info</p>
</div>
</section>
</section>
</div>
);
export default Coding;
|
modules/RouteContext.js
|
brownbathrobe/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
|
src/components/EditPaymentMethods.js
|
OpenCollective/frontend
|
import React from 'react';
import PropTypes from 'prop-types';
import { Button } from 'react-bootstrap';
import { defineMessages } from 'react-intl';
import withIntl from '../lib/withIntl';
import EditPaymentMethod from './EditPaymentMethod';
class EditPaymentMethods extends React.Component {
static propTypes = {
paymentMethods: PropTypes.arrayOf(PropTypes.object).isRequired,
collective: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
constructor(props) {
super(props);
this.renderPaymentMethod = this.renderPaymentMethod.bind(this);
this.addPaymentMethod = this.addPaymentMethod.bind(this);
this.removePaymentMethod = this.removePaymentMethod.bind(this);
this.editPaymentMethod = this.editPaymentMethod.bind(this);
this.onChange = props.onChange.bind(this);
this.defaultType = this.props.defaultType || 'TICKET';
this.messages = defineMessages({
'paymentMethods.add': {
id: 'paymentMethods.add',
defaultMessage: 'add another payment method',
},
'paymentMethods.remove': {
id: 'paymentMethods.remove',
defaultMessage: 'remove payment method',
},
});
}
/** Returns payment methods from props or a list with an empty entry if empty */
loadPaymentMethodsFromProps(props) {
return props.paymentMethods.length === 0 ? [{}] : props.paymentMethods;
}
editPaymentMethod(paymentMethodId, paymentMethod) {
const paymentMethods = [...this.props.paymentMethods];
const index = !paymentMethodId
? paymentMethods.findIndex(pm => !pm.id)
: paymentMethods.findIndex(pm => pm.id === paymentMethodId);
if (paymentMethod === null) {
return this.removePaymentMethod(index);
}
paymentMethods[index] = { ...paymentMethods[index], ...paymentMethod };
this.onChange({ paymentMethods });
}
addPaymentMethod(paymentMethod) {
const newPm = paymentMethod || {};
this.onChange({ paymentMethods: [...this.props.paymentMethods, newPm] });
}
removePaymentMethod(index) {
let paymentMethods = this.props.paymentMethods;
if (index < 0 || index > paymentMethods.length) return;
paymentMethods = [...paymentMethods.slice(0, index), ...paymentMethods.slice(index + 1)];
this.onChange({ paymentMethods });
}
renderPaymentMethod(paymentMethod) {
const { collective } = this.props;
const keyId = paymentMethod.id || 'new';
const hasMonthlyLimitPerMember = collective.type === 'ORGANIZATION' && paymentMethod.type !== 'prepaid';
return (
<div className="paymentMethod" key={`paymentMethod-${keyId}`}>
<EditPaymentMethod
paymentMethod={paymentMethod}
onChange={pm => this.editPaymentMethod(paymentMethod.id, pm)}
editMode={paymentMethod.id ? false : true}
monthlyLimitPerMember={hasMonthlyLimitPerMember}
currency={collective.currency}
slug={collective.slug}
/>
</div>
);
}
render() {
const { intl, paymentMethods = [] } = this.props;
const hasNewPaymentMethod = Boolean(this.props.paymentMethods.find(pm => !pm.id));
return (
<div className="EditPaymentMethods">
<style jsx>
{`
:global(.paymentMethodActions) {
text-align: right;
font-size: 1.3rem;
}
:global(.field) {
margin: 1rem;
}
.editPaymentMethodsActions {
text-align: right;
}
:global(.paymentMethod) {
margin: 3rem 0;
}
`}
</style>
<div className="paymentMethods">{paymentMethods.map(this.renderPaymentMethod)}</div>
{!hasNewPaymentMethod && (
<div className="editPaymentMethodsActions">
<Button bsStyle="primary" onClick={() => this.addPaymentMethod()}>
{intl.formatMessage(this.messages['paymentMethods.add'])}
</Button>
</div>
)}
</div>
);
}
}
export default withIntl(EditPaymentMethods);
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/TemplateInterpolation.js
|
johnslay/create-react-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load(name) {
return [
{ id: 1, name: `${name}1` },
{ id: 2, name: `${name}2` },
{ id: 3, name: `${name}3` },
{ id: 4, name: `${name}4` },
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load('user_');
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-template-interpolation">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
Libraries/Image/Image.ios.js
|
cdlewis/react-native
|
/**
* 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.
*
* @providesModule Image
* @flow
*/
'use strict';
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ImageResizeMode = require('ImageResizeMode');
const ImageSourcePropType = require('ImageSourcePropType');
const ImageStylePropTypes = require('ImageStylePropTypes');
const NativeMethodsMixin = require('NativeMethodsMixin');
const NativeModules = require('NativeModules');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const createReactClass = require('create-react-class');
const flattenStyle = require('flattenStyle');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const ImageViewManager = NativeModules.ImageViewManager;
/**
* A React component for displaying different types of images,
* including network images, static resources, temporary local images, and
* images from local disk, such as the camera roll.
*
* This example shows fetching and displaying an image from local storage
* as well as one from network and even from data provided in the `'data:'` uri scheme.
*
* > Note that for network and data images, you will need to manually specify the dimensions of your image!
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image } from 'react-native';
*
* export default class DisplayAnImage extends Component {
* render() {
* return (
* <View>
* <Image
* source={require('./img/favicon.png')}
* />
* <Image
* style={{width: 50, height: 50}}
* source={{uri: 'https://facebook.github.io/react-native/img/favicon.png'}}
* />
* <Image
* style={{width: 66, height: 58}}
* source={{uri: 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAADMAAAAzCAYAAAA6oTAqAAAAEXRFWHRTb2Z0d2FyZQBwbmdjcnVzaEB1SfMAAABQSURBVGje7dSxCQBACARB+2/ab8BEeQNhFi6WSYzYLYudDQYGBgYGBgYGBgYGBgYGBgZmcvDqYGBgmhivGQYGBgYGBgYGBgYGBgYGBgbmQw+P/eMrC5UTVAAAAABJRU5ErkJggg=='}}
* />
* </View>
* );
* }
* }
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);
* ```
*
* You can also add `style` to an image:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image, StyleSheet } from 'react-native';
*
* const styles = StyleSheet.create({
* stretch: {
* width: 50,
* height: 200
* }
* });
*
* export default class DisplayAnImageWithStyle extends Component {
* render() {
* return (
* <View>
* <Image
* style={styles.stretch}
* source={require('./img/favicon.png')}
* />
* </View>
* );
* }
* }
*
* // skip these lines if using Create React Native App
* AppRegistry.registerComponent(
* 'DisplayAnImageWithStyle',
* () => DisplayAnImageWithStyle
* );
* ```
*
* ### GIF and WebP support on Android
*
* When building your own native code, GIF and WebP are not supported by default on Android.
*
* You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app.
*
* ```
* dependencies {
* // If your app supports Android versions before Ice Cream Sandwich (API level 14)
* compile 'com.facebook.fresco:animated-base-support:1.3.0'
*
* // For animated GIF support
* compile 'com.facebook.fresco:animated-gif:1.3.0'
*
* // For WebP support, including animated WebP
* compile 'com.facebook.fresco:animated-webp:1.3.0'
* compile 'com.facebook.fresco:webpsupport:1.3.0'
*
* // For WebP support, without animations
* compile 'com.facebook.fresco:webpsupport:1.3.0'
* }
* ```
*
* Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` :
* ```
* -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl {
* public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier);
* }
* ```
*
*/
const Image = createReactClass({
displayName: 'Image',
propTypes: {
/**
* > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the
* > `resizeMode` style property on `Image` components. The values are `contain`, `cover`,
* > `stretch`, `center`, `repeat`.
*/
style: StyleSheetPropType(ImageStylePropTypes),
/**
* The image source (either a remote URL or a local file resource).
*
* This prop can also contain several remote URLs, specified together with
* their width and height and potentially with scale/other URI arguments.
* The native side will then choose the best `uri` to display based on the
* measured size of the image container. A `cache` property can be added to
* control how networked request interacts with the local cache.
*
* The currently supported formats are `png`, `jpg`, `jpeg`, `bmp`, `gif`,
* `webp` (Android only), `psd` (iOS only).
*/
source: ImageSourcePropType,
/**
* A static image to display while loading the image source.
*
* - `uri` - a string representing the resource identifier for the image, which
* should be either a local file path or the name of a static image resource
* (which should be wrapped in the `require('./path/to/image.png')` function).
* - `width`, `height` - can be specified if known at build time, in which case
* these will be used to set the default `<Image/>` component dimensions.
* - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if
* unspecified, meaning that one image pixel equates to one display point / DIP.
* - `number` - Opaque type returned by something like `require('./image.jpg')`.
*
* @platform ios
*/
defaultSource: PropTypes.oneOfType([
// TODO: Tooling to support documenting these directly and having them display in the docs.
PropTypes.shape({
uri: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
scale: PropTypes.number,
}),
PropTypes.number,
]),
/**
* When true, indicates the image is an accessibility element.
* @platform ios
*/
accessible: PropTypes.bool,
/**
* The text that's read by the screen reader when the user interacts with
* the image.
* @platform ios
*/
accessibilityLabel: PropTypes.node,
/**
* blurRadius: the blur radius of the blur filter added to the image
*/
blurRadius: PropTypes.number,
/**
* When the image is resized, the corners of the size specified
* by `capInsets` will stay a fixed size, but the center content and borders
* of the image will be stretched. This is useful for creating resizable
* rounded buttons, shadows, and other resizable assets. More info in the
* [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).
*
* @platform ios
*/
capInsets: EdgeInsetsPropType,
/**
* The mechanism that should be used to resize the image when the image's dimensions
* differ from the image view's dimensions. Defaults to `auto`.
*
* - `auto`: Use heuristics to pick between `resize` and `scale`.
*
* - `resize`: A software operation which changes the encoded image in memory before it
* gets decoded. This should be used instead of `scale` when the image is much larger
* than the view.
*
* - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is
* faster (usually hardware accelerated) and produces higher quality images. This
* should be used if the image is smaller than the view. It should also be used if the
* image is slightly bigger than the view.
*
* More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html.
*
* @platform android
*/
resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']),
/**
* Determines how to resize the image when the frame doesn't match the raw
* image dimensions.
*
* - `cover`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal
* to or larger than the corresponding dimension of the view (minus padding).
*
* - `contain`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal to
* or less than the corresponding dimension of the view (minus padding).
*
* - `stretch`: Scale width and height independently, This may change the
* aspect ratio of the src.
*
* - `repeat`: Repeat the image to cover the frame of the view. The
* image will keep it's size and aspect ratio. (iOS only)
*/
resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']),
/**
* A unique identifier for this element to be used in UI Automation
* testing scripts.
*/
testID: PropTypes.string,
/**
* Invoked on mount and layout changes with
* `{nativeEvent: {layout: {x, y, width, height}}}`.
*/
onLayout: PropTypes.func,
/**
* Invoked on load start.
*
* e.g., `onLoadStart={(e) => this.setState({loading: true})}`
*/
onLoadStart: PropTypes.func,
/**
* Invoked on download progress with `{nativeEvent: {loaded, total}}`.
* @platform ios
*/
onProgress: PropTypes.func,
/**
* Invoked on load error with `{nativeEvent: {error}}`.
*/
onError: PropTypes.func,
/**
* Invoked when a partial load of the image is complete. The definition of
* what constitutes a "partial load" is loader specific though this is meant
* for progressive JPEG loads.
* @platform ios
*/
onPartialLoad: PropTypes.func,
/**
* Invoked when load completes successfully.
*/
onLoad: PropTypes.func,
/**
* Invoked when load either succeeds or fails.
*/
onLoadEnd: PropTypes.func,
},
statics: {
resizeMode: ImageResizeMode,
/**
* Retrieve the width and height (in pixels) of an image prior to displaying it.
* This method can fail if the image cannot be found, or fails to download.
*
* In order to retrieve the image dimensions, the image may first need to be
* loaded or downloaded, after which it will be cached. This means that in
* principle you could use this method to preload images, however it is not
* optimized for that purpose, and may in future be implemented in a way that
* does not fully load/download the image data. A proper, supported way to
* preload images will be provided as a separate API.
*
* Does not work for static image resources.
*
* @param uri The location of the image.
* @param success The function that will be called if the image was successfully found and width
* and height retrieved.
* @param failure The function that will be called if there was an error, such as failing to
* to retrieve the image.
*
* @returns void
*
* @platform ios
*/
getSize: function(
uri: string,
success: (width: number, height: number) => void,
failure?: (error: any) => void,
) {
ImageViewManager.getSize(uri, success, failure || function() {
console.warn('Failed to get size for image: ' + uri);
});
},
/**
* Prefetches a remote image for later use by downloading it to the disk
* cache
*
* @param url The remote location of the image.
*
* @return The prefetched image.
*/
prefetch(url: string) {
return ImageViewManager.prefetchImage(url);
},
/**
* Resolves an asset reference into an object which has the properties `uri`, `width`,
* and `height`. The input may either be a number (opaque type returned by
* require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' }
*/
resolveAssetSource: resolveAssetSource,
},
mixins: [NativeMethodsMixin],
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
viewConfig: {
uiViewClassName: 'UIView',
validAttributes: ReactNativeViewAttributes.UIView
},
render: function() {
const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };
let sources;
let style;
if (Array.isArray(source)) {
style = flattenStyle([styles.base, this.props.style]) || {};
sources = source;
} else {
const {width, height, uri} = source;
style = flattenStyle([{width, height}, styles.base, this.props.style]) || {};
sources = [source];
if (uri === '') {
console.warn('source.uri should not be an empty string');
}
}
const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108
const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108
if (this.props.src) {
console.warn('The <Image> component requires a `source` property rather than `src`.');
}
if (this.props.children) {
throw new Error('The <Image> component cannot contain children. If you want to render content on top of the image, consider using aboslute positioning.');
}
return (
<RCTImageView
{...this.props}
style={style}
resizeMode={resizeMode}
tintColor={tintColor}
source={sources}
/>
);
},
});
const styles = StyleSheet.create({
base: {
overflow: 'hidden',
},
});
const RCTImageView = requireNativeComponent('RCTImageView', Image);
module.exports = Image;
|
client/src/components/instructor/InstructorCourseRow.js
|
yegor-sytnyk/contoso-express
|
import React from 'react';
const InstructorCourseRow = (props) => {
let course = props.course;
let activeClass = props.selectedCourseId === course.id ? 'success' : '';
return (
<tr className={activeClass}>
<td className="tools">
<a href="#" onClick={props.onSelectClick}><i className="fa fa-hand-o-up fa-lg"></i></a>
</td>
<td>{course.number}</td>
<td>{course.title}</td>
<td>{course.department.name}</td>
</tr>
);
};
InstructorCourseRow.propTypes = {
course: React.PropTypes.object.isRequired,
selectedCourseId: React.PropTypes.number.isRequired,
onSelectClick: React.PropTypes.func.isRequired
};
export default InstructorCourseRow;
|
fields/types/number/NumberColumn.js
|
ONode/keystone
|
import React from 'react';
import numeral from 'numeral';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var NumberColumn = React.createClass({
displayName: 'NumberColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || isNaN(value)) return null;
const formattedValue = (this.props.col.path === 'money') ? numeral(value).format('$0,0.00') : value;
return formattedValue;
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = NumberColumn;
|
examples/shopping-cart/test/components/Product.spec.js
|
chentsulin/redux
|
import expect from 'expect'
import React from 'react'
import { shallow } from 'enzyme'
import Product from '../../components/Product'
function setup(props) {
const component = shallow(
<Product {...props} />
)
return {
component: component
}
}
describe('Product component', () => {
it('should render title and price', () => {
const { component } = setup({ title: 'Test Product', price: 9.99 })
expect(component.text()).toMatch(/^ Test Product - \$9.99 {2}$/)
})
describe('when given quantity', () => {
it('should render title, price, and quantity', () => {
const { component } = setup({ title: 'Test Product', price: 9.99, quantity: 6 })
expect(component.text()).toMatch(/^ Test Product - \$9.99 x 6 $/)
})
})
})
|
src/routes/not-found/NotFound.js
|
murthymuddu/murthy-umg
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './NotFound.css';
class NotFound extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>
{this.props.title}
</h1>
<p>Sorry, the page you were trying to view does not exist.</p>
</div>
</div>
);
}
}
export default withStyles(s)(NotFound);
|
ButtonExample/src/containers/DisabledButtons.js
|
jacklam718/react-native-button-component
|
import React, { Component } from 'react';
import { View, ScrollView, StyleSheet } from 'react-native';
import ButtonComponent from 'react-native-button-component';
import GroupContainer from '../components/GroupContainer';
export default class DisabledButtons extends Component {
render() {
return (
<ScrollView style={styles.scrollView}>
<View style={styles.container}>
<GroupContainer
groupTitle="Button"
>
<ButtonComponent
disabled
backgroundColors={['#212122', '#414141']}
text={'Button'.toUpperCase()}
onPress={() => {
}}
/>
</GroupContainer>
<GroupContainer
groupTitle="Icon Button"
>
<ButtonComponent
disabled
image={require('../img/settings.png')}
text={'Icon Buttons'.toUpperCase()}
onPress={() => {
}}
/>
</GroupContainer>
</View>
</ScrollView>
);
}
}
const styles = StyleSheet.create({
scrollView: {
flex: 1,
backgroundColor: '#ffffff',
},
container: {
marginTop: 64,
alignItems: 'center',
marginLeft: 10,
marginRight: 10,
},
});
|
examples/todomvc/index.js
|
cyongen/redux
|
import React from 'react';
import App from './containers/App';
import 'todomvc-app-css/index.css';
React.render(
<App />,
document.getElementById('root')
);
|
inventapp/src/App/App.js
|
ladanv/learn-react-js
|
import React, { Component } from 'react';
import Header from './Header';
import SideNav from './SideNav';
import styles from './App.scss';
const App = ({ children }) => (
<div className="App">
<Header />
<SideNav />
<div className={styles.main}>
{children}
</div>
</div>
);
export default App;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.