path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/js/components/icons/base/Shift.js | odedre/grommet-final | /**
* @description Shift SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M12,0 L12,24 M2,12 L12,12 M22,12 L12,12 M6,8 L2,12 L6,16 M18,8 L22,12 L18,16"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-shift`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'shift');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M12,0 L12,24 M2,12 L12,12 M22,12 L12,12 M6,8 L2,12 L6,16 M18,8 L22,12 L18,16"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Shift';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
packages/showcase/plot/stacked-vertical-bar-chart.js | uber-common/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import ShowcaseButton from '../showcase-components/showcase-button';
import {
XYPlot,
XAxis,
YAxis,
VerticalGridLines,
HorizontalGridLines,
VerticalBarSeries,
VerticalBarSeriesCanvas
} from 'react-vis';
export default class Example extends React.Component {
state = {
useCanvas: false
};
render() {
const {useCanvas} = this.state;
const BarSeries = useCanvas ? VerticalBarSeriesCanvas : VerticalBarSeries;
const content = useCanvas ? 'TOGGLE TO SVG' : 'TOGGLE TO CANVAS';
return (
<div>
<ShowcaseButton
onClick={() => this.setState({useCanvas: !useCanvas})}
buttonContent={content}
/>
<XYPlot width={300} height={300} stackBy="y">
<VerticalGridLines />
<HorizontalGridLines />
<XAxis />
<YAxis />
<BarSeries
data={[
{x: 2, y: 10},
{x: 4, y: 5},
{x: 5, y: 15}
]}
/>
<BarSeries
data={[
{x: 2, y: 12},
{x: 4, y: 2},
{x: 5, y: 11}
]}
/>
</XYPlot>
</div>
);
}
}
|
src/svg-icons/editor/format-indent-increase.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatIndentIncrease = (props) => (
<SvgIcon {...props}>
<path d="M3 21h18v-2H3v2zM3 8v8l4-4-4-4zm8 9h10v-2H11v2zM3 3v2h18V3H3zm8 6h10V7H11v2zm0 4h10v-2H11v2z"/>
</SvgIcon>
);
EditorFormatIndentIncrease = pure(EditorFormatIndentIncrease);
EditorFormatIndentIncrease.displayName = 'EditorFormatIndentIncrease';
EditorFormatIndentIncrease.muiName = 'SvgIcon';
export default EditorFormatIndentIncrease;
|
src/server/frontend/Html.js | skyuplam/debt_mgmt | // @flow
/* eslint-disable react/no-danger */
import React from 'react';
const GoogleAnalytics = ({ id }) => (
<script
dangerouslySetInnerHTML={{ __html: `
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');
ga('create', '${id}', 'auto'); ga('send', 'pageview');`,
}}
/>
);
GoogleAnalytics.propTypes = {
id: React.PropTypes.string.isRequired,
};
type Props = {
appCssFilename: string,
bodyCss: string,
bodyHtml: string,
googleAnalyticsId: string,
helmet: Object,
isProduction: boolean,
};
const Html = ({
appCssFilename,
bodyCss,
bodyHtml,
googleAnalyticsId,
helmet,
isProduction,
}: Props) => (
<html {...helmet.htmlAttributes.toComponent()}>
<head>
{helmet.title.toComponent()}
{helmet.base.toComponent()}
{helmet.meta.toComponent()}
{helmet.link.toComponent()}
{helmet.script.toComponent()}
{appCssFilename &&
<link href={appCssFilename} rel="stylesheet" />
}
{isProduction && googleAnalyticsId !== 'UA-XXXXXXX-X' &&
<GoogleAnalytics id={googleAnalyticsId} />
}
<style dangerouslySetInnerHTML={{ __html: bodyCss }} id="stylesheet" />
</head>
<body dangerouslySetInnerHTML={{ __html: bodyHtml }} />
</html>
);
export default Html;
|
src/components/Footer.js | mimccio/Mbtn-site | import React from 'react'
import styled from 'styled-components'
import { palette } from 'm-btn'
const Wrapper = styled.section`
margin-top: auto;
padding-top: 3rem;
`
const LoveIcon = styled.i`
color: ${palette.warning.main};
`
export default () => (
<Wrapper>
<div>
<p>
<a href='https://github.com/mimccio/Mbtn-site'>
<i className='fa fa-github' aria-hidden='true' /> view source
</a>
</p>
<p>
made by <a href='https://twitter.com/mimccio' target='_blank'>
@mimccio
</a> with <LoveIcon className='fa fa-heart' aria-hidden='true' /> and <a
href='https://styled-components.com/' target='_blank'
>styled-components
</a>
</p>
</div>
</Wrapper>
)
|
src/client.js | hokustalkshow/friend-landing-page | /**
* THIS IS THE ENTRY POINT FOR THE CLIENT, JUST LIKE server.js IS THE ENTRY POINT FOR THE SERVER.
*/
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import io from 'socket.io-client';
import {Provider} from 'react-redux';
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { ReduxAsyncConnect } from 'redux-async-connect';
import useScroll from 'scroll-behavior/lib/useStandardScroll';
import getRoutes from './routes';
const client = new ApiClient();
const _browserHistory = useScroll(() => browserHistory)();
const dest = document.getElementById('content');
const store = createStore(_browserHistory, client, window.__data);
const history = syncHistoryWithStore(_browserHistory, store);
function initSocket() {
const socket = io('', {path: '/ws'});
socket.on('news', (data) => {
console.log(data);
socket.emit('my other event', { my: 'data from client' });
});
socket.on('msg', (data) => {
console.log(data);
});
return socket;
}
global.socket = initSocket();
const component = (
<Router render={(props) =>
<ReduxAsyncConnect {...props} helpers={{client}} filter={item => !item.deferred} />
} history={history}>
{getRoutes(store)}
</Router>
);
ReactDOM.render(
<Provider store={store} key="provider">
{component}
</Provider>,
dest
);
if (process.env.NODE_ENV !== 'production') {
window.React = React; // enable debugger
if (!dest || !dest.firstChild || !dest.firstChild.attributes || !dest.firstChild.attributes['data-react-checksum']) {
console.error('Server-side React render was discarded. Make sure that your initial render does not contain any client-side code.');
}
}
if (__DEVTOOLS__ && !window.devToolsExtension) {
const DevTools = require('./containers/DevTools/DevTools');
ReactDOM.render(
<Provider store={store} key="provider">
<div>
{component}
<DevTools />
</div>
</Provider>,
dest
);
}
|
assets/javascripts/kitten/components/action/social-button-icon-words/index.js | KissKissBankBank/kitten | import React from 'react'
import { Button } from '../../action/button'
import { FacebookIcon } from '../../graphics/icons/facebook-icon'
import { TwitterIcon } from '../../graphics/icons/twitter-icon'
import { LinkedinIcon } from '../../graphics/icons/linkedin-icon'
import { InstagramIcon } from '../../graphics/icons/instagram-icon'
export const FacebookButtonIconWords = ({ children, ...props }) => (
<Button {...props}>
<FacebookIcon height="14" width="7" />
<span>{children}</span>
</Button>
)
export const TwitterButtonIconWords = ({ children, ...props }) => (
<Button {...props}>
<TwitterIcon height="12" width="15" />
<span>{children}</span>
</Button>
)
export const InstagramButtonIconWords = ({ children, ...props }) => (
<Button {...props}>
<InstagramIcon height="16" width="16" />
<span>{children}</span>
</Button>
)
export const LinkedinButtonIconWords = ({ children, ...props }) => (
<Button {...props}>
<LinkedinIcon height="12" width="12" />
<span>{children}</span>
</Button>
)
const defaultProps = {
modifier: 'beryllium',
}
FacebookButtonIconWords.defaultProps = defaultProps
TwitterButtonIconWords.defaultProps = defaultProps
LinkedinButtonIconWords.defaultProps = defaultProps
InstagramButtonIconWords.defaultProps = defaultProps
|
reflux-app/App.js | Orientsoft/conalog-front | import React from 'react'
import ReactDom from 'react-dom'
import Reflux from 'reflux'
import RefluxPromise from 'reflux-promise'
import Promise from 'bluebird'
Reflux.use(RefluxPromise(Promise))
import _ from 'lodash'
// import 'antd/dist/antd.css'
let message = require('antd/lib/message')
let Modal = require('antd/lib/modal')
const confirm = Modal.confirm
import AppActions from './actions/AppActions'
import AppStore from './stores/AppStore'
import Nav from './components/Common/Nav'
import Footer from './components/Common/Footer'
import Home from './components/Home'
import Cert from './components/Cert'
import Collector from './components/Collector'
import Flow from './components/Flow'
import Parser from './components/Parser'
import Status from './components/Status'
import History from './components/History'
import Admin from './components/Admin'
import Login from './components/Login'
import Peg from './components/Peg'
import Management from './components/Management'
class App extends React.Component {
constructor(props) {
super(props)
this.state = {
location: 'Login',
collectorType: 'Active',
activeCollectorChecklist: [],
activeCollectorDeleteModal: false,
statusType: 'Active'
}
}
componentDidMount() {
this.unsubscribe = AppStore.listen(function(state) {
this.setState(state)
}.bind(this))
}
componentWillUnmount() {
if (_.isFunction(this.unsubscribe))
this.unsubscribe()
}
render() {
let modalStyle = {
overlay: {
position: 'fixed',
top: 0,
left: 0,
right: 0,
bottom: 0,
backgroundColor: 'rgba(255, 255, 255, 0.75)'
},
content: {
position: 'absolute',
top: '40px',
left: '40px',
right: '40px',
bottom: '40px',
border: '1px solid #ccc',
background: '#fff',
overflow: 'auto',
WebkitOverflowScrolling: 'touch',
borderRadius: '4px',
outline: 'none',
padding: '20px'
}
}
let page
// console.log(this.state.location)
switch (this.state.location)
{
case 'Login':
page = <div><Login /></div>
break;
case 'Cert':
page = <div>
<Nav location={ this.state.location } />
<Cert />
<Footer />
</div>
break
case 'Collector':
page = <div>
<Nav location={ this.state.location } />
<Collector collectorType={ this.state.collectorType } />
<Footer />
</div>
break;
case 'Parser':
page = <div>
<Nav location={ this.state.location } />
<Parser />
<Footer />
</div>
break;
case 'Home':
page = <div>
<Nav location={ this.state.location } />
<Home />
<Footer />
</div>
break;
case 'Flow':
page = <div>
<Nav location={ this.state.location } />
<Flow />
<Footer />
</div>
break;
case 'Peg':
page = <div>
<Nav location={ this.state.location } />
<Peg />
<Footer />
</div>
break;
case 'History':
page = <div>
<Nav location={ this.state.location } />
<History />
<Footer />
</div>
break;
case 'Status':
page = <div>
<Nav location={ this.state.location } />
<Status statusType={ this.state.statusType } />
<Footer />
</div>
break;
case 'Management':
page = <div>
<Nav location= { this.state.location } />
<Management />
<Footer />
</div>
break;
default:
page = <div><Login /></div>
break;
}
return (
<div>
{ page }
</div>
)
}
}
App.propTypes = {
}
App.defaultProps = {
}
export default App
|
zwdemoRect/src/components/frm/addfrm.js | send2ocean/nodelearn | import React from 'react'
import { connect } from 'react-redux'
import { add_frm } from '../../redux/actions'
let ADD_FRM = ({ dispatch }) => {
let input
return (
<div>
<form onSubmit={e => {
e.preventDefault()
if (!input.value.trim()) {
return
}
dispatch(add_frm(input.value))
input.value = ''
}}>
<input ref={node => {
input = node
}} />
<button type="submit">
Add Todo
</button>
</form>
</div>
)
}
ADD_FRM = connect()(ADD_FRM)
export default ADD_FRM
|
Activities/WebApp/src/app/footer.js | swcraftlyon/meetup | import React, { Component } from 'react';
const styles = {
footer: {
padding: '0.5rem',
fontSize: '1rem',
backgroundColor: '#3adbdb',
textAlign: 'center'
}
}
export class Footer extends Component {
render() {
return (
<footer style={styles.footer}>
<a href="https://github.com/swcraftlyon/meetup" target="_blank">
github
</a>
|
<a href="https://lyontechhub.slack.com/messages/swcrafts_meetup" target="_blank">
slack
</a>
|
<a href="https://trello.com/b/zuo7PmoE/swcraftmeetup#" target="_blank">
trello
</a>
</footer>
);
}
}
|
sampleApps/react/src/main/webapp/app/app.js | willbuck/g3-2016-grails-gradle-node | import React from 'react';
import ReactDOM from 'react-dom';
import About from './about';
require('./../styles/style.css');
ReactDOM.render(<About />, document.getElementById('app')); |
react-flux/demo01/js/components/Inspector.react.js | majunbao/xue | import React from 'react';
class Inspector extends React.Component {
render() {
return(
<div className="app-inspector"> Inspector </div>
)
}
}
export default Inspector; |
packages/material-ui-icons/src/ThumbsUpDown.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let ThumbsUpDown = props =>
<SvgIcon {...props}>
<path d="M12 6c0-.55-.45-1-1-1H5.82l.66-3.18.02-.23c0-.31-.13-.59-.33-.8L5.38 0 .44 4.94C.17 5.21 0 5.59 0 6v6.5c0 .83.67 1.5 1.5 1.5h6.75c.62 0 1.15-.38 1.38-.91l2.26-5.29c.07-.17.11-.36.11-.55V6zm10.5 4h-6.75c-.62 0-1.15.38-1.38.91l-2.26 5.29c-.07.17-.11.36-.11.55V18c0 .55.45 1 1 1h5.18l-.66 3.18-.02.24c0 .31.13.59.33.8l.79.78 4.94-4.94c.27-.27.44-.65.44-1.06v-6.5c0-.83-.67-1.5-1.5-1.5z" />
</SvgIcon>;
ThumbsUpDown = pure(ThumbsUpDown);
ThumbsUpDown.muiName = 'SvgIcon';
export default ThumbsUpDown;
|
admin/client/App/shared/InvalidFieldType.js | matthewstyers/keystone | /**
* Renders an "Invalid Field Type" error
*/
import React from 'react';
const InvalidFieldType = function (props) {
return (
<div className="alert alert-danger">
Invalid field type <strong>{props.type}</strong> at path <strong>{props.path}</strong>
</div>
);
};
InvalidFieldType.propTypes = {
path: React.PropTypes.string,
type: React.PropTypes.string,
};
module.exports = InvalidFieldType;
|
app/src/containers/BasePage.js | cs-cordero/mtgls | import React from 'react';
import NavBar from '../components/NavBar';
import Footer from '../components/Footer';
import Router from '../components/Router';
export default class BasePage extends React.Component {
render() {
return (
<div className='hero is-fullheight'>
<div className='hero-head'>
<NavBar />
</div>
<div className='hero-body'>
<Router />
</div>
<div className='hero-foot container'>
<Footer />
</div>
</div>
);
}
}
|
src/main/resources/static/bower_components/jqwidgets/demos/react/app/grid/filtering/app.js | dhawal9035/WebPLP | import React from 'react';
import ReactDOM from 'react-dom';
import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
import JqxCheckBox from '../../../jqwidgets-react/react_jqxcheckbox.js';
import JqxPanel from '../../../jqwidgets-react/react_jqxpanel.js';
class App extends React.Component {
componentDidMount() {
this.refs.Grid.on("filter", (event) => {
this.refs.Panel.clearcontent();
let filterinfo = this.refs.Grid.getfilterinformation();
let eventData = "Triggered 'filter' event";
for (i = 0; i < filterinfo.length; i++) {
let eventData = "Filter Column: " + filterinfo[i].filtercolumntext;
this.refs.Panel.prepend('<div style="margin-top: 5px;">' + eventData + '</div>');
}
});
this.refs.Button.on('click', () => {
this.refs.Grid.clearfilters();
});
// show/hide filter background
this.refs.CheckBox1.on('change', (event) => {
this.refs.Grid.showfiltercolumnbackground(event.args.checked);
});
// show/hide filter icons
this.refs.CheckBox2.on('change', (event) => {
this.refs.Grid.autoshowfiltericon(!event.args.checked);
});
this.addFilter()
}
addFilter() {
let filtergroup = new $.jqx.filter();
let filter_or_operator = 1;
let filtervalue = 'Beate';
let filtercondition = 'contains';
let filter1 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);
filtervalue = 'Andrew';
filtercondition = 'starts_with';
let filter2 = filtergroup.createfilter('stringfilter', filtervalue, filtercondition);
filtergroup.addfilter(filter_or_operator, filter1);
filtergroup.addfilter(filter_or_operator, filter2);
// add the filters.
this.refs.Grid.addfilter('firstname', filtergroup);
// apply the filters.
this.refs.Grid.applyfilters();
}
render () {
let data = generatedata(500);
let source =
{
localdata: data,
datafields:
[
{ name: 'firstname', type: 'string' },
{ name: 'lastname', type: 'string' },
{ name: 'productname', type: 'string' },
{ name: 'date', type: 'date' },
{ name: 'quantity', type: 'number' },
{ name: 'price', type: 'number' }
],
datatype: "array"
};
let dataAdapter = new $.jqx.dataAdapter(source);
let columns =
[
{ text: 'First Name', datafield: 'firstname', width: 160 },
{ text: 'Last Name', datafield: 'lastname', width: 160 },
{ text: 'Product', datafield: 'productname', width: 170 },
{ text: 'Order Date', datafield: 'date', filtertype: 'date', width: 160, cellsformat: 'dd-MMMM-yyyy' },
{ text: 'Quantity', datafield: 'quantity', width: 80, cellsalign: 'right' },
{ text: 'Unit Price', datafield: 'price', cellsalign: 'right', cellsformat: 'c2' }
];
return (
<div id='jqxWidget' style={{ fontSize: 13, fontFamily: 'Verdana', float: 'left' }}>
<JqxGrid ref='Grid'
width={850} source={dataAdapter} filterable={true}
sortable={true} autoshowfiltericon={true} columns={columns}
/>
<div id="eventslog" style={{ marginTop: 30 }}>
<div style={{ width: 200, float: 'left', marginRight: 10 }}>
<JqxButton ref='Button' height={25} value='Remove Filter'/>
<JqxCheckBox ref='CheckBox1' checked={true} height={25} style={{ marginTop: 10 }} value='Filter Background'/>
<JqxCheckBox ref='CheckBox2' checked={false} height={25} style={{ marginTop: 10 }} value='Show All Filter Icons'/>
</div>
<div style={{ float: 'left' }}>
Event Log:
<JqxPanel ref='Panel' width={300} height={80} style={{ border: 'none' }}/>
</div>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/templates/seo.js | ianmcgregor/mcgregor.codes | import React from 'react';
import Helmet from 'react-helmet';
export default ({
siteMetadata,
settings,
page
}) => {
const siteURL = siteMetadata.url;
const title = page.title && page.slug ? `${settings.title} / ${page.title.toUpperCase()}` : settings.title;
const description = page.description || settings.description;
const image = `https:${(page.image && page.image.file.url) || settings.image.file.url}`;
const favicon = settings.favicon.file.url;
return (
<Helmet title={title}>
<html lang="en" />
<meta name="description" content={description} />
<meta name="image" content={image} />
<meta property="og:url" content={siteURL} />
<meta property="og:title" content={title} />
<meta property="og:description" content={description} />
<meta property="og:image" content={image} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:creator" content={settings.twitterHandle}/>
<meta name="twitter:title" content={title} />
<meta name="twitter:description" content={description} />
<meta name="twitter:image" content={image} />
<link rel="sitemap" type="application/xml" href="/sitemap.xml"/>
<link rel="apple-touch-icon" sizes="180x180" href={`${favicon}?w=180`}/>
<link rel="icon" type="image/png" sizes="192x192" href={`${favicon}?w=192`}/>
<link rel="icon" type="image/png" sizes="32x32" href={`${favicon}?w=32`}/>
</Helmet>
);
};
|
client/containers/NotFound.js | ashoka-ireland/ashoka-ui | import React from 'react';
import { Link } from 'react-router';
import { Card } from 'antd';
import { Footer } from 'components';
const NotFound = () => {
return (
<div class="app">
<main class="container">
<Card>
<h2>404 Page Not Found</h2>
<p><Link to="/"> Go back to homepage </Link></p>
</Card>
</main>
<Footer />
</div>
);
};
export default NotFound;
|
src/components/CampaignTimeAndSalary/NotFound.js | goodjoblife/GoodJobShare | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import CommonNotFound from 'common/NotFound';
import Redirect from 'common/routing/Redirect';
import { queryCampaignInfoList } from '../../actions/campaignInfo';
import { isFetched } from '../../constants/status';
class NotFound extends Component {
static fetchData({ store: { dispatch } }) {
return dispatch(queryCampaignInfoList());
}
componentDidMount() {
this.props.queryCampaignInfoList();
}
render() {
const { campaignName, campaignEntries, campaignEntriesStatus } = this.props;
if (
isFetched(campaignEntriesStatus) &&
!campaignEntries.has(campaignName)
) {
return <CommonNotFound />;
}
return (
<Redirect
to={'/time-and-salary/campaigns/:campaign_name/latest'.replace(
':campaign_name',
campaignName,
)}
/>
);
}
}
NotFound.propTypes = {
campaignName: PropTypes.string.isRequired,
campaignEntries: ImmutablePropTypes.map.isRequired,
campaignEntriesStatus: PropTypes.string.isRequired,
queryCampaignInfoList: PropTypes.func.isRequired,
};
export default NotFound;
|
node_modules/react-bootstrap/es/FormGroup.js | cmccandless/SolRFrontEnd | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, bsSizes, getClassSet, splitBsPropsAndOmit } from './utils/bootstrapUtils';
import { Size } from './utils/StyleConfig';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = {
/**
* Sets `id` on `<FormControl>` and `htmlFor` on `<FormGroup.Label>`.
*/
controlId: React.PropTypes.string,
validationState: React.PropTypes.oneOf(['success', 'warning', 'error'])
};
var childContextTypes = {
$bs_formGroup: React.PropTypes.object.isRequired
};
var FormGroup = function (_React$Component) {
_inherits(FormGroup, _React$Component);
function FormGroup() {
_classCallCheck(this, FormGroup);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
FormGroup.prototype.getChildContext = function getChildContext() {
var _props = this.props,
controlId = _props.controlId,
validationState = _props.validationState;
return {
$bs_formGroup: {
controlId: controlId,
validationState: validationState
}
};
};
FormGroup.prototype.hasFeedback = function hasFeedback(children) {
var _this2 = this;
return ValidComponentChildren.some(children, function (child) {
return child.props.bsRole === 'feedback' || child.props.children && _this2.hasFeedback(child.props.children);
});
};
FormGroup.prototype.render = function render() {
var _props2 = this.props,
validationState = _props2.validationState,
className = _props2.className,
children = _props2.children,
props = _objectWithoutProperties(_props2, ['validationState', 'className', 'children']);
var _splitBsPropsAndOmit = splitBsPropsAndOmit(props, ['controlId']),
bsProps = _splitBsPropsAndOmit[0],
elementProps = _splitBsPropsAndOmit[1];
var classes = _extends({}, getClassSet(bsProps), {
'has-feedback': this.hasFeedback(children)
});
if (validationState) {
classes['has-' + validationState] = true;
}
return React.createElement(
'div',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
children
);
};
return FormGroup;
}(React.Component);
FormGroup.propTypes = propTypes;
FormGroup.childContextTypes = childContextTypes;
export default bsClass('form-group', bsSizes([Size.LARGE, Size.SMALL], FormGroup)); |
src/Router.js | aalluri-navaratan/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import Router from 'react-routing/src/Router';
import http from './core/HttpClient';
import App from './components/App';
import ContentPage from './components/ContentPage';
import ContactPage from './components/ContactPage';
import LoginPage from './components/LoginPage';
import RegisterPage from './components/RegisterPage';
import NotFoundPage from './components/NotFoundPage';
import ErrorPage from './components/ErrorPage';
const router = new Router(on => {
on('*', async (state, next) => {
const component = await next();
return component && <App context={state.context}>{component}</App>;
});
on('/contact', async () => <ContactPage />);
on('/login', async () => <LoginPage />);
on('/register', async () => <RegisterPage />);
on('*', async (state) => {
const content = await http.get(`/api/content?path=${state.path}`);
return content && <ContentPage {...content} />;
});
on('error', (state, error) => state.statusCode === 404 ?
<App context={state.context} error={error}><NotFoundPage /></App> :
<App context={state.context} error={error}><ErrorPage /></App>
);
});
export default router;
|
fields/types/money/MoneyField.js | belafontestudio/keystone | import Field from '../Field';
import React from 'react';
import { FormInput } from 'elemental';
module.exports = Field.create({
displayName: 'MoneyField',
valueChanged (event) {
var newValue = event.target.value.replace(/[^\d\s\,\.\$€£¥]/g, '');
if (newValue === this.props.value) return;
this.props.onChange({
path: this.props.path,
value: newValue
});
},
renderField () {
return <FormInput name={this.props.path} ref="focusTarget" value={this.props.value} onChange={this.valueChanged} autoComplete="off" />;
}
});
|
src/index.js | williamliew/brokerApp | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import { Router, Route, Link, browserHistory } from 'react-router';
const Home = React.createClass({
render() {
return (<h3>Message</h3>);
}
});
const What = React.createClass({
render() {
return (<h3>Test</h3>);
}
});
ReactDOM.render((
<Router history={browserHistory}>
<Route path="/" component={App}>
</Route>
</Router>
), document.getElementById('content'));
|
src/svg-icons/hardware/desktop-mac.js | rscnt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDesktopMac = (props) => (
<SvgIcon {...props}>
<path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7l-2 3v1h8v-1l-2-3h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 12H3V4h18v10z"/>
</SvgIcon>
);
HardwareDesktopMac = pure(HardwareDesktopMac);
HardwareDesktopMac.displayName = 'HardwareDesktopMac';
export default HardwareDesktopMac;
|
src/components/PostPage.js | michaelnyu/michaelnyu.github.io | import React from 'react';
import ReactMarkdown from 'react-markdown';
import { GRID_UNIT, VIEW_STYLES } from '~/src/shared/styles';
import { headingStyles, pStyles, FONT_WEIGHT } from '~/src/shared/typography';
const styles = {
body: {
'> h1': headingStyles({
marginBottom: GRID_UNIT * 8,
fontWeight: FONT_WEIGHT.BOLD,
}),
'> p': pStyles({
'> img': {
...VIEW_STYLES,
},
}),
'> pre': {
whiteSpace: 'pre-wrap',
wordBreak: 'break-word',
'> code': {
backgroundColor: '#E8E8E8',
borderRadius: 2,
padding: '0 4px 0 4px',
fontSize: 16,
},
},
},
};
const PagePost = ({ title, summary, ...otherProps }) => (
<div css={styles.body}>
<ReactMarkdown css={styles.body} {...otherProps} />
</div>
);
export default PagePost;
|
example/src/TreeChartDemo.js | rsamec/react-pathjs-chart | import React from 'react';
import {Tree} from 'react-pathjs-chart';
import genie from 'genie'
import ChartDemo from './ChartDemo.js';
export class TreeDemo {
get dataTemplate() {
var leafTemplate = {
min: 1,
max: 5,
template: {
name: {
pattern: 'lastName'
}
}
};
return {
name: {
format: 'Root'
},
children: {
min: 3,
max: 6,
template: {
name: {pattern: 'brState'},
children: leafTemplate
}
}
}
}
get options() {
return {
margin: {top: 20, left: 50, right: 80, bottom: 20},
width:600,
height:600,
fill: "#2980B9",
stroke: "#3E90F0",
r:5,
animate:{
type:'oneByOne',
duration:200,
fillTransition:3
},
label:{
fontFamily:'Arial',
fontSize:14,
fontWeight:true,
fill:'#34495E'
}
}
}
get props(){
return {}
}
generateData(dataTemplate){
return genie(dataTemplate);
}
}
export default class TreeChartDemo extends ChartDemo {
constructor(props) {
super(props, Tree, new TreeDemo());
}
}; |
app/javascript/mastodon/features/getting_started/index.js | kazh98/social.arnip.org | import React from 'react';
import Column from '../ui/components/column';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { me, profile_directory, showTrends } from '../../initial_state';
import { fetchFollowRequests } from 'mastodon/actions/accounts';
import { List as ImmutableList } from 'immutable';
import NavigationBar from '../compose/components/navigation_bar';
import Icon from 'mastodon/components/icon';
import LinkFooter from 'mastodon/features/ui/components/link_footer';
import TrendsContainer from './containers/trends_container';
const messages = defineMessages({
home_timeline: { id: 'tabs_bar.home', defaultMessage: 'Home' },
notifications: { id: 'tabs_bar.notifications', defaultMessage: 'Notifications' },
public_timeline: { id: 'navigation_bar.public_timeline', defaultMessage: 'Federated timeline' },
settings_subheading: { id: 'column_subheading.settings', defaultMessage: 'Settings' },
community_timeline: { id: 'navigation_bar.community_timeline', defaultMessage: 'Local timeline' },
direct: { id: 'navigation_bar.direct', defaultMessage: 'Direct messages' },
bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' },
preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' },
mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned toots' },
lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
discover: { id: 'navigation_bar.discover', defaultMessage: 'Discover' },
personal: { id: 'navigation_bar.personal', defaultMessage: 'Personal' },
security: { id: 'navigation_bar.security', defaultMessage: 'Security' },
menu: { id: 'getting_started.heading', defaultMessage: 'Getting started' },
profile_directory: { id: 'getting_started.directory', defaultMessage: 'Profile directory' },
});
const mapStateToProps = state => ({
myAccount: state.getIn(['accounts', me]),
unreadFollowRequests: state.getIn(['user_lists', 'follow_requests', 'items'], ImmutableList()).size,
});
const mapDispatchToProps = dispatch => ({
fetchFollowRequests: () => dispatch(fetchFollowRequests()),
});
const badgeDisplay = (number, limit) => {
if (number === 0) {
return undefined;
} else if (limit && number >= limit) {
return `${limit}+`;
} else {
return number;
}
};
const NAVIGATION_PANEL_BREAKPOINT = 600 + (285 * 2) + (10 * 2);
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class GettingStarted extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
myAccount: ImmutablePropTypes.map.isRequired,
columns: ImmutablePropTypes.list,
multiColumn: PropTypes.bool,
fetchFollowRequests: PropTypes.func.isRequired,
unreadFollowRequests: PropTypes.number,
unreadNotifications: PropTypes.number,
};
componentDidMount () {
const { fetchFollowRequests, multiColumn } = this.props;
if (!multiColumn && window.innerWidth >= NAVIGATION_PANEL_BREAKPOINT) {
this.context.router.history.replace('/timelines/home');
return;
}
fetchFollowRequests();
}
render () {
const { intl, myAccount, multiColumn, unreadFollowRequests } = this.props;
const navItems = [];
let i = 1;
let height = (multiColumn) ? 0 : 60;
if (multiColumn) {
navItems.push(
<ColumnSubheading key={i++} text={intl.formatMessage(messages.discover)} />,
<ColumnLink key={i++} icon='users' text={intl.formatMessage(messages.community_timeline)} to='/timelines/public/local' />,
<ColumnLink key={i++} icon='globe' text={intl.formatMessage(messages.public_timeline)} to='/timelines/public' />,
);
height += 34 + 48*2;
if (profile_directory) {
navItems.push(
<ColumnLink key={i++} icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />
);
height += 48;
}
navItems.push(
<ColumnSubheading key={i++} text={intl.formatMessage(messages.personal)} />
);
height += 34;
} else if (profile_directory) {
navItems.push(
<ColumnLink key={i++} icon='address-book' text={intl.formatMessage(messages.profile_directory)} to='/directory' />
);
height += 48;
}
navItems.push(
<ColumnLink key={i++} icon='envelope' text={intl.formatMessage(messages.direct)} to='/timelines/direct' />,
<ColumnLink key={i++} icon='bookmark' text={intl.formatMessage(messages.bookmarks)} to='/bookmarks' />,
<ColumnLink key={i++} icon='star' text={intl.formatMessage(messages.favourites)} to='/favourites' />,
<ColumnLink key={i++} icon='list-ul' text={intl.formatMessage(messages.lists)} to='/lists' />
);
height += 48*4;
if (myAccount.get('locked') || unreadFollowRequests > 0) {
navItems.push(<ColumnLink key={i++} icon='user-plus' text={intl.formatMessage(messages.follow_requests)} badge={badgeDisplay(unreadFollowRequests, 40)} to='/follow_requests' />);
height += 48;
}
if (!multiColumn) {
navItems.push(
<ColumnSubheading key={i++} text={intl.formatMessage(messages.settings_subheading)} />,
<ColumnLink key={i++} icon='gears' text={intl.formatMessage(messages.preferences)} href='/settings/preferences' />,
);
height += 34 + 48;
}
return (
<Column bindToDocument={!multiColumn} label={intl.formatMessage(messages.menu)}>
{multiColumn && <div className='column-header__wrapper'>
<h1 className='column-header'>
<button>
<Icon id='bars' className='column-header__icon' fixedWidth />
<FormattedMessage id='getting_started.heading' defaultMessage='Getting started' />
</button>
</h1>
</div>}
<div className='getting-started'>
<div className='getting-started__wrapper' style={{ height }}>
{!multiColumn && <NavigationBar account={myAccount} />}
{navItems}
</div>
{!multiColumn && <div className='flex-spacer' />}
<LinkFooter withHotkeys={multiColumn} />
</div>
{multiColumn && showTrends && <TrendsContainer />}
</Column>
);
}
}
|
front_end/front_end_app/src/server/frontend/render.js | carlodicelico/horizon | import DocumentTitle from 'react-document-title';
import Html from './html.react';
import Promise from 'bluebird';
import React from 'react';
import Router from 'react-router';
import config from '../config';
import immutable from 'immutable';
import initialState from '../initialstate';
import routes from '../../client/routes';
import stateMerger from '../lib/merger';
import useragent from 'useragent';
export default function render(req, res, ...customStates) {
const appState = immutable.fromJS(initialState).mergeWith(stateMerger, ...customStates).toJS();
return renderPage(req, res, appState);
}
function renderPage(req, res, appState) {
return new Promise((resolve, reject) => {
const router = Router.create({
routes,
location: req.originalUrl,
onError: reject,
onAbort: (abortReason) => {
// Some requireAuth higher order component requested redirect.
if (abortReason.constructor.name === 'Redirect') {
const {to, params, query} = abortReason;
const path = router.makePath(to, params, query);
res.redirect(path);
resolve();
return;
}
reject(abortReason);
}
});
router.run((Handler, routerState) => {
const ua = useragent.is(req.headers['user-agent']);
const html = getPageHtml(Handler, appState, {
hostname: req.hostname,
// TODO: Remove once Safari and IE without Intl will die.
needIntlPolyfill: ua.safari || (ua.ie && ua.version < '11')
});
const notFound = routerState.routes.some(route => route.name === 'not-found');
const status = notFound ? 404 : 200;
res.status(status).send(html);
resolve();
});
});
}
function getPageHtml(Handler, appState, {hostname, needIntlPolyfill}) {
const appHtml = `<div id="app">${
React.renderToString(<Handler initialState={appState} />)
}</div>`;
const appScriptSrc = config.isProduction
? '/build/app.js?v=' + config.version
: `//${hostname}:8888/build/app.js`;
let scriptHtml = '';
if (needIntlPolyfill) {
scriptHtml += `
<script src="/node_modules/intl/dist/Intl.min.js"></script>
<script src="/node_modules/intl/locale-data/jsonp/en-US.js"></script>`;
}
scriptHtml += `
<script>
window._initialState = ${JSON.stringify(appState)};
</script>
<script src="${appScriptSrc}"></script>
`;
if (config.isProduction && config.googleAnalyticsId !== 'UA-XXXXXXX-X')
scriptHtml += `
<script>
(function(b,o,i,l,e,r){b.GoogleAnalyticsObject=l;b[l]||(b[l]=
function(){(b[l].q=b[l].q||[]).push(arguments)});b[l].l=+new Date;
e=o.createElement(i);r=o.getElementsByTagName(i)[0];
e.src='//www.google-analytics.com/analytics.js';
r.parentNode.insertBefore(e,r)}(window,document,'script','ga'));
ga('create','${config.googleAnalyticsId}');ga('send','pageview');
</script>`;
const title = DocumentTitle.rewind();
return '<!DOCTYPE html>' + React.renderToStaticMarkup(
<Html
bodyHtml={appHtml + scriptHtml}
isProduction={config.isProduction}
title={title}
version={config.version}
/>
);
}
|
src/components/render-in-body/RenderInBody.js | edgemesh/emui | import React, { Component } from 'react';
import { render, unmountComponentAtNode } from 'react-dom';
class RenderInBody extends Component {
componentDidMount() {
this.child = document.createElement('div');
document.body.appendChild(this.child);
this._renderLayer();
}
componentDidUpdate() {
this._renderLayer();
}
componentWillUnmount() {
unmountComponentAtNode(this.child);
document.body.removeChild(this.child);
}
_renderLayer() {
render(this.props.children, this.child);
}
render() {
// Render a placeholder
return (<div/>);
}
}
const decorateRenderInBody = (ComposedComponent, options = {}) => {
return class extends Component {
child = null;
componentDidMount() {
this.child = document.createElement('div');
document.body.appendChild(this.child);
this._renderLayer();
}
componentDidUpdate() {
this._renderLayer();
}
componentWillUnmount() {
unmountComponentAtNode(this.child);
document.body.removeChild(this.child);
}
_renderLayer() {
render(<ComposedComponent />, this.child);
}
render() {
// Render a placeholder
return (<div/>);
}
}
}
const _RenderInBody = (element, options = {}) => {
switch(typeof element) {
case 'object':
return (<RenderInBody>{element.children}</RenderInBody>);
case 'function':
return decorateRenderInBody(element);
default:
return;
}
}
export default _RenderInBody;
|
library_js/src/components/addBook.js | HoldYourBreath/Library | import React from 'react';
import ShowThumbnail from './ShowThumbnail';
import sessionStore from '../stores/Session';
import { observer } from 'mobx-react';
import locationStore from '../stores/LocationStore';
import { Redirect } from 'react-router'
import {FormGroup,
Button,
Col,
Alert,
Form,
FormControl,
ControlLabel} from 'react-bootstrap';
const request = require('superagent');
const FontAwesome = require('react-fontawesome');
class AddBook extends React.Component {
constructor(props) {
super(props);
this.state = {
loadingBookData: false,
errorMsg: '',
infoMsg: '',
room_id: '',
isbn: '',
tag: '',
title: '',
authors: '',
description: '',
format: '',
pages: '',
publication_date: '',
thumbnail: ''
};
}
onFormInput(e) {
this.setState({[e.target.id]: e.target.value});
}
onTagKeyPress(e) {
if (e.key === 'Enter') {
this.submitBook();
}
}
onIsbnChange(e) {
this.setState({[e.target.id]: e.target.value});
let isbn = e.target.value;
if (isbn.length === 13) {
this.getBookData(isbn);
}
}
getBookData(isbn) {
let url = `${window.API_URL}/api/books/goodreads/${isbn}`;
this.setState({loadingBookData: true});
request
.get(url)
.type('application/json')
.on('error', (err) => {
this.setState({
errorMsg: `Unable to fetch book info for ${isbn}`,
loadingBookData: false
});
})
.end((err, res) => {
if (err) {
return;
}
this.setState({
loadingBookData: false,
errorMsg: null
});
let state = Object.assign({}, res.body);
state.pages = state.num_pages;
state.isbn = isbn;
delete state.num_pages;
delete state.errorMsg;
this.setState(state);
document.getElementById("tag").focus();
});
}
reset(e) {
this.setState({
loadingBookData: false,
thumbnail: null,
isbn: '',
title: '',
tag: '',
authors: '',
description: '',
format: '',
pages: '',
publication_date: ''
});
}
submitBook() {
let url = `${window.API_URL}/api/books/ebids/${this.state.tag}`;
request
.get(url)
.then((res) => {
// HTTP 200 response, book exists
this.setState({
infoMsg: null,
errorMsg: `Book ${this.state.tag} already exists`
});
},
(res) => {
// Error response
if (res.status === 404) {
this.addBook();
}
else {
this.setState({errorMsg: `Unable to fetch data for book: ${res.response.text}`});
}
}
);
}
addBook() {
let url = `${window.API_URL}/api/books/ebids/${this.state.tag}`;
request
.put(url)
.send(this.state)
.type('application/json')
.on('error', (err) => {
this.setState({errorMsg: `Unable to post new book: ${err.response.text}`});
})
.end((err, res) => {
if (!err) {
this.setState({
errorMsg: null,
infoMsg: `New book with tag ${res.body.id} added!`,
});
let isbn = document.getElementById("isbn");
isbn.focus();
isbn.scrollIntoView();
this.reset();
}
});
}
onRoomChange(e) {
this.setState({room_id: e.target.value});
locationStore.selectRoom(e.target.value);
}
render() {
const ErrAlert = this.state.errorMsg ? <Alert bsStyle="danger"><strong>{this.state.errorMsg}</strong></Alert> : null;
const InfoAlert = this.state.infoMsg ? <Alert bsStyle="success"><strong>{this.state.infoMsg}</strong></Alert> : null;
if (!sessionStore.loggedIn) {
return <Redirect to="/login" push={false} />
}
return (
<div>
<h1>Add book</h1>
{ErrAlert}
{InfoAlert}
<Form horizontal>
<FormGroup>
<Col smOffset={2} sm={1}>
<Button
disabled={!this.state.isbn || !this.state.tag}
onClick={this.submitBook.bind(this)}>
Submit book
</Button>
</Col>
<Col smOffset={2} sm={1}>
<Button
onClick={this.reset.bind(this)}>
Reset
</Button>
</Col>
</FormGroup>
<FormGroup controlId="isbn">
<Col componentClass={ControlLabel} sm={2}>
ISBN-13
</Col>
<Col sm={5}>
<FormControl
value={this.state.isbn}
onChange={this.onIsbnChange.bind(this)}
disabled={this.state.loadingBookData}
type="text"
autoComplete="off"
autoFocus="true"
placeholder=""/>
</Col>
<Col sm={1}>
{this.state.loadingBookData ? <FontAwesome name='spinner' size='2x'spin/> : null}
</Col>
</FormGroup>
<FormGroup controlId="tag">
<Col componentClass={ControlLabel} sm={2}>
TAG
</Col>
<Col sm={5}>
<FormControl
value={this.state.tag}
onChange={this.onFormInput.bind(this)}
onKeyPress={this.onTagKeyPress.bind(this)}
type="text"
autoComplete="off"
placeholder=""/>
</Col>
</FormGroup>
<FormGroup controlId="title">
<Col componentClass={ControlLabel} sm={2}>
Title
</Col>
<Col sm={7}>
<FormControl
value={this.state.title}
onChange={this.onFormInput.bind(this)}
type="text"
autoComplete="off"
placeholder=""/>
</Col>
</FormGroup>
<FormGroup controlId="room_id">
<Col componentClass={ControlLabel} sm={2}>
Room
</Col>
<Col sm={7}>
<FormControl
componentClass="select"
defaultValue={locationStore.selectedRoom}
onChange={this.onRoomChange.bind(this)}
placeholder="select">
<option />
{locationStore.rooms.map((room) => {
return <option
key={room.roomId}
value={room.roomId}>{room.roomName}</option>
})
}
</FormControl>
</Col>
</FormGroup>
<FormGroup controlId="authors">
<Col componentClass={ControlLabel} sm={2}>
Authors
</Col>
<Col sm={7}>
<FormControl
value={this.state.authors}
onChange={this.onFormInput.bind(this)}
type="text"
autoComplete="off"
placeholder=""/>
</Col>
</FormGroup>
<FormGroup controlId="description">
<Col componentClass={ControlLabel} sm={2}>
Description
</Col>
<Col sm={10}>
<FormControl
value={this.state.description}
onChange={this.onFormInput.bind(this)}
style={{height: '150px'}}
componentClass="textarea"
autoComplete="off"
placeholder=""/>
</Col>
</FormGroup>
<FormGroup controlId="format">
<Col componentClass={ControlLabel} sm={2}>
Format
</Col>
<Col sm={2}>
<FormControl
value={this.state.format}
onChange={this.onFormInput.bind(this)}
autoComplete="off"
placeholder=""/>
</Col>
<Col componentClass={ControlLabel} sm={2}>
Pages
</Col>
<Col sm={2}>
<FormControl
value={this.state.pages}
onChange={this.onFormInput.bind(this)}
autoComplete="off"
placeholder=""/>
</Col>
<Col componentClass={ControlLabel} sm={2}>
Publication date
</Col>
<Col sm={2}>
<FormControl
value={this.state.publication_date}
onChange={this.onFormInput.bind(this)}
autoComplete="off"
placeholder=""/>
<br/>
</Col>
</FormGroup>
<FormGroup controlId="publication_date">
<Col componentClass={ControlLabel} sm={2}>
Thumbnail
</Col>
<Col sm={6}>
<ShowThumbnail thumbnailUrl={this.state.thumbnail}/>
</Col>
</FormGroup>
</Form>
</div>
);
}
}
export default observer(AddBook);
|
client/routes.js | sharvit/my-blog-react | /* eslint-disable global-require */
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './modules/App/App';
// Import Middlewares
import { isAuthenticated, isAuthenticatedSeller } from './modules/Auth/middlewares';
// require.ensure polyfill for node
if (typeof require.ensure !== 'function') {
require.ensure = function requireModule(deps, callback) {
callback(require);
};
}
/* Workaround for async react routes to work with react-hot-reloader till
https://github.com/reactjs/react-router/issues/2182 and
https://github.com/gaearon/react-hot-loader/issues/288 is fixed.
*/
if (process.env.NODE_ENV !== 'production') {
// Require async routes only in development for react-hot-reloader to work.
require('./modules/Auth/pages/SigninPage/SigninPage');
require('./modules/Auth/pages/SignupPage/SignupPage');
require('./modules/Layouts/AppLayout/AppLayout');
require('./modules/App/pages/HomePage/HomePage');
require('./modules/Rental/pages/RentalListPage/RentalListPage');
require('./modules/Layouts/DashboardLayout/DashboardLayout');
require('./modules/Dashboard/Dashboard');
require('./modules/Dashboard/pages/RentalListPage/RentalListPage');
require('./modules/Dashboard/pages/RentalItemPage/RentalItemPage');
}
// react-router setup with code-splitting
// More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/
export default function (store) {
return (
<Route path="/" component={App}>
<Route path="signin"
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Auth/pages/SigninPage/SigninPage').default);
});
}}
/>
<Route path="signup"
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Auth/pages/SignupPage/SignupPage').default);
});
}}
/>
<Route path=""
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Layouts/AppLayout/AppLayout').default);
});
}}
>
<IndexRoute
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/App/pages/HomePage/HomePage').default);
});
}}
/>
<Route path="rentals/:country/:region/:city/:type"
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Rental/pages/RentalListPage/RentalListPage').default);
});
}}
/>
</Route>
<Route path="dashboard"
onEnter={isAuthenticatedSeller.bind(this, store)}
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Layouts/DashboardLayout/DashboardLayout').default);
});
}}
>
<IndexRoute
onEnter={(p, replace) => replace('/dashboard/home')}
/>
<Route path="home"
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Dashboard/Dashboard').default);
});
}}
/>
<Route path="rentals"
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Dashboard/pages/RentalListPage/RentalListPage').default);
});
}}
/>
<Route path="rentals/:id"
getComponent={(nextState, cb) => {
require.ensure([], require => {
cb(null, require('./modules/Dashboard/pages/RentalItemPage/RentalItemPage').default);
});
}}
/>
</Route>
</Route>
);
}
|
src/components/testing.js | ProjectSunday/rooibus | import React from 'react'
import * as Actions from '../actions/actions'
class Testing extends React.Component {
test1Clicked = () => {
Actions.test1()
}
test2Clicked = () => {
Actions.test2()
}
render() {
return (
<div>
{/*<div className="testing">TESTING</div>*/}
{/*<button onClick={this.test1Clicked}>Test1</button>*/}
{/*<button onClick={this.test2Clicked}>Test2</button>*/}
</div>
)
}
}
export default Testing
|
src/ButtonGroup.js | coderstudy/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
const ButtonGroup = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
vertical: React.PropTypes.bool,
justified: React.PropTypes.bool,
/**
* Display block buttons, only useful when used with the "vertical" prop.
* @type {bool}
*/
block: CustomPropTypes.all([
React.PropTypes.bool,
function(props, propName, componentName) {
if (props.block && !props.vertical) {
return new Error('The block property requires the vertical property to be set to have any effect');
}
}
])
},
getDefaultProps() {
return {
bsClass: 'button-group'
};
},
render() {
let classes = this.getBsClassSet();
classes['btn-group'] = !this.props.vertical;
classes['btn-group-vertical'] = this.props.vertical;
classes['btn-group-justified'] = this.props.justified;
classes['btn-block'] = this.props.block;
return (
<div
{...this.props}
className={classNames(this.props.className, classes)}>
{this.props.children}
</div>
);
}
});
export default ButtonGroup;
|
assets/javascripts/kitten/components/graphics/icons/file-icon/index.js | KissKissBankBank/kitten | import React from 'react'
import PropTypes from 'prop-types'
export const FileIcon = ({ color, title, ...props }) => (
<svg
width="16"
height="20"
viewBox="0 0 16 20"
xmlns="http://www.w3.org/2000/svg"
{...props}
>
{title && <title>{title}</title>}
<path
d="M16 20H0V0h11l5 5v15zM10 2H2v16h12V6h-4V2zm1.5 10.25v1.5h-7v-1.5h7zm0-3v1.5h-7v-1.5h7zm-4-3v1.5h-3v-1.5h3z"
fill={color}
/>
</svg>
)
FileIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string,
}
FileIcon.defaultProps = {
color: '#222',
title: '',
}
|
components/DeviceFrame/DeviceFrame.js | NGMarmaduke/bloom | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { canUseDOM } from 'exenv';
import getValidIndex from '../../utils/getValidIndex/getValidIndex';
import Swap from '../Animate/Swap';
export default class DeviceFrame extends Component {
static propTypes = {
children: PropTypes.arrayOf(
PropTypes.shape({
/* eslint-disable react/no-unused-prop-types */
src: PropTypes.string,
alt: PropTypes.string,
/* eslint-enable react/no-unused-prop-types */
})
).isRequired,
deviceImage: PropTypes.string.isRequired,
interval: PropTypes.number,
css: PropTypes.shape({
/* eslint-disable react/no-unused-prop-types */
root: PropTypes.string,
frame: PropTypes.string,
inner: PropTypes.string,
img: PropTypes.string,
/* eslint-enable react/no-unused-prop-types */
}),
};
static defaultProps = {
interval: 3000,
};
state = {
activeIndex: 0,
};
componentDidMount() {
const { children, interval } = this.props;
this.preloadImages();
if (children.length > 1) {
this.interval = setInterval(this.incrementActiveIndex, interval);
}
}
componentWillUnmount() {
if (this.interval) clearInterval(this.interval);
}
incrementActiveIndex = () => {
const { children } = this.props;
const { activeIndex } = this.state;
this.setState({
activeIndex: getValidIndex(activeIndex + 1, children.length, 1),
});
};
preloadImages = () => {
const { children } = this.props;
if (canUseDOM) {
children.forEach(({ src }) => {
/* eslint-disable no-undef */
const imgElm = new Image();
imgElm.src = src;
/* eslint-enable no-undef */
});
}
}
render() {
const { children, interval, css, deviceImage } = this.props;
const { activeIndex } = this.state;
const img = children[activeIndex];
return (
<div className={ css.root }>
<img
className={ css.frame }
src={ deviceImage }
role="presentation"
/>
<div className={ css.inner }>
<Swap animationTimeout={ interval }>
<img
key={ activeIndex }
className={ css.img }
src={ img.src }
alt={ img.alt }
/>
</Swap>
</div>
</div>
);
}
}
|
app/components/profile/ChangeField.js | ritishgumber/dashboard-ui | import React from 'react';
class ChangeField extends React.Component {
constructor(props) {
super(props);
this.state = {
editMode: false
};
}
render() {
const editField = () => this.setState({ editMode: true });
const closeEditing = () => {
this.setState({ editMode: false });
}
const handleKeyUp = (e) => {
if(e.which === 13) {
closeEditing();
this.props.keyUpHandler();
}
}
let InputField = null;
if (this.state.editMode === false) {
if(this.props.field === 'name') {
InputField = (
<input className="input-field inputedit" ref={this.props.field} type="text" placeholder="Type here" defaultValue={this.props.value} onClick={editField} onFocus={editField} />
);
} else {
InputField = (
<input className="input-field inputedit" ref={this.props.field} type="password" placeholder="Type here" value={this.props.value} onClick={editField} onFocus={editField} />
);
}
} else {
if(this.props.field === 'name') {
InputField = (
<input className="input-field inputeditenable" ref={this.props.field} type="text" defaultValue={this.props.value} placeholder="Type here" onChange={(event) => this.props.changeHandler(this.props.field, event)} onBlur={closeEditing} onKeyUp={handleKeyUp}/>
);
} else {
InputField = (
<input className="input-field inputeditenable" ref={this.props.field} type="password" value={this.props.value} placeholder="Type here" onChange={(event) => this.props.changeHandler(this.props.field, event)} onBlur={closeEditing} onKeyUp={handleKeyUp}/>
);
}
}
return (
<div>
{InputField}
</div>
);
}
}
export default ChangeField; |
web/react/components/validation/FieldValidation.js | vdyachenko-determine/tasker | import React from 'react';
/**
* React component for custom field validation
*/
class FieldValidation extends React.Component {
/**
* Constructor
*
* @param props component's properties
*/
constructor(props) {
super(props);
// this declaration allows us to use this inside of the function
this.handleChange = this.handleChange.bind(this);
// get props value and set it to the state
this.state = {
type: props.type, // type is mandatory only for input field
name: props.name, // name of the field
value: props.value, // value of the field
icon: props.icon, // field's icon
placeholder: props.placeholder, // field's placeholder
rules: 'filled', // validation rules #TODO add another rules
errorMessage: props.error, // error message
isFieldValid: -1 // is field valid flag: 0 - no, 1 - yes, -1 - initial state
}
}
/**
* Function calls when props has been changed. Do not call
* @param nextProps
*/
componentWillReceiveProps(nextProps) {
if (nextProps.isFormSubmit) {
this.setState({
errorMessage: nextProps.error, // error message
isFieldValid: nextProps.error == '' ? 1 : 0
})
}
}
/**
* Changing handler
* If field is invalid, update error's property state and call form function for checking form validity
*
* @param e
*/
handleChange (e) {
// current field value
var currentValue = e.target.value;
var errorMessage = '';
var isFieldValid = true;
// if field is empty - set error message and turn valid flag to false
if (currentValue.length === 0) {
errorMessage = 'Field should not be empty!';
isFieldValid = false;
}
// change state of needed validation properties
this.setState({
errorMessage: errorMessage,
value: currentValue,
isFieldValid: isFieldValid,
});
// call parent form validation callback
if (this.props.parentValidation) {
// field name
var fieldName = this.state.name;
this.props.parentValidation(fieldName, isFieldValid);
}
}
render() {
// get field error class
let fieldErrorClass = '';
if (this.state.isFieldValid == true) {
fieldErrorClass = 'has-success';
}
if (this.state.isFieldValid == false) {
fieldErrorClass = 'has-error';
}
return(
<div className={['form-group', fieldErrorClass].join(' ')}>
<div className="input-group">
<span className="input-group-addon">
<i className={["fa", this.state.icon].join(' ')}></i>
</span>
<input
onChange={this.handleChange} // call validation callback after value changing
name={this.state.name} // set field's name
type={this.state.type} // set field's type
className="form-control" // set field's class
value={this.state.value} // set field's value
placeholder={this.state.placeholder} // set field's placeholder
/>
</div>
<div className="form-error-message">
{this.state.errorMessage}
</div>
</div>
);
}
}
export default FieldValidation;
|
src/svg-icons/maps/traffic.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsTraffic = (props) => (
<SvgIcon {...props}>
<path d="M20 10h-3V8.86c1.72-.45 3-2 3-3.86h-3V4c0-.55-.45-1-1-1H8c-.55 0-1 .45-1 1v1H4c0 1.86 1.28 3.41 3 3.86V10H4c0 1.86 1.28 3.41 3 3.86V15H4c0 1.86 1.28 3.41 3 3.86V20c0 .55.45 1 1 1h8c.55 0 1-.45 1-1v-1.14c1.72-.45 3-2 3-3.86h-3v-1.14c1.72-.45 3-2 3-3.86zm-8 9c-1.11 0-2-.9-2-2s.89-2 2-2c1.1 0 2 .9 2 2s-.89 2-2 2zm0-5c-1.11 0-2-.9-2-2s.89-2 2-2c1.1 0 2 .9 2 2s-.89 2-2 2zm0-5c-1.11 0-2-.9-2-2 0-1.11.89-2 2-2 1.1 0 2 .89 2 2 0 1.1-.89 2-2 2z"/>
</SvgIcon>
);
MapsTraffic = pure(MapsTraffic);
MapsTraffic.displayName = 'MapsTraffic';
MapsTraffic.muiName = 'SvgIcon';
export default MapsTraffic;
|
client/guidestours/config.js | allendav/wp-calypso | /**
* External dependencies
*/
import React from 'react';
/**
* Internal dependencies
*/
import Gridicon from 'components/gridicon';
import i18n from 'lib/mixins/i18n';
const config = {
init: {
text: i18n.translate( '{{strong}}Need a hand?{{/strong}} We\'d love to show you around the place, and give you some ideas for what to do next.', {
components: {
strong: <strong />,
}
} ),
type: 'GuidesFirstStep',
next: 'my-sites',
},
'my-sites': {
target: 'my-sites',
type: 'GuidesActionStep',
icon: 'my-sites',
placement: 'below',
text: i18n.translate( "First things first. Up here, you'll find tools for managing your site's content and design." ),
next: 'posts-pages',
},
'posts-pages': {
text: i18n.translate( "Posts aren't Pages. Would you like to know more?" ),
type: 'GuidesLinkStep',
linkLabel: i18n.translate( 'Learn more about Posts and Pages' ),
linkUrl: 'https://en.support.wordpress.com/post-vs-page/',
next: 'reader',
},
reader: {
target: 'reader',
type: 'GuidesActionStep',
icon: 'reader',
placement: 'beside',
text: i18n.translate( "This is the Reader. It shows you fresh posts from other sites you're following." ),
next: 'finish'
},
finish: {
target: 'me',
placement: 'beside',
text: i18n.translate( "{{strong}}That's it!{{/strong}} Now that you know a few of the basics, feel free to wander around. You can get more help by going to the {{gridicon/}} {{strong}}Me{{/strong}} section.", {
components: {
strong: <strong />,
gridicon: <Gridicon icon="user-circle" size={ 18 } />,
}
} ),
type: 'GuidesFinishStep',
linkLabel: 'Get the Most from WordPress.com',
linkUrl: 'https://learn.wordpress.com',
}
}
export default config;
|
modules/gob-web/modules/course-table/missing-course.js | hawkrives/gobbldygook | // @flow
import React from 'react'
import FakeCourse from './fake-course'
type Props = {
+className?: string,
+clbid: string,
+error: Error,
}
export default function MissingCourse(props: Props) {
return (
<FakeCourse
title={`Cannot load course ${props.clbid}`}
details={String(props.error.message)}
className={`missing ${props.className || ''}`}
/>
)
}
|
packages/web/src/components/range/SingleRange.js | appbaseio/reactivesearch | import React, { Component } from 'react';
import { updateQuery, setQueryOptions, setCustomQuery } from '@appbaseio/reactivecore/lib/actions';
import hoistNonReactStatics from 'hoist-non-react-statics';
import {
isEqual,
checkValueChange,
checkSomePropChange,
getClassName,
updateCustomQuery,
getOptionsFromQuery,
} from '@appbaseio/reactivecore/lib/utils/helper';
import types from '@appbaseio/reactivecore/lib/utils/types';
import { componentTypes } from '@appbaseio/reactivecore/lib/utils/constants';
import Title from '../../styles/Title';
import Container from '../../styles/Container';
import { UL, Radio } from '../../styles/FormControlList';
import { connect, getRangeQueryWithNullValues } from '../../utils';
import ComponentWrapper from '../basic/ComponentWrapper';
class SingleRange extends Component {
constructor(props) {
super(props);
const defaultValue = props.defaultValue || props.value;
const value = props.selectedValue || defaultValue || null;
const currentValue = SingleRange.parseValue(value, props);
this.state = {
currentValue,
};
this.type = 'range';
// Set custom query in store
updateCustomQuery(props.componentId, props, currentValue);
const hasMounted = false;
if (currentValue) {
this.setValue(currentValue, props, hasMounted);
}
}
componentDidMount() {
const { enableAppbase, index } = this.props;
if (!enableAppbase && index) {
console.warn(
'Warning(ReactiveSearch): In order to use the `index` prop, the `enableAppbase` prop must be set to true in `ReactiveBase`.',
);
}
}
componentDidUpdate(prevProps) {
checkSomePropChange(this.props, prevProps, ['dataField', 'nestedField'], () => {
this.updateQuery(this.state.currentValue, this.props);
});
if (!isEqual(this.props.value, prevProps.value)) {
this.setValue(this.props.value);
} else if (
!isEqual(this.state.currentValue, this.props.selectedValue)
&& !isEqual(this.props.selectedValue, prevProps.selectedValue)
) {
const { value, onChange } = this.props;
if (value === undefined) {
this.setValue(this.props.selectedValue || null);
} else if (onChange) {
onChange(this.props.selectedValue || null);
} else {
this.setValue(this.state.currentValue);
}
}
}
// parses range label to get start and end
static parseValue = (value, props) => props.data.find(item => item.label === value) || null;
static defaultQuery = (value, props) => {
let query = null;
if (value) {
query = getRangeQueryWithNullValues([value.start, value.end], props);
}
if (query && props.nestedField) {
return {
nested: {
path: props.nestedField,
query,
},
};
}
return query;
};
setValue = (value, props = this.props, hasMounted = true) => {
const currentValue
= typeof value === 'string' ? SingleRange.parseValue(value, props) : value;
const performUpdate = () => {
const handleUpdates = () => {
this.updateQuery(currentValue, props);
if (props.onValueChange) props.onValueChange(currentValue);
};
if (hasMounted) {
this.setState(
{
currentValue,
},
handleUpdates,
);
} else {
handleUpdates();
}
};
checkValueChange(props.componentId, currentValue, props.beforeValueChange, performUpdate);
};
updateQuery = (value, props) => {
const { customQuery } = props;
let query = SingleRange.defaultQuery(value, props);
let customQueryOptions;
if (customQuery) {
({ query } = customQuery(value, props) || {});
customQueryOptions = getOptionsFromQuery(customQuery(value, props));
updateCustomQuery(props.componentId, props, value);
}
props.setQueryOptions(props.componentId, customQueryOptions);
props.updateQuery({
componentId: props.componentId,
query,
value,
label: props.filterLabel,
showFilter: props.showFilter,
URLParams: props.URLParams,
componentType: componentTypes.singleRange,
});
};
handleClick = (e) => {
const { value, onChange } = this.props;
const { value: rangeValue } = e.target;
if (value === undefined) {
this.setValue(rangeValue);
} else if (onChange) {
onChange(rangeValue);
}
};
render() {
return (
<Container style={this.props.style} className={this.props.className}>
{this.props.title && (
<Title className={getClassName(this.props.innerClass, 'title') || null}>
{this.props.title}
</Title>
)}
<UL
className={getClassName(this.props.innerClass, 'list') || null}
aria-label={`${this.props.componentId}-items`}
role="radiogroup"
>
{this.props.data.map((item) => {
const selected
= !!this.state.currentValue
&& this.state.currentValue.label === item.label;
return (
<li
key={item.label}
className={`${selected ? 'active' : ''}`}
role="radio"
aria-checked={selected}
>
<Radio
className={getClassName(this.props.innerClass, 'radio')}
id={`${this.props.componentId}-${item.label}`}
tabIndex={selected ? '-1' : '0'}
value={item.label}
onChange={this.handleClick}
checked={selected}
show={this.props.showRadio}
/>
<label
className={getClassName(this.props.innerClass, 'label') || null}
htmlFor={`${this.props.componentId}-${item.label}`}
>
<span>{item.label}</span>
</label>
</li>
);
})}
</UL>
</Container>
);
}
}
SingleRange.propTypes = {
updateQuery: types.funcRequired,
selectedValue: types.selectedValue,
setCustomQuery: types.funcRequired,
enableAppbase: types.bool,
// component props
beforeValueChange: types.func,
className: types.string,
componentId: types.stringRequired,
customQuery: types.func,
data: types.data,
dataField: types.stringRequired,
defaultValue: types.string,
value: types.string,
filterLabel: types.string,
innerClass: types.style,
nestedField: types.string,
onQueryChange: types.func,
onValueChange: types.func,
onChange: types.func,
react: types.react,
showFilter: types.bool,
showRadio: types.boolRequired,
style: types.style,
title: types.title,
URLParams: types.bool,
includeNullValues: types.bool,
index: types.string,
};
SingleRange.defaultProps = {
className: null,
showFilter: true,
showRadio: true,
style: {},
URLParams: false,
includeNullValues: false,
};
// Add componentType for SSR
SingleRange.componentType = componentTypes.singleRange;
const mapStateToProps = (state, props) => ({
selectedValue:
(state.selectedValues[props.componentId]
&& state.selectedValues[props.componentId].value)
|| null,
enableAppbase: state.config.enableAppbase,
});
const mapDispatchtoProps = dispatch => ({
setCustomQuery: (component, query) => dispatch(setCustomQuery(component, query)),
updateQuery: updateQueryObject => dispatch(updateQuery(updateQueryObject)),
setQueryOptions: (component, props, execute) =>
dispatch(setQueryOptions(component, props, execute)),
});
const ConnectedComponent = connect(
mapStateToProps,
mapDispatchtoProps,
)(props => (
<ComponentWrapper {...props} componentType={componentTypes.singleRange}>
{() => <SingleRange ref={props.myForwardedRef} {...props} />}
</ComponentWrapper>
));
// eslint-disable-next-line
const ForwardRefComponent = React.forwardRef((props, ref) => (
<ConnectedComponent {...props} myForwardedRef={ref} />
));
hoistNonReactStatics(ForwardRefComponent, SingleRange);
ForwardRefComponent.displayName = 'SingleRange';
export default ForwardRefComponent;
|
app/javascript/mastodon/components/permalink.js | Arukas/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class Permalink extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
className: PropTypes.string,
href: PropTypes.string.isRequired,
to: PropTypes.string.isRequired,
children: PropTypes.node,
};
handleClick = (e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(this.props.to);
}
}
render () {
const { href, children, className, ...other } = this.props;
return (
<a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}>
{children}
</a>
);
}
}
|
frontend/src/index.js | rossnomann/playlog | import 'whatwg-fetch';
import React from 'react';
import ReactDOM from 'react-dom';
import {Provider} from 'react-redux';
import App from './app';
import {store} from './redux';
import './index.css';
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);
|
src/svg-icons/action/pageview.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPageview = (props) => (
<SvgIcon {...props}>
<path d="M11.5 9C10.12 9 9 10.12 9 11.5s1.12 2.5 2.5 2.5 2.5-1.12 2.5-2.5S12.88 9 11.5 9zM20 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-3.21 14.21l-2.91-2.91c-.69.44-1.51.7-2.39.7C9.01 16 7 13.99 7 11.5S9.01 7 11.5 7 16 9.01 16 11.5c0 .88-.26 1.69-.7 2.39l2.91 2.9-1.42 1.42z"/>
</SvgIcon>
);
ActionPageview = pure(ActionPageview);
ActionPageview.displayName = 'ActionPageview';
ActionPageview.muiName = 'SvgIcon';
export default ActionPageview;
|
src/client/components/admin/GalleryListView.js | dtekcth/dfotose | import React from 'react';
import {Link} from "react-router-dom";
import GalleryList from './GalleryList';
import GalleryStore from '../../GalleryStore';
class GalleryListView extends React.Component {
render() {
const store = new GalleryStore(true);
return (
<div>
<h4> Gallerier </h4>
<Link to="/admin/gallery/new"><button type="button">Skapa nytt galleri</button></Link>
<GalleryList galleries={ store } />
</div>
);
}
}
export default GalleryListView; |
imports/client/ui/pages/NewEvent/loadable.js | mordka/fl-events | import React from 'react'
import Loadable from 'react-loadable'
const LoadableComponent = Loadable({
loader: () => import('./index'),
render (loaded, props) {
let Component = loaded.default
return <Component { ...props } />
},
loading () { return <div /> }
})
export default LoadableComponent
|
components/FunnelInputField/FunnelInputField.js | NGMarmaduke/bloom | import PropTypes from 'prop-types';
import React from 'react';
import mergeObjectStrings from '../../utils/mergeObjectStrings/mergeObjectStrings';
import InputField from '../Form/InputField/InputField';
import css from './FunnelInputField.css';
const FunnelInputField = ({ classNames, ...rest }) => {
const classes = mergeObjectStrings(css, classNames);
return (
<InputField
{ ...rest }
classNames={ classes }
/>
);
};
FunnelInputField.propTypes = {
classNames: PropTypes.shape({
root: PropTypes.string,
meta: PropTypes.string,
label: PropTypes.string,
valueReplay: PropTypes.string,
placeholder: PropTypes.string,
description: PropTypes.string,
}),
};
FunnelInputField.defaultProps = {
classNames: {},
};
export default FunnelInputField;
|
src/App.js | vincentaudebert/people-recog | /* eslint no-undef: 0 */
import React, { Component } from 'react';
import './App.css';
import '../node_modules/tracking/build/tracking-min';
import '../node_modules/tracking/build/data/face';
import Webcam from 'webcamjs';
import resemble from 'resemblejs';
import Modal from 'react-modal';
const debounce = (func, wait, immediate) => {
let timeout;
return function() {
const context = this, args = arguments;
const later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
const callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
class App extends Component {
constructor(props) {
super(props);
this.state = {
pic: '',
resultPic: '',
match: 0,
name: '',
openModal: false,
nameSaved: false,
noFace: true,
};
}
componentDidMount() {
const tracker = new tracking.ObjectTracker('face');
tracker.setInitialScale(4);
tracker.setStepSize(2);
tracker.setEdgesDensity(0.1);
tracking.track('#video', tracker, { camera: true });
tracker.on('track', this.track.bind(this));
Webcam.attach('#video');
}
track(event) {
if (event.data.length >= 1) {
if (this.state.pic !== '' && this.state.nameSaved) {
debounce(this.doMatch(), 2000);
}
this.setState({
noFace: false,
});
} else {
this.setState({
noFace: true,
});
};
}
takeSnapshot(callback) {
Webcam.snap(callback);
}
afterOpenModal() {
this.setState({
nameSaved: false,
});
}
openModal(callback) {
this.setState({
openModal: true,
});
this.takeSnapshot(callback);
}
closeModal() {
this.setState({
openModal: false,
nameSaved: true,
});
}
addImageToCanvas(canvasId, dataUri, x, y, width, height) {
return new Promise((resolve, reject) => {
const canvasHidden = document.getElementById(canvasId);
const context = canvasHidden.getContext('2d');
const image = new Image();
image.addEventListener('load', () => {
canvas.width = image.width;
canvas.height = image.height;
context.drawImage(image, x, y, canvas.width, canvas.height);
resolve(true);
}, false);
image.src = dataUri;
});
}
snapshot(dataUri) {
this.setState({
pic: dataUri,
});
}
doMatch() {
this.takeSnapshot(this.compareImages.bind(this));
}
compareImages(cameraData) {
const width = 640;
const height = 480;
const canvasHidden = document.getElementById('canvashidden');
this.addImageToCanvas('canvashidden', this.state.pic, 0, 0, width, height).then(() => {
this.addImageToCanvas('canvashidden', cameraData, width, 0, width, height).then((ret) => {
const imageElement = document.createElement('img');
imageElement.src = canvasHidden.toDataURL();
imageElement.width = width * 2;
imageElement.height = height;
const tracker2 = new tracking.ObjectTracker('face');
tracker2.setInitialScale(4);
tracker2.setStepSize(2);
tracker2.setEdgesDensity(0.1);
tracking.track(imageElement, tracker2);
tracker2.once('track', (rect) => {
if (rect.data.length >= 2) {
const context = canvasHidden.getContext('2d');
const data1 = rect.data[0];
const imageData1 = context.getImageData(data1.x, data1.y, data1.width, data1.height);
const data2 = rect.data[1];
const imageData2 = context.getImageData(data2.x, data2.y, data2.width, data2.height);
resemble(imageData1)
.compareTo(imageData2)
.ignoreColors()
.ignoreAntialiasing()
.scaleToSameSize()
.onComplete((data) => {
this.setState({
resultPic: data.getImageDataUrl(),
match: 100 - data.misMatchPercentage,
});
});
}
});
});
});
}
render() {
return (
<div className="App">
<div className="demo-frame">
<div className="demo-container">
<video id="video" width="640" height="480" preload autoPlay loop muted></video>
<canvas id="canvas" width="640" height="480"></canvas>
</div>
</div>
<div className="snapshot">
<div>
<button
onClick={() => this.openModal(this.snapshot.bind(this)).bind(this)}
disabled={this.state.noFace}
className="button"
>
Snapshot
</button>
</div>
<Modal
isOpen={this.state.openModal}
onAfterOpen={this.afterOpenModal.bind(this)}
onRequestClose={this.closeModal.bind(this)}
contentLabel="Modal"
className="modal__content"
overlayClassName="modal__overlay"
>
<div>
{this.state.pic !== '' && (
<div>
<img className="snapshot__img" src={this.state.pic} alt="Snapshot" />
</div>
)}
<div>
<label className="label" htmlFor="input-name">
May I ask your name?
</label>
</div>
<div>
<input
id="input-name"
className="input"
name="name"
type="text"
placeHolder="Your name"
onBlur={(evt) => this.setState({ name: evt.target.value })}
/>
</div>
<div>
<button
onClick={this.closeModal.bind(this)}
type="button"
className="button"
>
Save
</button>
</div>
</div>
</Modal>
</div>
<canvas id="canvashidden" width="1280" height="480" style={{ display: 'none' }}></canvas>
<div className="result">
{this.state.nameSaved ? (
<div>
{this.state.match > 50 ? (
<p>Hi {this.state.name}! I recognised you ;)</p>
) : (
<p>Oh :( I don't know you.</p>
)}
{this.state.resultPic !== '' && (
<div className="result__picture">
<p><img src={this.state.resultPic} alt="Result pic" /></p>
<p>Match: {parseFloat(this.state.match).toFixed(2)}%</p>
</div>
)}
</div>
) : (
<p>Who are you? Take a snapshot so I can recognise you!</p>
)}
</div>
</div>
);
}
}
export default App;
|
src/components/Login/LoginCtrl.js | folio-org/stripes-core | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect as reduxConnect } from 'react-redux';
import {
withRouter,
matchPath,
} from 'react-router-dom';
import { ConnectContext } from '@folio/stripes-connect';
import {
requestLogin,
requestSSOLogin,
} from '../../loginServices';
import { setAuthError } from '../../okapiActions';
import Login from './Login';
class LoginCtrl extends Component {
static propTypes = {
authFailure: PropTypes.arrayOf(PropTypes.object),
ssoEnabled: PropTypes.bool,
autoLogin: PropTypes.shape({
username: PropTypes.string.isRequired,
password: PropTypes.string.isRequired,
}),
clearAuthErrors: PropTypes.func.isRequired,
history: PropTypes.shape({
push: PropTypes.func.isRequired,
}).isRequired,
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
};
static contextType = ConnectContext;
constructor(props) {
super(props);
this.sys = require('stripes-config'); // eslint-disable-line global-require
this.okapiUrl = this.sys.okapi.url;
this.tenant = this.sys.okapi.tenant;
if (props.autoLogin && props.autoLogin.username) {
this.handleSubmit(props.autoLogin);
}
}
componentWillUnmount() {
this.props.clearAuthErrors();
}
handleSuccessfulLogin = () => {
if (matchPath(this.props.location.pathname, '/login')) {
this.props.history.push('/');
}
}
handleSubmit = (data) => {
return requestLogin(this.okapiUrl, this.context.store, this.tenant, data)
.then(this.handleSuccessfulLogin);
}
handleSSOLogin = () => {
requestSSOLogin(this.okapiUrl, this.tenant);
}
render() {
const { authFailure, ssoEnabled } = this.props;
return (
<Login
onSubmit={this.handleSubmit}
authErrors={authFailure}
handleSSOLogin={this.handleSSOLogin}
ssoActive={ssoEnabled}
/>
);
}
}
const mapStateToProps = state => ({
authFailure: state.okapi.authFailure,
ssoEnabled: state.okapi.ssoEnabled,
});
const mapDispatchToProps = dispatch => ({
clearAuthErrors: () => dispatch(setAuthError([])),
});
export default reduxConnect(mapStateToProps, mapDispatchToProps)(withRouter(LoginCtrl));
|
react-router-demo/lessons/03-navigating-with-link/modules/App.js | zhangjunhd/react-examples | import React from 'react'
export default React.createClass({
render() {
return <div>Hello, React Router!</div>
}
})
|
docs/app/Examples/modules/Progress/States/index.js | ben174/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/render-to-layer.js | esleducation/material-ui | import React from 'react';
import ReactDOM from 'react-dom';
import Events from './utils/events';
import Dom from './utils/dom';
import {debounce} from 'lodash';
// heavily inspired by https://github.com/Khan/react-components/blob/master/js/layered-component-mixin.jsx
const RenderToLayer = React.createClass({
componentDidMount() {
this._renderLayer();
},
componentDidUpdate() {
this._renderLayer();
},
componentWillUnmount() {
this._unbindClickAway();
if (this._layer) {
this._unrenderLayer();
}
},
_checkClickAway(e) {
if (!this.canClickAway) {
return;
}
const el = this._layer;
if (e.target !== el && (e.target === window)
|| (document.documentElement.contains(e.target) && !Dom.isDescendant(el, e.target))) {
if (this.props.componentClickAway) {
this.props.componentClickAway(e);
}
}
},
_preventClickAway(e) {
if (e.detail === this) {
return;
}
this.canClickAway = false;
},
_allowClickAway() {
this.canClickAway = true;
},
getLayer() {
return this._layer;
},
render() {
return null;
},
_renderLayer() {
if (this.props.open) {
if (!this._layer) {
this._layer = document.createElement('div');
document.body.appendChild(this._layer);
}
this._bindClickAway();
if (this.reactUnmount) {
this.reactUnmount.cancel();
}
} else if (this._layer) {
this._unbindClickAway();
this._unrenderLayer();
} else {
return;
}
// By calling this method in componentDidMount() and
// componentDidUpdate(), you're effectively creating a "wormhole" that
// funnels React's hierarchical updates through to a DOM node on an
// entirely different part of the page.
const layerElement = this.props.render();
// Renders can return null, but React.render() doesn't like being asked
// to render null. If we get null back from renderLayer(), just render
// a noscript element, like React does when an element's render returns
// null.
if (layerElement === null) {
this.layerElement = ReactDOM.unstable_renderSubtreeIntoContainer (this, <noscript />, this._layer);
} else {
this.layerElement = ReactDOM.unstable_renderSubtreeIntoContainer(this, layerElement, this._layer);
}
},
_unrenderLayer: function() {
if (!this.reactUnmount)
this.reactUnmount = debounce(() => {
if (this._layer) {
if (this.layerWillUnmount) {
this.layerWillUnmount(this._layer);
}
ReactDOM.unmountComponentAtNode(this._layer);
document.body.removeChild(this._layer);
this._layer = null;
}
}, 1000);
this.reactUnmount();
},
_bindClickAway() {
if (typeof(this.canClickAway) === "undefined") {
this.canClickAway = true;
}
Events.on(window, 'focus', this._checkClickAway);
Events.on(document, 'mousedown', this._checkClickAway);
Events.on(document, 'touchend', this._checkClickAway);
Events.on(document, 'popOverOnShow', this._preventClickAway);
Events.on(document, 'popOverOnHide', this._allowClickAway);
},
_unbindClickAway() {
Events.off(window, 'focus', this._checkClickAway);
Events.off(document, 'mousedown', this._checkClickAway);
Events.off(document, 'touchend', this._checkClickAway);
Events.off(document, 'popOverOnShow', this._preventClickAway);
Events.off(document, 'popOverOnHide', this._allowClickAway);
},
});
export default RenderToLayer;
|
src/shared/types/react.js | amcsi/teamap | /* @flow */
// Note: we already have the definitions from
// https://github.com/facebook/flow/blob/master/lib/react.js
// so the below are merely helpful extensions.
import React from 'react';
export type ReactElement = React.Element<any>;
export type ReactNode = string | number | ReactElement | Array<ReactElement>;
export type ReactChild = ReactNode | boolean | void | null;
export type ReactChildren = ReactChild | Array<ReactChildren>;
|
actor-apps/app-web/src/app/components/modals/Preferences.react.js | luwei2012/actor-platform | import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
import PreferencesStore from 'stores/PreferencesStore';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isOpen: PreferencesStore.isModalOpen()
};
};
@ReactMixin.decorate(IntlMixin)
class PreferencesModal extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
PreferencesStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
PreferencesStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
PreferencesActionCreators.hide();
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
render() {
let menuItems = [
{ payload: '1', text: 'English' },
{ payload: '2', text: 'Russian' }
];
if (this.state.isOpen === true) {
return (
<Modal className="modal-new modal-new--preferences"
closeTimeoutMS={150}
isOpen={this.state.isOpen}
style={{width: 760}}>
<div className="modal-new__header">
<i className="modal-new__header__icon material-icons">settings</i>
<h3 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/>
</h3>
<div className="pull-right">
<FlatButton hoverColor="rgba(81,145,219,.17)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</div>
<div className="modal-new__body">
<div className="preferences">
<aside className="preferences__tabs">
<a className="preferences__tabs__tab preferences__tabs__tab--active">General</a>
<a className="preferences__tabs__tab">Notifications</a>
<a className="preferences__tabs__tab">Sidebar colors</a>
<a className="preferences__tabs__tab">Security</a>
<a className="preferences__tabs__tab">Other Options</a>
</aside>
<div className="preferences__body">
<div className="preferences__list">
<div className="preferences__list__item preferences__list__item--general">
<ul>
<li>
<i className="icon material-icons">keyboard</i>
<RadioButtonGroup defaultSelected="default" name="send">
<RadioButton label="Enter – send message, Shift + Enter – new line"
style={{marginBottom: 12}}
value="default"/>
<RadioButton label="Cmd + Enter – send message, Enter – new line"
//style={{marginBottom: 16}}
value="alt"/>
</RadioButtonGroup>
</li>
<li className="language">
<i className="icon material-icons">menu</i>
Language: <DropDownMenu labelStyle={{color: '#5191db'}}
menuItemStyle={{height: '40px', lineHeight: '40px'}}
menuItems={menuItems}
style={{verticalAlign: 'top', height: 52}}
underlineStyle={{display: 'none'}}/>
</li>
</ul>
</div>
<div className="preferences__list__item preferences__list__item--notifications">
<ul>
<li>
<i className="icon material-icons">notifications</i>
<RadioButtonGroup defaultSelected="all" name="notifications">
<RadioButton label="Notifications for activity of any kind"
style={{marginBottom: 12}}
value="all"/>
<RadioButton label="Notifications for Highlight Words and direct messages"
style={{marginBottom: 12}}
value="quiet"/>
<RadioButton label="Never send me notifications"
style={{marginBottom: 12}}
value="disable"/>
</RadioButtonGroup>
<p className="hint">
You can override your desktop notification preference on a case-by-case
basis for channels and groups from the channel or group menu.
</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default PreferencesModal;
|
subfind_web/ui/src/components/AdminLTE.js | thongdong7/subfind | import React from 'react'
export default class AdminLTE extends React.Component {
render() {
return (
<div className="container">
{this.props.children}
</div>
)
}
}
|
examples/src/components/NumericSelect.js | OpenGov/react-select | import React from 'react';
import createClass from 'create-react-class';
import PropTypes from 'prop-types';
import Select from 'react-select';
var ValuesAsNumbersField = createClass({
displayName: 'ValuesAsNumbersField',
propTypes: {
label: PropTypes.string
},
getInitialState () {
return {
options: [
{ value: 10, label: 'Ten' },
{ value: 11, label: 'Eleven' },
{ value: 12, label: 'Twelve' },
{ value: 23, label: 'Twenty-three' },
{ value: 24, label: 'Twenty-four' }
],
matchPos: 'any',
matchValue: true,
matchLabel: true,
value: null,
multi: false
};
},
onChangeMatchStart(event) {
this.setState({
matchPos: event.target.checked ? 'start' : 'any'
});
},
onChangeMatchValue(event) {
this.setState({
matchValue: event.target.checked
});
},
onChangeMatchLabel(event) {
this.setState({
matchLabel: event.target.checked
});
},
onChange(value) {
this.setState({ value });
console.log('Numeric Select value changed to', value);
},
onChangeMulti(event) {
this.setState({
multi: event.target.checked
});
},
render () {
var matchProp = 'any';
if (this.state.matchLabel && !this.state.matchValue) {
matchProp = 'label';
}
if (!this.state.matchLabel && this.state.matchValue) {
matchProp = 'value';
}
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select
matchPos={this.state.matchPos}
matchProp={matchProp}
multi={this.state.multi}
onChange={this.onChange}
options={this.state.options}
simpleValue
value={this.state.value}
/>
<div className="checkbox-list">
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.multi} onChange={this.onChangeMulti} />
<span className="checkbox-label">Multi-Select</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchValue} onChange={this.onChangeMatchValue} />
<span className="checkbox-label">Match value</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchLabel} onChange={this.onChangeMatchLabel} />
<span className="checkbox-label">Match label</span>
</label>
<label className="checkbox">
<input type="checkbox" className="checkbox-control" checked={this.state.matchPos === 'start'} onChange={this.onChangeMatchStart} />
<span className="checkbox-label">Only include matches from the start of the string</span>
</label>
</div>
<div className="hint">This example uses simple numeric values</div>
</div>
);
}
});
module.exports = ValuesAsNumbersField;
|
src/svg-icons/action/account-balance-wallet.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccountBalanceWallet = (props) => (
<SvgIcon {...props}>
<path d="M21 18v1c0 1.1-.9 2-2 2H5c-1.11 0-2-.9-2-2V5c0-1.1.89-2 2-2h14c1.1 0 2 .9 2 2v1h-9c-1.11 0-2 .9-2 2v8c0 1.1.89 2 2 2h9zm-9-2h10V8H12v8zm4-2.5c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
ActionAccountBalanceWallet = pure(ActionAccountBalanceWallet);
ActionAccountBalanceWallet.displayName = 'ActionAccountBalanceWallet';
export default ActionAccountBalanceWallet;
|
client/packages/core-dashboard-worona/src/dashboard/loading-dashboard-theme-worona/components/Theme/index.js | worona/worona | import React from 'react';
import Footer from '../Footer';
import styles from './style.css';
export const Theme = ({ children }) => (
<div className={styles.app}>
<div></div>
<div className={styles.main}>
{children}
</div>
<div className={styles.footer}>
<Footer />
</div>
</div>
);
Theme.propTypes = {
children: React.PropTypes.node.isRequired,
};
export default Theme;
|
frontend/src/components/forms/fields/projectFields/locationField/locationsMap.js | unicef/un-partner-portal |
import React, { Component } from 'react';
import R from 'ramda';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Place from 'material-ui-icons/Place';
import { Marker, Popup, ZoomControl } from "react-mapbox-gl";
import MapContainer from '../../../../common/map/MapContainer';
import { errorToBeAdded } from '../../../../../reducers/errorReducer';
import LocationsGeocoder from './locationsGeocoder';
const mbxGeocoding = require('@mapbox/mapbox-sdk/services/geocoding');
const geocodingClient = mbxGeocoding({ accessToken: process.env.MAP_BOX_KEY });
/**
* this component is controlled implementation of map.
* To work, it needs to recieve focused country name, than it will center and zoom to this
* specific country through geolocation.
* It supports clicking on the map to make save specific location, but only in selected country.
* The map is in controlled mode, that means it doesn't store locations, so it needs callbacks to
* manipulate location storage: saveLocation, removeLocation, removeAllLocations
* Markers, geolocation calls, search function, infoboxes are all controlled by this component
* itself.
* Model used to save location:
* {
* country_code
* admin_level_1: { name },
* lat
* lon
* formatted_address
* }
*/
const messages = {
error: 'Please indicate locations within the geographic boundaries of the selected country',
};
class LocationsMapBase extends Component {
constructor() {
super();
this.state = {
pos: null,
previousCountry: null,
activeMarker: null,
hoverMarker: null,
activeMarkerNumber: null,
activeLocation: null,
};
this.initMap = this.initMap.bind(this);
this.mapClicked = this.mapClicked.bind(this);
this.onMarkerOver = this.onMarkerOver.bind(this);
this.onMarkerOut = this.onMarkerOut.bind(this);
this.clearBounds = this.clearBounds.bind(this);
this.removeMarker = this.removeMarker.bind(this);
}
componentDidMount() {
const { currentCountry } = this.props;
if (currentCountry) {
this.initMap(currentCountry);
}
}
componentWillReceiveProps(nextProps) {
const { currentCountry } = this.props;
const nextCountry = nextProps.currentCountry;
if (currentCountry !== nextCountry) {
this.initMap(nextCountry);
}
}
onMarkerOut() {
this.setState({
activeLocation: null,
activeMarker: null,
});
}
onMarkerOver(lat, lon, admin) {
if (!this.state.activeLocation) {
this.setState({
activeLocation: { lat, lon, name: admin.name },
});
}
}
initMap(country) {
const { countries, removeAllLocations } = this.props;
if (this.state.previousCountry && this.state.previousCountry !== country && !this.props.readOnly) {
removeAllLocations();
}
let code;
if (!countries[country]) {
code = R.keys(countries)[R.indexOf(country, R.values(countries))]
}
geocodingClient.forwardGeocode({ query: countries[country] || country, limit: 1, countries: [code || country] })
.send()
.then(response => {
if (response.body.features.length > 0) {
const match = response.body.features[0];
this.setState({
pos: match.center,
bounds: match.bbox,
});
}
});
this.setState({ previousCountry: country });
}
clearBounds() {
this.setState({ rebound: false });
}
mapClicked(arg, clickEvent) {
const { readOnly, postError, currentCountryCode, saveLocation } = this.props;
if (!readOnly) {
geocodingClient.reverseGeocode({ query: [clickEvent.lngLat.lng, clickEvent.lngLat.lat], language: ['en'] })
.send()
.then(response => {
if (response.statusCode === 200) {
let region = R.filter(feature => feature.place_type[0] === 'region', response.body.features)[0];
let country = R.filter(feature => feature.place_type[0] === 'country', response.body.features)[0];
if (region && country && country.properties && currentCountryCode === country.properties.short_code.toUpperCase()) {
const newLocation = {
admin_level_1: {
name: region.text_en,
country_code: currentCountryCode
},
lat: clickEvent.lngLat.lat.toFixed(5),
lon: clickEvent.lngLat.lng.toFixed(5),
};
saveLocation(newLocation);
} else {
postError(messages.error);
}
} else {
postError(messages.error);
}
});
}
}
removeMarker(index) {
const { removeLocation, readOnly } = this.props;
this.setState({
activeLocation: null,
});
if (!readOnly) {
removeLocation(index);
}
}
render() {
const { showMap, locations, readOnly } = this.props;
const {
pos,
bounds,
activeLocation,
} = this.state;
return (pos && showMap && <MapContainer
center={pos}
bounds={bounds}
onClick={this.mapClicked}
>
{!readOnly && <LocationsGeocoder />}
<ZoomControl position="bottom-right" />
{locations && locations.map(({ lat, lon, admin_level_1 }, index) => (
<Marker onClick={(event) => this.removeMarker(index)}
onMouseEnter={() => this.onMarkerOver(lat, lon, admin_level_1)}
onMouseLeave={this.onMarkerOut} coordinates={[lon, lat]} key={index} anchor="bottom">
<Place color="accent" />
</Marker>
))}
{activeLocation
&& <Popup
coordinates={[activeLocation.lon, activeLocation.lat]}
offset={{ 'bottom-left': [12, -38], 'bottom': [0, -38], 'bottom-right': [-12, -38] }}>
{activeLocation.name}
</Popup>}
</MapContainer>
);
}
}
LocationsMapBase.propTypes = {
/**
* country code of currently focused country, used to disable clicking on other countries
*/
currentCountryCode: PropTypes.string,
/**
* focused country full name used for geolocation to reduce disambiguation
*/
currentCountry: PropTypes.string,
/**
* selected locations array, as map is controlled-only
*/
locations: PropTypes.array,
/**
* callback to save single location in external storage, fired when map is clicked
*/
saveLocation: PropTypes.func,
/**
* calllback to remove location from external storage, fired when marker is removed by double-tap
*/
removeLocation: PropTypes.func,
/**
* callback to remove all locations from external storage, fired when main country switches
*/
removeAllLocations: PropTypes.func,
/**
* bool to show map (also focused country name is required to show map)
*/
showMap: PropTypes.bool,
/**
* bool to disable map clicks to read only mode
*/
readOnly: PropTypes.bool,
/**
* function to save error in redux and display snackbar
*/
postError: PropTypes.func,
countries: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
countries: state.countries,
})
const mapDispatchToProps = (dispatch, ownProps) => ({
postError: error => dispatch(errorToBeAdded(
error, `pinNotAdded${ownProps.activeMarkercurrentCountryCode}`, messages.error)),
});
export default connect(mapStateToProps, mapDispatchToProps)(LocationsMapBase);
|
node_modules/react-spinner-children/utils/tester.js | caughtclean/but-thats-wrong-blog | import TestUtils from 'react-addons-test-utils';
import React from 'react';
const jsdom = require('jsdom');
function renderComponent(react, props) {
global.document = jsdom.jsdom('<!DOCTYPE html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};
const rendered = TestUtils.renderIntoDocument(React.createElement(react, props));
return TestUtils.findRenderedComponentWithType(rendered, react);
}
export function renderJSX(jsx, context) {
return renderComponent(React.createClass({
displayName: 'TestJSX',
render: () => jsx,
}), undefined, context);
}
|
docs/pages/performance/table-emotion.js | lgollut/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import styled from '@emotion/styled';
import NoSsr from '@material-ui/core/NoSsr';
const createComponent = (defaultComponent) => {
const MyComponent = React.forwardRef(function MyComponent(props, ref) {
const { component: Component = defaultComponent, ...other } = props;
return <Component ref={ref} {...other} />;
});
MyComponent.propTypes = {
component: PropTypes.elementType,
};
return styled(MyComponent)`
background: pink;
`;
};
const Table = createComponent('table');
const TableHead = createComponent('thead');
const TableRow = createComponent('tr');
const TableCell = createComponent('td');
const TableBody = createComponent('tbody');
const data = { name: 'Frozen yoghurt', calories: 159, fat: 6.0, carbs: 24, protein: 4.0 };
const rows = Array.from(new Array(100)).map(() => data);
function TableEmotion() {
return (
<NoSsr defer>
<Table>
<TableHead>
<TableRow>
<TableCell>Dessert (100g serving)</TableCell>
<TableCell>Calories</TableCell>
<TableCell>Fat (g)</TableCell>
<TableCell>Carbs (g)</TableCell>
<TableCell>Protein (g)</TableCell>
</TableRow>
</TableHead>
<TableBody>
{rows.map((row, index) => (
<TableRow key={index}>
<TableCell component="th" scope="row">
{row.name}
</TableCell>
<TableCell>{row.calories}</TableCell>
<TableCell>{row.fat}</TableCell>
<TableCell>{row.carbs}</TableCell>
<TableCell>{row.protein}</TableCell>
</TableRow>
))}
</TableBody>
</Table>
</NoSsr>
);
}
export default TableEmotion;
|
frontend/react-stack/react/aluraflix/src/components/Menu/index.js | wesleyegberto/courses-projects | // must be import to be in scope
import React from 'react';
import { Link } from 'react-router-dom';
import './menu.css';
import ButtonLink from './components/ButtonLink';
import Logo from '../../assets/img/LogoMain.png';
// Long way: recommended when there is state
// class Menu extends React.Component {
// render() {
// return (
// <div>
// <nav>
// AluraFlix!
// </nav>
// </div>
// );
// }
// }
function Menu() {
return (
<nav className="Menu">
<Link to="/">
<img className="Logo" src={Logo} alt="AluraFlix" />
</Link>
<ButtonLink href="/novo-video" className="ButtonLink">
Novo Vídeo
</ButtonLink>
</nav>
);
}
export default Menu;
|
client/modules/Post/__tests__/components/PostCreateWidget.spec.js | vibhas77/Student-Wallet | import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { FormattedMessage } from 'react-intl';
import { PostCreateWidget } from '../../components/PostCreateWidget/PostCreateWidget';
import { mountWithIntl, shallowWithIntl } from '../../../../util/react-intl-test-helper';
const props = {
addPost: () => {},
showAddPost: true,
};
test('renders properly', t => {
const wrapper = shallowWithIntl(
<PostCreateWidget {...props} />
);
t.truthy(wrapper.hasClass('form'));
t.truthy(wrapper.hasClass('appear'));
t.truthy(wrapper.find('h2').first().containsMatchingElement(<FormattedMessage id="createNewPost" />));
t.is(wrapper.find('input').length, 2);
t.is(wrapper.find('textarea').length, 1);
});
test('hide when showAddPost is false', t => {
const wrapper = mountWithIntl(
<PostCreateWidget {...props} />
);
wrapper.setProps({ showAddPost: false });
t.falsy(wrapper.hasClass('appear'));
});
test('has correct props', t => {
const wrapper = mountWithIntl(
<PostCreateWidget {...props} />
);
t.is(wrapper.prop('addPost'), props.addPost);
t.is(wrapper.prop('showAddPost'), props.showAddPost);
});
test('calls addPost', t => {
const addPost = sinon.spy();
const wrapper = mountWithIntl(
<PostCreateWidget addPost={addPost} showAddPost />
);
wrapper.ref('name').get(0).value = 'David';
wrapper.ref('title').get(0).value = 'Some Title';
wrapper.ref('content').get(0).value = 'Bla Bla Bla';
wrapper.find('a').first().simulate('click');
t.truthy(addPost.calledOnce);
t.truthy(addPost.calledWith('David', 'Some Title', 'Bla Bla Bla'));
});
test('empty form doesn\'t call addPost', t => {
const addPost = sinon.spy();
const wrapper = mountWithIntl(
<PostCreateWidget addPost={addPost} showAddPost />
);
wrapper.find('a').first().simulate('click');
t.falsy(addPost.called);
});
|
src/components/controller/AppController.js | DataKind-BLR/antara | import React from 'react';
import RightSidebar from '../views/rightsidebar/RightSidebar';
import ReportView from "../views/reportview/ReportView";
import { appController } from "../ConfigMap";
class AppController extends React.Component {
constructor(props) {
super(props);
this.state = {
heirarchyLevel : this.props.params.heirarchy_level,
categorySlug : this.props.params.category,
recordSlug : this.props.params.record,
series : this.props.route.panelName,
viewBy: "choropleth",
budgetAttr : "BE",
categoryName :null,
sectorSelected:null,
recordData: null,
sectorName:null,
recordNotes : null,
addtional_details : null
};
this.handleChange = this.handleChange.bind(this);
this.onChangeBudgetAttr =this.onChangeBudgetAttr.bind(this);
this.setCategoryName = this.setCategoryName.bind(this);
//this.setNotes = this.setNotes.bind(this);
this.setCategorySlug = this.setCategorySlug.bind(this);
this.setRecordSlug = this.setRecordSlug.bind(this);
this.setRecordData = this.setRecordData.bind(this);
this.setYearChange = this.setYearChange.bind(this);
//this.setAdditionalDetails = this.setAdditionalDetails.bind(this);
}
componentWillMount(){
this.setCategoryName();
this.setRecordData();
this.setState({heirarchyLevel : this.props.params.heirarchy_level,
categorySlug : this.props.params.category,
recordSlug : this.props.params.record,
series : this.props.route.panelName});
//this.setNotes();
//this.setAdditionalDetails();
}
componentDidUpdate(prevProps, prevState) {
if(prevState.categorySlug != this.props.params.category && this.props.params.heirarchy_level == 2){
this.setCategorySlug();
this.setCategoryName();
}
if(prevState.recordSlug != this.props.params.record || prevState.categorySlug != this.props.params.category){
this.setRecordSlug();
this.setRecordData();
}
if(prevState.categorySlug != this.props.params.category || prevState.recordSlug != this.props.params.record || prevState.heirarchyLevel != this.props.params.heirarchy_level){
//this.setNotes();
}
if(prevProps.params.category != this.props.params.category && this.state.heirarchyLevel == 2){
//this.setAdditionalDetails();
}
if(prevProps.params.record != this.props.params.record && this.state.heirarchyLevel == 1){
//this.setAdditionalDetails();
}
}
setCategorySlug(){
this.setState({categorySlug:this.props.params.category});
}
setRecordSlug(){
this.setState({recordSlug:this.props.params.record});
}
setRecordData(){
let currentState = this.state;
if(this.props.params.heirarchy_level == 2 ){
let recordData = appController.dataseries.find(function(series){
return series.title_slug == currentState.series;
}).data.find(function(category){
return category.category_slug == currentState.categorySlug;
}).sub_records.find(function(record){
return record.record_slug == currentState.recordSlug;
});
this.setState({recordData:recordData});
}
else
{
let recordData = appController.dataseries.find(function(series){
return series.title_slug == currentState.series;
}).data.find(function(record){
return record.record_slug == currentState.recordSlug;
});
this.setState({recordData:recordData});
}
}
setCategoryName(){
let currentState = this.state;
let categoryName = appController.dataseries.find(function(series){
if (series.title_slug == currentState.series)
{
return series;
}
}).data.find(function(category){
if(category.category_slug == currentState.categorySlug){
return category;
}
}).category_name;
this.setState({categoryName:categoryName});
}
setNotes(){
let currentState = this.state;
let currentProps = this.props;
if(this.props.params.heirarchy_level == 2 ){
let recordNotes = appController.dataseries.find(function(series){
return series.title_slug == currentState.series;
}).meta_data.find(function(record){
return (record.category_slug == currentProps.params.category && record.record_slug == currentProps.params.record);
});
this.setState({recordNotes:recordNotes});
}
if(this.props.params.heirarchy_level == 1 ){
let recordNotes = appController.dataseries.find(function(series){
{
return series.title_slug == currentState.series;
}
}).meta_data.find(function(record){
{
return record.record_slug == currentProps.params.record;
}
});
this.setState({recordNotes:recordNotes});
}
}
setAdditionalDetails(){
let currentState = this.state;
let currentProps = this.props;
if(this.props.params.heirarchy_level == 2 ){
let additionalDetails = appController.dataseries.find(function(series){
return series.title_slug == currentState.series;
}).addtional_meta_data.find(function(category){
return (category.category_slug == currentProps.params.category);
});
this.setState({addtional_details:additionalDetails});
}
else{
let additionalDetails = appController.dataseries.find(function(series){
return series.title_slug == currentState.series;
}).addtional_meta_data.find(function(record){
return (record.record_slug == currentProps.params.record);
});
this.setState({addtional_details:additionalDetails});
}
}
handleChange(value){
this.setState({ viewBy: value });
}
onChangeBudgetAttr(value){
this.setState({ budgetAttr :value});
}
setYearChange(value){
this.setState({selectedYear:value});
}
/*
additionalDetails={this.state.addtional_details}
*/
render() {
return (
<div>
<div className = "col-lg-10" >
<ReportView heirarchyLevel={this.state.heirarchyLevel}
category={this.state.categoryName}
record={this.state.recordData}
recordName={this.state.recordData.record_name}
budgetAttr={this.state.budgetAttr}
viewBy={this.state.viewBy}
recordNotes={this.state.recordNotes}
setYearChange={this.setYearChange}
selectedYear={this.state.selectedYear}
/>
</div>
<div className = "col-lg-2 rightsidebar" >
<RightSidebar viewByChange={this.handleChange} budgetAttrChange={this.onChangeBudgetAttr}/>
</div>
</div>
);
}
}
AppController.propTypes = {
params: React.PropTypes.object,
route: React.PropTypes.object
};
export default AppController;
|
app/javascript/mastodon/features/mutes/index.js | KnzkDev/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountContainer from '../../containers/account_container';
import { fetchMutes, expandMutes } from '../../actions/mutes';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.mutes', defaultMessage: 'Muted users' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'mutes', 'items']),
hasMore: !!state.getIn(['user_lists', 'mutes', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Mutes extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
hasMore: PropTypes.bool,
accountIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchMutes());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandMutes());
}, 300, { leading: true });
render () {
const { intl, shouldUpdateScroll, hasMore, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.mutes' defaultMessage="You haven't muted any users yet." />;
return (
<Column icon='volume-off' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='mutes'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
>
{accountIds.map(id =>
<AccountContainer key={id} id={id} />
)}
</ScrollableList>
</Column>
);
}
}
|
analysis/demonhuntervengeance/src/modules/talents/SoulBarrier.js | anom0ly/WoWAnalyzer | import { t } from '@lingui/macro';
import { formatPercentage, formatNumber } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import DamageTracker from 'parser/shared/modules/AbilityTracker';
import Enemies from 'parser/shared/modules/Enemies';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import TalentStatisticBox from 'parser/ui/TalentStatisticBox';
import React from 'react';
class SoulBarrier extends Analyzer {
get uptime() {
return (
this.selectedCombatant.getBuffUptime(SPELLS.SOUL_BARRIER_TALENT.id) / this.owner.fightDuration
);
}
get suggestionThresholdsEfficiency() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.35,
average: 0.3,
major: 0.25,
},
style: 'percentage',
};
}
static dependencies = {
damageTracker: DamageTracker,
enemies: Enemies,
};
casts = 0;
totalAbsorbed = 0;
buffApplied = 0;
buffRemoved = 0;
buffLength = 0;
avgBuffLength = 0;
totalBuffLength = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SOUL_BARRIER_TALENT.id);
this.addEventListener(
Events.applybuff.to(SELECTED_PLAYER).spell(SPELLS.SOUL_BARRIER_TALENT),
this.onApplyBuff,
);
this.addEventListener(
Events.absorbed.to(SELECTED_PLAYER).spell(SPELLS.SOUL_BARRIER_TALENT),
this.onAbsorb,
);
this.addEventListener(
Events.removebuff.to(SELECTED_PLAYER).spell(SPELLS.SOUL_BARRIER_TALENT),
this.onRemoveBuff,
);
}
onApplyBuff(event) {
this.casts += 1;
this.buffApplied = event.timestamp;
}
onAbsorb(event) {
this.totalAbsorbed += event.amount;
}
onRemoveBuff(event) {
if (event.ability.guid !== SPELLS.SOUL_BARRIER_TALENT.id) {
return;
}
this.buffRemoved = event.timestamp;
this.buffLength = this.buffRemoved - this.buffApplied;
this.totalBuffLength += this.buffLength;
}
suggestions(when) {
when(this.suggestionThresholdsEfficiency).addSuggestion((suggest, actual, recommended) =>
suggest(
<>
Your uptime with <SpellLink id={SPELLS.SOUL_BARRIER_TALENT.id} /> can be improved.
</>,
)
.icon(SPELLS.SOUL_BARRIER_TALENT.icon)
.actual(
t({
id: 'demonhunter.vengeance.suggestions.soulBarrier.uptime',
message: `${formatPercentage(actual)}% Soul Barrier`,
}),
)
.recommended(`>${formatPercentage(recommended)}% is recommended`),
);
}
statistic() {
const avgBuffLength = this.totalBuffLength / this.casts / 1000;
return (
<TalentStatisticBox
talent={SPELLS.SOUL_BARRIER_TALENT.id}
position={STATISTIC_ORDER.CORE(7)}
value={`${formatPercentage(this.uptime)} %`}
label="Soul Barrier uptime"
tooltip={
<>
Average Buff Length: <strong>{formatNumber(avgBuffLength)} seconds</strong>
<br />
Total Damage Absorbed: <strong>{formatNumber(this.totalAbsorbed)}</strong>
<br />
Healing <strong>{this.owner.formatItemHealingDone(this.totalAbsorbed)}</strong>
<br />
Total Casts: <strong>{this.casts}</strong>
</>
}
/>
);
}
}
export default SoulBarrier;
|
node_modules/react-router/es6/Link.js | dwmorrisdev/ReactWeather | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object]),
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
};
},
handleClick: function handleClick(event) {
if (this.props.onClick) this.props.onClick(event);
if (event.defaultPrevented) return;
!this.context.router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0;
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) return;
event.preventDefault();
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(location);
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0;
// Ignore if rendered outside the context of router, simplifies unit testing.
var router = this.context.router;
if (router) {
// If user does not specify a `to` prop, return an empty anchor tag.
if (to == null) {
return React.createElement('a', props);
}
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(location);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(location, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ' ' + activeClassName;
} else {
props.className = activeClassName;
}
}
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link; |
src/components/Timekit-Calendar.js | sogalutira/PollerBears | import React, { Component } from 'react';
import TimekitBooking from 'timekit-booking';
import Livemap from '../components/Map';
require('jquery');
const widget = new TimekitBooking();
class TimekitCalendar extends Component{
componentDidMount(){
console.log(Livemap);
console.log(document.getElementsByClassName("email"));
widget.init({
widgetId: '9c9f7906-99d7-4008-9719-e8bbb2044dd1',
callbacks: {
findTimeStarted: function(args) { console.log('findTimeStarted', args); },
findTimeSuccessful: function(response) { console.log('findTimeSuccessful', response); },
findTimeFailed: function(response) { console.log('findTimeFailed', response); },
createBookingStarted: function(args) { console.log('createBookingStarted', args); },
createBookingSuccessful: function(response) { console.log('createBookingSuccessful', response); },
createBookingFailed: function(response) { console.log('createBookingFailed', response); },
getUserTimezoneStarted: function(args) { console.log('getUserTimezoneStarted', args); },
getUserTimezoneSuccesful: function(response) { console.log('getUserTimezoneSuccesful', response); },
getUserTimezoneFailed: function(response) { console.log('getUserTimezoneFailed', response); },
fullCalendarInitialized: function() { console.log('fullCalendarInitialized'); },
renderCompleted: function() { console.log('renderCompleted'); },
showBookingPage: function(slot) { console.log('showBookingPage', slot); },
closeBookingPage: function() { console.log('closeBookingPage'); },
submitBookingForm: function(values) { console.log('submitBookingForm', values); }
}
});
var divElem = document.createElement('DIV');
divElem = widget;
console.log(divElem);
}
render(){
return (
<div>Hello</div>
);
}
}
export default TimekitCalendar; |
src/interface/news/RegularArticle.js | FaideWW/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Contributor from 'interface/contributor/Button';
import makeNewsUrl from 'interface/news/makeUrl';
class RegularArticle extends React.PureComponent {
static propTypes = {
title: PropTypes.node.isRequired,
children: PropTypes.node.isRequired,
bodyStyle: PropTypes.object,
publishedAt: PropTypes.string.isRequired,
publishedBy: PropTypes.shape({
nickname: PropTypes.string.isRequired,
}).isRequired,
};
render() {
const { title, children, bodyStyle, publishedAt, publishedBy } = this.props;
return (
<article>
<div className="panel">
<div className="panel-heading">
<Link to={makeNewsUrl(title)} className="hidden-link"><h2>{title}</h2></Link>
</div>
<div className="panel-body" style={bodyStyle}>
{children}
<div style={{ marginTop: '1em' }}>
Published at {publishedAt} by <Contributor {...publishedBy} />.
</div>
</div>
</div>
</article>
);
}
}
export default RegularArticle;
|
docs/app/Examples/collections/Table/Variations/TableExampleFixed.js | koenvg/Semantic-UI-React | import React from 'react'
import { Table } from 'semantic-ui-react'
const TableExampleFixed = () => {
return (
<Table fixed>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Status</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>John</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>
John is an interesting boy but sometimes you don't really have enough room to describe everything you'd like
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>
Jamie is a kind girl but sometimes you don't really have enough room to describe everything you'd like
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jill</Table.Cell>
<Table.Cell>Denied</Table.Cell>
<Table.Cell>
Jill is an alright girl but sometimes you don't really have enough room to describe everything you'd like
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
)
}
export default TableExampleFixed
|
react-ui/src/components/Footer/Footer.js | morewines/refund-calculator-bigcommerce | import React from 'react';
// CSS
import './Footer.css';
const Footer = () => (
<footer className="footer-wrap">
<div className="container">
Built by{' '}
<a href="http://andrewmaidah.com/" target="_blank">
AM
</a>{' '}
for{' '}
<a href="https://www.morewines.com" target="_blank">
MoreWines
</a>
</div>
</footer>
);
export default Footer;
|
src/views/clubLayout/Disconnected/Disconnected.js | BudIT/vclub | import React from 'react';
import styles from './Disconnected.css';
export default function Disconnected() {
return (
<div className={styles.container}>
<span>Приложение было отключенно от сервера. Обновите страницу или попробуйте позже.</span>
</div>
);
}
|
index.js | pillys/react-native-html5 | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
Linking,
PixelRatio,
} from 'react-native';
import htmlparser from './lib/htmlparser';
const ratio = PixelRatio.get();
const InlineTags = ['b','font','i','em','big','strong','small','sub','sup','u','ins','mark','code','address','del','s','strike','a','label','span', 'br'];
const defaultStyle = {
h1: {
fontWeight: '500',
fontSize: 36,
marginVertical: 5,
},
h2: {
fontWeight: '500',
fontSize: 30,
marginVertical: 5,
},
h3: {
fontWeight: '500',
fontSize: 24,
marginVertical: 5,
},
h4: {
fontWeight: '500',
fontSize: 18,
marginVertical: 5,
},
h5: {
fontWeight: '500',
fontSize: 14,
marginVertical: 5,
},
h6: {
fontWeight: '500',
fontSize: 12,
marginVertical: 10,
},
a: {
color: '#007aff',
fontWeight: '500',
},
b: {
fontWeight: 'bold',
},
strong: {
fontWeight: 'bold',
},
i: {
fontStyle: 'italic',
},
em: {
fontStyle: 'italic',
},
big: {
fontSize: 16,
},
small: {
fontSize: 10,
},
u: {
textDecorationLine: 'underline',
textDecorationStyle: 'solid',
},
ins: {
textDecorationLine: 'underline',
textDecorationStyle: 'solid',
},
del: {
textDecorationLine: 'line-through',
textDecorationStyle: 'solid',
},
s: {
textDecorationLine: 'line-through',
textDecorationStyle: 'solid',
},
strike: {
textDecorationLine: 'line-through',
textDecorationStyle: 'solid',
},
mark: {
backgroundColor: '#fcf8e3',
borderRadius: 3,
},
code: {
fontFamily: 'Menlo',
color: '#c9314e',
backgroundColor: '#faf3f4',
borderRadius: 3,
},
blockquote: {
borderLeftWidth: 5,
borderLeftColor: '#eeeeee',
paddingVertical: 5,
paddingHorizontal: 10,
},
p: {
marginVertical: 5,
},
};
const defaultExternalStyle = {
p: {
textIndent: 0,
}
};
export default class Html5 extends Component {
constructor(props) {
super(props);
this.state = {};
}
componentDidMount() {
this.parse();
}
parse() {
var handler = new htmlparser.DefaultHandler((err, doms) => {
if(err) {
console.log(err);
} else {
this.setState({
doms: doms
});
}
}, {
ignoreWhitespace: true
});
var parser = new htmlparser.Parser(handler);
parser.parseComplete(this.props.rawHtml.trim());
}
unescapeHTML(source) {
return source
.replace(/</g, '<')
.replace(/>/g, '>')
.replace(/ /g, ' ')
.replace(/"/g, '"')
.replace(/&/g, '&')
.replace(/©/g, '©');
}
compile(doms) {
var styleSheet = this.props.styleSheet || {};
var externalStyleSheet = this.props.externalStyleSheet || {};
return doms.map((dom, index) => {
if(dom.type === 'tag') {
let style = Object.assign({}, defaultStyle[dom.name], styleSheet[dom.name]);
let externalStyle = Object.assign({}, defaultExternalStyle[dom.name], externalStyleSheet[dom.name]);
switch(dom.name) {
case 'img':
if(dom.attribs.width) {
style.width = parseInt(dom.attribs.width);
}
if(dom.attribs.height) {
style.height = parseInt(dom.attribs.height);
}
return (
<XImage
key={index}
source={{uri: dom.attribs.src, }}
style={style}
resizeMode={Image.resizeMode.strech}
/>
);
case 'font':
case 'i':
case 'em':
case 'b':
case 'strong':
case 'big':
case 'small':
case 'sub':
case 'sup':
case 'mark':
case 'code':
case 'u':
case 'ins':
case 'del':
case 's':
case 'strike':
case 'span':
case 'time':
case 'label':
case 'h1':
case 'h2':
case 'h3':
case 'h4':
case 'h5':
case 'h6':
return (
<Text
key={index}
style={style}
>{this.compile(dom.children)}</Text>
);
case 'a':
return (
<Text
key={index}
style={style}
onPress={() => Linking.openURL(dom.attribs.href)}
>{this.compile(dom.children)}</Text>
);
case 'br':
return (
<Text key={index}>{'\n'}</Text>
);
default:
let blockChild = dom.children.find(child => {
return child.type !== 'text' && !InlineTags.includes(child.name);
});
//\u3000
if(blockChild) {
return (
<View
key={index}
style={style}
>{this.compile(dom.children)}</View>
);
} else {
if(dom.name === 'p') {
return (
<View
key={index}
style={style}
>
<Text>
<Text>{' '.repeat(externalStyle.textIndent)}</Text>
{this.compile(dom.children)}
</Text>
</View>
);
} else {
return (
<View
key={index}
style={style}
>
<Text>
{this.compile(dom.children)}
</Text>
</View>
);
}
}
}
} else if(dom.type === 'text') {
return (
<Text key={index}>{this.unescapeHTML(dom.data)}</Text>
);
} else {
return (
<View key={index}>{this.compile(dom.children)}</View>
);
}
});
}
render() {
if(!this.state.doms) {
return (
<View></View>
);
} else {
return (
<View>
{this.compile(this.state.doms)}
</View>
);
}
}
}
class XImage extends Component {
constructor(props) {
super(props);
this.state = {
loaded: false,
};
}
componentDidMount() {
this.fetch();
}
fetch() {
var { style } = this.props;
if(style.width && style.height) {
this.setState({
width: style.width,
height: style.height,
loaded: true
});
} else {
Image.getSize(this.props.source.uri, (width, height) => {
this.setState({
width: width / ratio,
height: height / ratio,
loaded: true
});
});
}
}
render() {
if(!this.state.loaded) {
return <Text></Text>;
} else {
var size = {
width: this.state.width,
height: this.state.height,
};
Object.assign(this.props.style, size);
return (
<Image
{...this.props}
/>
);
}
}
} |
src/svg-icons/hardware/keyboard-backspace.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardBackspace = (props) => (
<SvgIcon {...props}>
<path d="M21 11H6.83l3.58-3.59L9 6l-6 6 6 6 1.41-1.41L6.83 13H21z"/>
</SvgIcon>
);
HardwareKeyboardBackspace = pure(HardwareKeyboardBackspace);
HardwareKeyboardBackspace.displayName = 'HardwareKeyboardBackspace';
HardwareKeyboardBackspace.muiName = 'SvgIcon';
export default HardwareKeyboardBackspace;
|
src/svg-icons/image/image.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageImage = (props) => (
<SvgIcon {...props}>
<path d="M21 19V5c0-1.1-.9-2-2-2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2zM8.5 13.5l2.5 3.01L14.5 12l4.5 6H5l3.5-4.5z"/>
</SvgIcon>
);
ImageImage = pure(ImageImage);
ImageImage.displayName = 'ImageImage';
ImageImage.muiName = 'SvgIcon';
export default ImageImage;
|
app/app.js | dfmcphee/pinnr | import React from 'react';
import { Link } from 'react-router';
import { Button, Container, Menu, Segment } from 'semantic-ui-react';
import AuthenticationStore from './stores/authentication-store';
export default class App extends React.Component {
constructor(props) {
super(props);
this.state = {
authenticated: false
}
AuthenticationStore.init();
}
updateAuthentication() {
this.setState({
authenticated: AuthenticationStore.isAuthenticated(),
user: AuthenticationStore.getUser()
});
}
componentDidMount() {
AuthenticationStore.addChangeListener(() => this.updateAuthentication())
}
componentWillUnmount() {
AuthenticationStore.removeChangeListener(() => this.updateAuthentication())
}
logout() {
AuthenticationStore.logout();
}
authenticatedMenu() {
if (!this.state.authenticated) {
return;
}
return (
<Menu inverted pointing secondary>
<Link to="/groups" className="item" activeClassName='active'>My groups</Link>
<Link to="/add" className="item" activeClassName='active'>Add group</Link>
<Menu.Menu position='right'>
<Button primary className="item" onClick={() => this.logout()}>Logout</Button>
</Menu.Menu>
</Menu>
);
}
unauthenticatedMenu() {
if (this.state.authenticated) {
return;
}
return (
<Menu inverted pointing secondary>
<Menu.Menu position='right'>
<Link to="/login" className="item" activeClassName='active'>Login</Link>
<Link to="/signup" className="item" activeClassName='active'>Signup</Link>
</Menu.Menu>
</Menu>
);
}
render() {
return (
<div>
<Segment basic inverted>
{this.authenticatedMenu()}
{this.unauthenticatedMenu()}
</Segment>
<Container>
<section>
{this.props.children}
</section>
</Container>
</div>
);
}
}
|
packages/wix-style-react/src/Slider/test/Slider.visual.js | wix/wix-style-react | import React from 'react';
import { storiesOf } from '@storybook/react';
import Slider from '../Slider';
import Box from '../../Box';
import { Cell, Layout } from '../../Layout';
const commonProps = {
min: 0,
max: 10,
value: 4,
displayMarks: false,
onChange: e => e,
};
const tests = [
{
describe: '',
its: [
{
it: 'default',
props: {},
},
{
it: 'disabled',
props: {
disabled: true,
},
},
{
it: 'displayMarks',
props: {
displayMarks: true,
},
},
{
it: 'step = 2',
props: {
step: 2,
displayMarks: true,
},
},
{
it: 'custom marks',
props: {
marks: {
0: '$0',
2: '$79',
4: '$129',
6: '$199',
8: '$349',
10: '$499',
},
displayMarks: true,
},
},
{
it: 'start point',
props: { startPoint: 4, displayMarks: true },
},
],
},
];
tests.forEach(({ describe, its }) => {
its.forEach(({ it, props, container }) => {
storiesOf(`Slider${describe ? '/' + describe : ''}`, module).add(it, () => (
<Box direction={'vertical'}>
{[0, 4, 10].map((value, key) => (
<Box key={key} margin={4} {...container}>
<Layout>
<Cell>
<Slider {...commonProps} {...props} value={value} />
</Cell>
</Layout>
</Box>
))}
</Box>
));
});
});
|
openex-front/src/private/components/exercises/injects/InjectAddAudiences.js | Luatix/OpenEx | import React, { Component } from 'react';
import * as PropTypes from 'prop-types';
import { connect } from 'react-redux';
import * as R from 'ramda';
import Button from '@mui/material/Button';
import Chip from '@mui/material/Chip';
import List from '@mui/material/List';
import ListItem from '@mui/material/ListItem';
import ListItemText from '@mui/material/ListItemText';
import Dialog from '@mui/material/Dialog';
import DialogTitle from '@mui/material/DialogTitle';
import DialogContent from '@mui/material/DialogContent';
import DialogActions from '@mui/material/DialogActions';
import {
CastForEducationOutlined,
ControlPointOutlined,
} from '@mui/icons-material';
import Box from '@mui/material/Box';
import withStyles from '@mui/styles/withStyles';
import { ListItemIcon } from '@mui/material';
import Grid from '@mui/material/Grid';
import SearchFilter from '../../../../components/SearchFilter';
import inject18n from '../../../../components/i18n';
import { storeHelper } from '../../../../actions/Schema';
import { fetchAudiences } from '../../../../actions/Audience';
import CreateAudience from '../audiences/CreateAudience';
import { truncate } from '../../../../utils/String';
import { isExerciseReadOnly } from '../../../../utils/Exercise';
import { Transition } from '../../../../utils/Environment';
import TagsFilter from '../../../../components/TagsFilter';
import ItemTags from '../../../../components/ItemTags';
const styles = (theme) => ({
createButton: {
position: 'fixed',
bottom: 30,
right: 30,
},
box: {
width: '100%',
minHeight: '100%',
padding: 20,
border: '1px dashed rgba(255, 255, 255, 0.3)',
},
chip: {
margin: '0 10px 10px 0',
},
item: {
paddingLeft: 10,
height: 50,
},
text: {
fontSize: 15,
color: theme.palette.primary.main,
fontWeight: 500,
},
});
class InjectAddAudiences extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
keyword: '',
audiencesIds: [],
tags: [],
};
}
componentDidMount() {
this.props.fetchAudiences(this.props.exerciseId);
}
handleOpen() {
this.setState({ open: true });
}
handleClose() {
this.setState({ open: false, keyword: '', audiencesIds: [] });
}
handleSearchAudiences(value) {
this.setState({ keyword: value });
}
handleAddTag(value) {
if (value) {
this.setState({ tags: [value] });
}
}
handleClearTag() {
this.setState({ tags: [] });
}
addAudience(audienceId) {
this.setState({
audiencesIds: R.append(audienceId, this.state.audiencesIds),
});
}
removeAudience(audienceId) {
this.setState({
audiencesIds: R.filter((u) => u !== audienceId, this.state.audiencesIds),
});
}
submitAddAudiences() {
this.props.handleAddAudiences(this.state.audiencesIds);
this.handleClose();
}
onCreate(result) {
this.addAudience(result);
}
render() {
const {
classes,
t,
audiences,
injectAudiencesIds,
exerciseId,
exercise,
audiencesMap,
} = this.props;
const { keyword, audiencesIds, tags } = this.state;
const filterByKeyword = (n) => keyword === ''
|| (n.audience_name || '').toLowerCase().indexOf(keyword.toLowerCase())
!== -1
|| (n.audience_description || '')
.toLowerCase()
.indexOf(keyword.toLowerCase()) !== -1;
const filteredAudiences = R.pipe(
R.filter(
(n) => tags.length === 0
|| R.any(
(filter) => R.includes(filter, n.audience_tags),
R.pluck('id', tags),
),
),
R.filter(filterByKeyword),
R.take(10),
)(audiences);
return (
<div>
<ListItem
classes={{ root: classes.item }}
button={true}
divider={true}
onClick={this.handleOpen.bind(this)}
color="primary"
disabled={isExerciseReadOnly(exercise)}
>
<ListItemIcon color="primary">
<ControlPointOutlined color="primary" />
</ListItemIcon>
<ListItemText
primary={t('Add target audiences')}
classes={{ primary: classes.text }}
/>
</ListItem>
<Dialog
open={this.state.open}
TransitionComponent={Transition}
onClose={this.handleClose.bind(this)}
fullWidth={true}
maxWidth="lg"
PaperProps={{
elevation: 1,
sx: {
minHeight: 580,
maxHeight: 580,
},
}}
>
<DialogTitle>{t('Add target audiences in this inject')}</DialogTitle>
<DialogContent>
<Grid container={true} spacing={3} style={{ marginTop: -15 }}>
<Grid item={true} xs={8}>
<Grid container={true} spacing={3}>
<Grid item={true} xs={6}>
<SearchFilter
onChange={this.handleSearchAudiences.bind(this)}
fullWidth={true}
/>
</Grid>
<Grid item={true} xs={6}>
<TagsFilter
onAddTag={this.handleAddTag.bind(this)}
onClearTag={this.handleClearTag.bind(this)}
currentTags={tags}
fullWidth={true}
/>
</Grid>
</Grid>
<List>
{filteredAudiences.map((audience) => {
const disabled = audiencesIds.includes(audience.audience_id)
|| injectAudiencesIds.includes(audience.audience_id);
return (
<ListItem
key={audience.audience_id}
disabled={disabled}
button={true}
divider={true}
dense={true}
onClick={this.addAudience.bind(
this,
audience.audience_id,
)}
>
<ListItemIcon>
<CastForEducationOutlined />
</ListItemIcon>
<ListItemText
primary={audience.audience_name}
secondary={audience.audience_description}
/>
<ItemTags
variant="list"
tags={audience.audience_tags}
/>
</ListItem>
);
})}
<CreateAudience
exerciseId={exerciseId}
inline={true}
onCreate={this.onCreate.bind(this)}
/>
</List>
</Grid>
<Grid item={true} xs={4}>
<Box className={classes.box}>
{this.state.audiencesIds.map((audienceId) => {
const audience = audiencesMap[audienceId];
return (
<Chip
key={audienceId}
onDelete={this.removeAudience.bind(this, audienceId)}
label={truncate(audience.audience_name, 22)}
icon={<CastForEducationOutlined />}
classes={{ root: classes.chip }}
/>
);
})}
</Box>
</Grid>
</Grid>
</DialogContent>
<DialogActions>
<Button onClick={this.handleClose.bind(this)}>{t('Cancel')}</Button>
<Button
color="secondary"
onClick={this.submitAddAudiences.bind(this)}
>
{t('Add')}
</Button>
</DialogActions>
</Dialog>
</div>
);
}
}
InjectAddAudiences.propTypes = {
t: PropTypes.func,
exerciseId: PropTypes.string,
exercise: PropTypes.object,
fetchAudiences: PropTypes.func,
handleAddAudiences: PropTypes.func,
organizations: PropTypes.array,
audiences: PropTypes.array,
injectAudiencesIds: PropTypes.array,
attachment: PropTypes.bool,
};
const select = (state, ownProps) => {
const helper = storeHelper(state);
const { exerciseId } = ownProps;
const exercise = helper.getExercise(exerciseId);
const audiences = helper.getExerciseAudiences(exerciseId);
const audiencesMap = helper.getAudiencesMap();
return { exercise, audiences, audiencesMap };
};
export default R.compose(
connect(select, { fetchAudiences }),
inject18n,
withStyles(styles),
)(InjectAddAudiences);
|
app/components/GoogleMapMarker/Marker.js | 7ruth/PadStats2 | import React from 'react';
import PropTypes from 'prop-types';
import { camelize } from '../../utils/GoogleMapsUtils/String';
// const evtNames = ['mouseover', 'click', 'recenter', 'dragend'];
const wrappedPromise = () => {
const wrappedPromise = {}, //eslint-disable-line
promise = new Promise((resolve, reject) => {
wrappedPromise.resolve = resolve;
wrappedPromise.reject = reject;
});
wrappedPromise.then = promise.then.bind(promise);
wrappedPromise.catch = promise.catch.bind(promise);
wrappedPromise.promise = promise;
return wrappedPromise;
};
export class Marker extends React.Component {
componentDidMount() {
this.markerPromise = wrappedPromise();
this.renderMarker();
}
componentDidUpdate(prevProps) {
if ((this.props.map !== prevProps.map) ||
(this.props.position !== prevProps.position)) {
if (this.marker) {
this.marker.setMap(null);
}
this.renderMarker();
}
}
componentWillUnmount() {
if (this.marker) {
this.marker.setMap(null);
}
}
getMarker() {
return this.markerPromise;
}
handleEvent(evt) {
return (e) => {
const evtName = `on${camelize(evt)}`;
if (this.props[evtName]) {
this.props[evtName](this.props, this.marker, e);
}
};
}
renderMarker() {
let {
map, google, position, mapCenter, icon, label, draggable, title, //eslint-disable-line
} = this.props;
if (!google) {
return null;
}
const pos = position || mapCenter;
if (!(pos instanceof google.maps.LatLng)) {
position = new google.maps.LatLng(pos.lat, pos.lng);
}
const pref = {
map: map, //eslint-disable-line
position: position, //eslint-disable-line
icon: icon, //eslint-disable-line
label: label, //eslint-disable-line
title: title, //eslint-disable-line
draggable: draggable, //eslint-disable-line
};
this.marker = new google.maps.Marker(pref);
// evtNames.forEach((e) => {
// this.marker.addListener(e, this.handleEvent(e));
// });
return this.markerPromise.resolve(this.marker);
}
render() {
return null;
}
}
Marker.propTypes = {
position: PropTypes.object,
map: PropTypes.object,
};
// evtNames.forEach((e) => Marker.propTypes[e] = PropTypes.func); //eslint-disable-line
Marker.defaultProps = {
name: 'Marker',
};
export default Marker;
|
packages/showcase/plot/big-base-bar-chart.js | uber-common/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import ShowcaseButton from '../showcase-components/showcase-button';
import {
XYPlot,
XAxis,
YAxis,
VerticalBarSeries,
VerticalBarSeriesCanvas
} from 'react-vis';
const myDATA = [
{id: '00036', y: 200400, x: 1504121437},
{id: '00036', y: 200350, x: 1504121156},
{id: '00036', y: 200310, x: 1504120874},
{id: '00036', y: 200260, x: 1504120590},
{id: '00036', y: 200210, x: 1504120306},
{id: '00036', y: 200160, x: 1504120024},
{id: '00036', y: 200120, x: 1504119740},
{id: '00036', y: 200070, x: 1504119458},
{id: '00036', y: 200020, x: 1504119177},
{id: '00036', y: 199980, x: 1504118893},
{id: '00036', y: 199930, x: 1504118611},
{id: '00036', y: 199880, x: 1504118330},
{id: '00036', y: 199830, x: 1504118048},
{id: '00036', y: 199790, x: 1504117763},
{id: '00036', y: 199740, x: 1504117481}
];
const yDomain = myDATA.reduce(
(res, row) => {
return {
max: Math.max(res.max, row.y),
min: Math.min(res.min, row.y)
};
},
{max: -Infinity, min: Infinity}
);
export default class Example extends React.Component {
state = {
useCanvas: false
};
render() {
const {useCanvas} = this.state;
const content = useCanvas ? 'TOGGLE TO SVG' : 'TOGGLE TO CANVAS';
const BarSeries = useCanvas ? VerticalBarSeriesCanvas : VerticalBarSeries;
return (
<div>
<ShowcaseButton
onClick={() => this.setState({useCanvas: !useCanvas})}
buttonContent={content}
/>
<XYPlot
margin={{left: 75}}
xType="time"
width={300}
height={300}
yDomain={[yDomain.min, yDomain.max]}
>
<BarSeries className="vertical-bar-series-example" data={myDATA} />
<XAxis />
<YAxis />
</XYPlot>
</div>
);
}
}
|
js/components/Main.js | syarul/isoblog | import React from 'react';
import { Grid, Row, Button, Well } from 'react-bootstrap';
export default class Main extends React.Component {
propTypes: {
counter: React.PropTypes.number.isRequired,
onCounterClicked: React.PropTypes.func.isRequired,
falcorGreet: React.PropTypes.string.isRequired
}
render() {
/*
var model = new falcor.Model({source: new falcor.HttpDataSource('/model.json') });
// retrieve the "greeting" key from the root of the Virtual JSON resource
model.
get("greeting").
then(function(response) {
var falcorVal = response.json.greeting;
});
*/
return (
<div className="main">
<Grid>
<Row fluid={true}>
<h1>Falcor said: {this.props.falcorGreet}</h1>
{/*<button onClick={this.props.onCounterClicked}>Count Add</button><br />*/}
<Button bsStyle="primary" onClick={this.props.onCounterClicked}>Count</Button><br />
<Well>
<p>counter: {this.props.counter}</p>
</Well>
</Row>
</Grid>
</div>
);
}
};
|
docs/app/Examples/collections/Form/Shorthand/FormExampleFieldLabelObject.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Checkbox, Form } from 'semantic-ui-react'
const FormExampleFieldLabelElement = () => (
<Form>
<Form.Field
control={Checkbox}
label={<label>I agree to the Terms and Conditions</label>}
/>
</Form>
)
export default FormExampleFieldLabelElement
|
src/svg-icons/hardware/desktop-mac.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDesktopMac = (props) => (
<SvgIcon {...props}>
<path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7l-2 3v1h8v-1l-2-3h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 12H3V4h18v10z"/>
</SvgIcon>
);
HardwareDesktopMac = pure(HardwareDesktopMac);
HardwareDesktopMac.displayName = 'HardwareDesktopMac';
HardwareDesktopMac.muiName = 'SvgIcon';
export default HardwareDesktopMac;
|
src/components/Analyser/Analyser.js | KNETIC-KRPF/KNETIC-CLIENT | import React, { Component } from 'react';
import "./Analyser.css";
class Analyser extends Component {
componentDidMount() {
this.makeAnalyser();
}
makeAnalyser() {
const self = this;
const width = window.innerWidth;
setInterval( function() {
self.props.analyser.fftSize = 1024;
const bufferLength = self.props.analyser.frequencyBinCount;
const dataArray = new Uint8Array(self.props.analyser.frequencyBinCount);
self.props.analyser.getByteFrequencyData(dataArray);
const canvas = document.getElementById("canvas");
const ctx = canvas.getContext("2d");
ctx.clearRect(0, 0, width, 100);
ctx.fillStyle = '#1F1C1B';
ctx.fillRect(0, 0, width, 100);
var barWidth = (width / bufferLength) * 2.5;
var barHeight;
var x = 0;
for(var i = 0; i < bufferLength; i++) {
barHeight = dataArray[i];
ctx.fillStyle = 'rgb(148, 228, 194)';
ctx.fillRect(x, 100-barHeight/3,barWidth,barHeight/2);
x += barWidth + 1;
}
}, 1);
}
render() {
const width = window.innerWidth;
return (
<div>
<canvas id="canvas" width={width} height="100"></canvas>
</div>
);
}
}
export default Analyser;
|
pootle/static/js/editor/index.js | phlax/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import assign from 'object-assign';
import React from 'react';
import ReactDOM from 'react-dom';
import ReactRenderer from 'utils/ReactRenderer';
import { q, qAll } from 'utils/dom';
import SuggestionFeedbackForm from './components/SuggestionFeedbackForm';
import { loadFormatAdaptor } from './formats/FormatLoader';
import { hasCRLF, normalize, denormalize } from './utils/normalizer';
import { insertAtCaret, setValue } from './utils/RawFontAware';
const ReactEditor = {
init(props) {
this.node = q('.js-mount-editor');
this.sourceNode = q('.js-mount-editor-original-src');
this.alternativeSourceNodes = qAll('.js-mount-editor-alt-src');
this.suggestionValueNodes = qAll('.js-mnt-suggestion');
this.props = {};
this.hasCRLF = props.sourceValues.some(hasCRLF);
ReactRenderer.unmountComponents();
loadFormatAdaptor(props, (newProps, adaptor) => {
this.formatAdaptor = adaptor;
this.setProps(newProps);
this.renderSuggestions(newProps.initialValues);
});
},
setProps(props) {
this.props = assign(this.props, props);
/* ,
* __ _.-"` `'-.
* /||\'._ __{}_( CUSTOMS CHECK: we convert potential CRLFs to LFs
* |||| |'--.__\ when passing values down to components (`extraProps`),
* | L.( ^_\^ but we keep the original values in `this.props`
* \ .-' | _ | just in case the outside world needs to query them.
* | | )\___/
* | \-'`:._]
* \__/; '-.
*/
const extraProps = {};
if (this.hasCRLF && props.hasOwnProperty('initialValues')) {
extraProps.initialValues = normalize(props.initialValues);
}
this.editorInstance = ReactRenderer.render(
<this.formatAdaptor.editorComponent
onChange={this.handleChange}
{...this.props}
{...extraProps}
/>,
this.node
);
ReactRenderer.render(
<this.formatAdaptor.unitSourceComponent
id={this.props.unitId}
values={this.props.sourceValues}
hasPlurals={this.props.hasPlurals}
sourceLocaleCode={this.props.sourceLocaleCode}
sourceLocaleDir={this.props.sourceLocaleDir}
/>,
this.sourceNode
);
for (let i = 0; i < this.alternativeSourceNodes.length; i++) {
const mountNode = this.alternativeSourceNodes[i];
const unit = this.props.alternativeSources[mountNode.dataset.id];
ReactRenderer.render(
<this.formatAdaptor.unitSourceComponent
id={unit.id}
values={unit.target}
hasPlurals={unit.has_plurals}
sourceLocaleCode={unit.language_code}
sourceLocaleDir={unit.language_direction}
/>,
mountNode
);
}
},
renderViewUnitComponent(unit, mountNode) {
loadFormatAdaptor(unit, (newProps, adaptor) => {
ReactRenderer.render(<adaptor.viewUnitComponent {...newProps} />, mountNode);
});
},
renderSuggestions(initialValues) {
for (let i = 0; i < this.suggestionValueNodes.length; i++) {
const mountNode = this.suggestionValueNodes[i];
const suggestion = this.props.suggestions[mountNode.dataset.id];
ReactRenderer.render(
<this.formatAdaptor.suggestionValueComponent
id={suggestion.id}
values={suggestion.target}
hasPlurals={this.props.hasPlurals}
currentLocaleCode={this.props.currentLocaleCode}
currentLocaleDir={this.props.currentLocaleDir}
initialValues={initialValues}
/>,
mountNode
);
}
},
renderSuggestionFeedbackForm(props, mountNode) {
const suggestion = this.props.suggestions[props.suggId];
this.feedbackMountNode = mountNode;
this.suggestionEditorInstance = ReactDOM.render(
<SuggestionFeedbackForm
initialSuggestionValues={suggestion.target}
sourceValues={this.props.sourceValues}
editorComponent={this.formatAdaptor.editorComponent}
currentLocaleCode={this.props.currentLocaleCode}
currentLocaleDir={this.props.currentLocaleDir}
targetNplurals={this.props.targetNplurals}
isDisabled={this.props.isDisabled}
{...props}
/>,
mountNode
);
},
unmountSuggestionFeedbackForm() {
if (this.feedbackMountNode) {
ReactDOM.unmountComponentAtNode(this.feedbackMountNode);
this.feedbackMountNode = undefined;
}
},
get stateValues() {
return this._stateValues(this.editorInstance);
},
get stateSuggestionValues() {
return this._stateValues(this.suggestionEditorInstance);
},
// FIXME: this additional layer of state tracking is only kept to allow
// interaction from the outside world. Remove ASAP.
_stateValues(editorInstance) {
const stateValues = editorInstance.getStateValues();
/* ,
* __ _.-"` `'-.
* /||\'._ __{}_( CUSTOMS CHECK: if any CRLF => LF conversion was done
* |||| |'--.__\ when passing values down (`this.hasCRLF`), we need to
* | L.( ^_\^ convert values back to their original form (LF => CRLF)
* \ .-' | _ | when providing the hook to the outside world, making
* | | )\___/ them unaware of what happened within the component's
* | \-'`:._] ecosystem.
* \__/; '-.
*/
if (this.hasCRLF) {
return denormalize(stateValues);
}
return stateValues;
},
handleChange() {
PTL.editor.onTextareaChange();
},
// FIXME: the following are ad-hoc methods for "communication". We should
// rather drill holes in some other way, e.g. using Redux.
/**
* Sets a new textarea value.
*/
setValueFor(indexOrElement, value) {
if (this.props.isDisabled) {
return;
}
const textareas = this.editorInstance.getAreas();
const index = (
typeof indexOrElement === 'object' ?
textareas.indexOf(indexOrElement) :
indexOrElement
);
setValue(textareas[index], value,
{ isRawMode: this.props.isRawMode, triggerChange: true });
textareas[index].focus();
},
setValues(values) {
const areaValues = this.editorInstance.getAreaValues(values);
for (let i = 0; i < areaValues.length; i++) {
ReactEditor.setValueFor(i, areaValues[i]);
}
},
/**
* Inserts a value in the current caret position.
*/
insertAtCaretFor(indexOrElement, value) {
const textareas = this.editorInstance.getAreas();
const index = (
typeof indexOrElement === 'object' ?
textareas.indexOf(indexOrElement) :
indexOrElement
);
insertAtCaret(textareas[index], value, { isRawMode: this.props.isRawMode,
triggerChange: true });
textareas[index].focus();
},
};
export default ReactEditor;
|
NewsAppDemo/Component/Message.js | SpadeZach/RNNewsApp | import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
class Message extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
消息
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
}
});
module.exports = Message; |
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | brunolimadevelopment/brunolimadevelopment.github.io | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
src/selectPluginRoutes.js | jcoreio/redux-plugins-immutable-react-router | /* @flow */
import * as Immutable from 'immutable'
import React from 'react'
import memoize from 'lodash.memoize'
import {createSelector, createSelectorCreator, defaultMemoize} from 'reselect'
function shallowEqual(a, b) {
if (a === b) return true
if (a && b) {
if (a.size !== b.size) return false
return a.every((value, key) => value === b.get(key))
}
return false
}
const createShallowEqualSelector = createSelectorCreator(defaultMemoize, shallowEqual)
const selectPluginRoutes: (routeKeyOrFunc: string | (plugin: Immutable.Map<any, any>) => any) => (state: any) => any[] = memoize(
routeKeyOrFunc => {
const getRoutes = routeKeyOrFunc instanceof Function
? routeKeyOrFunc
: plugin => plugin.getIn(['routes', routeKeyOrFunc])
const stage0 = createSelector(
state => state.get('plugins'),
plugins => plugins.map(getRoutes)
)
return createShallowEqualSelector(
state => stage0(state),
routeMap => {
const result = []
routeMap.forEach(routes => {
if (routes) {
if (Array.isArray(routes)) result.push(...routes)
else result.push(routes)
}
})
return result.map((route, index) => React.isValidElement(route)
? React.cloneElement(route, {key: index})
: route)
}
)
}
)
export default selectPluginRoutes
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestParameters.js | ontruck/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load({ id = 0, ...rest }) {
return [
{ id: id + 1, name: '1' },
{ id: id + 2, name: '2' },
{ id: id + 3, name: '3' },
rest.user,
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load({ id: 0, user: { id: 42, name: '42' } });
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-rest-parameters">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
admin/client/App/components/Navigation/Primary/index.js | frontyard/keystone | /**
* The primary (i.e. uppermost) navigation on desktop. Renders all sections and
* the home-, website- and signout buttons.
*/
import React from 'react';
import { Container } from '../../../elemental';
import PrimaryNavItem from './NavItem';
var PrimaryNavigation = React.createClass({
displayName: 'PrimaryNavigation',
propTypes: {
brand: React.PropTypes.string,
currentSectionKey: React.PropTypes.string,
sections: React.PropTypes.array.isRequired,
signoutUrl: React.PropTypes.string,
},
getInitialState () {
return {};
},
// Handle resizing, hide this navigation on mobile (i.e. < 768px) screens
componentDidMount () {
this.handleResize();
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
},
handleResize () {
this.setState({
navIsVisible: window.innerWidth >= 768,
});
},
// Render the sign out button
renderSignout () {
if (!this.props.signoutUrl) return null;
return (
<PrimaryNavItem
label="octicon-sign-out"
href={this.props.signoutUrl}
title="Sign Out"
>
<span className="octicon octicon-sign-out" />
</PrimaryNavItem>
);
},
// Render the back button
renderBackButton () {
if (!Keystone.backUrl) return null;
return (
<PrimaryNavItem
label="octicon-globe"
href={Keystone.backUrl}
title={'Front page - ' + this.props.brand}
>
<span className="octicon octicon-globe" />
</PrimaryNavItem>
);
},
// Render the link to the webpage
renderFrontLink () {
return (
<ul className="app-nav app-nav--primary app-nav--right">
{this.renderBackButton()}
{this.renderSignout()}
</ul>
);
},
renderBrand () {
// TODO: support navbarLogo from keystone config
const { brand, currentSectionKey } = this.props;
const className = currentSectionKey === 'dashboard' ? 'primary-navbar__brand primary-navbar__item--active' : 'primary-navbar__brand';
return (
<PrimaryNavItem
className={className}
label="octicon-home"
title={'Dashboard - ' + brand}
to={Keystone.adminPath}
>
<span className="octicon octicon-home" />
</PrimaryNavItem>
);
},
// Render the navigation
renderNavigation () {
if (!this.props.sections || !this.props.sections.length) return null;
return this.props.sections.map((section) => {
// Get the link and the class name
const to = !section.lists[0].external && `${Keystone.adminPath}/${section.lists[0].path}`;
const href = section.lists[0].external && section.lists[0].path;
const isActive = this.props.currentSectionKey && this.props.currentSectionKey === section.key;
const className = isActive ? 'primary-navbar__item--active' : null;
return (
<PrimaryNavItem
active={isActive}
key={section.key}
label={section.label}
className={className}
to={to}
href={href}
>
{section.label}
</PrimaryNavItem>
);
});
},
render () {
if (!this.state.navIsVisible) return null;
return (
<nav className="primary-navbar">
<Container clearFloatingChildren>
<ul className="app-nav app-nav--primary app-nav--left">
{this.renderBrand()}
{this.renderNavigation()}
</ul>
{this.renderFrontLink()}
</Container>
</nav>
);
},
});
module.exports = PrimaryNavigation;
|
web/components/BucketSelector.js | ByzantineFailure/TweetStream | import React from 'react';
const values = [
{ label: '1 second', value: 1000 },
{ label: '3 seconds', value: 3000 },
{ label: '5 seconds', value: 5000 },
{ label: '10 seconds', value: 10000 },
{ label: '30 seconds', value: 30000 },
{ label: '1 minute', value: 60000 }
]
class BucketSelector extends React.Component {
constructor() {
super();
this.onChange = this.onChange.bind(this);
}
onChange(e) {
this.props.selectCallback(Number(e.target.value));
}
render() {
const options = values.map(val =>
<option key={val.value} value={val.value}>{val.label}</option>
);
return <select onChange={this.onChange}>
{options}
</select>
}
}
BucketSelector.propTypes = {
selectCallback: React.PropTypes.func.isRequired
};
export default BucketSelector;
|
docs/src/pages/components/timeline/ColorsTimeline.js | lgollut/material-ui | import React from 'react';
import Timeline from '@material-ui/lab/Timeline';
import TimelineItem from '@material-ui/lab/TimelineItem';
import TimelineSeparator from '@material-ui/lab/TimelineSeparator';
import TimelineConnector from '@material-ui/lab/TimelineConnector';
import TimelineContent from '@material-ui/lab/TimelineContent';
import TimelineDot from '@material-ui/lab/TimelineDot';
export default function ColorsTimeline() {
return (
<Timeline align="alternate">
<TimelineItem>
<TimelineSeparator>
<TimelineDot />
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>Eat</TimelineContent>
</TimelineItem>
<TimelineItem>
<TimelineSeparator>
<TimelineDot color="primary" />
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>Code</TimelineContent>
</TimelineItem>
<TimelineItem>
<TimelineSeparator>
<TimelineDot color="secondary" />
<TimelineConnector />
</TimelineSeparator>
<TimelineContent>Sleep</TimelineContent>
</TimelineItem>
<TimelineItem>
<TimelineSeparator>
<TimelineDot />
</TimelineSeparator>
<TimelineContent>Repeat</TimelineContent>
</TimelineItem>
</Timeline>
);
}
|
src/components/children/ArtistCard.js | Nfinley/Showcase-Playlist-Generator | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import CardMedia from '@material-ui/core/CardMedia';
import IconButton from '@material-ui/core/IconButton';
import Typography from '@material-ui/core/Typography';
import PlayArrowIcon from '@material-ui/icons/PlayArrow';
import PauseIcon from '@material-ui/icons/PauseCircleOutline';
import moment from 'moment';
const styles = theme => ({
card: {
display: 'flex'
},
details: {
display: 'flex',
flexDirection: 'column'
},
content: {
flex: '1 0 auto'
},
cover: {
width: 200,
height: 200
},
controls: {
display: 'flex',
alignItems: 'center',
paddingLeft: theme.spacing.unit,
paddingBottom: theme.spacing.unit
},
playIcon: {
height: 38,
width: 38
}
});
function ArtistCard(props) {
const { classes, theme, data, playAudio, audioOn } = props;
const { image, id, name, songkickData, trackInfo } = data;
const AudioButton = audioOn ? PauseIcon : PlayArrowIcon;
const previewTrack = trackInfo && trackInfo[0].preview_url && trackInfo[0].preview_url;
return (
<div className="card-image-cover">
{/* eslint-disable-next-line */}
<audio id={id}>
<source src={previewTrack} />
<track
src={previewTrack}
kind="subtitles"
srcLang="en"
label="English"
/>
</audio>
<Card className={classes.card}>
<div className={classes.details}>
<CardContent className={classes.content}>
<Typography variant="headline">{name}</Typography>
<Typography variant="subheading" color="textSecondary">
{' '}
{moment(songkickData[0].date).format('MMM Do YYYY')} @{' '}
{songkickData[0].venue}
</Typography>
<Typography variant="subheading">
<a target="_blank" href={songkickData[0].uri}>
{' '}
Ticket Info{' '}
</a>
</Typography>
</CardContent>
<div className={classes.controls}>
<IconButton
id={id}
aria-label="Play/pause"
onClick={() => playAudio(id)}
>
<AudioButton className={classes.playIcon} />
</IconButton>
<Typography variant="subheading">
<p> {trackInfo[0].name}</p>
</Typography>
</div>
</div>
<CardMedia
className={classes.cover}
image={`${image}`}
title={`${name} @ ${data.songkickData[0].venue}`}
/>
</Card>
</div>
);
}
ArtistCard.propTypes = {
audioOn: PropTypes.bool.isRequired,
classes: PropTypes.object.isRequired,
theme: PropTypes.object.isRequired,
data: PropTypes.object.isRequired,
playAudio: PropTypes.func.isRequired
};
export default withStyles(styles, { withTheme: true })(ArtistCard);
|
src/components/widgets/ot/publisher/Media.js | brancusi/lingo-client-react | import React from 'react';
import Radium from 'radium';
import { fromJS } from 'immutable';
export const WIDTH = 200;
export const HEIGHT = 150;
@Radium
export default class Media extends React.Component {
static propTypes = {
session: React.PropTypes.object,
publishVideo: React.PropTypes.bool.isRequired,
publishAudio: React.PropTypes.bool.isRequired,
profileImageUrl: React.PropTypes.string
}
componentDidMount () {
this._createPublisher();
this._syncVideoState();
this._syncAudioState();
}
shouldComponentUpdate ( nextProps ) {
// const sessionChanged = _hasChanged(nextProps.session, this.props.session);
const videoStateChanged = nextProps.publishVideo !== this.props.publishVideo;
const audioStateChanged = nextProps.publishAudio !== this.props.publishAudio;
return videoStateChanged || audioStateChanged;
}
componentDidUpdate ( prevProps ) {
// const sessionChanged = _hasChanged(nextProps.session, this.props.session);
const videoStateChanged = prevProps.publishVideo !== this.props.publishVideo;
const audioStateChanged = prevProps.publishAudio !== this.props.publishAudio;
// if(sessionChanged)this._createPublisher();
if ( videoStateChanged )this._syncVideoState();
if ( audioStateChanged )this._syncAudioState();
}
componentWillUnmount () {
const { session } = this.props;
session.unpublish(this.publisher);
}
_createPublisher () {
const { session } = this.props;
const options = {
width : WIDTH,
height: HEIGHT,
showControls: false,
publishVideo: false,
publishAudio: false
};
this.publisher = session.publish(this.container, options);
}
_hasChanged (obj, against) {
return !fromJS(this.props).equals(fromJS(against));
}
_syncAudioState () {
const { publishAudio } = this.props;
if ( publishAudio ) {
this.publisher.publishAudio(true);
} else {
this.publisher.publishAudio(false);
}
}
_syncVideoState () {
const { publishVideo } = this.props;
if ( publishVideo ) {
this.publisher.publishVideo(true);
} else {
this.publisher.publishVideo(false);
}
}
render () {
const containerStyles = {
width: WIDTH,
height: HEIGHT
};
return (
<div style={containerStyles}>
<div ref={node => this.container = node}/>
</div>
);
}
}
|
assets/jqwidgets/demos/react/app/datetimeinput/disabled/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxDateTimeInput from '../../../jqwidgets-react/react_jqxdatetimeinput.js';
class App extends React.Component {
render() {
return (
<JqxDateTimeInput
width={250} height={25} disabled={true}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
examples/auth-with-shared-root/components/Login.js | rubengrill/react-router | import React from 'react'
import { History } from 'react-router'
import auth from '../utils/auth.js'
const Login = React.createClass({
mixins: [ History ],
getInitialState() {
return {
error: false
}
},
handleSubmit(event) {
event.preventDefault()
const email = this.refs.email.value
const pass = this.refs.pass.value
auth.login(email, pass, (loggedIn) => {
if (!loggedIn)
return this.setState({ error: true })
const { location } = this.props
if (location.state && location.state.nextPathname) {
this.history.replaceState(null, location.state.nextPathname)
} else {
this.history.replaceState(null, '/')
}
})
},
render() {
return (
<form onSubmit={this.handleSubmit}>
<label><input ref="email" placeholder="email" defaultValue="[email protected]" /></label>
<label><input ref="pass" placeholder="password" /></label> (hint: password1)<br />
<button type="submit">login</button>
{this.state.error && (
<p>Bad login information</p>
)}
</form>
)
}
})
export default Login
|
src/components/DBTable/InnerCapacityDetail.js | lijinfengworm/ant-design-reactjs | import React from 'react';
import {
Button,
Table,
Icon,
Modal,
message,
notification,
Affix,
Card, Col, Row, Switch
} from 'antd';
import Logger from '../../utils/Logger';
import Utils from '../../utils';
import ajax from '../../utils/ajax';
import moment from 'moment';
import ImageSlider from '../ImageSlider';
import InnerTableSchemaUtils from './InnerTableSchemaUtils';
import InnerTableRenderUtils, {ACTION_KEY} from './InnerTableRenderUtils';
const logger = Logger.getLogger('InnerList');
/**
* 内部表格组件
*/
class InnerCapacityDetail extends React.PureComponent {
// 对于InnerTable组件而言, 既有表格又有表单
// 虽然传进来的是dataSchema, 但要parse两次, 分别变成表格和表单的schema
state = {
modalVisible: false, // modal是否可见
modalTitle: '新增', // modal标题
modalInsert: true, // 当前modal是用来insert还是update
selectedRowKeys: [], // 当前有哪些行被选中, 这里只保存key
// FIXME: 这里可能会有点问题, 父组件中有一个data, 这里又有一个data, 都表示的是表格中的数据, 两边状态不一致, 可能有潜在的bug
data: [], // 表格中显示的数据
// 图片预览相关状态
previewVisible: false, // 是否显示图片预览modal
previewImages: [], // 要预览的图片
// 用户自定义组件modal, 一般用于实现单条记录的更新
componentModalVisible: false,
};
/**
* 组件初次挂载时parse schema
*/
componentWillMount() {
this.parseTableSchema(this.props);
this.parseTableData(this.props);
}
/**
* InnerTable组件的re-render有两种情况: 自身状态变化导致的render vs 父组件导致的render
* 正常情况下, 只有父组件导致的render才会触发这个方法, InnerTable自身的变化应该不会触发
*
* 父组件触发这个方法也有两种情况:
* 1. 只有data变化, 比如改变了查询条件/分页等等
* 2. schema和data都变化了, 比如在react router中切换了菜单项
*
* @param nextProps
*/
componentWillReceiveProps(nextProps) {
logger.debug('receive new props and try to render, nextProps=%o', nextProps);
// 之前因为antd的Form组件搞了一些黑盒操作, 表单每输入一次都会触发这个方法, 现在表单独立成一个组件了, 应该好了
// 只有表名变化时才需要重新parse schema
if (this.props.tableName !== nextProps.tableName) {
logger.debug('tableName changed and try to refresh schema');
this.parseTableSchema(nextProps);
this.formComponent = undefined; // 这个别忘了, 如果schema变了, 表单当然也要变
}
// 这里要还原初始状态, 理论上来讲, InnerTable所有自己的状态都应该还原, 但其实也是看情况的
// 比如这里的this.state.data就不用还原, 因为下面的parseTableData方法会更新this.state.data
// 哪些状态做成this.xxx, 哪些做成this.state.xxx, 还是有点迷惑的, 如果全都塞到state里是不是不太好
this.state.modalVisible = false;
this.state.modalTitle = '新增';
this.state.modalInsert = true;
this.state.selectedRowKeys = [];
// 是否要刷新表格中显示的数据? 这个逻辑还有点绕
// 1. 如果schema变化了, 必须刷新数据
// 2. 如果schema没变, 但表格要进入loading状态, 就不要刷新数据, 这样用户体验更好
if (this.props.tableName !== nextProps.tableName || !nextProps.tableLoading) {
this.parseTableData(nextProps);
}
}
/**
* 当前组件unmount时清除render函数缓存
*/
componentWillUnmount() {
logger.debug('InnerTable component unmount and reset RenderUtils');
InnerTableRenderUtils.reset();
}
/*下面是一些数据处理相关的方法*/
/**
* 解析表格的schema
*/
parseTableSchema(props) {
const {tableName, schema} = props;
const parseResult = InnerTableSchemaUtils.getTableSchema(tableName, schema);
this.primaryKey = parseResult.primaryKey;
// fieldMap是对原始的dataSchema做了一些处理, 方便查询用的
this.fieldMap = parseResult.fieldMap;
// tableSchema是转换后的Table组件可用的schema
// 对于tableSchema, 即使命中了缓存, 也要重新设置下render函数
this.tableSchema = InnerTableRenderUtils.bindRender(parseResult.tableSchema, tableName, this);
}
/**
* 解析表格要显示的数据
* 后端返回的数据不能直接在table中显示
*/
parseTableData(props) {
// 每行数据都必须有个key属性, 如果指定了主键, 就以主键为key
// 否则直接用个自增数字做key
const newData = [];
let i = 0;
props.data.forEach((obj) => {
const newObj = this.transformRawDataToTable(obj);
if (this.primaryKey) {
newObj.key = obj[this.primaryKey];
} else {
newObj.key = i;
i++;
}
newData.push(newObj);
});
// 在这里, 下面两种写法是等效的, 因为parseTableData方法只会被componentWillReceiveProps调用, 而componentWillReceiveProps的下一步就是判断是否re-render
// 但要注意, 不是任何情况下都等效
//this.setState({data: newData});
this.state.data = newData;
}
/**
* 将后端返回的一条数据转换为前端表格中能显示的一条数据
* 后端返回的往往是数字(比如0表示屏蔽, 1表示正常)
* 而表格中要显示对应的汉字, 跟dataSchema中的配置对应
*/
transformRawDataToTable(obj) {
const newObj = {};
// 这段代码真是好蛋疼...
for (const key in obj) {
if (this.fieldMap.get(key).$$optionMap) {
const optionMap = this.fieldMap.get(key).$$optionMap;
if (obj[key] instanceof Array) {
const newArray = [];
for (const optionKey of obj[key]) {
newArray.push(optionMap[optionKey]);
}
newObj[key] = newArray.join(',');
} else {
newObj[key] = optionMap[obj[key]];
}
} else {
newObj[key] = obj[key];
}
}
newObj.$$rawData = obj; // 原始数据还是要保存下的, 后面update会用到
return newObj;
}
/**
* 将后端返回的一条数据转换为表单中能显示的数据
* 主要是处理日期字段, 必须是moment对象
*/
transformRawDataToForm(obj) {
const newObj = {};
for (const key in obj) {
// rawData中可能有些undefined或null的字段, 过滤掉
if (!obj[key])
continue;
if (this.fieldMap.get(key).dataType === 'datetime') { // 判断是否是日期类型的字段
newObj[key] = moment(obj[key]);
} else {
newObj[key] = obj[key];
}
}
return newObj;
}
/**
* 将表格中的一条数据转换为表单中能显示的数据
*/
transformTableDataToForm(obj) {
return this.transformRawDataToForm(obj.$$rawData);
}
/**
* 设置表单要显示的数据
*/
setFormData(data) {
// 注意这里, 由于antd modal的特殊性, this.formComponent可能是undefined, 要判断一下
if (this.formComponent) {
this.formComponent.resetFields();
if (data) {
this.formComponent.setFieldsValue(data);
}
} else {
this.formInitData = data;
}
}
/*下面是一些事件处理的方法*/
/**
* 点击新增按钮, 弹出一个内嵌表单的modal
*
* @param e
*/
onClickInsert = (e) => {
e.preventDefault();
// this.setFormData({}); // insert时弹出的表单应该是空的
this.setState({
modalVisible: true,
modalTitle: '新增',
modalInsert: true,
}, () => this.setFormData({}));
};
/**
* 点击更新按钮, 弹出一个内嵌表单的modal
* 注意区分单条更新和批量更新
*
* @param e
*/
onClickUpdate = (e) => {
e.preventDefault();
// 重置下keysToUpdate, 因为点击表格上方的更新按钮时, 默认是所有字段都可以更新
this.singleRecordKey = undefined;
this.keysToUpdate = undefined;
// 要显示在表单中的值
const newData = {};
const multiSelected = this.state.selectedRowKeys.length > 1; // 是否选择了多项
// 如果只选择了一项, 就把原来的值填到表单里
// 否则就只把要更新的主键填到表单里
if (!multiSelected) {
logger.debug('update single record, and fill original values');
const selectedKey = this.state.selectedRowKeys[0];
for (const record of this.state.data) { // 找到被选择的那条记录
if (record.key === selectedKey) {
Object.assign(newData, this.transformTableDataToForm(record));
break;
}
}
} else {
newData[this.primaryKey] = this.state.selectedRowKeys.join(', ');
logger.debug('update multiple records, keys = %s', newData[this.primaryKey]);
}
//this.setFormData(newData);
// 理论上来说应该先设置好表单的值(setFieldsValue)再显示modal
// 美中不足的是表单的值变化需要一个时间, 显示modal的过程中可能被用户看到"旧值变新值"的过程, 在FileUploader组件上传图片时这个现象很明显
// 跟组件的实现方式有关, 可能是css动画的问题, 也可能是setState异步的问题, 似乎暂时无解...
if (multiSelected) {
this.setState({modalVisible: true, modalTitle: '批量更新', modalInsert: false}, () => this.setFormData(newData));
} else {
this.setState({modalVisible: true, modalTitle: '更新', modalInsert: false}, () => this.setFormData(newData));
}
};
/**
* 点击删除按钮, 弹出一个确认对话框
* 注意区分单条删除和批量删除
*
* @param e
*/
onClickDelete = (e) => {
e.preventDefault();
Modal.confirm({
title: this.state.selectedRowKeys.length > 1 ? '确认批量删除' : '确认删除',
content: `当前被选中的行: ${this.state.selectedRowKeys.join(', ')}`,
// 这里注意要用箭头函数, 否则this不生效
onOk: () => {
this.handleDelete();
},
});
};
/**
* 处理表格的选择事件
*
* @param selectedRowKeys
*/
onTableSelectChange = (selectedRowKeys) => {
this.setState({selectedRowKeys});
};
/**
* 隐藏modal
*/
hideModal = () => {
this.setState({modalVisible: false});
};
/**
* 点击modal中确认按钮的回调, 清洗数据并准备传给后端
*/
handleModalOk = () => {
// 提交表单之前, 要先校验下数据
let validated = true;
this.formComponent.validateFieldsAndScroll((err, values) => validated = err ? false : validated); // 不知道有没有更好的办法
if (!validated) {
logger.debug('validate form error');
return;
}
// 1. 将表单中的undefined去掉
// 2. 转换日期格式
const newObj = {};
const oldObj = this.formComponent.getFieldsValue(); // 这里的formComponent必定不是undefined
for (const key in oldObj) {
// if (!oldObj[key]) {
// 原来的这种写法是有bug的, 因为空字符串也会被过滤掉, 而有时候空字符串传回后端也是有意义的
// 这里有个问题, 更新的时候, 某个字段后端接收到了null, 到底是忽略这个字段还是将字段更新为null(默认值)? 用过mybatis的应该能明白啥意思
// 这个问题貌似是无解的, 在后端字段只有null/not null两种状态, 而前端可以用3种状态: undefined表示不更新, null表示更新为null, 其他值表示更新为特定的值
// 只能认为undefined/null都对应于后端的null
// 换句话说, 如果DB里某个字段已经有值了, 就不可能再修改为null了, 即使建表时是允许null的. 最多更新成空字符串. 除非跟后端约定一个特殊的值去表示null.
// 一般情况下这不会有什么影响, 但某些corner case里可能有bug...
// 另外, 要理解antd form的取值逻辑. antd的form是controlled components, 只有当FormItem变化时才会取到值(通过onChange方法), 否则对应的key就是undefined
// 例如, 如果有一个输入框, 如果不动它, 然后getFieldsValue, 得到的是undefined; 如果先输入几个字符, 然后再全部删除, 再getFieldsValue, 得到的是空字符串
// 注意下日期类型, 它返回的是一个moment对象, 所以取到的值可能是null
// 如果写自己的FormItem组件, 一定要注意下这个问题
if (oldObj[key] === undefined || oldObj[key] === null) {
continue;
}
// 跟InnerForm中的filterQueryObj方法很相似
if (key === this.primaryKey && typeof oldObj[key] === 'string') { // 我在InnerTableSchemaUtils限制死了, modal中的主键字段必定是个string
// 对于主键而言, 我本来想在这里转换成array, 后来想想不用, this.state.selectedRowKeys中就已经保存着主键了, 可以直接用
// for (const str of oldObj[key].split(', ')) {
// primaryKeyArray.push(str);
// }
// do nothing
} else if (oldObj[key] instanceof Date) {
newObj[key] = oldObj[key].format('yyyy-MM-dd HH:mm:ss');
} else if (moment.isMoment(oldObj[key])) { // 处理moment对象
newObj[key] = oldObj[key].format('YYYY-MM-DD HH:mm:ss');
} else {
newObj[key] = oldObj[key];
}
}
// 至此表单中的数据格式转换完毕
this.hideModal();
logger.debug('click modal OK and the form obj = %o', newObj);
// 将转换后的数据传给后端
if (this.state.modalInsert) {
this.handleInsert(newObj);
} else {
// 这个modal可能是用于表格上方的"修改"按钮, 也可能用于单条记录的更新
// 这里要判断一下
if (this.singleRecordKey) {
const keys = [];
keys.push(this.singleRecordKey);
this.handleUpdate(newObj, keys);
} else {
this.handleUpdate(newObj);
}
}
};
/**
* 点击图片时显示幻灯片
*
* @param text
*/
onClickImage = (text) => {
const newImageArray = [];
if (Utils.isString(text) && text.length > 0) {
newImageArray.push({url: text, alt: '图片加载失败'});
} else if (text instanceof Array) {
for (const tmp of text) {
newImageArray.push({url: tmp, alt: '图片加载失败'});
}
}
// 如果没有图片, 点击就不要显示modal
if (newImageArray.length > 0) {
this.setState({previewVisible: true, previewImages: newImageArray});
}
};
/**
* 隐藏图片预览
*/
cancelPreview = () => {
this.setState({previewVisible: false});
};
/**
* 针对单条记录的更新
*
* @param record 要更新的记录
* @param keysToUpdate 允许更新哪些字段(弹出的modal中显示哪些字段)
*/
onSingleRecordUpdate = (record, keysToUpdate) => {
// 传进来的record是表格中显示的一条数据, 要转换下才能填到表单中
// 比如checkbox在表格中显示的是逗号分隔字符串, 但在表单中还是要还原为key数组的
const transformedRecord = this.transformTableDataToForm(record);
this.singleRecordKey = record[this.primaryKey]; // 要更新哪条记录
if (keysToUpdate) {
this.keysToUpdate = new Set(keysToUpdate);
} else {
this.keysToUpdate = undefined;
}
//this.setFormData(transformedRecord);
// 这里又有一个hack
// 我本来是先setFormData再setState的, 但表单的显示总是有点问题, setFieldsValue设置表单的值有时不生效
// 只要keysToUpdate改变, 表单的值的显示就会有问题
// 换句话说, 一旦表单的schema变化, setFieldsValue就有问题
// 猜测是setFieldsValue(data)方法的实现比较特殊, 它不会收集data中的所有值, 而是只会收集当前schema中有用的值, 姑且叫做collectKeys
// 比如传入的data是{a:1, b:2, c:3}, 而render方法中有用的key是a和b, 调用setFieldsValue时就会忽略c的值
// 每次render的时候才会更新collectKeys, 应该是通过getFieldDecorator方法收集的
// 我碰到的问题, 如果先setFormData, 表单组件只会按当前的schema去收集值
// 而setState时会触发表单组件的render方法, 这个表单的schema其实是根据keysToUpdate动态生成的, 很可能collectKeys跟之前完全不一样
// 所以渲染出来的表单, 没有把值填进去, 虽然我setFieldsValue时传入了完整的一行记录...
// 唉antd的黑盒太难琢磨, 源码还是typescript的, 有点看不懂...
this.setState({
modalVisible: true,
modalTitle: '更新',
modalInsert: false,
}, () => this.setFormData(transformedRecord)); // 这种方法可以保证在表单组件render后才setFieldsValue, 就会按新的schema去收集值了
};
/**
* 针对单条记录的删除
*
* @param record
*/
onSingleRecordDelete = (record) => {
const selectedKey = record[this.primaryKey];
Modal.confirm({
title: '确认删除',
content: `当前被选中的行: ${selectedKey}`,
onOk: () => {
const keys = [];
keys.push(selectedKey);
this.handleDelete(keys);
},
});
};
/**
* 自定义组件实现对单条记录的更新
* 可以满足一些定制化的需求, 优化用户体验
*
* @param record 要更新的记录
* @param component 要渲染的组件, 会将对应的组件渲染到modal中
* @param name 显示modal时的标题
*/
onSingleRecordComponent = (record, component, name) => {
// 暂存对应的信息, 后面会用到
this.updateComponent = component; // react组件对应的class, 其实就是个函数
this.updateComponentRecord = record;
this.updateComponentModalTitle = name;
this.setState({componentModalVisible: true});
};
/**
* 隐藏自定义组件modal
*/
handleComponentModalCancel = () => {
this.setState({componentModalVisible: false});
};
/**
* 自定义组件modal点击确认时的回调
*/
handleComponentModalOk = () => {
// 首先关闭modal
this.setState({componentModalVisible: false});
// 自定义的组件正常挂载后, 会以ref的形式暂存
if (!this.updateComponentMounted) { // 正常情况下不会出现这种情况
logger.error('user-defined component does not mount');
return;
}
// 用户是否定义了getFieldsValue函数
if (!this.updateComponentMounted.getFieldsValue) {
logger.debug('user does not define getFieldsValue function');
return;
}
// 获取用户自定义组件的返回值
const data = this.updateComponentMounted.getFieldsValue();
logger.debug('user-defined component getFieldsValue = %o', data);
// 如果组件返回false/undefined, 就什么都不做
if (!data) {
return;
}
// 否则更新对应的记录
const keys = [];
keys.push(this.updateComponentRecord[this.primaryKey]);
this.handleUpdate(data, keys);
// TODO: 其实用户自定义组件不只可以用于更新, 还可以做很多事, e.g. 如果定义了xxx方法就直接跳转某个url之类的
// 本质上来讲是和用户约定好的一套协议
};
/*下面开始才是真正的数据库操作*/
error(errorMsg) {
// 对于错误信息, 要很明显的提示用户, 这个通知框要用户手动关闭
notification.error({
message: '出错啦!',
description: `请联系管理员, 错误信息: ${errorMsg}`,
duration: 0,
});
}
/**
* 真正去新增数据
*/
async handleInsert(obj) {
const CRUD = ajax.CRUD(this.props.tableName);
const hide = message.loading('正在新增...', 0);
try {
const res = await CRUD.insert(obj);
hide();
if (res.success) {
notification.success({
message: '新增成功',
description: this.primaryKey ? `新增数据行 主键=${res.data[this.primaryKey]}` : '',
duration: 3,
});
// 数据变化后, 刷新下表格, 我之前是变化后刷新整个页面的, 想想还是只刷新表格比较好
// 新增的数据放到第一行
const newData = [];
const transformedData = this.transformRawDataToTable(res.data);
// 表格中的每条记录都必须有个唯一的key, 否则会有warn, 如果有主键就用主键, 否则只能随便给个
// 如果key有重复的, 会有warn, 显示也会有问题, 所以后端接口要注意下, 如果DB主键都能重复, 也只能呵呵了...
if (this.primaryKey) {
transformedData.key = res.data[this.primaryKey];
} else {
transformedData.key = Math.floor(Math.random() * 233333); // MAGIC NUMBER
}
newData.push(transformedData);
for (const record of this.state.data) {
newData.push(record);
}
this.setState({selectedRowKeys: [], data: newData});
} else {
this.error(res.message);
}
} catch (ex) {
logger.error('insert exception, %o', ex);
hide();
this.error(`网络请求出错: ${ex.message}`);
}
}
/**
* 真正去更新数据
*/
async handleUpdate(obj, keys = this.state.selectedRowKeys) {
const CRUD = ajax.CRUD(this.props.tableName);
const hide = message.loading('正在更新...', 0);
try {
const res = await CRUD.update(keys, obj);
hide();
if (res.success) {
notification.success({
message: '更新成功',
description: `更新${res.data}条数据`,
duration: 3,
});
// 数据变化后, 刷新下表格
const transformedData = this.transformRawDataToTable(obj);
const newData = [];
const keySet = new Set(keys); // array转set
for (const record of this.state.data) {
if (keySet.has(record.key)) { // 是否是被更新的记录
const newRecord = Object.assign({}, record, transformedData); // 这个应该是浅拷贝
newRecord.$$rawData = Object.assign({}, record.$$rawData, transformedData.$$rawData);
logger.debug('newRecord = %o', newRecord);
newData.push(newRecord);
} else {
newData.push(record);
}
}
this.setState({selectedRowKeys: [], data: newData});
} else {
this.error(res.message);
}
} catch (ex) {
logger.error('update exception, %o', ex);
hide();
this.error(`网络请求出错: ${ex.message}`);
}
}
/**
* 真正去删除数据
*/
async handleDelete(keys = this.state.selectedRowKeys) {
const CRUD = ajax.CRUD(this.props.tableName);
const hide = message.loading('正在删除...', 0);
try {
const res = await CRUD.delete(keys);
hide();
if (res.success) {
notification.success({
message: '删除成功',
description: `删除${res.data}条数据`,
duration: 3,
});
// 数据变化后, 刷新下表格
const newData = [];
const keySet = new Set(keys); // array转set
for (const record of this.state.data) {
if (!keySet.has(record.key)) { // 是否是被删除的记录
newData.push(record);
}
}
this.setState({selectedRowKeys: [], data: newData});
} else {
this.error(res.message);
}
} catch (ex) {
logger.error('delete exception, %o', ex);
hide();
this.error(`网络请求出错: ${ex.message}`);
}
}
render() {
const {tableName, schema, tableLoading, tableConfig} = this.props;
// 根据当前的tableName, 获取对应的表单组件
const FormComponent = InnerTableSchemaUtils.getForm(tableName, schema);
const rowSelection = {
selectedRowKeys: this.state.selectedRowKeys,
onChange: this.onTableSelectChange,
};
const hasSelected = this.state.selectedRowKeys.length > 0; // 是否选择
const multiSelected = this.state.selectedRowKeys.length > 1; // 是否选择了多项
const UpdateComponent = this.updateComponent;
var cardNode = this.state.data.map(function(cad){
console.info(cad);
let onText, runningText, onIcon, runningIcon;
return (
<div>
<Col span={8} className="row-list">
<Card title={cad.name} bordered={false} >
<div className="custom-image">
<Row type="flex" className="yield">
<Col span={24} order={1}>{cad.yield}</Col>
</Row>
<Row type="flex">
<Col span={24} order={1}>{cad.yield_msg}</Col>
</Row>
</div>
<div className="custom-list">
<Row type="flex">
<Col span={12} order={1} className="left">{cad.left.name}<span>{cad.left.value}</span></Col>
<Col span={12} order={2} className="right">{cad.right.name}<span>{cad.right.value}</span></Col>
</Row>
</div>
</Card>
</Col>
</div>
);
});
return (
<div className="capacity-province-main" style={{ background: '#f8f8f8', padding: '30px' }}>
<div><p></p></div>
<Row gutter={16}>
{cardNode}
</Row>
</div>
);
}
}
export default InnerCapacityDetail;
|
Code/V1/src/src/Login.js | neurotechuoft/MindType | import React, { Component } from 'react';
import logo from './mindtype_logo.png';
import io from "socket.io-client";
const nlp_socket = io('http://34.73.165.89:8001'); // Socket to connect to NLP Service.
const robot_socket = io('http://localhost:8003'); // Socket to connect to RobotJS
class Login extends React.Component {
constructor(props) {
super(props);
this.state = {
emailValue: '',
passwordValue: ''
};
this.handleLoginClick = this.handleLoginClick.bind(this);
this.checkLogin = this.checkLogin.bind(this);
}
handleLoginClick(){
let login = {
'username': this.state.emailValue,
'password': this.state.passwordValue
};
robot_socket.emit("login", JSON.stringify(login), this.checkLogin);
this.props.loginHandler();
}
checkLogin(sid, tf){
if (tf === false){
alert('Please enter a valid email that has not been taken and a valid password');
} else {
this.props.loginHandler();
}
}
render(){
return (
<div>
<img src={logo} className="logoMindType"/><br />
<br/>
<input type="email" value={this.state.emailValue} className="email-input" placeholder="Email"></input><br />
<br />
<input type="password" value={this.state.passwordValue} className="password-input" placeholder="Password"></input><br />
<br />
<button className="login" onClick={this.handleLoginClick}>Login</button>
<br />
<button className="back" onClick={this.props.goBack}>Go Back</button>
</div>
)
}
}
export default Login;
|
packages/material-ui-icons/src/Message.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Message = props =>
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z" />
</SvgIcon>;
Message = pure(Message);
Message.muiName = 'SvgIcon';
export default Message;
|
app/components/Header/index.js | lizhaogai/lyda-dada-v | import React from 'react';
import {FormattedMessage} from 'react-intl';
import A from './A';
import Img from './Img';
import NavBar from './NavBar';
import HeaderLink from './HeaderLink';
import Banner from './banner.jpg';
import messages from './messages';
class Header extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<A href="https://twitter.com/mxstbr">
<Img src={Banner} alt="react-boilerplate - Logo"/>
</A>
<NavBar>
<HeaderLink to="/">
<FormattedMessage {...messages.home} />
</HeaderLink>
<HeaderLink to="/features">
<FormattedMessage {...messages.features} />
</HeaderLink>
<HeaderLink to="/123/data_v/dataSource">
LydaDataV
</HeaderLink>
</NavBar>
</div>
);
}
}
export default Header;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.