path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
lib/editor/components/editors/ImageManager.js | jirokun/survey-designer-js | /* eslint-env browser */
import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import classNames from 'classnames';
import $ from 'jquery';
import S from 'string';
import '../../css/imageManager.scss';
/**
* TinyMCEからも画像管理からも使うので、プレーンなReactコンポーネントとして実装する。Reduxは使わない
*/
export default class ImageManager extends Component {
constructor(props) {
super(props);
this.bindedHandleInsertFormSubmitMessage = this.handleInsertFormSubmitMessage.bind(this);
this.state = {
image: null,
size: 'normal',
clickAction: 'none',
clickRequired: false,
};
}
componentDidMount() {
window.addEventListener('message', this.bindedHandleInsertFormSubmitMessage, false);
}
componentWillUnmount() {
window.removeEventListener('message', this.bindedHandleFormSubmitMessage);
}
getFormData($form) {
const ar = $form.serializeArray();
const params = {};
$.map(ar, (n) => { params[n.name] = n.value; });
return params;
}
handleChangeForm(e) {
const target = e.target;
const name = target.name;
if (target.type === 'checkbox') {
this.setState({ [name]: target.checked });
} else {
const value = target.value;
const state = {};
if (name === 'clickAction' && value === 'none') {
state.clickRequired = false;
}
state[name] = value;
this.setState(state);
}
}
handleUploadFiles(e) {
const { uploadImagesFunc } = this.props;
e.preventDefault();
if (S(this.imageFileListEl.value).isEmpty()) {
alert('ファイルが選択されていません');
return;
}
const formEl = e.target;
const formData = new FormData(this.uploadFormEl);
uploadImagesFunc(formData);
formEl.reset();
}
handleInsertFormSubmitMessage(e) {
if (e.origin !== location.origin) {
alert('オリジンが一致しません');
return;
}
if (e.data.type !== 'submitInsertForm') return;
if (this.state.image === null) {
alert('挿入する画像が選択されていません');
return;
}
const params = this.state;
this.props.insertImageFunc({ params });
}
handleChangeUploadFiles(e) {
const files = e.target.files;
for (let i = 0, len = files.length; i < len; i++) {
const file = files[i];
if (file.size > 1024 * 1024 * 3) {
e.target.value = null;
alert(`${file.name}のファイルサイズが3MBを超えています`);
return;
}
}
}
handleClickDelete(image) {
this.props.deleteImageFunc(image);
}
handleClickImage(image) {
this.setState({ image });
}
submitInsertForm() {
const param = this.getFormData($(this.insertFormEl));
window.parent.postMessage({ type: 'insertImage', value: JSON.stringify(param) }, '*');
}
render() {
const imageList = this.props.imageList;
const image = this.state.image;
return (
<div>
<form ref={(el) => { this.uploadFormEl = el; }} className="upload-form" onSubmit={e => this.handleUploadFiles(e)}>
<fieldset className="container-fluid">
<legend>画像のアップロード</legend>
<div className="row">
<div className="col-sm-12">
画像は複数まとめてアップロードできます。<br />
ファイルサイズは3MBまでです。<br />
対応ファイル形式は(JPG, GIF, PNG)です。
</div>
</div>
<div className="row">
<div className="col-sm-12">
<input ref={(el) => { this.imageFileListEl = el; }} name="imageFileList" type="file" onChange={e => this.handleChangeUploadFiles(e)} accept="image/jpeg,image/gif,image/png" multiple />
<Button type="submit">アップロード</Button>
</div>
</div>
</fieldset>
</form>
<form ref={(el) => { this.insertFormEl = el; }} onChange={e => this.handleChangeForm(e)}>
<fieldset className="container-fluid">
<legend>画像の挿入</legend>
<div className="row">
<div className="col-sm-4">
<div className="form-group">
<label>画像サイズ</label>
<div className="radio"><label><input type="radio" name="size" value="normal" checked={this.state.size === 'normal'} /> 通常サイズ(横幅最大600px)</label></div>
<div className="radio"><label><input type="radio" name="size" value="thumb" checked={this.state.size === 'thumb'} /> サムネイル(横幅最大150px)</label></div>
</div>
</div>
<div className="col-sm-4">
<div className="form-group">
<label>クリック時の動作</label>
<div className="radio"><label><input type="radio" name="clickAction" value="none" checked={this.state.clickAction === 'none'} /> 何もしない </label></div>
<div className="radio"><label><input type="radio" name="clickAction" value="original" checked={this.state.clickAction === 'original'} /> オリジナル画像を表示</label></div>
<div className="radio"><label><input type="radio" name="clickAction" value="normal" checked={this.state.clickAction === 'normal'} /> 通常サイズを表示(横幅最大600px)</label></div>
<div>クリック時の画像サイズが画面幅を超える場合拡大できます</div>
</div>
</div>
<div className="col-sm-4">
<div className="form-group">
<label>その他</label>
<div className="checkbox">
<label>
<input type="checkbox" name="clickRequired" checked={this.state.clickRequired} disabled={this.state.clickAction === 'none'} /> クリック必須
</label>
</div>
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<div className="form-group">
<label>画像のタイトル</label>
<input type="text" name="title" className="form-control" />
</div>
</div>
</div>
<div className="row">
<div className="col-sm-12">
<div className="form-group">
<label>挿入する画像</label>
<div className="image-container">
{
imageList.map((img) => {
const isSelected = image && image.id === img.id;
return (
<div key={img.id} className="image-block">
<a
className={classNames('image-link', { selected: isSelected })}
href="javascript:void(0)"
onClick={() => this.handleClickImage(img)}
>
<img src={img.thumbnailUrl} alt={img.title} />
</a>
<Button bsStyle="danger" bsSize="xs" className="pull-left" onClick={() => this.handleClickDelete(img)}>削除</Button>
</div>
);
})
}
</div>
</div>
</div>
</div>
</fieldset>
</form>
</div>
);
}
}
|
src/svg-icons/device/brightness-high.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBrightnessHigh = (props) => (
<SvgIcon {...props}>
<path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-3.31 0-6-2.69-6-6s2.69-6 6-6 6 2.69 6 6-2.69 6-6 6zm0-10c-2.21 0-4 1.79-4 4s1.79 4 4 4 4-1.79 4-4-1.79-4-4-4z"/>
</SvgIcon>
);
DeviceBrightnessHigh = pure(DeviceBrightnessHigh);
DeviceBrightnessHigh.displayName = 'DeviceBrightnessHigh';
export default DeviceBrightnessHigh;
|
elements/Polyline.js | msand/react-native-svg | import React from 'react';
import Path from './Path';
import Shape from './Shape';
import extractPolyPoints from '../lib/extract/extractPolyPoints';
export default class Polyline extends Shape {
static displayName = 'Polyline';
static defaultProps = {
points: '',
};
setNativeProps = props => {
const { points } = props;
if (points) {
props.d = `M${extractPolyPoints(points)}`;
}
this.root.setNativeProps(props);
};
render() {
const { props } = this;
const { points } = props;
return (
<Path
ref={this.refMethod}
d={`M${extractPolyPoints(points)}`}
{...props}
/>
);
}
}
|
src/components/post/tools/subscribe.js | Lokiedu/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2016 Loki Education (Social Enterprise)
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 React from 'react';
export default class PostSubscribe extends React.Component {
shouldComponentUpdate(nextProps) {
return nextProps !== this.props;
}
handleToggleSubscription = async (e) => {
const { postId } = this.props;
if (e.target.checked) {
await this.props.onSubscribeToPost(postId);
} else {
await this.props.onUnsubscribeFromPost(postId);
}
};
render() {
if (!this.props.is_logged_in) {
return false;
}
const { subscriptions, postId } = this.props;
const isSubscribed = subscriptions.includes(postId);
return (
<label title="Recieve email notifications about new comments">
<span className="checkbox__label-left">Subscribe</span>
<input
checked={isSubscribed}
type="checkbox"
onClick={this.handleToggleSubscription}
/>
</label>
);
}
}
|
src/js/components/Menu.js | mmmigalll/react-starter | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { NavLink, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
class Menu extends Component {
render() {
return (
<div className="inner-resize">
<div
className="logo"
>
<img title="There will be some image" />
</div>
<ul className="topUl">
<NavLink
to="/home"
>
<li>Home</li>
</NavLink>
<NavLink
to="/industries"
>
<li>Industries</li>
</NavLink>
<NavLink
to="/login"
>
<li>Login</li>
</NavLink>
</ul>
</div >
);
}
}
export default withRouter(Menu);
|
src/scripts/pages/Index/Index.js | lenshq/lens_front | import React from 'react';
import './styles.css';
export default class Index {
render() {
return (
<section className='page page--index'>
<header className='promo'>
<div className='promo__content'>
<h1 className='promo__title'>LensHQ</h1>
<p className='promo__desc'>
Smart profiling tool for Rails apps.
</p>
</div>
<a href={`${settings.apiRoot}/auth/github`} className='button button--bordered'>
<span className='icon icon--large icon--github'></span>
<span className='button__label'>Sign in with GitHub</span>
</a>
</header>
</section>
);
}
}
|
app/javascript/mastodon/features/mutes/index.js | sylph-sin-tyaku/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountContainer from '../../containers/account_container';
import { fetchMutes, expandMutes } from '../../actions/mutes';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.mutes', defaultMessage: 'Muted users' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'mutes', 'items']),
hasMore: !!state.getIn(['user_lists', 'mutes', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Mutes extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
hasMore: PropTypes.bool,
accountIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchMutes());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandMutes());
}, 300, { leading: true });
render () {
const { intl, shouldUpdateScroll, hasMore, accountIds, multiColumn } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.mutes' defaultMessage="You haven't muted any users yet." />;
return (
<Column bindToDocument={!multiColumn} icon='volume-off' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='mutes'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{accountIds.map(id =>
<AccountContainer key={id} id={id} />
)}
</ScrollableList>
</Column>
);
}
}
|
app/components/Known.js | chena/kiminonawa-web | import React from 'react';
import axios from 'axios';
import Button from 'muicss/lib/react/button';
import Container from 'muicss/lib/react/container';
import Divider from 'muicss/lib/react/divider';
import Row from 'muicss/lib/react/row';
import Col from 'muicss/lib/react/col';
import { Link } from 'react-router';
import Case from './Case';
import styles from '../styles.css';
import knownIcon from '../images/known_icon.png';
// sample data
const sampleData = [
{
"_id":"57d77205e2f4ec0e00304cea",
"caseId":"1473737221646",
"count":1,
"organization":"Rutgers University ",
"organizationEmail":null,
"situation":"International student orientation: Trip to philly",
"userName":"Shih-Yen Lin",
"userEmail":"suntop.lin@gmail.com",
"__v":0,
"date":"2016-09-13T03:27:01.590Z",
"status":"init",
"url":"",
"imgUrl":"https://ucarecdn.com/ca398641-4236-4481-962a-c9b0fd7e99e4/"
},
{
"_id":"581e89988ea2550e0014b5ed",
"caseId":"1462835747800",
"count":1,
"organization":"ICIJ (國際調查記者聯盟)",
"organizationEmail":"https://www.icij.org/email/node/190/field_email",
"situation":"巴拿馬文件->以國家搜尋",
"__v":0,
"date":"2016-11-06T01:38:32.222Z",
"status":"init",
"url":"https://offshoreleaks.icij.org/",
"imgUrl":"https://ucarecdn.com/aac30e04-9405-4f08-8e79-1d99808d26c5/"
}
];
export default class Known extends React.Component {
constructor(props) {
super(props);
this.state = {
data: []
};
}
componentDidMount() {
axios.get('http://localhost:3001/api/topics')
.then(response => {
this.setState({data: response.data});
});
}
_getCases() {
const {data} = this.state;
const records = data && !!data.length ?
data : sampleData;
return records.map(record => (
<Case situation={record.situation}
url={record.url}
imgUrl={record.imgUrl}
key={record._id} />
));
}
render() {
const cases = this._getCases();
return (
<div>
<Container className={styles.pageBody}>
<Row className={styles.pageTop}>
<Col md="4" md-offset="4">
<img src={knownIcon} className={styles.icon} />
<h3 className={styles.heading}> 已知回報 </h3>
<p className={styles.bodyText}>
本頁為我們已收到的民眾通報清單,所有被舉報的網站都已收到由台灣人公共事務會 Formosan Association for Public Affairs 寄出的更改名稱要求,
如果您願意為此運動盡一份力,請按“加入舉報”由您的個人信箱寄出抗議信,讓負責單位聽到更多台灣人的聲音。
</p>
</Col>
</Row>
<Row>
{cases}
</Row>
</Container>
</div>
);
}
}
|
src/svg-icons/action/view-list.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewList = (props) => (
<SvgIcon {...props}>
<path d="M4 14h4v-4H4v4zm0 5h4v-4H4v4zM4 9h4V5H4v4zm5 5h12v-4H9v4zm0 5h12v-4H9v4zM9 5v4h12V5H9z"/>
</SvgIcon>
);
ActionViewList = pure(ActionViewList);
ActionViewList.displayName = 'ActionViewList';
ActionViewList.muiName = 'SvgIcon';
export default ActionViewList;
|
src/containers/Main.js | afikris6/afikris6.github.io | import React from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { calcDistances } from '../helpers/location';
import * as MainActions from '../reducers/main';
import LocationList from '../components/LocationList';
import AddButton from '../components/AddButton';
const Main = (props) => {
const { actions, current, settings, demo, geo: { latitude, longitude, orientation } } = props;
return (
<div>
{settings.detailed && latitude &&
<div className="fixed-bottom"
style={{ left: '15px', backgroundColor: 'white' }} >
({latitude.toFixed(4) }, {longitude.toFixed(4) }) {orientation}°
</div>
}
<LocationList {...props} />
{!current.editing && !demo &&
(<AddButton
loading={!latitude}
onClick={() => actions.showNewLocation(true)}
/>)}
</div>);
};
const mapStateToProps = ({ main, settings }) => ({
...main,
settings,
locations: main.locations.map(calcDistances(main.geo.latitude, main.geo.longitude))
});
Main.propTypes = {
demo: PropTypes.bool,
dialog: PropTypes.object,
route: PropTypes.object,
geo: PropTypes.object,
settings: PropTypes.object,
current: PropTypes.object,
actions: PropTypes.object
};
const mapDispatchToProps = (dispatch) => ({
actions: bindActionCreators(MainActions, dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(Main);
|
react-universal-web-apps-simple/app/components/dashboard/Dashboard.js | joekraken/react-demos | import React from 'react';
export default class Dashboard extends React.Component {
render() {
return (
<main className="app-content dashboard">
{this.props.children}
</main>
);
}
}
|
packages/react-scripts/fixtures/kitchensink/template/src/features/webpack/SassModulesInclusion.js | jdcrensh/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import styles from './assets/sass-styles.module.sass';
import indexStyles from './assets/index.module.sass';
const SassModulesInclusion = () => (
<div>
<p className={styles.sassModulesInclusion}>SASS Modules are working!</p>
<p className={indexStyles.sassModulesIndexInclusion}>
SASS Modules with index are working!
</p>
</div>
);
export default SassModulesInclusion;
|
src/svg-icons/action/stars.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionStars = (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 2zm4.24 16L12 15.45 7.77 18l1.12-4.81-3.73-3.23 4.92-.42L12 5l1.92 4.53 4.92.42-3.73 3.23L16.23 18z"/>
</SvgIcon>
);
ActionStars = pure(ActionStars);
ActionStars.displayName = 'ActionStars';
export default ActionStars;
|
src/components/ModalWrapper/ModalWrapper.js | kuao775/mandragora | import React from 'react';
function ModalWrapper(WrappedModal, WrappedComponent) {
return class modalWrapper extends React.Component {
state = { modalOpen: false };
handleOpen = () => this.setState({ modalOpen: true });
handleClose = () => this.setState({ modalOpen: false });
render() {
return (
<div>
<WrappedComponent onClick={this.handleOpen} {...this.props} />
<WrappedModal
{...this.props}
open={this.state.modalOpen}
onClose={this.handleClose}
/>
</div>
);
}
};
}
export default ModalWrapper;
|
src/routes/contact/index.js | agiron123/react-starter-kit-TDDOList | /**
* 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 Contact from './Contact';
export default {
path: '/contact',
action() {
return <Contact />;
},
};
|
app/jsx/files/MoveDialog.js | venturehive/canvas-lms | /*
* Copyright (C) 2015 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas 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, version 3 of the License.
*
* Canvas 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 I18n from 'i18n!react_files'
import React from 'react'
import MoveDialog from 'compiled/react_files/components/MoveDialog'
import Modal from 'jsx/shared/modal'
import ModalContent from 'jsx/shared/modal-content'
import ModalButtons from 'jsx/shared/modal-buttons'
import BBTreeBrowser from 'jsx/files/BBTreeBrowser'
import classnames from 'classnames'
MoveDialog.renderMoveButton = function () {
const buttonClassNames = classnames({
'disabled': !this.state.destinationFolder,
'btn': true,
'btn-primary': true
});
if (this.state.isCopyingFile) {
return (
<button
type='submit'
aria-disabled={!this.state.destinationFolder}
className={buttonClassNames}
data-text-while-loading={I18n.t('Copying...')}
>
{I18n.t('Copy to Folder')}
</button>
);
} else {
return (
<button
type='submit'
aria-disabled={!this.state.destinationFolder}
className={buttonClassNames}
data-text-while-loading={I18n.t('Moving...')}
>
{I18n.t('Move')}
</button>
);
}
};
MoveDialog.render = function () {
return (
<Modal
className='ReactModal__Content--canvas ReactModal__Content--mini-modal'
overlayClassName='ReactModal__Overlay--canvas'
ref='canvasModal'
isOpen={this.state.isOpen}
title={this.getTitle()}
onRequestClose={this.closeDialog}
onSubmit={this.submit}
>
<ModalContent>
<BBTreeBrowser
rootFoldersToShow={this.props.rootFoldersToShow}
onSelectFolder={this.onSelectFolder}
/>
</ModalContent>
<ModalButtons>
<button
type='button'
className='btn'
onClick={this.closeDialog}
>
{I18n.t('Cancel')}
</button>
{this.renderMoveButton()}
</ModalButtons>
</Modal>
);
};
export default React.createClass(MoveDialog)
|
src/modules/teamwork/index.js | skydaya/react-sell | /**
* Created by dllo on 17/8/28.
*/
import React from 'react'
import ReactDOM from 'react-dom'
import App from './app'
ReactDOM.render(
<App />,
document.getElementById('teamwork')
)
|
demo/components/Header.js | philpl/react-live | import React from 'react';
import styled from 'styled-components';
import * as polished from 'polished';
import { ProjectBadge } from 'formidable-oss-badges';
import { background, blue } from '../utils/colors';
const SubTitle = styled.h2`
font-size: ${polished.modularScale(1)};
font-weight: normal;
color: ${blue};
margin: 0;
margin-left: ${polished.rem(20)};
letter-spacing: ${polished.rem(0.3)};
line-height: 1.5;
@media (max-width: 600px) {
margin-left: 0;
margin-top: ${polished.rem(30)};
}
`;
const StyledProjectBadge = styled(ProjectBadge)`
height: 230px;
`;
const Title = styled.h1`
font-weight: normal;
font-size: ${polished.modularScale(4)};
line-height: 1.1;
margin: 0;
margin-left: ${polished.rem(20)};
@media (max-width: 600px) {
margin-left: 0;
margin-top: ${polished.rem(25)};
margin-top: ${polished.rem(25)};
}
`;
const TitleRow = styled.div`
display: flex;
align-items: center;
justify-content: center;
flex-direction: row;
text-align: left;
margin: ${polished.rem(30)} 0;
@media (max-width: 600px) {
flex-direction: column;
text-align: center;
}
`;
const Description = styled.div`
margin: ${polished.rem(50)};
text-align: center;
font-size: ${polished.modularScale(1)};
color: ${blue};
line-height: 1.5;
@media (max-width: 600px) {
margin: ${polished.rem(50)} 0;
}
`;
const Button = styled.a`
display: inline-block;
width: auto;
padding: ${polished.rem(10)} ${polished.rem(20)};
text-decoration: none;
border-radius: ${polished.rem(3)};
background: ${blue};
color: ${background};
margin: ${polished.rem(30)} 0;
`;
const Container = styled.div`
width: 100%;
margin-bottom: ${polished.rem(60)};
`;
const Header = () => (
<Container>
<TitleRow>
<StyledProjectBadge
color="#f677e1"
abbreviation="Rl"
description="React Live"
/>
<div>
<Title>React Live</Title>
<SubTitle>A flexible playground for live editing React code</SubTitle>
</div>
</TitleRow>
<Description>
<div>
Easily render live editable React components with server-side rendering
support and a tiny bundle size, thanks to Bublé and a Prism.js-based
editor.
</div>
<Button
href="https://github.com/FormidableLabs/react-live"
target="_blank"
rel="noopener"
>
GitHub
</Button>
</Description>
</Container>
);
export default Header;
|
app/components/Demo/ChildrenComponent/index.js | jakubrohleder/aurelius | import React from 'react';
import styles from './styles.css';
export default function ChildrenComponent(props) {
const { children } = props;
return (
<div className={styles.wrapper}>
<h4>ChildrenComponent</h4>
{children}
</div>
);
}
ChildrenComponent.propTypes = {
children: React.PropTypes.node.isRequired,
};
|
blueocean-material-icons/src/js/components/svg-icons/image/panorama-wide-angle.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImagePanoramaWideAngle = (props) => (
<SvgIcon {...props}>
<path d="M12 6c2.45 0 4.71.2 7.29.64.47 1.78.71 3.58.71 5.36 0 1.78-.24 3.58-.71 5.36-2.58.44-4.84.64-7.29.64s-4.71-.2-7.29-.64C4.24 15.58 4 13.78 4 12c0-1.78.24-3.58.71-5.36C7.29 6.2 9.55 6 12 6m0-2c-2.73 0-5.22.24-7.95.72l-.93.16-.25.9C2.29 7.85 2 9.93 2 12s.29 4.15.87 6.22l.25.89.93.16c2.73.49 5.22.73 7.95.73s5.22-.24 7.95-.72l.93-.16.25-.89c.58-2.08.87-4.16.87-6.23s-.29-4.15-.87-6.22l-.25-.89-.93-.16C17.22 4.24 14.73 4 12 4z"/>
</SvgIcon>
);
ImagePanoramaWideAngle.displayName = 'ImagePanoramaWideAngle';
ImagePanoramaWideAngle.muiName = 'SvgIcon';
export default ImagePanoramaWideAngle;
|
spec/components/chip.js | rubenmoya/react-toolbox | import React from 'react';
import Avatar from '../../components/avatar';
import Chip from '../../components/chip';
import style from '../style';
class ChipTest extends React.Component {
state = {
deleted: false,
};
handleDeleteClick = () => {
this.setState({
deleted: true,
});
};
render() {
return (
<section>
<h5>Chips</h5>
<p>Chips can be deletable and have an avatar.</p>
<Chip>Example chip</Chip>
<Chip>
<span style={{ textDecoration: 'line-through' }}>Standard</span>
<strong>Custom</strong> chip <small>(custom markup)</small>
</Chip>
{
this.state.deleted ? null : (
<Chip
deletable
onDeleteClick={this.handleDeleteClick}
>
Deletable Chip
</Chip>
)
}
<Chip>
<Avatar style={{ backgroundColor: 'deepskyblue' }} icon="folder" />
<span>Avatar Chip</span>
</Chip>
<Chip>
<Avatar title="A" /><span>Initial chip</span>
</Chip>
<Chip>
<Avatar><img src="https://placeimg.com/80/80/animals" /></Avatar>
<span>Image contact chip</span>
</Chip>
<div className={style.chipTruncateWrapper}>
<Chip deletable>
Truncated chip with long label. Lorem ipsum Amet quis mollit Excepteur id dolore.
</Chip>
</div>
</section>
);
}
}
export default ChipTest;
|
examples/js/custom/delete-button/fully-custom-delete-button.js | echaouchna/react-bootstrap-tab | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-alert: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn, InsertButton } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class FullyCustomInsertButtonTable extends React.Component {
createCustomDeleteButton = (onBtnClick) => {
return (
<button style={ { color: 'red' } } onClick={ onBtnClick }>Delete it!!!</button>
);
}
render() {
const options = {
deleteBtn: this.createCustomDeleteButton
};
const selectRow = {
mode: 'checkbox'
};
return (
<BootstrapTable selectRow={ selectRow } data={ products } options={ options } deleteRow>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
artifact/components/admin/menu/index.js | uinika/saga | import React from 'react';
class AdminMenu extends React.Component {
componentDidMount() {
console.log('AdminMenu');
};
render() {
return (
<div id='admin-Menu'>
<h1>AdminMenu</h1>
</div>
);
}
};
export default AdminMenu;
|
styleguide/screens/Patterns/Medallion/Medallion.js | NGMarmaduke/bloom | import React from 'react';
import cx from 'classnames';
import Medallion from '../../../../components/Medallion/Medallion';
import Specimen from '../../../components/Specimen/Specimen';
import { H, T, C } from '../../../components/Scaffold/Scaffold';
import css from './Medallion.css';
import m from '../../../../globals/modifiers.css';
const MedallionDocumentation = () => (
<div>
<H level={ 1 }>Medallion</H>
<T elm="p" className={ cx(m.mtr, m.largeI, m.demi) }>
Medallions are used to display a numerical value alongside other
information, such as a label.
</T>
<T elm="p" className={ m.mtLgIi }>
Medallions currently exist in 2 variations, <C>light</C> for dark
backgrounds, and <C>dark</C> for lighter backgrounds.
</T>
<div className={ css.group }>
<Specimen
classNames={ {
root: css.specimenRoot,
specimenContainer: m.par,
} }
code={ '<Medallion>10</Medallion>' }
variant="dark"
>
<Medallion>10</Medallion>
</Specimen>
<Specimen
classNames={ {
root: css.specimenRoot,
specimenContainer: m.par,
} }
code={ '<Medallion variant="dark">10</Medallion>' }
>
<Medallion variant="dark">10</Medallion>
</Specimen>
</div>
</div>
);
export default MedallionDocumentation;
|
app/javascript/mastodon/features/ui/util/react_router_helpers.js | Ryanaka/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { Switch, Route } from 'react-router-dom';
import ColumnLoading from '../components/column_loading';
import BundleColumnError from '../components/bundle_column_error';
import BundleContainer from '../containers/bundle_container';
// Small wrapper to pass multiColumn to the route components
export class WrappedSwitch extends React.PureComponent {
render () {
const { multiColumn, children } = this.props;
return (
<Switch>
{React.Children.map(children, child => React.cloneElement(child, { multiColumn }))}
</Switch>
);
}
}
WrappedSwitch.propTypes = {
multiColumn: PropTypes.bool,
children: PropTypes.node,
};
// Small Wrapper to extract the params from the route and pass
// them to the rendered component, together with the content to
// be rendered inside (the children)
export class WrappedRoute extends React.Component {
static propTypes = {
component: PropTypes.func.isRequired,
content: PropTypes.node,
multiColumn: PropTypes.bool,
componentParams: PropTypes.object,
};
static defaultProps = {
componentParams: {},
};
renderComponent = ({ match }) => {
const { component, content, multiColumn, componentParams } = this.props;
return (
<BundleContainer fetchComponent={component} loading={this.renderLoading} error={this.renderError}>
{Component => <Component params={match.params} multiColumn={multiColumn} {...componentParams}>{content}</Component>}
</BundleContainer>
);
}
renderLoading = () => {
return <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { component: Component, content, ...rest } = this.props;
return <Route {...rest} render={this.renderComponent} />;
}
}
|
React Native/Demos/address_book/Views/manager/modifyPassword.js | AngryLi/ResourceSummary | /**
* Created by Liyazhou on 16/8/28.
*/
import React from 'react';
import {View, Text, ScrollView, StyleSheet, TouchableOpacity, TextInput, AlertIOS, AsyncStorage} from 'react-native';
import Util from './../util';
import Service from './../service';
export default class ModifyPassword extends React.Component {
_getOldPassword(val) {
this.setState({
oldPassword: val,
});
}
_getNewPassword(val) {
this.setState({
newPassword: val,
});
}
_resetPassword() {
let path = Service.host + Service.updatePassword;
let that = this;
AsyncStorage.getItem('token', function (err, data) {
if (!err) {
Util.post(path,{token: data, password: this.state.newPassword, oldPassword:this.state.oldPassword}, function (data) {
if (data.status) {
AlertIOS.alert('成功', data.data);
} else {
AlertIOS.alert('失败', data.data);
}
});
} else {
AlertIOS.alert('失败', data.data);
}
})
}
render() {
return <ScrollView>
<View style={{height:35, marginTop:30}}>
<TextInput style={styles.input}
password={true}
placeholder={'原始密码'}
onChangeText={(text)=>this._getOldPassword(text)}>
</TextInput>
</View>
<View style={{height:35, top:5}}>
<TextInput style={styles.input}
password={true}
onChangeText={(text)=>this._getNewPassword(text)}
placeholder={'新密码'}></TextInput>
</View>
<View>
<TouchableOpacity onPress={()=>this._resetPassword()}>
<View style={styles.btn}>
<Text style={{color: '#fff'}}>
修改密码
</Text>
</View>
</TouchableOpacity>
</View>
</ScrollView>
}
}
const styles = StyleSheet.create({
input: {
flex:1,
marginLeft:20,
marginRight:20,
height:50,
borderWidth:1,
borderColor:'#ddd',
borderRadius:4,
paddingLeft:5,
fontSize:13,
},
btn: {
justifyContent:'center',
alignItems:'center',
marginTop:20,
backgroundColor:'#1db8ff',
height:38,
marginLeft:20,
marginRight:20,
borderRadius:4,
},
}); |
techCurriculum/ui/solutions/7.1/src/components/Message.js | tadas412/EngineeringEssentials | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
**/
import React from 'react';
function Message(props) {
return (
<div className='message-text'>
<p>{props.text}</p>
</div>
);
}
export default Message;
|
src/components/home/home.js | ebenezer-unitec/ReactNativeSBO | import React from 'react';
import styles from '../../themes/styles';
import {getRoutes, getCardsInformation, postTransaction} from '../api/requester';
import {write, readDir, unlink, exist, mkdir, read} from '../FileSystem/fileSystem';
import{
View,
Text,
StyleSheet,
TouchableOpacity,
Dimensions,
Image,
ActivityIndicator,
NetInfo
} from 'react-native';
import {
Button,
Content,
Container,
Icon,
Header,
Title
} from 'native-base'
import {
Actions,
} from 'react-native-router-flux';
const deviceHeight = Dimensions.get('window').height;
//const background = require('../imgs/shadow.png');
// write the file
let RNFS = require('react-native-fs')
class Home extends React.Component {
constructor(){
super();
this.state ={
rutas :[],
isLoading: false,
isConnected: false
}
this.navigate = this.navigate.bind(this);
}
setIsConnected(isConnected){
this.setState(
{
rutas :this.state.rutas,
isLoading: this.state.isLoading,
isConnected: isConnected
}
)
//this.state.isConnected = isConnected;
//console.log("is conected "+isConnected);
if(!isConnected){
alert("Se ha perdido la conexión del internet.");
}
}
componentWillMount() {
const dispatchConnected = isConnected => (this.setIsConnected(isConnected));
NetInfo.isConnected.fetch().then(
isConnected => {
this.setState(
{
rutas :[],
isLoading: false,
isConnected: isConnected
}
)
}
).done(() => {
NetInfo.isConnected.addEventListener('change', dispatchConnected);
});
}
navigate(name){
this.props.navigator.push({name})
}
handleSyncButton(){
if(!this.state.isConnected){
alert("No se está conectado al internet; por lo tanto, no puede sincronizar los datos.");
return;
}
/*------------GETING--------------*/
this.state.isLoading = true;
let routes =[];
getRoutes().then(res => {
routes = res;
for(let i=0; i< routes.length; i++){
delete routes[i].descripcion;
}
write('routes.txt',JSON.stringify(routes));
})
.catch(error => {alert(`ERROR AL SYNC RUTAS\n${error}`)});
let passengers = [];
getCardsInformation().then(res => {
passengers= res;
write('cardsInformation.txt',JSON.stringify(passengers.getWithClient));
})
.catch(error => {alert(`ERROR AL SYNC TARJETAS \n${error}`)});
/*-----------POSTING------------*/
exist('trips')
.then((res) =>{
if(res===true){
readDir('trips')
.then(files =>{
files.forEach((file) =>{
//unlink(file.name);
read('trips/'+file.name)
.then((trip)=>{
postTransaction(trip.idRuta, trip.fecha, trip.busPlaca, trip.tipoMovimiento, trip.transacciones)
.then((response) => {
alert("Enviando transacciones de un viaje.");
unlink('trips/'+file.name);
})
.catch(error => {alert(`Error al postear viaje ${file.name}\n${error}`)})
});
});
//unlink('trips');
})
.catch(error => {alert(error);});
}
alert("Se han actualizado los datos de rutas, clientes, y subido los viajes pendientes.");
});
//console.log(RNFS.ExternalStorageDirectoryPath);
//console.log(RNFS.ExternalDirectoryPath);
//unlink('trips');
this.state.isLoading = false;
}
render(){
let spinner = this.state.isLoading ?
( <ActivityIndicator
size='large'/> ) :
( <View/>);
let style_bar;
if(this.state.isConnected){
style_bar = {
backgroundColor:'green',
alignItems:'center'
};
}else{
style_bar = {
backgroundColor:'red',
alignItems:'center'
};
}
return (
<Container>
<Header style={styles.navBar}>
<Button transparent onPress={() => this.props.reset(this.props.navigation.key)}>
<Text style={{fontWeight:'800', color:'#FFF'}}>{'Salir'}</Text>
</Button>
<Title style={styles.navBarTitle}>{'Home'}</Title>
</Header>
<View style={styles.container}>
<Content>
<Image source={require('../../imgs/logo-4.png')} style={styles.shadow}></Image>
<View style={styles.bg}>
<Button style={styles.btn} onPress = { () => {
this.props.navigator.push({name: 'rutasView'})
}}
>
Cargar Rutas
</Button>
<Button disabled={this.state.isLoading} style={styles.btn} onPress = {this.handleSyncButton.bind(this)}>
Sync
</Button>
</View>
</Content>
<View style={style_bar }><Text style={styles.text}>{this.state.isConnected?'Online':'Offline'}</Text></View>
{ spinner }
</View>
</Container>
);
}
}
export default Home;
|
src/components/pages/Account/ResetConfirm.js | ESTEBANMURUZABAL/my-ecommerce-template | /**
* Imports
*/
import React from 'react';
import connectToStores from 'fluxible-addons-react/connectToStores';
import {FormattedMessage} from 'react-intl';
// Flux
import IntlStore from '../../../stores/Application/IntlStore';
import ResetStore from '../../../stores/Account/ResetStore';
import resetConfirm from '../../../actions/Account/resetConfirm';
// Required components
import Button from '../../common/buttons/Button';
import Heading from '../../common/typography/Heading';
import InputField from '../../common/forms/InputField';
import Modal from '../../common/modals/Modal';
import Text from '../../common/typography/Text';
// Translation data for this component
import intlData from './ResetConfirm.intl';
/**
* Component
*/
class ResetConfirm extends React.Component {
static contextTypes = {
executeAction: React.PropTypes.func.isRequired,
getStore: React.PropTypes.func.isRequired,
router: React.PropTypes.func.isRequired
};
//*** Page Title and Snippets ***//
static pageTitleAndSnippets = function (context) {
return {
title: context.getStore(IntlStore).getMessage(intlData, 'title')
}
};
//*** Initial State ***//
state = {
loading: this.context.getStore(ResetStore).isLoading(),
error: this.context.getStore(ResetStore).getError(),
password: undefined,
passwordConfirm: undefined,
fieldErrors: {},
errorMessage: undefined,
showSuccessModal: false
};
//*** Component Lifecycle ***//
componentDidMount() {
// Component styles
require('./ResetConfirm.scss');
}
componentWillReceiveProps(nextProps) {
// Find field error descriptions in request response
let fieldErrors = {};
if (this.state.loading && !nextProps._loading && nextProps._error) {
if (nextProps._error.validation && nextProps._error.validation.keys) {
nextProps._error.validation.keys.forEach((field) => {
fieldErrors[field] = nextProps._error.validation.details[field];
if (field === 'token') {
this.setState({errorMessage: nextProps._error.validation.details[field]});
}
});
} else if (nextProps._error.hasOwnProperty('message')) {
this.setState({errorMessage: nextProps._error.message});
} else {
this.setState({
errorMessage: this.context.getStore(IntlStore).getMessage(intlData, 'unknownError')
});
}
}
// Check for a successful reset request
if (this.state.loading && !nextProps._loading && !nextProps._error) {
this.setState({showSuccessModal: true});
}
// Update state
this.setState({
loading: nextProps._loading,
error: nextProps._error,
fieldErrors: fieldErrors
})
}
//*** View Controllers ***//
handleFieldChange = (param, value) => {
this.setState({[param]: value});
};
handleSubmitClick = () => {
let intlStore = this.context.getStore(IntlStore);
this.setState({errorMessage: null});
this.setState({fieldErrors: {}});
let fieldErrors = {};
if (!this.state.password) {
fieldErrors.password = intlStore.getMessage(intlData, 'fieldRequired');
}
if (!this.state.passwordConfirm) {
fieldErrors.passwordConfirm = intlStore.getMessage(intlData, 'fieldRequired');
}
if (this.state.password && this.state.passwordConfirm && this.state.password != this.state.passwordConfirm) {
fieldErrors.passwordConfirm = intlStore.getMessage(intlData, 'passwordMismatch');
}
this.setState({fieldErrors: fieldErrors});
if (Object.keys(fieldErrors).length === 0) {
this.context.executeAction(resetConfirm, {
token: this.props.params.token,
password: this.state.password
});
}
};
handleModalContinueClick = () => {
this.context.router.transitionTo('login', {locale: this.context.getStore(IntlStore).getCurrentLocale()});
};
//*** Template ***//
render() {
//
// Helper methods & variables
//
let intlStore = this.context.getStore(IntlStore);
let successModal = () => {
if (this.state.showSuccessModal) {
return (
<Modal title={intlStore.getMessage(intlData, 'successModalTitle')}>
<div className="reset-confirm__modal-body">
<Text size="medium">
<FormattedMessage
message={intlStore.getMessage(intlData, 'successModalBody')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
<div className="reset-confirm__modal-footer">
<Button type="primary" onClick={this.handleModalContinueClick}>
<FormattedMessage message={intlStore.getMessage(intlData, 'successModalContinue')}
locales={intlStore.getCurrentLocale()} />
</Button>
</div>
</Modal>
);
}
};
//
// Return
//
return (
<div className="reset-confirm">
{successModal()}
<div className="reset-confirm__container">
<div className="reset-confirm__header">
<Heading>
<FormattedMessage message={intlStore.getMessage(intlData, 'title')}
locales={intlStore.getCurrentLocale()} />
</Heading>
</div>
{this.state.errorMessage ?
<div className="reset-confirm__error-message">
<Text size="small">{this.state.errorMessage}</Text>
</div>
:
null
}
<div className="reset-confirm__form">
<div className="reset-confirm__form-item">
<InputField type="password"
label={intlStore.getMessage(intlData, 'password')}
onChange={this.handleFieldChange.bind(null, 'password')}
onEnterPress={this.handleSubmitClick}
error={this.state.fieldErrors['password']}
value={this.state.password} />
</div>
<div className="reset-confirm__form-item">
<InputField type="password"
label={intlStore.getMessage(intlData, 'passwordConfirm')}
onChange={this.handleFieldChange.bind(null, 'passwordConfirm')}
onEnterPress={this.handleSubmitClick}
error={this.state.fieldErrors['passwordConfirm']}
value={this.state.passwordConfirm} />
</div>
<div className="reset-confirm__form-actions">
<Button type="primary" onClick={this.handleSubmitClick} disabled={this.state.loading}>
<FormattedMessage message={intlStore.getMessage(intlData, 'submit')}
locales={intlStore.getCurrentLocale()} />
</Button>
</div>
</div>
</div>
</div>
);
}
}
/**
* Flux
*/
ResetConfirm = connectToStores(ResetConfirm, [ResetStore], (context) => {
return {
_error: context.getStore(ResetStore).getError(),
_loading: context.getStore(ResetStore).isLoading()
};
});
/**
* Exports
*/
export default ResetConfirm;
|
app/viewControllers/components/SplitSpreads.js | Evyy/cffs-ui | 'use strict';
import React from 'react';
import SplitSpread from './SplitSpread';
import blurbs from '../../blurbs.json';
import _ from 'lodash';
class SplitSpreads extends React.Component {
constructor (props) {
super(props);
this.renderSplitSpread = this
.renderSplitSpread
.bind(this);
}
static propTypes = {
blurbIds: React.PropTypes.array.isRequired,
startNumber: React.PropTypes.number.isRequired
};
renderSplitSpread (blurbId, index) {
let startNumber = this.props.startNumber || 1;
let headingNumber = "0" + (index + startNumber);
console.log("headingNumber", headingNumber);
let imageRight = ((index % 2) === 0);
let blurb = _.find(blurbs, {'id': blurbId})
return <SplitSpread
key={blurb.id}
id={blurb.id}
title={blurb.title}
body={blurb.body}
image={blurb.image}
number={headingNumber}
imageRight={imageRight}/>
}
render () {
let splitSpreads = this.props.blurbIds;
return (
<div className="split-spreads">
{splitSpreads.map(this.renderSplitSpread)}
</div>
);
}
}
export default SplitSpreads;
|
src/routes/home/NewPoll.js | binyuace/vote | import React from 'react';
const NewPoll = ({ fetch, store }) => {
let input;
return (
<div>
<form
onSubmit={e => {
e.preventDefault();
if (store.getState().user === null) {
alert('you need to log in first');
window.location.href = '/login';
return;
}
if (!input.value.trim()) {
return;
}
newPollAsync(fetch, input.value);
input.value = '';
}}
>
<input
ref={node => {
input = node;
}}
/>
<button type="submit">New Poll</button>
</form>
</div>
);
};
function postPoll(fetch, val) {
return fetch('/api/newpoll', {
method: 'POST',
body: JSON.stringify({ title: val }),
});
}
function newPollAsync(fetch, val) {
postPoll(fetch, val)
.then(response => response.json())
.then(json => {
window.location.href = `/poll/${json.url}`;
})
.catch(error => console.error(error));
}
export default NewPoll;
|
monkey/monkey_island/cc/ui/src/components/attack/techniques/T1504.js | guardicore/monkey | import React from 'react';
import ReactTable from 'react-table';
import {renderMachineFromSystemData, ScanStatus} from './Helpers';
import MitigationsComponent from './MitigationsComponent';
class T1504 extends React.Component {
constructor(props) {
super(props);
}
static getColumns() {
return ([{
columns: [
{ Header: 'Machine',
id: 'machine',
accessor: x => renderMachineFromSystemData(x.machine),
style: {'whiteSpace': 'unset'}},
{ Header: 'Result',
id: 'result',
accessor: x => x.result,
style: {'whiteSpace': 'unset'}}
]
}])
}
render() {
return (
<div>
<div>{this.props.data.message_html}</div>
<br/>
{this.props.data.status === ScanStatus.USED ?
<ReactTable
columns={T1504.getColumns()}
data={this.props.data.info}
showPagination={false}
defaultPageSize={this.props.data.info.length}
/> : ''}
<MitigationsComponent mitigations={this.props.data.mitigations}/>
</div>
);
}
}
export default T1504;
|
examples/src/app.js | reactjs/react-tabs | import React from 'react';
import * as ReactDOM from 'react-dom/client';
import './example.less';
import SuperMario from './components/examples/SuperMario';
import MattGroening from './components/examples/MattGroening';
import Avengers from './components/examples/Avengers';
import RightToLeft from './components/examples/RightToLeft';
const root = ReactDOM.createRoot(document.getElementById('example'));
root.render(
<div>
<SuperMario />
<MattGroening />
<Avengers />
<RightToLeft />
</div>,
);
|
examples/js/custom/insert-modal/default-custom-insert-modal-footer.js | prajapati-parth/react-bootstrap-table | /* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-alert: 0 */
/* eslint no-console: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn, InsertModalFooter } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class DefaultCustomInsertModalFooterTable extends React.Component {
beforeClose(e) {
alert(`[Custom Event]: Modal close event triggered!`);
}
beforeSave(e) {
alert(`[Custom Event]: Modal save event triggered!`);
}
handleModalClose(closeModal) {
// Custom your onCloseModal event here,
// it's not necessary to implement this function if you have no any process before modal close
console.log('This is my custom function for modal close event');
closeModal();
}
handleSave(save) {
// Custom your onSave event here,
// it's not necessary to implement this function if you have no any process before save
console.log('This is my custom function for save event');
save();
}
createCustomModalFooter = (closeModal, save) => {
return (
<InsertModalFooter
className='my-custom-class'
saveBtnText='CustomSaveText'
closeBtnText='CustomCloseText'
closeBtnContextual='btn-warning'
saveBtnContextual='btn-success'
closeBtnClass='my-close-btn-class'
saveBtnClass='my-save-btn-class'
beforeClose={ this.beforeClose }
beforeSave={ this.beforeSave }
onModalClose={ () => this.handleModalClose(closeModal) }
onSave={ () => this.handleSave(save) }/>
);
// If you want have more power to custom the child of InsertModalFooter,
// you can do it like following
// return (
// <InsertModalFooter
// onModalClose={ () => this.handleModalClose(closeModal) }
// onSave={ () => this.handleSave(save) }>
// { ... }
// </InsertModalFooter>
// );
}
render() {
const options = {
insertModalFooter: this.createCustomModalFooter
};
return (
<BootstrapTable data={ products } options={ options } insertRow>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
examples/01 Dustbin/Stress Test/Container.js | Reggino/react-dnd | import React, { Component } from 'react';
import { DragDropContext } from 'react-dnd';
import HTML5Backend, { NativeTypes } from 'react-dnd/modules/backends/HTML5';
import Dustbin from './Dustbin';
import Box from './Box';
import ItemTypes from './ItemTypes';
import shuffle from 'lodash/collection/shuffle';
import update from 'react/lib/update';
@DragDropContext(HTML5Backend)
export default class Container extends Component {
constructor(props) {
super(props);
this.state = {
dustbins: [
{ accepts: [ItemTypes.GLASS], lastDroppedItem: null },
{ accepts: [ItemTypes.FOOD], lastDroppedItem: null },
{ accepts: [ItemTypes.PAPER, ItemTypes.GLASS, NativeTypes.URL], lastDroppedItem: null },
{ accepts: [ItemTypes.PAPER, NativeTypes.FILE], lastDroppedItem: null }
],
boxes: [
{ name: 'Bottle', type: ItemTypes.GLASS },
{ name: 'Banana', type: ItemTypes.FOOD },
{ name: 'Magazine', type: ItemTypes.PAPER }
],
droppedBoxNames: []
};
}
componentDidMount() {
this.interval = setInterval(() => this.tickTock(), 1000);
}
tickTock() {
this.setState({
boxes: shuffle(this.state.boxes),
dustbins: shuffle(this.state.dustbins)
});
}
componentWillUnmount() {
clearInterval(this.interval);
}
isDropped(boxName) {
return this.state.droppedBoxNames.indexOf(boxName) > -1;
}
render() {
const { boxes, dustbins } = this.state;
return (
<div>
<div style={{ overflow: 'hidden', clear: 'both' }}>
{dustbins.map(({ accepts, lastDroppedItem }, index) =>
<Dustbin accepts={accepts}
lastDroppedItem={lastDroppedItem}
onDrop={(item) => this.handleDrop(index, item)} />
)}
</div>
<div style={{ overflow: 'hidden', clear: 'both' }}>
{boxes.map(({ name, type }) =>
<Box name={name}
type={type}
isDropped={this.isDropped(name)} />
)}
</div>
</div>
);
}
handleDrop(index, item) {
const { name } = item;
this.setState(update(this.state, {
dustbins: {
[index]: {
lastDroppedItem: {
$set: item
}
}
},
droppedBoxNames: name ? {
$push: [name]
} : {}
}));
}
} |
client/pages/Home.js | rockchalkwushock/photography-frontend | import React, { Component } from 'react';
import { browserHistory } from 'react-router/es';
import { withTranslate } from 'react-redux-multilingual';
import { connect } from 'react-redux/es';
import { Loader } from '../commons';
import { AppCarousel, fetchCategory } from '../modules';
@connect(
state => ({
photos: state.carousel
}),
{ fetchCategory }
)
class Home extends Component {
state = { loading: true }
componentDidMount() {
(async () => {
await this.props.fetchCategory('home');
this.setState({ loading: false });
})();
}
async _onClick(category) {
await this.props.fetchCategory(category);
browserHistory.push(`/portfolio/${category}`);
}
render() {
const { params, photos, translate } = this.props;
if (this.state.loading) return <Loader />;
const { collection } = params;
const category = collection === undefined ? 'home' : collection;
const images = photos[category];
return (
<div className='homepage'>
<AppCarousel gallery={images} />
<nav className="nav-portfolio">
<div className="menu-container">
<ul>
<li onClick={() => this._onClick('family')}>
{translate('family')}
</li>
<li onClick={() => this._onClick('portrait')}>
{translate('portrait')}
</li>
<li onClick={() => this._onClick('travel')}>
{translate('travel')}
</li>
<li onClick={() => this._onClick('wedding')}>
{translate('wedding')}
</li>
</ul>
</div>
</nav>
</div>
);
}
}
export default withTranslate(Home);
|
client/components/Navigation/Navigation.js | djaracz/useless-app | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Logo from '../Logo/Logo';
import styles from './navigation.scss';
import OwnLink from '../OwnLink/OwnLink';
export default class Nav extends Component {
constructor(props) {
super(props);
this.handleOnLinkClick = this.handleOnLinkClick.bind(this);
}
handleOnLinkClick(currentTab) {
const { setCurrentTab } = this.props;
setCurrentTab(currentTab);
}
render() {
const { currentTab, links } = this.props;
const linksToRender = links.map((link, i) => {
return (link.linkTitle === currentTab) ?
<OwnLink
key={i}
handleOnClick={this.handleOnLinkClick}
linkTo={link.linkTo}
linkTitle={link.linkTitle}
active
/> :
<OwnLink
key={i}
handleOnClick={this.handleOnLinkClick}
linkTo={link.linkTo}
linkTitle={link.linkTitle}
/>;
});
return (
<nav className={styles.nav}>
<Logo />
<ul className={styles.navLinks}>
{linksToRender}
</ul>
</nav>
);
}
}
Nav.propTypes = {
currentTab: PropTypes.string.isRequired,
links: PropTypes.array.isRequired,
setCurrentTab: PropTypes.func.isRequired
};
|
nextApp/pageComponents/weeklyReport/EventForm/index.js | liximomo/toolpages | import React from 'react';
import Formsy from 'formsy-react';
import Paper from 'material-ui/Paper';
import Toggle from 'material-ui/Toggle';
import FlatButton from 'material-ui/FlatButton';
import MenuItem from 'material-ui/MenuItem';
import {
FormsyCheckbox, FormsyDate, FormsyRadio, FormsyRadioGroup,
FormsySelect, FormsyText, FormsyTime, FormsyToggle, FormsyAutoComplete
} from 'formsy-material-ui/lib';
const DEPARTMENTS = [
'总经办',
'人事',
'财务',
'营销中心',
'策划中心',
'运营部',
'直播部',
'新媒体',
'福州公司',
'合规部',
];
const CONTACTS = [
'陈彬',
'钟姚洁',
'杨海斌',
'伍远强',
'庞小龙',
'范旭',
'魏海龙',
'孙建国',
'付信军',
'吴奇东',
'徐琰璋',
'黄波',
'胡日猛',
'刘欢',
'涂凤朝',
'李玺',
'徐阳红',
'季娜',
'丁薛',
'岳颂杰',
'赵丽忠',
'殷逸伦',
'黄宇微',
'李凯华',
'李腾',
'徐鑫',
'黄毓鸣',
];
const styles = {
paperStyle: {
width: 300,
margin: 'auto',
padding: 20,
},
row: {
display: 'block',
margin: '0.8em 0',
},
formControll: {
margin: '0 1.2em',
},
formControllInline: {
display: 'inline-block',
margin: '0 1.2em',
}
};
const Row = (props) => (
<div style={styles.row}>
{props.children}
</div>
);
const FormControll = (props) => (
<div style={styles.formControll}>
{props.children}
</div>
);
const FormControllInline = (props) => (
<div style={styles.formControllInline}>
{props.children}
</div>
);
export default class EventForm extends React.PureComponent {
constructor(props, context) {
super(props, context);
this.state = {
more: false,
};
}
showMore = () => {
this.setState({
more: true,
});
}
handleValid = () => {
this.props.onValid();
}
handleInValid = () => {
this.props.onInValid();
}
submit() {
this.props.onSubmit({
id: this.props.id,
...this.refs.form.getModel(),
isNext: this.isNext,
});
}
handleWeekChange = (event, isNext) => {
this.isNext = isNext;
}
more() {
const props = this.props;
return (
<Paper style={{ padding: '2em 0', display: this.state.more ? 'block' : 'none' }} zDepth={1}>
<p
style={{
margin: '-0.8em 1.4em 0',
color: this.context.muiTheme.palette.accent1Color
}}>补充内容
</p>
<Row>
<FormControllInline>
<FormsyDate
name="expectDate"
floatingLabelText="目标时间"
hintText="事项的目标终止时间"
defaultDate={props.expectDate}
/>
</FormControllInline>
<FormControllInline>
<FormsyText
name="relation"
floatingLabelText="第三方/协助方"
hintText="事项相关协方(人,部门)"
defaultValue={props.relation}
/>
</FormControllInline>
</Row>
<Row>
<FormControll>
<FormsyText
name="descripe"
floatingLabelFixed
multiLine
floatingLabelText="事项描述"
hintText="详细描述事项内容"
style={{
width: '100%'
}}
defaultValue={props.descripe}
/>
</FormControll>
</Row>
<Row>
<FormControll>
<FormsyText
name="currentState"
floatingLabelFixed
multiLine
floatingLabelText="当前状态"
hintText="描述事项当前的进展,处于什么状态"
style={{
width: '100%'
}}
defaultValue={props.currentState}
/>
</FormControll>
</Row>
<Row>
<FormControll>
<FormsyText
name="nextState"
floatingLabelFixed
multiLine
floatingLabelText="下一步打算"
hintText="描述事项接下来的进展,要完成的目标"
style={{
width: '100%'
}}
defaultValue={props.nextState}
/>
</FormControll>
</Row>
<Row>
<FormControll>
<FormsyText
name="expectState"
floatingLabelFixed
multiLine
floatingLabelText="目标状态"
hintText="描述事项完成时应达到的状态"
style={{
width: '100%'
}}
defaultValue={props.expectState}
/>
</FormControll>
</Row>
<Row>
<FormControll>
<FormsyText
name="obstacle"
floatingLabelFixed
multiLine
floatingLabelText="阻碍"
hintText="描述事项要达到目标状态会遇到或可能存在的疑问、难点、关键点"
style={{
width: '100%'
}}
defaultValue={props.obstacle}
/>
</FormControll>
</Row>
</Paper>
);
}
render() {
this.isNext = this.props.isNext || false;
const props = this.props;
return (
<Formsy.Form
ref="form"
onValid={this.handleValid}
onInvalid={this.handleInValid}
>
<Row>
<FormControll>
<Toggle
onToggle={this.handleWeekChange}
label="下周事项?"
name="isNext"
labelStyle={{
color: 'red',
}}
thumbStyle={{
backgroundColor: '#ffcccc',
}}
defaultToggled={props.isNext}
/>
</FormControll>
</Row>
<Row>
<FormControll>
<FormsyText
name="event"
required
floatingLabelText="事项"
hintText="事项简述"
defaultValue={props.event}
/>
</FormControll>
</Row>
<Row>
<FormControll>
<FormsySelect
name="priority"
floatingLabelText="优先级象限"
value={props.priority || 'p3'}
>
<MenuItem value={'p0'} primaryText="紧急且重要" />
<MenuItem value={'p1'} primaryText="重要但不紧急" />
<MenuItem value={'p2'} primaryText="紧急但不重要" />
<MenuItem value={'p3'} primaryText="不重要不紧急" />
</FormsySelect>
</FormControll>
</Row>
<Row>
<FormControllInline>
<FormsyText
name="department"
required
floatingLabelText="责任部门"
defaultValue={props.department || '新媒体'}
/>
</FormControllInline>
<FormControllInline>
<FormsyText
name="person"
required
floatingLabelText="责任人"
hintText="事项负责人"
defaultValue={props.person}
/>
</FormControllInline>
</Row>
{!this.state.more
? <FlatButton
style={{
left: -8,
top: 10
}}
label="更多"
secondary={true}
onClick={this.showMore}
/>
: null
}
{this.more()}
</Formsy.Form>
)
}
}
EventForm.contextTypes = {
muiTheme: React.PropTypes.object,
};
|
src/app/components/pages/ContentPage/ContentPage.js | tvarner/PortfolioApp | import React from 'react';
import _ from 'lodash';
import Collapse from './../../utilComponents/collapse/src/Collapse.jsx';
import Panel from './../../utilComponents/collapse/src/Panel.jsx';
import './styles.css';
import ContentCollectionContainer from './../../utilComponents/ContentCollection/ContentCollectionContainer';
import ContentCollectionHeader from './../../utilComponents/ContentCollectionHeader/ContentCollectionHeader';
// import firebase from 'firebase';
// Since this component is simple and static, there's no parent container for it.
const ContentPage = React.createClass({
getInitialState() {
const contentMonolith = require('./../../../../content/_content.json');
const category = this.props.category;
return {
contentMonolith: contentMonolith,
category: category,
collections: null
};
},
componentWillMount() {
// Initialize Firebase
/*
const firebaseConfig = {
apiKey: "AIzaSyDVVrCSvqkeFSYavW_fK8X-bjXklpZLFlI",
authDomain: "jbportfolioapp.firebaseapp.com",
databaseURL: "https://jbportfolioapp.firebaseio.com",
storageBucket: "jbportfolioapp.appspot.com",
messagingSenderId: "687303676021"
};
const firebaseApp = firebase.initializeApp(firebaseConfig);
// Get a reference to the storage service, which is used to create references in your storage bucket
const storage = firebase.storage();
// Create a storage reference from our storage service
const storageRef = storage.ref();
const contentRef = storageRef.child('content');
const database = firebase.database();
*/
// debugger;
// remove arg later
const collections = this.getCollections(this.state.contentMonolith);
this.setState({
collections: collections
});
},
getCollections(contentMonolith) {
// query contentMonolith from database here instead of passing content monolith
const _contentMonolithQueryFn = function(collection) {
const _collectionQueryFn = function(collection) {
const _categoryQueryFn = function(category) {
return this.props.category === category;
};
return _.find(collection.category, _categoryQueryFn.bind(this));
};
return _collectionQueryFn.call(this, collection);
};
return _.filter(contentMonolith.collections, _contentMonolithQueryFn.bind(this));
},
_checkIfContentCollectionActive(key) {
for (let i = 0; i <= this.props.page.activePanelKey.length; i++) {
if (this.props.page.activePanelKey[i] === key.toString()) {
return true;
}
}
return false;
},
sortCollectionsByTitle(collections) {
collections.sort(function(a, b) {
const titleA = a.name.toUpperCase(); // ignore upper and lowercase
const titleB = b.name.toUpperCase(); // ignore upper and lowercase
if (titleA < titleB) {
return -1;
}
if (titleA > titleB) {
return 1;
}
// names must be equal
return 0;
});
},
sortCollectionsByAuthor(collections) {
collections.sort(function(a, b) {
const authorA = a.authors[0].toUpperCase(); // ignore upper and lowercase
const authorB = b.authors[0].toUpperCase(); // ignore upper and lowercase
if (authorA < authorB) {
return -1;
}
if (authorA > authorB) {
return 1;
}
// names must be equal
return 0;
});
},
sortCollectionsByDate(collections) {
collections.sort(function(a, b) {
return new Date(a.dateCreated) - new Date(b.dateCreated);
});
},
getHeader(carouselRef, content) {
return (
<div>
<ContentCollectionHeader carouselRef={carouselRef} content={content} />
</div>
);
},
getContentCollection(content, key) {
const headerCarouselRef = 'headerCarousel' + key.toString();
const mainCarouselRef = 'mainCarousel' + key.toString();
// add alpha jump ids here:
let alphaJumpElementId = 'alpha-jump-no-jump';
if (this.props.page.sortBy === 'title') {
// get first character
const _alphaJumpFirstChar = content.name.charAt(0);
// check if first character is in provided alphabet array. remove if present. update alphaJumpElementId
if (_.find(this._alphabet, function(letter) { return (letter === _alphaJumpFirstChar); })) {
_.remove(this._alphabet, function(letter) { return (letter === _alphaJumpFirstChar); });
alphaJumpElementId = 'alpha-jump-' + _alphaJumpFirstChar.toUpperCase();
}
} else if (this.props.page.sortBy === 'author') {
// get first character
const _alphaJumpFirstChar = content.authors[0].charAt(0);
// check if first character is in provided alphabet array. remove if present. update alphaJumpElementId
if (_.find(this._alphabet, function(letter) { return letter === _alphaJumpFirstChar; })) {
_.remove(this._alphabet, function(letter) { return letter === _alphaJumpFirstChar; });
alphaJumpElementId = 'alpha-jump-' + _alphaJumpFirstChar.toUpperCase();
}
}
if (this._checkIfContentCollectionActive(key)) {
return (
<Panel header={this.getHeader(headerCarouselRef, content)} key={key} externalId={alphaJumpElementId}>
<ContentCollectionContainer carouselRef={mainCarouselRef} content={content} />
</Panel>
);
} else {
return (
<Panel header={this.getHeader(headerCarouselRef, content)} key={key} externalId={alphaJumpElementId} />
);
}
},
getContentCollections() {
// remove arg later
const _collections = this.getCollections(this.state.contentMonolith);
if (this.props.page.sortBy === 'title') {
// sort collections by title
this.sortCollectionsByTitle(_collections);
} else if (this.props.page.sortBy === 'date') {
// sort collections by date
this.sortCollectionsByDate(_collections);
} else if (this.props.page.sortBy === 'author') {
// sort collecitons by author
this.sortCollectionsByAuthor(_collections);
}
this._alphabet = ["A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
const collections = _collections.map(this.getContentCollection);
if (collections.length === 0) {
return (
<div className={'coming-soon-container'}>
Coming soon. ;)
</div>
);
}
return (
<Collapse
accordion={this.props.page.accordion}
onChange={this.props.onChange}
activeKey={this.props.page.activePanelKey}
>
{collections}
</Collapse>
);
},
render() {
const _alphaJumpIcons = ["#", "A", "B", "C", "D", "E", "F", "G", "H", "I", "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V", "W", "X", "Y", "Z"];
const _getIconFn = function(icon, i) {
if (icon === "#") {
return (
<div key={i} onClick={this.props.openSortCollectionsModal} className={"alphabetical-jump-icon"}>{icon}</div>
);
}
if (this.props.page.sortBy === 'title' || this.props.page.sortBy === 'author') {
const alphaJumpId = 'alpha-jump-' + icon;
const alphaJumpHandler = function() {
if (document.getElementById(alphaJumpId)) {
document.getElementById(alphaJumpId).scrollIntoView();
}
};
return (
<div
key={i}
className={"alphabetical-jump-icon"}
onClick={alphaJumpHandler}>
{icon}
</div>
);
}
};
const getAlphaJumpIcons = _alphaJumpIcons.map(_getIconFn.bind(this));
return (
<div style={{ width: '100%' }}>
<div className={"content-page"}>
<div className={"alphabetical-jump"}>
{getAlphaJumpIcons}
</div>
<div className={"content-container"}>
<div className={'header-container'}>{this.props.header}</div>
{this.getContentCollections()}
</div>
</div>
</div>
);
}
});
export default ContentPage; |
src/main.js | linxlad/tracksy-client | import React from 'react';
import ReactDOM from 'react-dom';
import createStore from './store/createStore';
import './styles/main.scss';
// Store Initialization
// ------------------------------------
const store = createStore(window.__INITIAL_STATE__);
// Render Setup
// ------------------------------------
const MOUNT_NODE = document.getElementById('root');
let render = () => {
const App = require('./App').default;
const routes = require('./routes/index').default(store);
ReactDOM.render(
<App store={store} routes={routes} />,
MOUNT_NODE
);
};
// Development Tools
// ------------------------------------
if (__DEV__) {
if (module.hot) {
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default;
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE);
};
render = () => {
try {
renderApp();
} catch (e) {
console.error(e);
renderError(e);
}
};
// Setup hot module replacement
module.hot.accept([
'App',
'./routes/index'
], () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render();
})
);
}
}
// Let's Go!
// ------------------------------------
if (!__TEST__) render();
|
src/client/components/editable.react.js | jaeh/este | import './editable.styl';
import Component from '../components/component.react';
import React from 'react';
import Textarea from 'react-textarea-autosize';
import classnames from 'classnames';
import immutable from 'immutable';
import {msg} from '../intl/store';
const State = immutable.Record({
isEditing: false,
value: ''
});
const initialState = new State;
export default class Editable extends Component {
static propTypes = {
className: React.PropTypes.string,
disabled: React.PropTypes.bool,
editButtons: React.PropTypes.func,
id: React.PropTypes.oneOfType([React.PropTypes.number, React.PropTypes.string]).isRequired,
isRequired: React.PropTypes.bool,
maxRows: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
name: React.PropTypes.string.isRequired,
onSave: React.PropTypes.func.isRequired,
onState: React.PropTypes.func.isRequired,
rows: React.PropTypes.oneOfType([React.PropTypes.string, React.PropTypes.number]),
showEditButtons: React.PropTypes.bool,
showViewButtons: React.PropTypes.bool,
state: React.PropTypes.instanceOf(State),
text: React.PropTypes.string.isRequired,
type: React.PropTypes.string,
viewButtons: React.PropTypes.func
};
static defaultProps = {
isRequired: true,
showEditButtons: false,
showViewButtons: false,
editButtons: (onSaveClick, onCancelClick, disabled) =>
<div className="btn-group">
<button disabled={disabled} onClick={onSaveClick}>Save</button>
<button disabled={disabled} onClick={onCancelClick}>Cancel</button>
</div>,
viewButtons: (onEditClick, disabled) =>
<div className="btn-group">
<button disabled={disabled} onClick={onEditClick}>Edit</button>
</div>
};
constructor(props) {
super(props);
this.cancelEdit = ::this.cancelEdit;
this.enableEdit = ::this.enableEdit;
this.onInputChange = ::this.onInputChange;
this.onInputFocus = ::this.onInputFocus;
this.onInputKeyDown = ::this.onInputKeyDown;
this.onViewClick = ::this.onViewClick;
this.saveEdit = ::this.saveEdit;
}
onInputChange(e) {
this.setState(state => state.set('value', e.target.value));
}
onInputFocus(e) {
this.moveCaretToEnd(e.target);
}
moveCaretToEnd(field) {
const isSelectable = /text|password|search|tel|url/.test(field.type);
if (!isSelectable) return;
const length = field.value.length;
field.selectionStart = length;
field.selectionEnd = length;
}
onInputKeyDown(e) {
switch (e.key) {
case 'Enter': this.onKeyEnter(); break;
case 'Escape': this.onKeyEscape(); break;
}
}
onKeyEnter() {
if (this.props.type === 'textarea') return;
this.saveEdit();
}
saveEdit() {
if (!this.isDirty()) {
this.disableEdit();
return;
}
const value = this.props.state.value.trim();
if (!value && this.props.isRequired)
return;
this.props
.onSave(this.props.id, this.props.name, value)
.then(() => {
this.disableEdit();
});
}
isDirty() {
return this.props.state.value !== this.props.text;
}
onKeyEscape() {
this.cancelEdit();
}
cancelEdit() {
if (this.isDirty())
if (!confirm(msg('components.editable.cancelEdit'))) // eslint-disable-line no-alert
return;
this.disableEdit();
}
disableEdit() {
this.setState(state => null);
}
onViewClick(e) {
this.enableEdit();
}
enableEdit() {
this.setState(state => state.merge({
isEditing: true,
value: this.props.text
}));
}
setState(callback) {
this.props.onState(
this.props.id,
this.props.name,
callback(this.props.state || initialState)
);
}
render() {
const {
className, disabled, editButtons, maxRows, rows, showEditButtons,
showViewButtons, state, text, type, viewButtons
} = this.props;
const isEditing = state && state.isEditing;
if (!isEditing) return (
<div className={classnames('editable view', className)}>
<span onClick={this.onViewClick}>{text}</span>
{showViewButtons && viewButtons(this.enableEdit, disabled)}
</div>
);
const fieldProps = {
autoFocus: true,
disabled: disabled,
onChange: this.onInputChange,
onFocus: this.onInputFocus,
onKeyDown: this.onInputKeyDown,
value: state.value
};
const field = type === 'textarea'
? <Textarea {...fieldProps} maxRows={maxRows} rows={rows} />
: <input {...fieldProps} type={type || 'text'} />;
return (
<div className={classnames('editable edit', className)}>
{field}
{(showEditButtons || type === 'textarea') &&
editButtons(this.saveEdit, this.cancelEdit, disabled)}
</div>
);
}
}
|
src/containers/Profile/index.js | andresmechali/shareify | import React from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { BrowserRouter, Route} from 'react-router-dom';
import { withApollo } from 'react-apollo';
import USER_QUERY from '../../utils/queries/USER_QUERY';
import { addFlashMessage, deleteFlashMessage } from "../../redux/actions/flashMessages";
import { setCurrentUser } from "../../redux/actions/authActions";
import Loading from '../../components/Loading/Bounce';
import Main from './Main';
import Settings from './Settings';
import Activity from '../../components/Profile/Activity';
import ChangePassword from "./ChangePassword";
import Conversation from '../../containers/Conversation';
import Offer from '../../containers/Offer';
import Request from '../../containers/Request';
import ItemRequest from '../../containers/ItemRequest';
import Transaction from '../../containers/Transaction';
import ChangeImage from "./ChangeImage";
class Profile extends React.Component {
constructor(props) {
super(props);
this.state = {
user: {},
loading: true,
active: 'main',
lastConversationId: '',
lastRequestId: '',
lastTransactionId: '',
image: '',
}
}
componentWillMount() {
this.props.client.query({
query: USER_QUERY,
variables: {_id: this.props.auth.user._id},
})
.then(res => {
let lastConversationId = res.data.userById.conversations.slice().sort(
function compare(a, b) {
if (a.lastDate < b.lastDate) return 1;
if (a.lastDate > b.lastDate) return -1;
return 0;
}
)[0];
let lastRequestId = res.data.userById.requests.slice().sort(
function compare(a, b) {
if (a.date < b.date) return 1;
if (a.date > b.date) return -1;
return 0;
}
)[0];
let lastTransactionId = res.data.userById.transactions.slice().sort(
function compare(a, b) {
if (a.dateCreated < b.dateCreated) return 1;
if (a.dateCreated > b.dateCreated) return -1;
return 0;
}
)[0];
this.setState({
user: res.data.userById,
loading: false,
lastConversationId: lastConversationId? lastConversationId._id : "",
lastRequestId: lastRequestId? lastRequestId._id : "",
lastTransactionId: lastTransactionId? lastTransactionId._id : "",
})
})
.catch(err => {
console.log(err);
//this.props.push('/login');
})
}
setImage(img) {
if (typeof img === "object") {
let reader = new FileReader();
reader.readAsDataURL(img[0]);
reader.onloadend = () => {
this.setState({image: reader.result});
};
}
else {
this.setState({image: ''});
}
}
render() {
if (this.state.loading) {
return (
<div className="container">
<Loading />
</div>
)
}
return (
<BrowserRouter>
<div className="container user-profile">
<Route
path='/profile/main'
exact={true}
component={() => <Main
user={this.state.user}
auth={this.props.auth}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
/>}
/>
<Route
path='/profile/activity'
exact={true}
component={() => <Activity
user={this.state.user}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
auth={this.props.auth}
/>}
/>
<Route
path='/profile/settings'
exact={true}
component={() => <Settings
user={this.state.user}
auth={this.props.auth}
flashMessages={this.props.flashMessages}
push={this.props.push}
setCurrentUser={this.props.setCurrentUser}
addFlashMessage={this.props.addFlashMessage}
deleteFlashMessage={this.props.deleteFlashMessage}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
/>}
/>
<Route
path='/profile/settings/password'
exact={true}
component={() => <ChangePassword
user={this.state.user}
auth={this.props.auth}
flashMessages={this.props.flashMessages}
push={this.props.push}
setCurrentUser={this.props.setCurrentUser}
addFlashMessage={this.props.addFlashMessage}
deleteFlashMessage={this.props.deleteFlashMessage}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
/>}
/>
<Route
path='/profile/settings/picture'
exact={true}
component={() => <ChangeImage
user={this.state.user}
auth={this.props.auth}
flashMessages={this.props.flashMessages}
push={this.props.push}
setCurrentUser={this.props.setCurrentUser}
addFlashMessage={this.props.addFlashMessage}
deleteFlashMessage={this.props.deleteFlashMessage}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
setImage={this.setImage.bind(this)}
image={this.state.image}
/>}
/>
<Route
path='/profile/messages/:id'
render={(props) => <Conversation
{...props}
user={this.state.user}
auth={this.props.auth}
flashMessages={this.props.flashMessages}
push={this.props.push}
setCurrentUser={this.props.setCurrentUser}
addFlashMessage={this.props.addFlashMessage}
deleteFlashMessage={this.props.deleteFlashMessage}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
/>}
/>
<Route
path='/profile/request/:id'
render={(props) => <ItemRequest
{...props}
user={this.state.user}
auth={this.props.auth}
flashMessages={this.props.flashMessages}
push={this.props.push}
setCurrentUser={this.props.setCurrentUser}
addFlashMessage={this.props.addFlashMessage}
deleteFlashMessage={this.props.deleteFlashMessage}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
/>}
/>
<Route
path='/profile/transaction/:id'
render={(props) => <Transaction
{...props}
user={this.state.user}
auth={this.props.auth}
flashMessages={this.props.flashMessages}
push={this.props.push}
setCurrentUser={this.props.setCurrentUser}
addFlashMessage={this.props.addFlashMessage}
deleteFlashMessage={this.props.deleteFlashMessage}
lastConversationId={this.state.lastConversationId}
lastRequestId={this.state.lastRequestId}
lastTransactionId={this.state.lastTransactionId}
/>}
/>
<Route
path='/offer/new'
exact={true}
component={() => <Offer />}
/>
<Route
path='/ask/new'
exact={true}
component={() => <Request />}
/>
</div>
</BrowserRouter>
)
}
}
Profile.propTypes = {
};
const mapStateToProps = (state) => {
return {
auth: state.auth,
flashMessages: state.flashMessages,
}
};
const mapDispatchToProps = (dispatch) => {
return {
push: (path) => dispatch(push(path)),
setCurrentUser: (userToken) => dispatch(setCurrentUser(userToken)),
addFlashMessage: (msg) => dispatch(addFlashMessage(msg)),
deleteFlashMessage: () => dispatch(deleteFlashMessage()),
}
};
export default withApollo(connect(mapStateToProps, mapDispatchToProps)(Profile)); |
app/javascript/mastodon/features/notifications/components/setting_toggle.js | ebihara99999/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
class SettingToggle extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
settingKey: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
onChange: PropTypes.func.isRequired,
htmlFor: PropTypes.string,
}
onChange = (e) => {
this.props.onChange(this.props.settingKey, e.target.checked);
}
render () {
const { settings, settingKey, label, onChange, htmlFor = '' } = this.props;
return (
<label htmlFor={htmlFor} className='setting-toggle__label'>
<Toggle checked={settings.getIn(settingKey)} onChange={this.onChange} />
<span className='setting-toggle'>{label}</span>
</label>
);
}
}
export default SettingToggle;
|
www/src/components/Main.js | glenjamin/react-bootstrap | import PropTypes from 'prop-types';
import React from 'react';
import Container from 'react-bootstrap/lib/Container';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import { css } from 'astroturf';
import SideNav from './SideNav';
import Toc, { TocProvider } from './Toc';
const styles = css`
@import '../css/theme.scss';
.nav {
position: sticky;
top: 4rem;
height: calc(100vh - 4rem);
background-color: #f7f7f7;
}
.main {
order: 1;
padding: 2rem 4rem;
@include media-breakpoint-down(sm) {
padding: 1rem 0.83rem;
}
& > h2:not(:first-child) {
margin-top: 3rem;
}
> h3 {
margin-top: 1.5rem;
}
> ul li,
> ol li {
margin-bottom: 0.25rem;
}
> table {
width: 100%;
max-width: 100%;
margin-bottom: 1rem;
@include media-breakpoint-down(sm) {
display: block;
overflow-x: auto;
-ms-overflow-style: -ms-autohiding-scrollbar;
}
}
@include media-breakpoint-up(lg) {
> ul,
> ol,
> p {
max-width: 80%;
}
}
}
`;
const propTypes = {
location: PropTypes.object.isRequired,
};
function Main({ children, ...props }) {
return (
<Container fluid>
<Row className="flex-xl-nowrap">
<TocProvider>
<Col as={SideNav} xs={12} md={3} xl={2} location={props.location} />
<Col as={Toc} className="d-none d-xl-block" xl={2} />
<Col
xs={12}
md={9}
xl={8}
as="main"
id="rb-docs-content"
className={styles.main}
>
{children}
</Col>
</TocProvider>
</Row>
</Container>
);
}
Main.propTypes = propTypes;
export default Main;
|
app/components/SelectTable/index.js | bruceli1986/react-qdp | /**
*
* SelectTable
*
*/
import React from 'react';
import _ from 'lodash';
import { Modal, Table, Button, Input } from 'antd';
import classNames from 'classnames';
import QdpAdvanceSearcher from 'components/QdpAdvanceSearcher';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
import styles from './styles.css';
const InputGroup = Input.Group;
class SelectTable extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props, context) {
super(props, context);
this.state = {
visible: false,
selectedRowKeys: [],
query: {},
filter: {},
};
}
componentWillReceiveProps(nextProps) {
if (!nextProps.value) {
this.setState({
selectedRowKeys: [],
query: {},
filter: {},
});
}
}
getClassName = (record, index) => {
const { selectedRowKeys } = this.state;
if (selectedRowKeys.indexOf(record[this.props.valueField]) >= 0) {
return 'qdp-row-selected';
}
return '';
}
showModal = () => {
if (this.props.disabled !== true) {
let show = true;
if (this.props.onClick) {
show = this.props.onClick(this.props.value);
}
this.setState({
visible: show,
});
}
}
getValue() {
const dataSource = this.filterDateSource();
const field = this.props.valueField;
if (!field) {
return '';
}
const result = this.state.selectedRowKeys.map((x) => {
const record = dataSource.find(function (y) {
return y[field] === x;
});
if (!record) {
return [];
}
return record[field];
});
// console.log('getValue', result.toString());
return result.toString();
}
getRecords() {
const dataSource = this.props.dataSource;
const field = this.props.valueField;
if (!field) {
return [];
}
const result = this.state.selectedRowKeys.map((x) => (dataSource.find(function (y) {
return y[field] === x;
})));
return result;
}
handleOk = () => {
this.setState({
visible: false,
});
if (this.props.onChange && this.getValue() !== this.props.value) {
this.props.onChange(this.getValue(), this.getRecords());
}
}
handleCancel = (e) => {
this.setState({
visible: false,
});
}
// 通过 rowSelection 对象表明需要行选择
clickRow = (record, index) => {
const field = this.props.valueField;
if(!this.props.multiple) {
this.setState({
selectedRowKeys: [record[field]],
});
} else {
if (this.state.selectedRowKeys.indexOf(record[field]) >= 0) {
_.remove(this.state.selectedRowKeys, function(x) {
return x === record[field];
});
this.setState({
selectedRowKeys: this.state.selectedRowKeys,
});
} else {
this.state.selectedRowKeys.push(record[field]);
this.setState({
selectedRowKeys: this.state.selectedRowKeys,
});
}
}
}
getText() {
const { textField, valueField, value, dataSource } = this.props;
const _value = value ? value.split(',') : [];
// console.log('_value:', _value);
const field = textField ? textField : valueField;
const records = dataSource ? dataSource.filter((x) => _value.indexOf(x[valueField]) >= 0) : [];
// console.log('records:', records);
const text = records ? records.map((x) => x[field]).toString() : '';
return text;
}
setQuery = (fields) => {
this.setState({
query: Object.assign(this.state.query, fields),
});
}
_Submit = (form) => {
if (this.props.onSearch) {
this.props.onSearch(form);
} else {
this.setState({ filter: form });
}
}
showSearcher() {
if (this.props.queryItems && this.props.queryItems.length !== 0) {
return (<QdpAdvanceSearcher
items={this.props.queryItems}
query={this.state.query}
fieldChange={this.setQuery}
onSubmit={this._Submit}
divide={this.props.divide} />);
}
}
filterDateSource() {
const { dataSource } = this.props;
const { filter } = this.state;
let result = [];
if (dataSource) {
result = dataSource.filter(function (x) {
let a = true;
for (var key in filter) {
let reg = new RegExp(`${filter[key]}`, 'i');
if (filter[key] && x[key].search(reg) < 0) {
return false;
}
}
return a;
});
}
return result;
}
render() {
const { style, placeholder, multiple } = this.props;
const { loading, selectedRowKeys } = this.state;
// console.log('SelectTable', this.props.value);
const rowSelection = {
selectedRowKeys,
type: multiple ? 'checkbox' : 'radio',
onSelect : (record, selected, selectedRows) => {
const field = this.props.valueField;
this.setState({
selectedRowKeys: [record[field]],
});
},
};
const btnCls = classNames({
'ant-search-btn': true,
'ant-search-btn-noempty': !!(this.props.value || '').trim(),
});
const searchCls = classNames({
'ant-search-input': true,
'ant-search-input-focus': true,
});
const dataSource = this.filterDateSource();
return (
<div>
<div className="ant-search-input-wrapper" style={style}>
<InputGroup className={searchCls}>
<Input placeholder={placeholder} onClick={this.showModal} value={this.getText()} disabled={this.props.disabled} />
<Input style={{ display: 'none' }} value={this.props.value} />
<div className="ant-input-group-wrap">
<Button icon="search" className={btnCls} size="small" onClick={this.handleSearch} style={{ height: '26px' }} />
</div>
</InputGroup>
</div>
<Modal
title={this.props.title}
visible={this.state.visible}
onOk={this.handleOk}
onCancel={this.handleCancel}
maskClosable={false}
width={this.props.modalWidth}
>
{
this.showSearcher()
}
<Table rowKey={this.props.valueField} size="small"
onRowClick={this.clickRow}
rowSelection={rowSelection}
columns={this.props.columns}
dataSource={dataSource}
rowClassName={this.getClassName} />
</Modal>
</div>
);
}
}
export default SelectTable;
|
examples/using-jest/src/components/image.js | 0x80/gatsby | import React from 'react'
import { StaticQuery, graphql } from 'gatsby'
import Img from 'gatsby-image'
/*
* This component is built using `gatsby-image` to automatically serve optimized
* images with lazy loading and reduced file sizes. The image is loaded using a
* `StaticQuery`, which allows us to load the image from directly within this
* component, rather than having to pass the image data down from pages.
*
* For more information, see the docs:
* - `gatsby-image`: https://gatsby.app/gatsby-image
* - `StaticQuery`: https://gatsby.app/staticquery
*/
const Image = () => (
<StaticQuery
query={graphql`
query {
placeholderImage: file(relativePath: { eq: "gatsby-astronaut.png" }) {
childImageSharp {
fluid(maxWidth: 300) {
...GatsbyImageSharpFluid
}
}
}
}
`}
render={data => <Img fluid={data.placeholderImage.childImageSharp.fluid} />}
/>
)
export default Image
|
frontend/src/Album/Details/AlbumDetailsMediumConnector.js | lidarr/Lidarr | import _ from 'lodash';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { executeCommand } from 'Store/Actions/commandActions';
import { setTracksTableOption } from 'Store/Actions/trackActions';
import createDimensionsSelector from 'Store/Selectors/createDimensionsSelector';
import AlbumDetailsMedium from './AlbumDetailsMedium';
function createMapStateToProps() {
return createSelector(
(state, { mediumNumber }) => mediumNumber,
(state) => state.tracks,
createDimensionsSelector(),
(mediumNumber, tracks, dimensions) => {
const tracksInMedium = _.filter(tracks.items, { mediumNumber });
const sortedTracks = _.orderBy(tracksInMedium, ['absoluteTrackNumber'], ['asc']);
return {
items: sortedTracks,
columns: tracks.columns,
isSmallScreen: dimensions.isSmallScreen
};
}
);
}
const mapDispatchToProps = {
setTracksTableOption,
executeCommand
};
class AlbumDetailsMediumConnector extends Component {
//
// Listeners
onTableOptionChange = (payload) => {
this.props.setTracksTableOption(payload);
}
//
// Render
render() {
return (
<AlbumDetailsMedium
{...this.props}
onTableOptionChange={this.onTableOptionChange}
/>
);
}
}
AlbumDetailsMediumConnector.propTypes = {
albumId: PropTypes.number.isRequired,
albumMonitored: PropTypes.bool.isRequired,
mediumNumber: PropTypes.number.isRequired,
setTracksTableOption: PropTypes.func.isRequired,
executeCommand: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, mapDispatchToProps)(AlbumDetailsMediumConnector);
|
packages/react-error-overlay/src/containers/StackFrame.js | HelpfulHuman/helpful-react-scripts | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React, { Component } from 'react';
import CodeBlock from './StackFrameCodeBlock';
import { getPrettyURL } from '../utils/getPrettyURL';
import { darkGray } from '../styles';
import type { StackFrame as StackFrameType } from '../utils/stack-frame';
import type { ErrorLocation } from '../utils/parseCompileError';
const linkStyle = {
fontSize: '0.9em',
marginBottom: '0.9em',
};
const anchorStyle = {
textDecoration: 'none',
color: darkGray,
cursor: 'pointer',
};
const codeAnchorStyle = {
cursor: 'pointer',
};
const toggleStyle = {
marginBottom: '1.5em',
color: darkGray,
cursor: 'pointer',
border: 'none',
display: 'block',
width: '100%',
textAlign: 'left',
background: '#fff',
fontFamily: 'Consolas, Menlo, monospace',
fontSize: '1em',
padding: '0px',
lineHeight: '1.5',
};
type Props = {|
frame: StackFrameType,
contextSize: number,
critical: boolean,
showCode: boolean,
editorHandler: (errorLoc: ErrorLocation) => void,
|};
type State = {|
compiled: boolean,
|};
class StackFrame extends Component<Props, State> {
state = {
compiled: false,
};
toggleCompiled = () => {
this.setState(state => ({
compiled: !state.compiled,
}));
};
getErrorLocation(): ErrorLocation | null {
const {
_originalFileName: fileName,
_originalLineNumber: lineNumber,
} = this.props.frame;
// Unknown file
if (!fileName) {
return null;
}
// e.g. "/path-to-my-app/webpack/bootstrap eaddeb46b67d75e4dfc1"
const isInternalWebpackBootstrapCode = fileName.trim().indexOf(' ') !== -1;
if (isInternalWebpackBootstrapCode) {
return null;
}
// Code is in a real file
return { fileName, lineNumber: lineNumber || 1 };
}
editorHandler = () => {
const errorLoc = this.getErrorLocation();
if (!errorLoc) {
return;
}
this.props.editorHandler(errorLoc);
};
onKeyDown = (e: SyntheticKeyboardEvent<>) => {
if (e.key === 'Enter') {
this.editorHandler();
}
};
render() {
const { frame, contextSize, critical, showCode } = this.props;
const {
fileName,
lineNumber,
columnNumber,
_scriptCode: scriptLines,
_originalFileName: sourceFileName,
_originalLineNumber: sourceLineNumber,
_originalColumnNumber: sourceColumnNumber,
_originalScriptCode: sourceLines,
} = frame;
const functionName = frame.getFunctionName();
const compiled = this.state.compiled;
const url = getPrettyURL(
sourceFileName,
sourceLineNumber,
sourceColumnNumber,
fileName,
lineNumber,
columnNumber,
compiled
);
let codeBlockProps = null;
if (showCode) {
if (
compiled &&
scriptLines &&
scriptLines.length !== 0 &&
lineNumber != null
) {
codeBlockProps = {
lines: scriptLines,
lineNum: lineNumber,
columnNum: columnNumber,
contextSize,
main: critical,
};
} else if (
!compiled &&
sourceLines &&
sourceLines.length !== 0 &&
sourceLineNumber != null
) {
codeBlockProps = {
lines: sourceLines,
lineNum: sourceLineNumber,
columnNum: sourceColumnNumber,
contextSize,
main: critical,
};
}
}
const canOpenInEditor =
this.getErrorLocation() !== null && this.props.editorHandler !== null;
return (
<div>
<div>
{functionName}
</div>
<div style={linkStyle}>
<a
style={canOpenInEditor ? anchorStyle : null}
onClick={canOpenInEditor ? this.editorHandler : null}
onKeyDown={canOpenInEditor ? this.onKeyDown : null}
tabIndex={canOpenInEditor ? '0' : null}
>
{url}
</a>
</div>
{codeBlockProps &&
<span>
<a
onClick={canOpenInEditor ? this.editorHandler : null}
style={canOpenInEditor ? codeAnchorStyle : null}
>
<CodeBlock {...codeBlockProps} />
</a>
<button style={toggleStyle} onClick={this.toggleCompiled}>
{'View ' + (compiled ? 'source' : 'compiled')}
</button>
</span>}
</div>
);
}
}
export default StackFrame;
|
components/NewWordForm/NewWordForm.js | nelseric/fhack-yo | import React, { Component } from 'react';
import Actions from '../../lib/Actions';
import WordStore from '../../lib/WordStore';
class NewWordForm extends Component {
constructor(){
super();
this.state = {newWord: ""};
this._handleNewWordChange = this._handleNewWordChange.bind(this);
this._handleFormSubmit = this._handleFormSubmit.bind(this);
}
_handleFormSubmit(evt){
evt.preventDefault();
Actions.addWord(this.state.newWord);
this.setState({newWord: ""});
}
_handleNewWordChange(evt){
this.setState({newWord: evt.target.value});
}
render(){
return(
<form onSubmit={this._handleFormSubmit}>
<input value={this.state.newWord} onChange={this._handleNewWordChange} />
<button type="submit">Add Word</button>
</form>
);
}
}
export default NewWordForm;
|
www/src/components/PropExample.js | haneev/react-widgets | import get from 'lodash/get'
import PropTypes from 'prop-types';
import React from 'react';
import EditableExample from './EditableExample';
const examples = require.context('../examples', false)
const keys = examples.keys();
const propTypes = {
prop: PropTypes.object.isRequired,
displayName: PropTypes.string.isRequired,
};
function PropExample({ prop, displayName }) {
let example = get(prop, 'doclets.example', null);
let exampleName = example;
let args;
if (typeof example === 'string')
example = eval(example);
if (Array.isArray(example)) {
[exampleName, args] = example
}
if (exampleName === false) return null;
if (!exampleName) exampleName = prop.name;
if (!keys.includes(`./${exampleName}`)) return null;
args = args == null ? [] : [].concat(args);
return (
<EditableExample
codeText={examples(`./${exampleName}`).default(displayName, ...args)}
/>
);
}
PropExample.propTypes = propTypes;
export default PropExample;
export const propFragment = graphql`
fragment PropExample_prop on ComponentProp {
name
doclets
}
`
|
src/renderer/components/account-switcher.js | r7kamura/retro-twitter-client | import React from 'react';
export default class AccountSwitcher extends React.Component {
render() {
return(
<div className="account-switcher">
<ul className="accounts">
<li className="accounts-item accounts-item-selected">
<img className="accounts-item-avatar" src={this.props.account.profile_image_url} />
<div className="accounts-item-key">
⌘1
</div>
</li>
</ul>
</div>
);
}
}
|
test/helpers/shallowRenderHelper.js | superyorklin/gallery-by-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
src/svg-icons/notification/phone-bluetooth-speaker.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationPhoneBluetoothSpeaker = (props) => (
<SvgIcon {...props}>
<path d="M14.71 9.5L17 7.21V11h.5l2.85-2.85L18.21 6l2.15-2.15L17.5 1H17v3.79L14.71 2.5l-.71.71L16.79 6 14 8.79l.71.71zM18 2.91l.94.94-.94.94V2.91zm0 4.3l.94.94-.94.94V7.21zm2 8.29c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1z"/>
</SvgIcon>
);
NotificationPhoneBluetoothSpeaker = pure(NotificationPhoneBluetoothSpeaker);
NotificationPhoneBluetoothSpeaker.displayName = 'NotificationPhoneBluetoothSpeaker';
NotificationPhoneBluetoothSpeaker.muiName = 'SvgIcon';
export default NotificationPhoneBluetoothSpeaker;
|
src/Components/Login.js | NickGlenn/React-Project | import React, { Component } from 'react';
export default class Login extends Component {
static propTypes = {
onLogin: React.PropTypes.func
};
static defaultProps = {
};
onLogin () {
let email = this.refs.email.value;
let pass = this.refs.pass.value;
if (this.props.onLogin) this.props.onLogin(email, pass);
}
render () {
return (
<div className='login'>
{ this.props.isLoading ? 'Logging in...' : null }
<input type='email' ref='email' placeholder='E-Mail Address' />
<input type='password' ref='pass' placeholder='Password' />
<button
onClick={this.onLogin.bind(this)}
disabled={this.props.isLoading}>
Login
</button>
</div>
);
}
}
|
Components/SplashScreen.js | colm2/mizen | import React, { Component } from 'react';
import {
View,
StatusBar,
StyleSheet,
Image,
ActivityIndicator
} from 'react-native';
import Spacing from './Spacing';
export class SplashScreen extends Component{
render(){
return (
<View style={styles.splashScreen}>
<Spacing />
<Image source={require('./splashimg.png')}
style={{width: 400, height:400}} />
<ActivityIndicator
animating={true}
style={{height: 80}}
size="large"
color="white"
/>
</View>
);
}
}
const styles = StyleSheet.create({
splashScreen: {
flex: 1,
backgroundColor: '#2196f3',
justifyContent: 'center',
alignItems: 'center'
},
});
export default SplashScreen; |
components/BtnGroup/BtnGroup.story.js | NGMarmaduke/bloom | import React from 'react';
import { storiesOf } from '@storybook/react';
import cx from 'classnames';
import Medallion from '../Medallion/Medallion';
import m from '../../globals/modifiers.css';
import BtnGroup from './BtnGroup';
import Icon from '../Icon/Icon';
import Btn from '../Btn/Btn';
storiesOf('BtnGroup', module)
.add('Default Button Group', () => (
<BtnGroup>
<Btn>
<Icon className={ m.mrRegular } name="filter" />
Filters
<Medallion className={ cx(m.mlRegular, m.fr) }>1</Medallion>
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="map" /> Map
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="bogroll" /> Flush
</Btn>
</BtnGroup>
))
.add('Primary Button Group', () => (
<BtnGroup context="primary">
<Btn>
<Icon className={ m.mrRegular } name="filter" />
Filters
<Medallion className={ cx(m.mlRegular, m.fr) }>1</Medallion>
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="map" /> Map
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="bogroll" /> Flush
</Btn>
</BtnGroup>
))
.add('Action Button Group', () => (
<BtnGroup context="action">
<Btn>
<Icon className={ m.mrRegular } name="filter" />
Filters
<Medallion className={ cx(m.mlRegular, m.fr) }>12</Medallion>
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="map" /> Map
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="bogroll" /> Flush
</Btn>
</BtnGroup>
))
.add('Danger Button Group', () => (
<BtnGroup context="danger">
<Btn>
<Icon className={ m.mrRegular } name="filter" />
Filters
<Medallion className={ cx(m.mlRegular, m.fr) }>124</Medallion>
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="map" /> Map
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="bogroll" /> Flush
</Btn>
</BtnGroup>
))
.add('Whiteout Button Group', () => (
<BtnGroup context="whiteout">
<Btn>
<Icon className={ m.mrRegular } name="filter" />
Filters
<Medallion variant="dark" className={ cx(m.mlRegular, m.fr) }>9001</Medallion>
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="map" /> Map
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="bogroll" /> Flush
</Btn>
</BtnGroup>
))
.add('High priority Button Group', () => (
<BtnGroup priority="high">
<Btn>
<Icon className={ m.mrRegular } name="filter" />
Filters
<Medallion className={ cx(m.mlRegular, m.fr) }>1</Medallion>
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="map" /> Map
</Btn>
<Btn>
<Icon className={ m.mrRegular } name="bogroll" /> Flush
</Btn>
</BtnGroup>
));
|
rmod/src/components/__name__/__Name__.js | caohaijiang/dingyou-dingtalk-mobile | require('./<%- Name %>.less');
import React from 'react';
import { WhiteSpace, WingBlank, List, } from "antd-mobile";
/* import <%- Name %> from 'components/<%= name %>';
<<%- Name %> attribute={ } attribute={ } attribute={ } />
attribute: 说明
https://mobile.ant.design/components/<%- name %>
*/
const Item = List.Item;
class <%- Name %> extends React.Component {
constructor(props){super( props );
this.state = { value:this.props.defaultValue, };
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
}
handleChange(val){
this.setState({ value:val });
}
handleClick(val){
this.setState({ value:val });
}
render() {
const {{ value }} = this.state;
const {{ keyname, title, data, defaultValue, extra, only=true, onChange }} = this.props;
return (
<div className="<%= name %> ">
component <%= name %>
</div>
);
}
}
export default <%- Name %> ; |
teamlog/src/main/webapp/src/components/base/input/CInput.js | suxi-666666/learn | import React from 'react';
import PropTypes from 'prop-types';
import {
Form,
Input,
InputNumber,
Checkbox,
Radio,
Select,
Switch,
TreeSelect,
TimePicker,
DatePicker,
AutoComplete,
Cascader,
Slider,
Rate,
Mention,
Transfer,
Upload,
Col
} from 'antd';
const {MonthPicker, RangePicker, WeekPicker} = DatePicker;
const CheckboxGroup = Checkbox.Group;
const FormItem = Form.Item;
export const inputTypes = [
'input',
'number',
'checkbox',
'radio',
'select',
'switch',
'tree',
'time',
'date',
'month',
'range',
'week',
'autocomplete',
'cascader',
'slider',
'rate',
'mention',
'transfer',
'upload'
];
const inputTypeNode = {};
inputTypeNode[inputTypes[0]] = Input;
inputTypeNode[inputTypes[1]] = InputNumber;
inputTypeNode[inputTypes[2]] = CheckboxGroup;
inputTypeNode[inputTypes[3]] = Radio;
inputTypeNode[inputTypes[4]] = Select;
inputTypeNode[inputTypes[5]] = Switch;
inputTypeNode[inputTypes[6]] = TreeSelect;
inputTypeNode[inputTypes[7]] = TimePicker;
inputTypeNode[inputTypes[8]] = DatePicker;
inputTypeNode[inputTypes[9]] = MonthPicker;
inputTypeNode[inputTypes[10]] = RangePicker;
inputTypeNode[inputTypes[11]] = WeekPicker;
inputTypeNode[inputTypes[12]] = AutoComplete;
inputTypeNode[inputTypes[13]] = Cascader;
inputTypeNode[inputTypes[14]] = Slider;
inputTypeNode[inputTypes[15]] = Rate;
inputTypeNode[inputTypes[16]] = Mention;
inputTypeNode[inputTypes[17]] = Transfer;
inputTypeNode[inputTypes[18]] = Upload;
import commonProps from '../../../common/CommonProps';
class CInput extends React.Component {
render () {
const props = this.props;
const {inputType, type, label, field, rules, wrapCol = true} = props;
const {getFieldDecorator} = props.form;
let placeholder = `请输入${label}`;
switch (inputType) {
case inputTypes[4]:
case inputTypes[8]:
placeholder = `请选择${label}`;
break;
case inputTypes[10]:
placeholder = ['开始日期', '结束日期'];
break;
}
const inputProps = {placeholder: placeholder, ...commonProps.inputProps(), ...props.inputProps};
if (type && type === 'hidden') {
return (
getFieldDecorator(field, rules)(
<Input {...inputProps} type={type} value={props.value}/>
)
);
}
const formItemProps = {...commonProps.formItem6Props(), ...props.formItemProps, label: label};
const InputNode = inputTypes.indexOf(inputType) > -1 ? inputTypeNode[inputType] : inputTypeNode[inputTypes[0]];
const InputNodeItem = (
<FormItem {...formItemProps}>
{getFieldDecorator(field, rules)(
<InputNode {...inputProps}/>
)}
</FormItem>
);
if (wrapCol) {
let colProps = {...commonProps.col6Props(), ...props.colProps};
return (
<Col {...colProps}>
{InputNodeItem}
</Col>
);
}
return ({InputNodeItem});
}
}
CInput.propTypes = {
type: PropTypes.string,
form: PropTypes.object.isRequired,
label: PropTypes.string,
field: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
rules: PropTypes.arrayOf(PropTypes.object),
options: PropTypes.array,
formItemProps: PropTypes.object,
inputProps: PropTypes.object,
inputType: PropTypes.oneOf(inputTypes),
wrapCol: PropTypes.bool,
colProps: PropTypes.object,
};
export default CInput; |
src/svg-icons/image/adjust.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAdjust = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10 10-4.49 10-10S17.51 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 8zm3-8c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3z"/>
</SvgIcon>
);
ImageAdjust = pure(ImageAdjust);
ImageAdjust.displayName = 'ImageAdjust';
ImageAdjust.muiName = 'SvgIcon';
export default ImageAdjust;
|
src/modules/query/containers/container-query.js | otissv/graphql-guru-ide | import React from 'react';
import axios from 'axios';
import autobind from 'class-autobind';
import { connect } from '../../../store';
import getClassMethods from '../../../helpers/get-class-methods';
import { buildClientSchema, parse, print } from 'graphql';
import cuid from 'cuid';
import { initialState } from '../redux/redux-query';
import { initialState as formsInitialState } from '../../forms/redux/redux-forms';
class GraphiQLContainer extends React.Component {
constructor () {
super(...arguments);
autobind(this);
this.query = {
id: null,
collection: { value: this.props.forms.saveForm.fields.collection.value },
query: '',
variables: ''
};
}
componentWillMount () {
const {
createQueryCollections,
createQueryHistory,
getQueries,
selectedQuery
} = this.props;
const endpoint = selectedQuery.endpoint;
if (endpoint && endpoint.trim() !== '') {
// fetch graphql schema
this.getGraphQLSchema(endpoint);
// fetch queries and history from server
getQueries().payload
.then(response => {
if (response.data.ideQueryFindAll) {
createQueryCollections(response.data.ideQueryFindAll);
}
if (response.data.ideQueryHistoryFindAll) {
createQueryHistory(response.data.ideQueryHistoryFindAll);
}
})
.catch(error => console.log(error));
}
}
buildSchema () {
if (this.props.introspection.__schema) {
return buildClientSchema(this.props.introspection);
} else {
return null;
}
}
fetcher (graphQLParams) {
if (graphQLParams.query === '') {
return Promise.resolve('Please provide a query.');
} else {
const {
addQueryHistoryItem,
saveQueryHistory,
selectedQuery,
setQueryResultProps,
setSelectedQuery
} = this.props;
const endpoint = selectedQuery.endpoint;
// axios defaults
axios.defaults.baseURL = endpoint;
axios.defaults.headers.post['Content-Type'] =
'application/x-www-form-urlencoded';
const axiosConfig = {
url: endpoint,
method: 'POST'
};
const startResponseTime = new Date().getTime();
return axios({
...axiosConfig,
data: graphQLParams
})
.then(response => {
const payload = {
endpoint,
query: graphQLParams.query,
results: {
request: {
data: response.config.data,
headers: response.config.headers,
method: 'POST',
url: response.config.url,
xsrfCookieName: response.config.xsrfCookieName,
xsrfHeaderName: response.config.xsrfHeaderName
},
headers: response.headers,
status: `${response.status} ${response.statusText}`,
code: 200,
time: `${new Date().getTime() - startResponseTime}`,
response: response.data
},
variables: graphQLParams.variables
? JSON.stringify(graphQLParams.variables)
: ''
};
const date = Date.parse(new Date());
setSelectedQuery({
...selectedQuery,
...this.query,
...payload
});
addQueryHistoryItem({
[date]: payload
});
saveQueryHistory({
[date]: payload
});
return response.data.data;
})
.catch(error => {
if (error.response) {
console.log(error.response);
// Response status code 2xx
setQueryResultProps({
response: error.response.data,
status: `${error.response.status} failed`,
code: parseInt(error.response.code, 10),
headers: error.response.headers
});
} else if (error.request) {
// No response was received
console.log(error.request);
setQueryResultProps({
response: error.response.data,
status: '502 failed...',
code: 502,
headers: {}
});
} else {
console.log(error);
setQueryResultProps({
response: 'Connection failed',
status:'500 failed',
code: 500,
headers: {}
});
}
});
}
}
handleClickPrettify (event) {
const { setSelectedQuery, selectedQuery } = this.props;
const query =
this.query.query.trim() !== ''
? this.query.query.trim()
: selectedQuery.query;
const prettyText = this.prettyQuery(query);
setSelectedQuery({
...selectedQuery,
query: prettyText
});
}
handelOnEditQuery (query) {
this.query.query = query;
}
handelOnEditVariables (variables) {
this.query.variables = variables;
}
handleClickRest () {
this.query = {
id: null,
collection: { value: '' },
query: '',
variables: ''
};
this.props.selectedQueryToInitialState();
this.forceUpdate();
this.props.resetForm('saveForm');
}
setInfoModal (bool) {
this.props.setUiQueryProps({ isInfoModalOpen: bool });
}
setSaveModal (bool) {
const { selectedQuery, setQueryResultProps, setUiQueryProps, setSaveFormFields, setSelectedQueryProps } = this.props;
setSelectedQueryProps({ query: this.query.query });
setSaveFormFields({
name: { value: selectedQuery.name },
collection: { value: selectedQuery.collection },
description: { value: selectedQuery.description }
});
if ((this.query.query === '') && (selectedQuery.query.trim() === '')) {
setQueryResultProps({ response: 'Please provide a query.' });
} else {
setUiQueryProps({ isSaveModalOpen: bool });
}
}
handleClickSave (values) {
const {
addQueryCollection,
createQuery,
resetForm,
selectedQuery,
setSelectedQuery,
setUiQueryProps
} = this.props;
const { collection, description, name } = values;
const data = {
...this.query,
collection,
description,
endpoint: selectedQuery.endpoint,
id: selectedQuery.id || cuid(),
name,
results: JSON.stringify(selectedQuery.results)
};
setSelectedQuery(data);
addQueryCollection(data);
createQuery(data).payload
.then(response => {
if (response.data.ideQueryCreate.RESULTS_.result === 'failed') {
}
})
.catch(error => console.log(error));
setUiQueryProps({ isSaveModalOpen: false });
resetForm('saveForm');
}
validateSaveModule (data) {
const errors = {};
const { name, collection } = data;
if (collection == null || collection.trim() === '') {
errors.collection = 'Please enter a collection name';
}
if (name == null || name.trim() === '') {
errors.name = 'Please enter a query name';
}
return Object.keys(errors).length !== 0 ? errors : null;
}
showSidebarQueryCollection (event) {
this.props.setUiQueryProps({ sidebarQueryContent: 'collection' });
}
showSidebarQueryHistory (event) {
this.props.setUiQueryProps({ sidebarQueryContent: 'history' });
}
handleQueryCollectionItemClick (event) {
if (event.nativeEvent.target.tagName.toUpperCase() === 'BUTTON') return;
const { queryCollectionAll, selectedQuery, setSelectedQuery } = this.props;
const target = event.nativeEvent.target;
const id = target.dataset.kitid;
const collection =
target.parentNode.dataset.collection || target.dataset.collection;
const query = queryCollectionAll[collection][id];
this.getGraphQLSchema(query.endpoint);
if (query.id !== selectedQuery.id) {
this.query = {
collection: { value: query.collection },
description: query.description,
id: query.id,
name: query.name,
query: query.query,
variables: query.variables
};
setSelectedQuery({
...query,
results: {
...query.results,
status: 'Waiting...',
time: null
}
});
} else {
setSelectedQuery({
...query,
results: initialState.selectedQuery.results
});
}
}
handleQueryHistoryItemClick (event) {
const {
initialState,
queryHistoryAll,
setQueryResultProps,
setSelectedQuery
} = this.props;
const target = event.nativeEvent.target;
const id = target.dataset.kitid;
const historyItem = queryHistoryAll[id];
const data = {
...initialState.query.selectedQuery,
...historyItem
};
this.query.query = data.query;
this.query.variables = data.variables;
this.getGraphQLSchema(historyItem.endpoint);
setSelectedQuery(data);
setQueryResultProps({ status: 'Waiting' });
}
getGraphQLSchema (endpoint) {
const {
getGraphqlSchema,
selectedQuery,
setGraphqlSchema,
setSchemaIsConnected
} = this.props;
if (endpoint !== selectedQuery.endpoint) {
getGraphqlSchema(endpoint).payload
.then(response => {
if (response.data && response.data.__schema) {
setGraphqlSchema(response.data);
setSchemaIsConnected(true);
}
})
.catch(error => {
console.log(error);
setGraphqlSchema({});
setSchemaIsConnected(false);
});
}
}
prettyQuery (query) {
return print(parse(query));
}
getQuery () {
const { selectedQuery } = this.props;
if (this.query.query.trim() !== '') {
return this.prettyQuery(this.query.query);
} else if (selectedQuery.query && selectedQuery.query.trim() !== '') {
return this.prettyQuery(selectedQuery.query);
} else {
return '';
}
}
render () {
const { component, uiQueryEditor, selectedQuery } = this.props;
const { gqlTheme, gqlThemePaper } = uiQueryEditor;
const query = this.getQuery();
const variables = selectedQuery ? selectedQuery.variables : '';
const Component = component;
const schema = this.buildSchema();
const _response =
JSON.stringify(selectedQuery.results.response, null, 2) || '';
const response =
_response.trim() === '' || _response === '{}' || _response === '""'
? null
: _response;
return (
<div
className={`graphiql-theme ${gqlTheme} ${gqlThemePaper ? 'paper' : ''}`}
>
<Component
{...getClassMethods(this)}
query={query}
response={response}
variables={variables}
schema={schema}
operationName={null}
storage={null}
defaultQuery={null}
onEditQuery={this.handelOnEditQuery}
onEditVariables={this.handelOnEditVariables}
onEditOperationName={null}
getDefaultFieldNames={null}
editorTheme={gqlTheme}
resultTheme={gqlTheme}
result={selectedQuery.results}
queryCollection={this.query.collection.value}
/>
</div>
);
}
}
export default connect(GraphiQLContainer);
|
src/components/chars.js | mcekiera/hangman | import React from 'react';
function renderChars(chars) {
console.log(chars);
const data = [];
for(let i = 0; i < chars.length; i += 1) {
data.push(<p key={i}>{chars[i]}</p>)
}
return data;
}
export default (props) => {
return (
<div className='hangman__charbox'>
{renderChars(props.chars)}
</div>
);
} |
frontend/component/MarkdownEditor.js | a2393439531/nodepractice | import React from 'react';
import Codemirror from 'react-codemirror';
import 'codemirror/lib/codemirror.css';
import 'codemirror/mode/gfm/gfm';
import '../lib/style.css';
export default class MarkdownEditor extends React.Component {
render() {
return (
<Codemirror value={this.props.value} options={{
mode: 'gfm',
lineNumbers: false,
theme: 'default',
viewportMargin: Infinity,
}} onChange={(value) => this.props.onChange({target: {value}})} />
)
}
}
|
src/components/vis/BubbleRowChart.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import * as d3 from 'd3';
import { FormattedMessage, injectIntl } from 'react-intl';
const DEFAULT_WIDTH = 530;
const DEFAULT_MIN_BUBBLE_RADIUS = 5;
const DEFAULT_MAX_BUBBLE_RADIUS = 70;
const DEFAULT_HEIGHT = 200;
const PADDING_BETWEEN_BUBBLES = 10;
const DEFAULT_DOM_ID = 'bubble-chart-wrapper';
const localMessages = {
noData: { id: 'chart.bubble.noData', defaultMessage: 'Sorry, but we don\'t have any data to draw this chart.' },
};
function drawViz(wrapperElement, {
data, width, height, minCutoffValue, maxBubbleRadius, asPercentage, minBubbleRadius, padding,
domId, onBubbleClick,
}) {
// const { formatNumber } = this.props.intl;
const options = {
width,
height,
maxBubbleRadius,
minBubbleRadius,
padding,
minCutoffValue,
};
if ((width === null) || (width === undefined)) {
options.width = DEFAULT_WIDTH;
}
if ((height === null) || (height === undefined)) {
options.height = DEFAULT_HEIGHT;
}
if ((minBubbleRadius === null) || (minBubbleRadius === undefined)) {
options.minBubbleRadius = DEFAULT_MIN_BUBBLE_RADIUS;
}
if ((maxBubbleRadius === null) || (maxBubbleRadius === undefined)) {
options.maxBubbleRadius = DEFAULT_MAX_BUBBLE_RADIUS;
}
if ((padding === null) || (padding === undefined)) {
options.padding = 0;
}
if (minCutoffValue === null || minCutoffValue === undefined) {
options.minCutoffValue = 0;
}
let circles = null;
// prep the data and some config (scale by sqrt of value so we map to area, not radius)
const maxValue = d3.max(data.map(d => d.value));
let radiusScale;
// We size bubbles based on area instead of radius
if (asPercentage) {
radiusScale = d3.scaleSqrt().domain([0, 1]).range([0, options.maxBubbleRadius]);
} else {
radiusScale = d3.scaleSqrt().domain([0, maxValue]).range([0, options.maxBubbleRadius]);
}
const trimmedData = data.filter(d => (d.value > options.minCutoffValue ? d : null));
if (asPercentage) {
circles = trimmedData.map((d, idx) => {
let xOffset = 0;
xOffset = options.maxBubbleRadius + (((options.maxBubbleRadius * 2) + PADDING_BETWEEN_BUBBLES) * idx);
return {
...d,
scaledRadius: radiusScale(d.value),
y: 0,
x: xOffset,
};
});
} else {
circles = trimmedData.map((d, idx, list) => {
let xOffset = 0;
const scaledRadius = radiusScale(d.value);
if (idx > 0) {
const preceeding = list.slice(0, idx);
const diameters = preceeding.map(d2 => (radiusScale(d2.value) * 2) + PADDING_BETWEEN_BUBBLES);
xOffset = d3.sum(diameters);
}
xOffset += scaledRadius;
return {
...d,
scaledRadius,
y: 0,
x: xOffset,
};
});
}
if (circles && circles.length > 0) {
// render it all
const node = d3.select(wrapperElement).html(''); // important to empty this out
const div = node.append('div').attr('id', 'bubble-chart-wrapper');
const svg = div.append('svg:svg');
svg.attr('id', domId || DEFAULT_DOM_ID)
.attr('width', options.width)
.attr('height', options.height)
.attr('class', 'bubble-chart');
// rollover tooltip
const rollover = d3.select('#bubble-chart-tooltip')
.style('opacity', 0);
// calculate the diameter of all the circles, subtract that from the width and divide by two
const paddingAroundAllBubbles = (options.width - ((options.maxBubbleRadius * 2 * circles.length) + (PADDING_BETWEEN_BUBBLES * (circles.length - 1)))) / 2;
const horizontalTranslaton = paddingAroundAllBubbles;
// draw background circles
if (asPercentage) {
const totalBubbles = svg.append('g')
.attr('transform', `translate(${horizontalTranslaton},${options.height / 2})`)
.selectAll('.total-bubble')
.data(circles)
.enter();
totalBubbles.append('circle')
.attr('class', 'total')
.attr('r', options.maxBubbleRadius)
.attr('cx', d => d.x)
.attr('cy', d => d.y);
}
// now add the bubbles on top
const bubbles = svg.append('g')
.attr('transform', `translate(${horizontalTranslaton},${options.height / 2})`)
.selectAll('.bubble')
.data(circles)
.enter();
const cursor = onBubbleClick ? 'pointer' : '';
bubbles.append('circle')
.attr('class', 'pct')
.attr('r', d => d.scaledRadius)
.attr('cx', d => d.x)
.attr('cy', d => d.y)
.style('fill', d => d.fill || '')
.style('cursor', () => cursor);
// add tooltip to bubbles
bubbles.selectAll('circle')
.on('mouseover', (d) => {
const pixel = 'px';
rollover.html(d.rolloverText ? d.rolloverText : '')
.style('left', d3.event.pageX + pixel)
.style('top', d3.event.pageY + pixel);
rollover.transition().duration(200).style('opacity', 0.9);
})
.on('mouseout', () => {
rollover.transition().duration(500).style('opacity', 0);
})
.on('click', (d) => {
if (onBubbleClick) {
onBubbleClick(d);
}
});
// add center labels
bubbles.append('text')
.attr('x', d => d.x)
.attr('y', d => d.y + 4)
.attr('text-anchor', 'middle')
.attr('fill', d => (d.centerTextColor ? `${d.centerTextColor} !important` : ''))
.attr('font-family', 'Lato, Helvetica, sans')
.attr('font-size', '10px')
.text(d => (d.centerText ? d.centerText : ''));
// add top labels
bubbles.append('text')
.attr('x', d => d.x)
.attr('y', d => (asPercentage ? d.y - options.maxBubbleRadius - 12 : d.y - d.scaledRadius - 12))
.attr('text-anchor', 'middle')
.attr('fill', d => (d.aboveTextColor ? `${d.aboveTextColor} !important` : ''))
.attr('font-family', 'Lato, Helvetica, sans')
.attr('font-size', '10px')
.text(d => (d.aboveText ? d.aboveText : ''));
// add bottom labels
bubbles.append('text')
.attr('x', d => d.x)
.attr('y', d => (asPercentage ? d.y + options.maxBubbleRadius + 20 : d.y + d.scaledRadius + 20))
.attr('text-anchor', 'middle')
.attr('fill', d => (d.belowTextColor ? `${d.belowTextColor} !important` : ''))
.attr('font-family', 'Lato, Helvetica, sans')
.attr('font-size', '10spx')
.text(d => (d.belowText ? d.belowText : ''));
}
}
/**
* Draw a bubble chart with labels. Values are mapped to area, not radius.
*/
class BubbleRowChart extends React.Component {
constructor(props) {
super(props);
this.chartWrapperRef = React.createRef();
}
componentDidMount() {
drawViz(this.chartWrapperRef.current, this.props);
}
componentDidUpdate() {
drawViz(this.chartWrapperRef.current, this.props);
}
render() {
const { data } = this.props;
// bail if no data
if (data.length === 0) {
return (
<div>
<p><FormattedMessage {...localMessages.noData} /></p>
</div>
);
}
// otherwise there is data, so draw it
return (
<div className="bubble-row-chart-wrapper" ref={this.chartWrapperRef} />
);
}
}
BubbleRowChart.propTypes = {
intl: PropTypes.object.isRequired,
/*
[{
'value': number,
'fill': string(optional),
'centerText': string(optional),
'centerTextColor': string(optional),
'aboveText': string(optional),
'aboveTextColor': string(optional),
'belowText': string(optional),
'belowTextColor': string(optional),
'rolloverText': string(optional),
}]
*/
onBubbleClick: PropTypes.func,
data: PropTypes.array.isRequired,
domId: PropTypes.string, // to make download work
width: PropTypes.number,
height: PropTypes.number,
placement: PropTypes.string,
maxBubbleRadius: PropTypes.number,
minBubbleRadius: PropTypes.number,
minCutoffValue: PropTypes.number,
asPercentage: PropTypes.bool, // draw each circle as a pct of a larger one
padding: PropTypes.number,
};
export default injectIntl(BubbleRowChart);
|
shared/components/TodoInput.js | gzoreslav/panda-iso | import React from 'react';
const ESCAPE_KEY = 27;
const ENTER_KEY = 13;
class TodoList extends React.Component {
handleKeyDown(event) {
if (event.which !== ENTER_KEY) {
return;
}
event.preventDefault();
let value = this.refs.task.getDOMNode().value.trim();
if (value) {
this.props.handleNewTask(value);
this.refs.task.getDOMNode().value = '';
}
}
render() {
return (
<input className="new-todo"
placeholder="What needs to be done?"
onKeyDown={this.handleKeyDown.bind(this)}
ref="task" />
);
}
}
export default TodoList;
|
src/commons/DisplayIfCond.js | zenria/react-redux-sandbox | import React from 'react';
const DisplayIfCond = ({cond, children})=> (
cond && children
)
export default DisplayIfCond;
|
src/js/components/Tabs/stories/Scrollable.js | HewlettPackard/grommet | import React from 'react';
import { Box, Heading, Tab, Tabs } from 'grommet';
import { TreeOption } from 'grommet-icons';
const ScrollableTabs = () => (
// Uncomment <Grommet> lines when using outside of storybook
// <Grommet theme={...}>
<Box fill>
<Tabs flex>
<Tab title="Tab 1">
<Box
fill
overflow="auto"
pad="xlarge"
align="center"
background="accent-1"
>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
<Heading>hello!</Heading>
</Box>
</Tab>
<Tab title="Tab 2">
<Box margin="small" pad="large" align="center" background="accent-2">
<TreeOption size="xlarge" />
</Box>
</Tab>
</Tabs>
</Box>
// </Grommet>
);
export const Scrollable = () => <ScrollableTabs />;
Scrollable.args = {
full: true,
};
export default {
title: 'Controls/Tabs/Scrollable',
};
|
src/js/components/app.js | mtharrison/whereyouat | import React, { Component } from 'react';
import MapView from './map-view';
import RecentPins from './recent-pins';
import PinControls from './pin-controls';
import UserStatusBar from './user-status-bar';
export default ({
pins,
auth,
mapOptions,
updateMapPrefs,
addPin,
removeAllPins,
loginAttempt,
logoutAttempt,
recentPinClicked,
logs
}) => (
<div>
<div className="row">
<div className="col-md-12">
<div className="page-header" id="header">
<h1>whereyouat <small>share your memorable locations</small></h1>
<UserStatusBar
loginAttempt={loginAttempt}
logoutAttempt={logoutAttempt}
authData={auth.data}
/>
</div>
</div>
</div>
<div className="row">
<MapView
pins={pins}
center={mapOptions.center}
zoom={mapOptions.zoom}
updateMapPrefs={updateMapPrefs}
onRightClick={addPin}
/>
<RecentPins
pins={pins}
recentPinClicked={recentPinClicked}
/>
<PinControls
removeAllPins={removeAllPins}
/>
</div>
</div>
);
|
src/entypo/Mixi.js | cox-auto-kc/react-entypo | import React from 'react';
import EntypoIcon from '../EntypoIcon';
const iconClass = 'entypo-svgicon entypo--Mixi';
let EntypoMixi = (props) => (
<EntypoIcon propClass={iconClass} {...props}>
<path d="M9.546,17.258h0.955v2.143c6.51-0.684,9.982-7.143,9.421-11.691C19.358,3.16,14.471,0.018,8.978,0.69C3.486,1.364-0.49,5.598,0.072,10.149C0.585,14.287,4.674,17.262,9.546,17.258z M15.694,12.86h-1.831V7.907c0-0.199-0.018-0.387-0.053-0.557c-0.029-0.148-0.084-0.273-0.164-0.381c-0.076-0.1-0.187-0.182-0.33-0.244c-0.152-0.066-0.363-0.1-0.623-0.1c-0.537,0-0.957,0.141-1.251,0.416c-0.291,0.273-0.433,0.633-0.433,1.1v4.719H9.179V7.907c0-0.205-0.019-0.395-0.059-0.564c-0.034-0.15-0.091-0.277-0.173-0.387C8.87,6.854,8.768,6.778,8.633,6.719c-0.144-0.062-0.34-0.094-0.58-0.094c-0.312,0-0.58,0.059-0.795,0.174c-0.223,0.117-0.405,0.26-0.541,0.422C6.579,7.385,6.478,7.555,6.418,7.727C6.356,7.899,6.326,8.037,6.326,8.141v4.719H4.494V5.164h1.758v0.6c0.574-0.508,1.306-0.766,2.181-0.766c0.51,0,0.981,0.103,1.399,0.305c0.306,0.147,0.554,0.365,0.738,0.652c0.231-0.248,0.504-0.451,0.814-0.609c0.454-0.231,0.958-0.348,1.499-0.348c0.402,0,0.773,0.043,1.102,0.127c0.343,0.086,0.644,0.225,0.895,0.412c0.258,0.193,0.46,0.445,0.602,0.75c0.141,0.301,0.212,0.66,0.212,1.07V12.86z"/>
</EntypoIcon>
);
export default EntypoMixi;
|
views/blocks/Search/search.js | FairTex/team5 | import React from 'react';
import SearchBar from './../SearchBar/SearchBar';
import SearchResult from './../SearchResult/SearchResult';
import SearchResultItem from './../SearchResult/ResultItem';
import Card from './../QuestCard/questCard';
import constants from './../../constants/defaultStates';
const Searcher = require('./Searcher.js');
class Search extends React.Component {
constructor(props) {
super(props);
this.handleResultChange = this.handleResultChange.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.search = this.search.bind(this);
this.state = constants.defaultState;
}
componentDidMount() {
this.search(this.state.currentPage);
}
handleSubmit() {
this.search(1);
this.setState({
loading: true
});
}
search(newPageNumber) {
var params = Searcher.getSearchParameters(this.state, newPageNumber);
Searcher.searchRequest(params)
.then(function (response) {
return response.json();
})
.then(this.handleResultChange);
}
handleResultChange(data) {
this.setState({
result: data.quests,
currentPage: data.pageNumber,
pageCount: data.maxPageNumber,
loading: false
});
}
handleInputChange(name, value) {
this.setState({
[name]: value
});
}
renderResult() {
return (
<SearchResult currentPage={this.state.currentPage}
pageCount={this.state.pageCount} onPageChange={this.search}>
{this.state.result.map(card =>
<SearchResultItem key={card.slug.toString()}>
<Card card={card} />
</SearchResultItem>)}
</SearchResult>);
}
render() {
return (
<div className="Search">
<SearchBar handleSubmit={this.handleSubmit}
onInputChange={this.handleInputChange} params={this.state}/>
{(this.state.result.length > 0) ?
this.renderResult() :
!this.state.loading && <div>Таких квестов нет :(</div>}
</div>
);
}
}
export default Search;
|
mlflow/server/js/src/model-registry/components/RegisterModelButton.js | mlflow/mlflow | import React from 'react';
import _ from 'lodash';
import { Modal, Button } from 'antd';
import { FormattedMessage, injectIntl } from 'react-intl';
import {
RegisterModelForm,
CREATE_NEW_MODEL_OPTION_VALUE,
SELECTED_MODEL_FIELD,
MODEL_NAME_FIELD,
} from './RegisterModelForm';
import {
createRegisteredModelApi,
createModelVersionApi,
listRegisteredModelsApi,
searchModelVersionsApi,
searchRegisteredModelsApi,
} from '../actions';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Utils from '../../common/utils/Utils';
import { getUUID } from '../../common/utils/ActionUtils';
import { getModelNameFilter } from '../../model-registry/utils/SearchUtils';
const MAX_SEARCH_REGISTERED_MODELS = 5; // used in drop-down list so not many are visible at once
export class RegisterModelButtonImpl extends React.Component {
static propTypes = {
// own props
disabled: PropTypes.bool.isRequired,
runUuid: PropTypes.string.isRequired,
modelPath: PropTypes.string,
// connected props
modelByName: PropTypes.object.isRequired,
createRegisteredModelApi: PropTypes.func.isRequired,
createModelVersionApi: PropTypes.func.isRequired,
listRegisteredModelsApi: PropTypes.func.isRequired,
searchModelVersionsApi: PropTypes.func.isRequired,
searchRegisteredModelsApi: PropTypes.func.isRequired,
intl: PropTypes.shape({ formatMessage: PropTypes.func.isRequired }).isRequired,
};
state = {
visible: false,
confirmLoading: false,
modelByName: {},
};
createRegisteredModelRequestId = getUUID();
createModelVersionRequestId = getUUID();
searchModelVersionRequestId = getUUID();
constructor() {
super();
this.form = React.createRef();
}
showRegisterModal = () => {
this.setState({ visible: true });
};
hideRegisterModal = () => {
this.setState({ visible: false });
};
resetAndClearModalForm = () => {
this.setState({ visible: false, confirmLoading: false });
this.form.current.resetFields();
};
handleRegistrationFailure = (e) => {
this.setState({ confirmLoading: false });
Utils.logErrorAndNotifyUser(e);
};
handleSearchRegisteredModels = (input) => {
this.props.searchRegisteredModelsApi(getModelNameFilter(input), MAX_SEARCH_REGISTERED_MODELS);
};
reloadModelVersionsForCurrentRun = () => {
const { runUuid } = this.props;
return this.props.searchModelVersionsApi({ run_id: runUuid }, this.searchModelVersionRequestId);
};
handleRegisterModel = () => {
this.form.current.validateFields().then((values) => {
this.setState({ confirmLoading: true });
const { runUuid, modelPath } = this.props;
const selectedModelName = values[SELECTED_MODEL_FIELD];
if (selectedModelName === CREATE_NEW_MODEL_OPTION_VALUE) {
// When user choose to create a new registered model during the registration, we need to
// 1. Create a new registered model
// 2. Create model version #1 in the new registered model
this.props
.createRegisteredModelApi(values[MODEL_NAME_FIELD], this.createRegisteredModelRequestId)
.then(() =>
this.props.createModelVersionApi(
values[MODEL_NAME_FIELD],
modelPath,
runUuid,
this.createModelVersionRequestId,
),
)
.then(this.resetAndClearModalForm)
.catch(this.handleRegistrationFailure)
.then(this.reloadModelVersionsForCurrentRun)
.catch(Utils.logErrorAndNotifyUser);
} else {
this.props
.createModelVersionApi(
selectedModelName,
modelPath,
runUuid,
this.createModelVersionRequestId,
)
.then(this.resetAndClearModalForm)
.catch(this.handleRegistrationFailure)
.then(this.reloadModelVersionsForCurrentRun)
.catch(Utils.logErrorAndNotifyUser);
}
});
};
componentDidMount() {
this.props.listRegisteredModelsApi();
}
componentDidUpdate(prevProps, prevState) {
// Repopulate registered model list every time user launch the modal
if (prevState.visible === false && this.state.visible === true) {
this.props.listRegisteredModelsApi();
}
}
render() {
const { visible, confirmLoading } = this.state;
const { disabled, modelByName } = this.props;
return (
<div className='register-model-btn-wrapper'>
<Button
className='register-model-btn'
type='primary'
onClick={this.showRegisterModal}
disabled={disabled}
htmlType='button'
>
<FormattedMessage
defaultMessage='Register Model'
description='Button text to register the model for deployment'
/>
</Button>
<Modal
title={this.props.intl.formatMessage({
defaultMessage: 'Register Model',
description: 'Register model modal title to register the model for deployment',
})}
width={540}
visible={visible}
onOk={this.handleRegisterModel}
okText={this.props.intl.formatMessage({
defaultMessage: 'Register',
description: 'Confirmation text to register the model',
})}
confirmLoading={confirmLoading}
onCancel={this.hideRegisterModal}
centered
footer={[
<Button key='back' onClick={this.hideRegisterModal}>
<FormattedMessage
defaultMessage='Cancel'
description='Cancel button text to cancel the flow to register the model'
/>
</Button>,
<Button
key='submit'
type='primary'
onClick={this.handleRegisterModel}
data-test-id='confirm-register-model'
>
<FormattedMessage
defaultMessage='Register'
description='Register button text to register the model'
/>
</Button>,
]}
>
<RegisterModelForm
modelByName={modelByName}
innerRef={this.form}
onSearchRegisteredModels={_.debounce(this.handleSearchRegisteredModels, 300)}
/>
</Modal>
</div>
);
}
}
const mapStateToProps = (state) => ({
modelByName: state.entities.modelByName,
});
const mapDispatchToProps = {
createRegisteredModelApi,
createModelVersionApi,
listRegisteredModelsApi,
searchModelVersionsApi,
searchRegisteredModelsApi,
};
export const RegisterModelButtonWithIntl = injectIntl(RegisterModelButtonImpl);
export const RegisterModelButton = connect(
mapStateToProps,
mapDispatchToProps,
)(RegisterModelButtonWithIntl);
|
stories/pages/HomePage.js | suranartnc/react-universal-starter-kit | import React from 'react'
import { storiesOf } from '@kadira/storybook'
import faker from 'faker'
import HomePage from 'shared/pages/HomePage/HomePage'
import App from 'shared/pages/App/App'
const posts = [];
for (let i = 0; i < 5; ++i) {
posts.push({
id: i + 1,
title: faker.lorem.sentence(),
excerpt: faker.lorem.paragraphs(2),
body: faker.lorem.paragraphs(10),
name: `${faker.name.firstName()} ${faker.name.lastName()}`,
avatar: faker.image.avatar(),
tags: faker.lorem.sentence().replace('.', '').split(''),
pubDate: '2 hours ago'
})
}
storiesOf('Home Page', module)
.addDecorator((story) => (
<App children={story()} />
))
.add('default', () => (
<HomePage posts={posts} />
))
|
react/eventwizard/components/infoTab/SyncCodeInput.js | bdaroz/the-blue-alliance |
import React from 'react'
import PropTypes from 'prop-types'
import EVENT_SHAPE from '../../constants/ApiEvent'
const SyncCodeInput = (props) => (
<div className="form-group">
<label htmlFor="first_code" className="col-sm-2 control-label">
FIRST Sync Code
</label>
<div className="col-sm-10">
<input
type="text"
className="form-control"
id="first_code"
placeholder="IRI"
value={props.eventInfo && props.eventInfo.first_event_code}
disabled={props.eventInfo === null}
onChange={props.setSyncCode}
/>
</div>
</div>
)
SyncCodeInput.propTypes = {
eventInfo: PropTypes.shape(EVENT_SHAPE),
setSyncCode: PropTypes.func.isRequired,
}
export default SyncCodeInput
|
src/components/Layout/SearchDrawer/SearchOptionList/SearchOption/presenter.js | ndlib/usurper |
import React from 'react'
import PropTypes from 'prop-types'
const SearchOption = (props) => {
return (
<li
id={`uSearchOption_${props.index}`}
className='uSearchOption'
onClick={props.onClick}
onKeyDown={props.onKeyDown}
tabIndex={props.search.searchBoxOpen ? '0' : '-1'}
role='option'
value={props.index}
aria-selected={props.item.uid === props.search.searchType}
>
<p>{props.item.title}</p>
<small>{props.item.description}</small>
</li>
)
}
SearchOption.propTypes = {
onClick: PropTypes.func,
index: PropTypes.number,
item: PropTypes.shape({
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
uid: PropTypes.string.isRequired,
}).isRequired,
onKeyDown: PropTypes.func,
search: PropTypes.shape({
searchBoxOpen: PropTypes.bool,
searchType: PropTypes.string.isRequired,
}),
}
export default SearchOption
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js | aastey/react-router | /*globals COURSES:true */
import React from 'react'
import { Link } from 'react-router'
class Sidebar extends React.Component {
render() {
let { assignments } = COURSES[this.props.params.courseId]
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
)
}
}
export default Sidebar
|
src/app/config/Routes.js | allangrds/Terminator-React-Starter-Kit | import React from 'react';
import {
BrowserRouter as Router,
Switch,
Route,
browserHistory,
NavLink
} from 'react-router-dom';
/**/
import Orders from './Orders';
import Errors from './Errors';
import Home from '../components/Home';
const About = () => <h1>About</h1>;
const Links = () => (
<nav>
<NavLink exact activeClassName="active" to="/">Home </NavLink>
<NavLink activeClassName="active" to="/about">Sobre</NavLink>
<NavLink activeClassName="active" to="/orders">Pedidos</NavLink>
</nav>
);
const Routes = () => (
<Router history={browserHistory}>
<div>
<Links />
<Switch>
<Route exact path="/" component={Home} />
<Route path="/about" component={About} />
<Orders />
<Errors />
</Switch>
</div>
</Router>
);
export default Routes;
|
src/components/shared/Snippet/Snippet.js | AgtLucas/css-modules-playground | import styles from './Snippet.css';
import React from 'react';
export default class Snippet extends React.Component {
render() {
return(
<div className={styles.root}>
<div className={styles.output}>
<div className={styles.fileName}>Output</div>
<div className={styles.outputContent}>
{ this.props.children }
</div>
</div>
{
this.props.files.map(file => (
<div key={file.name} className={styles.file}>
<div className={styles.fileName}>{ file.name }</div>
<pre className={styles.pre}>{ file.source }</pre>
</div>
))
}
</div>
);
}
};
|
app/javascript/mastodon/features/favourites/index.js | verniy6462/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';
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', Number(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(Number(this.props.params.statusId)));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchFavourites(Number(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>
);
}
}
|
example/with-template/template.js | iansinnott/react-static-webpack-plugin | import React from 'react';
const Html = (props) => (
<html lang='en'>
<head>
<meta charSet='utf-8' />
<meta httpEquiv='X-UA-Compatible' content='IE=edge' />
<meta name='viewport' content='width=device-width, minimum-scale=1.0' />
<title>Super awesome package</title>
<script dangerouslySetInnerHTML={{ __html: 'console.log("analytics")' }} />
</head>
<body>
<div id='root' dangerouslySetInnerHTML={{ __html: props.body }} />
<script src='/app.js' />
</body>
</html>
);
export default Html;
|
src/components/form/InputTitle.js | ashmaroli/jekyll-admin | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import TextareaAutosize from 'react-textarea-autosize';
export default class InputTitle extends Component {
shouldComponentUpdate(nextProps) {
return nextProps.title !== this.props.title;
}
handleChange(e){
const { onChange } = this.props;
onChange(e.target.value);
}
render() {
const { title } = this.props;
return (
<div className="input-title">
<label>Title</label>
<TextareaAutosize
onChange={(e) => this.handleChange(e)}
placeholder="Title"
defaultValue={title}
ref="input" />
</div>
);
}
}
InputTitle.propTypes = {
title: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired
};
|
client/components/About.js | jordanallen98/nimblecode | import React, { Component } from 'react';
import AboutProfile from './AboutProfile.js';
var team = [{
key: 1,
name: "Mark Kim",
bio: "Completely synergize resource taxing relationships via premier niche markets. Professionally cultivate one-to-one customer service with robust ideas. Dynamically innovate resource-leveling customer service for state of the art customer service.",
image: "../assets/mark-profile.jpg",
git: "https://github.com/marksanghoonkim",
linked: "https://www.linkedin.com/in/marksanghoonkim"
}, {
key: 2,
name: "Rick Yeh",
bio: "Objectively innovate empowered manufactured products whereas parallel platforms. Holisticly predominate extensible testing procedures for reliable supply chains. Dramatically engage top-line web services vis-a-vis cutting-edge deliverables.",
image: "../assets/rick-profile.jpg",
git: "https://github.com/rickyeh",
linked: "https://www.linkedin.com/in/rickyeh"
}, {
key: 3,
name: "Jordan Allen",
bio: "Jordan is a Software Engineer who owned his own business at 21, is a avid, self taught(mostly), guitarist, and also has owned and worked on a couple project cars(0 - 60 around 4 seconds). He loves traveling around the world every chance he gets.",
image: "../assets/jordan-profile.jpg",
git: "https://github.com/jordanallen98",
linked: "https://www.linkedin.com/in/jordandallen"
}, {
key: 4,
name: "Nicholas Der",
bio: "Efficiently unleash cross-media information without cross-media value. Quickly maximize timely deliverables for real-time schemas. Dramatically maintain clicks-and-mortar solutions without functional solutions.",
image: "../assets/nick-profile.jpg",
git: "https://github.com/kiritsuzu",
linked: "https://www.linkedin.com/in/kiritsuzu"
}];
class About extends Component {
render() {
var Profiles = team.map(function(profile){
return ( <AboutProfile key={profile.key} name={profile.name} bio={profile.bio} image={profile.image} git={profile.git} linked={profile.linked}> </AboutProfile> );
});
return (
<div className="container">
<h2 className="text-center no-top-margin">Meet The Team</h2>
<h4 className="text-center"><a href="http://github.com/linearatworst/nimblecode"><i className="text-center fa fa-github-square fa-2x about-icon"></i></a> nimblecode repo</h4>
<div className="row row-spacer"></div>
<div className="">
{Profiles}
</div>
</div>
);
}
}
export default About;
|
node_modules/react-bootstrap/es/NavbarHeader.js | premcool/getmydeal | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { prefix } from './utils/bootstrapUtils';
var contextTypes = {
$bs_navbar: React.PropTypes.shape({
bsClass: React.PropTypes.string
})
};
var NavbarHeader = function (_React$Component) {
_inherits(NavbarHeader, _React$Component);
function NavbarHeader() {
_classCallCheck(this, NavbarHeader);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavbarHeader.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' };
var bsClassName = prefix(navbarProps, 'header');
return React.createElement('div', _extends({}, props, { className: classNames(className, bsClassName) }));
};
return NavbarHeader;
}(React.Component);
NavbarHeader.contextTypes = contextTypes;
export default NavbarHeader; |
src/scripts/pages/about.js | modesty/react2html | import React from 'react';
import Main from '../components/Main';
const About = ({chrome, page}) => {
return (
<Main chrome={chrome} page={page} >
<>
<h1>About React2Html</h1>
<p>More details can be found at <a href="https://github.com/modesty/react2html"> GitHub </a></p>
</>
</Main>
);
};
export default About;
|
daily-frontend/src/routes.js | zooyalove/dailynote | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import {
MainRoute,
WriteRoute,
OrdererRoute,
NullInfoRoute,
OrdererInfoRoute,
SearchRoute,
StatRoute,
LoginRoute
} from './containers/routes';
export default (
<Route path="/" component={App}>
<IndexRoute component={MainRoute} />
<Route path="login" component={LoginRoute} />
<Route path="write" component={WriteRoute} />
<Route path="orderer" component={OrdererRoute}>
<IndexRoute component={NullInfoRoute} />
<Route path=":userid" component={OrdererInfoRoute} />
</Route>
<Route path="search" component={SearchRoute} />
<Route path="stat" component={StatRoute} />
</Route>
);
|
src/svg-icons/image/filter-9-plus.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter9Plus = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm11 7V8c0-1.11-.9-2-2-2h-1c-1.1 0-2 .89-2 2v1c0 1.11.9 2 2 2h1v1H9v2h3c1.1 0 2-.89 2-2zm-3-3V8h1v1h-1zm10-8H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 8h-2V7h-2v2h-2v2h2v2h2v-2h2v6H7V3h14v6z"/>
</SvgIcon>
);
ImageFilter9Plus = pure(ImageFilter9Plus);
ImageFilter9Plus.displayName = 'ImageFilter9Plus';
ImageFilter9Plus.muiName = 'SvgIcon';
export default ImageFilter9Plus;
|
webpack/scenes/Hosts/ChangeContentSource/components/FormField.js | snagoor/katello | import React from 'react';
import {
FormGroup,
FormSelect,
FormSelectOption,
GridItem,
} from '@patternfly/react-core';
import { translate as __ } from 'foremanReact/common/I18n';
import PropTypes from 'prop-types';
const FormField = ({
label, id, value, items, onChange, isLoading, contentHostsCount,
}) => (
<GridItem span={7}>
<FormGroup label={label} fieldId={id} isRequired>
<FormSelect
value={value}
onChange={v => onChange(v)}
className="without_select2"
isDisabled={isLoading || items.length === 0 || contentHostsCount === 0}
id={`${id}_select`}
isRequired
>
<FormSelectOption key={0} value="" label={__('Select ...')} />
{items.map(item => (
<FormSelectOption key={item.id} value={item.id} label={item.name} />
))}
</FormSelect>
</FormGroup>
</GridItem>
);
FormField.propTypes = {
label: PropTypes.string.isRequired,
id: PropTypes.string.isRequired,
value: PropTypes.string.isRequired,
items: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
onChange: PropTypes.func.isRequired,
isLoading: PropTypes.bool.isRequired,
contentHostsCount: PropTypes.number.isRequired,
};
export default FormField;
|
src/svg-icons/image/linked-camera.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageLinkedCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="14" r="3.2"/><path d="M16 3.33c2.58 0 4.67 2.09 4.67 4.67H22c0-3.31-2.69-6-6-6v1.33M16 6c1.11 0 2 .89 2 2h1.33c0-1.84-1.49-3.33-3.33-3.33V6"/><path d="M17 9c0-1.11-.89-2-2-2V4H9L7.17 6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9h-5zm-5 10c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImageLinkedCamera = pure(ImageLinkedCamera);
ImageLinkedCamera.displayName = 'ImageLinkedCamera';
ImageLinkedCamera.muiName = 'SvgIcon';
export default ImageLinkedCamera;
|
src/routes/NotFound/NotFound.js | SteveHoggNZ/Choice-As | import React from 'react'
import { browserHistory } from 'react-router'
const goBack = (e) => {
e.preventDefault()
return browserHistory.goBack()
}
export const NotFound = () => (
<div>
<h4>Page not found!</h4>
<p><a href='#' onClick={goBack}>← Back</a></p>
</div>
)
export default NotFound
|
app/containers/App/index.js | gitlab-classroom/classroom-web | /**
*
* 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)
*/
import React from 'react';
import Helmet from 'react-helmet';
import styled from 'styled-components';
import Header from '../Header';
import ErrorIndicator from '../ErrorIndicator';
const AppWrapper = styled.div`
max-width: calc(960px + 16px * 2);
margin: 64px auto 0 auto;
display: flex;
min-height: 100%;
padding: 0 16px;
zIndex: 100;
flex-direction: column;
`;
function App(props) {
return (
<div>
<AppWrapper>
<Helmet
titleTemplate="%s - GitLab Classroom"
defaultTitle="GitLab Classroom"
meta={[
{ name: 'description', content: 'GitLab Classroom' },
]}
/>
{React.Children.toArray(props.children)}
</AppWrapper>
<Header />
<ErrorIndicator />
</div>
);
}
App.propTypes = {
children: React.PropTypes.node,
};
export default App;
|
src/components/Choice.js | quintel/etmobile | import React from 'react';
import PropTypes from 'prop-types';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import ChoiceButton from './ChoiceButton';
import IconOrBadge from './IconOrBadge';
const Choice = ({ index, selectedIndex, choice, onChoiceSelected, showExplanations }) => (
<div className="choice-info" key={`choice-${index}`}>
<div className="icon-wrapper">
<IconOrBadge
choice={choice}
index={index}
selectedIndex={selectedIndex}
onChoiceSelected={onChoiceSelected}
/>
</div>
<ReactCSSTransitionGroup
component="div"
transitionName={{ enter: 'fadeIn', leave: 'bounceOut' }}
transitionEnterTimeout={1000}
transitionLeaveTimeout={1000}
>
<ChoiceButton
key={`${index}-${selectedIndex === index ? '1' : '0'}`}
index={index}
isCorrect={choice.isCorrect}
onClick={onChoiceSelected}
selectedIndex={selectedIndex}
>
{choice.name}
</ChoiceButton>
</ReactCSSTransitionGroup>
<div style={{ position: 'relative' }}>
<ReactCSSTransitionGroup
component="div"
transitionName={{ enter: 'fadeIn', leave: 'fadeOut' }}
transitionEnterTimeout={1000}
transitionLeaveTimeout={1000}
>
<p
style={{ position: 'absolute' }}
className="description animated"
key={`choice-description-${showExplanations ? '0' : '1'}`}
dangerouslySetInnerHTML={{
__html: (showExplanations ? choice.why : choice.description)
}}
/>
</ReactCSSTransitionGroup>
</div>
</div>
);
// Choice shape prior to translations.
const sparseShapeObj = {
delta: PropTypes.number.isRequired,
icon: PropTypes.string.isRequired,
isCorrect: PropTypes.bool
};
Choice.propTypes = {
choice: PropTypes.shape({
...sparseShapeObj,
description: PropTypes.string.isRequired,
name: PropTypes.string.isRequired
}).isRequired,
index: PropTypes.number.isRequired,
selectedIndex: PropTypes.number,
onChoiceSelected: PropTypes.func.isRequired
};
export const sparseChoiceShape = PropTypes.shape(sparseShapeObj);
export default Choice;
|
src/js/containers/DevTools.js | pololanik/puzzle | import React from 'react';
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
import SliderMonitor from 'redux-slider-monitor';
// createDevTools takes a monitor and produces a DevTools component
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q"
changeMonitorKey="ctrl-m">
<LogMonitor theme="nicinabox" />
<SliderMonitor keyboardEnabled />
</DockMonitor>
);
|
src/components/GLMap.js | twelch/react-mapbox-gl-seed | import React, { Component } from 'react';
// NotWorkingShimInstead import mapboxgl from 'mapbox-gl';
require('script!mapbox-gl/dist/mapbox-gl-dev.js');
class GLMap extends Component {
static propTypes = {
// Default map view
view: React.PropTypes.object,
// Style of map container
mapStyle: React.PropTypes.object,
// Current base layer
baselayer: React.PropTypes.string,
// Mapbox map token
token: React.PropTypes.string,
// onStyleEvent fired after style loaded. Map object is passed
onStyleLoad: React.PropTypes.func
}
componentDidMount() {
mapboxgl.accessToken = this.props.token;
this.map = new mapboxgl.Map(this.props.view);
this.map.on('style.load', () => {
this.map.addSource('satellite', {
type: 'raster',
url: 'mapbox://mapbox.satellite'
});
this.map.addLayer({
'id': 'satellite',
'type': 'raster',
'source': 'satellite',
'layout': {
'visibility': 'none'
}
});
if (this.props.onStyleLoad) {
this.props.onStyleLoad(this.map);
}
});
}
componentDidUpdate() {
if (this.props.baselayer === 'satellite') {
this.map.setLayoutProperty('satellite', 'visibility', 'visible');
} else {
this.map.setLayoutProperty('satellite', 'visibility', 'none');
}
}
componentWillUnmount() {
this.map.remove();
}
render() {
return (
<div>
<div style={this.props.mapStyle} id='map'></div>
</div>
);
}
}
export default GLMap;
|
app/javascript/packs/activity_pack.js | emrojo/samples_extraction | import React from 'react'
import ReactDOM from 'react-dom'
import PropTypes from 'prop-types'
import WebpackerReact from 'webpacker-react'
import Activity from 'components/activity'
import Steps from 'components/step_components/steps'
import StepsFinished from 'components/step_components/steps_finished'
import FactsSvg from 'components/asset_components/facts_svg'
import Facts from 'components/asset_components/facts'
import FactsEditor from 'components/asset_components/facts_editor'
import ReactTooltip from 'react-tooltip'
import ButtonWithLoading from 'components/lib/button_with_loading'
import SearchControl from 'components/lib/search_control'
window.React = React;
WebpackerReact.setup({React,Activity,SearchControl, ButtonWithLoading,Steps,StepsFinished,FactsSvg,Facts,FactsEditor,ReactTooltip})
|
src/components/ui/Logo.js | yuri/notality | import React from 'react';
import LogoImage from '../../assets/rangleio-logo.svg';
const Logo = ({ style = {} }) => {
return (
<img
style={{ ...styles.base, ...style }}
src={ LogoImage }
alt="Rangle.io" />
);
};
const styles = {
base: {
width: 128,
},
};
export default Logo;
|
node_modules/react-bootstrap/es/Clearfix.js | ProjectSunday/rooibus | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
import capitalize from './utils/capitalize';
import { DEVICE_SIZES } from './utils/StyleConfig';
var propTypes = {
componentClass: elementType,
/**
* Apply clearfix
*
* on Extra small devices Phones
*
* adds class `visible-xs-block`
*/
visibleXsBlock: React.PropTypes.bool,
/**
* Apply clearfix
*
* on Small devices Tablets
*
* adds class `visible-sm-block`
*/
visibleSmBlock: React.PropTypes.bool,
/**
* Apply clearfix
*
* on Medium devices Desktops
*
* adds class `visible-md-block`
*/
visibleMdBlock: React.PropTypes.bool,
/**
* Apply clearfix
*
* on Large devices Desktops
*
* adds class `visible-lg-block`
*/
visibleLgBlock: React.PropTypes.bool
};
var defaultProps = {
componentClass: 'div'
};
var Clearfix = function (_React$Component) {
_inherits(Clearfix, _React$Component);
function Clearfix() {
_classCallCheck(this, Clearfix);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Clearfix.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
DEVICE_SIZES.forEach(function (size) {
var propName = 'visible' + capitalize(size) + 'Block';
if (elementProps[propName]) {
classes['visible-' + size + '-block'] = true;
}
delete elementProps[propName];
});
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return Clearfix;
}(React.Component);
Clearfix.propTypes = propTypes;
Clearfix.defaultProps = defaultProps;
export default bsClass('clearfix', Clearfix); |
src/svg-icons/hardware/security.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSecurity = (props) => (
<SvgIcon {...props}>
<path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"/>
</SvgIcon>
);
HardwareSecurity = pure(HardwareSecurity);
HardwareSecurity.displayName = 'HardwareSecurity';
HardwareSecurity.muiName = 'SvgIcon';
export default HardwareSecurity;
|
caseStudy/ui/src/App.js | jennybkim/engineeringessentials | /**
* Copyright 2017 Goldman Sachs.
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import React from 'react';
import './style/App.css';
import StockTicker from './components/StockTicker';
import Date from './components/Date';
import Charts from './components/Charts';
import Input from './components/Input';
import Title from './components/Title';
import LineChart from './components/charts/LineChart';
/**
* TODO:
* Import your components
*/
class App extends React.Component{
constructor(props) {
super(props);
this.state = {
/**
* TODO
* Add state objects for the user inputs and anything else you may need to render the highchart.
*/
};
}
render () {
return (
<div className="page-display">
<div className="input">
<Title/>
{/**
* TODO
* Render the StockTicker and Date components. You can use the date component twice
* for both the start and end dates.
* Add onChange props to the StockTicker and both Date components.
* These props methods should set state and help determine if the
* highchart should be displayed by changing the state of that boolean.
* Don't forget to bind these methods!
*/}
<div className="date-range">
</div>
</div>
<Input/>
<LineChart/>
{/*<Charts/>*/}
{/**
* TODO
* Create a div element that shows a highchart when the ticker, start date, end date
* states ALL have values and nothing (null) otherwise. You will need to use a conditional here
* to help control rendering and pass these states as props to the component. This conditional can
* be maintained as a state object.
* http://reactpatterns.com/#conditional-rendering
*/}
</div>
);
}
}
export default App;
|
src/routes/increase/components/Increase.js | magic-FE/react-redux-boilerplate | //
import React from 'react';
type props = {
result: number,
doubleAsync: () => void,
increment: () => void
};
export const Increase = (props: props) => {
return (
<div>
<h2>Counter: {props.result}</h2>
<button className="btn btn-default" onClick={() => props.increment()}>
Increment
</button>
{' '}
<button className="btn btn-default" onClick={() => props.doubleAsync()}>
Double (Async)
</button>
</div>
);
};
export default Increase;
|
src/server.js | CSE-437/WebServer | /**
* 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 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
import assets from './assets';
import { port } from './config';
import morgan from 'morgan';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import session from 'express-session';
var ParseStore = require('connect-parse')(session);
import Parse from 'parse/node';
Parse.initialize(process.env.APP_ID || "AnkiHubParse");
Parse.serverURL = process.env.SERVER_URL || "https://ankihubparse2.herokuapp.com/parse";
var io = require('socket.io')(server);
const server = global.server = express();
import timeout from 'connect-timeout';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(morgan('dev'));//log every request to console
server.use(cookieParser()); //read cookies for authentication
server.use(bodyParser.json({limit: '50mb'}));
server.use(bodyParser.urlencoded({limit:'50mb',extended: true}));
//Connects to the sessions table of our database
server.use(session({
secret:process.env.SESSION_SECRET || 'ankilove',
store: new ParseStore({
client: Parse
}),
resave: true,
saveUninitialized: true
}));
server.use(express.static(path.join(__dirname, 'public')));
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
server.use('/api/users', require('./api/users/UserRouter'));
server.use('/api/decks', require('./api/decks/DeckRouter'));
server.use('/api/cards', require('./api/cards/CardRouter'));
server.use('/api/transactions', require('./api/transactions/TransactionRouter'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '', entry: assets.main.js };
const css = [];
const context = {
insertCss: styles => css.push(styles._getCss()),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, query: req.query, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//Instantiate Socket IO
var onlineUsers = 0;//TODO get rid of when done testing
io.sockets.on('connection', function(socket){
onlineUsers++;
io.sockets.emit('onlineUsers', {onlineUsers: onlineUsers});
socket.on('disconnect', function(){
onlineUsers--;
io.sockets.emit('onlineUsers', {onlineUsers: onlineUsers});
});
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
/* eslint-disable no-console */
console.log(`The server is running at http://localhost:${port}/`);
});
|
test/integration/scss-fixtures/npm-import/pages/_app.js | JeromeFitz/next.js | import React from 'react'
import App from 'next/app'
import '../styles/global.scss'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
|
src/router.js | nobesnickr/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import Router from 'react-routing/src/Router';
import http from './core/http';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import LoginPage from './components/LoginPage';
import RegisterPage from './components/RegisterPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
const router = new Router(on => {
on('*', async (state, next) => {
const component = await next();
return component && <App context={state.context}>{component}</App>;
});
on('/contact', async () => <ContactPage />);
on('/login', async () => <LoginPage />);
on('/register', async () => <RegisterPage />);
on('*', async (state) => {
const content = await http.get(`/api/content?path=${state.path}`);
return content && <ContentPage {...content} />;
});
on('error', (state, error) => state.statusCode === 404 ?
<App context={state.context} error={error}><NotFoundPage /></App> :
<App context={state.context} error={error}><ErrorPage /></App>);
});
export default router;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.