path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
app/components/Journal.js | billyvg/pokemon-journal | import React, { Component } from 'react';
import {
inject,
observer,
} from 'mobx-react';
import autobind from 'autobind-decorator';
import PokemonList from './PokemonList';
import styles from './Journal.css';
@inject('authStore')
@autobind
@observer
export default class Journal extends Component {
render() {
return (
<div className={styles.container}>
<PokemonList />
</div>
);
}
}
|
src/containers/InfoModalContainer/index.js | MatthewKosloski/lugar | import React from 'react';
import { connect } from 'react-redux';
import InfoModal from '../../components/InfoModal';
const InfoModalContainer = (props) => <InfoModal {...props} />;
const mapStateToProps = (state) => {
const { photo } = state;
const { user, urls } = photo.data;
const username = user.name;
const downloadLink = urls.full;
const profileLink = user.links.html;
return { username, downloadLink, profileLink }
}
export default connect(
mapStateToProps
)(InfoModalContainer); |
examples/huge-apps/routes/Course/routes/Assignments/components/Assignments.js | flocks/react-router | import React from 'react';
class Assignments extends React.Component {
render () {
return (
<div>
<h3>Assignments</h3>
{this.props.children || <p>Choose an assignment from the sidebar.</p>}
</div>
);
}
}
export default Assignments;
|
src/containers/DevTools/DevTools.js | gregsabo/beanstalk-movie-critic | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor
toggleVisibilityKey="ctrl-H"
changePositionKey="ctrl-Q"
defaultIsVisible={false}
>
<LogMonitor />
</DockMonitor>
);
|
src/svg-icons/navigation/expand-more.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationExpandMore = (props) => (
<SvgIcon {...props}>
<path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/>
</SvgIcon>
);
NavigationExpandMore = pure(NavigationExpandMore);
NavigationExpandMore.displayName = 'NavigationExpandMore';
NavigationExpandMore.muiName = 'SvgIcon';
export default NavigationExpandMore;
|
app/index.js | gammapy/web-experiments | import React from 'react';
import { render } from 'react-dom';
import App from './App';
import 'leaflet/dist/leaflet.css!css';
import './style/reset.css!css';
import './style/app.css!css';
import './style/react-select.min.css!css';
// Create a node to attach the virtual react dom
// tree to the body
const node = document.createElement('div');
node.setAttribute('id', 'node');
document.body.appendChild(node);
// Render the App
render(<App/>, node);
|
examples/sections/src/components/Button/Button.js | styleguidist/react-styleguidist | import React from 'react';
import PropTypes from 'prop-types';
import './Button.css';
/**
* The only true button.
*/
export default function Button({ color, size, children }) {
const styles = {
color,
fontSize: Button.sizes[size],
};
return (
<button className="button" style={styles}>
{children}
</button>
);
}
Button.propTypes = {
/**
* Button label.
*/
children: PropTypes.string.isRequired,
color: PropTypes.string,
size: PropTypes.oneOf(['small', 'normal', 'large']),
};
Button.defaultProps = {
color: '#333',
size: 'normal',
};
Button.sizes = {
small: '10px',
normal: '14px',
large: '18px',
};
|
src/svg-icons/editor/bubble-chart.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBubbleChart = (props) => (
<SvgIcon {...props}>
<circle cx="7.2" cy="14.4" r="3.2"/><circle cx="14.8" cy="18" r="2"/><circle cx="15.2" cy="8.8" r="4.8"/>
</SvgIcon>
);
EditorBubbleChart = pure(EditorBubbleChart);
EditorBubbleChart.displayName = 'EditorBubbleChart';
EditorBubbleChart.muiName = 'SvgIcon';
export default EditorBubbleChart;
|
example/components/react/Counter.js | subuta/redux-virtual-dom | import React from 'react'
import { connect, inject } from 'example/store.js'
import { createSelector } from 'reselect';
import { bindActionCreators } from 'redux'
import { getCount } from 'example/reducers/counter.js';
const dummyActions = {
dummyAction: () => {
return {
type: 'dummy'
}
}
};
const mapStateToProps = null;
const mapDispatchToProps = (dispatch) => {
return {
...bindActionCreators(dummyActions, dispatch)
}
};
const render = ({ props }) => {
console.log('[react-counter] rendered');
return (
<span onClick={(ev) => props.dummyAction()}>
{props.children}
</span>
);
};
// react-redux way
export default connect(
mapStateToProps,
mapDispatchToProps
)(render);
//// ** you can do same thing as deku flavored way **
// export default inject(({props}) => {
// return (
// <span onClick={(ev) => props.dummyAction()}>
// {props.children}
// </span>
// );
// },
// mapStateToProps,
// mapDispatchToProps
// );
|
src/MainMenu.js | scapp281/cliff-effects | import React from 'react';
import {
// Button,
Container,
Image,
Menu,
} from 'semantic-ui-react';
import { Link } from 'react-router-dom';
import { BetaWarning } from './BetaWarning';
import logo from './images/logo.svg';
const MainMenu = function ( props ) {
return(
<Container>
<Menu inverted secondary size='large'>
<Menu.Item>
<a href="http://www.codeforboston.org" target="_blank" rel="noopener noreferrer"><Image src={logo} size='tiny' /></a>
</Menu.Item>
<Menu.Item><Link to="/">Home</Link></Menu.Item>
<Menu.Item><Link to="/about">About</Link></Menu.Item>
<Menu.Item position='right'>
{/*<Link to="/login"><Button inverted>Log in</Button></Link>*/}
{/*<Button as='a' inverted style={{ marginLeft: '0.5em' }}>Sign Up</Button>*/}
</Menu.Item>
<BetaWarning/>
</Menu>
</Container>
);
}; // End MainMenu(<>)
export { MainMenu };
|
src/components/google_map.js | sean1rose/WeatherApp | // uses react-google-maps
import React from 'react';
import { GoogleMapLoader, GoogleMap } from 'react-google-maps';
export default (props) => {
return (
<GoogleMapLoader
containerElement={ <div style={{height: '100%'}} /> }
googleMapElement={
<GoogleMap defaultZoom={9} defaultCenter={{lat: props.lat, lng: props.lon}} />
}
/>
)
} |
src/svg-icons/image/burst-mode.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBurstMode = (props) => (
<SvgIcon {...props}>
<path d="M1 5h2v14H1zm4 0h2v14H5zm17 0H10c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM11 17l2.5-3.15L15.29 16l2.5-3.22L21 17H11z"/>
</SvgIcon>
);
ImageBurstMode = pure(ImageBurstMode);
ImageBurstMode.displayName = 'ImageBurstMode';
ImageBurstMode.muiName = 'SvgIcon';
export default ImageBurstMode;
|
imports/ui/home/components/home_carousel.js | dououFullstack/atomic | import React from 'react';
import Carousel from 'nuka-carousel';
import Loading from '/imports/ui/loading';
class Pics extends React.Component {
render() {
return (
this.props.ready ?
<Carousel wrapAround autoplay autoplayInterval={5000}>
{this.props.carousels.map( (v,k) =>
v.link ?
<div key={k} className="single_review">
<a href={v.link}>
<img src={v.src} onLoad={() => window.dispatchEvent(new Event('resize'))} width="100%" height="100%"/>
</a>
</div>
:
<div key={k} className="single_review">
<img src={v.src} onLoad={() => window.dispatchEvent(new Event('resize'))} width="100%" height="100%"/>
</div>)
}
</Carousel>
:
<Loading/>
);
}
}
export default Pics;
|
actor-apps/app-web/src/app/components/modals/CreateGroup.react.js | gale320/actor-platform | import React from 'react';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import CreateGroupStore from 'stores/CreateGroupStore';
import CreateGroupForm from './create-group/Form.react';
import Modal from 'react-modal';
import { KeyCodes } from 'constants/ActorAppConstants';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const getStateFromStores = () => {
return {
isShown: CreateGroupStore.isModalOpen()
};
};
class CreateGroup extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
CreateGroupStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
CreateGroupStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
render() {
const isShown = this.state.isShown;
return (
<Modal className="modal-new modal-new--create-group" closeTimeoutMS={150} isOpen={isShown}>
<header className="modal-new__header">
<a className="modal-new__header__close modal-new__header__icon material-icons" onClick={this.onClose}>clear</a>
<h3 className="modal-new__header__title">Create group</h3>
</header>
<CreateGroupForm/>
</Modal>
);
}
onChange = () => {
this.setState(getStateFromStores());
}
onClose = () => {
CreateGroupActionCreators.closeModal();
}
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
}
}
CreateGroup.displayName = 'CreateGroup';
export default CreateGroup;
|
examples/custom-picker/src/index.js | casesandberg/react-color | import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
ReactDOM.render(
<App />,
document.getElementById('root'),
)
|
frontend/src/components/select-editor/sysadmin-user-status-editor.js | miurahr/seahub | import React from 'react';
import PropTypes from 'prop-types';
import { gettext } from '../../utils/constants';
import SelectEditor from './select-editor';
const propTypes = {
isTextMode: PropTypes.bool.isRequired,
isEditIconShow: PropTypes.bool.isRequired,
statusOptions: PropTypes.array.isRequired,
currentStatus: PropTypes.string.isRequired,
onStatusChanged: PropTypes.func.isRequired
};
class SysAdminUserStatusEditor extends React.Component {
translateStatus = (status) => {
switch (status) {
case 'active':
return gettext('Active');
case 'inactive':
return gettext('Inactive');
}
}
render() {
return (
<SelectEditor
isTextMode={this.props.isTextMode}
isEditIconShow={this.props.isEditIconShow}
options={this.props.statusOptions}
currentOption={this.props.currentStatus}
onOptionChanged={this.props.onStatusChanged}
translateOption={this.translateStatus}
/>
);
}
}
SysAdminUserStatusEditor.propTypes = propTypes;
export default SysAdminUserStatusEditor;
|
src/ProgressiveImage.js | MiguelCrespo/react-progressive-loading | import React from 'react';
import SimpleImage from './SimpleImage';
import SolidImage from './SolidImage';
import BlurImage from './BlurImage';
import BlurBackground from './BlurBackground';
import './styles.css';
export {
SimpleImage,
BlurImage,
BlurBackground
};
export default {
SimpleImage,
BlurImage,
BlurBackground
}; |
apps/mk-app-delivery-order-list/action.js | ziaochina/mk-demo | import React from 'react'
import { action as MetaAction, AppLoader } from 'mk-meta-engine'
import { fromJS } from 'immutable'
import config from './config'
import moment from 'moment'
import utils from 'mk-utils'
import extend from './extend'
class action {
constructor(option) {
this.metaAction = option.metaAction
this.extendAction = option.extendAction
this.config = config.current
this.webapi = this.config.webapi
}
onInit = ({ component, injections }) => {
this.extendAction.gridAction.onInit({ component, injections })
this.component = component
this.injections = injections
injections.reduce('init')
const pagination = this.metaAction.gf('data.pagination').toJS()
const filter = this.metaAction.gf('data.filter').toJS()
this.load(pagination, filter)
}
load = async (pagination, filter) => {
const response = await this.webapi.deliverOrderList.init({ pagination, filter })
response.filter = filter
this.injections.reduce('load', response)
}
reload = async () => {
const pagination = this.metaAction.gf('data.pagination').toJS()
const filter = this.metaAction.gf('data.filter').toJS()
this.load(pagination, filter)
}
add = async () => {
if (!this.config.apps['mk-app-delivery-order']) {
throw '依赖mk-app-delivery-order app,请使用mk clone mk-app-delivery-order命令添加'
}
this.component.props.setPortalContent &&
this.component.props.setPortalContent('销售出库单', 'mk-app-delivery-order')
}
batchMenuClick = (e) => {
switch (e.key) {
case 'del':
this.batchDel()
break
case 'audit':
this.batchAudit()
break
}
}
batchDel = async () => {
const lst = this.metaAction.gf('data.list')
if (!lst || lst.size == 0) {
this.metaAction.toast('error', '请选中要删除的记录')
return
}
const selectRows = lst.filter(o => o.get('selected'))
if (!selectRows || selectRows.size == 0) {
this.metaAction.toast('error', '请选中要删除的记录')
return
}
const ret = await this.metaAction.modal('confirm', {
title: '删除',
content: '确认删除?'
})
if (!ret)
return
const ids = selectRows.map(o => o.get('id')).toJS()
await this.webapi.deliverOrderList.del({ ids })
this.metaAction.toast('success', '删除成功')
this.reload()
}
batchAudit = async () => {
const lst = this.metaAction.gf('data.list')
if (!lst || lst.size == 0) {
this.metaAction.toast('error', '请选中要审核的记录')
return
}
const selectRows = lst.filter(o => o.get('selected'))
if (!selectRows || selectRows.size == 0) {
this.metaAction.toast('error', '请选中要审核的记录')
return
}
const ids = selectRows.map(o => o.get('id')).toJS()
await this.webapi.deliverOrderList.audit({ ids })
this.metaAction.toast('success', '审核成功')
this.reload()
}
audit = (id) => async () => {
await this.webapi.deliverOrderList.audit({ ids: [id] })
this.metaAction.toast('success', '审核成功')
this.reload()
}
reject = (id) => async () => {
await this.webapi.deliverOrderList.reject({ ids: [id] })
this.metaAction.toast('success', '反审核成功')
this.reload()
}
del = (id) => async () => {
const ret = await this.metaAction.modal('confirm', {
title: '删除',
content: '确认删除?'
})
if (!ret)
return
await this.webapi.deliverOrderList.del({ ids: [id] })
this.metaAction.toast('success', '删除成功')
this.reload()
}
modify = (id) => async () => {
if (!this.config.apps['mk-app-delivery-order']) {
throw '依赖mk-app-delivery-order app,请使用mk clone mk-app-delivery-order命令添加'
}
this.component.props.setPortalContent &&
this.component.props.setPortalContent('存货卡片', 'mk-app-delivery-order', { deliveryOrderId: id })
}
toggleShowAdvanceFilter = () => {
this.metaAction.sf('data.other.isFold', !this.metaAction.gf('data.other.isFold'))
}
commonFilterChange = async (e) => {
const key = e.target.value
const pagination = this.metaAction.gf('data.pagination').toJS(),
filter = this.metaAction.gf('data.filter').toJS()
filter.common = key
const response = await this.webapi.deliverOrderList.query({ pagination, filter })
response.filter = filter
this.load(pagination, filter)
}
tabChange = async (key) => {
const pagination = this.metaAction.gf('data.pagination').toJS(),
filter = this.metaAction.gf('data.filter').toJS()
filter.targetList = key
const response = await this.webapi.deliverOrderList.query({ pagination, filter })
response.filter = filter
this.load(pagination, filter)
}
customerChange = (v) => {
const ds = this.metaAction.gf('data.other.customers')
const hit = ds.find(o => o.get('id') == v)
this.metaAction.sf(`data.filter.customer`, hit)
}
search = () => {
this.reload()
}
pageChanged = (current, pageSize) => {
const filter = this.metaAction.gf('data.filter').toJS()
this.load({ current, pageSize }, filter)
}
receipt = () => {
throw '请实现收框功能'
}
print = () => {
throw '请实现打印功能'
}
exp = () => {
throw '请实现导出功能'
}
setting = () => {
throw '请实现设置功能'
}
numberFormat = utils.number.format
}
export default function creator(option) {
const metaAction = new MetaAction(option),
extendAction = extend.actionCreator({ ...option, metaAction }),
o = new action({ ...option, metaAction, extendAction })
const ret = { ...metaAction, ...extendAction.gridAction, ...o }
metaAction.config({ metaHandlers: ret })
return ret
} |
src/index.js | VuongVu/React_Training | import React from 'react';
import { render } from 'react-dom';
import App from './components/App';
import './index.css';
render(<App />, document.getElementById('app')); |
listen.js | JonArnfred/react_component_editor | import { transformFile } from 'babel-core'; // we want to compile specific js files runtime
import fs from 'fs';
import ReactDOMServer from 'react-dom/server';
import React from 'react';
// there should be a way to inject this
const directory = 'component/';
// filename is the name given to the file
// and event is the change in the file, either rename or change
// returned object is a fs.FSWatcher
// filename is the name of the file which triggered the event.
fs.watch(directory, function (event, filename) {
// here we should pass the resulting filename resolved to Java.
// should find and recompile the file, serve it to the html folder
const htmlName = filename.replace(/\.[^/.]+$/, "")+".html"; // removes extension
// get full path of filename
var fullHtmlPath = ("./html/" + htmlName);
// filenameJS is what is shown in the editor and edited
// it's also what we compile to filenameBabel
var filenameJS = directory + filename; // extension is .js
console.log('JAVA filename:'+filenameJS);
// filenameBabel is what is picked up as a React component in the node code
var filenameBabel = "./bablified/" + filename; // extension is .js
switch(event){
case "change":
//transformFile is babel API: result // => { code, map, ast }
transformFile(filenameJS, function (err, result) {
if(err) console.log("error:", err);
if(result){
//console.log("result.code ", result.code);
// save the transpiled js
fs.writeFile(filenameBabel, result.code, function(err){
if(err) return console.log(err);
// the transpiled code is saved as an object, so we access it there
var ReactComponent = require(filenameBabel).ReactComponent;
// if undefined, it means that it was not bablified aka that it's plain es5,
// so here we just require it in a normal fashion
if(ReactComponent === undefined){
ReactComponent = require(filenameBabel);
}
// requires are chached..., so it's the same file
const html = ReactDOMServer.renderToStaticMarkup(<ReactComponent/>);
// after we've used the ReactComponent, we
// delete the cached module, since we want it to reload entirely
// when the code has changed
delete require.cache[require.resolve(filenameBabel)];
const fullHtml = "<html><head></head><body>"+html+"</body></html>";
fs.writeFile(fullHtmlPath, fullHtml, function(err) {
if(err) return console.log(err);
console.log("JAVA: html changed"); // this is the line that executes a reload in the java webview
})
});
}
});
}
});
|
src/components/ScrollToTop/index.js | zsxsoft/blog.zsxsoft.com | import React from 'react'
import { animateToTop } from '../../utils/scroll'
import { withRouter } from 'next/router'
import PropTypes from 'prop-types'
class ScrollToTop extends React.PureComponent {
static propTypes = {
router: PropTypes.object
}
componentDidUpdate (prevProps) {
if (this.props.router.asPath !== prevProps.router.asPath) {
setTimeout(animateToTop, 100)
}
}
render () {
return this.props.children // eslint-disable-line
}
}
export default withRouter(ScrollToTop)
|
imports/ui/views/change-password.js | dklisiaris/grabber | import React from 'react';
import { Link } from 'react-router';
import { browserHistory } from 'react-router';
import { Meteor } from 'meteor/meteor';
import { renderErrorsFor } from '../../modules/utils';
export class ChangePassword extends React.Component {
constructor(props) {
super(props);
this.state = {
errors: {}
};
this._handleSubmit = this._handleSubmit.bind(this);
}
_handleSubmit(event) {
event.preventDefault();
const { location } = this.props;
const inputData = {
oldPassword: this.refs.oldPassword.value,
password: this.refs.password.value,
passwordConfirmation: this.refs.passwordConfirmation.value
};
if(this._validateInputData(inputData)){
Accounts.changePassword(inputData.oldPassword, inputData.password, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
browserHistory.push('/');
Bert.alert('Password changed!', 'success');
}
});
}
}
_validateInputData(inputData) {
let errors = {};
if (! inputData.oldPassword) {
errors.oldPassword = 'Old password is required';
}
if (! inputData.password) {
errors.password = 'New Password is required';
}
else if (inputData.password.length < 6) {
errors.password = 'Passwords must be at least 6 characters.';
}
if (inputData.passwordConfirmation !== inputData.password) {
errors.passwordConfirmation = 'Passwords do not match';
}
this.setState({errors: errors});
return (Object.keys(errors).length === 0);
}
render() {
const errors = this.state.errors;
return (
<div className='view-container sessions new'>
<main>
<form ref="changePassword" id="change-password-form" onSubmit={this._handleSubmit}>
<div className="field">
<input
ref="oldPassword"
type="password"
id="old-user-password"
placeholder="Old Password"
required={true}/>
{renderErrorsFor(errors, 'oldPassword')}
</div>
<div className="field">
<input
ref="password"
id="password"
type="password"
placeholder="New Password"
required={true} />
{renderErrorsFor(errors, 'password')}
</div>
<div className="field">
<input
ref="passwordConfirmation"
id="password-confirmation"
type="password"
placeholder="Confirm New Password"
required={true} />
{renderErrorsFor(errors, 'passwordConfirmation')}
</div>
<button type="submit">Change Password</button>
</form>
</main>
</div>
);
}
}
|
src/svg-icons/hardware/phonelink-off.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwarePhonelinkOff = (props) => (
<SvgIcon {...props}>
<path d="M22 6V4H6.82l2 2H22zM1.92 1.65L.65 2.92l1.82 1.82C2.18 5.08 2 5.52 2 6v11H0v3h17.73l2.35 2.35 1.27-1.27L3.89 3.62 1.92 1.65zM4 6.27L14.73 17H4V6.27zM23 8h-6c-.55 0-1 .45-1 1v4.18l2 2V10h4v7h-2.18l3 3H23c.55 0 1-.45 1-1V9c0-.55-.45-1-1-1z"/>
</SvgIcon>
);
HardwarePhonelinkOff = pure(HardwarePhonelinkOff);
HardwarePhonelinkOff.displayName = 'HardwarePhonelinkOff';
HardwarePhonelinkOff.muiName = 'SvgIcon';
export default HardwarePhonelinkOff;
|
src/js/components/video/Overlay.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Box from '../Box';
import Heading from '../Heading';
import VideoShare from './Share';
import VideoPlayButton from './PlayButton';
import CSSClassnames from '../../utils/CSSClassnames';
const CLASS_ROOT = CSSClassnames.VIDEO;
export default class Overlay extends Component {
constructor (props, context) {
super(props, context);
this._onResponsive = this._onResponsive.bind(this);
this.state = {
iconSize: props.size &&
(props.size === 'small' || props.size === 'medium') ?
'large' : 'xlarge'
};
}
componentWillReceiveProps (newProps) {
if (newProps.size !== this.props.size) {
this.setState({
iconSize: newProps.size &&
(newProps.size === 'small' || newProps.size === 'medium') ?
'large' : 'xlarge'
});
}
}
_onResponsive (small) {
if (small) {
this.setState({ iconSize: 'medium' });
} else {
let iconSize = (('small' === this.props.size) ? undefined : 'xlarge');
this.setState({ iconSize: iconSize });
}
}
_renderReplayMenu() {
const { ended, shareLink, shareHeadline, shareText } = this.props;
let replayContent;
if (ended) {
replayContent = (
<Box className={`${CLASS_ROOT}__replay`} align="center">
<Heading tag="h3" strong={true} uppercase={true}>Replay</Heading>
<VideoShare shareLink={shareLink} shareHeadline={shareHeadline}
shareText={shareText} />
</Box>
);
}
return replayContent;
}
render() {
const { ended, playing, togglePlay, videoHeader } = this.props;
return (
<Box pad="none" align="center" justify="center"
className={`${CLASS_ROOT}__overlay`}>
{videoHeader}
<Box pad="none" align="center" justify="center">
<VideoPlayButton iconSize={this.state.iconSize}
playing={playing}
ended={ended}
togglePlay={togglePlay} />
</Box>
{this._renderReplayMenu()}
</Box>
);
}
}
|
src/js/routes.js | Chandransh/calculate-cost-redux | import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
import App from './components/App';
import BillingApp from './containers/BillingApp/BillingApp';
import NotFoundView from './views/NotFoundView';
export default (
<Route path="/" component={App}>
<IndexRoute component={BillingApp} />
<Route path="404" component={NotFoundView} />
<Redirect from="*" to="404" />
</Route>
);
|
frontend/src/components/SearchInput.js | purocean/yii2-template | import React from 'react';
import { Input, Button} from 'antd';
import classNames from 'classnames';
const InputGroup = Input.Group;
class Component extends React.Component {
constructor(props){
super(props);
this.state = {
value: this.props.value,
focus: false,
};
}
handleInputChange(e) {
this.setState({
value: e.target.value,
});
}
handleFocusBlur(e) {
this.setState({
focus: e.target === document.activeElement,
});
}
handleSearch() {
if (this.props.onSearch) {
this.props.onSearch(this.state.value);
}
}
render() {
const { style, size, placeholder } = this.props;
const btnCls = classNames({
'ant-search-btn': true,
'ant-search-btn-noempty': !!this.state.value.trim(),
});
const searchCls = classNames({
'ant-search-input': true,
'ant-search-input-focus': this.state.focus,
});
return (
<div className="ant-search-input-wrapper" style={style}>
<InputGroup className={searchCls}>
<Input placeholder={placeholder} value={this.state.value} onChange={this.handleInputChange.bind(this)}
onFocus={this.handleFocusBlur.bind(this)} onBlur={this.handleFocusBlur.bind(this)} onPressEnter={this.handleSearch.bind(this)}
/>
<div className="ant-input-group-wrap">
<Button icon="search" className={btnCls} size={size} onClick={this.handleSearch.bind(this)} />
</div>
</InputGroup>
</div>
);
}
}
Component.defaultProps = {
value: '',
};
export default Component;
|
example_app/src/routes/register/index.js | blueberryapps/radium-bootstrap-grid | /**
* 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 Register from './Register';
export const path = '/register';
export const action = async (state) => {
const title = 'New User Registration';
state.context.onSetTitle(title);
return <Register title={title} />;
};
|
src/components/dropdowns/DropdownHeader.js | ProAI/react-essentials | import React from 'react';
import PropTypes from 'prop-types';
import BaseView from '../../utils/rnw-compat/BaseView';
const propTypes = {
children: PropTypes.node.isRequired,
};
const DropdownHeader = React.forwardRef((props, ref) => (
<BaseView
{...props}
ref={ref}
accessibilityRole="heading"
aria-level={6}
essentials={{ className: 'dropdown-header' }}
/>
));
DropdownHeader.displayName = 'DropdownHeader';
DropdownHeader.propTypes = propTypes;
export default DropdownHeader;
|
react-src/catalog/components/voyages/CatalogVoyageTitle.js | gabzon/experiensa | import React from 'react';
export default class CatalogVoyageTitle extends React.Component {
constructor(){
super()
}
render() {
return (
<div className="content">
<div className="header catalog-title">{this.props.title}</div>
</div>
);
}
}
|
src/svg-icons/action/bug-report.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionBugReport = (props) => (
<SvgIcon {...props}>
<path d="M20 8h-2.81c-.45-.78-1.07-1.45-1.82-1.96L17 4.41 15.59 3l-2.17 2.17C12.96 5.06 12.49 5 12 5c-.49 0-.96.06-1.41.17L8.41 3 7 4.41l1.62 1.63C7.88 6.55 7.26 7.22 6.81 8H4v2h2.09c-.05.33-.09.66-.09 1v1H4v2h2v1c0 .34.04.67.09 1H4v2h2.81c1.04 1.79 2.97 3 5.19 3s4.15-1.21 5.19-3H20v-2h-2.09c.05-.33.09-.66.09-1v-1h2v-2h-2v-1c0-.34-.04-.67-.09-1H20V8zm-6 8h-4v-2h4v2zm0-4h-4v-2h4v2z"/>
</SvgIcon>
);
ActionBugReport = pure(ActionBugReport);
ActionBugReport.displayName = 'ActionBugReport';
ActionBugReport.muiName = 'SvgIcon';
export default ActionBugReport;
|
src/index.js | pjkarlik/Hacker | require('console-polyfill');
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Router, useRouterHistory } from 'react-router';
import { createHistory } from 'history';
const history = useRouterHistory(createHistory)({ basename: window.baseName || '/' });
/**
Entry Point JavaScript
*/
require.ensure(['./routes'], (require) => {
const routes = require('./routes').default;
const prefetchRoutes = require('./routes').prefetchRoutes;
render(
<Router history={history} routes={routes} />,
document.getElementById('react-mount'));
prefetchRoutes();
});
/**
Fancy console log statement
*/
const version = require('../package.json').version;
const description = require('../package.json').description;
const args = [
'\n %c %c %c ' + description + ' %c ver ' + version + ' %c \n\n',
'background: #000; padding:5px 0;',
'background: #FFF; padding:5px 0; border-top: 1px solid #000; border-bottom: 1px solid #000;',
'color: white; background: #000; padding:5px 0; border-top: 1px solid #000; border-bottom: 1px solid #000;',
'color: black; background: #FFF; padding:5px 0; border-top: 1px solid #000; border-bottom: 1px solid #000;',
'background: #000; padding:5px 0;'
];
// Check to see if browser can handle fancy console log else just blurb text
try {
window.console.log.apply(console, args);
} catch (e) {
window.console.log('The Hacker ' + version);
}
|
demo/celsius_react/src/index.js | gristlabs/grainjs | // This comes from https://reactjs.org/docs/lifting-state-up.html, and from the
// linked CodePen https://codepen.io/gaearon/pen/WZpxpz?editors=0010.
import React from 'react';
import ReactDOM from 'react-dom';
const scaleNames = {
c: 'Celsius',
f: 'Fahrenheit'
};
function toCelsius(fahrenheit) {
return (fahrenheit - 32) * 5 / 9;
}
function toFahrenheit(celsius) {
return (celsius * 9 / 5) + 32;
}
function tryConvert(temperature, convert) {
const input = parseFloat(temperature);
if (Number.isNaN(input)) {
return '';
}
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
}
function BoilingVerdict(props) {
if (props.celsius >= 100) {
return <p>The water would boil.</p>;
}
return <p>The water would not boil.</p>;
}
class TemperatureInput extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
}
handleChange(e) {
this.props.onTemperatureChange(e.target.value);
}
render() {
const temperature = this.props.temperature;
const scale = this.props.scale;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input value={temperature}
onChange={this.handleChange} />
</fieldset>
);
}
}
class Calculator extends React.Component {
constructor(props) {
super(props);
this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
this.state = {temperature: '', scale: 'c'};
}
handleCelsiusChange(temperature) {
this.setState({scale: 'c', temperature});
}
handleFahrenheitChange(temperature) {
this.setState({scale: 'f', temperature});
}
render() {
const scale = this.state.scale;
const temperature = this.state.temperature;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
return (
<div>
<TemperatureInput
scale="c"
temperature={celsius}
onTemperatureChange={this.handleCelsiusChange} />
<TemperatureInput
scale="f"
temperature={fahrenheit}
onTemperatureChange={this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
);
}
}
ReactDOM.render(<Calculator />, document.getElementById('root'));
|
packages/elza-react/src/utils/withErrors.js | octree-gva/elzajs | import _ from 'lodash';
import React from 'react';
import PropTypes from 'prop-types';
import {List} from 'immutable';
import {getForm} from 'elza-core';
export default function(Component) {
return class withErrors extends React.Component {
static displayName = 'withErrors(' + Component + ')';
static propTypes = {
className: PropTypes.string,
htmlFor: PropTypes.string,
name: PropTypes.string,
};
static defaultProps = {
className: '',
};
/**
* @constructor
* @param {Object} props
*/
constructor(props) {
super(props);
this.form = null;
this.state = {errors: new List()};
_.bindAll(this, 'receiveErrors', 'formName', 'fieldName');
}
formName() {
const name = this.fieldName();
return name.substr(0, name.indexOf('.'));
}
fieldName() {
let name = this.props.htmlFor;
if (_.isNil(name)) name = this.props.name;
return name;
}
receiveErrors(formData) {
if (!formData.errors.any() && this.state.errors.size === 0) return;
const fieldName = this.fieldName();
console.log('fieldName = ', fieldName);
const errors = _.get(formData.errors, 'errors.' + fieldName, []);
// Be sure error list is immutable
this.setState({errors: new List(errors)});
}
componentDidMount() {
// Explode the form name
const formName = this.formName();
this.form = getForm(formName);
// Client side errors
this.form.onChange(this.receiveErrors);
this.form.onAfter('validation', this.receiveErrors);
this.form.onAfter('submit', this.receiveErrors);
}
/**
* @override
*/
render() {
let {className, ...otherProps} = this.props;
if (this.state.errors.size > 0) className += ' has-errors';
return (
<Component
className={className}
errors={this.state.errors}
formName={this.formName()}
fieldName={this.fieldName()}
{...otherProps}
/>
);
}
};
}
|
src/pages/reading.js | pascalwhoop/pascalwhoop.github.io | import React from 'react'
import { graphql } from 'gatsby'
import Layout from '../components/layout'
import Helmet from 'react-helmet'
import WordLimit from 'react-word-limit'
const Reading = ({ data }) => {
const books = data.goodreadsShelf.reviews.sort(
(a, b) => a.dateAdded > b.dateAdded
)
return (
<Layout>
<Helmet>
<title>PB</title>
<meta name="description" content="Readinglist" />
</Helmet>
<div className="main">
<div className="inner">
<div>
{/* <div className="grid-wrapper"> */}
{/* <h2>Podcasts</h2> */}
<h2>Books</h2>
{books.map(book => (
<div className="bookBlock" key={book.book.bookID}>
{/* <div className="col-6" key={book.book.bookID}> */}
<h4>{book.book.title}</h4>
<div>
<div className="bookCover">
<img src={book.book.imageUrl} alt="" />
</div>
<WordLimit limit={100}>
<div>
<div
className="bookDescription"
dangerouslySetInnerHTML={{
__html: book.book.description.substring(0, 500),
}}
></div>
<a
href={book.book.link}
target="_blank"
className="button"
>
See more
</a>
</div>
</WordLimit>
</div>
</div>
))}
</div>
</div>
</div>
</Layout>
)
}
export default Reading
export const query = graphql`
query GoodreadsQuery {
goodreadsShelf {
reviews {
book {
title
uri
largeImageUrl
imageUrl
link
bookID
description
}
dateAdded
dateUpdated
rating
}
}
}
`
|
src/components/Tag/Tag.js | VumeroInstitute/Vumero-Talent-Matrix | /**
* Created by wangdi on 6/10/17.
*/
import React from 'react';
import PropTypes from 'prop-types';
import './tag.css';
export default class Tag extends React.Component{
static propTypes = {
title: PropTypes.string,
deleteCallback: PropTypes.func
};
render(){
return (
<div className="tag-container">
<label>{this.props.title}</label>
<button onClick={this.props.deleteCallback}><i className="fa fa-times" aria-hidden="true"/></button>
</div>
);
}
} |
docs/src/sections/TabsSection.js | Lucifier129/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function TabsSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="tabs">Togglable tabs</Anchor> <small>Tabs, Tab</small>
</h2>
<p>Add quick, dynamic tab functionality to transition through panes of local content.</p>
<h3><Anchor id="tabs-uncontrolled">Uncontrolled</Anchor></h3>
<p>Allow the component to control its own state.</p>
<ReactPlayground codeText={Samples.TabsUncontrolled} exampleClassName="bs-example-tabs" />
<h3><Anchor id="tabs-controlled">Controlled</Anchor></h3>
<p>Pass down the active state on render via props.</p>
<ReactPlayground codeText={Samples.TabsControlled} exampleClassName="bs-example-tabs" />
<h3><Anchor id="tabs-no-animation">No animation</Anchor></h3>
<p>Set the <code>animation</code> prop to <code>false</code></p>
<ReactPlayground codeText={Samples.TabsNoAnimation} exampleClassName="bs-example-tabs" />
<h3><Anchor id="left-tabs">Left tabs</Anchor></h3>
<p>Set <code>position</code> to <code>"left"</code>. Optionally, <code>tabWidth</code> can be passed the number of columns for the tabs.</p>
<ReactPlayground codeText={Samples.LeftTabs} exampleClassName="bs-example-tabs" />
<h3><Anchor id="tabs-props">Props</Anchor></h3>
<h4><Anchor id="tabs-props-area">Tabs</Anchor></h4>
<PropTable component="Tabs"/>
<h4><Anchor id="tabs-props-pane">Tab</Anchor></h4>
<PropTable component="Tab"/>
</div>
);
}
|
photos/static/js/components/photo-panel.js | dpetzold/django-react-djangocon2015 | import React from 'react'
import {
Thumbnail, ButtonGroup, Button, ButtonToolbar, ListGroupItem, Col, Row
} from 'react-bootstrap'
import {
LAYOUT_THUMBNAILS, LAYOUT_LIST, TYPE_ALL, TYPE_COLOR, TYPE_BW, ControlBar
} from './control-bar'
import {isFavorite} from '../utils'
import Actions from '../actions'
const PhotoPanel = React.createClass({
getInitialState() {
return {
layout: LAYOUT_THUMBNAILS,
photoType: TYPE_ALL
};
},
/**
* Returns the filtered list of photos that have the given photoType
* (Color or Black & White).
*/
filterPhotos(photos, photoType) {
return photos.filter((photo) => {
switch (photoType) {
case TYPE_COLOR:
// Only return color photos
return photo.is_color;
case TYPE_BW:
// Only return B&W photos
return !photo.is_color;
default:
// Return all photos
return true;
}
});
},
/*****************************************************************
*
* EVENT HANDLERS
*
*****************************************************************/
onPhotoTypeChange(photoType) {
this.setState({photoType: photoType});
},
onLayoutChange(layout) {
this.setState({layout: layout});
},
/*****************************************************************
*
* RENDERING
*
*****************************************************************/
/**
* Main render function.
*/
render() {
let filteredPhotos = this.filterPhotos(
this.props.photos, this.state.photoType
);
return (
<div className="album">
<ControlBar
layout={this.state.layout}
photoType={this.state.photoType}
onPhotoTypeChange={this.onPhotoTypeChange}
onLayoutChange={this.onLayoutChange}
/>
<Row>
{this.renderPhotos(filteredPhotos)}
</Row>
</div>
)
},
/**
* Renders the given photos.
*/
renderPhotos(photos) {
return photos.map((photo) => {
// Compute the photo's attributes
let photoIsFavorite = isFavorite(this.props.favorites, photo.id);
let style = photoIsFavorite ? {backgroundColor: '#F65374'} : {};
let action = Actions.toggleFavorite.bind(this, photo);
// Render the photo as thumbnail or list item based on the
// selected layout option
switch (this.state.layout) {
case LAYOUT_THUMBNAILS:
return this.renderPhotoAsThumbnail(photo, style, action);
break;
case LAYOUT_LIST:
return this.renderPhotoAsListItem(photo, style, action);
break;
}
});
},
/**
* Renders a single photo as a thumbnail.
*/
renderPhotoAsThumbnail(photo, style, action) {
return (
<Col md={4} sm={4} key={photo.id}>
<Thumbnail src={photo.url} onClick={action} style={style} />
</Col>
)
},
/**
* Renders a single photo as a list item.
*/
renderPhotoAsListItem(photo, style, action) {
return (
<ListGroupItem key={photo.id} onClick={action} style={style}>
<img src={photo.url} width={60}/>
</ListGroupItem>
)
}
});
export default PhotoPanel; |
stories/Anchor/SimpleLinkPluginEditor/index.js | dagopert/draft-js-plugins | import React, { Component } from 'react';
import Editor, { createEditorStateWithText } from 'draft-js-plugins-editor';
import createInlineToolbarPlugin from 'draft-js-inline-toolbar-plugin';
import createLinkPlugin from 'draft-js-anchor-plugin';
import { ItalicButton, BoldButton, UnderlineButton } from 'draft-js-buttons';
import editorStyles from './editorStyles.css';
const linkPlugin = createLinkPlugin();
const inlineToolbarPlugin = createInlineToolbarPlugin({
structure: [
BoldButton,
ItalicButton,
UnderlineButton,
linkPlugin.LinkButton
]
});
const { InlineToolbar } = inlineToolbarPlugin;
const plugins = [inlineToolbarPlugin, linkPlugin];
const text = 'Try selecting a part of this text and click on the link button in the toolbar that appears …';
export default class SimpleLinkPluginEditor extends Component {
state = {
editorState: createEditorStateWithText(text)
};
onChange = (editorState) =>
this.setState({ editorState });
focus = () =>
this.editor.focus();
render() {
return (
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => { this.editor = element; }}
/>
<InlineToolbar />
</div>
);
}
}
|
app/javascript/mastodon/components/edited_timestamp/index.js | lindwurm/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl } from 'react-intl';
import Icon from 'mastodon/components/icon';
import DropdownMenu from './containers/dropdown_menu_container';
import { connect } from 'react-redux';
import { openModal } from 'mastodon/actions/modal';
import RelativeTimestamp from 'mastodon/components/relative_timestamp';
import InlineAccount from 'mastodon/components/inline_account';
const mapDispatchToProps = (dispatch, { statusId }) => ({
onItemClick (index) {
dispatch(openModal('COMPARE_HISTORY', { index, statusId }));
},
});
export default @connect(null, mapDispatchToProps)
@injectIntl
class EditedTimestamp extends React.PureComponent {
static propTypes = {
statusId: PropTypes.string.isRequired,
timestamp: PropTypes.string.isRequired,
intl: PropTypes.object.isRequired,
onItemClick: PropTypes.func.isRequired,
};
handleItemClick = (item, i) => {
const { onItemClick } = this.props;
onItemClick(i);
};
renderHeader = items => {
return (
<FormattedMessage id='status.edited_x_times' defaultMessage='Edited {count, plural, one {{count} time} other {{count} times}}' values={{ count: items.size - 1 }} />
);
}
renderItem = (item, index, { onClick, onKeyPress }) => {
const formattedDate = <RelativeTimestamp timestamp={item.get('created_at')} short={false} />;
const formattedName = <InlineAccount accountId={item.get('account')} />;
const label = item.get('original') ? (
<FormattedMessage id='status.history.created' defaultMessage='{name} created {date}' values={{ name: formattedName, date: formattedDate }} />
) : (
<FormattedMessage id='status.history.edited' defaultMessage='{name} edited {date}' values={{ name: formattedName, date: formattedDate }} />
);
return (
<li className='dropdown-menu__item edited-timestamp__history__item' key={item.get('created_at')}>
<button data-index={index} onClick={onClick} onKeyPress={onKeyPress}>{label}</button>
</li>
);
}
render () {
const { timestamp, intl, statusId } = this.props;
return (
<DropdownMenu statusId={statusId} renderItem={this.renderItem} scrollable renderHeader={this.renderHeader} onItemClick={this.handleItemClick}>
<button className='dropdown-menu__text-button'>
<FormattedMessage id='status.edited' defaultMessage='Edited {date}' values={{ date: intl.formatDate(timestamp, { hour12: false, month: 'short', day: '2-digit', hour: '2-digit', minute: '2-digit' }) }} /> <Icon id='caret-down' />
</button>
</DropdownMenu>
);
}
}
|
entry_types/scrolled/package/src/frontend/Panorama/FullscreenIndicator.js | tf/pageflow | import React from 'react';
import classNames from 'classnames';
import ArrowLeftIcon from '../icons/arrowLeft.svg';
import styles from './FullscreenIndicator.module.css';
export function FullscreenIndicator({visible, onClick}) {
const size = 50;
return (
<div className={classNames(styles.indicator, {[styles.visible]: visible})}>
<div className={styles.icons}>
<div className={styles.iconTopLeft}>
<ArrowLeftIcon width={size} height={size} />
</div>
<div className={styles.iconTopRight}>
<ArrowLeftIcon width={size} height={size} />
</div>
<div className={styles.iconBottomRight}>
<ArrowLeftIcon width={size} height={size} />
</div>
<div className={styles.iconBottomLeft}>
<ArrowLeftIcon width={size} height={size} />
</div>
</div>
<div className={styles.text}>
360°
</div>
</div>
);
}
|
docs/app/Examples/elements/Step/Groups/index.js | jcarbo/stardust | import React from 'react'
import { Icon, Message } from 'stardust'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const Groups = () => (
<ExampleSection title='Groups'>
<ComponentExample
title='Steps'
description='A set of steps.'
examplePath='elements/Step/Groups/Groups'
>
<Message positive icon>
<Icon name='mobile' />
<Message.Content>
<Message.Header>Responsive Element</Message.Header>
Steps will automatically stack on mobile.
To make steps automatically stack for tablet use the <code>stackable='tablet'</code> variation.
</Message.Content>
</Message>
</ComponentExample>
<ComponentExample
title='Ordered'
description='A step can show a ordered sequence of steps.'
examplePath='elements/Step/Groups/Ordered'
/>
<ComponentExample
title='Vertical'
description='A step can be displayed stacked vertically.'
examplePath='elements/Step/Groups/Vertical'
/>
</ExampleSection>
)
export default Groups
|
lib/index.js | ppot/hyper | import {webFrame} from 'electron';
import forceUpdate from 'react-deep-force-update';
import {Provider} from 'react-redux';
import React from 'react';
import {render} from 'react-dom';
import rpc from './rpc';
import init from './actions/index';
import * as config from './utils/config';
import * as plugins from './utils/plugins';
import * as uiActions from './actions/ui';
import * as updaterActions from './actions/updater';
import * as sessionActions from './actions/sessions';
import * as termGroupActions from './actions/term-groups';
import {addNotificationMessage} from './actions/notifications';
import {loadConfig, reloadConfig} from './actions/config';
import HyperContainer from './containers/hyper';
import configureStore from './store/configure-store';
// Disable pinch zoom
webFrame.setZoomLevelLimits(1, 1);
const store_ = configureStore();
window.__defineGetter__('store', () => store_);
window.__defineGetter__('rpc', () => rpc);
window.__defineGetter__('config', () => config);
window.__defineGetter__('plugins', () => plugins);
// initialize config
store_.dispatch(loadConfig(config.getConfig()));
config.subscribe(() => {
store_.dispatch(reloadConfig(config.getConfig()));
});
// initialize communication with main electron process
// and subscribe to all user intents for example from menus
rpc.on('ready', () => {
store_.dispatch(init());
store_.dispatch(uiActions.setFontSmoothing());
});
rpc.on('session add', data => {
store_.dispatch(sessionActions.addSession(data));
});
rpc.on('session data', d => {
// the uid is a uuid v4 so it's 36 chars long
const uid = d.slice(0, 36);
const data = d.slice(36);
store_.dispatch(sessionActions.addSessionData(uid, data));
});
rpc.on('session data send', ({uid, data, escaped}) => {
store_.dispatch(sessionActions.sendSessionData(uid, data, escaped));
});
rpc.on('session exit', ({uid}) => {
store_.dispatch(termGroupActions.ptyExitTermGroup(uid));
});
rpc.on('termgroup close req', () => {
store_.dispatch(termGroupActions.exitActiveTermGroup());
});
rpc.on('session clear req', () => {
store_.dispatch(sessionActions.clearActiveSession());
});
rpc.on('session move word left req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x1bb'));
});
rpc.on('session move word right req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x1bf'));
});
rpc.on('session move line beginning req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x1bOH'));
});
rpc.on('session move line end req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x1bOF'));
});
rpc.on('session del word left req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x1b\x7f'));
});
rpc.on('session del word right req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x1bd'));
});
rpc.on('session del line beginning req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x1bw'));
});
rpc.on('session del line end req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x10B'));
});
rpc.on('session break req', () => {
store_.dispatch(sessionActions.sendSessionData(null, '\x03'));
});
rpc.on('termgroup add req', () => {
store_.dispatch(termGroupActions.requestTermGroup());
});
rpc.on('split request horizontal', () => {
store_.dispatch(termGroupActions.requestHorizontalSplit());
});
rpc.on('split request vertical', () => {
store_.dispatch(termGroupActions.requestVerticalSplit());
});
rpc.on('reset fontSize req', () => {
store_.dispatch(uiActions.resetFontSize());
});
rpc.on('increase fontSize req', () => {
store_.dispatch(uiActions.increaseFontSize());
});
rpc.on('decrease fontSize req', () => {
store_.dispatch(uiActions.decreaseFontSize());
});
rpc.on('move left req', () => {
store_.dispatch(uiActions.moveLeft());
});
rpc.on('move right req', () => {
store_.dispatch(uiActions.moveRight());
});
rpc.on('move jump req', index => {
store_.dispatch(uiActions.moveTo(index));
});
rpc.on('next pane req', () => {
store_.dispatch(uiActions.moveToNextPane());
});
rpc.on('prev pane req', () => {
store_.dispatch(uiActions.moveToPreviousPane());
});
rpc.on('open file', ({path}) => {
store_.dispatch(uiActions.openFile(path));
});
rpc.on('open ssh', url => {
store_.dispatch(uiActions.openSSH(url));
});
rpc.on('update available', ({releaseName, releaseNotes, releaseUrl, canInstall}) => {
store_.dispatch(updaterActions.updateAvailable(releaseName, releaseNotes, releaseUrl, canInstall));
});
rpc.on('move', () => {
store_.dispatch(uiActions.windowMove());
});
rpc.on('windowGeometry change', () => {
store_.dispatch(uiActions.windowGeometryUpdated());
});
rpc.on('add notification', ({text, url, dismissable}) => {
store_.dispatch(addNotificationMessage(text, url, dismissable));
});
const app = render(
<Provider store={store_}>
<HyperContainer />
</Provider>,
document.getElementById('mount')
);
rpc.on('reload', () => {
plugins.reload();
forceUpdate(app);
});
|
es/components/toolbar/toolbar.js | cvdlab/react-planner | var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { MdSettings, MdUndo, MdDirectionsRun } from 'react-icons/md';
import { FaFile, FaMousePointer, FaPlus } from 'react-icons/fa';
import ToolbarButton from './toolbar-button';
import ToolbarSaveButton from './toolbar-save-button';
import ToolbarLoadButton from './toolbar-load-button';
import If from '../../utils/react-if';
import { MODE_IDLE, MODE_3D_VIEW, MODE_3D_FIRST_PERSON, MODE_VIEWING_CATALOG, MODE_CONFIGURING_PROJECT } from '../../constants';
import * as SharedStyle from '../../shared-style';
var iconTextStyle = {
fontSize: '19px',
textDecoration: 'none',
fontWeight: 'bold',
margin: '0px',
userSelect: 'none'
};
var Icon2D = function Icon2D(_ref) {
var style = _ref.style;
return React.createElement(
'p',
{ style: _extends({}, iconTextStyle, style) },
'2D'
);
};
var Icon3D = function Icon3D(_ref2) {
var style = _ref2.style;
return React.createElement(
'p',
{ style: _extends({}, iconTextStyle, style) },
'3D'
);
};
var ASIDE_STYLE = {
backgroundColor: SharedStyle.PRIMARY_COLOR.main,
padding: '10px'
};
var sortButtonsCb = function sortButtonsCb(a, b) {
if (a.index === undefined || a.index === null) {
a.index = Number.MAX_SAFE_INTEGER;
}
if (b.index === undefined || b.index === null) {
b.index = Number.MAX_SAFE_INTEGER;
}
return a.index - b.index;
};
var mapButtonsCb = function mapButtonsCb(el, ind) {
return React.createElement(
If,
{
key: ind,
condition: el.condition,
style: { position: 'relative' }
},
el.dom
);
};
var Toolbar = function (_Component) {
_inherits(Toolbar, _Component);
function Toolbar(props, context) {
_classCallCheck(this, Toolbar);
var _this = _possibleConstructorReturn(this, (Toolbar.__proto__ || Object.getPrototypeOf(Toolbar)).call(this, props, context));
_this.state = {};
return _this;
}
_createClass(Toolbar, [{
key: 'shouldComponentUpdate',
value: function shouldComponentUpdate(nextProps, nextState) {
return this.props.state.mode !== nextProps.state.mode || this.props.height !== nextProps.height || this.props.width !== nextProps.width || this.props.state.alterate !== nextProps.state.alterate;
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
state = _props.state,
width = _props.width,
height = _props.height,
toolbarButtons = _props.toolbarButtons,
allowProjectFileSupport = _props.allowProjectFileSupport,
_context = this.context,
projectActions = _context.projectActions,
viewer3DActions = _context.viewer3DActions,
translator = _context.translator;
var mode = state.get('mode');
var alterate = state.get('alterate');
var alterateColor = alterate ? SharedStyle.MATERIAL_COLORS[500].orange : '';
var sorter = [{
index: 0, condition: allowProjectFileSupport, dom: React.createElement(
ToolbarButton,
{
active: false,
tooltip: translator.t('New project'),
onClick: function onClick(event) {
return confirm(translator.t('Would you want to start a new Project?')) ? projectActions.newProject() : null;
} },
React.createElement(FaFile, null)
)
}, {
index: 1, condition: allowProjectFileSupport,
dom: React.createElement(ToolbarSaveButton, { state: state })
}, {
index: 2, condition: allowProjectFileSupport,
dom: React.createElement(ToolbarLoadButton, { state: state })
}, {
index: 3, condition: true,
dom: React.createElement(
ToolbarButton,
{
active: [MODE_VIEWING_CATALOG].includes(mode),
tooltip: translator.t('Open catalog'),
onClick: function onClick(event) {
return projectActions.openCatalog();
} },
React.createElement(FaPlus, null)
)
}, {
index: 4, condition: true, dom: React.createElement(
ToolbarButton,
{
active: [MODE_3D_VIEW].includes(mode),
tooltip: translator.t('3D View'),
onClick: function onClick(event) {
return viewer3DActions.selectTool3DView();
} },
React.createElement(Icon3D, null)
)
}, {
index: 5, condition: true, dom: React.createElement(
ToolbarButton,
{
active: [MODE_IDLE].includes(mode),
tooltip: translator.t('2D View'),
onClick: function onClick(event) {
return projectActions.setMode(MODE_IDLE);
} },
[MODE_3D_FIRST_PERSON, MODE_3D_VIEW].includes(mode) ? React.createElement(Icon2D, { style: { color: alterateColor } }) : React.createElement(FaMousePointer, { style: { color: alterateColor } })
)
}, {
index: 6, condition: true, dom: React.createElement(
ToolbarButton,
{
active: [MODE_3D_FIRST_PERSON].includes(mode),
tooltip: translator.t('3D First Person'),
onClick: function onClick(event) {
return viewer3DActions.selectTool3DFirstPerson();
} },
React.createElement(MdDirectionsRun, null)
)
}, {
index: 7, condition: true, dom: React.createElement(
ToolbarButton,
{
active: false,
tooltip: translator.t('Undo (CTRL-Z)'),
onClick: function onClick(event) {
return projectActions.undo();
} },
React.createElement(MdUndo, null)
)
}, {
index: 8, condition: true, dom: React.createElement(
ToolbarButton,
{
active: [MODE_CONFIGURING_PROJECT].includes(mode),
tooltip: translator.t('Configure project'),
onClick: function onClick(event) {
return projectActions.openProjectConfigurator();
} },
React.createElement(MdSettings, null)
)
}];
sorter = sorter.concat(toolbarButtons.map(function (Component, key) {
return Component.prototype ? //if is a react component
{
condition: true,
dom: React.createElement(Component, { mode: mode, state: state, key: key })
} : { //else is a sortable toolbar button
index: Component.index,
condition: Component.condition,
dom: React.createElement(Component.dom, { mode: mode, state: state, key: key })
};
}));
return React.createElement(
'aside',
{ style: _extends({}, ASIDE_STYLE, { maxWidth: width, maxHeight: height }), className: 'toolbar' },
sorter.sort(sortButtonsCb).map(mapButtonsCb)
);
}
}]);
return Toolbar;
}(Component);
export default Toolbar;
Toolbar.propTypes = {
state: PropTypes.object.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
allowProjectFileSupport: PropTypes.bool.isRequired,
toolbarButtons: PropTypes.array
};
Toolbar.contextTypes = {
projectActions: PropTypes.object.isRequired,
viewer2DActions: PropTypes.object.isRequired,
viewer3DActions: PropTypes.object.isRequired,
linesActions: PropTypes.object.isRequired,
holesActions: PropTypes.object.isRequired,
itemsActions: PropTypes.object.isRequired,
translator: PropTypes.object.isRequired
}; |
src/index.js | mianuddin/GPA-Goal-Graph | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, useRouterHistory } from 'react-router';
import { createHashHistory } from 'history';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import { fromJS } from 'immutable';
import { combineReducers } from 'redux-immutable';
import * as reducers from './reducers';
import routes from './routes';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
const initialState = fromJS({
mainForm: {
includeClasses: false,
classTotal: {
grade: 0,
credits: 0,
},
canSubmit: true,
},
classes: [],
classForm: {
selectedClass: 0,
canSubmit: true,
dialogOpen: false,
},
});
const store = createStore(
combineReducers(reducers),
initialState,
window.devToolsExtension ? window.devToolsExtension() : undefined
);
const appHistory = useRouterHistory(createHashHistory)({ queryKey: false });
ReactDOM.render(
<Provider store={store}>
<Router history={appHistory} onUpdate={() => window.scrollTo(0, 0)}>
{routes}
</Router>
</Provider>,
document.getElementById('app')
);
|
client/src/javascript/components/general/WindowTitle.js | jfurrow/flood | import {injectIntl} from 'react-intl';
import React from 'react';
import connectStores from '../../util/connectStores';
import {compute, getTranslationString} from '../../util/size';
import EventTypes from '../../constants/EventTypes';
import TransferDataStore from '../../stores/TransferDataStore';
const WindowTitle = props => {
const {intl, summary} = props;
React.useEffect(
() => {
let title = 'Flood';
if (Object.keys(summary).length > 0) {
const down = compute(summary.downRate);
const up = compute(summary.upRate);
const formattedDownSpeed = intl.formatNumber(down.value);
const formattedUpSpeed = intl.formatNumber(up.value);
const translatedDownUnit = intl.formatMessage(
{
id: 'unit.speed',
defaultMessage: '{baseUnit}/s',
},
{
baseUnit: intl.formatMessage({id: getTranslationString(down.unit)}),
},
);
const translatedUpUnit = intl.formatMessage(
{
id: 'unit.speed',
defaultMessage: '{baseUnit}/s',
},
{
baseUnit: intl.formatMessage({id: getTranslationString(up.unit)}),
},
);
title = intl.formatMessage(
{
id: 'window.title',
// \u2193 and \u2191 are down and up arrows, respectively
defaultMessage: '\u2193 {down} \u2191 {up} - Flood',
},
{
down: `${formattedDownSpeed} ${translatedDownUnit}`,
up: `${formattedUpSpeed} ${translatedUpUnit}`,
},
);
}
document.title = title;
},
[intl, summary],
);
return null;
};
const ConnectedWindowTitle = connectStores(injectIntl(WindowTitle), () => {
return [
{
store: TransferDataStore,
event: EventTypes.CLIENT_TRANSFER_SUMMARY_CHANGE,
getValue: ({store}) => {
return {
summary: store.getTransferSummary(),
};
},
},
];
});
export default ConnectedWindowTitle;
|
app/index.js | jpsierens/webpack-react-redux | import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import { configureStore, history } from './store/configureStore';
import Root from './containers/Root';
const store = configureStore();
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept('./containers/Root', () => {
const newConfigureStore = require('./store/configureStore');
const newStore = newConfigureStore.configureStore();
const newHistory = newConfigureStore.history;
const NewRoot = require('./containers/Root').default;
render(
<AppContainer>
<NewRoot store={newStore} history={newHistory} />
</AppContainer>,
document.getElementById('root')
);
});
}
|
src/server.js | Sawtaytoes/Ghadyani-Framework-Webpack-React-Redux | import React from 'react'
import { renderToString } from 'react-dom/server'
import { StaticRouter as Router } from 'react-router-dom'
import { Provider } from 'react-redux'
import { compose, createStore } from 'redux'
import 'utils/polyfills'
import Pages from 'components/pages'
import renderSite from 'renderers/renderSite'
import { rootReducer } from 'reducers'
import { updatePageMeta } from 'reducers/pageMeta'
module.exports = (req, res) => {
const context = {}
const store = compose()(createStore)(rootReducer)
const renderedContent = renderToString(
<Provider store={store}>
<Router
location={req.url}
context={context}
>
<Pages />
</Router>
</Provider>
)
store.dispatch(
updatePageMeta(req.url)
)
const renderedPage = renderSite(renderedContent, store.getState())
if (context.url) {
res
.writeHead(302, { Location: context.url })
.end()
} else {
res
.send(renderedPage)
.end()
}
}
|
src/components/Cover/index.js | mother/oio | import PropTypes from 'prop-types'
import React from 'react'
const Cover = ({
src,
size = 'cover',
position,
children,
className }) => {
const style = {
float: 'left',
position: 'relative',
width: '100%',
height: '100%',
backgroundImage: `url(${src})`,
backgroundSize: size,
backgroundPosition: position,
backgroundRepeat: 'no-repeat'
}
return (
<div className={className} style={style}>{children}</div>
)
}
Cover.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
position: PropTypes.string,
size: PropTypes.string,
src: PropTypes.string
}
Cover.defaultProps = {
position: 'center center'
}
export default Cover
|
src/app/components/source/UserInfo.js | meedan/check-web | import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import { browserHistory } from 'react-router';
import IconButton from '@material-ui/core/IconButton';
import IconEdit from '@material-ui/icons/Edit';
import AccountChips from './AccountChips';
import Can from '../Can';
import ParsedText from '../ParsedText';
import { parseStringUnixTimestamp, truncateLength } from '../../helpers';
import SourcePicture from './SourcePicture';
import {
StyledContactInfo,
StyledTwoColumns,
StyledSmallColumn,
StyledBigColumn,
StyledName,
StyledDescription,
} from '../../styles/js/HeaderCard';
import { Row } from '../../styles/js/shared';
import globalStrings from '../../globalStrings';
const UserInfo = (props) => {
if (props.user.source === null) return null;
return (
<StyledTwoColumns>
<StyledSmallColumn>
<SourcePicture
size="large"
object={props.user.source}
type="user"
className="source__avatar"
/>
</StyledSmallColumn>
<StyledBigColumn>
<div className="source__primary-info">
<StyledName className="source__name">
<Row>
{props.user.name}
<Can permissions={props.user.permissions} permission="update User">
<IconButton
className="source__edit-source-button"
onClick={() => {
if (props.user.dbid === props.context.currentUser.dbid) {
browserHistory.push('/check/me/edit');
} else {
browserHistory.push(`/check/user/${props.user.dbid}/edit`);
}
}}
tooltip={props.intl.formatMessage(globalStrings.edit)}
>
<IconEdit />
</IconButton>
</Can>
</Row>
</StyledName>
<StyledDescription>
<p>
<ParsedText text={truncateLength(props.user.source.description, 600)} />
</p>
</StyledDescription>
</div>
<AccountChips
accounts={props.user.source.account_sources.edges.map(as => as.node.account)}
/>
<StyledContactInfo>
<FormattedMessage
id="userInfo.dateJoined"
defaultMessage="Joined {date}"
values={{
date: props.intl.formatDate(
parseStringUnixTimestamp(props.user.source.created_at),
{ year: 'numeric', month: 'short', day: '2-digit' },
),
}}
/>
<FormattedMessage
id="userInfo.teamsCount"
defaultMessage="{teamsCount, plural, one {# workspace} other {# workspaces}}"
values={{
teamsCount: props.user.team_users.edges.length || 0,
}}
/>
</StyledContactInfo>
</StyledBigColumn>
</StyledTwoColumns>
);
};
export default injectIntl(UserInfo);
|
src/components/Iconfont/Iconfont.js | china2008qyj/DVA-DEMO | import React from 'react'
import PropTypes from 'prop-types'
import './iconfont.less'
const Iconfont = ({ type, colorful }) => {
if (colorful) {
return (<span
dangerouslySetInnerHTML={{
__html: `<svg class="colorful-icon" aria-hidden="true"><use xlink:href="#${type.startsWith('#') ? type.replace(/#/, '') : type}"></use></svg>`,
}}
/>)
}
return <i className={`antdadmin icon-${type}`} />
}
Iconfont.propTypes = {
type: PropTypes.string,
colorful: PropTypes.bool,
}
export default Iconfont
|
src/app/modules/Network/components/dialogs/AddProxyDialog.js | toxzilla/app | import React from 'react';
import {connect} from 'cerebral-view-react';
import {Content} from './../../../../common/UserInterface';
import {Dialog} from './../../../Dialog';
import ProxyForm from './../forms/ProxyForm';
export default connect({
dialogName: 'dialog.name'
}, class AddProxyDialog extends React.Component {
static displayName = 'AddProxyDialog'
static propTypes = {
signals: React.PropTypes.object.isRequired,
dialogName: React.PropTypes.string.isRequired
}
state = {
isOpen: true
}
render () {
const {isOpen} = this.state;
return (
<Dialog open={isOpen}
skippable={true}
onClose={this._handleClose}>
<Content header={{id: 'addProxy'}}>
<ProxyForm onSubmit={this._handleSubmit}
onCancel={this._handleCancel}/>
</Content>
</Dialog>
);
}
_handleSubmit = (event, formData) => {
this.props.signals.dialog.closeDialog({
dialogName: this.props.dialogName,
success: true,
...formData
});
}
_handleCancel = () => {
this.setState({
isOpen: false
});
}
_handleClose = () => {
this.props.signals.dialog.closeDialog({
dialogName: this.props.dialogName,
success: false
});
}
});
|
src/components/topic/wizard/TopicSettingsForm.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { reduxForm, Field } from 'redux-form';
import { Row, Col } from 'react-flexbox-grid/lib';
import AppButton from '../../common/AppButton';
import withIntlForm from '../../common/hocs/IntlForm';
const localMessages = {
name: { id: 'topic.form.detail.name', defaultMessage: 'Topic Name (what is this about?)' },
nameError: { id: 'topic.form.detail.name.error', defaultMessage: 'Your topic needs a short dsecriptive name.' },
description: { id: 'topic.form.detail.description', defaultMessage: 'Description (why are you making this?)' },
descriptionError: { id: 'topic.form.detail.desciption.error', defaultMessage: 'Your topic need a description.' },
maxStories: { id: 'topic.form.detail.maxStories', defaultMessage: 'Maximum # of Stories' },
maxSeedStoriesHelp: { id: 'topic.form.detail.maxStories', defaultMessage: 'Public users can make topics with up to 100,000 total stories. Change this if you want to allow a special case exception.' },
public: { id: 'topic.form.detail.public', defaultMessage: 'Public?' },
logogram: { id: 'topic.form.detail.logogram', defaultMessage: 'Content in a Logographic Language? (ie. Chinese or Japanese Kanji?)' },
crimsonHexagon: { id: 'topic.form.detail.crimsonHexagon', defaultMessage: 'Crimson Hexagon Id' },
crimsonHexagonHelp: { id: 'topic.form.detail.crimsonHexagon.help', defaultMessage: 'If you have set up a Crimson Hexagon monitor on our associated account, enter it\'s numeric ID here and we will automatically pull in all the stories linked to by tweets in your monitor.' },
maxIterations: { id: 'topic.form.detail.maxIterations', defaultMessage: 'Max Spider Iterations' },
maxIterationsHelp: { id: 'topic.form.detail.maxIterations.help', defaultMessage: 'You can change how many rounds of spidering you want to do. If you expect this topic to explode with lots and lots of linked-to stories about the same topic, then keep this small. Otherwise leave it with the default of 15.' },
};
const TopicSettingsForm = (props) => {
const { renderTextField, renderCheckbox, handleSubmit, pristine, submitting, asyncValidating, initialValues, onSubmit } = props;
const { formatMessage } = props.intl;
return (
<form className="edit-topic-settings" name="topicForm" onSubmit={handleSubmit(onSubmit.bind(this))}>
<Row>
<Col lg={6}>
<Field
name="name"
component={renderTextField}
fullWidth
label={formatMessage(localMessages.name)}
/>
</Col>
</Row>
<Row>
<Col lg={6}>
<Field
name="description"
component={renderTextField}
fullWidth
label={formatMessage(localMessages.description)}
rows={4}
multiline
/>
</Col>
</Row>
<Row>
<Col lg={8}>
<Field
name="is_logogram"
component={renderCheckbox}
fullWidth
label={formatMessage(localMessages.logogram)}
/>
</Col>
</Row>
<Row>
<Col lg={12}>
<AppButton
style={{ marginTop: 30 }}
type="submit"
disabled={pristine || submitting || asyncValidating === true}
label={initialValues.buttonLabel}
primary
/>
</Col>
</Row>
</form>
);
};
TopicSettingsForm.propTypes = {
// from compositional chain
intl: PropTypes.object.isRequired,
renderTextField: PropTypes.func.isRequired,
renderCheckbox: PropTypes.func.isRequired,
renderSelect: PropTypes.func.isRequired,
// from parent
initialValues: PropTypes.object,
handleSubmit: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
pristine: PropTypes.bool.isRequired,
error: PropTypes.string,
asyncValidating: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool,
]).isRequired,
submitting: PropTypes.bool.isRequired,
};
const reduxFormConfig = {
form: 'topicForm',
};
export default
withIntlForm(
reduxForm(reduxFormConfig)(
TopicSettingsForm
)
);
|
components/Property.js | stucco/ui | import React from 'react'
class Property extends React.Component {
render () {
return (
<div>
<dt>{this.props.propertyName}</dt>
<dd>{this.props.propertyValue}</dd>
</div>
)
}
}
Property.propTypes = {
propertyName: React.PropTypes.string,
propertyValue: React.PropTypes.any
}
export default Property
|
www/src/components/survey/RenderValidationField.js | cygwin255/SimpleSurvey | import React from 'react'
const RenderValidationField = ({
input,
meta: { touched, error, warning },
span,
textarea,
...props
}) => {
let errorProps = {}
let externalError
if (touched && error) {
errorProps.className = props.className + ' is-invalid'
if (!input.value) {
errorProps.placeholder = `${props.placeholder} ${error}`
} else {
externalError = (
<div className='red'>
{`${props.placeholder} ${error}`}
</div>
)
}
}
if (textarea) {
return (
<span>
<textarea
{...input}
{...props}
{...errorProps}
/>
{externalError}
</span>
)
} else {
return (
<span>
<input
{...input}
{...props}
{...errorProps}
/>
{externalError}
</span>
)
}
}
export default RenderValidationField
|
node_modules/react-router/modules/IndexRedirect.js | FrancoCotter/ReactWeatherApp | import React from 'react'
import warning from './routerWarning'
import invariant from 'invariant'
import Redirect from './Redirect'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
const IndexRedirect = React.createClass({
statics: {
createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = Redirect.createRouteFromReactElement(element)
} else {
warning(
false,
'An <IndexRedirect> does not make sense at the root of your route config'
)
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render() {
invariant(
false,
'<IndexRedirect> elements are for router configuration only and should not be rendered'
)
}
})
export default IndexRedirect
|
photoView.js | dcy0701/ReactNativeServer | 'use strict'
import {
StyleSheet,
Text,
View,
TabBarIOS,
NavigatorIOS,
ScrollView,
Dimensions,
TouchableOpacity,
Image,
AsyncStorage,
AlertIOS
} from 'react-native';
import React from 'react';
import {API} from './config';
var Icon = require('react-native-vector-icons/FontAwesome');
const PhotoView = React.createClass({
getInitialState(){
return{
}
},
sign(){
//此处收集所有数据 进行签到。。。。
// 或者把数据放在这里。。签到。。
//并且在此页面,根据不同的结果进行判断,判断是否替换。。。
//是否申请替换 负责人
//然后签到流程到此结束
//oh yeah!!!!
//TODO
//
let formData = new FormData();
var project_id = this.props.passMes.sonProjectIndex;
formData.append('photo',{uri:this.props.imageUrl.path,type:'image/jpg',name:'image.jpg'});
formData.append('location',this.props.passMes.latitude+'$'+this.props.passMes.longitude);
formData.append('project_id',project_id);
AsyncStorage.getItem('loginStatus',function(error,result){
//mock data ***************************************************
let username = result.split('$')[0];
formData.append('user',username);
let options = {headers:{}};
options.body = formData;
options.method = 'POST';
console.log(options);
fetch(API.LOCATION_API,options).then(function(res){
return res.json();
}).then(function(json){
console.log(json);
if(json.status=='s'){
AlertIOS.alert('签到成功');
}else if(json.status=='-1'){
AlertIOS.alert(
'签到成功但是'+json.text,
'是否申请为负责人?',
[
{text: '确定', onPress: () => {
console.log(API.UPDATECHAGEMENT_API+'?user='+username+'&project_id='+project_id);
fetch(API.UPDATECHAGEMENT_API+'?user='+username+'&project_id='+project_id)
.then(function(res){
console.log(res);
if(res=='apply error'){
AlertIOS.alert('工程不存在');
}else{
AlertIOS.alert('申请成功请等待');
}
this.props.navigator.popToTop();
}.bind(this))
}},
{text: '取消', onPress: () => {
// do nothing
this.props.navigator.popToTop();
}},
]
);
}else if(json.status=='1'){
AlertIOS.alert(json.text)
}else{
AlertIOS.alert(json.text)
}
}.bind(this));
}.bind(this));
//user
console.log(this.props.passMes)
},
render:function(){
var imgurl = this.props.imageUrl;
console.log(imgurl);
return (
<View style={styles.container}>
<Image style={styles.image}
source={{uri:imgurl.path}}
resizeMode='contain'
/>
<TouchableOpacity style={styles.sign} onPress={this.sign}>
<Text style={styles.text} onPress={this.sign}>
<Icon name="forumbee" size={20} color="white" /> 签到
</Text>
</TouchableOpacity>
</View>
)
}
});
var styles = StyleSheet.create({
image:{
flex:1,
height: Dimensions.get('window').height-55,
width: Dimensions.get('window').width,
marginRight:10,
marginTop:20,
justifyContent:'center',
alignItems:'center'
},
container:{
flex:1,
backgroundColor:'rgb(42,52,63)'
},
sign:{
flex: 0,
backgroundColor: '#fff',
borderRadius: 15,
marginLeft:130,
marginRight:130,
//color: 'pink',
padding: 10,
marginTop:4,
marginBottom:55,
backgroundColor:'rgb(39,217,179)',
justifyContent:'center',
},
text:{
textAlign:'center',
fontSize:20,
color:'white',
fontWeight:'bold',
}
});
module.exports=PhotoView;
|
app/app.js | azothForgotten/Newznab-Frontend | // ES6 Component
// Import React and ReactDOM
import React from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
import AppContainer from './containers/app.container';
// Search component created as a class
class App extends React.Component {
// render method is most important
// render method returns JSX template
render() {
return (
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
<AppContainer />
</MuiThemeProvider>
);
}
}
// Render to ID content in the DOM
ReactDOM.render( <App /> ,
document.getElementById('content')
);
|
src/components/javascript/plain/JavascriptPlain.js | fpoumian/react-devicon | import React from 'react'
import PropTypes from 'prop-types'
import SVGDeviconInline from '../../_base/SVGDeviconInline'
import iconSVG from './JavascriptPlain.svg'
/** JavascriptPlain */
function JavascriptPlain({ width, height, className }) {
return (
<SVGDeviconInline
className={'JavascriptPlain' + ' ' + className}
iconSVG={iconSVG}
width={width}
height={height}
/>
)
}
JavascriptPlain.propTypes = {
className: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
height: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
}
export default JavascriptPlain
|
src/elements/parserElements.js | EtherTyper/react-lang | import React from 'react'
import { generateAST } from '..';
const Parser = (Super = Object) => class BasicElements extends Super {
static parse(element, props, children) {
let babylon = props.babylon;
if (babylon) {
let [ code ] = children;
let ast = babylon.parse(code.value).program;
let handler = props.handler || ((program) => program);
return handler(ast);
} else {
throw new TypeError("Babylon instance not supplied.");
}
}
}
export default Parser; |
lesson-6/todos/src/components/Header.js | msd-code-academy/lessons | import React from 'react'
import { Link } from 'react-router-dom'
import NewNoteModal from './NewNoteModal'
import logo from '../logo.png'
import '../styles/Header.css'
class Header extends React.Component {
getNoteCountMessage(noteCount){
const isPlural = noteCount > 1;
return `(containing ${noteCount} idea${isPlural ? 's' : ''})`
}
render() {
const { ...props } = this.props
return (
<div className="Header">
<div className="Header-logo">
<img src={logo} alt="logo" />
<b>IDEA JOURNAL</b>
<span><Link to="/" >List Notes</Link></span>
<span><Link to="/Summary" >Summary</Link></span>
</div>
<NewNoteModal />
</div>
)
}
}
export default Header
|
src/components/ButtonList/Button.js | kshvmdn/seen-it | import React from 'react'
import classNames from 'classnames'
import toSentenceCase from 'utils/sentenceCase'
import styles from './styles.module.css'
export default class Button extends React.Component {
constructor(props) {
super(props);
}
handleClick() {
return this.props.onClick(this.props.name)
}
render() {
return (
<a href='#' className={classNames(styles.button, this.props.name)} onClick={this.handleClick.bind(this)}>
{toSentenceCase(this.props.name)}
</a>
)
}
}
|
src/admin/components/Programi.js | zeljkoX/e-learning | import React from 'react';
import {State, History} from 'react-router';
import { Menu, Mixins, Styles } from 'material-ui';
import Content from '../../components/layout/Content';
import ContentHeader from '../../components/layout/ContentHeader';
import Tabela from '../../components/Tabela';
class Programi extends React.Component {
displayName: "React-breadcrumbs";
render() {
var menu = [{name:'Dodaj Program', link:'programi/add'}];
return (
<Content>
<ContentHeader title='Naziv stranice' menu={menu}/>
<Tabela/>
</Content>
);
}
}
export default Programi;
|
src/svg-icons/communication/stay-current-landscape.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationStayCurrentLandscape = (props) => (
<SvgIcon {...props}>
<path d="M1.01 7L1 17c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2H3c-1.1 0-1.99.9-1.99 2zM19 7v10H5V7h14z"/>
</SvgIcon>
);
CommunicationStayCurrentLandscape = pure(CommunicationStayCurrentLandscape);
CommunicationStayCurrentLandscape.displayName = 'CommunicationStayCurrentLandscape';
CommunicationStayCurrentLandscape.muiName = 'SvgIcon';
export default CommunicationStayCurrentLandscape;
|
admin/client/Signin/index.js | brianjd/keystone | /**
* The signin page, it renders a page with a username and password input form.
*
* This is decoupled from the main app (in the "App/" folder) because we inject
* lots of data into the other screens (like the lists that exist) that we don't
* want to have injected here, so this is a completely separate route and template.
*/
import qs from 'qs';
import React from 'react';
import ReactDOM from 'react-dom';
import Signin from './Signin';
const params = qs.parse(window.location.search.replace(/^\?/, ''));
ReactDOM.render(
<Signin
brand={Keystone.brand}
from={params.from}
logo={Keystone.logo}
user={Keystone.user}
userCanAccessKeystone={Keystone.userCanAccessKeystone}
/>,
document.getElementById('signin-view')
);
|
src/components/BaseRouteComponent.js | kooinam/awry-utilities | import React, { Component } from 'react';
import { Route, Switch } from 'react-router-dom';
import { matchRouteParams } from './BreadcrumbsNavigator';
import { connect } from 'react-redux';
import type { Connector } from 'react-redux';
class BaseRouteComponent extends Component {
render() {
const { match, matchedRoutes, onMount, routes } = this.props;
let url = '';
if (match) {
if (match.url && match.url.length > 1) {
url = `${match.url}/`;
}
else {
url = match.url;
}
}
const routeWithSubRoutes = (route) => {
let key = `${url}${route.path}`
const matchedRoute = matchedRoutes.find((r) => {
return r.originalPath === key;
});
if (matchedRoute) {
key = matchedRoute.path;
}
return (
<Route
key={key}
exact={route.exact || false}
path={`${url}${route.path}`}
render={childProps => (
// Pass the sub-routes down to keep nesting
<route.component { ...this.props } {...childProps} routes={route.routes || []} routeProps={route.routeProps} onMount={onMount} matchedRoutes={matchedRoutes} />
)}
/>
);
}
return (
<Switch location={this.props.location}>
{routes.map(route => routeWithSubRoutes(route))}
</Switch>
);
}
};
/* eslint-disable no-unused-vars */
const connector: Connector<{}, Props> = connect(
(state) => {
return {
location: state.router.location,
};
}
);
/* eslint-enable no-unused-vars */
export default connector(BaseRouteComponent); |
client/extensions/woocommerce/woocommerce-services/views/shipping-label/label-purchase-modal/address-step/suggestion.js | Automattic/woocommerce-connect-client | /** @format */
/**
* External dependencies
*/
import React from 'react';
import PropTypes from 'prop-types';
import { localize } from 'i18n-calypso';
import { omit } from 'lodash';
import classNames from 'classnames';
/**
* Internal dependencies
*/
import FormLabel from 'components/forms/form-label';
import FormRadio from 'components/forms/form-radio';
import FormButton from 'components/forms/form-button';
import Notice from 'components/notice';
import AddressSummary from './summary';
const RadioButton = props => {
return (
<FormLabel
className={ classNames( 'address-step__suggestion', { 'is-selected': props.checked } ) }
>
<FormRadio { ...omit( props, 'children' ) } />
{ props.children }
</FormLabel>
);
};
const AddressSuggestion = ( {
values,
normalized,
selectNormalized,
selectNormalizedAddress,
editAddress,
confirmAddressSuggestion,
countryNames,
translate,
} ) => {
const onToggleSelectNormalizedAddress = value => () => selectNormalizedAddress( value );
const errorClass = 'error-notice';
return (
<div>
<Notice className={ errorClass } status="is-info" showDismiss={ false }>
{ translate(
'We have slightly modified the address entered. ' +
'If correct, please use the suggested address to ensure accurate delivery.'
) }
</Notice>
<div className="address-step__suggestion-container">
<RadioButton
checked={ ! selectNormalized }
onChange={ onToggleSelectNormalizedAddress( false ) }
>
<span className="address-step__suggestion-title">{ translate( 'Address entered' ) }</span>
<AddressSummary values={ values } countryNames={ countryNames } />
</RadioButton>
<RadioButton
checked={ selectNormalized }
onChange={ onToggleSelectNormalizedAddress( true ) }
>
<span className="address-step__suggestion-title">
{ translate( 'Suggested address' ) }
</span>
<AddressSummary
values={ normalized }
originalValues={ values }
countryNames={ countryNames }
/>
</RadioButton>
</div>
<div className="address-step__actions">
<FormButton type="button" onClick={ confirmAddressSuggestion }>
{ translate( 'Use selected address' ) }
</FormButton>
<FormButton type="button" onClick={ editAddress } borderless>
{ translate( 'Edit address' ) }
</FormButton>
</div>
</div>
);
};
AddressSuggestion.propTypes = {
values: PropTypes.object.isRequired,
normalized: PropTypes.object,
selectNormalized: PropTypes.bool.isRequired,
selectNormalizedAddress: PropTypes.func.isRequired,
confirmAddressSuggestion: PropTypes.func.isRequired,
editAddress: PropTypes.func.isRequired,
countryNames: PropTypes.object.isRequired,
};
export default localize( AddressSuggestion );
|
src/svg-icons/hardware/sim-card.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSimCard = (props) => (
<SvgIcon {...props}>
<path d="M19.99 4c0-1.1-.89-2-1.99-2h-8L4 8v12c0 1.1.9 2 2 2h12.01c1.1 0 1.99-.9 1.99-2l-.01-16zM9 19H7v-2h2v2zm8 0h-2v-2h2v2zm-8-4H7v-4h2v4zm4 4h-2v-4h2v4zm0-6h-2v-2h2v2zm4 2h-2v-4h2v4z"/>
</SvgIcon>
);
HardwareSimCard = pure(HardwareSimCard);
HardwareSimCard.displayName = 'HardwareSimCard';
HardwareSimCard.muiName = 'SvgIcon';
export default HardwareSimCard;
|
src/components/Footer/Footer.js | medevelopment/updatemeadmin | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
class Footer extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
</div>
</div>
);
}
}
export default withStyles(s)(Footer);
|
views/blocks/Likes/LikesContainer.js | FairTex/team5 | import React from 'react';
import sender from './../Sender/Sender';
import CommentsPoster from './../comments/CommentsPoster.js';
import Likes from './Likes';
const LikesWithSending = sender(Likes);
export default class LikesContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
likesCount: this.props.likesCount,
liked: this.props.liked
};
this.handleLikesChange = this.handleLikesChange.bind(this);
this.handleFailedSend = this.handleFailedSend.bind(this);
}
handleLikesChange() {
this.setState(prevState => ({
likesCount: prevState.likesCount + (prevState.liked ? -1 : 1),
liked: !prevState.liked
}));
}
handleFailedSend() {
setTimeout(this.handleLikesChange, 500);
}
render() {
return (
<LikesWithSending {...this.state}
data={this.props.id}
handleAction={CommentsPoster.likeComment}
onLike={this.handleLikesChange}
onFailedSend={this.handleFailedSend}
disabledLike={this.props.disabledLike}>
</LikesWithSending>);
}
}
|
src/TagCloud/TagCloud.js | resmio/mantecao | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import Tag from '../Tag'
const ItemStyled = styled.div`
display: inline-block;
margin: 0.4em 0.4em 0.4em 0;
`
const TagCloud = ({ names, onClickAction }) =>
<div>
{names.map((name, i) =>
<ItemStyled key={i}>
{onClickAction
? <Tag name={name} onClickAction={name => onClickAction(name)} />
: <Tag name={name} />}
</ItemStyled>
)}
</div>
TagCloud.propTypes = {
names: PropTypes.array,
onClickAction: PropTypes.func
}
export default TagCloud
|
src/components/StartAuction/TimeDuration.js | chochinlu/ens-bid-dapp | import React from 'react';
import classNames from 'classnames';
import {momentFromNow} from '../../lib/util';
import './TimeDuration.css';
const TimeBlock = (props) => {
const classes = classNames( 'TimeDuration-block', props.step);
const title = props.step === 'reveal'
? 'Reveal Bids On'
: 'Auction Finalizes On';
return (
<div className={classes}>
<p>{title}</p>
<h3>{props.thisTime.toString()}</h3>
<p>{momentFromNow(props.thisTime).toString()}</p>
</div>
);
};
export const TimeDuration = (props) => (
<div className='TimeDuration'>
<TimeBlock step='reveal' thisTime={props.unsealStartsAt} />
<TimeBlock step='finalize' thisTime={props.registratesAt} />
</div>
); |
lib/components/inner-dock.js | conveyal/scenario-editor | // @flow
import React from 'react'
export default class InnerDock extends React.PureComponent {
_el: HTMLElement
state: {
height?: number
}
componentDidMount () {
window.addEventListener('resize', this._setHeight)
}
componentWillUnmount () {
window.removeEventListener('resize', this._setHeight)
}
_ref = (el: HTMLElement) => {
this._el = el
this._setHeight()
}
_setHeight = () => {
if (this._el) {
this.setState({
height: window.innerHeight - this._el.offsetTop
})
}
}
render () {
return <div
className={`InnerDock ${this.props.className || ''}`}
ref={this._ref}
style={this.state}
>{this.props.children}</div>
}
}
|
components/User/UserProfile/UserLTIs.js | slidewiki/slidewiki-platform | import PropTypes from 'prop-types';
import React from 'react';
import {NavLink, navigateAction} from 'fluxible-router';
import updateUserlti from '../../../actions/user/userprofile/updateUserlti';
import deleteUserlti from '../../../actions/user/userprofile/deleteUserlti';
import leaveUserlti from '../../../actions/user/userprofile/leaveUserlti';
import { LTI_ID } from '../../../configs/general';
class UserLTIs extends React.Component {
constructor(props){
super(props);
this.styles = {'backgroundColor': '#2185D0', 'color': 'white'};
}
componentWillReceiveProps(nextProps) {
if (nextProps.error.action !== undefined && this.props.error === '') {
let message = 'Error while deleting the lti: ';
if (nextProps.error.action === 'leave')
message = 'Error while leaving the lti: ';
swal({
title: 'Error',
text: message + nextProps.error.message,
type: 'error',
confirmButtonText: 'Close',
confirmButtonClass: 'negative ui button',
allowEscapeKey: false,
allowOutsideClick: false,
buttonsStyling: false
})
.then(() => {
this.context.executeAction(updateUserlti, {lti: {}, offline: true});
return true;
})
.catch();
return;
}
}
handleClickOnEditLTI(e) {
e.preventDefault();
// console.log('handleClickOnEditLTI:', e.target.attributes.name.value);
const action = e.target.attributes.name.value; //eg. changeLTI_2
const ltiid = action.split('_')[1];
let lti = this.props.ltis.find((lti) => {
return lti._id.toString() === ltiid;
});
this.context.executeAction(updateUserlti, {lti: lti, offline: false});
this.context.executeAction(navigateAction, {
url: '/user/' + this.props.username + '/ltis/edit'
});
}
handleClickOnRemoveLTI(e) {
e.preventDefault();
console.log('handleClickOnRemoveLTI:', e.target.attributes.name.value);
const action = e.target.attributes.name.value; //eg. changeLTI_2
const ltiid = action.split('_')[1];
swal({
titleText: 'Are you sure you want to delete this service?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete it!'
}).then((accepted) => {
this.context.executeAction(deleteUserlti, {ltiid: ltiid});
swal('LTI Service successfully deleted');
}, (cancelled) => {/*do nothing*/})
.catch(swal.noop);
}
handleClickOnLeaveLTI(e) {
e.preventDefault();
console.log('handleClickOnLeaveLTI:', e.target.attributes.name.value);
const action = e.target.attributes.name.value; //eg. changeLTI_2
const ltiid = action.split('_')[1];
this.context.executeAction(leaveUserlti, {ltiid: ltiid});
}
handleCLickNewLTI(e) {
e.preventDefault();
this.context.executeAction(updateUserlti, {lti: {}, offline: true});
this.context.executeAction(navigateAction, {
url: '/user/' + this.props.username + '/ltis/edit'
});
}
render() {
let items = [];
console.log('render userLTIs:', this.props.userid, this.props.ltis);
if(! (this.props.username.endsWith(LTI_ID))){
this.props.ltis.forEach((lti) => {
items.push( (
<div key={lti._id} className="ui vertical segment" >
<div className="ui two column grid container">
<div className="column">
<div className="ui header"><h3>{lti.key}</h3></div>
<div
className="meta">{lti.members.length+1} member{((lti.members.length+1) !== 1) ? 's': ''}</div>
</div>
<div className="right aligned column">
{((this.props.userid === lti.creator) || (this.props.userid === lti.creator.userid)) ? (
<div>
<button className="ui large basic icon button" data-tooltip="LTI deletion" aria-label="LTI deletion" name={'deleteLTI_' + lti._id} onClick={this.handleClickOnRemoveLTI.bind(this)} >
<i className="remove icon" name={'deleteLTI_' + lti._id} ></i>
</button>
<button className="ui large basic icon button" data-tooltip="LTI settings" aria-label="LTI settings" name={'changeLTI_' + lti._id} onClick={this.handleClickOnEditLTI.bind(this)} >
<i className="setting icon" name={'changeLTI_' + lti._id} ></i>
</button>
</div>
) : (
<button className="ui large basic icon button" data-tooltip="Leave LTI" aria-label="Leave LTI" name={'leaveLTI_' + lti._id} onClick={this.handleClickOnLeaveLTI.bind(this)} >
<i className="remove icon" name={'leaveLTI_' + lti._id} ></i>
</button>
)}
</div>
</div>
</div>
));
});
}//end if(! (this.props.username.endsWith(LTI_ID))
else{
this.props.ltis.forEach((lti) => {
items.push( (
<div key={lti._id} className="ui vertical segment" >
<div className="ui two column grid container">
<div className="column">
<div className="ui header"><h3>{lti.key}</h3></div>
<div
className="meta">{lti.members.length+1} member{((lti.members.length+1) !== 1) ? 's': ''}</div>
</div>
</div>
</div>
));
});
}
if (this.props.ltis === undefined || this.props.ltis === null || this.props.ltis.length < 1) {
items = [(
<div key="dummy" className="ui vertical segment" >
<div className="ui two column stackable grid container">
<h4>No LTI Services connected.</h4>
</div>
</div>
)];
}
if(! (this.props.username.endsWith(LTI_ID))){
return (
<div className="ui segments">
<div className="ui secondary clearing segment" >
<h3 className="ui left floated header" >Learning Services (LTIs)</h3>
<button className="ui right floated labeled icon button" tabIndex="0" onClick={this.handleCLickNewLTI.bind(this)}>
<i className="icon plus"/>
<p>Add new service</p>
</button>
</div>
{(this.props.status === 'pending') ? <div className="ui active dimmer"><div className="ui text loader">Loading</div></div> : ''}
{items}
</div>
);
}//end if
else{
return (
<div className="ui segments">
<div className="ui secondary clearing segment" >
<h3 className="ui left floated header" >Learning Services (LTIs)</h3>
</div>
{(this.props.status === 'pending') ? <div className="ui active dimmer"><div className="ui text loader">Loading</div></div> : ''}
{items}
</div>
);
}//end else
}
}
UserLTIs.contextTypes = {
executeAction: PropTypes.func.isRequired
};
export default UserLTIs;
|
src/docs/pages/list.js | gabrielcsapo/psychic-ui | import React from 'react';
import Example from '../components/example';
class List extends React.Component {
render() {
const { brand } = this.props;
const height = window.innerHeight;
return (
<section style={{ 'minHeight': height, position: "relative"}}>
<div style={{padding: "50px"}}>
<h3> List </h3>
<div style={{ margin: '0 auto' }}>
<Example summary={"Basic list"}>
<ul className="list">
<li className="list-item">Item 1</li>
<li className="list-item">Item 2</li>
</ul>
</Example>
<Example summary={"Basic list colored"}>
<ul className="list">
<li className="list-item">Item 1</li>
<li className={`list-item list-item-${brand}`}>Item 2</li>
<li className="list-item">Item 3</li>
<li className={`list-item list-item-${brand}`}>Item 4</li>
</ul>
</Example>
<Example summary={"List with badges"}>
<ul className="list">
<li className="list-item">Item 1
<div className={ `badge badge-${brand}` }>14</div>
</li>
<li className="list-item">Item 2
<div className={ `badge badge-${brand}` }>3</div>
</li>
</ul>
</Example>
<Example summary={"List with left and right positioned items"}>
<ul className="list">
<li className="list-item">
<div className="list-item-left">Left</div>
<div className="list-item-right">Right</div>
</li>
</ul>
</Example>
</div>
</div>
</section>
);
}
}
export default List;
|
src/renderer/components/attributions.js | sirbrillig/gitnews-menubar | import React from 'react';
import BellIcon from '../components/bell-icon';
import MuteIcon from '../components/mute-icon';
export default function Attributions({ openUrl }) {
const openLink = event => {
event.preventDefault();
openUrl(event.target.href);
};
return (
<div className="attributions">
<h3>Attribution</h3>
<div className="attributions__text">
<BellIcon className="attributions__icon" />
Bell icon by
<a
onClick={openLink}
href="http://www.flaticon.com/authors/daniel-bruce"
title="Daniel Bruce"
>
Daniel Bruce
</a>
from
<a onClick={openLink} href="http://www.flaticon.com" title="Flaticon">
Flaticon
</a>
(
<a
onClick={openLink}
href="http://creativecommons.org/licenses/by/3.0/"
title="Creative Commons BY 3.0"
>
CC 3 BY
</a>
)
<p>
<MuteIcon className="attributions__icon" />
Mute icons by{' '}
<a
onClick={openLink}
href="https://www.flaticon.com/authors/freepik"
title="Freepik"
>
Freepik
</a>{' '}
from{' '}
<a onClick={openLink} href="http://www.flaticon.com" title="Flaticon">
Flaticon
</a>
(
<a
onClick={openLink}
href="http://creativecommons.org/licenses/by/3.0/"
title="Creative Commons BY 3.0"
>
CC 3 BY
</a>
)
</p>
</div>
</div>
);
}
|
index.ios.js | monicasoni/react-native-calculator | // It's property of Monica Soni
import React, { Component } from 'react';
import {
AppRegistry,Button,
StyleSheet,TouchableHighlight,
Text,
View
} from 'react-native';
export default class Calculator extends Component {
constructor(props) {
super(props)
this.state = { show: '' };
this.v1 = 0;
this.operator = null;
this.reset = false;
}
//////Perform operations on Tapping
onTaping(value) {
const result = this.reset ? '' : this.state.show;
this.reset = false;
this.setState({ show: result+value });
}
calculate(operator) {
if (this.operator && !this.reset) {
let result = 0;
switch (this.operator) {
case '+': result = Number(this.v1) + Number(this.state.show); break;
case '-': result = Number(this.v1) - Number(this.state.show); break;
case '*': result = Number(this.v1) * Number(this.state.show); break;
case '/': result = Number(this.v1) / Number(this.state.show); break;
break;
}
this.operator = operator;
this.v1 = result;
this.reset = true;
this.setState({ show: ''+result });
} else {
this.operator = operator;
this.v1 = this.reset ? this.v1 : this.state.show;
this.reset = true;
}
}
enterTapped(enterVal) {
this.setState({value1: eval(''+this.state.value1+this.state.operatorValue+this.state.value2)});
}
//////To create button
renderButton(value){
const onPress = () => this.onTaping(value);
return this.renderElement(value, onPress);
}
//To create Cancel button
renderCancel (value){
const onPress = () => this.onPressingCancelBtn(value);
return this.renderElement(value, onPress, {backgroundColor: 'red'}, {color: 'white', fontSize: 30,});
}
//////To create operator
renderOperator(operator){
const onPress = () => this.calculate(operator);
return this.renderElement(operator, onPress, {backgroundColor: 'orange'}, {color: 'white', fontWeight: '400', fontSize: 35,});
}
renderElement(value, onPress, style = null, textStyle= null) {
return (
<TouchableHighlight
style={[styles.instructions, style]}
onPress={onPress}
activeOpacity= {0.5}
underlayColor= 'darkgray'
>
<Text style={[styles.welcome, textStyle]}>
{value}
</Text>
</TouchableHighlight>
)
}
onPressingCancelBtn(value){
this.setState({ show: 0 });
this.v1 = 0;
this.operator = 0;
}
render() {
return (
<View style={styles.container}>
<View style={{flex:1, backgroundColor:'black',justifyContent:'flex-end'}}>
<Text style = {{textAlign: 'right', fontSize:35, color: 'white'}}>{this.state.show}</Text>
</View>
<View style={{flex:2, justifyContent:'space-around',flexWrap:'wrap',backgroundColor: '#193441'}}>
<View style={styles.rows}>
{this.renderButton(7)}
{this.renderButton(8)}
{this.renderButton(9)}
{this.renderOperator('*')}
</View>
<View style={styles.rows}>
{this.renderButton(4)}
{this.renderButton(5)}
{this.renderButton(6)}
{this.renderOperator('-')}
</View>
<View style={styles.rows}>
{this.renderButton(1)}
{this.renderButton(2)}
{this.renderButton(3)}
{this.renderOperator('+')}
</View>
<View style={styles.rows}>
{!this.props.hideCButton && this.renderCancel('C')}
{this.renderButton(0)}
{this.renderButton('.')}
{this.renderOperator('=')}
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'black',
},
welcome: {
fontSize: 20,
textAlign: 'center',
color:'black',
fontWeight: '500'
},
instructions: {
flex:1,
justifyContent: 'center',
backgroundColor: 'rgba(224,224,224,1)',
borderWidth: 0.5,
borderColor: 'black'
},
rows: {
flex:1,
flexDirection:'row',
justifyContent:'space-around',
flexWrap:'wrap'
},
});
class TestCalc extends Component {
render() {
return (
<View style={{flex: 1, shadowColor: 'gray', shadowOpacity: 2}}>
<View style={{flex: 1, paddingHorizontal: 0, paddingVertical: 0}} >
<Calculator hideCButton={false} />
</View>
</View>
);
}
}
AppRegistry.registerComponent('Calculator', () => TestCalc);
|
node_modules/react-router/es/IndexRoute.js | AdamB59/Klient | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { createRouteFromReactElement as _createRouteFromReactElement } from './RouteUtils';
import { component, components, falsy } from './InternalPropTypes';
var func = React.PropTypes.func;
/**
* An <IndexRoute> is used to specify its parent's <Route indexRoute> in
* a JSX route config.
*/
/* eslint-disable react/require-render-return */
var IndexRoute = React.createClass({
displayName: 'IndexRoute',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = _createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRoute> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
path: falsy,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRoute> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRoute; |
app/components/auth/Register.js | JoaoCnh/picto-pc | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Auth.css';
import AuthError from './AuthError';
import Button from '../common/Button';
import AuthAPI from '../../api/auth';
import strUtils from '../../utils/str';
export default class Register extends Component {
_handleRegisterAttempt(event) {
event.preventDefault();
let invalidUsername = strUtils.isEmptyOrWhitespace(this.props.register.registerUsername);
let invalidPassword = strUtils.isEmptyOrWhitespace(this.props.register.registerPassword);
let invalidConfirmation
= strUtils.isEmptyOrWhitespace(this.props.register.registerPasswordConfirmation);
if (invalidUsername || invalidPassword || invalidConfirmation) {
return this.props.registerError("Please fill all the form fields");
}
if (this.props.register.registerPassword !== this.props.register.registerPasswordConfirmation) {
return this.props.registerError("The Passwords don't match!", true);
}
this.props.attemptRegister();
AuthAPI.tryRegister(this.props.register.registerUsername, this.props.register.registerPassword)
.then((res) => {
if (res.error) {
return this.props.registerError(res.message);
}
this.props.registerSuccess();
setTimeout(() => {
this.props.push("/auth/login");
}, 1500);
})
.catch((err) => {
this.props.registerError(err.message);
});
}
_handleUsernameChange(event) {
this.props.usernameChanged(event.target.value);
}
_handlePasswordChange(event) {
this.props.passwordChanged(event.target.value);
}
_handlePasswordConfirmationChange(event) {
this.props.passwordConfirmationChanged(event.target.value);
}
render() {
let error = this.props.register.registerError ?
<AuthError errorMessage={this.props.register.registerErrorMessage} /> : <div />;
let btnTxt = this.props.register.isAttemptingRegister ? "Please wait..." : "Register";
let registeringIcon = this.props.register.isAttemptingRegister ? "circle-o-notch fa-spin fa-fw" : null;
let formClassName = this.props.register.registerSuccess ? styles.fadeOut : "";
let titleClassName = this.props.register.registerSuccess ? styles.slideDown : "";
return (
<div className={styles.authContainer}>
<h1 className={titleClassName}>
{this.props.register.title}
</h1>
{error}
<form className={formClassName}>
<input type="text" placeholder="Username / Email"
value={this.props.register.registerUsername}
onChange={this._handleUsernameChange.bind(this)} />
<input type="password" placeholder="Password"
value={this.props.register.registerPassword}
onChange={this._handlePasswordChange.bind(this)} />
<input type="password" placeholder="Password Confirmation"
value={this.props.register.registerPasswordConfirmation}
onChange={this._handlePasswordConfirmationChange.bind(this)} />
<Button disabled={this.props.register.isAttemptingRegister}
callback={this._handleRegisterAttempt.bind(this)}
icon={registeringIcon} text={btnTxt} />
<div className={styles.authExtraLink}>
{'Already have an account? '}
<Link to="/auth/login">
{'Login here '}
<i className="fa fa-arrow-right"></i>
</Link>
</div>
</form>
</div>
);
}
}
|
src/svg-icons/device/battery-30.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBattery30 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V15h10V5.33z"/><path d="M7 15v5.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V15H7z"/>
</SvgIcon>
);
DeviceBattery30 = pure(DeviceBattery30);
DeviceBattery30.displayName = 'DeviceBattery30';
DeviceBattery30.muiName = 'SvgIcon';
export default DeviceBattery30;
|
src/svg-icons/content/redo.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentRedo = (props) => (
<SvgIcon {...props}>
<path d="M18.4 10.6C16.55 8.99 14.15 8 11.5 8c-4.65 0-8.58 3.03-9.96 7.22L3.9 16c1.05-3.19 4.05-5.5 7.6-5.5 1.95 0 3.73.72 5.12 1.88L13 16h9V7l-3.6 3.6z"/>
</SvgIcon>
);
ContentRedo = pure(ContentRedo);
ContentRedo.displayName = 'ContentRedo';
ContentRedo.muiName = 'SvgIcon';
export default ContentRedo;
|
stories/ReadOnly/index.js | jpuri/react-draft-wysiwyg | /* @flow */
import React from 'react';
import { Editor } from '../../src';
const Basic = () =>
(<div className="rdw-storybook-root">
<h3>ReadOnly editor</h3>
<Editor
readOnly
toolbarClassName="rdw-storybook--toolbar"
wrapperClassName="rdw-storybook-wrapper"
editorClassName="rdw-storybook-editor"
/>
</div>);
export default Basic;
|
Realization/frontend/czechidm-core/src/content/role/RoleIdentities.js | bcvsolutions/CzechIdMng | import React from 'react';
import Helmet from 'react-helmet';
import _ from 'lodash';
//
import * as Basic from '../../components/basic';
import { IdentityManager } from '../../redux';
import SearchParameters from '../../domain/SearchParameters';
import IdentityTableComponent, { IdentityTable } from '../identity/IdentityTable';
/**
* Identities with assigned role
*
* @author Radek Tomiška
*/
export default class RoleIdentities extends Basic.AbstractContent {
constructor(props, context) {
super(props, context);
this.identityManager = new IdentityManager();
}
getManager() {
return this.identityManager;
}
getContentKey() {
return 'content.role.identities';
}
getNavigationKey() {
return this.getRequestNavigationKey('role-identities', this.props.match.params);
}
render() {
const forceSearchParameters = new SearchParameters().setFilter('role', this.props.match.params.entityId);
const columns = _.difference(IdentityTable.defaultProps.columns, ['username']);
columns.unshift('entityInfo');
//
return (
<div>
<Helmet title={ this.i18n('title') } />
<Basic.ContentHeader icon="fa:group" text={ this.i18n('header') } style={{ marginBottom: 0 }}/>
<IdentityTableComponent
uiKey="role-identities-table"
identityManager={ this.getManager() }
prohibitedActions={[ 'identity-delete-bulk-action', 'identity-add-role-bulk-action' ]}
filterOpened={ false }
forceSearchParameters={ forceSearchParameters }
showAddButton={ false }
showRowSelection
columns={ columns }
className="no-margin"/>
</div>
);
}
}
|
client/app/components/auth/Login.js | joelseq/SourceGrade | import React from 'react';
import PropTypes from 'prop-types';
import { Field, reduxForm } from 'redux-form';
import {
Button,
Grid,
Row,
Col,
Alert,
} from 'react-bootstrap';
import { userLogin } from '../../modules/auth';
import { history } from '../../store';
import UsernameInput from './UsernameInput';
import PasswordInput from './PasswordInput';
class Login extends React.Component {
static propTypes = {
/**
* Prop passed from Redux Form to help with form submit
* @type {function}
*/
handleSubmit: PropTypes.func,
/**
* Redux Form string for form submission related errors
* @type {string}
*/
error: PropTypes.string,
/**
* Whether form is in invalid (has validation errors)
* @type {boolean}
*/
invalid: PropTypes.bool,
/**
* Whether form is submitting
* @type {boolean}
*/
submitting: PropTypes.bool,
}
static defaultProps = {
handleSubmit() {},
error: null,
invalid: true,
submitting: false,
}
componentWillMount() {
if (localStorage.getItem('token')) {
history.replace('/');
}
}
render() {
const {
handleSubmit,
error,
submitting,
invalid,
} = this.props;
const disableButton = submitting || invalid;
return (
<Grid>
<Row>
<Col lg={6} lgOffset={3} md={8} mdOffset={2}>
<h2>Login to an existing account</h2>
<form onSubmit={handleSubmit}>
<Field name="username" component={UsernameInput} />
<Field name="password" component={PasswordInput} />
<Button disabled={disableButton} type="submit">Submit</Button>
{error && <Alert bsStyle="danger" style={{ marginTop: '20px' }}>{error}</Alert>}
</form>
</Col>
</Row>
</Grid>
);
}
}
const validate = ({ username, password }) => {
const errors = {};
if (!username) {
errors.username = 'Username cannot be empty';
}
if (!password) {
errors.password = 'Password cannot be empty';
}
return errors;
};
export default reduxForm({
form: 'login',
validate,
onSubmit: (values, dispatch) => {
return dispatch(userLogin(values));
},
})(Login);
|
examples/huge-apps/app.js | maksad/react-router | import React from 'react';
import { Router } from 'react-router';
import stubbedCourses from './stubs/COURSES';
var rootRoute = {
component: 'div',
childRoutes: [{
path: '/',
component: require('./components/App'),
childRoutes: [
require('./routes/Calendar'),
require('./routes/Course'),
require('./routes/Grades'),
require('./routes/Messages'),
require('./routes/Profile'),
]
}]
};
React.render(
<Router routes={rootRoute} />,
document.getElementById('example')
);
// I've unrolled the recursive directory loop that is happening above to get a
// better idea of just what this huge-apps Router looks like
//
// import { Route } from 'react-router'
// import App from './components/App';
// import Course from './routes/Course/components/Course';
// import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar';
// import Announcements from './routes/Course/routes/Announcements/components/Announcements';
// import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement';
// import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar';
// import Assignments from './routes/Course/routes/Assignments/components/Assignments';
// import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment';
// import CourseGrades from './routes/Course/routes/Grades/components/Grades';
// import Calendar from './routes/Calendar/components/Calendar';
// import Grades from './routes/Grades/components/Grades';
// import Messages from './routes/Messages/components/Messages';
// React.render(
// <Router>
// <Route path="/" component={App}>
// <Route path="calendar" component={Calendar} />
// <Route path="course/:courseId" component={Course}>
// <Route path="announcements" components={{
// sidebar: AnnouncementsSidebar,
// main: Announcements
// }}>
// <Route path=":announcementId" component={Announcement} />
// </Route>
// <Route path="assignments" components={{
// sidebar: AssignmentsSidebar,
// main: Assignments
// }}>
// <Route path=":assignmentId" component={Assignment} />
// </Route>
// <Route path="grades" component={CourseGrades} />
// </Route>
// <Route path="grades" component={Grades} />
// <Route path="messages" component={Messages} />
// <Route path="profile" component={Calendar} />
// </Route>
// </Router>,
// document.getElementById('example')
// );
|
src/containers/NotFoundPage/index.js | sebacorrea33/todoinstitutos | import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Oops! Error 404!</h1>
<p>Esa página no existe!</p>
</div>
);
}
|
admin/src/component/Icon.js | zentrope/webl | //
// Copyright (c) 2017 Keith Irwin
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published
// by the Free Software Foundation, either version 3 of the License,
// or (at your option) any later version.
//
// 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React from 'react'
import { Map } from 'immutable'
import './Icon.css'
const icon = name => (color) => {
return (
<i className={"fa " + name + " Icon-" + color + " fa-fw"} aria-hidden="true"></i>
)
}
const icons = Map({
"new-post": icon("fa-plus"),
"edit-site": icon("fa-cog"),
"list-posts": icon("fa-file-text-o"),
"edit-account": icon("fa-user-circle"),
"change-password": icon("fa-lock"),
"list-activity": icon("fa-area-chart"),
"metrics": icon("fa-line-chart"),
delete: icon("fa-trash-o"),
draft: icon("fa-toggle-off"),
edit: icon("fa-pencil-square-o"),
published: icon("fa-toggle-on"),
question: icon("fa-question"),
visit: icon("fa-external-link"),
signout: icon("fa-sign-out")
})
class Icon extends React.PureComponent {
render() {
const { type, color } = this.props
const icon = icons.get(type, icons.get("question"))(color)
return ( icon )
}
}
export { Icon }
|
step6-serviceapi/node_modules/react-router/modules/RouteContext.js | jintoppy/react-training | import warning from './routerWarning'
import React from 'react'
const { object } = React.PropTypes
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
const RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext() {
return {
route: this.props.route
}
},
componentWillMount() {
warning(false, 'The `RouteContext` mixin is deprecated. You can provide `this.props.route` on context with your own `contextTypes`. http://tiny.cc/router-routecontextmixin')
}
}
export default RouteContext
|
client/src/components/Draftail/Tooltip/Tooltip.js | nealtodd/wagtail | import PropTypes from 'prop-types';
import React from 'react';
const TOP = 'top';
const LEFT = 'left';
const TOP_LEFT = 'top-left';
const getTooltipStyles = (target, direction) => {
const top = window.pageYOffset + target.top;
const left = window.pageXOffset + target.left;
switch (direction) {
case TOP:
return {
top: top + target.height,
left: left + target.width / 2,
};
case LEFT:
return {
top: top + target.height / 2,
left: left + target.width,
};
case TOP_LEFT:
default:
return {
top: top + target.height,
left: left,
};
}
};
/**
* A tooltip, with arbitrary content.
*/
const Tooltip = ({ target, children, direction }) => (
<div
style={getTooltipStyles(target, direction)}
className={`Tooltip Tooltip--${direction}`}
role="tooltip"
>
{children}
</div>
);
Tooltip.propTypes = {
target: PropTypes.shape({
top: PropTypes.number.isRequired,
left: PropTypes.number.isRequired,
width: PropTypes.number.isRequired,
height: PropTypes.number.isRequired,
}).isRequired,
direction: PropTypes.oneOf([TOP, LEFT, TOP_LEFT]).isRequired,
children: PropTypes.node.isRequired,
};
export default Tooltip;
|
client/src/components/dayBooking/slot.js | joejknowles/Open-Up | import React from 'react';
import '../../styles/DayBooking.css';
import { connect } from 'react-redux';
import { createSlotSelector } from '../../reducers';
import BookButton from './bookButton';
import format from 'date-fns/format';
const formatTime = (time) => (
format(time, 'HH:mm')
);
export const Slot = (props) => (
<div className="Slot">
{
props.booking ?
<UnavailableSlot { ...props } />
:
<BookButton { ...props } />
}
</div>
);
export const UnavailableSlot = ({ startTime, endTime, booking }) => {
const message = booking === "pending" ? '-' : `unavailable ${ formatTime(startTime) } to ${ formatTime(endTime) }`
return (
<div className="unavailableSlot slot-content">
<span className="message">
{ message }
</span>
</div>
);
}
const mapStateToProps = (state, { id }) => (
createSlotSelector(id)
);
export default connect(mapStateToProps)(Slot);
|
code/workspaces/web-app/src/components/common/buttons/SecondaryActionButton.js | NERC-CEH/datalab | import React from 'react';
import Button from '@material-ui/core/Button';
const SecondaryActionButton = ({ children, ...rest }) => (
<Button
{...rest}
variant="outlined"
color="secondary"
>
{children}
</Button>
);
export default SecondaryActionButton;
|
js/Header.js | aurimas-darguzis/react-intro | import React from 'react'
import { connect } from 'react-redux'
import { setSearchTerm } from './actionCreators'
import { Link } from 'react-router'
class Header extends React.Component {
constructor (props) {
super(props)
this.handleSearchTermChange = this.handleSearchTermChange.bind(this)
}
handleSearchTermChange (event) {
this.props.dispatch(setSearchTerm(event.target.value))
}
render () {
let utilSpace
if (this.props.showSearch) {
utilSpace = <input onChange={this.handleSearchTermChange} value={this.props.searchTerm} type='text' placeholder='Search' />
} else {
utilSpace = (
<h2>
<Link to='/search'>
Back
</Link>
</h2>
)
}
return (
<header>
<h1>
<Link to='/'>
svideo
</Link>
</h1>
{utilSpace}
</header>
)
}
}
const { func, bool, string } = React.PropTypes
Header.propTypes = {
dispatch: func,
showSearch: bool,
searchTerm: string
}
const mapStateToProps = (state) => {
return {
searchTerm: state.searchTerm
}
}
export default connect(mapStateToProps)(Header)
|
src/svg-icons/Cancel.js | AndriusBil/material-ui | // @flow
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../SvgIcon';
/**
* @ignore - internal component.
*/
let Cancel = props => (
<SvgIcon {...props}>
<path d="M12 2C6.47 2 2 6.47 2 12s4.47 10 10 10 10-4.47 10-10S17.53 2 12 2zm5 13.59L15.59 17 12 13.41 8.41 17 7 15.59 10.59 12 7 8.41 8.41 7 12 10.59 15.59 7 17 8.41 13.41 12 17 15.59z" />
</SvgIcon>
);
Cancel = pure(Cancel);
Cancel.muiName = 'SvgIcon';
export default Cancel;
|
app/javascript/mastodon/components/setting_text.js | ambition-vietnam/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
export default class SettingText extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
settingKey: PropTypes.array.isRequired,
label: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
};
handleChange = (e) => {
this.props.onChange(this.props.settingKey, e.target.value);
}
render () {
const { settings, settingKey, label } = this.props;
return (
<label>
<span style={{ display: 'none' }}>{label}</span>
<input
className='setting-text'
value={settings.getIn(settingKey)}
onChange={this.handleChange}
placeholder={label}
/>
</label>
);
}
}
|
app/components/Navbar.js | migueloop/1streaction | import React from 'react';
import {Link} from 'react-router';
import NavbarStore from '../stores/NavbarStore';
import NavbarActions from '../actions/NavbarActions';
import ShapesListActions from '../actions/ShapesListActions';
class Navbar extends React.Component {
constructor(props) {
super(props);
this.state = NavbarStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount() {
}
componentWillUnmount() {
}
onChange(state) {
this.setState(state);
}
render() {
return (
<nav className='navbar navbar-default navbar-static-top'>
<div className='navbar-header'>
<button type='button' className='navbar-toggle collapsed' data-toggle='collapse' data-target='#navbar'>
<span className='sr-only'>Toggle navigation</span>
<span className='icon-bar'></span>
<span className='icon-bar'></span>
<span className='icon-bar'></span>
</button>
</div>
<div id='navbar' className='navbar-collapse collapse'>
<ul className='nav navbar-nav'>
<li><Link to='/'>Home</Link></li>
<li><Link to='/stats'>Stats</Link></li>
<li className='dropdown'>
<a href='#' className='dropdown-toggle' data-toggle='dropdown'>Filter by <span className='caret'></span></a>
<ul className='dropdown-menu'>
<li><Link to='/filter/color' onClick={ShapesListActions.getFilteredShapes.bind(this, 'color')}>Color</Link></li>
<li><Link to='/filter/type' onClick={ShapesListActions.getFilteredShapes.bind(this, 'type')}>Type</Link></li>
</ul>
</li>
</ul>
</div>
</nav>
);
}
}
export default Navbar;
|
client/src/components/Footer.js | commandzpdx/habit-calendar | import React from 'react';
export default function Footer() {
return (
<footer>
<p>@habitcalendar2017</p>
</footer>
);
}
|
docs/app/Examples/modules/Progress/States/index.js | koenvg/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import { Message } from 'semantic-ui-react'
const ProgressStatesExamples = () => (
<ExampleSection title='States'>
<Message info>
Semantic UI states <code>success</code>, <code>warning</code>, and <code>error</code>
{' '}are only retained at 100% completion.
</Message>
<ComponentExample
title='Active'
description='A progress bar can show activity.'
examplePath='modules/Progress/States/ProgressExampleActive'
/>
<ComponentExample
title='Success'
description='A progress bar can show a success state.'
examplePath='modules/Progress/States/ProgressExampleSuccess'
/>
<ComponentExample
title='Warning'
description='A progress bar can show a warning state.'
examplePath='modules/Progress/States/ProgressExampleWarning'
/>
<ComponentExample
title='Error'
description='A progress bar can show an error state.'
examplePath='modules/Progress/States/ProgressExampleError'
/>
<ComponentExample
title='Disabled'
description='A progress bar can be disabled.'
examplePath='modules/Progress/States/ProgressExampleDisabled'
/>
</ExampleSection>
)
export default ProgressStatesExamples
|
src/svg-icons/communication/contacts.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationContacts = (props) => (
<SvgIcon {...props}>
<path d="M20 0H4v2h16V0zM4 24h16v-2H4v2zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 2.75c1.24 0 2.25 1.01 2.25 2.25s-1.01 2.25-2.25 2.25S9.75 10.24 9.75 9 10.76 6.75 12 6.75zM17 17H7v-1.5c0-1.67 3.33-2.5 5-2.5s5 .83 5 2.5V17z"/>
</SvgIcon>
);
CommunicationContacts = pure(CommunicationContacts);
CommunicationContacts.displayName = 'CommunicationContacts';
CommunicationContacts.muiName = 'SvgIcon';
export default CommunicationContacts;
|
src/containers/searchOverlay.js | joakikr/SAAS | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { clearSearch } from '../actions/index';
import { Jumbotron, Button, Glyphicon, Modal, ModalHeader, ModalBody, Row, Col } from 'react-bootstrap';
import SearchBar from '../containers/searchContainer';
import SearchList from '../containers/searchList';
class SearchOverlay extends Component {
constructor (props) {
super(props);
// Overlay should not be shown at start
this.state = {
showModal: false
};
this.handleOpenModal = this.handleOpenModal.bind(this);
this.handleCloseModal = this.handleCloseModal.bind(this);
}
handleOpenModal () {
this.setState({ showModal: true });
}
handleCloseModal () {
this.setState({ showModal: false });
// Clear search field when closing modal
this.props.clearSearch();
}
render() {
const { albums } = this.props;
const noAlbums = !albums || albums.length == 0;
const noAlbumsJSX = (
<div className="vertical-center">
<Jumbotron>
<Row>
<Col xs={12} >
<h1>OBS!</h1>
</Col>
<Col xs={12} >
<p>Det ser ikke ut til at du har lagt inn noen <i>album</i> enda.</p>
</Col>
<Col xs={12} >
<Button bsStyle="primary" bsSize="large" onClick={this.handleOpenModal} >
Utforsk
<Glyphicon glyph="search" />
</Button>
</Col>
</Row>
</Jumbotron>
</div>
);
const someAlbumsJSX = (
<div className="search-overlay-container">
<Button bsSize="large" bsStyle="default" onClick={this.handleOpenModal}>
<Glyphicon glyph="search" /> Finn Album
</Button>
<hr/>
<Modal
show={this.state.showModal}
onHide={this.handleCloseModal}
contentLabel="Search for album photos and add them to your album view.">
<ModalHeader>
<SearchBar/>
</ModalHeader>
<ModalBody>
<SearchList/>
</ModalBody>
</Modal>
</div>
);
if(noAlbums && !this.state.showModal) {
return noAlbumsJSX;
} else {
return someAlbumsJSX;
}
}
}
function mapStateToProps({ albums, search }) {
return { albums, search };
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ clearSearch }, dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchOverlay); |
src/components/fieldset-component.js | davidkpiano/redux-simple-form | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import getModel from '../utils/get-model';
import omit from '../utils/omit';
import resolveModel from '../utils/resolve-model';
const propTypes = {
model: PropTypes.string.isRequired,
component: PropTypes.any,
dispatch: PropTypes.func,
store: PropTypes.shape({
subscribe: PropTypes.func,
dispatch: PropTypes.func,
getState: PropTypes.func,
}),
storeSubscription: PropTypes.any,
};
class Fieldset extends Component {
getChildContext() {
return { model: this.props.model };
}
render() {
const { component } = this.props;
const allowedProps = omit(this.props, Object.keys(propTypes));
return React.createElement(
component,
allowedProps);
}
}
Fieldset.displayName = 'Fieldset';
Fieldset.childContextTypes = {
model: PropTypes.any,
};
Fieldset.propTypes = propTypes;
Fieldset.defaultProps = {
component: 'div',
};
function mapStateToProps(state, { model }) {
const modelString = getModel(model, state);
return {
model: modelString,
};
}
export default resolveModel(connect(mapStateToProps)(Fieldset));
|
app/javascript/mastodon/components/modal_root.js | gol-cha/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import 'wicg-inert';
import { createBrowserHistory } from 'history';
import { multiply } from 'color-blend';
export default class ModalRoot extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
children: PropTypes.node,
onClose: PropTypes.func.isRequired,
backgroundColor: PropTypes.shape({
r: PropTypes.number,
g: PropTypes.number,
b: PropTypes.number,
}),
ignoreFocus: PropTypes.bool,
};
activeElement = this.props.children ? document.activeElement : null;
handleKeyUp = (e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!this.props.children) {
this.props.onClose();
}
}
handleKeyDown = (e) => {
if (e.key === 'Tab') {
const focusable = Array.from(this.node.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((x) => window.getComputedStyle(x).display !== 'none');
const index = focusable.indexOf(e.target);
let element;
if (e.shiftKey) {
element = focusable[index - 1] || focusable[focusable.length - 1];
} else {
element = focusable[index + 1] || focusable[0];
}
if (element) {
element.focus();
e.stopPropagation();
e.preventDefault();
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
window.addEventListener('keydown', this.handleKeyDown, false);
this.history = this.context.router ? this.context.router.history : createBrowserHistory();
}
componentWillReceiveProps (nextProps) {
if (!!nextProps.children && !this.props.children) {
this.activeElement = document.activeElement;
this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
}
}
componentDidUpdate (prevProps) {
if (!this.props.children && !!prevProps.children) {
this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
// Because of the wicg-inert polyfill, the activeElement may not be
// immediately selectable, we have to wait for observers to run, as
// described in https://github.com/WICG/inert#performance-and-gotchas
Promise.resolve().then(() => {
if (!this.props.ignoreFocus) {
this.activeElement.focus({ preventScroll: true });
}
this.activeElement = null;
}).catch(console.error);
this._handleModalClose();
}
if (this.props.children && !prevProps.children) {
this._handleModalOpen();
}
if (this.props.children) {
this._ensureHistoryBuffer();
}
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
window.removeEventListener('keydown', this.handleKeyDown);
}
_handleModalOpen () {
this._modalHistoryKey = Date.now();
this.unlistenHistory = this.history.listen((_, action) => {
if (action === 'POP') {
this.props.onClose();
}
});
}
_handleModalClose () {
if (this.unlistenHistory) {
this.unlistenHistory();
}
const { state } = this.history.location;
if (state && state.mastodonModalKey === this._modalHistoryKey) {
this.history.goBack();
}
}
_ensureHistoryBuffer () {
const { pathname, state } = this.history.location;
if (!state || state.mastodonModalKey !== this._modalHistoryKey) {
this.history.push(pathname, { ...state, mastodonModalKey: this._modalHistoryKey });
}
}
getSiblings = () => {
return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
}
setRef = ref => {
this.node = ref;
}
render () {
const { children, onClose } = this.props;
const visible = !!children;
if (!visible) {
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
);
}
let backgroundColor = null;
if (this.props.backgroundColor) {
backgroundColor = multiply({ ...this.props.backgroundColor, a: 1 }, { r: 0, g: 0, b: 0, a: 0.7 });
}
return (
<div className='modal-root' ref={this.setRef}>
<div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
<div role='presentation' className='modal-root__overlay' onClick={onClose} style={{ backgroundColor: backgroundColor ? `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, 0.7)` : null }} />
<div role='dialog' className='modal-root__container'>{children}</div>
</div>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.