path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
docs/src/examples/addons/Ref/index.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Message, Icon } from 'semantic-ui-react'
import Types from './Types'
const RefExamples = () => (
<>
<Message icon warning>
<Icon name='warning sign' />
<Message.Content>
<Message.Header>Deprecation notice</Message.Header>
<p>
<code>Ref</code> component is deprecated and will be removed in the
next major release. Please follow our{' '}
<a href='https://github.com/Semantic-Org/Semantic-UI-React/pull/4324'>
upgrade guide
</a>{' '}
to avoid breaks during upgrade to v3.
</p>
<p>
It's still recommended to use <code>Ref</code> component with v2 to
get refs to HTML elements from Semantic UI React components, but as it
uses deprecated <code>ReactDOM.findDOMNode()</code> you may receive
warnings in React's StrictMode. We are working on it in{' '}
<a href='https://github.com/Semantic-Org/Semantic-UI-React/issues/3819'>
Semantic-Org/Semantic-UI-React#3819
</a>
.
</p>
</Message.Content>
</Message>
<Types />
</>
)
export default RefExamples
|
src/components/Json/index.js | bogas04/SikhJS | import React from 'react';
import Fetch from '../Fetch';
/* eslint-disable react/jsx-no-bind */
export default props => <Fetch initialValue={[]} transform={r => r.json()} {...props} />;
|
maodou/events/client/components/admin/eventsAdd.js | LIYINGZHEN/meteor-react-redux-base | import React from 'react';
export default class EventAdd extends React.Component {
constructor(props) {
super(props);
this.state = { unit: '$' };
this.changeUnit = this.changeUnit.bind(this);
}
changeUnit() {
if (this.state.unit === '$') {
this.setState({ unit: '¥' });
} else {
this.setState({ unit: '$' });
}
}
render() {
return (
<div className="row">
<div className="col-sm-12">
<h1>新建活动</h1>
<form onSubmit={(e) => this.props.dispatch(this.props.addEvent(e))}>
<div className="form-group">
<label>活动名称</label>
<input className="form-control" type="text" placeholder="title" name="title" />
</div>
<div className="form-group">
<label>日期</label>
<input className="form-control" type="date" placeholder="time" name="time" />
</div>
<div className="form-group">
<label>地点</label>
<input className="form-control" type="text" placeholder="location" name="location" />
</div>
<div className="form-group">
<label>人数限制</label>
<input className="form-control" type="text" placeholder="limit" name="limit" />
</div>
<div className="row">
<div className="col-xs-5">
<div className="form-group">
<label>付款单位</label>
<select defaultValue="dollar" onChange={this.changeUnit} className="form-control" name="unit">
<option value="dollar">美金</option>
<option value="rmb">RMB</option>
</select>
</div>
</div>
<div className="col-xs-7">
<div className="form-group">
<label>费用</label>
<div className="input-group m-b">
<span className="input-group-addon">{this.state.unit}</span>
<input type="text" name="fee" className="form-control"/>
</div>
</div>
</div>
</div>
<br />
<label>活动描述</label>
<div id="editor" />
<button className="btn btn-default" type="submit">Submit</button>
</form>
</div>
</div>
);
}
}
|
app/addons/config/routes.js | popojargo/couchdb-fauxton | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import React from 'react';
import FauxtonAPI from "../../core/api";
import Config from "./resources";
import ClusterActions from "../cluster/cluster.actions";
import ConfigActions from "./actions";
import Layout from './layout';
var ConfigDisabledRouteObject = FauxtonAPI.RouteObject.extend({
selectedHeader: 'Configuration',
routes: {
'_config': 'checkNodes',
},
crumbs: [
{ name: 'Config disabled' }
],
checkNodes: function () {
ClusterActions.navigateToNodeBasedOnNodeCount('/_config/');
}
});
var ConfigPerNodeRouteObject = FauxtonAPI.RouteObject.extend({
roles: ['_admin'],
selectedHeader: 'Configuration',
apiUrl: function () {
return [this.configs.url(), this.configs.documentation];
},
routes: {
'_config/:node': 'configForNode',
'_config/:node/cors': 'configCorsForNode'
},
initialize: function (_a, options) {
var node = options[0];
this.configs = new Config.ConfigModel({ node: node });
},
configForNode: function (node) {
ConfigActions.fetchAndEditConfig(node);
return <Layout
node={node}
docURL={this.configs.documentation}
endpoint={this.configs.url()}
crumbs={[{ name: 'Config' }]}
showCors={false}
/>;
},
configCorsForNode: function (node) {
return <Layout
node={node}
docURL={this.configs.documentation}
endpoint={this.configs.url()}
crumbs={[{ name: 'Config' }]}
showCors={true}
/>;
}
});
Config.RouteObjects = [ConfigPerNodeRouteObject, ConfigDisabledRouteObject];
export default Config;
|
src/main/components/App.js | padcom/react-example-02 | import React from 'react';
import Title from './Title';
import Input from './Input';
import css from './App.less'
/**
* Main application component
*
* @class App
*/
const App = () => (
<div class={css.component}>
<Input />
<Title />
</div>
)
export default App;
|
src/shop/shop.js | bschneier/credit-cards-front-end | import React, { Component } from 'react';
import { connect } from 'react-redux';
import apiClient from '../api/apiClient';
import CONSTANTS from '../shared/constants';
class Shop extends Component {
constructor() {
super();
this.state = {
username: "username"
};
}
componentWillMount() {
apiClient.callCreditCardsApi(CONSTANTS.HTTP_METHODS.GET, '/users/profile', (response) => {
this.setState({ username: response.data.user.firstName });
});
}
render()
{
return (
<h1>Hello {this.state.username}. This is the shop page</h1>
);
}
}
const mapStateToProps = (state) => {
return {
sessionId: state.session.sessionId
};
};
export default connect(mapStateToProps)(Shop);
|
react-ebay-network-aware-code-splitting/src/components/CenterPanelInternal/ProductSummary/index.js | GoogleChromeLabs/adaptive-loading |
import React from 'react';
import LeftSummary from './LeftSummary';
import RightSummary from './RightSummary';
import './product-summary.css';
const ProductSummary = () => {
return (
<div className='product-summary'>
<div className='left-product-summary'>
<LeftSummary />
</div>
<div className='right-product-summary'>
<RightSummary />
</div>
</div>
);
};
export default ProductSummary;
|
src/components/SubSection.js | irla/react-cv | // @flow
import React from 'react';
import '../styles/sections.scss';
type Props = {
className?: string,
title: string,
info?: string,
children: any
}
const SubSection = (props: Props) => (
<div className={`popover popover-static sub-section ${props.className}`}>
<h3 className="popover-title">
{props.title}
<small style={{ float: 'right' }}>{props.info}</small>
</h3>
<div className="popover-content">
{props.children}
</div>
</div>
);
SubSection.defaultProps = {
className: '',
info: ''
};
export default SubSection;
|
src/containers/AddTodo.js | finfort/TodoReactApp | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { addTodo } from '../actions';
let nextTodoId = 0;
let Todo = ({dispatch }) => {
let input;
return (
<div>
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
//dispatch(addTodo(input.value))// not dispatch but use connect
dispatch({
type: 'ADD_TODO',
id: nextTodoId++,
text: input.value
})
input.value = ''
} }>
<input ref={node => {
input = node
} } />
<button type="submit">
Add Todo
</button>
</form>
</div>
<ul>
{/*this.props.todos.map(todo =>
<li
key={todo.id}
{...todo}
></li>
)*/}
</ul>
</div>
);
}
export default connect()(Todo); |
src/svg-icons/hardware/device-hub.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDeviceHub = (props) => (
<SvgIcon {...props}>
<path d="M17 16l-4-4V8.82C14.16 8.4 15 7.3 15 6c0-1.66-1.34-3-3-3S9 4.34 9 6c0 1.3.84 2.4 2 2.82V12l-4 4H3v5h5v-3.05l4-4.2 4 4.2V21h5v-5h-4z"/>
</SvgIcon>
);
HardwareDeviceHub = pure(HardwareDeviceHub);
HardwareDeviceHub.displayName = 'HardwareDeviceHub';
HardwareDeviceHub.muiName = 'SvgIcon';
export default HardwareDeviceHub;
|
src/routes/UIElement/dropOption/index.js | zhouchao0924/SLCOPY | import React from 'react'
import { DropOption } from '../../../components'
import { Table, Row, Col, Card, message } from 'antd'
const DropOptionPage = () => <div className="content-inner">
<Row gutter={32}>
<Col lg={8} md={12}>
<Card title="默认">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="样式">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} buttonStyle={{ border: 'solid 1px #eee', width: 60 }} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="事件">
<DropOption
menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]}
buttonStyle={{ border: 'solid 1px #eee', width: 60 }}
onMenuClick={({ key }) => {
switch (key) {
case '1':
message.success('点击了编辑')
break
case '2':
message.success('点击了删除')
break
default:
break
}
}}
/>
</Card>
</Col>
</Row>
<h2 style={{ margin: '16px 0' }}>Props</h2>
<Row>
<Col lg={18} md={24}>
<Table
rowKey={(record, key) => key}
pagination={false}
bordered
scroll={{ x: 800 }}
columns={[
{
title: '参数',
dataIndex: 'props',
},
{
title: '说明',
dataIndex: 'desciption',
},
{
title: '类型',
dataIndex: 'type',
},
{
title: '默认值',
dataIndex: 'default',
},
]}
dataSource={[
{
props: 'menuOptions',
desciption: '下拉操作的选项,格式为[{name:string,key:string}]',
type: 'Array',
default: '必选',
},
{
props: 'onMenuClick',
desciption: '点击 menuitem 调用此函数,参数为 {item, key, keyPath}',
type: 'Function',
default: '-',
},
{
props: 'buttonStyle',
desciption: '按钮的样式',
type: 'Object',
default: '-',
},
{
props: 'dropdownProps',
desciption: '下拉菜单的参数,可参考antd的【Dropdown】组件',
type: 'Object',
default: '-',
},
]}
/>
</Col>
</Row>
</div>
export default DropOptionPage
|
_~2017/react/todos/src/containers/AddTodo.js | zhoukekestar/drafts | import React from 'react'
import { connect } from 'react-redux'
import { addTodo } from '../actions'
let AddTodo = ({ dispatch }) => {
let input
return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(addTodo(input.value))
input.value = ''
}}>
<input ref={node => {
input = node
}} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
AddTodo = connect()(AddTodo)
export default AddTodo
|
src/pages/todo/components/footer.js | mvtnghia/web-boilerplate | import classNames from 'classnames';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { changeFilter, clearCompleted } from '../actions';
import { SHOW_ACTIVE, SHOW_ALL, SHOW_COMPLETED } from '../constants';
import {
activeCountSelector,
activeTodoListSelector,
selectedFilterSelector,
} from '../selectors';
import type { Todos } from '../types';
const FILTER_TITLES = {
SHOW_ALL,
SHOW_ACTIVE,
SHOW_COMPLETED,
};
export type Props = {
activeTodoList: Todos,
activeCount: number,
selectedFilter: string,
changeFilter: Function,
clearCompleted: Function,
};
type State = {};
class Footer extends Component<void, Props, State> {
state: State;
props: Props;
renderTodoCount = props => {
const itemWord = props.activeCount === 1 ? 'item' : 'items';
const activeCount = props.activeCount || 'No';
return (
<span className="todo-count">{`${activeCount} ${itemWord} left`}</span>
);
};
renderFilterLink = (filter, props) => {
const selectedFilter =
props.selectedFilter || Object.values(FILTER_TITLES)[0];
const linkCls = classNames({ selected: filter === selectedFilter });
return (
<button
type="button"
className={linkCls}
onClick={() => props.changeFilter(filter)}
>
{filter}
</button>
);
};
renderFilter = props => (
<ul className="filters">
{Object.keys(FILTER_TITLES).map(key => (
<li key={key}>{this.renderFilterLink(FILTER_TITLES[key], props)}</li>
))}
</ul>
);
renderClearButton = props => {
if (!props.activeCount) return null;
return (
<button
type="button"
className="clear-completed"
onClick={() => props.clearCompleted(props.activeTodoList)}
>
Clear completed
</button>
);
};
renderComponent(props) {
return (
<div className="footer">
{this.renderTodoCount(props)}
{this.renderFilter(props)}
{this.renderClearButton(props)}
</div>
);
}
render() {
return this.renderComponent(this.props);
}
}
export default connect(
state => ({
selectedFilter: selectedFilterSelector(state),
activeCount: activeCountSelector(state),
activeTodoList: activeTodoListSelector(state),
}),
dispatch => bindActionCreators({ clearCompleted, changeFilter }, dispatch),
)(Footer);
|
front/src/components/DateTimePicker.js | ethbets/ebets | /* Copyright (C) 2017 ethbets
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
import DatePicker from 'material-ui/DatePicker';
import TimePickerDialog from './TimePicker/TimePickerDialog';
import moment from 'moment';
import React, { Component } from 'react';
class DateTimePicker extends Component {
constructor(props) {
super(props);
this.state = {
_selectedDate: null,
dateTime: this.props.defaultDate
}
}
onSelectedDate = (err, dateObject) => {
this.setState({_selectedDate : moment(dateObject)});
this.dueDatePicker.show();
}
onSelectedTime = (timeObject) => {
const momentDate = new moment(this.state._selectedDate);
const momentTime = new moment(timeObject);
const dateTime = new moment({
year: momentDate.year(),
month: momentDate.month(),
day: momentDate.date(),
hour: momentTime.hours(),
minute: momentTime.minutes()
});
this.setState({dateTime: dateTime.toDate()});
this.props.onChange(dateTime);
this.dueDatePicker.dismiss();
}
openTimePicker = () => {
this.dueDatePicker.show();
};
dateTimeFormatter = (date) => {
var returnDate;
if (moment(this.props.defaultDate).isAfter(moment(date))) {
returnDate = this.props.defaultDate;
}
else
returnDate = date;
return moment(returnDate).format('LLL');
}
render() {
return (
<div>
<TimePickerDialog ref={(e) => this.dueDatePicker = e}
initialTime={this.props.initialTime}
firstDayOfWeek={0}
onAccept={this.onSelectedTime}
/>
<DatePicker floatingLabelText={this.props.floatingLabelText}
formatDate={this.dateTimeFormatter}
value={this.state.dateTime}
defaultDate={this.props.defaultDate}
onChange={this.onSelectedDate}
/>
</div>
)
}
}
export default DateTimePicker;
|
docs/app/Examples/modules/Dropdown/Content/DropdownExampleImage.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Dropdown } from 'semantic-ui-react'
import { friendOptions } from '../common'
const DropdownExampleImage = () => (
<Dropdown text='Add user' floating labeled button className='icon'>
{/* <i class="add user icon"></i> */}
<Dropdown.Menu>
<Dropdown.Header content='People You Might Know' />
{friendOptions.map((option) => <Dropdown.Item key={option.value} {...option} />)}
</Dropdown.Menu>
</Dropdown>
)
export default DropdownExampleImage
|
src/containers/LiveMarkedArea.js | MattMcFarland/react-markdown-area | /*
Import React
*/
import React from 'react';
/*
Import Components
*/
import {
MarkedPreview,
MarkedInput
} from '../components';
/*
MarkedArea Container Class
*/
export class LiveMarkedArea extends React.Component {
constructor(props) {
super(props);
this.state = {
value: props.defaultValue ? props.defaultValue : ''
};
}
static defaultProps = {
id: 'mmc-marked-area',
label: '',
classNames: {
root: 'marked-area',
header: 'marked-area-header',
activeButton: 'marked-area-button active',
defaultButton: 'marked-area-button',
helpLink: 'marked-area-help-link',
textContainer: 'marked-area-text-container',
liveDivider: 'marked-area-live-divider'
}
};
componentWillReceiveProps(props) {
this.setState({value: props.value});
};
handleTextChange = (e) => {
this.setState({value: e.target.value});
};
render() {
let {id, label, classNames, placeholder} = this.props;
let {value} = this.state;
return (
<section className={classNames.root}>
<header className={classNames.header}>
<label htmlFor={id}>{label}</label>
</header>
<MarkedInput
placeholder={placeholder}
classNames={classNames}
onChange={this.handleTextChange}
value={value} />
<MarkedPreview classNames={classNames}
value={value} />
</section>
);
}
}
|
spec/components/drawer.js | VACO-GitHub/vaco-components-library | import React from 'react';
import Button from '../../components/button';
import Drawer from '../../components/drawer';
class DrawerTest extends React.Component {
state = {
leftActive: false,
rightActive: false
};
handleToggleLeft = () => {
this.setState({leftActive: !this.state.leftActive});
};
handleToggleRight = () => {
this.setState({rightActive: !this.state.rightActive});
};
render () {
return (
<section>
<h5>Drawer</h5>
<p>You can navigate using a drawer to the left or right.</p>
<Drawer active={this.state.leftActive} onOverlayClick={this.handleToggleLeft}>
<h5>Officia deserunt mollit.</h5>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</Drawer>
<Drawer active={this.state.rightActive} type='right'>
<Button primary label='Close' onClick={this.handleToggleRight} />
</Drawer>
<nav>
<Button label='Drawer left' raised primary onClick={this.handleToggleLeft} />
<Button label='Drawer right' raised accent onClick={this.handleToggleRight} />
</nav>
</section>
);
}
}
export default DrawerTest;
|
client/scripts/components/user/entities/numeric-control/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import React from 'react';
export class NumericControl extends React.Component {
constructor() {
super();
this.onChange = this.onChange.bind(this);
}
onChange(evt) {
this.props.onChange(evt.target.value, this.props.questionId);
}
render() {
const {invalid, readonly, answer = '', entityId, questionId} = this.props;
let requiredFieldError;
if (invalid) {
requiredFieldError = (
<div className={styles.invalidError}>Required Field</div>
);
}
if (readonly) {
return (
<div className={styles.value}>
{answer}
</div>
);
}
return (
<div>
<div className={styles.container}>
<input
className={styles.textbox}
type="number"
id={`eqa${entityId}${questionId}`}
onChange={this.onChange}
value={answer}
/>
</div>
{requiredFieldError}
</div>
);
}
}
|
packages/react-reconciler/src/ReactFiberClassComponent.js | kaushik94/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {Fiber} from './ReactFiber';
import type {ExpirationTime} from './ReactFiberExpirationTime';
import React from 'react';
import {Update, Snapshot} from 'shared/ReactSideEffectTags';
import {
debugRenderPhaseSideEffects,
debugRenderPhaseSideEffectsForStrictMode,
warnAboutDeprecatedLifecycles,
} from 'shared/ReactFeatureFlags';
import ReactStrictModeWarnings from './ReactStrictModeWarnings';
import {isMounted} from 'react-reconciler/reflection';
import {get as getInstance, set as setInstance} from 'shared/ReactInstanceMap';
import shallowEqual from 'shared/shallowEqual';
import getComponentName from 'shared/getComponentName';
import invariant from 'shared/invariant';
import warningWithoutStack from 'shared/warningWithoutStack';
import {REACT_CONTEXT_TYPE} from 'shared/ReactSymbols';
import {startPhaseTimer, stopPhaseTimer} from './ReactDebugFiberPerf';
import {resolveDefaultProps} from './ReactFiberLazyComponent';
import {StrictMode} from './ReactTypeOfMode';
import {
enqueueUpdate,
processUpdateQueue,
checkHasForceUpdateAfterProcessing,
resetHasForceUpdateBeforeProcessing,
createUpdate,
ReplaceState,
ForceUpdate,
} from './ReactUpdateQueue';
import {NoWork} from './ReactFiberExpirationTime';
import {
cacheContext,
getMaskedContext,
getUnmaskedContext,
hasContextChanged,
emptyContextObject,
} from './ReactFiberContext';
import {readContext} from './ReactFiberNewContext';
import {
requestCurrentTime,
computeExpirationForFiber,
scheduleWork,
flushPassiveEffects,
} from './ReactFiberScheduler';
const fakeInternalInstance = {};
const isArray = Array.isArray;
// React.Component uses a shared frozen object by default.
// We'll use it to determine whether we need to initialize legacy refs.
export const emptyRefsObject = new React.Component().refs;
let didWarnAboutStateAssignmentForComponent;
let didWarnAboutUninitializedState;
let didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate;
let didWarnAboutLegacyLifecyclesAndDerivedState;
let didWarnAboutUndefinedDerivedState;
let warnOnUndefinedDerivedState;
let warnOnInvalidCallback;
let didWarnAboutDirectlyAssigningPropsToState;
let didWarnAboutContextTypeAndContextTypes;
let didWarnAboutInvalidateContextType;
if (__DEV__) {
didWarnAboutStateAssignmentForComponent = new Set();
didWarnAboutUninitializedState = new Set();
didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate = new Set();
didWarnAboutLegacyLifecyclesAndDerivedState = new Set();
didWarnAboutDirectlyAssigningPropsToState = new Set();
didWarnAboutUndefinedDerivedState = new Set();
didWarnAboutContextTypeAndContextTypes = new Set();
didWarnAboutInvalidateContextType = new Set();
const didWarnOnInvalidCallback = new Set();
warnOnInvalidCallback = function(callback: mixed, callerName: string) {
if (callback === null || typeof callback === 'function') {
return;
}
const key = `${callerName}_${(callback: any)}`;
if (!didWarnOnInvalidCallback.has(key)) {
didWarnOnInvalidCallback.add(key);
warningWithoutStack(
false,
'%s(...): Expected the last optional `callback` argument to be a ' +
'function. Instead received: %s.',
callerName,
callback,
);
}
};
warnOnUndefinedDerivedState = function(type, partialState) {
if (partialState === undefined) {
const componentName = getComponentName(type) || 'Component';
if (!didWarnAboutUndefinedDerivedState.has(componentName)) {
didWarnAboutUndefinedDerivedState.add(componentName);
warningWithoutStack(
false,
'%s.getDerivedStateFromProps(): A valid state object (or null) must be returned. ' +
'You have returned undefined.',
componentName,
);
}
}
};
// This is so gross but it's at least non-critical and can be removed if
// it causes problems. This is meant to give a nicer error message for
// ReactDOM15.unstable_renderSubtreeIntoContainer(reactDOM16Component,
// ...)) which otherwise throws a "_processChildContext is not a function"
// exception.
Object.defineProperty(fakeInternalInstance, '_processChildContext', {
enumerable: false,
value: function() {
invariant(
false,
'_processChildContext is not available in React 16+. This likely ' +
'means you have multiple copies of React and are attempting to nest ' +
'a React 15 tree inside a React 16 tree using ' +
"unstable_renderSubtreeIntoContainer, which isn't supported. Try " +
'to make sure you have only one copy of React (and ideally, switch ' +
'to ReactDOM.createPortal).',
);
},
});
Object.freeze(fakeInternalInstance);
}
export function applyDerivedStateFromProps(
workInProgress: Fiber,
ctor: any,
getDerivedStateFromProps: (props: any, state: any) => any,
nextProps: any,
) {
const prevState = workInProgress.memoizedState;
if (__DEV__) {
if (
debugRenderPhaseSideEffects ||
(debugRenderPhaseSideEffectsForStrictMode &&
workInProgress.mode & StrictMode)
) {
// Invoke the function an extra time to help detect side-effects.
getDerivedStateFromProps(nextProps, prevState);
}
}
const partialState = getDerivedStateFromProps(nextProps, prevState);
if (__DEV__) {
warnOnUndefinedDerivedState(ctor, partialState);
}
// Merge the partial state and the previous state.
const memoizedState =
partialState === null || partialState === undefined
? prevState
: Object.assign({}, prevState, partialState);
workInProgress.memoizedState = memoizedState;
// Once the update queue is empty, persist the derived state onto the
// base state.
const updateQueue = workInProgress.updateQueue;
if (updateQueue !== null && workInProgress.expirationTime === NoWork) {
updateQueue.baseState = memoizedState;
}
}
const classComponentUpdater = {
isMounted,
enqueueSetState(inst, payload, callback) {
const fiber = getInstance(inst);
const currentTime = requestCurrentTime();
const expirationTime = computeExpirationForFiber(currentTime, fiber);
const update = createUpdate(expirationTime);
update.payload = payload;
if (callback !== undefined && callback !== null) {
if (__DEV__) {
warnOnInvalidCallback(callback, 'setState');
}
update.callback = callback;
}
flushPassiveEffects();
enqueueUpdate(fiber, update);
scheduleWork(fiber, expirationTime);
},
enqueueReplaceState(inst, payload, callback) {
const fiber = getInstance(inst);
const currentTime = requestCurrentTime();
const expirationTime = computeExpirationForFiber(currentTime, fiber);
const update = createUpdate(expirationTime);
update.tag = ReplaceState;
update.payload = payload;
if (callback !== undefined && callback !== null) {
if (__DEV__) {
warnOnInvalidCallback(callback, 'replaceState');
}
update.callback = callback;
}
flushPassiveEffects();
enqueueUpdate(fiber, update);
scheduleWork(fiber, expirationTime);
},
enqueueForceUpdate(inst, callback) {
const fiber = getInstance(inst);
const currentTime = requestCurrentTime();
const expirationTime = computeExpirationForFiber(currentTime, fiber);
const update = createUpdate(expirationTime);
update.tag = ForceUpdate;
if (callback !== undefined && callback !== null) {
if (__DEV__) {
warnOnInvalidCallback(callback, 'forceUpdate');
}
update.callback = callback;
}
flushPassiveEffects();
enqueueUpdate(fiber, update);
scheduleWork(fiber, expirationTime);
},
};
function checkShouldComponentUpdate(
workInProgress,
ctor,
oldProps,
newProps,
oldState,
newState,
nextContext,
) {
const instance = workInProgress.stateNode;
if (typeof instance.shouldComponentUpdate === 'function') {
startPhaseTimer(workInProgress, 'shouldComponentUpdate');
const shouldUpdate = instance.shouldComponentUpdate(
newProps,
newState,
nextContext,
);
stopPhaseTimer();
if (__DEV__) {
warningWithoutStack(
shouldUpdate !== undefined,
'%s.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.',
getComponentName(ctor) || 'Component',
);
}
return shouldUpdate;
}
if (ctor.prototype && ctor.prototype.isPureReactComponent) {
return (
!shallowEqual(oldProps, newProps) || !shallowEqual(oldState, newState)
);
}
return true;
}
function checkClassInstance(workInProgress: Fiber, ctor: any, newProps: any) {
const instance = workInProgress.stateNode;
if (__DEV__) {
const name = getComponentName(ctor) || 'Component';
const renderPresent = instance.render;
if (!renderPresent) {
if (ctor.prototype && typeof ctor.prototype.render === 'function') {
warningWithoutStack(
false,
'%s(...): No `render` method found on the returned component ' +
'instance: did you accidentally return an object from the constructor?',
name,
);
} else {
warningWithoutStack(
false,
'%s(...): No `render` method found on the returned component ' +
'instance: you may have forgotten to define `render`.',
name,
);
}
}
const noGetInitialStateOnES6 =
!instance.getInitialState ||
instance.getInitialState.isReactClassApproved ||
instance.state;
warningWithoutStack(
noGetInitialStateOnES6,
'getInitialState was defined on %s, a plain JavaScript class. ' +
'This is only supported for classes created using React.createClass. ' +
'Did you mean to define a state property instead?',
name,
);
const noGetDefaultPropsOnES6 =
!instance.getDefaultProps ||
instance.getDefaultProps.isReactClassApproved;
warningWithoutStack(
noGetDefaultPropsOnES6,
'getDefaultProps was defined on %s, a plain JavaScript class. ' +
'This is only supported for classes created using React.createClass. ' +
'Use a static property to define defaultProps instead.',
name,
);
const noInstancePropTypes = !instance.propTypes;
warningWithoutStack(
noInstancePropTypes,
'propTypes was defined as an instance property on %s. Use a static ' +
'property to define propTypes instead.',
name,
);
const noInstanceContextType = !instance.contextType;
warningWithoutStack(
noInstanceContextType,
'contextType was defined as an instance property on %s. Use a static ' +
'property to define contextType instead.',
name,
);
const noInstanceContextTypes = !instance.contextTypes;
warningWithoutStack(
noInstanceContextTypes,
'contextTypes was defined as an instance property on %s. Use a static ' +
'property to define contextTypes instead.',
name,
);
if (
ctor.contextType &&
ctor.contextTypes &&
!didWarnAboutContextTypeAndContextTypes.has(ctor)
) {
didWarnAboutContextTypeAndContextTypes.add(ctor);
warningWithoutStack(
false,
'%s declares both contextTypes and contextType static properties. ' +
'The legacy contextTypes property will be ignored.',
name,
);
}
const noComponentShouldUpdate =
typeof instance.componentShouldUpdate !== 'function';
warningWithoutStack(
noComponentShouldUpdate,
'%s has a method called ' +
'componentShouldUpdate(). Did you mean shouldComponentUpdate()? ' +
'The name is phrased as a question because the function is ' +
'expected to return a value.',
name,
);
if (
ctor.prototype &&
ctor.prototype.isPureReactComponent &&
typeof instance.shouldComponentUpdate !== 'undefined'
) {
warningWithoutStack(
false,
'%s has a method called shouldComponentUpdate(). ' +
'shouldComponentUpdate should not be used when extending React.PureComponent. ' +
'Please extend React.Component if shouldComponentUpdate is used.',
getComponentName(ctor) || 'A pure component',
);
}
const noComponentDidUnmount =
typeof instance.componentDidUnmount !== 'function';
warningWithoutStack(
noComponentDidUnmount,
'%s has a method called ' +
'componentDidUnmount(). But there is no such lifecycle method. ' +
'Did you mean componentWillUnmount()?',
name,
);
const noComponentDidReceiveProps =
typeof instance.componentDidReceiveProps !== 'function';
warningWithoutStack(
noComponentDidReceiveProps,
'%s has a method called ' +
'componentDidReceiveProps(). But there is no such lifecycle method. ' +
'If you meant to update the state in response to changing props, ' +
'use componentWillReceiveProps(). If you meant to fetch data or ' +
'run side-effects or mutations after React has updated the UI, use componentDidUpdate().',
name,
);
const noComponentWillRecieveProps =
typeof instance.componentWillRecieveProps !== 'function';
warningWithoutStack(
noComponentWillRecieveProps,
'%s has a method called ' +
'componentWillRecieveProps(). Did you mean componentWillReceiveProps()?',
name,
);
const noUnsafeComponentWillRecieveProps =
typeof instance.UNSAFE_componentWillRecieveProps !== 'function';
warningWithoutStack(
noUnsafeComponentWillRecieveProps,
'%s has a method called ' +
'UNSAFE_componentWillRecieveProps(). Did you mean UNSAFE_componentWillReceiveProps()?',
name,
);
const hasMutatedProps = instance.props !== newProps;
warningWithoutStack(
instance.props === undefined || !hasMutatedProps,
'%s(...): When calling super() in `%s`, make sure to pass ' +
"up the same props that your component's constructor was passed.",
name,
name,
);
const noInstanceDefaultProps = !instance.defaultProps;
warningWithoutStack(
noInstanceDefaultProps,
'Setting defaultProps as an instance property on %s is not supported and will be ignored.' +
' Instead, define defaultProps as a static property on %s.',
name,
name,
);
if (
typeof instance.getSnapshotBeforeUpdate === 'function' &&
typeof instance.componentDidUpdate !== 'function' &&
!didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.has(ctor)
) {
didWarnAboutGetSnapshotBeforeUpdateWithoutDidUpdate.add(ctor);
warningWithoutStack(
false,
'%s: getSnapshotBeforeUpdate() should be used with componentDidUpdate(). ' +
'This component defines getSnapshotBeforeUpdate() only.',
getComponentName(ctor),
);
}
const noInstanceGetDerivedStateFromProps =
typeof instance.getDerivedStateFromProps !== 'function';
warningWithoutStack(
noInstanceGetDerivedStateFromProps,
'%s: getDerivedStateFromProps() is defined as an instance method ' +
'and will be ignored. Instead, declare it as a static method.',
name,
);
const noInstanceGetDerivedStateFromCatch =
typeof instance.getDerivedStateFromError !== 'function';
warningWithoutStack(
noInstanceGetDerivedStateFromCatch,
'%s: getDerivedStateFromError() is defined as an instance method ' +
'and will be ignored. Instead, declare it as a static method.',
name,
);
const noStaticGetSnapshotBeforeUpdate =
typeof ctor.getSnapshotBeforeUpdate !== 'function';
warningWithoutStack(
noStaticGetSnapshotBeforeUpdate,
'%s: getSnapshotBeforeUpdate() is defined as a static method ' +
'and will be ignored. Instead, declare it as an instance method.',
name,
);
const state = instance.state;
if (state && (typeof state !== 'object' || isArray(state))) {
warningWithoutStack(
false,
'%s.state: must be set to an object or null',
name,
);
}
if (typeof instance.getChildContext === 'function') {
warningWithoutStack(
typeof ctor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
name,
);
}
}
}
function adoptClassInstance(workInProgress: Fiber, instance: any): void {
instance.updater = classComponentUpdater;
workInProgress.stateNode = instance;
// The instance needs access to the fiber so that it can schedule updates
setInstance(instance, workInProgress);
if (__DEV__) {
instance._reactInternalInstance = fakeInternalInstance;
}
}
function constructClassInstance(
workInProgress: Fiber,
ctor: any,
props: any,
renderExpirationTime: ExpirationTime,
): any {
let isLegacyContextConsumer = false;
let unmaskedContext = emptyContextObject;
let context = null;
const contextType = ctor.contextType;
if (typeof contextType === 'object' && contextType !== null) {
if (__DEV__) {
if (
contextType.$$typeof !== REACT_CONTEXT_TYPE &&
!didWarnAboutInvalidateContextType.has(ctor)
) {
didWarnAboutInvalidateContextType.add(ctor);
warningWithoutStack(
false,
'%s defines an invalid contextType. ' +
'contextType should point to the Context object returned by React.createContext(). ' +
'Did you accidentally pass the Context.Provider instead?',
getComponentName(ctor) || 'Component',
);
}
}
context = readContext((contextType: any));
} else {
unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
const contextTypes = ctor.contextTypes;
isLegacyContextConsumer =
contextTypes !== null && contextTypes !== undefined;
context = isLegacyContextConsumer
? getMaskedContext(workInProgress, unmaskedContext)
: emptyContextObject;
}
// Instantiate twice to help detect side-effects.
if (__DEV__) {
if (
debugRenderPhaseSideEffects ||
(debugRenderPhaseSideEffectsForStrictMode &&
workInProgress.mode & StrictMode)
) {
new ctor(props, context); // eslint-disable-line no-new
}
}
const instance = new ctor(props, context);
const state = (workInProgress.memoizedState =
instance.state !== null && instance.state !== undefined
? instance.state
: null);
adoptClassInstance(workInProgress, instance);
if (__DEV__) {
if (typeof ctor.getDerivedStateFromProps === 'function' && state === null) {
const componentName = getComponentName(ctor) || 'Component';
if (!didWarnAboutUninitializedState.has(componentName)) {
didWarnAboutUninitializedState.add(componentName);
warningWithoutStack(
false,
'`%s` uses `getDerivedStateFromProps` but its initial state is ' +
'%s. This is not recommended. Instead, define the initial state by ' +
'assigning an object to `this.state` in the constructor of `%s`. ' +
'This ensures that `getDerivedStateFromProps` arguments have a consistent shape.',
componentName,
instance.state === null ? 'null' : 'undefined',
componentName,
);
}
}
// If new component APIs are defined, "unsafe" lifecycles won't be called.
// Warn about these lifecycles if they are present.
// Don't warn about react-lifecycles-compat polyfilled methods though.
if (
typeof ctor.getDerivedStateFromProps === 'function' ||
typeof instance.getSnapshotBeforeUpdate === 'function'
) {
let foundWillMountName = null;
let foundWillReceivePropsName = null;
let foundWillUpdateName = null;
if (
typeof instance.componentWillMount === 'function' &&
instance.componentWillMount.__suppressDeprecationWarning !== true
) {
foundWillMountName = 'componentWillMount';
} else if (typeof instance.UNSAFE_componentWillMount === 'function') {
foundWillMountName = 'UNSAFE_componentWillMount';
}
if (
typeof instance.componentWillReceiveProps === 'function' &&
instance.componentWillReceiveProps.__suppressDeprecationWarning !== true
) {
foundWillReceivePropsName = 'componentWillReceiveProps';
} else if (
typeof instance.UNSAFE_componentWillReceiveProps === 'function'
) {
foundWillReceivePropsName = 'UNSAFE_componentWillReceiveProps';
}
if (
typeof instance.componentWillUpdate === 'function' &&
instance.componentWillUpdate.__suppressDeprecationWarning !== true
) {
foundWillUpdateName = 'componentWillUpdate';
} else if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
foundWillUpdateName = 'UNSAFE_componentWillUpdate';
}
if (
foundWillMountName !== null ||
foundWillReceivePropsName !== null ||
foundWillUpdateName !== null
) {
const componentName = getComponentName(ctor) || 'Component';
const newApiName =
typeof ctor.getDerivedStateFromProps === 'function'
? 'getDerivedStateFromProps()'
: 'getSnapshotBeforeUpdate()';
if (!didWarnAboutLegacyLifecyclesAndDerivedState.has(componentName)) {
didWarnAboutLegacyLifecyclesAndDerivedState.add(componentName);
warningWithoutStack(
false,
'Unsafe legacy lifecycles will not be called for components using new component APIs.\n\n' +
'%s uses %s but also contains the following legacy lifecycles:%s%s%s\n\n' +
'The above lifecycles should be removed. Learn more about this warning here:\n' +
'https://fb.me/react-async-component-lifecycle-hooks',
componentName,
newApiName,
foundWillMountName !== null ? `\n ${foundWillMountName}` : '',
foundWillReceivePropsName !== null
? `\n ${foundWillReceivePropsName}`
: '',
foundWillUpdateName !== null ? `\n ${foundWillUpdateName}` : '',
);
}
}
}
}
// Cache unmasked context so we can avoid recreating masked context unless necessary.
// ReactFiberContext usually updates this cache but can't for newly-created instances.
if (isLegacyContextConsumer) {
cacheContext(workInProgress, unmaskedContext, context);
}
return instance;
}
function callComponentWillMount(workInProgress, instance) {
startPhaseTimer(workInProgress, 'componentWillMount');
const oldState = instance.state;
if (typeof instance.componentWillMount === 'function') {
instance.componentWillMount();
}
if (typeof instance.UNSAFE_componentWillMount === 'function') {
instance.UNSAFE_componentWillMount();
}
stopPhaseTimer();
if (oldState !== instance.state) {
if (__DEV__) {
warningWithoutStack(
false,
'%s.componentWillMount(): Assigning directly to this.state is ' +
"deprecated (except inside a component's " +
'constructor). Use setState instead.',
getComponentName(workInProgress.type) || 'Component',
);
}
classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
}
}
function callComponentWillReceiveProps(
workInProgress,
instance,
newProps,
nextContext,
) {
const oldState = instance.state;
startPhaseTimer(workInProgress, 'componentWillReceiveProps');
if (typeof instance.componentWillReceiveProps === 'function') {
instance.componentWillReceiveProps(newProps, nextContext);
}
if (typeof instance.UNSAFE_componentWillReceiveProps === 'function') {
instance.UNSAFE_componentWillReceiveProps(newProps, nextContext);
}
stopPhaseTimer();
if (instance.state !== oldState) {
if (__DEV__) {
const componentName =
getComponentName(workInProgress.type) || 'Component';
if (!didWarnAboutStateAssignmentForComponent.has(componentName)) {
didWarnAboutStateAssignmentForComponent.add(componentName);
warningWithoutStack(
false,
'%s.componentWillReceiveProps(): Assigning directly to ' +
"this.state is deprecated (except inside a component's " +
'constructor). Use setState instead.',
componentName,
);
}
}
classComponentUpdater.enqueueReplaceState(instance, instance.state, null);
}
}
// Invokes the mount life-cycles on a previously never rendered instance.
function mountClassInstance(
workInProgress: Fiber,
ctor: any,
newProps: any,
renderExpirationTime: ExpirationTime,
): void {
if (__DEV__) {
checkClassInstance(workInProgress, ctor, newProps);
}
const instance = workInProgress.stateNode;
instance.props = newProps;
instance.state = workInProgress.memoizedState;
instance.refs = emptyRefsObject;
const contextType = ctor.contextType;
if (typeof contextType === 'object' && contextType !== null) {
instance.context = readContext(contextType);
} else {
const unmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
instance.context = getMaskedContext(workInProgress, unmaskedContext);
}
if (__DEV__) {
if (instance.state === newProps) {
const componentName = getComponentName(ctor) || 'Component';
if (!didWarnAboutDirectlyAssigningPropsToState.has(componentName)) {
didWarnAboutDirectlyAssigningPropsToState.add(componentName);
warningWithoutStack(
false,
'%s: It is not recommended to assign props directly to state ' +
"because updates to props won't be reflected in state. " +
'In most cases, it is better to use props directly.',
componentName,
);
}
}
if (workInProgress.mode & StrictMode) {
ReactStrictModeWarnings.recordUnsafeLifecycleWarnings(
workInProgress,
instance,
);
ReactStrictModeWarnings.recordLegacyContextWarning(
workInProgress,
instance,
);
}
if (warnAboutDeprecatedLifecycles) {
ReactStrictModeWarnings.recordDeprecationWarnings(
workInProgress,
instance,
);
}
}
let updateQueue = workInProgress.updateQueue;
if (updateQueue !== null) {
processUpdateQueue(
workInProgress,
updateQueue,
newProps,
instance,
renderExpirationTime,
);
instance.state = workInProgress.memoizedState;
}
const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
if (typeof getDerivedStateFromProps === 'function') {
applyDerivedStateFromProps(
workInProgress,
ctor,
getDerivedStateFromProps,
newProps,
);
instance.state = workInProgress.memoizedState;
}
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (
typeof ctor.getDerivedStateFromProps !== 'function' &&
typeof instance.getSnapshotBeforeUpdate !== 'function' &&
(typeof instance.UNSAFE_componentWillMount === 'function' ||
typeof instance.componentWillMount === 'function')
) {
callComponentWillMount(workInProgress, instance);
// If we had additional state updates during this life-cycle, let's
// process them now.
updateQueue = workInProgress.updateQueue;
if (updateQueue !== null) {
processUpdateQueue(
workInProgress,
updateQueue,
newProps,
instance,
renderExpirationTime,
);
instance.state = workInProgress.memoizedState;
}
}
if (typeof instance.componentDidMount === 'function') {
workInProgress.effectTag |= Update;
}
}
function resumeMountClassInstance(
workInProgress: Fiber,
ctor: any,
newProps: any,
renderExpirationTime: ExpirationTime,
): boolean {
const instance = workInProgress.stateNode;
const oldProps = workInProgress.memoizedProps;
instance.props = oldProps;
const oldContext = instance.context;
const contextType = ctor.contextType;
let nextContext;
if (typeof contextType === 'object' && contextType !== null) {
nextContext = readContext(contextType);
} else {
const nextLegacyUnmaskedContext = getUnmaskedContext(
workInProgress,
ctor,
true,
);
nextContext = getMaskedContext(workInProgress, nextLegacyUnmaskedContext);
}
const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
const hasNewLifecycles =
typeof getDerivedStateFromProps === 'function' ||
typeof instance.getSnapshotBeforeUpdate === 'function';
// Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (
!hasNewLifecycles &&
(typeof instance.UNSAFE_componentWillReceiveProps === 'function' ||
typeof instance.componentWillReceiveProps === 'function')
) {
if (oldProps !== newProps || oldContext !== nextContext) {
callComponentWillReceiveProps(
workInProgress,
instance,
newProps,
nextContext,
);
}
}
resetHasForceUpdateBeforeProcessing();
const oldState = workInProgress.memoizedState;
let newState = (instance.state = oldState);
let updateQueue = workInProgress.updateQueue;
if (updateQueue !== null) {
processUpdateQueue(
workInProgress,
updateQueue,
newProps,
instance,
renderExpirationTime,
);
newState = workInProgress.memoizedState;
}
if (
oldProps === newProps &&
oldState === newState &&
!hasContextChanged() &&
!checkHasForceUpdateAfterProcessing()
) {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidMount === 'function') {
workInProgress.effectTag |= Update;
}
return false;
}
if (typeof getDerivedStateFromProps === 'function') {
applyDerivedStateFromProps(
workInProgress,
ctor,
getDerivedStateFromProps,
newProps,
);
newState = workInProgress.memoizedState;
}
const shouldUpdate =
checkHasForceUpdateAfterProcessing() ||
checkShouldComponentUpdate(
workInProgress,
ctor,
oldProps,
newProps,
oldState,
newState,
nextContext,
);
if (shouldUpdate) {
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (
!hasNewLifecycles &&
(typeof instance.UNSAFE_componentWillMount === 'function' ||
typeof instance.componentWillMount === 'function')
) {
startPhaseTimer(workInProgress, 'componentWillMount');
if (typeof instance.componentWillMount === 'function') {
instance.componentWillMount();
}
if (typeof instance.UNSAFE_componentWillMount === 'function') {
instance.UNSAFE_componentWillMount();
}
stopPhaseTimer();
}
if (typeof instance.componentDidMount === 'function') {
workInProgress.effectTag |= Update;
}
} else {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidMount === 'function') {
workInProgress.effectTag |= Update;
}
// If shouldComponentUpdate returned false, we should still update the
// memoized state to indicate that this work can be reused.
workInProgress.memoizedProps = newProps;
workInProgress.memoizedState = newState;
}
// Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props = newProps;
instance.state = newState;
instance.context = nextContext;
return shouldUpdate;
}
// Invokes the update life-cycles and returns false if it shouldn't rerender.
function updateClassInstance(
current: Fiber,
workInProgress: Fiber,
ctor: any,
newProps: any,
renderExpirationTime: ExpirationTime,
): boolean {
const instance = workInProgress.stateNode;
const oldProps = workInProgress.memoizedProps;
instance.props =
workInProgress.type === workInProgress.elementType
? oldProps
: resolveDefaultProps(workInProgress.type, oldProps);
const oldContext = instance.context;
const contextType = ctor.contextType;
let nextContext;
if (typeof contextType === 'object' && contextType !== null) {
nextContext = readContext(contextType);
} else {
const nextUnmaskedContext = getUnmaskedContext(workInProgress, ctor, true);
nextContext = getMaskedContext(workInProgress, nextUnmaskedContext);
}
const getDerivedStateFromProps = ctor.getDerivedStateFromProps;
const hasNewLifecycles =
typeof getDerivedStateFromProps === 'function' ||
typeof instance.getSnapshotBeforeUpdate === 'function';
// Note: During these life-cycles, instance.props/instance.state are what
// ever the previously attempted to render - not the "current". However,
// during componentDidUpdate we pass the "current" props.
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (
!hasNewLifecycles &&
(typeof instance.UNSAFE_componentWillReceiveProps === 'function' ||
typeof instance.componentWillReceiveProps === 'function')
) {
if (oldProps !== newProps || oldContext !== nextContext) {
callComponentWillReceiveProps(
workInProgress,
instance,
newProps,
nextContext,
);
}
}
resetHasForceUpdateBeforeProcessing();
const oldState = workInProgress.memoizedState;
let newState = (instance.state = oldState);
let updateQueue = workInProgress.updateQueue;
if (updateQueue !== null) {
processUpdateQueue(
workInProgress,
updateQueue,
newProps,
instance,
renderExpirationTime,
);
newState = workInProgress.memoizedState;
}
if (
oldProps === newProps &&
oldState === newState &&
!hasContextChanged() &&
!checkHasForceUpdateAfterProcessing()
) {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidUpdate === 'function') {
if (
oldProps !== current.memoizedProps ||
oldState !== current.memoizedState
) {
workInProgress.effectTag |= Update;
}
}
if (typeof instance.getSnapshotBeforeUpdate === 'function') {
if (
oldProps !== current.memoizedProps ||
oldState !== current.memoizedState
) {
workInProgress.effectTag |= Snapshot;
}
}
return false;
}
if (typeof getDerivedStateFromProps === 'function') {
applyDerivedStateFromProps(
workInProgress,
ctor,
getDerivedStateFromProps,
newProps,
);
newState = workInProgress.memoizedState;
}
const shouldUpdate =
checkHasForceUpdateAfterProcessing() ||
checkShouldComponentUpdate(
workInProgress,
ctor,
oldProps,
newProps,
oldState,
newState,
nextContext,
);
if (shouldUpdate) {
// In order to support react-lifecycles-compat polyfilled components,
// Unsafe lifecycles should not be invoked for components using the new APIs.
if (
!hasNewLifecycles &&
(typeof instance.UNSAFE_componentWillUpdate === 'function' ||
typeof instance.componentWillUpdate === 'function')
) {
startPhaseTimer(workInProgress, 'componentWillUpdate');
if (typeof instance.componentWillUpdate === 'function') {
instance.componentWillUpdate(newProps, newState, nextContext);
}
if (typeof instance.UNSAFE_componentWillUpdate === 'function') {
instance.UNSAFE_componentWillUpdate(newProps, newState, nextContext);
}
stopPhaseTimer();
}
if (typeof instance.componentDidUpdate === 'function') {
workInProgress.effectTag |= Update;
}
if (typeof instance.getSnapshotBeforeUpdate === 'function') {
workInProgress.effectTag |= Snapshot;
}
} else {
// If an update was already in progress, we should schedule an Update
// effect even though we're bailing out, so that cWU/cDU are called.
if (typeof instance.componentDidUpdate === 'function') {
if (
oldProps !== current.memoizedProps ||
oldState !== current.memoizedState
) {
workInProgress.effectTag |= Update;
}
}
if (typeof instance.getSnapshotBeforeUpdate === 'function') {
if (
oldProps !== current.memoizedProps ||
oldState !== current.memoizedState
) {
workInProgress.effectTag |= Snapshot;
}
}
// If shouldComponentUpdate returned false, we should still update the
// memoized props/state to indicate that this work can be reused.
workInProgress.memoizedProps = newProps;
workInProgress.memoizedState = newState;
}
// Update the existing instance's state, props, and context pointers even
// if shouldComponentUpdate returns false.
instance.props = newProps;
instance.state = newState;
instance.context = nextContext;
return shouldUpdate;
}
export {
adoptClassInstance,
constructClassInstance,
mountClassInstance,
resumeMountClassInstance,
updateClassInstance,
};
|
src/TextOnlyElement/index.js | christianalfoni/ducky-components | import React from 'react';
import PropTypes from 'prop-types';
import Typography from '../Typography';
import classNames from 'classnames';
import styles from './styles.css';
const BREAK_TEXT_LENGTH = 415;
function TextOnlyElement(props) {
let textLength = props.children.length;
if (typeof props.children !== 'string') {
textLength = props.children.map((child) => {
if (typeof child !== 'string') {
return child.props.children.length;
}
return child.length;
}).reduce((total, value) => {
return total + value;
}, 0);
}
if (textLength > BREAK_TEXT_LENGTH && !props.showFullText) {
return (
<div
className={classNames(styles.shadowWrapper, {
[styles[`${props.category}Wrapper`]]: props.category,
[props.className]: props.className
})}
onClick={props.onClick}
>
<Typography
className={classNames(styles.text, {
[styles.noCategory]: !props.category
})}
type="bodyTextNormal"
>
{props.children}
</Typography>
<div
className={classNames(styles.gradient, {
[styles[`${props.category}Gradient`]]: props.category
})}
>
</div>
</div>
);
}
return (
<div
className={classNames(styles.wrapper, {
[styles[`${props.category}Wrapper`]]: props.category,
[props.className]: props.className
})}
onClick={props.onClick}
>
<Typography
className={classNames(styles.text, {
[styles.noCategory]: !props.category
})}
type="bodyTextNormal"
>
{props.children}
</Typography>
</div>
);
}
TextOnlyElement.propTypes = {
category: PropTypes.oneOf(['food', 'consumption', 'energy', 'transport', 'social']),
children: PropTypes.node,
className: PropTypes.string,
onClick: PropTypes.func,
showFullText: PropTypes.bool
};
export default TextOnlyElement;
|
addons/centered/example/index.js | nfl/react-storybook | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import decorator from '../index';
const content = decorator(() => 'Hello World!');
const wrapper = document.querySelector('#content');
ReactDOM.render(content, wrapper);
|
docs/pages/components/cards.js | lgollut/material-ui | import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'components/cards';
const requireDemo = require.context('docs/src/pages/components/cards', false, /\.(js|tsx)$/);
const requireRaw = require.context(
'!raw-loader!../../src/pages/components/cards',
false,
/\.(js|md|tsx)$/,
);
export default function Page({ demos, docs }) {
return <MarkdownDocs demos={demos} docs={docs} requireDemo={requireDemo} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
frontend/eyeballing/src/components/SearchField.js | linea-it/dri | import React from 'react';
import PropTypes from 'prop-types';
import { makeStyles, fade } from '@material-ui/core/styles';
import InputBase from '@material-ui/core/InputBase';
import IconButton from '@material-ui/core/IconButton';
import SearchIcon from '@material-ui/icons/Search';
import CloseIcon from '@material-ui/icons/Close';
import CircularProgress from '@material-ui/core/CircularProgress';
const useStyles = makeStyles(theme => ({
search: {
position: 'relative',
borderRadius: theme.shape.borderRadius,
backgroundColor: fade(theme.palette.common.black, 0.03),
'&:hover': {
backgroundColor: fade(theme.palette.common.black, 0.07),
},
marginRight: theme.spacing(1),
marginLeft: 0,
width: '100%',
padding: `0 ${theme.spacing(1)}px`,
},
inputRoot: {
color: 'inherit',
width: '100%',
},
inputInput: {
padding: theme.spacing(1, 1, 1, 0),
// vertical padding + font size from searchIcon
paddingLeft: `calc(1em + ${theme.spacing(2)}px)`,
transition: theme.transitions.create('width'),
width: '100%',
},
searchIcon: {
padding: 0,
height: '100%',
position: 'absolute',
pointerEvents: 'none',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
},
clearIcon: {
padding: '0 4px',
height: '100%',
position: 'absolute',
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
right: 0,
top: 0,
zIndex: 1,
cursor: 'pointer',
'&:hover': {
backgroundColor: 'transparent',
},
},
}));
function SearchField(props) {
const classes = useStyles();
const {
searchRef, handleInputSearch, disabled,
} = props;
const handleClearSearch = () => {
searchRef.current.value = '';
handleInputSearch();
};
return (
<div className={classes.search}>
<div className={classes.searchIcon}>
{disabled ? <CircularProgress color="inherit" size={24} /> : <SearchIcon />}
</div>
<InputBase
inputRef={searchRef}
onChange={handleInputSearch}
disabled={disabled}
placeholder="Search…"
classes={{
root: classes.inputRoot,
input: classes.inputInput,
}}
inputProps={{ 'aria-label': 'Search' }}
/>
{searchRef.current && searchRef.current.value.length > 0 && (
<IconButton className={classes.clearIcon} onClick={handleClearSearch}>
<CloseIcon size={16} />
</IconButton>
)}
</div>
);
}
SearchField.propTypes = {
handleInputSearch: PropTypes.func.isRequired,
searchRef: PropTypes.shape({
current: PropTypes.oneOfType([
PropTypes.instanceOf(Element),
PropTypes.string,
]),
}).isRequired,
disabled: PropTypes.bool.isRequired,
};
export default SearchField;
|
src/components/Breadcrumb/index.js | lijinfengworm/ant-design-reactjs | import React from 'react';
import {Breadcrumb, Icon} from 'antd';
import sidebarMenu, {headerMenu} from 'menu.js'; // 注意这种引用方式
import Logger from '../../utils/Logger';
import './index.less';
const Item = Breadcrumb.Item;
const logger = Logger.getLogger('Breadcrumb');
/**
* 定义面包屑导航, 由于和已有的组件重名, 所以改个类名
*/
class Bread extends React.PureComponent {
//static inited = false; // 表示下面两个map是否初始化
//static iconMap = new Map(); // 暂存menu.js中key->icon的对应关系
//static nameMap = new Map(); // 暂存menu.js中key->name的对应关系
// 上面两个map本来是做成static变量的, 后来感觉还是当成普通的成员变量好些
// 如果是static变量, 那就跟react组件的生命周期完全没关系了
// 话说, 虽然constructor和componentWillMount方法作用差不多, 但我还是觉得componentWillMount更好用
// 因为constructor还要super(props), 有点啰嗦
// 虽然react官方推荐constructor, 因为constructor中可以设置初始状态
// 不过实际上初始状态可以直接通过定义成员变量的方式设置, 不一定要在constructor中
componentWillMount() {
// 准备初始化iconMap和nameMap
const iconMap = new Map();
const nameMap = new Map();
// 这是个很有意思的函数, 本质是dfs, 但用js写出来就觉得很神奇
const browseMenu = (item) => {
nameMap.set(item.key, item.name);
logger.debug('nameMap add entry: key=%s, value=%s', item.key, item.name);
iconMap.set(item.key, item.icon);
logger.debug('iconMap add entry: key=%s, value=%s', item.key, item.icon);
if (item.child) {
item.child.forEach(browseMenu);
}
};
sidebarMenu.forEach(browseMenu);
headerMenu.forEach(browseMenu);
this.iconMap = iconMap;
this.nameMap = nameMap;
}
render() {
const itemArray = [];
// 面包屑导航的最开始都是一个home图标, 并且这个图标是可以点击的
itemArray.push(<Item key="systemHome" href="#"><Icon type="home"/> 首页</Item>);
// this.props.routes是react-router传进来的
for (const route of this.props.routes) {
logger.debug('path=%s, route=%o', route.path, route);
const name = this.nameMap.get(route.path);
if (name) {
const icon = this.iconMap.get(route.path);
if (icon) {
itemArray.push(<Item key={name}><Icon type={icon}/> {name}</Item>); // 有图标的话带上图标
} else {
// 这个key属性不是antd需要的, 只是react要求同一个array中各个元素要是不同的, 否则有warning
itemArray.push(<Item key={name}>{name}</Item>);
}
}
}
// 这个面包屑是不可点击的(除了第一级的home图标), 只是给用户一个提示
return (
<div className="ant-layout-breadcrumb">
<Breadcrumb>{itemArray}</Breadcrumb>
</div>
);
}
}
export default Bread;
|
examples/passing-props-to-children/app.js | shunitoh/react-router | import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router, Route, Link, withRouter } from 'react-router'
import withExampleBasename from '../withExampleBasename'
import './app.css'
const App = withRouter(
React.createClass({
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
}
},
addTaco() {
let name = prompt('taco name?')
this.setState({
tacos: this.state.tacos.concat({ name })
})
},
handleRemoveTaco(removedTaco) {
this.setState({
tacos: this.state.tacos.filter(function (taco) {
return taco.name != removedTaco
})
})
this.props.router.push('/')
},
render() {
let links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
)
})
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
)
}
})
)
const Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name)
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
)
}
})
render((
<Router history={withExampleBasename(browserHistory, __dirname)}>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'))
|
src/svg-icons/device/signal-cellular-connected-no-internet-1-bar.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet1Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 10v8h2v-8h-2zm-8 12V12L2 22h10zm8 0h2v-2h-2v2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet1Bar = pure(DeviceSignalCellularConnectedNoInternet1Bar);
DeviceSignalCellularConnectedNoInternet1Bar.displayName = 'DeviceSignalCellularConnectedNoInternet1Bar';
DeviceSignalCellularConnectedNoInternet1Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet1Bar;
|
src/renderer/components/requests/request-pane.js | niklasi/halland-proxy | import React from 'react'
import {Card, CardHeader} from 'material-ui/Card'
import Avatar from 'material-ui/Avatar'
import RequestPaneToolbar from './request-pane-toolbar'
import PureRenderMixin from 'react-addons-pure-render-mixin'
import muiThemeable from 'material-ui/styles/muiThemeable'
import Stats from './request-stats'
/* eslint-disable react/jsx-indent */
class RequestPane extends React.Component {
constructor (props) {
super(props)
this.shouldComponentUpdate = PureRenderMixin.shouldComponentUpdate.bind(this)
}
render () {
const { request, response = {} } = this.props
const subtitleStyle = {
overflow: 'hidden',
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
maxWidth: '95%'
}
const subtitle = `${request.method} ${request.path} HTTP/${request.httpVersion}`
return <div style={{display: 'flex'}}>
<div style={{flex: '1 1 100%', overflowX: 'hidden'}}>
<Card>
<CardHeader
avatar={<Avatar>{response.statusCode}</Avatar>}
title={request.host}
subtitle={subtitle}
textStyle={{minWidth: '100%', maxWidth: '100%'}}
subtitleStyle={subtitleStyle} />
<Stats metadata={response.metadata} />
</Card>
</div>
<div style={{flex: '1 1 140px', backgroundColor: this.props.muiTheme.baseTheme.palette.canvasColor}}>
<RequestPaneToolbar requestId={request.id} />
</div>
</div>
}
}
export default muiThemeable()(RequestPane)
// Export without HoC to make testing easier
export { RequestPane }
/* eslint-enable react/jsx-indent */
|
routes/editHtml.js | jfengsky/Ayr | import register from 'babel-register'
import nodeJsx from 'node-jsx'
import React from 'react'
import reactServer from 'react-dom/server'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import reducer from '../tools/src/reducers/reducer'
import Edit from '../tools/src/component/Edit'
// node下支持jsx
register({presets: ['es2015', 'react', 'stage-0']})
nodeJsx.install({
extension:'.jsx'
})
const store = createStore(reducer)
let indexHtml = reactServer.renderToString(
<Provider store={store}>
<Edit />
</Provider>
)
export default indexHtml |
fields/types/cloudinaryimages/CloudinaryImagesField.js | pr1ntr/keystone | import _ from 'lodash';
import React from 'react';
import Field from '../Field';
import { Button, FormField, FormInput, FormNote } from 'elemental';
import Lightbox from '../../components/Lightbox';
import classnames from 'classnames';
const SUPPORTED_TYPES = ['image/gif', 'image/png', 'image/jpeg', 'image/bmp', 'image/x-icon', 'application/pdf', 'image/x-tiff', 'image/x-tiff', 'application/postscript', 'image/vnd.adobe.photoshop', 'image/svg+xml'];
const iconClassDeleted = [
'delete-pending',
'mega-octicon',
'octicon-x',
];
const iconClassQueued = [
'img-uploading',
'mega-octicon',
'octicon-cloud-upload',
];
var Thumbnail = React.createClass({
displayName: 'CloudinaryImagesFieldThumbnail',
propTypes: {
deleted: React.PropTypes.bool,
height: React.PropTypes.number,
isQueued: React.PropTypes.bool,
openLightbox: React.PropTypes.func,
shouldRenderActionButton: React.PropTypes.bool,
toggleDelete: React.PropTypes.func,
url: React.PropTypes.string,
width: React.PropTypes.number,
},
applyTransforms (url) {
var format = this.props.format;
if (format === 'pdf') {
// support cloudinary pdf previews in jpg format
url = url.substr(0, url.lastIndexOf('.')) + '.jpg';
url = url.replace(/image\/upload/, 'image/upload/c_thumb,h_90,w_90');
} else {
// add cloudinary thumbnail parameters to the url
url = url.replace(/image\/upload/, 'image/upload/c_thumb,g_face,h_90,w_90');
}
return url;
},
renderActionButton () {
if (!this.props.shouldRenderActionButton || this.props.isQueued) return null;
return <Button type={this.props.deleted ? 'link-text' : 'link-cancel'} block onClick={this.props.toggleDelete}>{this.props.deleted ? 'Undo' : 'Remove'}</Button>;
},
render () {
let iconClassName;
const { deleted, height, isQueued, url, width, openLightbox, format } = this.props;
const previewClassName = classnames('image-preview', {
action: (deleted || isQueued),
});
const title = (width && height) ? (width + ' × ' + height) : '';
if (deleted) {
iconClassName = classnames(iconClassDeleted);
} else if (isQueued) {
iconClassName = classnames(iconClassQueued);
}
const shouldOpenLightbox = (format !== 'pdf');
let thumbUrl = this.applyTransforms(url);
return (
<div className="image-field image-sortable" title={title}>
<div className={previewClassName}>
<a href={url} onClick={shouldOpenLightbox ? openLightbox : null} className="img-thumbnail" target="_blank">
<img style={{ height: '90' }} className="img-load" src={thumbUrl} />
<span className={iconClassName} />
</a>
</div>
{this.renderActionButton()}
</div>
);
},
});
module.exports = Field.create({
displayName: 'CloudinaryImagesField',
statics: {
type: 'CloudinaryImages',
},
getInitialState () {
var thumbnails = [];
var self = this;
_.forEach(this.props.value, function (item) {
self.pushThumbnail(item, thumbnails);
});
return { thumbnails: thumbnails };
},
openLightbox (index) {
event.preventDefault();
this.setState({
lightboxIsVisible: true,
lightboxImageIndex: index,
});
},
closeLightbox () {
this.setState({
lightboxIsVisible: false,
lightboxImageIndex: null,
});
},
renderLightbox () {
if (!this.props.value || !this.props.value.length) return;
const images = this.props.value.map(image => image.url);
return (
<Lightbox
images={images}
initialImage={this.state.lightboxImageIndex}
isOpen={this.state.lightboxIsVisible}
onCancel={this.closeLightbox}
/>
);
},
removeThumbnail (i) {
var thumbs = this.state.thumbnails;
var thumb = thumbs[i];
if (thumb.props.isQueued) {
thumbs[i] = null;
} else {
thumb.props.deleted = !thumb.props.deleted;
}
this.setState({ thumbnails: thumbs });
},
pushThumbnail (args, thumbs) {
thumbs = thumbs || this.state.thumbnails;
var i = thumbs.length;
args.toggleDelete = this.removeThumbnail.bind(this, i);
args.shouldRenderActionButton = this.shouldRenderField();
args.openLightbox = this.openLightbox.bind(this, i);
thumbs.push(<Thumbnail key={i} {...args} />);
},
fileFieldNode () {
return this.refs.fileField;
},
getCount (key) {
var count = 0;
_.forEach(this.state.thumbnails, function (thumb) {
if (thumb && thumb.props[key]) count++;
});
return count;
},
renderFileField () {
if (!this.shouldRenderField()) return null;
return <input ref="fileField" type="file" name={this.getInputName(this.props.paths.upload)} multiple className="field-upload" onChange={this.uploadFile} tabIndex="-1" />;
},
clearFiles () {
this.fileFieldNode().value = '';
this.setState({
thumbnails: this.state.thumbnails.filter(function (thumb) {
return !thumb.props.isQueued;
}),
});
},
uploadFile (event) {
var self = this;
var files = event.target.files;
_.forEach(files, function (f) {
if (!_.includes(SUPPORTED_TYPES, f.type)) {
alert('Unsupported file type. Supported formats are: GIF, PNG, JPG, BMP, ICO, PDF, TIFF, EPS, PSD, SVG');
return;
}
if (window.FileReader) {
var fileReader = new FileReader();
fileReader.onload = function (e) {
self.pushThumbnail({ isQueued: true, url: e.target.result });
self.forceUpdate();
};
fileReader.readAsDataURL(f);
} else {
self.pushThumbnail({ isQueued: true, url: '#' });
self.forceUpdate();
}
});
},
changeImage () {
this.fileFieldNode().click();
},
hasFiles () {
return this.refs.fileField && this.fileFieldNode().value;
},
renderToolbar () {
if (!this.shouldRenderField()) return null;
var body = [];
var push = function (queueType, alertType, count, action) {
if (count <= 0) return;
var imageText = count === 1 ? 'image' : 'images';
body.push(<div key={queueType + '-toolbar'} className={queueType + '-queued' + ' u-float-left'}>
<FormInput noedit>{count} {imageText} {action}</FormInput>
</div>);
};
push('upload', 'success', this.getCount('isQueued'), 'selected - save to upload');
push('delete', 'danger', this.getCount('deleted'), 'removed - save to confirm');
var clearFilesButton;
if (this.hasFiles()) {
clearFilesButton = <Button type="link-cancel" onClick={this.clearFiles} className="ml-5">Clear selection</Button>;
}
return (
<div className="images-toolbar">
<div className="u-float-left">
<Button onClick={this.changeImage}>Upload Images</Button>
{clearFilesButton}
</div>
{body}
</div>
);
},
renderPlaceholder () {
return (
<div className="image-field image-field--upload" onClick={this.changeImage}>
<div className="image-preview">
<span className="img-thumbnail">
<span className="img-dropzone" />
<div className="img-uploading mega-octicon octicon-file-media" />
</span>
</div>
<div className="image-details">
<span className="image-message">Click to upload</span>
</div>
</div>
);
},
renderContainer () {
return (
<div className="images-container">
{this.state.thumbnails}
</div>
);
},
renderFieldAction () {
if (!this.shouldRenderField()) return null;
var value = '';
var remove = [];
_.forEach(this.state.thumbnails, function (thumb) {
if (thumb && thumb.props.deleted) remove.push(thumb.props.public_id);
});
if (remove.length) value = 'remove:' + remove.join(',');
return <input ref="action" className="field-action" type="hidden" value={value} name={this.getInputName(this.props.paths.action)} />;
},
renderUploadsField () {
if (!this.shouldRenderField()) return null;
return <input ref="uploads" className="field-uploads" type="hidden" name={this.getInputName(this.props.paths.uploads)} />;
},
renderNote () {
return this.props.note ? <FormNote note={this.props.note} /> : null;
},
renderUI () {
return (
<FormField label={this.props.label} className="field-type-cloudinaryimages" htmlFor={this.props.path}>
{this.renderFieldAction()}
{this.renderUploadsField()}
{this.renderFileField()}
{this.renderContainer()}
{this.renderToolbar()}
{this.renderNote()}
{this.renderLightbox()}
</FormField>
);
},
});
|
src/icons/Thumbsdown.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class Thumbsdown extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g>
<path d="M87.8,252.7C74,257.2,64,270.2,64,285.5c0,19,15.4,34.5,34.5,34.5h102.6c-2,25-10,53.6-1.1,87.3
c7.5,28.4,39.4,49.7,52.4,36.8c5-4.9,3.5-15.2,3.5-33.8c0-42.8,17.8-86.1,39.8-108.7c9.4-9.7,25.2-13,40.2-13.6v16h112V64H336v32
c-20.6,0.5-52.6-5.2-75.8-6.6c-52-3.1-102,2.4-126.3,8.1c-24.3,5.7-35,13-35,30.6c0,6.4,1.9,12.3,5.1,17.3
c-11.8,4.7-20.1,16.2-20.1,29.7c0,7.2,2.4,13.8,6.4,19.2c-11.9,4.6-20.4,16.2-20.4,29.8C70,236.6,77.3,247.5,87.8,252.7z M400,96.3
c8.8,0,16,7.1,16,16c0,8.8-7.2,16-16,16s-16-7.1-16-16C384,103.5,391.2,96.3,400,96.3z"></path>
</g>
</g>;
} return <IconBase>
<g>
<path d="M87.8,252.7C74,257.2,64,270.2,64,285.5c0,19,15.4,34.5,34.5,34.5h102.6c-2,25-10,53.6-1.1,87.3
c7.5,28.4,39.4,49.7,52.4,36.8c5-4.9,3.5-15.2,3.5-33.8c0-42.8,17.8-86.1,39.8-108.7c9.4-9.7,25.2-13,40.2-13.6v16h112V64H336v32
c-20.6,0.5-52.6-5.2-75.8-6.6c-52-3.1-102,2.4-126.3,8.1c-24.3,5.7-35,13-35,30.6c0,6.4,1.9,12.3,5.1,17.3
c-11.8,4.7-20.1,16.2-20.1,29.7c0,7.2,2.4,13.8,6.4,19.2c-11.9,4.6-20.4,16.2-20.4,29.8C70,236.6,77.3,247.5,87.8,252.7z M400,96.3
c8.8,0,16,7.1,16,16c0,8.8-7.2,16-16,16s-16-7.1-16-16C384,103.5,391.2,96.3,400,96.3z"></path>
</g>
</IconBase>;
}
};Thumbsdown.defaultProps = {bare: false} |
actor-apps/app-web/src/app/components/common/Fold.React.js | lstNull/actor-platform | /* eslint-disable */
import React from 'react';
import classnames from 'classnames';
class Fold extends React.Component {
static PropTypes = {
icon: React.PropTypes.string,
iconClassName: React.PropTypes.string,
title: React.PropTypes.string.isRequired
};
state = {
isOpen: false
};
constructor(props) {
super(props);
}
render() {
const { icon, iconClassName, title, iconElement } = this.props;
const titleIconClassName = classnames('material-icons icon', iconClassName);
const className = classnames({
'fold': true,
'fold--open': this.state.isOpen
});
let foldIcon;
if (icon) {
foldIcon = <i className={titleIconClassName}>{icon}</i>;
}
if (iconElement) {
foldIcon = iconElement;
}
return (
<div className={className}>
<div className="fold__title" onClick={this.onClick}>
{foldIcon}
{title}
<i className="fold__indicator material-icons pull-right">arrow_drop_down</i>
</div>
<div className="fold__content">
{this.props.children}
</div>
</div>
);
}
onClick = () => {
this.setState({isOpen: !this.state.isOpen});
};
}
export default Fold;
|
[2]. Demo_RN/[5]. textInput_component/index.ios.js | knightsj/RN_Demo | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TextInput,
} from 'react-native';
//Search 组件
var Search = React.createClass({
//设置初始状态
getInitialState: function(){
return {
show: false
};
},
getValue: function(text){
var value = text;
this.setState({})
this.setState({
show: true,
value: value
});
},
hide: function(val){
this.setState({
show: false,
value: val
});
},
render: function(){
return (
<View style={styles.flex}>
<View style={[styles.flexDirection, styles.inputHeight]}>
<View style={styles.flex}>
<TextInput
style={styles.input}
returnKeyType="search"
placeholder="请输入关键字"
onEndEditing={this.hide.bind(this, this.state.value)}//结束编辑时触发
value={this.state.value}
//监听输入值的变化
onChangeText={this.getValue}/>
</View>
<View style={styles.btn}>
<Text style={styles.search} onPress={this.hide.bind(this, this.state.value)}>搜索</Text>
</View>
</View>
{
this.state.show?
<View style={[styles.result]}>
<Text onPress={this.hide.bind(this, this.state.value + '哈')}
style={styles.item} numberOfLines={1}>{this.state.value}哈</Text>
<Text onPress={this.hide.bind(this, this.state.value + '哈哈')}
style={styles.item} numberOfLines={1}>{this.state.value}哈哈</Text>
<Text onPress={this.hide.bind(this, 80 + this.state.value + '哈哈哈')}
style={styles.item} numberOfLines={1}>80{this.state.value}啊哈哈哈</Text>
<Text onPress={this.hide.bind(this, this.state.value + '哦哦')}
style={styles.item} numberOfLines={1}>{this.state.value}哦哦</Text>
<Text onPress={this.hide.bind(this, '哦' + this.state.value + '嗯')}
style={styles.item} numberOfLines={1}>诶?{this.state.value}</Text>
</View>
: null
}
</View>
);
},
});
var App = React.createClass({
render: function(){
return(
<View style={[styles.flex, styles.topStatus]}>
<Search></Search>
</View>
);
}
});
var styles = StyleSheet.create({
flex:{
flex: 1,
},
flexDirection:{
flexDirection:'row'
},
topStatus:{
marginTop:25,
},
inputHeight:{
height:45,
},
input:{
height:45,
borderWidth:1,
marginLeft: 5,
paddingLeft:5,
borderColor: '#ccc',
borderRadius: 4
},
btn:{
width:55,
marginLeft:-5,
marginRight:5,
backgroundColor:'#23BEFF',
height:45,
justifyContent:'center',
alignItems: 'center'
},
search:{
color:'#fff',
fontSize:15,
fontWeight:'bold'
},
result:{
marginTop:1,
marginLeft:5,
marginRight:5,
height:200,
borderColor:'#ccc',
borderTopWidth:1,
},
item:{
fontSize:16,
padding:5,
paddingTop:10,
paddingBottom:10,
borderWidth:1,
borderColor:'#ddd',
borderTopWidth:0,
}
});
AppRegistry.registerComponent('component_demo', () => App); |
components/common/CC-BY-SA.js | slidewiki/slidewiki-platform | import PropTypes from 'prop-types';
import React from 'react';
import { Image } from 'semantic-ui-react';
class CCBYSA extends React.Component {
render() {
return (
<Image.Group>
<Image>
<svg x="0px" y="0px" width="54.953px" height="54.953px" viewBox="0 0 54.953 54.953" enableBackground="new 0 0 54.953 54.953">
<g>
<path fill="rgba(0, 0, 0, 0.87)" d="M36.307,32.333c-1.21,0-2.126-0.442-2.748-1.326c-0.622-0.883-0.933-2.061-0.933-3.531c0-3.238,1.228-4.857,3.681-4.857c0.522,0,1.071,0.164,1.644,0.491c0.572,0.327,1.055,0.9,1.448,1.717l3.63-1.914c-1.439-2.649-3.859-3.974-7.261-3.974c-2.323,0-4.244,0.769-5.765,2.306c-1.521,1.538-2.281,3.615-2.281,6.231c0,2.682,0.744,4.775,2.232,6.279c1.487,1.504,3.475,2.258,5.961,2.258c1.504,0,2.895-0.385,4.17-1.153s2.289-1.823,3.041-3.165l-3.435-1.717C39.039,31.548,37.91,32.333,36.307,32.333z"/>
<path fill="rgba(0, 0, 0, 0.87)" d="M20.459,32.333c-1.21,0-2.126-0.442-2.748-1.326c-0.622-0.883-0.932-2.061-0.932-3.531c0-3.238,1.227-4.857,3.68-4.857c0.491,0,1.022,0.164,1.595,0.491c0.572,0.327,1.055,0.9,1.447,1.717l3.68-1.914c-1.472-2.649-3.909-3.974-7.311-3.974c-2.323,0-4.244,0.769-5.765,2.306c-1.521,1.538-2.282,3.615-2.282,6.231c0,2.682,0.752,4.775,2.257,6.279c1.504,1.504,3.483,2.258,5.937,2.258c1.537,0,2.944-0.385,4.219-1.153c1.276-0.769,2.273-1.823,2.993-3.165l-3.385-1.717C23.19,31.548,22.062,32.333,20.459,32.333z"/>
<path fill="rgba(0, 0, 0, 0.87)" d="M52.94,16.903c-1.342-3.32-3.304-6.272-5.888-8.856C41.655,2.683,35.113,0,27.427,0c-7.622,0-14.05,2.667-19.282,7.998c-2.649,2.649-4.669,5.651-6.059,9.003C0.694,20.354,0,23.845,0,27.476c0,3.664,0.687,7.146,2.061,10.451c1.374,3.304,3.377,6.271,6.01,8.904c2.633,2.633,5.609,4.646,8.93,6.035c3.32,1.391,6.795,2.086,10.426,2.086c3.631,0,7.147-0.703,10.549-2.111c3.4-1.405,6.443-3.434,9.125-6.084c2.583-2.518,4.539-5.42,5.863-8.707c1.324-3.288,1.986-6.812,1.986-10.573C54.953,23.747,54.281,20.223,52.94,16.903zM43.569,43.226c-2.225,2.158-4.719,3.811-7.481,4.955c-2.766,1.146-5.618,1.717-8.562,1.717c-2.977,0-5.823-0.564-8.537-1.691c-2.715-1.129-5.152-2.765-7.311-4.908c-2.159-2.141-3.819-4.578-4.98-7.311c-1.162-2.73-1.742-5.568-1.742-8.512c0-2.976,0.58-5.83,1.742-8.562c1.161-2.731,2.821-5.192,4.98-7.384c4.285-4.383,9.567-6.575,15.848-6.575c6.214,0,11.53,2.208,15.946,6.624c2.125,2.127,3.745,4.547,4.856,7.262c1.112,2.715,1.668,5.593,1.668,8.635C49.996,33.789,47.854,39.039,43.569,43.226z"/>
</g>
</svg>
</Image>
<Image>
<svg x="0px" y="0px" width="54.953px" height="54.953px" viewBox="0 0 54.953 54.953" enableBackground="new 0 0 54.953 54.953">
<g>
<path fill="rgba(0, 0, 0, 0.87)" d="M27.476,17.418c2.551,0,3.827-1.276,3.827-3.827c0-2.583-1.275-3.876-3.827-3.876s-3.827,1.292-3.827,3.876C23.649,16.142,24.924,17.418,27.476,17.418z"/>
<path fill="rgba(0, 0, 0, 0.87)" d="M46.955,7.949C41.654,2.649,35.146,0,27.427,0C19.838,0,13.395,2.649,8.096,7.949C2.699,13.444,0,19.953,0,27.476C0,35,2.699,41.458,8.096,46.855c5.462,5.397,11.905,8.098,19.331,8.098c7.556,0,14.114-2.73,19.675-8.195c5.231-5.135,7.852-11.562,7.852-19.281C54.953,19.79,52.285,13.28,46.955,7.949z M43.52,43.227c-4.547,4.479-9.877,6.723-15.995,6.723c-6.15,0-11.449-2.225-15.897-6.674c-4.449-4.447-6.672-9.715-6.672-15.798c0-6.051,2.24-11.366,6.722-15.946c4.317-4.383,9.6-6.575,15.848-6.575c6.214,0,11.513,2.192,15.896,6.575c4.385,4.383,6.576,9.698,6.576,15.946C49.996,33.822,47.837,39.072,43.52,43.227z"/>
<path fill="rgba(0, 0, 0, 0.87)" d="M33.119,18.89H21.833c-0.491,0-0.908,0.172-1.251,0.515c-0.343,0.344-0.515,0.761-0.515,1.251v11.234h3.14v13.346h8.537V31.893h3.141V20.656c0-0.491-0.18-0.908-0.539-1.251C33.984,19.062,33.576,18.89,33.119,18.89z"/>
</g>
</svg>
</Image>
<Image>
<svg x="0px" y="0px" width="54.953px" height="54.951px" viewBox="0 0 54.953 54.951" enableBackground="new 0 0 54.953 54.951">
<g>
<path fill="rgba(0, 0, 0, 0.87)" d="M27.329,13.002c-3.14,0-5.807,0.924-7.998,2.772c-2.192,1.848-3.549,4.457-4.072,7.826H13.1l5.446,5.446l5.446-5.446H21.98c0.458-3.238,2.519-4.857,6.182-4.857c2.028,0,3.582,0.761,4.662,2.282c1.078,1.521,1.618,3.737,1.618,6.648c0,2.781-0.589,5.004-1.767,6.674c-1.178,1.668-2.731,2.502-4.661,2.502c-3.86,0-5.872-1.668-6.035-5.005h-6.918c0.458,3.435,1.815,6.084,4.072,7.948c2.257,1.865,4.938,2.797,8.046,2.797c4.22,0,7.654-1.398,10.304-4.195s3.974-6.305,3.974-10.523c0-4.35-1.275-7.916-3.826-10.696C35.082,14.393,31.646,13.002,27.329,13.002z"/>
<path fill="rgba(0, 0, 0, 0.87)" d="M46.955,7.998C41.623,2.666,35.113,0,27.427,0c-7.556,0-14,2.666-19.331,7.998C2.699,13.493,0,19.986,0,27.476C0,35,2.699,41.459,8.096,46.856c5.462,5.396,11.905,8.095,19.331,8.095c7.588,0,14.147-2.714,19.674-8.146c5.232-5.201,7.852-11.644,7.852-19.331C54.953,19.79,52.285,13.296,46.955,7.998zM43.52,43.226c-4.547,4.481-9.878,6.722-15.995,6.722c-6.15,0-11.449-2.224-15.897-6.673c-4.449-4.416-6.672-9.682-6.672-15.798c0-6.051,2.24-11.35,6.722-15.896c4.317-4.416,9.6-6.624,15.848-6.624c6.247,0,11.546,2.208,15.896,6.624c4.384,4.317,6.576,9.616,6.576,15.896C49.996,33.789,47.837,39.039,43.52,43.226z"/>
</g>
</svg>
</Image>
</Image.Group>
);
}
}
export default CCBYSA;
|
src/Donut.js | neilff/react-d3-examples | import React from 'react';
import d3 from 'd3';
const defaultColors = d3.scale.category10();
import { Chart } from './common';
const Donut = (props) => {
const {
values = [],
width = 300,
radius = 25,
colors,
} = props;
const arc = d3.svg.arc()
.outerRadius(width / 2)
.innerRadius((width / 2) - radius);
const pie = d3.layout.pie();
return (
<Chart width={ width } height={ width }>
{
pie(values).map((i, idx) => {
const color = colors && colors[idx] ? colors[idx] : defaultColors(idx);
return (
<g className="arc" key={ idx }>
<path d={ arc(i) } fill={ color }></path>
</g>
);
})
}
</Chart>
);
};
export default Donut;
|
JotunheimenPlaces/node_modules/react-native/local-cli/templates/HelloWorld/index.ios.js | designrad/Jotunheimen-tracking | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class HelloWorld extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('HelloWorld', () => HelloWorld);
|
modules/dreamview/frontend/src/offline.js | jinghaomiao/apollo | /* import "whatwg-fetch";
* import "font-awesome-webpack"; */
import * as ReactDOM from 'react-dom';
import React from 'react';
import { Provider } from 'mobx-react';
import 'styles/main.scss';
import STORE from 'store';
import Offlineview from 'components/Offlineview';
ReactDOM.render(
<Provider store={STORE}>
<Offlineview />
</Provider>,
document.getElementById('root'),
);
|
lib/shared/screens/admin/screens/schemas/screens/single/components/new/index.js | relax/relax | import bind from 'decorators/bind';
import Component from 'components/component';
import React from 'react';
import PropTypes from 'prop-types';
import {addSchemaEntry} from 'actions/schema-entry';
import New from './new';
export default class NewSchemaEntryContainer extends Component {
static propTypes = {
onClose: PropTypes.func.isRequired,
schemaId: PropTypes.string.isRequired
};
static contextTypes = {
store: PropTypes.object.isRequired
};
getInitState () {
return {
title: '',
loading: false
};
}
@bind
changeTitle (title) {
this.setState({
title
});
}
@bind
submit () {
if (!this.state.loading) {
this.setState({
loading: true
}, () => {
const {store} = this.context;
const {onClose, schemaId} = this.props;
const {title} = this.state;
store.dispatch(addSchemaEntry(schemaId, 'single', {title}, true)).then(() => {
onClose && onClose();
});
});
}
}
render () {
return (
<New
{...this.state}
changeTitle={this.changeTitle}
submit={this.submit}
/>
);
}
}
|
react-redux-demo/运行不了或报错/real-world/src/routes.js | fengnovo/webpack-react | import React from 'react'
import { Route } from 'react-router'
import App from './containers/App'
import UserPage from './containers/UserPage'
import RepoPage from './containers/RepoPage'
export default <Route path="/" component={App}>
<Route path="/:login/:name"
component={RepoPage} />
<Route path="/:login"
component={UserPage} />
</Route>
|
node_modules/react-sparklines/src/Sparklines.js | TheeSweeney/ComplexReactReduxMiddlewareReview | import React from 'react';
import SparklinesLine from './SparklinesLine';
import SparklinesCurve from './SparklinesCurve';
import SparklinesBars from './SparklinesBars';
import SparklinesSpots from './SparklinesSpots';
import SparklinesReferenceLine from './SparklinesReferenceLine';
import SparklinesNormalBand from './SparklinesNormalBand';
import dataToPoints from './dataProcessing/dataToPoints';
import shallowCompare from 'react-addons-shallow-compare';
class Sparklines extends React.Component {
static propTypes = {
data: React.PropTypes.array,
limit: React.PropTypes.number,
width: React.PropTypes.number,
height: React.PropTypes.number,
svgWidth: React.PropTypes.number,
svgHeight: React.PropTypes.number,
preserveAspectRatio: React.PropTypes.string,
margin: React.PropTypes.number,
style: React.PropTypes.object,
min: React.PropTypes.number,
max: React.PropTypes.number
};
static defaultProps = {
data: [],
width: 240,
height: 60,
//Scale the graphic content of the given element non-uniformly if necessary such that the element's bounding box exactly matches the viewport rectangle.
preserveAspectRatio: 'none', //https://www.w3.org/TR/SVG/coords.html#PreserveAspectRatioAttribute
margin: 2
};
constructor (props) {
super(props);
}
shouldComponentUpdate(nextProps) {
return shallowCompare(this, nextProps);
}
render() {
const { data, limit, width, height, svgWidth, svgHeight, preserveAspectRatio, margin, style, max, min } = this.props;
if (data.length === 0) return null;
const points = dataToPoints({ data, limit, width, height, margin, max, min });
const svgOpts = { style: style, viewBox: `0 0 ${width} ${height}`, preserveAspectRatio: preserveAspectRatio };
if (svgWidth > 0) svgOpts.width = svgWidth;
if (svgHeight > 0) svgOpts.height = svgHeight;
return (
<svg {...svgOpts} >
{React.Children.map(this.props.children, child =>
React.cloneElement(child, { points, width, height, margin })
)}
</svg>
);
}
}
export { Sparklines, SparklinesLine, SparklinesCurve, SparklinesBars, SparklinesSpots, SparklinesReferenceLine, SparklinesNormalBand }
|
src/routes/login/index.js | dervos/react-starter-kit | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Login from './Login';
export const path = '/login';
export const action = async (state) => {
const title = 'Log In';
state.context.onSetTitle(title);
return <Login title={title} />;
};
|
node_modules/react-router/es6/IndexLink.js | mattrusso/mattrusso.github.io | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import React from 'react';
import Link from './Link';
/**
* An <IndexLink> is used to link to an <IndexRoute>.
*/
var IndexLink = React.createClass({
displayName: 'IndexLink',
render: function render() {
return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true }));
}
});
export default IndexLink; |
examples/css-modules-custom/app.js | aruberto/react-foundation-components | /* eslint-disable import/no-unresolved */
import React from 'react';
import ReactDOM from 'react-dom';
import '../../lib/_typography.scss';
import { Button } from '../../lib/button';
import { ButtonGroup } from '../../lib/button-group';
import { ButtonGroup as FlexButtonGroup } from '../../lib/button-group-flex';
const App = () => (
<div>
<h1>Welcome to CSS Modules Custom example!</h1>
<p>
Importing a component will import the components required CSS. This means that your final
CSS stylesheet generated by bundler will always contain minimum required amount of class
names.
</p>
<p>
We've also imported <code>react-foundation-components/lib/_typography.scss</code> for
general look and feel.
</p>
<p>
We are also using https://www.npmjs.com/package/jsontosass-loader to prepend theme.json
to all CSS modules imported. Here theme.json is changing the secondary color to purple.
</p>
<div>
<h3>Button <code>react-foundation-components/lib/button</code></h3>
<Button>Click Me!</Button>
<Button color="secondary">Purple is Secondary Color</Button>
</div>
<div>
<h3>ButtonGroup <code>react-foundation-components/lib/button-group</code></h3>
<ButtonGroup>
<Button>A</Button>
<Button>B</Button>
<Button>C</Button>
</ButtonGroup>
</div>
<div>
<h3>
Flexbox ButtonGroup <code>react-foundation-components/lib/button-group-flex</code>
</h3>
<p>
Because CSS Modules creates class names that are scoped locally to the component,
we can use same Flexbox based and Float based components at same time! CSS Modules FTW!
</p>
<FlexButtonGroup>
<Button>A</Button>
<Button>B</Button>
<Button>C</Button>
</FlexButtonGroup>
</div>
</div>
);
ReactDOM.render(<App />, document.getElementById('app'));
|
src/parser/priest/shadow/modules/spells/Dispersion.js | FaideWW/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import Analyzer from 'parser/core/Analyzer';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import calculateMaxCasts from 'parser/core/calculateMaxCasts';
import Voidform from './Voidform';
const DISPERSION_BASE_CD = 90;
const DISPERSION_UPTIME_MS = 6000;
class Disperion extends Analyzer {
static dependencies = {
voidform: Voidform,
};
_dispersions = {};
_previousDispersionCast = null;
get dispersions() {
return Object.keys(this._dispersions).map(key => this._dispersions[key]);
}
startDispersion(event) {
this._dispersions[event.timestamp] = {
start: event.timestamp,
};
this._previousDispersionCast = event;
}
endDispersion(event) {
this._dispersions[this._previousDispersionCast.timestamp] = {
...this._dispersions[this._previousDispersionCast.timestamp],
end: event.timestamp,
};
if(this.voidform.inVoidform){
this.voidform.addVoidformEvent(SPELLS.DISPERSION.id, {
start: this.voidform.normalizeTimestamp({timestamp: this._previousDispersionCast.timestamp}),
end: this.voidform.normalizeTimestamp(event),
});
}
this._previousDispersionCast = null;
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.DISPERSION.id) this.startDispersion(event);
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.DISPERSION.id) this.endDispersion(event);
}
suggestions(when) {
const dispersionUptime = this.selectedCombatant.getBuffUptime(SPELLS.DISPERSION.id);
const maxDispersiontime = Math.floor(calculateMaxCasts(DISPERSION_BASE_CD, this.owner.fightDuration)) * DISPERSION_UPTIME_MS;
const dispersedTime = dispersionUptime / this.maxUptime;
when(dispersedTime).isGreaterThan(0.20)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You spent {Math.round(dispersionUptime / 1000)} seconds (out of a possible {Math.round(maxDispersiontime / 1000)} seconds) in <SpellLink id={SPELLS.DISPERSION.id} />. Consider using <SpellLink id={SPELLS.DISPERSION.id} /> less or cancel it early.</span>)
.icon(SPELLS.DISPERSION.icon)
.actual(`${formatPercentage(actual)}% Dispersion uptime`)
.recommended(`<${formatPercentage(recommended)}% is recommended, unless the encounter requires it.`)
.regular(recommended + 0.05).major(recommended + 0.15);
});
}
}
export default Disperion;
|
test/integration/production/components/hello-context.js | zeit/next.js | import React from 'react'
import PropTypes from 'prop-types'
export default class extends React.Component {
static contextTypes = {
data: PropTypes.object,
}
render() {
const { data } = this.context
return <div>{data.title}</div>
}
}
|
node_modules/react-bootstrap/es/InputGroupButton.js | firdiansyah/crud-req | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var InputGroupButton = function (_React$Component) {
_inherits(InputGroupButton, _React$Component);
function InputGroupButton() {
_classCallCheck(this, InputGroupButton);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
InputGroupButton.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('span', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return InputGroupButton;
}(React.Component);
export default bsClass('input-group-btn', InputGroupButton); |
src/containers/PlayerContainer.js | ptrslr/silent-party | import React from 'react';
import SC from 'soundcloud';
import { connect } from 'react-redux';
import { togglePlay, playPrevTrack, playNextTrack, playTrack} from '../actions';
import Player from '../components/Player';
var audio;
const mapStateToProps = state => {
return {
isPlaying: state.isPlaying,
trackId: state.trackId,
trackIndex: state.trackIndex,
trackDuration: state.trackDuration,
trackTime: state.trackTime,
username: state.username,
title: state.title,
img: state.img,
tracks: state.tracks
}
}
const mapDispatchTopPros = dispatch => {
return {
onPrevClick: () => {
dispatch(playPrevTrack());
},
onNextClick: () => {
dispatch(playNextTrack());
},
onPlayClick: (isPlaying) => {
dispatch(togglePlay(isPlaying));
},
}
}
const PlayerContainer = connect(
mapStateToProps,
mapDispatchTopPros
)(Player);
// componentDidMount() {
// let audioData;
// let $this = this;
// audio = new Audio();
// audio.addEventListener('ended', this.handleTrackEnded);
// // audio.addEventListener('timeupdate', this.handleTimeUpdate);
// this.timerID = setInterval(() => this.handleTimeUpdate(), 1000);
// SC.initialize({
// client_id: CLIENT_ID
// });
// this.resolveAudio();
// }
// componentWillUnmount() {
// clearInterval(this.timerID);
// }
// getStreamURL(track) {
// const result = track.stream_url + '?client_id=' + CLIENT_ID;
// return result;
// }
// resolveAudio() {
// let $this = this;
// SC.resolve(this.props.audioURL).then(function (result) {
// console.log(result);
// let audioData = result;
// let kind = audioData.kind;
// let tracks = [];
// if (kind === "playlist") {
// tracks = audioData.tracks;
// } else {
// tracks.push(audioData);
// }
// let user = audioData.user;
// let username = user.username;
// let title = audioData.title;
// let img = tracks[0].artwork_url ? tracks[0].artwork_url : tracks[0].user.avatar_url;
// img = img.replace(/(.*)(-large)(\..*)/, '$1-t500x500$3');
// // console.log(img);
// let currentTrackId = tracks[0].id;
// let streamURL = $this.getStreamURL(tracks[0]);
// $this.setState({
// isPlaying: false,
// currentTrackNo: 0,
// currentTrackId: currentTrackId,
// currentTrackDuration: tracks[0].duration,
// audioData: result,
// username: username,
// title: title,
// img: img,
// streamURL: streamURL,
// tracks: tracks
// }, function () {
// audio.src = streamURL;
// $this.playPause();
// $this.playlist.resolvePlaylist();
// })
// // console.log($this.state);
// }, function (err) {
// alert('Error resolving audio...perhaps bad url?' + err);
// });
// }
// handleTrackEnded() {
// // console.log('ended');
// if (this.state.currentTrackNo === this.state.tracks.length - 1) {
// this.setState({
// isPlaying: false
// })
// } else {
// this.playByTrackNo(this.state.currentTrackNo + 1);
// }
// }
// handleTimeUpdate() {
// this.setState({
// currentTrackTime: audio.currentTime * 1000
// })
// }
// playByTrackNo(no) {
// if (no === this.state.currentTrackNo) {
// this.playPause();
// } else {
// let track = this.state.tracks[no];
// let img = track.artwork_url ? track.artwork_url : track.user.avatar_url;
// img = img.replace(/(.*)(-large)(\..*)/, '$1-t500x500$3');
// this.setState({
// isPlaying: true,
// currentTrackNo: no,
// currentTrackId: track.id,
// currentTrackDuration: track.duration,
// currentTrackTime: 0,
// audioData: track,
// username: track.user.username,
// title: track.title,
// img: img,
// streamURL: this.getStreamURL(track),
// }, function () {
// audio.src = this.state.streamURL;
// this.play();
// this.playlist.resolvePlaylist();
// })
// }
// }
// playPause() {
// if (this.state.isPlaying) {
// // console.log('pause that shit');
// this.pause();
// this.setState({
// isPlaying: false
// })
// } else {
// // console.log('pump up the jam');
// this.play();
// this.setState({
// isPlaying: true
// })
// }
// }
// play() {
// audio.play();
// }
// pause() {
// clearInterval()
// audio.pause();
// }
// previous() {
// let currentTrackNo = this.state.currentTrackNo;
// this.playByTrackNo(currentTrackNo - 1 >= 0 ? currentTrackNo - 1 : 0)
// }
// next() {
// let currentTrackNo = this.state.currentTrackNo;
// this.playByTrackNo(currentTrackNo + 1 < this.state.tracks.length ? currentTrackNo + 1 : this.state.tracks.length - 1)
// }
// render() {
// return (
// <Player />
// );
// }
// }
export default PlayerContainer; |
src/svg-icons/action/lightbulb-outline.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLightbulbOutline = (props) => (
<SvgIcon {...props}>
<path d="M9 21c0 .55.45 1 1 1h4c.55 0 1-.45 1-1v-1H9v1zm3-19C8.14 2 5 5.14 5 9c0 2.38 1.19 4.47 3 5.74V17c0 .55.45 1 1 1h6c.55 0 1-.45 1-1v-2.26c1.81-1.27 3-3.36 3-5.74 0-3.86-3.14-7-7-7zm2.85 11.1l-.85.6V16h-4v-2.3l-.85-.6C7.8 12.16 7 10.63 7 9c0-2.76 2.24-5 5-5s5 2.24 5 5c0 1.63-.8 3.16-2.15 4.1z"/>
</SvgIcon>
);
ActionLightbulbOutline = pure(ActionLightbulbOutline);
ActionLightbulbOutline.displayName = 'ActionLightbulbOutline';
ActionLightbulbOutline.muiName = 'SvgIcon';
export default ActionLightbulbOutline;
|
src/svg-icons/editor/attach-money.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorAttachMoney = (props) => (
<SvgIcon {...props}>
<path d="M11.8 10.9c-2.27-.59-3-1.2-3-2.15 0-1.09 1.01-1.85 2.7-1.85 1.78 0 2.44.85 2.5 2.1h2.21c-.07-1.72-1.12-3.3-3.21-3.81V3h-3v2.16c-1.94.42-3.5 1.68-3.5 3.61 0 2.31 1.91 3.46 4.7 4.13 2.5.6 3 1.48 3 2.41 0 .69-.49 1.79-2.7 1.79-2.06 0-2.87-.92-2.98-2.1h-2.2c.12 2.19 1.76 3.42 3.68 3.83V21h3v-2.15c1.95-.37 3.5-1.5 3.5-3.55 0-2.84-2.43-3.81-4.7-4.4z"/>
</SvgIcon>
);
EditorAttachMoney = pure(EditorAttachMoney);
EditorAttachMoney.displayName = 'EditorAttachMoney';
EditorAttachMoney.muiName = 'SvgIcon';
export default EditorAttachMoney;
|
src/components/CardBody.js | carlyleec/cc-react | import React from 'react'; // eslint-disable-line
import styled from 'styled-components';
const CardBody = styled.div`
font-size: 1em;
font-weight: 400;
line-height: 2;
color: inherit;
width: 100%;
display: flex;
flex-wrap: wrap;
flex: 1 1 90%;
margin-bottom: 5px;
overflow: auto;
@media (min-width: 480px) {
font-size: 1em;
}
@media (min-width: 768px) {
font-size: 1em;
}
@media (min-width: 992px) {
font-size: 1.2em;
margin: 20px;
}
>ul>li{
list-style-type: square;
}
`;
export default CardBody;
|
app/components/ProgressBar/index.js | Princess310/onehower-frontend | import React from 'react';
import ProgressBar from './ProgressBar';
function withProgressBar(WrappedComponent) {
class AppWithProgressBar extends React.Component {
constructor(props) {
super(props);
this.state = {
progress: -1,
loadedRoutes: props.location && [props.location.pathname],
};
this.updateProgress = this.updateProgress.bind(this);
}
componentWillMount() {
// Store a reference to the listener.
/* istanbul ignore next */
this.unsubscribeHistory = this.props.router && this.props.router.listenBefore((location) => {
// Do not show progress bar for already loaded routes.
if (this.state.loadedRoutes.indexOf(location.pathname) === -1) {
this.updateProgress(0);
}
});
}
componentWillUpdate(newProps, newState) {
const { loadedRoutes, progress } = this.state;
const { pathname } = newProps.location;
// Complete progress when route changes. But prevent state update while re-rendering.
if (loadedRoutes.indexOf(pathname) === -1 && progress !== -1 && newState.progress < 100) {
this.updateProgress(100);
this.setState({
loadedRoutes: loadedRoutes.concat([pathname]),
});
}
}
componentWillUnmount() {
// Unset unsubscribeHistory since it won't be garbage-collected.
this.unsubscribeHistory = undefined;
}
updateProgress(progress) {
this.setState({ progress });
}
render() {
return (
<div>
<ProgressBar percent={this.state.progress} updateProgress={this.updateProgress} />
<WrappedComponent {...this.props} />
</div>
);
}
}
AppWithProgressBar.propTypes = {
location: React.PropTypes.object,
router: React.PropTypes.object,
};
return AppWithProgressBar;
}
export default withProgressBar;
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-bricks-google-map.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import ReactDOM from 'react-dom';
import $ from 'jquery';
import {BaseMixin, ElementaryMixin} from '../common/common.js';
import './google-map.less';
export const GoogleMap = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Bricks.GoogleMap',
classNames: {
main: 'uu5-bricks-google-map'
},
defaults: {
loadLibsEvent: 'uu5-bricks-google-map-load-libs',
apiKeyUrl: 'https://maps.googleapis.com/maps/api/js'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
mapType: React.PropTypes.oneOf(['satellite', 'roadmap']),
latitude: React.PropTypes.number,
longitude: React.PropTypes.number,
markers: React.PropTypes.arrayOf(React.PropTypes.shape({
latitude: React.PropTypes.number,
longitude: React.PropTypes.number,
title: React.PropTypes.string,
label: React.PropTypes.string
})),
zoom: React.PropTypes.number,
disableZoom: React.PropTypes.bool,
draggable: React.PropTypes.bool,
disableDefaultUI: React.PropTypes.bool,
googleApiKey: React.PropTypes.string,
height: React.PropTypes.string,
width: React.PropTypes.string,
// https://developers.google.com/maps/documentation/javascript/styling
mapStyle: React.PropTypes.arrayOf(React.PropTypes.object)
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps() {
return {
mapType: 'roadmap',
latitude: 50.107799,
longitude: 14.453689,
markers: [],
zoom: 14,
disableZoom: false,
draggable: true,
disableDefaultUI: false,
googleApiKey: null,
height: '400px',
width: '100%',
mapStyle: null
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
componentDidMount() {
this._initialize();
},
// setting map options through props
// for additions see https://developers.google.com/maps/documentation/javascript/reference#MapOptions
componentWillReceiveProps(nextProps) {
if (nextProps.controlled) {
let newMapOptions = {};
(nextProps.draggable !== undefined) && (newMapOptions.draggable = nextProps.draggable);
(nextProps.disableZoom !== undefined) && (newMapOptions.scrollwheel = !nextProps.disableZoom);
(nextProps.disableDefaultUI !== undefined) && (newMapOptions.disableDefaultUI = nextProps.disableDefaultUI);
Object.keys(newMapOptions).length && this.setMapOptions(newMapOptions);
if (this.props.markers !== nextProps.markers) {
this._initialize(nextProps.markers);
}
}
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
getMap() {
return this._googleMap;
},
setMapOptions(options) {
if (typeof options === 'object' && options !== null) {
this._googleMap.setOptions(options);
}
return this;
},
//@@viewOff:interface
//@@viewOn:overridingMethods
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_initialize(markers){
markers = markers || this.props.markers;
if (typeof google === 'undefined' && !window.googleMapApiLoading) {
this._loadLibraries(this._initMap);
} else if (googleMapApiLoading) {
if (window.googleMapApiLoaded) {
this._initMap(markers);
} else {
$(window).on(this.getDefault().loadLibsEvent, this._initMap);
}
} else {
this._loadLibraries.this._initMap(markers);
}
},
_loadLibraries(callback) {
let googleMap = this;
window.google = false;
window.googleMapApiLoading = true;
let script = document.createElement('script');
document.head.appendChild(script);
script.onload = function () {
window.googleMapApiLoaded = true;
$(window).trigger(googleMap.getDefault().loadLibsEvent);
typeof callback === 'function' && callback();
};
script.src = this.getDefault().apiKeyUrl +
(this.props.googleApiKey ? '?key=' + this.props.googleApiKey : '');
},
_initMap(markers) {
markers = markers || this.props.markers;
let myCenter = new google.maps.LatLng(this.props.latitude, this.props.longitude);
let mapProps = {
center: myCenter,
zoom: this.props.zoom,
zoomControl: !this.props.disableZoom,
scrollwheel: !this.props.disableZoom,
disableDoubleClickZoom: this.props.disableZoom,
draggable: this.props.draggable,
disableDefaultUI: this.props.disableDefaultUI,
mapTypeId: google.maps.MapTypeId[this.props.mapType.toUpperCase()]
};
this._googleMap = this._googleMap || new google.maps.Map(ReactDOM.findDOMNode(this._map), mapProps);
if (this._markers && this._markers.length > 0) {
this._markers.forEach((marker) => {
marker.setMap(null); //clear old markers
})
}
if (this.props.mapStyle) {
let styledMap = new google.maps.StyledMapType(this.props.mapStyle);
this._googleMap.mapTypes.set('map_style', styledMap);
this._googleMap.setMapTypeId('map_style');
}
if (markers !== null) {
this._markers = [];
if (!markers.length) {
let marker = new google.maps.Marker({
position: myCenter
});
this._markers.push(marker);
marker.setMap(this._googleMap);
} else {
markers.forEach((markerProps) => {
let position = new google.maps.LatLng(markerProps.latitude, markerProps.longitude);
let animation = markerProps.animation ? google.maps.Animation[markerProps.animation.toUpperCase()] : null;
let newMarker = new google.maps.Marker({
position: position,
center: position,
title: markerProps.title,
label: markerProps.label,
icon: markerProps.icon,
animation: animation
});
if (typeof markerProps.onClick === 'function') {
newMarker.addListener('click', (e) => markerProps.onClick(this, newMarker, e))
}
this._markers.push(newMarker);
newMarker.setMap(this._googleMap);
});
}
}
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render() {
let mainAttrs = this.buildMainAttrs();
let mapAttrs = {
ref: (ref) => this._map = ref,
style: {height: this.props.height, width: this.props.width}
};
return (
<div {...mainAttrs}>
<div {...mapAttrs} />
{this.getDisabledCover()}
</div>
);
}
//@@viewOff:render
});
export default GoogleMap;
|
src/svg-icons/image/slideshow.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageSlideshow = (props) => (
<SvgIcon {...props}>
<path d="M10 8v8l5-4-5-4zm9-5H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/>
</SvgIcon>
);
ImageSlideshow = pure(ImageSlideshow);
ImageSlideshow.displayName = 'ImageSlideshow';
export default ImageSlideshow;
|
src/components/AsyncComponent.js | btoo/btoo.github.io | import React, { Component } from 'react';
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null,
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C
? <C {...this.props} />
: null;
}
}
return AsyncComponent;
} |
core/server/lib/members/static/auth/components/CheckoutForm.js | Gargol/Ghost | import React, { Component } from 'react';
import { CardElement } from 'react-stripe-elements';
class CheckoutForm extends Component {
constructor(props) {
super(props);
}
render() {
let style = {
base: {
'::placeholder': {
color: '#8795A1',
fontSize: '15px'
}
},
invalid: {
'::placeholder': {
color: 'rgba(240, 82, 48, 0.75)'
}
}
};
return (
<div className="gm-form-element">
<CardElement style={ style } />
</div>
);
}
}
export default CheckoutForm;
|
app/javascript/mastodon/features/account_gallery/components/media_item.js | blackle/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Permalink from '../../../components/permalink';
import { displaySensitiveMedia } from '../../../initial_state';
export default class MediaItem extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
};
state = {
visible: !this.props.media.getIn(['status', 'sensitive']) || displaySensitiveMedia,
};
handleClick = () => {
if (!this.state.visible) {
this.setState({ visible: true });
return true;
}
return false;
}
render () {
const { media } = this.props;
const { visible } = this.state;
const status = media.get('status');
const focusX = media.getIn(['meta', 'focus', 'x']);
const focusY = media.getIn(['meta', 'focus', 'y']);
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
const style = {};
let label, icon;
if (media.get('type') === 'gifv') {
label = <span className='media-gallery__gifv__label'>GIF</span>;
}
if (visible) {
style.backgroundImage = `url(${media.get('preview_url')})`;
style.backgroundPosition = `${x}% ${y}%`;
} else {
icon = (
<span className='account-gallery__item__icons'>
<i className='fa fa-eye-slash' />
</span>
);
}
return (
<div className='account-gallery__item'>
<Permalink to={`/statuses/${status.get('id')}`} href={status.get('url')} style={style} onInterceptClick={this.handleClick}>
{icon}
{label}
</Permalink>
</div>
);
}
}
|
src/components/Average/index.js | Vizzuality/iadb | 'use strict';
import './style.css';
import $ from 'jquery';
import React from 'react';
import helpers from '../../helpers';
class Average extends React.Component {
constructor(props) {
super(props);
this.state = {
name: null,
value: null,
natValue: null,
codgov: props.codgov,
layerName: props.layerName,
layerData: props.layerData,
date: props.date,
rank: null,
maxRank: null,
population: null
};
}
fetchData() {
let query = (this.state.layerData.total) ? this.props.queryTotal : this.props.queryPerc;
const username = this.props.cartodbUser;
const sql = query
.replace(/\$\{relatedColumn\}/g, this.state.layerData.relatedColumn || '')
.replace(/\$\{tableName\}/g, this.state.layerData.tableName || '')
.replace(/\$\{columnName\}/g, this.state.layerName)
.replace(/\$\{year\}/g, this.state.date.getFullYear())
.replace(/\$\{codgov\}/g, this.state.codgov);
const url = `https:\/\/${username}.cartodb.com/api/v2/sql?q=${sql}`;
$.getJSON(url, data => {
const d = data.rows[0];
this.setState({
name: d.name,
value: d.average_value,
natValue: this.state.layerData.columnName === 'indicator' ? null : d.nat_average_value,
rank: d.rank,
maxRank: d.maxrank,
population: d.population
});
}).fail((err) => {
throw err.responseText;
});
}
componentDidUpdate(prevProps, prevState) {
if (!this.state.codgov) {
return;
}
if (!this.state.name) {
this.fetchData();
}
if (prevState.codgov !== this.state.codgov ||
prevState.layerName !== this.state.layerName ||
prevState.date !== this.state.date) {
this.fetchData();
}
}
componentDidMount() {
if (this.state.codgov) {
this.fetchData();
}
}
render() {
let rank = null;
if (!this.state.name) {
return (
<div className="average">
<h2>Seleccione un municipio en el mapa</h2>
</div>
);
}
if (this.state.rank) {
rank = <div className="panels">
<div className="panel">
<h3>Ranking</h3>
<div className="nat-value">{`${helpers.formatNumber(this.state.rank, 0)} / ${helpers.formatNumber(this.state.maxRank, 0)}`}</div>
</div>
<div className="panel">
<h3>Population</h3>
<div className="nat-value">{helpers.formatNumber(this.state.population, 0)}</div>
</div>
</div>;
}
const avgNat = (this.state.natValue || this.state.value === 0) ? helpers.formatNumber(this.state.natValue, 3) : '-';
const avgMun = (this.state.value || this.state.value === 0) ? helpers.formatNumber(this.state.value, 3) : '-';
return (
<div className="average">
<h2>{this.state.name}</h2>
{rank}
<div className="panels">
<div className="panel">
<h3>Media nacional</h3>
<div className="nat-value">{avgNat} <span className="unit">{this.state.layerData.unit}</span></div>
</div>
<div className="panel">
<h3>Media municipal</h3>
<div className="value">{avgMun} <span className="unit">{this.state.layerData.unit}</span></div>
</div>
</div>
</div>
);
}
}
Average.propTypes = {
cartodbUser: React.PropTypes.string,
layerName: React.PropTypes.string,
codgov: React.PropTypes.string,
date: React.PropTypes.object,
query: React.PropTypes.string
};
export default Average;
|
docs/app/Examples/collections/Breadcrumb/Content/BreadcrumbExampleSectionProps.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Breadcrumb } from 'semantic-ui-react'
const sections = [
{ key: 'home', content: 'Home', link: true },
{ key: 'search', content: 'Search', active: true },
]
const BreadcrumbExampleSectionProps = () => (
<Breadcrumb sections={sections} />
)
export default BreadcrumbExampleSectionProps
|
src/views/NoChild.js | SBP07/frontend | import React from 'react';
export default class HomeView extends React.Component {
render() {
return (
<div className="container" style={{
'textAlign': 'center'
}}>
<img src={require('../images/speellogo.png')} width="auto" height="50px" style={{
'margin': '10px'
}} />
</div>
);
}
}
|
docs/src/sections/PageHeaderSection.js | SSLcom/Bootsharp | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function PageHeaderSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="page-header">Page header</Anchor> <small>PageHeader</small>
</h2>
<p>A simple shell for an <code>h1</code> to appropriately space out and segment sections of content on a page. It can utilize the <code>h1</code>’s default <code>small</code> element, as well as most other components (with additional styles).</p>
<ReactPlayground codeText={Samples.PageHeader} />
<h3><Anchor id="page-header-props">Props</Anchor></h3>
<PropTable component="PageHeader"/>
</div>
);
}
|
app/javascript/mastodon/features/compose/components/upload_progress.js | kibousoft/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { FormattedMessage } from 'react-intl';
export default class UploadProgress extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
progress: PropTypes.number,
};
render () {
const { active, progress } = this.props;
if (!active) {
return null;
}
return (
<div className='upload-progress'>
<div className='upload-progress__icon'>
<i className='fa fa-upload' />
</div>
<div className='upload-progress__message'>
<FormattedMessage id='upload_progress.label' defaultMessage='Uploading...' />
<div className='upload-progress__backdrop'>
<Motion defaultStyle={{ width: 0 }} style={{ width: spring(progress) }}>
{({ width }) =>
<div className='upload-progress__tracker' style={{ width: `${width}%` }} />
}
</Motion>
</div>
</div>
</div>
);
}
}
|
actor-apps/app-web/src/app/components/modals/Contacts.react.js | ONode/actor-platform | //
// Deprecated
//
import _ from 'lodash';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import ContactStore from 'stores/ContactStore';
import Modal from 'react-modal';
import AvatarItem from 'components/common/AvatarItem.react';
let appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
let getStateFromStores = () => {
return {
contacts: ContactStore.getContacts(),
isShown: ContactStore.isContactsOpen()
};
};
class Contacts extends React.Component {
componentWillMount() {
ContactStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
ContactStore.removeChangeListener(this._onChange);
}
constructor() {
super();
this._onClose = this._onClose.bind(this);
this._onChange = this._onChange.bind(this);
this.state = getStateFromStores();
}
_onChange() {
this.setState(getStateFromStores());
}
_onClose() {
ContactActionCreators.hideContactList();
}
render() {
let contacts = this.state.contacts;
let isShown = this.state.isShown;
let contactList = _.map(contacts, (contact, i) => {
return (
<Contacts.ContactItem contact={contact} key={i}/>
);
});
if (contacts !== null) {
return (
<Modal className="modal contacts"
closeTimeoutMS={150}
isOpen={isShown}>
<header className="modal__header">
<a className="modal__header__close material-icons" onClick={this._onClose}>clear</a>
<h3>Contact list</h3>
</header>
<div className="modal__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
} else {
return (null);
}
}
}
Contacts.ContactItem = React.createClass({
propTypes: {
contact: React.PropTypes.object
},
mixins: [PureRenderMixin],
_openNewPrivateCoversation() {
DialogActionCreators.selectDialogPeerUser(this.props.contact.uid);
ContactActionCreators.hideContactList();
},
render() {
let contact = this.props.contact;
return (
<li className="contacts__list__item row">
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
<div className="controls">
<a className="material-icons" onClick={this._openNewPrivateCoversation}>message</a>
</div>
</li>
);
}
});
export default Contacts;
|
packages/ringcentral-widgets/components/VoicemailPlayer/index.js | ringcentral/ringcentral-js-widget | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import formatDuration from '../../lib/formatDuration';
import DownloadIcon from '../../assets/images/Download.svg';
import PlayIcon from '../../assets/images/Play.svg';
import PauseIcon from '../../assets/images/Pause.svg';
import { Button } from '../Button';
import styles from './styles.scss';
import i18n from './i18n';
const audiosMap = {};
class VoicemailPlayer extends Component {
constructor(props) {
super(props);
this.state = {
playing: false,
paused: false,
progress: 0,
};
this._id = `${props.uri &&
props.uri
.split('?')[0]
.split('/')
.pop()}/${new Date().getTime()}`;
this._audio = new Audio();
this._audio.preload = false;
this._audio.volume = 1;
audiosMap[this._id] = this._audio;
this._audio.addEventListener('timeupdate', () => {
if (!this._mounted) {
return;
}
this.setState({
progress: this._audio.currentTime / this._audio.duration,
});
});
this._audio.addEventListener('ended', () => {
if (!this._mounted) {
return;
}
this.setState({
playing: false,
});
this._audio.isPlaying = false;
});
this._audio.addEventListener('pause', () => {
if (!this._mounted) {
return;
}
this.setState({
paused: true,
playing: false,
});
this._audio.isPlaying = false;
});
this._audio.addEventListener('play', () => {
if (!this._mounted) {
return;
}
this.setState({
playing: true,
paused: false,
});
this._audio.isPlaying = true;
});
this._audio.addEventListener('error', () => {
console.error(this._audio.error);
});
this._playAudio = () => {
if (this.state.playing) {
return;
}
if (!this.state.paused) {
this._audio.src = this.props.uri;
this._audio.load(this.props.uri);
if (!Number.isNaN(this._audio.duration)) {
this._audio.currentTime = 0;
}
}
this._pauseOtherAudios();
this._audio._playPromise = this._audio.play();
if (typeof this.props.onPlay === 'function') {
this.props.onPlay();
}
};
this._pauseAudio = () => {
if (this.state.paused) {
return;
}
if (this._audio._playPromise !== undefined) {
this._audio._playPromise.then(() => {
this._audio.pause();
});
}
};
this._onDownloadClick = (e) => {
if (this.props.disabled) {
e.preventDefault();
}
};
}
_pauseOtherAudios() {
Object.keys(audiosMap).forEach((id) => {
if (id === this._id) {
return;
}
const otherAudio = audiosMap[id];
if (otherAudio.isPlaying && otherAudio._playPromise) {
otherAudio._playPromise.then(() => {
otherAudio.pause();
});
}
});
}
componentDidMount() {
this._mounted = true;
}
componentWillUnmount() {
this._mounted = false;
if (!Number.isNaN(this._audio.duration)) {
this._audio.currentTime = 0;
}
this._audio.pause();
delete audiosMap[this._id];
}
render() {
const { className, duration, uri, disabled, currentLocale } = this.props;
let icon;
if (this.state.playing) {
icon = (
<Button
className={classnames(styles.play, disabled ? styles.disabled : null)}
onClick={this._pauseAudio}
disabled={disabled}
>
<span title={i18n.getString('pause', currentLocale)}>
<PauseIcon width={18} height={18} />
</span>
</Button>
);
} else {
icon = (
<Button
className={classnames(styles.play, disabled ? styles.disabled : null)}
onClick={this._playAudio}
disabled={disabled}
>
<span title={i18n.getString('play', currentLocale)} data-sign="play">
<PlayIcon width={18} height={18} />
</span>
</Button>
);
}
const currentTime =
this._audio.currentTime < duration ? this._audio.currentTime : duration;
const downloadUri = `${uri}&contentDisposition=Attachment`;
return (
<div className={classnames(styles.root, className)}>
{icon}
<span className={styles.startTime}>{formatDuration(currentTime)}</span>
<a
className={classnames(
styles.download,
disabled ? styles.disabled : null,
)}
target="_blank"
download
data-sign="download"
title={i18n.getString('download', currentLocale)}
href={downloadUri}
onClick={this._onDownloadClick}
>
<DownloadIcon width={18} height={18} />
</a>
<span className={styles.endTime}>{formatDuration(duration)}</span>
<div className={styles.progress}>
<div className={styles.all} />
<div
className={styles.done}
style={{ width: `${this.state.progress * 100}%` }}
/>
<div
className={styles.current}
style={{ left: `${this.state.progress * 100}%` }}
/>
</div>
</div>
);
}
}
VoicemailPlayer.propTypes = {
duration: PropTypes.number,
uri: PropTypes.string.isRequired,
className: PropTypes.string,
onPlay: PropTypes.func,
disabled: PropTypes.bool,
currentLocale: PropTypes.string.isRequired,
};
VoicemailPlayer.defaultProps = {
duration: 0,
className: undefined,
onPlay: undefined,
disabled: false,
};
export default VoicemailPlayer;
|
frontend/src/components/recipes/edit/Create.js | jf248/scrape-the-plate | import React from 'react';
import { Scraper } from 'controllers/scraper';
import CreatePres from './CreatePres';
function Create() {
const renderFunc = scraperProps => {
return <CreatePres {...scraperProps} />;
};
return <Scraper render={renderFunc} />;
}
export default Create;
|
docs/app/Examples/modules/Tab/Usage/TabExamplePaneShorthand.js | shengnian/shengnian-ui-react | import React from 'react'
import { List, Label, Tab } from 'shengnian-ui-react'
const panes = [
{ menuItem: 'Tab 1', pane: { key: 'tab1', content: 'This is massive tab', size: 'massive' } },
{ menuItem: 'Tab 2', pane: { key: 'tab2', content: 'This tab has a center aligned text', textAlign: 'center' } },
{ menuItem: 'Tab 3', pane: { key: 'tab3', content: <div>This tab contains an <Label>JSX</Label> element</div> } },
{ menuItem: 'Tab 4',
pane: (
<Tab.Pane key='tab4'>
<p>This tab has a complex content</p>
<List>
<List.Item>Apples</List.Item>
<List.Item>Pears</List.Item>
<List.Item>Oranges</List.Item>
</List>
</Tab.Pane>
) },
]
const TabExampleContentShorthand = () => (
<Tab panes={panes} renderActiveOnly={false} />
)
export default TabExampleContentShorthand
|
app/components/login-signup/FormWrapper.js | adrilo/headek | import React, { Component } from 'react';
import Form from './Form';
export default class FormWrapper extends Component {
render() {
let wrapperStyles = {
outer: {
left: '50%',
position: 'fixed',
top: '50%',
transform: 'translate(-50%, -60%)'
},
inner: {
width: '280px'
}
};
let bottomContentStyle = {
textAlign: 'center'
};
return (
<div style={wrapperStyles.outer}>
<div style={wrapperStyles.inner}>
<Form
type={this.props.formType}
submitLabel={this.props.formSubmitLabel}
onSubmit={this.props.onSubmit}
disableSubmit={this.props.disableSubmit}
error={this.props.error} />
<p style={bottomContentStyle}>
{this.props.bottomContent}
</p>
</div>
</div>
);
}
}
|
node_modules/react-bootstrap/es/Accordion.js | ASIX-ALS/asix-final-project-frontend | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PanelGroup from './PanelGroup';
var Accordion = function (_React$Component) {
_inherits(Accordion, _React$Component);
function Accordion() {
_classCallCheck(this, Accordion);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Accordion.prototype.render = function render() {
return React.createElement(
PanelGroup,
_extends({}, this.props, { accordion: true }),
this.props.children
);
};
return Accordion;
}(React.Component);
export default Accordion; |
examples/shared-root/app.js | MattSPalmer/react-router | import React from 'react';
import { Router, Route, Link } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
<p>
This illustrates how routes can share UI w/o sharing the URL.
When routes have no path, they never match themselves but their
children can, allowing "/signin" and "/forgot-password" to both
be render in the <code>SignedOut</code> component.
</p>
<ol>
<li><Link to="/home">Home</Link></li>
<li><Link to="/signin">Sign in</Link></li>
<li><Link to="/forgot-password">Forgot Password</Link></li>
</ol>
{this.props.children}
</div>
);
}
});
var SignedIn = React.createClass({
render() {
return (
<div>
<h2>Signed In</h2>
{this.props.children}
</div>
);
}
});
var Home = React.createClass({
render() {
return (
<h3>Welcome home!</h3>
);
}
});
var SignedOut = React.createClass({
render() {
return (
<div>
<h2>Signed Out</h2>
{this.props.children}
</div>
);
}
});
var SignIn = React.createClass({
render() {
return (
<h3>Please sign in.</h3>
);
}
});
var ForgotPassword = React.createClass({
render() {
return (
<h3>Forgot your password?</h3>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route component={SignedOut}>
<Route path="signin" component={SignIn} />
<Route path="forgot-password" component={ForgotPassword} />
</Route>
<Route component={SignedIn}>
<Route path="home" component={Home} />
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
src/ProjectOne/ProjectOne.js | brz0/folio-v11 | import React from 'react';
import ReactTooltip from 'react-tooltip';
import Gallery from 'react-photo-gallery';
import LazyLoad from 'react-lazyload';
var Scroll = require('react-scroll');
var Link = Scroll.Link;
var Element = Scroll.Element;
var Events = Scroll.Events;
var scroll = Scroll.animateScroll;
var scrollSpy = Scroll.scrollSpy;
import Nav from '../Nav/Nav.js';
import ProjBgLink from '../img/bg.png';
import ProjLogo from '../img/logos/logo-projects-01.svg';
import ProjBgHeaderPath from '../img/project-header/projbg1.jpg';
const ProjBgHeader = {backgroundImage: 'url(' + ProjBgHeaderPath + ')'};
// Pagination
import PaginationLogoPrev from '../img/logos/logo-projects-05.svg';
import PaginationImgPrevPath from '../img/home/project-06.jpg';
const PaginationImgPrev = {backgroundImage: 'url(' + PaginationImgPrevPath + ')'};
import PaginationLogoNext from '../img/logos/logo-projects-02.svg';
import PaginationImgNextPath from '../img/home/project-02.jpg';
const PaginationImgNext = {backgroundImage: 'url(' + PaginationImgNextPath + ')'};
// Tech Icons
import Sass from '../img/tech/sass.png';
import DThree from '../img/tech/d3.png';
import ReactJs from '../img/tech/react.png';
import Javascript from '../img/tech/js.png';
import NodeJs from '../img/tech/nodejs.png';
import PostCss from '../img/tech/postcss.png';
import Webpack from '../img/tech/webpack.png';
import Sketch from '../img/tech/sketch.png';
import Illustrator from '../img/tech/illustrator.png';
const ProjOnePartTwoA = 'https://mir-s3-cdn-cf.behance.net/project_modules/fs/ae71a149062167.58aa45fb8c0ee.jpg';
const ProjOnePartTwoB = 'https://mir-s3-cdn-cf.behance.net/project_modules/fs/31145d49062167.58aa643058b88.jpg';
const ProjOnePartTwoC = 'https://mir-s3-cdn-cf.behance.net/project_modules/fs/dbf9af49062167.58aa6430582fc.jpg';
const ProjOnePartThreeA = 'https://mir-s3-cdn-cf.behance.net/project_modules/fs/35625349062167.58aa4b8944201.jpg';
const ProjOnePartThreeB = 'https://mir-s3-cdn-cf.behance.net/project_modules/max_3840/2f850649062167.58aa643057a61.png';
const ProjOnePartFourA = 'https://mir-s3-cdn-cf.behance.net/project_modules/fs/023c9e49062167.58aa5b5f4f89b.png';
const ProjOnePartFourB = 'https://mir-s3-cdn-cf.behance.net/project_modules/fs/1bc66a49062167.58aa615e54a1e.png';
const ProjOnePartFiveA = 'https://mir-s3-cdn-cf.behance.net/project_modules/fs/9b499049062167.58aa615e55237.jpg';
const ProjOnePartTwo = [
{ src: ProjOnePartTwoA, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartTwoA, }},
{ src: ProjOnePartTwoB, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartTwoB, }},
{ src: ProjOnePartTwoC, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartTwoC, }},
];
const ProjOnePartThree = [
{ src: ProjOnePartThreeA, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartThreeA, }},
{ src: ProjOnePartThreeB, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartThreeB, }},
];
const ProjOnePartFour = [
{ src: ProjOnePartFourA, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartFourA, }},
{ src: ProjOnePartFourB, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartFourB, }},
];
const ProjOnePartFive = [
{ src: ProjOnePartFiveA, width: 120, height: 120, aspectRatio: 1, lightboxImage: { src: ProjOnePartFiveA, }},
];
export default class ProjectOne extends React.Component {
constructor(props) {
super(props)
document.title = "Chart Suite";
document.body.style.backgroundAttachment = 'fixed';
document.body.style.backgroundSize = 'cover';
document.body.style.backgroundPosition = 'center center';
if (window.matchMedia('(max-width: 767px)').matches) {
document.body.style.backgroundImage = 'none';
} else {
document.body.style.backgroundImage = 'url(' + ProjBgLink + ')';
}
}
componentDidMount() { scrollSpy.update(); }
componentWillUnmount() {
Events.scrollEvent.remove('begin');
Events.scrollEvent.remove('end');
}
componentWillMount() { scroll.scrollToTop(); }
scrollToTop() { scroll.scrollToTop(); }
scrollToBottom() { scroll.scrollToBottom(); }
scrollTo() { scroll.scrollTo(100); }
scrollMore() { scroll.scrollMore(100); }
render() {
return (
<div>
<Nav />
<div className="projectIntro">
<div style={ProjBgHeader} className="projectIntroBanner">
<div className="projTextWrap projTextWrapTop">
<div className="projIntroTop">
<div className="projIntroLinksWrap">
<img src={ProjLogo} className="projectLogo"/>
<a href="http://chart-suite.netlify.com" className="projIntroLinks projIntroLinkOne">
<i className="ion-ios-world-outline"></i> website
</a>
<a href="https://github.com/brz0/chart-suite" className="projIntroLinks projIntroLinkTwo">
<i className="ion-social-github-outline"></i> github
</a>
<a href="https://www.behance.net/gallery/49062167/Chart-Suite" className="projIntroLinks projIntroLinkThree">
<i className="ion-social-github-outline"></i> behance
</a>
</div>
<p className="projTextIntro">A web app for creating interactive charts to easily display data and update the information in browser. Lets you add info via browser on any device, and save as a PNG image. Options of different charts and settings. All info can be edited in real time via the settings sidebar.</p>
<span className="projTags">charts, interaction, webapp, UI, presentation, live updates</span>
<Link activeClass="active" to="projects" spy={true}
smooth={true} offset={-42} duration={500} onSetActive={this.handleSetActive}>
<button className="homeBtn hvr-pulse projViewBtn">
<i className="ion-ios-bolt-outline"></i> VIEW PROJECT
</button>
</Link>
</div>
</div>
</div>
</div>
<div className="projTextWrap projTextWrapBody">
<Element name="projects"></Element>
<h2 className="projHeaderTxt">Wireframes</h2>
<p className="projDesc">The wireframes covered a wide range of possibilities for the chart layouts and behaviour for this project, which led an excessive amount of initial concepts. The screens mapped out were initially mapped for some extra features, and alternate behaviours. The chart editor page has quite a few options as well initially that ended up being one result.</p>
<LazyLoad height={300}><Gallery photos={ProjOnePartTwo} preloadNextImage={false} /></LazyLoad><div className="clearfix"></div>
<h2 className="projHeaderTxt">UI</h2>
<p className="projDesc">As with the wireframes, the UI mockups for this project initially were extensive. The mockups reduced a few of the ideas in wireframes, and helped to hone down and focus on the important layouts for the initial version of the web app. This stage also had some refactoring of the layout for the same reason. In this stage other responsive elements were worked out, as well as finalizing the chart editor.</p>
<LazyLoad height={300}><Gallery photos={ProjOnePartFour} preloadNextImage={false} /></LazyLoad><div className="clearfix"></div>
<h2 className="projHeaderTxt">Branding</h2>
<p className="projDesc">The main goal for the branding of this project is to visually simplify the users data into something easily digestible, while of course looking good simultaniously. The process work for the logo had some predictable chart type solutions, and some abstract idea progression. The best outcome from this came with a geometric shape resembling a few different charts combined. An in between of the obvious chart type logo, and some nice looking abstract geometric shapes.</p>
<LazyLoad height={300}><Gallery photos={ProjOnePartThree} preloadNextImage={false} /></LazyLoad><div className="clearfix"></div>
<h2 className="projHeaderTxt">Features</h2>
<p className="projDesc">Layout options were built with re useable components to be added throughout the layouts, and possible future layouts. The charts themselves have extensive interactivity that adjust in real time to the user input. The data is also displayed with a high level of interaction on hover/touch events. Forms and buttons have a high level of contract and some basic animations for ease of navigation.</p>
<LazyLoad height={300}><Gallery photos={ProjOnePartFive} preloadNextImage={false} /></LazyLoad><div className="clearfix"></div>
<h2 className="projHeaderTxt">Tech</h2>
<p className="projDesc">The project is built with a nodeJS server for a speed and to use many popular front end javascript tools easily. The app itself consists of components with functionality built in React JS, and some external libraries. The charts themselves use a react component chart library called Recharts. The styling used involved a collection of PostCSS plugins and SASS mixins for layout and re useable CSS parts. All mockups were created in Sketch, Branding/Concepts built in Adobe Illustrator, and photo editing done with Adobe Photoshop.</p>
<ReactTooltip />
<img src={Sass} className="techIcon" data-tip="Sass" data-effect="solid"/>
<img src={DThree} className="techIcon" data-tip="D3" data-effect="solid"/>
<img src={ReactJs} className="techIcon" data-tip="React" data-effect="solid"/>
<img src={Javascript} className="techIcon" data-tip="Javascript" data-effect="solid"/>
<img src={NodeJs} className="techIcon" data-tip="Node" data-effect="solid"/>
<img src={PostCss} className="techIcon" data-tip="PostCSS" data-effect="solid"/>
<img src={Webpack} className="techIcon" data-tip="Webpack" data-effect="solid"/>
<img src={Sketch} className="techIcon" data-tip="Sketch" data-effect="solid"/>
<img src={Illustrator} className="techIcon" data-tip="Illustrator" data-effect="solid"/><br />
<h2 className="projHeaderTxt projHeaderTxtLast">More Projects</h2><br />
<a href="gold-tooth" className="paginationLinkWrap">
<div style={PaginationImgPrev} className="projPagination">
<img src={PaginationLogoPrev} className="projPaginationLogo" />
</div>
</a>
<a href="terminal-ui" className="paginationLinkWrap">
<div style={PaginationImgNext} className="projPagination">
<img src={PaginationLogoNext} className="projPaginationLogo terminalPagination" />
</div>
</a>
</div>
</div>
)
}
}
|
src/Components/Measure.js | vpodolyan/measurements | import React from 'react';
export default class Measure extends React.Component {
shouldComponentUpdate (nextProps) {
const {measurements} = nextProps;
if (!measurements || measurements.length === 0) {
return false;
}
return true;
}
render () {
const {measurements, name, unit, ValueElement} = this.props;
return (
<div>
<h3>{name}</h3>
<div>
{
measurements.map(item => (
<div key={item[0]} className="item">
<div>t = {new Date(item[0]).toLocaleString()}</div>
<div>v = <ValueElement value={item[1]} unit={unit}/></div>
</div>
))
}
</div>
</div>
)
}
} |
client/components/midi/Player.js | bsubedi26/Project-Revised | import React from 'react';
class Player extends React.Component {
render() {
return (
<div className="player row">
<h2 className="white-text">Currently Playing | {this.props.playing}</h2>
</div>
);
}
}
Player.propTypes = {
playing: React.PropTypes.string.isRequired,
}
export default Player; |
src/components/Callback/index.js | vladovidiu/soundcloud | import React from 'react';
class Callback extends React.Component {
componentDidMount() {
window.setTimeout(opener.SC.connectCallback, 1);
}
render() {
return <div><p>This page should close soon.</p></div>
}
}
export default Callback;
|
src/decorators/withViewport.js | maquessime/stack-to-issue-ui | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
rio/assets/routes.js | soasme/rio | import React from 'react'
import {Redirect, Route, IndexRoute} from 'react-router'
import App from './views/app'
let routes = (
<Route path="/dashboard" component={App}>
</Route>
)
export default routes;
|
app/static/src/performer/TestTypeResultForm_modules/PolymerisationDegreeTestForm.js | vsilent/Vision | import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import Button from 'react-bootstrap/lib/Button';
import Panel from 'react-bootstrap/lib/Panel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
import {NotificationContainer, NotificationManager} from 'react-notifications';
const TextField = React.createClass({
render: function() {
var label = (this.props.label != null) ? this.props.label: "";
var name = (this.props.name != null) ? this.props.name: "";
var value = (this.props.value != null) ? this.props.value: "";
return (
<FormGroup validationState={this.props.errors[name] ? 'error' : null}>
<FormControl type="text"
placeholder={label}
name={name}
value={value}
data-type={this.props["data-type"]}
data-len={this.props["data-len"]}
/>
<HelpBlock className="warning">{this.props.errors[name]}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
);
}
});
const CheckBox = React.createClass({
render: function () {
var name = (this.props.name != null) ? this.props.name : "";
return (
<Checkbox name={name}>
<span className="glyphicon glyphicon-menu-left">
</span>
</Checkbox>
);
}
});
var PolymerisationDegreeTestForm = React.createClass({
getInitialState: function () {
return {
loading: false,
errors: {},
fields: [
'phase_a1', 'phase_a2', 'phase_a3', 'phase_b1', 'phase_b2',
'phase_b3', 'phase_c1', 'phase_c2', 'phase_c3',
'lead_a', 'lead_b', 'lead_c', 'lead_n',
'winding'
]
}
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.tableName + '/?test_result_id=' + this.props.testResultId;
this.serverRequest = $.authorizedGet(source, function (result) {
var res = (result['result']);
if (res.length > 0) {
var fields = this.state.fields;
fields.push('id');
var data = res[0];
var state = {};
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
if (data.hasOwnProperty(key)) {
state[key] = data[key];
}
}
this.setState(state);
}
}.bind(this), 'json');
},
_create: function () {
var fields = this.state.fields;
var data = {test_result_id: this.props.testResultId};
var url = '/api/v1.0/' + this.props.tableName + '/';
for (var i = 0; i < fields.length; i++) {
var key = fields[i];
data[key] = this.state[key];
}
if ('id' in this.state) {
url += this.state['id'];
}
return $.authorizedAjax({
url: url,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
beforeSend: function () {
this.setState({loading: true});
}.bind(this)
})
},
_onSubmit: function (e) {
e.preventDefault();
// Do not propagate the submit event of the main form
e.stopPropagation();
if (!this.is_valid()){
NotificationManager.error('Please correct the errors');
e.stopPropagation();
return false;
}
var xhr = this._create();
xhr.done(this._onSuccess)
.fail(this._onError)
.always(this.hideLoading)
},
hideLoading: function () {
this.setState({loading: false});
},
_onSuccess: function (data) {
// this.setState(this.getInitialState());
NotificationManager.success('Test values have been saved successfully.');
},
_onError: function (data) {
var message = "Failed to create";
var res = data.responseJSON;
if (res.message) {
message = data.responseJSON.message;
}
if (res.error) {
// We get list of errors
if (data.status >= 500) {
message = res.error.join(". ");
} else if (res.error instanceof Object){
// We get object of errors with field names as key
for (var field in res.error) {
var errorMessage = res.error[field];
if (Array.isArray(errorMessage)) {
errorMessage = errorMessage.join(". ");
}
res.error[field] = errorMessage;
}
this.setState({
errors: res.error
});
} else {
message = res.error;
}
}
NotificationManager.error(message);
},
_onChange: function (e) {
var state = {};
if (e.target.type == 'checkbox') {
state[e.target.name] = e.target.checked;
} else if (e.target.type == 'select-one') {
state[e.target.name] = e.target.value;
} else {
state[e.target.name] = e.target.value;
}
var errors = this._validate(e);
state = this._updateFieldErrors(e.target.name, state, errors);
this.setState(state);
},
_validate: function (e) {
var errors = [];
var error;
error = this._validateFieldType(e.target.value, e.target.getAttribute("data-type"));
if (error){
errors.push(error);
}
error = this._validateFieldLength(e.target.value, e.target.getAttribute("data-len"));
if (error){
errors.push(error);
}
return errors;
},
_validateFieldType: function (value, type){
var error = "";
if (type != undefined && value){
var typePatterns = {
"float": /^(-|\+?)[0-9]+(\.)?[0-9]*$/
};
if (!typePatterns[type].test(value)){
error = "Invalid " + type + " value";
}
}
return error;
},
_validateFieldLength: function (value, length){
var error = "";
if (value && length){
if (value.length > length){
error = "Value should be maximum " + length + " characters long"
}
}
return error;
},
_updateFieldErrors: function (fieldName, state, errors){
// Clear existing errors related to the current field as it has been edited
state.errors = this.state.errors;
delete state.errors[fieldName];
// Update errors with new ones, if present
if (Object.keys(errors).length){
state.errors[fieldName] = errors.join(". ");
}
return state;
},
is_valid: function () {
return (Object.keys(this.state.errors).length <= 0);
},
_formGroupClass: function (field) {
var className = "form-group ";
if (field) {
className += " has-error"
}
return className;
},
render: function () {
return (
<div className="form-container">
<form method="post" action="#" onSubmit={this._onSubmit} onChange={this._onChange}>
<div className="row">
<div className="col-md-3 col-md-offset-3">
<Panel header="Primary">
</Panel>
</div>
<div className="col-md-3">
<Panel header="Secondary">
</Panel>
</div>
<div className="col-md-3">
<Panel header="Connection">
</Panel>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-1">
<b>Phase A</b>
</div>
<div className="col-md-3">
<TextField label="phase_a1" name="phase_a1" value={this.state.phase_a1}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_a2" name="phase_a2" value={this.state.phase_a2}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_a3" name="phase_a3" value={this.state.phase_a3}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-1">
<b>Phase B</b>
</div>
<div className="col-md-3">
<TextField label="phase_b1" name="phase_b1" value={this.state.phase_b1}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_b2" name="phase_b2" value={this.state.phase_b2}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_b3" name="phase_b3" value={this.state.phase_b3}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2 col-md-offset-1">
<b>Phase C</b>
</div>
<div className="col-md-3">
<TextField label="phase_c1" name="phase_c1" value={this.state.phase_c1}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_c2" name="phase_c2" value={this.state.phase_c2}
errors={this.state.errors} data-type="float"/>
</div>
<div className="col-md-3">
<TextField label="phase_c3" name="phase_c3" value={this.state.phase_c3}
errors={this.state.errors} data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-12 ">
<Panel header="Lead & Winding">
</Panel>
</div>
</div>
<div className="row">
<div className="col-md-1">
<b>Lead A</b>
</div>
<div className="col-md-2">
<TextField label="lead_a" name="lead_a" value={this.state.lead_a}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
<div className="col-md-1">
<b>Lead B</b>
</div>
<div className="col-md-2">
<TextField label="lead_b" name="lead_b" value={this.state.lead_b}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
<div className="col-md-1">
<b>Lead C</b>
</div>
<div className="col-md-2">
<TextField label="lead_c" name="lead_c" value={this.state.lead_c}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
<div className="col-md-1">
<b>Lead N</b>
</div>
<div className="col-md-2">
<TextField label="lead_n" name="lead_n" value={this.state.lead_n}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
</div>
<div className="row">
<div className="col-md-3 pull-right">
<b>Winding</b>
<TextField label="winding" name="winding" value={this.state.winding}
errors={this.state.errors} data-type="float" data-len="4"/>
</div>
</div>
<div className="row">
<div className="col-md-12 ">
<Button bsStyle="success"
className="pull-right"
type="submit">Save</Button>
<Button bsStyle="danger"
className="pull-right margin-right-xs"
onClick={this.props.handleClose}
>Cancel</Button>
</div>
</div>
</form>
</div>
);
}
});
export default PolymerisationDegreeTestForm;
|
client/app/components/common/ValidatedInput.js | Zuehlke/poinz | import React from 'react';
import PropTypes from 'prop-types';
/**
*/
const ValidatedInput = (props) => {
const {fieldValue, setFieldValue, onEnter, regexPattern, allLowercase, ...restProps} = props;
const pattern = typeof regexPattern === 'string' ? new RegExp(regexPattern) : regexPattern;
return (
<input {...restProps} value={fieldValue} onChange={onChange} onKeyPress={onInputKeyPress} />
);
function onInputKeyPress(e) {
if (!onEnter) {
return;
}
if (e.key === 'Enter') {
e.preventDefault();
onEnter();
}
}
function onChange(ev) {
const val = allLowercase ? ev.target.value.toLowerCase() : ev.target.value;
if (pattern.test(val)) {
setFieldValue(val);
}
}
};
ValidatedInput.propTypes = {
fieldValue: PropTypes.any.isRequired,
setFieldValue: PropTypes.func.isRequired,
onEnter: PropTypes.func,
allLowercase: PropTypes.bool, // if true, entered characters get "lowercased" before pattern checking
regexPattern: PropTypes.oneOfType([PropTypes.string, PropTypes.instanceOf(RegExp)]).isRequired
};
export default ValidatedInput;
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | nguyendt214/poloniex | 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'));
|
src/components/login/LoginForm.js | fusionalliance/autorenter-react | import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, Form, FormGroup } from 'react-bootstrap';
import { connect } from 'react-redux';
import { Field, reduxForm, formValueSelector } from 'redux-form';
import styles from './loginStyles.css';
import inputField from '../common/form/inputField';
import validate from './loginValidation';
let LoginForm = ({ submissionError, handleSubmit, pristine, submitting, hasUsername, hasPassword }) => {
return (
<Row className={styles.loginContainer}>
<Form onSubmit={handleSubmit} horizontal>
<legend>Login</legend>
{
submissionError ?
<div className={styles.loginError}>
There was a problem logging in. Please check your credentials and try again.
</div> :
''
}
<FormGroup controlId="formHorizontalUsername">
<Col sm={2}>
Username
</Col>
<Col sm={10}>
<Field
name="username"
component={inputField}
/>
</Col>
</FormGroup>
<FormGroup controlId="formHorizontalPassword">
<Col sm={2}>
Password
</Col>
<Col sm={10}>
<Field
name="password"
component={inputField}
type="password"
/>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<button type="submit" className="btn btn-default" disabled={!hasUsername || !hasPassword || pristine || submitting}>
Sign in
</button>
</Col>
</FormGroup>
</Form>
</Row>
);
};
LoginForm.propTypes = {
onFormChange: PropTypes.func,
onFormSubmit: PropTypes.func,
handleSubmit: PropTypes.func,
submitting: PropTypes.bool,
pristine: PropTypes.bool,
hasUsername: PropTypes.string,
hasPassword: PropTypes.string,
submissionError: PropTypes.object
};
LoginForm = reduxForm({
form: 'loginForm',
validate
})(LoginForm);
const selector = formValueSelector('loginForm');
LoginForm = connect(state => {
const submissionError = state.userData.error;
const hasUsername = selector(state, 'username');
const hasPassword = selector(state, 'password');
return {
hasUsername,
hasPassword,
submissionError
};
})(LoginForm);
export default LoginForm;
|
client/kit/entry/server.js | Bartekus/FuseR | /* eslint-disable no-param-reassign, no-console */
// Server entry point, for Webpack. This will spawn a Koa web server
// and listen for HTTP requests. Clients will get a return render of React
// or the file they have requested
//
// Note: No HTTP optimisation is performed here (gzip, http/2, etc). Node.js
// will nearly always be slower than Nginx or an equivalent, dedicated proxy,
// so it's usually better to leave that stuff to a faster upstream provider
// ----------------------
// IMPORTS
/* Node */
import path from 'path';
/* NPM */
// Patch global.`fetch` so that Apollo calls to GraphQL work
import 'isomorphic-fetch';
// Needed to read manifest files
import { readFileSync } from 'fs';
// React UI
import React from 'react';
// React utility to transform JSX to HTML (to send back to the client)
import ReactDOMServer from 'react-dom/server';
// Koa 2 web server. Handles incoming HTTP requests, and will serve back
// the React render, or any of the static assets being compiled
import Koa from 'koa';
// Apollo tools to connect to a GraphQL server. We'll grab the
// `ApolloProvider` HOC component, which will inject any 'listening' React
// components with GraphQL data props. We'll also use `getDataFromTree`
// to await data being ready before rendering back HTML to the client
import { ApolloProvider, getDataFromTree } from 'react-apollo';
// HTTP header hardening
import koaHelmet from 'koa-helmet';
// Koa Router, for handling URL requests
import KoaRouter from 'koa-router';
// Static file handler
import koaStatic from 'koa-static';
// High-precision timing, so we can debug response time to serve a request
import ms from 'microseconds';
// React Router HOC for figuring out the exact React hierarchy to display
// based on the URL
import { StaticRouter } from 'react-router';
// <Helmet> component for retrieving <head> section, so we can set page
// title, meta info, etc along with the initial HTML
import Helmet from 'react-helmet';
/* Local */
// Grab the shared Apollo Client
import { serverClient } from 'kit/lib/apollo';
// Custom redux store creator. This will allow us to create a store 'outside'
// of Apollo, so we can apply our own reducers and make use of the Redux dev
// tools in the browser
import createNewStore from 'kit/lib/redux';
// Initial view to send back HTML render
import Html from 'kit/views/ssr';
// App entry point
import App from 'src/app';
// Import paths. We'll use this to figure out where our public folder is
// so we can serve static files
import PATHS from 'config/paths';
// ----------------------
// Read in manifest files
const [manifest, chunkManifest] = ['manifest', 'chunk-manifest'].map(
name => JSON.parse(
readFileSync(path.resolve(PATHS.dist, `${name}.json`), 'utf8'),
),
);
const scripts = [
'manifest.js',
'vendor.js',
'browser.js'].map(key => manifest[key]);
// Port to bind to. Takes this from the `PORT` environment var, or assigns
// to 4000 by default
const PORT = process.env.PORT || 4000;
// Run the server
(async function server() {
// Set up routes
const router = (new KoaRouter())
// Set-up a general purpose /ping route to check the server is alive
.get('/ping', async ctx => {
ctx.body = 'pong';
})
// Favicon.ico. By default, we'll serve this as a 204 No Content.
// If /favicon.ico is available as a static file, it'll try that first
.get('/favicon.ico', async ctx => {
ctx.res.statusCode = 204;
})
// Everything else is React
.get('/*', async ctx => {
const route = {};
// Create a new server Apollo client for this request
const client = serverClient();
// Create a new Redux store for this request
const store = createNewStore(client);
// Generate the HTML from our React tree. We're wrapping the result
// in `react-router`'s <StaticRouter> which will pull out URL info and
// store it in our empty `route` object
const components = (
<StaticRouter location={ctx.request.url} context={route}>
<ApolloProvider store={store} client={client}>
<App />
</ApolloProvider>
</StaticRouter>
);
// Wait for GraphQL data to be available in our initial render,
// before dumping HTML back to the client
await getDataFromTree(components);
// Full React HTML render
const html = ReactDOMServer.renderToString(components);
// Render the view with our injected React data. We'll pass in the
// Helmet component to generate the <head> tag, as well as our Redux
// store state so that the browser can continue from the server
ctx.body = `<!DOCTYPE html>\n${ReactDOMServer.renderToStaticMarkup(
<Html
html={html}
head={Helmet.rewind()}
window={{
webpackManifest: chunkManifest,
__STATE__: store.getState(),
}}
scripts={scripts}
css={manifest['browser.css']} />,
)}`;
});
// Start Koa
(new Koa())
// Preliminary security for HTTP headers
.use(koaHelmet())
// Error wrapper. If an error manages to slip through the middleware
// chain, it will be caught and logged back here
.use(async (ctx, next) => {
try {
await next();
} catch (e) {
// TODO we've used rudimentary console logging here. In your own
// app, I'd recommend you implement third-party logging so you can
// capture errors properly
console.log('Error', e.message);
ctx.body = 'There was an error. Please try again later.';
}
})
// It's useful to see how long a request takes to respond. Add the
// timing to a HTTP Response header
.use(async (ctx, next) => {
const start = ms.now();
await next();
const end = ms.parse(ms.since(start));
const total = end.microseconds + (end.milliseconds * 1e3) + (end.seconds * 1e6);
ctx.set('Response-Time', `${total / 1e3}ms`);
})
// Serve static files from our dist/public directory, which is where
// the compiled JS, images, etc will wind up. Note this is being checked
// FIRST before any routes -- static files always take priority
.use(koaStatic(PATHS.public, {
// All asset names contain the hashes of their contents so we can
// assume they are immutable for caching
maxage: 31536000000,
// Don't defer to middleware. If we have a file, serve it immediately
defer: false,
}))
// If the requests makes it here, we'll assume they need to be handled
// by the router
.use(router.routes())
.use(router.allowedMethods())
// Bind to the specified port
.listen(PORT);
}());
|
actor-apps/app-web/src/app/components/common/Favicon.react.js | gale320/actor-platform | import React from 'react';
export default class Fav extends React.Component {
static propTypes = {
path: React.PropTypes.string
}
constructor(props) {
super(props);
//// Create link element and it's attributes
//let favicon = document.createElement('link');
//let rel = document.createAttribute('rel');
//let type = document.createAttribute('type');
//let href = document.createAttribute('href');
//let id = document.createAttribute('id');
//
//// Set attributes values
//rel.value = 'icon';
//type.value = 'image/png';
//href.value = props.path;
//id.value = 'favicon';
//
//// Set attributes to favicon element
//favicon.setAttributeNode(rel);
//favicon.setAttributeNode(type);
//favicon.setAttributeNode(href);
//favicon.setAttributeNode(id);
//
//// Append favicon to head
//document.head.appendChild(favicon);
}
componentDidUpdate() {
// Clone created element and create href attribute
let updatedFavicon = document.getElementById('favicon').cloneNode(true);
let href = document.createAttribute('href');
// Set new href attribute
href.value = this.props.path;
updatedFavicon.setAttributeNode(href);
// Remove old and add new favicon
document.getElementById('favicon').remove();
document.head.appendChild(updatedFavicon);
}
render() {
return null;
}
}
|
examples/huge-apps/routes/Profile/components/Profile.js | jamiehill/react-router | import React from 'react';
class Profile extends React.Component {
render () {
return (
<div>
<h2>Profile</h2>
</div>
);
}
}
export default Profile;
|
app/components/feedback/feedback.js | imankit/dashboard-ui | import React from 'react';
import Popover from 'material-ui/Popover';
import {ToolbarTitle} from 'material-ui/Toolbar';
import Badge from 'material-ui/Badge';
import NotificationsIcon from 'material-ui/svg-icons/social/notifications';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
import IconMenu from 'material-ui/IconMenu';
import IconButton from 'material-ui/IconButton';
import axios from 'axios'
require('./style.css')
class Notifications extends React.Component {
constructor(props) {
super(props)
this.state = {
open: false,
disableSendBtn: true,
value: ''
}
}
handleTouchTap = (event) => {
event.preventDefault();
this.setState({open: true, anchorEl: event.currentTarget, feedbackSent: false})
this.props.updateBeacon(this.props.beacons, 'dashboardFeedback');
}
handleRequestClose = () => {
this.setState({open: false})
}
handleChange(e) {
let value = e.target.value
if (value) {
this.setState({disableSendBtn: false, value: value});
} else {
this.setState({disableSendBtn: true, value: ''});
}
}
sendFeedback() {
console.log(this.props.user);
if (this.state.value) {
// post to slack webhook, make chages here for updating webhook
axios({
url: "https://hooks.slack.com/services/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",
method: 'post',
withCredentials: false,
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
name: this.props.user.user.name,
email: this.props.user.user.email,
text: this.state.value
}
}).then((res) => {
this.setState({value: ''});
}, (err) => {
this.setState({value: ''});
})
this.setState({feedbackSent: true, value: ''});
}
}
render() {
const disabledBtnStyle = {
fontSize: 10,
marginTop: -1,
background: '#eff1f5',
height: 24,
display: 'block',
paddingTop: 6,
borderRadius: 3,
color: '#b2b1b1'
};
const sendBtnStyle = {
fontSize: 10,
marginTop: -1,
background: '#549afc',
height: 24,
display: 'block',
paddingTop: 6,
borderRadius: 3,
color: 'white'
}
return (
<div >
<IconButton onClick={this.handleTouchTap.bind(this)}>
<svg xmlns="http://www.w3.org/2000/svg" width="29" height="29" viewBox="0 -4 26 26">
<g fill="none" fillRule="evenodd"><path fill="#9e9e9e" d="M2.666 11.995a304.44 304.44 0 0 1-1.841-.776s-.41-.14-.558-.638c-.148-.498-.187-1.058 0-1.627.187-.57.558-.735.558-.735s9.626-4.07 13.64-5.43c.53-.179 1.18-.156 1.18-.156C17.607 2.702 19 6.034 19 9.9c0 3.866-1.62 6.808-3.354 6.84 0 0-.484.1-1.18-.135-2.189-.733-5.283-1.946-7.971-3.035-.114-.045-.31-.13-.338.177v.589c0 .56-.413.833-.923.627l-1.405-.566c-.51-.206-.923-.822-.923-1.378v-.63c.018-.29-.162-.362-.24-.394zM15.25 15.15c1.367 0 2.475-2.462 2.475-5.5s-1.108-5.5-2.475-5.5-2.475 2.462-2.475 5.5 1.108 5.5 2.475 5.5z"/></g>
</svg>
</IconButton>
<span className={this.props.beacons.dashboardFeedback
? 'hide'
: "gps_ring feedback_beacon"} onClick={this.handleTouchTap.bind(this)}></span>
<Popover open={this.state.open} anchorEl={this.state.anchorEl} anchorOrigin={{
horizontal: 'right',
vertical: 'bottom'
}} targetOrigin={{
horizontal: 'right',
vertical: 'top'
}} onRequestClose={this.handleRequestClose} className="feedbackpopover">
<p className="headingpop">Feedback
</p>
<textarea cols="30" rows="4" placeholder="Your thoughts?" className={!this.state.feedbackSent
? "feedback-textarea"
: 'hide'} onChange={this.handleChange.bind(this)} value={this.state.value}></textarea>
<br/>
<div className={!this.state.feedbackSent
? ''
: 'hide'}>
<button className="feedback-sendbtn" onTouchTap={this.sendFeedback.bind(this)} disabled={this.state.disableSendBtn}>Send Feedback</button>
</div>
<div className={this.state.feedbackSent
? 'feedbackSent'
: 'hide'}>
<IconButton touch={true} style={{
marginLeft: '37%',
marginTop: -30
}}>
<svg xmlns="http://www.w3.org/2000/svg" width="50" height="50" viewBox="0 -4 26 26">
<g fill="none" fillRule="evenodd"><path fill="#549afc" d="M2.666 11.995a304.44 304.44 0 0 1-1.841-.776s-.41-.14-.558-.638c-.148-.498-.187-1.058 0-1.627.187-.57.558-.735.558-.735s9.626-4.07 13.64-5.43c.53-.179 1.18-.156 1.18-.156C17.607 2.702 19 6.034 19 9.9c0 3.866-1.62 6.808-3.354 6.84 0 0-.484.1-1.18-.135-2.189-.733-5.283-1.946-7.971-3.035-.114-.045-.31-.13-.338.177v.589c0 .56-.413.833-.923.627l-1.405-.566c-.51-.206-.923-.822-.923-1.378v-.63c.018-.29-.162-.362-.24-.394zM15.25 15.15c1.367 0 2.475-2.462 2.475-5.5s-1.108-5.5-2.475-5.5-2.475 2.462-2.475 5.5 1.108 5.5 2.475 5.5z"/></g>
</svg>
</IconButton>
<span className="thanks-text">Thanks</span>
<span className="note-text">We really appreciate your feedback!</span>
</div>
</Popover>
</div>
)
}
}
export default Notifications;
|
features/fileCenter/components/fileItem.js | zymokey/mission-park | import React from 'react';
import { connect } from 'react-redux';
import axios from 'axios';
import { formatFileSize, getIndexOfArrayByValue, getArrayOfSpecKey } from '../../../utils';
import {
updateFileName, changeCurrentFolder,
updateUploadProgress, addUploadFile,
updateCompletedCount, updateFileSuccess,
updateFileFailure, selectItem, unselectItem } from '../actions';
import DeletePopover from './deletePopover';
import FileInput from '../../common/components/fileInput';
class FileItem extends React.Component {
constructor(props){
super(props);
this.state = {
editable: false,
deleteFlag: false
}
this.user = jwt_decode(localStorage.getItem('token'));
this.documentClick = this.documentClick.bind(this);
this.fileinputData = {
handleUpload: this.handleUpload.bind(this),
icon: '',
id: `update_file_${this.props.file._id}`,
accept: '',
title: 'update file',
labelText: '更新'
};
}
componentDidMount(){
document.addEventListener('click', this.documentClick, false);
}
componentWillUnmount(){
document.removeEventListener('click', this.documentClick, false);
}
documentClick(e){
let element = $('.fc-popover:visible')[0];
if(!element){return;}
if(e.target.getAttribute('data-refer') != 'delete' && e.target !== element && !element.contains(e.target)){
this.setState({
deleteFlag: false
});
}
//set the deleteFlag to false to remove the popover, otherwise it would be still shown on the next file, I don't know why...
if(e.target.getAttribute('data-refer') == 'delete-confirmed'){
this.setState({
deleteFlag: false
});
}
}
handleSelect(e){
let payload = {
fileId: this.props.file._id,
filename: this.props.file.filename
}
let ele = $(e.target).find('span').andSelf();
if(ele.hasClass('unselected')){
this.props.selectItem(payload);
ele.removeClass('unselected');
} else {
this.props.unselectItem(payload);
ele.addClass('unselected');
}
}
handleUpload(e){
// this.props.uploadFile(e);
let that = this;
let oldFile = this.props.file;
let newFile = e.target.files[0];
let data = new FormData();
data.append('fileId', oldFile._id);
data.append('uploadDate', new Date());
data.append('file', newFile);
let progressData = {
timestamp: Date.now(),
filename: newFile.name,
fileSize: newFile.size,
folder: this.props.currentFolder
}
axios.post('/filecenter/update', data, {
headers: {
'Content-Type': 'multipart/form-data'
},
onUploadProgress: function(progressEvent){
let percentCompleted = Math.floor( (progressEvent.loaded * 100) / progressEvent.total);
progressData.percentage = percentCompleted;
//if file is uploading, just update uploading percentage, otherwise, add new uploading file item in upload list
if(~getIndexOfArrayByValue(that.props.uploadFiles, 'timestamp', progressData.timestamp)){
that.props.updateUploadProgress(progressData);
} else {
that.props.addUploadFile(progressData);
}
if(progressData.percentage == 100){
that.props.updateCompletedCount();
}
}
})
.then(function(res){
that.props.updateFileSuccess(oldFile._id, res.data.newFile);
})
.catch(function(err){
that.props.updateFileFailure(err);
});
}
changeEditable(){
this.setState({
editable: !this.state.editable
});
}
renameFile(e){
let that = this;
let val = e.target.value.trim();
if(val == ''){ return; }
let filename = this.props.file.filename;
let fileType = ~filename.indexOf('.') ? '.' + filename.split('.')[filename.split('.').length -1] : '';
let newName = `${val}${fileType}`;
axios.post('/filecenter/rename',{
newName: newName,
fileId: this.props.file._id
})
.then(function(res){
that.props.updateFileName(res.data.file);
})
.catch(function(err){
console.log(err);
});
this.setState({
editable: false
});
}
handleKeyDown(e){
if(e.which == 13){
this.renameFile(e);
}
}
handleClickItem(e){
if(this.props.file.length || e.target.tagName.toLocaleLowerCase() == 'input'){
return;
}
let payload = {
folderId: this.props.file._id,
folderName: this.props.file.filename
}
this.props.changeCurrentFolder(payload);
}
clickDeleteFile(e){
this.setState({
deleteFlag: true
});
}
render(){
const file = this.props.file;
let fileInfo = file.metadata;
let filename = file.filename;
let filenamePart1 = filename.slice(0, -6);
let filenamePart2 = filename.slice(-6);
let fileType = ~filename.indexOf('.') ? '.' + filename.split('.')[filename.split('.').length -1] : '';
return(
<li className="file-list-item clearfix" >
<a className="check-box" onClick={this.handleSelect.bind(this)}>
<span className="unselected glyphicon glyphicon-ok"></span>
</a>
<div className="clearfix" >
<div className="list-item-detail">
<div className="clearfix" onClick={this.handleClickItem.bind(this)}>
{
file.length == 0 ?
<span className="item-icon glyphicon glyphicon-folder-close"></span> :
<span className="item-icon glyphicon glyphicon-file"></span>
}
{
!this.state.editable &&
<div className="item-name" title={filename} >
<span>{filenamePart1}</span>
<span>{filenamePart2}</span>
</div>
}
{
this.state.editable &&
<input type="text" className="form-control editName"
defaultValue={filename.replace(`${fileType}`, '')}
onBlur={this.renameFile.bind(this)}
onKeyDown={this.handleKeyDown.bind(this)} />
}
</div>
</div>
<div className="list-item-info">
<div className="item-size">{`${file.length ? formatFileSize(file.length) : ''}`}</div>
<div className="item-creator" title={fileInfo.creatorName} >{fileInfo.creatorName}</div>
<div className="item-date">{(new Date(file.uploadDate)).toLocaleDateString()}</div>
<div className="item-handler" >
<a className="handler-item" href={`/filecenter/download/?fileId=${file._id}&filename=${filename}`} download >下载</a>
{
!!file.length &&
<a className="handler-item" >
<FileInput data={this.fileinputData} />
</a>
}
<a className="handler-item" >移动</a>
<a className="handler-item" onClick={this.changeEditable.bind(this)} >重命名</a>
<a className="handler-item" data-refer="delete" onClick={this.clickDeleteFile.bind(this)} >删除</a>
{this.state.deleteFlag && <DeletePopover file={file} />}
</div>
</div>
</div>
</li>
);
}
}
const mapStateToProps = state => ({
folderList: state.fileCenter.folderList,
currentFolder: state.fileCenter.currentFolder,
uploadFiles: state.fileCenter.uploadFiles
});
const mapDispatchToProps = dispatch => ({
selectItem: payload => { dispatch(selectItem(payload)); },
unselectItem: payload => { dispatch(unselectItem(payload)); },
updateFileName: file => { dispatch(updateFileName(file)); },
changeCurrentFolder: folder => { dispatch(changeCurrentFolder(folder)); },
updateUploadProgress: data => { dispatch(updateUploadProgress(data)); },
addUploadFile: data => { dispatch(addUploadFile(data)); },
updateCompletedCount: () => { dispatch(updateCompletedCount()); },
updateFileSuccess: (oldFileId, file) => { dispatch(updateFileSuccess(oldFileId, file)); },
updateFileFailure: err => { dispatch(updateFileFailure(err)); }
});
export default connect(mapStateToProps, mapDispatchToProps)(FileItem); |
app/components/yeast/YeastList.js | MitchLillie/brewhome | import React from 'react'
import Yeast from './Yeast'
import YeastForm from './YeastForm'
const YeastList = React.createClass({
render: function () {
let list = this.props.yeast.map((yeast, i) => {
return <Yeast {...yeast} key={i + 1} />
})
return (
<table className='table table-hover table-condensed table-no-bottom yeast-list'>
<tbody>
{list}
<YeastForm onYeastSubmit={this.props.onYeastSubmit}/>
<tr>
<td colSpan='2'>
<button type='button' data-toggle='collapse' data-target='#yeast-form-input' className='btn btn-default'>+</button>
</td>
</tr>
</tbody>
</table>
)
},
propTypes: {
yeast: React.PropTypes.array,
onYeastSubmit: React.PropTypes.func
}
})
export default YeastList
|
actor-apps/app-web/src/app/components/Install.react.js | amezcua/actor-platform | import React from 'react';
export default class Install extends React.Component {
render() {
return (
<section className="mobile-placeholder col-xs row center-xs middle-xs">
<div>
<img alt="Actor messenger"
className="logo"
src="assets/img/logo.png"
srcSet="assets/img/logo@2x.png 2x"/>
<h1>Web version of <b>Actor</b> works only on desktop browsers at this time</h1>
<h3>Please install our apps for using <b>Actor</b> on your phone.</h3>
<p>
<a href="//actor.im/ios">iPhone</a> | <a href="//actor.im/android">Android</a>
</p>
</div>
</section>
);
}
}
|
Agenda/src/components/faq.js | interlegis/agenda-evento | import React, { Component } from 'react';
import { connect } from 'react-redux';
import _ from 'lodash';
import { getUsuario } from '../actions';
import { FIELD_FAQ, FIELD_FAQ2 } from './forms/faq_types';
class Faq extends Component {
constructor(props){
super(props);
}
componentWillMount() {
if (this.props.authenticated) {
this.props.getUsuario();
}
}
renderItems(itemConfig) {
return(
<li key={`${itemConfig}`} className="list-group-item">{itemConfig}</li>
);
}
renderPanel(panelConfig) {
return(
<div key={`${panelConfig.id}\_${panelConfig.parentid}`} className="panel panel-default">
<div className="panel-heading">
<h4 className="panel-title">
<a data-toggle="collapse" data-parent={`#${panelConfig.parentid}`} href={`#${panelConfig.id}`} className="">
{panelConfig.titulo}
</a>
</h4>
</div>
<div id={`${panelConfig.id}`} className="panel-collapse collapse" style={{height: `0px`,}}>
<div className="panel-body">
<ul className="list-group">
{_.map(panelConfig.items, this.renderItems.bind(this))}
</ul>
</div>
</div>
</div>
);
}
render(){
return(
<div className="container">
<div className="row">
<div className="section-title item_bottom text-center" style={{
opacity: `1`,
bottom: `0px`,
}}>
<div>
<span className="fa fa-cogs fa-2x"></span>
</div>
<h1 className="white">Perguntas&<span>Respostas</span>
</h1>
</div>
<div className="col-lg-6 col-md-6 col-sm-12">
<h2 className="faqh">Pedidos</h2>
<div className="panel-group" id="accordion-1">
{_.map(FIELD_FAQ, this.renderPanel.bind(this))}
</div>
</div>
<div className="col-lg-6 col-md-6 col-sm-12">
<h2 className="faqh">Agenda</h2>
<div className="panel-group" id="accordion-2">
{_.map(FIELD_FAQ2, this.renderPanel.bind(this))}
</div>
</div>
</div>
</div>
);
}
}
function mapStateToProps(state){
return {
authenticated: state.authentication.authenticated
};
}
export default connect(mapStateToProps, { getUsuario })(Faq);
|
docs/src/pages/customization/OverridesInlineStyle.js | AndriusBil/material-ui | // @flow weak
import React from 'react';
import Button from 'material-ui/Button';
// We can use inline-style
const style = {
background: 'linear-gradient(45deg, #FE6B8B 30%, #FF8E53 90%)',
borderRadius: 3,
border: 0,
color: 'white',
height: 48,
padding: '0 30px',
boxShadow: '0 3px 5px 2px rgba(255, 105, 135, .30)',
};
function OverridesInlineStyle() {
return <Button style={style}>{'inline-style'}</Button>;
}
export default OverridesInlineStyle;
|
src/components/FrontPage.js | ffossum/gamesite3-client | /* @flow */
import React from 'react';
import ChatContainer from '../redux/modules/chat/ChatContainer';
export default function FrontPage() {
return (
<main>
<h1>Welcome</h1>
<section>
<h2>News</h2>
</section>
<section>
<ChatContainer channelName="general" />
</section>
</main>
);
}
|
web/src/VmprobeConsole.js | vmprobe/vmprobe | import React from 'react';
import PureComponent from 'react-pure-render/component';
import update from './update';
import Timeline from './Timeline';
import $ from 'jquery';
require("../css/bootstrap.min.css");
export default class VmprobeConsole extends PureComponent {
constructor(props) {
super(props);
this.state = {
session_token: null,
events: [],
};
$.ajax({
method: "GET",
url: "/api/connect",
dataType: "json",
success: (data) => {
this.setState({ session_token: data.token });
this.getMsgs();
},
});
}
render() {
if (this.state.session_token === null) {
return (
<div className="vmprobe-console">
Connecting...
</div>
)
}
return (
<div>
<Timeline events={this.state.events} ref="timeline" />
</div>
);
}
getMsgs() {
$.ajax({
method: "GET",
url: "/api/get_events",
data: { token: this.state.session_token, from: this.state.latest_event_id },
dataType: "json",
success: (msgs) => {
this.handleMsgs(msgs);
this.getMsgs();
},
error: () => {
setTimeout(() => this.getMsgs(), 1000);
},
});
}
handleMsgs(msgs) {
for (let msg of msgs) {
this.setState(update(this.state, { latest_event_id: { $set: msg.event_id }, events: { $push: [msg] } }));
}
this.refs.timeline.addEvents(msgs);
}
}
|
exercise-05-solution/src/components/Pokedex.js | learnapollo/pokedex-react | import React from 'react'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
import styled from 'styled-components'
import PokemonPreview from '../components/PokemonPreview'
import AddPokemonPreview from '../components/AddPokemonPreview'
const Title = styled.div`
color: #7F7F7F;
font-size: 32px;
font-weight: 300;
`
class Pokedex extends React.Component {
static propTypes = {
data: React.PropTypes.shape({
loading: React.PropTypes.bool,
error: React.PropTypes.object,
Trainer: React.PropTypes.object,
}).isRequired,
}
render () {
if (this.props.data.loading) {
return (<div>Loading</div>)
}
if (this.props.data.error) {
console.log(this.props.data.error)
return (<div>An unexpected error occurred</div>)
}
return (
<div className='w-100 bg-light-gray min-vh-100'>
<Title className='tc pa5'>
Hey {this.props.data.Trainer.name}, there are {this.props.data.Trainer.ownedPokemons.length} Pokemons in your pokedex
</Title>
<div className='flex flex-wrap justify-center center w-75'>
<AddPokemonPreview trainerId={this.props.data.Trainer.id} />
{this.props.data.Trainer.ownedPokemons.map((pokemon) =>
<PokemonPreview key={pokemon.id} pokemon={pokemon} />
)}
</div>
</div>
)
}
}
const TrainerQuery = gql`query TrainerQuery($name: String!) {
Trainer(name: $name) {
id
name
ownedPokemons {
id
name
url
}
}
}`
const PokedexWithData = graphql(TrainerQuery, {
options: {
variables: {
name: '__NAME__'
}
}
}
)(Pokedex)
export default PokedexWithData
|
src/components/video_list_item.js | robertorb21/ReduxSimpleStarter | import React from 'react'
//const VideoListItem = (props) => {
//const video = props.video
//esas dos lineas las podemos hacer una si le agregamos {} al parametro props y le ponemos direactamente la propiedad
const VideoListItem = ({video, onVideoSelect}) => {
const imageUrl = video.snippet.thumbnails.default.url
//console.log(video)
return (
<li onClick={() => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imageUrl} />
</div>
<div className="media-body">
<div className="media-heading">{video.snippet.title}</div>
</div>
</div>
</li>
)
};
export default VideoListItem;
|
src/components/StartingPage.js | googleinterns/step236-2020 | /**
* Copyright 2020 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Grid from '@material-ui/core/Grid';
import Paper from '@material-ui/core/Paper';
import Button from '@material-ui/core/Button';
import {useStyles} from './LayoutStyles';
import {Link} from 'react-router-dom';
import {signInWithGoogle} from '../firebaseFeatures';
export default function StartingPage() {
const classes = useStyles();
return (
<Paper className={classes.paper}>
<Grid
container
direction="column"
justify="flex-start"
alignItems="stretch"
className={classes.gridContainer}>
<Grid
item
className={classes.gridItem}>
<Button
variant="outlined"
fullWidth
className={classes.button}
onClick={signInWithGoogle}>
Log in
</Button>
</Grid>
<Grid
item
className={classes.gridItem}>
<Button
variant="outlined"
fullWidth
className={classes.button}
component={Link}
to="/form"
onClick={signInWithGoogle}>
Join the community!
</Button>
</Grid>
</Grid>
</Paper>
);
}
|
src/website/app/pages/ComponentDoc/DocExamples.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import ComponentDocExample from '../../ComponentDocExample';
import Section from './DocSection';
import type { Examples } from './types';
type Props = {
examples: Examples,
slug: string
};
export default function DocExamples(props: Props) {
let { examples, slug } = props;
if (process.env.NODE_ENV === 'production') {
examples = examples.filter((example) => !example.hideFromProd);
}
return (
<Section>
{examples.map((example, index) => {
const exampleProps = {
slug,
...example
};
return <ComponentDocExample {...exampleProps} key={index} />;
})}
</Section>
);
}
|
frontend/app/site/pages/Styles/Styles.js | briancappello/flask-react-spa | import React from 'react'
import Helmet from 'react-helmet'
import { HashLink, PageContent } from 'components'
import BlockQuote from './BlockQuote'
import Buttons from './Buttons'
import Code from './Code'
import Forms from './Forms'
import Grid from './Grid'
import Lists from './Lists'
import Navigation from './Navigation'
import Tables from './Tables'
import Typography from './Typography'
import './styles-layout.scss'
export default class Styles extends React.Component {
html = `\
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Super Skeleton</title>
</head>
<body>
<header>
<nav>
<a class="brand">
superskeleton.<span class="tld">com</span>
</a>
<div class="menu">
<!-- top-level menu links -->
</div>
</nav>
</header>
<main class="container">
<!-- your content here -->
</main>
<footer>
<!-- footer content -->
</footer>
</body>
</html>
`
render() {
return (
<PageContent className="row styles-grid">
<Helmet>
<title>Styles</title>
</Helmet>
<aside className="menu-col">
<h4>Styles</h4>
<ul>
<li><span><HashLink to="#site-template">Site Template</HashLink></span></li>
<li><span><HashLink to="#navigation">Navigation</HashLink></span></li>
<li><span><HashLink to="#block-quotes">Block Quotes</HashLink></span></li>
<li>
<HashLink to="#grid">Grid</HashLink>
<ul>
<li><span><HashLink to="#columns">Columns</HashLink></span></li>
<li><span><HashLink to="#fractions">Fractions</HashLink></span></li>
<li><span><HashLink to="#column-offsets">Column Offsets</HashLink></span></li>
<li><span><HashLink to="#fraction-offsets">Fraction Offsets</HashLink></span></li>
</ul>
</li>
<li><span><HashLink to="#typography">Typography</HashLink></span></li>
<li><span><HashLink to="#buttons">Buttons</HashLink></span></li>
<li><span><HashLink to="#forms">Forms</HashLink></span></li>
<li><span><HashLink to="#lists">Lists</HashLink></span></li>
<li><span><HashLink to="#code">Code</HashLink></span></li>
<li><span><HashLink to="#tables">Tables</HashLink></span></li>
</ul>
</aside>
<div className="content-col">
<h1 id="styles">Styles!</h1>
<p>
The included styles are a fork of{' '}
<a href="https://github.com/WhatsNewSaes/Skeleton-Sass">
Skeleton Sass
</a>, which in turn is based on{' '}
<a href="http://getskeleton.com/" target="_blank">
Skeleton
</a>.
</p>
<h2 id="site-template">Site Template</h2>
<p>
Content should be wrapped in <code>.container</code>. It defaults to{' '}
<code>max-width: 1200px</code>.
</p>
<pre>
<code>
{this.html}
</code>
</pre>
<Navigation />
<BlockQuote />
<Grid />
<Typography />
<Buttons />
<Forms />
<Lists />
<Code />
<Tables />
</div>
</PageContent>
)
}
}
|
app/components/AboutComponent.js | cdillon85/the-art-store | import React from 'react'
export default function AboutComponent (props) {
return (
<div>
<h1 className="about-header"> Welcome </h1>
<p className="text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Donec hendrerit tempor tellus. Donec pretium posuere tellus.
Proin quam nisl, tincidunt et, mattis eget, convallis nec, purus.
Cum sociis natoque penatibus et magnis dis parturient montes, nascetur
ridiculus mus. Nulla posuere.</p>
<p className="text">Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec hendrerit
tempor tellus. Donec pretium posuere tellus. Proin quam nisl, tincidunt et,
mattis eget, convallis nec, purus. Cum sociis natoque penatibus et magnis dis
parturient montes, nascetur ridiculus mus. Nulla posuere.</p>
</div>
)
} |
src/client/pages/todos.react.js | grabbou/este | import Buttons from '../todos/buttons.react';
import Component from '../components/component.react';
import DocumentTitle from 'react-document-title';
import List from '../todos/list.react';
import NewTodo from '../todos/newtodo.react';
import React from 'react';
import ToCheck from './tocheck.react';
import immutable from 'immutable';
import {msg} from '../intl/store';
class Todos extends Component {
render() {
const {todos, pendingActions} = this.props;
const list = todos.get('list');
return (
<DocumentTitle title={msg('todos.title')}>
<div className="todos-page">
<NewTodo todo={todos.get('newTodo')} />
<List
editables={todos.get('editables')}
pendingActions={pendingActions}
todos={list}
/>
<Buttons clearAllEnabled={list.size > 0} />
<ToCheck />
</div>
</DocumentTitle>
);
}
}
Todos.propTypes = {
pendingActions: React.PropTypes.instanceOf(immutable.Map).isRequired,
todos: React.PropTypes.instanceOf(immutable.Map).isRequired
};
export default Todos;
|
app/javascript/mastodon/components/column_back_button_slim.js | robotstart/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
class ColumnBackButtonSlim extends React.PureComponent {
constructor (props, context) {
super(props, context);
this.handleClick = this.handleClick.bind(this);
}
handleClick () {
this.context.router.push('/');
}
render () {
return (
<div className='column-back-button--slim'>
<div role='button' tabIndex='0' onClick={this.handleClick} className='column-back-button column-back-button--slim-button'>
<i className='fa fa-fw fa-chevron-left column-back-button__icon' />
<FormattedMessage id='column_back_button.label' defaultMessage='Back' />
</div>
</div>
);
}
}
ColumnBackButtonSlim.contextTypes = {
router: PropTypes.object
};
export default ColumnBackButtonSlim;
|
app/javascript/mastodon/features/compose/containers/warning_container.js | verniy6462/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { connect } from 'react-redux';
import Warning from '../components/warning';
import { createSelector } from 'reselect';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { OrderedSet } from 'immutable';
const getMentionedUsernames = createSelector(state => state.getIn(['compose', 'text']), text => text.match(/(?:^|[^\/\w])@([a-z0-9_]+@[a-z0-9\.\-]+)/ig));
const getMentionedDomains = createSelector(getMentionedUsernames, mentionedUsernamesWithDomains => {
return OrderedSet(mentionedUsernamesWithDomains !== null ? mentionedUsernamesWithDomains.map(item => item.split('@')[2]) : []);
});
const mapStateToProps = state => {
const mentionedUsernames = getMentionedUsernames(state);
const mentionedUsernamesWithDomains = getMentionedDomains(state);
return {
needsLeakWarning: (state.getIn(['compose', 'privacy']) === 'private' || state.getIn(['compose', 'privacy']) === 'direct') && mentionedUsernames !== null,
mentionedDomains: mentionedUsernamesWithDomains,
needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', state.getIn(['meta', 'me']), 'locked']),
};
};
const WarningWrapper = ({ needsLeakWarning, needsLockWarning, mentionedDomains }) => {
if (needsLockWarning) {
return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />;
} else if (needsLeakWarning) {
return (
<Warning
message={<FormattedMessage
id='compose_form.privacy_disclaimer'
defaultMessage='Your private status will be delivered to mentioned users on {domains}. Do you trust {domainsCount, plural, one {that server} other {those servers}}? Post privacy only works on Mastodon instances. If {domains} {domainsCount, plural, one {is not a Mastodon instance} other {are not Mastodon instances}}, there will be no indication that your post is private, and it may be boosted or otherwise made visible to unintended recipients.'
values={{ domains: <strong>{mentionedDomains.join(', ')}</strong>, domainsCount: mentionedDomains.size }}
/>}
/>
);
}
return null;
};
WarningWrapper.propTypes = {
needsLeakWarning: PropTypes.bool,
needsLockWarning: PropTypes.bool,
mentionedDomains: ImmutablePropTypes.orderedSet.isRequired,
};
export default connect(mapStateToProps)(WarningWrapper);
|
app/src/Frontend/libs/weui/components/cell/cell_body.js | ptphp/ptphp | /**
* Created by jf on 15/11/12.
*/
import React from 'react';
import classNames from 'classnames';
export default class CellBody extends React.Component {
render() {
const {children, ...others} = this.props;
const className = classNames({
weui_cell_bd: true,
weui_cell_primary: true
});
return (
<div className={className} {...others}>{children}</div>
);
}
}; |
app/scripts/components/node-details/node-details-property-list.js | hustbill/autorender-js | import React from 'react';
import { Map as makeMap } from 'immutable';
import sortBy from 'lodash/sortBy';
import { NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT } from '../../constants/limits';
import NodeDetailsControlButton from './node-details-control-button';
import MatchedText from '../matched-text';
import ShowMore from '../show-more';
const Controls = controls => (
<div className="node-details-property-list-controls">
{sortBy(controls, 'rank').map(control => <NodeDetailsControlButton
nodeId={control.nodeId} control={control} key={control.id} />)}
</div>
);
export default class NodeDetailsPropertyList extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
limit: NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT,
};
this.handleLimitClick = this.handleLimitClick.bind(this);
}
handleLimitClick() {
const limit = this.state.limit ? 0 : NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT;
this.setState({limit});
}
render() {
const { controls, matches = makeMap() } = this.props;
let rows = this.props.rows;
let notShown = 0;
const limited = rows && this.state.limit > 0 && rows.length > this.state.limit;
const expanded = this.state.limit === 0;
if (rows && limited) {
const hasNotShownMatch = rows.filter((row, index) => index >= this.state.limit
&& matches.has(row.id)).length > 0;
if (!hasNotShownMatch) {
notShown = rows.length - NODE_DETAILS_DATA_ROWS_DEFAULT_LIMIT;
rows = rows.slice(0, this.state.limit);
}
}
return (
<div className="node-details-property-list">
{controls && Controls(controls)}
{rows.map(field => (
<div className="node-details-property-list-field" key={field.id}>
<div
className="node-details-property-list-field-label truncate"
title={field.entries.label} key={field.id}>
{field.entries.label}
</div>
<div
className="node-details-property-list-field-value truncate"
title={field.entries.value}>
<MatchedText text={field.entries.value} match={matches.get(field.id)} />
</div>
</div>
))}
<ShowMore
handleClick={this.handleLimitClick} collection={this.props.rows}
expanded={expanded} notShown={notShown} />
</div>
);
}
}
|
src/index.js | Rakshay/InfiniteScroller | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import PropTypes from 'prop-types';
import axios from 'axios';
import classnames from 'classnames';
import InfiniteList from './messageScroller';
import Message from './message.js';
/**
* This react component will fetch the messages from the api (url must be passed as a prop) and renders it for the user
* @class
*/
class MessagesViewer extends React.Component {
/** @constructs */
constructor () {
super();
this.state = {
pageToken: undefined,
messages: [],
containerHeight: '10'
};
this.fetchMessage = (pageToken) => this._fetchMessage(pageToken);
this.mergeMessages = (currentMessages, newMessages) => this._mergeMessages(currentMessages, newMessages);
this.fetchMessages = (messageCount, currentPageToken) => this._fetchMessages(messageCount, currentPageToken);
this.getMessage = (messageIndex) => this._getMessage(messageIndex);
this.buildMessages = (start, end) => this._buildMessages(start, end);
this.getMessages = () => this._getMessages();
}
/**
* Fetches the stream of messages to be rendered (if provided a page Token will fetch the specific page of data)
* @param {string} [pageToken] Optional pageToken
* @returns {undefined}
*/
_fetchMessage (pageToken) {
return axios({
url: this.props.apiEndPoint,
params: {
pageToken,
limit: 100
}
});
}
/**
*
* @param {Array.Object} currentMessages Array of messages currently held
* @param {Array.Object} newMessages New Array of messages that have to be merged
* @returns {Array.Object} New Array which is combination of currentMessages and newMessages
*/
_mergeMessages (currentMessages, newMessages) {
return currentMessages.concat(newMessages);
}
/**
* A recursive function that will fetch the number of messages required
* @param {number} messageCount Total number of messages required
* @param {string} [currentPageToken] Optional pageToken
* @returns {Promise} Promise object that returns the messages fetched along with a pageToken (if any)
*/
_fetchMessages (messageCount, currentPageToken) {
return new Promise((resolve, reject) => {
this.fetchMessage(currentPageToken)
.then((response) => {
let messages = response.data.messages,
pageToken = response.data.pageToken;
if (messageCount > 100) {
this.fetchMessages((messageCount - 100), pageToken)
.then((messagesReponse) => {
messages = this.mergeMessages(messages, messagesReponse.messages);
resolve({
messages,
pageToken: messagesReponse.pageToken
});
});
} else {
resolve({
messages,
pageToken
});
}
})
.catch((err) => {
reject(err);
});
});
}
/* eslint-disable require-jsdoc */
componentDidMount () {
/* eslint-disable react/no-find-dom-node */
let containerHeight = ReactDOM.findDOMNode(this.container).offsetHeight;
/* eslint-enable react/no-find-dom-node */
this.fetchMessages(800)
.then((messagesReponse) => {
this.setState({
messages: messagesReponse.messages,
pageToken: messagesReponse.pageToken,
containerHeight
});
});
}
/* eslint-enable require-jsdoc */
/**
* Fetches the next batch of messages to be cached for later rendering
* @returns {undefined}
*/
_getMessages () {
if (this.state.fetchingMessages !== true) {
this.setState({
fetchingMessages: true
}, () => {
this.fetchMessages(100, this.state.pageToken)
.then((messagesReponse) => {
this.setState({
messages: this.mergeMessages(this.state.messages, messagesReponse.messages),
pageToken: messagesReponse.pageToken,
fetchingMessages: false
});
});
});
}
}
/**
* Fetches the next batch of messages to be rendered
* @param {number} start The start index, co-relates to a message's index in the list of messages
* @param {number} end The end index, co-relates to a message's index in the list of messages
* @returns {Array.Object} An array of Message elements(React elements) to be rendered
*/
_buildMessages (start, end) {
let elements = [],
messageCount = this.state.messages.length;
if ((messageCount - end) < 600) {
this.getMessages();
}
for (let i = start; i < end; i++) {
let message = this.state.messages[i];
elements.push(<Message key={i} {...message} />);
}
return elements;
}
/* eslint-disable require-jsdoc */
render () {
let className = classnames('infinite-message-list', 'fill-height');
/* eslint-disable indent */
return (
<div className={className} ref={(container) => {this.container = container;}}>
{
(() => {
if (this.state.messages.length > 0) {
return <InfiniteList containerHeight={this.state.containerHeight}
getMessage={this.getMessage}
buildMessages={this.buildMessages} />;
} else {
return <div className="loading-indicator" />;
}
})()
}
</div>
);
}
/* eslint-enable require-jsdoc */
}
MessagesViewer.displayName = 'InfiniteScroller';
MessagesViewer.propTypes = {
/**
* The api base url which feeds the messsages
*/
apiEndPoint: PropTypes.string.isRequired
};
export default MessagesViewer;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.