path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/index.js | ldstudio-ca/react-pdfjs-mobile | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
export default App;
// let root = document.getElementById('root');
// ReactDOM.render(<App url="../how-to-setup.pdf"
// onClose={ () => {
// ReactDOM.unmountComponentAtNode(root);
// } } />, root);
|
src/Parser/Hunter/Survival/Modules/Talents/SteelTrap.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer from 'Parser/Core/Analyzer';
import SpellIcon from 'common/SpellIcon';
import Combatants from 'Parser/Core/Modules/Combatants';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import SpellLink from 'common/SpellLink';
import ItemDamageDone from 'Main/ItemDamageDone';
class SteelTrap extends Analyzer {
static dependencies = {
combatants: Combatants,
spellUsable: SpellUsable,
};
bonusDamage = 0;
casts = 0;
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.STEEL_TRAP_TALENT.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.STEEL_TRAP_TALENT.id) {
return;
}
this.casts++;
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.STEEL_TRAP_DEBUFF.id) {
return;
}
if (this.casts === 0) {
this.casts++;
this.spellUsable.beginCooldown(SPELLS.STEEL_TRAP_TALENT.id);
}
this.bonusDamage += event.amount + (event.absorbed || 0);
}
subStatistic() {
return (
<div className="flex">
<div className="flex-main">
<SpellLink id={SPELLS.STEEL_TRAP_TALENT.id}>
<SpellIcon id={SPELLS.STEEL_TRAP_TALENT.id} noLink /> Steel Trap
</SpellLink>
</div>
<div className="flex-sub text-right">
<ItemDamageDone amount={this.bonusDamage} />
</div>
</div>
);
}
}
export default SteelTrap;
|
Realization/frontend/czechidm-core/src/components/advanced/Filter/FilterToogleButton.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import AbstractContextComponent from '../../basic/AbstractContextComponent/AbstractContextComponent';
import * as Basic from '../../basic';
import * as Domain from '../../../domain';
import { DataManager, IdentityManager } from '../../../redux';
//
const dataManager = new DataManager();
const identityManager = new IdentityManager();
/**
* Button for closable filter mainly for advanced table.
*
* @author Radek Tomiška
*/
class FilterToogleButton extends AbstractContextComponent {
constructor(props, context) {
super(props, context);
//
this.state = {
filterOpened: this.props.filterOpened
};
}
_filterOpen(opened) {
const { filterOpen, uiKey, userContext } = this.props;
//
this.setState({
filterOpened: opened
}, () => {
if (uiKey) {
if (opened) {
this.context.store.dispatch(dataManager.expandFilter(uiKey));
if (userContext && userContext.username) {
this.context.store.dispatch(identityManager.expandPanel(userContext.username, uiKey));
}
} else {
this.context.store.dispatch(dataManager.collapseFilter(uiKey));
if (userContext && userContext.username) {
this.context.store.dispatch(identityManager.collapsePanel(userContext.username, uiKey));
}
}
}
if (filterOpen) {
filterOpen(opened);
}
});
}
render() {
const {
rendered,
showLoading,
searchParameters,
forceSearchParameters,
...others
} = this.props;
const { filterOpened } = this.state;
if (!rendered) {
return null;
}
let level = 'default';
let tooltip = this.i18n('component.advanced.Table.filter.empty');
if (!Domain.SearchParameters.isEmptyFilter(searchParameters, forceSearchParameters)) {
level = 'info';
tooltip = this.i18n('component.advanced.Table.filter.notEmpty');
}
//
return (
<Basic.Tooltip value={tooltip}>
<span>
<Basic.Button
level={ level }
buttonSize="xs"
onClick={ this._filterOpen.bind(this, !filterOpened) }
showLoading={ showLoading }
icon="filter"
endIcon={
<Basic.Icon value={ !filterOpened ? 'triangle-bottom' : 'triangle-top' } style={{ fontSize: '0.8em' }}/>
}
text={ this.i18n('button.filter.toogle') }
{ ...others }/>
</span>
</Basic.Tooltip>
);
}
}
FilterToogleButton.propTypes = {
...Basic.AbstractContextComponent.propTypes,
/**
* Callback, when filter is opened
* @type {function} function(bool)
*/
filterOpen: PropTypes.func,
/**
* Filter is opened
* @type {bool}
*/
filterOpened: PropTypes.bool,
/**
* Used search parameters in redux
*
* @type {SearchParameters}
*/
searchParameters: PropTypes.object,
/**
* "Hard filters"
*
* @type {SearchParameters}
*/
forceSearchParameters: PropTypes.object,
};
FilterToogleButton.defaultProps = {
...Basic.AbstractContextComponent.defaultProps
};
function select(state) {
return {
userContext: state.security.userContext
};
}
export default connect(select)(FilterToogleButton);
|
src/decorators/withViewport.js | cheshire137/cheevo-plotter | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 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, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = { width: window.innerWidth, height: window.innerHeight };
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({ viewport: value }); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
test/fixtures/builds-with-multiple-runtimes/src/index.js | mangomint/create-react-app | import React from 'react';
import dva from 'dva';
import createHistory from 'history/createHashHistory';
import ky from 'ky';
const app = dva({ history: createHistory() });
app.router(() => {
ky.get('https://canihazip.com/s')
.then(r => r.text())
.then(console.log, console.error)
.then(() => console.log('ok'));
return <div>Test</div>;
});
app.start('#root');
|
site/demos/earthquake-reporter/src/index.js | appbaseio/reactivesearch | import React from 'react';
import ReactDOM from 'react-dom';
import {
ReactiveBase,
SelectedFilters,
RangeSlider,
DynamicRangeSlider,
SingleList,
} from '@appbaseio/reactivesearch';
import { ReactiveGoogleMap, ReactiveOpenStreetMap } from '@appbaseio/reactivemaps';
import Dropdown from '@appbaseio/reactivesearch/lib/components/shared/Dropdown';
import './index.css';
const providers = [
{
label: 'Google Map',
value: 'googleMap',
},
{
label: 'OpenStreet Map',
value: 'openstreetMap',
},
];
class App extends React.Component {
constructor() {
super();
this.state = {
mapProvider: providers[0],
};
this.setProvider = this.setProvider.bind(this);
}
setProvider(mapProvider) {
this.setState({
mapProvider,
});
}
render() {
const mapProps = {
dataField: 'location',
defaultMapStyle: 'Light Monochrome',
title: 'Reactive Maps',
defaultZoom: 3,
size: 50,
react: {
and: ['magnitude-filter', 'year-filter', 'places'],
},
onPopoverClick: item => <div>{item.place}</div>,
showMapStyles: true,
renderItem: result => ({
custom: (
<div
style={{
background: 'dodgerblue',
color: '#fff',
paddingLeft: 5,
paddingRight: 5,
borderRadius: 3,
padding: 10,
}}
>
<i className="fas fa-globe-europe" />
{result.magnitude}
</div>
),
}),
};
return (
<ReactiveBase
app="earthquakes"
url="https://a03a1cb71321:75b6603d-9456-4a5a-af6b-a487b309eb61@appbase-demo-ansible-abxiydt-arc.searchbase.io"
enableAppbase
mapKey="AIzaSyA9JzjtHeXg_C_hh_GdTBdLxREWdj3nsOU"
>
<div className="container">
<div className="filters-container">
{' '}
<h1>Earthquakes Reporter</h1>
<SelectedFilters />
<hr />
<SingleList
title="Filter By Places"
componentId="places"
dataField="place.keyword"
size={50}
showSearch
/>
<hr />
<RangeSlider
title="Filter By Magnitude"
componentId="magnitude-filter"
dataField="magnitude"
range={{
start: 1,
end: 10,
}}
rangeLabels={{
start: '1',
end: '10',
}}
tooltipTrigger="hover"
/>
<hr />
<DynamicRangeSlider
title="Filter By Year"
componentId="year-filter"
dataField="time"
queryFormat="date"
rangeLabels={(min, max) => ({
start: new Date(min).toISOString().substring(0, 10),
end: new Date(max).toISOString().substring(0, 10),
})}
/>
</div>
<div className="maps-container">
<div style={{ marginTop: '10px' }}>
{' '}
<div
style={{
position: 'relative',
zIndex: 9999999,
marginBottom: '1rem',
}}
>
<div
style={{
marginTop: '20px',
marginBottom: '5px',
fontSize: '1 rem',
}}
>
<b>Select Map Provider</b>
</div>
<Dropdown
items={providers}
onChange={this.setProvider}
selectedItem={this.state.mapProvider}
keyField="label"
returnsObject
/>
</div>
<hr />
{this.state.mapProvider.value === 'googleMap' ? (
<ReactiveGoogleMap
style={{ height: '90vh' }}
componentId="googleMap"
{...mapProps}
/>
) : (
<ReactiveOpenStreetMap
style={{ height: '90vh' }}
componentId="openstreetMap"
{...mapProps}
/>
)}
</div>
</div>
</div>
</ReactiveBase>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
|
src/components/extensions/overview/blocks/cost.js | vFujin/HearthLounge | import React from 'react';
import PropTypes from 'prop-types';
const Cost = ({extensionCost}) => {
const PriceTableRows = ({price}) => {
return (
<tr>
<th>{price.desc}</th>
<td>{price.gold}</td>
<td>{price.usd}</td>
<td>{price.eur}</td>
<td>{price.gbp}</td>
</tr>
)
};
const CostTable = ({cost}) => {
return (
<table>
<thead>
<tr>
<th>Wing</th>
<th>Gold</th>
<th>USD</th>
<th>EUR</th>
<th>GBP</th>
</tr>
</thead>
<tbody>
{cost.map((price, i) => <PriceTableRows key={i} price={price}/>)}
</tbody>
</table>
)
};
return (
<div className="cost inner-container">
<CostTable cost={extensionCost}/>
</div>
);
};
export default Cost;
Cost.propTypes = {
extensionCost: PropTypes.array.isRequired
};
|
src/RegionSelect.js | casavi/react-region-select | import React, { Component } from 'react';
import { PropTypes } from 'prop-types';
import objectAssign from 'object-assign';
import Region from './Region';
import style from './style';
class RegionSelect extends Component {
constructor (props) {
super(props);
this.onComponentMouseTouchDown = this.onComponentMouseTouchDown.bind(this);
this.onDocMouseTouchMove = this.onDocMouseTouchMove.bind(this);
this.onDocMouseTouchEnd = this.onDocMouseTouchEnd.bind(this);
this.onRegionMoveStart = this.onRegionMoveStart.bind(this);
this.regionCounter = 0;
}
componentDidMount() {
document.addEventListener('mousemove', this.onDocMouseTouchMove);
document.addEventListener('touchmove', this.onDocMouseTouchMove);
document.addEventListener('mouseup', this.onDocMouseTouchEnd);
document.addEventListener('touchend', this.onDocMouseTouchEnd);
document.addEventListener('touchcancel', this.onDocMouseTouchEnd);
}
componentWillUnmount() {
document.removeEventListener('mousemove', this.onDocMouseTouchMove);
document.removeEventListener('touchmove', this.onDocMouseTouchMove);
document.removeEventListener('mouseup', this.onDocMouseTouchEnd);
document.removeEventListener('touchend', this.onDocMouseTouchEnd);
document.removeEventListener('touchcancel', this.onDocMouseTouchEnd);
}
getClientPos(e) {
let pageX, pageY;
if (e.touches) {
pageX = e.touches[0].pageX;
pageY = e.touches[0].pageY;
} else {
pageX = e.pageX;
pageY = e.pageY;
}
return {
x: pageX,
y: pageY
};
}
onDocMouseTouchMove (event) {
if (!this.isChanging) {
return;
}
const index = this.regionChangeIndex;
const updatingRegion = this.props.regions[index];
const clientPos = this.getClientPos(event);
const regionChangeData = this.regionChangeData;
let x, y, width, height;
if (!regionChangeData.isMove) {
let x1Pc, y1Pc, x2Pc, y2Pc;
x1Pc = (regionChangeData.clientPosXStart - regionChangeData.imageOffsetLeft) / regionChangeData.imageWidth * 100;
y1Pc = (regionChangeData.clientPosYStart - regionChangeData.imageOffsetTop) / regionChangeData.imageHeight * 100;
x2Pc = (clientPos.x - regionChangeData.imageOffsetLeft) / regionChangeData.imageWidth * 100;
y2Pc = (clientPos.y - regionChangeData.imageOffsetTop) / regionChangeData.imageHeight * 100;
x = Math.min(x1Pc, x2Pc);
y = Math.min(y1Pc, y2Pc);
width = Math.abs(x1Pc - x2Pc);
height = Math.abs(y1Pc - y2Pc);
if(this.props.constraint){
if (x2Pc >= 100) { x = x1Pc; width = 100 - x1Pc; }
if (y2Pc >= 100) { y = y1Pc; height = 100 - y1Pc; }
if (x2Pc <= 0) { x = 0; width = x1Pc; }
if (y2Pc <= 0) { y = 0; height = y1Pc; }
}
} else {
x = (clientPos.x + regionChangeData.clientPosXOffset - regionChangeData.imageOffsetLeft) / regionChangeData.imageWidth * 100;
y = (clientPos.y + regionChangeData.clientPosYOffset - regionChangeData.imageOffsetTop) / regionChangeData.imageHeight * 100;
width = updatingRegion.width;
height = updatingRegion.height;
if(this.props.constraint){
if (x + width >= 100) { x = Math.round(100 - width); }
if (y + height >= 100) { y = Math.round(100 - height); }
if (x <= 0) { x = 0; }
if (y <= 0) { y = 0; }
}
}
const rect = {
x: x,
y: y,
width: width,
height: height,
isChanging: true
};
this.props.onChange([
...this.props.regions.slice(0, index),
objectAssign({}, updatingRegion, rect),
...this.props.regions.slice(index + 1)
]);
}
onDocMouseTouchEnd () {
if (this.isChanging) {
this.isChanging = false;
const index = this.regionChangeIndex;
const updatingRegion = this.props.regions[index];
const changes = {
new: false,
isChanging: false
};
this.regionChangeIndex = null;
this.regionChangeData = null;
this.props.onChange([
...this.props.regions.slice(0, index),
objectAssign({}, updatingRegion, changes),
...this.props.regions.slice(index + 1)
]);
}
}
onComponentMouseTouchDown (event) {
if (event.target.dataset.wrapper || event.target.dataset.dir || isSubElement(event.target, (el) => el.dataset && el.dataset.wrapper)) {
return;
}
event.preventDefault();
const clientPos = this.getClientPos(event);
const imageOffset = this.getElementOffset(this.refs.image);
const xPc = (clientPos.x - imageOffset.left) / this.refs.image.offsetWidth * 100;
const yPc = (clientPos.y - imageOffset.top) / this.refs.image.offsetHeight * 100;
this.isChanging = true;
const rect = {
x: xPc,
y: yPc,
width: 0,
height: 0,
new: true,
data: { index: this.regionCounter },
isChanging: true
};
this.regionCounter += 1;
this.regionChangeData = {
imageOffsetLeft: imageOffset.left,
imageOffsetTop: imageOffset.top,
clientPosXStart: clientPos.x,
clientPosYStart: clientPos.y,
imageWidth: this.refs.image.offsetWidth,
imageHeight: this.refs.image.offsetHeight,
isMove: false
};
if (this.props.regions.length < this.props.maxRegions) {
this.props.onChange(this.props.regions.concat(rect));
this.regionChangeIndex = this.props.regions.length;
} else {
this.props.onChange([
...this.props.regions.slice(0, this.props.maxRegions - 1),
rect
]);
this.regionChangeIndex = this.props.maxRegions - 1;
}
}
getElementOffset (el) {
const rect = el.getBoundingClientRect();
const docEl = document.documentElement;
const rectTop = rect.top + window.pageYOffset - docEl.clientTop;
const rectLeft = rect.left + window.pageXOffset - docEl.clientLeft;
return {
top: rectTop,
left: rectLeft
};
}
onRegionMoveStart (event, index) {
if (!event.target.dataset.wrapper && !event.target.dataset.dir) {
return;
}
event.preventDefault();
const clientPos = this.getClientPos(event);
const imageOffset = this.getElementOffset(this.refs.image);
let clientPosXStart, clientPosYStart;
const currentRegion = this.props.regions[index];
const regionLeft = (currentRegion.x / 100 * this.refs.image.offsetWidth) + imageOffset.left;
const regionTop = (currentRegion.y / 100 * this.refs.image.offsetHeight) + imageOffset.top;
const regionWidth = (currentRegion.width / 100 * this.refs.image.offsetWidth);
const regionHeight = (currentRegion.height / 100 * this.refs.image.offsetHeight);
const clientPosDiffX = regionLeft - clientPos.x;
const clientPosDiffY = regionTop - clientPos.y;
const resizeDir = event.target.dataset.dir;
if (resizeDir) {
if (resizeDir === 'se') {
clientPosXStart = regionLeft;
clientPosYStart = regionTop;
} else if (resizeDir === 'sw') {
clientPosXStart = regionLeft + regionWidth;
clientPosYStart = regionTop;
} else if (resizeDir === 'nw') {
clientPosXStart = regionLeft + regionWidth;
clientPosYStart = regionTop + regionHeight;
} else if (resizeDir === 'ne') {
clientPosXStart = regionLeft;
clientPosYStart = regionTop + regionHeight;
}
} else {
clientPosXStart = clientPos.x;
clientPosYStart = clientPos.y;
}
this.isChanging = true;
this.regionChangeData = {
imageOffsetLeft: imageOffset.left,
imageOffsetTop: imageOffset.top,
clientPosXStart: clientPosXStart,
clientPosYStart: clientPosYStart,
clientPosXOffset: clientPosDiffX,
clientPosYOffset: clientPosDiffY,
imageWidth: this.refs.image.offsetWidth,
imageHeight: this.refs.image.offsetHeight,
isMove: resizeDir ? false : true,
resizeDir: resizeDir
};
this.regionChangeIndex = index;
}
renderRect (rect, index) {
return <Region
x={rect.x}
y={rect.y}
width={rect.width}
height={rect.height}
handles={!rect.new}
data={rect.data}
key={index}
index={index}
customStyle={this.props.regionStyle}
dataRenderer={this.props.regionRenderer}
onCropStart={(event) => this.onRegionMoveStart(event, index)}
changing={index === this.regionChangeIndex}
/>;
}
render () {
const regions = this.props.regions;
return (
<div
ref='image'
style={objectAssign({}, style.RegionSelect, this.props.style)}
className={this.props.className}
onTouchStart={this.onComponentMouseTouchDown}
onMouseDown={this.onComponentMouseTouchDown}>
{regions.map(this.renderRect.bind(this))}
{this.props.debug
? <table style={{position:'absolute', right: 0, top: 0}}>
<tbody>
{regions.map((rect, index) => {
return (
<tr key={index}>
<td>x: {Math.round(rect.x, 1)}</td>
<td>y: {Math.round(rect.y, 1)}</td>
<td>width: {Math.round(rect.width, 1)}</td>
<td>height: {Math.round(rect.height, 1)}</td>
</tr>
);
})}
</tbody>
</table>
: null }
{this.props.children}
</div>
);
}
}
RegionSelect.propTypes = {
constraint: PropTypes.bool,
regions: PropTypes.array,
children: PropTypes.any,
onChange: PropTypes.func.isRequired,
regionRenderer: PropTypes.func,
maxRegions: PropTypes.number,
debug: PropTypes.bool,
className: PropTypes.string,
style: PropTypes.object,
regionStyle: PropTypes.object
};
RegionSelect.defaultProps = {
maxRegions: Infinity,
debug: false,
regions: [],
constraint: false
};
function isSubElement (el, check) {
if (el === null) {
return false;
} else if (check(el)) {
return true;
} else {
return isSubElement(el.parentNode, check);
}
}
// support both es6 modules and common js
module.exports = RegionSelect;
module.exports.default = RegionSelect;
|
client/modules/DangTin/DangTinPages.js | tranphong001/BIGVN | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Modal, Button } from 'react-bootstrap';
import { getCategories, getCities, getDistricts, getWards, getId } from '../App/AppReducer';
import { fetchDistricts, fetchWards, addDistricts, addWards, setNotify } from '../App/AppActions';
import { postNews, uploadImage } from './DangTinActions';
import CKEditor from 'react-ckeditor-component';
import styles from '../../main.css';
import 'react-image-crop/dist/ReactCrop.css';
import {Cropper} from 'react-image-cropper'
import numeral from 'numeral';
class DangTinPages extends Component {
constructor(props) {
super(props);
this.state = {
category: '',
city: 'none',
district: 'none',
ward: 'none',
address: '',
title: '',
price: '',
content: '',
name: '',
phone: '',
addressContact: '',
check: false,
images: [],
imagesBase64: [],
isCrop: false,
cropSrc: '',
thumbnail: 0,
thumbnailTemp: 0,
isAction: false,
isSubmitting: false,
};
}
componentWillMount() {
if (this.props.id === '') {
this.context.router.push('/');
}
}
isNumeric = (n) => {
return !isNaN(parseFloat(n)) && isFinite(n);
};
updateContent = (newContent) => {
this.setState({
content: newContent
});
};
onChange = (evt) => {
const newContent = evt.editor.getData();
this.setState({
content: newContent
});
};
selectCategory = (event) => {
this.setState({ category: event.target.value });
};
selectCity = (event) => {
this.setState({ city: event.target.value });
if (event.target.value !== 'none') {
this.props.dispatch(fetchDistricts(event.target.value));
} else {
this.setState({ district: 'none', ward: 'none' });
this.props.dispatch(addDistricts([]));
this.props.dispatch(addWards([]));
}
};
selectDistrict = (event) => {
this.setState({ district: event.target.value });
if (event.target.value !== 'none') {
this.props.dispatch(fetchWards(event.target.value));
} else {
this.setState({ ward: 'none' });
this.props.dispatch(addWards([]));
}
};
selectWard = (event) => {
this.setState({ ward: event.target.value });
};
handleAddress = (eventKey) => { this.setState({ address: eventKey.target.value }); };
handleTitle = (eventKey) => { this.setState({ title: eventKey.target.value }); };
handlePrice = (eventKey) => {
if (this.isNumeric(eventKey.target.value.trim().replace(/,/g, ''))) {
this.setState({ price: eventKey.target.value.trim().replace(/,/g, '') });
} else {
this.setState({ price: '' });
}
};
handleName = (eventKey) => { this.setState({ name: eventKey.target.value }); };
handlePhone = (eventKey) => { this.setState({ phone: eventKey.target.value.trim()}); };
handleAddressContact = (eventKey) => { this.setState({ addressContact: eventKey.target.value }); };
handleCheck = () => { this.setState({ check: !this.state.check }); };
submit = () => {
if (this.state.check) {
if (this.state.imagesBase64.length === 0) {
this.props.dispatch(setNotify('Bạn phải upload ít nhất một hình'));
return;
}
if (this.state.category.trim() === '') {
this.props.dispatch(setNotify('Vui lòng chọn danh mục'));
return;
}
if (this.state.price.trim() === '') {
this.props.dispatch(setNotify('Vui lòng nhập giá'));
return;
}
if (this.state.city.trim() === '') {
this.props.dispatch(setNotify('Vui lòng chọn Tỉnh/Thành'));
return;
}
if (this.state.district.trim() === '') {
this.props.dispatch(setNotify('Vui lòng chọn Quận/Huyện'));
return;
}
if (this.state.ward.trim() === '') {
this.props.dispatch(setNotify('Vui lòng chọn Phường/Xã'));
return;
}
if (this.state.address.trim() === '') {
this.props.dispatch(setNotify('Vui lòng nhập địa chỉ'));
return;
}
if (this.state.title.trim() === '') {
this.props.dispatch(setNotify('Vui lòng nhập tiêu đề tin rao vặt'));
return;
}
if (this.state.content.trim() === '') {
this.props.dispatch(setNotify('Vui lòng nhập nội dung tin rao vặt'));
return;
}
if (this.state.name.trim() === '') {
this.props.dispatch(setNotify('Vui lòng nhập tên liên lạc'));
return;
}
if (this.state.phone.trim() === '') {
this.props.dispatch(setNotify('Vui lòng nhập số điện thoại liên lạc'));
return;
}
if (this.state.addressContact.trim() === '') {
this.props.dispatch(setNotify('Vui lòng nhập địa chỉ liên lạc'));
return;
}
const news = {
category: this.state.category,
userId: this.props.id,
city: this.state.city,
district: this.state.district,
ward: this.state.ward,
type: 'news',
address: this.state.address,
keywords: [],
title: this.state.title,
price: this.state.price,
content: this.state.content,
check: this.state.check,
imagesBase64: this.state.imagesBase64,
thumbnail: this.state.thumbnail,
contact: {
name: this.state.name,
phone: this.state.phone,
address: this.state.addressContact,
},
};
this.setState({ isSubmitting: true });
this.props.dispatch(postNews(news)).then((res) => {
console.log(res);
this.setState({ isSubmitting: false });
if (res.news === 'success') {
this.context.router.push('/');
this.props.dispatch(setNotify('Tin đang được chờ phê duyệt!'));
} else {
this.props.dispatch(setNotify('Tin đã bị cấm đăng'));
}
});
} else {
this.props.dispatch(setNotify('Bạn chưa cam đoán thông tin của tin rao!'));
}
};
onCrop = (e) => {
e.preventDefault();
const reader = new FileReader();
const file = e.target.files[0];
let base64image = null;
reader.onload = (readerEvt) => {
base64image = readerEvt.target.result;
};
reader.onloadend = () => {
this.setState({
cropSrc: base64image,
isCrop: true
});
};
reader.readAsDataURL(file);
};
hideCrop = () => { this.setState({ isCrop: false }); };
saveCrop = () => {
this.setState({ imagesBase64: [...this.state.imagesBase64, this.refs.cropper.crop()], isCrop: false });
};
onAction = (index) => { this.setState({ isAction: true, thumbnailTemp: index }); };
onHideAction = () => { this.setState({ isAction: false }); };
pickThumbnail = () => {
this.setState({ thumbnail: this.state.thumbnailTemp, isAction: false });
};
deleteUploadImage = () => {
if (this.state.thumbnailTemp >= this.state.thumbnail) {
this.setState({
imagesBase64: this.state.imagesBase64.filter((image, index) => index != this.state.thumbnailTemp),
isAction: false,
thumbnail: 0
});
} else {
this.setState({
imagesBase64: this.state.imagesBase64.filter((image, index) => index != this.state.thumbnailTemp),
isAction: false
});
}
};
render() {
return (
<div>
<div className="panel panel-default col-md-8 col-md-offset-2 col-sm-8 col-sm-offset-2">
<div className="col-md-10 col-md-offset-1">
<div className={styles.registerTitle}>
<p className={styles.postNews}>ĐĂNG TIN</p>
<div className="form-horizontal">
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Chọn danh mục</label>
<div className="col-sm-9">
<select className="input-large form-control" onChange={this.selectCategory}>
<option value="none" style={{ fontSize: '11pt' }}>Chọn danh mục</option>
{
this.props.categories.map((cate, index) => (
<option key={`${index}Cate`} value={cate._id} style={{ fontSize: '11pt' }}>{cate.title}</option>
))
}
</select>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Tỉnh thành</label>
<div className="col-sm-9">
<select className="input-large form-control" onChange={this.selectCity}>
<option value="none" style={{ fontSize: '11pt' }}>Chọn tỉnh thành</option>
{
this.props.cities.map((city, index) => (
<option key={`${index}City`} value={city._id} style={{ fontSize: '11pt' }}>{city.name}</option>
))
}
</select>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Quận/Huyện</label>
<div className="col-sm-9">
<select className="input-large form-control" onChange={this.selectDistrict}>
<option value="none">
{
(this.state.city === 'none') ?
'Vui lòng chọn tỉnh thành'
: this.props.districts.length > 0 ? 'Chọn Quận/Huyện' : 'Đang tải'
}
</option>
{
this.props.districts.map((district, index) => (
<option key={`${index}District`} value={district._id} style={{ fontSize: '11pt' }}>{district.name}</option>
))
}
</select>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Phường/Xã</label>
<div className="col-sm-9">
<select className="input-large form-control" onChange={this.selectWard}>
<option value="none">
{
(this.state.district === 'none') ?
'Vui lòng chọn Quận/Huyện'
: this.props.wards.length > 0 ? 'Chọn Phường/Xã' : 'Đang tải'
}
</option>
{
this.props.wards.map((ward, index) => (
<option key={`${index}Ward`} value={ward._id} style={{ fontSize: '11pt' }}>{ward.name}</option>
))
}
</select>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Địa chỉ</label>
<div className="col-sm-9">
<input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.address} onChange={this.handleAddress} />
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Tiêu đề</label>
<div className="col-sm-9">
<input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.title} onChange={this.handleTitle} maxLength="200" />
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Giá (VNĐ)</label>
<div className="col-sm-9">
<input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.price.toString().replace(/\B(?=(\d{3})+(?!\d))/g, ',')} onChange={this.handlePrice} />
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>
Nội dung<br /><p style={{ color: 'rgb(204, 204, 204)', fontSize: '10pt', fontStyle: 'italic', paddingTop: '16px' }}>(Tối đa 2000 kí tự)</p>
</label>
<div className="col-sm-9">
<CKEditor
activeClass={`p10 ${styles.customCKeditor}`}
content={this.state.content}
events={{ change: this.onChange, blur: () => {}, afterPaste: () => {} }}
/>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Hình ảnh</label>
<div className="col-sm-9">
<div style={{ overflow: 'auto' }}>
{
this.state.imagesBase64.map((r, index) => {
if (this.state.thumbnail === index) {
return (
<div key={`${index}Newser`} className={styles.containerImages}>
<a onClick={() => this.onAction(index)}>
<div style={{ position: 'relative' }}>
<img width={100} height={75} src={r}/>
<div style={{
position: 'absolute',
width: '100%',
height: '100%',
top: '0',
left: '0',
border: '3px solid rgb(243, 146, 31)',
borderRadius: '3px'
}}>
<div style={{ display: 'table', verticalAlign: 'middle', textAlign: 'center',width: '100%', height: '100%' }}>
<span style={{ display: 'table-cell', verticalAlign: 'middle' }}>
Hình nền
</span>
</div>
</div>
</div>
</a>
</div>
)
} else {
return (
<div key={`${index}Newser`} className={styles.containerImages}>
<a onClick={() => this.onAction(index)}>
<img width={100} height={75} src={r}/>
</a>
</div>
)
}
})
}
{
(this.state.imagesBase64.length < 5) ? (
<div className={styles.containerImages}>
<label htmlFor="file-upload" className={styles.customUpload}>
<i className="fa fa-cloud-upload" style={{ color: '#03a9f4' }} />
Tải hình ảnh
</label>
<input id="file-upload" accept="image/jpeg, image/png" type="file" style={{ display: 'none' }} onChange={this.onCrop} />
</div>
) : ''
}
</div>
<div><p style={{ fontSize: '10pt', color: '#ccc', textAlign: 'left', paddingTop: '10px', fontStyle: 'italic' }}>(Số lượng hình tối đa 5 hình, kích thước hình uu tiên là 960x720px)</p></div>
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Tên liên hệ</label>
<div className="col-sm-9">
<input className="form-control"type="text" style={{ fontSize: '11pt' }} value={this.state.name} onChange={this.handleName} />
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Số điện thoại</label>
<div className="col-sm-9">
<input className="form-control" type="text" style={{ fontSize: '11pt' }} value={this.state.phone} onChange={this.handlePhone} />
</div>
</div>
<div className="form-group">
<label className="col-sm-3 control-label" style={{ textAlign: 'left', fontSize: '11pt' }}>Địa chỉ</label>
<div className="col-sm-9">
<input className="form-control" style={{ fontSize: '11pt' }} type="text" value={this.state.addressContact} onChange={this.handleAddressContact} />
</div>
</div>
<div className="form-group">
<div className="col-md-3"></div>
<div className="col-sm-9" style={{ textAlign: 'left', fontSize: '11pt' }}>
<label>
<input type="checkbox" checked={this.state.check} onChange={this.handleCheck} className={styles.marginRight10} />
<span style={{ paddingLeft: '5px', fontSize: '10pt' }}>Cam đoan tính xác thực của tin rao này</span>
</label>
</div>
</div>
<div className="form-group">
<div className="col-md-3"></div>
<div className="col-sm-9">
<button onClick={this.submit} className={styles.submitNews} disabled={this.state.isSubmitting} style={{ fontSize: '11pt', fontWeight: 'bold' }} >
{this.state.isSubmitting ? 'ĐANG GỬI' : 'ĐĂNG TIN'}
</button>
</div>
</div>
</div>
</div>
</div>
<Modal
show={this.state.isCrop}
onHide={this.hideCrop}
backdrop="static"
>
<Modal.Header closeButton>
<Modal.Title>Cắt hình</Modal.Title>
</Modal.Header>
<Modal.Body>
<Cropper
src={this.state.cropSrc}
ref="cropper"
ratio={4/3}
/>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.saveCrop}>Chọn</Button>
<Button onClick={this.hideCrop}>Thoát</Button>
</Modal.Footer>
</Modal>
<Modal
show={this.state.isAction}
onHide={this.onHideAction}
backdrop="static"
>
<Modal.Header closeButton>
<Modal.Title>Thao tác</Modal.Title>
</Modal.Header>
<Modal.Body>
Xóa ảnh hoặc chọn ảnh làm hình nền
</Modal.Body>
<Modal.Footer>
<Button onClick={this.onHideAction}>Thoát</Button>
<Button onClick={this.deleteUploadImage}>Xóa</Button>
<Button onClick={this.pickThumbnail}>Chọn làm hình nền</Button>
</Modal.Footer>
</Modal>
</div>
</div>
);
}
}
// Retrieve data from store as props
function mapStateToProps(state) {
return {
categories: getCategories(state),
cities: getCities(state),
districts: getDistricts(state),
wards: getWards(state),
id: getId(state),
};
}
DangTinPages.propTypes = {
dispatch: PropTypes.func.isRequired,
id: PropTypes.string.isRequired,
categories: PropTypes.array.isRequired,
cities: PropTypes.array.isRequired,
districts: PropTypes.array.isRequired,
wards: PropTypes.array.isRequired,
};
DangTinPages.contextTypes = {
router: PropTypes.object,
};
export default connect(mapStateToProps)(DangTinPages);
|
src/svg-icons/image/navigate-before.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageNavigateBefore = (props) => (
<SvgIcon {...props}>
<path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
</SvgIcon>
);
ImageNavigateBefore = pure(ImageNavigateBefore);
ImageNavigateBefore.displayName = 'ImageNavigateBefore';
ImageNavigateBefore.muiName = 'SvgIcon';
export default ImageNavigateBefore;
|
src/client.js | derek-duncan/challenge | 'use strict';
import Iso from 'iso';
import Router from 'react-router';
import React from 'react';
import createBrowserHistory from 'history/lib/createBrowserHistory'
import reactRoutes from './routes/client';
import alt from './alt';
Iso.bootstrap((state, _, container) => {
alt.bootstrap(state);
let history = createBrowserHistory()
React.render(<Router history={history}>{reactRoutes}</Router>, container);
});
|
example/src/screens/types/tabs/TabOne.js | luggit/react-native-navigation | import React from 'react';
import { StyleSheet, View, Text, Dimensions, Button } from 'react-native';
class TabOne extends React.Component {
render() {
return (
<View>
<Text>Tab One</Text>
</View>
);
}
}
export default TabOne;
|
docs/src/NotFoundPage.js | Firfi/meteor-react-bootstrap | import React from 'react';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
const NotFoundPage = React.createClass({
render() {
return (
<div>
<NavMain activePage='' />
<PageHeader
title='404'
subTitle='Hmmm this is awkward.' />
<PageFooter />
</div>
);
}
});
export default NotFoundPage;
|
node_modules/react-router/es6/Link.js | sharonjean/React-Netflix | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object]).isRequired,
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
};
},
handleClick: function handleClick(event) {
if (this.props.onClick) this.props.onClick(event);
if (event.defaultPrevented) return;
!this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0;
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) return;
event.preventDefault();
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(location);
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(location);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(location, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ' ' + activeClassName;
} else {
props.className = activeClassName;
}
}
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link; |
src/back-office/components/Logo.js | mihailgaberov/es6-bingo-game | import React from 'react';
class Logo extends React.Component {
render() {
return <div id="logo" />;
}
}
export default Logo;
|
client/src/transforms/FormAction/ownerAwareUnpublish.js | open-sausages/silverstripe-asset-admin | /* global confirm */
import React from 'react';
import i18n from 'i18n';
const ownerAwareUnpublish = (FormAction) => (props) => {
const originalOnclick = props.onClick;
const newProps = {
...props,
onClick(e, nameOrID) {
const { owners } = props.data;
let message = null;
if (owners && parseInt(owners, 10) > 0) {
message = [
i18n.inject(
i18n._t(
'AssetAdmin.SINGLE_OWNED_WARNING_1',
'This file is being used in {count} other published section(s).',
),
{ count: owners }
),
i18n._t(
'AssetAdmin.SINGLE_OWNED_WARNING_2',
'Ensure files are removed from content areas prior to unpublishing them. Otherwise, they will appear as broken links.'
),
i18n._t(
'AssetAdmin.SINGLE_OWNED_WARNING_3',
'Do you want to unpublish this file anyway?'
)
].join('\n\n');
} else {
message = i18n._t('AssetAdmin.CONFIRMUNPUBLISH', 'Are you sure you want to unpublish this record?');
}
// eslint-disable-next-line no-alert
if (confirm(message)) {
originalOnclick(e, nameOrID);
} else {
e.preventDefault();
}
}
};
return <FormAction {...newProps} />;
};
export default ownerAwareUnpublish;
|
app/components/UGFooterSitemap/index.js | perry-ugroop/ugroop-react-dup2 | import React from 'react';
import messages from './messages';
import { FormattedMessage } from 'react-intl';
import { Grid, Row, Col, FormGroup } from 'react-bootstrap';
import UGFooterSitemap from './UGFooterSitemap';
import UGFooterBtn from './UGFooterBtn';
import UGFooterH3 from './UGFooterH3';
import UGFooterULWithIcon from './UGFooterULWithIcon';
import UGFooterULDefault from './UGFooterULDefault';
import FollowUsList from './FollowUsList';
import CustomerServiceList from './CustomerServiceList';
import AboutUsList from './AboutUsList';
import UGFooterInput from './UGFooterInput';
function FooterSiteMap() {
return (
<UGFooterSitemap>
<Grid>
<Row>
<Col md={3} sm={6}>
<UGFooterH3>Follow Us:</UGFooterH3>
<UGFooterULWithIcon>
{FollowUsList}
</UGFooterULWithIcon>
</Col>
<Col md={3} sm={6}>
<UGFooterH3>About Us</UGFooterH3>
<UGFooterULDefault>
{AboutUsList}
</UGFooterULDefault>
</Col>
<Col md={3} sm={6}>
<UGFooterH3>Customer Service</UGFooterH3>
<UGFooterULDefault>
{CustomerServiceList}
</UGFooterULDefault>
</Col>
<Col md={3} sm={6}>
<UGFooterH3> Promotion & offers</UGFooterH3>
<p><FormattedMessage {...messages.promotionMessage} /></p>
<form>
<FormGroup>
<UGFooterInput
type="text"
id="fc-name"
placeholder="Name"
/>
</FormGroup>
<FormGroup>
<UGFooterInput
type="email"
id="fc-email"
placeholder="Email"
/>
</FormGroup>
<UGFooterBtn>Submit</UGFooterBtn>
</form>
</Col>
</Row>
</Grid>
</UGFooterSitemap>
);
}
export default FooterSiteMap;
|
src/lib/reactors/Showcase/ItemThumbnail.js | EsriJapan/photospot-finder | // Copyright (c) 2016 Yusuke Nunokawa (https://ynunokawa.github.io)
//
// 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 { Thumbnail } from 'react-bootstrap';
class ItemThumbnail extends React.Component {
constructor (props) {
super(props);
this._onClickThumbnail = this._onClickThumbnail.bind(this);
this._onMouseoverThumbnail = this._onMouseoverThumbnail.bind(this);
this._onMouseoutThumbnail = this._onMouseoutThumbnail.bind(this);
}
_onClickThumbnail () {
const coordinates = [this.props.feature.geometry.coordinates[1], this.props.feature.geometry.coordinates[0]];
this.props.onClickThumbnail(coordinates, 15);
}
_onMouseoverThumbnail () {
const feature = this.props.feature;
this.props.onMouseoverThumbnail(feature);
}
_onMouseoutThumbnail () {
this.props.onMouseoutThumbnail(null);
}
render () {
const feature = this.props.feature;
const layoutFields = this.props.layoutFields;
let imageUrl = feature.properties[layoutFields.image];
const name = feature.properties[layoutFields.name];
const description = feature.properties[layoutFields.description];
if (layoutFields.imageUrlPrefix !== undefined && layoutFields.imageUrlPrefix !== '') {
imageUrl = layoutFields.imageUrlPrefix + imageUrl;
}
return (
<Thumbnail
src={imageUrl}
onClick={this._onClickThumbnail}
onMouseOver={this._onMouseoverThumbnail}
onMouseOut={this._onMouseoutThumbnail}
className="react-webmap-item-thumbnail"
>
<h3>{name}</h3>
<p>{description}</p>
</Thumbnail>
);
}
}
ItemThumbnail.propTypes = {
feature: React.PropTypes.any,
layoutFields: React.PropTypes.object,
onClickThumbnail: React.PropTypes.func,
onMouseoverThumbnail: React.PropTypes.func,
onMouseoutThumbnail: React.PropTypes.func
};
ItemThumbnail.displayName = 'ItemThumbnail';
export default ItemThumbnail;
|
src/containers/entitysetforms/CreateEntitySet.js | kryptnostic/gallery | import React from 'react';
import Immutable, { List } from 'immutable';
import PropTypes from 'prop-types';
import Select from 'react-select';
import styled from 'styled-components';
import { FormControl, FormGroup, ControlLabel, Button, Alert } from 'react-bootstrap';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import StyledCheckbox from '../../components/controls/StyledCheckbox';
import AsyncContent, { AsyncStatePropType } from '../../components/asynccontent/AsyncContent';
import { fetchAllEntityTypesRequest } from '../edm/EdmActionFactory';
import { createEntitySetRequest } from './CreateEntitySetActionFactories';
import { fetchWritableOrganizations } from '../organizations/actions/OrganizationsActionFactory';
const ENTITY_SET_TYPES = {
ENTITY_SET: 'Entity Set',
LINKED_ENTITY_SET: 'Linked Entity Set'
};
const PERSON_TYPE_FQN = 'general.person';
const SubmitButton = styled(Button)`
margin-top: 10px;
`;
const FormGroupMarginTop = styled(FormGroup)`
margin-top: 10px;
`;
class CreateEntitySet extends React.Component {
static propTypes = {
actions: PropTypes.shape({
onCreateEntitySet: PropTypes.func.isRequired,
fetchAllEntityTypesRequest: PropTypes.func.isRequired,
fetchWritableOrganizations: PropTypes.func.isRequired
}).isRequired,
createEntitySetAsyncState: AsyncStatePropType.isRequired,
defaultContact: PropTypes.string,
entityTypes: PropTypes.instanceOf(Immutable.Map).isRequired,
entitySets: PropTypes.instanceOf(Immutable.Map).isRequired,
isAdmin: PropTypes.bool.isRequired,
personEntityTypeId: PropTypes.string.isRequired,
writableOrganizations: PropTypes.instanceOf(Immutable.List).isRequired
};
constructor(props) {
super(props);
this.state = {
type: ENTITY_SET_TYPES.ENTITY_SET,
title: '',
description: '',
name: '',
contact: props.defaultContact,
entityTypeId: null,
organizationId: null,
entitySetIds: [],
external: true
};
}
componentDidMount() {
this.props.actions.fetchAllEntityTypesRequest();
this.props.actions.fetchWritableOrganizations();
}
onTypeChange = (option) => {
const entityTypeId = (option.value === ENTITY_SET_TYPES.LINKED_ENTITY_SET)
? this.props.personEntityTypeId
: null;
this.setState({
type: option.value,
entityTypeId,
entitySetIds: []
});
}
onTitleChange = (event) => {
this.setState({
title: event.target.value
});
};
onNameChange = (event) => {
this.setState({
name: event.target.value
});
};
onDescriptionChange = (event) => {
this.setState({
description: event.target.value
});
};
onContactChange = (event) => {
this.setState({
contact: event.target.value
});
}
onEntityTypeChange = (option) => {
const entityTypeId = (option) ? option.value : null;
this.setState({ entityTypeId });
};
onOrganizationChange = (option) => {
const organizationId = (option) ? option.value : null;
this.setState({ organizationId });
};
onEntitySetsChange = (entitySetIds) => {
const entityTypeId = (entitySetIds.length) ? entitySetIds[0].entityTypeId : null;
this.setState({ entitySetIds, entityTypeId });
}
onSubmit = () => {
const {
type,
title,
name,
description,
contact,
entityTypeId,
organizationId,
entitySetIds,
personEntityTypeId,
external
} = this.state;
const isLinking = type === ENTITY_SET_TYPES.LINKED_ENTITY_SET;
const flags = [];
if (isLinking) {
flags.push('LINKING');
}
if (external) {
flags.push('EXTERNAL');
}
const entitySet = {
title,
name,
description,
entityTypeId,
organizationId,
contacts: [contact],
linkedEntitySets: isLinking ? entitySetIds.map(({ value }) => value) : [],
flags
};
this.props.actions.onCreateEntitySet(entitySet);
}
getTypeOptions = () => {
const options = [];
Object.values(ENTITY_SET_TYPES).forEach((type) => {
options.push({
value: type,
label: type
});
});
return options;
}
getEntityTypeOptions() {
const options = [];
this.props.entityTypes.forEach((entityType) => {
if (!entityType.isEmpty()) {
options.push({
value: entityType.get('id'),
label: entityType.get('title')
});
}
});
return options;
}
getOrganizationOptions() {
const options = [];
this.props.writableOrganizations.forEach((organization) => {
if (!organization.isEmpty()) {
options.push({
value: organization.get('id'),
label: organization.get('title')
});
}
});
return options;
}
getEntitySetOptions = () => {
const options = [];
this.props.entitySets.valueSeq().filter(entitySet => !entitySet.get('flags', List()).includes('LINKING')).forEach((entitySet) => {
if (!this.state.entityTypeId || this.state.entityTypeId === entitySet.get('entityTypeId')) {
options.push({
value: entitySet.get('id'),
label: entitySet.get('title'),
entityTypeId: entitySet.get('entityTypeId')
});
}
});
return options;
}
renderEntityTypeOrEntitySetSelection = () => {
if (this.state.type === ENTITY_SET_TYPES.LINKED_ENTITY_SET) {
return (
<FormGroup>
<ControlLabel>Entity sets</ControlLabel>
<Select
multi
value={this.state.entitySetIds}
options={this.getEntitySetOptions()}
onChange={this.onEntitySetsChange} />
</FormGroup>
);
}
return (
<FormGroup>
<ControlLabel>Entity type</ControlLabel>
<Select
value={this.state.entityTypeId}
options={this.getEntityTypeOptions()}
onChange={this.onEntityTypeChange} />
</FormGroup>
);
}
renderPending = () => {
return (
<form onSubmit={this.onSubmit}>
{
this.props.isAdmin && (
<FormGroup>
<ControlLabel>Type</ControlLabel>
<Select
value={this.state.type}
options={this.getTypeOptions()}
onChange={this.onTypeChange} />
</FormGroup>
)
}
<FormGroup>
<ControlLabel>Title</ControlLabel>
<FormControl type="text" onChange={this.onTitleChange} />
</FormGroup>
<FormGroup>
<ControlLabel>Name</ControlLabel>
<FormControl type="text" onChange={this.onNameChange} />
</FormGroup>
<FormGroup>
<ControlLabel>Description</ControlLabel>
<FormControl componentClass="textarea" onChange={this.onDescriptionChange} />
</FormGroup>
<FormGroup>
<ControlLabel>Contact</ControlLabel>
<FormControl
type="text"
value={this.state.contact}
onChange={this.onContactChange} />
</FormGroup>
{ this.renderEntityTypeOrEntitySetSelection() }
<FormGroup>
<ControlLabel>Organization</ControlLabel>
<Select
value={this.state.organizationId}
options={this.getOrganizationOptions()}
onChange={this.onOrganizationChange} />
</FormGroup>
<FormGroupMarginTop>
<StyledCheckbox
name="external"
label="External"
checked={this.state.external}
onChange={({ target }) => this.setState({ external: target.checked })} />
</FormGroupMarginTop>
<SubmitButton type="submit" bsStyle="primary">Create</SubmitButton>
</form>
);
};
renderSuccess = () => {
return (
<Alert bsStyle="success">
Successfully saved Dataset
</Alert>
);
};
render() {
return (
<AsyncContent
{...this.props.createEntitySetAsyncState}
pendingContent={this.renderPending()}
content={this.renderSuccess} />
);
}
}
function mapStateToProps(state) {
const createEntitySetState = state.get('createEntitySet').toJS();
const entityTypes = state.getIn(['edm', 'entityTypes'], Immutable.Map());
const entitySets = state.getIn(['edm', 'entitySets'], Immutable.Map());
const writableOrganizations = state.getIn(['organizations', 'writableOrganizations'], Immutable.List());
let personEntityTypeId = '';
entityTypes.valueSeq().forEach((entityType) => {
const namespace = `${entityType.getIn(['type', 'namespace'])}`;
const name = `${entityType.getIn(['type', 'name'])}`;
if (`${namespace}.${name}` === PERSON_TYPE_FQN) personEntityTypeId = entityType.get('id');
});
return {
entityTypes,
entitySets,
personEntityTypeId,
writableOrganizations,
createEntitySetAsyncState: createEntitySetState.createEntitySetAsyncState
};
}
function mapDispatchToProps(dispatch) {
const actions = {
fetchAllEntityTypesRequest,
fetchWritableOrganizations,
onCreateEntitySet: createEntitySetRequest
};
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CreateEntitySet);
|
app/javascript/mastodon/features/standalone/hashtag_timeline/index.js | MastodonCloud/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../../ui/containers/status_list_container';
import { expandHashtagTimeline } from '../../../actions/timelines';
import Column from '../../../components/column';
import ColumnHeader from '../../../components/column_header';
import { connectHashtagStream } from '../../../actions/streaming';
@connect()
export default class HashtagTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
hashtag: PropTypes.string.isRequired,
};
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
componentDidMount () {
const { dispatch, hashtag } = this.props;
dispatch(expandHashtagTimeline(hashtag));
this.disconnect = dispatch(connectHashtagStream(hashtag));
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandHashtagTimeline(this.props.hashtag, { maxId }));
}
render () {
const { hashtag } = this.props;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='hashtag'
title={hashtag}
onClick={this.handleHeaderClick}
/>
<StatusListContainer
trackScroll={false}
scrollKey='standalone_hashtag_timeline'
timelineId={`hashtag:${hashtag}`}
onLoadMore={this.handleLoadMore}
/>
</Column>
);
}
}
|
client/containers/overview.js | nearform/vidi-dashboard | 'use strict'
import React from 'react'
import {connect} from 'react-redux'
import {Link} from 'react-router'
import {Panel, PageHeader, HealthList} from '../components/index'
import ChartistGraph from 'react-chartist'
import {subscribe, unsubscribe} from '../actions/vidi'
import _ from 'lodash'
export const Overview = React.createClass({
componentDidMount () {
this.props.dispatch(subscribe('processes'))
this.props.dispatch(subscribe('event_loop'))
},
componentWillUnmount () {
this.props.dispatch(unsubscribe('processes'))
this.props.dispatch(unsubscribe('event_loop'))
},
render () {
var sections = []
var groups = _.groupBy(this.props.process_stats, 'tag')
_.each(groups, (group) => {
if (group) {
var proc_sections = []
var data = _.orderBy(group, ['pid'], ['desc'])
var count = data.length
var tag = ''
_.each(data, (process) => {
if (process) {
tag = process.tag
var event_loop = _.find(this.props.event_loop_stats, ['pid', process.pid])
proc_sections.push(make_process_sections(process, event_loop))
}
})
sections.push(
<div key={tag} className="process-group panel">
<div className="panel-heading cf">
<h3 className="m0 fl-left">Processes tagged with <strong>{tag}</strong></h3>
<a href="" className="fl-right icon icon-collapse"></a>
</div>
<div className="panel-body">
<HealthList count={count}/>
{proc_sections}
</div>
</div>
)
}
})
return (
<div className="page page-processes">
<div className="container-fluid">
<PageHeader title={'Overview'} />
</div>
<div className="container-fluid">
{sections}
</div>
</div>
)
}
})
export default connect((state) => {
var vidi = state.vidi
var processes = vidi.processes || {data: [null]}
var event_loop = vidi.event_loop || {data: [null]}
return {
process_stats: processes.data,
event_loop_stats: event_loop.data
}
})(Overview)
function make_search () {
return (
<div className="row middle-xs search-wrapper">
<div className="col-xs-12 col-sm-8 col-md-8 search-input-wrapper">
<input type="search" className="input-large" placeholder="Find a process"/>
</div>
<div className="col-xs-12 col-sm-4 col-md-4 txt-left search-btn-wrapper">
<button className="btn btn-large btn-search">Search</button>
</div>
</div>
)
}
function make_process_sections (data, event_loop) {
var section = []
var now = data.latest
var delay = (Math.round(event_loop.latest.delay * 100) / 100)
var link = `/process/${now.pid}`
return (
<div key={now.pid} className="process-card">
<div className="process-heading has-icon">
<span className="status status-healthy status-small" title="Status: healthy"></span>
<Link to={link}>{now.pid}</Link>
</div>
<div className="process-stats-row cf row no-gutter">
<div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated">
<ul className="list-unstyled list-inline cf">
<li><h4 className="m0">Process uptime:</h4></li>
<li>{now.proc_uptime}</li>
</ul>
</div>
<div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated">
<ul className="list-unstyled list-inline cf">
<li><h4 className="m0">System uptime:</h4></li>
<li>{now.sys_uptime}</li>
</ul>
</div>
<div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated">
<ul className="list-unstyled list-inline cf">
<li><h4 className="m0">Heap usage:</h4></li>
<li>{`${now.heap_used} out of ${now.heap_total} (${now.heap_rss} RSS)`}</li>
</ul>
</div>
<div className="col-xs-12 col-sm-6 col-md-3 col-lg-3 process-stats-container process-stats-floated">
<ul className="list-unstyled list-inline cf">
<li><h4 className="m0">Event loop:</h4></li>
<li>{`${delay}s delay (${event_loop.latest.limit}s limit)`}</li>
</ul>
</div>
</div>
</div>
)
}
|
Faw.Web.Client/src/routes/Achivment/Details/components/AchivmentDetails.js | Demenovich-A-J/Family-s-adventure-world | import React from 'react'
import { Grid, Cell, Button } from 'react-mdl'
import { Stepper, Step, SelectField, Option } from 'react-mdl-extra'
import AchivmentDetailsForm from './AchivmentDetailsForm'
import PropertyEditor from './PropertyEditor'
import AchivmentStepperButtons from './AchivmentStepperButtons'
import AchivmentExpressionList from './AchivmentExpressionList'
import './AchivmentDetails.scss'
export const AchivmentDetails = (props) => (
<Grid className='faw-achivment-details-conatiner'>
<Cell col={7} shadow={0}>
<Cell col={12} className='-section-title mdl-typography--headline' component='h4'>
Achivment Details
</Cell>
<Cell col={12}>
<AchivmentDetailsForm
enabled={props.achivmentEnabled}
disabled={props.achivmentSubmitting || props.achivmentLoading} />
<Button raised ripple primary
onClick={props.submitAchivmentInfo}
disabled={props.achivmentSubmitting || props.achivmentLoading}>
Save
</Button>
</Cell>
</Cell>
<Cell col={5} shadow={0}>
<Cell col={12} className='-section-title mdl-typography--headline' component='h4'>
Achivment condition
</Cell>
<Cell col={12}>
<AchivmentExpressionList
expressionProperties={props.expressionProperties}
removeAchivmentExpression={props.removeAchivmentExpression}
editAchivmentExpression={props.editAchivmentExpression}
disabled={props.achivmentSubmitting || props.achivmentLoading} />
</Cell>
</Cell>
<Cell col={12}>
<Stepper
activeStep={props.activeStep}
onStepTitleClick={props.onStepTitleClick}
disabled={props.achivmentSubmitting || props.achivmentLoading}
>
<Step title={'Introduction'}>
<div className='-stepper-content'>
<h4>Welcom to achivment condition stepper</h4>
<p>Here you can configure achivment expression step by step</p>
<AchivmentStepperButtons
length={2}
activeStep={props.activeStep}
previousStep={props.previousStep}
nextStep={props.nextStep}
restart={props.restart}
finish={props.finish}
selectedModelName={props.selectedModelName}
disabled={props.achivmentSubmitting || props.achivmentLoading}
/>
</div>
</Step>
<Step title={'Expression model selection'}>
<div className='-stepper-content'>
<p>Select model name to use for expression</p>
<SelectField
floatingLabel
label={'Select model name'}
value={props.selectedModelName}
onChange={props.selectModelName}
disabled={props.achivmentSubmitting || props.achivmentLoading}
>
{
props.modelNames && props.modelNames.map((name, index) => (
<Option key={index} value={name}>{name}</Option>
))
}
</SelectField>
<SelectField
floatingLabel
label={'Conncetor'}
value={props.selectedConnector}
onChange={props.selectConnector}
className='-connector-select'
disabled={props.achivmentSubmitting || props.achivmentLoading}
>
{
props.connectors && props.connectors.map((name, index) => (
<Option key={index} value={name}>{name}</Option>
))
}
</SelectField>
<AchivmentStepperButtons
length={2}
activeStep={props.activeStep}
previousStep={props.previousStep}
nextStep={props.nextStep}
restart={props.restart}
finish={props.finish}
selectedModelName={props.selectedModelName}
disabled={props.achivmentSubmitting || props.achivmentLoading}
/>
</div>
</Step>
<Step title={'Condition setup'}>
<div className='-stepper-content'>
<Grid className='-stepper-editor'>
<Cell col={12}>
<p>Fill folowing inputs to add condition</p>
</Cell>
<PropertyEditor
propertyNames={props.modelProperties}
propertyNameChanged={props.propertyNameChanged}
propertyValueChanged={props.propertyValueChanged}
propertyTypeChanged={props.propertyTypeChanged}
valueMode={false}
propertyValue={props.leftPropertyValue}
selectedModelName={props.selectedModelName}
side={'left'}
valueTypes={props.valueTypes}
disabled={props.achivmentSubmitting || props.achivmentLoading}
/>
<Cell col={4}>
<SelectField
floatingLabel
label={'Comparer'}
value={props.selectedComparer}
onChange={props.selectComparer}
className='-comparer-select'
disabled={props.achivmentSubmitting || props.achivmentLoading}
>
{
props.comparers && props.comparers.map((name, index) => (
<Option key={index} value={name}>{name}</Option>
))
}
</SelectField>
</Cell>
<PropertyEditor
propertyNames={props.modelProperties}
propertyNameChanged={props.propertyNameChanged}
propertyValueChanged={props.propertyValueChanged}
propertyTypeChanged={props.propertyTypeChanged}
valueMode
propertyValue={props.rightPropertyValue}
selectedModelName={props.selectedModelName}
side={'right'}
valueTypes={props.valueTypes}
disabled={props.achivmentSubmitting || props.achivmentLoading}
/>
</Grid>
<AchivmentStepperButtons
length={2}
activeStep={props.activeStep}
previousStep={props.previousStep}
nextStep={props.nextStep}
restart={props.restart}
finish={props.finish}
selectedModelName={props.selectedModelName}
disabled={props.achivmentSubmitting || props.achivmentLoading}
/>
</div>
</Step>
</Stepper>
</Cell>
</Grid>
)
AchivmentDetails.propTypes = {
submitAchivmentInfo: React.PropTypes.func.isRequired,
modelNames: React.PropTypes.array.isRequired,
modelProperties: React.PropTypes.object.isRequired,
leftPropertyValue: React.PropTypes.object.isRequired,
rightPropertyValue: React.PropTypes.object.isRequired,
selectedModelName: React.PropTypes.string,
selectedComparer: React.PropTypes.string,
selectedConnector: React.PropTypes.string,
activeStep: React.PropTypes.number.isRequired,
max: React.PropTypes.number.isRequired,
previousStep: React.PropTypes.func.isRequired,
nextStep: React.PropTypes.func.isRequired,
restart: React.PropTypes.func.isRequired,
onStepTitleClick: React.PropTypes.func.isRequired,
selectModelName: React.PropTypes.func.isRequired,
connectors: React.PropTypes.array.isRequired,
selectConnector: React.PropTypes.func.isRequired,
selectComparer: React.PropTypes.func.isRequired,
propertyNameChanged: React.PropTypes.func.isRequired,
propertyValueChanged: React.PropTypes.func.isRequired,
propertyTypeChanged: React.PropTypes.func.isRequired,
valueTypes: React.PropTypes.array.isRequired,
comparers: React.PropTypes.array.isRequired,
finish: React.PropTypes.func.isRequired,
expressionProperties: React.PropTypes.array.isRequired,
achivmentEnabled: React.PropTypes.bool.isRequired,
removeAchivmentExpression: React.PropTypes.func.isRequired,
editAchivmentExpression: React.PropTypes.func.isRequired,
achivmentSubmitting: React.PropTypes.bool.isRequired,
achivmentLoading: React.PropTypes.bool.isRequired
}
export default AchivmentDetails
|
client/routes.js | izolate/skeleton | import React from 'react'
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import DefaultLayout from './layouts/Default'
import HomePage from './pages/Home'
import Error404Page from './pages/404'
const routes = <Router history={browserHistory}>
<Route path='/' component={DefaultLayout}>
<IndexRoute component={HomePage} />
<Route path='*' status={404} component={Error404Page} />
</Route>
</Router>
export default routes
|
js/src/modals/CreateWallet/createWalletStore.js | BSDStudios/parity | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import { observable, computed, action, transaction } from 'mobx';
import React from 'react';
import { FormattedMessage } from 'react-intl';
import Contract from '~/api/contract';
import { ERROR_CODES } from '~/api/transport/error';
import Contracts from '~/contracts';
import { wallet as walletAbi } from '~/contracts/abi';
import { wallet as walletCode, walletLibraryRegKey, fullWalletCode } from '~/contracts/code/wallet';
import { validateUint, validateAddress, validateName } from '~/util/validation';
import { toWei } from '~/api/util/wei';
import WalletsUtils from '~/util/wallets';
const STEPS = {
TYPE: {
title: (
<FormattedMessage
id='createWallet.steps.type'
defaultMessage='wallet type'
/>
)
},
DETAILS: {
title: (
<FormattedMessage
id='createWallet.steps.details'
defaultMessage='wallet details'
/>
)
},
DEPLOYMENT: {
title: (
<FormattedMessage
id='createWallet.steps.deployment'
defaultMessage='wallet deployment'
/>
),
waiting: true
},
INFO: {
title: (
<FormattedMessage
id='createWallet.steps.info'
defaultMessage='wallet informaton'
/>
)
}
};
export default class CreateWalletStore {
@observable step = null;
@observable rejected = false;
@observable deployState = null;
@observable deployError = null;
@observable deployed = false;
@observable txhash = null;
@observable wallet = {
account: '',
address: '',
owners: [],
required: 1,
daylimit: toWei(1),
name: '',
description: ''
};
@observable walletType = 'MULTISIG';
@observable errors = {
account: null,
address: null,
owners: null,
required: null,
daylimit: null,
name: null
};
@computed get stage () {
return this.stepsKeys.findIndex((k) => k === this.step);
}
@computed get hasErrors () {
return !!Object.keys(this.errors)
.filter((errorKey) => {
if (this.walletType === 'WATCH') {
return ['address', 'name'].includes(errorKey);
}
return errorKey !== 'address';
})
.find((key) => !!this.errors[key]);
}
@computed get stepsKeys () {
return this.steps.map((s) => s.key);
}
@computed get steps () {
return Object
.keys(STEPS)
.map((key) => {
return {
...STEPS[key],
key
};
})
.filter((step) => {
return (this.walletType !== 'WATCH' || step.key !== 'DEPLOYMENT');
});
}
@computed get waiting () {
this.steps
.map((s, idx) => ({ idx, waiting: s.waiting }))
.filter((s) => s.waiting)
.map((s) => s.idx);
}
constructor (api, accounts) {
this.api = api;
this.step = this.stepsKeys[0];
this.wallet.account = Object.values(accounts)[0].address;
this.validateWallet(this.wallet);
}
@action onTypeChange = (type) => {
this.walletType = type;
this.validateWallet(this.wallet);
}
@action onNext = () => {
const stepIndex = this.stepsKeys.findIndex((k) => k === this.step) + 1;
this.step = this.stepsKeys[stepIndex];
}
@action onChange = (_wallet) => {
const newWallet = Object.assign({}, this.wallet, _wallet);
this.validateWallet(newWallet);
}
@action onAdd = () => {
if (this.hasErrors) {
return;
}
const walletContract = new Contract(this.api, walletAbi).at(this.wallet.address);
return Promise
.all([
WalletsUtils.fetchRequire(walletContract),
WalletsUtils.fetchOwners(walletContract),
WalletsUtils.fetchDailylimit(walletContract)
])
.then(([ require, owners, dailylimit ]) => {
transaction(() => {
this.wallet.owners = owners;
this.wallet.required = require.toNumber();
this.wallet.dailylimit = dailylimit.limit;
});
return this.addWallet(this.wallet);
});
}
@action onCreate = () => {
if (this.hasErrors) {
return;
}
this.step = 'DEPLOYMENT';
const { account, owners, required, daylimit } = this.wallet;
Contracts
.get()
.registry
.lookupAddress(walletLibraryRegKey)
.catch(() => {
return null; // exception when registry is not available
})
.then((address) => {
const walletLibraryAddress = (address || '').replace(/^0x/, '').toLowerCase();
const code = walletLibraryAddress.length && !/^0+$/.test(walletLibraryAddress)
? walletCode.replace(/(_)+WalletLibrary(_)+/g, walletLibraryAddress)
: fullWalletCode;
const options = {
data: code,
from: account
};
return this.api
.newContract(walletAbi)
.deploy(options, [ owners, required, daylimit ], this.onDeploymentState);
})
.then((address) => {
this.deployed = true;
this.wallet.address = address;
return this.addWallet(this.wallet);
})
.catch((error) => {
if (error.code === ERROR_CODES.REQUEST_REJECTED) {
this.rejected = true;
return;
}
console.error('error deploying contract', error);
this.deployError = error;
});
}
@action addWallet = (wallet) => {
const { address, name, description } = wallet;
return Promise
.all([
this.api.parity.setAccountName(address, name),
this.api.parity.setAccountMeta(address, {
abi: walletAbi,
wallet: true,
timestamp: Date.now(),
deleted: false,
description,
name,
tags: ['wallet']
})
])
.then(() => {
this.step = 'INFO';
});
}
onDeploymentState = (error, data) => {
if (error) {
return console.error('createWallet::onDeploymentState', error);
}
switch (data.state) {
case 'estimateGas':
case 'postTransaction':
this.deployState = (
<FormattedMessage
id='createWallet.states.preparing'
defaultMessage='Preparing transaction for network transmission'
/>
);
return;
case 'checkRequest':
this.deployState = (
<FormattedMessage
id='createWallet.states.waitingConfirm'
defaultMessage='Waiting for confirmation of the transaction in the Parity Secure Signer'
/>
);
return;
case 'getTransactionReceipt':
this.deployState = (
<FormattedMessage
id='createWallet.states.waitingReceipt'
defaultMessage='Waiting for the contract deployment transaction receipt'
/>
);
this.txhash = data.txhash;
return;
case 'hasReceipt':
case 'getCode':
this.deployState = (
<FormattedMessage
id='createWallet.states.validatingCode'
defaultMessage='Validating the deployed contract code'
/>
);
return;
case 'completed':
this.deployState = (
<FormattedMessage
id='createWallet.states.completed'
defaultMessage='The contract deployment has been completed'
/>
);
return;
default:
console.error('createWallet::onDeploymentState', 'unknow contract deployment state', data);
return;
}
}
@action validateWallet = (_wallet) => {
const addressValidation = validateAddress(_wallet.address);
const accountValidation = validateAddress(_wallet.account);
const requiredValidation = validateUint(_wallet.required);
const daylimitValidation = validateUint(_wallet.daylimit);
const nameValidation = validateName(_wallet.name);
const errors = {
address: addressValidation.addressError,
account: accountValidation.addressError,
required: requiredValidation.valueError,
daylimit: daylimitValidation.valueError,
name: nameValidation.nameError
};
const wallet = {
..._wallet,
address: addressValidation.address,
account: accountValidation.address,
required: requiredValidation.value,
daylimit: daylimitValidation.value,
name: nameValidation.name
};
transaction(() => {
this.wallet = wallet;
this.errors = errors;
});
}
}
|
examples/js/selection/unselectable-table.js | AllenFang/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
const selectRowProp = {
mode: 'checkbox',
clickToSelect: true,
unselectable: [ 1, 3 ] // give rowkeys for unselectable row
};
export default class UnSelectableTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } selectRow={ selectRowProp }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
local-cli/templates/HelloNavigation/views/MainNavigator.js | cpunion/react-native | 'use strict';
/**
* This is an example React Native app demonstrates ListViews, text input and
* navigation between a few screens.
* https://github.com/facebook/react-native
*/
import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import HomeScreenTabNavigator from './HomeScreenTabNavigator';
import ChatScreen from './chat/ChatScreen';
/**
* Top-level navigator. Renders the application UI.
*/
const MainNavigator = StackNavigator({
Home: {
screen: HomeScreenTabNavigator,
},
Chat: {
screen: ChatScreen,
},
});
export default MainNavigator;
|
webpack/components/accounts/ProfileEditor.js | CDCgov/SDP-Vocabulary-Service | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Modal } from 'react-bootstrap';
import values from 'lodash/values';
import filter from 'lodash/filter';
import clone from 'lodash/clone';
import Errors from '../Errors.js';
import NestedSearchBar from '../NestedSearchBar';
import { surveillanceSystemsProps }from '../../prop-types/surveillance_system_props';
import { surveillanceProgramsProps } from '../../prop-types/surveillance_program_props';
import currentUserProps from '../../prop-types/current_user_props';
// This is an abstract class that is never intended to
// be used directly.
export default class ProfileEditor extends Component {
constructor(props) {
super(props);
this.programSearch = this.programSearch.bind(this);
this.systemSearch = this.systemSearch.bind(this);
}
componentWillReceiveProps(nextProps){
var surveillanceSystems = values(nextProps.surveillanceSystems);
var surveillancePrograms = values(nextProps.surveillancePrograms);
this.setState({surveillanceSystems: surveillanceSystems,
surveillancePrograms: surveillancePrograms,
defaultProgramId: (surveillancePrograms[0] && surveillancePrograms[0].id) || -1,
defaultSystemId: (surveillanceSystems[0] && surveillanceSystems[0].id) || -1
});
}
render() {
return (
<Modal animation={false} show={this.props.show} onHide={this.props.closer} aria-label={this.title()}>
<Modal.Header closeButton>
<Modal.Title componentClass="h1">{this.title()}</Modal.Title>
</Modal.Header>
<Modal.Body>
<form>
<Errors errors={this.state.errors} />
{this.userInfo() }
{this.extraContent()}
<div className="field">
{this.surveillanceProgramsField()}
</div><br/>
<div className="field">
{this.surveillanceSystemsField()}
</div>
</form>
</Modal.Body>
<Modal.Footer>
<button type="button" className="btn btn-default" onClick={this.props.closer}>Close</button>
{this.actionButton()}
</Modal.Footer>
</Modal>
);
}
userInfo(){
if(this.props.disableUserUpdate == 'true'){
return("");
}else{
return this.renderUserInfo();
}
}
renderUserInfo(){
return(
<div>
<div className="form-group">
<label className="control-label" htmlFor="email">E-mail</label>
<input autoFocus="autofocus" placeholder="" className="form-control" type="email"
value={this.state.email} name="email" id="email" onChange={this.handleChange('email')} />
<span className="help-block">Please provide your E-mail</span>
</div>
<div className="row">
<div className="form-group col-sm-6">
<label className="control-label" htmlFor="firstName">First name</label>
<input className="form-control" type="text" name="firstName" id="firstName"
value={this.state.firstName} onChange={this.handleChange('firstName')}/>
</div>
<div className="form-group col-sm-6">
<label className="control-label" htmlFor="lastName">Last name</label>
<input className="form-control" type="text" name="lastName" id="lastName"
value={this.state.lastName} onChange={this.handleChange('lastName')}/>
</div>
</div>
<div className="form-group">
<label className="control-label">Roles</label><br/>
{ this.props.currentUser && this.props.currentUser.admin && <text>Admin, </text>}
{ this.props.currentUser && this.props.currentUser.publisher && <text>Publisher, </text>}
{ this.props.currentUser && this.props.currentUser.author ? (
<text>Author</text>
) : (
<text>Collaborator</text>
)}
</div>
<div className="form-group">
<label className="control-label">Groups</label>
<p>{this.state.groups.length > 0 ? (this.state.groups.map((group, i) => {
if (i+1 < this.state.groups.length) {
return (<text key={group.id}>{group.name}, </text>);
} else {
return (<text key={group.id}>{group.name}</text>);
}
})) : (
<text>No groups, contact admin to be added to a group.</text>
)}</p>
</div>
</div>);
}
programSearch(programSearchTerm){
var surveillancePrograms = values(this.props.surveillancePrograms);
if(programSearchTerm && programSearchTerm.length > 1){
surveillancePrograms = filter(surveillancePrograms, (sp) => sp.name.toLowerCase().includes(programSearchTerm.toLowerCase()) || sp.id === this.state.lastProgramId || sp.id.toString() === this.state.lastProgramId);
}
this.setState({surveillancePrograms: surveillancePrograms, defaultProgramId: (surveillancePrograms[0] && surveillancePrograms[0].id) || -1});
}
systemSearch(systemSearchTerm){
var surveillanceSystems = values(this.props.surveillanceSystems);
if(systemSearchTerm && systemSearchTerm.length > 1){
surveillanceSystems = filter(surveillanceSystems, (ss) => ss.name.toLowerCase().includes(systemSearchTerm.toLowerCase()) || ss.id === this.state.lastSystemId || ss.id.toString() === this.state.lastSystemId);
}
this.setState({surveillanceSystems: surveillanceSystems, defaultSystemId:(surveillanceSystems[0] && surveillanceSystems[0].id) || -1});
}
surveillanceProgramsField() {
return (<div id="search-programs">
<label className="control-label" htmlFor="lastProgramId">Default Surveillance Program</label>
<NestedSearchBar onSearchTermChange={this.programSearch} modelName="Program" />
<select size='5' className="form-control" name="lastProgramId" id="lastProgramId" value={this.state.lastProgramId} onChange={this.handleChange('lastProgramId')} >
{this.state.surveillancePrograms && this.state.surveillancePrograms.map((sp) => {
return <option key={sp.id} value={sp.id}>{sp.name}</option>;
})}
</select>
</div>);
}
surveillanceSystemsField() {
return (<div id="search-systems">
<label className="control-label" htmlFor="lastSystemId">Default Surveillance System</label>
<NestedSearchBar onSearchTermChange={this.systemSearch} modelName="System" />
<select size='5' className="form-control" name="lastSystemId" id="lastSystemId" value={this.state.lastSystemId} onChange={this.handleChange('lastSystemId')} >
{this.state.surveillanceSystems && this.state.surveillanceSystems.map((ss) => {
return <option key={ss.id} value={ss.id}>{ss.name}</option>;
})}
</select>
</div>);
}
profileInformation() {
let profileInformation = clone(this.state);
delete profileInformation.errors;
if (profileInformation.lastSystemId === -1) {
if (profileInformation.defaultSystemId !== -1){
profileInformation.lastSystemId = profileInformation.defaultSystemId;
} else {
delete profileInformation.lastSystemId;
}
}
if (profileInformation.lastProgramId === -1) {
if (profileInformation.defaultProgramId !== -1){
profileInformation.lastProgramId = profileInformation.defaultProgramId;
} else {
delete profileInformation.lastProgramId;
}
}
return profileInformation;
}
handleChange(field) {
return (event) => {
let newState = {};
newState[field] = event.target.value;
this.setState(newState);
};
}
}
ProfileEditor.propTypes = {
closer: PropTypes.func.isRequired,
show: PropTypes.bool.isRequired,
disableUserUpdate:PropTypes.string,
surveillanceSystems: surveillanceSystemsProps,
surveillancePrograms: surveillanceProgramsProps,
currentUser: currentUserProps
};
|
examples/react-refetch/src/index.js | gaearon/react-hot-loader | import React from 'react';
import { render } from 'react-dom';
import App from './App';
const root = document.createElement('div');
document.body.appendChild(root);
render(<App />, root);
|
app/m_components/Hotdot.js | kongchun/BigData-Web | import React from 'react';
import {
Link
} from 'react-router';
import HotdotActions from '../actions/HotdotActions';
import HotdotObjStore from '../stores/HotdotObjStore';
import MyInfoNavbar from './MyInfoNavbar';
import Weixin from './Weixin';
class Hotdot extends React.Component {
constructor(props) {
super(props);
this.state = HotdotObjStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
HotdotActions.getHotdotDatas();
$(".month-search").hide();
$(".navbar-hotdot").on("touchend",function(){
var index = $(this).index();
if(index==0){
//本周
$(".month-search").hide();
$(".week-search").show();
}else{
//本月
$(".month-search").show();
$(".week-search").hide();
}
});
HotdotObjStore.listen(this.onChange);
Weixin.getUrl();
Weixin.weixinReady();
}
componentWillUnmount() {
HotdotObjStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
getUpOrDown(curData,preData,isWeek){
var preDataItem = isWeek ? preData.week:preData.month;
if(preData==false || preData == [] || preDataItem==undefined){
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span>
<span className="badge">{curData.value}</span></span>);
}else{
for(var i = 0;i < preDataItem.length;i++){
if(preDataItem[i].word == curData.word){
if(preDataItem[i].value < curData.value){
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span>
<span className="badge">{curData.value}</span></span>);
}else{
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-down"></span>
<span className="badge" style={{backgroundColor:"#4F81E3"}}>{curData.value}</span></span>);
}
}
}
}
return (<span className="hotdotRight"><span className="glyphicon-trend glyphicon glyphicon-arrow-up"></span>
<span className="badge">{curData.value}</span></span>);
}
render() {
var hotdotData = (this.state.data);
var firstHotData = hotdotData[0];
var preHotData ;
if(hotdotData.length > 7){
preHotData = hotdotData[7];
}else{
preHotData = [];
}
if(firstHotData){
var weekList = firstHotData.week.map((weekItem,i)=>(
<li className="list-group-item" key={i}>
{this.getUpOrDown(weekItem,preHotData,true)}
{weekItem.word}
</li>
));
if(weekList.length==0){
weekList = <div className = "noData">数据还没有准备好,要不去其他页面瞅瞅?</div>
}
var monthList = firstHotData.month.map((monthItem,i)=>(
<li className="list-group-item" key={i}>
{this.getUpOrDown(monthItem,preHotData,false)}
{monthItem.word}
</li>
));
if(monthList.length==0){
monthList = <div className = "noData">Whops,这个页面的数据没有准备好,去其他页面瞅瞅?</div>
}
}else{
var weekList = (<span>正在构建,敬请期待...</span>);
var monthList = (<span>正在构建,敬请期待...</span>);
}
return (<div>
<div className="content-container">
<div className="week-search">
<div className="panel panel-back">
<div className="panel-heading">
<span className="panel-title">本周关键字排行榜</span>
<div className="navbar-key-container">
<span className="navbar-hotdot navbar-week navbar-hotdot-active">本周</span>
<span className="navbar-hotdot navbar-month">本月</span>
</div>
</div>
<div className="panel-body">
<ul className="list-group">
{weekList}
</ul>
</div>
</div>
</div>
<div className="month-search">
<div className="panel panel-back">
<div className="panel-heading">
<span className="panel-title">本月关键字排行榜</span>
<div className="navbar-key-container">
<span className="navbar-hotdot navbar-week">本周</span>
<span className="navbar-hotdot navbar-month navbar-hotdot-active">本月</span>
</div>
</div>
<div className="panel-body">
<ul className="list-group">
{monthList}
</ul>
</div>
</div>
</div>
</div>
</div>);
}
}
export default Hotdot; |
examples/passing-props-to-children/app.js | taion/rrtr | import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link } from 'rrtr'
import './app.css'
const App = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
}
},
addTaco() {
let name = prompt('taco name?')
this.setState({
tacos: this.state.tacos.concat({ name })
})
},
handleRemoveTaco(removedTaco) {
this.setState({
tacos: this.state.tacos.filter(function (taco) {
return taco.name != removedTaco
})
})
this.context.router.push('/')
},
render() {
let links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
)
})
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
)
}
})
const Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name)
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
)
}
})
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'))
|
src/components/docs/breadcrumbs.js | nordsoftware/react-foundation-docs | import React from 'react';
import Playground from 'component-playground';
import {
Inline,
Grid,
Cell,
Breadcrumbs,
BreadcrumbItem,
} from 'react-foundation';
export const BreadcrumbsDocs = () => (
<section className="breadcrumbs-docs">
<Grid>
<Cell large={12}>
<h2>Breadcrumbs</h2>
<Playground codeText={require('raw-loader!../examples/breadcrumbs/basics').default}
scope={{ React, Inline, Breadcrumbs, BreadcrumbItem }}
theme="eiffel"/>
</Cell>
</Grid>
</section>
);
export default BreadcrumbsDocs;
|
src/svg-icons/image/timer-10.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTimer10 = (props) => (
<SvgIcon {...props}>
<path d="M0 7.72V9.4l3-1V18h2V6h-.25L0 7.72zm23.78 6.65c-.14-.28-.35-.53-.63-.74-.28-.21-.61-.39-1.01-.53s-.85-.27-1.35-.38c-.35-.07-.64-.15-.87-.23-.23-.08-.41-.16-.55-.25-.14-.09-.23-.19-.28-.3-.05-.11-.08-.24-.08-.39 0-.14.03-.28.09-.41.06-.13.15-.25.27-.34.12-.1.27-.18.45-.24s.4-.09.64-.09c.25 0 .47.04.66.11.19.07.35.17.48.29.13.12.22.26.29.42.06.16.1.32.1.49h1.95c0-.39-.08-.75-.24-1.09-.16-.34-.39-.63-.69-.88-.3-.25-.66-.44-1.09-.59C21.49 9.07 21 9 20.46 9c-.51 0-.98.07-1.39.21-.41.14-.77.33-1.06.57-.29.24-.51.52-.67.84-.16.32-.23.65-.23 1.01s.08.69.23.96c.15.28.36.52.64.73.27.21.6.38.98.53.38.14.81.26 1.27.36.39.08.71.17.95.26s.43.19.57.29c.13.1.22.22.27.34.05.12.07.25.07.39 0 .32-.13.57-.4.77-.27.2-.66.29-1.17.29-.22 0-.43-.02-.64-.08-.21-.05-.4-.13-.56-.24-.17-.11-.3-.26-.41-.44-.11-.18-.17-.41-.18-.67h-1.89c0 .36.08.71.24 1.05.16.34.39.65.7.93.31.27.69.49 1.15.66.46.17.98.25 1.58.25.53 0 1.01-.06 1.44-.19.43-.13.8-.31 1.11-.54.31-.23.54-.51.71-.83.17-.32.25-.67.25-1.06-.02-.4-.09-.74-.24-1.02zm-9.96-7.32c-.34-.4-.75-.7-1.23-.88-.47-.18-1.01-.27-1.59-.27-.58 0-1.11.09-1.59.27-.48.18-.89.47-1.23.88-.34.41-.6.93-.79 1.59-.18.65-.28 1.45-.28 2.39v1.92c0 .94.09 1.74.28 2.39.19.66.45 1.19.8 1.6.34.41.75.71 1.23.89.48.18 1.01.28 1.59.28.59 0 1.12-.09 1.59-.28.48-.18.88-.48 1.22-.89.34-.41.6-.94.78-1.6.18-.65.28-1.45.28-2.39v-1.92c0-.94-.09-1.74-.28-2.39-.18-.66-.44-1.19-.78-1.59zm-.92 6.17c0 .6-.04 1.11-.12 1.53-.08.42-.2.76-.36 1.02-.16.26-.36.45-.59.57-.23.12-.51.18-.82.18-.3 0-.58-.06-.82-.18s-.44-.31-.6-.57c-.16-.26-.29-.6-.38-1.02-.09-.42-.13-.93-.13-1.53v-2.5c0-.6.04-1.11.13-1.52.09-.41.21-.74.38-1 .16-.25.36-.43.6-.55.24-.11.51-.17.81-.17.31 0 .58.06.81.17.24.11.44.29.6.55.16.25.29.58.37.99.08.41.13.92.13 1.52v2.51z"/>
</SvgIcon>
);
ImageTimer10 = pure(ImageTimer10);
ImageTimer10.displayName = 'ImageTimer10';
export default ImageTimer10;
|
scripts/index.js | doron2402/flux-react-router-example | import React from 'react';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import HashHistory from 'react-router/lib/HashHistory';
import Root from './Root';
const rootEl = document.getElementById('root');
// Use hash location for Github Pages
// but switch to HTML5 history locally.
const history = process.env.NODE_ENV === 'production' ?
new HashHistory() :
new BrowserHistory();
React.render(<Root history={history} />, rootEl);
|
src/parser/deathknight/blood/modules/features/BoneShield.js | FaideWW/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatDuration, formatPercentage } from 'common/format';
import { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import StatisticBox from 'interface/others/StatisticBox';
import StatTracker from 'parser/shared/modules/StatTracker';
import BoneShieldTimesByStacks from './/BoneShieldTimesByStacks';
class BoneShield extends Analyzer {
static dependencies = {
statTracker: StatTracker,
boneShieldTimesByStacks: BoneShieldTimesByStacks,
};
get boneShieldTimesByStack() {
return this.boneShieldTimesByStacks.boneShieldTimesByStacks;
}
get uptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.BONE_SHIELD.id) / this.owner.fightDuration;
}
get uptimeSuggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.95,
average: 0.9,
major: .8,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.uptimeSuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest('Your Bone Shield uptime can be improved. Try to keep it up at all times.')
.icon(SPELLS.BONE_SHIELD.icon)
.actual(`${formatPercentage(actual)}% Bone Shield uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BONE_SHIELD.id} />}
value={`${formatPercentage(this.uptime)} %`}
label="Bone Shield uptime"
>
<table className="table table-condensed">
<thead>
<tr>
<th>Stacks</th>
<th>Time (s)</th>
<th>Time (%)</th>
</tr>
</thead>
<tbody>
{Object.values(this.boneShieldTimesByStack).map((e, i) => (
<tr key={i}>
<th>{i}</th>
<td>{formatDuration(e.reduce((a, b) => a + b, 0) / 1000)}</td>
<td>{formatPercentage(e.reduce((a, b) => a + b, 0) / this.owner.fightDuration)}%</td>
</tr>
))}
</tbody>
</table>
</StatisticBox>
);
}
statisticOrder = STATISTIC_ORDER.CORE(5);
}
export default BoneShield;
|
src/components/navigation.js | inkdropapp/docs | import { StaticQuery, graphql, Link } from 'gatsby'
import { Container } from 'semantic-ui-react'
import React from 'react'
import { GatsbyImage } from 'gatsby-plugin-image'
import './navigation.less'
const Navigation = () => (
<Container className="app--navigation">
<nav className="ui grid">
<div className="row">
<Link to="/" className="app--logo">
<StaticQuery
query={graphql`
query {
placeholderImage: file(
relativePath: { eq: "navbar-logo.png" }
) {
childImageSharp {
gatsbyImageData(layout: FIXED, width: 142, height: 45)
}
}
}
`}
render={data => (
<GatsbyImage
image={data.placeholderImage.childImageSharp.gatsbyImageData}
/>
)}
/>
</Link>
<ul className="app--navbar reset-list un-select">
<li>
<a href="https://inkdrop.app/">Home</a>
</li>
<li>
<a href="https://my.inkdrop.app/plugins">Plugins</a>
</li>
<li className="ui simple dropdown item">
More
<i className="dropdown icon" />
<div className="menu">
<a className="item" href="https://inkdrop.app/pricing">
Pricing
</a>
<Link className="item" to="/faq">
FAQ
</Link>
<div className="divider" />
<a className="item" href="https://forum.inkdrop.app/">
User Forum
</a>
<div className="divider" />
<a className="item" href="https://twitter.com/inkdrop_app">
Twitter
</a>
<a className="item" href="https://medium.com/@inkdrop">
Blog
</a>
</div>
</li>
<li>
<a href="https://my.inkdrop.app/" className="login">
<i className="sign in icon" />
Log in
</a>
</li>
</ul>
</div>
</nav>
</Container>
)
export default Navigation
|
src/components/SitePage/index.js | narendrasoni1989/react-site | import React from 'react'
class SitePage extends React.Component {
render() {
const post = this.props.data.post
return <div dangerouslySetInnerHTML={{ __html: post.html }} />
}
}
export default SitePage
|
es/AppBar/AppBar.js | uplevel-technology/material-ui-next | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
// @inheritedComponent Paper
import React from 'react';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
import { capitalizeFirstLetter } from '../utils/helpers';
import Paper from '../Paper';
export const styles = theme => ({
root: {
display: 'flex',
flexDirection: 'column',
width: '100%',
boxSizing: 'border-box', // Prevent padding issue with the Modal and fixed positioned AppBar.
zIndex: theme.zIndex.appBar,
flexShrink: 0
},
positionFixed: {
position: 'fixed',
top: 0,
left: 'auto',
right: 0
},
positionAbsolute: {
position: 'absolute',
top: 0,
left: 'auto',
right: 0
},
positionStatic: {
position: 'static',
flexShrink: 0
},
colorDefault: {
backgroundColor: theme.palette.background.appBar,
color: theme.palette.getContrastText(theme.palette.background.appBar)
},
colorPrimary: {
backgroundColor: theme.palette.primary[500],
color: theme.palette.getContrastText(theme.palette.primary[500])
},
colorAccent: {
backgroundColor: theme.palette.secondary.A200,
color: theme.palette.getContrastText(theme.palette.secondary.A200)
}
});
class AppBar extends React.Component {
render() {
const _props = this.props,
{ children, classes, className: classNameProp, color, position } = _props,
other = _objectWithoutProperties(_props, ['children', 'classes', 'className', 'color', 'position']);
const className = classNames(classes.root, classes[`position${capitalizeFirstLetter(position)}`], {
[classes[`color${capitalizeFirstLetter(color)}`]]: color !== 'inherit',
'mui-fixed': position === 'fixed' // Useful for the Dialog
}, classNameProp);
return React.createElement(
Paper,
_extends({ square: true, component: 'header', elevation: 4, className: className }, other),
children
);
}
}
AppBar.defaultProps = {
color: 'primary',
position: 'fixed'
};
export default withStyles(styles, { name: 'MuiAppBar' })(AppBar); |
src/routes/privacy/index.js | chaudhryjunaid/chaudhryjunaid.com | /**
* 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 Layout from '../../components/Layout';
import Page from '../../components/Page';
import privacy from './privacy.md';
function action() {
return {
chunks: ['privacy'],
title: privacy.title,
component: (
<Layout>
<Page {...privacy} />
</Layout>
),
};
}
export default action;
|
src/components/components/mobile_list.js | highcoder1/ReactNews | import React from 'react';
import {Row,Col} from 'antd';
import {Link} from 'react-router-dom';
export default class MobileList extends React.Component {
constructor() {
super();
this.state = {
news: ''
};
}
componentWillMount() {
var myFetchOptions = {
method: 'GET'
};
fetch('http://newsapi.gugujiankong.com/Handler.ashx?action=getnews&type=' + this.props.type + '&count=' + this.props.count, myFetchOptions).then(response => response.json()).then(json => this.setState({news: json}));
}
render() {
const {news} = this.state;
const newsList = news.length
? news.map((newsItem, index) => (
<section key={index} className='m_article list-item special_section clearfix'>
<Link to={`details/${newsItem.uniquekey}`}>
<div className='m_article_img'>
<img src={newsItem.thumbnail_pic_s} alt={newsItem.title} />
</div>
<div className='m_article_info'>
<div className='m_article_title'>
<span>{newsItem.title}</span>
</div>
<div className='m_article_desc clearfix'>
<div className='m_article_desc_l'>
<span className='m_article_channel'>{newsItem.realtype}</span>
<span className='m_article_time'>{newsItem.date}</span>
</div>
</div>
</div>
</Link>
</section>
))
: '没有加载到任何新闻';
return (
<div>
<Row>
<Col span={24}>
{newsList}
</Col>
</Row>
</div>
);
}
}
|
src/components/hand-signal/hand-signal.js | greaveselliott/rock-paper-scissors | import React from 'react'
import './hand-signal.scss';
import Icon from '../icon';
import PropTypes from 'prop-types';
const HandSignal = ({name, className, modifier, click_handler}) => {
return (
<figure onClick={click_handler} className={`${className} m-hand-signal${modifier}`}>
<div className="m-hand-signal__face">
<Icon className="m-hand-signal__icon" icon={name}/>
<figcaption className="m-hand-signal__name">{name}</figcaption>
</div>
<div className="m-hand-signal__back">
<Icon className="m-hand-signal__icon--small" icon="rock"/>
<Icon className="m-hand-signal__icon--small" icon="paper"/>
<Icon className="m-hand-signal__icon--small" icon="scissors"/>
</div>
</figure>
);
};
HandSignal.propTypes = {
name: PropTypes.string.isRequired,
modifier: PropTypes.string
}
export default HandSignal; |
server/sonar-web/src/main/js/components/controls/DateInput.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import $ from 'jquery';
import React from 'react';
import { pick } from 'lodash';
import './styles.css';
export default class DateInput extends React.Component {
static propTypes = {
value: React.PropTypes.string,
format: React.PropTypes.string,
name: React.PropTypes.string,
placeholder: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired
};
static defaultProps = {
value: '',
format: 'yy-mm-dd'
};
componentDidMount() {
this.attachDatePicker();
}
componentWillReceiveProps(nextProps) {
this.refs.input.value = nextProps.value;
}
handleChange() {
const { value } = this.refs.input;
this.props.onChange(value);
}
attachDatePicker() {
const opts = {
dateFormat: this.props.format,
changeMonth: true,
changeYear: true,
onSelect: this.handleChange.bind(this)
};
if ($.fn && $.fn.datepicker) {
$(this.refs.input).datepicker(opts);
}
}
render() {
const inputProps = pick(this.props, ['placeholder', 'name']);
/* eslint max-len: 0 */
return (
<span className="date-input-control">
<input
className="date-input-control-input"
ref="input"
type="text"
initialValue={this.props.value}
readOnly={true}
{...inputProps}
/>
<span className="date-input-control-icon">
<svg width="14" height="14" viewBox="0 0 16 16">
<path
d="M5.5 6h2v2h-2V6zm3 0h2v2h-2V6zm3 0h2v2h-2V6zm-9 6h2v2h-2v-2zm3 0h2v2h-2v-2zm3 0h2v2h-2v-2zm-3-3h2v2h-2V9zm3 0h2v2h-2V9zm3 0h2v2h-2V9zm-9 0h2v2h-2V9zm11-9v1h-2V0h-7v1h-2V0h-2v16h15V0h-2zm1 15h-13V4h13v11z"
/>
</svg>
</span>
</span>
);
}
}
|
src/view/header.js | alexreardon/fullon-markdown | import React, { Component } from 'react';
import injectStyles from 'react-jss';
import ReactPlayer from 'react-player';
import Modal from 'react-modal';
import headerImage from '../img/header-image_860x391.jpg';
import logo from '../img/full-on-2020-logo.svg'
import config from '../../config';
import { button, gutters, contentWidth } from './global-style';
import { relative } from 'path';
const modalStyles = {
content: {
backgroundColor: 'black',
border: 'none',
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
},
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'black',
},
};
const style = {
container: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
backgroundSize: 'contain',
},
logo: {
position: 'relative',
maxWidth: contentWidth,
width: '100%',
marginBottom: gutters.medium,
marginTop: 0,
overflow: 'hidden'
},
button,
closeModalButton: {
...button,
display: 'block',
marginLeft: 'auto',
marginRight: 'auto',
marginTop: gutters.large * 2,
},
};
@injectStyles(style)
class Header extends Component {
state = {
isModalOpen: false,
};
closeModal = () => {
this.setState({
isModalOpen: false,
});
};
openModal = () => {
this.setState({
isModalOpen: true,
});
};
render() {
const {sheet: {classes}} = this.props;
const {isModalOpen} = this.state;
return (
<div className={classes.container}>
<div className={classes.logo}>
<img
src={headerImage}
alt='Full On 2020 Youth Camp'
style={{
filter: 'blur(3px)',
paddingTop: '0px',
paddingBottom: '0px',
transform: 'scale(1.1)'
}}
/>
<img
src={logo}
style={{
position: 'absolute',
paddingTop: '0px',
paddingBottom: '0px',
top: '0px',
left: '0px',
}}
/>
</div>
<Modal
isOpen={isModalOpen}
onRequestClose={this.closeModal}
style={modalStyles}
>
<ReactPlayer
url={config.trailerUrl}
playing
onEnded={this.closeModal}
width={800}
height={450}
style={{maxWidth: '100vw'}}
/>
<button
className={classes.closeModalButton}
onClick={this.closeModal}
>
Close Video
</button>
</Modal>
<button
onClick={this.openModal}
className={classes.button}
>
What is Full On? (Video)
</button>
</div>
);
}
}
export default Header;
|
clientwebapp/src/index.js | jcocchi/IoTPlantWatering | import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App'
import registerServiceWorker from './registerServiceWorker'
import './css/index.css'
ReactDOM.render(<App />, document.getElementById('root'))
registerServiceWorker()
|
docs/src/app/components/pages/components/Dialog/Page.js | frnk94/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import dialogReadmeText from './README';
import DialogExampleSimple from './ExampleSimple';
import dialogExampleSimpleCode from '!raw!./ExampleSimple';
import DialogExampleModal from './ExampleModal';
import dialogExampleModalCode from '!raw!./ExampleModal';
import DialogExampleCustomWidth from './ExampleCustomWidth';
import dialogExampleCustomWidthCode from '!raw!./ExampleCustomWidth';
import DialogExampleDialogDatePicker from './ExampleDialogDatePicker';
import dialogExampleDialogDatePickerCode from '!raw!./ExampleDialogDatePicker';
import DialogExampleScrollable from './ExampleScrollable';
import DialogExampleScrollableCode from '!raw!./ExampleScrollable';
import DialogExampleAlert from './ExampleAlert';
import DialogExampleAlertCode from '!raw!./ExampleAlert';
import dialogCode from '!raw!material-ui/Dialog/Dialog';
const DialogPage = () => (
<div>
<Title render={(previousTitle) => `Dialog - ${previousTitle}`} />
<MarkdownElement text={dialogReadmeText} />
<CodeExample
title="Simple dialog"
code={dialogExampleSimpleCode}
>
<DialogExampleSimple />
</CodeExample>
<CodeExample
title="Modal dialog"
code={dialogExampleModalCode}
>
<DialogExampleModal />
</CodeExample>
<CodeExample
title="Styled dialog"
code={dialogExampleCustomWidthCode}
>
<DialogExampleCustomWidth />
</CodeExample>
<CodeExample
title="Nested dialogs"
code={dialogExampleDialogDatePickerCode}
>
<DialogExampleDialogDatePicker />
</CodeExample>
<CodeExample
title="Scrollable dialog"
code={DialogExampleScrollableCode}
>
<DialogExampleScrollable />
</CodeExample>
<CodeExample
title="Alert dialog"
code={DialogExampleAlertCode}
>
<DialogExampleAlert />
</CodeExample>
<PropTypeDescription code={dialogCode} />
</div>
);
export default DialogPage;
|
examples/Overlay.js | BespokeInsights/react-overlays | import React from 'react';
import Overlay from 'react-overlays/Overlay';
import Button from 'react-bootstrap/lib/Button';
// Styles Mostly from Bootstrap
const TooltipStyle = {
position: 'absolute',
padding: '0 5px'
};
const TooltipInnerStyle = {
padding: '3px 8px',
color: '#fff',
textAlign: 'center',
borderRadius: 3,
backgroundColor: '#000',
opacity: .75
};
const TooltipArrowStyle = {
position: 'absolute',
width: 0, height: 0,
borderRightColor: 'transparent',
borderLeftColor: 'transparent',
borderTopColor: 'transparent',
borderBottomColor: 'transparent',
borderStyle: 'solid',
opacity: .75
};
const PlacementStyles = {
left: {
tooltip: { marginLeft: -3, padding: '0 5px' },
arrow: {
right: 0, marginTop: -5, borderWidth: '5px 0 5px 5px', borderLeftColor: '#000'
}
},
right: {
tooltip: { marginRight: 3, padding: '0 5px' },
arrow: { left: 0, marginTop: -5, borderWidth: '5px 5px 5px 0', borderRightColor: '#000' }
},
top: {
tooltip: { marginTop: -3, padding: '5px 0' },
arrow: { bottom: 0, marginLeft: -5, borderWidth: '5px 5px 0', borderTopColor: '#000' }
},
bottom: {
tooltip: { marginBottom: 3, padding: '5px 0' },
arrow: { top: 0, marginLeft: -5, borderWidth: '0 5px 5px', borderBottomColor: '#000' }
}
};
class ToolTip {
render(){
let placementStyle = PlacementStyles[this.props.placement];
let {
style,
arrowOffsetLeft: left = placementStyle.arrow.left,
arrowOffsetTop: top = placementStyle.arrow.top,
...props } = this.props;
return (
<div style={{...TooltipStyle, ...placementStyle.tooltip, ...style}}>
<div style={{...TooltipArrowStyle, ...placementStyle.arrow, left, top }}/>
<div style={TooltipInnerStyle}>
{ props.children }
</div>
</div>
);
}
}
const OverlayExample = React.createClass({
getInitialState(){
return { show: false };
},
toggle(){
let show = this.state.show;
let placements = ['left', 'top', 'right', 'bottom'];
let placement = this.state.placement;
placement = placements[placements.indexOf(placement) + 1];
if (!show) {
show = true;
placement = placements[0];
}
else if (!placement) {
show = false;
}
return this.setState({ show, placement });
},
render(){
return (
<div className='overlay-example'>
<Button bsStyle='primary' ref='target' onClick={this.toggle}>
I am an Overlay target
</Button>
<p>
keep clicking to see the overlay placement change
</p>
<Overlay
show={this.state.show}
onHide={() => this.setState({ show: false })}
placement={this.state.placement}
container={this}
target={ props => React.findDOMNode(this.refs.target)}
>
<ToolTip>
I'm placed to the: <strong>{this.state.placement}</strong>
</ToolTip>
</Overlay>
</div>
);
}
});
export default OverlayExample;
|
js/components/nutrientList.js | codeocelot/soylent-industries | import React from 'react'
import NutrientStore from '../stores/nutrientStore'
import {Cell} from 'react-pure'
import {Table} from 'elemental'
import Nutrient from './nutrient'
import constants from '../constants/constants'
export default class NutrientList extends React.Component{
constructor(props){
super(props);
this.state = {nutrients:[]}
}
componentDidMount = () =>{
NutrientStore.listen((type,data)=>{
switch(type){
case constants.ALL_NUTRIENTS:
this.setState({nutrients:data})
break;
}
})
}
render(){
let nutrients = this.state.nutrients.map((n,i)=>{
return(<Nutrient {...n} key={i}/>)
})
return(
<Table style={{width:"100%"}}>
<colgroup>
<col width="70%" />
<col width=""/>
<col width="15%"/>
</colgroup>
<thead>
<tr>
<th>Nutrient</th>
<th>Quantity</th>
<th>Recommended Amount</th>
</tr>
</thead>
<tbody>
{nutrients}
</tbody>
</Table>
)
}
}
|
example/app.js | georgeOsdDev/react-ellipsis-text | 'use strict';
import React from 'react';
import ReactDom from 'react-dom';
import EllipsisText from '../lib/components/EllipsisText';
//allow react dev tools work
window.React = React;
const styles = {
title: {
marginTop: '40px'
},
content: {
padding: '10px'
},
removed:{
marginTop: '40px',
textDecoration: 'line-through'
}
}
class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h2 style={styles.title}>Simple ellipsify</h2>
<p>text='1234567890'</p>
<p>length= -1 ~ 11</p>
<div style={styles.content}>
<EllipsisText text={'1234567890'} length={-1} /> <br/>
<EllipsisText text={'1234567890'} length={0} /> <br/>
<EllipsisText text={'1234567890'} length={1} /> <br/>
<EllipsisText text={'1234567890'} length={2} /> <br/>
<EllipsisText text={'1234567890'} length={3} /> <br/>
<EllipsisText text={'1234567890'} length={4} /> <br/>
<EllipsisText text={'1234567890'} length={5} /> <br/>
<EllipsisText text={'1234567890'} length={6} /> <br/>
<EllipsisText text={'1234567890'} length={7} /> <br/>
<EllipsisText text={'1234567890'} length={8} /> <br/>
<EllipsisText text={'1234567890'} length={9} /> <br/>
<EllipsisText text={'1234567890'} length={10} /> <br/>
<EllipsisText text={'1234567890'} length={11} /> <br/>
</div>
<h2 style={styles.title}>Custom tail</h2>
<div style={styles.content}>
<EllipsisText text={'1234567890'} length={8} tailClassName={'myTail'}/> <br/>
<EllipsisText text={'1234567890'} length={8} tail={'~~~'}/> <br/>
</div>
<h2 style={styles.removed}>Tooltip</h2>
<div style={styles.content}>
Tooltip feature is removed from V1.0. You should implement it by your self with <code>onMouseEnter</code> and <code>onMouseLeave</code>
</div>
<h2 style={styles.removed}>Tooltip with Clipboard copy</h2>
<div style={styles.content}>
Clipboard feature is removed from V1.0. You should implement it by your self with <code>onClick</code>
</div>
</div>
)
}
};
ReactDom.render(<App/>, document.getElementById('out'));
|
src/routes.js | raulmatei/frux-table-test | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Root from './root';
import NotFound from './not-found';
import TableView from './components/table-view';
export default (
<Route path='/' component={Root}>
<IndexRoute component={TableView}/>
<Route path='show' component={TableView}/>
<Route path='*' component={NotFound}/>
</Route>
); |
server/sonar-web/src/main/js/apps/permission-templates/components/Defaults.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { sortBy } from 'lodash';
import { translate } from '../../../helpers/l10n';
import { PermissionTemplateType } from '../propTypes';
export default class Defaults extends React.Component {
static propTypes = {
organization: React.PropTypes.object,
permissionTemplate: PermissionTemplateType.isRequired
};
render() {
const qualifiersToDisplay = this.props.organization && !this.props.organization.isDefault
? ['TRK']
: this.props.permissionTemplate.defaultFor;
const qualifiers = sortBy(qualifiersToDisplay)
.map(qualifier => translate('qualifiers', qualifier))
.join(', ');
return (
<div>
<span className="badge spacer-right">
{translate('default')} for {qualifiers}
</span>
</div>
);
}
}
|
client/app.js | Eschocolat/Pinbook | import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import { AppContainer as HotReloader } from 'react-hot-loader';
import routes from './routes';
const appElement = document.getElementById('app');
const root = (
<Router history={browserHistory}>
{routes}
</Router>
);
render(
<HotReloader>{root}</HotReloader>,
appElement
);
const renderRoot = () => {
const routes = require('./routes').default;
render(
<HotReloader>
<Router history={browserHistory}>
{routes}
</Router>
</HotReloader>,
appElement)
};
if (module.hot) {
module.hot.accept('./routes', renderRoot);
}
|
app/pages/index.js | booee/nextfire | import React from 'react'
export default class extends React.Component {
render() {
return (
<div>Hello, World!</div>
)
}
}
|
UI/Charts/LineChart.js | Datasilk/Dedicate | import React from 'react';
import {View, ScrollView, StyleSheet, Dimensions, TouchableWithoutFeedback, Animated} from 'react-native';
import Text from 'text/Text';
import AppStyles from 'dedicate/AppStyles';
import {Svg, Line, Polyline, Circle} from 'react-native-svg';
import IconSwipeArrow from 'icons/IconSwipeArrow';
import DbRecords from 'db/DbRecords';
import ChartFilter from 'utility/ChartFilter'
import ToNumber from 'utility/ToNumber';
import ProperNumber from 'utility/ProperNumber';
import GetDate from 'utility/Date';
export default class LineChart extends React.Component{
constructor(props){
super(props);
let date = GetDate();
const days = this.props.days || 14;
const {width} = Dimensions.get('window');
this.width = width;
this.state = {
datestart: this.props.dateStart || date.setDate(date.getDate() - days),
days: days,
chart:this.props.chart || {name:'Unknown'},
records:this.props.records || [],
chartinfo:null,
height: this.props.height || 120,
padding: this.props.padding || 30,
lines:[],
line1:{min:'', max:''},
line2:{min:'', max:''},
minmax:[],
view:-1, //-1 = all
dots:[],
dotsminmax:[],
legend:[],
showLegendTaskNames: this.props.showLegendTaskNames || false,
update:this.props.update || Math.round(999 * Math.random())
}
//bind methods
this.onLayout = this.onLayout.bind(this);
this.getChart = this.getChart.bind(this);
this.getPoints = this.getPoints.bind(this);
this.getLine = this.getLine.bind(this);
this.getDots = this.getDots.bind(this);
this.getLegendLine = this.getLegendLine.bind(this);
this.getLegendDot = this.getLegendDot.bind(this);
this.onPressChart = this.onPressChart.bind(this);
}
componentWillMount(){
if(this.state.records.length == 0){
//get records for chart
this.setState({records:this.getRecords()}, () => {
this.getChart();
});
}else{
this.getChart();
}
}
componentDidUpdate(){
if(this.props.update != null && this.state.update != this.props.update){
const days = this.props.days || 14;
let date = GetDate();
date = this.props.dateStart || date.setDate(date.getDate() - days);
this.setState({
datestart: date,
days: days,
chart: this.props.chart || {name:'Unknown'},
records: this.props.records || this.getRecords(),
legend:[],
chartinfo: null,
width: this.props.width || 300,
height: this.props.height || 120,
padding: this.props.padding || 30,
update: this.props.update
}, () =>{
this.getChart();
});
}
}
onLayout(e){
const w = e.nativeEvent.layout.width;
if(this.width != w){
this.width = w;
this.getChart();
}
}
getRecords(){
const dbRecords = new DbRecords();
const chart = this.state.chart;
let records = [];
for(let x = 0; x < chart.sources.length; x++){
let source = chart.sources[x];
let filtered = null;
if(source.filters != null && source.filters.length > 0){
filtered = ChartFilter(source.filters);
}
records.push(dbRecords.GetList({taskId:source.taskId, filtered:filtered}));
}
return records;
}
// Generate Chart //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getChart(){
let info = [];
let lines = [];
let chartinfo = this.state.chartinfo || null;
let dots = [];
let minmax = this.state.minmax || [];
let dotsminmax = this.state.dotsminmax || [];
let legend = this.state.legend || [];
if(chartinfo == null){
//generate chart information from database (if neccessary)
let legends = [];
let legendIds = [];
let offsetType = '';
switch(this.state.chart.offset){
case 1: offsetType = 'Day'; break;
case 2: offsetType = 'Week'; break;
case 3: offsetType = 'Month'; break;
case 4: offsetType = 'Year'; break;
}
chartinfo = {lines:[], dots:[]};
for(let x = 0; x < this.state.records.length; x++){
let source = this.state.chart.sources[x];
let records = this.state.records[x];
let input = source.input;
if(input != null){
if(legendIds.indexOf(source.taskId) < 0){
//create legend for new task
legendIds.push(source.taskId);
legends.push({name:source.task.name, items:[]});
}
let legendIndex = legendIds.indexOf(source.taskId);
if(input.type == 0 || input.type == 5 || input.type == 7){ //number
let color = this.getColor(source.color);
let minmaxExtra = '';
if(source.offset && source.offset > 0){
minmaxExtra = ' (-' + source.offset + ' ' + offsetType + (source.offset > 1 ? 's' : '') + ')';
}
info = this.getPoints(records, input, source);
info.color = color;
chartinfo.lines.push(info);
legends[legendIndex].items.push(this.getLegendLine((this.state.showLegendTaskNames ? source.task.name + ': ' : '') + input.name, color));
if(input.type == 5){
//currency
const currency = Currencies.filter(c => c.value == input.option)[0];
minmax.push({
name:source.task.name + ': ' + input.name + minmaxExtra,
min:currency.symbol + ProperNumber(info.min.toFixed(2)),
max:currency.symbol + ProperNumber(info.max.toFixed(2))
});
} else{
//number
minmax.push({name:source.task.name + ': ' + input.name + minmaxExtra, min:info.min, max:info.max});
}
}else if(input.type == 6){ //yes/no
let color = this.getColor(source.color);
chartinfo.dots.push(this.getDots(records, input, color));
legends[legendIndex].items.push(this.getLegendDot((this.state.showLegendTaskNames ? source.task.name + ': ' : '') + input.name, color));
dotsminmax.push({name:source.task.name + ': ' + input.name, min:'', max:''});
}
}
}
for(let x = 0; x < legends.length; x++){
legend.push(
<View key={'legend' + x} style={[this.styles.legendContainer, {width:this.width, height:this.state.height + 5, padding:this.state.padding}]}>
{legends[x].items}
<Text style={this.styles.legendName}>{legends[x].name}</Text>
<View style={this.styles.legendArrows}>
{x < legends.length - 1 &&
<IconSwipeArrow direction="next" size="xxsmall" opacity={0.15}/>
}
</View>
</View>
);
}
}
//get lines based on cached chart info
for(let x = 0; x < chartinfo.lines.length; x++){
const info = chartinfo.lines[x];
lines.push({line:this.getLine(info.points, info.min, info.max, x, info.color), show:true, opacity: new Animated.Value(1), x: new Animated.Value(0), y: new Animated.Value(0)});
}
//get dots based on cached chart info
for(let x = 0; x < chartinfo.dots.length; x++){
const info = chartinfo.dots[x];
dots.push({dot:info, show:true, opacity: new Animated.Value(1)});
}
this.setState({chartinfo:chartinfo, lines:lines, dots:dots, legend:legend, line1:minmax[0] || {min:'', max:''}, minmax:minmax,
line2:minmax.length > 1 ? minmax[1] : {min:'', max:''}, dotsminmax:dotsminmax});
}
// Lines //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getPoints = (records, input, source) => {
let min = 999999;
let max = 0;
let points = [];
let days = this.state.days;
let offsetType = this.state.chart.offset || 0;
let datestart = GetDate(this.state.datestart);
switch(offsetType){
case 1: //day
datestart.setDate(datestart.getDate() - (source.offset || 0));
break;
case 2: //week
datestart.setDate(datestart.getDate() - ((source.offset || 0) * 7));
break;
case 3: //month
datestart.setMonth(datestart.getMonth() - (source.offset || 0));
break;
case 4: //year
datestart.setYear(datestart.getYear() - (source.offset || 0));
break;
}
let curry = 0;
//find first record for first day
for(let y = 0; y < records.length; y++){
let rec = records[y];
if(rec.datestart > datestart){
curry = y;
}else{
break;
}
}
//get totals for each day
for(let x = 0; x <= days; x++){
let count = 0;
let date = GetDate(datestart);
date.setDate(date.getDate() + x);
for(let y = curry; y >= 0; y--){
let rec = records[y];
if(rec == null || rec.datestart == null){continue;}
if(DatesMatch(date, GetDate(rec.datestart))){
let i = rec.inputs.map(a => a.inputId).indexOf(input.id);
if(rec.inputs.length > i && i > -1){
if(rec.inputs[i].number != null){
count += rec.inputs[i].number;
}
}
}else{
curry = y;
break;
}
}
points.push(ToNumber(count, 2));
}
//check totals for min & max
for(let x = 0; x < points.length; x++){
if(points[x] < min){ min = points[x];}
if(points[x] > max){ max = points[x];}
}
if(max == 0){max = 1;}
return {points:points, min:ToNumber(min, 2), max:ToNumber(max, 2)};
}
getLine = (points, min, max, index, stroke) => {
//draw lines
let lines = [];
let days = this.state.days;
let width = this.width - this.state.padding - AppStyles.paddingLarge;
let height = this.state.height - 70;
for(let x = 0; x < points.length; x++){
lines.push(Math.round(((width / days) * x) + 10) + ',' + Math.round((height + 20) - ((height) / (max - min)) * (points[x] - min)));
}
return (
<Svg width={width + 20} height={height + 30}>
<Polyline key={'line'}
stroke={stroke}
strokeWidth="5"
fill="none"
points={lines.join(' ')}
></Polyline>
</Svg>
);
}
// Dots //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getDots = (records, input, color) => {
let dots = [];
let days = this.state.days;
let width = this.width - this.state.padding - AppStyles.paddingLarge;
let height = this.state.height - 70;
for(let x = 1; x <= days; x++){
let date = GetDate();
date = GetDate(date.setDate(date.getDate() - (days - x)));
for(let y = 0; y < records.length; y++){
const rec = records[y];
if(DatesMatch(date, GetDate(rec.datestart))){
let i = rec.inputs.map(a => a.inputId).indexOf(input.id);
if(i >= 0){
if(rec.inputs[i].number != null){
if(rec.inputs[i].type == 6 && rec.inputs[i].number == 1){
dots.push(
<Circle key={'dot' + x}
cx={Math.round(((width / days) * x) + 10)}
cy={height + 20}
r={5}
fill={color}
></Circle>
)
}
}
}
}
}
}
return (<Svg width={width + 20} height={height + 30}>{dots}</Svg>);
}
// Legend //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getLegendLine(name, color){
return (
<View style={[this.styles.legendItem, this.state.showLegendTaskNames ? {flexDirection:'column'} : {}]} key={name}>
<View style={this.styles.legendItemIcon}>
<Svg width="20" height="10">
<Line x1="0" x2="20" y1="4" y2="4" strokeWidth="5" stroke={color}></Line>
</Svg>
</View>
<View style={this.styles.legendItemLabel}>
<Text style={this.styles.legendItemText}>{name}</Text>
</View>
</View>
);
}
getLegendDot(name, color){
return (
<View style={[this.styles.legendItem, this.state.showLegendTaskNames ? {flexDirection:'column'} : {}]} key={name}>
<View style={this.styles.legendItemIcon}>
<Svg width="20" height="10">
<Circle cx={10} cy={5} r={5} fill={color}></Circle>
</Svg>
</View>
<View style={this.styles.legendItemLabel}>
<Text style={this.styles.legendItemText}>{name}</Text>
</View>
</View>
);
}
// Line Color //////////////////////////////////////////////////////////////////////////////////////////////////////////////
getColor(index){
switch(index){
case 1: default:
return AppStyles.chartLine1Stroke;
case 2:
return AppStyles.chartLine2Stroke;
case 3:
return AppStyles.chartLine3Stroke;
case 4:
return AppStyles.chartLine4Stroke;
case 5:
return AppStyles.chartLine5Stroke;
case 6:
return AppStyles.chartLine6Stroke;
case 7:
return AppStyles.chartLine7Stroke;
case 8:
return AppStyles.chartLine8Stroke;
}
}
// Change Chart View //////////////////////////////////////////////////////////////////////////////////////////////////////////////
onPressChart(event){
let view = this.state.view;
let inc = 1;
let lines = this.state.lines;
let dots = this.state.dots;
let line1 = this.state.line1;
let line2 = this.state.line2;
let minmax = this.state.minmax;
let dotsminmax = this.state.dotsminmax;
//if(touches >= 2){
// inc = -1;
//}
if(view+inc == lines.length + dots.length || view+inc == -1){
view = -1;
for(let x = 0; x < lines.length; x++){
if(lines[x].show == false){
lines[x].show = true;
Animated.timing(
this.state.lines[x].opacity,
{
toValue:1,
duration:300
}
).start();
}
}
if(this.state.dots.length > 0){
dots[0].show = true;
Animated.timing(
this.state.dots[0].opacity,
{
toValue:1,
duration:300
}
).start();
}
line1 = minmax[0];
if(minmax.length > 1){
line2 = minmax[1];
}else{
line2 = {min:'', max:''};
}
}else{
view = view + inc;
if(view == -2){
view = (lines.length - 1) + dots.length;
}
for(let x = 0; x < lines.length; x++){
if(lines[x].show == true){
if(x != view){
//fade out lines
lines[x].show = false;
Animated.timing(
this.state.lines[x].opacity,
{
toValue:0,
duration:300
}
).start();
}
}else{
if(x == view){
//fade in line
lines[x].show = true;
Animated.timing(
this.state.lines[x].opacity,
{
toValue:1,
duration:300
}
).start();
}
}
}
if(view < lines.length){
//hide dot
line1 = minmax[view];
line2 = {min:'', max:minmax[view].name};
if(this.state.dots.length > 0){
Animated.timing(
this.state.dots[0].opacity,
{
toValue:0,
duration:300
}
).start();
}
}else{
//show dot instead of line
Animated.timing(
this.state.dots[0].opacity,
{
toValue:1,
duration:300
}
).start();
line1 = dotsminmax[0];
line2 = {min:'', max:dotsminmax[0].name};
}
}
this.setState({view:view, lines:lines, line1:line1, line2:line2});
}
render(){
return (
<ScrollView onLayout={this.onLayout} horizontal={true} pagingEnabled={true} showsHorizontalScrollIndicator={false}>
<View style={[this.styles.chartContainer, {width:this.width, paddingHorizontal:this.state.padding - 5}]}>
<TouchableWithoutFeedback onPress={this.onPressChart}>
<View style={{height:this.state.height, width:this.width - this.state.padding}}>
<View style={this.styles.chartLine1MinMax}>
<Text style={[this.styles.chartLabel, this.styles.chartLineMax]}>{this.state.line1.max}</Text>
<Text style={[this.styles.chartLabel, this.styles.chartLineMin]}>{this.state.line1.min}</Text>
</View>
<View style={this.styles.chartLine2MinMax}>
<Text style={[this.styles.chartLabel, this.styles.chartLineMax, this.styles.chartLabelEnd]}>{this.state.line2.max}</Text>
<Text style={[this.styles.chartLabel, this.styles.chartLineMin, this.styles.chartLabelEnd]}>{this.state.line2.min}</Text>
</View>
<View style={[this.styles.chart]}>
{this.state.lines.map(line => { return (
<Animated.View
key={line.name+(Math.round(9999 * Math.random()))}
style={[this.styles.chartLine, {opacity:line.opacity, left:line.x, top:line.y}]}
>{line.line}</Animated.View>
);}).reverse()}
{this.state.dots.map(dot => { return (
<Animated.View key='dots' style={[this.styles.chartDots, {opacity:dot.opacity}]}>{dot.dot}</Animated.View>
);})}
</View>
<Text style={this.styles.chartName}>{this.state.chart.name}</Text>
</View>
</TouchableWithoutFeedback>
</View>
{this.props.extraPage &&
<View style={[{width:this.width, height:this.state.height + 5, padding:this.state.padding}]}>
{this.props.extraPage}
<Text style={this.styles.legendName}>{this.state.chart.name}</Text>
<View style={this.styles.legendArrows}>
<IconSwipeArrow direction="next" size="xxsmall" opacity={0.15}/>
</View>
</View>
}
{this.state.legend}
</ScrollView>
);
}
styles = StyleSheet.create({
chartContainer: {paddingBottom:20, paddingTop:5, width:'100%'},
chart:{position:'absolute', width:'100%', height:'100%', top:15, left:-5},
chartName: {position:'absolute', bottom:0, fontSize:20, width:'100%', left:-10, textAlign:'center'},
chartLine:{position:'absolute', height:'100%'},
chartLineMax:{position:'absolute', top:0},
chartLineMin:{position:'absolute', bottom:0},
chartLine1MinMax:{position:'absolute', height:'100%'},
chartLine2MinMax:{position:'absolute', height:'100%', right:20, alignItems:'flex-end'},
chartLabel:{fontSize:20, opacity:0.5},
chartLabelEnd:{textAlign:'right'},
chartDots:{position:'absolute'},
legendContainer:{flexDirection:'row', flexWrap:'wrap'},
legendItem:{flex:1, alignSelf:'flex-start', flexDirection:'row'},
legendItemIcon:{paddingRight:10, paddingTop:7, height:20},
legendItemLabel:{},
legendItemText:{fontSize:17},
legendName:{position:'absolute', width:'100%', bottom:0, fontSize:20, left:30, textAlign:'center', alignSelf:'center'},
legendArrows:{position:'absolute', width:'100%', bottom:0, flexDirection:'row', justifyContent:'flex-end', left:30},
legendArrowBack:{opacity:0.3},
legendArrowNext:{opacity:0.3}
});
} |
actor-apps/app-web/src/app/index.js | JeeLiu/actor-platform | import crosstab from 'crosstab';
import React from 'react';
import Router from 'react-router';
import Raven from 'utils/Raven'; // eslint-disable-line
import injectTapEventPlugin from 'react-tap-event-plugin';
import Deactivated from 'components/Deactivated.react';
import Login from 'components/Login.react';
import Main from 'components/Main.react';
import JoinGroup from 'components/JoinGroup.react';
import LoginStore from 'stores/LoginStore';
import LoginActionCreators from 'actions/LoginActionCreators';
//import AppCache from 'utils/AppCache'; // eslint-disable-line
import Pace from 'pace';
Pace.start({
ajax: false,
restartOnRequestAfter: false,
restartOnPushState: false
});
const DefaultRoute = Router.DefaultRoute;
const Route = Router.Route;
const RouteHandler = Router.RouteHandler;
const ActorInitEvent = 'concurrentActorInit';
if (crosstab.supported) {
crosstab.on(ActorInitEvent, (msg) => {
if (msg.origin !== crosstab.id && window.location.hash !== '#/deactivated') {
window.location.assign('#/deactivated');
window.location.reload();
}
});
}
const initReact = () => {
if (window.location.hash !== '#/deactivated') {
if (crosstab.supported) {
crosstab.broadcast(ActorInitEvent, {});
}
if (location.pathname === '/app/index.html') {
window.messenger = new window.actor.ActorApp(['ws://' + location.hostname + ':9080/']);
} else {
window.messenger = new window.actor.ActorApp();
}
}
const App = React.createClass({
render() {
return <RouteHandler/>;
}
});
const routes = (
<Route handler={App} name="app" path="/">
<Route handler={Main} name="main" path="/"/>
<Route handler={JoinGroup} name="join" path="/join/:token"/>
<Route handler={Login} name="login" path="/auth"/>
<Route handler={Deactivated} name="deactivated" path="/deactivated"/>
<DefaultRoute handler={Main}/>
</Route>
);
const router = Router.run(routes, Router.HashLocation, function (Handler) {
injectTapEventPlugin();
React.render(<Handler/>, document.getElementById('actor-web-app'));
});
if (window.location.hash !== '#/deactivated') {
if (LoginStore.isLoggedIn()) {
LoginActionCreators.setLoggedIn(router, {redirect: false});
}
}
};
window.jsAppLoaded = () => {
setTimeout(initReact, 0);
};
|
app/containers/SideBar/PermissionsNavTree.js | klpdotorg/tada-frontend | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import TreeView from 'react-treeview';
import { Link } from 'react-router';
import { capitalize } from '../../utils';
import { filterBoundaries } from './utils';
import {
collapsedProgramEntity,
getBoundariesEntities,
openPermissionBoundary,
} from '../../actions/';
import { Loading, Message } from '../../components/common';
class NavTree extends Component {
componentDidMount() {
this.props.getBoundariesEntities([{ depth: 0, uniqueId: this.props.parentId }]);
}
getTreeNodes(index) {
const nodes = this.props.entitiesByParentId[index];
if (nodes) {
const updatedNodes = nodes.map((node) => {
return { entity: this.props.entities[node], uniqueId: node };
});
if (index !== 0) {
return updatedNodes;
}
const filterEntities = filterBoundaries(updatedNodes, this.props.selectedPrimary);
return filterEntities;
}
return [];
}
renderLabel(node, depth, collapsed) {
const { entity } = node;
const label =
capitalize(entity.label) || capitalize(entity.name) || capitalize(entity.first_name);
return (
<Link
key={entity.name || entity.id}
tabIndex="0"
onClick={() => {
if (!collapsed) {
this.props.getBoundariesEntities([
{
id: entity.id,
depth,
uniqueId: node.uniqueId,
},
]);
}
this.props.openBoundary(node.uniqueId, depth);
}}
>
<span>{label}</span>
</Link>
);
}
renderSubTree(node, index, depth) {
const newDepth = depth + 1;
const { entity } = node;
const treeNodes = this.getTreeNodes(newDepth);
const collapsed = this.props.uncollapsed[newDepth] === node.uniqueId;
const name = this.renderLabel(node, newDepth, collapsed);
if (depth >= 2) {
return <span key={index} />;
}
return (
<TreeView
key={index}
onClick={() => {
this.props.getBoundariesEntities([
{
id: entity.id,
depth: newDepth,
uniqueId: node.uniqueId,
},
]);
}}
nodeLabel={name}
collapsed={!collapsed}
>
{depth <= 2 && collapsed ? (
treeNodes.map((child, i) => {
return this.renderSubTree(child, i + 1, newDepth);
})
) : (
<div />
)}
{!treeNodes.length && this.props.loading ? <Loading /> : <span />}
</TreeView>
);
}
renderBoundariesState(length) {
if (this.props.loading && !length) {
return <Loading />;
}
if (!length) {
return <Message message="No Boundaries Found" />;
}
return <span />;
}
render() {
const nodes = this.getTreeNodes(0);
return (
<div>
{nodes.map((element, i) => {
return this.renderSubTree(element, i, 0);
})}
{this.renderBoundariesState(nodes.length)}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
entities: state.boundaries.boundaryDetails,
entitiesByParentId: state.boundaries.boundariesByParentId,
uncollapsed: state.boundaries.uncollapsedEntities,
loading: state.appstate.loadingBoundary,
selectedPrimary: state.schoolSelection.primarySchool,
parentId: state.profile.parentNodeId,
};
};
NavTree.propTypes = {
getBoundariesEntities: PropTypes.func,
uncollapsed: PropTypes.object,
entitiesByParentId: PropTypes.object,
entities: PropTypes.object,
openBoundary: PropTypes.func,
loading: PropTypes.bool,
selectedPrimary: PropTypes.bool,
parentId: PropTypes.string,
};
const PermissionsNavTree = connect(mapStateToProps, {
collapsedProgramEntity,
getBoundariesEntities,
openBoundary: openPermissionBoundary,
})(NavTree);
export { PermissionsNavTree };
|
pootle/static/js/admin/components/Language/LanguageAdd.js | phlax/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import LanguageForm from './LanguageForm';
const LanguageAdd = React.createClass({
propTypes: {
collection: React.PropTypes.object.isRequired,
model: React.PropTypes.func.isRequired,
onCancel: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
},
render() {
const Model = this.props.model;
return (
<div className="item-add">
<div className="hd">
<h2>{gettext('Add Language')}</h2>
<button
onClick={this.props.onCancel}
className="btn btn-primary"
>
{gettext('Cancel')}
</button>
</div>
<div className="bd">
<LanguageForm
model={new Model()}
collection={this.props.collection}
onSuccess={this.props.onSuccess}
/>
</div>
</div>
);
},
});
export default LanguageAdd;
|
test/helpers/shallowRenderHelper.js | Aleczhang1992/gallery-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
internals/templates/containers/HomePage/index.js | mhoffman/CatAppBrowser | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/index.js | wmaurer/frontend_pizza_react_redux | import 'babel-polyfill';
require('./app.css');
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import App from './containers/App';
import DevTools from './containers/DevTools';
import configureStore from './store/configureStore';
const store = configureStore();
ReactDOM.render(
<Provider store={store}>
<div>
<App />
<DevTools />
</div>
</Provider>,
document.getElementById('root')
);
|
ReactComponents/CauseListView.js | DoSomething/LetsDoThis-iOS | 'use strict';
import React from 'react';
import {
AppRegistry,
ListView,
StyleSheet,
Text,
Image,
RefreshControl,
TouchableHighlight,
View
} from 'react-native';
var Style = require('./Style.js');
var Bridge = require('react-native').NativeModules.LDTReactBridge;
var NetworkErrorView = require('./NetworkErrorView.js');
var NetworkLoadingView = require('./NetworkLoadingView.js')
var CauseListView = React.createClass({
getInitialState: function() {
return {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
isRefreshing: false,
loaded: false,
error: false,
};
},
componentDidMount: function() {
this.fetchData();
},
fetchData: function() {
this.setState({
error: false,
loaded: false,
});
fetch(this.props.url)
.then((response) => response.json())
.catch((error) => this.catchError(error))
.then((responseData) => {
if (!responseData) {
return;
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData.categories),
loaded: true,
});
})
.done();
},
catchError: function(error) {
console.log("CauseListView.catchError");
this.setState({
error: error,
});
},
render: function() {
if (this.state.error) {
return (
<NetworkErrorView
title="Actions aren't loading right now"
retryHandler={this.fetchData}
errorMessage={this.state.error.message}
/>);
}
if (!this.state.loaded) {
return <NetworkLoadingView text="Loading actions..." />;
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
refreshControl={<RefreshControl
onRefresh={this._onRefresh}
refreshing={this.state.isRefreshing}
tintColor="#CCC" />}
/>
);
},
_onRefresh: function () {
this.setState({isRefreshing: true});
setTimeout(() => {
this.fetchData();
this.setState({
isRefreshing: false,
});
}, 1000);
},
_onPressRow(cause) {
Bridge.pushCause(cause);
},
renderRow: function(cause) {
var causeColorStyle = {backgroundColor: '#' + cause.hex};
return (
<TouchableHighlight onPress={() => this._onPressRow(cause)}>
<View style={styles.row}>
<View style={[styles.causeColor, causeColorStyle]} />
<View style={[styles.contentContainer, styles.bordered]}>
<View>
<Text style={Style.textHeading}>{cause.title}</Text>
</View>
</View>
<View style={[styles.arrowContainer, styles.bordered]}>
<Image
style={styles.arrowImage}
source={require('image!Arrow')}
/>
</View>
</View>
</TouchableHighlight>
);
},
});
var styles = StyleSheet.create({
listView: {
backgroundColor: '#FFFFFF',
paddingBottom: 10,
},
row: {
backgroundColor: '#FFFFFF',
flex: 1,
flexDirection: 'row',
},
causeColor: {
width: 8,
backgroundColor: '#00FF00',
height: 84,
},
bordered: {
borderColor: '#EDEDED',
borderTopWidth: 2,
borderBottomWidth: 2,
},
contentContainer: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
paddingLeft: 8,
height: 84,
},
arrowContainer: {
width: 38,
height: 84,
alignItems: 'center',
justifyContent: 'center',
flexDirection: 'row',
},
arrowImage: {
width: 12,
height: 21,
},
});
module.exports = CauseListView;
|
src/modules/Checkbox/Checkbox.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
AutoControlledComponent as Component,
createHTMLLabel,
customPropTypes,
getElementType,
getUnhandledProps,
makeDebugger,
META,
partitionHTMLInputProps,
useKeyOnly,
} from '../../lib'
const debug = makeDebugger('checkbox')
/**
* A checkbox allows a user to select a value from a small set of options, often binary.
* @see Form
* @see Radio
*/
export default class Checkbox extends Component {
static propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Whether or not checkbox is checked. */
checked: PropTypes.bool,
/** Additional classes. */
className: PropTypes.string,
/** The initial value of checked. */
defaultChecked: PropTypes.bool,
/** Whether or not checkbox is indeterminate. */
defaultIndeterminate: PropTypes.bool,
/** A checkbox can appear disabled and be unable to change states */
disabled: PropTypes.bool,
/** Removes padding for a label. Auto applied when there is no label. */
fitted: PropTypes.bool,
/** Whether or not checkbox is indeterminate. */
indeterminate: PropTypes.bool,
/** The text of the associated label element. */
label: customPropTypes.itemShorthand,
/** The HTML input name. */
name: PropTypes.string,
/**
* Called when the user attempts to change the checked state.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and proposed checked/indeterminate state.
*/
onChange: PropTypes.func,
/**
* Called when the checkbox or label is clicked.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and current checked/indeterminate state.
*/
onClick: PropTypes.func,
/**
* Called when the user presses down on the mouse.
*
* @param {SyntheticEvent} event - React's original SyntheticEvent.
* @param {object} data - All props and current checked/indeterminate state.
*/
onMouseDown: PropTypes.func,
/** Format as a radio element. This means it is an exclusive option. */
radio: customPropTypes.every([
PropTypes.bool,
customPropTypes.disallow(['slider', 'toggle']),
]),
/** A checkbox can be read-only and unable to change states. */
readOnly: PropTypes.bool,
/** Format to emphasize the current selection state. */
slider: customPropTypes.every([
PropTypes.bool,
customPropTypes.disallow(['radio', 'toggle']),
]),
/** A checkbox can receive focus. */
tabIndex: PropTypes.oneOfType([
PropTypes.number,
PropTypes.string,
]),
/** Format to show an on or off choice. */
toggle: customPropTypes.every([
PropTypes.bool,
customPropTypes.disallow(['radio', 'slider']),
]),
/** HTML input type, either checkbox or radio. */
type: PropTypes.oneOf(['checkbox', 'radio']),
/** The HTML input value. */
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
}
static defaultProps = {
type: 'checkbox',
}
static autoControlledProps = [
'checked',
'indeterminate',
]
static _meta = {
name: 'Checkbox',
type: META.TYPES.MODULE,
}
componentDidMount() {
this.setIndeterminate()
}
componentDidUpdate() {
this.setIndeterminate()
}
canToggle = () => {
const { disabled, radio, readOnly } = this.props
const { checked } = this.state
return !disabled && !readOnly && !(radio && checked)
}
computeTabIndex = () => {
const { disabled, tabIndex } = this.props
if (!_.isNil(tabIndex)) return tabIndex
return disabled ? -1 : 0
}
handleInputRef = c => (this.inputRef = c)
handleClick = (e) => {
debug('handleClick()')
const { checked, indeterminate } = this.state
if (!this.canToggle()) return
_.invoke(this.props, 'onClick', e, { ...this.props, checked: !checked, indeterminate: !!indeterminate })
_.invoke(this.props, 'onChange', e, { ...this.props, checked: !checked, indeterminate: false })
this.trySetState({ checked: !checked, indeterminate: false })
}
handleMouseDown = (e) => {
debug('handleMouseDown()')
const { checked, indeterminate } = this.state
_.invoke(this.props, 'onMouseDown', e, { ...this.props, checked: !!checked, indeterminate: !!indeterminate })
_.invoke(this.inputRef, 'focus')
e.preventDefault()
}
// Note: You can't directly set the indeterminate prop on the input, so we
// need to maintain a ref to the input and set it manually whenever the
// component updates.
setIndeterminate = () => {
const { indeterminate } = this.state
if (this.inputRef) this.inputRef.indeterminate = !!indeterminate
}
render() {
const {
className,
disabled,
label,
name,
radio,
readOnly,
slider,
toggle,
type,
value,
} = this.props
const { checked, indeterminate } = this.state
const classes = cx(
'ui',
useKeyOnly(checked, 'checked'),
useKeyOnly(disabled, 'disabled'),
useKeyOnly(indeterminate, 'indeterminate'),
// auto apply fitted class to compact white space when there is no label
// https://shengnian.github.io/modules/checkbox.html#fitted
useKeyOnly(!label, 'fitted'),
useKeyOnly(radio, 'radio'),
useKeyOnly(readOnly, 'read-only'),
useKeyOnly(slider, 'slider'),
useKeyOnly(toggle, 'toggle'),
'checkbox',
className,
)
const unhandled = getUnhandledProps(Checkbox, this.props)
const ElementType = getElementType(Checkbox, this.props)
const [htmlInputProps, rest] = partitionHTMLInputProps(unhandled, { htmlProps: [] })
return (
<ElementType
{...rest}
className={classes}
onChange={this.handleClick}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
>
<input
{...htmlInputProps}
checked={checked}
className='hidden'
name={name}
readOnly
ref={this.handleInputRef}
tabIndex={this.computeTabIndex()}
type={type}
value={value}
/>
{/*
Heads Up!
Do not remove empty labels, they are required by SUI CSS
*/}
{createHTMLLabel(label) || <label />}
</ElementType>
)
}
}
|
app/javascript/mastodon/components/modal_root.js | rainyday/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import 'wicg-inert';
export default class ModalRoot extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
onClose: PropTypes.func.isRequired,
};
state = {
revealed: !!this.props.children,
};
activeElement = this.state.revealed ? document.activeElement : null;
handleKeyUp = (e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!this.props.children) {
this.props.onClose();
}
}
handleKeyDown = (e) => {
if (e.key === 'Tab') {
const focusable = Array.from(this.node.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((x) => window.getComputedStyle(x).display !== 'none');
const index = focusable.indexOf(e.target);
let element;
if (e.shiftKey) {
element = focusable[index - 1] || focusable[focusable.length - 1];
} else {
element = focusable[index + 1] || focusable[0];
}
if (element) {
element.focus();
e.stopPropagation();
e.preventDefault();
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
window.addEventListener('keydown', this.handleKeyDown, false);
}
componentWillReceiveProps (nextProps) {
if (!!nextProps.children && !this.props.children) {
this.activeElement = document.activeElement;
this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
} else if (!nextProps.children) {
this.setState({ revealed: false });
}
}
componentDidUpdate (prevProps) {
if (!this.props.children && !!prevProps.children) {
this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
// Because of the wicg-inert polyfill, the activeElement may not be
// immediately selectable, we have to wait for observers to run, as
// described in https://github.com/WICG/inert#performance-and-gotchas
Promise.resolve().then(() => {
this.activeElement.focus();
this.activeElement = null;
}).catch((error) => {
console.error(error);
});
}
if (this.props.children) {
requestAnimationFrame(() => {
this.setState({ revealed: true });
});
}
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
window.removeEventListener('keydown', this.handleKeyDown);
}
getSiblings = () => {
return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
}
setRef = ref => {
this.node = ref;
}
render () {
const { children, onClose } = this.props;
const { revealed } = this.state;
const visible = !!children;
if (!visible) {
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
);
}
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: revealed ? 1 : 0 }}>
<div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
<div role='presentation' className='modal-root__overlay' onClick={onClose} />
<div role='dialog' className='modal-root__container'>{children}</div>
</div>
</div>
);
}
}
|
src/components/Icon/Icon-story.js | joshblack/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { iconAdd, iconAddSolid, iconAddOutline } from 'carbon-icons';
import { storiesOf } from '@storybook/react';
import { withKnobs, select, text } from '@storybook/addon-knobs';
import Icon from '../Icon';
import IconSkeleton from '../Icon/Icon.Skeleton';
const icons = {
'Add (iconAdd from `carbon-icons`)': 'iconAdd',
'Add with filled circle (iconAddSolid from `carbon-icons`)': 'iconAddSolid',
'Add with circle (iconAddOutline from `carbon-icons`)': 'iconAddOutline',
};
const iconMap = {
iconAdd,
iconAddSolid,
iconAddOutline,
};
const props = () => {
const selectedIcon = select(
'The icon (icon (regular)/name (legacy))',
icons,
'iconAdd'
);
return {
style: {
margin: '50px',
},
icon: iconMap[selectedIcon],
name: iconMap[selectedIcon] ? undefined : selectedIcon,
role: text('ARIA role (role)', ''),
fill: text('The SVG `fill` attribute (fill)', 'grey'),
fillRule: text('The SVG `fillRule` attribute (fillRule)', ''),
width: text('The SVG `width` attribute (width)', ''),
height: text('The SVG `height` attribute (height)', ''),
description: text(
'The a11y text (description)',
'This is a description of the icon and what it does in context'
),
iconTitle: text('The content in <title> in SVG (iconTitle)', ''),
className: 'extra-class',
};
};
const propsSkeleton = {
style: {
margin: '50px',
},
};
const propsSkeleton2 = {
style: {
margin: '50px',
width: '24px',
height: '24px',
},
};
storiesOf('Icon', module)
.addDecorator(withKnobs)
.add(
'Default',
() => (
<div>
<Icon {...props()} />
</div>
),
{
info: {
text: `
Icons are used in the product to present common actions and commands. Modify the fill property to change the color of the icon. The name property defines which icon to display. For accessibility, provide a context-rich description with the description prop. For a full list of icon names, see carbondesignsystem.com/style/iconography/library
`,
},
}
)
.add(
'Skeleton',
() => (
<div>
<IconSkeleton {...propsSkeleton} />
<IconSkeleton {...propsSkeleton2} />
</div>
),
{
info: {
text: `
Icons are used in the product to present common actions and commands. Modify the fill property to change the color of the icon. The name property defines which icon to display. For accessibility, provide a context-rich description with the description prop. For a full list of icon names, see carbondesignsystem.com/style/iconography/library
`,
},
}
);
|
blueocean-material-icons/src/js/components/svg-icons/action/info.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionInfo = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-6h2v6zm0-8h-2V7h2v2z"/>
</SvgIcon>
);
ActionInfo.displayName = 'ActionInfo';
ActionInfo.muiName = 'SvgIcon';
export default ActionInfo;
|
src/components/TextInputStyledComponents/TextInputStyledComponents.js | thomashoggard/ps-react-tom | import React from 'react';
import PropTypes from 'prop-types';
import Label from '../Label';
import styled from 'styled-components';
/** Text input with integrated label to enforce consistency in layout, error display, label placement, and required field marker. */
function TextInput({ htmlId, name, label, type = "text", required = false, onChange, placeholder, value, error, children, ...props }) {
const Error = styled.div`
color: red;
`;
const Input = styled.input`
border: ${error && 'solid 1px red'};
display: block;
`;
const Fieldset = styled.div`
margin-bottom: 16px;
`;
return (
<Fieldset>
<Label htmlFor={htmlId} label={label} required={required} />
<Input
id={htmlId}
type={type}
name={name}
placeholder={placeholder}
value={value}
onChange={onChange}
{...props} />
{children}
{error && <Error>{error}</Error>}
</Fieldset>
);
};
TextInput.propTypes = {
/** Unique HTML ID. Used for tying label to HTML input. Handy hook for automated testing. */
htmlId: PropTypes.string.isRequired,
/** Input name. Recommend setting this to match object's property so a single change handler can be used. */
name: PropTypes.string.isRequired,
/** Input label */
label: PropTypes.string.isRequired,
/** Input type */
type: PropTypes.oneOf(['text', 'number', 'password']),
/** Mark label with asterisk if set to true */
required: PropTypes.bool,
/** Function to call onChange */
onChange: PropTypes.func.isRequired,
/** Placeholder to display when empty */
placeholder: PropTypes.string,
/** Value */
value: PropTypes.any,
/** String to display when error occurs */
error: PropTypes.string,
/** Child component to display next to the input */
children: PropTypes.node
};
export default TextInput;
|
packages/icons/src/dv/Vue.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function DvVue(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M45 5.831L24 42.169 3 5.831h3.413L24 36.264 41.587 5.83H45zm-21 8.264l4.855-8.264h7.363L24 26.973 11.782 5.831h7.363L24 14.095z" />
</IconBase>
);
}
export default DvVue;
|
demo/index.js | JulienPradet/react-flip | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { HashRouter } from 'react-router-dom';
import Navigation from './Navigation';
import Examples from './Examples';
import './style/index.scss';
class App extends Component {
render() {
return (
<HashRouter>
<div>
<Navigation />
<Examples />
</div>
</HashRouter>
);
}
}
ReactDOM.render(<App />, document.getElementById('root'));
|
app/components/Menu/MenuHeader.js | cdiezmoran/playgrounds-desktop | /**
* Created on Tue Nov 8 2016
*
* Side-bar menu header component containing the user profile pic and username
* and the search bar component.
*
* @flow
*/
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import jwtDecode from 'jwt-decode';
// import SearchBar from '../SearchBar';
class MenuHeader extends Component {
render() {
const token = localStorage.getItem('id_token');
const currentUser = jwtDecode(token);
return (
<div className="menu-header">
<div className="menu-user container">
<div className="row flex-items-xs-center center-align">
<Link to="/" className="menu-profile">
<img src={currentUser.profilePic} className="circular-img" alt="" />
<p className="username">
{currentUser.username}
</p>
</Link>
</div>
</div>
</div>
);
}
}
export default MenuHeader;
|
src/src/components/SideBar/Nav.js | chaitanya1375/Myprojects | import React, { Component } from 'react';
import { Link, withRouter } from 'react-router-dom';
import { Collapse } from 'react-bootstrap';
class Nav extends Component {
state = {};
render() {
let { location } = this.props;
return (
<ul className="nav">
<li className={location.pathname === '/' ? 'active' : null}>
<Link to="/">
<i className="pe-7s-graph"></i>
<p>Dashboard</p>
</Link>
</li>
<li className={this.isPathActive('/charts') ? 'active' : null}>
<Link to="/charts">
<i className="pe-7s-graph"></i>
<p>Charts</p>
</Link>
</li>
</ul>
);
}
isPathActive(path) {
return this.props.location.pathname.startsWith(path);
}
}
export default withRouter(Nav); |
src/Col.js | xsistens/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import styleMaps from './styleMaps';
import CustomPropTypes from './utils/CustomPropTypes';
const Col = React.createClass({
propTypes: {
/**
* The number of columns you wish to span
*
* for Extra small devices Phones (<768px)
*
* class-prefix `col-xs-`
*/
xs: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Small devices Tablets (≥768px)
*
* class-prefix `col-sm-`
*/
sm: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Medium devices Desktops (≥992px)
*
* class-prefix `col-md-`
*/
md: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Large devices Desktops (≥1200px)
*
* class-prefix `col-lg-`
*/
lg: React.PropTypes.number,
/**
* Move columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-offset-`
*/
xsOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-offset-`
*/
smOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-offset-`
*/
mdOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-offset-`
*/
lgOffset: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-push-`
*/
xsPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-push-`
*/
smPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-push-`
*/
mdPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-push-`
*/
lgPush: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Extra small devices Phones
*
* class-prefix `col-xs-pull-`
*/
xsPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Small devices Tablets
*
* class-prefix `col-sm-pull-`
*/
smPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Medium devices Desktops
*
* class-prefix `col-md-pull-`
*/
mdPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Large devices Desktops
*
* class-prefix `col-lg-pull-`
*/
lgPull: React.PropTypes.number,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
let classes = {};
Object.keys(styleMaps.SIZES).forEach(function (key) {
let size = styleMaps.SIZES[key];
let prop = size;
let classPart = size + '-';
if (this.props[prop]) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Offset';
classPart = size + '-offset-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Push';
classPart = size + '-push-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Pull';
classPart = size + '-pull-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
}, this);
return (
<ComponentClass {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</ComponentClass>
);
}
});
export default Col;
|
node_modules/react-scripts/template/src/index.js | webtutorial/builder | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
import './index.css';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
src/components/performance/LineAndBarsChart.js | jmporchet/bravakin-client | import React from 'react';
import { AreaClosed, BarGroup, LinePath } from '@vx/shape';
import { Group } from '@vx/group';
import { AxisLeft, AxisBottom } from '@vx/axis';
import { scaleTime, scaleBand, scaleLinear, scaleOrdinal } from '@vx/scale';
import { curveMonotoneX } from '@vx/curve';
import { timeFormat } from 'd3-time-format';
import { extent, max } from 'd3-array';
import { Grid } from '@vx/grid';
// accessors
const xDate = d => d.date;
const yLine = d => d.engagement;
const yBar = d => Math.max(d.likes, d.comments)
export default ({
data,
width,
height,
margin = {
top: 10,
left: 50,
right: 20,
bottom: 100,
}
}) => {
if (width < 10) return null;
const keys = Object.keys(data[0]).filter(d => d !== 'date' && d !== 'followers' && d !== 'engagement');
const format = timeFormat("%H");
const formatDate = (date) => format(date);
// bounds
const xMax = width - margin.left - margin.right;
const yMax = height - margin.top - margin.bottom;
// Bar scales
// hours on x axis
const x0Scale = scaleBand({
rangeRound: [0, xMax],
domain: data.map(xDate),
padding: 0.1,
tickFormat: () => (val) => formatDate(val)
});
const x1Scale = scaleBand({
rangeRound: [0, x0Scale.bandwidth()],
domain: keys,
padding: 0.1
});
// colors for the bars
const zScale = scaleOrdinal({
domain: keys,
range: ['#aeeef8', '#e5fd3d']
});
// Engagement line scales
const xLineScale = scaleTime({
range: [0, xMax],
domain: extent(data, xDate),
});
const yLineScale = scaleLinear({
range: [yMax, 0],
domain: [0, max(data, yLine)],
nice: true,
});
const yBarScale = scaleLinear({
range: [yMax ,0],
domain: [0, max(data, yBar)],
nice: true,
})
// responsive utils for axis ticks
function numTicksForHeight(height) {
if (height <= 300) return 3;
if (300 < height && height <= 600) return 5;
return 10;
}
function numTicksForWidth(width) {
if (width <= 300) return 3;
if (300 < width && width <= 400) return 6;
return 12;
}
return (
<svg width={width} height={height} >
<Grid
top={margin.top}
left={margin.left}
xScale={xLineScale}
yScale={yLineScale}
stroke='#8a265f'
strokeDasharray='1,15'
width={xMax}
height={yMax}
numTicksRows={numTicksForHeight(height)}
numTicksColumns={numTicksForWidth(width)}
/>
<AxisLeft
top={margin.top}
left={margin.left}
scale={yLineScale}
hideZero
numTicks={numTicksForHeight(height)}
label={
<text
fill="#8e205f"
textAnchor="middle"
fontSize={10}
fontFamily="Arial"
>
likes
</text>
}
stroke="#1b1a1e"
tickLabelComponent={
<text
fill="#8e205f"
textAnchor="end"
fontSize={10}
fontFamily="Arial"
dx="-0.25em"
dy="0.25em"
/>
}
/>
<AxisBottom
scale={xLineScale}
top={height - margin.bottom}
left={margin.left}
numTicks={numTicksForWidth(width)}
stroke='#1b1a1e'
tickStroke='#1b1a1e'
tickLabelComponent={(
<text
fill="#8e205f"
textAnchor="middle"
fontSize={10}
fontFamily="Arial"
dy="0.25em"
/>
)}
/>
<BarGroup
top={margin.top}
left={margin.left}
data={data}
keys={keys}
height={yMax}
x0={xDate}
x0Scale={x0Scale}
x1Scale={x1Scale}
yScale={yBarScale}
zScale={zScale}
rx={4}
/>
<Group top={margin.top} left={margin.left+7}>
<AreaClosed
data={data}
xScale={x0Scale}
yScale={yLineScale}
x={xDate}
y={yLine}
strokeWidth={2}
stroke='transparent'
fill="url('#orangeRed')"
curve={curveMonotoneX}
/>
<LinePath
data={data}
xScale={x0Scale}
yScale={yLineScale}
x={xDate}
y={yLine}
stroke="url('#orangeRed')"
strokeWidth={2}
curve={curveMonotoneX}
/>
</Group>
</svg>
);
}
|
docs/src/app/components/pages/components/Menu/ExampleNested.js | owencm/material-ui | import React from 'react';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import Divider from 'material-ui/Divider';
import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right';
const style = {
display: 'inline-block',
margin: '16px 32px 16px 0',
};
const MenuExampleNested = () => (
<div>
<Paper style={style}>
<Menu desktop={true} width={320}>
<MenuItem primaryText="Single" insetChildren={true} />
<MenuItem primaryText="1.15" insetChildren={true} />
<MenuItem primaryText="Double" insetChildren={true} />
<MenuItem
primaryText="Custom: 1.2"
checked={true}
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem
primaryText="Show"
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem primaryText="Show Level 2" />,
<MenuItem primaryText="Grid lines" checked={true} />,
<MenuItem primaryText="Page breaks" insetChildren={true} />,
<MenuItem primaryText="Rules" checked={true} />,
]}
/>,
<MenuItem primaryText="Grid lines" checked={true} />,
<MenuItem primaryText="Page breaks" insetChildren={true} />,
<MenuItem primaryText="Rules" checked={true} />,
]}
/>
<Divider />
<MenuItem primaryText="Add space before paragraph" />
<MenuItem primaryText="Add space after paragraph" />
<Divider />
<MenuItem primaryText="Custom spacing..." />
</Menu>
</Paper>
</div>
);
export default MenuExampleNested;
|
src/modules/pages/feeds/js/feedStore.js | lenxeon/react | import React from 'react';
let FeedStore = {
list(cat, page, size, cb) {
cat = cat || 'all';
page = page || 1;
size = size || 20;
$.get('/dist/data/feeds/list_' + cat + '.json', function(result) {
let list = result[0].card_group;
setTimeout(() => {
cb({
list: list
});
}, 500)
}.bind(this));
},
listTag(feedId, cb) {
let list = [];
for (let i = 0; i < 5; i++) {
list.push({
uuid: i,
name: '标签'+i
})
}
setTimeout(() => {
cb({
list: list
});
}, 500)
},
searchTag(val, cb) {
let list = [];
let size = Math.round(Math.random()*10)+1;
for (let i = 0; i < size; i++) {
list.push({
uuid: i,
name: 'tag:('+val+')'+i
})
}
setTimeout(() => {
cb({
list: list
});
}, 200)
},
saveTag(feedId, tagId, tagName, cb) {
setTimeout(() => {
cb({
uuid: 'global',
cli_uuid: tagId,
name: tagName
});
}, 500)
},
}
export default FeedStore; |
client/app/components/MapPage.js | BeaconCorp/beacon | import React from 'react';
import { Link } from 'react-router';
import { Map, Marker, Popup, TileLayer } from 'react-leaflet';
import { getAllBeacons } from '../utils/helpers';
var MapPage = React.createClass({
getInitialState: () => {
console.log('MapPage.getInitialState()');
return {
beacons: [],
};
},
componentDidMount: function () {
console.log('MapPage.componentDidMount()');
navigator.geolocation.getCurrentPosition((data) => {
getAllBeacons(data.coords.latitude, data.coords.longitude)
.then((response) => {
console.log('MapPage.componentDidMount(), got location successfully.',
response);
this.setState({ beacons: response.data });
this.renderBeacons();
});
});
},
renderBeacons: function () {
console.log('MapPage.renderBeacons()', this.state.beacons);
let beacons = this.state.beacons.map((beacon, index) => {
let position = [beacon.lat, beacon.lng];
return (
<Marker position={position} key={index}>
<Popup>
<div>
<h3>{beacon.title}</h3>
<p>{beacon.description}</p>
<p>{beacon.topics}</p>
</div>
</Popup>
</Marker>
);
});
return beacons;
},
render: function () {
const position = [43.044591, -76.150566]; // tech garden
const mapStyle = { height: '100%' };
return (
<div className="map">
<Map center={position} zoom={12} style={mapStyle}>
<TileLayer
url='http://{s}.tile.osm.org/{z}/{x}/{y}.png'
attribution='© <a href="http://osm.org/copyright">OpenStreetMap</a> contributors'
/>
{ this.renderBeacons() }
</Map>
<Link to='new-beacon' className="btn btn-primary btn-fab add-beacon">
<i className="material-icons">+</i>
</Link>
</div>
);
},
});
module.exports = MapPage;
|
clients/libs/slate-editor-list-plugin/src/ListButtonBar.js | nossas/bonde-client | /* eslint-disable no-undef */
import React from 'react'
import { UnorderedListButton, OrderedListButton } from './'
// FIXME: Needs to handle assets files to work with SSR
// eslint-disable-next-line @typescript-eslint/no-var-requires
if (require('exenv').canUseDOM) require('./ListButtonBar.module.css')
const ListButtonBar = props => (
<div className='slate-list-plugin--button-bar'>
<UnorderedListButton {...props} />
<OrderedListButton {...props} />
</div>
)
export default ListButtonBar
|
src/client/components/Note.js | ampext/graphql-notes | import React from 'react';
import PropTypes from 'prop-types';
import { createFragmentContainer } from 'react-relay';
import Button from './Button';
class Note extends React.PureComponent {
onRemoveButton = () => this.props.onRemove(this.props.item.id);
onEditButton = () => {
const {id, content, date} = this.props.item;
this.props.onEdit(id, content);
};
render() {
const {content, date} = this.props.item;
const classNames = ['note'];
if (this.props.highlighted) {
classNames.push('note--highlighted');
}
return (
<div className='note-container'>
<div className='note-container__avatar' />
<div className='note-container__body'>
<div className={classNames.join(' ')}>
<span className='note__content'>{content}</span>
<Button key='edit' faName='fa-pencil' onClick={this.onEditButton} />
<Button key='remove' faName='fa-times' onClick={this.onRemoveButton} />
</div>
<span className='note-container__date'>{new Date(date).toLocaleString()}</span>
</div>
</div>
);
}
}
Note.propTypes = {
item: PropTypes.object,
highlighted: PropTypes.bool,
onRemove: PropTypes.func,
onEdit: PropTypes.func
};
export default createFragmentContainer(Note,
graphql`
fragment Note_item on Note {
id,
content,
date
}
`
); |
packages/mineral-ui-icons/src/IconMonochromePhotos.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconMonochromePhotos(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M20 5h-3.2L15 3H9L7.2 5H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 14h-8v-1c-2.8 0-5-2.2-5-5s2.2-5 5-5V7h8v12zm-3-6c0-2.8-2.2-5-5-5v1.8c1.8 0 3.2 1.4 3.2 3.2s-1.4 3.2-3.2 3.2V18c2.8 0 5-2.2 5-5zm-8.2 0c0 1.8 1.4 3.2 3.2 3.2V9.8c-1.8 0-3.2 1.4-3.2 3.2z"/>
</g>
</Icon>
);
}
IconMonochromePhotos.displayName = 'IconMonochromePhotos';
IconMonochromePhotos.category = 'image';
|
src/scripts/views/detailView.js | sharnee/instaClone | import React from 'react'
import Header from './header'
import Footer from './footer'
// import Likes from './likes'
import CommentsHeader from './commentsHeader'
import Comments from './comments'
import Image from './image'
var DetailView = React.createClass({
render: function() {
return (
<div className="detail-body-container">
<Header />
<div className="flex-wrapper">
<ImagePost model={this.props.model} />
</div>
<Footer />
</div>
)
}
})
var ImagePost = React.createClass({
render: function() {
var detailData = this.props.model
return (
<section className="image-wrapper">
<div className="image-container">
<Image model={this.props.model} />
</div>
<div className="details-container">
<CommentsHeader model={this.props.model} />
<Comments model={this.props.model} />
</div>
</section>
)
}
})
export default DetailView |
src/Jumbotron.js | dongtong/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import CustomPropTypes from './utils/CustomPropTypes';
const Jumbotron = React.createClass({
propTypes: {
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return { componentClass: 'div' };
},
render() {
const ComponentClass = this.props.componentClass;
return (
<ComponentClass {...this.props} className={classNames(this.props.className, 'jumbotron')}>
{this.props.children}
</ComponentClass>
);
}
});
export default Jumbotron;
|
packages/spust-koa/src/BodyParser.js | michalkvasnicak/spust | // @flow
import koaBodyParser from 'koa-bodyparser';
import React from 'react';
import { type Context as ServerContext, serverContextType } from './Server';
export default class BodyParser extends React.Component<void, *, void> {
static contextTypes = serverContextType;
context: ServerContext;
constructor(props: any, context: ServerContext) {
super(props, context);
this.context.use(koaBodyParser());
}
render() {
return null;
}
}
|
src/svg-icons/notification/confirmation-number.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationConfirmationNumber = (props) => (
<SvgIcon {...props}>
<path d="M22 10V6c0-1.11-.9-2-2-2H4c-1.1 0-1.99.89-1.99 2v4c1.1 0 1.99.9 1.99 2s-.89 2-2 2v4c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-4c-1.1 0-2-.9-2-2s.9-2 2-2zm-9 7.5h-2v-2h2v2zm0-4.5h-2v-2h2v2zm0-4.5h-2v-2h2v2z"/>
</SvgIcon>
);
NotificationConfirmationNumber = pure(NotificationConfirmationNumber);
NotificationConfirmationNumber.displayName = 'NotificationConfirmationNumber';
NotificationConfirmationNumber.muiName = 'SvgIcon';
export default NotificationConfirmationNumber;
|
custom_modules/Picture.js | hustmsc/hustmsc-app | import React, { Component } from 'react';
import {
StyleSheet,
Image
} from 'react-native';
export default class Picture extends Component {
render() {
return (
<Image source={this.props.src} style={styles.images} />
);
}
}
const styles = StyleSheet.create({
images: {
width: 193,
height: 110,
},
});
|
app/components/Form/FormField.js | acebusters/ab-web | import React from 'react';
import PropTypes from 'prop-types';
import FormGroup from './FormGroup';
import Input from '../Input';
import Label from '../Label';
import { ErrorMessage, WarningMessage } from '../../components/FormMessages';
const FormField = ({ input, label, type, meta: { touched, error, warning }, ...props }) => (
<FormGroup>
<Label htmlFor={input.name}>{label}</Label>
<Input {...input} {...props} type={type} id={input.name} />
{touched && error && <ErrorMessage error={error} />}
{touched && warning && <WarningMessage error={warning} />}
</FormGroup>
);
FormField.propTypes = {
input: PropTypes.object,
label: PropTypes.node,
type: PropTypes.string,
meta: PropTypes.object,
};
export default FormField;
|
src/svg-icons/social/sentiment-dissatisfied.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentDissatisfied = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-6c-2.33 0-4.32 1.45-5.12 3.5h1.67c.69-1.19 1.97-2 3.45-2s2.75.81 3.45 2h1.67c-.8-2.05-2.79-3.5-5.12-3.5z"/>
</SvgIcon>
);
SocialSentimentDissatisfied = pure(SocialSentimentDissatisfied);
SocialSentimentDissatisfied.displayName = 'SocialSentimentDissatisfied';
SocialSentimentDissatisfied.muiName = 'SvgIcon';
export default SocialSentimentDissatisfied;
|
js/src/ui/ModalBox/summary.js | nipunn1313/parity | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React from 'react';
import { nodeOrStringProptype } from '~/util/proptypes';
import styles from './modalBox.css';
export default function Summary ({ summary }) {
if (!summary) {
return null;
}
return (
<div className={ styles.summary }>
{ summary }
</div>
);
}
Summary.propTypes = {
summary: nodeOrStringProptype()
};
|
admin/client/views/signin.js | Ftonso/keystone | 'use strict';
import classnames from 'classnames';
import React from 'react';
import ReactDOM from 'react-dom';
import SessionStore from '../stores/SessionStore';
import { Alert, Button, Form, FormField, FormInput } from 'elemental';
import { createHistory } from 'history';
var history = createHistory();
var SigninView = React.createClass({
getInitialState () {
return {
email: '',
password: '',
isAnimating: false,
isInvalid: false,
invalidMessage: '',
signedOut: window.location.search === '?signedout'
};
},
componentDidMount () {
if (this.state.signedOut && window.history.replaceState) {
history.replaceState({}, window.location.pathname);
}
if (this.refs.email) {
ReactDOM.findDOMNode(this.refs.email).select();
}
},
handleInputChange (e) {
let newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
},
handleSubmit (e) {
e.preventDefault();
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
SessionStore.signin({
email: this.state.email,
password: this.state.password
}, (err, data) => {
if (err || data && data.error) {
this.displayError('The email and password you entered are not valid.');
} else {
// TODO: Handle custom signin redirections
top.location.href = Keystone.adminPath;
}
});
},
displayError (message) {
this.setState({
isAnimating: true,
isInvalid: true,
invalidMessage: message
});
setTimeout(this.finishAnimation, 750);
},
finishAnimation () {
if (!this.isMounted()) return;
if (this.refs.email) {
ReactDOM.findDOMNode(this.refs.email).select();
}
this.setState({
isAnimating: false
});
},
renderBrand () {
let logo = { src: `${Keystone.adminPath}/images/logo.png`, width: 205, height: 68 };
if (this.props.logo) {
logo = typeof this.props.logo === 'string' ? { src: this.props.logo } : this.props.logo;
// TODO: Deprecate this
if (Array.isArray(logo)) {
logo = { src: logo[0], width: logo[1], height: logo[2] };
}
}
return (
<div className="auth-box__col">
<div className="auth-box__brand">
<a href="/" className="auth-box__brand__logo">
<img src={logo.src} width={logo.width ? logo.width : null} height={logo.height ? logo.height : null} alt={this.props.brand} />
</a>
</div>
</div>
);
},
renderUserInfo () {
if (!this.props.user) return null;
let openKeystoneButton = this.props.userCanAccessKeystone ? <Button href={Keystone.adminPath} type="primary">Open Keystone</Button> : null;
return (
<div className="auth-box__col">
<p>Hi {this.props.user.name.first},</p>
<p>You're already signed in.</p>
{openKeystoneButton}
<Button href={`${Keystone.adminPath}/signout`} type="link-cancel">Sign Out</Button>
</div>
);
},
renderAlert () {
if (this.state.isInvalid) {
return <Alert key="error" type="danger" style={{ textAlign: 'center' }}>{this.state.invalidMessage}</Alert>;
} else if (this.state.signedOut) {
return <Alert key="signed-out" type="info" style={{ textAlign: 'center' }}>You have been signed out.</Alert>;
} else {
/* eslint-disable react/self-closing-comp */
// TODO: This probably isn't the best way to do this, we
// shouldn't be using Elemental classNames instead of components
return <div key="fake" className="Alert Alert--placeholder"> </div>;
/* eslint-enable */
}
},
renderForm () {
if (this.props.user) return null;
return (
<div className="auth-box__col">
<Form method="post" onSubmit={this.handleSubmit} noValidate>
<FormField label="Email" htmlFor="email">
<FormInput type="email" name="email" onChange={this.handleInputChange} value={this.state.email} ref="email" />
</FormField>
<FormField label="Password" htmlFor="password">
<FormInput type="password" name="password" onChange={this.handleInputChange} value={this.state.password} ref="password" />
</FormField>
<Button disabled={this.state.animating} type="primary" submit>Sign In</Button>
{/*<Button disabled={this.state.animating} type="link-text">Forgot Password?</Button>*/}
</Form>
</div>
);
},
render () {
let boxClassname = classnames('auth-box', {
'auth-box--has-errors': this.state.isAnimating
});
return (
<div className="auth-wrapper">
{this.renderAlert()}
<div className={boxClassname}>
<h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1>
<div className="auth-box__inner">
{this.renderBrand()}
{this.renderUserInfo()}
{this.renderForm()}
</div>
</div>
<div className="auth-footer">
<span>Powered by </span>
<a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a>
</div>
</div>
);
}
});
ReactDOM.render(<SigninView
brand={Keystone.brand}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>, document.getElementById('signin-view'));
|
src/components/HabitPageContent.js | simplebee/everyday | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { withRouter } from 'react-router';
import { Route, Link } from 'react-router-dom';
import { Button } from 'antd';
import Calendar from './Calendar';
import Datapoints from './Datapoints';
import Graph from './Graph';
import { deleteHabit } from '../actions/habitActions';
class HabitPageContent extends Component {
handleDeleteClick = () => {
const { habitId } = this.props.match.params;
this.props
.deleteHabit(habitId)
.then(() => this.props.history.push('/app'))
.catch(error => console.log(error));
};
render() {
const { match } = this.props;
return (
<React.Fragment>
<div>
<Link to={`${match.url}/edit`}>
<Button icon="edit">Edit</Button>
</Link>
<Button type="danger" icon="delete" onClick={this.handleDeleteClick}>
Delete
</Button>
</div>
<Route path={`${match.path}`} exact component={Calendar} />
<Route path={`${match.path}/datapoints`} component={Datapoints} />
<Route path={`${match.path}/graph`} component={Graph} />
</React.Fragment>
);
}
}
const mapDispatchToProps = { deleteHabit };
export default withRouter(
connect(
null,
mapDispatchToProps
)(HabitPageContent)
);
|
examples/js/selection/select-bgcolor-table.js | powerhome/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
const selectRowProp = {
mode: 'checkbox',
bgColor: 'pink'
};
export default class SelectBgColorTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } selectRow={ selectRowProp }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
node_modules/react-router/es6/Link.js | save-password/save-password.github.io | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object]),
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
};
},
handleClick: function handleClick(event) {
if (this.props.onClick) this.props.onClick(event);
if (event.defaultPrevented) return;
!this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0;
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) return;
event.preventDefault();
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(location);
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
// If user does not specify a `to` prop, return an empty anchor tag.
if (to == null) {
return React.createElement('a', props);
}
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(location);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(location, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ' ' + activeClassName;
} else {
props.className = activeClassName;
}
}
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link; |
generators/js-framework/modules/react/components/Footer.js | sahat/boilerplate | import React from 'react';
class Footer extends React.Component {
render() {
return (
<footer>
<p>© 2016 Company, Inc. All Rights Reserved.</p>
</footer>
);
}
}
export default Footer;
|
src/MediaListItem.js | mmarcant/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
class MediaListItem extends React.Component {
render() {
const { className, ...props } = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = getClassSet(bsProps);
return (
<li
{...elementProps}
className={classNames(className, classes)}
/>
);
}
}
export default bsClass('media', MediaListItem);
|
examples/src/components/CustomRenderField.js | silppuri/react-select | import React from 'react';
import Select from 'react-select';
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
var CustomRenderField = React.createClass({
displayName: 'CustomRenderField',
propTypes: {
delimiter: React.PropTypes.string,
label: React.PropTypes.string,
multi: React.PropTypes.bool,
},
renderOption (option) {
return <span style={{ color: option.hex }}>{option.label} ({option.hex})</span>;
},
renderValue (option) {
return <strong style={{ color: option.hex }}>{option.label}</strong>;
},
render () {
var ops = [
{ label: 'Red', value: 'red', hex: '#EC6230' },
{ label: 'Green', value: 'green', hex: '#4ED84E' },
{ label: 'Blue', value: 'blue', hex: '#6D97E2' }
];
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
delimiter={this.props.delimiter}
multi={this.props.multi}
allowCreate
placeholder="Select your favourite"
options={ops}
optionRenderer={this.renderOption}
valueRenderer={this.renderValue}
onChange={logChange} />
</div>
);
}
});
module.exports = CustomRenderField;
|
client/index.js | Jakeyrob/chill | import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
require('./styles.css');
ReactDOM.render(
<App />,
document.getElementById('app')
); |
src/components/Start.js | Babbins/fullstalker | import React from 'react';
import {Link} from 'react-router';
function myFunction() {
console.log('your mom!');
}
export default () => (
<div>
<br />
<br />
<br />
<div className="valign-wrapper row">
<div className="valign col s7 center">
<img id="logo" className="text-align" src="/media/logo.png" />
</div>
<div className="valgin col s5 center">
<div className="start-text">
<h5>
Fullstalkr will learn you the names of the many faces of Fullstack and Grace Hopper Academy!
</h5>
</div>
<Link to="/flashcard">
<button className="waves-effect waves-light btn-large amber darken-3">Begin!</button>
</Link>
</div>
</div>
</div>
);
|
fields/types/select/SelectField.js | riyadhalnur/keystone | import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import { FormInput } from 'elemental';
/**
* TODO:
* - Custom path support
*/
module.exports = Field.create({
displayName: 'SelectField',
valueChanged (newValue) {
// TODO: This should be natively handled by the Select component
if (this.props.numeric && 'string' === typeof newValue) {
newValue = newValue ? Number(newValue) : undefined;
}
this.props.onChange({
path: this.props.path,
value: newValue
});
},
renderValue () {
var selected = this.props.ops.find(option => option.value === this.props.value);
return <FormInput noedit>{selected ? selected.label : null}</FormInput>;
},
renderField () {
// TODO: This should be natively handled by the Select component
var ops = (this.props.numeric) ? this.props.ops.map(function(i) { return { label: i.label, value: String(i.value) }; }) : this.props.ops;
var value = ('number' === typeof this.props.value) ? String(this.props.value) : this.props.value;
return <Select simpleValue name={this.props.path} value={value} options={ops} onChange={this.valueChanged} />;
}
});
|
src/react/JSONTree/JSONStringNode.js | threepointone/redux-devtools | import React from 'react';
import reactMixin from 'react-mixin';
import { SquashClickEventMixin } from './mixins';
import hexToRgb from '../../utils/hexToRgb';
const styles = {
base: {
paddingTop: 3,
paddingBottom: 3,
paddingRight: 0,
marginLeft: 14
},
label: {
display: 'inline-block',
marginRight: 5
}
};
@reactMixin.decorate(SquashClickEventMixin)
export default class JSONStringNode extends React.Component {
render() {
let backgroundColor = 'transparent';
if (this.props.previousValue !== this.props.value) {
const bgColor = hexToRgb(this.props.theme.base06);
backgroundColor = `rgba(${bgColor.r}, ${bgColor.g}, ${bgColor.b}, 0.1)`;
}
return (
<li style={{ ...styles.base, backgroundColor }} onClick={::this.handleClick}>
<label style={{
...styles.label,
color: this.props.theme.base0D
}}>
{this.props.keyName}:
</label>
<span style={{ color: this.props.theme.base0B }}>"{this.props.value}"</span>
</li>
);
}
}
|
src/svg-icons/action/settings-input-antenna.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsInputAntenna = (props) => (
<SvgIcon {...props}>
<path d="M12 5c-3.87 0-7 3.13-7 7h2c0-2.76 2.24-5 5-5s5 2.24 5 5h2c0-3.87-3.13-7-7-7zm1 9.29c.88-.39 1.5-1.26 1.5-2.29 0-1.38-1.12-2.5-2.5-2.5S9.5 10.62 9.5 12c0 1.02.62 1.9 1.5 2.29v3.3L7.59 21 9 22.41l3-3 3 3L16.41 21 13 17.59v-3.3zM12 1C5.93 1 1 5.93 1 12h2c0-4.97 4.03-9 9-9s9 4.03 9 9h2c0-6.07-4.93-11-11-11z"/>
</SvgIcon>
);
ActionSettingsInputAntenna = pure(ActionSettingsInputAntenna);
ActionSettingsInputAntenna.displayName = 'ActionSettingsInputAntenna';
export default ActionSettingsInputAntenna;
|
app/javascript/mastodon/features/notifications/components/setting_toggle.js | tri-star/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
export default class SettingToggle extends React.PureComponent {
static propTypes = {
prefix: PropTypes.string,
settings: ImmutablePropTypes.map.isRequired,
settingPath: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
onChange: PropTypes.func.isRequired,
defaultValue: PropTypes.bool,
disabled: PropTypes.bool,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingPath, target.checked);
}
render () {
const { prefix, settings, settingPath, label, defaultValue, disabled } = this.props;
const id = ['setting-toggle', prefix, ...settingPath].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle disabled={disabled} id={id} checked={settings.getIn(settingPath, defaultValue)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
</div>
);
}
}
|
src/component/check.js | stevenocchipinti/react-toggle | import React from 'react'
export default () => (
<svg width='14' height='11' viewBox='0 0 14 11'>
<title>
switch-check
</title>
<path d='M11.264 0L5.26 6.004 2.103 2.847 0 4.95l5.26 5.26 8.108-8.107L11.264 0' fill='#fff' fillRule='evenodd' />
</svg>
)
|
src/app/components/Delta.js | devgru/color | import React from 'react';
import { hcl } from 'd3-color';
import deltae from 'deltae';
import toString from '../domain/ColorToString';
import classNames from 'classnames';
import round from 'round-to-precision';
const cents = round(0.01);
function Delta(props) {
let delta = 0;
const hcl1 = hcl(props.colors[0]);
const hcl2 = hcl(props.colors[1]);
deltae.delta(toString(hcl1), toString(hcl2), function(d) {
delta = cents(d);
});
const textClasses = classNames({
delta: true,
'color-card__text_bright': hcl1.l + hcl2.l > 100,
'color-card__text_dark': hcl1.l + hcl2.l <= 100,
});
const style = {
background:
'-webkit-linear-gradient(left, ' + hcl1 + ' 0%, ' + hcl2 + ' 100%)',
};
return (
<div style={style} className={textClasses}>
<span>{delta}</span>
</div>
);
}
export default Delta;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.