path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
Root.js | praida/admin | import React from 'react';
import PropTypes from 'prop-types';
import { IntlProvider } from 'react-intl';
import { Provider } from 'react-redux';
import './styles/normalize.scss';
import './styles/default.scss';
import './styles/layout.scss';
import Routes from './Routes';
const Root = props => (
<IntlProvider locale="en">
<Provider store={props.store}>
<Routes />
</Provider>
</IntlProvider>
);
Root.propTypes = {
store: PropTypes.object.isRequired,
};
export default Root;
|
src/interface/common/Alert/index.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
class Alert extends React.PureComponent {
static propTypes = {
kind: PropTypes.oneOf(['danger', 'warning', 'info']),
children: PropTypes.node.isRequired,
className: PropTypes.string,
};
render() {
const { kind, children, className, ...others } = this.props;
return (
<div className={`alert alert-${kind} ${className || ''}`} {...others}>
{children}
</div>
);
}
}
export default Alert;
|
app/javascript/flavours/glitch/features/ui/components/image_loader.js | vahnj/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class ImageLoader extends React.PureComponent {
static propTypes = {
alt: PropTypes.string,
src: PropTypes.string.isRequired,
previewSrc: PropTypes.string.isRequired,
width: PropTypes.number,
height: PropTypes.number,
}
static defaultProps = {
alt: '',
width: null,
height: null,
};
state = {
loading: true,
error: false,
}
removers = [];
get canvasContext() {
if (!this.canvas) {
return null;
}
this._canvasContext = this._canvasContext || this.canvas.getContext('2d');
return this._canvasContext;
}
componentDidMount () {
this.loadImage(this.props);
}
componentWillReceiveProps (nextProps) {
if (this.props.src !== nextProps.src) {
this.loadImage(nextProps);
}
}
loadImage (props) {
this.removeEventListeners();
this.setState({ loading: true, error: false });
Promise.all([
this.loadPreviewCanvas(props),
this.hasSize() && this.loadOriginalImage(props),
].filter(Boolean))
.then(() => {
this.setState({ loading: false, error: false });
this.clearPreviewCanvas();
})
.catch(() => this.setState({ loading: false, error: true }));
}
loadPreviewCanvas = ({ previewSrc, width, height }) => new Promise((resolve, reject) => {
const image = new Image();
const removeEventListeners = () => {
image.removeEventListener('error', handleError);
image.removeEventListener('load', handleLoad);
};
const handleError = () => {
removeEventListeners();
reject();
};
const handleLoad = () => {
removeEventListeners();
this.canvasContext.drawImage(image, 0, 0, width, height);
resolve();
};
image.addEventListener('error', handleError);
image.addEventListener('load', handleLoad);
image.src = previewSrc;
this.removers.push(removeEventListeners);
})
clearPreviewCanvas () {
const { width, height } = this.canvas;
this.canvasContext.clearRect(0, 0, width, height);
}
loadOriginalImage = ({ src }) => new Promise((resolve, reject) => {
const image = new Image();
const removeEventListeners = () => {
image.removeEventListener('error', handleError);
image.removeEventListener('load', handleLoad);
};
const handleError = () => {
removeEventListeners();
reject();
};
const handleLoad = () => {
removeEventListeners();
resolve();
};
image.addEventListener('error', handleError);
image.addEventListener('load', handleLoad);
image.src = src;
this.removers.push(removeEventListeners);
});
removeEventListeners () {
this.removers.forEach(listeners => listeners());
this.removers = [];
}
hasSize () {
const { width, height } = this.props;
return typeof width === 'number' && typeof height === 'number';
}
setCanvasRef = c => {
this.canvas = c;
}
render () {
const { alt, src, width, height } = this.props;
const { loading } = this.state;
const className = classNames('image-loader', {
'image-loader--loading': loading,
'image-loader--amorphous': !this.hasSize(),
});
return (
<div className={className}>
<canvas
className='image-loader__preview-canvas'
width={width}
height={height}
ref={this.setCanvasRef}
style={{ opacity: loading ? 1 : 0 }}
/>
{!loading && (
<img
alt={alt}
className='image-loader__img'
src={src}
width={width}
height={height}
/>
)}
</div>
);
}
}
|
src/pages/PrivacyPage.js | neontribe/gbptm | import React from 'react';
import { Helmet } from 'react-helmet';
import PageLayout from '../components/PageLayout';
import Container from '../components/Container';
import Text from '../components/Text';
import Spacer from '../components/Spacer';
import Button from '../components/Button';
import config from '../config';
const PrivacyPage = () => {
return (
<PageLayout layoutMode="blog">
<Helmet>
<title>{config.getTitle('Privacy Policy')}</title>
</Helmet>
<Container maxWidth={845}>
<Text fontSize={6} fontWeight="bold" textAlign="center">
<h1>Privacy Policy</h1>
</Text>
<Spacer mb={5} />
<Text fontSize={3} fontWeight="bold">
<h2>Visitors to the site</h2>
</Text>
<Spacer mb={3} />
<p>
The Great British Public Toilet Map uses a cookieless approach to
gather anonymous data such as which pages are viewed, what time the
visit occurred, and which site referred the visitor to the web page
etc.
</p>
<p>
Public Convenience Ltd also notes and saves information such as time
of day, browser type and content requested. That information is used
to provide more relevant services to users.
</p>
<p>
We will not associate any data gathered from this site through
navigation and with any personally identifying information from any
source. We may also log Internet Protocol (IP) address (but nothing
that directly identifies visitors) in order to receive and send the
required information over the internet.
</p>
<Spacer mb={4} />
<Text fontSize={3} fontWeight="bold">
<h2>Contributors to the site</h2>
</Text>
<Spacer mb={3} />
<p>
Contributors to The Great British Public Toilet Map website are asked
to sign-in via the Auth0 platform using their email address. This
helps us to share data on the quantity and spread of contributions to
the site which helps show how the community value the project, to
improve our interfaces for our users, to protect our dataset from
misuse and to recognise contributions from a user if that user is
adding unsuitable content, whether intentionally or inadvertently.
</p>
<p>
A full list of a contributor’s activities will only be accessible to
Public Convenience Ltd, for
moderating the dataset. A contributor’s full email address will never
be disclosed or shared and is only visible to Public Convenience Ltd.
</p>
<Spacer mb={4} />
<p>
If you'd like to know what we've stored about you, or ask us to forget
you, or to let us know about something you'd like changed please drop
us a line at{' '}
<Button
as="a"
variant="link"
href="mailto:[email protected]"
target="_blank"
rel="noopener noreferrer"
>
[email protected]
</Button>
. If you'd like to exercise any of your rights under the GDPR that's
the address to use.
</p>
</Container>
</PageLayout>
);
};
export default PrivacyPage;
|
src/components/IntroScreen/index.js | vogelino/design-timeline | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import ReactMarkdown from 'react-markdown';
import ScrollArea from '../ScrollArea';
import { combineCssClasses } from '../../helpers/styleHelper';
import * as introScreenActions from '../../redux/actions/introScreenActions';
import IntroBubbles from './IntroBubbles';
import './IntroScreen.css';
export const IntroScreenComponent = ({
visible,
text,
title,
buttonText,
hideIntroScreen,
}) => (
<div
className={combineCssClasses({
introscreen: true,
'introscreen--visible': visible,
'introscreen--hidden': !visible,
})}
>
<div className="introscreen_content">
<div className="introscreen_start-title">{title}</div>
<ScrollArea className="introscreen_start-text">
<ReactMarkdown source={text} />
</ScrollArea>
<button
className="introscreen_start-button"
onClick={hideIntroScreen}
>
{buttonText}
</button>
</div>
<div className="introscreen_ocean">
<div className="introscreen_wave" />
</div>
<IntroBubbles />
</div>
);
IntroScreenComponent.defaultProps = {
visible: true,
title: '',
text: '',
buttonText: '',
hideIntroScreen: (x) => x,
};
IntroScreenComponent.propTypes = {
visible: PropTypes.bool,
title: PropTypes.string,
text: PropTypes.string,
buttonText: PropTypes.string,
hideIntroScreen: PropTypes.func,
};
const mapStateToProps = ({ introScreen }) => ({ ...introScreen });
const mapDispatchToProps = (dispatch) => bindActionCreators(introScreenActions, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(IntroScreenComponent);
|
src/svg-icons/notification/phone-paused.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationPhonePaused = (props) => (
<SvgIcon {...props}>
<path d="M17 3h-2v7h2V3zm3 12.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 3v7h2V3h-2z"/>
</SvgIcon>
);
NotificationPhonePaused = pure(NotificationPhonePaused);
NotificationPhonePaused.displayName = 'NotificationPhonePaused';
NotificationPhonePaused.muiName = 'SvgIcon';
export default NotificationPhonePaused;
|
docs/src/main.js | kwangkim/nuclear-js | import React from 'react'
import ItemFilterExample from './components/item-filter-example'
import addScrollClass from './utils/scroll-class'
addScrollClass("scrolled")
render(ItemFilterExample, 'item-filter-example')
updateSideBar()
function render(component, id) {
var el = document.getElementById(id)
if (el) {
React.render(React.createElement(component), el)
}
}
function updateSideBar() {
var sideBarElements = document.getElementsByClassName('sidebar-links--item')
for (var i in sideBarElements) {
if (sideBarElements[i].firstChild) {
if (window.location.href === sideBarElements[i].firstChild.href) {
sideBarElements[i].className = 'sidebar-links--item-active'
} else {
sideBarElements[i].className = 'sidebar-links--item'
}
}
}
}
|
src/App.js | stevecd/mpcnc_calc_react | import React, { Component } from 'react';
import update from 'react-addons-update';
import {Navbar, Tabs, Tab, Input, Grid, Row, Col, Button } from 'react-bootstrap';
import 'bootstrap/dist/css/bootstrap.css';
import './App.css';
let defaultState = {
x: 21,
y: 21,
z: 6.1,
xCa: 11,
yCa: 11,
zCa: 7.9,
xBa: 7,
yBa: 7,
units: "Inches"
}
export default class App extends Component {
constructor(props) {
super(props)
const { query } = this.props.location
defaultState = update(defaultState, { $merge: query })
this.state = defaultState
}
handleXChange = (e) => {
const newState = update(this.state, {
x: {$set: e.target.value}
})
this.setState(newState)
}
handleYChange = (e) => {
const newState = update(this.state, {
y: {$set: e.target.value}
})
this.setState(newState)
}
handleZChange = (e) => {
const newState = update(this.state, {
z: {$set: e.target.value}
})
this.setState(newState)
}
handleResetToDefaults = (e) => {
const newState = defaultState
this.setState(newState)
}
handleXAdditionChange = (e) => {
const newState = update(this.state, { xCa: {$set: e.target.value} })
this.setState(newState)
}
handleYAdditionChange = (e) => {
const newState = update(this.state, {yCa: {$set: e.target.value}})
this.setState(newState)
}
handleZAdditionChange = (e) => {
const newState = update(this.state, {zCa: {$set: e.target.value}})
this.setState(newState)
}
handleXBeltAdditionChange = (e) => {
const newState = update(this.state, {xBa: {$set: e.target.value}})
this.setState(newState)
}
handleYBeltAdditionChange = (e) => {
const newState = update(this.state, {yBa: {$set: e.target.value}})
this.setState(newState)
}
handleUnitsChange = (e) => {
if(this.state.units == "Centimeters" && e.target.value == "Inches"){
let convertedValues = {}
for(let key in this.state) {
if(!isNaN(this.state[key])) {
convertedValues[key] = this.state[key] / 2.54
}
}
convertedValues.units = "Inches"
this.setState(convertedValues)
} else if(this.state.units == "Inches" && e.target.value == "Centimeters") {
let convertedValues = {}
for(let key in this.state) {
if(!isNaN(this.state[key])) {
convertedValues[key] = this.state[key] * 2.54
}
}
convertedValues.units = "Centimeters"
this.setState(convertedValues)
}
}
// http://stackoverflow.com/questions/1714786/querystring-encoding-of-a-javascript-object
serialize(obj) {
let str = [];
for(let p in obj)
if (obj.hasOwnProperty(p)) {
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
}
return str.join("&");
}
calculateValues = () => {
let result = {
xConduitLength: parseFloat(this.state.x) + parseFloat(this.state.xCa),
yConduitLength: parseFloat(this.state.y) + parseFloat(this.state.yCa),
zConduitLength: parseFloat(this.state.z) + parseFloat(this.state.zCa),
}
result.zThreadedRod = result.zConduitLength - 2
result.xBelt = result.xConduitLength + parseFloat(this.state.xBa),
result.yBelt = result.yConduitLength + parseFloat(this.state.yBa),
result.totalXConduit = result.xConduitLength * 3
result.totalYConduit = result.yConduitLength * 3
result.totalZConduit = result.zConduitLength * 2
result.totalConduit = result.totalXConduit + result.totalYConduit + result.totalZConduit
result.totalXBelt = result.xBelt * 2
result.totalYBelt = result.yBelt * 2
result.totalBelt = result.totalXBelt + result.totalYBelt
for(let key in result) {
if(isNaN(result[key])) {
result[key] = NaN
} else {
result[key] = parseFloat(result[key]).toFixed(1)
}
}
result.link = new RegExp(/^.*\//).exec(window.location.href) + "?" + this.serialize(this.state)
return result
}
render() {
const calculatedValues = this.calculateValues()
return (
<Grid>
<Navbar fixedTop>
<Navbar.Header>
<Navbar.Brand>
Simple MPCNC Calc
</Navbar.Brand>
</Navbar.Header>
</Navbar>
<Row>
<Tabs defaultActiveKey={1} animation={false}>
<br/>
<Tab eventKey={1} title="Calc">
<Row>
<Col xs={4} md={4}>
<form className="form-horizontal">
<fieldset>
<legend>Desired Cutting Area</legend>
<Input
type="number"
step="0.1"
placeholder="X Dimension"
value={this.state.x}
onChange={this.handleXChange}
label="X:"
labelClassName="col-xs-2"
wrapperClassName="col-xs-10"
/>
<Input
type="number"
step="0.1"
placeholder="Y Dimension"
value={this.state.y}
onChange={this.handleYChange}
label="Y:"
labelClassName="col-xs-2"
wrapperClassName="col-xs-10"
/>
<Input
type="number"
step="0.1"
placeholder="Z Dimension"
value={this.state.z}
onChange={this.handleZChange}
label="Z:"
labelClassName="col-xs-2"
wrapperClassName="col-xs-10"
/>
<Input
type="select"
label="Units:"
labelClassName="col-xs-2"
wrapperClassName="col-xs-8 col-xs-offset-2"
onChange={this.handleUnitsChange}
value={this.state.units}
>
<option value="Inches">Inches</option>
<option value="Centimeters">Centimeters</option>
</Input>
<Button
className="pull-right"
onClick={this.handleResetToDefaults}
>Reset To Defaults</Button><br /><br />
<Input
type="textarea"
placeholder="Link to this config"
label="Link:"
value={calculatedValues.link}
rows={4}
readOnly
/>
</fieldset>
</form>
</Col>
<Col xs={4} md={4}>
<form className="form-horizontal">
<fieldset>
<legend>Piece Lengths</legend>
<Input type="text" label="X Conduit" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.xConduitLength} addonAfter="x 3" readOnly />
<Input type="text" label="Y Conduit" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.yConduitLength} addonAfter="x 3" readOnly />
<Input type="text" label="Z Conduit" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.zConduitLength} addonAfter="x 2" readOnly />
<hr/>
<Input type="text" label="Z Rod" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.zThreadedRod} addonAfter="x 1" readOnly />
<hr />
<Input type="text" label="X Belt" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.xBelt} addonAfter="x 2" readOnly />
<Input type="text" label="Y Belt" labelClassName="col-xs-5" wrapperClassName="col-xs-7" value={calculatedValues.yBelt} addonAfter="x 2" readOnly />
</fieldset>
</form>
</Col>
<Col xs={4} md={4}>
<form className="form-horizontal">
<fieldset>
<legend>Total Lengths</legend>
<Input type="text" label="X Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalXConduit} readOnly />
<Input type="text" label="Y Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalYConduit} readOnly />
<Input type="text" label="Z Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalZConduit} readOnly />
<Input type="text" label="Total Conduit" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalConduit} readOnly />
<hr/>
<Input type="text" label="X Total Belt" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalXBelt} readOnly />
<Input type="text" label="Y Total Belt" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalYBelt} readOnly />
<Input type="text" label="Total Belt" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={calculatedValues.totalBelt} readOnly />
</fieldset>
</form>
</Col>
</Row>
<Row>
<form className="form-horizontal">
<fieldset>
<legend>Settings</legend>
<Col xs={6}>
<Input type="number" step="0.1" label="Added to X Conduits" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.xCa} onChange={this.handleXAdditionChange}/>
<Input type="number" step="0.1" label="Added to Y Conduits" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.yCa} onChange={this.handleYAdditionChange}/>
<Input type="number" step="0.1" label="Added to Z Conduits" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.zCa} onChange={this.handleZAdditionChange}/>
</Col>
<Col xs={6}>
<Input type="number" step="0.1" label="Added to X Belts" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.xBa} onChange={this.handleXBeltAdditionChange}/>
<Input type="number" step="0.1" label="Added to Y Belts" labelClassName="col-xs-7" wrapperClassName="col-xs-5" value={this.state.yBa} onChange={this.handleYBeltAdditionChange}/>
</Col>
</fieldset>
</form>
</Row>
</Tab>
<Tab eventKey={3} title="About">
<Row>
<ul>
<li>
Values for default settings ( <a href="http://stevecd.github.io/mpcnc_calc_react/">http://stevecd.github.io/mpcnc_calc_react/</a> ) come from these <a href="http://public.vicious1.de/Assembly_Instructions_v0.2.pdf">Detailed Assembly Instructions</a> by <a href="http://www.vicious1.com/forums/users/bofferle/">Bofferle</a> .
</li>
<li>
I made this app while following along with the React.js <a href="https://facebook.github.io/react/docs/getting-started.html">getting started tutorial.</a>
</li>
<li>
It is a simple take on the <a href="http://www.thingiverse.com/thing:948320">Mostly Printed CNC / Multitool Layout Size Calculator</a> by <a href="http://www.thingiverse.com/GeoDave/about">GeoDave</a>.
</li>
<li>
repo at <a href="https://github.com/stevecd/mpcnc_calc_react">https://github.com/stevecd/mpcnc_calc_react</a>
</li>
</ul>
</Row>
</Tab>
</Tabs>
</Row>
</Grid>
);
}
}
|
packages/reactor-kitchensink/src/examples/DragAndDrop/Proxies/Proxies.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Panel } from '@extjs/ext-react';
import './styles.css';
Ext.require(['Ext.drag.*']);
export default class Proxies extends Component {
state = {
noneText: 'No Proxy'
}
render() {
const {noneText} = this.state;
return (
<Panel
ref="mainPanel"
padding={5}
shadow
>
<div ref="none" className="proxy-none proxy-source">{noneText}</div>
<div ref="original" className="proxy-original proxy-source">Element as proxy with revert: true</div>
<div ref="placeholder" className="proxy-placeholder proxy-source">Placeholder</div>
</Panel>
)
}
componentDidMount() {
this.sources = [
// No proxy, just track the mouse cursor
new Ext.drag.Source({
element: this.refs.none,
constrain: this.refs.mainPanel.el,
proxy: 'none',
listeners: {
dragmove: (source, info) => {
const pos = info.proxy.current,
noneText = Ext.String.format('X: {0}, Y: {1}', Math.round(pos.x), Math.round(pos.y));
this.setState({ noneText });
},
dragend: () => {
this.setState({ noneText: 'No Proxy' });
}
}
}),
// Use the drag element as the proxy. Animate it back into position on drop.
new Ext.drag.Source({
element: this.refs.original,
revert: true,
constrain: this.refs.mainPanel.el,
proxy: 'original'
}),
// Leave the drag element in place and create a custom placeholder.
new Ext.drag.Source({
element: this.refs.placeholder,
constrain: this.refs.mainPanel.el,
proxy: {
type: 'placeholder',
cls: 'proxy-drag-custom',
html: 'Custom'
}
})
];
}
componentWillUnmount() {
this.sources.forEach(Ext.destroy.bind(Ext));
}
} |
src/components/searchBar.js | gabriellisboa/reduxStudies | import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: '' };
}
onInputChange(event) {
this.setState({
term: event.target.value,
});
}
render() {
return (
<div className="search-bar">
<input
value={this.state.term}
onChange={(event) => this.onInputChange(event.target.value)}
/>
</div>
);
}
onInputChange(term) {
this.setState({ term });
this.props.onSearchTermChange(term);
}
};
export default SearchBar; |
src/svg-icons/action/stars.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionStars = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zm4.24 16L12 15.45 7.77 18l1.12-4.81-3.73-3.23 4.92-.42L12 5l1.92 4.53 4.92.42-3.73 3.23L16.23 18z"/>
</SvgIcon>
);
ActionStars = pure(ActionStars);
ActionStars.displayName = 'ActionStars';
ActionStars.muiName = 'SvgIcon';
export default ActionStars;
|
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js | Jaeandroid/actor-platform | import React from 'react';
import { PureRenderMixin } from 'react/addons';
import classNames from 'classnames';
import DialogStore from 'stores/DialogStore';
export default React.createClass({
mixins: [PureRenderMixin],
getInitialState() {
return {
typing: null,
show: false
};
},
componentDidMount() {
DialogStore.addTypingListener(this.onTypingChange);
},
componentWillUnmount() {
DialogStore.removeTypingListener(this.onTypingChange);
},
onTypingChange() {
const typing = DialogStore.getSelectedDialogTyping();
if (typing === null) {
this.setState({show: false});
} else {
this.setState({typing: typing, show: true});
}
},
render() {
const typing = this.state.typing;
const show = this.state.show;
const typingClassName = classNames('typing', {
'typing--hidden': show === false
});
return (
<div className={typingClassName}>
<div className="typing-indicator"><i></i><i></i><i></i></div>
<span>{typing}</span>
</div>
);
}
});
|
src/app/js/index.js | AppSaloon/socket.io-tester | import { Provider } from 'react-redux'
import { createStore } from 'redux'
import React from 'react'
import { render } from 'react-dom'
import reducer from './reducers/reducer'
import App from './components/App'
const store = createStore(reducer,
window.devToolsExtension ? window.devToolsExtension() : undefined
);
export { store }
render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('app')
)
|
src/components/PostDetail.js | ksco/reblog | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Header, Segment } from 'semantic-ui-react';
import marked from 'marked';
import getPostDetail from '../actions/post';
import getPostComments from '../actions/comments';
import { post } from '../selectors';
import Spinner from './Spinner';
import Empty from './Empty';
import Comments from './Comments';
import Labels from './Labels';
class PostDetail extends Component {
componentDidMount() {
this.fetchPost(this.props);
}
fetchPost({ post, selectedPostId, accessToken, fetchPost, fetchComments }) {
if (!post) {
fetchPost(selectedPostId, accessToken);
}
fetchComments(selectedPostId, accessToken);
}
render() {
const { post, postLoading, commentsLoading } = this.props;
if (post === null) {
if (postLoading === true) {
return <Spinner />;
}
return <Empty />;
}
return (
<div>
<Header
as='h2'
textAlign='center'
attached='top'
style={{ marginTop: '1em' }}
>
{post.title}
</Header>
<Segment attached>
<div className='marked' dangerouslySetInnerHTML={{__html: marked(post.body)}}></div>
</Segment>
<Labels labels={post.labels} />
<Comments comments={post.comments} loading={commentsLoading} />
</div>
);
}
}
const mapStateToProps = (state) => ({
post: post(state),
selectedPostId: parseInt(state.router.params.postId, 10),
postLoading: state.state.loading.post,
commentsLoading: state.state.loading.comments,
accessToken: state.state.auth.accessToken,
});
const mapDispatchToProps = (dispatch) => ({
fetchPost: (selectedPostId, accessToken) => dispatch(getPostDetail(selectedPostId, accessToken)),
fetchComments: (selectedPostId, accessToken) => dispatch(getPostComments(selectedPostId, accessToken)),
});
export default connect(mapStateToProps, mapDispatchToProps)(PostDetail); |
src/components/Currency.js | KingKone/oversee | import React, { Component } from 'react';
import { ipcRenderer } from 'electron';
import { LineChart, Line, XAxis, YAxis, CartesianGrid, Tooltip, Legend } from 'recharts';
let data = [];
let lcup = 0;
class Currency extends React.Component {
render() {
return (
<div className="currency">
<div className="cusymb"><h1>{this.props.data.symbol}</h1> </div>
<div className="cutext">
<h4>{this.props.data.name}</h4>
<p>{this.props.data.price_usd} USD</p>
</div>
</div>
);
}
}
export default Currency;
|
docs/app/Examples/elements/Image/index.js | jcarbo/stardust | import React from 'react'
import Types from './Types'
import States from './States'
import Variations from './Variations'
import Groups from './Groups'
const ImageExamples = () => (
<div>
<Types />
<States />
<Variations />
<Groups />
</div>
)
export default ImageExamples
|
src/elements/Image/ImageGroup.js | shengnian/shengnian-ui-react | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
SUI,
} from '../../lib'
/**
* A group of images.
*/
function ImageGroup(props) {
const { children, className, content, size } = props
const classes = cx('ui', size, className, 'images')
const rest = getUnhandledProps(ImageGroup, props)
const ElementType = getElementType(ImageGroup, props)
return (
<ElementType {...rest} className={classes}>
{childrenUtils.isNil(children) ? content : children}
</ElementType>
)
}
ImageGroup._meta = {
name: 'ImageGroup',
parent: 'Image',
type: META.TYPES.ELEMENT,
}
ImageGroup.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Shorthand for primary content. */
content: customPropTypes.contentShorthand,
/** A group of images can be formatted to have the same size. */
size: PropTypes.oneOf(SUI.SIZES),
}
export default ImageGroup
|
packages/wix-style-react/src/Page/test/examples/Breadcrumbs.js | wix/wix-style-react | import React from 'react';
import { Breadcrumbs } from 'wix-style-react';
export default (
<Breadcrumbs
items={[1, 2, 3].map(i => ({ id: `${i}`, value: `#${i} item` }))}
activeId="3"
size="medium"
theme="onGrayBackground"
onClick={() => {}}
/>
);
|
src/index.js | shhaumb/react-redux-subapp | import React from 'react';
import PropTypes from 'prop-types';
import hoistStatics from 'hoist-non-react-statics';
import { subspace, namespaced } from 'redux-subspace';
import { subspaced } from 'redux-subspace-saga';
import { addReducer } from 'redux-transient';
import { subAppEnhancer } from './enhancer';
export { subAppEnhancer } from './enhancer';
// Depricated
export const enhancer = subAppEnhancer;
const ACTION_INITIALIZE_REDUCER_TYPE = '@react-redux-subapp/INIT';
const initializeReducer = () => ({
type: ACTION_INITIALIZE_REDUCER_TYPE,
});
const sagaRunForSubAppKeyMap = {};
const mapState = subAppKey => (state) => {
let subState = state;
const keys = subAppKey.split('.');
keys.forEach((key) => {
if (subState !== undefined) {
subState = subState[key];
}
});
return subState;
};
const subAppCreator = (subAppKey, WrappedComponent, reducer, options) => {
const wrappedComponentName = WrappedComponent.displayName
|| WrappedComponent.name
|| 'Component';
const displayName = `SubApp(${wrappedComponentName}, subAppKey=${subAppKey})`;
class SubApp extends React.Component {
getChildContext() {
return {
store: subspace(mapState(subAppKey), subAppKey)(this.getStore()),
};
}
componentWillMount() {
const store = this.getStore();
store.dispatch(addReducer(reducer));
store.dispatch(initializeReducer());
if (options.saga && (!sagaRunForSubAppKeyMap[subAppKey])) {
const subspacedSaga = subspaced(mapState(subAppKey), subAppKey)(options.saga);
store.runSaga(subspacedSaga);
sagaRunForSubAppKeyMap[subAppKey] = true;
}
}
getStore() {
let { store } = this.context;
if (store.rootStore) {
store = store.rootStore;
}
return store;
}
render() {
return <WrappedComponent {...this.props} />;
}
}
SubApp.propTypes = {};
SubApp.contextTypes = {
store: PropTypes.object.isRequired,
};
SubApp.childContextTypes = {
store: PropTypes.object,
};
SubApp.WrappedComponent = WrappedComponent;
SubApp.displayName = displayName;
return hoistStatics(SubApp, WrappedComponent);
};
const refined = (subAppKey, reducer, initialState) => (state, action) => {
let subState = mapState(subAppKey)(state);
if (subState === undefined) {
subState = initialState;
}
const keys = subAppKey.split('.');
const resultState = {
...state,
};
let parentState = resultState;
if (keys.length > 1) {
keys.splice(0, keys.length - 1).forEach((key) => {
if (parentState[key] === undefined) {
parentState[key] = {};
}
parentState = parentState[key];
});
}
parentState[keys[0]] = reducer(subState, action);
return resultState;
};
const mapping = {};
export const createAppFactory = (WrappedComponent, reducer, initialState, options = {}) => (subAppKey) => {
if (subAppKey in mapping) {
if (mapping[subAppKey].wrapped === WrappedComponent) {
return mapping[subAppKey].subApp;
}
throw new Error(`store's key=${subAppKey} is already mapped with another component ${mapping[subAppKey].wrapped}`);
}
const namespacedReducer = namespaced(subAppKey)(reducer);
const refinedReducer = refined(subAppKey, namespacedReducer, initialState);
const subApp = subAppCreator(subAppKey, WrappedComponent, refinedReducer, options);
mapping[subAppKey] = {
wrapped: WrappedComponent,
subApp,
};
return subApp;
};
|
Skins/VetoccitanT3/ReactSrc/node_modules/react-redux/src/hooks/useStore.js | ENG-SYSTEMS/Kob-Eye | import { useContext } from 'react'
import { ReactReduxContext } from '../components/Context'
import { useReduxContext as useDefaultReduxContext } from './useReduxContext'
/**
* Hook factory, which creates a `useStore` hook bound to a given context.
*
* @param {React.Context} [context=ReactReduxContext] Context passed to your `<Provider>`.
* @returns {Function} A `useStore` hook bound to the specified context.
*/
export function createStoreHook(context = ReactReduxContext) {
const useReduxContext =
context === ReactReduxContext
? useDefaultReduxContext
: () => useContext(context)
return function useStore() {
const { store } = useReduxContext()
return store
}
}
/**
* A hook to access the redux store.
*
* @returns {any} the redux store
*
* @example
*
* import React from 'react'
* import { useStore } from 'react-redux'
*
* export const ExampleComponent = () => {
* const store = useStore()
* return <div>{store.getState()}</div>
* }
*/
export const useStore = /*#__PURE__*/ createStoreHook()
|
src/components/views/elements/AddressSelector.js | aperezdc/matrix-react-sdk | /*
Copyright 2015, 2016 OpenMarket Ltd
Copyright 2017 Vector Creations Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import sdk from '../../../index';
import classNames from 'classnames';
import { UserAddressType } from '../../../UserAddress';
export default React.createClass({
displayName: 'AddressSelector',
propTypes: {
onSelected: PropTypes.func.isRequired,
// List of the addresses to display
addressList: PropTypes.arrayOf(UserAddressType).isRequired,
// Whether to show the address on the address tiles
showAddress: PropTypes.bool,
truncateAt: PropTypes.number.isRequired,
selected: PropTypes.number,
// Element to put as a header on top of the list
header: PropTypes.node,
},
getInitialState: function() {
return {
selected: this.props.selected === undefined ? 0 : this.props.selected,
hover: false,
};
},
componentWillReceiveProps: function(props) {
// Make sure the selected item isn't outside the list bounds
const selected = this.state.selected;
const maxSelected = this._maxSelected(props.addressList);
if (selected > maxSelected) {
this.setState({ selected: maxSelected });
}
},
componentDidUpdate: function() {
// As the user scrolls with the arrow keys keep the selected item
// at the top of the window.
if (this.scrollElement && this.props.addressList.length > 0 && !this.state.hover) {
const elementHeight = this.addressListElement.getBoundingClientRect().height;
this.scrollElement.scrollTop = (this.state.selected * elementHeight) - elementHeight;
}
},
moveSelectionTop: function() {
if (this.state.selected > 0) {
this.setState({
selected: 0,
hover: false,
});
}
},
moveSelectionUp: function() {
if (this.state.selected > 0) {
this.setState({
selected: this.state.selected - 1,
hover: false,
});
}
},
moveSelectionDown: function() {
if (this.state.selected < this._maxSelected(this.props.addressList)) {
this.setState({
selected: this.state.selected + 1,
hover: false,
});
}
},
chooseSelection: function() {
this.selectAddress(this.state.selected);
},
onClick: function(index) {
this.selectAddress(index);
},
onMouseEnter: function(index) {
this.setState({
selected: index,
hover: true,
});
},
onMouseLeave: function() {
this.setState({ hover: false });
},
selectAddress: function(index) {
// Only try to select an address if one exists
if (this.props.addressList.length !== 0) {
this.props.onSelected(index);
this.setState({ hover: false });
}
},
createAddressListTiles: function() {
const self = this;
const AddressTile = sdk.getComponent("elements.AddressTile");
const maxSelected = this._maxSelected(this.props.addressList);
const addressList = [];
// Only create the address elements if there are address
if (this.props.addressList.length > 0) {
for (let i = 0; i <= maxSelected; i++) {
const classes = classNames({
"mx_AddressSelector_addressListElement": true,
"mx_AddressSelector_selected": this.state.selected === i,
});
// NOTE: Defaulting to "vector" as the network, until the network backend stuff is done.
// Saving the addressListElement so we can use it to work out, in the componentDidUpdate
// method, how far to scroll when using the arrow keys
addressList.push(
<div
className={classes}
onClick={this.onClick.bind(this, i)}
onMouseEnter={this.onMouseEnter.bind(this, i)}
onMouseLeave={this.onMouseLeave}
key={this.props.addressList[i].addressType + "/" + this.props.addressList[i].address}
ref={(ref) => { this.addressListElement = ref; }}
>
<AddressTile
address={this.props.addressList[i]}
showAddress={this.props.showAddress}
justified={true}
networkName="vector"
networkUrl="img/search-icon-vector.svg"
/>
</div>,
);
}
}
return addressList;
},
_maxSelected: function(list) {
const listSize = list.length === 0 ? 0 : list.length - 1;
const maxSelected = listSize > (this.props.truncateAt - 1) ? (this.props.truncateAt - 1) : listSize;
return maxSelected;
},
render: function() {
const classes = classNames({
"mx_AddressSelector": true,
"mx_AddressSelector_empty": this.props.addressList.length === 0,
});
return (
<div className={classes} ref={(ref) => {this.scrollElement = ref;}}>
{ this.props.header }
{ this.createAddressListTiles() }
</div>
);
},
});
|
src/components/Button/Button.js | guilhermecvm/react-dribbble-components | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
const Button = styled.button`
padding: 5px 20px;
border-radius: 10px;
border: 0;
color: #ffffff;
text-align: left;
text-transform: uppercase;
font-size: 14px;
box-shadow: 0px 0px 20px -5px rgba(0, 0, 0, 0.75);
${props => props.width && `width: ${props.width}px`};
${props => props.background && `background-color: ${props.background}`};
`
const Button2 = ({ Icon, ...props }) => (
<Button {...props}>
<Icon size={32} style={styles.icon} /> {props.children}
</Button>
)
export const PrimaryButton = props => (
<Button2 background="#6f5f5c" {...props} />
)
export const Secondary1Button = props => (
<Button2 background="#815D5C" {...props} />
)
export const Secondary2Button = props => (
<Button2 background="#A16B62" {...props} />
)
export const Secondary3Button = props => (
<Button2 background="#E18F74" {...props} />
)
export const AccentButton = props => <Button2 background="#EFB175" {...props} />
const styles = {
icon: {
marginRight: 10,
},
}
|
admin/client/App/shared/Portal.js | ratecity/keystone | /**
* Used by the Popout component and the Lightbox component of the fields for
* popouts. Renders a non-react DOM node.
*/
import React from 'react';
import ReactDOM from 'react-dom';
module.exports = React.createClass({
displayName: 'Portal',
portalElement: null, // eslint-disable-line react/sort-comp
componentDidMount () {
const el = document.createElement('div');
document.body.appendChild(el);
this.portalElement = el;
this.componentDidUpdate();
},
componentWillUnmount () {
document.body.removeChild(this.portalElement);
},
componentDidUpdate () {
ReactDOM.render(<div {...this.props} />, this.portalElement);
},
getPortalDOMNode () {
return this.portalElement;
},
render () {
return null;
},
});
|
mobx-src/components/User.js | xiedidan/smart-territory-demo | import React from 'react'
import {observer} from 'mobx-react'
import _ from 'lodash'
import * as THREE from 'three'
import {Layout, Menu, Breadcrumb, Form, Input, Icon, Checkbox, Button, Row, Col} from 'antd'
import constants from '../utilities/constants'
const { SubMenu } = Menu
const { Header, Content, Sider } = Layout
@observer class User extends React.Component {
constructor() {
super()
// member function
this.render = this.render.bind(this)
}
render() {
return <div>
</div>
}
}
export default User
|
src/svg-icons/communication/chat.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationChat = (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-2zM6 9h12v2H6V9zm8 5H6v-2h8v2zm4-6H6V6h12v2z"/>
</SvgIcon>
);
CommunicationChat = pure(CommunicationChat);
CommunicationChat.displayName = 'CommunicationChat';
export default CommunicationChat;
|
src/scripts/components/button/button.component.js | pponugo/react-dev-ops | import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
class Button extends React.Component {
constructor(props) {
super(props);
this._onEvent = this._onEvent.bind(this);
}
_onEvent(e, eventName, args) {
this.props.onEvent(eventName, args);
}
render() {
const { ariaLabel, autofocus, className, classNameWrapper,
disabled, form, hidden, label, name, type, value } = this.props;
if (hidden) {
return (<div />);
}
return (
<div className={cn(classNameWrapper)}>
<button
aria-label={ariaLabel || label || value}
autoFocus={autofocus}
className={cn(className)}
disabled={disabled}
form={form}
name={name || value}
type={type}
value={value}
onClick={e => this._onEvent(e, 'click', value)}
onMouseDown={e => this._onEvent(e, 'mouseDown', value)}
onMouseUp={e => this._onEvent(e, 'mouseUp', value)}
onFocus={e => this._onEvent(e, 'focus', value)}
onBlur={e => this._onEvent(e, 'blur', value)}
>
{label || value}
</button>
</div>
);
}
}
Button.propTypes = {
ariaLabel: PropTypes.string,
autofocus: PropTypes.bool,
className: PropTypes.string,
classNameWrapper: PropTypes.string,
disabled: PropTypes.bool,
form: PropTypes.string,
hidden: PropTypes.bool,
label: PropTypes.string,
name: PropTypes.string,
onEvent: PropTypes.func,
type: PropTypes.oneOf(['button', 'reset', 'submit']),
value: PropTypes.string,
};
Button.defaultProps = {
ariaLabel: undefined,
autofocus: false,
className: 'btn-blue',
classNameWrapper: undefined,
disabled: false,
form: undefined,
hidden: false,
label: undefined,
name: undefined,
onEvent: undefined,
type: 'button',
value: 'click',
};
export default Button;
|
client/src/components/User/Settings.js | hutchgrant/react-boilerplate | import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions/auth';
class Settings extends Component {
render() {
return (
<div>
<h2>Settings</h2>
<h5>Welcome {this.props.auth.username}</h5>
</div>
);
}
};
function mapStateToProps({ auth }) {
return { auth };
}
export default connect(mapStateToProps, actions)(Settings); |
src/containers/NotFound/NotFound.js | micooz/react-redux-universal-hot-example | import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
actor-apps/app-web/src/app/components/activity/UserProfile.react.js | gale320/actor-platform | import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classnames from 'classnames';
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import AvatarItem from 'components/common/AvatarItem.react';
//import UserProfileContactInfo from 'components/activity/UserProfileContactInfo.react';
import Fold from 'components/common/Fold.React';
const getStateFromStores = (userId) => {
const thisPeer = PeerStore.getUserPeer(userId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer)
};
};
@ReactMixin.decorate(IntlMixin)
class UserProfile extends React.Component {
static propTypes = {
user: React.PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.state = _.assign({
isActionsDropdownOpen: false
}, getStateFromStores(props.user.id));
DialogStore.addNotificationsListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.user.id));
}
addToContacts = () => {
ContactActionCreators.addContact(this.props.user.id);
};
removeFromContacts =() => {
ContactActionCreators.removeContact(this.props.user.id);
};
onNotificationChange = (event) => {
DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked);
};
onChange = () => {
this.setState(getStateFromStores(this.props.user.id));
};
toggleActionsDropdown = () => {
const isActionsDropdownOpen = this.state.isActionsDropdownOpen;
if (!isActionsDropdownOpen) {
this.setState({isActionsDropdownOpen: true});
document.addEventListener('click', this.closeActionsDropdown, false);
} else {
this.closeActionsDropdown();
}
};
closeActionsDropdown = () => {
this.setState({isActionsDropdownOpen: false});
document.removeEventListener('click', this.closeActionsDropdown, false);
};
render() {
const user = this.props.user;
const isNotificationsEnabled = this.state.isNotificationsEnabled;
let actions;
if (user.isContact === false) {
actions = (
<li className="dropdown__menu__item" onClick={this.addToContacts}>
<FormattedMessage message={this.getIntlMessage('addToContacts')}/>
</li>
);
} else {
actions = (
<li className="dropdown__menu__item" onClick={this.removeFromContacts}>
<FormattedMessage message={this.getIntlMessage('removeFromContacts')}/>
</li>
);
}
let dropdownClassNames = classnames('dropdown pull-left', {
'dropdown--opened': this.state.isActionsDropdownOpen
});
// Mock
const nickname = '@username';
const email = '[email protected]';
return (
<div className="activity__body user_profile">
<ul className="profile__list">
<li className="profile__list__item user_profile__meta">
<header>
<AvatarItem image={user.bigAvatar}
placeholder={user.placeholder}
size="big"
title={user.name}/>
<h3 className="user_profile__meta__title">{user.name}</h3>
<div className="user_profile__meta__presence">{user.presence}</div>
</header>
<footer>
<div className={dropdownClassNames}>
<button className="dropdown__button button button--light-blue" onClick={this.toggleActionsDropdown}>
<i className="material-icons">more_horiz</i>
<FormattedMessage message={this.getIntlMessage('actions')}/>
</button>
<ul className="dropdown__menu dropdown__menu--left">
{actions}
</ul>
</div>
</footer>
</li>
<li className="profile__list__item user_profile__contact_info no-p">
<ul className="user_profile__contact_info__list">
<li className="hide">
<svg className="icon icon--pink"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#username"/>'}}/>
<span className="title">{nickname}</span>
<span className="description">nickname</span>
</li>
<li>
<i className="material-icons icon icon--green">call</i>
<span className="title">{'+' + user.phones[0].number}</span>
<span className="description">mobile</span>
</li>
<li className="hide">
<i className="material-icons icon icon--blue">mail</i>
<span className="title">{email}</span>
<span className="description">email</span>
</li>
</ul>
</li>
<li className="profile__list__item user_profile__media no-p hide">
<Fold icon="attach_file" iconClassName="icon--gray" title={this.getIntlMessage('sharedMedia')}>
<ul>
<li><a>230 Shared Photos and Videos</a></li>
<li><a>49 Shared Links</a></li>
<li><a>49 Shared Files</a></li>
</ul>
</Fold>
</li>
<li className="profile__list__item user_profile__notifications no-p">
<label htmlFor="notifications">
<i className="material-icons icon icon--squash">notifications_none</i>
<FormattedMessage message={this.getIntlMessage('notifications')}/>
<div className="switch pull-right">
<input checked={isNotificationsEnabled}
id="notifications"
onChange={this.onNotificationChange}
type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</label>
</li>
</ul>
</div>
);
}
}
export default UserProfile;
|
information/blendle-frontend-react-source/app/modules/sectionsPage/components/PersonalPage/UpsellBanner/index.js | BramscoChill/BlendleParser | import React from 'react';
import PremiumBannerContainer from 'modules/item/containers/GetPremiumBannerContainer';
import CSS from './style.scss';
function UpsellBanner() {
return (
<div className={CSS.upsellBannerContainer}>
<PremiumBannerContainer
shouldCheckItemConditions={false}
shouldHideOnMobile={false}
analytics={{
internal_location: 'timeline/premium',
location_in_layout: 'sections',
}}
/>
</div>
);
}
export default UpsellBanner;
// WEBPACK FOOTER //
// ./src/js/app/modules/sectionsPage/components/PersonalPage/UpsellBanner/index.js |
src/svg-icons/maps/local-dining.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalDining = (props) => (
<SvgIcon {...props}>
<path d="M8.1 13.34l2.83-2.83L3.91 3.5c-1.56 1.56-1.56 4.09 0 5.66l4.19 4.18zm6.78-1.81c1.53.71 3.68.21 5.27-1.38 1.91-1.91 2.28-4.65.81-6.12-1.46-1.46-4.2-1.1-6.12.81-1.59 1.59-2.09 3.74-1.38 5.27L3.7 19.87l1.41 1.41L12 14.41l6.88 6.88 1.41-1.41L13.41 13l1.47-1.47z"/>
</SvgIcon>
);
MapsLocalDining = pure(MapsLocalDining);
MapsLocalDining.displayName = 'MapsLocalDining';
MapsLocalDining.muiName = 'SvgIcon';
export default MapsLocalDining;
|
step07o/src/index.js | panacloud/learn-react | import React from 'react';
import ReactDOM from 'react-dom';
import App from './containers/app/App';
import './index.css';
import store from './store'
import { Provider } from 'react-redux'
ReactDOM.render(
//Wraping up in Provider
<Provider store={store}>
<div>
<App/>
</div>
</Provider>
,
document.getElementById('root')
);
|
app/components/2_Users/AuthManager.js | shug0/Awesomidi | // CORE
import React, { Component } from 'react';
var { browserHistory } = require('react-router');
// Components
import LoginBox from './Auth/LoginBox';
class AuthManager extends Component {
constructor(){
super();
this.handleTwitterAuth = this.handleTwitterAuth.bind(this);
}
componentWillUpdate(nextProps, nextState) {
if (nextProps.isLogged === true) {
browserHistory.push('/');
}
}
handleTwitterAuth() {
let authHandler = function(error, user) {
this.props.newUserAuth(user);
};
this.props.base.authWithOAuthPopup('twitter', authHandler.bind(this));
}
render() {
return (
<LoginBox
twitterAuth={this.handleTwitterAuth}
/>
);
}
}
export default AuthManager;
|
scenes/change-account.js | APU-Flow/FlowApp | // change-account.js
// Flow
'use strict';
import React, { Component } from 'react';
import { StyleSheet, Text, Alert, View, TouchableHighlight } from 'react-native';
import { KeyboardAwareScrollView } from 'react-native-keyboard-aware-scroll-view';
import ModalDropdown from 'react-native-modal-dropdown';
export default class ChangeAccount extends Component {
constructor(props) {
super(props);
// Initialize state variables
this.state = {
// TODO: Populate these with real data
switchableAccounts: ['Jim', 'Bill'],
settingsOptions: ['I', 'Am', 'Unsure', 'What', 'Should', 'Be', 'Here']
};
this.dropdownRenderRow = this.dropdownRenderRow.bind(this);
this.confirmDeleteAccount = this.confirmDeleteAccount.bind(this);
}
render() {
return (
<KeyboardAwareScrollView style={styles.container}>
<Text style={styles.title}>Change Account</Text>
<Text style={styles.text}>You're currently logged in as...</Text>
<ModalDropdown style={styles.dropdown}
options={this.state.switchableAccounts}
textStyle={styles.dropdownText}
dropdownStyle={styles.dropdownDropdown}
defaultValue='Switch to Which Account?'
renderRow={this.dropdownRenderRow}
/>
<ModalDropdown style={styles.dropdown}
options={this.state.settingsOptions}
textStyle={styles.dropdownText}
dropdownStyle={styles.dropdownDropdown}
defaultValue='Account Settings'
renderRow={this.dropdownRenderRow}
/>
<TouchableHighlight onPress={this.confirmDeleteAccount}>
<View style={styles.dropdown}>
<Text style={styles.dropdownText}>Delete My Account</Text>
</View>
</TouchableHighlight>
</KeyboardAwareScrollView>
);
}
dropdownRenderRow(rowData, rowID, highlighted) {
let evenRow = rowID % 2;
return (
<TouchableHighlight underlayColor='#6495ED'>
<View style={[styles.dropdownRow, {backgroundColor: evenRow ? '#87CEEB' : '#87CEFA'}]}>
<Text style={styles.dropdownRowText}>{rowData}</Text>
</View>
</TouchableHighlight>
);
}
confirmDeleteAccount() {
Alert.alert(
'Delete Account',
'Are you sure you want to delete your account?',
[
{text: 'Cancel', onPress: null, style: 'cancel' },
{text: 'Yes, Delete my account', onPress: null},
],
{ cancelable: false }
);
}
}
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
flex: 1,
backgroundColor:'rgb(52,152,219)',
},
title: {
textAlign: 'center',
color: 'white',
marginTop: 25,
fontSize: 20,
fontWeight: '400',
marginBottom: 15
},
text: {
textAlign: 'center',
color: 'white',
marginTop: 5,
fontSize: 18,
fontWeight: '400',
marginBottom: 15
},
dropdown: {
margin: 8,
borderColor: 'rgb(31,58,147)',
backgroundColor: 'rgb(31,58,147)',
borderWidth: 1,
borderRadius: 1,
},
dropdownText: {
marginVertical: 10,
marginHorizontal: 6,
fontSize: 18,
color: 'white',
textAlign: 'center',
textAlignVertical: 'center',
},
dropdownDropdown: {
margin: 8,
width: 320,
height: 100,
borderColor: 'rgb(31,58,147)',
borderWidth: 2,
borderRadius: 3,
backgroundColor: 'rgb(31,58,147)',
},
dropdownRow: {
flexDirection: 'row',
height: 40,
alignItems: 'center',
backgroundColor: 'rgb(31,58,147)'
},
dropdownRowText: {
marginHorizontal: 4,
fontSize: 16,
color: 'white',
textAlignVertical: 'center',
textAlign: 'center',
}
});
|
src/svg-icons/social/sentiment-dissatisfied.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentDissatisfied = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-6c-2.33 0-4.32 1.45-5.12 3.5h1.67c.69-1.19 1.97-2 3.45-2s2.75.81 3.45 2h1.67c-.8-2.05-2.79-3.5-5.12-3.5z"/>
</SvgIcon>
);
SocialSentimentDissatisfied = pure(SocialSentimentDissatisfied);
SocialSentimentDissatisfied.displayName = 'SocialSentimentDissatisfied';
export default SocialSentimentDissatisfied;
|
lib/encoding/MultiBrowser.js | waynecraig/encoding-present | require('./sass/fullpage.sass');
import React, { Component } from 'react';
export default class Slide extends Component {
render() {
return (
<div className='fullpage'>
<h1>不同浏览器的区别</h1>
<p>待续...</p>
</div>
)
}
}
|
js/components/Header/4.js | YeisonGomez/RNAmanda |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Button, Icon, Left, Right, Body, Text } from 'native-base';
import { Actions } from 'react-native-router-flux';
import { actions } from 'react-native-navigation-redux-helpers';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
const {
popRoute,
} = actions;
class Header4 extends Component { // eslint-disable-line
static propTypes = {
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Header</Title>
</Body>
<Right>
<Button transparent onPress={() => Actions.pop()}>
<Text>Cancel</Text>
</Button>
</Right>
</Header>
<Content padder>
<Text>
Header With Icon Button & Text Buttons
</Text>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(Header4);
|
imports/ui/NotFound.js | dandev237/short-lnk | /**
* Created by Daniel on 18/06/2017.
*/
import React from 'react';
import {Link} from 'react-router-dom';
export default () => {
return(
<div className="boxed-view">
<div className="boxed-view__box">
<h1>Page Not Found</h1>
<p>Hmmm, we're unable to find that page.</p>
<Link className="button button--link" to="/">HEAD HOME</Link>
</div>
</div>
);
} |
src/js/components/settings/form/Profile.js | barumel/ultritium-radio-player | import React from 'react';
import { Form, FormGroup, FormControl, ControlLabel, InputGroup, Col, Button } from 'react-bootstrap';
export class SettingsFormProfile extends React.Component {
constructor() {
super();
}
render() {
const hidden = this.props.locked ? 'hidden' : '';
return(
<Form horizontal>
{ /* Username */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Username
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-users"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Username"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* First name */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
First name
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-user"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="First name"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Name */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Name
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-user"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Name"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Name */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Email
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-envelope"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Email"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Password */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-key"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Email"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
{ /* Password confirm */ }
<FormGroup>
<Col componentClass={ControlLabel} sm={2}>
Confirm Password
</Col>
<Col sm={10}>
<InputGroup>
<InputGroup.Addon><i class="fa fa-key"></i></InputGroup.Addon>
<FormControl
type="text"
placeholder="Confirm Email"
disabled={this.props.locked}/>
</InputGroup>
</Col>
</FormGroup>
<FormGroup>
<Col componentClass={ControlLabel} class={"btn-group btn-block " + hidden} sm={2}>
<Button bsStyle="success" bsSize="medium" block>Save</Button>
</Col>
<Col componentClass={ControlLabel} class={"btn-group btn-block " + hidden} sm={2}>
<Button bsStyle="warning" bsSize="medium" block>Cancel</Button>
</Col>
</FormGroup>
</Form>
);
}
}
|
src/js/components/catalog/app-catalog-item.js | rafaelkyrdan/flux-app | import React from 'react';
import AppStore from '../../stores/app-store';
import AppActions from '../../actions/app-actions';
import CartButton from '../cart/app-cart-button';
import StoreWatchMixin from '../../mixins/StoreWatchMixin';
import { Link } from 'react-router';
function getCatalogItem(props){
let item = AppStore.getCatalog().find( ({id}) => id === props.id);
return {item};
}
const CatalogItem = (props) => {
let itemStyle = {
borderBottom:'1px solid #ccc',
paddingBottom:'15px',
};
return (
<div className="col-xs-6 col-sm-4 col-md-3" style={itemStyle}>
<h4>{props.item.title}</h4>
<img src="http://placehold.it/250x250" width="100%" className="img-responsive"/>
<p>{props.item.summary}</p>
<p> $ {props.item.cost} <span className="text-success">
{props.item.qty && `(${props.item.qty} in the cart)`}</span>
</p>
<div className="btn-group">
<Link to={ `/item/${props.item.id}` } className="btn btn-default btn-sm">Learn more</Link>
<CartButton handler={ AppActions.addItem.bind(null, props.item)}
txt="Add to Cart" />
</div>
</div>
);
}
export default StoreWatchMixin( CatalogItem, getCatalogItem );
|
src/components/common/svg-icons/device/add-alarm.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceAddAlarm = (props) => (
<SvgIcon {...props}>
<path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/>
</SvgIcon>
);
DeviceAddAlarm = pure(DeviceAddAlarm);
DeviceAddAlarm.displayName = 'DeviceAddAlarm';
DeviceAddAlarm.muiName = 'SvgIcon';
export default DeviceAddAlarm;
|
src/server.js | webmasterkai/boiler | import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
import {ReduxRouter} from 'redux-router';
import createHistory from 'history/lib/createMemoryHistory';
import {reduxReactRouter, match} from 'redux-router/server';
import {Provider} from 'react-redux';
import qs from 'query-string';
import getRoutes from './routes';
import getStatusFromRoutes from './helpers/getStatusFromRoutes';
import defaultState from './defaultState';
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
// Proxy our API server.
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort,
ws: true, // activate websocket support.
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
let json;
if (error.code !== 'ECONNRESET') {
console.error('proxy error', error);
}
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = {error: 'proxy_error', reason: error.message};
res.end(JSON.stringify(json));
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
webpackIsomorphicTools.refresh();
}
const client = new ApiClient(req);
const store = createStore(reduxReactRouter, getRoutes, createHistory, client, defaultState);
function hydrateOnClient() {
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} store={store}/>));
}
if (__DISABLE_SSR__) {
hydrateOnClient();
return;
}
store.dispatch(match(req.originalUrl, (error, redirectLocation, routerState) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
console.error('ROUTER ERROR:', pretty.render(error));
res.status(500);
hydrateOnClient();
} else if (!routerState) {
res.status(500);
hydrateOnClient();
} else {
// Workaround redux-router query string issue:
// https://github.com/rackt/redux-router/issues/106
if (routerState.location.search && !routerState.location.query) {
routerState.location.query = qs.parse(routerState.location.search);
}
store.getState().router.then(() => {
const component = (
<Provider store={store} key="provider">
<ReduxRouter/>
</Provider>
);
const status = getStatusFromRoutes(routerState.routes);
if (status) {
res.status(status);
}
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
}).catch((err) => {
console.error('DATA FETCHING ERROR:', pretty.render(err));
res.status(500);
hydrateOnClient();
});
}
}));
});
if (config.port) {
if (config.isProduction) {
const io = new SocketIo(server);
io.path('/api/ws');
}
server.listen(config.port, (err) => {
if (err) {
console.error(err);
}
console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.name, config.apiPort);
console.info('==> 💻 Open http://localhost:%s in a browser to view the app.', config.port);
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
src/App.js | aquiladev/browniecoin | import React, { Component } from 'react';
import Wallet from './Wallet'
class App extends Component {
render() {
return (
<div className="App">
<Wallet />
</div>
);
}
}
export default App;
|
admin/client/App/shared/FlashMessages.js | frontyard/keystone | /**
* Render a few flash messages, e.g. errors, success messages, warnings,...
*
* Use like this:
* <FlashMessages
* messages={{
* error: [{
* title: 'There is a network problem',
* detail: 'Please try again later...',
* }],
* }}
* />
*
* Instead of error, it can also be hilight, info, success or warning
*/
import React from 'react';
import _ from 'lodash';
import FlashMessage from './FlashMessage';
var FlashMessages = React.createClass({
displayName: 'FlashMessages',
propTypes: {
messages: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.shape({
error: React.PropTypes.array,
hilight: React.PropTypes.array,
info: React.PropTypes.array,
success: React.PropTypes.array,
warning: React.PropTypes.array,
}),
]),
},
// Render messages by their type
renderMessages (messages, type) {
if (!messages || !messages.length) return null;
return messages.map((message, i) => {
return <FlashMessage message={message} type={type} key={`i${i}`} />;
});
},
// Render the individual messages based on their type
renderTypes (types) {
return Object.keys(types).map(type => this.renderMessages(types[type], type));
},
render () {
if (!this.props.messages) return null;
return (
<div className="flash-messages">
{_.isPlainObject(this.props.messages) && this.renderTypes(this.props.messages)}
</div>
);
},
});
module.exports = FlashMessages;
|
src/routes/NotFound/NotFound.js | Xvakin/quiz | import React from 'react'
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
)
}
|
pages/articles/client.js | hschlichter/react-redux-pages-demo | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from '../../shared/store/clientstore';
import reducers from './reducers';
import Layout from './components/layout';
const store = configureStore(reducers, context.state);
if (typeof window !== 'undefined') {
window.onload = function() {
ReactDOM.render(
<Provider store={store}>
<Layout articleId={context.params.id}/>
</Provider>,
document.getElementById('main')
);
};
}
|
client-src/components/category/list/compare/ComparePaneClearButton.js | minimus/final-task | import React from 'react'
import classNames from 'classnames'
import propTypes from 'prop-types'
export default function ComparePaneClearButton({ disabled, onClick }) {
const buttonClass = (disabled) ? 'disabled' : ''
return (
<button className={classNames(buttonClass, 'compare-clear-button')} onClick={onClick}>
<i className="material-icons md-48">delete_forever</i>
</button>
)
}
ComparePaneClearButton.propTypes = {
disabled: propTypes.bool.isRequired,
onClick: propTypes.func.isRequired,
}
|
frontend/react/index.js | kamyarg/payments-frontend |
import React from 'react';
import ReactDOM from 'react-dom';
import PaymentsInspectionComp from './PaymentsInspectionComp';
ReactDOM.render(
<PaymentsInspectionComp />,
document.getElementById('payment-div')
);
|
internals/templates/app.js | Frai/Events | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
app/javascript/mastodon/features/notifications/components/setting_toggle.js | SerCom-KC/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
export default class SettingToggle extends React.PureComponent {
static propTypes = {
prefix: PropTypes.string,
settings: ImmutablePropTypes.map.isRequired,
settingPath: PropTypes.array.isRequired,
label: PropTypes.node.isRequired,
meta: PropTypes.node,
onChange: PropTypes.func.isRequired,
}
onChange = ({ target }) => {
this.props.onChange(this.props.settingPath, target.checked);
}
render () {
const { prefix, settings, settingPath, label, meta } = this.props;
const id = ['setting-toggle', prefix, ...settingPath].filter(Boolean).join('-');
return (
<div className='setting-toggle'>
<Toggle id={id} checked={settings.getIn(settingPath)} onChange={this.onChange} onKeyDown={this.onKeyDown} />
<label htmlFor={id} className='setting-toggle__label'>{label}</label>
{meta && <span className='setting-meta__label'>{meta}</span>}
</div>
);
}
}
|
client/modules/List/pages/ListDetailPage.js | jeojoe/emplist | import React, { Component } from 'react';
import { Link, withRouter } from 'react-router';
import moment from 'moment';
import callApi from '../../../util/apiCaller';
import AdminHeader from '../../Admin/components/AdminHeader';
import { LoaderWithText } from '../../App/components/Loader';
import s from './ListDetailPage.css';
import sSkill from '../components/ListItem.css';
import { getToken } from '../../Admin/authToken';
// import HeaderText from '../components/HeaderText';
class ListDetailPage extends Component {
constructor(props) {
super(props);
this.state = {
list: null,
err: null,
};
}
componentDidMount() {
const id = this.props.params.id;
const { pathname } = this.props.location;
const isAdmin = pathname.indexOf('/admin/request/') >= 0;
if (!isAdmin) {
callApi(`/list/${id}`, 'get').then((res, err) => {
if (err) {
this.setState({ err });
} else {
const list = res.list;
if (list) {
this.setState({ list });
} else {
this.setState({ err: 'List not found.' });
}
}
});
} else {
const token = getToken();
if (!token) {
alert('No token.');
return;
}
callApi(`/requests/${id}?token=${token}`, 'get').then((res, err) => {
if (err) {
this.setState({ err });
} else {
const list = res.data;
if (list) {
this.setState({ list });
} else {
this.setState({ err: 'List not found.' });
}
}
});
}
}
renderList(list) {
const {
company_image,
company_name,
company_location,
skills,
salary,
details,
how_to_apply,
updated_at,
} = list;
const Tags = skills.map((skill, i) => <span className={sSkill.skill} key={i}>{skill}</span>);
const Location = `${company_location.city}, ${company_location.country}`;
const LocationDetail = company_location.detail;
const formatCurrency = (num) => parseInt(num, 10).toLocaleString();
const Salary = salary.max === 9999999 ? 'Unspecified' : `${formatCurrency(salary.min)} - ${formatCurrency(salary.max)} THB`;
return (
<div id={s.content}>
<div className={s.companyWrapper}>
<div className={s.companyNameWrapper}>
<img src={company_image} alt={`${company_name}'s logo`} />
<span>{company_name}</span>
</div>
<div className={s.companyDetailRow}>
<strong>Location : </strong> {Location} <span className={s.subDetail}>({LocationDetail})</span>
</div>
<div className={s.companyDetailRow}>
<strong>Skills Wanted : </strong> {Tags}
</div>
<div className={s.companyDetailRow}>
<strong>Salary Offered : </strong> {Salary}
{/*
FOR AUNNNNN
if company didn't insert salary detail i made default min, max salary to 0 and 9999999 respectively (for analytic purpose). So if you need to check whether company has specified salary or not you need to check max salary is equal to 9999999 or not.
*/}
</div>
</div>
<div id={s.detailWrapper}>
<div dangerouslySetInnerHTML={{ __html: details }} />
</div>
<div className={s.howWrapper}>
<h5>How to apply</h5>
<p>{how_to_apply}</p>
</div>
<div>
<p>Updated: {moment(updated_at).fromNow()}</p>
</div>
</div>
);
}
render() {
const { list, err } = this.state;
if (!list) {
return (
<div className="container">
{err ? <div>{err}</div> : <LoaderWithText text="Loading" centerInPage />}
</div>
);
}
const { location: { pathname }, params: { id } } = this.props;
const isAdmin = pathname.indexOf('/admin/request/') >= 0;
return (
<div className="container">
<div>
{isAdmin ?
<AdminHeader list={list} /> : ''
}
<div id={s.titleWrapper}>
<h4 className={s.title}>{list.title}</h4>
</div>
<div id={s.wrapper}>
{this.renderList(list)}
{
!isAdmin &&
<Link to={`/el/${id}/auth`}>
Manage
</Link>
}
<div className={s.divider} />
<sub style={{ color: '#999' }}>All jobs on this site disregard of gender, age, ethnic and disability.</sub>
</div>
</div>
</div>
);
}
}
ListDetailPage.propTypes = {
params: React.PropTypes.object.isRequired,
};
export default withRouter(ListDetailPage);
|
app/src/components/plugins/MenuItem/index.js | ouxu/NEUQ-OJ | /**
* Created by out_xu on 17/3/19.
*/
import React from 'react'
import { Icon, Menu, Tooltip } from 'antd'
import { Link } from 'react-router'
const MenuItem = {
normal: [
<Menu.Item key={'homepage'}>
<Link to='/homepage' className='showitem'>
<span className='nav-text'><Icon type='home' /> 首页</span>
</Link>
<Link to='/homepage' className='hideitem'>
<Tooltip placement='right' title='首页'>
<span className='sidericon'><Icon type='home' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'problems'}>
<Link to='/problems' className='showitem'>
<span className='nav-text'><Icon type='bars' /> 问题</span>
</Link>
<Link to='/problems' className='hideitem'>
<Tooltip placement='right' title='问题'>
<span className='sidericon'><Icon type='bars' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'contests'}>
<Link to='/contests' className='showitem'>
<span className='nav-text'><Icon type='smile' /> 竞赛&作业</span>
</Link>
<Link to='/contests' className='hideitem'>
<Tooltip placement='right' title='竞赛&作业'>
<span className='sidericon'><Icon type='smile' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'status'}>
<Link to='/status' className='showitem'>
<span className='nav-text'><Icon type='clock-circle' /> 状态</span>
</Link>
<Link to='/status' className='hideitem'>
<Tooltip placement='right' title='状态'>
<span className='sidericon'><Icon type='clock-circle' /></span>
</Tooltip>
</Link>
</Menu.Item>,
<Menu.Item key={'ranklist'}>
<Link to='/ranklist' className='showitem'>
<span className='nav-text'><Icon type='area-chart' /> 排名</span>
</Link>
<Link to='/ranklist' className='hideitem'>
<Tooltip placement='right' title='排名'>
<span className='sidericon'><Icon type='area-chart' /></span>
</Tooltip>
</Link>
</Menu.Item>
],
admin: []
}
export default item => MenuItem[item]
|
pages/join.js | aunnnn/open-ideas | import React, { Component } from 'react';
import Router from 'next/router'
import { Router as CustomRouter } from '../routes'
import { connect } from 'react-redux';
import { graphql, gql, compose } from 'react-apollo'
import Head from 'next/head'
import { loggedIn } from '../lib/authActions'
import Page from '../layouts/main'
import withData from '../lib/withData'
import { logEvent } from '../lib/analytics'
class LoginPage extends Component {
static async getInitialProps({ asPath }) {
// Either user comes throguh '/join' or '/login'
return {
isInitialLoginMode: asPath === '/login'
}
}
constructor(props) {
super(props)
this.state = {
loginMode: props.isInitialLoginMode ? true : false,
email: '',
password: '',
username: '',
loading: false,
}
}
onConfirm = async (e) => {
e.preventDefault()
this.setState({
loading: true
})
try {
if (this.state.loginMode) {
const { email, password } = this.state
const result = await this.props.signinUserMutation({
variables: {
email,
password
}
})
const _id = result.data.authenticateUser.id
const _token = result.data.authenticateUser.token
const _username = result.data.authenticateUser.username
this._saveUserDataToStore(_token, _id, _username)
} else {
const { username, email, password } = this.state
const result = await this.props.createUserMutation({
variables: {
username,
email,
password
}
})
// const _id = result.data.signupUser.id
// const _token = result.data.signupUser.token
// const _username = result.data.signupUser.username
// this._saveUserDataToStore(_token, _id, _username)
alert('👋 Successfully created account. Please check your email and click on the confirmation link.')
}
Router.push({
pathname: '/'
})
} catch(err) {
alert("Oops: " + (
err.graphQLErrors
&& err.graphQLErrors.length >= 1
&& (err.graphQLErrors[0].functionError || err.graphQLErrors[0].message))
|| err);
this.setState({
loading: false
})
}
}
_saveUserDataToStore = (token, id, username) => {
this.props.onLoggedIn(token, id, username)
}
render() {
const pageTitle = this.state.loginMode ? 'Login' : 'Sign Up'
const confirmDisabled = !this.state.email || !this.state.password || (!this.state.loginMode && !this.state.username)
return (
<Page>
<Head>
<title>{pageTitle}</title>
</Head>
<div className="main">
<h1>{pageTitle}</h1>
<form onSubmit={confirmDisabled ? null : this.onConfirm}>
<br />
{/* If sign up mode */
!this.state.loginMode &&
<input
value={this.state.username}
onChange={(e) => this.setState({ username: e.target.value })}
type="text"
placeholder="username"
/>
}
<input
value={this.state.email}
onChange={(e) => this.setState({ email: e.target.value })}
type="email"
placeholder="email address"
/>
<input
value={this.state.password}
onChange={(e) => this.setState({ password: e.target.value })}
type="password"
placeholder={this.state.loginMode ? 'Your password' : 'Choose a safe password'}
/>
{!this.state.loading ?
<div>
<button
type="submit"
className="primary-button"
disabled={confirmDisabled}
>
{this.state.loginMode ? 'login' : 'create account'}
</button>
<div
className="change-mode-button"
onClick={() => {
logEvent('Join', this.state.loginMode ? 'Signup' : 'Login')
const nextPath = this.state.loginMode ? '/join' : '/login'
CustomRouter.pushRoute(nextPath)
this.setState({ loginMode: !this.state.loginMode })
}}
>
{this.state.loginMode ? 'need to create an account?' : 'already have an account?' }
</div>
</div>
:
<div>
👀
</div>
}
</form>
</div>
<style jsx>{`
.main {
margin: 8px;
}
.main input {
display: block;
margin: 8px 0;
}
.change-mode-button {
cursor: pointer;
margin-top: 20px;
font-size: 16px;
color: blue;
}
`}</style>
</Page>)
}
}
const CREATE_USER_MUTATION = gql`
mutation CreateUserMutation($username: String!, $email: String!, $password: String!) {
signupUser(
email: $email,
password: $password,
username: $username,
) {
id
}
}
`
const SIGNIN_USER_MUTATION = gql`
mutation SigninUserMutation($email: String!, $password: String!) {
authenticateUser(
email: $email,
password: $password
) {
token
id
username
}
}
`
const LoginPageWithState = connect(
null,
(dispatch) => ({
onLoggedIn(token, id, username) {
dispatch(loggedIn(token, id, username))
}
})
)(LoginPage)
export default withData(compose(
graphql(SIGNIN_USER_MUTATION, { name: 'signinUserMutation'}),
graphql(CREATE_USER_MUTATION, { name: 'createUserMutation'}),
)(LoginPageWithState))
|
src/components/Radial.react.js | hypriot/kitematic | import React from 'react';
import classNames from 'classnames';
var Radial = React.createClass({
render: function () {
var percentage;
if ((this.props.progress !== null && this.props.progress !== undefined) && !this.props.spin && !this.props.error) {
percentage = (
<div className="percentage"></div>
);
} else {
percentage = <div></div>;
}
var classes = classNames({
'radial-progress': true,
'radial-spinner': this.props.spin,
'radial-negative': this.props.error,
'radial-thick': this.props.thick || false,
'radial-gray': this.props.gray || false,
'radial-transparent': this.props.transparent || false
});
return (
<div className={classes} data-progress={this.props.progress}>
<div className="circle">
<div className="mask full">
<div className="fill"></div>
</div>
<div className="mask half">
<div className="fill"></div>
<div className="fill fix"></div>
</div>
<div className="shadow"></div>
</div>
<div className="inset">
{percentage}
</div>
</div>
);
}
});
module.exports = Radial;
|
src/components/chart.js | frandm182/reactReduxWeather | import React, { Component } from 'react';
import { Sparklines, SparklinesLine, SparklinesReferenceLine } from 'react-sparklines';
import _ from 'lodash';
function average(data) {
return _.round(_.sum(data)/data.length);
}
export default (props) => {
return (
<div>
<Sparklines height={120} width={180} data={props.data}>
<SparklinesLine color={props.color} />
<SparklinesReferenceLine type="avg" />
</Sparklines>
<div>{average(props.data)} {props.units}</div>
</div>
);
} |
lib/Loading/stories/LoadingPane.story.js | folio-org/stripes-components | import React from 'react';
import Paneset from '../../Paneset';
import LoadingPane from '../LoadingPane';
export default () => (
<Paneset>
<LoadingPane paneTitle="Loading pane" />
</Paneset>
);
|
client/src/lib/i18n.js | andris9/mailtrain | 'use strict';
import React from 'react';
import * as ri18n from 'react-i18next';
import {I18nextProvider} from 'react-i18next';
import i18n from 'i18next';
import LanguageDetector from 'i18next-browser-languagedetector';
import mailtrainConfig from 'mailtrainConfig';
import moment from 'moment';
import {convertToFake, getLang} from '../../../shared/langs';
import {createComponentMixin} from "./decorator-helpers";
import lang_en_US_common from "../../../locales/en-US/common";
import lang_es_ES_common from "../../../locales/es-ES/common";
import lang_pt_BR_common from "../../../locales/pt-BR/common";
import lang_de_DE_common from "../../../locales/de-DE/common";
import lang_fr_FR_common from "../../../locales/fr-FR/common";
import lang_ru_RU_common from "../../../locales/ru-RU/common";
const resourcesCommon = {
'en-US': lang_en_US_common,
'es-ES': lang_es_ES_common,
'pt-BR': lang_pt_BR_common,
'de-DE': lang_de_DE_common,
'fr-FR': lang_fr_FR_common,
'ru_RU': lang_ru_RU_common,
'fk-FK': convertToFake(lang_en_US_common)
};
const resources = {};
for (const lng of mailtrainConfig.enabledLanguages) {
const langDesc = getLang(lng);
resources[langDesc.longCode] = {
common: resourcesCommon[langDesc.longCode]
};
}
i18n
.use(LanguageDetector)
.init({
resources,
fallbackLng: mailtrainConfig.defaultLanguage,
defaultNS: 'common',
interpolation: {
escapeValue: false // not needed for react
},
react: {
wait: true
},
detection: {
order: ['querystring', 'cookie', 'localStorage', 'navigator'],
lookupQuerystring: 'locale',
lookupCookie: 'i18nextLng',
lookupLocalStorage: 'i18nextLng',
caches: ['localStorage', 'cookie']
},
whitelist: mailtrainConfig.enabledLanguages,
load: 'currentOnly',
debug: false
});
// Show moment text in selected language
moment.locale(i18n.language);
export default i18n;
export const TranslationContext = React.createContext(null);
export const withTranslation = createComponentMixin({
contexts: [{context: TranslationContext, propName: 't'}]
});
const TranslationContextProvider = ri18n.withTranslation()(props => {
return (
<TranslationContext.Provider value={props.t}>
{props.children}
</TranslationContext.Provider>
);
});
export function TranslationRoot(props) {
return (
<I18nextProvider i18n={ i18n }>
<TranslationContextProvider>
{props.children}
</TranslationContextProvider>
</I18nextProvider>
);
}
export function tMark(key) {
return key;
}
|
clients/packages/admin-client/src/intl/helpers/shallow-with-intl.js | nossas/bonde-client | //
// For reference see: https://github.com/yahoo/react-intl/wiki/Testing-with-React-Intl#enzyme
//
import React from 'react';
import { IntlProvider } from 'react-intl';
import { shallow } from 'enzyme';
import pt from '../../intl/locale-data/pt-BR';
const intlProvider = new IntlProvider({ locale: 'pt-BR', messages: pt }, {});
const { intl } = intlProvider.getChildContext();
const nodeWithIntlProp = (node) => React.cloneElement(node, { intl });
const shallowWithIntl = (node, { context } = {}) =>
shallow(nodeWithIntlProp(node), {
context: Object.assign({}, context, { intl }),
});
export default shallowWithIntl;
|
src/BarGraphGroup/bar_graph_column.js | jrfferreira/react-cubedb | // @flow
// TODO remove lodash
import _map from 'lodash/map'
import React from 'react'
import BarGraph from '../BarGraph'
export default class BarGraphColumn extends React.Component {
constructor(props) {
super(props)
this.state = {
stretched: [],
search: []
}
}
onStretch = serie => () => {
this.setState({
stretched: Object.assign({}, this.state.stretched, {
[this.props.name + serie]: !this.state.stretched[this.props.name + serie]
})
})
};
onSearch = serie => e => {
const search = e.target.value
if (search.length) {
try {
new RegExp(search, 'i')
this.setState({
search: Object.assign({}, this.state.search, {
[serie]: search
})
})
} catch (e) {
this.setState({
search: Object.assign({}, this.state.search, {
[serie]: false
})
})
}
} else {
this.setState({
search: Object.assign({}, this.state.search, {
[serie]: undefined
})
})
}
};
render() {
return (
<div className="cube_graph__column">
{_map(this.props.data, (serie, key) => {
const description = this.props.dataDescription ? this.props.dataDescription[key] : undefined
return (
<div key={key} className={'bar-graph-group__list'}>
<BarGraph
name={key}
description={description}
data={serie}
comparingTo={this.props.comparingTo && this.props.comparingTo[key]}
selected={this.props.selectedItems && this.props.selectedItems[key]}
onChange={this.props.onChange}
slice={this.props.slice}
group={this.props.group}
lookup={this.props.lookup}
getColor={this.props.getColor}
allData={this.props.allData}
/>
</div>
)
})}
</div>
)
}
}
|
src/components/MainPageWithNav.js | zeljkoX/e-learning | import React from 'react';
import ReactDOM from'react-dom';
import Header from './layout/Header';
import PageWithNav from './layout/PageWithNav';
import Breadcrumbs from 'react-breadcrumbs';
class MainPageWithNav extends React.Component {
render() {
let menuItems = [
{ route: 'studenti', text: 'Studenti'},
{ route: 'profesori', text: 'Profesori'},
{ route: 'kursevi', text: 'Kursevi'},
{ route: 'program', text: 'Programi'}
];
return (
<Header>
<PageWithNav menuItems={menuItems}>
<Breadcrumbs {...this.props}/>
{this.props.children}
</PageWithNav>
</Header>
)
}
}
export default MainPageWithNav;
|
src/components/Header/Header.js | mjasinski5/dashboardWookiees | import React from 'react'
import { IndexLink, Link } from 'react-router'
import classes from './Header.scss'
export const Header = () => (
<div>
<h2>DashboardJS</h2>
<Link to='/'> Home </Link>
<Link to='/img'> ImgHome </Link>
</div>
)
export default Header
|
public/client/routes/users/containers/users.js | Concorda/concorda-dashboard | 'use strict'
import React from 'react'
import {connect} from 'react-redux'
import { pushPath } from 'redux-simple-router'
import _ from 'lodash'
// actions
import {getUsers, deleteUser, getUser, closeSession, disableUser, enableUser} from '../../../modules/user/actions/index'
import Panel from '../../components/panel'
export const Users = React.createClass({
componentDidMount () {
this.props.dispatch(getUsers())
},
handleAdd () {
this.props.dispatch(pushPath('/user/add'))
},
handleInviteUser () {
this.props.dispatch(pushPath('/invite_user'))
},
handleEdit (userId) {
this.props.dispatch(getUser(userId, `/user/${userId}/edit`))
},
handleEditClient (clientId) {
this.props.dispatch(pushPath(`/client/${clientId}/edit`))
},
handleEditGroup (groupId) {
this.props.dispatch(pushPath(`/group/${groupId}/edit`))
},
handleDelete (id) {
this.props.dispatch(deleteUser(id))
},
handleDisable (id) {
this.props.dispatch(disableUser(id))
},
handleEnable (id) {
this.props.dispatch(enableUser(id))
},
handleCloseSession (id) {
this.props.dispatch(closeSession(id))
},
render () {
const {users} = this.props
let body = null
if (users) {
body = (
<div className="user-list">
<div className="user-list-heading cf row">
<div className="col-xs-12 col-md-2"><h4 className="m0">Name</h4></div>
<div className="col-xs-12 col-md-2"><h4 className="m0">Email</h4></div>
<div className="col-xs-2 col-md-2"><h4 className="m0">Clients</h4></div>
<div className="col-xs-2 col-md-2"><h4 className="m0">Groups</h4></div>
<div className="col-xs-4 col-md-4"><h4 className="m0">Actions</h4></div>
</div>
{users.map((user) => {
return (
<div key={user.id} className="user-list-row row cf">
<div className="col-xs-12 col-md-2">{user.name}</div>
<div className="col-xs-12 col-md-2">{user.email}</div>
<div className="col-xs-2 col-md-2">{_.map(user.clients, (client) => { return <a onClick={() => { this.handleEditClient(client.id) }}>{client.name}, </a> })}</div>
<div className="col-xs-2 col-md-2">{_.map(user.groups, (group) => { return <a onClick={() => { this.handleEditGroup(group.id) }}>{group.name}, </a> })}</div>
<div className="col-xs-4 col-md-4">
<ul className="list-unstyled list-inline">
<li><a onClick={() => { this.handleEdit(user.id) }}>Edit</a></li>
{(() => {
if (user.active) {
return <li><a onClick={() => { this.handleDisable(user.id) }}>Disable</a></li>
}
else {
return <li><a onClick={() => { this.handleEnable(user.id) }}>Enable</a></li>
}
})()}
<li><a onClick={() => { this.handleDelete(user.id) }}>Delete</a></li>
<li><a onClick={() => { this.handleCloseSession(user.id) }}>Close Session</a></li>
</ul>
</div>
</div>
)
})}
</div>
)
}
return (
<div className="page page-users container-fluid">
<div className="row middle-xs page-heading">
<h2 className="col-xs-6 col-sm-6">Users</h2>
<div className="col-xs-6 col-sm-6 txt-right">
<button onClick={() => { this.handleAdd() }} className="btn btn-primary">Add User</button>
<button onClick={() => { this.handleInviteUser() }} className="btn btn-primary btn-send-invite">Invite
User
</button>
</div>
</div>
<div className="row middle-xs search-wrapper">
<div className="col-xs-12 col-sm-8 col-md-8 search-input-wrapper">
<input type="search" className="input-large" placeholder="Find a user"/>
<ul className="list-unstyled search-dropdown-active">
<li><a href="">Item one</a></li>
<li><a href="">Item two</a></li>
<li><a href="">Item three</a></li>
</ul>
</div>
<div className="col-xs-12 col-sm-4 col-md-4 txt-left">
<button className="btn btn-large btn-search">Search</button>
</div>
</div>
<Panel title={'User List'}>
{body}
</Panel>
<nav role="navigation" className="txt-center">
<ul className="list-unstyled list-inline pagination">
<li><a href="">Prev</a></li>
<li><a href="">1</a></li>
<li><a href="" className="page-current">2</a></li>
<li><a href="">3</a></li>
<li><a href="" className="page-unavailable">Next</a></li>
</ul>
</nav>
</div>
)
}
})
export default connect((state) => {
return {
users: state.user.result
}
})(Users)
|
docs/src/components/index/Content.js | HsuTing/cat-components | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import radium from 'radium';
import Markdown from 'react-markdown';
import * as style from './style/index';
@radium
export default class Content extends React.Component {
static propTypes = {
name: PropTypes.string.isRequired,
text: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]).isRequired,
component: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.func
]).isRequired,
example: PropTypes.string.isRequired
}
render() {
const {name, text, component, example} = this.props;
return (
<div id={name}
style={style.block}
>
<Markdown source={typeof text === 'string' ? text : text(example)} />
{
!component ?
null: React.createElement(component)
}
</div>
);
}
}
|
examples/04 Sortable/Simple/Container.js | pairyo/react-dnd | import React, { Component } from 'react';
import update from 'react/lib/update';
import Card from './Card';
import { DragDropContext } from 'react-dnd';
import HTML5Backend from 'react-dnd/modules/backends/HTML5';
const style = {
width: 400
};
@DragDropContext(HTML5Backend)
export default class Container extends Component {
constructor(props) {
super(props);
this.moveCard = this.moveCard.bind(this);
this.state = {
cards: [{
id: 1,
text: 'Write a cool JS library'
}, {
id: 2,
text: 'Make it generic enough'
}, {
id: 3,
text: 'Write README'
}, {
id: 4,
text: 'Create some examples'
}, {
id: 5,
text: 'Spam in Twitter and IRC to promote it'
}, {
id: 6,
text: '???'
}, {
id: 7,
text: 'PROFIT'
}]
};
}
moveCard(id, afterId) {
const { cards } = this.state;
const card = cards.filter(c => c.id === id)[0];
const afterCard = cards.filter(c => c.id === afterId)[0];
const cardIndex = cards.indexOf(card);
const afterIndex = cards.indexOf(afterCard);
this.setState(update(this.state, {
cards: {
$splice: [
[cardIndex, 1],
[afterIndex, 0, card]
]
}
}));
}
render() {
const { cards } = this.state;
return (
<div style={style}>
{cards.map(card => {
return (
<Card key={card.id}
id={card.id}
text={card.text}
moveCard={this.moveCard} />
);
})}
</div>
);
}
} |
demo/src/components/App/components/Examples/components/MultipleSections/MultipleSections.js | CoreFiling/react-autosuggest | import styles from './MultipleSections.less';
import theme from './theme.less';
import React, { Component } from 'react';
import isMobile from 'ismobilejs';
import Link from 'Link/Link';
import Autosuggest from 'Autosuggest';
import languages from './languages';
import { escapeRegexCharacters } from 'utils/utils';
const focusInputOnSuggestionClick = !isMobile.any;
const getSuggestions = value => {
const escapedValue = escapeRegexCharacters(value.trim());
if (escapedValue === '') {
return [];
}
const regex = new RegExp('^' + escapedValue, 'i');
return languages
.map(section => {
return {
title: section.title,
languages: section.languages.filter(language => regex.test(language.name))
};
})
.filter(section => section.languages.length > 0);
};
const getSuggestionValue = suggestion => suggestion.name;
const renderSuggestion = suggestion => (
<span>{suggestion.name}</span>
);
const renderSectionTitle = section => (
<strong>{section.title}</strong>
);
const getSectionSuggestions = section => section.languages;
export default class MultipleSections extends Component {
constructor() {
super();
this.state = {
value: '',
suggestions: []
};
}
onChange = (event, { newValue }) => {
this.setState({
value: newValue
});
};
onSuggestionsFetchRequested = ({ value }) => {
this.setState({
suggestions: getSuggestions(value)
});
};
onSuggestionsClearRequested = () => {
this.setState({
suggestions: []
});
};
render() {
const { value, suggestions } = this.state;
const inputProps = {
placeholder: 'Type \'c\'',
value,
onChange: this.onChange
};
return (
<div id="multiple-sections-example" className={styles.container}>
<div className={styles.textContainer}>
<div className={styles.title}>
Multiple sections
</div>
<div className={styles.description}>
Suggestions can also be presented in multiple sections.
Note that we highlight the first suggestion by default here.
</div>
<Link
className={styles.codepenLink}
href="http://codepen.io/moroshko/pen/qbRNjV"
underline={false}
>
Codepen
</Link>
</div>
<div className={styles.autosuggest}>
<Autosuggest
multiSection={true}
suggestions={suggestions}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
getSuggestionValue={getSuggestionValue}
renderSuggestion={renderSuggestion}
renderSectionTitle={renderSectionTitle}
getSectionSuggestions={getSectionSuggestions}
inputProps={inputProps}
highlightFirstSuggestion={true}
focusInputOnSuggestionClick={focusInputOnSuggestionClick}
theme={theme}
id="multiple-sections-example"
/>
</div>
</div>
);
}
}
|
app/components/Counter.js | lynks-p2p/lynks-client | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Counter.css';
class Counter extends Component {
props: {
increment: () => void,
incrementIfOdd: () => void,
incrementAsync: () => void,
decrement: () => void,
counter: number
};
render() {
const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;
return (
<div>
<div className={styles.backButton}>
<Link to="/">
<i className="fa fa-arrow-left fa-3x" />
</Link>
</div>
<div className={`counter ${styles.counter}`}>
{counter}
</div>
<div className={styles.btnGroup}>
<button className={styles.btn} onClick={increment}>
<i className="fa fa-plus" />
</button>
<button className={styles.btn} onClick={decrement}>
<i className="fa fa-minus" />
</button>
<button className={styles.btn} onClick={incrementIfOdd}>odd</button>
<button className={styles.btn} onClick={() => incrementAsync()}>async</button>
</div>
</div>
);
}
}
export default Counter;
|
app/javascript/mastodon/containers/status_container.js | ebihara99999/mastodon | import React from 'react';
import { connect } from 'react-redux';
import Status from '../components/status';
import { makeGetStatus } from '../selectors';
import {
replyCompose,
mentionCompose,
} from '../actions/compose';
import {
reblog,
favourite,
unreblog,
unfavourite,
} from '../actions/interactions';
import {
blockAccount,
muteAccount,
} from '../actions/accounts';
import { muteStatus, unmuteStatus, deleteStatus } from '../actions/statuses';
import { initReport } from '../actions/reports';
import { openModal } from '../actions/modal';
import { createSelector } from 'reselect';
import { isMobile } from '../is_mobile';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
muteConfirm: { id: 'confirmations.mute.confirm', defaultMessage: 'Mute' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => ({
status: getStatus(state, props.id),
me: state.getIn(['meta', 'me']),
boostModal: state.getIn(['meta', 'boost_modal']),
autoPlayGif: state.getIn(['meta', 'auto_play_gif']),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onReply (status, router) {
dispatch(replyCompose(status, router));
},
onModalReblog (status) {
dispatch(reblog(status));
},
onReblog (status, e) {
if (status.get('reblogged')) {
dispatch(unreblog(status));
} else {
if (e.shiftKey || !this.boostModal) {
this.onModalReblog(status);
} else {
dispatch(openModal('BOOST', { status, onReblog: this.onModalReblog }));
}
}
},
onFavourite (status) {
if (status.get('favourited')) {
dispatch(unfavourite(status));
} else {
dispatch(favourite(status));
}
},
onDelete (status) {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.deleteMessage),
confirm: intl.formatMessage(messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'))),
}));
},
onMention (account, router) {
dispatch(mentionCompose(account, router));
},
onOpenMedia (media, index) {
dispatch(openModal('MEDIA', { media, index }));
},
onOpenVideo (media, time) {
dispatch(openModal('VIDEO', { media, time }));
},
onBlock (account) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
},
onReport (status) {
dispatch(initReport(status.get('account'), status));
},
onMute (account) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.mute.message' defaultMessage='Are you sure you want to mute {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.muteConfirm),
onConfirm: () => dispatch(muteAccount(account.get('id'))),
}));
},
onMuteConversation (status) {
if (status.get('muted')) {
dispatch(unmuteStatus(status.get('id')));
} else {
dispatch(muteStatus(status.get('id')));
}
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Status));
|
src/app/components/Layout.js | jordanco/drafter-frontend | import React, { Component } from 'react';
import '../../assets/css/normalize.css';
import '../../assets/css/webflow.css';
import '../../assets/css/drafter2.webflow.css';
import ActionSidebarMenu from '../components/menu/action-sidebar';
export default (props) => {
return (
<div className="master">
<ActionSidebarMenu />
{props.children}
</div>
);
}; |
src/views/mainPage.js | IllegalCreed/pwdsaver_app | /**
* @providesModule MainPage
*/
import React, { Component } from 'react';
import {
TouchableWithoutFeedback,
KeyboardAvoidingView,
TouchableOpacity,
SectionList,
ScrollView,
StyleSheet,
Dimensions,
TextInput,
Platform,
Button,
Modal,
Alert,
Image,
Text,
View
} from 'react-native';
import Crypto from 'crypto-js';
import { requestState } from 'ReducerUtils';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import Actions from 'Actions';
export class MainPage extends Component {
static navigationOptions = {
title: '拔粪宝',
headerStyle: {
backgroundColor: '#232323'
},
headerTitleStyle: {
fontSize: 20,
},
headerTintColor: 'white'
}
constructor(props) {
super(props);
this.state = {
addPwdModalVisible: false,
addGroupModalVisible: false,
updateGroupModalVisible: false,
updatePwdModalVisible: false,
key: '',
account: '',
password: '',
newPassword: '',
currentPwdId: '',
currentGroupId: '',
currentGroupName: '',
tempGroupName: '',
currentSelectPwd: '',
}
this.renderSectionHeader = this.renderSectionHeader.bind(this);
this.renderItemComponent = this.renderItemComponent.bind(this);
this.pwdHasSameKey = this.pwdHasSameKey.bind(this);
this.pwdHasSameKeyWithoutSelf = this.pwdHasSameKeyWithoutSelf.bind(this);
this.groupHasSameKey = this.groupHasSameKey.bind(this);
this.groupHasSameKeyWithoutSelf = this.groupHasSameKeyWithoutSelf.bind(this);
this.props.dispatch(Actions.getPwdList());
}
componentWillReceiveProps(nextProps) {
if (nextProps.addPwdState != this.props.addPwdState) {
switch (nextProps.addPwdState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetAddPwdState());
console.log('添加密码成功');
break;
case requestState.ERROR:
console.log('添加密码失败');
break;
}
}
if (nextProps.updatePwdState != this.props.updatePwdState) {
switch (nextProps.updatePwdState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetUpdatePwdState());
console.log('更新密码成功');
break;
case requestState.ERROR:
console.log('更新密码失败');
break;
}
}
if (nextProps.deletePwdState != this.props.deletePwdState) {
switch (nextProps.deletePwdState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetDeletePwdState());
console.log('删除密码成功');
break;
case requestState.ERROR:
console.log('删除密码失败');
break;
}
}
if (nextProps.addGroupState != this.props.addGroupState) {
switch (nextProps.addGroupState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetAddGroupState());
console.log('添加分组成功');
break;
case requestState.ERROR:
console.log('添加分组失败');
break;
}
}
if (nextProps.updateGroupState != this.props.updateGroupState) {
switch (nextProps.updateGroupState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetUpdateGroupState());
console.log('更新分组成功');
break;
case requestState.ERROR:
console.log('更新分组失败');
break;
}
}
if (nextProps.deleteGroupState != this.props.deleteGroupState) {
switch (nextProps.deleteGroupState) {
case requestState.LOADED:
this.props.dispatch(Actions.getPwdList());
this.props.dispatch(Actions.resetDeleteGroupState());
console.log('删除分组成功');
break;
case requestState.ERROR:
console.log('删除分组失败');
break;
}
}
}
renderSectionHeader({ section }) {
return (
<TouchableOpacity onLongPress={() => {
this.setState({ updateGroupModalVisible: true, currentGroupName: section.groupName, currentGroupId: section.key, tempGroupName: section.groupName })
}}>
<View style={{
justifyContent: 'space-between',
flexDirection: 'row',
alignItems: 'center',
backgroundColor: '#3b3b3b',
paddingLeft: 10,
paddingRight: 15,
height: 40
}}>
<Text style={{
color: 'white',
fontSize: 20,
fontWeight: 'bold'
}}>{section.groupName}</Text>
<TouchableOpacity
onPress={() => {
this.setState({ addPwdModalVisible: true, currentGroupName: section.groupName, currentGroupId: section.key })
}} >
<Text style={{ fontSize: 30, color: 'white', marginTop: -4 }}>{'+'}</Text>
</TouchableOpacity>
</View>
</TouchableOpacity >
)
}
renderItemComponent({ item }) {
if (this.state.currentSelectPwd == item.pid) {
let decrypted = Crypto.AES.decrypt(item.pwd, this.props.password);
return (
<TouchableOpacity
onPress={() => {
this.setState({ currentSelectPwd: '' });
}}
onLongPress={() => {
this.setState({ updatePwdModalVisible: true, key: item.key, account: item.account, password: item.pwd, newPassword: '', currentPwdId: item.pid, currentGroupId: item.gid })
}}>
<View style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingLeft: 10,
height: 35
}}>
<Text style={{
color: '#7EC880',
fontSize: 16,
marginLeft: 10,
}}>{item.account}</Text>
<Text style={{
color: '#80C080',
fontSize: 16,
marginRight: 15,
}}>{decrypted.toString(Crypto.enc.Utf8)}</Text>
</View>
</TouchableOpacity>
)
} else {
return (
<TouchableOpacity
onPress={() => {
this.setState({ currentSelectPwd: item.pid });
}}
onLongPress={() => {
this.setState({ updatePwdModalVisible: true, key: item.key, account: item.account, password: item.pwd, newPassword: '', currentPwdId: item.pid, currentGroupId: item.gid })
}}>
<View style={{
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
paddingLeft: 10,
height: 35
}}>
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 10,
}}>{item.key}</Text>
<Text style={{
color: 'white',
fontSize: 16,
marginRight: 15,
}}>{item.account}</Text>
</View>
</TouchableOpacity>
)
}
}
groupHasSameKey(key) {
for (let group of this.props.pwdList) {
if (group.groupName == key) {
return true;
}
}
return false;
}
groupHasSameKeyWithoutSelf(key, id) {
for (let group of this.props.pwdList) {
if (group.groupName == key && group.key != id) {
return true;
}
}
return false;
}
pwdHasSameKey(key) {
for (let group of this.props.pwdList) {
for (let pwd of group.data) {
if (pwd.key == key) {
return true;
}
}
}
return false;
}
pwdHasSameKeyWithoutSelf(key, id) {
for (let group of this.props.pwdList) {
for (let pwd of group.data) {
if (pwd.key == key && id != pwd.pid) {
return true;
}
}
}
return false;
}
render() {
const Container = Platform.OS === 'ios' ? KeyboardAvoidingView : View;
return (
<View style={{ flex: 1, backgroundColor: '#232323' }}>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.addPwdModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ addPwdModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 270,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 12,
marginBottom: 15
}}>{'向' + this.state.currentGroupName + '中添加新密码'}</Text>
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="名称"
onChangeText={(text) => this.setState({ key: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="账号"
onChangeText={(text) => this.setState({ account: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="密码"
onChangeText={(text) => this.setState({ password: text })} />
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 20 }]}
onPress={() => {
if (this.pwdHasSameKey(this.state.key)) {
Alert.alert('名称重复');
return;
}
let encrypted = Crypto.AES.encrypt(this.state.password, this.props.password);
this.props.dispatch(Actions.addPwd(this.state.currentGroupId, this.state.key, this.state.account, encrypted.toString()));
this.setState({ addPwdModalVisible: false });
}} >
<Text style={styles.buttonText}>{'添加'}</Text>
</TouchableOpacity>
</View>
</Container>
</Modal>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.addGroupModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ addGroupModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 130,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="分组名称"
onChangeText={(text) => this.setState({ currentGroupName: text })} />
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 20 }]}
onPress={() => {
if (this.groupHasSameKey(this.state.currentGroupName)) {
Alert.alert('名称重复');
return;
}
this.props.dispatch(Actions.addGroup(this.state.currentGroupName));
this.setState({ addGroupModalVisible: false });
}} >
<Text style={styles.buttonText}>{'添加'}</Text>
</TouchableOpacity>
</View>
</Container>
</Modal>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.updateGroupModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ updateGroupModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 160,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 12,
marginBottom: 15
}}>{'修改' + this.state.tempGroupName}</Text>
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="名称"
value={this.state.currentGroupName}
onChangeText={(text) => this.setState({ currentGroupName: text })} />
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 10, flex: 1 }]}
onPress={() => {
if (this.groupHasSameKeyWithoutSelf(this.state.currentGroupName, this.state.currentGroupId)) {
Alert.alert('名称重复');
return;
}
this.props.dispatch(Actions.updateGroup(this.state.currentGroupId, this.state.currentGroupName));
this.setState({ updateGroupModalVisible: false });
}} >
<Text style={styles.buttonText}>{'修改'}</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, { marginLeft: 10, marginRight: 20, flex: 1 }]}
onPress={() => {
this.props.dispatch(Actions.deleteGroup(this.state.currentGroupId));
this.setState({ updateGroupModalVisible: false });
}} >
<Text style={styles.buttonText}>{'删除'}</Text>
</TouchableOpacity>
</View>
</View>
</Container>
</Modal>
<Modal
animationType={"fade"}
transparent={true}
visible={this.state.updatePwdModalVisible}>
<Container behavior={'padding'} style={{
flex: 1,
backgroundColor: '#00000088',
justifyContent: 'flex-end',
}}>
<TouchableWithoutFeedback
style={{ flex: 1 }}
onPress={() => {
this.setState({ updatePwdModalVisible: false })
}}>
<View style={{ flex: 1 }}></View>
</TouchableWithoutFeedback>
<View style={{
height: 270,
backgroundColor: '#232323',
}}>
<View style={{ height: 1, backgroundColor: '#666666', marginBottom: 15 }} />
<Text style={{
color: 'white',
fontSize: 16,
marginLeft: 12,
marginBottom: 15
}}>{'修改密码'}</Text>
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="名称"
value={this.state.key}
onChangeText={(text) => this.setState({ key: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="账号"
value={this.state.account}
onChangeText={(text) => this.setState({ account: text })} />
<TextInput
placeholderTextColor="#bfbfbf"
underlineColorAndroid="transparent"
style={styles.singleLine}
placeholder="密码"
value={this.state.newPassword}
onChangeText={(text) => this.setState({ newPassword: text })} />
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 10, flex: 1 }]}
onPress={() => {
if (this.pwdHasSameKeyWithoutSelf(this.state.key, this.state.currentPwdId)) {
Alert.alert('名称重复');
return;
}
let pwd = '';
if (this.state.newPassword == '') {
pwd = this.state.password;
} else {
let encrypted = Crypto.AES.encrypt(this.state.newPassword, this.props.password);
pwd = encrypted.toString();
}
this.props.dispatch(Actions.updatePwd(this.state.currentPwdId, this.state.currentGroupId, this.state.key, this.state.account, pwd));
this.setState({ updatePwdModalVisible: false });
}} >
<Text style={styles.buttonText}>{'修改'}</Text>
</TouchableOpacity>
<TouchableOpacity style={[styles.button, { marginLeft: 10, marginRight: 20, flex: 1 }]}
onPress={() => {
this.props.dispatch(Actions.deletePwd(this.state.currentPwdId));
this.setState({ updatePwdModalVisible: false });
}} >
<Text style={styles.buttonText}>{'删除'}</Text>
</TouchableOpacity>
</View>
</View>
</Container>
</Modal>
<SectionList
ListFooterComponent={F =>
<TouchableOpacity style={[styles.button, { marginLeft: 20, marginRight: 20, marginBottom: 50, marginTop: 15 }]}
onPress={() => {
this.setState({ addGroupModalVisible: true });
}} >
<Text style={styles.buttonText}>{'添加分组'}</Text>
</TouchableOpacity>
}
SectionSeparatorComponent={() =>
<View style={{ height: 2, backgroundColor: '#232323' }} />
}
ItemSeparatorComponent={() =>
<View style={{ height: 1, backgroundColor: 'black' }} />
}
renderItem={this.renderItemComponent}
renderSectionHeader={this.renderSectionHeader}
sections={this.props.pwdList}
/>
</View>
)
}
}
var styles = StyleSheet.create({
button: {
borderRadius: 4,
marginTop: 10,
height: 35,
backgroundColor: '#6e6e6e',
alignItems: 'center',
},
buttonText: {
color: '#FFFFFF',
fontSize: 16,
lineHeight: 30,
},
singleLine: {
borderRadius: 4,
marginLeft: 10,
marginRight: 10,
marginBottom: 5,
backgroundColor: '#3e3e3e',
color: '#FFFFFF',
fontSize: 16,
padding: 0,
paddingLeft: 15,
height: 50,
},
});
const getPwdList = state => state.pwd.pwdList;
const getPwd = state => state.user.password;
const getAddPwdState = state => state.pwd.addPwdState
const getUpdatePwdState = state => state.pwd.updatePwdState
const getDeletePwdState = state => state.pwd.deletePwdState
const getAddGroupState = state => state.pwd.addGroupState
const getUpdateGroupState = state => state.pwd.updateGroupState
const getDeleteGroupState = state => state.pwd.deleteGroupState
const MainPageSelector = createSelector([getPwdList, getPwd, getAddPwdState, getUpdatePwdState, getDeletePwdState, getAddGroupState, getUpdateGroupState, getDeleteGroupState], (pwdList, password, addPwdState, updatePwdState, deletePwdState, addGroupState, updateGroupState, deleteGroupState) => {
return {
pwdList,
password,
addPwdState,
updatePwdState,
deletePwdState,
addGroupState,
updateGroupState,
deleteGroupState,
}
});
export default connect(MainPageSelector)(MainPage); |
src/components/frontPageDisplay.js | gordongordon/hom | import React from 'react'
import { Carousel, WhiteSpace, WingBlank } from 'antd-mobile';
export default class FrontPageDisplay extends React.Component {
state = {
data: ['', '', ''],
initialHeight: 200,
}
componentDidMount() {
// simulate img loading
setTimeout(() => {
this.setState({
data: ['AiyWuByWklrrUDlFignR', 'TekJlZRVCjLFexlOCuWn', 'IJOtIlfsYdTyaDTRVrLI'],
});
}, 100);
}
render() {
const hProp = this.state.initialHeight ? { height: this.state.initialHeight } : {};
return (
<WingBlank>
<Carousel
className="my-carousel"
autoplay={false}
infinite
selectedIndex={1}
swipeSpeed={35}
beforeChange={(from, to) => console.log(`slide from ${from} to ${to}`)}
afterChange={index => console.log('slide to', index)}
>
{this.state.data.map(ii => (
<a href="http://www.baidu.com" key={ii} style={hProp}>
<img
src={`https://zos.alipayobjects.com/rmsportal/${ii || 'QcWDkUhvYIVEcvtosxMF'}.png`}
alt="icon"
onLoad={() => {
// fire window resize event to change height
window.dispatchEvent(new Event('resize'));
this.setState({
initialHeight: null,
});
}}
/>
</a>
))}
</Carousel>
</WingBlank>
);
}
}
|
04/EW/trding/trding/src/components/notfound/NotFound.js | rgllm/uminho | import React from 'react';
import { Link } from 'react-router-dom';
import './NotFound.css';
const NotFound = () =>{
return(
<div className="NotFound">
<h1 clasName="NotFound-title">Page not found!</h1>
<Link to="/" className="NotFound-link">Go to homepage</Link>
</div>
);
}
export default NotFound;
|
test/integration/image-component/base-path/pages/hidden-parent.js | zeit/next.js | import Image from 'next/image'
import React from 'react'
const Page = () => {
return (
<div>
<p>Hello World</p>
<div style={{ visibility: 'hidden' }}>
<Image
id="hidden-image"
src="/docs/test.jpg"
width="400"
height="400"
></Image>
</div>
<p id="stubtext">This is the hidden parent page</p>
</div>
)
}
export default Page
|
app/containers/HomePage/index.js | litdevelopers/tinder | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/component/Account.js | BristolPound/cyclos-mobile-3-TownPound | import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { View, ListView, TouchableHighlight } from 'react-native'
import DefaultText from './DefaultText'
import Colors from '@Colors/colors'
import { logout } from '../store/reducer/login'
import { updateStatus } from '../store/reducer/statusMessage'
import ProfileHeader from './profileScreen/ProfileHeader'
import styles from './AccountStyle'
const renderSeparator = (sectionID, rowID) =>
<View style={styles.separator} key={`sep:${sectionID}:${rowID}`}/>
const renderSectionHeader = (sectionData, sectionID) =>
<View style={styles.sectionHeader.container} key={sectionID}>
<DefaultText style={styles.sectionHeader.text}>
{sectionID.toUpperCase()}
</DefaultText>
</View>
const AccountOption = ({text, secondaryText, onPress, index}) =>
<TouchableHighlight
onPress={() => onPress ? onPress() : undefined}
key={index}
underlayColor={onPress ? Colors.gray5 : Colors.transparent}>
<View style={styles.row.container}>
<DefaultText style={styles.row.label}>{text}</DefaultText>
{ secondaryText
? <DefaultText style={styles.row.secondary}>{secondaryText}</DefaultText>
: undefined }
</View>
</TouchableHighlight>
const Account = (props) => {
let ds = new ListView.DataSource({
rowHasChanged: (a, b) => a.text !== b.text || a.secondaryText !== b.secondaryText,
sectionHeaderHasChanged: (a, b) => a !== b
})
const data = {
'Profile Settings': [{
text: 'Email',
secondaryText: (props.details && props.details.email) || 'Not set'
}, {
text: 'Phone',
secondaryText: (props.details && props.details.phones && props.details.phones.length > 0) ? props.details.phones[0].normalizedNumber : 'Not set'
}, {
text: 'Log out',
onPress: () => {
props.logout()
props.updateStatus('Logged out ✓')
}
}]
}
ds = ds.cloneWithRowsAndSections(data, Object.keys(data))
return (
<View style={styles.container}>
<ProfileHeader
name={props.details.display}
username={props.details.shortDisplay}
image={props.details.image && props.details.image.url}
category='person'/>
<ListView
style={styles.detailsList}
dataSource={ds}
scrollEnabled={false}
renderSeparator={renderSeparator}
renderSectionHeader={renderSectionHeader}
renderRow={(accountOption, i) => <AccountOption {...accountOption} index={i}/> }
removeClippedSubviews={false}/>
</View>
)
}
const mapDispatchToProps = (dispatch) =>
bindActionCreators({ logout, updateStatus }, dispatch)
const mapStateToProps = state => state.account
export default connect(mapStateToProps, mapDispatchToProps)(Account)
|
src/components/Forms/CheckboxOrRadio.js | josedigital/koala-app | import React from 'react'
const CheckboxOrRadio = (props) => {
return (
<div className="formElement">
<label className="form-label">{props.title}</label>
<div className="checkbox-group">
{props.options.map(opt => {
return (
<label key={opt} className="form-label capitalize">
<input
className="form-checkbox"
name={props.name}
onChange={props.controlFunction}
value={opt}
checked={ props.selectedOptions.indexOf(opt) > -1 }
type={props.type} /> {opt}
</label>
);
})}
</div>
</div>
)
}
CheckboxOrRadio.propTypes = {
title: React.PropTypes.string.isRequired,
type: React.PropTypes.oneOf(['checkbox', 'radio']).isRequired,
name: React.PropTypes.string.isRequired,
options: React.PropTypes.array.isRequired,
selectedOptions: React.PropTypes.array,
controlFunction: React.PropTypes.func.isRequired
};
export default CheckboxOrRadio
|
client/app/components/common/Avatar.js | Zuehlke/poinz | import React from 'react';
import PropTypes from 'prop-types';
import avatarIcons, {SPECIAL} from '../../assets/avatars';
import {StyledAvatar} from './_styled';
const Avatar = ({user, isOwn, shaded, onClick}) => (
<StyledAvatar
className="avatar"
src={getImageSource(user)}
isOwn={isOwn}
shaded={shaded}
onClick={onClick}
/>
);
function getImageSource(user) {
if (user.email) {
return `https://www.gravatar.com/avatar/${user.emailHash}?size=60`; // the gravatar case
} else if (user.avatar) {
return user.avatar === -1 ? SPECIAL : avatarIcons[user.avatar % avatarIcons.length];
} else {
return avatarIcons[0];
}
}
Avatar.propTypes = {
user: PropTypes.object,
isOwn: PropTypes.bool,
shaded: PropTypes.bool,
onClick: PropTypes.func
};
export default Avatar;
|
src/shared/components/timeline/ViewCount.js | sbekti/path-web-client | import React from 'react'
import ReactDOM from 'react-dom'
import { Link } from 'react-router'
import Cookies from 'js-cookie'
import request from 'superagent'
class ViewCount extends React.Component {
constructor(props) {
super(props)
this.state = {
expanded: false
}
this.handleViewClick = this.handleViewClick.bind(this)
this.handleEmotionClick = this.handleEmotionClick.bind(this)
}
handleViewClick() {
const newExpanded = !this.state.expanded
this.setState({
expanded: newExpanded
})
}
handleEmotionClick(e) {
const { moment, user, customGeo, realGeo } = this.props
const emotionType = e.target.dataset.tag
this.setState({
expanded: false
})
let body = {
moment_id: moment.get('id'),
emotion_type: emotionType,
token: user.get('oauth_token')
}
const spoofLocation = Cookies.get('spoof_location')
if (spoofLocation === 'true') {
body.lat = customGeo.get('lat')
body.lng = customGeo.get('lng')
} else {
body.lat = realGeo.get('lat')
body.lng = realGeo.get('lng')
}
request
.post('/api/v1/emotion/add')
.send(body)
.end((err, res) => {
this.props.onEmotionClick(moment.get('id'))
})
}
render() {
const { views, dark } = this.props
const { expanded } = this.state
let element = null
if (expanded) {
element = (
<div className='emotion-actions'>
<button className='btn btn-default emotion-button' data-tag='happy' onClick={this.handleEmotionClick}>🙂</button>
<button className='btn btn-default emotion-button' data-tag='laugh' onClick={this.handleEmotionClick}>😂</button>
<button className='btn btn-default emotion-button' data-tag='surprise' onClick={this.handleEmotionClick}>😮</button>
<button className='btn btn-default emotion-button' data-tag='sad' onClick={this.handleEmotionClick}>😢</button>
<button className='btn btn-default emotion-button' data-tag='love' onClick={this.handleEmotionClick}>❤️</button>
</div>
)
}
return (
<div className='view-count'>
<div className='emotion-actions-wrap'>
{element}
<button className='btn btn-default emotion-button' onClick={this.handleViewClick}>
<span className='glyphicon glyphicon-heart'></span> {views}
</button>
</div>
</div>
)
}
}
export default ViewCount
|
src/web/client/src/components/shared/individual-search.js | devmynd/cloud-access-manager | import React from 'react'
import TypeAheadInput from './type-ahead-input'
import MessagesContainer from './messages-container'
import graphqlApi from '../../graphql-api'
export default class IndividualSearch extends React.Component {
query = async (text, callback) => {
const query = `{ individuals(fuzzySearch:"${text}", limit: ${10})
{
id, primaryEmail, fullName
serviceUserIdentities {
serviceId
userIdentity {
email
userId
fullName
}
}
accessRules {
service {
id
displayName
}
accessRules {
asset
role
}
}
groups
}
}`
const response = await graphqlApi.request(query)
if (response.error) {
this.messagesContainer.push({
title: 'Could not access existing individuals',
body: response.error.message
})
return
}
callback(response.data.individuals)
}
renderIndividual = (individual) => {
const additionalDetails = this.props.additionalDetailsRenderer
? this.props.additionalDetailsRenderer(individual)
: false
return (
<div>
<span>{individual.fullName}</span>
{ individual.primaryEmail &&
<span> ({ individual.primaryEmail })</span>
}
{ additionalDetails }
</div>
)
}
render () {
return (
<div className="indvidual-search">
<TypeAheadInput
placeholder='Search for individual by name or email'
query={this.query}
isMatchDisabled={this.props.shouldDisableIndividual}
matchRenderer={this.renderIndividual}
onMatchSelected={this.props.onIndividualSelected}
/>
<MessagesContainer ref={(container) => { this.messagesContainer = container }} />
</div>
)
}
}
|
imports/ui/components/CreditNotes/ListCreditNotes/ListCreditNotes.js | haraneesh/mydev | import React from 'react';
import { Meteor } from 'meteor/meteor';
import PropTypes from 'prop-types';
import {
Button, Row, Table, Col, Panel, Glyphicon,
} from 'react-bootstrap';
import { toast } from 'react-toastify';
import { getFormattedMoney, getDayWithoutTime } from '../../../../modules/helpers';
import './ListCreditNotes.scss';
class ListCreditNotes extends React.Component {
constructor(props) {
super(props);
this.state = {
isCreditNotesLoading: true,
creditNotes: [],
creditNoteDetail: {},
};
this.fetchCreditNotes = this.fetchCreditNotes.bind(this);
this.fetchCreditNote = this.fetchCreditNote.bind(this);
}
fetchCreditNotes() {
Meteor.call('creditNotes.getCreditNotes',
(error, creditNotes) => {
if (error) {
// toast.error(error.reason);
toast.error(error.reason);
} else {
this.setState({
creditNotes,
isCreditNotesLoading: false,
});
}
});
}
fetchCreditNote(creditNoteId) {
Meteor.call('creditNotes.getCreditNote', creditNoteId,
(error, creditNote) => {
if (error) {
// toast.error(error.reason);
toast.error(error.reason);
} else {
this.setState({
creditNoteDetail: creditNote,
});
}
});
}
refundDetails(creditNoteDetail) {
return (
<section className="refund-section">
{
creditNoteDetail.line_items.map((item) => (
<Row className="refund-item">
<Col xs={8}>{item.name}</Col>
<Col xs={4}>{getFormattedMoney(item.item_total)}</Col>
</Row>
))
}
</section>
);
}
render() {
const { creditNotes } = this.state;
const { creditNoteDetail } = this.state;
return !this.state.isCreditNotesLoading ? (
<Panel>
{/* } <Row>
<Button type="button" onClick={this.fetchCreditNotes}>Show Refunds</Button>
</Row>
*/}
{creditNotes.length > 0 && (
<Col xs={12}>
<Row className="refund-heading">
<Col xs={5}><b>Refund Date</b></Col>
<Col xs={5}><b>Refund Amount</b></Col>
<Col xs={2} />
</Row>
{
creditNotes.map((creditNote) => {
const isCurrentRow = creditNote.creditnote_id === creditNoteDetail.creditnote_id;
return (
<Row className="refund-row" key={creditNote.creditnote_id}>
<Col xs={5}>{getDayWithoutTime(new Date(creditNote.date))}</Col>
<Col xs={5}>{getFormattedMoney(creditNote.total)}</Col>
<Col xs={2}>
{(!isCurrentRow) && (<Glyphicon glyph="plus" className="refund-expand" onClick={() => { this.fetchCreditNote(creditNote.creditnote_id); }} />) }
</Col>
<Col xs={12}>
{(isCurrentRow) && this.refundDetails(creditNoteDetail)}
</Col>
</Row>
);
})
}
</Col>
)}
</Panel>
) : (
<Panel>
{' '}
<button className="btn btn-sm btn-default" onClick={this.fetchCreditNotes}> Fetch Refund History </button>
{' '}
</Panel>
);
}
}
export default ListCreditNotes;
|
site/src/components/DemoBox.js | apisandipas/elemental | import React from 'react';
import classnames from 'classnames';
import E from '../../../src/constants';
const ALIGN_TRANSFORM = {
'center': 'center',
'left': 'flex-start',
'right': 'flex-end',
}
var DemoBox = React.createClass({
propTypes: {
align: React.PropTypes.oneOf(['center', 'left', 'right']),
children: React.PropTypes.node.isRequired,
},
getDefaultProps () {
return {
align: 'center'
};
},
render () {
let boxStyle = {
backgroundColor: 'rgba(0,0,0,0.05)',
borderRadius: 4,
display: 'flex',
justifyContent: ALIGN_TRANSFORM[this.props.align],
msFlexPack: ALIGN_TRANSFORM[this.props.align],
WebkitJustifyContent: ALIGN_TRANSFORM[this.props.align],
marginBottom: E.width.gutter,
padding: '.66em 1.5em',
};
if (this.props.inverted) {
boxStyle['backgroundColor'] = E.color.appPrimary;
}
let className = classnames('DemoBox', this.props.className);
return <div {...this.props} style={Object.assign({}, boxStyle, this.props.style)} className={className} />;
}
});
module.exports = DemoBox;
|
src/client/app/components/app-root.js | LINKIWI/apache-auth | import Favicon from 'react-favicon';
import React from 'react';
const AppRoot = ({children}) => (
<div className="app-root">
<Favicon
animated={false}
url={['/static/img/favicon.png']}
/>
{children}
</div>
);
export default AppRoot;
|
src/containers/fbpage.js | alexcurtis/react-fbpage | 'use strict';
import React from 'react';
import { connect } from 'react-redux';
import Page from '../components/page';
import {loadPage} from '../actions';
import defaultTheme from '../themes/default';
@connect(state => ({
loading: state.page.loading,
page: state.page.attributes,
feed: state.page.feed
}))
class FbPage extends React.Component {
componentDidMount(){
this.fetch(this.props.name);
}
componentWillReceiveProps(props){
if(props.name !== this.props.name){ this.fetch(props.name); }
}
fetch(name){
this.props.dispatch(loadPage({ name }));
}
render(){
return (
<Page
style={this.props.style}
loading={this.props.loading}
cover={this.props.page.cover}
profile={this.props.page.profile}
actions={this.props.page.actions}
feed={this.props.feed}
/>
);
}
}
FbPage.propTypes = {
style: React.PropTypes.object,
loading: React.PropTypes.bool,
name: React.PropTypes.string,
page: React.PropTypes.object,
feed: React.PropTypes.object,
dispatch: React.PropTypes.func
};
FbPage.defaultProps = {
style: defaultTheme
};
export default FbPage;
|
src/__mocks__/react-native.js | jimthedev/snowflake | /* eslint-disable react/no-multi-comp */
/**
* @see http://www.schibsted.pl/2015/10/testing-react-native-components-with-jest/
*/
import React from 'react';
const ReactNative = React;
ReactNative.StyleSheet = {
create: function create(styles) {
return styles;
}
};
class View extends React.Component {
render() { return false; }
}
class PixelRatio extends React.Component {
static get() { return 1; }
}
ReactNative.View = View;
ReactNative.ScrollView = View;
ReactNative.Text = View;
ReactNative.TouchableOpacity = View;
ReactNative.TouchableWithoutFeedback = View;
ReactNative.ToolbarAndroid = View;
ReactNative.Image = View;
ReactNative.PixelRatio = PixelRatio;
ReactNative.NativeModules= {};
ReactNative.Platform = {};
module.exports = ReactNative;
|
src/components/Footer/Footer.js | jshin47/ireactforyou | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.scss';
import Link from '../Link';
function Footer() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Your Company</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">Home</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/privacy">Privacy</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/not-found">Not Found</Link>
</div>
</div>
);
}
export default withStyles(Footer, s);
|
src/components/video_list_item.js | fzoozai/redux-stephenGrider | import React from 'react';
const VideoListItem = ({ video, onVideoSelect }) => {
const imageUrl = video.snippet.thumbnails.default.url;
return (
<li onClick={() => onVideoSelect(video)} className="list-group-item">
<div className="video-list media">
<div className="media-left">
<img className="media-object" src={imageUrl} />
</div>
<div className="media-body">
<div className="media-heading">{video.snippet.title}</div>
</div>
</div>
</li>
);
};
export default VideoListItem; |
source/generator-apparena-pattern/generators/app/templates/index.js | apparena/patterns | import React from 'react';
import PropTypes from 'prop-types';
import {ReactComponent} from 'apparena-patterns-react';
import cx from 'classnames';
import styles from './component.scss';
export default class <%= patternName %> extends ReactComponent {
render()
{
return (
<div>
</div>
);
}
}
|
src/views/HotspotSelector.js | learnfwd/lfa-printview-hotspot-editor | import React, { Component } from 'react';
import { connect } from 'react-redux';
import Select from 'react-select';
import { Button } from 'react-bootstrap';
import { selectedHotspotChange, createHotspot, deleteHotspot } from '../actions/UIActions';
import styles from './HotspotSelector.css';
class HotspotSelector extends Component {
selectionChanged = ({ value }) => {
this.props.dispatch(selectedHotspotChange(value));
}
createHotspot = () => {
const value = {
atom: 'atom_name',
top: 10,
left: 10,
width: 80,
height: 20,
};
this.props.dispatch(createHotspot(value));
}
deleteHotspot = () => {
this.props.dispatch(deleteHotspot());
}
render() {
const { selectedHotspot, page } = this.props;
const options = page.get('hotspots').map((hotspot, idx) => ({
value: idx,
label: `Hotspot ${idx + 1}`,
})).toJS();
const deleteButton = (selectedHotspot === null) ? null :
<Button onClick={this.deleteHotspot} className={styles.button}>
<i className='fa fa-fw fa-trash'/>
</Button>;
return <div className={styles.container}>
<Select
className={styles.selector}
placeholder='Select a hotspot'
value={selectedHotspot === null ? null : options[selectedHotspot]}
options={options}
onChange={this.selectionChanged}
/>
{deleteButton}
<Button onClick={this.createHotspot} className={styles.button}>
<i className='fa fa-fw fa-plus'/>
</Button>
</div>;
}
}
export default connect(state => ({
selectedHotspot: state.ui.selectedHotspot,
}))(HotspotSelector);
|
app/javascript/mastodon/features/list_editor/components/search.js | honpya/taketodon | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { defineMessages, injectIntl } from 'react-intl';
import { fetchListSuggestions, clearListSuggestions, changeListSuggestions } from '../../../actions/lists';
import classNames from 'classnames';
const messages = defineMessages({
search: { id: 'lists.search', defaultMessage: 'Search among people you follow' },
});
const mapStateToProps = state => ({
value: state.getIn(['listEditor', 'suggestions', 'value']),
});
const mapDispatchToProps = dispatch => ({
onSubmit: value => dispatch(fetchListSuggestions(value)),
onClear: () => dispatch(clearListSuggestions()),
onChange: value => dispatch(changeListSuggestions(value)),
});
@connect(mapStateToProps, mapDispatchToProps)
@injectIntl
export default class Search extends React.PureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
};
handleChange = e => {
this.props.onChange(e.target.value);
}
handleKeyUp = e => {
if (e.keyCode === 13) {
this.props.onSubmit(this.props.value);
}
}
handleClear = () => {
this.props.onClear();
}
render () {
const { value, intl } = this.props;
const hasValue = value.length > 0;
return (
<div className='list-editor__search search'>
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.search)}</span>
<input
className='search__input'
type='text'
value={value}
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
placeholder={intl.formatMessage(messages.search)}
/>
</label>
<div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}>
<i className={classNames('fa fa-search', { active: !hasValue })} />
<i aria-label={intl.formatMessage(messages.search)} className={classNames('fa fa-times-circle', { active: hasValue })} />
</div>
</div>
);
}
}
|
docs/src/app/components/pages/components/Card/ExampleControlled.js | hwo411/material-ui | import React from 'react';
import {Card, CardActions, CardHeader, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import Toggle from 'material-ui/Toggle';
export default class CardExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
expanded: false,
};
}
handleExpandChange = (expanded) => {
this.setState({expanded: expanded});
};
handleToggle = (event, toggle) => {
this.setState({expanded: toggle});
};
handleExpand = () => {
this.setState({expanded: true});
};
handleReduce = () => {
this.setState({expanded: false});
};
render() {
return (
<Card expanded={this.state.expanded} onExpandChange={this.handleExpandChange}>
<CardHeader
title="URL Avatar"
subtitle="Subtitle"
avatar="images/ok-128.jpg"
actAsExpander={true}
showExpandableButton={true}
/>
<CardText>
<Toggle
toggled={this.state.expanded}
onToggle={this.handleToggle}
labelPosition="right"
label="This toggle controls the expanded state of the component."
/>
</CardText>
<CardMedia
expandable={true}
overlay={<CardTitle title="Overlay title" subtitle="Overlay subtitle" />}
>
<img src="images/nature-600-337.jpg" alt="" />
</CardMedia>
<CardTitle title="Card title" subtitle="Card subtitle" expandable={true} />
<CardText expandable={true}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit.
Donec mattis pretium massa. Aliquam erat volutpat. Nulla facilisi.
Donec vulputate interdum sollicitudin. Nunc lacinia auctor quam sed pellentesque.
Aliquam dui mauris, mattis quis lacus id, pellentesque lobortis odio.
</CardText>
<CardActions>
<FlatButton label="Expand" onTouchTap={this.handleExpand} />
<FlatButton label="Reduce" onTouchTap={this.handleReduce} />
</CardActions>
</Card>
);
}
}
|
src/workflows/openfoam/tutorials/components/steps/Introduction/index.js | Kitware/HPCCloud | import React from 'react';
import DocumentationHTML from '../../../../../generic/components/steps/DocumentationHTML';
import staticContent from './content.html';
export default (props) => <DocumentationHTML staticContent={staticContent} />;
|
dashboard/app/components/LoginMfaForm/LoginMfaForm.js | tlisonbee/cerberus-management-service | import React from 'react'
import { Component } from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { reduxForm, touch } from 'redux-form'
import { finalizeMfaLogin } from '../../actions/authenticationActions'
import MfaDeviceSelect from '../MfaDeviceSelect/MfaDeviceSelect'
import './LoginFormMfa.scss'
const formName = 'login-mfa-form'
/**
* This is the smart component for the create new bucket page,
* This component contains the actual for and handle passing needed things into the dumb component views
*/
export const fields = ['otpToken', 'mfaDeviceId']
// define our client side form validation rules
const validate = values => {
const errors = {}
if (! values.otpToken) {
errors.otpToken = 'Required'
}
if (! values.mfaDeviceId) {
errors.mfaDeviceId = 'Required'
}
return errors
}
@connect((state) => {
return {
mfaDevices: state.auth.mfaDevices,
stateToken: state.auth.stateToken,
isAuthenticating: state.auth.isAuthenticating,
statusText: state.auth.statusText,
initialValues: {
redirectTo: state.routing.locationBeforeTransitions.query.next || '/',
}
}
})
// wire up the redux form
@reduxForm(
{
form: formName,
fields: fields,
validate
}
)
export default class LoginMfaForm extends Component {
static propTypes = {
fields: PropTypes.object.isRequired,
stateToken: PropTypes.string.isRequired,
isAuthenticating: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired,
}
render() {
const {fields: {otpToken, mfaDeviceId}, stateToken, handleSubmit, isAuthenticating, mfaDevices, dispatch} = this.props
return (
<div >
<h3 id="mfa-required-header" className="text-color-">MFA is required.</h3>
<form id={formName} onSubmit={handleSubmit( data => {
dispatch(finalizeMfaLogin(data.otpToken, data.mfaDeviceId, stateToken))
})}>
<div>
<label className='ncss-label'>MFA Devices:</label>
<div id='top-section'>
<MfaDeviceSelect {...mfaDeviceId}
mfaDevices={mfaDevices}
handleBeingTouched={() => {dispatch(touch(formName, 'mfaDeviceId'))}} />
</div>
<div id='security-code-div' className='ncss-form-group'>
<div className={((otpToken.touched && otpToken.error) ? 'ncss-input-container error' : 'ncss-input-container')}>
<label className='ncss-label'>Security Code</label>
<input type='text'
className='ncss-input pt2-sm pr4-sm pb2-sm pl4-sm r'
placeholder='Please enter your OTP token'
autoFocus={true}
{...otpToken}/>
{otpToken.touched && otpToken.error && <div className='ncss-error-msg'>{otpToken.error}</div>}
</div>
</div>
</div>
<div id='login-form-submit-container'>
<div id="login-help">
<a target="_blank" href="/dashboard/help/index.html">Need help?</a>
</div>
<button id='login-mfa-btn'
type='submit'
className='ncss-btn-offwhite ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
disabled={isAuthenticating}>Login</button>
</div>
</form>
</div>
)
}
}
|
src/components/Main.js | fayfei/gallery-by-react | require('normalize.css/normalize.css');
require('styles/main.scss');
import React from 'react';
import ReactDOM from 'react-dom';
//获取图片相关的数据
let imageDatas = require('../data/imageDatas.json');
//利用自执行函数,将图片名信息转成图片URL路径信息
imageDatas = (imageDatasArr => {
for (var i = 0; i < imageDatasArr.length; i++) {
let singleImageData = imageDatasArr[i];
singleImageData.imageURL = require('../images/' + singleImageData.fileName);
imageDatasArr[i] = singleImageData;
}
return imageDatasArr;
})(imageDatas);
function getRangeRandom(low, high) {
return Math.ceil(Math.random() * (high - low)) + low;
}
function get30DegRandom() {
return (Math.random() > 0.5 ? '' : '-') + Math.ceil(Math.random() * 30);
}
class ImgFigure extends React.Component {
handleClick(e) {
if (this.props.arrange.isCenter) {
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render() {
let styleObj = {};
if (this.props.arrange.pos) {
styleObj = this.props.arrange.pos;
}
if (this.props.arrange.rotate) {
['-moz-','-ms-','-webkit-',''].forEach(value => {
styleObj[value + 'transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)';
});
}
if (this.props.arrange.isCenter) {
styleObj['zIndex'] = 11;
}
let ImgFigureClassName = 'img-figure';
ImgFigureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
return (
<figure className={ImgFigureClassName} style={styleObj} onClick={this.handleClick.bind(this)}>
<img src={this.props.data.imageURL} alt={this.props.data.title}/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick.bind(this)}>
<p>{this.props.data.desc}</p>
</div>
</figcaption>
</figure>
);
}
}
class ControllerUnit extends React.Component {
handleClick(e) {
if (this.props.arrange.isCenter) {
this.props.inverse();
} else {
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render() {
let controllerUnitClassName = 'controller-unit';
if (this.props.arrange.isCenter) {
controllerUnitClassName += ' is-center';
if (this.props.arrange.isInverse) {
controllerUnitClassName += ' is-inverse';
}
}
return (
<span className={controllerUnitClassName} onClick={this.handleClick.bind(this)}></span>
)
}
}
class GalleryByReactApp extends React.Component {
constructor() {
super();
this.Constant = {
centerPos: {
left: 0,
top: 0
},
hPosRange: {
leftSecX: [0, 0],
rightSecX: [0, 0],
y: [0, 0]
},
vPosRange: {
x: [0, 0],
topY: [0, 0]
}
};
this.state = {
imgsArrangeArr: []
};
}
inverse(index) {
return () => {
let imgsArrangeArr = this.state.imgsArrangeArr;
imgsArrangeArr[index].isInverse = !imgsArrangeArr[index].isInverse;
this.setState({
imgsArrangeArr: imgsArrangeArr
});
};
}
rearrange(centerIndex) {
let imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecX,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgsArrangeTopArr = [],
topImgNum = Math.floor(Math.random() * 2),
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex, 1);
imgsArrangeCenterArr[0] = {
pos: centerPos,
rotate: 0,
isInverse: false,
isCenter: true
};
topImgSpliceIndex = Math.ceil(Math.random() * (imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex, topImgNum);
imgsArrangeTopArr.forEach((value, index) => {
imgsArrangeTopArr[index] = {
pos: {
top: getRangeRandom(vPosRangeTopY[0], vPosRangeTopY[1]),
left: getRangeRandom(vPosRangeX[0], vPosRangeX[1])
},
rotate: get30DegRandom(),
isInverse: false,
isCenter: false
}
});
for (let i = 0; i < imgsArrangeArr.length; i++) {
let hPosRangeLORX = null;
if (i < imgsArrangeArr.length / 2) {
hPosRangeLORX = hPosRangeLeftSecX;
} else {
hPosRangeLORX = hPosRangeRightSecX;
}
imgsArrangeArr[i] = {
pos: {
top: getRangeRandom(hPosRangeY[0], hPosRangeY[1]),
left: getRangeRandom(hPosRangeLORX[0], hPosRangeLORX[1])
},
rotate: get30DegRandom(),
isInverse: false,
isCenter:false
}
}
if (imgsArrangeTopArr && imgsArrangeTopArr[0]) {
imgsArrangeArr.splice(topImgSpliceIndex, 0, imgsArrangeTopArr[0]);
}
imgsArrangeArr.splice(centerIndex, 0, imgsArrangeCenterArr[0]);
this.setState({
imgsArrangeArr: imgsArrangeArr
});
}
center(index) {
return () => this.rearrange(index);
}
componentDidMount() {
let stageDom = this.refs.stage,
stageW = stageDom.scrollWidth,
stageH = stageDom.scrollHeight,
halfStageW = Math.ceil(stageW / 2),
halfStageH = Math.ceil(stageH / 2);
let imgFigureObj = this.refs.imgFigure0,
imgFigureDom = ReactDOM.findDOMNode(imgFigureObj),
imgW = imgFigureDom.scrollWidth,
imgH = imgFigureDom.scrollHeight,
halfImgW = Math.ceil(imgW / 2),
halfImgH = Math.ceil(imgH / 2);
this.Constant.centerPos = {
left: halfStageW - halfImgW,
top: halfStageH - halfImgH
};
this.Constant.hPosRange.leftSecX[0] = -halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImgW;
this.Constant.hPosRange.rightSecX[1] = stageW - halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageH - halfImgH;
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.Constant.vPosRange.x[0] = halfStageW - imgW;
this.Constant.vPosRange.x[1] = halfStageW;
this.rearrange(0);
}
render() {
let controllerUnits = [],
imgFigures = [];
imageDatas.forEach((value, index) => {
if (!this.state.imgsArrangeArr[index]) {
this.state.imgsArrangeArr[index] = {
pos: {
left: 0,
top: 0
},
rotate: 0,
isInverse: false,
isCenter: false
}
}
imgFigures.push(<ImgFigure key={index} data={value} ref={'imgFigure' + index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
controllerUnits.push(<ControllerUnit key={index} arrange={this.state.imgsArrangeArr[index]} inverse={this.inverse(index)} center={this.center(index)}></ControllerUnit>)
});
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgFigures}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
}
GalleryByReactApp.defaultProps = {
};
export default GalleryByReactApp;
|
examples/huge-apps/components/GlobalNav.js | joeyates/react-router | import React from 'react';
import { Link } from 'react-router';
const styles = {};
class GlobalNav extends React.Component {
static defaultProps = {
user: {
id: 1,
name: 'Ryan Florence'
}
};
constructor (props, context) {
super(props, context);
this.logOut = this.logOut.bind(this);
}
logOut () {
alert('log out');
}
render () {
var { user } = this.props;
return (
<div style={styles.wrapper}>
<div style={{float: 'left'}}>
<Link to="/" style={styles.link}>Home</Link>{' '}
<Link to="/calendar" style={styles.link} activeStyle={styles.activeLink}>Calendar</Link>{' '}
<Link to="/grades" style={styles.link} activeStyle={styles.activeLink}>Grades</Link>{' '}
<Link to="/messages" style={styles.link} activeStyle={styles.activeLink}>Messages</Link>{' '}
</div>
<div style={{float: 'right'}}>
<Link style={styles.link} to="/profile">{user.name}</Link> <button onClick={this.logOut}>log out</button>
</div>
</div>
);
}
}
var dark = 'hsl(200, 20%, 20%)';
var light = '#fff';
styles.wrapper = {
padding: '10px 20px',
overflow: 'hidden',
background: dark,
color: light
};
styles.link = {
padding: 11,
color: light,
fontWeight: 200
}
styles.activeLink = Object.assign({}, styles.link, {
background: light,
color: dark
});
export default GlobalNav;
|
lib/ErrorModal/ErrorModal.js | folio-org/stripes-components | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Button from '../Button';
import Modal from '../Modal';
import ModalFooter from '../ModalFooter';
const ErrorModal = ({
ariaLabel,
bodyTag: Element,
open,
content,
label,
buttonLabel,
onClose,
...rest
}) => {
const footer = (
<ModalFooter>
<Button
data-test-error-modal-close-button
onClick={onClose}
>
{buttonLabel || <FormattedMessage id="stripes-components.close" />}
</Button>
</ModalFooter>
);
return (
<Modal
data-test-error-modal
aria-label={rest['aria-label'] || ariaLabel}
open={open}
size="small"
label={label}
footer={footer}
>
<Element data-test-error-modal-content>
{content}
</Element>
</Modal>
);
};
ErrorModal.propTypes = {
ariaLabel: PropTypes.string,
bodyTag: PropTypes.string,
buttonLabel: PropTypes.oneOfType([
PropTypes.string,
PropTypes.node,
]),
content: PropTypes.node.isRequired,
label: PropTypes.node.isRequired,
onClose: PropTypes.func.isRequired,
open: PropTypes.bool.isRequired,
};
ErrorModal.defaultProps = {
bodyTag: 'div',
};
export default ErrorModal;
|
src/client/components/ui/slider/Slider.js | JulienPradet/quizzALJP | import React from 'react'
import Error from '../error/Error'
export default class Slider extends React.Component {
render() {
const activeSlide = this.props.children.length > this.props.activeIndex
? this.props.children[activeIndex]
: <Error>Wrong index displayed</Error>
return (
<div>
{ this.props.children[activeIndex] }
</div>
)
}
}
|
app/components/link1.js | varunagg45/webpack-react-sample-project | import React from 'react';
export default React.createClass({
getInitialState: function() {
return {
'page': 'This is from Link 1'
};
},
render: function() {
return (
<div>{this.state.page}</div>
);
}
});
|
src/svg-icons/action/important-devices.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionImportantDevices = (props) => (
<SvgIcon {...props}>
<path d="M23 11.01L18 11c-.55 0-1 .45-1 1v9c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-9c0-.55-.45-.99-1-.99zM23 20h-5v-7h5v7zM20 2H2C.89 2 0 2.89 0 4v12c0 1.1.89 2 2 2h7v2H7v2h8v-2h-2v-2h2v-2H2V4h18v5h2V4c0-1.11-.9-2-2-2zm-8.03 7L11 6l-.97 3H7l2.47 1.76-.94 2.91 2.47-1.8 2.47 1.8-.94-2.91L15 9h-3.03z"/>
</SvgIcon>
);
ActionImportantDevices = pure(ActionImportantDevices);
ActionImportantDevices.displayName = 'ActionImportantDevices';
ActionImportantDevices.muiName = 'SvgIcon';
export default ActionImportantDevices;
|
client/src/components/app.js | kat09kat09/GigRTC | import React from 'react';
import { Component,PropTypes } from 'react';
import SideBar from './sidebar';
import Header from './header';
import MyRawTheme from '../../public/css/giggTheme';
import ThemeManager from 'material-ui/lib/styles/theme-manager';
import ThemeDecorator from 'material-ui/lib/styles/theme-decorator';
import {determineEnvironment,refreshLoginState} from '../actions';
import {connect} from 'react-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
import mui from 'material-ui';
import AppBar from 'material-ui/lib/app-bar';
import jwtDecode from 'jwt-decode'
//let ThemeManager = mui.Styles.ThemeManager;
// let Colors = mui.Styles.Colors;
// let Style= mui.Styles.LightRawTheme;
injectTapEventPlugin();
export class App extends Component {
constructor(props) {
super(props);
}
componentWillMount(){
const{dispatch} = this.props
if(localStorage.getItem('token')){
dispatch(refreshLoginState({email : jwtDecode(localStorage.getItem('token')).user_name}))
}
}
getChildContext() {
return {
stores: this.props.stores,
muiTheme: ThemeManager.getMuiTheme(MyRawTheme)
};
}
render() {
return (
<div className="appComponentBody">
<Header/>
<SideBar/>
<div className="videoWrapper">
{this.props.children}
</div>
</div>
);
}
}
App.childContextTypes = {
stores: React.PropTypes.object,
muiTheme: React.PropTypes.object
};
function mapStateToProps(state){
return {
environment : state.environment,
tokenState : state.auth
}
}
export default connect(mapStateToProps)(App)
|
packages/material-ui-icons/src/InsertDriveFile.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let InsertDriveFile = props =>
<SvgIcon {...props}>
<path d="M6 2c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6H6zm7 7V3.5L18.5 9H13z" />
</SvgIcon>;
InsertDriveFile = pure(InsertDriveFile);
InsertDriveFile.muiName = 'SvgIcon';
export default InsertDriveFile;
|
frontend/src/System/Backup/BackupsConnector.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import * as commandNames from 'Commands/commandNames';
import { executeCommand } from 'Store/Actions/commandActions';
import { deleteBackup, fetchBackups } from 'Store/Actions/systemActions';
import createCommandExecutingSelector from 'Store/Selectors/createCommandExecutingSelector';
import Backups from './Backups';
function createMapStateToProps() {
return createSelector(
(state) => state.system.backups,
createCommandExecutingSelector(commandNames.BACKUP),
(backups, backupExecuting) => {
const {
isFetching,
isPopulated,
error,
items
} = backups;
return {
isFetching,
isPopulated,
error,
items,
backupExecuting
};
}
);
}
function createMapDispatchToProps(dispatch, props) {
return {
dispatchFetchBackups() {
dispatch(fetchBackups());
},
onDeleteBackupPress(id) {
dispatch(deleteBackup({ id }));
},
onBackupPress() {
dispatch(executeCommand({
name: commandNames.BACKUP
}));
}
};
}
class BackupsConnector extends Component {
//
// Lifecycle
componentDidMount() {
this.props.dispatchFetchBackups();
}
componentDidUpdate(prevProps) {
if (prevProps.backupExecuting && !this.props.backupExecuting) {
this.props.dispatchFetchBackups();
}
}
//
// Render
render() {
return (
<Backups
{...this.props}
/>
);
}
}
BackupsConnector.propTypes = {
backupExecuting: PropTypes.bool.isRequired,
dispatchFetchBackups: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, createMapDispatchToProps)(BackupsConnector);
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.