path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
examples/js/remote/remote-sorting.js | powerhome/react-bootstrap-table | import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
export default class RemoteSorting extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<BootstrapTable data={ this.props.data }
remote={ true }
options={ { onSortChange: this.props.onSortChange } }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price' dataSort={ true }>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/components/FileSelector/FileSelector.js | propertybase/react-lds | import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import Dropzone from 'react-dropzone';
import {
FormElement,
FormElementControl,
FormElementError,
} from '../Form';
import { Button } from '../Button';
const preventDefault = e => e.preventDefault();
const FileSelector = ({
accept,
buttonText,
id,
error,
fatalError,
label,
minSize,
maxSize,
multiple,
onDragEnter,
onDragLeave,
onDrop,
selectorText,
selectorType,
}) => {
const errorStr = fatalError || error;
const fileSelectorClasses = [
'slds-file-selector',
`slds-file-selector_${selectorType}`
];
const primaryLabelId = `${id}-primary-label`;
const secondaryLabelId = `${id}-secondary-label`;
return (
<FormElement error={errorStr}>
<span className="slds-form-element__label" id={primaryLabelId}>
{label}
</span>
<FormElementControl>
<div className={cx(fileSelectorClasses)}>
<Dropzone
accept={accept}
disabled={!!fatalError}
minSize={minSize}
maxSize={maxSize}
multiple={multiple}
onDrop={onDrop}
onDragEnter={onDragEnter}
onDragLeave={onDragLeave}
>
{({
getRootProps,
getInputProps,
isDragActive,
}) => (
<div
{...getRootProps({
className: cx([
'slds-file-selector__dropzone',
{ 'slds-has-drag-over': isDragActive && !fatalError },
])
})}
>
<input
{...getInputProps({
'aria-labelledby': `${primaryLabelId} ${secondaryLabelId}`,
className: 'slds-file-selector__input slds-assistive-text',
disabled: fatalError,
id,
})}
/>
<label
className="slds-file-selector__body"
htmlFor={id}
// Fixes dialog not working due to default `label<>input` event handling (Safari,Chrome)
onClick={preventDefault}
id={secondaryLabelId}
>
<Button
buttonEl="span"
className="slds-file-selector__button"
flavor="neutral"
icon="upload"
sprite="utility"
title={buttonText}
/>
<span className="slds-file-selector__text slds-medium-show">
{selectorText}
</span>
</label>
</div>
)}
</Dropzone>
</div>
</FormElementControl>
<FormElementError error={errorStr} id={id} />
</FormElement>
);
};
FileSelector.defaultProps = {
accept: null,
error: null,
fatalError: null,
minSize: 0,
maxSize: null,
multiple: false,
onDragEnter: null,
onDragLeave: null,
selectorType: 'files',
};
FileSelector.propTypes = {
/**
* Maps to the HTML5 `accept` attribute. Used to narrow down allowed file types
*/
accept: PropTypes.string,
/**
* Button title
*/
buttonText: PropTypes.string.isRequired,
/**
* Error displayed below form. This should be used for informational messages as it does not disable the dropzone
*/
error: PropTypes.string,
/**
* Takes precedence over `error` and _will_ disable the dropzone
*/
fatalError: PropTypes.string,
/**
* Id of this file selector
*/
id: PropTypes.string.isRequired,
/**
* Top-level label
*/
label: PropTypes.string.isRequired,
/**
* Minimum file size (in bytes)
*/
minSize: PropTypes.number,
/**
* Maximum file size (in bytes)
*/
maxSize: PropTypes.number,
/**
* Maps to the HTML5 `multiple` attribute
*/
multiple: PropTypes.bool,
/**
* `onDragEnter` passed to `Dropzone`. Called with:
* - `event`
*/
onDragEnter: PropTypes.func,
/**
* `onDragLeave` passed to `Dropzone`. Called with:
* - `event`
*/
onDragLeave: PropTypes.func,
/**
* `onDrop` passed to `Dropzone`. Called with:
* - `acceptedFiles`
* - `rejectedFiles`
* - `event`
*/
onDrop: PropTypes.func.isRequired,
/**
* Addl. text rendered next to the button
*/
selectorText: PropTypes.string.isRequired,
/**
* Toggles display style
*/
selectorType: PropTypes.oneOf(['files', 'images']),
};
export default FileSelector;
|
src/components/commons/background.js | jesus-chacon/cookBook | import React, { Component } from 'react';
import { connect } from 'react-redux';
class Background extends Component {
render() {
if (!!this.props.background && this.props.background.length > 0) {
return (
<img id="bg" src={this.props.background} alt="background image" />
);
}else {
return (
<div id="bg"></div>
);
}
}
}
const mapStateToProps = ({backgroundReducer}) => ({
background: backgroundReducer.background
});
export default connect(mapStateToProps)(Background); |
demo/tabs/tabs.js | koorchik/react-mdl | import React from 'react';
import Tabs, { Tab } from '../../src/tabs/Tabs';
class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
activeTab: 0
};
this._handleChange = this._handleChange.bind(this);
}
_handleChange(tabId) {
this.setState({
activeTab: tabId
});
}
_getTabContent() {
var list = [];
switch(this.state.activeTab) {
case 1:
list.push('Tywin', 'Cersei', 'Jamie', 'Tyrion');
break;
case 2:
list.push('Viserys', 'Daenerys');
break;
default:
list.push('Eddard', 'Catelyn', 'Robb', 'Sansa', 'Brandon', 'Arya', 'Rickon');
break;
}
return (
<ul>
{list.map(e => <li key={e}>{e}</li>)}
</ul>
);
}
render() {
return (
<div style={{display: 'inline-block', paddingLeft: '30%'}}>
<Tabs activeTab={this.state.activeTab} onChange={this._handleChange}>
<Tab>Starks</Tab>
<Tab>Lannisters</Tab>
<Tab>Targaryens</Tab>
</Tabs>
<section>
{this._getTabContent()}
</section>
</div>
);
}
}
React.render(<Demo />, document.getElementById('app'));
|
js/components/splashscreen/index.js | phamngoclinh/PetOnline_vs2 |
import React, { Component } from 'react';
import { Image } from 'react-native';
const launchscreen = require('../../../images/shadow.png');
export default class SplashPage extends Component {
static propTypes = {
navigator: React.PropTypes.shape({}),
}
componentWillMount() {
const navigator = this.props.navigator;
setTimeout(() => {
navigator.replace({
id: 'login',
});
}, 1500);
}
render() { // eslint-disable-line class-methods-use-this
return (
<Image source={launchscreen} style={{ flex: 1, height: null, width: null }} />
);
}
}
|
assets/js/app.js | Subash/sundar-nepal.subash.me | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import 'whatwg-fetch';
import * as util from './util.js';
import 'babel-polyfill';
import Container from './container';
class App {
constructor() {
this.initializeSDK();
this.userData = {};
this.render();
}
async updateUserData(userData) {
const regenerateImage = userData.userId && this.userData.userId !== userData.userId;
this.userData = { ...this.userData, ...userData };
if (regenerateImage) await this.generateImage();
this.render();
}
async generateImage() {
const imageSize = { width: 800, height: 800 };
const imageUrls = [
`/profile-picture/${this.userData.userId}?rand=${Math.random()}`,
'/img/flag.png'
];
try {
const image = await util.mergeImages(imageUrls, imageSize);
this.updateUserData({ image });
} catch (err) {
alert('Failed to create profile picture. ' + err.message);
}
}
clearUserData() {
this.userData = {};
this.render();
}
render() {
ReactDOM.render(
<Container userData={this.userData} />,
document.getElementById('app')
);
}
showLoading() {
this.updateUserData({ loading: true });
}
hideLoading() {
this.updateUserData({ loading: false });
}
async login() {
try {
this.clearUserData();
this.showLoading();
const userData = await this._login();
await this.updateUserData(userData);
this.hideLoading();
} catch (err) {
this.hideLoading();
alert(err.message);
}
}
_login() {
return new Promise((resolve, reject) => {
FB.getLoginStatus(response => {
if (response.status === 'connected') {
resolve({
userId: response.authResponse.userID,
accessToken: response.authResponse.accessToken
});
} else {
FB.login(response => {
if (response.authResponse) {
resolve({
userId: response.authResponse.userID,
accessToken: response.authResponse.accessToken
});
} else {
reject(new Error('Failed to login with Facebook'));
}
});
}
});
});
}
initializeSDK() {
if (!global.FB) return alert('Failed to load Facebook SDK. Please temporarily disable tracking and ad blockers.');
FB.init({
appId: '519129691585992',
autoLogAppEvents: true,
xfbml: true,
version: 'v2.10'
});
}
static init() {
global.app = new App();
}
}
App.init();
|
node_modules/react-bootstrap/es/NavDropdown.js | chenjic215/search-doctor | import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import Dropdown from './Dropdown';
import splitComponentProps from './utils/splitComponentProps';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = _extends({}, Dropdown.propTypes, {
// Toggle props.
title: PropTypes.node.isRequired,
noCaret: PropTypes.bool,
active: PropTypes.bool,
// Override generated docs from <Dropdown>.
/**
* @private
*/
children: PropTypes.node
});
var NavDropdown = function (_React$Component) {
_inherits(NavDropdown, _React$Component);
function NavDropdown() {
_classCallCheck(this, NavDropdown);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavDropdown.prototype.isActive = function isActive(_ref, activeKey, activeHref) {
var props = _ref.props;
var _this2 = this;
if (props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref) {
return true;
}
if (ValidComponentChildren.some(props.children, function (child) {
return _this2.isActive(child, activeKey, activeHref);
})) {
return true;
}
return props.active;
};
NavDropdown.prototype.render = function render() {
var _this3 = this;
var _props = this.props,
title = _props.title,
activeKey = _props.activeKey,
activeHref = _props.activeHref,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['title', 'activeKey', 'activeHref', 'className', 'style', 'children']);
var active = this.isActive(this, activeKey, activeHref);
delete props.active; // Accessed via this.isActive().
delete props.eventKey; // Accessed via this.isActive().
var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent),
dropdownProps = _splitComponentProps[0],
toggleProps = _splitComponentProps[1];
// Unlike for the other dropdowns, styling needs to go to the `<Dropdown>`
// rather than the `<Dropdown.Toggle>`.
return React.createElement(
Dropdown,
_extends({}, dropdownProps, {
componentClass: 'li',
className: classNames(className, { active: active }),
style: style
}),
React.createElement(
Dropdown.Toggle,
_extends({}, toggleProps, { useAnchor: true }),
title
),
React.createElement(
Dropdown.Menu,
null,
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
active: _this3.isActive(child, activeKey, activeHref)
});
})
)
);
};
return NavDropdown;
}(React.Component);
NavDropdown.propTypes = propTypes;
export default NavDropdown; |
src/app/js/pages/About.js | skratchdot/colorify | import React, { Component } from 'react';
import { Row, Col, Well } from 'react-bootstrap';
import Page from '../Page';
import { main, links } from '../Readme';
class About extends Component {
render() {
return (
<Page pageName="About">
<Row>
<Col md={8}>
<Well dangerouslySetInnerHTML={{ __html: main }} />
</Col>
<Col md={4}>
<Well dangerouslySetInnerHTML={{ __html: links }} />
</Col>
</Row>
</Page>
);
}
}
export default About;
|
pages/index.js | mvasilkov/mvasilkov.ovh | import React from 'react'
import Link from 'next/link'
import Article from '../app/article'
export const pagePath = 'index'
export const pageTitle = 'Start page'
export default class extends React.Component {
constructor(props) {
super(props)
this.state = { email: '' }
}
componentDidMount() {
setTimeout(t => {
if (Date.now() - t > 250) {
const args = 'compmvasilkovpgmail'.split('p').sort()
this.setState({ email: `${args.pop()}@${args.pop()}.${args.pop()}` })
}
}, 256, Date.now())
}
render() {
const { email } = this.state
return (
<Article path={pagePath} title={pageTitle}>
<header>
<h1>Mark Vasilkov</h1>
<p>Computer programmer from Israel</p>
</header>
<p className="short">I work in Python, Django, JavaScript, and React.</p>
{email ?
<p className="short">Write to me: <a href={`mailto:${email}`}>{email}</a></p> :
<p className="short">{'\u200b'}</p>}
<hr />
<p className="short">This is my personal home page.</p>
<p className="short"><Link href="/contents"><a>Contents</a></Link></p>
</Article>
)
}
}
|
app/javascript/mastodon/features/favourites/index.js | mstdn-jp/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import { fetchFavourites } from '../../actions/interactions';
import { ScrollContainer } from 'react-router-scroll-4';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'favourited_by', props.params.statusId]),
});
@connect(mapStateToProps)
export default class Favourites extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
};
componentWillMount () {
this.props.dispatch(fetchFavourites(this.props.params.statusId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchFavourites(nextProps.params.statusId));
}
}
render () {
const { accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='favourites'>
<div className='scrollable'>
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
</div>
</ScrollContainer>
</Column>
);
}
}
|
server/sonar-web/src/main/js/apps/settings/components/inputs/MultiValueInput.js | Builders-SonarSource/sonarqube-bis | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import PrimitiveInput from './PrimitiveInput';
import { getEmptyValue } from '../../utils';
export default class MultiValueInput extends React.Component {
static propTypes = {
setting: React.PropTypes.object.isRequired,
value: React.PropTypes.array,
onChange: React.PropTypes.func.isRequired
};
ensureValue () {
return this.props.value || [];
}
handleSingleInputChange (index, value) {
const newValue = [...this.ensureValue()];
newValue.splice(index, 1, value);
this.props.onChange(newValue);
}
handleDeleteValue (e, index) {
e.preventDefault();
e.target.blur();
const newValue = [...this.ensureValue()];
newValue.splice(index, 1);
this.props.onChange(newValue);
}
prepareSetting () {
const { setting } = this.props;
const newDefinition = { ...setting.definition, multiValues: false };
return {
...setting,
definition: newDefinition,
values: undefined
};
}
renderInput (value, index, isLast) {
return (
<li key={index} className="spacer-bottom">
<PrimitiveInput
setting={this.prepareSetting()}
value={value}
onChange={this.handleSingleInputChange.bind(this, index)}/>
{!isLast && (
<div className="display-inline-block spacer-left">
<button className="js-remove-value button-clean" onClick={e => this.handleDeleteValue(e, index)}>
<i className="icon-delete"/>
</button>
</div>
)}
</li>
);
}
render () {
const displayedValue = [...this.ensureValue(), ...getEmptyValue(this.props.setting.definition)];
return (
<div>
<ul>
{displayedValue.map((value, index) => this.renderInput(value, index, index === displayedValue.length - 1))}
</ul>
</div>
);
}
}
|
src/components/common/svg-icons/navigation/subdirectory-arrow-right.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationSubdirectoryArrowRight = (props) => (
<SvgIcon {...props}>
<path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z"/>
</SvgIcon>
);
NavigationSubdirectoryArrowRight = pure(NavigationSubdirectoryArrowRight);
NavigationSubdirectoryArrowRight.displayName = 'NavigationSubdirectoryArrowRight';
NavigationSubdirectoryArrowRight.muiName = 'SvgIcon';
export default NavigationSubdirectoryArrowRight;
|
js/components/button/rounded.js | YeisonGomez/RNAmanda |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text, H3 } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { actions } from 'react-native-navigation-redux-helpers';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
const {
popRoute,
} = actions;
class Rounded extends Component { // eslint-disable-line
static propTypes = {
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Rounded</Title>
</Body>
<Right />
</Header>
<Content padder style={{ backgroundColor: '#FFF', padding: 20 }}>
<Button rounded light style={styles.mb15}><Text>Light</Text></Button>
<Button rounded info style={styles.mb15}><Text>Info</Text></Button>
<Button rounded danger style={styles.mb15}><Text>Danger</Text></Button>
<Button rounded primary style={styles.mb15}><Text>Primary</Text></Button>
<Button rounded warning style={styles.mb15}><Text>Warning</Text></Button>
<Button rounded success style={styles.mb15}><Text>Success</Text></Button>
<Button rounded dark style={styles.mb15}><Text>Dark</Text></Button>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(Rounded);
|
frontend/src/Settings/MediaManagement/MediaManagement.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import FieldSet from 'Components/FieldSet';
import Form from 'Components/Form/Form';
import FormGroup from 'Components/Form/FormGroup';
import FormInputGroup from 'Components/Form/FormInputGroup';
import FormLabel from 'Components/Form/FormLabel';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import PageContent from 'Components/Page/PageContent';
import PageContentBody from 'Components/Page/PageContentBody';
import { inputTypes, sizes } from 'Helpers/Props';
import SettingsToolbarConnector from 'Settings/SettingsToolbarConnector';
import NamingConnector from './Naming/NamingConnector';
import RootFoldersConnector from './RootFolder/RootFoldersConnector';
const rescanAfterRefreshOptions = [
{ key: 'always', value: 'Always' },
{ key: 'afterManual', value: 'After Manual Refresh' },
{ key: 'never', value: 'Never' }
];
const allowFingerprintingOptions = [
{ key: 'allFiles', value: 'Always' },
{ key: 'newFiles', value: 'For new imports only' },
{ key: 'never', value: 'Never' }
];
const downloadPropersAndRepacksOptions = [
{ key: 'preferAndUpgrade', value: 'Prefer and Upgrade' },
{ key: 'doNotUpgrade', value: 'Do not Upgrade Automatically' },
{ key: 'doNotPrefer', value: 'Do not Prefer' }
];
const fileDateOptions = [
{ key: 'none', value: 'None' },
{ key: 'albumReleaseDate', value: 'Album Release Date' }
];
class MediaManagement extends Component {
//
// Render
render() {
const {
advancedSettings,
isFetching,
error,
settings,
hasSettings,
isWindows,
onInputChange,
onSavePress,
...otherProps
} = this.props;
return (
<PageContent title="Media Management Settings">
<SettingsToolbarConnector
advancedSettings={advancedSettings}
{...otherProps}
onSavePress={onSavePress}
/>
<PageContentBody>
<RootFoldersConnector />
<NamingConnector />
{
isFetching &&
<FieldSet legend="Naming Settings">
<LoadingIndicator />
</FieldSet>
}
{
!isFetching && error &&
<FieldSet legend="Naming Settings">
<div>Unable to load Media Management settings</div>
</FieldSet>
}
{
hasSettings && !isFetching && !error &&
<Form
id="mediaManagementSettings"
{...otherProps}
>
{
advancedSettings &&
<FieldSet legend="Folders">
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Create empty artist folders</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="createEmptyArtistFolders"
helpText="Create missing artist folders during disk scan"
onChange={onInputChange}
{...settings.createEmptyArtistFolders}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Delete empty folders</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="deleteEmptyFolders"
helpText="Delete empty artist and album folders during disk scan and when track files are deleted"
onChange={onInputChange}
{...settings.deleteEmptyFolders}
/>
</FormGroup>
</FieldSet>
}
{
advancedSettings &&
<FieldSet
legend="Importing"
>
{
!isWindows &&
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Skip Free Space Check</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="skipFreeSpaceCheckWhenImporting"
helpText="Use when Lidarr is unable to detect free space from your artist root folder"
onChange={onInputChange}
{...settings.skipFreeSpaceCheckWhenImporting}
/>
</FormGroup>
}
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Minimum Free Space</FormLabel>
<FormInputGroup
type={inputTypes.NUMBER}
unit='MB'
name="minimumFreeSpaceWhenImporting"
helpText="Prevent import if it would leave less than this amount of disk space available"
onChange={onInputChange}
{...settings.minimumFreeSpaceWhenImporting}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Use Hardlinks instead of Copy</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="copyUsingHardlinks"
helpText="Use Hardlinks when trying to copy files from torrents that are still being seeded"
helpTextWarning="Occasionally, file locks may prevent renaming files that are being seeded. You may temporarily disable seeding and use Lidarr's rename function as a work around."
onChange={onInputChange}
{...settings.copyUsingHardlinks}
/>
</FormGroup>
<FormGroup size={sizes.MEDIUM}>
<FormLabel>Import Extra Files</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="importExtraFiles"
helpText="Import matching extra files (subtitles, nfo, etc) after importing an track file"
onChange={onInputChange}
{...settings.importExtraFiles}
/>
</FormGroup>
{
settings.importExtraFiles.value &&
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>Import Extra Files</FormLabel>
<FormInputGroup
type={inputTypes.TEXT}
name="extraFileExtensions"
helpTexts={[
'Comma separated list of extra files to import (.nfo will be imported as .nfo-orig)',
'Examples: ".sub, .nfo" or "sub,nfo"'
]}
onChange={onInputChange}
{...settings.extraFileExtensions}
/>
</FormGroup>
}
</FieldSet>
}
<FieldSet
legend="File Management"
>
<FormGroup size={sizes.MEDIUM}>
<FormLabel>Ignore Deleted Tracks</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="autoUnmonitorPreviouslyDownloadedTracks"
helpText="Tracks deleted from disk are automatically unmonitored in Lidarr"
onChange={onInputChange}
{...settings.autoUnmonitorPreviouslyDownloadedTracks}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Propers and Repacks</FormLabel>
<FormInputGroup
type={inputTypes.SELECT}
name="downloadPropersAndRepacks"
helpTexts={[
'Whether or not to automatically upgrade to Propers/Repacks',
'Use \'Do not Prefer\' to sort by preferred word score over propers/repacks'
]}
helpTextWarning={
settings.downloadPropersAndRepacks.value === 'doNotPrefer' ?
'Use preferred words for automatic upgrades to propers/repacks' :
undefined
}
values={downloadPropersAndRepacksOptions}
onChange={onInputChange}
{...settings.downloadPropersAndRepacks}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Watch Root Folders for file changes</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="watchLibraryForChanges"
helpText="Rescan automatically when files change in a root folder"
onChange={onInputChange}
{...settings.watchLibraryForChanges}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>Rescan Artist Folder after Refresh</FormLabel>
<FormInputGroup
type={inputTypes.SELECT}
name="rescanAfterRefresh"
helpText="Rescan the artist folder after refreshing the artist"
helpTextWarning="Lidarr will not automatically detect changes to files when not set to 'Always'"
values={rescanAfterRefreshOptions}
onChange={onInputChange}
{...settings.rescanAfterRefresh}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>Allow Fingerprinting</FormLabel>
<FormInputGroup
type={inputTypes.SELECT}
name="allowFingerprinting"
helpText="Use fingerprinting to improve accuracy of track matching"
helpTextWarning="This requires Lidarr to read parts of the file which will slow down scans and may cause high disk or network activity."
values={allowFingerprintingOptions}
onChange={onInputChange}
{...settings.allowFingerprinting}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>Change File Date</FormLabel>
<FormInputGroup
type={inputTypes.SELECT}
name="fileDate"
helpText="Change file date on import/rescan"
values={fileDateOptions}
onChange={onInputChange}
{...settings.fileDate}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>Recycling Bin</FormLabel>
<FormInputGroup
type={inputTypes.PATH}
name="recycleBin"
helpText="Track files will go here when deleted instead of being permanently deleted"
onChange={onInputChange}
{...settings.recycleBin}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>Recycling Bin Cleanup</FormLabel>
<FormInputGroup
type={inputTypes.NUMBER}
name="recycleBinCleanupDays"
helpText="Set to 0 to disable automatic cleanup"
helpTextWarning="Files in the recycle bin older than the selected number of days will be cleaned up automatically"
min={0}
onChange={onInputChange}
{...settings.recycleBinCleanupDays}
/>
</FormGroup>
</FieldSet>
{
advancedSettings && !isWindows &&
<FieldSet
legend="Permissions"
>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
size={sizes.MEDIUM}
>
<FormLabel>Set Permissions</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="setPermissionsLinux"
helpText="Should chmod be run when files are imported/renamed?"
helpTextWarning="If you're unsure what these settings do, do not alter them."
onChange={onInputChange}
{...settings.setPermissionsLinux}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>chmod Folder</FormLabel>
<FormInputGroup
type={inputTypes.UMASK}
name="chmodFolder"
helpText="Octal, applied during import/rename to media folders and files (without execute bits)"
helpTextWarning="This only works if the user running Lidarr is the owner of the file. It's better to ensure the download client sets the permissions properly."
onChange={onInputChange}
{...settings.chmodFolder}
/>
</FormGroup>
<FormGroup
advancedSettings={advancedSettings}
isAdvanced={true}
>
<FormLabel>chown Group</FormLabel>
<FormInputGroup
type={inputTypes.TEXT}
name="chownGroup"
helpText="Group name or gid. Use gid for remote file systems."
helpTextWarning="This only works if the user running Lidarr is the owner of the file. It's better to ensure the download client uses the same group as Lidarr."
values={fileDateOptions}
onChange={onInputChange}
{...settings.chownGroup}
/>
</FormGroup>
</FieldSet>
}
</Form>
}
</PageContentBody>
</PageContent>
);
}
}
MediaManagement.propTypes = {
advancedSettings: PropTypes.bool.isRequired,
isFetching: PropTypes.bool.isRequired,
error: PropTypes.object,
settings: PropTypes.object.isRequired,
hasSettings: PropTypes.bool.isRequired,
isWindows: PropTypes.bool.isRequired,
onSavePress: PropTypes.func.isRequired,
onInputChange: PropTypes.func.isRequired
};
export default MediaManagement;
|
src/svg-icons/image/tag-faces.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageTagFaces = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm3.5-9c.83 0 1.5-.67 1.5-1.5S16.33 8 15.5 8 14 8.67 14 9.5s.67 1.5 1.5 1.5zm-7 0c.83 0 1.5-.67 1.5-1.5S9.33 8 8.5 8 7 8.67 7 9.5 7.67 11 8.5 11zm3.5 6.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</SvgIcon>
);
ImageTagFaces = pure(ImageTagFaces);
ImageTagFaces.displayName = 'ImageTagFaces';
ImageTagFaces.muiName = 'SvgIcon';
export default ImageTagFaces;
|
src/containers/Home.js | alcat2008/electron-react-starter | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from '../styles/views/Home.less';
export default class Home extends Component {
render() {
return (
<div>
<div className={styles.container}>
<h2>Home</h2>
<Link to="/counter">to Counter</Link>
</div>
</div>
);
}
}
|
src/routes/ReviewAndSubmit/components/ReviewAndSubmit.js | dannyrdalton/example_signup_flow | import React from 'react'
import { Link } from 'react-router'
import { FORM_FIELDS as PERSONAL_INFORMATION_FORM_FIELDS } from '../../PersonalInformation/config/personal_information_config'
import { FORM_FIELDS as DENTAL_HISTORY_FORM_FIELDS } from '../../DentalHistory/config/dental_history_config'
import { FORM_FIELDS as DENTAL_GOALS_FORM_FIELDS } from '../../DentalGoals/config/dental_goals_config'
import { FORM_FIELDS as SELECT_INSURANCE_FORM_FIELDS } from '../../SelectInsurance/config/select_insurance_config'
export const ReviewAndSubmit = (props) => (
<div>
<h2>Review And Submit</h2>
<div>
<h3>Personal Information</h3>
<div>
{PERSONAL_INFORMATION_FORM_FIELDS.map(field =>
<div className="row" key={field.key}>
<span>{field.label}:</span>
<span>{props.reviewAndSubmit.data.pinfo.data[field.name]}</span>
</div>
)}
</div>
<h3>Profile Picture</h3>
<div>
<img src={props.reviewAndSubmit.data.imageSelect.data.file.preview} alt=""/>
</div>
<h3>Dental History</h3>
<div>
{DENTAL_HISTORY_FORM_FIELDS.map(field =>
<div className="row" key={field.key}>
<span>{field.label}:</span>
<span>{props.reviewAndSubmit.data.dentalHistory.data[field.name]}</span>
</div>
)}
</div>
<div>
<h3>Dental Goals</h3>
{DENTAL_GOALS_FORM_FIELDS.map(field =>
<div className="row" key={field.key}>
<span>{props.reviewAndSubmit.data.dentalGoals.data[field.name].value}</span>
<div><img src={props.reviewAndSubmit.data.dentalGoals.data[field.name].imgSrc} alt=""/></div>
</div>
)}
</div>
<div>
<h3>Select Insurance</h3>
{SELECT_INSURANCE_FORM_FIELDS.map(field =>
<div className="row" key={field.key}>
<span>{props.reviewAndSubmit.data.selectInsurance.data[field.name]}</span>
</div>
)}
</div>
</div>
{'------------------------------------------'}
<div>
<button className="btn btn-default" onClick={props.back}>Back</button>
<button className="btn btn-primary" onClick={props.submitAllUserInfo}>submit</button>
</div>
</div>
)
export default ReviewAndSubmit
|
frontend/src/lib/react-virtualized-sticky-list/index.js | jf248/scrape-the-plate | import React from 'react';
import * as Virtualized from 'react-virtualized';
class StickyList extends React.PureComponent {
static defaultProps = {
itemToGroup: item => item && item['group'],
wrapperStyle: {},
};
getGroupedItems = (items, itemToGroup) => {
let newIndex = 0;
const itemsAndGroups = [];
const groupIndicies = [];
const itemsMap = {};
items.forEach((el, i) => {
if (
itemToGroup(el) &&
itemToGroup(el) !== itemToGroup(items[i - 1] || null)
) {
groupIndicies.push(newIndex);
itemsAndGroups.push(itemToGroup(el));
newIndex++;
}
itemsAndGroups.push(el);
itemsMap[newIndex] = i;
newIndex++;
});
return [itemsAndGroups, groupIndicies, itemsMap];
};
stepFunc = (beg, end) => x => {
if (x < beg) {
return 0;
}
if (x > end) {
return 1;
}
return (x - beg) / (end - beg);
};
getLabelScrollTop = (mainScrollTop, groupIndicies) => {
return (
groupIndicies
.slice(1)
.map(index => this.stepFunc(index, index + 1))
.reduce(
(acc, f) => acc + f(mainScrollTop / this.props.rowHeight + 1),
0
) * this.props.rowHeight
);
};
render() {
const {
height,
itemToGroup,
items,
labelRenderer,
rowHeight,
rowRenderer: rowRendererProp,
width,
wrapperStyle,
...rest
} = this.props;
const [itemsAndGroups, groupIndicies, itemsMap] = this.getGroupedItems(
items,
itemToGroup
);
const rowRenderer = ({ index, ...other }) => {
if (groupIndicies.includes(index)) {
let label = itemsAndGroups[index];
return labelRenderer({ label, ...other });
}
const oldIndex = itemsMap[index];
return rowRendererProp({ index: oldIndex, ...other });
};
// No groups, default to basic `Virtualized.List`
if (groupIndicies.length === 0) {
return (
<Virtualized.List
{...{
...rest,
height,
width,
rowCount: itemsAndGroups.length,
rowHeight,
rowRenderer,
}}
/>
);
}
return (
<Virtualized.ScrollSync>
{({ onScroll, scrollTop }) => (
<div style={{ ...wrapperStyle, position: 'relative', width, height }}>
<Virtualized.List
{...{
style: { position: 'absolute', zIndex: 10, overflow: 'hidden' },
width: width - 17,
height: rowHeight,
scrollTop: this.getLabelScrollTop(scrollTop, groupIndicies),
rowHeight,
rowCount: groupIndicies.length,
rowRenderer: ({ index, ...other }) =>
labelRenderer({
label: itemsAndGroups[groupIndicies[index]],
...other,
}),
}}
/>
<Virtualized.List
{...{
...rest,
height,
width,
rowCount: itemsAndGroups.length,
rowHeight,
rowRenderer,
onScroll,
}}
/>
</div>
)}
</Virtualized.ScrollSync>
);
}
}
export default StickyList;
|
frontend/src/Movie/Index/Posters/MovieIndexPoster.js | geogolem/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import CheckInput from 'Components/Form/CheckInput';
import Icon from 'Components/Icon';
import Label from 'Components/Label';
import IconButton from 'Components/Link/IconButton';
import Link from 'Components/Link/Link';
import SpinnerIconButton from 'Components/Link/SpinnerIconButton';
import Popover from 'Components/Tooltip/Popover';
import { icons } from 'Helpers/Props';
import DeleteMovieModal from 'Movie/Delete/DeleteMovieModal';
import MovieDetailsLinks from 'Movie/Details/MovieDetailsLinks';
import EditMovieModalConnector from 'Movie/Edit/EditMovieModalConnector';
import MovieIndexProgressBar from 'Movie/Index/ProgressBar/MovieIndexProgressBar';
import MoviePoster from 'Movie/MoviePoster';
import getRelativeDate from 'Utilities/Date/getRelativeDate';
import translate from 'Utilities/String/translate';
import MovieIndexPosterInfo from './MovieIndexPosterInfo';
import styles from './MovieIndexPoster.css';
class MovieIndexPoster extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
hasPosterError: false,
isEditMovieModalOpen: false,
isDeleteMovieModalOpen: false
};
}
//
// Listeners
onEditMoviePress = () => {
this.setState({ isEditMovieModalOpen: true });
}
onEditMovieModalClose = () => {
this.setState({ isEditMovieModalOpen: false });
}
onDeleteMoviePress = () => {
this.setState({
isEditMovieModalOpen: false,
isDeleteMovieModalOpen: true
});
}
onDeleteMovieModalClose = () => {
this.setState({ isDeleteMovieModalOpen: false });
}
onPosterLoad = () => {
if (this.state.hasPosterError) {
this.setState({ hasPosterError: false });
}
}
onPosterLoadError = () => {
if (!this.state.hasPosterError) {
this.setState({ hasPosterError: true });
}
}
onChange = ({ value, shiftKey }) => {
const {
id,
onSelectedChange
} = this.props;
onSelectedChange({ id, value, shiftKey });
}
//
// Render
render() {
const {
id,
tmdbId,
imdbId,
youTubeTrailerId,
title,
monitored,
hasFile,
isAvailable,
status,
titleSlug,
images,
posterWidth,
posterHeight,
detailedProgressBar,
showTitle,
showMonitored,
showQualityProfile,
qualityProfile,
showSearchAction,
showRelativeDates,
shortDateFormat,
showReleaseDate,
showCinemaRelease,
inCinemas,
physicalRelease,
digitalRelease,
timeFormat,
isRefreshingMovie,
isSearchingMovie,
onRefreshMoviePress,
onSearchPress,
isMovieEditorActive,
isSelected,
onSelectedChange,
queueStatus,
queueState,
...otherProps
} = this.props;
const {
hasPosterError,
isEditMovieModalOpen,
isDeleteMovieModalOpen
} = this.state;
const link = `/movie/${titleSlug}`;
const elementStyle = {
width: `${posterWidth}px`,
height: `${posterHeight}px`
};
let releaseDate = '';
let releaseDateType = '';
if (physicalRelease && digitalRelease) {
releaseDate = (physicalRelease < digitalRelease) ? physicalRelease : digitalRelease;
releaseDateType = (physicalRelease < digitalRelease) ? 'Released' : 'Digital';
} else if (physicalRelease && !digitalRelease) {
releaseDate = physicalRelease;
releaseDateType = 'Released';
} else if (digitalRelease && !physicalRelease) {
releaseDate = digitalRelease;
releaseDateType = 'Digital';
}
return (
<div className={styles.content}>
<div className={styles.posterContainer}>
{
isMovieEditorActive &&
<div className={styles.editorSelect}>
<CheckInput
className={styles.checkInput}
name={id.toString()}
value={isSelected}
onChange={this.onChange}
/>
</div>
}
<Label className={styles.controls}>
<SpinnerIconButton
className={styles.action}
name={icons.REFRESH}
title={translate('RefreshMovie')}
isSpinning={isRefreshingMovie}
onPress={onRefreshMoviePress}
/>
{
showSearchAction &&
<SpinnerIconButton
className={styles.action}
name={icons.SEARCH}
title={translate('SearchForMovie')}
isSpinning={isSearchingMovie}
onPress={onSearchPress}
/>
}
<IconButton
className={styles.action}
name={icons.EDIT}
title={translate('EditMovie')}
onPress={this.onEditMoviePress}
/>
<span className={styles.externalLinks}>
<Popover
anchor={
<Icon
name={icons.EXTERNAL_LINK}
size={12}
/>
}
title={translate('Links')}
body={
<MovieDetailsLinks
tmdbId={tmdbId}
imdbId={imdbId}
youTubeTrailerId={youTubeTrailerId}
/>
}
/>
</span>
</Label>
{
status === 'ended' &&
<div
className={styles.ended}
title={translate('Ended')}
/>
}
<Link
className={styles.link}
style={elementStyle}
to={link}
>
<MoviePoster
className={styles.poster}
style={elementStyle}
images={images}
size={250}
lazy={false}
overflow={true}
onError={this.onPosterLoadError}
onLoad={this.onPosterLoad}
/>
{
hasPosterError &&
<div className={styles.overlayTitle}>
{title}
</div>
}
</Link>
</div>
<MovieIndexProgressBar
monitored={monitored}
hasFile={hasFile}
status={status}
posterWidth={posterWidth}
detailedProgressBar={detailedProgressBar}
queueStatus={queueStatus}
queueState={queueState}
isAvailable={isAvailable}
/>
{
showTitle &&
<div className={styles.title}>
{title}
</div>
}
{
showMonitored &&
<div className={styles.title}>
{monitored ? translate('Monitored') : translate('Unmonitored')}
</div>
}
{
showQualityProfile &&
<div className={styles.title}>
{qualityProfile.name}
</div>
}
{
showCinemaRelease && inCinemas &&
<div className={styles.title}>
<Icon
name={icons.IN_CINEMAS}
/> {getRelativeDate(
inCinemas,
shortDateFormat,
showRelativeDates,
{
timeFormat,
timeForToday: false
}
)}
</div>
}
{
showReleaseDate && releaseDateType === 'Released' &&
<div className={styles.title}>
<Icon
name={icons.DISC}
/> {getRelativeDate(
releaseDate,
shortDateFormat,
showRelativeDates,
{
timeFormat,
timeForToday: false
}
)}
</div>
}
{
showReleaseDate && releaseDateType === 'Digital' &&
<div className={styles.title}>
<Icon
name={icons.MOVIE_FILE}
/> {getRelativeDate(
releaseDate,
shortDateFormat,
showRelativeDates,
{
timeFormat,
timeForToday: false
}
)}
</div>
}
<MovieIndexPosterInfo
qualityProfile={qualityProfile}
showQualityProfile={showQualityProfile}
showReleaseDate={showReleaseDate}
showRelativeDates={showRelativeDates}
shortDateFormat={shortDateFormat}
timeFormat={timeFormat}
inCinemas={inCinemas}
physicalRelease={physicalRelease}
digitalRelease={digitalRelease}
{...otherProps}
/>
<EditMovieModalConnector
isOpen={isEditMovieModalOpen}
movieId={id}
onModalClose={this.onEditMovieModalClose}
onDeleteMoviePress={this.onDeleteMoviePress}
/>
<DeleteMovieModal
isOpen={isDeleteMovieModalOpen}
movieId={id}
onModalClose={this.onDeleteMovieModalClose}
/>
</div>
);
}
}
MovieIndexPoster.propTypes = {
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
monitored: PropTypes.bool.isRequired,
hasFile: PropTypes.bool.isRequired,
isAvailable: PropTypes.bool.isRequired,
status: PropTypes.string.isRequired,
titleSlug: PropTypes.string.isRequired,
images: PropTypes.arrayOf(PropTypes.object).isRequired,
posterWidth: PropTypes.number.isRequired,
posterHeight: PropTypes.number.isRequired,
detailedProgressBar: PropTypes.bool.isRequired,
showTitle: PropTypes.bool.isRequired,
showMonitored: PropTypes.bool.isRequired,
showQualityProfile: PropTypes.bool.isRequired,
qualityProfile: PropTypes.object.isRequired,
showSearchAction: PropTypes.bool.isRequired,
showRelativeDates: PropTypes.bool.isRequired,
shortDateFormat: PropTypes.string.isRequired,
showCinemaRelease: PropTypes.bool.isRequired,
showReleaseDate: PropTypes.bool.isRequired,
inCinemas: PropTypes.string,
physicalRelease: PropTypes.string,
digitalRelease: PropTypes.string,
timeFormat: PropTypes.string.isRequired,
isRefreshingMovie: PropTypes.bool.isRequired,
isSearchingMovie: PropTypes.bool.isRequired,
onRefreshMoviePress: PropTypes.func.isRequired,
onSearchPress: PropTypes.func.isRequired,
isMovieEditorActive: PropTypes.bool.isRequired,
isSelected: PropTypes.bool,
onSelectedChange: PropTypes.func.isRequired,
tmdbId: PropTypes.number.isRequired,
imdbId: PropTypes.string,
youTubeTrailerId: PropTypes.string,
queueStatus: PropTypes.string,
queueState: PropTypes.string
};
MovieIndexPoster.defaultProps = {
statistics: {
movieFileCount: 0
}
};
export default MovieIndexPoster;
|
books-redux/src/containers/book-list.js | rsancle/udemy-react | import React, { Component } from 'react';
import { connect } from 'react-redux';
import {selectBook} from "../actions/index";
import {bindActionCreators} from 'redux';
/*
* React Component that returns a books html list
*/
class BookList extends Component{
renderlist() {
// For each book
return this.props.books.map( (book) => {
return (
<li
key = {book.title}
onClick = {() => this.props.selectBook(book)}
className = "list-group-item">
{ book.title }
</li>
);
});
}
render() {
return (
<ul className="list-group col-sm-4">
{ this.renderlist() }
</ul>
);
}
}
// populate prop's component
// take the books from the redux and put it in the props
function mapStateToProps(state) {
return {
books : state.books
};
}
// Anything returned from this function will end up as a prop
// on the BookList Container
function mapDispatchToProps(dispatch) {
// Whenever selectBook action is called,the result should be
// past to all our reducers
return bindActionCreators({selectBook: selectBook}, dispatch);
}
//connect our map state with our component
//connect-> function of react-redux lib
// export the container populated
export default connect(mapStateToProps, mapDispatchToProps)(BookList);
|
docs/app/Examples/elements/Segment/Variations/SegmentExampleAttachedComplex.js | clemensw/stardust | import React from 'react'
import { Header, Icon, Message, Segment } from 'semantic-ui-react'
const SegmentExampleAttachedComplex = () => (
<div>
<Header as='h5' attached='top'>
Dogs
</Header>
<Segment attached>
Dogs are one type of animal.
</Segment>
<Header as='h5' attached>
Cats
</Header>
<Segment attached>
Cats are thought of as being related to dogs, but only humans think this.
</Segment>
<Header as='h5' attached>
Lions
</Header>
<Segment attached>
Humans don't think of lions as being like cats, but they are.
</Segment>
<Message warning attached='bottom'>
<Icon name='warning' />
You've reached the end of this content segment!
</Message>
</div>
)
export default SegmentExampleAttachedComplex
|
thingmenn-frontend/src/components/not-found/index.js | baering/thingmenn | import React from 'react'
import './styles.css'
export default class NotFound extends React.Component {
render() {
return (
<div className="not-found">
<h1>404</h1>
<div className="travolta"></div>
</div>
)
}
}
|
demos/function-tree-demos/src/mobx/components/App/index.js | FWeinb/cerebral | import React from 'react'
import run from '../../run'
import './styles.css'
import AddAssignment from '../AddAssignment'
import Assignments from '../Assignments'
import appMounted from '../../events/appMounted'
class App extends React.Component {
componentDidMount () {
run('appMounted', appMounted)
}
render () {
return (
<div className='App'>
<AddAssignment store={this.props.store} />
<Assignments store={this.props.store} />
</div>
)
}
}
export default App
|
client/routes/login/Login.js | ansgmlen/ai-mirror | import React from 'react';
import ReactDOM from 'react-dom';
var classNames = require('classnames');
//var Colours = require('../mixins/Colours');
//var Defaults = require('../mixins/Defaults');
var LoginService = require("../login/LoginService");
var CONFIG = JSON.parse(localStorage.getItem('CONFIG'));
//module.exports = class Login extends Component {
module.exports = React.createClass({
displayName: 'VIEW_Login',
getInitialState: function() {
return {
email: "",
password: "",
user: {}
};
},
componentDidMount: function() {
//initial function here
},
changeEmail: function(e) {
console.log(e.target.value);
this.setState({
email: e.target.value
});
},
changePassword: function(e) {
console.log(e.target.value);
this.setState({
password: e.target.value
});
},
/**
* login
* @param - email{string}, password{string}
*/
login: function(credentials) {
LoginService.login(credentials).then(function(res){
console.log("response: ", res);
//TODO show sweetalert
if(res && res.response){
localStorage.setItem('currentUser', JSON.stringify(res.response.users[0])); //store user info
localStorage.setItem('sessionId', res.meta.session_id);
window.open(CONFIG.currentEnv.endpoint + "home", '_self', false); //open home
}else{
alert(res.meta.message);
}
});
},
render() {
var creds = {
login : this.state.email,
password: this.state.password
}
var componentStyles = {
background: 'none',
border: '1px solid transparent',
//borderRadius: self.ui.borderRadius.base,
cursor: 'pointer',
display: 'inline-block',
fontWeight: 500,
//height: self.ui.component.height,
//lineHeight: self.ui.component.lineHeight,
marginTop: 10,
marginBottom: '0',
overflow: 'hidden',
//padding: '0 ' + self.ui.component.padding,
textAlign: 'center',
touchAction: 'manipulation',
verticalAlign: 'middle',
WebkitAppearance: 'none',
whiteSpace: 'nowrap'
}
/*
let button = null;
if (isLoggedIn) {
button = <LogoutButton onClick={this.handleLogoutClick} />;
} else {
button = <LoginButton onClick={this.handleLoginClick} />;
}
*/
//this.state = {isToggleOn: true};
return ( <div className = "page-container" >
<h1> MBBC CMS Login </h1> <div>
<div>
<input className = "inputField"
type = "email"
placeholder = "Email"
value = {
creds.email
}
onChange = {
this.changeEmail
} /></div>
<div>
<
input className = "inputField"
type = "password"
placeholder = "Password"
value = {
creds.password
}
onChange = {
this.changePassword
} /> < /
div > <
div className = "button"
style = {
componentStyles
}
>
<button type = "button" className="btn btn-primary"
onClick = {
() => this.login(creds)
} > Login < /button> < /
div > <
/div> < /
div >
);
}
});
|
src/shared/components/TestPage.js | dherault/Playlister | import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import config from '../../config';
import ac from '../state/actionCreators';
import definitions from '../models/definitions';
// import xhr from '../utils/xhr';
import customFetch from '../utils/customFetch';
import { capitalizeFirstChar } from '../utils/textUtils';
import { randomInteger, randomString, randomEmail } from '../utils/randomUtils';
const cfc = capitalizeFirstChar;
class TestPage extends React.Component {
constructor() {
super();
this.state = {
recordsOffset: 0,
model: 'user',
id: '',
updateOneKey: '',
updateOneValue: '',
createUserEmail: '',
createUserPassword: '12345678',
createImageSize: 200,
createImageUrl: '',
createImageOriginalUrl: '',
createImageOriginalName: '',
kvsKey: '',
kvsValue: '',
};
}
componentDidMount() {
this.handleCreateUserRandom();
}
handleClear() {
this.setState({ recordsOffset: this.props.records.length });
}
handleModelSelection(e) {
this.setState({ model: e.target.value });
}
handleInput(k, e) {
this.setState({ [k]: e.target.value });
}
// READ ALL
handleReadAllClick() {
this.props.dispatch(ac.readAll({ table: definitions[this.state.model].pluralName }));
}
// READ ONE
handleReadOneClick() {
this.props.dispatch(ac['read' + cfc(this.state.model)]({ id: this.state.id }));
}
// UPDATE ONE
handleUpdateOneClick() {
this.props.dispatch(ac['update' + cfc(this.state.model)]({
id: this.state.id,
[this.state.updateOneKey]: this.state.updateOneValue
}));
}
// DELETE ONE
handleDeleteOneClick() {
this.props.dispatch(ac['delete' + cfc(this.state.model)]({ id: this.state.id }));
}
// CREATE USER
handleCreateUserClick() {
this.props.dispatch(ac.createUser({
email: this.state.createUserEmail,
password: this.state.createUserPassword,
username: this.state.createUserEmail,
}));
}
handleCreateUserRandom() {
this.setState({ createUserEmail: randomEmail() });
}
handleCreateXClick(email) {
this.props.dispatch(ac.createUser({ email, username: email, password: 'password'}));
}
// KVS SERVER
handleCKvsClick(op) {
const url = config.services.kvs.url;
const key = this.state.kvsKey;
const value = this.state.kvsValue;
const store = 'test';
if (op === 'get') {
customFetch(url, { key, store })
.then(r => console.log(r))
.catch(err => console.error(err));
} else if (op === 'set') {
customFetch(url, { key, value, store }, { method: 'put' })
.then(r => console.log(r))
.catch(err => console.error(err));
}
}
// CREATE IMAGE
handleCreateImageClick() {
console.log('Calling image server');
customFetch(config.services.image.url + 'random/' + this.state.createImageSize)
.then(r => this.setState({
createImageUrl: r.url,
createImageOriginalUrl: r.originalUrl,
createImageOriginalName: r.originalName,
}))
.catch(err => console.error(err));
}
render() {
const { state, props } = this;
const m = cfc(state.model);
const wrapperStyle = {
width: '80%',
margin: 'auto',
};
return <div style={wrapperStyle} className="section group">
<div className="col span_6_of_12">
<h1>Test Page</h1>
<div>It's time to manually test stuff!</div>
<div>
<span>Current model: </span>
<select value={state.model} onChange={this.handleModelSelection.bind(this)}>
{
Object.keys(definitions).map(key => <option key={key} value={key}>{ cfc(key) }</option>)
}
</select>
</div>
<section>
<h2>readAll</h2>
<button onClick={this.handleReadAllClick.bind(this)}>readAll</button>
</section>
<section>
<h2>readOne</h2>
<input type="text" value={state.id} onChange={this.handleInput.bind(this, 'id')} placeholder="id"/>
<button onClick={this.handleReadOneClick.bind(this)}>{ 'read' + m }</button>
</section>
<section>
<h2>updateOne</h2>
<input
type="text"
placeholder="id"
value={state.id}
onChange={this.handleInput.bind(this, 'id')} />
<input
type="text"
placeholder="key"
value={state.updateOneKey}
onChange={this.handleInput.bind(this, 'updateOneKey')} />
<input
type="text"
placeholder="value"
value={state.updateOneValue}
onChange={this.handleInput.bind(this, 'updateOneValue')} />
<button onClick={this.handleUpdateOneClick.bind(this)}>{ 'update' + m }</button>
</section>
<section>
<h2>deleteOne</h2>
<input type="text" value={state.id} onChange={this.handleInput.bind(this, 'id')} placeholder="id"/>
<button onClick={this.handleDeleteOneClick.bind(this)}>{ 'delete' + m }</button>
</section>
<section>
<h2>createUser</h2>
<div>
<input type="text" value={state.createUserEmail} onChange={this.handleInput.bind(this, 'createUserEmail')} />
<input type="text" value={state.createUserPassword} onChange={this.handleInput.bind(this, 'createUserPassword')} />
<button onClick={this.handleCreateUserClick.bind(this)}>createUser</button>
<button onClick={this.handleCreateUserRandom.bind(this)}>ʘ</button>
</div>
<div>
<button onClick={this.handleCreateXClick.bind(this, 'admin')}>createAdmin</button>
<button onClick={this.handleCreateXClick.bind(this, '[email protected]')}>createJoe</button>
</div>
</section>
<section>
<h2>Logout</h2>
<button onClick={() => props.dispatch(ac.logout())}>Bye bye!</button>
</section>
<section>
<h2>Failed validation</h2>
<button onClick={() => props.dispatch(ac.readAll({ yolo: true }))}>This should fail on client</button>
<button onClick={() => window.fetch(config.services.api.url + 'readAll?yolo=true')}>This should fail on server</button>
</section>
<section>
<h2>KVS server</h2>
<input
type="text"
placeholder="key"
value={state.kvsKey}
onChange={this.handleInput.bind(this, 'kvsKey')} />
<input
type="text"
placeholder="value"
value={state.kvsValue}
onChange={this.handleInput.bind(this, 'kvsValue')} />
<button onClick={this.handleCKvsClick.bind(this, 'get')}>Get</button>
<button onClick={this.handleCKvsClick.bind(this, 'set')}>Set</button>
</section>
<section>
<h2>createImage</h2>
<div>
<input type="integer" value={state.createImageSize} onChange={this.handleInput.bind(this, 'createImageSize')} />
<button onClick={this.handleCreateImageClick.bind(this)}>createImage</button>
</div>
<img src={state.createImageUrl} style={{borderRadius: state.createImageSize/2}}/>
<span>{ state.createImageOriginalName }</span>
<img src={state.createImageOriginalUrl} />
<div>
</div>
</section>
</div>
<div className="col span_6_of_12">
<div>
<h2 style={{display:'inline-block'}}>Records</h2>
<button onClick={this.handleClear.bind(this)}>Clear</button>
</div>
<ol start={state.recordsOffset}>
{
props.records.map((record, i) => {
if (i < state.recordsOffset) return;
const { type, payload, params } = record;
return <li key={i}>
<strong>{ type }</strong>
- { JSON.stringify(params) }
- { JSON.stringify(payload) }
</li>;
})
}
</ol>
</div>
</div>;
}
}
export default connect(s => ({ records: s.records }))(TestPage);
|
ui-antd/src/routes/error.js | pkaq/Tara | import React from 'react'
import {Icon} from 'antd'
import styles from './error.less'
const Error = () => <div className='content-inner'>
<div className={styles.error}>
<Icon type='frown-o' />
<h1>404 Not Found</h1>
</div>
</div>
export default Error
|
packages/demos/demo/src/components/Project/Select.js | yusufsafak/cerebral | import React from 'react'
import { connect } from 'cerebral/react'
import { props, signal, state } from 'cerebral/tags'
import translations from '../../common/compute/translations'
export default connect(
{
// autoFocus
clients: state`clients.all`,
// field
// placeholderKey
value: state`projects.$draft.${props`field`}`,
valueChanged: signal`projects.formValueChanged`,
t: translations,
},
function Input({
autoFocus,
clients,
field,
placeholder,
value,
valueChanged,
t,
}) {
const onChange = e => {
valueChanged({ key: field, value: e.target.value })
}
const clientsList = Object.keys(clients)
.map(ref => clients[ref])
.sort((a, b) => (a <= b ? -1 : 1))
return (
<select
className="select"
placeholder={t[placeholder]}
onChange={onChange}
value={value || ''}
name={field}
>
{clientsList.map(c => (
<option key={c.key} value={c.key}>
{c.name}
</option>
))}
</select>
)
}
)
|
newclient/scripts/components/user/projects/project-relation-dialog/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 classNames from 'classnames';
import React from 'react';
import {DisclosureActions} from '../../../../actions/disclosure-actions';
import {EntityRelation} from '../../entity-relation';
import {BlueButton} from '../../../blue-button';
import {GreyButton} from '../../../grey-button';
export class ProjectRelationDialog extends React.Component {
constructor() {
super();
this.onNext = this.onNext.bind(this);
this.onPrevious = this.onPrevious.bind(this);
this.findDeclarationTypeByEntity = this.findDeclarationTypeByEntity.bind(this);
this.findCommentByEntity = this.findCommentByEntity.bind(this);
this.setAll = this.setAll.bind(this);
}
shouldComponentUpdate() { return true; }
onNext() {
this.props.onNext(this.props.id, 'PROJECT');
}
onPrevious() {
this.props.onPrevious(this.props.id, 'PROJECT');
}
findDeclarationTypeByEntity(id) {
const declaration = this.props.declarations.find(element => {
return element.finEntityId === id;
});
if (declaration) {
return declaration.typeCd;
}
return null;
}
findCommentByEntity(id) {
const declaration = this.props.declarations.find(element => {
return element.finEntityId === id;
});
if (declaration) {
return declaration.comments;
}
return null;
}
setAll() {
DisclosureActions.setAllForProject(
'PROJECT',
this.props.projectId,
parseInt(this.refs.setAllSelect.value)
);
}
render() {
const entityRelations = [];
this.props.entities
.filter(element => element.active === 1)
.forEach((element) => {
entityRelations.push(
<EntityRelation
entity={element}
relationType="PROJECT"
projectId={this.props.projectId}
typeCd={this.findDeclarationTypeByEntity(element.id)}
comments={this.findCommentByEntity(element.id)}
declarationTypes={this.props.declarationTypes}
key={element.id}
/>
);
});
const declarationTypeOptions = this.props.declarationTypes.map(declarationType => {
return (
<option
key={declarationType.typeCd}
value={declarationType.typeCd}
>
{declarationType.description}
</option>
);
});
const navButtons = [];
if (this.props.projectCount > 0) {
if (this.props.id > 0) {
navButtons.push(
<GreyButton key='previous' onClick={this.onPrevious} className={`${styles.override} ${styles.button}`}>
Previous Project
<i className={'fa fa-caret-up'} style={{marginLeft: 5}} />
</GreyButton>
);
}
if (this.props.id < this.props.projectCount - 1) {
navButtons.push(
<GreyButton key='next' onClick={this.onNext} className={`${styles.override} ${styles.button}`}>
Next Project
<i className={'fa fa-caret-down'} style={{marginLeft: 5}} />
</GreyButton>
);
}
}
const classes = classNames(
styles.container,
this.props.className,
{[styles.multipleProjects]: this.props.projectCount > 1}
);
return (
<div className={classes} >
<div className={styles.content}>
<div className={styles.instructions}>
Indicate how each Financial Entity is related to project
<span style={{marginLeft: 3}}>{this.props.title}</span>:
</div>
<div>
<BlueButton onClick={this.setAll} className={`${styles.override} ${styles.setAllButton}`}>
Set All:
</BlueButton>
to:
<select ref="setAllSelect" style={{marginLeft: 10}}>
{declarationTypeOptions}
</select>
</div>
<div className={styles.headings}>
<span className={styles.heading} style={{width: '25%'}}>FINANCIAL ENTITY</span>
<span className={styles.heading} style={{width: '30%'}}>REPORTER RELATIONSHIP</span>
<span className={styles.heading} style={{width: '45%'}}>REPORTER COMMENTS</span>
</div>
{entityRelations}
</div>
<div className={styles.buttons}>
<div>
{navButtons}
<span className={styles.spacer} />
<GreyButton onClick={this.props.onSave} className={`${styles.override} ${styles.button}`}>
Done
</GreyButton>
</div>
</div>
</div>
);
}
}
|
docs/src/app/components/pages/components/Table/Page.js | verdan/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import tableReadmeText from './README';
import TableExampleSimple from './ExampleSimple';
import tableExampleSimpleCode from '!raw!./ExampleSimple';
import TableExampleComplex from './ExampleComplex';
import tableExampleComplexCode from '!raw!./ExampleComplex';
import tableCode from '!raw!material-ui/Table/Table';
import tableRowCode from '!raw!material-ui/Table/TableRow';
import tableRowColumnCode from '!raw!material-ui/Table/TableRowColumn';
import tableHeaderCode from '!raw!material-ui/Table/TableHeader';
import tableHeaderColumnCode from '!raw!material-ui/Table/TableHeaderColumn';
import tableBodyCode from '!raw!material-ui/Table/TableBody';
import tableFooterCode from '!raw!material-ui/Table/TableFooter';
const descriptions = {
simple: 'A simple table demonstrating the hierarchy of the `Table` component and its sub-components.',
complex: 'A more complex example, allowing the table height to be set, and key boolean properties to be toggled.',
};
const TablePage = () => (
<div>
<Title render={(previousTitle) => `Table - ${previousTitle}`} />
<MarkdownElement text={tableReadmeText} />
<CodeExample
title="Simple example"
description={descriptions.simple}
code={tableExampleSimpleCode}
>
<TableExampleSimple />
</CodeExample>
<CodeExample
title="Complex example"
description={descriptions.complex}
code={tableExampleComplexCode}
>
<TableExampleComplex />
</CodeExample>
<PropTypeDescription code={tableCode} header="### Table Properties" />
<PropTypeDescription code={tableRowCode} header="### TableRow Properties" />
<PropTypeDescription code={tableRowColumnCode} header="### TableRowColumn Properties" />
<PropTypeDescription code={tableHeaderCode} header="### TableHeader Properties" />
<PropTypeDescription code={tableHeaderColumnCode} header="### TableHeaderColumn Properties" />
<PropTypeDescription code={tableBodyCode} header="### TableBody Properties" />
<PropTypeDescription code={tableFooterCode} header="### TableFooter Properties" />
</div>
);
export default TablePage;
|
src/components/video_detail.js | Jaberwalky/ReduxCourse | import React from 'react'
const VideoDetail = ({ video }) => {
if (!video) {
return <div>Loading...</div>
}
const videoID = video.id.videoId
const url = `https://www.youtube.com/embed/${videoID}`
return(
<div className="video-detail col-md-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={url}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
)
}
export default VideoDetail
|
src/components/google_map.js | nike331185/weather | import React, { Component } from 'react';
class GoogleMap extends Component{
componentDidMount(){
new google.maps.Map(this.refs.map,{
zoom: 12, //放大倍數
center:{
lat:this.props.lat, //經緯度
lng:this.props.lon
}
});
}
render() {
//
return <div ref="map" />
}
}
export default GoogleMap;
|
src/server.js | SmartStepGroup/react-starter | import express from 'express'
import browserify from 'browserify'
import React from 'react'
import ReactDOM from 'react-dom/server'
import path from 'path'
import cookieParser from 'cookie-parser'
import bodyParser from 'body-parser'
import passport from './auth/passport'
import { Html } from './components'
import expressGraphQL from 'express-graphql';
import validateFacebookToken from './auth/validateFacebookToken'
import schema from './data/schema'
import fs from 'fs'
const app = express()
app.use(express.static(path.join(__dirname, 'public')))
app.use(cookieParser())
app.use(bodyParser.urlencoded({ extended: true }))
app.use(bodyParser.json())
app.use(passport.initialize())
browserify(path.join(__dirname + '/client.js'), {
debug: true
})
.transform("babelify")
.bundle()
.pipe(fs.createWriteStream(path.join(__dirname + '/bundle.js')));
app.use('/bundle.js', (req, res) => {
res.setHeader('content-type', 'application/javascript')
res.sendFile(path.join(__dirname + '/bundle.js'));
})
app.get('/authenticate', passport.authenticate('facebook', { scope: ['email'], session: false }))
app.get('/authenticate/return', passport.authenticate('facebook', { session: false }), (req, res) => {
const expiresIn = 60 * 60 * 24 * 180; // 180 days
res.cookie('id_token', req.user.token, { maxAge: 1000 * expiresIn, httpOnly: true });
res.redirect('/secured');
})
app.get('/isAuthenticated', (req, res) => {
var token = req.cookies.id_token
validateFacebookToken(token, function(isValid) {
if (isValid) return res.sendStatus(200)
return res.sendStatus(401)
})
})
app.use('/graphql', expressGraphQL(req => ({
schema,
graphiql: true,
rootValue: { request: req },
pretty: process.env.NODE_ENV !== 'production',
})));
app.use('/', (req, res) => {
res.setHeader('Content-Type', 'text/html')
const html = ReactDOM.renderToStaticMarkup(<Html title="SSG React starter kit"></Html>)
res.end(`<!doctype html>${html}`)
})
var server = app.listen(3000, function() {
var addr = server.address()
console.log('Listening @ http://%s:%d', addr.address, addr.port)
})
|
src/containers/LoginRegister/LoginForm.js | anitrack/anitrack-web | import React, { Component } from 'react';
import { Button, Card, Form, FormGroup, Input } from 'reactstrap';
import { login, getMyUserData } from 'actions/user';
import StatusAlert from 'components/StatusAlert';
import * as css from './css';
import { isValidEmail } from 'helper';
class LoginForm extends Component {
constructor(props){
super(props);
this.state = {email: "", password: ""};
}
login(e){
e.preventDefault();
this.alert.getWrappedInstance().reset();
if(this.state.email === ""){
this.alert.getWrappedInstance().err("Email cannot be empty");
return;
}else if(!isValidEmail(this.state.email)){
this.alert.getWrappedInstance().err("Invalid email");
return;
}else if(this.state.password === ""){
this.alert.getWrappedInstance().err("Password cannot be empty");
return;
}
login({email: this.state.email, password: this.state.password}).then((res) => {
if(res.status === "success"){
this.onSuccess();
}else{
this.alert.getWrappedInstance().err(res.error);
}
})
}
onSuccess(){
getMyUserData();
window.location.replace('/');
}
render() {
return (
<Card style={css.card}>
<h3 style={css.loginTitle}>AniTrack</h3>
<StatusAlert ref={(a) => {this.alert = a}} />
<Form onSubmit={(e) => {this.login(e)}}>
<FormGroup>
<Input style={css.inputBox} type="email" placeholder="Email" value={this.state.email} onChange={(e) => {this.setState({email: e.target.value});}}/>
</FormGroup>
<FormGroup>
<Input style={css.inputBox} type="password" placeholder="Password" value={this.state.password} onChange={(e) => {this.setState({password: e.target.value});}}/>
</FormGroup>
<Button type="submit" style={css.loginButton}>Login</Button>{' '}
</Form>
</Card>
);
}
}
export default LoginForm;
|
backend/src/main/js/watcher/watcher.js | joostvdg/keep-watching | /*jshint esversion: 6 */
import React from 'react';
import Panel from 'react-bootstrap/lib/Panel';
import Table from 'react-bootstrap/lib/Table';
const rest = require('rest');
const mime = require('rest/interceptor/mime');
export class ShowWatcher extends React.Component {
constructor(props) {
super(props);
this.state = {
name: '',
id: ''
};
}
componentDidMount() {
let client = rest.wrap(mime);
client({ path: '/user',
headers: {'Accept': 'application/json'}}).then(response => {
this.setState({name: response.entity.name});
this.setState({id: response.entity.principle});
});
}
render() {
const title = (
<h3>Profile</h3>
);
return (
<div>
<Panel header={title} bsStyle="primary">
<Table responsive>
<thead >
<tr>
<th>Name</th>
<th>Identifier</th>
</tr>
</thead>
<tbody>
<td>{this.state.name}</td>
<td>{this.state.id}</td>
</tbody>
</Table>
</Panel>
</div>
);
}
} |
examples/official-storybook/stories/demo/welcome.stories.js | storybooks/react-storybook | import React from 'react';
import { linkTo } from '@storybook/addon-links';
import { Welcome } from '@storybook/react/demo';
export default {
title: 'Other/Demo/Welcome',
component: Welcome,
};
// Some other valid values:
// - 'other-demo-buttonmdx--with-text'
// - 'Other/Demo/ButtonMdx'
export const ToStorybook = () => <Welcome showApp={linkTo('Other/Demo/Button')} />;
ToStorybook.story = {
name: 'to Storybook',
};
|
packages/fyndiq-ui-test/stories/component-productcard.js | fyndiq/fyndiq-ui | import React from 'react'
import { storiesOf } from '@storybook/react'
import Productcard from 'fyndiq-component-productcard'
storiesOf('Product card', module)
.addDecorator(story => (
<div style={{ backgroundColor: '#c4e5e9', padding: '1em' }}>{story()}</div>
))
.addWithInfo('default', () => (
<Productcard
title="Vita Konstläder Sneakers - Ombloggade Street skor"
price="149 kr"
url="https://cdn.fyndiq.se/product/d1/de/26/2a08917d54bf6726e70441b86d86400d9e/original.png"
/>
))
.addWithInfo('with old price', () => (
<Productcard
title="Wheeler Taklampa Koppar"
price="599 kr"
oldprice="1390 kr"
url="https://cdn.fyndiq.se/product/e8/74/3c/a1a451ba9af03f19e6bdd54890bd05b6ec/original.png"
/>
))
.addWithInfo('with rating', () => (
<Productcard
title="Spirelli-Spagettiskärare för rawfood"
price="199 kr"
oldprice="399 kr"
url="https://cdn.fyndiq.se/product/f7/e7/ea/15f91dc30f5b264568c551a9842863d0c9/original.png"
rating={4.4}
/>
))
|
blocks/panel.js | UXtemple/panels | import React from 'react'
import Vertical from './vertical.js'
export default class Panel extends React.Component {
render() {
const { props } = this
return (
<Vertical
aria-labelledby={props['aria-labelledby']}
role={props.role}
ref={props._ref}
style={{
height: '100%',
overflowY: 'auto',
...props.style,
}}
>
{props.children}
</Vertical>
)
}
}
|
src/screens/App/screens/Home/components/Search/index.js | tulsajs/redux-workshop | import React, { Component } from 'react';
import debounce from 'lodash.debounce';
import { Input, Box } from 'BuildingBlocks';
export default class index extends Component {
setupEvent = event => {
event.persist();
this.handleChange(event);
};
handleChange = debounce(event => {
const value = event.target.value === '' ? null : event.target.value;
this.props.updateSearch(value);
}, 500);
render() {
return (
<Box width={[1, 1 / 2]} py={3}>
<Input
p={2}
fontSize={3}
width={1}
type="text"
placeholder="Search Movies"
onChange={this.setupEvent}
/>
</Box>
);
}
}
|
src/components/Footer/index.js | lukekarrys/repeatone.club | 'use strict';
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import CSSModules from 'react-css-modules';
import Icon from '../Icon';
@CSSModules(require('./style.less'))
export default class Footer extends Component {
render() {
return (
<footer styleName="root">
<Link to="/">
<Icon name="home">Home</Icon>
</Link>
<a href="https://github.com/lukekarrys/repeatone">
<Icon name="github">GitHub</Icon>
</a>
</footer>
);
}
}
|
public/app/components/vpanel-project-tab/properties-project.js | vincent-tr/mylife-home-studio | 'use strict';
import React from 'react';
import icons from '../icons';
import PropertiesLabel from '../properties/properties-label';
import PropertiesTitle from '../properties/properties-title';
import PropertiesValue from '../properties/properties-value';
import PropertiesEditor from '../properties/properties-editor';
const PropertiesProject = ({ project, onChangeName }) => (
<div>
<PropertiesTitle icon={<icons.tabs.VPanel/>} text={'Project'} />
{/* details */}
<table>
<tbody>
<tr>
<td><PropertiesLabel text={'Name'}/></td>
<td><PropertiesEditor id={`${project.uid}_name`} value={project.name} onChange={onChangeName} type={'s'} /></td>
</tr>
<tr>
<td><PropertiesLabel text={'Creation'}/></td>
<td><PropertiesValue value={project.creationDate.toISOString()}/></td>
</tr>
<tr>
<td><PropertiesLabel text={'Last update'}/></td>
<td><PropertiesValue value={project.lastUpdate.toISOString()}/></td>
</tr>
</tbody>
</table>
</div>
);
PropertiesProject.propTypes = {
project : React.PropTypes.object.isRequired,
onChangeName : React.PropTypes.func.isRequired
};
export default PropertiesProject;
|
src/js/views/Modals/HotkeysInfo.js | jaedb/Iris | import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Modal from './Modal';
import * as uiActions from '../../services/ui/actions';
import { I18n, i18n } from '../../locale';
const hotkeys = [
{ label: 'info', keysets: [['i']] },
{ label: 'play_pause', keysets: [['p'], ['spacebar']] },
{ label: 'stop', keysets: [['s']] },
{ label: 'rewind', keysets: [['r']] },
{ label: 'fastforward', keysets: [['f']] },
{ label: 'next', keysets: [['.'], ['>']] },
{ label: 'previous', keysets: [[','], ['<']] },
{ label: 'volume_up', keysets: [['=']] },
{ label: 'volume_down', keysets: [['-']] },
{ label: 'mute', keysets: [['0']] },
{ label: 'snapcast_volume_up', keysets: [['n', '=']] },
{ label: 'snapcast_volume_down', keysets: [['n', '=']] },
{ label: 'snapcast_mute', keysets: [['n', '0']] },
{ label: 'exit', keysets: [['esc']] },
];
class HotkeysInfo extends React.Component {
componentDidMount() {
const { uiActions: { setWindowTitle } } = this.props;
setWindowTitle('Hotkeys');
}
render = () => (
<Modal className="modal--hotkeys-info">
<h1><I18n path="modal.hotkeys_info.title" /></h1>
<div className="list small playlists">
{hotkeys.map((hotkey) => (
<div className="list__item list__item--no-interaction" key={hotkey.label}>
{hotkey.keysets.map((keyset, keysetIndex) => (
<>
{keyset.map((key, keyIndex) => (
<>
<pre>
{key}
</pre>
{keyIndex === 0 && keyset.length > 1 && ' + '}
</>
))}
{keysetIndex === 0 && hotkey.keysets.length > 1 && ' or '}
</>
))}
<span className="description">
{i18n(`modal.hotkeys_info.keys.${hotkey.label}`)}
</span>
</div>
))}
</div>
</Modal>
)
}
const mapStateToProps = () => ({});
const mapDispatchToProps = (dispatch) => ({
uiActions: bindActionCreators(uiActions, dispatch),
});
export default connect(mapStateToProps, mapDispatchToProps)(HotkeysInfo);
|
app/components/Counter.js | pavelkomiagin/npmr | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Counter.css';
class Counter extends Component {
props: {
increment: () => void,
incrementIfOdd: () => void,
incrementAsync: () => void,
decrement: () => void,
counter: number
};
render() {
const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;
return (
<div>
<div className={styles.backButton}>
<Link to="/">
<i className="fa fa-arrow-left fa-3x" />
</Link>
</div>
<div className={`counter ${styles.counter}`}>
{counter}
</div>
<div className={styles.btnGroup}>
<button className={styles.btn} onClick={increment}>
<i className="fa fa-plus" />
</button>
<button className={styles.btn} onClick={decrement}>
<i className="fa fa-minus" />
</button>
<button className={styles.btn} onClick={incrementIfOdd}>odd</button>
<button className={styles.btn} onClick={() => incrementAsync()}>async</button>
</div>
</div>
);
}
}
export default Counter;
|
frontend/src/Components/Form/Form.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React from 'react';
import Alert from 'Components/Alert';
import { kinds } from 'Helpers/Props';
import styles from './Form.css';
function Form({ children, validationErrors, validationWarnings, ...otherProps }) {
return (
<div>
{
validationErrors.length || validationWarnings.length ?
<div className={styles.validationFailures}>
{
validationErrors.map((error, index) => {
return (
<Alert
key={index}
kind={kinds.DANGER}
>
{error.errorMessage}
</Alert>
);
})
}
{
validationWarnings.map((warning, index) => {
return (
<Alert
key={index}
kind={kinds.WARNING}
>
{warning.errorMessage}
</Alert>
);
})
}
</div> :
null
}
{children}
</div>
);
}
Form.propTypes = {
children: PropTypes.node.isRequired,
validationErrors: PropTypes.arrayOf(PropTypes.object).isRequired,
validationWarnings: PropTypes.arrayOf(PropTypes.object).isRequired
};
Form.defaultProps = {
validationErrors: [],
validationWarnings: []
};
export default Form;
|
src/components/Auth/index.js | galsen0/hair-dv-front | /**
* Created by diop on 07/05/2017.
*/
import React from 'react';
import LoginFormComponent from './LoginForm';
import SignUpFormComponent from './SignUpForm';
import { Divider, Grid } from 'semantic-ui-react';
class Auth extends React.Component{
render(){
return(
<Grid columns="equal" centered>
<Grid.Row></Grid.Row>
<Grid.Row></Grid.Row>
<Grid.Row>
<Grid.Column width={12} textAlign={"center"}>
<LoginFormComponent/>
<Divider horizontal>Ou</Divider>
<SignUpFormComponent/>
</Grid.Column>
</Grid.Row>
<Grid.Row></Grid.Row>
</Grid>
);
}
}
export default Auth; |
src/routes.js | MoonTahoe/ski-day-counter-redux | import React from 'react'
import { Router, Route, IndexRoute, hashHistory } from 'react-router'
import { App, Whoops404 } from './components'
import SkiDayCount from './components/containers/SkiDayCount'
import AddDayForm from './components/containers/AddDayForm'
import SkiDayList from './components/containers/SkiDayList'
const routes = (
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={SkiDayCount}/>
<Route path="add-day" component={AddDayForm}/>
<Route path="list-days" component={SkiDayList}>
<Route path=":filter" component={SkiDayList}/>
</Route>
<Route path="*" component={Whoops404}/>
</Route>
</Router>
)
export default routes |
storybooks/web/stories/carousels/carousel-2.js | opensource-cards/binary-ui | import ActionIcon from 'binary-ui-components/mobile/ActionIcon';
import IconArrowLeft from 'binary-ui-icons/binary/ArrowLeft';
import IconArrowRight from 'binary-ui-icons/binary/ArrowRight';
import React from 'react';
import BinaryUICarousel from 'binary-ui-carousel';
const colors = ['#AA3939', '#AA6C39'];
function getStyle(color) {
return {
width: '100%',
height: '100%',
backgroundColor: color,
};
}
export default class Example extends React.Component {
constructor(props) {
super(props);
this.state = {
selectedIndex: 0,
};
}
render() {
return (
<BinaryUICarousel
containerHeight={200}
containerWidth={300}
selectedIndex={this.state.selectedIndex}
onChangeIndex={(page) => { this.setState({ selectedIndex: page }); }}
renderButtonLeft={props => (
<ActionIcon title="Left" renderIcon={rest => (<IconArrowLeft {...rest} size={18} />)} {...props} />
)}
renderButtonRight={props => (
<ActionIcon title="Left" renderIcon={rest => (<IconArrowRight {...rest} size={18} />)} {...props} />
)}
>
{colors.map((color, index) => (
<div key={color} style={getStyle(color)}>{index}</div>
))}
</BinaryUICarousel>
);
}
}
|
src/components/DeveloperMenu.android.js | fabriziomoscon/pepperoni-app-kit | import React from 'react';
import * as snapshot from '../utils/snapshot';
import {
View,
Text,
TouchableOpacity,
StyleSheet
} from 'react-native';
/**
* Simple developer menu, which allows e.g. to clear the app state.
* It can be accessed through a tiny button in the bottom right corner of the screen.
* ONLY FOR DEVELOPMENT MODE!
*/
const DeveloperMenu = React.createClass({
displayName: 'DeveloperMenu',
getInitialState() {
return {visible: false};
},
showDeveloperMenu() {
this.setState({isVisible: true});
},
async clearState() {
await snapshot.clearSnapshot();
console.warn('(╯°□°)╯︵ ┻━┻ \nState cleared, Cmd+R to reload the application now');
this.closeMenu();
},
closeMenu() {
this.setState({isVisible: false});
},
renderMenuItem(text, onPress) {
return (
<TouchableOpacity
key={text}
onPress={onPress}
style={styles.menuItem}
>
<Text style={styles.menuItemText}>{text}</Text>
</TouchableOpacity>
);
},
render() {
if (!__DEV__) {
return null;
}
if (!this.state.isVisible) {
return (
<TouchableOpacity
style={styles.circle}
onPress={this.showDeveloperMenu}
/>
);
}
const buttons = [
this.renderMenuItem('Clear state', this.clearState),
this.renderMenuItem('Cancel', this.closeMenu)
];
return (
<View style={styles.menu}>
{buttons}
</View>
);
}
});
const styles = StyleSheet.create({
circle: {
position: 'absolute',
bottom: 5,
right: 5,
width: 10,
height: 10,
borderRadius: 5,
backgroundColor: '#fff'
},
menu: {
backgroundColor: 'white',
position: 'absolute',
left: 0,
right: 0,
bottom: 0
},
menuItem: {
flex: 1,
flexDirection: 'row',
alignItems: 'center',
borderTopWidth: 1,
borderTopColor: '#eee',
padding: 10,
height: 60
},
menuItemText: {
fontSize: 20
}
});
export default DeveloperMenu;
|
examples/FlatButton.js | 15lyfromsaturn/react-materialize | import React from 'react';
import Button from '../src/Button';
export default
<Button flat waves='light'>Button</Button>;
|
example/src/screens/types/TopTabs.js | junedomingo/react-native-navigation | import React from 'react';
import {PixelRatio} from 'react-native';
class TopTabs extends React.Component {
static navigatorStyle = {
topTabTextColor: '#ffffff',
selectedTopTabTextColor: '#ff505c',
// Icons
topTabIconColor: '#ffffff',
selectedTopTabIconColor: '#ff505c',
// Tab indicator
selectedTopTabIndicatorHeight: PixelRatio.get() * 2,
selectedTopTabIndicatorColor: '#ff505c',
};
}
export default TopTabs;
|
src/templates/page.js | zccz14/blog | import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import SEO from '../components/seo'
import Layout from '../components/layout'
import Post from '../components/post'
const BlogPostTemplate = ({ data, pageContext }) => {
const {
frontmatter: { title, date, path, author, coverImage, excerpt, tags },
excerpt: autoExcerpt,
id,
html,
} = data.markdownRemark
const { next, previous } = pageContext
return (
<Layout>
<SEO title={title} description={excerpt || autoExcerpt} />
<Post
key={id}
title={title}
date={date}
path={path}
author={author}
coverImage={coverImage}
html={html}
tags={tags}
previousPost={previous}
nextPost={next}
/>
</Layout>
)
}
export default BlogPostTemplate
BlogPostTemplate.propTypes = {
data: PropTypes.object.isRequired,
pageContext: PropTypes.shape({
next: PropTypes.object,
previous: PropTypes.object,
}),
}
export const pageQuery = graphql`
query($path: String) {
markdownRemark(frontmatter: { path: { eq: $path } }) {
frontmatter {
title
date(formatString: "DD MMMM YYYY")
path
author
excerpt
tags
coverImage {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFluid
}
}
}
}
id
html
excerpt
}
}
`
|
src/@ui/BulletListItem/index.js | NewSpring/Apollos | import React from 'react';
import { compose, pure, setPropTypes } from 'recompose';
import PropTypes from 'prop-types';
import { View } from 'react-native';
import styled from '@ui/styled';
import { BodyText } from '@ui/typography';
const enhance = compose(
pure,
setPropTypes({
children: PropTypes.oneOfType([
/*
* There is no way to type check against known text nodes but expect problems if you try to
* pass something other than a string or text elements (this includes children of children).
*/
PropTypes.string,
PropTypes.node,
]),
}),
);
const Wrapper = styled({
flexDirection: 'row',
})(View);
const Bullet = styled(({ theme }) => ({
// Set in a typographic unit to reflect changes in the default type size.
paddingRight: theme.helpers.rem(1) / 2,
}))(View);
const IosTextWrapFix = styled({ // 😢
flexShrink: 1,
})(View);
const BulletListItem = enhance(({
children,
}) => (
<Wrapper>
<Bullet>
<BodyText>•</BodyText>
</Bullet>
<IosTextWrapFix>
{typeof children === 'string' ? <BodyText>{children}</BodyText> : children}
</IosTextWrapFix>
</Wrapper>
));
export default BulletListItem;
|
src/app/components/Header.js | skratchdot/js-playground | import React, { Component } from 'react';
import { Link } from 'react-router';
import { Row, Col, Nav } from 'react-bootstrap';
import { connect } from 'react-redux';
const packageInfo = require('../../../package.json');
class Header extends Component {
isLinkActive(pathname) {
return this.context.history.isActive(pathname) ? 'active' : '';
}
render() {
return (
<header>
<Row className="header">
<Col md={6}>
<Link to={`/${packageInfo.name}`}>
<h1 className="title">
js-playground
<small>version {packageInfo.version}</small>
</h1>
</Link>
</Col>
<Col md={6}>
<Nav bsStyle="pills">
<li key="home" className={
this.isLinkActive(`/${packageInfo.name}`) +
this.isLinkActive(`/${packageInfo.name}/home`)}>
<Link to={`/${packageInfo.name}`}>Home</Link>
</li>
<li key="about" className={this.isLinkActive(`/${packageInfo.name}/about`)}>
<Link to={`/${packageInfo.name}/about`}>About</Link>
</li>
</Nav>
</Col>
</Row>
<Row>
<Col md={12}><div className="main-seperator"></div></Col>
</Row>
</header>
);
}
}
Header.contextTypes = {
history: React.PropTypes.object
};
export default connect()(Header);
|
src/index.js | dtying/gallery-by-react | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/routes/about/index.js | zmj1316/InfomationVisualizationCourseWork | /**
* 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 Layout from '../../components/Layout';
import Page from '../../components/Page';
export default {
path: '/about',
async action() {
const data = await new Promise((resolve) => {
require.ensure([], require => {
resolve(require('./about.md'));
}, 'about');
});
return {
title: data.title,
component: <Layout><Page {...data} /></Layout>,
};
},
};
|
client/components/Markdown/elements/_th.js | LetAmericaVote/strikeout | import React from 'react';
const th = (props) => {
const { children } = props;
return (
<th>{ children }</th>
);
};
export default th;
|
docs/src/pages/docs/index.js | mcanthony/nuclear-js | import React from 'react'
import Redirect from '../../layouts/redirect'
import { BASE_URL } from '../../globals'
export default React.createClass({
render() {
return <Redirect to={BASE_URL} />
}
})
|
website/src/pages/components/home/Footer.js | frontyard/keystone | import React, { Component } from 'react';
import Container from '../../../../components/Container';
import { compose } from 'glamor';
import Link from 'gatsby-link';
import theme from '../../../../theme';
export default class ValueProps extends Component {
render () {
return (
<div className={compose(styles.background)}>
<Container>
<p>Created by <a href="http://twitter.com/jedwatson" className={compose(styles.list_links_anchor)}>@jedwatson</a>, <a href="http://twitter.com/bladey" className={compose(styles.list_links_anchor)}>@bladey</a> and <a href="http://twitter.com/jossmackison" className={compose(styles.list_links_anchor)}>@jossmackison</a> at <a href="http://www.thinkmill.com.au/" className={compose(styles.list_links_anchor)}>Thinkmill</a>, and other <a href="https://github.com/keystonejs/keystone/contributors" className={compose(styles.list_links_anchor)}>contributors</a> under the <a href="http://opensource.org/licenses/MIT" className={compose(styles.list_links_anchor)}>MIT License</a></p>
<ul className={compose(styles.list_links)}>
<li className={compose(styles.list_links_item)}><Link to="/getting-started" className={compose(styles.list_links_anchor)}>Getting Started</Link></li>
<li className={compose(styles.list_links_item)}><Link to="/documentation" className={compose(styles.list_links_anchor)}>Documentation</Link></li>
<li className={compose(styles.list_links_item)}><a className={compose(styles.list_links_anchor)} href="https://github.com/keystonejs/keystone">Github Project</a></li>
<li className={compose(styles.list_links_item)}><a className={compose(styles.list_links_anchor)} href="https://groups.google.com/forum/#!forum/keystonejs">Google Group</a></li>
<li className={compose(styles.list_links_item)}><a className={compose(styles.list_links_anchor)} href="http://demo.keystonejs.com/">Demo Website</a></li>
</ul>
</Container>
</div>
);
}
};
const styles = {
list_links: {
listStyle: 'none',
marginLeft: '0',
marginBottom: '0',
},
list_links_item: {
display: 'inline-block',
paddingLeft: '0.625rem',
paddingRight: '0.625rem',
},
list_links_anchor: {
textDecoration: 'none',
color: '#00263e',
':hover': {
textDecoration: 'underline',
},
},
background: {
backgroundColor: theme.color.gray05,
paddingTop: '3rem',
paddingBottom: '3rem',
width: '100%',
textAlign: 'center',
color: theme.color.gray50,
fontSize: '0.9rem',
},
};
|
examples/todomvc/containers/App.js | mrblueblue/redux | import React, { Component } from 'react';
import TodoApp from './TodoApp';
import { createRedux } from 'redux';
import { Provider } from 'redux/react';
import * as stores from '../stores';
const redux = createRedux(stores);
export default class App extends Component {
render() {
return (
<Provider redux={redux}>
{() => <TodoApp />}
</Provider>
);
}
}
|
src/client/lib/flux/devtools.js | gaurav-/este | import Component from '../../components/component.react';
import React from 'react';
export default function devTools(BaseComponent) {
return class DevTools extends Component {
static propTypes = {
flux: React.PropTypes.object.isRequired
}
constructor(props) {
super(props);
this.history = [this.props.flux.state];
this.onDocumentKeyPress = ::this.onDocumentKeyPress;
this.onFluxDispatch = ::this.onFluxDispatch;
this.onFluxRender = ::this.onFluxRender;
}
componentWillMount() {
document.addEventListener('keypress', this.onDocumentKeyPress);
this.props.flux.on('dispatch', this.onFluxDispatch);
this.props.flux.on('render', this.onFluxRender);
}
componentWillUnmount() {
document.removeEventListener('keypress', this.onDocumentKeyPress);
this.props.flux.removeListener('dispatch', this.onFluxDispatch);
this.props.flux.removeListener('render', this.onFluxRender);
}
onDocumentKeyPress({ctrlKey, shiftKey, keyCode}) {
if (!ctrlKey || !shiftKey) return;
switch (keyCode) {
case 12: this.loadStateFromPrompt(); break; // eslint-disable-line no-undef
case 19: this.saveStateToConsole(); break; // eslint-disable-line no-undef
}
}
onFluxDispatch(state, action, payload, meta) {
// TODO: Store only several last states on production.
// if (process.env.NODE_ENV === 'production') ...
this.history.push({state, action, payload, meta});
this.logDispatch();
}
onFluxRender(total) {
this.log(total);
}
logDispatch() {
const last = this.history[this.history.length - 1];
const {action, meta} = last;
const feature = meta && meta.feature;
const actionName = action && action.name;
this.log(feature + '/' + actionName);
}
// ctrl+shift+l
loadStateFromPrompt() {
const stateStr = window.prompt('Paste the serialized state into the input.'); // eslint-disable-line no-alert
if (!stateStr) return;
const newState = JSON.parse(stateStr);
this.props.flux.load(newState);
this.log('App state loaded');
}
// ctrl+shift+s
saveStateToConsole() {
const appStateJson = this.props.flux.state.toJS();
window._savedAppState = JSON.stringify(appStateJson);
this.log('App state saved. Copy to clipboard: copy(_savedAppState)'); // eslint-disable-line no-console
this.log(appStateJson); // eslint-disable-line no-console
}
log(msg) {
// TODO: Add UI toggle, consider move logging to dev tools UI.
console.log('[este]', msg); // eslint-disable-line no-console
}
render() {
return <BaseComponent {...this.props} />;
}
};
}
|
webpack/scenes/Subscriptions/Details/SubscriptionDetailProducts.js | jlsherrill/katello | import React from 'react';
import PropTypes from 'prop-types';
const SubscriptionDetailProducts = ({ subscriptionDetails }) => (
<div>
<h2>{__('Provided Products')}</h2>
<ul>
{subscriptionDetails.provided_products &&
subscriptionDetails.provided_products.map(prod => (
<li key={prod.id}>{prod.name}</li>
))}
</ul>
</div>
);
SubscriptionDetailProducts.propTypes = {
subscriptionDetails: PropTypes.shape({}).isRequired,
};
export default SubscriptionDetailProducts;
|
analysis/deathknightblood/src/modules/features/BoneShield.js | yajinni/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import { formatDuration, formatPercentage } from 'common/format';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import { t } from '@lingui/macro';
import StatTracker from 'parser/shared/modules/StatTracker';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import UptimeIcon from 'interface/icons/Uptime';
import Statistic from 'parser/ui/Statistic';
import BoneShieldTimesByStacks from './BoneShieldTimesByStacks';
class BoneShield extends Analyzer {
static dependencies = {
statTracker: StatTracker,
boneShieldTimesByStacks: BoneShieldTimesByStacks,
};
get boneShieldTimesByStack() {
return this.boneShieldTimesByStacks.boneShieldTimesByStacks;
}
get uptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.BONE_SHIELD.id) / this.owner.fightDuration;
}
get uptimeSuggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.95,
average: 0.9,
major: .8,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.uptimeSuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => suggest('Your Bone Shield uptime can be improved. Try to keep it up at all times.')
.icon(SPELLS.BONE_SHIELD.icon)
.actual(t({
id: "deathknight.blood.suggestions.boneShield.uptime",
message: `${formatPercentage(actual)}% Bone Shield uptime`
}))
.recommended(`>${formatPercentage(recommended)}% is recommended`));
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.CORE(5)}
size="flexible"
dropdown={(
<>
<table className="table table-condensed">
<thead>
<tr>
<th>Stacks</th>
<th>Time (s)</th>
<th>Time (%)</th>
</tr>
</thead>
<tbody>
{Object.values(this.boneShieldTimesByStack).map((e, i) => (
<tr key={i}>
<th>{i}</th>
<td>{formatDuration(e.reduce((a, b) => a + b, 0) / 1000)}</td>
<td>{formatPercentage(e.reduce((a, b) => a + b, 0) / this.owner.fightDuration)}%</td>
</tr>
))}
</tbody>
</table>
</>
)}
>
<BoringSpellValueText spell={SPELLS.BONE_SHIELD}>
<>
<UptimeIcon /> {formatPercentage(this.uptime)}% <small>uptime</small>
</>
</BoringSpellValueText>
</Statistic>
);
}
}
export default BoneShield;
|
src/svg-icons/content/add-circle-outline.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentAddCircleOutline = (props) => (
<SvgIcon {...props}>
<path d="M13 7h-2v4H7v2h4v4h2v-4h4v-2h-4V7zm-1-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z"/>
</SvgIcon>
);
ContentAddCircleOutline = pure(ContentAddCircleOutline);
ContentAddCircleOutline.displayName = 'ContentAddCircleOutline';
ContentAddCircleOutline.muiName = 'SvgIcon';
export default ContentAddCircleOutline;
|
src/components/InputIcon/input-icon.js | emsiengineering/emsi-ui | import CSSModules from 'react-css-modules';
import React from 'react';
import CSS from './input-icon.styl';
import Icon from '../Icon';
type Props = {
name: string,
styles?: Object
}
function InputIcon({ name, styles, ...other }: Props) {
return (
<Icon name={name} styleName='input-icon' size='medium' />
);
}
InputIcon.defaultProps = {
name: 'search'
};
export default CSSModules(InputIcon, CSS, { allowMultiple: true });
|
packages/react/src/components/forms/Label/index.js | massgov/mayflower | /**
* Label module.
* @module @massds/mayflower-react/Label
* @requires module:@massds/mayflower-assets/scss/01-atoms/helper-text
*/
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
const Label = ({
children, inputId, hidden, disabled, conditionText, className, useLegend
}) => {
const inputLabelClasses = classNames(className, {
ma__label: true,
'ma__label--hidden': hidden,
'ma__label--disabled': disabled
});
const Tag = useLegend ? 'legend' : 'label';
return(
<Tag htmlFor={inputId} className={inputLabelClasses}>
{children}
{conditionText && conditionText.length > 0 && (
<span className="ma__label-condition">
{` (${conditionText})`}
</span>
)}
</Tag>
);
};
Label.propTypes = {
/** The text rendered as the label */
children: PropTypes.string,
/** The ID of the corresponding input field */
inputId: PropTypes.string.isRequired,
/** Render the visually hidden style for label */
hidden: PropTypes.bool,
/** Render the disabled style for label */
disabled: PropTypes.bool,
/** The text describing the conditional status of the field */
conditionText: PropTypes.string,
/** Additional classNames for label */
className: PropTypes.string,
/** Use legend tag instead of label. Use legend to caption a <fieldset> */
useLegend: PropTypes.bool
};
export default Label;
|
admin/node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | develnk/irbispanel | 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'));
|
examples/example-react/client.js | as-com/alef | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-alef'
import App from './app'
import createRenderer from './renderer'
const renderer = createRenderer()
render(
<Provider renderer={renderer}>
<App />
</Provider>,
document.getElementById('app')
)
|
src/FormsyAutoComplete/FormsyAutoComplete.spec.js | maccuaa/formsy-mui | import 'jsdom-global/register';
import React from 'react';
import PropTypes from 'prop-types';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import {Form} from 'formsy-react-2';
import Enzyme, { mount } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import test from 'tape';
import Sinon from 'sinon';
import AutoComplete from 'material-ui/AutoComplete';
import TextField from 'material-ui/TextField';
import FormsyAutoComplete from './FormsyAutoComplete';
Enzyme.configure({ adapter: new Adapter() });
const muiTheme = getMuiTheme();
const mountWithContext = (node) => mount(node, {
context: {muiTheme},
childContextTypes: {muiTheme: PropTypes.object.isRequired}
});
test('FormsyAutoComplete renders a material-ui AutoComplete', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} />
</Form>
);
assert.equals(wrapper.find(AutoComplete).length, 1);
assert.end();
});
test('FormsyAutoComplete change event propogates value to Formsy Form', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} />
</Form>
);
const formsyForm = wrapper.instance();
const formsyAutoComplete = wrapper.find(FormsyAutoComplete).instance();
const expected = 'foo';
wrapper.find('input').simulate('change', {target: {value: expected}});
// Make sure the FormsyAutoComplete component has the right value
assert.equals(formsyAutoComplete.getValue(), expected);
// Make sure the Formsy Form component has the right value
assert.equals(formsyForm.getCurrentValues().test, expected);
// Make sure the DOM has the right value
assert.equals(wrapper.find('input').instance().value, expected);
assert.end();
});
test('FormsyAutoComplete searchText prop sends value to Formsy Form', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} searchText='foo' />
</Form>
);
const formsyForm = wrapper.instance();
const expected = 'foo';
assert.equals(formsyForm.getCurrentValues().test, expected);
assert.equals(wrapper.find('input').instance().value, expected);
assert.end();
});
test('FormsyAutoComplete validation Errors are displayed', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} validations='maxLength:2' validationError='foo' searchText='bar' />
</Form>
);
const formsyAutoComplete = wrapper.find(FormsyAutoComplete).instance();
const textField = wrapper.find(TextField).instance();
assert.equals(formsyAutoComplete.getErrorMessage(), 'foo');
assert.equals(textField.state.errorText, 'foo');
assert.false(formsyAutoComplete.isValid());
assert.end();
});
test('FormsyAutoComplete validation Errors are not displayed', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} validations='maxLength:3' validationError='foo' searchText='bar' />
</Form>
);
const formsyAutoComplete = wrapper.find(FormsyAutoComplete).instance();
assert.equals(formsyAutoComplete.getErrorMessage(), null);
assert.true(formsyAutoComplete.isValid());
assert.end();
});
test('FormsyAutoComplete resetValue sets value back to original value', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} searchText='foo' />
</Form>
);
const formsyAutoComplete = wrapper.find(FormsyAutoComplete).instance();
assert.equals(formsyAutoComplete.getValue(), 'foo');
wrapper.find('input').simulate('change', {target: {value: 'bar'}});
assert.equals(formsyAutoComplete.getValue(), 'bar');
formsyAutoComplete.resetValue();
assert.equals(formsyAutoComplete.getValue(), 'foo');
assert.end();
});
test('FormsyAutoComplete Blur event updates the value', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} searchText='foo' />
</Form>
);
const formsyAutoComplete = wrapper.find(FormsyAutoComplete).instance();
assert.equals(formsyAutoComplete.getValue(), 'foo');
wrapper.find('input').simulate('blur', {target: {value: 'bar'}});
assert.equals(formsyAutoComplete.getValue(), 'bar');
assert.end();
});
test('FormsyAutoComplete onChange prop is called', (assert) => {
const onChangeSpy = Sinon.spy();
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} onChange={onChangeSpy} />
</Form>
);
wrapper.find('input').simulate('change', {target: {value: 'bar'}});
assert.true(onChangeSpy.calledOnce);
assert.end();
});
test('FormsyAutoComplete respects disabled prop of Formsy Form', (assert) => {
const wrapper = mountWithContext(
<Form disabled>
<FormsyAutoComplete name='test' dataSource={[]} />
</Form>
);
assert.true(wrapper.find('input').instance().disabled);
assert.end();
});
test('FormsyAutoComplete disabled prop propagetes to Material UI AutoComplete', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} searchText='foo' disabled />
</Form>
);
assert.true(wrapper.find(FormsyAutoComplete).instance().props.disabled);
assert.true(wrapper.find(AutoComplete).instance().props.disabled);
assert.true(wrapper.find('input').instance().disabled);
assert.end();
});
test('FormsyAutoComplete allows overriding Formsy Form disabled prop', (assert) => {
const wrapper = mountWithContext(
<Form disabled>
<FormsyAutoComplete name='test' dataSource={[]} searchText='foo' disabled={false} />
</Form>
);
assert.true(wrapper.instance().props.disabled);
assert.false(wrapper.find(FormsyAutoComplete).instance().props.disabled);
assert.false(wrapper.find(AutoComplete).instance().props.disabled);
assert.false(wrapper.find('input').instance().disabled);
assert.end();
});
test('FormsyAutoComplete required prop invalidates form', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} required />
</Form>
);
const formsyForm = wrapper.instance();
const formsyAutoComplete = wrapper.find(FormsyAutoComplete).instance();
const input = wrapper.find('input').instance();
assert.false(formsyForm.state.isValid);
assert.true(formsyAutoComplete.isRequired());
assert.true(formsyAutoComplete.showRequired());
assert.false(formsyAutoComplete.isValidValue());
assert.true(input.required);
assert.end();
});
test('FormsyAutoComplete requiredError message is displayed', (assert) => {
const wrapper = mountWithContext(
<Form>
<FormsyAutoComplete name='test' dataSource={[]} required requiredError='foo' />
</Form>
);
const formsyAutoComplete = wrapper.find(FormsyAutoComplete).instance();
const textField = wrapper.find(TextField).instance();
// Required error will not be displayed until the form is submitted
assert.equals(formsyAutoComplete.getErrorMessage(), null);
wrapper.simulate('submit');
assert.equals(formsyAutoComplete.getErrorMessage(), 'foo');
assert.equals(textField.state.errorText, 'foo');
assert.end();
});
|
public/src/components/jobs/NewJobScreen.js | sio-iago/essential-plaform-back | // React
import React, { Component } from 'react';
// Redux actions
import { connect } from 'react-redux';
// Main application class
import ApplicationScreen from './../application/ApplicationScreen';
import { Link } from 'react-router-dom';
// Bootstrap Classes
import { Row, Col, Button, FormGroup, ControlLabel, FormControl } from 'react-bootstrap';
// FA Icons
import 'font-awesome/css/font-awesome.min.css';
const FontAwesome = require('react-fontawesome');
// API Methods
const api = require('../../api/endpoints');
// Actions
const onFormSubmit = (evt, history) => {
evt.preventDefault();
const formData = new FormData(evt.target);
api.uploadFastaFile(formData);
history.push('/dashboard');
};
class NewJobScreen extends Component {
getGoBackButton = () => {
return (
<Button bsStyle="default" onClick={ () => this.props.history.goBack() }>
<FontAwesome name="arrow-left"></FontAwesome> Back
</Button>
);
}
render() {
return (
<ApplicationScreen {...this.props}>
<h1>Create a new Job</h1>
<hr/>
{this.getGoBackButton()}
<hr />
<Row>
<Col xs={12}>
<form encType="application/x-www-form-urlencoded"
onSubmit={(evt) => onFormSubmit(evt,this.props.history)}>
<FormGroup>
<FormGroup>
<ControlLabel>Select A Model Organism or Upload Your Own</ControlLabel>
<select name="organism" className="form-control">
<option value=""></option>
<option value="degaa-e-scer.fasta">Saccharomyces cerevisiae</option>
<option value="degaa-e-dani.fasta">Danio Rerio</option>
<option value="degaa-e-eleg.fasta">Caenorhabditis elegans</option>
</select>
<input type="file"
name="modelFile" />
</FormGroup>
<ControlLabel>Upload your target organism file</ControlLabel>
<input type="file"
name="fastaFile" />
</FormGroup>
<FormGroup>
<input type="submit"
value="Start Job"
className="btn btn-md btn-success" />
</FormGroup>
</form>
</Col>
</Row>
</ApplicationScreen>
);
}
}
const mapStateToProps = (state, ownProps) => ({
username: state.userReducer.username,
token: state.userReducer.token,
});
export default connect(mapStateToProps, null)(NewJobScreen);
|
scripts/src/pages/login.js | Twogether/just-meet-frontend | import ReactDOM from 'react-dom';
import React from 'react';
import view from './views/login';
import api from '../utils/api';
import Authentication from '../utils/authentication';
import { browserHistory } from 'react-router';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {};
}
validate(e){
e.preventDefault();
// Get inputs
var self = this,
valid = true,
inputs = Object.keys(this.refs).filter(
key => key.indexOf('form-field-') == 0
).reduce((data, key) => {
data[key] = self.refs[key];
return data;
}, {});
// Validate all inputs
for(let key in inputs) if(inputs[key].validate && !inputs[key].validate()) valid = false;
// Handle validation
if(!valid) {
e.preventDefault();
} else {
const formData = Array.from(e.target.elements)
.filter(el => el.name)
.reduce((a, b) => ({...a, [b.name]: b.value}), {});
this.login(formData);
}
}
async login(data) {
api.getUsers().then(res => {
const user = res.data.filter(user => user.email == data.email)[0];
if (user) {
Authentication.setUser(user);
browserHistory.push({
pathname: '/dashboard'
});
} else {
alert("invalid email");
}
});
}
render(){
return view(this);
}
};
export default Home;
|
internals/templates/appContainer.js | Rohitbels/KolheshwariIndustries | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
Realization/frontend/czechidm-core/src/components/basic/Panel/Panel.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { useSelector } from 'react-redux';
//
import { makeStyles } from '@material-ui/core/styles';
//
import * as Utils from '../../../utils';
import AbstractComponent from '../AbstractComponent/AbstractComponent';
import Div from '../Div/Div';
const useStyles = makeStyles((theme) => {
return {
root: {
backgroundColor: theme.palette.background.paper,
borderRadius: theme.shape.borderRadius,
'& .panel-heading': {
borderTopRightRadius: theme.shape.borderRadius,
borderTopLeftRadius: theme.shape.borderRadius
}
},
default: {
backgroundColor: theme.palette.background.paper,
borderColor: theme.palette.divider,
'& .panel-heading': {
borderColor: theme.palette.divider
}
},
info: {
borderColor: theme.palette.info.main,
'& .panel-heading': {
color: theme.palette.info.contrastText,
borderColor: theme.palette.info.main,
backgroundColor: theme.palette.info.light
}
},
warning: {
borderColor: theme.palette.warning.main,
'& .panel-heading': {
color: theme.palette.warning.contrastText,
borderColor: theme.palette.warning.main,
backgroundColor: theme.palette.warning.light
}
},
error: {
borderColor: theme.palette.error.main,
'& .panel-heading': {
color: theme.palette.error.contrastText,
borderColor: theme.palette.error.main,
backgroundColor: theme.palette.error.light
}
},
success: {
borderColor: theme.palette.success.main,
'& .panel-heading': {
color: theme.palette.success.contrastText,
borderColor: theme.palette.success.main,
backgroundColor: theme.palette.success.light
}
},
primary: {
borderColor: theme.palette.primary.main,
'& .panel-heading': {
color: theme.palette.primary.contrastText,
borderColor: theme.palette.primary.main,
backgroundColor: theme.palette.primary.light
}
},
secondary: {
borderColor: theme.palette.secondary.main,
'& .panel-heading': {
color: theme.palette.secondary.contrastText,
borderColor: theme.palette.secondary.main,
backgroundColor: theme.palette.secondary.light
}
}
};
});
/**
* Basic panel decorator.
*
* @author Radek Tomiška
*/
export default function Panel(props) {
const { className, rendered, showLoading, level, style, children, onClick } = props;
const classes = useStyles();
const userContext = useSelector((state) => state.security.userContext);
//
if (rendered === null || rendered === undefined || rendered === '' || rendered === false) {
return null;
}
//
// try to find panel header and its uiKey => resolve panel is collapsed or not
// lookout: is required here, because panel is rerendered, after profile is persisted and loaded into redux again
let _collapsed = false;
const _children = React.Children.map(children, child => {
if (React.isValidElement(child)) {
if (child.type
&& child.type.__PanelHeader__
&& child.props.uiKey
&& userContext
&& userContext.profile
&& userContext.profile.setting
&& userContext.profile.setting[child.props.uiKey]) { // or personalized by profile
_collapsed = !!userContext.profile.setting[child.props.uiKey].collapsed;
}
}
return child;
});
//
const classNames = classnames(
'basic-panel',
'panel',
{ collapsed: _collapsed },
classes.root,
classes[Utils.Ui.toLevel(level)],
className,
);
//
return (
<Div className={ classNames } style={ style } onClick={ onClick } showLoading={ showLoading }>
{ _children }
</Div>
);
}
Panel.propTypes = {
...AbstractComponent.propTypes,
/**
* Panel level / css / class
*/
level: PropTypes.oneOf(['default', 'success', 'warning', 'info', 'danger', 'primary'])
};
Panel.defaultProps = {
...AbstractComponent.defaultProps,
level: 'default'
};
|
client/components/atoms/TextI18n/index.js | defe266/keystone-starter | import React from 'react'
import { connect } from 'react-redux'
import BlockHTML from '../../atoms/BlockHTML';
var TextI18n = function (props) {
var lang = props.lang;
var value = props.value;
var output = value;
if(value && lang && typeof value === 'object'){
output = value[lang]
}
if(props.html) return <BlockHTML>{output}</BlockHTML>
return <span>{output}</span>
}
module.exports = connect((state) => {
return {
lang: state.i18nState.lang
}
})(TextI18n) |
app/javascript/mastodon/features/compose/components/poll_form.js | ikuradon/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import IconButton from 'mastodon/components/icon_button';
import Icon from 'mastodon/components/icon';
import AutosuggestInput from 'mastodon/components/autosuggest_input';
import classNames from 'classnames';
const messages = defineMessages({
option_placeholder: { id: 'compose_form.poll.option_placeholder', defaultMessage: 'Choice {number}' },
add_option: { id: 'compose_form.poll.add_option', defaultMessage: 'Add a choice' },
remove_option: { id: 'compose_form.poll.remove_option', defaultMessage: 'Remove this choice' },
poll_duration: { id: 'compose_form.poll.duration', defaultMessage: 'Poll duration' },
switchToMultiple: { id: 'compose_form.poll.switch_to_multiple', defaultMessage: 'Change poll to allow multiple choices' },
switchToSingle: { id: 'compose_form.poll.switch_to_single', defaultMessage: 'Change poll to allow for a single choice' },
minutes: { id: 'intervals.full.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}}' },
hours: { id: 'intervals.full.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}}' },
days: { id: 'intervals.full.days', defaultMessage: '{number, plural, one {# day} other {# days}}' },
});
@injectIntl
class Option extends React.PureComponent {
static propTypes = {
title: PropTypes.string.isRequired,
index: PropTypes.number.isRequired,
isPollMultiple: PropTypes.bool,
autoFocus: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onRemove: PropTypes.func.isRequired,
onToggleMultiple: PropTypes.func.isRequired,
suggestions: ImmutablePropTypes.list,
onClearSuggestions: PropTypes.func.isRequired,
onFetchSuggestions: PropTypes.func.isRequired,
onSuggestionSelected: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleOptionTitleChange = e => {
this.props.onChange(this.props.index, e.target.value);
};
handleOptionRemove = () => {
this.props.onRemove(this.props.index);
};
handleToggleMultiple = e => {
this.props.onToggleMultiple();
e.preventDefault();
e.stopPropagation();
};
handleCheckboxKeypress = e => {
if (e.key === 'Enter' || e.key === ' ') {
this.handleToggleMultiple(e);
}
}
onSuggestionsClearRequested = () => {
this.props.onClearSuggestions();
}
onSuggestionsFetchRequested = (token) => {
this.props.onFetchSuggestions(token);
}
onSuggestionSelected = (tokenStart, token, value) => {
this.props.onSuggestionSelected(tokenStart, token, value, ['poll', 'options', this.props.index]);
}
render () {
const { isPollMultiple, title, index, autoFocus, intl } = this.props;
return (
<li>
<label className='poll__option editable'>
<span
className={classNames('poll__input', { checkbox: isPollMultiple })}
onClick={this.handleToggleMultiple}
onKeyPress={this.handleCheckboxKeypress}
role='button'
tabIndex='0'
title={intl.formatMessage(isPollMultiple ? messages.switchToSingle : messages.switchToMultiple)}
aria-label={intl.formatMessage(isPollMultiple ? messages.switchToSingle : messages.switchToMultiple)}
/>
<AutosuggestInput
placeholder={intl.formatMessage(messages.option_placeholder, { number: index + 1 })}
maxLength={50}
value={title}
onChange={this.handleOptionTitleChange}
suggestions={this.props.suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
onSuggestionSelected={this.onSuggestionSelected}
searchTokens={[':']}
autoFocus={autoFocus}
/>
</label>
<div className='poll__cancel'>
<IconButton disabled={index <= 1} title={intl.formatMessage(messages.remove_option)} icon='times' onClick={this.handleOptionRemove} />
</div>
</li>
);
}
}
export default
@injectIntl
class PollForm extends ImmutablePureComponent {
static propTypes = {
options: ImmutablePropTypes.list,
expiresIn: PropTypes.number,
isMultiple: PropTypes.bool,
onChangeOption: PropTypes.func.isRequired,
onAddOption: PropTypes.func.isRequired,
onRemoveOption: PropTypes.func.isRequired,
onChangeSettings: PropTypes.func.isRequired,
suggestions: ImmutablePropTypes.list,
onClearSuggestions: PropTypes.func.isRequired,
onFetchSuggestions: PropTypes.func.isRequired,
onSuggestionSelected: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleAddOption = () => {
this.props.onAddOption('');
};
handleSelectDuration = e => {
this.props.onChangeSettings(e.target.value, this.props.isMultiple);
};
handleToggleMultiple = () => {
this.props.onChangeSettings(this.props.expiresIn, !this.props.isMultiple);
};
render () {
const { options, expiresIn, isMultiple, onChangeOption, onRemoveOption, intl, ...other } = this.props;
if (!options) {
return null;
}
const autoFocusIndex = options.indexOf('');
return (
<div className='compose-form__poll-wrapper'>
<ul>
{options.map((title, i) => <Option title={title} key={i} index={i} onChange={onChangeOption} onRemove={onRemoveOption} isPollMultiple={isMultiple} onToggleMultiple={this.handleToggleMultiple} autoFocus={i === autoFocusIndex} {...other} />)}
</ul>
<div className='poll__footer'>
<button disabled={options.size >= 4} className='button button-secondary' onClick={this.handleAddOption}><Icon id='plus' /> <FormattedMessage {...messages.add_option} /></button>
{/* eslint-disable-next-line jsx-a11y/no-onchange */}
<select value={expiresIn} onChange={this.handleSelectDuration}>
<option value={300}>{intl.formatMessage(messages.minutes, { number: 5 })}</option>
<option value={1800}>{intl.formatMessage(messages.minutes, { number: 30 })}</option>
<option value={3600}>{intl.formatMessage(messages.hours, { number: 1 })}</option>
<option value={21600}>{intl.formatMessage(messages.hours, { number: 6 })}</option>
<option value={86400}>{intl.formatMessage(messages.days, { number: 1 })}</option>
<option value={259200}>{intl.formatMessage(messages.days, { number: 3 })}</option>
<option value={604800}>{intl.formatMessage(messages.days, { number: 7 })}</option>
</select>
</div>
</div>
);
}
}
|
frontend/src/components/eois/modals/changeSummary/changeSummaryModal.js | unicef/un-partner-portal | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { submit, SubmissionError } from 'redux-form';
import ControlledModal from '../../../common/modals/controlledModal';
import { updateReviewSummary } from '../../../../reducers/cfeiReviewSummary';
import ChangeSummaryForm from './changeSummaryForm';
import { changedValues } from '../../../../helpers/apiHelper';
import { selectCfeiReviewSummary } from '../../../../store';
const messages = {
title: (_, edit) => `${edit ? 'Edit' : 'Add'} Review Summary`,
header: 'You can provide comments or add an attachment to summarize the review process.',
error: 'Sorry, update failed',
};
class ChangeSummaryModal extends Component {
constructor(props) {
super(props);
this.onFormSubmit = this.onFormSubmit.bind(this);
}
onFormSubmit(values) {
const { handleDialogClose, updateReviewSummary, initSummary } = this.props;
return updateReviewSummary(changedValues(initSummary, values))
.then(() => handleDialogClose())
.catch((error) => {
const errorMsg = messages.error;
throw new SubmissionError({
...error.response.data,
_error: errorMsg,
});
});
}
render() {
const { cfeiId, edit, submit, dialogOpen, handleDialogClose } = this.props;
return (
<div>
<ControlledModal
maxWidth="md"
title={messages.title`${edit}`}
trigger={dialogOpen}
handleDialogClose={handleDialogClose}
info={{ title: messages.header }}
buttons={{
flat: {
handleClick: handleDialogClose,
},
raised: {
handleClick: submit,
label: messages.save,
},
}}
content={<ChangeSummaryForm
form="changeSummary"
cfeiId={cfeiId}
onSubmit={this.onFormSubmit}
/>}
/>
</div >
);
}
}
ChangeSummaryModal.propTypes = {
dialogOpen: PropTypes.bool,
cfeiId: PropTypes.string,
submit: PropTypes.func,
edit: PropTypes.bool,
updateReviewSummary: PropTypes.func,
handleDialogClose: PropTypes.func,
initSummary: PropTypes.object,
};
const mapStateToProps = (state, ownProps) => ({
initSummary: selectCfeiReviewSummary(state, ownProps.cfeiId),
});
const mapDispatchToProps = (dispatch, ownProps) => {
const { cfeiId } = ownProps;
return {
updateReviewSummary: body => dispatch(updateReviewSummary(
cfeiId, body)),
submit: () => dispatch(submit('changeSummary')),
};
};
export default connect(
mapStateToProps,
mapDispatchToProps,
)(ChangeSummaryModal);
|
addons/docs/src/frameworks/react/__testfixtures__/9586-js-react-memo/input.js | storybooks/storybook | import React from 'react';
import PropTypes from 'prop-types';
function Button({ label, onClick }) {
// eslint-disable-next-line react/button-has-type
return <button onClick={onClick}>{label}</button>;
}
Button.propTypes = {
label: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
};
const MemoButton = React.memo(Button);
export const component = MemoButton;
|
src-client/modules/generator/containers/GeneratorList/index.js | ipselon/structor | /*
* Copyright 2017 Alexander Pustovalov
*
* 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, { Component } from 'react';
import { connect } from 'react-redux';
import { modelSelector } from './selectors.js';
import { containerActions } from './actions.js';
import { Grid, Row, Col } from 'react-bootstrap';
import { Tabs, Tab } from 'react-bootstrap';
import { GeneratorKeyTitleView } from 'components';
import GeneratorBriefPanel from 'modules/generator/containers/GeneratorBriefPanel';
class Container extends Component {
constructor(props) {
super(props);
this.state = {
activePage: 1,
itemsPerPage: 7,
};
this.handleTabSelect = this.handleTabSelect.bind(this);
}
handleTabSelect(eventKey){
if(eventKey){
this.props.setSelectedTab(eventKey);
}
}
render(){
const {
componentModel: {generators, recentGenerators, selectedTabKey}
} = this.props;
let generatorPanelList = [];
if (selectedTabKey === 1) {
if(generators && generators.length > 0) {
generators.forEach((item, index) => {
generatorPanelList.push(
<GeneratorBriefPanel
key={item.name + index}
name={item.name}
dirPath={item.dirPath}
readmeFilePath={item.readmeFilePath}
screenshotFilePath={item.screenshotFilePath}
readmeText={item.readmeText}
/>
);
});
}
} else if (selectedTabKey === 2){
if (generators && generators.length > 0 && recentGenerators && recentGenerators.length > 0) {
generators.forEach((item, index) => {
if (recentGenerators.indexOf(item.name) >= 0) {
generatorPanelList.push(
<GeneratorBriefPanel
key={item.name + index}
name={item.name}
dirPath={item.dirPath}
readmeFilePath={item.readmeFilePath}
screenshotFilePath={item.screenshotFilePath}
readmeText={item.readmeText}
isRecentPanel={true}
/>
);
}
});
}
}
return (
<Grid fluid={ true }>
<Row style={ { minHeight: '40em', position: 'relative'} }>
<Col xs={ 12 } md={ 8 } sm={ 12 } lg={ 8 } mdOffset={2} lgOffset={2}>
<Tabs
activeKey={selectedTabKey}
onSelect={this.handleTabSelect}
id="generatorListTabs"
animation={false}
>
<Tab
key="scaffoldGenerators"
eventKey={1}
title="Generators"
>
<div style={{marginTop: '2em'}}>
{generatorPanelList}
</div>
</Tab>
<Tab
key="favoriteGenerators"
eventKey={2}
disabled={!recentGenerators || recentGenerators.length <= 0}
title="Recently Used"
>
<div style={{marginTop: '2em'}}>
{generatorPanelList}
</div>
</Tab>
</Tabs>
</Col>
</Row>
</Grid>
);
}
}
export default connect(modelSelector, containerActions)(Container);
|
Card.js | srserx/react-native-ui-common | import React from 'react';
import { View } from 'react-native';
// This class is intended for styling only. Because there's not shared CSS styles
// in react-native. So a style that is to be shared, must be by using a class.
const Card = (props) => {
return (
<View style={styles.containerStyle}>
{ props.children }
</View>
);
};
const styles = {
containerStyle: {
borderWidth: 1,
borderRadius: 2,
borderColor: '#ddd',
borderBottomWidth: 0,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.1,
shadowRadius: 2,
elevation: 1,
marginLeft: 5,
marginRight: 5,
marginTop: 10
}
};
export { Card };
|
example/src/components/component10.js | jpuri/darsh | import React, { Component } from 'react';
import { configureStore } from 'react-component-store';
export default class Component10 extends Component {
render() {
return (
<div style={{padding: 30, border: '1px solid gray'}}>
<p>CHILD OF CHILD COMPONENT-1 (Dumb component)</p>
<div>This is current value of data1: {this.props.data1}</div>
</div>
);
}
};
|
pootle/static/js/auth/components/AuthContent.js | dwaynebailey/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import assign from 'object-assign';
import React from 'react';
import { PureRenderMixin } from 'react-addons-pure-render-mixin';
const AuthContent = React.createClass({
propTypes: {
children: React.PropTypes.node,
style: React.PropTypes.object,
},
mixins: [PureRenderMixin],
render() {
// FIXME: use flexbox when possible
const outer = assign({
display: 'table',
height: '22em',
width: '100%',
}, this.props.style);
const style = {
outer,
inner: {
display: 'table-cell',
verticalAlign: 'middle',
},
};
return (
<div style={style.outer}>
<div style={style.inner}>
{this.props.children}
</div>
</div>
);
},
});
export default AuthContent;
|
Console/app/node_modules/rc-input-number/es/index.ios.js | RisenEsports/RisenEsports.github.io | import React from 'react';
import PropTypes from 'prop-types';
import createReactClass from 'create-react-class';
import { Text, TextInput, TouchableWithoutFeedback, View } from 'react-native';
import mixin from './mixin';
var InputNumber = createReactClass({
propTypes: {
styles: PropTypes.object,
style: PropTypes.object,
upStyle: PropTypes.object,
downStyle: PropTypes.object,
inputStyle: PropTypes.object,
onChange: PropTypes.func,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
max: PropTypes.number,
min: PropTypes.number,
autoFocus: PropTypes.bool,
disabled: PropTypes.bool,
step: PropTypes.number,
value: PropTypes.number,
defaultValue: PropTypes.number,
readOnly: PropTypes.bool,
keyboardType: PropTypes.string
},
mixins: [mixin],
onPressIn: function onPressIn(type) {
if (this.props.disabled) {
return;
}
var styles = this.props.styles;
this[type].setNativeProps({
style: [styles.stepWrap, styles.highlightStepBorderColor]
});
this[type + 'Text'].setNativeProps({
style: [styles.stepText, styles.highlightStepTextColor]
});
},
onPressOut: function onPressOut(type) {
if (this.props.disabled) {
return;
}
var styles = this.props.styles;
this[type].setNativeProps({
style: [styles.stepWrap]
});
this[type + 'Text'].setNativeProps({
style: [styles.stepText]
});
},
onPressInDown: function onPressInDown(e) {
this.onPressIn('_stepDown');
this.down(e, true);
},
onPressOutDown: function onPressOutDown() {
this.onPressOut('_stepDown');
this.stop();
},
onPressInUp: function onPressInUp(e) {
this.onPressIn('_stepUp');
this.up(e, true);
},
onPressOutUp: function onPressOutUp() {
this.onPressOut('_stepUp');
this.stop();
},
getValueFromEvent: function getValueFromEvent(e) {
return e.nativeEvent.text;
},
render: function render() {
var _this = this;
var props = this.props,
state = this.state;
var _props = this.props,
style = _props.style,
upStyle = _props.upStyle,
downStyle = _props.downStyle,
inputStyle = _props.inputStyle,
styles = _props.styles;
var editable = !this.props.readOnly && !this.props.disabled;
var upDisabledStyle = null;
var downDisabledStyle = null;
var upDisabledTextStyle = null;
var downDisabledTextStyle = null;
var value = state.value;
if (!isNaN(value)) {
var val = Number(value);
if (val >= props.max) {
upDisabledStyle = styles.stepDisabled;
upDisabledTextStyle = styles.disabledStepTextColor;
}
if (val <= props.min) {
downDisabledStyle = styles.stepDisabled;
downDisabledTextStyle = styles.disabledStepTextColor;
}
} else {
upDisabledStyle = styles.stepDisabled;
downDisabledStyle = styles.stepDisabled;
upDisabledTextStyle = styles.disabledStepTextColor;
downDisabledTextStyle = styles.disabledStepTextColor;
}
var inputDisabledStyle = null;
if (props.disabled) {
upDisabledStyle = styles.stepDisabled;
downDisabledStyle = styles.stepDisabled;
upDisabledTextStyle = styles.disabledStepTextColor;
downDisabledTextStyle = styles.disabledStepTextColor;
inputDisabledStyle = styles.disabledStepTextColor;
}
var inputDisplayValue = void 0;
if (state.focused) {
inputDisplayValue = '' + state.inputValue;
} else {
inputDisplayValue = '' + state.value;
}
if (inputDisplayValue === undefined) {
inputDisplayValue = '';
}
return React.createElement(
View,
{ style: [styles.container, style] },
React.createElement(
TouchableWithoutFeedback,
{
onPressIn: editable && !downDisabledStyle ? this.onPressInDown : undefined,
onPressOut: editable && !downDisabledStyle ? this.onPressOutDown : undefined,
accessible: true,
accessibilityLabel: 'Decrease Value',
accessibilityComponentType: 'button',
accessibilityTraits: editable && !downDisabledStyle ? 'button' : 'disabled'
},
React.createElement(
View,
{
ref: function ref(component) {
return _this._stepDown = component;
},
style: [styles.stepWrap, downDisabledStyle, downStyle]
},
React.createElement(
Text,
{
ref: function ref(component) {
return _this._stepDownText = component;
},
style: [styles.stepText, downDisabledTextStyle]
},
'-'
)
)
),
React.createElement(TextInput, {
style: [styles.input, inputDisabledStyle, inputStyle],
ref: 'input',
value: inputDisplayValue,
autoFocus: props.autoFocus,
editable: editable,
onFocus: this.onFocus,
onEndEditing: this.onBlur,
onChange: this.onChange,
underlineColorAndroid: 'transparent',
keyboardType: props.keyboardType
}),
React.createElement(
TouchableWithoutFeedback,
{
onPressIn: editable && !upDisabledStyle ? this.onPressInUp : undefined,
onPressOut: editable && !upDisabledStyle ? this.onPressOutUp : undefined,
accessible: true,
accessibilityLabel: 'Increase Value',
accessibilityComponentType: 'button',
accessibilityTraits: editable && !upDisabledStyle ? 'button' : 'disabled'
},
React.createElement(
View,
{
ref: function ref(component) {
return _this._stepUp = component;
},
style: [styles.stepWrap, upDisabledStyle, upStyle]
},
React.createElement(
Text,
{
ref: function ref(component) {
return _this._stepUpText = component;
},
style: [styles.stepText, upDisabledTextStyle]
},
'+'
)
)
)
);
}
});
export default InputNumber; |
ui/server.js | nlhuykhang/apollo-react-quotes-client | import 'isomorphic-fetch';
import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { ApolloProvider, renderToStringWithData } from 'react-apollo';
import { match, RouterContext } from 'react-router';
import path from 'path';
import proxy from 'http-proxy-middleware';
import routes from './routes';
import Html from './routes/Html';
import createApolloClient from './helpers/create-apollo-client';
import getNetworkInterface from './transport';
let PORT = 3000;
if (process.env.PORT) {
PORT = parseInt(process.env.PORT, 10);
}
const API_HOST = process.env.NODE_ENV !== 'production' ? 'http://localhost:3010' : 'http://api.githunt.com';
const app = new Express();
const apiProxy = proxy({ target: API_HOST, changeOrigin: true });
app.use('/graphql', apiProxy);
app.use('/graphiql', apiProxy);
app.use('/login', apiProxy);
app.use('/logout', apiProxy);
if (process.env.NODE_ENV === 'production') {
// In production we want to serve our JavaScripts from a file on the file
// system.
app.use('/static', Express.static(path.join(process.cwd(), 'build/client')));
} else {
// Otherwise we want to proxy the webpack development server.
app.use('/static', proxy({ target: 'http://localhost:3020', pathRewrite: { '^/static': '' } }));
}
app.use((req, res) => {
match({ routes, location: req.originalUrl }, (error, redirectLocation, renderProps) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
console.error('ROUTER ERROR:', error); // eslint-disable-line no-console
res.status(500);
} else if (renderProps) {
const client = createApolloClient({
ssrMode: true,
networkInterface: getNetworkInterface(API_HOST, { cookie: req.header('Cookie') }),
});
const component = (
<MuiThemeProvider>
<ApolloProvider client={client}>
<RouterContext {...renderProps} />
</ApolloProvider>
</MuiThemeProvider>
);
renderToStringWithData(component).then((content) => {
const data = client.store.getState().apollo.data;
res.status(200);
const html = (<Html
content={content}
state={{ apollo: { data } }}
/>);
res.send(`<!doctype html>\n${ReactDOM.renderToStaticMarkup(html)}`);
res.end();
}).catch((e) => {
console.error('RENDERING ERROR:', e); // eslint-disable-line no-console
res.status(500);
res.end(`An error occurred. Please submit an issue to [https://github.com/apollographql/GitHunt-React] with the following stack trace:\n\n${e.stack}`);
});
} else {
res.status(404).send('Not found');
}
});
});
app.listen(PORT, () => console.log( // eslint-disable-line no-console
`App Server is now running on http://localhost:${PORT}`
));
|
src/articles/2018-01-31-1st-Anniversary/TimelineItemImage.js | anom0ly/WoWAnalyzer | import PropTypes from 'prop-types';
import React from 'react';
const TimelineItemImage = ({ source, description, wide }) => (
<figure style={wide ? { maxWidth: 800 } : undefined}>
<a href={source} target="_blank" rel="noopener noreferrer">
<img src={source} alt={description} />
</a>
<figcaption>{description}</figcaption>
</figure>
);
TimelineItemImage.propTypes = {
source: PropTypes.string.isRequired,
description: PropTypes.node.isRequired,
wide: PropTypes.bool,
};
export default TimelineItemImage;
|
elcri.men/src/components/MxHexTileMapTooltip.js | diegovalle/new.crimenmexico | import React from 'react'
import PropTypes from 'prop-types'
import MxHexTileMap from '../components/MxHexTileMap'
export const withTooltipPropTypes = {
tooltipOpen: PropTypes.bool,
tooltipLeft: PropTypes.number,
tooltipTop: PropTypes.number,
tooltipData: PropTypes.object,
updateTooltip: PropTypes.func,
showTooltip: PropTypes.func,
hideTooltip: PropTypes.func,
}
class MxHexTileMapTooltip extends React.Component {
constructor(props) {
super(props)
this.state = {
tooltipOpen: false,
tooltipLeft: undefined,
tooltipTop: undefined,
tooltipData: undefined,
}
this.updateTooltip = this.updateTooltip.bind(this)
this.showTooltip = this.showTooltip.bind(this)
this.hideTooltip = this.hideTooltip.bind(this)
}
updateTooltip({ tooltipOpen, tooltipLeft, tooltipTop, tooltipData }) {
this.setState(prevState => ({
...prevState,
tooltipOpen,
tooltipLeft,
tooltipTop,
tooltipData,
}))
}
showTooltip({ tooltipLeft, tooltipTop, tooltipData }) {
this.updateTooltip({
tooltipOpen: true,
tooltipLeft,
tooltipTop,
tooltipData,
})
}
hideTooltip() {
this.updateTooltip({
tooltipOpen: false,
tooltipLeft: undefined,
tooltipTop: undefined,
tooltipData: undefined,
})
}
render() {
return (
<div style={{height:" 100%"}}>
<MxHexTileMap
height={500}
selected_state={this.props.selected_state}
updateState={this.props.updateState}
selected_crime={this.props.selected_crime}
updateCrime={this.props.updateCrime}
updateTooltip={this.props.updateTooltip}
showTooltip={this.showTooltip}
hideTooltip={this.hideTooltip}
{...this.state}
{...this.props}
/>
</div>
)
}
}
export default MxHexTileMapTooltip
|
src/components/theme-legacy/login-form.js | MoveOnOrg/mop-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
const LoginForm = ({ setRef, errorList, handleSubmit, isSubmitting }) => (
<div className='container'>
<div className='row'>
<div className='span6 offset3'>
<div className='well login clearfix'>
<h1 className='lanky-header size-xl'>It’s time to log in!</h1>
<ul className='errors'>
{errorList && errorList()}
</ul>
<form method='POST' onSubmit={handleSubmit}>
<input
ref={setRef}
type='text'
name='email'
placeholder='Email'
/>
<input
ref={setRef}
type='password'
name='password'
placeholder='Password'
/>
<div>
<div className='bump-bottom-2'>
<input
value={isSubmitting ? 'Please wait...' : 'Login'}
disabled={isSubmitting}
type='submit'
className='button bump-top-2'
/>
</div>
<ul className='unstyled inline size-small'>
<li>
<Link to='/login/forgot_password.html'>
Forgot your password?
</Link>
</li>
<li>
Never used MoveOn’s petition website?{' '}
<Link to='/login/register.html'>Sign up now.</Link>
</li>
</ul>
</div>
</form>
</div>
</div>
</div>
</div>
)
LoginForm.propTypes = {
errorList: PropTypes.func,
handleSubmit: PropTypes.func,
setRef: PropTypes.func,
isSubmitting: PropTypes.bool
}
export default LoginForm
|
app/javascript/flavours/glitch/features/hashtag_timeline/index.js | vahnj/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from 'flavours/glitch/features/ui/containers/status_list_container';
import Column from 'flavours/glitch/components/column';
import ColumnHeader from 'flavours/glitch/components/column_header';
import {
refreshHashtagTimeline,
expandHashtagTimeline,
} from 'flavours/glitch/actions/timelines';
import { addColumn, removeColumn, moveColumn } from 'flavours/glitch/actions/columns';
import { FormattedMessage } from 'react-intl';
import { connectHashtagStream } from 'flavours/glitch/actions/streaming';
const mapStateToProps = (state, props) => ({
hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}`, 'unread']) > 0,
});
@connect(mapStateToProps)
export default class HashtagTimeline extends React.PureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
columnId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('HASHTAG', { id: this.props.params.id }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
_subscribe (dispatch, id) {
this.disconnect = dispatch(connectHashtagStream(id));
}
_unsubscribe () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
componentDidMount () {
const { dispatch } = this.props;
const { id } = this.props.params;
dispatch(refreshHashtagTimeline(id));
this._subscribe(dispatch, id);
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.id !== this.props.params.id) {
this.props.dispatch(refreshHashtagTimeline(nextProps.params.id));
this._unsubscribe();
this._subscribe(this.props.dispatch, nextProps.params.id);
}
}
componentWillUnmount () {
this._unsubscribe();
}
setRef = c => {
this.column = c;
}
handleLoadMore = () => {
this.props.dispatch(expandHashtagTimeline(this.props.params.id));
}
render () {
const { hasUnread, columnId, multiColumn } = this.props;
const { id } = this.props.params;
const pinned = !!columnId;
return (
<Column ref={this.setRef} name='hashtag'>
<ColumnHeader
icon='hashtag'
active={hasUnread}
title={id}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
/>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`hashtag_timeline-${columnId}`}
timelineId={`hashtag:${id}`}
loadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />}
/>
</Column>
);
}
}
|
local-cli/templates/HelloNavigation/views/welcome/WelcomeText.android.js | doochik/react-native | 'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export default class WelcomeText extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
This app shows the basics of navigating between a few screens,
working with ListView and handling text input.
</Text>
<Text style={styles.instructions}>
Modify any files to get started. For example try changing the
file views/welcome/WelcomeText.android.js.
</Text>
<Text style={styles.instructions}>
Double tap R on your keyboard to reload,{'\n'}
Shake or press menu button for dev menu.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
padding: 20,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 16,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 12,
},
});
|
source/js/main.js | mehan/nsf-challenge | /* eslint no-unused-vars: ["error", { "varsIgnorePattern": "React" }] */
import React from 'react';
import ReactDOM from 'react-dom';
import Faq from './components/faq.js';
import NsfNav from './components/nsf-nav.js';
import Challenges from './components/challenges.js';
if (document.getElementById(`sticky-nav`)) {
ReactDOM.render(
<NsfNav/>,
document.getElementById(`sticky-nav`)
);
}
if (document.getElementById(`expander-container`)) {
ReactDOM.render(
<Faq/>,
document.getElementById(`expander-container`)
);
}
if (document.getElementById(`challenges-switcher`)) {
ReactDOM.render(
<Challenges/>,
document.getElementById(`challenges-switcher`)
);
}
|
src/components/pages/login/Login.js | juandjara/open-crono | import React, { Component } from 'react';
import Input from 'react-toolbox/lib/input/Input'
import Checkbox from 'react-toolbox/lib/checkbox/Checkbox'
import Button from 'react-toolbox/lib/button/Button'
import { connect } from 'react-redux'
import { authenticate } from 'reducers/auth.reducer'
import './Login.css'
export class Login extends Component {
state = {
rememberMe: true,
form: {
email: '',
password: ''
}
}
onSubmit = (ev) => {
ev.preventDefault();
const { form, rememberMe } = this.state;
const { location } = this.props;
this.props.authenticate(form, rememberMe, location.query.next)
}
onChange = (text, ev) => {
const name = ev.target.name;
this.setState(prevState => ({
form: {
...prevState.form,
[name]: text
}
}))
}
onCheckboxChange = (checked) => {
this.setState({ rememberMe: checked })
}
render() {
const {loading, error} = this.props;
const {form, rememberMe} = this.state
return (
<div className="login-wrapper">
<div style={{minHeight: '400px'}} >
<h1 className="login-header">Open Crono</h1>
<p className="color-primary" style={{textAlign: 'center'}}>
{loading && 'Cargando ...'}
</p>
<p style={{color: 'tomato', textAlign: 'center'}}>{error}</p>
<form onSubmit={this.onSubmit} className="login-form shadow-z1">
<Input
label="Correo electronico" icon="email"
name="email" type="text" required
value={form.email} onChange={this.onChange} />
<Input
minLength={4}
label="Contraseña" type="password"
name="password" icon="lock" required
value={form.password} onChange={this.onChange} />
<div style={{marginTop: '1em'}}>
<Checkbox
name="rememberMe"
style={{opacity: 0.5}}
onChange={this.onCheckboxChange} checked={rememberMe}
label="Recordarme durante 24h" />
<Button
primary raised style={{width: '100%'}}
type="submit" disabled={loading}>
{loading ? 'Cargando ...' : 'Entrar'}
</Button>
</div>
</form>
</div>
</div>
);
}
}
const mapStateToProps = state => state.auth;
const actions = {authenticate}
export default connect(mapStateToProps, actions)(Login);
|
app/index.js | donofkarma/react-starter | import React from 'react';
import Async from 'react-code-splitting'
import ReactDOM from 'react-dom';
const App = () => <Async load={import('containers/app')} />;
ReactDOM.render(
<App />,
document.getElementById('app')
);
|
src/svg-icons/action/subject.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSubject = (props) => (
<SvgIcon {...props}>
<path d="M14 17H4v2h10v-2zm6-8H4v2h16V9zM4 15h16v-2H4v2zM4 5v2h16V5H4z"/>
</SvgIcon>
);
ActionSubject = pure(ActionSubject);
ActionSubject.displayName = 'ActionSubject';
export default ActionSubject;
|
src/client.js | Sawtaytoes/Ghadyani-Framework-Webpack-React-Redux | import React from 'react'
import { AppContainer } from 'react-hot-loader'
import { hydrate, render } from 'react-dom'
// Compatibility Polyfills
import 'react-fastclick'
import 'utils/polyfills'
import ClientRoot from 'components/root/ClientRoot'
const isProd = process.env.NODE_ENV === 'production'
const rootElement = document.getElementById('root')
Promise.resolve(
isProd
? hydrate
: render
)
.then(domRender => (
domRender(
(
<AppContainer>
<ClientRoot />
</AppContainer>
),
rootElement
)
))
const onHotReload = () => {
const ClientRootHotReload = require('./components/root/ClientRoot').default
render(
(
<AppContainer>
<ClientRootHotReload />
</AppContainer>
),
rootElement
)
}
module.hot
&& module.hot.accept('./components/root/ClientRoot', onHotReload)
|
node_modules/antd/es/timeline/TimelineItem.js | ZSMingNB/react-news | import _extends from 'babel-runtime/helpers/extends';
import _defineProperty from 'babel-runtime/helpers/defineProperty';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
var __rest = this && this.__rest || function (s, e) {
var t = {};
for (var p in s) {
if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) t[p] = s[p];
}if (s != null && typeof Object.getOwnPropertySymbols === "function") for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
if (e.indexOf(p[i]) < 0) t[p[i]] = s[p[i]];
}return t;
};
import React from 'react';
import classNames from 'classnames';
var TimelineItem = function (_React$Component) {
_inherits(TimelineItem, _React$Component);
function TimelineItem() {
_classCallCheck(this, TimelineItem);
return _possibleConstructorReturn(this, (TimelineItem.__proto__ || Object.getPrototypeOf(TimelineItem)).apply(this, arguments));
}
_createClass(TimelineItem, [{
key: 'render',
value: function render() {
var _classNames, _classNames2;
var _a = this.props,
prefixCls = _a.prefixCls,
className = _a.className,
_a$color = _a.color,
color = _a$color === undefined ? '' : _a$color,
last = _a.last,
children = _a.children,
pending = _a.pending,
dot = _a.dot,
restProps = __rest(_a, ["prefixCls", "className", "color", "last", "children", "pending", "dot"]);
var itemClassName = classNames((_classNames = {}, _defineProperty(_classNames, prefixCls + '-item', true), _defineProperty(_classNames, prefixCls + '-item-last', last), _defineProperty(_classNames, prefixCls + '-item-pending', pending), _classNames), className);
var dotClassName = classNames((_classNames2 = {}, _defineProperty(_classNames2, prefixCls + '-item-head', true), _defineProperty(_classNames2, prefixCls + '-item-head-custom', dot), _defineProperty(_classNames2, prefixCls + '-item-head-' + color, true), _classNames2));
return React.createElement(
'li',
_extends({}, restProps, { className: itemClassName }),
React.createElement('div', { className: prefixCls + '-item-tail' }),
React.createElement(
'div',
{ className: dotClassName, style: { borderColor: /blue|red|green/.test(color) ? null : color } },
dot
),
React.createElement(
'div',
{ className: prefixCls + '-item-content' },
children
)
);
}
}]);
return TimelineItem;
}(React.Component);
export default TimelineItem;
TimelineItem.defaultProps = {
prefixCls: 'ant-timeline',
color: 'blue',
last: false,
pending: false
}; |
src/js/components/icons/base/Standards-3dEffects.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-standards-3d-effects`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'standards-3d-effects');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><polygon fill="#231F20" fillRule="evenodd" points="13.009 1 6.844 2.988 20.203 7.315 20.203 15.838 11.301 18.715 3.787 16.287 3.787 7.934 11.051 10.282 17.216 8.294 3.837 3.958 0 5.206 0 19.045 11.301 22.702 24 18.595 24 4.547" stroke="none"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Standards3DEffects';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
app/javascript/mastodon/features/introduction/index.js | pinfort/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ReactSwipeableViews from 'react-swipeable-views';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { FormattedMessage } from 'react-intl';
import { closeOnboarding } from '../../actions/onboarding';
import screenHello from '../../../images/screen_hello.svg';
import screenFederation from '../../../images/screen_federation.svg';
import screenInteractions from '../../../images/screen_interactions.svg';
import logoTransparent from '../../../images/logo_transparent.svg';
import { disableSwiping } from 'mastodon/initial_state';
const FrameWelcome = ({ domain, onNext }) => (
<div className='introduction__frame'>
<div className='introduction__illustration' style={{ background: `url(${logoTransparent}) no-repeat center center / auto 80%` }}>
<img src={screenHello} alt='' />
</div>
<div className='introduction__text introduction__text--centered'>
<h3><FormattedMessage id='introduction.welcome.headline' defaultMessage='First steps' /></h3>
<p><FormattedMessage id='introduction.welcome.text' defaultMessage="Welcome to the fediverse! In a few moments, you'll be able to broadcast messages and talk to your friends across a wide variety of servers. But this server, {domain}, is special—it hosts your profile, so remember its name." values={{ domain: <code>{domain}</code> }} /></p>
</div>
<div className='introduction__action'>
<button className='button' onClick={onNext}><FormattedMessage id='introduction.welcome.action' defaultMessage="Let's go!" /></button>
</div>
</div>
);
FrameWelcome.propTypes = {
domain: PropTypes.string.isRequired,
onNext: PropTypes.func.isRequired,
};
const FrameFederation = ({ onNext }) => (
<div className='introduction__frame'>
<div className='introduction__illustration'>
<img src={screenFederation} alt='' />
</div>
<div className='introduction__text introduction__text--columnized'>
<div>
<h3><FormattedMessage id='introduction.federation.home.headline' defaultMessage='Home' /></h3>
<p><FormattedMessage id='introduction.federation.home.text' defaultMessage='Posts from people you follow will appear in your home feed. You can follow anyone on any server!' /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.federation.local.headline' defaultMessage='Local' /></h3>
<p><FormattedMessage id='introduction.federation.local.text' defaultMessage='Public posts from people on the same server as you will appear in the local timeline.' /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.federation.federated.headline' defaultMessage='Federated' /></h3>
<p><FormattedMessage id='introduction.federation.federated.text' defaultMessage='Public posts from other servers of the fediverse will appear in the federated timeline.' /></p>
</div>
</div>
<div className='introduction__action'>
<button className='button' onClick={onNext}><FormattedMessage id='introduction.federation.action' defaultMessage='Next' /></button>
</div>
</div>
);
FrameFederation.propTypes = {
onNext: PropTypes.func.isRequired,
};
const FrameInteractions = ({ onNext }) => (
<div className='introduction__frame'>
<div className='introduction__illustration'>
<img src={screenInteractions} alt='' />
</div>
<div className='introduction__text introduction__text--columnized'>
<div>
<h3><FormattedMessage id='introduction.interactions.reply.headline' defaultMessage='Reply' /></h3>
<p><FormattedMessage id='introduction.interactions.reply.text' defaultMessage="You can reply to other people's and your own toots, which will chain them together in a conversation." /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.interactions.reblog.headline' defaultMessage='Boost' /></h3>
<p><FormattedMessage id='introduction.interactions.reblog.text' defaultMessage="You can share other people's toots with your followers by boosting them." /></p>
</div>
<div>
<h3><FormattedMessage id='introduction.interactions.favourite.headline' defaultMessage='Favourite' /></h3>
<p><FormattedMessage id='introduction.interactions.favourite.text' defaultMessage='You can save a toot for later, and let the author know that you liked it, by favouriting it.' /></p>
</div>
</div>
<div className='introduction__action'>
<button className='button' onClick={onNext}><FormattedMessage id='introduction.interactions.action' defaultMessage='Finish toot-orial!' /></button>
</div>
</div>
);
FrameInteractions.propTypes = {
onNext: PropTypes.func.isRequired,
};
export default @connect(state => ({ domain: state.getIn(['meta', 'domain']) }))
class Introduction extends React.PureComponent {
static propTypes = {
domain: PropTypes.string.isRequired,
dispatch: PropTypes.func.isRequired,
};
state = {
currentIndex: 0,
};
componentWillMount () {
this.pages = [
<FrameWelcome domain={this.props.domain} onNext={this.handleNext} />,
<FrameFederation onNext={this.handleNext} />,
<FrameInteractions onNext={this.handleFinish} />,
];
}
componentDidMount() {
window.addEventListener('keyup', this.handleKeyUp);
}
componentWillUnmount() {
window.addEventListener('keyup', this.handleKeyUp);
}
handleDot = (e) => {
const i = Number(e.currentTarget.getAttribute('data-index'));
e.preventDefault();
this.setState({ currentIndex: i });
}
handlePrev = () => {
this.setState(({ currentIndex }) => ({
currentIndex: Math.max(0, currentIndex - 1),
}));
}
handleNext = () => {
const { pages } = this;
this.setState(({ currentIndex }) => ({
currentIndex: Math.min(currentIndex + 1, pages.length - 1),
}));
}
handleSwipe = (index) => {
this.setState({ currentIndex: index });
}
handleFinish = () => {
this.props.dispatch(closeOnboarding());
}
handleKeyUp = ({ key }) => {
switch (key) {
case 'ArrowLeft':
this.handlePrev();
break;
case 'ArrowRight':
this.handleNext();
break;
}
}
render () {
const { currentIndex } = this.state;
const { pages } = this;
return (
<div className='introduction'>
<ReactSwipeableViews index={currentIndex} onChangeIndex={this.handleSwipe} disabled={disableSwiping} className='introduction__pager'>
{pages.map((page, i) => (
<div key={i} className={classNames('introduction__frame-wrapper', { 'active': i === currentIndex })}>{page}</div>
))}
</ReactSwipeableViews>
<div className='introduction__dots'>
{pages.map((_, i) => (
<div
key={`dot-${i}`}
role='button'
tabIndex='0'
data-index={i}
onClick={this.handleDot}
className={classNames('introduction__dot', { active: i === currentIndex })}
/>
))}
</div>
</div>
);
}
}
|
pages/index.js | umbchackers/innovategood | import React from 'react';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers';
import TextSection from '../components/TextSection';
import Helmet from 'react-helmet';
import { config } from 'config';
import "./index.css";
import { styles } from '../components/IndexSections/styles';
import LogoHeader from '../components/IndexSections/LogoHeader/';
import ScheduleSection from '../components/IndexSections/ScheduleSection/';
import TracksSection from '../components/IndexSections/TracksSection/';
import FaqSection from '../components/IndexSections/FaqSection/';
import SponsorsSection from '../components/IndexSections/SponsorsSection/';
import PartnersSection from '../components/IndexSections/PartnersSection/';
import FontIcon from 'material-ui/FontIcon';
export default class Index extends React.Component {
render () {
return (
<div>
<Helmet
title={config.siteTitle}
meta={[
{"name": "og:url", "content": "https://innovate.hackumbc.org"},
{"name": "og:type", "content": "event"},
{"name": "og:description", "content": "Innovate Good gives you 24 hours to learn new skills, make friends, create your wildest idea, and share it with the world. Whether you wish to build a website, dabble with Photoshop, create a robotic arm, or develop a game, it's up to you to decide what to learn!"},
{"name": "og:image", "content": "https://innovate.hackumbc.org/images/og.png"},
{"name": "description", "content": "Innovate Good gives you 24 hours to learn new skills, make friends, create your wildest idea, and share it with the world. Whether you wish to build a website, dabble with Photoshop, create a robotic arm, or develop a game, it's up to you to decide what to learn!"},
{"name": "keywords", "content": "hackathon, hackumbc, innovate good"},
]}
/>
<LogoHeader />
<TextSection icon="info_outline" title="About">
Innovate Good gives you 24 hours to learn new skills, make friends, create your wildest idea, and share it with the world. Whether you wish to build a website, dabble with Photoshop, create a robotic arm, or develop a game, it's up to you to decide what to learn!
</TextSection>
<ScheduleSection />
<TracksSection />
<FaqSection />
<SponsorsSection />
<PartnersSection />
<h4 className="footer">
Built with
<FontIcon color="red" className="material-icons custom-heart">favorite_border</FontIcon>
by HackUMBC Organizers
</h4>
</div>
)
}
}
|
redux-form/simple/jsx/FieldArrayForm.js | Muzietto/react-playground | import React from 'react';
import {connect} from 'react-redux';
import {Field, FieldArray, reduxForm} from 'redux-form';
const mapStateToProps = state => {
return {
// mandatory key name
initialValues: state.submitted.fieldArray, // pull initial values from submitted reducer
};
};
let FieldArrayForm = props => {
const {handleSubmit, onReset} = props;
return (
<div className="form-div">
<h3>fieldArray form</h3>
<form onSubmit={handleSubmit}>
<FieldArray
name="campoMatrice"
component={userFields}/>
<button type="submit">Submit</button>
<button
type="button"
onClick={onReset}>Reset
</button>
</form>
</div>
);
};
FieldArrayForm = reduxForm({form: 'fieldArray'})(FieldArrayForm);
export default connect(mapStateToProps, () => ({}))(FieldArrayForm);
// contains Field
function userFields(props) {
// find out purpose of meta (cfr FieldArraysForm in redux-form examples)
let {fields, meta} = props;
return (
<ul>
<li>
<button type="button" onClick={() => fields.push({})}>
Add personal trait
</button>
</li>
{fields.map((trait, index) => (
<li key={index}>
<button
type="button"
onClick={() => fields.remove(index)}>
Delete trait
</button>
<Field
name={`${trait}.key`}
type="text"
placeholder="insert a key"
component={userField}
/>
<Field
name={`${trait}.value`}
type="text"
placeholder="insert a value"
component={userField}
/>
</li>
))}
</ul>
);
};
// defines Field
function userField({input, placeholder, type}) {
return (
<div>
<div>
<input {...input} type={type} placeholder={placeholder}/>
</div>
</div>
);
}
|
react/features/video-menu/components/web/GrantModeratorButton.js | gpolitis/jitsi-meet | /* @flow */
import React from 'react';
import ContextMenuItem from '../../../base/components/context-menu/ContextMenuItem';
import { translate } from '../../../base/i18n';
import { IconCrown } from '../../../base/icons';
import { connect } from '../../../base/redux';
import AbstractGrantModeratorButton, {
_mapStateToProps,
type Props
} from '../AbstractGrantModeratorButton';
declare var interfaceConfig: Object;
/**
* Implements a React {@link Component} which displays a button for granting
* moderator to a participant.
*/
class GrantModeratorButton extends AbstractGrantModeratorButton {
/**
* Instantiates a new {@code GrantModeratorButton}.
*
* @inheritdoc
*/
constructor(props: Props) {
super(props);
this._handleClick = this._handleClick.bind(this);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const { t, visible } = this.props;
if (!visible) {
return null;
}
return (
<ContextMenuItem
accessibilityLabel = { t('toolbar.accessibilityLabel.grantModerator') }
className = 'grantmoderatorlink'
icon = { IconCrown }
// eslint-disable-next-line react/jsx-handler-names
onClick = { this._handleClick }
text = { t('videothumbnail.grantModerator') } />
);
}
_handleClick: () => void;
}
export default translate(connect(_mapStateToProps)(GrantModeratorButton));
|
app/components/LoadingIndicator/index.js | anhldbk/react-boilerplate | import React from 'react';
import Circle from './Circle';
import Wrapper from './Wrapper';
const LoadingIndicator = () => (
<Wrapper>
<Circle />
<Circle rotate={30} delay={-1.1} />
<Circle rotate={60} delay={-1} />
<Circle rotate={90} delay={-0.9} />
<Circle rotate={120} delay={-0.8} />
<Circle rotate={150} delay={-0.7} />
<Circle rotate={180} delay={-0.6} />
<Circle rotate={210} delay={-0.5} />
<Circle rotate={240} delay={-0.4} />
<Circle rotate={270} delay={-0.3} />
<Circle rotate={300} delay={-0.2} />
<Circle rotate={330} delay={-0.1} />
</Wrapper>
);
export default LoadingIndicator;
|
src/pages/qrcode/result/index.js | yiweimatou/admin-antd | import React, { Component } from 'react';
import { Button, message, Modal } from 'antd'
import { download } from 'services/qrcode'
import style from './index.css'
class QRCodeResult extends Component {
clickHandler = () => {
const { list } = this.props
download({
rcmd_code_list: list
}).then((data) => {
window.open(data.path)
}).catch(error => message.error(error))
}
render() {
const { name1, name2, num, visible, onCancel } = this.props
return (
<Modal visible={visible} footer={null} onCancel={onCancel}>
<div className={style.container}>
<h2>二维码已生成</h2>
<div className={style.content}>
<span>辅导员: {name1}</span>
<span>业务员: {name2}</span>
<span>数量: {num}</span>
</div>
<Button type="primary" onClick={this.clickHandler}>批量下载二维码</Button>
</div>
</Modal>
);
}
}
export default QRCodeResult
|
src/components/Switch/Switch.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
const { prefix } = settings;
const Switch = props => {
const {
className,
index,
name,
onClick,
onKeyDown,
selected,
text,
...other
} = props;
const handleClick = e => {
e.preventDefault();
onClick({ index, name, text });
};
const handleKeyDown = e => {
const key = e.key || e.which;
if (key === 'Enter' || key === 13 || key === ' ' || key === 32) {
onKeyDown({ index, name, text });
}
};
const classes = classNames(className, `${prefix}--content-switcher-btn`, {
[`${prefix}--content-switcher--selected`]: selected,
});
const commonProps = {
onClick: handleClick,
onKeyDown: handleKeyDown,
className: classes,
};
return (
<button {...other} {...commonProps}>
<span className={`${prefix}--content-switcher__label`}>{text}</span>
</button>
);
};
Switch.propTypes = {
/**
* Specify an optional className to be added to your Switch
*/
className: PropTypes.string,
/**
* The index of your Switch in your ContentSwitcher that is used for event handlers.
* Reserved for usage in ContentSwitcher
*/
index: PropTypes.number,
/**
* Provide the name of your Switch that is used for event handlers
*/
name: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
/**
* A handler that is invoked when a user clicks on the control.
* Reserved for usage in ContentSwitcher
*/
onClick: PropTypes.func,
/**
* A handler that is invoked on the key down event for the control.
* Reserved for usage in ContentSwitcher
*/
onKeyDown: PropTypes.func,
/**
* Whether your Switch is selected. Reserved for usage in ContentSwitcher
*/
selected: PropTypes.bool,
/**
* Provide the contents of your Switch
*/
text: PropTypes.string.isRequired,
};
Switch.defaultProps = {
selected: false,
text: 'Provide text',
onClick: () => {},
onKeyDown: () => {},
};
export default Switch;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.