path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
node_modules/react-router/es/StaticRouter.js | Sweetgrassbuffalo/ReactionSweeGrass-v2 | 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; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import invariant from 'invariant';
import React from 'react';
import PropTypes from 'prop-types';
import { addLeadingSlash, createPath, parsePath } from 'history/PathUtils';
import Router from './Router';
var normalizeLocation = function normalizeLocation(object) {
var _object$pathname = object.pathname,
pathname = _object$pathname === undefined ? '/' : _object$pathname,
_object$search = object.search,
search = _object$search === undefined ? '' : _object$search,
_object$hash = object.hash,
hash = _object$hash === undefined ? '' : _object$hash;
return {
pathname: pathname,
search: search === '?' ? '' : search,
hash: hash === '#' ? '' : hash
};
};
var addBasename = function addBasename(basename, location) {
if (!basename) return location;
return _extends({}, location, {
pathname: addLeadingSlash(basename) + location.pathname
});
};
var stripBasename = function stripBasename(basename, location) {
if (!basename) return location;
var base = addLeadingSlash(basename);
if (location.pathname.indexOf(base) !== 0) return location;
return _extends({}, location, {
pathname: location.pathname.substr(base.length)
});
};
var createLocation = function createLocation(location) {
return typeof location === 'string' ? parsePath(location) : normalizeLocation(location);
};
var createURL = function createURL(location) {
return typeof location === 'string' ? location : createPath(location);
};
var staticHandler = function staticHandler(methodName) {
return function () {
invariant(false, 'You cannot %s with <StaticRouter>', methodName);
};
};
var noop = function noop() {};
/**
* The public top-level API for a "static" <Router>, so-called because it
* can't actually change the current location. Instead, it just records
* location changes in a context object. Useful mainly in testing and
* server-rendering scenarios.
*/
var StaticRouter = function (_React$Component) {
_inherits(StaticRouter, _React$Component);
function StaticRouter() {
var _temp, _this, _ret;
_classCallCheck(this, StaticRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.createHref = function (path) {
return addLeadingSlash(_this.props.basename + createURL(path));
}, _this.handlePush = function (location) {
var _this$props = _this.props,
basename = _this$props.basename,
context = _this$props.context;
context.action = 'PUSH';
context.location = addBasename(basename, createLocation(location));
context.url = createURL(context.location);
}, _this.handleReplace = function (location) {
var _this$props2 = _this.props,
basename = _this$props2.basename,
context = _this$props2.context;
context.action = 'REPLACE';
context.location = addBasename(basename, createLocation(location));
context.url = createURL(context.location);
}, _this.handleListen = function () {
return noop;
}, _this.handleBlock = function () {
return noop;
}, _temp), _possibleConstructorReturn(_this, _ret);
}
StaticRouter.prototype.getChildContext = function getChildContext() {
return {
router: {
staticContext: this.props.context
}
};
};
StaticRouter.prototype.render = function render() {
var _props = this.props,
basename = _props.basename,
context = _props.context,
location = _props.location,
props = _objectWithoutProperties(_props, ['basename', 'context', 'location']);
var history = {
createHref: this.createHref,
action: 'POP',
location: stripBasename(basename, createLocation(location)),
push: this.handlePush,
replace: this.handleReplace,
go: staticHandler('go'),
goBack: staticHandler('goBack'),
goForward: staticHandler('goForward'),
listen: this.handleListen,
block: this.handleBlock
};
return React.createElement(Router, _extends({}, props, { history: history }));
};
return StaticRouter;
}(React.Component);
StaticRouter.propTypes = {
basename: PropTypes.string,
context: PropTypes.object.isRequired,
location: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
};
StaticRouter.defaultProps = {
basename: '',
location: '/'
};
StaticRouter.childContextTypes = {
router: PropTypes.object.isRequired
};
export default StaticRouter; |
app/main.js | rolandaugusto/react-atm-simulator | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App.js';
ReactDOM.render(<App />, document.getElementById('root'));
|
examples/pagination/routes.js | lore/lore | import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
/**
* Wrapping the Master component with this decorator provides an easy way
* to redirect the user to a login experience if we don't know who they are.
*/
import UserIsAuthenticated from './src/decorators/UserIsAuthenticated';
/**
* Routes are used to declare your view hierarchy
* See: https://github.com/ReactTraining/react-router/blob/v3/docs/API.md
*/
import Master from './src/components/Master';
import Layout from './src/components/Layout';
export default (
<Route component={UserIsAuthenticated(Master)}>
<Route path="/" component={Layout} />
</Route>
);
|
src/js/Containers/Gallery.js | 7sleepwalker/addicted-to-mnt | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getPostGalleryByID } from '../Actions/galleryActions';
import ReturnHome from '../Components/returnHome.js';
import GalleryImage from '../Components/GalleryImage';
class Gallery extends Component {
componentWillMount() {
this.props.dispatch(getPostGalleryByID(this.props.match.params.id));
}
render() {
console.log(this.props);
const gallery = this.props.gallery.gallery;
let galleryRender;
let day = null;
let prevDay = -1;
if ( gallery ) {
galleryRender = gallery.map((item, n) => {
let featured=false, right=false;
if (n === 0) {
featured = true;
item.day = 'featured';
}
else if (n%2)
right = true;
if (prevDay !== item.day.toString())
day = item.day.toString();
else
day = null;
prevDay = item.day.toString();
return <GalleryImage key={n} id={n} content={item} featured={featured} right={right} day={day}/>
});
}
return (
<div className='gallery'>
<ReturnHome />
{galleryRender}
<div className='addictiv__page-number'> gallery </div>
</div>
);
}
}
const mapStateToProps = (state) => {
return {
gallery: state.gallery
};
};
export default connect(mapStateToProps)(Gallery);
|
src/components/itemsManager/ItemTypeRow.js | MrRandol/littleLight | /******************
REACT IMPORTS
******************/
import React from 'react';
import { View, Text, Image } from 'react-native';
/*****************
CUSTOM IMPORTS
******************/
import T from 'i18n-react';
var styles = require('../../styles/itemsManager/ItemTypeRow');
import * as BUNGIE from '../../utils/bungie/static';
import uid from 'uuid'
import Item from './Item'
var data = [];
class ItemTypeRow extends React.Component {
constructor(props) {
super(props);
}
getInventoryItem(index) {
return (
<Item
key={"inventoryItem-" + this.props.guardianId + index}
item={this.props.inventory ? this.props.inventory[index] : null}
itemOnPressCallback={this.showTransferModal.bind(this)}
styleRef='normal'
/>
);
}
getEquippedItem() {
return (
<Item
item={this.props.equipment ? this.props.equipment[0] : null}
itemOnPressCallback={this.showTransferModal.bind(this)}
styleRef='equipped'
/>
);
}
showTransferModal(item) {
this.props.showTransferModal.call(this, item, this.props.guardianId);
}
render() {
var data = [];
if (this.props.vault) {
var length = Math.max(this.props.inventory.length, 9);
data = Array(length).fill(null).map((item, index) => index );
} else {
data = Array(9).fill(null).map((item, index) => index );
}
var self = this;
var uid = this.props.vault ? 'vault' : this.props.guardianId;
var containerStyle = this.props.odd ? styles.itemTypeRowContainerOdd : styles.itemTypeRowContainer;
if (this.props.vault && data.length > 9) {
containerStyle = [containerStyle, {height: Math.ceil(data.length / 3) * 70 + 40}];
}
var emblemSource = this.props.vault ? BUNGIE.VAULT_ICON : BUNGIE.HOST+this.props.guardians[this.props.guardianId].emblemPath;
return(
<View key={"inventoryRow-" + uid} style={containerStyle} >
<View style={styles.itemTypeRowEquippedAndEmblem} >
<Image
style={styles.roundEmblem}
resizeMode="cover"
source={{uri: emblemSource}}
/>
{ !this.props.vault && this.getEquippedItem() }
</View>
<View style={styles.notEquippedItems}>
{
data.map(function (item) {
return self.getInventoryItem(item);
})
}
</View>
</View>
);
}
}
export default ItemTypeRow; |
actor-apps/app-web/src/app/components/modals/InviteUser.react.js | daodaoliang/actor-platform | import _ from 'lodash';
import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton } from 'material-ui';
import ActorTheme from 'constants/ActorTheme';
import ActorClient from 'utils/ActorClient';
import { KeyCodes } from 'constants/ActorAppConstants';
import InviteUserActions from 'actions/InviteUserActions';
import InviteUserByLinkActions from 'actions/InviteUserByLinkActions';
import ContactStore from 'stores/ContactStore';
import InviteUserStore from 'stores/InviteUserStore';
import ContactItem from './invite-user/ContactItem.react';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return ({
contacts: ContactStore.getContacts(),
group: InviteUserStore.getGroup(),
isOpen: InviteUserStore.isModalOpen()
});
};
const hasMember = (group, userId) =>
undefined !== _.find(group.members, (c) => c.peerInfo.peer.id === userId);
@ReactMixin.decorate(IntlMixin)
class InviteUser extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = _.assign({
search: ''
}, getStateFromStores());
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
InviteUserStore.addChangeListener(this.onChange);
ContactStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
InviteUserStore.removeChangeListener(this.onChange);
ContactStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
InviteUserActions.hide();
};
onContactSelect = (contact) => {
const { group } = this.state;
InviteUserActions.inviteUser(group.id, contact.uid);
};
onInviteUrlByClick = () => {
InviteUserByLinkActions.show(this.state.group);
InviteUserActions.hide();
};
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onSearchChange = (event) => {
this.setState({search: event.target.value});
};
render() {
const { contacts, group, search, isOpen } = this.state;
let contactList = [];
if (isOpen) {
_.forEach(contacts, (contact, i) => {
const name = contact.name.toLowerCase();
if (name.includes(search.toLowerCase())) {
if (!hasMember(group, contact.uid)) {
contactList.push(
<ContactItem contact={contact} key={i} onSelect={this.onContactSelect}/>
);
} else {
contactList.push(
<ContactItem contact={contact} key={i} isMember/>
);
}
}
}, this);
}
if (contactList.length === 0) {
contactList.push(
<li className="contacts__list__item contacts__list__item--empty text-center">
<FormattedMessage message={this.getIntlMessage('inviteModalNotFound')}/>
</li>
);
}
return (
<Modal className="modal-new modal-new--invite contacts"
closeTimeoutMS={150}
isOpen={isOpen}
style={{width: 400}}>
<header className="modal-new__header">
<a className="modal-new__header__icon material-icons">person_add</a>
<h4 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('inviteModalTitle')}/>
</h4>
<div className="pull-right">
<FlatButton hoverColor="rgba(74,144,226,.12)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</header>
<div className="modal-new__body">
<div className="modal-new__search">
<i className="material-icons">search</i>
<input className="input input--search"
onChange={this.onSearchChange}
placeholder={this.getIntlMessage('inviteModalSearch')}
type="search"
value={this.state.search}/>
</div>
<a className="link link--blue" onClick={this.onInviteUrlByClick}>
<i className="material-icons">link</i>
{this.getIntlMessage('inviteByLink')}
</a>
</div>
<div className="contacts__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
}
}
export default InviteUser;
|
stories/normal-login.js | wmzy/formsy-antd | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { Input, FormItem, Form, Checkbox } from 'formsy-antd';
import { Icon, Button } from 'antd';
function NormalLoginForm() {
const handleSubmit = data => {
action('submit')(data);
};
return (
<Form
style={{ maxWidth: '300px' }}
onSubmit={handleSubmit}
>
<FormItem>
<Input
name="username"
prefix={<Icon type="user" style={{ color: 'rgba(0,0,0,.25)' }} />}
placeholder="Username"
validations="required"
validationError="Please input your username!"
/>
</FormItem>
<FormItem>
<Input
name="password"
prefix={<Icon type="lock" style={{ color: 'rgba(0,0,0,.25)' }} />}
type="password"
placeholder="Password"
validations="required"
validationError="Please input your Password!"
/>
</FormItem>
<FormItem>
<Checkbox name="remember" value>Remember me</Checkbox>
<a style={{ float: 'right' }} href="">Forgot password</a>
<Button
style={{ width: '100%' }}
type="primary"
htmlType="submit"
>
Log in
</Button>
Or <a href="">register now!</a>
</FormItem>
</Form>
);
}
storiesOf('Form', module)
.add('normal-login', NormalLoginForm, {info: '普通的登录框,可以容纳更多的元素。'});
|
src/svg-icons/places/airport-shuttle.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesAirportShuttle = (props) => (
<SvgIcon {...props}>
<path d="M17 5H3c-1.1 0-2 .89-2 2v9h2c0 1.65 1.34 3 3 3s3-1.35 3-3h5.5c0 1.65 1.34 3 3 3s3-1.35 3-3H23v-5l-6-6zM3 11V7h4v4H3zm3 6.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm7-6.5H9V7h4v4zm4.5 6.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM15 11V7h1l4 4h-5z"/>
</SvgIcon>
);
PlacesAirportShuttle = pure(PlacesAirportShuttle);
PlacesAirportShuttle.displayName = 'PlacesAirportShuttle';
PlacesAirportShuttle.muiName = 'SvgIcon';
export default PlacesAirportShuttle;
|
hw6/frontend/src/components/footer.js | yusong-shen/comp531-web-development | /**
* Created by yusong on 10/23/16.
*/
import React from 'react'
const Footer = () => (
<div className="footer">
<p>
See the website's source code at <a href="https://github.com/yusong-shen/comp531-web-development/tree/master/hw5">Github</a>
</p>
<p>
Copyright : yusongtju@gmail.com
</p>
</div>
)
export default Footer
|
ui/src/main/js/components/TaskList.js | apache/aurora | import React from 'react';
import Icon from 'components/Icon';
import Pagination from 'components/Pagination';
import TaskListItem from 'components/TaskListItem';
import { isNully, pluralize } from 'utils/Common';
import { getClassForScheduleStatus, getLastEventTime } from 'utils/Task';
import { SCHEDULE_STATUS } from 'utils/Thrift';
// VisibleForTesting
export function searchTask(task, userQuery) {
const query = userQuery.toLowerCase();
return (task.assignedTask.instanceId.toString().startsWith(query) ||
(task.assignedTask.slaveHost && task.assignedTask.slaveHost.toLowerCase().includes(query)) ||
SCHEDULE_STATUS[task.status].toLowerCase().startsWith(query));
}
export function TaskListFilter({ numberPerPage, onChange, tasks }) {
if (tasks.length > numberPerPage) {
return (<div className='table-input-wrapper'>
<Icon name='search' />
<input
autoFocus
onChange={(e) => onChange(e)}
placeholder='Search tasks by instance-id, host or current status'
type='text' />
</div>);
}
return null;
}
export function TaskListStatus({ status }) {
return [
<span className={`img-circle ${getClassForScheduleStatus(ScheduleStatus[status])}`} />,
<span>{status}</span>
];
}
export function TaskListStatusFilter({ onClick, tasks }) {
const statuses = Object.keys(tasks.reduce((seen, task) => {
seen[SCHEDULE_STATUS[task.status]] = true;
return seen;
}, {}));
if (statuses.length <= 1) {
return (<div>
{pluralize(tasks, 'One task is ', `All ${tasks.length} tasks are `)}
<TaskListStatus status={statuses[0]} />
</div>);
}
return (<ul className='task-list-status-filter'>
<li>Filter by:</li>
<li onClick={(e) => onClick(null)}>all</li>
{statuses.map((status) => (<li key={status} onClick={(e) => onClick(status)}>
<TaskListStatus status={status} />
</li>))}
</ul>);
}
export function TaskListControls({ currentSort, onFilter, onSort, tasks }) {
return (<div className='task-list-controls'>
<ul className='task-list-main-sort'>
<li>Sort by:</li>
<li className={currentSort === 'default' ? 'active' : ''} onClick={(e) => onSort('default')}>
instance
</li>
<li className={currentSort === 'latest' ? 'active' : ''} onClick={(e) => onSort('latest')}>
updated
</li>
</ul>
<TaskListStatusFilter onClick={onFilter} tasks={tasks} />
</div>);
}
export default class TaskList extends React.Component {
constructor(props) {
super(props);
this.state = {
filter: props.filter,
reverseSort: props.reverse || false,
sortBy: props.sortBy || 'default'
};
}
setFilter(filter) {
this.setState({filter});
}
setSort(sortBy) {
if (sortBy === this.state.sortBy) {
this.setState({reverseSort: !this.state.reverseSort});
} else {
this.setState({sortBy});
}
}
render() {
const that = this;
const tasksPerPage = 25;
const filterFn = (t) => that.state.filter ? searchTask(t, that.state.filter) : true;
const sortFn = this.state.sortBy === 'latest'
? (t) => getLastEventTime(t) * -1
: (t) => t.assignedTask.instanceId;
const reasons = isNully(this.props.pendingReasons) ? {} : this.props.pendingReasons;
this.props.tasks.forEach((t) => {
if (t.status === ScheduleStatus.PENDING && reasons[t.assignedTask.taskId]) {
t.taskEvents[t.taskEvents.length - 1].message = reasons[t.assignedTask.taskId];
}
});
return (<div>
<TaskListFilter
numberPerPage={tasksPerPage}
onChange={(e) => that.setFilter(e.target.value)}
tasks={this.props.tasks} />
<TaskListControls
currentSort={this.state.sortBy}
onFilter={(query) => that.setFilter(query)}
onSort={(key) => that.setSort(key)}
tasks={this.props.tasks} />
<div className='task-list'>
<table className='psuedo-table'>
<Pagination
data={this.props.tasks}
filter={filterFn}
hideIfSinglePage
isTable
numberPerPage={tasksPerPage}
renderer={(t) => <TaskListItem key={t.assignedTask.taskId} task={t} />}
reverseSort={this.state.reverseSort}
sortBy={sortFn} />
</table>
</div>
</div>);
}
}
|
packages/react-vis/src/radial-chart/index.js | uber-common/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import PropTypes from 'prop-types';
import {pie as pieBuilder} from 'd3-shape';
import {AnimationPropType} from 'animation';
import ArcSeries from 'plot/series/arc-series';
import LabelSeries from 'plot/series/label-series';
import XYPlot from 'plot/xy-plot';
import {DISCRETE_COLOR_RANGE} from 'theme';
import {MarginPropType, getRadialLayoutMargin} from 'utils/chart-utils';
import {getRadialDomain} from 'utils/series-utils';
import {getCombinedClassName} from 'utils/styling-utils';
const predefinedClassName = 'rv-radial-chart';
const DEFAULT_RADIUS_MARGIN = 15;
/**
* Create the list of wedges to render.
* @param {Object} props
props.data {Object} - tree structured data (each node has a name anc an array of children)
* @returns {Array} Array of nodes.
*/
function getWedgesToRender({data, getAngle}) {
const pie = pieBuilder()
.sort(null)
.value(getAngle);
const pieData = pie(data).reverse();
return pieData.map((row, index) => {
return {
...row.data,
angle0: row.startAngle,
angle: row.endAngle,
radius0: row.data.innerRadius || 0,
radius: row.data.radius || 1,
color: row.data.color || index
};
});
}
function generateLabels(mappedData, accessors, labelsRadiusMultiplier = 1.1) {
const {getLabel, getSubLabel} = accessors;
return mappedData.reduce((res, row) => {
const {angle, angle0, radius} = row;
const centeredAngle = (angle + angle0) / 2;
// unfortunate, but true fact: d3 starts its radians at 12 oclock rather than 3
// and move clockwise rather than counter clockwise. why why why!
const updatedAngle = -1 * centeredAngle + Math.PI / 2;
const newLabels = [];
if (getLabel(row)) {
newLabels.push({
angle: updatedAngle,
radius: radius * labelsRadiusMultiplier,
label: getLabel(row)
});
}
if (getSubLabel(row)) {
newLabels.push({
angle: updatedAngle,
radius: radius * labelsRadiusMultiplier,
label: getSubLabel(row),
style: {fontSize: 10},
yOffset: 12
});
}
return res.concat(newLabels);
}, []);
// could add force direction here to make sure the labels dont overlap
}
/**
* Get the max radius so the chart can extend to the margin.
* @param {Number} width - container width
* @param {Number} height - container height
* @return {Number} radius
*/
function getMaxRadius(width, height) {
return Math.min(width, height) / 2 - DEFAULT_RADIUS_MARGIN;
}
function RadialChart(props) {
const {
animation,
className,
children,
colorType,
data,
getAngle,
getLabel,
getSubLabel,
height,
hideRootNode,
innerRadius,
labelsAboveChildren,
labelsRadiusMultiplier,
labelsStyle,
margin,
onMouseLeave,
onMouseEnter,
radius,
showLabels,
style,
width
} = props;
const mappedData = getWedgesToRender({
data,
height,
hideRootNode,
width,
getAngle
});
const radialDomain = getRadialDomain(mappedData);
const arcProps = {
colorType,
...props,
animation,
radiusDomain: [0, radialDomain],
data: mappedData,
radiusNoFallBack: true,
style,
arcClassName: 'rv-radial-chart__series--pie__slice'
};
if (radius) {
arcProps.radiusDomain = [0, 1];
arcProps.radiusRange = [innerRadius || 0, radius];
arcProps.radiusType = 'linear';
}
const maxRadius = radius ? radius : getMaxRadius(width, height);
const defaultMargin = getRadialLayoutMargin(width, height, maxRadius);
const labels = generateLabels(
mappedData,
{
getLabel,
getSubLabel
},
labelsRadiusMultiplier
);
return (
<XYPlot
height={height}
width={width}
margin={{
...defaultMargin,
...margin
}}
className={getCombinedClassName(className, predefinedClassName)}
onMouseLeave={onMouseLeave}
onMouseEnter={onMouseEnter}
xDomain={[-radialDomain, radialDomain]}
yDomain={[-radialDomain, radialDomain]}
>
<ArcSeries {...arcProps} getAngle={d => d.angle} />
{showLabels && !labelsAboveChildren && (
<LabelSeries data={labels} style={labelsStyle} />
)}
{children}
{showLabels && labelsAboveChildren && (
<LabelSeries data={labels} style={labelsStyle} />
)}
</XYPlot>
);
}
RadialChart.displayName = 'RadialChart';
RadialChart.propTypes = {
animation: AnimationPropType,
className: PropTypes.string,
colorType: PropTypes.string,
data: PropTypes.arrayOf(
PropTypes.shape({
angle: PropTypes.number,
className: PropTypes.string,
label: PropTypes.string,
radius: PropTypes.number,
style: PropTypes.object
})
).isRequired,
getAngle: PropTypes.func,
getAngle0: PropTypes.func,
padAngle: PropTypes.oneOfType([PropTypes.func, PropTypes.number]),
getRadius: PropTypes.func,
getRadius0: PropTypes.func,
getLabel: PropTypes.func,
height: PropTypes.number.isRequired,
labelsAboveChildren: PropTypes.bool,
labelsStyle: PropTypes.object,
margin: MarginPropType,
onValueClick: PropTypes.func,
onValueMouseOver: PropTypes.func,
onValueMouseOut: PropTypes.func,
showLabels: PropTypes.bool,
style: PropTypes.object,
subLabel: PropTypes.func,
width: PropTypes.number.isRequired
};
RadialChart.defaultProps = {
className: '',
colorType: 'category',
colorRange: DISCRETE_COLOR_RANGE,
padAngle: 0,
getAngle: d => d.angle,
getAngle0: d => d.angle0,
getRadius: d => d.radius,
getRadius0: d => d.radius0,
getLabel: d => d.label,
getSubLabel: d => d.subLabel
};
export default RadialChart;
|
packages/mineral-ui-icons/src/IconSettingsBackupRestore.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 IconSettingsBackupRestore(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M14 12c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2zm-2-9a9 9 0 0 0-9 9H0l4 4 4-4H5c0-3.87 3.13-7 7-7s7 3.13 7 7a6.995 6.995 0 0 1-11.06 5.7l-1.42 1.44A9 9 0 1 0 12 3z"/>
</g>
</Icon>
);
}
IconSettingsBackupRestore.displayName = 'IconSettingsBackupRestore';
IconSettingsBackupRestore.category = 'action';
|
src/Creatable.js | dmatteo/react-select | import React from 'react';
import Select from './Select';
import defaultFilterOptions from './utils/defaultFilterOptions';
import defaultMenuRenderer from './utils/defaultMenuRenderer';
const Creatable = React.createClass({
displayName: 'CreatableSelect',
propTypes: {
// Child function responsible for creating the inner Select component
// This component can be used to compose HOCs (eg Creatable and Async)
// (props: Object): PropTypes.element
children: React.PropTypes.func,
// See Select.propTypes.filterOptions
filterOptions: React.PropTypes.any,
// Searches for any matching option within the set of options.
// This function prevents duplicate options from being created.
// ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
isOptionUnique: React.PropTypes.func,
// Determines if the current input text represents a valid option.
// ({ label: string }): boolean
isValidNewOption: React.PropTypes.func,
// See Select.propTypes.menuRenderer
menuRenderer: React.PropTypes.any,
// Factory to create new option.
// ({ label: string, labelKey: string, valueKey: string }): Object
newOptionCreator: React.PropTypes.func,
// input change handler: function (inputValue) {}
onInputChange: React.PropTypes.func,
// input keyDown handler: function (event) {}
onInputKeyDown: React.PropTypes.func,
// new option click handler: function (option) {}
onNewOptionClick: React.PropTypes.func,
// See Select.propTypes.options
options: React.PropTypes.array,
// Creates prompt/placeholder option text.
// (filterText: string): string
promptTextCreator: React.PropTypes.func,
// Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option.
shouldKeyDownEventCreateNewOption: React.PropTypes.func,
},
// Default prop methods
statics: {
isOptionUnique,
isValidNewOption,
newOptionCreator,
promptTextCreator,
shouldKeyDownEventCreateNewOption
},
getDefaultProps () {
return {
filterOptions: defaultFilterOptions,
isOptionUnique,
isValidNewOption,
menuRenderer: defaultMenuRenderer,
newOptionCreator,
promptTextCreator,
shouldKeyDownEventCreateNewOption,
};
},
createNewOption () {
const {
isValidNewOption,
newOptionCreator,
onNewOptionClick,
options = [],
shouldKeyDownEventCreateNewOption
} = this.props;
if (isValidNewOption({ label: this.inputValue })) {
const option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey });
const isOptionUnique = this.isOptionUnique({ option });
// Don't add the same option twice.
if (isOptionUnique) {
if (onNewOptionClick) {
onNewOptionClick(option);
} else {
options.unshift(option);
this.select.selectValue(option);
}
}
}
},
filterOptions (...params) {
const { filterOptions, isValidNewOption, options, promptTextCreator } = this.props;
// TRICKY Check currently selected options as well.
// Don't display a create-prompt for a value that's selected.
// This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array.
const excludeOptions = params[2] || [];
const filteredOptions = filterOptions(...params) || [];
if (isValidNewOption({ label: this.inputValue })) {
const { newOptionCreator } = this.props;
const option = newOptionCreator({
label: this.inputValue,
labelKey: this.labelKey,
valueKey: this.valueKey
});
// TRICKY Compare to all options (not just filtered options) in case option has already been selected).
// For multi-selects, this would remove it from the filtered list.
const isOptionUnique = this.isOptionUnique({
option,
options: excludeOptions.concat(filteredOptions)
});
if (isOptionUnique) {
const prompt = promptTextCreator(this.inputValue);
this._createPlaceholderOption = newOptionCreator({
label: prompt,
labelKey: this.labelKey,
valueKey: this.valueKey
});
filteredOptions.unshift(this._createPlaceholderOption);
}
}
return filteredOptions;
},
isOptionUnique ({
option,
options
}) {
const { isOptionUnique } = this.props;
options = options || this.select.filterOptions();
return isOptionUnique({
labelKey: this.labelKey,
option,
options,
valueKey: this.valueKey
});
},
menuRenderer (params) {
const { menuRenderer } = this.props;
return menuRenderer({
...params,
onSelect: this.onOptionSelect,
selectValue: this.onOptionSelect
});
},
onInputChange (input) {
const { onInputChange } = this.props;
if (onInputChange) {
onInputChange(input);
}
// This value may be needed in between Select mounts (when this.select is null)
this.inputValue = input;
},
onInputKeyDown (event) {
const { shouldKeyDownEventCreateNewOption, onInputKeyDown } = this.props;
const focusedOption = this.select.getFocusedOption();
if (
focusedOption &&
focusedOption === this._createPlaceholderOption &&
shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })
) {
this.createNewOption();
// Prevent decorated Select from doing anything additional with this keyDown event
event.preventDefault();
} else if (onInputKeyDown) {
onInputKeyDown(event);
}
},
onOptionSelect (option, event) {
if (option === this._createPlaceholderOption) {
this.createNewOption();
} else {
this.select.selectValue(option);
}
},
render () {
const {
children = defaultChildren,
newOptionCreator,
shouldKeyDownEventCreateNewOption,
...restProps
} = this.props;
const props = {
...restProps,
allowCreate: true,
filterOptions: this.filterOptions,
menuRenderer: this.menuRenderer,
onInputChange: this.onInputChange,
onInputKeyDown: this.onInputKeyDown,
ref: (ref) => {
this.select = ref;
// These values may be needed in between Select mounts (when this.select is null)
if (ref) {
this.labelKey = ref.props.labelKey;
this.valueKey = ref.props.valueKey;
}
}
};
return children(props);
}
});
function defaultChildren (props) {
return (
<Select {...props} />
);
};
function isOptionUnique ({ option, options, labelKey, valueKey }) {
return options
.filter((existingOption) =>
existingOption[labelKey] === option[labelKey] ||
existingOption[valueKey] === option[valueKey]
)
.length === 0;
};
function isValidNewOption ({ label }) {
return !!label;
};
function newOptionCreator ({ label, labelKey, valueKey }) {
const option = {};
option[valueKey] = label;
option[labelKey] = label;
option.className = 'Select-create-option-placeholder';
return option;
};
function promptTextCreator (label) {
return `Create option "${label}"`;
}
function shouldKeyDownEventCreateNewOption ({ keyCode }) {
switch (keyCode) {
case 9: // TAB
case 13: // ENTER
case 188: // COMMA
return true;
}
return false;
};
module.exports = Creatable;
|
src/components/battlefield.js | SiAdcock/bg-prototype | import React from 'react';
import Card from './card';
class Battlefield extends React.Component {
render() {
const summoned = this.props.summoned.map(card => {
const key = `summoned-card-${card.id}`;
return (
<Card
key={key}
card={card}
/>
);
});
return (
<div className="battlefield">
{summoned}
</div>
);
}
}
export default Battlefield;
|
components/Auth/index.js | praida/admin | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import api from '../../api/'
import Form from '../../../praida/components/Form'
import FormField from '../../../praida/components/FormField'
import Message from 'praida-message'
import './styles.scss'
class Auth extends React.Component {
constructor (props) {
super(props)
this.onKeyPress = this.onKeyPress.bind(this)
this.userChanged = this.userChanged.bind(this)
this.passChanged = this.passChanged.bind(this)
this.testCredentials = this.testCredentials.bind(this)
this.dismissLoginError = this.dismissLoginError.bind(this)
if (this.props.user && this.props.pass) {
this.testCredentials()
}
}
userChanged (event) {
this.props.dispatch({
type: 'userChanged',
user: event.target.value
})
}
passChanged (event) {
this.props.dispatch({
type: 'passChanged',
pass: event.target.value
})
}
testCredentials () {
const creds = {
user: this.props.user,
pass: this.props.pass
}
api.testCredentials(this.props.dispatch, creds, this.props.searchQuery, this.props.searchFilters)
return false
}
onKeyPress (event) {
if (event.charCode === 13) {
this.testCredentials()
}
return false
}
dismissLoginError () {
this.props.dispatch({
type: 'dismissLoginError'
})
}
render () {
let loginErr
switch (this.props.loginError) {
case 401:
loginErr = 'Wrong username or password'
break
case 5:
loginErr = 'Oops, something went wrong. Please try again later.'
break
case 0:
default:
loginErr = null
break
}
let error = null
if (loginErr && !this.props.loggingIn) {
error = (
<Message className="loginError" level="error" onDismiss={this.dismissLoginError}>
<p>{loginErr}</p>
</Message>
)
}
const classes = ['auth']
if (this.props.loggedIn) {
classes.push('loggedIn')
}
const actions = [{
label: 'Login',
handler: this.testCredentials,
className: 'primaryBtn'
}]
return (
<Form
className={classes.join(' ')}
header="Sign in to PRAIDA"
actions={actions}
>
<FormField
id="username"
type="text"
label="Username"
onChange={this.userChanged}
defaultValue={this.props.user}
onKeyPress={this.onKeyPress}
/>
<FormField
id="password"
type="password"
label="Password"
onChange={this.passChanged}
defaultValue={this.props.pass}
onKeyPress={this.onKeyPress}
/>
{error}
</Form>
)
}
}
Auth.propTypes = {
dispatch: PropTypes.func.isRequired,
user: PropTypes.string.isRequired,
pass: PropTypes.string.isRequired,
loggingIn: PropTypes.bool.isRequired,
loginErr: PropTypes.number,
loggedIn: PropTypes.bool.isRequired,
searchQuery: PropTypes.string.isRequired,
searchFilters: PropTypes.object.isRequired,
}
module.exports = exports = connect()(Auth) |
fields/types/select/SelectField.js | danielmahon/keystone | import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import { FormInput } from '../../../admin/client/App/elemental';
/**
* TODO:
* - Custom path support
*/
module.exports = Field.create({
displayName: 'SelectField',
statics: {
type: 'Select',
},
valueChanged (newValue) {
// TODO: This should be natively handled by the Select component
if (this.props.numeric && typeof newValue === 'string') {
newValue = newValue ? Number(newValue) : undefined;
}
this.props.onChange({
path: this.props.path,
value: newValue,
});
},
renderValue () {
const { ops, value } = this.props;
const selected = ops.find(opt => opt.value === value);
return (
<FormInput noedit>
{selected ? selected.label : null}
</FormInput>
);
},
renderField () {
const { numeric, ops, path, value: val } = this.props;
// TODO: This should be natively handled by the Select component
const options = (numeric)
? ops.map(function (i) {
return { label: i.label, value: String(i.value) };
})
: ops;
const value = (typeof val === 'number')
? String(val)
: val;
return (
<div>
{/* This input element fools Safari's autocorrect in certain situations that completely break react-select */}
<input type="text" style={{ position: 'absolute', width: 1, height: 1, zIndex: -1, opacity: 0 }} tabIndex="-1"/>
<Select
simpleValue
name={this.getInputName(path)}
value={value}
options={options}
onChange={this.valueChanged}
/>
</div>
);
},
});
|
app/containers/SignIn/index.js | g00dman5/freemouthmedia | /*
*
* SignIn
*
*/
import React from 'react';
import Helmet from 'react-helmet';
export default class SignIn extends React.PureComponent {
constructor(props){
super(props);
this.state= {
email:"",
password:"",
}
}
handleEmail = (event)=> {
this.setState({
email:event.target.value
})
}
handlePassword = (event)=> {
this.setState({
password:event.target.value
})
}
signIn = () => {
var data = new FormData();
data.append("email",this.state.email);
data.append("password",this.state.password);
fetch("",{
method:"post",
body:data
})
.then(function(response){
return response.json();
})
.then(function(json){
if(json.success) {
alert(json.success);
}
else if (json.error) {
alert(json.error);
}
})
}
render() {
const bannerImage={
backgroundImage:"url(https://scontent-atl3-1.xx.fbcdn.net/v/t1.0-9/425176_10150581004417862_994448017_n.jpg?oh=7c454d2f298e22c78fc2799e24c8496b&oe=59969CD2)",
minHeight:"100vh",
backgroundSize:"cover",
backgroundAttachment:"scroll",
display:"block",
zIndex:"99999",
margin:"2px",
}
const inputStyle={
textAlign:"center",
}
return (
<div>
<Helmet title="SignIn" meta={[ { name: 'description', content: 'Description of SignIn' }]}/>
<div style={bannerImage}>
<div style={inputStyle}>
<input onChange={this.handleEmail} type="text" placeholder="Email"/>
<input onChange={this.handlePassword} type="password" placeholder="Password"/>
<input onTouchTap={this.signIn} type="submit" placeholder="Submit"/>
</div>
</div>
</div>
);
}
}
|
pages/_error.js | Meadowcottage/meadowcottagexyz | import React from 'react'
import { Zoom } from 'animate-components'
import stylesheet from '../styles/_error.scss'
export default class Error extends React.Component {
static getInitialProps ({ res, jsonPageRes }) {
const statusCode = res ? res.statusCode : (jsonPageRes ? jsonPageRes.status : null)
return { statusCode }
}
render () {
return (
<div className='_error'>
<style dangerouslySetInnerHTML={{ __html: stylesheet }} />
<Zoom as='h1' duration='1s'>{this.props.statusCode}</Zoom>
<Zoom as='div' duration='1.5s' className='_errorDescription'>
<p>An error occurred</p>
</Zoom>
</div>
)
}
}
|
src/Interpolate.js | mmartche/boilerplate-shop | // https://www.npmjs.org/package/react-interpolate-component
// TODO: Drop this in favor of es6 string interpolation
import React from 'react';
import ValidComponentChildren from './utils/ValidComponentChildren';
const REGEXP = /\%\((.+?)\)s/;
const Interpolate = React.createClass({
displayName: 'Interpolate',
propTypes: {
component: React.PropTypes.node,
format: React.PropTypes.string,
unsafe: React.PropTypes.bool
},
getDefaultProps() {
return {
component: 'span',
unsafe: false
};
},
render() {
let format = (ValidComponentChildren.hasValidComponent(this.props.children) ||
(typeof this.props.children === 'string')) ?
this.props.children : this.props.format;
let parent = this.props.component;
let unsafe = this.props.unsafe === true;
let props = {...this.props};
delete props.children;
delete props.format;
delete props.component;
delete props.unsafe;
if (unsafe) {
let content = format.split(REGEXP).reduce((memo, match, index) => {
let html;
if (index % 2 === 0) {
html = match;
} else {
html = props[match];
delete props[match];
}
if (React.isValidElement(html)) {
throw new Error('cannot interpolate a React component into unsafe text');
}
memo += html;
return memo;
}, '');
props.dangerouslySetInnerHTML = { __html: content };
return React.createElement(parent, props);
}
let kids = format.split(REGEXP).reduce((memo, match, index) => {
let child;
if (index % 2 === 0) {
if (match.length === 0) {
return memo;
}
child = match;
} else {
child = props[match];
delete props[match];
}
memo.push(child);
return memo;
}, []);
return React.createElement(parent, props, kids);
}
});
export default Interpolate;
|
client/src/components/privateRoute/index.js | csleary/nemp3 | import { Redirect, Route } from 'react-router-dom';
import { shallowEqual, useSelector } from 'react-redux';
import PropTypes from 'prop-types';
import React from 'react';
const PrivateRoute = ({ component: PrivateComponent, ...rest }) => {
const { user } = useSelector(state => state, shallowEqual);
return (
<Route
{...rest}
render={props => {
if (!user.auth) {
return (
<Redirect
to={{
pathname: '/login',
state: { from: props.location }
}}
/>
);
}
return <PrivateComponent {...props} />;
}}
/>
);
};
PrivateRoute.propTypes = {
component: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
location: PropTypes.object
};
export default PrivateRoute;
|
cryptography/lab2/client/components/LoginForm.js | Drapegnik/bsu | import React from 'react';
import { Text, View, TextInput, StyleSheet, Button } from 'react-native';
const styles = StyleSheet.create({
labelWrapper: {
marginTop: 10,
marginBottom: 10,
},
label: {
fontSize: 17,
},
input: {
width: 200,
margin: 2.5,
padding: 7.5,
borderWidth: 1,
borderColor: 'lightgrey',
borderRadius: 5,
},
});
export default ({ user, password, onChange, onSubmit }) => (
<View>
<View style={styles.labelWrapper}>
<Text style={styles.label}>login:</Text>
</View>
<TextInput value={user} style={styles.input} onChangeText={user => onChange({ user })} />
<View style={styles.labelWrapper}>
<Text style={styles.label}>password:</Text>
</View>
<TextInput
secureTextEntry
value={password}
style={styles.input}
onChangeText={password => onChange({ password })}
/>
<Button onPress={onSubmit} title="Login" />
</View>
);
|
examples/admin/src/components/Link/index.js | aranja/tux | import React from 'react'
import classNames from 'classnames'
import HistoryLink from '../HistoryLink'
import './styles.css'
const Link = ({ className, ...props }) => (
<HistoryLink className={classNames('Link', className)} {...props} />
)
export default Link
|
src/routes/Invoicer/Editor/InvoiceItemsEditor/index.js | joshhunt/money | import React, { Component } from 'react';
import TextField from '../../TextField';
import styles from './styles.styl';
export default class InvoiceItemsEditor extends Component {
_fieldChanged(index, key, event) {
this.props.onFieldChange(index, key, event.target.value);
}
render() {
return (
<div className={styles.root}>
<h3>Invoice items</h3>
{this.props.items.map((item, index) => {
return (
<div key={index} className={styles.fieldRow}>
<TextField
className={styles.largeField}
label='Description'
value={item.description}
onChange={this._fieldChanged.bind(this, index, 'description')}
/>
<TextField
className={styles.smallField}
label='Days'
value={item.quantity}
onChange={this._fieldChanged.bind(this, index, 'quantity')}
/>
<TextField
className={styles.smallField}
label='Rate'
value={item.rate}
onChange={this._fieldChanged.bind(this, index, 'rate')}
/>
<TextField
className={styles.smallField}
label='Amount'
value={item.amount}
onChange={this._fieldChanged.bind(this, index, 'amount')}
/>
</div>
);
})}
</div>
);
}
} |
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | r3lik/r3lik.github.io | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
app/core/atoms/Paragraph/index.js | codejunkienick/starter-lapis | import React from 'react';
const Paragraph = ({ children }: { children: React$Element<any> }) =>
<p>
{children}
</p>;
export default Paragraph;
|
node_modules/eslint-config-airbnb/test/test-react-order.js | CamAndPineapple/NES6-Platformer | import test from 'tape';
import { CLIEngine } from 'eslint';
import eslintrc from '../';
import baseConfig from '../base';
import reactRules from '../rules/react';
const cli = new CLIEngine({
useEslintrc: false,
baseConfig: eslintrc,
// This rule fails when executing on text.
rules: {indent: 0},
});
function lint(text) {
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
return cli.executeOnText(text).results[0];
}
function wrapComponent(body) {
return `
import React from 'react';
export default class MyComponent extends React.Component {
${body}
}
`;
}
test('validate react prop order', t => {
t.test('make sure our eslintrc has React linting dependencies', t => {
t.plan(2);
t.equal(baseConfig.parser, 'babel-eslint', 'uses babel-eslint');
t.equal(reactRules.plugins[0], 'react', 'uses eslint-plugin-react');
});
t.test('passes a good component', t => {
t.plan(3);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
someMethod() {}
renderDogs() {}
render() { return <div />; }
`));
t.notOk(result.warningCount, 'no warnings');
t.notOk(result.errorCount, 'no errors');
t.deepEquals(result.messages, [], 'no messages in results');
});
t.test('order: when random method is first', t => {
t.plan(2);
const result = lint(wrapComponent(`
someMethod() {}
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
t.test('order: when random method after lifecycle methods', t => {
t.plan(2);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
someMethod() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
});
|
www/ui/getting-started/saucelabs.js | ForbesLindesay/cabbie | import React from 'react';
import Heading from '../styling/heading';
import CodeBlock from '../documentation/code-block';
import Example from '../examples/saucelabs';
const dotenvExample = 'SAUCE_USERNAME={your sauce username}\nSAUCE_ACCESS_KEY={your sauce access key}';
function Documentation() {
return (
<div>
<Heading>Sauce Labs</Heading>
<p>
Sauce labs is a cloud provider. It requires a monthly or yearly subscription, but offers free plans for
open source projects.
</p>
<p>
Start by signing up for an account at{' '}<a href="https://saucelabs.com/">saucelabs.com</a>,
then set the following environment variables:
</p>
<dl>
<dt>SAUCE_USERNAME</dt>
<dd>Your sauce labs username.</dd>
<dt>SAUCE_ACCESS_KEY</dt>
<dd>Your sauce labs access key.</dd>
</dl>
<p>
To do this locally, you can create
a{' '}<a href="https://github.com/motdotla/dotenv"><code>.env</code></a>{' '}file in your project's
root directory:
</p>
<CodeBlock>{dotenvExample}</CodeBlock>
<p>Then you can test using code like:</p>
<Example />
</div>
);
}
export default Documentation;
|
source/client/index.js | gacosta89/knightsTour | // redux provider
import { Provider } from 'react-redux';
// store
import createStore from 'client/store';
// react
import React from 'react';
import { render } from 'react-dom';
// app component
import createApp from 'shared/components/app';
// actions
import { impSolutionFactory } from 'shared/actions/import';
// services
import codepenFactory from 'shared/util/codepen';
import 'static/MorrisRoman-Black.ttf';
const store = createStore(),
codepen = codepenFactory(),
impSolution = impSolutionFactory(codepen);
const App = createApp({impSolution});
const props = window.payload || {
title: 'Default client title'
};
render(
<Provider store={store}>
<App { ...props } />
</Provider>,
document.getElementById('root')
);
|
src/pages/index.js | kettui/tla-site | import React, { Component } from 'react';
import Link from 'gatsby-link';
import YouTube from 'react-youtube';
import queryString from 'query-string';
import axios from 'axios';
import ApplicationForm from '../components/ApplicationForm';
import BackgroundVideo from '../components/BackgroundVideo';
import TLALogo from "../assets/tla-small.png";
import GW2Logo from "../assets/GW2Logo.png";
import DiscordLogo from "../assets/Discord-Logo-Color.svg";
import { AuthParameters, COOLDOWN_KEY, DISCORD_API_BASE, SESSION_INFO_KEY, DISCORD_INFO_KEY, TLA_GUILD_INVITE_LINK } from "../constants";
class IndexPage extends Component {
static initialState = {
hasApplied: false,
loggedIn: false,
session: {},
user: {},
};
state = IndexPage.initialState;
componentDidMount() {
const { hash } = window.location;
if(hash.length > 0) {
return this.initializeSession(hash);
}
this.checkSession();
}
initializeSession = (hash) => {
const authParams = queryString.parse(hash);
const paramKeys = Object.keys(authParams);
if((paramKeys.length === AuthParameters.keys) && paramKeys.every((param, i) => param === AuthParameters[i])) {
console.log("blahg");
return;
}
authParams.expire_time = Date.now() + (parseInt(authParams.expires_in, 10) * 1000);
localStorage.setItem(SESSION_INFO_KEY, JSON.stringify(authParams));
this.setState({ session: authParams });
location.replace(location.origin);
}
checkSession = () => {
const sessionStr = localStorage.getItem(SESSION_INFO_KEY);
// No previous login session
if(!sessionStr) {
return;
}
const session = JSON.parse(sessionStr);
// Session expired
if(Date.now() >= session.expire_time) {
console.log("Token expired");
this.resetSession();
return;
}
const discordInfoStr = localStorage.getItem(DISCORD_INFO_KEY);
if(!discordInfoStr && session.access_token) {
console.log("Token is active but no Discord info found");
return this.fetchDiscordInfo(session);
}
const user = JSON.parse(discordInfoStr);
const cooldown = localStorage.getItem(`${COOLDOWN_KEY}_${user.id}`);
let hasApplied = false;
if(cooldown) {
if(Date.now() >= cooldown) {
localStorage.removeItem(`${COOLDOWN_KEY}_${user.id}`);
} else {
hasApplied = true;
}
}
this.setState({
hasApplied,
session,
user,
loggedIn: true
});
}
resetSession = () => {
console.log("Cleaning up session details from localStorage");
localStorage.removeItem(SESSION_INFO_KEY);
localStorage.removeItem(DISCORD_INFO_KEY);
this.setState(IndexPage.initialState);
}
fetchDiscordInfo = async (session) => {
const { access_token, token_type } = session;
try {
const { data } = await axios({
url: `${DISCORD_API_BASE}/users/@me`,
method: "GET",
headers: {
Authorization: `${token_type} ${access_token}`,
}
});
if(!data || !data.id) {
// probably not a legit scenario, but validation is validation
return;
}
localStorage.setItem(DISCORD_INFO_KEY, JSON.stringify(data));
this.setState({
session,
user: data,
loggedIn: true,
});
} catch(e) {
// login failed
console.error(e);
}
}
setApplicationCooldown = () => {
localStorage.setItem(`${COOLDOWN_KEY}_${this.state.user.id}`, Date.now() + 86400000);
this.setState({ hasApplied: true });
}
render() {
const { hasApplied, session, loggedIn, user } = this.state;
return (
<div>
<section
id="top"
className="top-container">
<div className="video-background">
<div className="video-foreground">
<BackgroundVideo />
</div>
</div>
<div className="video-overlay">
<div className="title-container">
<div className="main-title glow-blue">
<span>
<span className="initial text-blue">T</span>
<span>housand </span>
<span className="initial text-blue">L</span>
<span>akes </span>
<span className="initial text-blue">A</span>
<span>lliance</span>
</span>
</div>
<div className="main-description">
<span className="main-description__text glow-pink">Desolation EU</span>
</div>
</div>
</div>
</section>
<section
id="about-us"
className="about-us">
<div className="about-us__content">
<div className="about-us__intro card">
<div className="flex-between">
<div className="title">
Tietoa meistä
</div>
<div className="links">
<a
href={TLA_GUILD_INVITE_LINK}
rel="noopener noreferrer"
className="navigation__link"
target="_blank">
<img
src={DiscordLogo}
className="fa fa-discord"
/>
</a>
<a
href="https://www.facebook.com/groups/TheTLA/"
rel="noopener noreferrer"
className="navigation__link"
target="_blank">
<i className="fa fa-facebook" />
</a>
<a
href="http://www.youtube.com/user/1000LakesAlliance"
rel="noopener noreferrer"
className="navigation__link"
target="_blank">
<i className="fa fa-youtube" />
</a>
<a
href="http://steamcommunity.com/groups/tlakes"
rel="noopener noreferrer"
className="navigation__link"
target="_blank">
<i className="fa fa-steam" />
</a>
</div>
</div>
<b>[TLA] </b>
Thousand Lakes Alliance on <b>Guild Wars 2</b> -kilta, joka syntyi alun perin vuoden 2013 alussa, kun useat suomikillat Desolationilta yhdistivät voimansa. Voit tutustua meihin tarkemmin yllä listatuista palveluista.
</div>
<div className="about-us__groups">
<div className="about-us__group">
<div className="title">Tarjoamme jäsenillemme</div>
<div>
<div className="about-us__group__item">
Pelikokemuksen suomalaisten pelikavereiden kanssa.
</div>
<div className="about-us__group__item">
Discord serverin dankeilla memeillä
</div>
<div className="about-us__group__item">
<span>
Semiaikaansaamattoman mutta sinnikkään raidiryhmän (n. 1 raidi viikottain)
</span>
</div>
<div className="about-us__group__item">
<span>
Kokeneen coreporukan omiin WvW-juoksuihin (n. 10-20 henkeä, 1-2 raidia viikottain)
</span>
</div>
<div className="about-us__group__item">
Kiltahallin kaikilla herkuilla
</div>
<div className="about-us__group__item">
Peliseuraa ja juttua myös muissa peleissä
</div>
<div className="about-us__group__item">
Spesiaalieventtejä ja aktiviteetteja
</div>
</div>
</div>
<div className="about-us__group">
<div className="title">Jäseniltämme odotamme</div>
<div>
<div className="about-us__group__item">
Huumorintajua, tiimityöskentelytaitoa ja rehtiä asennetta.
</div>
<div className="about-us__group__item">
Täysi-ikäisyyttä, killan keski-ikä on n. 26 vuotta.
</div>
<div className="about-us__group__item">
Valmiutta kommunikoida kiltachatin lisäksi oman Discordin kautta.
</div>
</div>
</div>
</div>
</div>
<div className="flex center">
<div>
<div className="join-us">Liity joukkoon</div>
<i className="fa fa-angle-double-down fa-3x form-pointer" />
</div>
</div>
</section>
<section className="apply">
{ !loggedIn && (
<div className="login-overlay">
<div className="login-content">
<a
className="button"
href={`https://discordapp.com/api/oauth2/authorize?client_id=352516811331469322&scope=identify&response_type=token&redirect_uri=${process.env.REDIRECT_URI}`}>
<span>Kirjaudu sisään täyttääksesi hakemus</span>
</a>
<div className="hint">
Tarvitset Discord-tunnukset kirjautuaksesi sisään.
</div>
<div className="hint">
Nappia painamalla sinut ohjataan kirjautumissivulle.
</div>
</div>
</div>
) }
<ApplicationForm
hasApplied={hasApplied}
session={session}
loggedIn={loggedIn}
user={user}
logout={this.resetSession}
onSubmitApplication={this.setApplicationCooldown}
/>
</section>
<div className="contact">Ongelmia sivuston käytön kanssa? Ota yhteyttä Discordissa ciN#3758 tai ingame ciNi.1084. Päivitetty viimeksi 10.10.2017.</div>
</div>
);
}
}
export default IndexPage
|
packages/core/admin/admin/src/pages/SettingsPage/pages/Users/ListPage/utils/tableHeaders.js | wistityhq/strapi | import React from 'react';
import { Flex } from '@strapi/design-system/Flex';
import { Typography } from '@strapi/design-system/Typography';
import { Status } from '@strapi/helper-plugin';
const tableHeaders = [
{
name: 'firstname',
key: 'firstname',
metadatas: { label: 'Firstname', sortable: true },
},
{
name: 'lastname',
key: 'lastname',
metadatas: { label: 'Lastname', sortable: true },
},
{
key: 'email',
name: 'email',
metadatas: { label: 'Email', sortable: true },
},
{
key: 'roles',
name: 'roles',
metadatas: { label: 'Roles', sortable: false },
/* eslint-disable react/prop-types */
cellFormatter: ({ roles }) => {
return (
<Typography textColor="neutral800">{roles.map(role => role.name).join(',\n')}</Typography>
);
},
/* eslint-enable react/prop-types */
},
{
key: 'username',
name: 'username',
metadatas: { label: 'Username', sortable: true },
},
{
key: 'isActive',
name: 'isActive',
metadatas: { label: 'User status', sortable: false },
// eslint-disable-next-line react/prop-types
cellFormatter: ({ isActive }) => {
return (
<Flex>
<Status isActive={isActive} variant={isActive ? 'success' : 'danger'} />
<Typography textColor="neutral800">{isActive ? 'Active' : 'Inactive'}</Typography>
</Flex>
);
},
},
];
export default tableHeaders;
|
examples/src/app.js | mobile5dev/react-select | /* eslint react/prop-types: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import Select from 'react-select';
import './example.less';
import Creatable from './components/Creatable';
import Contributors from './components/Contributors';
import GithubUsers from './components/GithubUsers';
import CustomComponents from './components/CustomComponents';
import CustomRender from './components/CustomRender';
import Multiselect from './components/Multiselect';
import NumericSelect from './components/NumericSelect';
import BooleanSelect from './components/BooleanSelect';
import Virtualized from './components/Virtualized';
import States from './components/States';
ReactDOM.render(
<div>
<States label="States" searchable />
<Multiselect label="Multiselect" />
<Virtualized label="Virtualized" />
<Contributors label="Contributors (Async)" />
<GithubUsers label="Github users (Async with fetch.js)" />
<NumericSelect label="Numeric Values" />
<BooleanSelect label="Boolean Values" />
<CustomRender label="Custom Render Methods"/>
<CustomComponents label="Custom Placeholder, Option, Value, and Arrow Components" />
<Creatable
hint="Enter a value that's NOT in the list, then hit return"
label="Custom tag creation"
/>
</div>,
document.getElementById('example')
);
|
openex-front/src/components/AppThemeProvider.js | Luatix/OpenEx | import React from 'react';
import * as PropTypes from 'prop-types';
import { createTheme, ThemeProvider } from '@mui/material/styles';
import themeDark from './ThemeDark';
import themeLight from './ThemeLight';
import { useHelper } from '../store';
const AppThemeProvider = (props) => {
const { children } = props;
const theme = useHelper((helper) => {
const me = helper.getMe();
const settings = helper.getSettings();
const rawPlatformTheme = settings.platform_theme ?? 'auto';
const rawUserTheme = me?.user_theme ?? 'auto';
return rawUserTheme !== 'default' ? rawUserTheme : rawPlatformTheme;
});
let muiTheme = createTheme(themeDark());
if (theme === 'light') {
muiTheme = createTheme(themeLight());
}
return <ThemeProvider theme={muiTheme}>{children}</ThemeProvider>;
};
AppThemeProvider.propTypes = {
children: PropTypes.node,
};
export const ConnectedThemeProvider = AppThemeProvider;
|
src/svg-icons/navigation/arrow-downward.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationArrowDownward = (props) => (
<SvgIcon {...props}>
<path d="M20 12l-1.41-1.41L13 16.17V4h-2v12.17l-5.58-5.59L4 12l8 8 8-8z"/>
</SvgIcon>
);
NavigationArrowDownward = pure(NavigationArrowDownward);
NavigationArrowDownward.displayName = 'NavigationArrowDownward';
NavigationArrowDownward.muiName = 'SvgIcon';
export default NavigationArrowDownward;
|
src/components/TutorDropdown.js | fateseal/react-mtg-playtester | import React, { Component } from 'react';
import { connect } from 'react-redux';
import uniqBy from 'lodash/uniqBy';
import sortBy from 'lodash/sortBy';
import { LIBRARY, HAND } from '../constants/zoneTypes';
import { getCardsByZone } from '../reducers/playtester';
import { moveCard, shuffle } from '../actions/playtesterActions';
class TutorDropdown extends Component {
state = { value: 'choose' };
handleChange = event => {
const { moveCard, shuffle } = this.props;
moveCard({
id: parseInt(event.target.value, 10),
fromZone: LIBRARY,
toZone: HAND
});
shuffle();
};
render() {
const { cards } = this.props;
const items = uniqBy(cards, c => c.name);
const getTotalByName = name => cards.filter(c => c.name === name).length;
return (
<select
className="rmp--select tutor"
onChange={this.handleChange}
kind="light"
value={this.state.value}
>
<option value="choose" disabled>
Search library...
</option>
{sortBy(items, 'name').map(({ name, id }) => (
<option key={id} value={id}>
{name} ({getTotalByName(name)})
</option>
))}
</select>
);
}
}
const select = state => ({
cards: getCardsByZone(state, LIBRARY)
});
const actions = {
moveCard,
shuffle
};
export default connect(select, actions)(TutorDropdown);
|
src/js/components/game-of-life.js | morganney/gol | 'use strict'
import React from 'react'
import Legend from './legend'
import Status from './status'
import CellGrid from './cell-grid'
import Utils from '../utils'
const GENERATION_TIMESPAN = 2000
const NOT_RUNNING = 'game not running'
const RUNNING = 'game is running'
const ENDED = 'game has ended'
const ALIVE = 1
const DEAD = 0
class GameOfLife extends React.Component {
constructor (props) {
super(props)
this.generations = 1
this.state = {cells: [], status: NOT_RUNNING}
this.nextGeneration = this.nextGeneration.bind(this)
}
handleGridSizeChange (size) {
let cells = []
let status = NOT_RUNNING
this.generations = 1
if (this.timeout) {
clearTimeout(this.timeout)
}
if (parseInt(size, 10) !== 0) {
cells = Utils.getRandomMatrix(size)
status = RUNNING
}
this.setState({cells, status})
}
getRunningStatus () {
return `${RUNNING} generation ${this.generations}`
}
getEndedStatus () {
return `${ENDED} after ${this.generations} generations`
}
/**
* Determine the next generation of cells and whether the game has ended.
*
* @returns {Undefined}
*/
nextGeneration () {
let cells = []
let current = this.state.cells
let status = RUNNING
let foundLivingCell = false
this.state.cells.forEach((row, x) => {
cells[x] = []
row.forEach((cell, y) => {
let state = null
let numNeighbors = this.getNeighborCount(x, y)
if (cell === ALIVE) {
// determine if cell remains alive
state = (numNeighbors === 2 || numNeighbors === 3) ? ALIVE : DEAD
}
if (cell === DEAD) {
// determine if cell remains dead
state = numNeighbors === 3 ? ALIVE : DEAD
}
if (state === ALIVE) {
foundLivingCell = true
}
cells[x][y] = state
})
})
this.generations++
if (!foundLivingCell || JSON.stringify(cells) === JSON.stringify(current)) {
status = this.getEndedStatus()
this.generations = 1
}
this.setState({cells, status})
}
/**
* Checks the four corners and sides of cell (x,y) to see how many
* neighbors are alive.
*
* @param {Number} x
* @param {Number} y
*
* @returns {Number}
*/
getNeighborCount (x, y) {
let count = this.getCellState(x - 1, y - 1) + this.getCellState(x, y - 1)
count += this.getCellState(x + 1, y - 1) + this.getCellState(x - 1, y)
count += this.getCellState(x + 1, y) + this.getCellState(x - 1, y + 1)
count += this.getCellState(x, y + 1) + this.getCellState(x + 1, y + 1)
return count
}
/**
* Determines whether a cell is alive or not.
*
* NOTE: Wrapping of the grid sides is not in play here. If the cell is
* along the border it will be dead as determined by the rules.
*
* @param {Number} x
* @param {Number} y
*
* @returns {Undefined || Number}
*/
getCellState (x, y) {
let width = this.state.cells.length
let height = width
if (x < 0 || x >= width || y < 0 || y >= height) {
return 0
}
return this.state.cells[x][y]
}
render () {
let status = this.state.status
if (this.state.status === RUNNING) {
status = this.getRunningStatus()
this.timeout = setTimeout(this.nextGeneration, GENERATION_TIMESPAN)
}
return (
<div>
<Legend />
<Status status={status} />
<CellGrid cells={this.state.cells} />
</div>
)
}
}
export default GameOfLife
|
packages/wix-style-react/src/BadgeSelectItem/docs/index.story.js | wix/wix-style-react | import React from 'react';
import BadgeSelectItem from '../BadgeSelectItem';
import Box from '../../Box';
import {
header,
tabs,
tab,
description,
importExample,
title,
columns,
divider,
example,
playground,
api,
testkit,
} from 'wix-storybook-utils/Sections';
import { storySettings } from '../test/storySettings';
import * as examples from './examples';
export default {
category: storySettings.category,
storyName: storySettings.storyName,
component: BadgeSelectItem,
componentPath: '..',
componentProps: {
text: 'Badge select item title',
subtitle: 'Badge select item subtitle',
skin: 'warning',
},
sections: [
header({
component: (
<Box
width="500px"
backgroundColor="#f0f4f7"
padding="25px"
border="1px solid #e5e5e5"
>
<BadgeSelectItem text="Badge select item" suffix="Suffix" />
</Box>
),
}),
tabs([
tab({
title: 'Description',
sections: [
columns([
description({
title: 'Description',
text:
'An option builder for the `<DropdownLayout/>` component and its consumers.',
}),
]),
importExample(
`
// Use directly
import { BadgeSelectItem } from 'wix-style-react';
// Or use a builder
import { badgeSelectItemBuilder } from 'wix-style-react';
`,
),
divider(),
title('Examples'),
example({
title: 'Skin',
text:
"The component supports 13 different skins. Each skin represents a different status like warning or success. They are reflected in item's prefix.",
source: examples.skins,
}),
example({
title: 'Subtitle',
text:
'Additional information, like user email or address can be inserted to subtitle area.',
source: examples.subtitleExample,
}),
example({
title: 'Suffix',
text:
'Component has a suffix area. If plain text or icon is inserted, component automatically inverts the color when selected.',
source: examples.suffix,
}),
example({
title: 'Sizes',
text:
'The component supports 2 text sizes - medium (default) and small.',
source: examples.sizes,
}),
example({
title: 'Text cropping',
text:
'By default component wraps the text. If needed it can be configured to show ellipsis and display full value on hover.',
source: examples.textCropping,
}),
example({
title: 'Advanced Example',
text:
'All properties work together and can be combined in various ways. It can be rendered as standalone or as part of dropdown.',
source: examples.advancedExample,
}),
],
}),
...[
{ title: 'API', sections: [api()] },
{ title: 'Testkit', sections: [testkit()] },
{ title: 'Playground', sections: [playground()] },
].map(tab),
]),
],
};
|
src/svg-icons/notification/phone-forwarded.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationPhoneForwarded = (props) => (
<SvgIcon {...props}>
<path d="M18 11l5-5-5-5v3h-4v4h4v3zm2 4.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z"/>
</SvgIcon>
);
NotificationPhoneForwarded = pure(NotificationPhoneForwarded);
NotificationPhoneForwarded.displayName = 'NotificationPhoneForwarded';
NotificationPhoneForwarded.muiName = 'SvgIcon';
export default NotificationPhoneForwarded;
|
packages/design-system/src/templates/docs/Templates.stories.js | Talend/ui | import React from 'react';
import { Area } from '~docs';
import Template from '..';
import { Stepper } from '../../index';
export default {
title: 'Templates/Templates',
};
const args = {
header: <Area>Header</Area>,
nav: <Area style={{ width: '20rem' }}>Nav</Area>,
title: <Area>Title</Area>,
footer: <Area>Footer</Area>,
};
export const Card = props => (
<Template.Card {...props}>
<Area>Main</Area>
</Template.Card>
);
Card.args = args;
export const List = props => (
<Template.List {...props}>
<Area>Main</Area>
</Template.List>
);
List.args = args;
export const Full = props => (
<Template.Full {...props}>
<Area>Main</Area>
</Template.Full>
);
Full.args = args;
export const Step = props => (
<Template.Step {...props}>
<Area>Main</Area>
</Template.Step>
);
Step.args = {
...args,
stepper: (
<Stepper.Vertical>
<Stepper.Step.Validated>Validated</Stepper.Step.Validated>
<Stepper.Step.InProgress>InProgress</Stepper.Step.InProgress>
<Stepper.Step.Enabled>Enabled</Stepper.Step.Enabled>
</Stepper.Vertical>
),
};
|
client/components/settings/bank-accesses/confirm-delete-account.js | bnjbvr/kresus | import React from 'react';
import { connect } from 'react-redux';
import { translate as $t, displayLabel } from '../../../helpers';
import { get, actions } from '../../../store';
import { registerModal } from '../../ui/modal';
import ModalContent from '../../ui/modal/content';
import CancelAndDelete from '../../ui/modal/cancel-and-delete-buttons';
export const DELETE_ACCOUNT_MODAL_SLUG = 'confirm-delete-account';
const ConfirmDeleteModal = connect(
state => {
let accountId = get.modal(state).state;
let account = get.accountById(state, accountId);
let title = account ? displayLabel(account) : null;
return {
accountId,
title
};
},
dispatch => {
return {
deleteAccount(accountId) {
actions.deleteAccount(dispatch, accountId);
}
};
},
({ title, accountId }, { deleteAccount }) => {
return {
title,
handleDelete() {
deleteAccount(accountId);
}
};
}
)(props => {
return (
<ModalContent
title={$t('client.confirmdeletemodal.title')}
body={$t('client.settings.erase_account', { title: props.title })}
footer={<CancelAndDelete onDelete={props.handleDelete} />}
/>
);
});
registerModal(DELETE_ACCOUNT_MODAL_SLUG, () => <ConfirmDeleteModal />);
|
src/svg-icons/av/featured-play-list.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvFeaturedPlayList = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 8H3V9h9v2zm0-4H3V5h9v2z"/>
</SvgIcon>
);
AvFeaturedPlayList = pure(AvFeaturedPlayList);
AvFeaturedPlayList.displayName = 'AvFeaturedPlayList';
AvFeaturedPlayList.muiName = 'SvgIcon';
export default AvFeaturedPlayList;
|
src/svg-icons/alert/error-outline.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AlertErrorOutline = (props) => (
<SvgIcon {...props}>
<path d="M11 15h2v2h-2zm0-8h2v6h-2zm.99-5C6.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 8z"/>
</SvgIcon>
);
AlertErrorOutline = pure(AlertErrorOutline);
AlertErrorOutline.displayName = 'AlertErrorOutline';
AlertErrorOutline.muiName = 'SvgIcon';
export default AlertErrorOutline;
|
src/Spin/CubeGrid.js | Lobos/react-ui | import React from 'react'
import classnames from 'classnames'
import propTypes from './proptypes'
import _styles from '../styles/spin/_cube-grid.scss'
export default function CubeGrid (props) {
const { size, color, margin } = props
const className = classnames(
props.className,
_styles['cube-grid']
)
const style = {
width: size,
height: size,
margin
}
return (
<div style={style} className={className}>
{
[1, 2, 3, 4, 5, 6, 7, 8, 9].map(i => (
<div key={i} style={{backgroundColor: color}}
className={classnames(_styles.cube, _styles['cube' + i])} />
))
}
</div>
)
}
CubeGrid.propTypes = propTypes
|
src/index.js | g0v/react.vtaiwan.tw | "use strict"
import request from './utils/request'
import React from 'react'
import App from './App/App.jsx'
import Router, {Route} from 'react-router'
import ProposalBoard from './ProposalBoard/ProposalBoard.jsx'
import Proposal from './Proposal/Proposal.jsx'
import Category from './Category/Category.jsx'
import HTML from './HTML/HTML.jsx'
import 'normalize.css/normalize.css'
import './index.css'
const routes = (
<Route handler={App} path="/">
<Route name="proposals" path="/" handler={ProposalBoard} />
<Route name="about" path="/about/" handler={HTML} />
<Route name="how" path="/how/" handler={HTML} />
<Route name="tutorial" path="/tutorial/" handler={HTML} />
<Route name="proposal" path="/:proposalName/" handler={Proposal} />
<Route name="category" path="/:proposalName/:category/" handler={Category} />
<Route name="categoryPage" path="/:proposalName/:category/:page/" handler={Category} />
<Route name="categoryPagePost" path="/:proposalName/:category/:page/:postID/" handler={Category} />
</Route>
);
if(typeof document !== 'undefined') {
const root = document.getElementById('root');
Router.run(routes, Router.HistoryLocation, (Root) => {
React.render(<Root/>, root);
});
}
|
src/frontend/src/components/DonutChart.js | open-austin/influence-texas | import React from 'react'
import styled from 'styled-components'
import { PieChart, Pie, Tooltip, Cell } from 'recharts'
import { numberWithCommas } from 'utils'
import { useTheme } from '@material-ui/core'
const Wrapper = styled.div`
.large {
font-size: 50px;
font-weight: bold;
}
.recharts-default-legend {
margin-top: 50px !important;
}
.recharts-wrapper {
margin: auto;
}
`
/**
* @typedef {Object} Props
* @property {Array<{ name: string, color: string, value: number}>} data - slices of the chart
* @property {Number} totalCount - Total for middle
*/
/**
* @param {Props} props
*/
function DonutChart({
data = [{ name: 'loading', value: 100 }],
totalCount = 0,
totalText = 'Total',
selectedSlice = '',
loading,
}) {
const CHART_WIDTH = Math.min(440, window.innerWidth - 50)
const props = {
data,
cx: CHART_WIDTH / 2,
cy: CHART_WIDTH / 2,
paddingAngle: 2,
dataKey: 'value',
}
const { palette } = useTheme()
return (
<Wrapper>
<PieChart width={CHART_WIDTH} height={CHART_WIDTH}>
<Pie
{...props}
innerRadius={CHART_WIDTH / 2 - 30}
outerRadius={CHART_WIDTH / 2 - 10}
fill={palette.primary.main}
>
{data.map((entry, index) => {
return (
<Cell
key={`cell-${index}`}
fill={entry.name === selectedSlice ? '#ccc' : 'white'}
/>
)
})}
</Pie>
<Pie
{...props}
innerRadius={CHART_WIDTH / 2 - 30}
outerRadius={CHART_WIDTH / 2 - 10}
fill={loading ? '#ccc' : palette.primary.main}
></Pie>
<text x={CHART_WIDTH / 2} y={CHART_WIDTH / 2 + 20} textAnchor="middle">
{loading ? (
'loading'
) : (
<>
<tspan className="large">{numberWithCommas(totalCount)} </tspan>{' '}
{totalText}
</>
)}
</text>
<Tooltip />
</PieChart>
</Wrapper>
)
}
export default DonutChart
|
src/index.js | mazun/ExceedsTimer | import React from 'react';
import { render } from 'react-dom';
const CurrentAction = props => {
const { action } = props;
const text = action ? action.minute + "分 " + action.name + (action.note ? " (" + action.note + ")" : "") : "";
return (
<div>現: {text}</div>
);
};
const NextAction = props => {
const { action, date } = props;
const text = (() => {
if (action) {
const { name, minute } = action;
const second = action.second ? action.second : 0;
const m = date.getMinutes();
const s = date.getSeconds();
const restTotalSeconds = (minute * 60 + second) - (m * 60 + s);
const restMinute = Math.floor(restTotalSeconds / 60);
const restSeconds = restTotalSeconds % 60;
return minute + "分" + (second != 0 ? (second + "秒 ") : " ") + name + " (" + restMinute + ":" + ("0" + restSeconds).slice(-2) + ")"
} else {
return "";
}
})();
return (
<div className="small">次: {text}</div>
);
}
const Exceeds = props => {
const { data, date } = props;
const extract = (data, date) => {
const minute = date.getMinutes();
const second = date.getSeconds();
const actions = data.actions;
let i = 0;
for(; i < actions.length; i++) {
const m = actions[i].minute;
const s = actions[i].second ? actions[i].second : 0;
if(minute * 60 + second < m * 60 + s) break;
}
const current = 0 <= i - 1 && i - 1 < actions.length ? actions[i - 1] : undefined;
const next = 0 <= i && i < actions.length ? actions[i] : undefined;
return { current, next };
};
const { current, next } = extract(data, date);
return (
<div>
<h3>{data.title}</h3>
<p>現在時刻: {date.toLocaleTimeString()}</p>
<CurrentAction action={current} />
<NextAction action={next} date={date} />
</div>
);
};
setInterval(() => {
const date = new Date();
render(<Exceeds data={data} date={date} />, document.getElementById('app'));
}, 100);
|
client/mobile/src/components/Student/CourseAttendance.js | CongYunan/course_attendance | // 加载 React 相关组件
import React, { Component } from 'react';
// 加载 Ant Design 相关组件
import { message } from 'antd';
// 加载 Dva 相关组件
import { connect } from 'dva';
// 加载自定义组件
import { checkMapData } from '../../utils/Check';
// 加载样式
import Styles from '../../styles/CourseAttendance.less';
// 加载自定义组件
import CommonSearch from '../CommonSearch';
import CommonList from '../CommonList';
// 配置组件
message.config({
top: 40,
duration: 2,
});
// 创建 CourseAttendance 组件
class CourseAttendance extends Component {
// 自定义组件数据
datas = {
loginData: null, // 缓存登录数据
teacherCourseList: null, // 缓存教师授课列表
};
// 组件加载预处理方法
componentWillMount() {
const { mapLoginData } = this.props;
if (checkMapData(mapLoginData)) {
this.datas.loginData = mapLoginData.data[0]; // 缓存登录数据
let loginFp = this.datas.loginData['login_password'];
if (loginFp) {
this.props.dispatch({ // 获取授课列表
type: 'getTeacherCourseList/begin',
userRole: 'student',
userNo: this.datas.loginData['student_no'],
loginFp: loginFp,
listType: 'teacherCourse',
});
}
} else {
this.props.handleLoadingLayoutSwitch(true);
message.error('请先登录系统');
}
}
// 组件属性更新预处理方法
componentWillReceiveProps(newProps) {
const { mapTeacherCourseList } = newProps;
this.props.handleLoadingLayoutSwitch(mapTeacherCourseList.loading); // 显示loading
if (checkMapData(mapTeacherCourseList)) {
this.datas.teacherCourseList = mapTeacherCourseList.data; // 缓存教师授课列表数据
}
}
// 选择课程方法
handleChooseCourse(teacherCourseData) {
this.props.confirmAttendanceMessage.bind(this.props.parentThis, teacherCourseData)();
}
// 组件渲染方法
render() {
console.log(this.datas.teacherCourseList);
return (
<div className={Styles['course-attendance']}>
<CommonSearch />
<CommonList
dataSource={this.datas.teacherCourseList}
buttonText="选择课程"
parentThis={this}
buttonFunction={this.handleChooseCourse.bind(this)}
/>
</div>
);
}
}
// 定义待绑定的数据
const mapStateProps = (store) => {
return {
mapLoginData: store.getLoginData,
mapTeacherCourseList: store.getTeacherCourseList,
};
};
// 导出组件
export default connect(mapStateProps)(CourseAttendance); |
src/svg-icons/editor/insert-photo.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorInsertPhoto = (props) => (
<SvgIcon {...props}>
<path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
</SvgIcon>
);
EditorInsertPhoto = pure(EditorInsertPhoto);
EditorInsertPhoto.displayName = 'EditorInsertPhoto';
EditorInsertPhoto.muiName = 'SvgIcon';
export default EditorInsertPhoto;
|
packages/react-ui-components/src/Label/label.js | dimaip/neos-ui | import React from 'react';
import PropTypes from 'prop-types';
import mergeClassNames from 'classnames';
const Label = props => {
const {
children,
className,
htmlFor,
theme,
...rest
} = props;
const classNames = mergeClassNames({
[theme.label]: true,
[className]: className && className.length
});
return (
<label {...rest} htmlFor={htmlFor} className={classNames}>
{children}
</label>
);
};
Label.propTypes = {
/**
* The `for` standard html attribute, defined to make it always required.
*/
htmlFor: PropTypes.string.isRequired,
/**
* An optional className to render on the label node.
*/
className: PropTypes.string,
/**
* The children to render within the label node.
*/
children: PropTypes.node,
/**
* An optional css theme to be injected.
*/
theme: PropTypes.object
};
export default Label;
|
src/svg-icons/action/settings.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettings = (props) => (
<SvgIcon {...props}>
<path d="M19.43 12.98c.04-.32.07-.64.07-.98s-.03-.66-.07-.98l2.11-1.65c.19-.15.24-.42.12-.64l-2-3.46c-.12-.22-.39-.3-.61-.22l-2.49 1c-.52-.4-1.08-.73-1.69-.98l-.38-2.65C14.46 2.18 14.25 2 14 2h-4c-.25 0-.46.18-.49.42l-.38 2.65c-.61.25-1.17.59-1.69.98l-2.49-1c-.23-.09-.49 0-.61.22l-2 3.46c-.13.22-.07.49.12.64l2.11 1.65c-.04.32-.07.65-.07.98s.03.66.07.98l-2.11 1.65c-.19.15-.24.42-.12.64l2 3.46c.12.22.39.3.61.22l2.49-1c.52.4 1.08.73 1.69.98l.38 2.65c.03.24.24.42.49.42h4c.25 0 .46-.18.49-.42l.38-2.65c.61-.25 1.17-.59 1.69-.98l2.49 1c.23.09.49 0 .61-.22l2-3.46c.12-.22.07-.49-.12-.64l-2.11-1.65zM12 15.5c-1.93 0-3.5-1.57-3.5-3.5s1.57-3.5 3.5-3.5 3.5 1.57 3.5 3.5-1.57 3.5-3.5 3.5z"/>
</SvgIcon>
);
ActionSettings = pure(ActionSettings);
ActionSettings.displayName = 'ActionSettings';
ActionSettings.muiName = 'SvgIcon';
export default ActionSettings;
|
src/components/Footer/Footer.js | zsu13579/pinterest-apollo | /**
* 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 withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
class Footer extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© LV.com</span>
</div>
</div>
);
}
}
export default withStyles(s)(Footer);
|
blog/src/components/posts_index.js | williampuk/ReduxCasts | import _ from 'lodash';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { fetchPosts } from '../actions';
class PostsIndex extends Component {
componentDidMount() {
this.props.fetchPosts();
}
renderPosts() {
return _.map(this.props.posts, post => {
return (
<li className="list-group-item" key={post.id}>
<Link to={`/posts/${post.id}`}>
{post.title}
</Link>
</li>
);
});
}
render() {
return (
<div>
<div className="text-xs-right">
<Link className="btn btn-primary" to="/posts/new">
Add a Post
</Link>
</div>
<h3>Posts</h3>
<ul className="list-group">
{this.renderPosts()}
</ul>
</div>
);
}
}
function mapStateToProps(state) {
return { posts: state.posts };
}
export default connect(mapStateToProps, { fetchPosts })(PostsIndex);
|
docs/src/pages/components/text-fields/TextFieldSizes.js | lgollut/material-ui | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import TextField from '@material-ui/core/TextField';
const useStyles = makeStyles((theme) => ({
root: {
'& .MuiTextField-root': {
margin: theme.spacing(1),
width: 200,
},
},
}));
export default function TextFieldSizes() {
const classes = useStyles();
return (
<form className={classes.root} noValidate autoComplete="off">
<div>
<TextField label="Size" id="standard-size-small" defaultValue="Small" size="small" />
<TextField label="Size" id="standard-size-normal" defaultValue="Normal" />
</div>
<div>
<TextField
label="Size"
id="filled-size-small"
defaultValue="Small"
variant="filled"
size="small"
/>
<TextField label="Size" id="filled-size-normal" defaultValue="Normal" variant="filled" />
</div>
<div>
<TextField
label="Size"
id="outlined-size-small"
defaultValue="Small"
variant="outlined"
size="small"
/>
<TextField
label="Size"
id="outlined-size-normal"
defaultValue="Normal"
variant="outlined"
/>
</div>
</form>
);
}
|
sms_sponsorship/webapp/src/components/ChildDescription.js | CompassionCH/compassion-modules | import React from 'react';
import Typography from '@material-ui/core/Typography';
export default class extends React.Component {
getDescriptionJson = () => {
let div = document.createElement('div');
div.innerHTML = this.props.appContext.state.child.description;
let table = div.querySelector('table');
function s(selector) {
let elements = table.querySelectorAll(selector);
switch(elements.length) {
case 0:
return false;
case 1:
return elements[0].innerHTML;
default:
let result = [];
for (let i = 0; i < elements.length; i++) {
result.push(elements[i].innerHTML);
}
return result.join(", ");
}
}
function labelValue(parentClass, childClass) {
let result = {
label: s(parentClass + ' .desc_label' + childClass),
value: s(parentClass + ' .desc_value' + childClass),
};
return (result.label === false && result.value === false) ? false:result;
}
function labelValues(parentClass) {
let result = {
label: s(parentClass + ' ' + parentClass.replace('.', '#') + '_intro'),
value: s(parentClass + ' ' + parentClass.replace('.', '#') + '_list li'),
};
return (result.label === false && result.value === false) ? false:result;
}
return {
program_type: s('.program_type'),
birthday_estimate: s('.birthday_estimate'),
live_with: s('#live_with'),
family: {
// father_alive: labelValue('.father', '.is_alive'),
father_job: labelValue('.father_job', '.job'),
// mother_alive: labelValue('.mother', '.is_alive'),
mother_job: labelValue('.mother_job', '.job'),
brothers: labelValue('', '.brothers'),
sisters: labelValue('', '.sisters'),
},
school: {
school_attending: s('#school_attending'),
school_performance: labelValue('', '.school_performance'),
school_subject: labelValue('', '.school_subject'),
vocational_training: labelValue('', '.vocational_training'),
},
house_duties: labelValues('.house_duties'),
church_activities: labelValues('.church_activities'),
hobbies: labelValues('.hobbies'),
handicap: labelValues('.handicap'),
};
};
render() {
let description_json = this.getDescriptionJson();
return (
<div style={{marginTop: '8px', marginLeft: '8px'}}>
{Object.keys(description_json).map(item => <ChildDescriptionItem key={item} label={item} value={description_json[item]}/>)}
</div>
)
}
}
class ChildDescriptionItem extends React.Component {
render() {
const {value} = this.props;
if (!value) {
return "";
}
if (typeof value === 'object') {
let keys = Object.keys(value);
if (keys.length === 2 && value['label'] !== 'undefined') {
return <Typography variant="caption" gutterBottom>{value.label + " " + value.value}</Typography>;
}
return (
<div>
{keys.map(item => <ChildDescriptionItem key={item} label={item} value={value[item]}/>)}
</div>
)
}
return <Typography variant="caption" gutterBottom>{value}</Typography>;
}
} |
packages/eslint-config-universe/__tests__/fixtures/web-native-00.js | exponent/exponent | import React from 'react';
export default class Example extends React.Component {
state = {
x: 'x',
...{
y: 'y',
},
};
props;
static getInitialProps() {}
constructor(props, context) {
super(props, context);
this.state = {
...this.state,
x: props.x,
};
}
componentDidMount() {
fetch('http://example.com');
new XMLHttpRequest().send();
Uint16Array.from([1, 2, 3, 4, 5]);
new SharedArrayBuffer(16).slice();
}
shouldComponentUpdate() {}
render() {
return <div>{this.state.x}</div>;
}
_handleWhatever() {}
}
|
app/app.js | vingiesel/alljs | import React from 'react';
class MainApp extends React.Component {
render () {
return <p>hi</p>;
}
}
React.render(<MainApp />, document.body); |
assets/jqwidgets/demos/react/app/chart/columnserieswithmissingvalues/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxChart from '../../../jqwidgets-react/react_jqxchart.js';
class App extends React.Component {
render() {
let sampleData = [
{ Hour: 1, Sales: 135 },
{ Hour: 3, Sales: 145 },
{ Hour: 5, Sales: 90 },
{ Hour: 15, Sales: 66 },
{ Hour: 17, Sales: 43 },
{ Hour: 18, Sales: 122 },
{ Hour: 22, Sales: 59 },
{ Hour: 23, Sales: 70 }
];
let padding = { left: 5, top: 5, right: 10, bottom: 5 };
let titlePadding = { left: 90, top: 0, right: 0, bottom: 10 };
let xAxis =
{
dataField: 'Hour',
minValue: 0,
maxValue: 23,
unitInterval: 1,
valuesOnTicks: false,
labels: {
angle: 0,
formatFunction: (value) => {
return value.toString();
}
},
tickMarks: {
visible: true,
interval: 1
},
gridLines: {
visible: true,
interval: 3
}
};
let valueAxis =
{
visible: true,
minValue: 0,
maxValue: 200,
unitInterval: 50,
title: { text: 'Sales ($)<br>' },
labels: { horizontalAlignment: 'right' }
};
let seriesGroups =
[
{
type: 'column',
series: [
{ dataField: 'Sales', displayText: 'Sales', showLabels: true }
]
}
];
return (
<JqxChart style={{ width: 850, height: 500 }}
title={'Average store sales per hour'} description={''}
showLegend={true} enableAnimations={true} padding={padding}
titlePadding={titlePadding} source={sampleData} xAxis={xAxis}
valueAxis={valueAxis} colorScheme={'scheme02'} seriesGroups={seriesGroups}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
stories/examples/ListInline.js | reactstrap/reactstrap | import React from 'react';
import { List, ListInlineItem } from 'reactstrap';
const Example = (props) => {
return (
<List type="inline">
<ListInlineItem>Lorem ipsum</ListInlineItem>
<ListInlineItem>Phasellus iaculis</ListInlineItem>
<ListInlineItem>Nulla volutpat</ListInlineItem>
</List>
);
}
export default Example;
|
client/scripts/components/DiscoveryDetail.js | ahoarfrost/metaseek | import React from 'react';
import axios from 'axios';
import apiConfig from '../config/api.js';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import ColorPalette from './ColorPalette';
import Paper from 'material-ui/Paper';
import {Table, TableBody, TableFooter, TableHeader, TableHeaderColumn, TableRow, TableRowColumn} from 'material-ui/Table';
import RaisedButton from 'material-ui/RaisedButton';
// My component imports
import Header from './Header';
import VizDashboard from './VizDashboard';
import Loading from './Loading';
import {getReadableFileSizeString} from '../helpers';
import ExploreTable from './ExploreTable';
var apiRequest = axios.create({
baseURL: apiConfig.baseURL
});
var DiscoveryDetail = React.createClass({
getInitialState: function() {
return {
'discovery':{},
'summaryData': [],
'loaded': false,
'dataTable': {
'datasets': [],
'hasNext': false,
'hasPrevious' : false,
'nextUri' : "/datasets/search/2"
}
}
},
componentWillMount: function() {
var self = this;
apiRequest.get('/discovery/' + this.props.params.id)
.then(function (response) {
self.setState({"discovery": response.data.discovery});
apiRequest.post("/datasets/search/summary", {
"filter_params":response.data.discovery.filter_params
}).then(function (response) {
self.setState({"summaryData": response.data.summary, "loaded":true});
apiRequest.post("/datasets/search/1", {
"filter_params":self.state.discovery.filter_params,
}).then(function (response) {
self.setState({"dataTable":response.data,"loaded":true});
})
});
});
},
getPreviousDataPage : function() {
var self = this;
apiRequest.post(self.state.dataTable.previousUri, {
"filter_params":self.state.discovery.filter_params
}).then(function (response) {
self.setState({"dataTable":response.data});
});
},
getNextDataPage : function() {
var self = this;
apiRequest.post(self.state.dataTable.nextUri, {
"filter_params":self.state.discovery.filter_params
}).then(function (response) {
self.setState({"dataTable":response.data});
});
},
downloadIdCSV : function() {
var self = this;
var csvResultURL = apiConfig.baseURL + 'discovery/' + this.props.params.id + '/ids';
var downloadLink = document.createElement("a");
downloadLink.href = csvResultURL;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
},
downloadFullCSV : function() {
var self = this;
var csvResultURL = apiConfig.baseURL + 'discovery/' + this.props.params.id + '/download';
var downloadLink = document.createElement("a");
downloadLink.href = csvResultURL;
document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);
},
metadataDownloadLabel : function(threshold) {
if (this.state.summaryData.total_datasets < threshold) {
return "Download Full Metadata as .csv (~"+getReadableFileSizeString(this.state.summaryData.total_datasets*90*8)+")"
} else {
return "Data is too big for full download. Use the API!"
}
},
render: function() {
if (!this.state.loaded) return <Loading/>;
var tableHeaderStyles = {color:'#fff',fontFamily:'Roboto',fontSize:'14px',fontWeight:700};
const ruletypes = JSON.parse("{\"0\":\"=\", \"1\":\"<\", \"2\":\">\", \"3\":\"<=\", \"4\":\">=\", \"5\":\"=\", \"6\":\"!=\", \"7\":\"contains\", \"8\":\"is equal to\", \"9\": \"is not equal to\", \"10\":\"is not none\"}");
const n_threshold = 10000;
return (
<div>
<Header history={this.props.history}/>
<MuiThemeProvider muiTheme={getMuiTheme(ColorPalette)}>
<div className="discovery-details-container">
<Paper className="discovery-header" >
<h2>{this.state.discovery.discovery_title}</h2>
<h3>Discovery Details</h3>
<div className="discovery-description">
<span>{this.state.discovery.discovery_description}</span>
</div>
<div className="discovery-header-summary">
<div className="discovery-header-summary-left">
<span className="filterparam-table-title">Filter Parameters</span>
<div className="discovery-filterparam-table-container">
<Table className="filterparam-table" bodyStyle={{overflowX: 'scroll'}} fixedHeader={false} fixedFooter={false} selectable={false} style={{'tableLayout':'auto', 'overflow':'visible'}}>
<TableHeader className="discovery-filterparam-table-header" adjustForCheckbox={false} displaySelectAll={false} enableSelectAll={false}>
<TableRow selectable={false}>
<TableHeaderColumn style={tableHeaderStyles}>Field</TableHeaderColumn>
<TableHeaderColumn style={tableHeaderStyles}>Filter Type</TableHeaderColumn>
<TableHeaderColumn style={tableHeaderStyles}>Value</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody showRowHover={false} stripedRows={false} displayRowCheckbox={false} preScanRows={false}>
{JSON.parse(this.state.discovery.filter_params)["rules"].map( (rule, index) => (
<TableRow selectable={false} key={index}>
<TableRowColumn>{rule.field}</TableRowColumn>
<TableRowColumn>{ruletypes[JSON.stringify(rule.type)]}</TableRowColumn>
<TableRowColumn>{JSON.stringify(rule.value)}</TableRowColumn>
</TableRow>
))}
</TableBody>
</Table>
</div>
</div>
<div className="discovery-header-summary-right">
<span className="discovery-header-first"><span className="active">{this.state.summaryData.total_datasets} datasets</span></span>
<span className="discovery-header-second"> {getReadableFileSizeString(this.state.summaryData.total_download_size)} <span className="overview-title">Estimated Total Download Size</span></span>
<span className="discovery-header-user"><span>{"saved by metaseek user "+this.state.discovery.owner.firebase_name+" on "+this.state.discovery.timestamp.substr(0,16)}</span></span>
</div>
</div>
<div className="download-button-container">
<RaisedButton className="download-button-metadata"
label={"Download Dataset Ids as .csv (~"+getReadableFileSizeString(this.state.summaryData.total_datasets*4*8)+")"}
onClick={this.downloadIdCSV}
primary={true}
/>
<RaisedButton className="download-button-metadata"
label={this.metadataDownloadLabel(n_threshold)}
onClick={this.downloadFullCSV}
primary={true}
disabled={this.state.summaryData.total_datasets > n_threshold ? true : false}
/>
</div>
</Paper>
<Paper className="discovery-table">
<div className="discovery-datasets-title-container">
<span className="discovery-datasets-title">Datasets in This Discovery</span>
</div>
<ExploreTable getNextDataPage={this.getNextDataPage} getPreviousDataPage={this.getPreviousDataPage} dataTable={this.state.dataTable}/>
</Paper>
<VizDashboard wrapperClassName="discovery-child-grid" activeSummaryData={this.state.summaryData}/>
</div>
</MuiThemeProvider>
</div>
)
}
});
export default DiscoveryDetail;
|
src/components/HelpContents/UploadDialogHelp.js | synchu/schema | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import {Dialog, Button, Tabs, Tab} from 'react-toolbox'
import {InlineContent, EditCreateContent, UploadGeneralContent} from '../HelpContents/HelpContents'
import classes from './HelpDialog.scss'
export class UploadDialogHelp extends Component {
visible = true
static propTypes = {
helpActive: PropTypes.bool,
toggleHelp: PropTypes.func.isRequired
}
state = {
index: 0
}
constructor (props) {
super(props)
this.visible = true
}
handleVisibility = () => {
this.visible = false
this
.props
.toggleHelp()
}
handleTabChange = (index) => {
this.setState({index})
}
handleFixedTabChange = (index) => {
this.setState({fixedIndex: index})
}
handleInverseTabChange = (index) => {
this.setState({inverseIndex: index})
}
handleActive = () => {
console.log('Special one activated')
}
render = () => {
return (
<Dialog
active={this.visible}
theme={classes}
large
onEscKeyDown={this.handleVisibility}
onOverlayClick={this.handleVisibility}
title='SchemA application usage help'
style={{
overflow: 'auto',
height: '90%'
}}>
<div
style={{
overflow: 'auto',
minHeight: '80%',
maxHeight: '90%'
}}>
<div>
<strong>SchemA</strong> implements two features, allowing editing and uploading information:
<ul>
<li>Edit/Create amp item dialog</li>
<li>Inline editing within amplifier version item card</li>
</ul>
You cannot edit information in table view mode.
<br />
<br />
You must be logged and appropriately authorized in order to edit/create, inline edit amplifier information.
</div>
<br />
<section>
<Tabs index={this.state.index} onChange={this.handleTabChange}>
<Tab label='General'>
<UploadGeneralContent />
</Tab>
<Tab label='Edit/Create amp item'>
<EditCreateContent />
</Tab>
<Tab label='Inline Card Editing'>
<InlineContent />
</Tab>
</Tabs>
</section>
<Button
style={{
display: 'flex',
marginLeft: 'auto',
marginBottom: '10px'
}}
accent
label='X'
onClick={this.handleVisibility} />
</div>
</Dialog>
)
}
}
export default UploadDialogHelp
|
src/sunburst/index.js | Apercu/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import PropTypes from 'prop-types';
import {
hierarchy,
partition
} from 'd3-hierarchy';
import {
scaleLinear,
scaleSqrt
} from 'd3-scale';
import {AnimationPropType} from 'animation';
import LabelSeries from 'plot/series/label-series';
import ArcSeries from 'plot/series/arc-series';
import XYPlot from 'plot/xy-plot';
import {getRadialDomain} from 'utils/series-utils';
import {getRadialLayoutMargin} from 'utils/chart-utils';
const predefinedClassName = 'rv-sunburst';
const LISTENERS_TO_OVERWRITE = [
'onValueMouseOver',
'onValueMouseOut',
'onValueClick',
'onValueRightClick',
'onSeriesMouseOver',
'onSeriesMouseOut',
'onSeriesClick',
'onSeriesRightClick'
];
/**
* Create the list of nodes to render.
* @param {Object} props
props.data {Object} - tree structured data (each node has a name anc an array of children)
props.height {number} - the height of the graphic to be rendered
props.hideRootNode {boolean} - whether or not to hide the root node
props.width {number} - the width of the graphic to be rendered
* @returns {Array} Array of nodes.
*/
function getNodesToRender({data, height, hideRootNode, width}) {
const partitionFunction = partition();
const structuredInput = hierarchy(data).sum(d => d.size);
const radius = (Math.min(width, height) / 2) - 10;
const x = scaleLinear().range([0, 2 * Math.PI]);
const y = scaleSqrt().range([0, radius]);
return partitionFunction(structuredInput).descendants()
.reduce((res, cell, index) => {
if (hideRootNode && index === 0) {
return res;
}
return res.concat([{
angle0: Math.max(0, Math.min(2 * Math.PI, x(cell.x0))),
angle: Math.max(0, Math.min(2 * Math.PI, x(cell.x1))),
radius0: Math.max(0, y(cell.y0)),
radius: Math.max(0, y(cell.y1)),
depth: cell.depth,
parent: cell.parent,
...cell.data
}]);
}, []);
}
/**
* Convert arc nodes into label rows.
* Important to use mappedData rather than regular data, bc it is already unrolled
* @param {Array} mappedData - Array of nodes.
* @returns {Array} array of node for rendering as labels
*/
function buildLabels(mappedData) {
return mappedData
.filter(row => row.label)
.map(row => {
const truedAngle = -1 * row.angle + Math.PI / 2;
const truedAngle0 = -1 * row.angle0 + Math.PI / 2;
const angle = (truedAngle0 + truedAngle) / 2;
const rotateLabels = !row.dontRotateLabel;
const rotAngle = -angle / (2 * Math.PI) * 360;
return {
...row,
children: null,
angle: null,
radius: null,
x: row.radius0 * Math.cos(angle),
y: row.radius0 * Math.sin(angle),
// style: row.labelStyle,
style: {
textAnchor: rotAngle > 90 ? 'end' : 'start',
...row.labelStyle
},
rotation: rotateLabels ? (
rotAngle > 90 ? (rotAngle + 180) :
rotAngle === 90 ? 90 : (rotAngle)) : null
};
});
}
const NOOP = () => {};
class Sunburst extends React.Component {
render() {
const {
animation,
className,
children,
data,
height,
hideRootNode,
width,
colorType
} = this.props;
const mappedData = getNodesToRender({data, height, hideRootNode, width});
const radialDomain = getRadialDomain(mappedData);
const margin = getRadialLayoutMargin(width, height, radialDomain);
const labelData = buildLabels(mappedData);
const hofBuilder = f => (e, i) => f ? f(mappedData[e.index], i) : NOOP;
return (
<XYPlot
height={height}
width={width}
className={`${predefinedClassName} ${className}`}
margin={margin}
xDomain={[-radialDomain, radialDomain]}
yDomain={[-radialDomain, radialDomain]}>
<ArcSeries {...{
colorType,
...this.props,
animation,
radiusDomain: [0, radialDomain],
// need to present a stripped down version for interpolation
data: animation ?
mappedData.map((row, index) => ({...row, parent: null, children: null, index})) :
mappedData,
_data: animation ? mappedData : null,
arcClassName: `${predefinedClassName}__series--radial__arc`,
...(LISTENERS_TO_OVERWRITE.reduce((acc, propName) => {
const prop = this.props[propName];
acc[propName] = animation ? hofBuilder(prop) : prop;
return acc;
}, {}))
}}/>
{labelData.length > 0 && (<LabelSeries data={labelData} />)}
{children}
</XYPlot>
);
}
}
Sunburst.displayName = 'Sunburst';
Sunburst.propTypes = {
animation: AnimationPropType,
className: PropTypes.string,
colorType: PropTypes.string,
data: PropTypes.object.isRequired,
height: PropTypes.number.isRequired,
hideRootNode: PropTypes.bool,
onValueClick: PropTypes.func,
onValueMouseOver: PropTypes.func,
onValueMouseOut: PropTypes.func,
width: PropTypes.number.isRequired
};
Sunburst.defaultProps = {
className: '',
colorType: 'literal',
hideRootNode: false
};
export default Sunburst;
|
src/client/routes.js | steida/songary | import AddSong from './songs/add.react';
import App from './app/app.react';
import EditSong from './songs/edit.react';
import Home from './home/index.react';
import Latest from './songs/latest.react';
import Login from './auth/index.react';
import Me from './me/index.react';
import MySongs from './songs/my.react';
import NotFound from './components/notfound.react';
import React from 'react';
import Song from './songs/song.react';
import {DefaultRoute, NotFoundRoute, Route} from 'react-router';
export default (
<Route handler={App} path="/">
<DefaultRoute handler={Home} name="home" />
<NotFoundRoute handler={NotFound} name="not-found" />
<Route handler={AddSong} name="add-song" />
<Route handler={EditSong} name="songs-edit" path="songs/:id/edit" />
<Route handler={Login} name="login" />
<Route handler={Me} name="me" />
<Route handler={MySongs} name="my-songs" />
<Route handler={Latest} name="latest" path="latest/:createdAt?" />
<Route handler={Song} name="song" path="songs/:id" />
</Route>
);
|
src/components/Pagination.js | GriddleGriddle/Griddle | import React from 'react';
const Pagination = ({
Next,
Previous,
PageDropdown,
style,
className }) => (
<div style={style} className={className}>
{Previous && <Previous />}
{PageDropdown && <PageDropdown /> }
{Next && <Next /> }
</div>
);
export default Pagination;
|
app/routes.js | Andrew-Hird/bFM-desktop | // @flow
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import HomePage from './containers/HomePage';
import CounterPage from './containers/CounterPage';
export default (
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="/counter" component={CounterPage} />
</Route>
);
|
docs/src/app/components/pages/components/TimePicker/ExampleComplex.js | frnk94/material-ui | import React from 'react';
import TimePicker from 'material-ui/TimePicker';
export default class TimePickerExampleComplex extends React.Component {
constructor(props) {
super(props);
this.state = {value24: null, value12: null};
}
handleChangeTimePicker24 = (event, date) => {
this.setState({value24: date});
};
handleChangeTimePicker12 = (event, date) => {
this.setState({value12: date});
};
render() {
return (
<div>
<TimePicker
format="ampm"
hintText="12hr Format"
value={this.state.value12}
onChange={this.handleChangeTimePicker12}
/>
<TimePicker
format="24hr"
hintText="24hr Format"
value={this.state.value24}
onChange={this.handleChangeTimePicker24}
/>
</div>
);
}
}
|
docs/app/Examples/elements/Button/Variations/ButtonExampleColored.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Button } from 'semantic-ui-react'
const ButtonExampleColored = () => (
<div>
<Button color='red'>Red</Button>
<Button color='orange'>Orange</Button>
<Button color='yellow'>Yellow</Button>
<Button color='olive'>Olive</Button>
<Button color='green'>Green</Button>
<Button color='teal'>Teal</Button>
<Button color='blue'>Blue</Button>
<Button color='violet'>Violet</Button>
<Button color='purple'>Purple</Button>
<Button color='pink'>Pink</Button>
<Button color='brown'>Brown</Button>
<Button color='grey'>Grey</Button>
<Button color='black'>Black</Button>
</div>
)
export default ButtonExampleColored
|
upgrade-guides/v0.12-v0.13/es5/routes.js | lore/lore | import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
/**
* Wrapping the Master component with this decorator provides an easy way
* to redirect the user to a login experience if we don't know who they are.
*/
import UserIsAuthenticated from './src/decorators/UserIsAuthenticated';
/**
* Routes are used to declare your view hierarchy
* See: https://github.com/ReactTraining/react-router/blob/v3/docs/API.md
*/
import Master from './src/components/Master';
import Layout from './src/components/Layout';
export default (
<Route component={UserIsAuthenticated(Master)}>
<Route path="/" component={Layout} />
</Route>
);
|
components/textarea.js | volodalexey/spachat | import React from 'react'
import {element} from './element'
const Textarea = React.createClass({
renderExtraAttributes(){
let options = {}, config = this.props.config;
if (config.rows) {
options.rows = config.rows;
}
if (config.value !== "") {
options.value = config.value;
}
return options;
},
render() {
return (
<textarea {...element.renderAttributes(this.props, this.renderExtraAttributes())}>
{this.props.config.text}
</textarea>
)
}
});
export default Textarea; |
blueocean-material-icons/src/js/components/svg-icons/action/restore.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionRestore = (props) => (
<SvgIcon {...props}>
<path d="M13 3c-4.97 0-9 4.03-9 9H1l3.89 3.89.07.14L9 12H6c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.93 0-3.68-.79-4.94-2.06l-1.42 1.42C8.27 19.99 10.51 21 13 21c4.97 0 9-4.03 9-9s-4.03-9-9-9zm-1 5v5l4.28 2.54.72-1.21-3.5-2.08V8H12z"/>
</SvgIcon>
);
ActionRestore.displayName = 'ActionRestore';
ActionRestore.muiName = 'SvgIcon';
export default ActionRestore;
|
src/OffsetProvider.js | epotapov/react-fix | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import raf from 'raf';
function withOffsets(WrappedComponent) {
return class extends Component {
static propTypes = {
observeMutations: PropTypes.bool,
}
static defaultProps = {
observeMutations: true,
}
componentDidMount() {
this.events.forEach(event => window.addEventListener(event, this.recalc));
if (this.props.observeMutations) {
const config = { childList: true, subtree: true };
const callback = (mutationsList) => {
mutationsList.forEach((mutation) => {
if (mutation.type === 'childList') {
this.recalc();
}
});
};
const observer = new MutationObserver(callback);
observer.observe(this.node, config);
}
}
componentWillUnmount() {
this.events.forEach(event => window.removeEventListener(event, this.recalc));
}
subscribers = [];
subscribe = (handler) => {
this.subscribers = this.subscribers.concat(handler);
}
unsubscribe = (handler) => {
this.subscribers = this.subscribers.filter(current => current !== handler);
}
events = [
'resize',
'scroll',
'touchstart',
'touchmove',
'touchend',
'pageshow',
'load'
]
recalc = () => {
if (!this.framePending) {
raf(() => {
this.framePending = false;
const dimensions = this.node.getBoundingClientRect();
this.subscribers.forEach(handler => handler(dimensions));
});
this.framePending = true;
}
}
render() {
const {
...others
} = this.props;
return (
<WrappedComponent
subscribe={this.subscribe}
unsubscribe={this.unsubscribe}
initRef={(node) => {
this.node = node;
}}
{...others}
/>
);
}
};
}
export default withOffsets;
|
docs/src/app/components/pages/components/Divider/ExampleForm.js | ichiohta/material-ui | import React from 'react';
import Divider from 'material-ui/Divider';
import Paper from 'material-ui/Paper';
import TextField from 'material-ui/TextField';
const style = {
marginLeft: 20,
};
const DividerExampleForm = () => (
<Paper zDepth={2}>
<TextField hintText="First name" style={style} underlineShow={false} />
<Divider />
<TextField hintText="Middle name" style={style} underlineShow={false} />
<Divider />
<TextField hintText="Last name" style={style} underlineShow={false} />
<Divider />
<TextField hintText="Email address" style={style} underlineShow={false} />
<Divider />
</Paper>
);
export default DividerExampleForm;
|
src/index.js | lleohao/meow-ui | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
src/components/tableTeamComponent/tableTeamComponent.js | craigbilner/quizapp | 'use strict';
import React from 'react';
import radium from 'radium';
import PlayerSmartComponent from '../playerComponent/playerSmartComponent';
import PlayerComponent from '../playerComponent/playerComponent';
class TableTeamComponent extends React.Component {
constructor(props) {
super(props);
}
render() {
const compStyle = [
this.props.baseStyles.layout.columns,
this.props.baseStyles.layout.flex(1)
];
return (
<div style={compStyle}>
{
this.props.players
.sort((prev, next) => {
return prev.get('seat') < next.get('seat');
})
.map(player => {
return (
<PlayerSmartComponent
key={player.get('playerId')}
baseStyles={this.props.baseStyles}
>
<PlayerComponent
player={player}
baseStyles={this.props.baseStyles}
questioneeId={this.props.questioneeId}
answereeTeamType={this.props.answereeTeamType}
gameStatus={this.props.gameStatus}
round={this.props.round}
teamOwnQs={this.props.teamOwnQs}
/>
</PlayerSmartComponent>
);
})
}
</div>
);
}
}
TableTeamComponent.propTypes = {
players: React.PropTypes.object.isRequired,
baseStyles: React.PropTypes.object,
questioneeId: React.PropTypes.number,
answereeTeamType: React.PropTypes.number,
gameStatus: React.PropTypes.number.isRequired,
round: React.PropTypes.number.isRequired,
teamOwnQs: React.PropTypes.number.isRequired
};
TableTeamComponent.defaultProps = {};
export default radium(TableTeamComponent);
|
js/components/common/DatePicker.js | merodeadorNocturno/transfer | import React from 'react';
import DateSelect from 'react-datepicker';
import moment from 'moment';
class DatePicker extends React.Component {
constructor () {
super();
this.state = {startDate: moment() };
this.handleChange = this.handleChange.bind(this);
}
handleChange (date) {
this.setState({startDate: date});
}
render () {
const { id } = this.props;
return (
<DateSelect
id={id}
className="form-control"
selected={this.state.startDate}
onChange={this.handleChange} />
);
}
}
export default DatePicker; |
src/svg-icons/image/view-compact.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageViewCompact = (props) => (
<SvgIcon {...props}>
<path d="M3 19h6v-7H3v7zm7 0h12v-7H10v7zM3 5v6h19V5H3z"/>
</SvgIcon>
);
ImageViewCompact = pure(ImageViewCompact);
ImageViewCompact.displayName = 'ImageViewCompact';
ImageViewCompact.muiName = 'SvgIcon';
export default ImageViewCompact;
|
src/client/components/App.js | RossCasey/SecureDrop | import React, { Component } from 'react';
import {BrowserRouter, Route, Switch} from 'react-router-dom';
import Creator from './Creator';
import Drop from './Drop';
import BrowserSupport from './BrowserSupport';
import Error404 from './404';
import '../public/css/App.css';
import 'jquery';
import 'bootstrap';
class NavBarRight extends Component {
render() {
return (
<div id="navbar" className="navbar-collapse collapse">
<ul className="nav navbar-nav navbar-right">
<li><a href="/">Create</a></li>
</ul>
</div>
);
}
}
export default class App extends Component {
render() {
return (
<div>
<nav className="navbar navbar-inverse navbar-fixed-top">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar" aria-expanded="false" aria-controls="navbar">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"/>
<span className="icon-bar"/>
<span className="icon-bar"/>
</button>
<a className="navbar-brand" href="/">Secure Drop</a>
</div>
<NavBarRight/>
</div>
</nav>
<div className="container" role="main">
<div className="row">
<div className="col-xs-8 col-xs-offset-2">
<BrowserRouter>
<Switch>
<Route exact path="/" component={Creator}/>
<Route path="/drop/:dropId" component={Drop}/>
<Route path="/supportedBrowsers" component={BrowserSupport}/>
<Route component={Error404}/>
</Switch>
</BrowserRouter>
</div>
</div>
</div>
</div>
);
}
} |
docs/app/Examples/elements/Button/States/ButtonLoadingExample.js | jcarbo/stardust | import React from 'react'
import { Button } from 'stardust'
const ButtonLoadingExample = () => (
<div>
<Button loading>Loading</Button>
<Button basic loading>Loading</Button>
<Button loading primary>Loading</Button>
<Button loading secondary>Loading</Button>
</div>
)
export default ButtonLoadingExample
|
src/views/preview.js | zenoamaro/psd-viewer | /* @flow */
import React from 'react';
import PSD from 'psd';
import Highlight from './preview-highlight';
import Layer from './preview-layer';
let T = React.PropTypes;
export default React.createClass({
propTypes: {
psd: T.instanceOf(PSD).isRequired,
highlightedLayer: T.object
},
getInitialState() {
return {};
},
getScale() {
let {maxWidth} = this.state;
let image = this.props.psd.tree().width;
if (maxWidth && image > maxWidth) {
return maxWidth / image;
} else {
return 1;
}
},
componentDidMount() {
let container = this.refs.container.getDOMNode().clientWidth;
this.setState({ maxWidth: container });
},
render() {
let root = this.props.psd.tree();
let scale = this.getScale();
let height = scale * root.height;
let {highlightedLayer} = this.props;
return (
<div className='preview'>
<div ref="container"
className='preview--container'
style={{ height }}>
<div className='preview--layers'>
<Layer layer={root} scale={scale} />
</div>
<Highlight layer={highlightedLayer}
scale={scale} />
</div>
</div>
);
},
}); |
Libraries/Image/Image.ios.js | InterfaceInc/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Image
* @flow
*/
'use strict';
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ImageResizeMode = require('ImageResizeMode');
const ImageSourcePropType = require('ImageSourcePropType');
const ImageStylePropTypes = require('ImageStylePropTypes');
const NativeMethodsMixin = require('react/lib/NativeMethodsMixin');
const NativeModules = require('NativeModules');
const PropTypes = require('react/lib/ReactPropTypes');
const React = require('React');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const flattenStyle = require('flattenStyle');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const ImageViewManager = NativeModules.ImageViewManager;
/**
* A React component for displaying different types of images,
* including network images, static resources, temporary local images, and
* images from local disk, such as the camera roll.
*
* This exmaples shows both fetching and displaying an image from local storage as well as on from
* network.
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image } from 'react-native';
*
* class DisplayAnImage extends Component {
* render() {
* return (
* <View>
* <Image
* source={require('./img/favicon.png')}
* />
* <Image
* source={{uri: 'http://facebook.github.io/react/img/logo_og.png'}}
* />
* </View>
* );
* }
* }
*
* // App registration and rendering
* AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);
* ```
*
* You can also add `style` to an image:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image, StyleSheet} from 'react-native';
*
* const styles = StyleSheet.create({
* stretch: {
* width: 50,
* height: 200
* }
* });
*
*class DisplayAnImageWithStyle extends Component {
* render() {
* return (
* <View>
* <Image
* style={styles.stretch}
* source={require('./img/favicon.png')}
* />
* </View>
* );
* }
* }
*
* // App registration and rendering
* AppRegistry.registerComponent(
* 'DisplayAnImageWithStyle',
* () => DisplayAnImageWithStyle
* );
* ```
*/
const Image = React.createClass({
propTypes: {
/**
* > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the
* > `resizeMode` style property on `Image` components. The values are `contain`, `cover`,
* > `stretch`, `center`, `repeat`.
*/
style: StyleSheetPropType(ImageStylePropTypes),
/**
* The image source (either a remote URL or a local file resource).
*/
source: ImageSourcePropType,
/**
* A static image to display while loading the image source.
*
* - `uri` - a string representing the resource identifier for the image, which
* should be either a local file path or the name of a static image resource
* (which should be wrapped in the `require('./path/to/image.png')` function).
* - `width`, `height` - can be specified if known at build time, in which case
* these will be used to set the default `<Image/>` component dimensions.
* - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if
* unspecified, meaning that one image pixel equates to one display point / DIP.
* - `number` - Opaque type returned by something like `require('./image.jpg')`.
*
* @platform ios
*/
defaultSource: PropTypes.oneOfType([
// TODO: Tooling to support documenting these directly and having them display in the docs.
PropTypes.shape({
uri: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
scale: PropTypes.number,
}),
PropTypes.number,
]),
/**
* When true, indicates the image is an accessibility element.
* @platform ios
*/
accessible: PropTypes.bool,
/**
* The text that's read by the screen reader when the user interacts with
* the image.
* @platform ios
*/
accessibilityLabel: PropTypes.string,
/**
* blurRadius: the blur radius of the blur filter added to the image
* @platform ios
*/
blurRadius: PropTypes.number,
/**
* When the image is resized, the corners of the size specified
* by `capInsets` will stay a fixed size, but the center content and borders
* of the image will be stretched. This is useful for creating resizable
* rounded buttons, shadows, and other resizable assets. More info in the
* [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).
*
* @platform ios
*/
capInsets: EdgeInsetsPropType,
/**
* Determines how to resize the image when the frame doesn't match the raw
* image dimensions.
*
* - `cover`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal
* to or larger than the corresponding dimension of the view (minus padding).
*
* - `contain`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal to
* or less than the corresponding dimension of the view (minus padding).
*
* - `stretch`: Scale width and height independently, This may change the
* aspect ratio of the src.
*
* - `repeat`: Repeat the image to cover the frame of the view. The
* image will keep it's size and aspect ratio. (iOS only)
*/
resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']),
/**
* A unique identifier for this element to be used in UI Automation
* testing scripts.
*/
testID: PropTypes.string,
/**
* Invoked on mount and layout changes with
* `{nativeEvent: {layout: {x, y, width, height}}}`.
*/
onLayout: PropTypes.func,
/**
* Invoked on load start.
*
* e.g., `onLoadStart={(e) => this.setState({loading: true})}`
*/
onLoadStart: PropTypes.func,
/**
* Invoked on download progress with `{nativeEvent: {loaded, total}}`.
* @platform ios
*/
onProgress: PropTypes.func,
/**
* Invoked on load error with `{nativeEvent: {error}}`.
* @platform ios
*/
onError: PropTypes.func,
/**
* Invoked when load completes successfully.
*/
onLoad: PropTypes.func,
/**
* Invoked when load either succeeds or fails.
*/
onLoadEnd: PropTypes.func,
},
statics: {
resizeMode: ImageResizeMode,
/**
* Retrieve the width and height (in pixels) of an image prior to displaying it.
* This method can fail if the image cannot be found, or fails to download.
*
* In order to retrieve the image dimensions, the image may first need to be
* loaded or downloaded, after which it will be cached. This means that in
* principle you could use this method to preload images, however it is not
* optimized for that purpose, and may in future be implemented in a way that
* does not fully load/download the image data. A proper, supported way to
* preload images will be provided as a separate API.
*
* @param uri The location of the image.
* @param success The function that will be called if the image was sucessfully found and width
* and height retrieved.
* @param failure The function that will be called if there was an error, such as failing to
* to retrieve the image.
*
* @returns void
*
* @platform ios
*/
getSize: function(
uri: string,
success: (width: number, height: number) => void,
failure: (error: any) => void,
) {
ImageViewManager.getSize(uri, success, failure || function() {
console.warn('Failed to get size for image: ' + uri);
});
},
/**
* Prefetches a remote image for later use by downloading it to the disk
* cache
*
* @param url The remote location of the image.
*
* @return The prefetched image.
*/
prefetch(url: string) {
return ImageViewManager.prefetchImage(url);
},
},
mixins: [NativeMethodsMixin],
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
viewConfig: {
uiViewClassName: 'UIView',
validAttributes: ReactNativeViewAttributes.UIView
},
render: function() {
const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };
const {width, height, uri} = source;
const style = flattenStyle([{width, height}, styles.base, this.props.style]) || {};
const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108
const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108
if (uri === '') {
console.warn('source.uri should not be an empty string');
}
if (this.props.src) {
console.warn('The <Image> component requires a `source` property rather than `src`.');
}
return (
<RCTImageView
{...this.props}
style={style}
resizeMode={resizeMode}
tintColor={tintColor}
source={source}
/>
);
},
});
const styles = StyleSheet.create({
base: {
overflow: 'hidden',
},
});
const RCTImageView = requireNativeComponent('RCTImageView', Image);
module.exports = Image;
|
tests/lib/rules/vars-on-top.js | JedWatson/eslint | /**
* @fileoverview Tests for vars-on-top rule.
* @author Danny Fritz
* @author Gyandeep Singh
* @copyright 2014 Danny Fritz. All rights reserved.
* @copyright 2014 Gyandeep Singh. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var eslint = require("../../../lib/eslint"),
EslintTester = require("eslint-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var eslintTester = new EslintTester(eslint);
eslintTester.addRuleTest("lib/rules/vars-on-top", {
valid: [
[
"var first = 0;",
"function foo() {",
" first = 2;",
"}"
].join("\n"),
[
"function foo() {",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" if (true) {",
" first = true;",
" } else {",
" first = 1;",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" var third;",
" var fourth = 1, fifth, sixth = third;",
" var seventh;",
" if (true) {",
" third = true;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var i;",
" for (i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var outer;",
" function inner() {",
" var inner = 1;",
" var outer = inner;",
" }",
" outer = 1;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" //Hello",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" /*",
" Hello Clarice",
" */",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var first;",
" first = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var third;",
" third = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var bar = function(){",
" var third;",
" third = 5;",
" }",
" first = 5;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" first.onclick(function(){",
" var third;",
" third = 5;",
" });",
" first = 5;",
"}"
].join("\n"),
{
code: [
"function foo() {",
" var i = 0;",
" for (let j = 0; j < 10; j++) {",
" alert(j);",
" }",
" i = i + 1;",
"}"
].join("\n"),
ecmaFeatures: {
blockBindings: true
}
},
"'use strict'; var x; f();",
"'use strict'; 'directive'; var x; var y; f();",
"function f() { 'use strict'; var x; f(); }",
"function f() { 'use strict'; 'directive'; var x; var y; f(); }",
{code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}
],
invalid: [
{
code: [
"var first = 0;",
"function foo() {",
" first = 2;",
" second = 2;",
"}",
"var second = 0;"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" first = 1;",
" first = 2;",
" first = 3;",
" first = 4;",
" var second = 1;",
" second = 2;",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" if (true) {",
" var second = true;",
" }",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" for (var i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" for (i = 0; i < first; i ++) {",
" var second = i;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" switch (first) {",
" case 10:",
" var hello = 1;",
" break;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" var hello = 1;",
" } catch (e) {",
" alert('error');",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" asdf;",
" } catch (e) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" while (first) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" do {",
" var hello = 1;",
" } while (first == 10);",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" for (var item in first) {",
" item++;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"var foo = () => {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
ecmaFeatures: { arrowFunctions: true },
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: "'use strict'; 0; var x; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "'use strict'; var x; 'directive'; var y; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; 0; var x; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
}
]
});
|
src/svg-icons/toggle/check-box.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ToggleCheckBox = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.11 0 2-.9 2-2V5c0-1.1-.89-2-2-2zm-9 14l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z"/>
</SvgIcon>
);
ToggleCheckBox = pure(ToggleCheckBox);
ToggleCheckBox.displayName = 'ToggleCheckBox';
ToggleCheckBox.muiName = 'SvgIcon';
export default ToggleCheckBox;
|
anubis/ui/components/scratchpad/ScratchpadRecordsRowContainer.js | KawashiroNitori/Anubis | import React from 'react';
import classNames from 'classnames';
import { connect } from 'react-redux';
import TimeAgo from 'timeago-react';
import moment from 'moment';
import _ from 'lodash';
import { parse as parseMongoId } from '../../utils/mongoId';
import i18n from '../../utils/i18n';
import * as recordEnum from '../../constant/record';
const shouldShowDetail = (data) =>
recordEnum.STATUS_SCRATCHPAD_SHOW_DETAIL_FLAGS[data.status];
const isPretest = (data) =>
data.type === recordEnum.TYPE_PRETEST;
const getRecordDetail = (data) => {
if (!shouldShowDetail(data) || !isPretest(data)) {
return (
<a
className={`record-status--text ${recordEnum.STATUS_CODES[data.status]}`}
href={data.url}
target="_blank"
>
{recordEnum.STATUS_TEXTS[data.status]}
</a>
);
}
const stat = _.pick(
_.groupBy(data.cases || [], 'status'),
_.keys(recordEnum.STATUS_SCRATCHPAD_SHORT_TEXTS)
);
return _.map(recordEnum.STATUS_SCRATCHPAD_SHORT_TEXTS, (text, status) => {
const count = (stat[status] && stat[status].length) || 0;
const cn = classNames('icol icol--stat', {
'record-status--text': count > 0,
[recordEnum.STATUS_CODES[data.status]]: count > 0,
});
return (
<span key={text} className={cn}>
{text}: {count}
</span>
);
});
};
const mapStateToProps = (state) => ({
items: state.records.items,
});
const mergeProps = (stateProps, dispatchProps, ownProps) => ({
...dispatchProps,
data: stateProps.items[ownProps.id],
});
@connect(mapStateToProps, null, mergeProps)
export default class ScratchpadRecordsRowContainer extends React.PureComponent {
render() {
const { data } = this.props;
const submitAt = parseMongoId(data._id).timestamp * 1000;
return (
<tr>
<td className={`col--detail record-status--border ${recordEnum.STATUS_CODES[data.status]}`}>
<span className={`icon record-status--icon ${recordEnum.STATUS_CODES[data.status]}`}></span>
{getRecordDetail(data)}
<span className="icol icol--pretest">
{isPretest(data)
? <span
className={`flag record-status--background ${recordEnum.STATUS_CODES[data.status]}`}
>{i18n('Pretest')}</span>
: ''
}
</span>
</td>
<td className="col--memory">
{shouldShowDetail(data) ? `${Math.ceil(data.memory_kb / 1000)} MB` : '-'}
</td>
<td className="col--time">
{shouldShowDetail(data) ? `${data.time_ms}ms` : '-'}
</td>
<td className="col--at">
<time data-tooltip={moment(submitAt).format('YYYY-MM-DD HH:mm:ss')}>
<TimeAgo datetime={submitAt} locale={i18n('timeago_locale')} />
</time>
</td>
</tr>
);
}
}
|
packages/icons/src/md/hardware/PhoneAndroid.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdPhoneAndroid(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M32 2c3.31 0 6 2.69 6 6v32c0 3.31-2.69 6-6 6H16c-3.31 0-6-2.69-6-6V8c0-3.31 2.69-6 6-6h16zm-4 40v-2h-8v2h8zm6.5-6V8h-21v28h21z" />
</IconBase>
);
}
export default MdPhoneAndroid;
|
src/components/ApiTransactionCurlCommand.js | evaisse/swagger-open-api-ui | import React, { Component } from 'react';
export default class ApiTransactionCurlCommand extends Component {
getCurlCommand(args1, args2) {
let xhr = this.props.xhr;
let results = [];
let obj = xhr.request.options;
let isFormData = false;
let isMultipart = false;
results.push('-X ' + this.method.toUpperCase());
Object.keys(obj.headers || {}).forEach((key) => {
let value = obj.headers[key];
if (typeof value === 'string') {
value = value.replace(/\'/g, '\\u0027');
}
results.push('--header \'' + key + ': ' + value + '\'');
});
let type = obj.headers['Content-Type'];
if (type && type.indexOf('application/x-www-form-urlencoded') === 0) {
isFormData = true;
} else if (type && type.indexOf('multipart/form-data') === 0) {
isFormData = true;
isMultipart = true;
}
let body = this.getBodyContent({ isFormData, isMultipart, results });
return 'curl ' + (results.join(' ')) + ' \'' + xhr.responseURL + '\'';
}
appendBodyString({ isMultipart, isFormData, results }) {
let body;
if (typeof this.props.xhr.data != "string") {
body = this.stringifyBody();
} else {
body = this.props.xhr.data;
}
// escape @ => %40, ' => %27
body = body.replace(/\'/g, '%27').replace(/\n/g, ' \\ \n ');
if (!isFormData) {
// escape & => %26
body = body.replace(/&/g, '%26');
}
if (isMultipart) {
results.push(body);
} else {
results.push('-d \'' + body.replace(/@/g, '%40') + '\'');
}
}
stringifyBody({ body, isMultipart, isFormData, isJson }) {
return JSON.stringify(body);
// if (isMultipart) {
// return this.convertMultiPartBody({ body, isMultipart, isFormData, isJson });
// } else {
// return JSON.stringify(body);
// }
}
encodeMultiPartBody({ body, isMultipart, isFormData, isJson }) {
for (var i = 0; i < body.length; i++) {
var parameter = this.parameters[i];
if (parameter.in === 'formData') {
if (!body) {
body = '';
}
var paramValue;
if (typeof FormData === 'function' && body instanceof FormData) {
paramValue = body.getAll(parameter.name);
} else {
paramValue = body[parameter.name];
}
if (paramValue) {
if (parameter.type === 'file') {
if (paramValue.name) {
body += '-F ' + parameter.name + '=@"' + paramValue.name + '" ';
}
} else {
if (Array.isArray(paramValue)) {
if (parameter.collectionFormat === 'multi') {
for (var v in paramValue) {
body += '-F ' + this.encodeQueryKey(parameter.name) + '=' + paramValue[v] + ' ';
}
} else {
body += '-F ' + this.encodeQueryCollection(parameter.collectionFormat, parameter.name, paramValue) + ' ';
}
} else {
body += '-F ' + this.encodeQueryKey(parameter.name) + '=' + paramValue + ' ';
}
}
}
}
}
}
encodePathCollection(type, name, value) {
var encoded = '';
var i;
var separator = '';
if (type === 'ssv') {
separator = '%20';
} else if (type === 'tsv') {
separator = '%09';
} else if (type === 'pipes') {
separator = '|';
} else {
separator = ',';
}
for (i = 0; i < value.length; i++) {
if (i === 0) {
encoded = this.encodeQueryParam(value[i]);
} else {
encoded += separator + this.encodeQueryParam(value[i]);
}
}
return encoded;
};
encodeQueryCollection(type, name, value) {
var encoded = '';
var i;
type = type || 'default';
if (type === 'default' || type === 'multi') {
for (i = 0; i < value.length; i++) {
if (i > 0) {encoded += '&';}
encoded += this.encodeQueryKey(name) + '=' + this.encodeQueryParam(value[i]);
}
} else {
var separator = '';
if (type === 'csv') {
separator = ',';
} else if (type === 'ssv') {
separator = '%20';
} else if (type === 'tsv') {
separator = '%09';
} else if (type === 'pipes') {
separator = '|';
} else if (type === 'brackets') {
for (i = 0; i < value.length; i++) {
if (i !== 0) {
encoded += '&';
}
encoded += this.encodeQueryKey(name) + '[]=' + this.encodeQueryParam(value[i]);
}
}
if (separator !== '') {
for (i = 0; i < value.length; i++) {
if (i === 0) {
encoded = this.encodeQueryKey(name) + '=' + this.encodeQueryParam(value[i]);
} else {
encoded += separator + this.encodeQueryParam(value[i]);
}
}
}
}
return encoded;
}
encodeQueryKey(arg) {
return encodeURIComponent(arg)
.replace('%5B','[')
.replace('%5D', ']')
.replace('%24', '$');
}
encodeQueryParam(arg) {
return encodeURIComponent(arg);
}
encodePathParam(pathParam) {
return encodeURIComponent(pathParam);
}
render() {
try {
return (
<pre>{ this.getCurlCommand() }</pre>
);
} catch (e) {
return (
<pre>error when generating curl command</pre>
);
}
}
}
|
src/common/components/FieldTextarea.js | redcom/doctori-romani-in-berlin | // @flow
import type { TextareaProps } from './Textarea';
import Box from './Box';
import Textarea from './Textarea';
import React from 'react';
import Text from './Text';
// Custom TextInput with label and error.
type FieldProps = TextareaProps & { label?: string, error?: string, rows: number, cols: number};
const Field = ({
label,
error,
cols,
rows,
size = 0,
...props }: FieldProps) => (
<Box>
{label && <Text bold size={size - 1}>{label}</Text>}
<Textarea size={size} cols={cols} rows={rows} {...props} />
<Text bold color="danger" size={size - 1}>
{error || '\u00A0'/* Because we need to reserve real fontSize height. */}
</Text>
</Box>
);
export default Field;
|
src/parser/deathknight/blood/modules/talents/RuneStrike.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS/index';
import SpellLink from 'common/SpellLink';
import RESOURCE_TYPES from 'game/RESOURCE_TYPES';
import TalentStatisticBox from 'interface/others/TalentStatisticBox';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
import SpellUsable from 'parser/shared/modules/SpellUsable';
import { formatPercentage, formatDuration } from 'common/format';
import RuneTracker from '../../../shared/RuneTracker';
const MS_REDUCTION_PER_RUNE = 1000;
const ONLY_CAST_BELOW_RUNES = 3;
class RuneStrike extends Analyzer {
static dependencies = {
spellUsable: SpellUsable,
runeTracker: RuneTracker,
};
wastedReduction = 0;
effectiveReduction = 0;
badCasts = 0;
goodCasts = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.RUNE_STRIKE_TALENT.id);
}
on_byPlayer_cast(event) {
if (event.ability.guid === SPELLS.RUNE_STRIKE_TALENT.id && this.runeTracker.runesAvailable >= ONLY_CAST_BELOW_RUNES) {
event.meta = event.meta || {};
event.meta.isInefficientCast = true;
event.meta.inefficientCastReason = `${SPELLS.RUNE_STRIKE_TALENT.name} was used with ${this.runeTracker.runesAvailable} runes available, wasting potential recharge time on your runes.`;
this.badCasts += 1;
return;
}
if (event.ability.guid === SPELLS.RUNE_STRIKE_TALENT.id ) {
this.goodCasts += 1;
return;
}
if (!event.classResources) {
return;
}
event.classResources
.filter(resource => resource.type === RESOURCE_TYPES.RUNES.id)
.forEach(({ amount, cost }) => {
const runeCost = cost || 0;
if (runeCost <= 0) {
return;
}
for (let i = 0; i < runeCost; i++) {
if (!this.spellUsable.isOnCooldown(SPELLS.RUNE_STRIKE_TALENT.id)) {
this.wastedReduction += MS_REDUCTION_PER_RUNE;
} else {
const effectiveReduction = this.spellUsable.reduceCooldown(SPELLS.RUNE_STRIKE_TALENT.id, MS_REDUCTION_PER_RUNE);
this.effectiveReduction += effectiveReduction;
this.wastedReduction += MS_REDUCTION_PER_RUNE - effectiveReduction;
}
}
});
}
get cooldownReductionEfficiency() {
return this.effectiveReduction / (this.wastedReduction + this.effectiveReduction);
}
get goodCastEfficiency() {
return this.goodCasts / (this.goodCasts + this.badCasts);
}
get cooldownReductionThresholds() {
return {
actual: this.cooldownReductionEfficiency,
isLessThan: {
minor: 1,
average: 0.85,
major: 0.7,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.cooldownReductionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>You wasted {formatDuration(this.wastedReduction / 1000)} worth of reduction by capping out on <SpellLink id={SPELLS.RUNE_STRIKE_TALENT.id} /> charges.</>)
.icon(SPELLS.RUNE_STRIKE_TALENT.icon)
.actual(`${formatPercentage(this.cooldownReductionEfficiency)}% cooldown reduction used`)
.recommended(`${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.RUNE_STRIKE_TALENT.id}
position={STATISTIC_ORDER.OPTIONAL(1)}
value={`${formatPercentage(this.goodCastEfficiency)}%`}
label="Good casts"
tooltip={(
<>
{formatDuration(this.wastedReduction / 1000)} wasted cooldown reduction<br />
{formatDuration(this.effectiveReduction / 1000)} effective cooldown reduction<br /><br />
{this.goodCasts} good casts with less than {ONLY_CAST_BELOW_RUNES} runes available, {this.badCasts} with more than {ONLY_CAST_BELOW_RUNES} runes available.<br />
Avoid casting {SPELLS.RUNE_STRIKE_TALENT.name} with more than {ONLY_CAST_BELOW_RUNES} runes available, doing so would refill an already charging rune.
</>
)}
/>
);
}
}
export default RuneStrike;
|
app/react-icons/fa/drupal.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaDrupal extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m29.1 35.4q-0.2-0.4-0.6-0.1-0.7 0.5-1.9 0.9t-3 0.3q-2.8 0-4.3-1.1-0.1 0-0.2 0-0.3 0-0.6 0.2-0.2 0.2-0.2 0.4t0.2 0.4q0.7 0.7 1.9 1.1t2.3 0.2 2.2-0.1q0.9-0.1 1.9-0.4t1.5-0.7 0.6-0.5q0.3-0.2 0.1-0.6z m-0.9-2.6q-0.4-1-0.9-1.3-0.5-0.4-1.7-0.4-1 0-1.6 0.3-0.6 0.2-1.7 1.2-0.6 0.5-0.3 1 0.2 0.2 0.4 0.1t0.7-0.5q0.1-0.1 0.2-0.2t0.3-0.2 0.2-0.2 0.3-0.1 0.2-0.1 0.4-0.1 0.3-0.1 0.5 0q0.6 0 1 0.2t0.5 0.3 0.3 0.5q0.2 0.3 0.3 0.4t0.3 0q0.5-0.3 0.3-0.8z m7.9-6.2q0-0.5-0.1-1t-0.4-1-0.7-0.8-1.2-0.4q-0.7 0-2.2 1t-2.9 1.8-2.2 1q-0.6 0-1.4-0.5t-1.7-1.1-1.9-1.2-2.2-1.1-2.5-0.5q-2.6 0.1-4.4 1.8t-1.9 4q0 2.5 1.7 3.6 0.6 0.5 1.4 0.7t2.3 0.2q1.3 0 2.9-0.8t3-1.6 2.7-1.5 2.1-0.7q0.6 0 1.4 0.7t1.6 1.5 1.6 1.5 1.2 0.7q0.8 0.1 1.3-0.3t1.2-1.4q0.7-0.9 1-2.3t0.3-2.3z m1.2-3.6q0 3.7-1.4 6.8t-3.7 5.3-5.4 3.3-6.5 1.2-6.5-1.3-5.6-3.5-3.8-5.4-1.4-6.7q0-2 0.4-3.9t1.1-3.2 1.6-2.7 1.8-2.1 1.7-1.5 1.4-1.1 1-0.5q0.3-0.2 1.1-0.6t1.2-0.6 1.1-0.7 1.4-1q0.8-0.6 1.3-1.6t0.6-2.8q2.9 3.5 4.2 4.3 1 0.7 2.9 1.5t2.9 1.5q0.4 0.3 0.8 0.6t1.4 1 1.7 1.6 1.7 2.1 1.5 2.7 1.1 3.3 0.4 4z"/></g>
</IconBase>
);
}
}
|
test/test_helper.js | raninho/learning-reactjs | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/routes/Login/LoginForm.js | pmg1989/dva-admin | import React from 'react'
import PropTypes from 'prop-types'
import { Button, Form, Input } from 'antd'
import QueueAnim from 'rc-queue-anim'
import { config } from 'utils'
import styles from './LoginForm.less'
const FormItem = Form.Item
const Login = ({
loading,
onOk,
form: {
getFieldDecorator,
validateFieldsAndScroll,
},
}) => {
function handleOk (e) {
e.preventDefault()
validateFieldsAndScroll((errors, values) => {
if (errors) {
return
}
onOk(values)
})
}
return (
<div className={styles.form}>
<QueueAnim delay={200} type="top">
<div className={styles.logo} key="1">
<img src={config.logoSrc} alt={config.logoSrc} />
<span>{config.logoText}</span>
</div>
</QueueAnim>
<form onSubmit={handleOk}>
<QueueAnim delay={200} type="top">
<FormItem hasFeedback key="1">
{getFieldDecorator('username', {
rules: [
{
required: true,
message: '请填写用户名',
},
],
})(<Input size="large" placeholder="用户名" />)}
</FormItem>
<FormItem hasFeedback key="2">
{getFieldDecorator('password', {
rules: [
{
required: true,
message: '请填写密码',
},
],
})(<Input size="large" type="password" placeholder="密码" />)}
</FormItem>
<FormItem key="3">
<Button type="primary" htmlType="submit" size="large" loading={loading}>
登录
</Button>
</FormItem>
</QueueAnim>
</form>
</div>
)
}
Login.propTypes = {
form: PropTypes.object.isRequired,
loading: PropTypes.bool.isRequired,
onOk: PropTypes.func.isRequired,
}
export default Form.create()(Login)
|
app/javascript/mastodon/main.js | Craftodon/Craftodon | import * as registerPushNotifications from './actions/push_notifications';
import { default as Mastodon, store } from './containers/mastodon';
import React from 'react';
import ReactDOM from 'react-dom';
import ready from './ready';
const perf = require('./performance');
function main() {
perf.start('main()');
if (window.history && history.replaceState) {
const { pathname, search, hash } = window.location;
const path = pathname + search + hash;
if (!(/^\/web[$/]/).test(path)) {
history.replaceState(null, document.title, `/web${path}`);
}
}
ready(() => {
const mountNode = document.getElementById('mastodon');
const props = JSON.parse(mountNode.getAttribute('data-props'));
ReactDOM.render(<Mastodon {...props} />, mountNode);
if (process.env.NODE_ENV === 'production') {
// avoid offline in dev mode because it's harder to debug
require('offline-plugin/runtime').install();
store.dispatch(registerPushNotifications.register());
}
perf.stop('main()');
});
}
export default main;
|
Website/src/components/Home/DesignHeading.js | ameyjain/WallE- | import React, { Component } from 'react';
import { connect } from 'react-redux'
export default class DesignHeading extends Component {
render() {
return (
<div id="two" className="parallax">
<div className="heading1">
<h2 id="line1" >SIMPLE & INTUITIVE DESIGN</h2>
</div>
</div>
)
}
}
|
examples/universal/client.js | charlespwd/redux | import 'babel-core/polyfill';
import React from 'react';
import configureStore from './store/configureStore';
import { Provider } from 'react-redux';
import App from './containers/App';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
const rootElement = document.getElementById('app');
React.render(
<Provider store={store}>
{() => <App/>}
</Provider>,
rootElement
);
|
Paths/React/06.Styling React Components/6-react-styling-components-m6-exercise-files/After/src/app.js | phiratio/Pluralsight-materials | import autobind from 'autobind-decorator'
import React from 'react'
import Carousel from './carousel'
import Frame from './frame'
import Nav from './nav'
import Slide from './slide'
import css from './app.css'
@autobind
export default class DriftApp extends React.Component {
state = {
showIndex: 0,
numSlides: 5
}
handleClickPrevious() {
this.setState({
showIndex: Math.max(this.state.showIndex - 1, 0)
})
}
handleClickNext() {
this.setState({
showIndex: Math.min(this.state.showIndex + 1, this.state.numSlides - 1)
})
}
renderNav() {
return <Nav onPrevious={this.handleClickPrevious} hasPrevious={this.state.showIndex > 0}
onNext={this.handleClickNext} hasNext={this.state.showIndex < this.state.numSlides - 1} />
}
render() {
return (
<Frame>
<Carousel showIndex={this.state.showIndex} nav={this.renderNav()} width={640}>
<Slide image={require('./images/1.jpg')} title="Imperial Mockery">
In a show of defiance, rebels have again made mockery of the majesty that is service to the Empire.
These objects were immediately removed from the reflecting pool in Coruscant's Central Square when found
this morning.
</Slide>
<Slide image={require('./images/2.jpg')} title="Trooper Initiation">
In a tradition that predates the Empire, Troopers seen here are made to suffer the agony of
the limbo line. Such initiation techniques are currently under Imperial review.
</Slide>
<Slide image={require('./images/3.jpg')} title="Master and Apprentice">
Internships work! When determining a career path, it is wise to first find someone currently in that line of
work. They will likely be able to show you what it's really like before you commit your future.
</Slide>
<Slide image={require('./images/4.jpg')} title="Battle of Coruscant">
Modelers ran out of the pre-Empire model Star Destroyers in this reenactment of the Battle of Coruscant.
Various plans for future machines of war were used as filler.
</Slide>
<Slide image={require('./images/5.jpg')} title="The Wiles of the Forest">
After a number of nervous breakdowns, Empire personnel officers are investigating the possibility
rotating troopers stationed on the forest moons of Endor after several rotations.
</Slide>
</Carousel>
</Frame>
)
}
}
|
app/javascript/mastodon/features/reblogs/index.js | tateisu/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import { fetchReblogs } from '../../actions/interactions';
import { FormattedMessage } from 'react-intl';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import ColumnBackButton from '../../components/column_back_button';
import ScrollableList from '../../components/scrollable_list';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'reblogged_by', props.params.statusId]),
});
export default @connect(mapStateToProps)
class Reblogs extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
accountIds: ImmutablePropTypes.list,
};
componentWillMount () {
this.props.dispatch(fetchReblogs(this.props.params.statusId));
}
componentWillReceiveProps(nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchReblogs(nextProps.params.statusId));
}
}
render () {
const { shouldUpdateScroll, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='status.reblogs.empty' defaultMessage='No one has boosted this toot yet. When someone does, they will show up here.' />;
return (
<Column>
<ColumnBackButton />
<ScrollableList
scrollKey='reblogs'
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
>
{accountIds.map(id =>
<AccountContainer key={id} id={id} withNote={false} />
)}
</ScrollableList>
</Column>
);
}
}
|
js/components/layout/row.js | bengaara/simbapp |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Button, Icon, Left, Right, Body } from 'native-base';
import { Grid, Row } from 'react-native-easy-grid';
import { Actions } from 'react-native-router-flux';
import { openDrawer } from '../../actions/drawer';
const {
popRoute,
} = actions;
class RowNB extends Component { // eslint-disable-line
static propTypes = {
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Row Grid</Title>
</Body>
<Right />
</Header>
<Grid>
<Row style={{ backgroundColor: '#635DB7' }} />
<Row style={{ backgroundColor: '#00CE9F' }} />
</Grid>
</Container>
);
}
}
function bindAction(dispatch) {
return {
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(RowNB);
|
src/components/Feedback/Feedback.js | seanlin816/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react';
import styles from './Feedback.css';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Feedback extends Component {
render() {
return (
<div className="Feedback">
<div className="Feedback-container">
<a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className="Feedback-spacer">|</span>
<a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
interface/components/SendTx/Footer.js | ethereum/mist | import React, { Component } from 'react';
import MDSpinner from 'react-md-spinner';
class Footer extends Component {
constructor(props) {
super(props);
this.state = {
pw: ''
};
}
handleSubmit = e => {
e.preventDefault();
this.props.handleSubmit(this.state);
this.setState({ pw: '' });
};
render() {
const { gasPrice, gasError, estimatedGas, unlocking } = this.props;
if (!estimatedGas || !gasPrice || gasPrice === 0 || gasPrice === '0x0') {
return (
<MDSpinner singleColor="#00aafa" size={16} className="react-spinner" />
);
}
if (unlocking) {
return (
<div className="footer--unlocking">
<h2>{i18n.t('mist.sendTx.unlocking')}</h2>
</div>
);
}
return (
<div className="footer">
<form
onSubmit={this.handleSubmit}
className={gasError ? 'footer__form error' : 'footer__form'}
>
<input
className="footer__input"
type="password"
value={this.state.pw}
onChange={e => this.setState({ pw: e.target.value })}
placeholder={i18n.t('mist.sendTx.enterPassword')}
autoFocus
/>
<button
className={gasError ? 'footer__btn error' : 'footer__btn'}
disabled={!this.state.pw}
type="submit"
>
{i18n.t('mist.sendTx.execute')}
</button>
</form>
</div>
);
}
}
export default Footer;
|
app/javascript/mastodon/containers/mastodon.js | koba-lab/mastodon | import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { BrowserRouter, Route } from 'react-router-dom';
import { ScrollContext } from 'react-router-scroll-4';
import UI from '../features/ui';
import { fetchCustomEmojis } from '../actions/custom_emojis';
import { hydrateStore } from '../actions/store';
import { connectUserStream } from '../actions/streaming';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import initialState from '../initial_state';
import ErrorBoundary from '../components/error_boundary';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
export const store = configureStore();
const hydrateAction = hydrateStore(initialState);
store.dispatch(hydrateAction);
store.dispatch(fetchCustomEmojis());
const createIdentityContext = state => ({
signedIn: !!state.meta.me,
accountId: state.meta.me,
accessToken: state.meta.access_token,
});
export default class Mastodon extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
};
static childContextTypes = {
identity: PropTypes.shape({
signedIn: PropTypes.bool.isRequired,
accountId: PropTypes.string,
accessToken: PropTypes.string,
}).isRequired,
};
identity = createIdentityContext(initialState);
getChildContext() {
return {
identity: this.identity,
};
}
componentDidMount() {
if (this.identity.signedIn) {
this.disconnect = store.dispatch(connectUserStream());
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
shouldUpdateScroll (prevRouterProps, { location }) {
return !(location.state?.mastodonModalKey && location.state?.mastodonModalKey !== prevRouterProps?.location?.state?.mastodonModalKey);
}
render () {
const { locale } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<ErrorBoundary>
<BrowserRouter basename='/web'>
<ScrollContext shouldUpdateScroll={this.shouldUpdateScroll}>
<Route path='/' component={UI} />
</ScrollContext>
</BrowserRouter>
</ErrorBoundary>
</Provider>
</IntlProvider>
);
}
}
|
src/components/utility/logo.js | EncontrAR/backoffice | import React from 'react';
import { Link } from 'react-router-dom';
import { siteConfig } from '../../config.js';
// export default function({ collapsed, styling }) {
export default function({ collapsed }) {
return (
<div
className="isoLogoWrapper">
{collapsed
? <div>
<h3>
<Link to="/admin/campaigns">
<i className={siteConfig.siteIcon} />
</Link>
</h3>
</div>
: <h3>
<Link to="/admin/campaigns">
{siteConfig.siteName}
</Link>
</h3>}
</div>
);
}
|
src/app/TodoList.js | CompileYouth/SmallFish | import React from 'react';
import _ from 'lodash';
import {
View
} from 'react-native';
import TodoItem from './TodoItem';
import List from '../component/List';
export default class TodoList extends List {
constructor() {
super();
this._handleItemClick = this._handleItemClick.bind(this);
}
componentWillReceiveProps(props) {
if (props.showAllTodos) {
this.setState({
allTodos: this.ds.cloneWithRows(this.todos)
});
}
}
_handleScroll(e) {
if (e.nativeEvent.contentOffset.y < -10) {
console.log('Now you can create a new item.');
}
}
_renderTodo(todo) {
return (<TodoItem
prior={todo.prior}
text={todo.text}
date={todo.date}
onClick={this._handleItemClick}
/>);
}
_renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
return (
<View
key={`${sectionID}-${rowID}`}
style={{
height: adjacentRowHighlighted ? 0.5 : 0.5,
backgroundColor: adjacentRowHighlighted ? '#FAFAFA' : '#FAFAFA',
}}
/>
);
}
_handleItemClick(e, index) {
// Hide all todos above the selected todo
this.setState({
allTodos: this.ds.cloneWithRows(_.drop(this.todos, index))
});
// Show overlay
this.props.onItemClick();
}
render() {
const list = super.render();
return React.cloneElement(list, {
onScroll: this._handleScroll,
renderSeparator: this._renderSeparator
});
}
}
|
packages/editor/src/components/Controls/Emoji/EmojiLayout.js | strues/boldr | /* eslint-disable react/no-array-index-key */
/* @flow */
import React from 'react';
import type { Node } from 'react';
import cn from 'classnames';
import { Smile } from '../../Icons';
import { stopPropagation } from '../../../utils/common';
import type { EmojiConfig } from '../../../core/config';
import Option from '../../Option';
export type Props = {
onChange: Function,
expanded?: boolean,
onExpandEvent: Function,
config: EmojiConfig,
};
class EmojiLayout extends React.Component<Props, *> {
onChange: Function = (event: SyntheticEvent<>): void => {
const { onChange } = this.props;
onChange(event.target.innerHTML);
};
renderEmojiModal(): Node {
const { config: { modalClassName, emojis } } = this.props;
return (
<div className={cn('be-modal be-emoji', modalClassName)} onClick={stopPropagation}>
{emojis.map((emoji, index) => (
<span className={cn('be-emoji__icon')} key={index} alt="emoji" onClick={this.onChange}>
{emoji}
</span>
))}
</div>
);
}
render(): Node {
const { config: { className, title }, expanded, onExpandEvent } = this.props;
return (
<div
className={cn('be-ctrl__group', className)}
aria-haspopup="true"
aria-label="be-emoji__control"
aria-expanded={expanded}
title={title}>
<Option className={cn(className)} value="unordered-list-item" onClick={onExpandEvent}>
<Smile size={20} fill="#222" />
</Option>
{expanded ? this.renderEmojiModal() : undefined}
</div>
);
}
}
export default EmojiLayout;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.