path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/svg-icons/hardware/keyboard-backspace.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareKeyboardBackspace = (props) => (
<SvgIcon {...props}>
<path d="M21 11H6.83l3.58-3.59L9 6l-6 6 6 6 1.41-1.41L6.83 13H21z"/>
</SvgIcon>
);
HardwareKeyboardBackspace = pure(HardwareKeyboardBackspace);
HardwareKeyboardBackspace.displayName = 'HardwareKeyboardBackspace';
HardwareKeyboardBackspace.muiName = 'SvgIcon';
export default HardwareKeyboardBackspace;
|
components/Header.js | mauricius/redux-memory-game | import React from 'react';
export default ({
round,
restart
}) => (
<div>
<h2>Round: {round}</h2>
<button className="button button--warning text-center" onClick={() => restart()} disabled={round === 0}>Restart</button>
</div>
)
|
index.ios.js | yyoshiki41/fastlane-playground | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class AwesomeProject extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
|
src/js/components/configPage/Helper/index.js | zacyu/bilibili-helper | /**
* Author: DrowsyFlesh
* Create: 2018/10/29
* Description:
*/
import React from 'react';
import styled from 'styled-components';
import {Icon} from 'Components';
import {theme} from 'Styles';
const {color} = theme;
const HelperView = styled(Icon)`
margin-left: 10px;
color: ${color('google-grey-600')};
`;
export class Helper extends React.Component {
constructor(props) {
super(props);
}
handleOnClick = (e) => {
e.stopPropagation();
}
render() {
const {type, description, ...rest} = this.props;
return (
<HelperView
onClick={this.handleOnClick}
title={description}
iconfont={type}
{...rest}
/>
);
}
} |
src/decorators/withViewport.js | ernestho/toronto-subway-map | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
application/assets/javascripts/components/attendee-list.js | fevrcoding/name-selector | /**
* Applicatino Container: List of attendees
*
* @author Marco Solazzi
* @copyright (c) Marco solazzi
* @module components/attendees-list
*/
import React, { Component } from 'react';
import { connect } from 'react-redux';
import {attendeeListSelectAction} from '../actions';
import Attendee from './attendee';
import 'gsap';
function mapStateToProps(state) {
return {
attendees: state.attendeeList.filter((attendee) => state.selected.indexOf(attendee.id) === -1)
};
}
function mapDispatchToProps(dispatch) {
return {
onSelectAttendee: (id) => {
dispatch(attendeeListSelectAction(id));
}
};
}
export class AttendeeList extends Component {
spin() {
const body = this.refs.rouletteBody;
const height = body.offsetHeight;
var tl = new TimelineMax({repeat:2, stop: true});
tl.add( TweenMax.to(body, 1, {y: height * -1, ease: Power0.easeNone}) );
tl.add( TweenLite.set(body, {y: 0}) );
tl.play();
}
selectAttendee(id) {
this.props.onSelectAttendee(id);
}
render() {
let items = this.props.attendees.map((attendee) => (
<Attendee details={attendee} key={attendee.id} onSelectAttendee={this.selectAttendee.bind(this)} />
));
return (<section className="c-roulette">
<div className="c-roulette__mask">
<ul className="c-roulette__body c-attendee-list" ref="rouletteBody">{items}</ul>
</div>
<footer>
<button className="o-btn" onClick={this.spin.bind(this)}>{'Spin!'}</button>
</footer>
</section>);
}
}
AttendeeList.propTypes = {
attendees: React.PropTypes.array,
onSelectAttendee: React.PropTypes.func.isRequired
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(AttendeeList); |
src/svg-icons/av/replay-5.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvReplay5 = (props) => (
<SvgIcon {...props}>
<path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-1.3 8.9l.2-2.2h2.4v.7h-1.7l-.1.9s.1 0 .1-.1.1 0 .1-.1.1 0 .2 0h.2c.2 0 .4 0 .5.1s.3.2.4.3.2.3.3.5.1.4.1.6c0 .2 0 .4-.1.5s-.1.3-.3.5-.3.2-.4.3-.4.1-.6.1c-.2 0-.4 0-.5-.1s-.3-.1-.5-.2-.2-.2-.3-.4-.1-.3-.1-.5h.8c0 .2.1.3.2.4s.2.1.4.1c.1 0 .2 0 .3-.1l.2-.2s.1-.2.1-.3v-.6l-.1-.2-.2-.2s-.2-.1-.3-.1h-.2s-.1 0-.2.1-.1 0-.1.1-.1.1-.1.1h-.7z"/>
</SvgIcon>
);
AvReplay5 = pure(AvReplay5);
AvReplay5.displayName = 'AvReplay5';
AvReplay5.muiName = 'SvgIcon';
export default AvReplay5;
|
src/SparklinesLine.js | codevlabs/react-sparklines | import React from 'react';
export default class SparklinesLine extends React.Component {
static propTypes = {
color: React.PropTypes.string,
style: React.PropTypes.object
};
static defaultProps = {
style: {}
};
render() {
const { points, width, height, margin, color, style } = this.props;
const linePoints = points
.map((p) => [p.x, p.y])
.reduce((a, b) => a.concat(b));
const closePolyPoints = [
points[points.length - 1].x, height - margin,
margin, height - margin,
margin, points[0].y
];
const fillPoints = linePoints.concat(closePolyPoints);
const lineStyle = {
stroke: color || style.stroke || 'slategray',
strokeWidth: style.strokeWidth || '1',
strokeLinejoin: style.strokeLinejoin || 'round',
strokeLinecap: style.strokeLinecap || 'round',
fill: 'none'
};
const fillStyle = {
stroke: style.stroke || 'none',
strokeWidth: '0',
fillOpacity: style.fillOpacity || '.1',
fill: color || style.fill || 'slategray'
};
return (
<g>
<polyline points={fillPoints.join(' ')} style={fillStyle} />
<polyline points={linePoints.join(' ')} style={lineStyle} />
</g>
)
}
}
|
app/main.js | seentaoInternetOrganization/reactDemo | import React from 'react';
import Router from 'react-router';
import ReactDOM from 'react-dom';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import routes from './routes';
// import Navbar from './components/Navbar';
let history = createBrowserHistory();
ReactDOM.render(<Router history={history}>{routes}</Router>, document.getElementById('app')); |
react-app/src/Components/LoginForm.js | Binarysearch/quiz | import React, { Component } from 'react';
import styled from 'styled-components';
import axios from 'axios';
import { updateField } from '../Utils/UpdateField';
import FormField from './FormField';
import Button from './Button';
import { Redirect } from 'react-router-dom';
const StyledForm = styled.form`
background-color: white;
padding: 10px 30px;
border: 1px solid #cdcdcd;
border-radius: 5px;
box-sizing: border-box;
box-shadow: 2px 2px 3px rgba(0, 0, 0, 0.1);
width: 30%;
margin: 0 auto;
margin-top: 50px;
@media (max-width: 1200px) {
width: 60%;
}
@media (max-width: 768px) {
width: 90%;
}
`;
const FormTitle = styled.h1`
text-align: center;
font-size: 2rem;
font-weight: 700;
`;
const CenteredDiv = styled.div`
text-align: center;
`;
export class LoginForm extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
redirect: false
};
this.handleLogin = this.handleLogin.bind(this);
}
updateField = updateField.bind(this);
handleLogin() {
axios
.post(
`https://binarysearch.es/quiz/login?email=${
this.state.email
}&password=${this.state.password}`
)
.then((response) => {
if (response.data.token !== undefined) {
this.props.updateSession(response.data.token);
this.setState({ redirect: true });
}
});
}
render() {
if (this.state.redirect) {
return <Redirect to="/" />;
}
return (
<StyledForm>
<FormTitle>Login into Accout</FormTitle>
<FormField
value={this.state.email}
type="email"
name="email"
placeholder="Email"
labelText="Email:"
onChangeText={this.updateField}
/>
<FormField
value={this.state.password}
type="password"
name="password"
placeholder="Password"
labelText="Password:"
onChangeText={this.updateField}
/>
<CenteredDiv>
<Button
buttonText="Login"
onClick={(event) => {
event.preventDefault();
if (this.state.email !== '' && this.state.password !== '') {
this.handleLogin();
}
}}
/>
</CenteredDiv>
</StyledForm>
);
}
}
export default LoginForm;
|
src/components/ListParagraph/index.js | duheng/Mozi | import React from 'react';
import { StyleSheet, View, } from 'react-native';
import Placeholder from 'rn-placeholder';
const styles = StyleSheet.create({
title: {
marginBottom: 12,
},
item: {
margin: 12,
},
});
const Title = hasTitle => {
return hasTitle ? (
<View style={styles.title}>
<Placeholder.Line />
</View>
) : null;
};
const Placeholders = props => {
const { ParagraphLength, ParagraphType, hasTitle, ...others } = props;
const PlaceholderItem = Placeholder[ParagraphType];
const PlaceholderContent = [];
for (let key = 0; key < ParagraphLength; key++) {
PlaceholderContent.push(
<View style={styles.item} key={`PlaceholderContentKey${key}`}>
{Title(hasTitle)}
<PlaceholderItem {...others} />
</View>,
);
}
return <View>{PlaceholderContent}</View>;
};
const ListParagraph = props => {
const baseOption = {
ParagraphLength: 5,
ParagraphType: 'ImageContent',
hasTitle: false,
size: 60,
animate: 'fade',
lineNumber: 3,
lineSpacing: 12,
lastLineWidth: '60%',
};
const options = { ...baseOption, ...props, };
const { isLoading, list, } = props;
if (isLoading) {
return Placeholders(options);
}
return typeof list === 'function' && list();
};
export default Placeholder.connect(ListParagraph);
|
node_modules/babel-plugin-react-require/examples/with-imported-react.js | DouglasUrner/Mantra-Boilerplate | import React from 'react';
export default class Component {
render() {
return <div />;
}
}
|
fields/components/DateInput.js | Tangcuyu/keystone | import moment from 'moment';
import DayPicker from 'react-day-picker';
import React from 'react';
import ReactDOM from 'react-dom';
import Popout from '../../admin/client/components/Popout';
import { FormInput } from 'elemental';
let lastId = 0;
module.exports = React.createClass({
displayName: 'DateInput',
propTypes: {
format: React.PropTypes.string,
name: React.PropTypes.string,
onChange: React.PropTypes.func.isRequired,
path: React.PropTypes.string,
value: React.PropTypes.string.isRequired,
},
getDefaultProps () {
return {
format: 'YYYY-MM-DD',
};
},
getInitialState () {
const id = ++lastId;
let month = new Date();
const { format, value } = this.props;
if (moment(value, format, true).isValid()) {
month = moment(value, format).toDate();
}
return {
id: `_DateInput_${id}`,
month: month,
pickerIsOpen: false,
inputValue: value,
};
},
componentDidMount () {
this.showCurrentMonth();
},
componentWillReceiveProps: function (newProps) {
if (newProps.value === this.props.value) return;
this.setState({
month: moment(newProps.value, this.props.format).toDate(),
inputValue: newProps.value,
}, this.showCurrentMonth);
},
focus () {
if (!this.refs.input) return;
this.refs.input.focus();
},
handleInputChange (e) {
const { value } = e.target;
this.setState({ inputValue: value }, this.showCurrentMonth);
},
handleKeyPress (e) {
if (e.key === 'Enter') {
e.preventDefault();
const parsedDate = moment(this.state.inputValue, this.props.format);
// If the date is strictly equal to the format string, dispatch onChange
if (moment(this.state.inputValue, this.props.format, true).isValid()) {
this.props.onChange({ value: this.state.inputValue });
// If the date is not strictly equal, only change the tab that is displayed
} else if (moment(this.state.inputValue, this.props.format).isValid()) {
this.setState({
month: moment(this.state.inputValue, this.props.format).toDate(),
}, this.showCurrentMonth);
}
}
},
handleDaySelect (e, date, modifiers) {
if (modifiers.indexOf('disabled') > -1) {
return;
}
var value = moment(date).format(this.props.format);
this.props.onChange({ value });
this.setState({
pickerIsOpen: false,
month: date,
inputValue: value,
});
},
showPicker () {
this.setState({ pickerIsOpen: true }, this.showCurrentMonth);
},
showCurrentMonth () {
if (!this.refs.picker) return;
this.refs.picker.showMonth(this.state.month);
},
handleFocus (e) {
if (this.state.pickerIsOpen) return;
this.showPicker();
},
handleBlur (e) {
let rt = e.relatedTarget;
const popout = this.refs.popout.getPortalDOMNode();
while (rt) {
if (rt === popout) return;
rt = rt.parentNode;
}
this.setState({
pickerIsOpen: false,
});
},
render () {
const selectedDay = this.props.value;
// react-day-picker adds a class to the selected day based on this
const modifiers = {
selected: (day) => moment(day).format(this.props.format) === selectedDay,
};
return (
<div>
<FormInput
autoComplete="off"
id={this.state.id}
name={this.props.name}
onBlur={this.handleBlur}
onFocus={this.handleFocus}
onChange={this.handleInputChange}
placeholder={this.props.format}
ref="input"
onKeyPress={this.handleKeyPress}
value={this.state.inputValue} />
<Popout
ref="popout"
isOpen={this.state.pickerIsOpen}
onCancel={() => this.setState({ pickerIsOpen: false })}
relativeToID={this.state.id}
width={260}>
<DayPicker
ref="picker"
modifiers={modifiers}
onDayClick={this.handleDaySelect}
tabIndex={-1} />
</Popout>
</div>
);
},
});
|
src/components/compact/story.js | casesandberg/react-color | import React from 'react'
import { storiesOf } from '@storybook/react'
import { renderWithKnobs } from '../../../.storybook/report'
import SyncColorField from '../../../.storybook/SyncColorField'
import Compact from './Compact'
storiesOf('Pickers', module)
.add('CompactPicker', () => (
<SyncColorField component={ Compact }>
{ renderWithKnobs(Compact, {}, null, {
width: { range: true, min: 140, max: 500, step: 1 },
circleSize: { range: true, min: 8, max: 72, step: 4 },
circleSpacing: { range: true, min: 7, max: 42, step: 7 },
}) }
</SyncColorField>
))
|
test/integration/css-fixtures/bad-custom-configuration-arr-7/pages/_app.js | zeit/next.js | import React from 'react'
import App from 'next/app'
import '../styles/global.css'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
|
features/app/components/App.web.js | jitsi/jitsi-meet-react | import React from 'react';
import { Provider } from 'react-redux';
import {
browserHistory,
Route,
Router
} from 'react-router';
import { push, syncHistoryWithStore } from 'react-router-redux';
import { getDomain } from '../../base/connection';
import { RouteRegistry } from '../../base/navigator';
import { AbstractApp } from './AbstractApp';
/**
* Root application component.
*
* @extends AbstractApp
*/
export class App extends AbstractApp {
/**
* Initializes a new App instance.
*
* @param {Object} props - The read-only React Component props with which
* the new instance is to be initialized.
*/
constructor(props) {
super(props);
/**
* Create an enhanced history that syncs navigation events with the
* store.
* @link https://github.com/reactjs/react-router-redux#how-it-works
*/
this.history = syncHistoryWithStore(browserHistory, props.store);
// Bind event handlers so they are only bound once for every instance.
this._onRouteEnter = this._onRouteEnter.bind(this);
this._routerCreateElement = this._routerCreateElement.bind(this);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const routes = RouteRegistry.getRoutes();
/* eslint-disable no-extra-parens */
return (
<Provider store = { this.props.store }>
<Router
createElement = { this._routerCreateElement }
history = { this.history }>
{ routes.map(r => (
<Route
component = { r.component }
key = { r.component }
onEnter = { this._onRouteEnter }
path = { r.path } />
)) }
</Router>
</Provider>
);
/* eslint-enable no-extra-parens */
}
/**
* Navigates to a specific Route (via platform-specific means).
*
* @param {Route} route - The Route to which to navigate.
* @returns {void}
*/
_navigate(route) {
let path = route.path;
const store = this.props.store;
// The syntax :room bellow is defined by react-router. It "matches a URL
// segment up to the next /, ?, or #. The matched string is called a
// param."
path
= path.replace(
/:room/g,
store.getState()['features/base/conference'].room);
return store.dispatch(push(path));
}
/**
* Invoked by react-router to notify this App that a Route is about to be
* rendered.
*
* @private
* @returns {void}
*/
_onRouteEnter() {
// XXX The following is mandatory. Otherwise, moving back & forward
// through the browser's history could leave this App on the Conference
// page without a room name.
// Our Router configuration (at the time of this writing) is such that
// each Route corresponds to a single URL. Hence, entering into a Route
// is like opening a URL.
// XXX In order to unify work with URLs in web and native environments,
// we will construct URL here with correct domain from config.
const currentDomain = getDomain(this.props.store.getState);
const url
= new URL(window.location.pathname, `https://${currentDomain}`)
.toString();
this._openURL(url);
}
/**
* Create a ReactElement from the specified component and props on behalf of
* the associated Router.
*
* @param {Component} component - The component from which the ReactElement
* is to be created.
* @param {Object} props - The read-only React Component props with which
* the ReactElement is to be initialized.
* @private
* @returns {ReactElement}
*/
_routerCreateElement(component, props) {
return this._createElement(component, props);
}
}
/**
* App component's property types.
*
* @static
*/
App.propTypes = AbstractApp.propTypes;
|
docs/src/pages/components/lists/InsetList.js | lgollut/material-ui | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import StarIcon from '@material-ui/icons/Star';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
}));
export default function InsetList() {
const classes = useStyles();
return (
<List component="nav" className={classes.root} aria-label="contacts">
<ListItem button>
<ListItemIcon>
<StarIcon />
</ListItemIcon>
<ListItemText primary="Chelsea Otakan" />
</ListItem>
<ListItem button>
<ListItemText inset primary="Eric Hoffman" />
</ListItem>
</List>
);
}
|
samples/react-redux-patient-demographics-example/src/common/FormsyHiddenInput.js | GoTeamEpsilon/angular-to-react | import React from 'react'
import Formsy from 'formsy-react'
export const FormsyHiddenInput = React.createClass({
mixins: [Formsy.Mixin],
changeValue(event) {
let value = ''
if (event && event.currentTarget && event.currentTarget.value) {
value = event.currentTarget.value
event.currentTarget.value = value
}
this.props.onChange(event)
this.setValue(value)
},
render() {
return (
<div className='hidden'>
<input type='hidden'
onChange={this.changeValue}
value={this.getValue()}
name={this.props.name} />
</div>
)
}
})
|
examples/shopping-cart/src/main.js | aldanor/nuclear-js | 'use strict';
import React from 'react'
import App from './components/App'
import reactor from './reactor'
import actions from './actions'
import CartStore from './stores/CartStore'
import ProductStore from './stores/ProductStore'
reactor.registerStores({
cart: CartStore,
products: ProductStore,
})
actions.fetchProducts()
React.render(
React.createElement(App, null),
document.getElementById('flux-app')
);
|
classic/src/scenes/wbui/ReadingQueueSnackbarHelper.js | wavebox/waveboxapp | import React from 'react'
import { Snackbar, Button } from '@material-ui/core'
import shallowCompare from 'react-addons-shallow-compare'
import { ipcRenderer } from 'electron'
import {
WB_READING_QUEUE_LINK_ADDED,
WB_READING_QUEUE_CURRENT_PAGE_ADDED,
WB_READING_QUEUE_OPEN_URL,
WB_READING_QUEUE_OPEN_URL_EMPTY
} from 'shared/ipcEvents'
class ReadingQueueSnackbarHelper extends React.Component {
/* **************************************************************************/
// Component Lifecycle
/* **************************************************************************/
componentDidMount () {
ipcRenderer.on(WB_READING_QUEUE_LINK_ADDED, this.handleLinkAdded)
ipcRenderer.on(WB_READING_QUEUE_CURRENT_PAGE_ADDED, this.handleCurrentPageAdded)
ipcRenderer.on(WB_READING_QUEUE_OPEN_URL, this.handleUrlOpened)
ipcRenderer.on(WB_READING_QUEUE_OPEN_URL_EMPTY, this.handleUrlFailedOpenEmpty)
}
componentWillUnmount () {
ipcRenderer.removeListener(WB_READING_QUEUE_LINK_ADDED, this.handleLinkAdded)
ipcRenderer.removeListener(WB_READING_QUEUE_CURRENT_PAGE_ADDED, this.handleCurrentPageAdded)
ipcRenderer.removeListener(WB_READING_QUEUE_OPEN_URL, this.handleUrlOpened)
ipcRenderer.removeListener(WB_READING_QUEUE_OPEN_URL_EMPTY, this.handleUrlFailedOpenEmpty)
}
/* **************************************************************************/
// Data lifecycle
/* **************************************************************************/
state = {
open: false,
message: ''
}
/* **************************************************************************/
// UI Events
/* **************************************************************************/
handleLinkAdded = (evt) => {
this.setState({
open: true,
message: 'Added link to your Tasks'
})
}
handleCurrentPageAdded = (evt) => {
this.setState({
open: true,
message: 'Added current page to your Tasks'
})
}
handleUrlOpened = (evt, readingItem) => {
this.setState({
open: true,
message: [
'Opening',
readingItem.title
? `"${readingItem.title}"`
: 'item',
'from your Tasks'
].join(' ')
})
}
handleUrlFailedOpenEmpty = (evt) => {
this.setState({
open: true,
message: 'No more items in your Tasks'
})
}
handleDismiss = () => {
this.setState({ open: false })
}
/* **************************************************************************/
// Rendering
/* **************************************************************************/
shouldComponentUpdate (nextProps, nextState) {
return shallowCompare(this, nextProps, nextState)
}
render () {
const { open, message } = this.state
return (
<Snackbar
autoHideDuration={2500}
disableWindowBlurListener
key={message}
anchorOrigin={{ vertical: 'bottom', horizontal: 'center' }}
open={open}
onClose={this.handleDismiss}
action={(
<Button color='secondary' size='small' onClick={this.handleDismiss}>
Okay
</Button>
)}
message={message}
/>
)
}
}
export default ReadingQueueSnackbarHelper
|
src/components/Columns/Columns.js | nambawan/g-old | // taken from https://github.com/grommet/grommet/blob/master/src/js/components/Columns.js
/* eslint-disable */
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import withStyles from 'isomorphic-style-loader/withStyles';
import s from './Columns.css';
class Columns extends React.Component {
componentDidMount() {
if (this.props.masonry) {
throw Error('To implement');
// this._getColumnBreakpoints();
}
window.addEventListener('resize', this.onResize);
setTimeout(this.layout, 10);
}
onResize() {
clearTimeout(this.layoutTimer);
this.layoutTimer = setTimeout(this.layout, 50);
}
layout() {
const { masonry } = this.props;
const container = this.containerRef;
if (container && !masonry) {
// fills columns top to bottom, then left to right
const children = React.Children.toArray(this.props.children);
let count = 1;
const child = container.childNodes[0];
if (child) {
const rect = container.getBoundingClientRect();
const childRect = child.getBoundingClientRect();
const widestCount = Math.floor(rect.width / childRect.width);
const childrenPerColumn = Math.ceil(children.length / widestCount);
count = Math.ceil(children.length / childrenPerColumn);
}
if (count === 0) {
count = 1;
}
this.setState({ count });
}
}
renderColumns() {
const { masonry } = this.props;
const children = React.Children.toArray(this.props.children);
const groups = [];
if (masonry) {
const { maxCount } = this.state;
const columnGroups = {};
React.Children.map(
children,
(child, index) => {
const currentColumn = index % maxCount;
if (!columnGroups[currentColumn]) {
columnGroups[currentColumn] = [];
}
// place children into appropriate column
if (child) {
columnGroups[currentColumn].push(child);
}
},
this,
);
Object.keys(columnGroups).map((key, index) => {
if (columnGroups[index]) {
groups.push(columnGroups[index]);
}
});
} else {
const { count } = this.state;
const childrenPerColumn = Math.ceil(children.length / count);
let offset = 0;
while (groups.length < count) {
groups.push(children.slice(offset, offset + childrenPerColumn));
offset += childrenPerColumn;
}
}
return groups;
}
render() {
throw Error('Not finished!');
const { justify } = this.props;
const { margin } = this.state;
const groups = this.renderColumns();
const columns = groups.map((group, index) =>
<div key={index} className={s.column}>
{group}
</div>,
);
return (
<div ref={ref => (this.containerRef = ref)}>
{columns}
</div>
);
}
}
/* eslint-enable */
export default withStyles(s)(Columns);
|
src/js_src/containers/search/resultsTable.js | hitz/python-flask-es-test | import React, { Component } from 'react';
import style from './style.css';
import DetailList from './detailList';
import LogList from './logList';
import { makeFieldDisplayName } from '../../lib/searchHelpers';
import { NON_HIGHLIGHTED_FIELDS } from '../../constants';
const MATCH_LABEL = 'match_by';
const MAX_CHAR = 100;
class ResultsTable extends Component {
getFields() {
let fields;
switch(this.props.activeCategory) {
case 'gene':
fields = ['display_name', 'name', 'synonyms', 'source', 'species', 'gene_type', 'genomic_coordinates'];
break;
case 'go':
fields = ['display_name', 'id', 'synonyms', 'go_branch'];
break;
case 'disease':
fields = ['display_name', 'omim_id', 'synonyms'];
break;
default:
fields = ['display_name', 'synonyms'];
}
fields.push(MATCH_LABEL);
return fields;
}
renderHeader() {
let fields = this.getFields();
let nodes = fields.map( (d) => {
let processedName;
if (this.props.activeCategory === 'gene' && d === 'display_name') {
processedName = 'symbol';
} else if (d === 'display_name') {
processedName = 'name';
} else {
processedName = d;
}
return <th className={style.tableHeadCell} key={`srH.${d}`}>{makeFieldDisplayName(processedName)}</th>;
});
return (
<tr>
{nodes}
</tr>
);
}
renderTruncatedContent(original) {
original = original || '';
if (Array.isArray(original)) {
original = original.join(', ');
}
if (original.length > MAX_CHAR) {
return original.slice(0, MAX_CHAR) + '...';
} else {
return original;
}
}
renderRows() {
let entries = this.props.entries;
let fields = this.getFields();
let rowNodes = entries.map( (d, i) => {
let nodes = fields.map( (field) => {
let isMakeLowercase = d.category === 'disease';
let _className = isMakeLowercase ? style.lowercase : null;
let _key = `srtc.${i}.${field}`;
switch(field) {
case 'display_name':
case 'symbol':
return <td key={_key}><a className={_className} dangerouslySetInnerHTML={{ __html: d[field] }} href={d.href} target='_new' /></td>;
case 'source':
return <td key={_key}><a dangerouslySetInnerHTML={{ __html: d.id }} href={d.href} target='_new' /></td>;
case MATCH_LABEL:
return <td key={_key}>{this.renderHighlight(d.highlight, d.homologs)}</td>;
case 'species':
return <td key={_key}><i dangerouslySetInnerHTML={{ __html: d.species }} /></td>;
default:
return <td dangerouslySetInnerHTML={{ __html: this.renderTruncatedContent(d[field]) }} key={_key} />;
}
});
return (
<tr key={`tr${i}`}>
{nodes}
</tr>
);
});
return (
<tbody>
{rowNodes}
</tbody>
);
}
renderHighlight(highlight, homologs) {
homologs = homologs || [];
let _data = highlight;
let _fields = Object.keys(_data).filter( d => {
return (NON_HIGHLIGHTED_FIELDS.indexOf(d) < 0);
});
let logHighlight = highlight['homologs.symbol'] || highlight['homologs.panther_family'];
let homologNode = null;
if (homologs.length && logHighlight) {
homologNode = <LogList label='Homologs' logs={homologs} rawHighlight={logHighlight} />;
}
return (
<div>
<DetailList data={_data} fields={_fields} />
{homologNode}
</div>
);
}
render() {
let emptyNode = (this.props.entries.length === 0) ? <p className={style.tableEmpty}>No results</p> : null;
return (
<div className={style.tableContainer}>
<table className='table'>
<thead className='thead-default'>
{this.renderHeader()}
</thead>
{this.renderRows()}
</table>
{emptyNode}
</div>
);
}
}
ResultsTable.propTypes = {
activeCategory: React.PropTypes.string,
entries: React.PropTypes.array
};
export default ResultsTable;
|
src/routes.js | kiyonish/kiyonishimura | import React from 'react'
import { IndexRoute, Route } from 'react-router'
// import AnimationCanvas from './components/experiments/AnimationCanvas'
import {
App,
Home,
NotFound,
} from 'containers'
export default () => {
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="*" component={NotFound} status={404} />
</Route>
)
}
// <Route path="/animation/" component={AnimationCanvas} />
|
src/pages/flow.js | TASnomad/Fallon-react-native-app | import React, { Component } from 'react';
import {
AsyncStorage,
Button,
View,
Text,
ScrollView,
StyleSheet,
RefreshControl,
} from 'react-native';
import SideBar from '../components/SideBar';
import URLS from '../utils/ajaxURL';
const flowSheet = StyleSheet.create({
scrollContainer: {
flexGrow: 1,
},
nothingContainer: {
flex: 1,
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
},
nothingText: {
fontSize: 24,
},
retryBtn: {
marginTop: 30,
},
flowBlox: {
flex: 1,
flexDirection: 'column',
backgroundColor: '#F0F0F2',
padding: 15,
margin: 5,
borderRadius: 10,
},
flowContent: {
flex: 1,
flexDirection: 'column',
alignSelf: 'center',
justifyContent: 'center',
margin: 5,
},
flowHeader: {
flex: 1,
borderBottomWidth: 1,
borderBottomColor: '#4CAF50',
}
});
export default class Flow extends Component {
constructor(props) {
super(props);
var __that__ = this;
this.state = {
data: [],
asData: false,
requestPending: false,
urlToRetrieve: URLS.FLOW,
group: __that__.props.route.group,
nom: __that__.props.route.nom,
refresh: false,
};
this.retrieveFlow();
}
retrieveFlow() {
var __that__ = this;
this.setState({ requestPending: true });
fetch(this.state.urlToRetrieve, {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({ group: this.props.route.group })
}).then((data) => {
this.setState({
requestPending: false,
refresh: false,
});
if(data.ok)
return data.json();
else
return null;
}).then((res) => {
__that__.setState({
data: res.data,
asData: true
});
__that__.forceUpdate();
}).catch(function(error) {
__that__.setState({
data: [],
asData: false,
requestPending: false,
refresh: false
});
});
}
renderEmptyFlow() {
return (
<View
style={ flowSheet.nothingContainer }
refreshControl= {
<RefreshControl
refreshing={ this.state.refresh }
onRefresh={ this.retrieveFlow.bind(this) }
tintColor="#00FF00"
title="Chargement..."
titleColor="#FFFFFF"
colors={['#000000', '#FFFFFF', '#F44336']}
progressBackgroundColor="#FFFFFF" />
}>
<Text style={ flowSheet.nothingText }>Wow. Aucune absences ou retards !</Text>
<Button style={ flowSheet.retryBtn } title="Réessayer" onPress={ this.retrieveFlow.bind(this) }/>
</View>
);
}
renderFlow() {
return this.state.data.map((chunck, index) => {
/* Dummy way to capitalize the first letter ... */
chunck.type_imprevu = chunck.type_imprevu.charAt(0).toUpperCase() + chunck.type_imprevu.slice(1);
return (
<View key={ index } style={ flowSheet.flowBlox }>
<Text style={ flowSheet.flowHeader }>
{ chunck.type_imprevu } le { chunck.date_mes } envoyé par { (chunck.envoye_par == "") ? "l'administrateur" : chunck.envoye_par }
</Text>
<Text style={ flowSheet.flowContent }>
{ chunck.nom_prof }
</Text>
<Text style={ flowSheet.flowContent }>
{ chunck.message }
</Text>
</View>
);
});
}
render() {
let toRender = null;
(this.state.asData && this.state.data.length !== 0)
? toRender = this.renderFlow() : toRender = this.renderEmptyFlow();
return (
<SideBar group={ this.state.group } nom={ this.state.nom } navigator={ this.props.navigator }>
<ScrollView
contentContainerStyle={ flowSheet.scrollContainer }
refreshControl= {
<RefreshControl
refreshing={ this.state.refresh }
onRefresh={ this.retrieveFlow.bind(this) }
tintColor="#00FF00"
title="Chargement..."
titleColor="#FFFFFF"
colors={['#000000', '#FFFFFF', '#F44336']}
progressBackgroundColor="#FFFFFF" />
}>
{ toRender }
</ScrollView>
</SideBar>
);
}
}
|
tools/render.js | fmarcos83/mdocs | /**
* React Static Boilerplate
* https://github.com/koistya/react-static-boilerplate
* Copyright (c) Konstantin Tarkus (@koistya) | MIT license
*/
import glob from 'glob';
import { join, dirname } from 'path';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Html from '../components/Html';
import task from './lib/task';
import fs from './lib/fs';
const DEBUG = !process.argv.includes('release');
function getPages() {
return new Promise((resolve, reject) => {
glob('**/*.js', { cwd: join(__dirname, '../pages') }, (err, files) => {
if (err) {
reject(err);
} else {
const result = files.map(file => {
let path = '/' + file.substr(0, file.lastIndexOf('.'));
if (path === '/index') {
path = '/';
} else if (path.endsWith('/index')) {
path = path.substr(0, path.lastIndexOf('/index'));
}
return { path, file };
});
resolve(result);
}
});
});
}
async function renderPage(page, component) {
const data = {
body: ReactDOM.renderToString(component),
};
const file = join(__dirname, '../build', page.file.substr(0, page.file.lastIndexOf('.')) + '.html');
const html = '<!doctype html>\n' + ReactDOM.renderToStaticMarkup(<Html debug={DEBUG} {...data} />);
await fs.mkdir(dirname(file));
await fs.writeFile(file, html);
}
export default task(async function render() {
const pages = await getPages();
const { route } = require('../build/app.node');
for (const page of pages) {
await route(page.path, renderPage.bind(undefined, page));
}
});
|
src/Button.js | apisandipas/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
import ButtonInput from './ButtonInput';
const Button = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
block: React.PropTypes.bool,
navItem: React.PropTypes.bool,
navDropdown: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType,
href: React.PropTypes.string,
target: React.PropTypes.string,
/**
* Defines HTML button type Attribute
* @type {("button"|"reset"|"submit")}
* @defaultValue 'button'
*/
type: React.PropTypes.oneOf(ButtonInput.types)
},
getDefaultProps() {
return {
active: false,
block: false,
bsClass: 'button',
bsStyle: 'default',
disabled: false,
navItem: false,
navDropdown: false
};
},
render() {
let classes = this.props.navDropdown ? {} : this.getBsClassSet();
let renderFuncName;
classes = {
active: this.props.active,
'btn-block': this.props.block,
...classes
};
if (this.props.navItem) {
return this.renderNavItem(classes);
}
renderFuncName = this.props.href || this.props.target || this.props.navDropdown ?
'renderAnchor' : 'renderButton';
return this[renderFuncName](classes);
},
renderAnchor(classes) {
let Component = this.props.componentClass || 'a';
let href = this.props.href || '#';
classes.disabled = this.props.disabled;
return (
<Component
{...this.props}
href={href}
className={classNames(this.props.className, classes)}
role="button">
{this.props.children}
</Component>
);
},
renderButton(classes) {
let Component = this.props.componentClass || 'button';
return (
<Component
{...this.props}
type={this.props.type || 'button'}
className={classNames(this.props.className, classes)}>
{this.props.children}
</Component>
);
},
renderNavItem(classes) {
let liClasses = {
active: this.props.active
};
return (
<li className={classNames(liClasses)}>
{this.renderAnchor(classes)}
</li>
);
}
});
export default Button;
|
src/components/PostLIst.js | rhostem/blog | import Link from 'gatsby-link'
import React from 'react'
import { wordWrap } from 'polished'
import { media } from '../styles'
import styled from 'styled-components'
import { setHeightLimitAndEllipsis } from '../styles/mixin/setHeightLimit'
import format from 'date-fns/format'
import { getBodyHeight } from '../utils/getBodyHeight'
import { getPostRoute } from '../utils/routeResolver'
import * as R from 'ramda'
import throttle from 'utils/throttle'
export const PostListWrap = styled.div`
width: 100%;
margin: 2.8rem auto;
`
const PostLink = styled(Link)`
display: block;
border-radius: 2px;
padding-bottom: 0.7rem;
margin: 2.8rem 0;
&:first-child {
margin-top: 0;
}
`
const PostTitle = styled.h2`
${wordWrap('default')};
font-weight: 700;
line-height: 1.4;
margin: 0;
font-size: 1.2rem;
${media.OVER_MOBILE} {
font-size: 1.6rem;
}
`
const PostSubTitle = styled.h3`
font-size: 0.9rem;
line-height: 1.4;
font-weight: 400;
margin: 0.5rem 0;
color: var(--text);
${setHeightLimitAndEllipsis({
line: 2,
})};
`
const Info = styled.div`
display: block;
margin: 0.5rem 0;
font-size: 0.8rem;
font-weight: 400;
color: var(--text);
`
const MainImage = styled.div`
width: 200px;
`
export const PostListItem = ({
key,
path,
title,
subTitle,
date,
timeToRead,
}) => {
return (
<article key={key}>
<PostLink to={path}>
<PostTitle>{title}</PostTitle>
{subTitle && <PostSubTitle>{subTitle}</PostSubTitle>}
<Info>
{format(new Date(date), 'YYYY.MM.DD')} · {timeToRead} min to
read
</Info>
</PostLink>
</article>
)
}
type Props = {
isInfiniteScroll: boolean,
postEdges: Array<{
node: {
id: string,
timeToRead: number,
frontmatter: {
path: string,
title: string,
subTitle: string,
date: string,
},
},
}>,
}
type State = {}
class PostList extends React.Component<Props, State> {
static defaultProps = {
isInfiniteScroll: false,
postEdges: [],
}
pageSize = 10
get postEdgesInView() {
return R.slice(0, this.state.pageNum * this.pageSize, this.props.postEdges)
}
get lastPage() {
return Math.ceil(this.props.postEdges.length / this.pageSize)
}
constructor(props) {
super(props)
this.state = {
pageNum: 1,
}
}
componentDidMount() {
if (this.props.isInfiniteScroll) {
window.addEventListener('scroll', this.loadMorePost)
this.loadMorePost()
}
}
componentWillUnmount() {
if (this.props.isInfiniteScroll) {
window.removeEventListener('scroll', this.loadMorePost)
}
}
loadMorePost = throttle(300, e => {
const innerHeight = window.innerHeight
const bodyHeight = getBodyHeight()
const maximumScrollY = bodyHeight - innerHeight
const scrollY = window.scrollY
const isNextPageRequired =
maximumScrollY - scrollY < 200 && this.state.pageNum < this.lastPage
if (isNextPageRequired) {
this.setState({ pageNum: R.inc(this.state.pageNum) })
}
})
render() {
return (
<PostListWrap>
{this.postEdgesInView.map(({ node }) => {
const { frontmatter, timeToRead } = node
return (
<PostListItem
key={node.id}
path={getPostRoute(
frontmatter.path || frontmatter.title.replace(/\s/g, '_')
)}
title={frontmatter.title}
subTitle={frontmatter.subTitle}
date={frontmatter.date}
timeToRead={timeToRead}
/>
)
})}
</PostListWrap>
)
}
}
export default PostList
|
src/EventCell.js | manishksmd/react-scheduler-smartdata | import PropTypes from 'prop-types';
import React from 'react';
import cn from 'classnames';
import dates from './utils/dates';
import { accessor, elementType } from './utils/propTypes';
import { accessor as get } from './utils/accessors';
import Img from './img/doctor.png';
import AppointmentBox from './AppointmentBox';
let propTypes = {
event: PropTypes.object.isRequired,
slotStart: PropTypes.instanceOf(Date),
slotEnd: PropTypes.instanceOf(Date),
selected: PropTypes.bool,
eventPropGetter: PropTypes.func,
titleAccessor: accessor,
// @Appointment field info declaration
patientNameAccessor: accessor,
clinicianImageAccessor: accessor,
clinicianNameAccessor: accessor,
appointmentTypeAccessor: accessor,
appointmentTimeAccessor: accessor,
appointmentAddressAccessor: accessor,
coPayAccessor: accessor,
soapNoteTitleAccessor: accessor,
setProfileTitleAccessor: accessor,
staffsAccessor: accessor,
isRecurrenceAccessor: accessor,
isRecurrenceEditAccessor: accessor,
isEditAccessor: accessor,
isDeleteAccessor: accessor,
isCancelAccessor: accessor,
isUnCancelAccessor: accessor,
isApproveAccessor: accessor,
cancellationReasonAccessor: accessor,
isAppointmentRenderedAccessor: accessor,
isVideoCallAccessor: accessor,
isAppoinmentCancelledAccessor: accessor,
practitionerNameAccessor: accessor,
allDayAccessor: accessor,
startAccessor: accessor,
endAccessor: accessor,
eventComponent: elementType,
eventWrapperComponent: elementType.isRequired,
onSelect: PropTypes.func
}
class EventCell extends React.Component {
constructor(props) {
super(props);
this.hoverDialogActions = this.hoverDialogActions.bind(this);
}
render() {
let {
className
, event
, selected
, eventPropGetter
, startAccessor
, endAccessor
, titleAccessor
, isAppointmentRenderedAccessor
, isVideoCallAccessor
, isAppoinmentCancelledAccessor
, isRecurrenceAccessor
, slotStart
, slotEnd
, eventComponent: Event
, eventWrapperComponent: EventWrapper
, ...props } = this.props;
let title = get(event, titleAccessor)
, isRecurrence = get(event, isRecurrenceAccessor)
, isAppointmentRendered = get(event, isAppointmentRenderedAccessor)
, isVideoCall = get(event, isVideoCallAccessor)
, isAppoinmentCancelled = get(event, isAppoinmentCancelledAccessor)
, end = get(event, endAccessor)
, start = get(event, startAccessor)
, isAllDay = get(event, props.allDayAccessor)
, continuesPrior = dates.lt(start, slotStart, 'day')
, continuesAfter = dates.gt(end, slotEnd, 'day')
if (eventPropGetter)
var { style, className: xClassName } = eventPropGetter(event, start, end, selected);
return (
<EventWrapper event={event} isRow={true} isMonthView={true}>
<div
style={{...props.style, ...style}}
className={cn('rbc-event', className, xClassName, {
'rbc-selected': selected,
'rbc-event-allday': isAllDay || dates.diff(start, dates.ceil(end, 'day'), 'day') > 1,
'rbc-event-continues-prior': continuesPrior,
'rbc-event-continues-after': continuesAfter
})}
// onClick={(e) => onSelect(event, e)}
>
<div className='rbc-event-content'>
<ul className="quickview">
{isRecurrence === true ? <li><i className="fa fa-repeat" aria-hidden="true"></i></li> : ''}
{isAppointmentRendered ? <li><i className="fa fa-check-circle-o" aria-hidden="true"></i></li> : ''}
{isVideoCall ? <li><i className="fa fa-video-camera" aria-hidden="true"></i></li> : ''}
{isAppoinmentCancelled ? <li><i className="fa fa-ban" aria-hidden="true"></i></li> : ''}
</ul>
{ Event
? <Event event={event} title={title}/>
: title
}
<AppointmentBox
{...this.props}
popupClassName="appointment_box month_box"
hoverDialogActions={this.hoverDialogActions}
/>
</div>
</div>
</EventWrapper>
);
}
hoverDialogActions(event, e, action) {
e.preventDefault();
event.action = action;
this.props.onSelect(event, e);
}
}
EventCell.propTypes = propTypes;
export default EventCell
|
src/data-fields/checkbox-data-field.js | apconic/aos-forms | import React, { Component } from 'react';
import Checkbox from 'material-ui/Checkbox';
import PropTypes from 'prop-types';
export default class CheckboxDataField extends Component {
static propTypes = {
labelText: PropTypes.string,
onChange: PropTypes.func,
value: PropTypes.bool,
name: PropTypes.string,
checkedIcon: PropTypes.element,
disabled: PropTypes.bool,
iconStyle: PropTypes.object,
inputStyle: PropTypes.object,
labelPosition: PropTypes.string,
labelStyle: PropTypes.object,
style: PropTypes.object,
uncheckedIcon: PropTypes.element,
valueLink: PropTypes.object,
};
onCheck = (event, checked) => {
const { onChange, name } = this.props;
onChange(name, checked);
}
render() {
const {
labelText,
value,
name,
checkedIcon,
disabled,
iconStyle,
inputStyle,
labelPosition,
labelStyle,
style,
uncheckedIcon,
valueLink,
} = this.props;
return (
<Checkbox
label={labelText}
checked={value}
name={name}
checkedIcon={checkedIcon}
disabled={disabled}
iconStyle={iconStyle}
inputStyle={inputStyle}
labelPosition={labelPosition}
labelStyle={labelStyle}
onCheck={this.onCheck}
style={style}
uncheckedIcon={uncheckedIcon}
valueLink={valueLink}
/>
);
}
}
|
js/Details.js | Rehten/React-Project | import React from 'react'
const {shape, string} = React.PropTypes
import Header from './Header'
const Details = React.createClass({
propTypes: {
show: shape({
title: string,
year: string,
poster: string,
trailer: string,
description: string
})
},
render () {
const {title, year, poster, trailer, description} = this.props.show
return (
<div className="details">
<Header />
<section>
<h1>{title}</h1>
<h2>({year})</h2>
<img src={'/public/img/posters/' + poster} />
<p>{description}</p>
</section>
<div>
<iframe src={'https://www.youtube-nocookie.com/embed/' + trailer + '?rel=0&controls=0&showinfo=0'} frameBorder={0}
allowFullScreen />
</div>
</div>
)
}
})
export default Details
|
stories/Mention/CustomMentionEditor/index.js | dagopert/draft-js-plugins | import React, { Component } from 'react';
import { EditorState } from 'draft-js';
import Editor from 'draft-js-plugins-editor';
import createMentionPlugin, { defaultSuggestionsFilter } from 'draft-js-mention-plugin';
import editorStyles from './editorStyles.css';
import mentionsStyles from './mentionsStyles.css';
import mentions from './mentions';
const positionSuggestions = ({ state, props }) => {
let transform;
let transition;
if (state.isActive && props.suggestions.size > 0) {
transform = 'scaleY(1)';
transition = 'all 0.25s cubic-bezier(.3,1.2,.2,1)';
} else if (state.isActive) {
transform = 'scaleY(0)';
transition = 'all 0.25s cubic-bezier(.3,1,.2,1)';
}
return {
transform,
transition,
};
};
const mentionPlugin = createMentionPlugin({
mentions,
entityMutability: 'IMMUTABLE',
theme: mentionsStyles,
positionSuggestions,
mentionPrefix: '@',
});
const { MentionSuggestions } = mentionPlugin;
const plugins = [mentionPlugin];
const Entry = (props) => {
const {
mention,
theme,
searchValue, // eslint-disable-line no-unused-vars
...parentProps
} = props;
return (
<div {...parentProps}>
<div className={theme.mentionSuggestionsEntryContainer}>
<div className={theme.mentionSuggestionsEntryContainerLeft}>
<img
src={mention.get('avatar')}
className={theme.mentionSuggestionsEntryAvatar}
role="presentation"
/>
</div>
<div className={theme.mentionSuggestionsEntryContainerRight}>
<div className={theme.mentionSuggestionsEntryText}>
{mention.get('name')}
</div>
<div className={theme.mentionSuggestionsEntryTitle}>
{mention.get('title')}
</div>
</div>
</div>
</div>
);
};
export default class CustomMentionEditor extends Component {
state = {
editorState: EditorState.createEmpty(),
suggestions: mentions,
};
onChange = (editorState) => {
this.setState({
editorState,
});
};
onSearchChange = ({ value }) => {
this.setState({
suggestions: defaultSuggestionsFilter(value, mentions),
});
};
focus = () => {
this.editor.focus();
};
render() {
return (
<div className={editorStyles.editor} onClick={this.focus}>
<Editor
editorState={this.state.editorState}
onChange={this.onChange}
plugins={plugins}
ref={(element) => { this.editor = element; }}
/>
<MentionSuggestions
onSearchChange={this.onSearchChange}
suggestions={this.state.suggestions}
entryComponent={Entry}
/>
</div>
);
}
}
|
src/parser/shared/modules/spells/bfa/essences/NullDynamo.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS/index';
import SpellLink from 'common/SpellLink';
import STATISTIC_CATEGORY from 'interface/others/STATISTIC_CATEGORY';
import ItemStatistic from 'interface/statistics/ItemStatistic';
import StatisticGroup from 'interface/statistics/StatisticGroup';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import Abilities from 'parser/core/modules/Abilities';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import ItemDamageDone from 'interface/ItemDamageDone';
import ItemHealingDone from 'interface/ItemHealingDone';
import { TooltipElement } from 'common/Tooltip';
const DH_BUFF = 1.05;
// Null Dynamo --- Tank essence, minor absorbs magic damage, major is
// on-use (on-gcd ANGERY) magic absorb. R3 grants damage based on
// absorbed amount.
//
// R2 Minor: https://www.warcraftlogs.com/reports/MfTWJ38BA1XmQdCq/#fight=59&source=25
// R3 Major: https://www.warcraftlogs.com/reports/j2LCk4gxBMVDHKnJ/#fight=1&source=11
export default class NullDynamo extends Analyzer {
static dependencies = {
abilities: Abilities,
at: AbilityTracker,
};
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasEssence(SPELLS.NULL_DYNAMO.traitId);
if (!this.active) {
return;
}
const rank = this.selectedCombatant.essenceRank(SPELLS.NULL_DYNAMO.traitId);
this.hasMajor = this.selectedCombatant.hasMajor(SPELLS.NULL_DYNAMO.traitId);
if(this.hasMajor) {
this.abilities.add({
spell: SPELLS.NULL_DYNAMO,
category: Abilities.SPELL_CATEGORIES.ITEMS,
cooldown: (rank === 1) ? 180 : 135,
gcd: {
base: 1500,
},
castEfficiency: {
suggestion: true,
recommendedEfficiency: 0.8,
},
});
this.addEventListener(Events.absorbed.by(SELECTED_PLAYER).spell(SPELLS.NULL_DYNAMO), this._majorShield);
}
if (rank === 3) {
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(SPELLS.NULL_DYNAMO_DAMAGE), this._minorDamage);
}
this.addEventListener(Events.absorbed.by(SELECTED_PLAYER).spell(SPELLS.NULL_DYNAMO_SHIELD_MINOR), this._minorShield);
}
_totalDamage = 0;
_totalMinorAbsorbs = 0;
_totalMajorAbsorbs = 0;
_hypotheticalMinorDamage = 0;
_hypotheticalMajorDamage = 0;
_minorDamage(event) {
this._totalDamage += event.amount + (event.absorbed || 0);
}
_minorShield(event) {
this._totalMinorAbsorbs += event.amount;
this._hypotheticalMinorDamage += DH_BUFF * event.amount;
}
_majorShield(event) {
this._totalMajorAbsorbs += event.amount;
this._hypotheticalMajorDamage += DH_BUFF * event.amount;
}
get _hypotheticalDamage() {
return this._hypotheticalMajorDamage + this._hypotheticalMinorDamage;
}
// fraction of damage to attribute to major
get _damageSplit() {
return this._totalMajorAbsorbs / (this._totalMinorAbsorbs + this._totalMajorAbsorbs);
}
statistic() {
const rank = this.selectedCombatant.essenceRank(SPELLS.NULL_DYNAMO.traitId);
if (rank === 3 && Math.abs((this._totalDamage - this._hypotheticalDamage) / this._totalDamage) > 0.05) {
// more than 5% error on hypothetical damage, warn
this.warn("Null Dynamo damage estimate is way off", this._totalDamage, this._hypotheticalDamage);
}
let minorDamage;
let majorDamage;
if (rank === 3) {
minorDamage = <ItemDamageDone amount={this._totalDamage * (1 - this._damageSplit)} />;
majorDamage = <ItemDamageDone amount={this._totalDamage * this._damageSplit} />;
} else {
minorDamage = (
<>
<TooltipElement content={"No actual damage done. This estimates the amount it would deal at Rank 3."}>
<ItemDamageDone amount={this._hypotheticalMinorDamage} />
</TooltipElement>
</>
);
majorDamage = (
<>
<TooltipElement content={"No actual damage done. This estimates the amount it would deal at Rank 3."}>
<ItemDamageDone amount={this._hypotheticalMajorDamage} />
</TooltipElement>
</>
);
}
return (
<StatisticGroup category={STATISTIC_CATEGORY.ITEMS}>
<ItemStatistic ultrawide>
<div className="pad">
<label><SpellLink id={SPELLS.NULL_DYNAMO.id} /> - Minor Rank {rank}</label>
<div className="value">
<ItemHealingDone amount={this._totalMinorAbsorbs} /><br />
{minorDamage}
</div>
</div>
</ItemStatistic>
{this.hasMajor && (
<ItemStatistic ultrawide>
<div className="pad">
<label><SpellLink id={SPELLS.NULL_DYNAMO.id} /> - Major Rank {rank}</label>
<div className="value">
<ItemHealingDone amount={this._totalMajorAbsorbs} /><br />
{majorDamage}
</div>
</div>
</ItemStatistic>
)}
</StatisticGroup>
);
}
}
|
opentech/static_src/src/app/src/components/Select/index.js | OpenTechFund/WebApp | import React from 'react'
import PropTypes from 'prop-types'
const Option = ({ value, display }) => {
return <option value={value}>{display || value}</option>
}
Option.propTypes = {
value: PropTypes.string.isRequired,
display: PropTypes.string,
}
const Select = ({ options, onChange }) => {
const items = [{ display: '---', value: '' }].concat(options)
return (
<select onChange={evt => onChange(evt.target.value)} >
{items.map(({ value, display }) =>
<Option key={value} value={value} display={display} />
)}
</select>
)
}
Select.propTypes = {
options: PropTypes.arrayOf(PropTypes.shape({
value: PropTypes.string.isRequired,
display: PropTypes.string,
})),
onChange: PropTypes.func,
}
export default Select
|
pages/components/site-menu.js | LlamaSantos/crackerbox | "use strict";
import React from 'react';
import Personas from './personas';
export default React.createClass({
render() {
return (
<div className='ui vertical sidebar menu left uncover visible'>
<div className='ui segment'>Users</div>
<div className='item'>
<Personas />
</div>
</div>
);
}
})
|
example/src/index.js | ldstudio-ca/react-pdfjs-mobile | import React from 'react';
import ReactDOM from 'react-dom';
import App from 'react-pdfjs-mobile';
let root = document.getElementById('root');
ReactDOM.render(<App
url="http://www.ducatiusa.com/cms-web/upl/img/Redline_Magazine_2015/Redline_Magazine_2_ENG.pdf"
onClose={ () => {
ReactDOM.unmountComponentAtNode(root);
} } />, root);
|
Product/Websites/Feature/src/index.js | BerndWessels/terraform | /**
* Manapaho (https://github.com/Manapaho/)
*
* Copyright © 2016 Manapaho. 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 ReactDOM from 'react-dom';
/**
* Import the bootstrap theme.
*/
import theme from '../bootstrap/theme';
/**
* Import the icomoon icon font.
*/
import icomoon from '../public/assets/fonts/icomoon/style.css';
/**
* Import styles.
*/
import styles from './styles';
/**
* The entry component of the application.
*/
class Index extends React.Component {
// Initialize the component.
constructor(props) {
super(props);
}
// Declare the properties this component expects.
static defaultProps = {};
// Declare the context properties this component exposes.
static childContextTypes = {};
// Set the context property values this component exposes.
getChildContext() {
return {};
}
// Invoked once, both on the client and server, immediately before the initial rendering occurs.
// If you call setState within this method,
// render() will see the updated state and will be executed only once despite the state change.
componentWillMount() {
}
// Invoked once, only on the client (not on the server), immediately after the initial rendering occurs.
// At this point in the lifecycle, you can access any refs to your children
// (e.g., to access the underlying DOM representation).
// The componentDidMount() method of child components is invoked before that of parent components.
// If you want to integrate with other JavaScript frameworks, set timers using setTimeout or setInterval,
// or send AJAX requests, perform those operations in this method.
componentDidMount() {
}
// Invoked when a component is receiving new props. This method is not called for the initial render.
// Use this as an opportunity to react to a prop transition before render() is called
// by updating the state using this.setState(). The old props can be accessed via this.props.
// Calling this.setState() within this function will not trigger an additional render.
componentWillReceiveProps(nextProps) {
}
// Invoked before rendering when new props or state are being received.
// This method is not called for the initial render or when forceUpdate is used.
// Use this as an opportunity to return false
// when you're certain that the transition to the new props and state will not require a component update.
// If shouldComponentUpdate returns false, then render() will be completely skipped until the next state change.
// In addition, componentWillUpdate and componentDidUpdate will not be called.
shouldComponentUpdate(nextProps, nextState) {
// This is the root container which propagates all updates and renders the whole application.
return true;
}
// Invoked immediately before rendering when new props or state are being received.
// This method is not called for the initial render.
// Use this as an opportunity to perform preparation before an update occurs.
// You cannot use this.setState() in this method.
// If you need to update state in response to a prop change, use componentWillReceiveProps instead.
componentWillUpdate(nextProps, nextState) {
}
// Invoked immediately after the component's updates are flushed to the DOM.
// This method is not called for the initial render.
// Use this as an opportunity to operate on the DOM when the component has been updated.
componentDidUpdate(prevProps, prevState) {
}
// Invoked immediately before a component is unmounted from the DOM.
// Perform any necessary cleanup in this method,
// such as invalidating timers or cleaning up any DOM elements that were created in componentDidMount.
componentWillUnmount() {
}
// Render the component.
render() {
return (
<div>
<h1>Wessels Product</h1>
<span>See, there is an icon:</span>
<span className="icon-calendar"></span>
</div>
);
}
}
/**
* (Re-)Render the application.
*/
function render() {
// Set the index styles.
document.getElementById('index').className = styles.root;
// Render the application.
ReactDOM.render(
<Index/>,
document.getElementById('index')
);
}
// Render the application.
render();
|
client/modules/App/__tests__/Components/Header.spec.js | SwanCourses/example-app | import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import { FormattedMessage } from 'react-intl';
import { Header } from '../../components/Header/Header';
import { intl } from '../../../../util/react-intl-test-helper';
const intlProp = { ...intl, enabledLanguages: ['en', 'fr'] };
test('renders the header properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.truthy(wrapper.find('Link').first().containsMatchingElement(<FormattedMessage id="siteTitle" />));
t.is(wrapper.find('a').length, 1);
});
test('doesn\'t add post in pages other than home', t => {
const router = {
isActive: sinon.stub().returns(false),
};
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={() => {}} />,
{
context: {
router,
intl,
},
}
);
t.is(wrapper.find('a').length, 0);
});
test('toggleAddPost called properly', t => {
const router = {
isActive: sinon.stub().returns(true),
};
const toggleAddPost = sinon.spy();
const wrapper = shallow(
<Header switchLanguage={() => {}} intl={intlProp} toggleAddPost={toggleAddPost} />,
{
context: {
router,
intl,
},
}
);
wrapper.find('a').first().simulate('click');
t.truthy(toggleAddPost.calledOnce);
});
|
node_modules/react-icons/md/history.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const MdHistory = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m20 13.4h2.5v7l5.9 3.5-1.3 2-7.1-4.3v-8.2z m1.6-8.4q6.2 0 10.6 4.4t4.4 10.6-4.4 10.6-10.6 4.4-10.5-4.4l2.3-2.4q3.5 3.4 8.2 3.4 4.9 0 8.3-3.4t3.5-8.2-3.5-8.2-8.3-3.4-8.2 3.4-3.4 8.2h5l-6.7 6.7-0.2-0.2-6.5-6.5h5q0-6.2 4.5-10.6t10.5-4.4z"/></g>
</Icon>
)
export default MdHistory
|
app/containers/Root.js | luismreis/bootstrap-starter-template-react | import 'babel-core/polyfill';
import React, { Component } from 'react';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import { Provider } from 'react-redux';
import { Router, Route } from 'react-router';
import configureStore from '../store/configureStore';
import App from './App';
import HomePage from './HomePage';
import AboutPage from './AboutPage';
import ContactPage from './ContactPage';
const history = createBrowserHistory();
const store = configureStore();
export default class Root extends Component {
render() {
return (
<Provider store={store}>
{() =>
<Router history={history}>
<Route component={App}>
<Route path="/" component={HomePage}/>
<Route path="/about" component={AboutPage}/>
<Route path="/contact" component={ContactPage}/>
</Route>
</Router>
}
</Provider>
);
}
}
|
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-forms-v3-timepicker.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import {BaseMixin, ElementaryMixin, Tools} from './../common/common.js';
import Backdrop from './../bricks/backdrop.js';
import TextInput from './internal/text-input.js';
import Time from './time.js';
import TextInputMixin from './mixins/text-input-mixin.js'
import './timepicker.less';
const FORMAT_AM = 'AM';
const FORMAT_PM = 'PM';
const FORMAT_12 = '12';
const FORMAT_24 = '24';
export const Timepicker = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin,
TextInputMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Forms.Timepicker',
classNames: {
main: 'uu5-forms-timepicker',
open: 'uu5-forms-timepicker-open',
menu: 'uu5-forms-input-menu'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
value: React.PropTypes.string,
buttonHidden: React.PropTypes.bool,
glyphiconOpened: React.PropTypes.string,
glyphiconClosed: React.PropTypes.string,
format: React.PropTypes.oneOf([FORMAT_24, FORMAT_12]),
nanMessage: React.PropTypes.any
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps() {
return {
value: '',
isButtonHidden: false,
glyphiconOpened: 'uu-glyphicon-clock',
glyphiconClosed: 'uu-glyphicon-clock',
format: FORMAT_24,
nanMessage: 'Please insert a valid date.'
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
getInitialState() {
return {
opened: false
};
},
componentWillMount(){
if (typeof this.props.onValidate === 'function') {
let result = this._isValidTimeResult({ value: this._formatTime(this._parseTime(this.state.value), true) });
if (result) {
if (typeof result === 'object') {
if (result.feedback) {
this.setFeedback(result.feedback, result.message, this._formatTime(this._parseTime(result.value), true));
} else {
this._validateOnChange({
value: this._formatTime(this._parseTime(this.state.value), true),
event: null,
component: this
})
}
}
}
} else {
this.setState({ value: this._formatTime(this._parseTime(this.state.value), true) });
}
return this;
},
componentWillReceiveProps(nextProps) {
if (nextProps.controlled) {
let result = this._isValidTimeResult({ value: nextProps.value });
if (result) {
if (typeof result === 'object') {
if (result.feedback) {
this.setFeedback(result.feedback, result.message, result.value);
} else {
this.setFeedback(nextProps.feedback, nextProps.message, nextProps.value)
}
}
}
}
return this;
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
open (setStateCallback) {
this.setState({ opened: true }, setStateCallback);
return this;
},
toggle (setStateCallback) {
this.setState((state) => ({ opened: !state.opened }), setStateCallback);
return this;
},
//@@viewOff:interface
//@@viewOn:overridingMethods
setValue_(value, setStateCallback){
if (this._checkRequired({ value: value })) {
if (typeof this.props.onValidate === 'function') {
this._validateOnChange({ value: value, event: null, component: this });
} else {
this.props.required ? this.setSuccess(null, value, setStateCallback) : this.setInitial(null, value, setStateCallback);
}
}
return this;
},
isOpened_(){
return this.state.opened;
},
close_ (setStateCallback) {
this.setState({ opened: false }, setStateCallback);
return this;
},
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_onChange(e){
let opt = { value: e.target.value, event: e, component: this };
if (opt.value === '' || this._parseTime(opt.value)) {
if (!this.isDisabled() && !this.isReadOnly()) {
if (typeof this.props.onChange === 'function') {
this.props.onChange(opt);
} else {
if (this.props.validateOnChange) {
this._validateOnChange(opt);
} else {
if (opt.value === '') {
this.setState({ value: opt.value });
} else if (this._checkRequired({ value: opt.value })) {
opt.required = this.props.required;
let result = this.getChangeFeedback(opt);
if (!result.value ||
(this.props.format === FORMAT_12 && result.value.match(/^\d{1,2}:?\d{0,2} ?[PpAa]?\.?[Mm]?\.?$/)) ||
(this.props.format === FORMAT_24 && result.value.match(/^\d{1,2}:?\d{0,2}$/))) {
this.setFeedback(result.feedback, result.message, result.value);
}
}
}
}
}
}
return this;
},
_onBlur(e){
let opt = { value: e.target.value, event: e, component: this };
if (typeof this.props.onBlur === 'function') {
this.props.onBlur(opt);
} else {
if (this._checkRequired({ value: opt.value }) && !this.props.validateOnChange) {
opt.required = this.props.required;
let blurResult = this.getBlurFeedback(opt);
let result = this._isValidTimeResult(blurResult);
this.setFeedback(result.feedback, result.message, this._formatTime(this._parseTime(blurResult.value), true));
}
}
return this;
},
_isValidTimeResult(opt){
let result = opt;
let time = this._parseTime(opt.value);
if (!time && opt.value) {
result.feedback = 'error';
result.message = this.props.nanMessage;
}
return result;
},
_validateOnChange(opt){
let result = typeof this.props.onValidate === 'function' ? this.props.onValidate(opt) : null;
if (result) {
if (typeof result === 'object') {
if (result.feedback) {
this.setFeedback(result.feedback, result.message, result.value);
} else {
this.setState({ value: opt.value });
}
} else {
this.showError('validateError', null, { context: { event: e, func: this.props.onValidate, result: result } });
}
} else if (this.props.required && this.state.value) {
this.setSuccess(null, this.state.value)
}
return this;
},
_getFeedbackIcon(){
let icon = this.props.required ? this.props.successGlyphicon : null;
switch (this.getFeedback()) {
case 'success':
icon = this.props.successGlyphicon;
break;
case 'warning':
icon = this.props.warningGlyphicon;
break;
case 'error':
icon = this.props.errorGlyphicon;
break;
}
return icon;
},
_onTimeChange(opt) {
this.setState({ value: this._formatTime(opt.value, true) });
return this;
},
_getTimeProps(value) {
return {
className: this.getClassName().menu,
value: value,
ref_: this._refCalendar,
hidden: !this.isOpened(),
onChange: this._onTimeChange,
format: this.props.format,
controlled: true
};
},
_formatTime(value, fill0) {
let time = '';
if (value) {
if (fill0) {
time = Tools.rjust(value.hours, 2, '0') + ':' + Tools.rjust(value.minutes, 2, '0');
} else {
time = value.hours + ':' + value.minutes;
}
if (this.props.format === FORMAT_12) {
time += ' ' + (value.dayPart || FORMAT_AM);
}
}
return time;
},
_parseTime (stringTime) {
stringTime = stringTime.trim();
let value = null;
if (typeof stringTime === 'string' && stringTime !== '') {
value = {
hours: 0,
minutes: 0
};
if (stringTime.indexOf(':') !== -1) {
let dateArray = stringTime.split(':');
value.hours = parseInt(dateArray[0].trim()) || 0;
value.minutes = parseInt(dateArray[1].trim()) || 0;
} else {
value.hours = parseInt(stringTime) || 0;
}
if (value.hours < 0 || value.hours > 23 || value.minutes < 0 || value.minutes > 59) {
value = null;
} else if (this.props.format === FORMAT_12) {
if (value.hours > 12) {
value.hours -= 12;
} else if (value.hours == 0) {
value.hours = 12;
}
if (stringTime.match(/[Pp]\.?([Mm]\.?)?/)) {
value.dayPart = FORMAT_PM;
} else {
value.dayPart = FORMAT_AM;
}
}
}
return value;
},
_getTextInputAttrs() {
let props = {};
if (!this.isReadOnly() && !this.isDisabled()) {
props.onClick = () => {
this.open();
};
}
return props;
},
_getMainAttrs(){
let attrs = this._getInputAttrs();
if (this.isOpened()) {
attrs.className += ' ' + this.getClassName().open;
}
return attrs;
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render() {
let inputId = this.getId() + '-input';
let buttons = !this.isReadOnly() && !this.props.buttonHidden ?
[{
glyphicon: this.isOpened() ? this.props.glyphiconOpened : this.props.glyphiconClosed,
disabled: this.isDisabled(),
onClick: () => this.toggle(),
pressed: this.isOpened(),
colorSchema: 'default'
}]
: null;
let value = this._parseTime(this.state.value);
return (
<div {...this._getMainAttrs()}>
{this.getLabel(inputId)}
{this.getInputWrapper([
<TextInput
id={inputId}
name={this.props.name || inputId}
value={this.state.value || ''}
placeholder={this.props.placeholder}
type='text'
onChange={this._onChange}
onBlur={this._onBlur}
onFocus={this.onFocus}
mainAttrs={this._getTextInputAttrs() || this.props.inputAttrs}
disabled={this.isDisabled() || this.isLoading()}
readonly={this.isReadOnly()}
glyphicon={this._getFeedbackIcon()}
loading={this.isLoading()}
/>,
<Time {...this._getTimeProps(value)} />,
<Backdrop {...this._getBackdropProps()} />
],
buttons)}
</div>
);
}
//@@viewOn:render
});
export default Timepicker;
|
docs/app/Examples/elements/Rail/Types/RailDividingExample.js | jamiehill/stardust | import React from 'react'
import { Image, Grid, Rail, Segment } from 'stardust'
const RailDividingExample = () => (
<Grid columns={3}>
<Grid.Column>
<Segment>
<Image src='http://semantic-ui.com/images/wireframe/paragraph.png' />
<Rail dividing position='left'>
<Segment>Left Rail Content</Segment>
</Rail>
<Rail dividing position='right'>
<Segment>Right Rail Content</Segment>
</Rail>
</Segment>
</Grid.Column>
</Grid>
)
export default RailDividingExample
|
dispatch/static/manager/src/js/pages/Events/NewEventPage.js | ubyssey/dispatch | import React from 'react'
import EventEditor from '../../components/EventEditor'
export default function NewEventPage(props) {
return (
<EventEditor
isNew={true}
goBack={props.router.goBack} />
)
}
|
src/components/Filter/index.js | KNETIC-KRPF/KNETIC-CLIENT | import React, { Component } from 'react';
import Knob from '../Knob';
import './Filter.css';
class Filter extends Component {
render() {
return(
<div>
<h4>FILTER</h4>
<div className="filter-grid">
<div className="controller">
<select className="" value={this.props.patch.filter.type} onChange={(event) => this.props.sendDispatch('filter', 'type', event.target.value)}>
<option value="lowpass">Low Pass</option>
<option value="highpass">High Pass</option>
<option value="bandpass">Band Pass</option>
<option value="allpass">All Pass</option>
<option value="lowshelf">Low Shelf</option>
<option value="highshelf">High Shelf</option>
<option value="notch">Notch</option>
</select>
</div>
<div className="controller">
<Knob
id="filterFreq"
patchState={this.props.patch.filter.frequency}
sendDispatch={this.props.sendDispatch}
type="filter"
property="frequency"
min={20}
max={19999}
step={100}
/>
<label htmlFor="frequency">FREQUENCY</label>
</div>
<div className="controller">
<Knob
id="filterQ"
patchState={this.props.patch.filter.Q}
sendDispatch={this.props.sendDispatch}
type="filter"
property="Q"
min={0}
max={20}
step={1}
/>
<label htmlFor="q-factor">Q</label>
</div>
<div className="controller">
<Knob
id="filterGain"
patchState={this.props.patch.filter.gain}
sendDispatch={this.props.sendDispatch}
type="filter"
property="gain"
min={0}
max={100}
step={10}
/>
<label htmlFor="filter-gain">GAIN</label>
</div>
</div>
<hr />
</div>
);
}
}
export default Filter;
|
src/Tabs/TabIndicator.js | dsslimshaddy/material-ui | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import withStyles from '../styles/withStyles';
import { capitalizeFirstLetter } from '../utils/helpers';
export const styles = (theme: Object) => ({
root: {
position: 'relative',
height: 2,
marginTop: -2,
transition: theme.transitions.create(),
willChange: 'left, width',
},
colorAccent: {
backgroundColor: theme.palette.accent.A200,
},
colorPrimary: {
backgroundColor: theme.palette.primary[500],
},
});
/**
* @ignore - internal component.
*/
function TabIndicator(props) {
const { classes, className: classNameProp, color, style: styleProp } = props;
const colorPredefined = ['primary', 'accent'].indexOf(color) !== -1;
const className = classNames(
classes.root,
{
[classes[`color${capitalizeFirstLetter(color)}`]]: colorPredefined,
},
classNameProp,
);
const style = colorPredefined
? styleProp
: {
...styleProp,
backgroundColor: color,
};
return <div className={className} style={style} />;
}
TabIndicator.propTypes = {
/**
* Useful to extend the style applied to components.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
* The color of the tab indicator.
*/
color: PropTypes.oneOfType([PropTypes.oneOf(['accent', 'primary']), PropTypes.string]).isRequired,
/**
* @ignore
* The style of the root element.
*/
style: PropTypes.shape({
left: PropTypes.number,
width: PropTypes.number,
}).isRequired,
};
export default withStyles(styles, { name: 'MuiTabIndicator' })(TabIndicator);
|
examples/auth-with-shared-root/components/Dashboard.js | djkirby/react-router | import React from 'react'
import auth from '../utils/auth'
const Dashboard = React.createClass({
render() {
const token = auth.getToken()
return (
<div>
<h1>Dashboard</h1>
<p>You made it!</p>
<p>{token}</p>
{this.props.children}
</div>
)
}
})
module.exports = Dashboard
|
src/svg-icons/places/free-breakfast.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesFreeBreakfast = (props) => (
<SvgIcon {...props}>
<path d="M20 3H4v10c0 2.21 1.79 4 4 4h6c2.21 0 4-1.79 4-4v-3h2c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zm0 5h-2V5h2v3zM4 19h16v2H4z"/>
</SvgIcon>
);
PlacesFreeBreakfast = pure(PlacesFreeBreakfast);
PlacesFreeBreakfast.displayName = 'PlacesFreeBreakfast';
PlacesFreeBreakfast.muiName = 'SvgIcon';
export default PlacesFreeBreakfast;
|
src/lib/plugins/battery.js | edoren/hyperline | import React from 'react'
import Component from 'hyper/component'
import BatteryIcon from './battery/battery-icon'
import leftPad from 'left-pad'
export default class Battery extends Component {
static displayName() {
return 'Battery plugin'
}
constructor(props) {
super(props)
this.state = {
charging: false,
percentage: '--'
}
this.batteryEvents = [ 'chargingchange', 'chargingtimechange', 'dischargingtimechange', 'levelchange' ]
this.handleEvent = this.handleEvent.bind(this)
}
setBatteryStatus(battery) {
this.setState({
charging: battery.charging,
percentage: Math.floor(battery.level * 100)
})
}
handleEvent(event) {
this.setBatteryStatus(event.target)
}
componentDidMount() {
navigator.getBattery().then(battery => {
this.setBatteryStatus(battery)
this.batteryEvents.forEach(event => {
battery.addEventListener(event, this.handleEvent, false)
})
})
}
componentWillUnmount() {
navigator.getBattery().then(battery => {
this.batteryEvents.forEach(event => {
battery.removeEventListener(event, this.handleEvent)
})
})
}
styles() {
return {
wrapper: {
display: 'flex',
alignItems: 'center'
}
}
}
template(css) {
const { charging, percentage } = this.state
return (
<div className={css('wrapper')}>
<BatteryIcon charging={charging} percentage={percentage} /> {leftPad(percentage, 2, 0)}%
</div>
)
}
}
|
project/react-ant/src/containers/AssetMgmt/Add/index.js | FFF-team/generator-earth | import React from 'react'
import moment from 'moment'
import { DatePicker, Button, Form, Input, Col } from 'antd'
import BaseContainer from 'ROOT_SOURCE/base/BaseContainer'
import request from 'ROOT_SOURCE/utils/request'
import { mapMoment } from 'ROOT_SOURCE/utils/fieldFormatter'
import Rules from 'ROOT_SOURCE/utils/validateRules'
const FormItem = Form.Item
export default Form.create()(class extends BaseContainer {
/**
* 提交表单
*/
submitForm = (e) => {
e && e.preventDefault()
const { form } = this.props
form.validateFieldsAndScroll(async (err, values) => {
if (err) {
return;
}
// 提交表单最好新一个事务,不受其他事务影响
await this.sleep()
let _formData = { ...form.getFieldsValue() }
// _formData里的一些值需要适配
_formData = mapMoment(_formData, 'YYYY-MM-DD HH:mm:ss')
// action
await request.post('/asset/addAsset', _formData)
// 提交后返回list页
this.props.history.push(`${this.context.CONTAINER_ROUTE_PREFIX}/list`)
})
}
render() {
let { form } = this.props
let { getFieldDecorator } = form
return (
<div className="ui-background">
<Form layout="inline" onSubmit={this.submitForm}>
<FormItem label="资产方名称">
{getFieldDecorator('assetName', {
rules: [{ required: true }]
})(<Input/>)}
</FormItem>
<FormItem label="签约主体">
{getFieldDecorator('contract', {
rules: [{ required: true }]
})(<Input/>)}
</FormItem>
<FormItem label="签约时间">
{getFieldDecorator('contractDate', {
rules: [{ type: 'object', required: true }]
})(<DatePicker showTime format='YYYY年MM月DD HH:mm:ss' style={{ width: '100%' }}/>)}
</FormItem>
<FormItem label="联系人">
{getFieldDecorator('contacts')(<Input/>)}
</FormItem>
<FormItem label="联系电话" hasFeedback>
{getFieldDecorator('contactsPhone', {
rules: [{ pattern: Rules.phone, message: '无效' }]
})(<Input maxLength="11"/>)}
</FormItem>
<FormItem>
<Button type="primary" htmlType="submit"> 提交 </Button>
</FormItem>
<FormItem>
<Button type="primary" onClick={e => window.history.back()}> 取消/返回 </Button>
</FormItem>
</Form>
</div>
)
}
})
|
src/js/components/icons/base/Diamond.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-diamond`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'diamond');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M6,3 L18,3 L22,9 L12,21 L2,9 L6,3 Z M2,9 L22,9 M11,3 L7,9 L12,20 M13,3 L17,9 L12,20"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Diamond';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
app/containers/Home/index.js | Jasonlucas724/SWASH | /*
*
* Home
*
*/
import React from 'react';
import Helmet from 'react-helmet';
import Responsive from 'react-responsive';
import {Link} from 'react-router';
import Menu from 'material-ui/svg-icons/navigation/Menu';
import TextField from 'material-ui/TextField';
import Person from 'material-ui/svg-icons/social/person';
import Description from 'material-ui/svg-icons/action/description';
import AccountBalance from 'material-ui/svg-icons/action/account-balance';
import ContentCopy from 'material-ui/svg-icons/content/content-copy';
import Assignment from 'material-ui/svg-icons/action/assignment';
import AttachMoney from 'material-ui/svg-icons/editor/attach-money';
import CheckCircle from 'material-ui/svg-icons/action/check-circle';
import Toggle from 'material-ui/Toggle';
import FlatButton from "material-ui/FlatButton";
import RaisedButton from 'material-ui/RaisedButton';
export default class Home extends React.PureComponent {
constructor(props){
super(props);
this.state={
email:"",
}
}
handleEmail = (event) => {
this.setState({
email:event.target.value
})
}
storeContact = () => {
var data = new FormData ();
data.append("email", this.state.email);
fetch("http://localhost:8000/api/storeEmail",{
method:"post",
body:data
})
.then(function(response){
return response.json();
})
.then(function(json){
if(json.success){
this.setState({
email:""
})
alert(json.success);
}
else if (json.error){
alert(json.error);
}
}.bind(this))
}
render() {
const headerStyle={
display:"flex",
minHeight:"100vh",
background:"url(http://h4z.it/Image/644192_betten-40145.jpg)",
backgroundSize:"cover",
width:"100%",
flexDirection:"column",
justifyContent:"center",
alignItems:"center"
}
const navBar={
display:"flex",
flexDirection:"row",
width:"100%",
height:"100px",
justifyContent:"space-between",
position:"fixed",
top:"0",
background:"rgba(0,0,0,.5)",
}
const imageStyle={
display:"flex",
flexDirection:"row",
}
const logoStyle={
width:"200px",
height:"50px",
marginTop:"30px",
color:"#ffffff",
background:"url(http://h4z.it/Image/80b7ee_swash.png)",
backgroundSize:"100%,",
marginLeft:"50px",
fontSize:"30px",
}
const navLink={
textDecoration:"0",
display:"flex",
flexDirection:"column",
padding:"15px",
marginTop:"25px",
color:"#000000",
fontSize:"18px",
fontFamily:"Roboto, sans serif",
color:"#ffffff"
}
const boxOne={
display:"flex",
flexDirection:"column",
width:"300px",
height:"300px",
color:"#F28705",
margin:"0 auto",
}
const heading={
display:"flex",
fontSize:"25px",
justifyContent:"center",
color:"#ffffff",
fontFamily:"Roboto, sans serif",
padding:"10px",
marginTop:"20px"
}
const parStyle1={
display:"flex",
fontSize:"15px",
justifyContent:"center",
color:"#ffffff",
fontFamily:"Roboto, sans serif",
padding:"10px",
marginTop:"20px"
}
const paragraphStyle={
display:"flex",
fontSize:"25px",
justifyContent:"row",
color:"#ffffff",
fontFamily:"Roboto, sans serif",
textAlign:"center",
width:"300px",
height:"100px"
}
const mainStyle={
display:"flex",
flexDirection:"row",
justifyContent:"space-around",
alignItems:"space-around",
marginTop:"100px",
}
const boxTwo={
width:"300px",
height:"300px",
background:"url(http://www.yak-tribe.com/wp-content/uploads/fishingbuddy.jpg)",
backgroundSize:"100% 100%"
}
const boxThree={
width:"300px",
height:"300px",
background:"url(https://s-media-cache-ak0.pinimg.com/736x/46/ae/cc/46aecccb2f911c8bf1b6d2a96c6ee9b2.jpg)",
}
const boxFour={
width:"300px",
height:"300px",
background:"url(https://images-na.ssl-images-amazon.com/images/I/61Bk-hUKwcL._SY300_.jpg)",
}
const h1={
fontFamily:"Roboto, sans serif",
fontSize:"80px",
alignSelf:"center"
}
const article={
fontSize:"20px",
fontFamily:"Railway"
}
const h2={
display:"flex",
flexDirection:"row",
width:"100%",
height:"300px",
justifyContent:"space-around",
fontFamily:"Roboto, sans serif",
fontSize:"20px",
}
const container={
display:"flex",
flexDirection:"row",
width:"100%",
height:"500px",
justifyContent:"space-around",
justifyContent:"center",
backgroundImage: "url(http://awesomwallpaper.com/img1/C69A882C5159/beautiful-argentina-landscape.jpg)",
backgroundAttachment: "fixed",
backgroundPosition: "center",
backgroundRepeat: "no-repeat",
backgroundSize:"cover",
}
const imageStyle2={
backgroundSize:"cover",
width:"600px",
height:"400px",
marginTop:"25px"
}
const article2={
fontSize:"30px",
fontFamily:"Railway",
color:"#ffffff",
alignSelf:"center"
}
const menu={
display:"flex",
flexDirection:"column",
width:"100%",
height:"300px",
justifyContent:"space-around",
fontFamily:"Roboto, sans serif",
fontSize:"20px",
}
const menuStyle={
fontSize:"10px",
fontFamily:"Railway"
}
const footer={
display:"flex",
flexDirection:"column",
width:"100%",
height:"200px",
}
const link={
background:"#ffffff",
backgroundSize:"cover",
width:"100%",
height:"800px"
}
const copyright={
display:"flex",
justifyContent:"center",
fontSize:"20px",
marginTop:"100px"
}
const containerTwo={
display:"flex",
flexDirection:"column",
justifyContent:"center",
width:"500px",
height:"500px",
alignItems:"center"
}
const wrapper={
}
const buttonStyle={
margin:"12"
}
const button={
margin:"12"
}
return (
<div>
<Helmet title="Home" meta={[ { name: 'description', content: 'Description of Home' }]}/>
<div>
<Responsive minDeviceWidth={1024}>
<div>
<header style={headerStyle}>
<nav style={navBar}>
<div style={logoStyle}></div>
<Link to="/" style={navLink}>Home</Link>
<Link to="/Products" style={navLink}>Products</Link>
<Link to="/About" style={navLink}>About</Link>
<Link to="/Contact" style={navLink}>Contact</Link>
</nav>
<div style={boxOne}>
<div style={heading}></div>
<div style={parStyle1}></div>
<h1 style={h1}>Swashbuckler:</h1>
<p style={paragraphStyle}>Swaggering or daring soldier or adventurer.</p>
</div>
</header>
</div>
<div style={mainStyle}>
<div style={boxTwo}></div>
<div style={boxThree}></div>
<div style={boxFour}></div>
</div>
<div style={h2}>
<h1 style={article} to="/Fishing Gear">Fishing Gear</h1>
<h1 style={article} to="/Camping Gear">Camping Gear</h1>
<h1 style={article} to="/Hiking Gear">Hiking Gear</h1>
</div>
<div style={container}>
<div style={article2}>A company's best advantage should be a quality product offered at the right price.</div>
<div style={imageStyle2}></div>
<div style={article2}></div>
</div>
<div style={containerTwo}>
<TextField style={wrapper}
hintText="Email"
/><br />
<br />
<TextField style={wrapper}
hintText="Password"
/><br />
<TextField style={wrapper}
id="Forgot Username Or Password"
defaultValue="Forgot Username Or Password"
/><br />
<TextField style={wrapper}
hintText="Send By Email"
floatingLabelText="Forgot User ID"
/><br />
<TextField style={wrapper}
defaultValue="Send By Email"
floatingLabelText="Forgot Password"
/><br />
<div style={button}>
<RaisedButton label="Log In" primary={true} style={buttonStyle} />
</div>
</div>
<footer style={footer}>
<div style={link}>
<h1 style={copyright}>© 2017 Web Design by Jason Lucas & Johnathan Marshall </h1>
</div>
</footer>
</Responsive>
</div>
<Responsive maxDeviceWidth={1023}>
<div>
<header style={headerStyle}>
<nav style={navBar}>
<div style={logoStyle}></div>
<Link to="/" style={navLink}>Home</Link>
<Link to="/Products" style={navLink}>Products</Link>
<Link to="/About" style={navLink}>About</Link>
<Link to="/Contact" style={navLink}>Contact</Link>
</nav>
<div style={boxOne}>
<div style={heading}></div>
<div style={parStyle1}></div>
<h1 style={h1}>Swashbuckler:</h1>
<p style={paragraphStyle}>Swaggering or daring soldier or adventurer.</p>
</div>
</header>
</div>
<div style={mainStyle}>
<div style={boxTwo}></div>
<div style={boxThree}></div>
<div style={boxFour}></div>
</div>
<div style={h2}>
<Link style={article} to="/Tents">Tents</Link>
<Link style={article} to="/LedLanterns">Led Lanterns</Link>
<Link style={article} to="/Hammicks">Hammicks</Link>
</div>
<div style={container}>
<div style={article2}>A company's best advantage should be a quality product offered at the right price.</div>
<div style={imageStyle2}></div>
<div style={article2}></div>
</div>
<div style={containerTwo}>
<TextField style={wrapper}
hintText="Email"
/><br />
<br />
<TextField style={wrapper}
hintText="Password"
/><br />
<TextField style={wrapper}
id="Forgot Username Or Password"
defaultValue="Forgot Username Or Password"
/><br />
<TextField style={wrapper}
hintText="Send By Email"
floatingLabelText="Forgot User ID"
/><br />
<TextField style={wrapper}
defaultValue="Send By Email"
floatingLabelText="Forgot Password"
/><br />
</div>
<div style={button}>
<RaisedButton label="Log In" primary={true} style={buttonStyle} />
</div>
<footer style={footer}>
<div style={link}>
<h1 style={copyright}>© 2017 Web Design by Jason Lucas & Johnathan Marshall</h1>
</div>
</footer>
</Responsive>
</div>
);
}
}
|
js/components/tab/tabOne.js | HomelandGvarim/FE-Phone | import React, { Component } from 'react';
import { Container, Content, Card, CardItem, Text, View, Body } from 'native-base';
import styles from './styles';
export default class TabOne extends Component {
// eslint-disable-line
render() {
// eslint-disable-line
return (
<Content padder>
<Card>
<CardItem>
<Body>
<Text>NativeBase is open source and free.</Text>
</Body>
</CardItem>
<CardItem>
<Body>
<Text>Platform specific codebase for components.</Text>
</Body>
</CardItem>
<CardItem>
<Body>
<Text>Any native third-party libraries can be included.</Text>
</Body>
</CardItem>
</Card>
</Content>
);
}
}
|
src/js/components/Sky.js | alexoviedo999/vr-carpet-ride | import {Entity} from 'aframe-react';
import React from 'react';
export default props => (
<Entity geometry={{primitive: 'sphere', radius: 5000}}
material={{color: "#73CFF0", shader: 'flat', src: '#sky'}}
scale="1 1 -1"/>
);
|
src/components/GalleryBrick/index.js | line64/landricks-components | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import FontAwesome from 'react-fontawesome';
import { GenericBrick } from '../../';
import styles from './styles';
class GalleryBrick extends Component {
constructor(props){
super(props);
this.state = { currentPage: 1 }
}
calculatePages(){
let { children, itemsPerPage } = this.props;
let pages = parseInt(children.length / itemsPerPage);
return (children.length % itemsPerPage > 0) ? pages + 1 : pages;
}
renderItem(item, key, style){
return item
}
renderPageOfItems(items, style){
if (!items) return null;
let initial = (this.state.currentPage - 1) * this.props.itemsPerPage;
let boxItems = items.slice(initial, initial + this.props.itemsPerPage );
return boxItems.map((item, key) => this.renderItem(item, key, style));
}
renderPrevBtn(style){
let styleCustom = {};
if(this.state.currentPage === 1) styleCustom = { opacity : '0', pointerEvents : 'none' }
return (
<a
style={{ ...style.controls, ...styleCustom }}
onClick={ () => this.setState({ currentPage : this.state.currentPage - 1 }) } >
<FontAwesome name="chevron-left" />
</a>
)
}
renderNextBtn(style){
let styleCustom = {};
if(this.state.currentPage >= this.calculatePages()) styleCustom = { opacity : '0', pointerEvents : 'none' }
return (
<a
style={{ ...style.controls, ...styleCustom }}
onClick={ () => this.setState({ currentPage : this.state.currentPage + 1 }) } >
<FontAwesome name="chevron-right" />
</a>
)
}
renderIndicators(style){
let {currentPage} = this.state;
let count = [...Array(this.calculatePages()).keys()];
if(this.calculatePages() < 2) return null;
return count.map((item) =>{
return (
<FontAwesome
style={ style.indicator }
onClick={ ()=> this.setState({ currentPage : item + 1 }) }
name={ (currentPage === item + 1) ? 'circle' : 'circle-o' }
/>
)
});
}
render() {
let style = styles(this.props);
let items = this.props.children;
return (
<GenericBrick {...this.props} contentStyle={ style.container }>
<div style={ style.wrapper }>
{ this.renderPrevBtn(style) }
<div style={ style.pageWrapper } >
{ this.renderPageOfItems(items, style) }
</div>
{ this.renderNextBtn(style) }
</div>
{ this.renderIndicators(style) }
</GenericBrick>
);
}
}
GalleryBrick.propTypes = {
title : PropTypes.string,
subtitle : PropTypes.string,
items: PropTypes.array,
itemsPerPage : PropTypes.number
};
export default GalleryBrick;
|
boilerplates/demo/src/components/TitleBar/index.js | flicker85/react-redux-saga-cli | import React from 'react';
import styles from './index.less';
export default function({ title }) {
return (
<div className={ styles.normal }>{ title }</div>
);
} |
docs/app/Examples/elements/Header/Types/HeaderExampleSubheaders.js | clemensw/stardust | import React from 'react'
import { Header } from 'semantic-ui-react'
const HeaderExampleSubheaders = () => (
<div>
<Header sub>Price</Header>
<span>$10.99</span>
</div>
)
export default HeaderExampleSubheaders
|
src/client/assets/js/nodes/processors/uibuilder/features/canvas/components/svg/Line.js | me-box/databox-sdk | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import {camelise} from 'nodes/processors/uibuilder/utils';
import { actionCreators as canvasActions, selector } from '../..';
import { connect } from 'react-redux';
@connect(selector, (dispatch) => {
return{
actions: bindActionCreators(canvasActions, dispatch)
}
})
export default class Line extends Component {
constructor(props){
super(props);
this._templateSelected = this._templateSelected.bind(this);
}
shouldComponentUpdate(nextProps, nextState){
return this.props.template != nextProps.template || this.props.selected != nextProps.selected;
}
render(){
const {id, template} = this.props;
const {x1,x2,y1,y2,style} = template;
const _style = camelise(style);
return <line onClick={this._templateSelected} x1={x1} x2={x2} y1={y1} y2={y2} style={_style}/>
}
_templateSelected(){
const {nid, id, template} = this.props;
this.props.actions.templateSelected(nid,{path:[id], type:template.type});
}
} |
src/js/components/icons/base/Optimize.js | odedre/grommet-final | /**
* @description Optimize SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M2,22 L6,22 L6,18 L2,18 L2,22 Z M22,2 L12,12 M22,10 L22,2 L14,2 M22,13 L18,13 L18,22 L22,22 L22,13 Z M10,22 L14,22 L14,16 L10,16 L10,22 Z"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-optimize`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'optimize');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M2,22 L6,22 L6,18 L2,18 L2,22 Z M22,2 L12,12 M22,10 L22,2 L14,2 M22,13 L18,13 L18,22 L22,22 L22,13 Z M10,22 L14,22 L14,16 L10,16 L10,22 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Optimize';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/mobile/components/App/Overlays.js | welovekpop/uwave-web-welovekpop.club | import React from 'react';
import PropTypes from 'prop-types';
import CSSTransition from 'react-transition-group/CSSTransition';
import TransitionGroup from 'react-transition-group/TransitionGroup';
const Overlays = ({ children, active }) => {
let view;
if (Array.isArray(children)) {
view = children.find(child => child.key === active);
} else if (children.key === active) {
view = children;
}
if (view) {
// Pass on the `view.key` so that overlays are mounted and unmounted correctly
// when switching from one to the other.
view = (
<CSSTransition
key={view.key}
mountOnEnter
unmountOnExit
classNames="Overlay"
timeout={180}
>
{view}
</CSSTransition>
);
}
return (
<TransitionGroup className="Overlays">
{view}
</TransitionGroup>
);
};
Overlays.propTypes = {
children: PropTypes.node,
active: PropTypes.string,
};
export default Overlays;
|
docs/src/app/components/pages/components/List/ExampleMessages.js | owencm/material-ui | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import Subheader from 'material-ui/Subheader';
import Avatar from 'material-ui/Avatar';
import {grey400, darkBlack, lightBlack} from 'material-ui/styles/colors';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
const iconButtonElement = (
<IconButton
touch={true}
tooltip="more"
tooltipPosition="bottom-left"
>
<MoreVertIcon color={grey400} />
</IconButton>
);
const rightIconMenu = (
<IconMenu iconButtonElement={iconButtonElement}>
<MenuItem>Reply</MenuItem>
<MenuItem>Forward</MenuItem>
<MenuItem>Delete</MenuItem>
</IconMenu>
);
const ListExampleMessages = () => (
<div>
<MobileTearSheet>
<List>
<Subheader>Today</Subheader>
<ListItem
leftAvatar={<Avatar src="images/ok-128.jpg" />}
primaryText="Brunch this weekend?"
secondaryText={
<p>
<span style={{color: darkBlack}}>Brendan Lim</span> --
I'll be in your neighborhood doing errands this weekend. Do you want to grab brunch?
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/kolage-128.jpg" />}
primaryText={
<p>Summer BBQ <span style={{color: lightBlack}}>4</span></p>
}
secondaryText={
<p>
<span style={{color: darkBlack}}>to me, Scott, Jennifer</span> --
Wish I could come, but I'm out of town this weekend.
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/uxceo-128.jpg" />}
primaryText="Oui oui"
secondaryText={
<p>
<span style={{color: darkBlack}}>Grace Ng</span> --
Do you have Paris recommendations? Have you ever been?
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/kerem-128.jpg" />}
primaryText="Birdthday gift"
secondaryText={
<p>
<span style={{color: darkBlack}}>Kerem Suer</span> --
Do you have any ideas what we can get Heidi for her birthday? How about a pony?
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />}
primaryText="Recipe to try"
secondaryText={
<p>
<span style={{color: darkBlack}}>Raquel Parrado</span> --
We should eat this: grated squash. Corn and tomatillo tacos.
</p>
}
secondaryTextLines={2}
/>
</List>
</MobileTearSheet>
<MobileTearSheet>
<List>
<Subheader>Today</Subheader>
<ListItem
leftAvatar={<Avatar src="images/ok-128.jpg" />}
rightIconButton={rightIconMenu}
primaryText="Brendan Lim"
secondaryText={
<p>
<span style={{color: darkBlack}}>Brunch this weekend?</span><br />
I'll be in your neighborhood doing errands this weekend. Do you want to grab brunch?
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/kolage-128.jpg" />}
rightIconButton={rightIconMenu}
primaryText="me, Scott, Jennifer"
secondaryText={
<p>
<span style={{color: darkBlack}}>Summer BBQ</span><br />
Wish I could come, but I'm out of town this weekend.
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/uxceo-128.jpg" />}
rightIconButton={rightIconMenu}
primaryText="Grace Ng"
secondaryText={
<p>
<span style={{color: darkBlack}}>Oui oui</span><br />
Do you have any Paris recs? Have you ever been?
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/kerem-128.jpg" />}
rightIconButton={rightIconMenu}
primaryText="Kerem Suer"
secondaryText={
<p>
<span style={{color: darkBlack}}>Birthday gift</span><br />
Do you have any ideas what we can get Heidi for her birthday? How about a pony?
</p>
}
secondaryTextLines={2}
/>
<Divider inset={true} />
<ListItem
leftAvatar={<Avatar src="images/raquelromanp-128.jpg" />}
rightIconButton={rightIconMenu}
primaryText="Raquel Parrado"
secondaryText={
<p>
<span style={{color: darkBlack}}>Recipe to try</span><br />
We should eat this: grated squash. Corn and tomatillo tacos.
</p>
}
secondaryTextLines={2}
/>
</List>
</MobileTearSheet>
</div>
);
export default ListExampleMessages;
|
app/javascript/mastodon/features/search/index.js | imas/mastodon | import React from 'react';
import SearchContainer from 'mastodon/features/compose/containers/search_container';
import SearchResultsContainer from 'mastodon/features/compose/containers/search_results_container';
const Search = () => (
<div className='column search-page'>
<SearchContainer />
<div className='drawer__pager'>
<div className='drawer__inner darker'>
<SearchResultsContainer />
</div>
</div>
</div>
);
export default Search;
|
examples/App/components/Doc.js | tangjinzhou/biz-mobile-ui | import React from 'react'
import marked from 'marked'
import highlight from 'highlight.js'
import request from '../request';
import { Link, History } from 'react-router'
marked.setOptions({
renderer: new marked.Renderer(),
gfm: true,
tables: true,
breaks: false,
pedantic: false,
sanitize: false,
smartLists: true,
smartypants: false,
highlight: function (code) {
return highlight.highlightAuto(code).value;
}
});
export default class Doc extends React.Component {
constructor(props) {
super(props);
this.state = {doc: ''};
this._isMounted = true;
}
componentWillMount(){
this.getDoc(this.props.name);
}
componentWillReceiveProps(nextProps){
if(nextProps.name !== this.props.name){
this.getDoc(nextProps.name);
}
}
componentWillUnmount(){
this._isMounted = false;
}
getDoc = (name)=>{
let that = this;
request('/getDoc', {
name: name
}).then(function(res){
if(that._isMounted) {
that.setState({doc: res.data.doc});
}
})
}
render() {
const {style} = this.props;
return (
<div style={style}>
<div className="markdown" dangerouslySetInnerHTML={{__html: marked(this.state.doc)}} />
</div>
)
}
} |
src/mui/layout/Layout.js | matteolc/admin-on-rest | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import autoprefixer from 'material-ui/utils/autoprefixer';
import CircularProgress from 'material-ui/CircularProgress';
import withWidth from 'material-ui/utils/withWidth';
import compose from 'recompose/compose';
import injectTapEventPlugin from 'react-tap-event-plugin';
import AdminRoutes from '../../AdminRoutes';
import AppBar from './AppBar';
import Sidebar from './Sidebar';
import Notification from './Notification';
import defaultTheme from '../defaultTheme';
import { setSidebarVisibility as setSidebarVisibilityAction } from '../../actions';
injectTapEventPlugin();
const styles = {
wrapper: {
// Avoid IE bug with Flexbox, see #467
display: 'flex',
flexDirection: 'column',
},
main: {
display: 'flex',
flexDirection: 'column',
minHeight: '100vh',
},
body: {
backgroundColor: '#edecec',
display: 'flex',
flex: 1,
overflowY: 'hidden',
overflowX: 'scroll',
},
bodySmall: {
backgroundColor: '#fff',
},
content: {
flex: 1,
padding: '2em',
},
contentSmall: {
flex: 1,
paddingTop: '3em',
},
loader: {
position: 'absolute',
top: 0,
right: 0,
margin: 16,
zIndex: 1200,
},
};
const prefixedStyles = {};
class Layout extends Component {
componentWillMount() {
if (this.props.width !== 1) {
this.props.setSidebarVisibility(true);
}
}
render() {
const {
authClient,
customRoutes,
dashboard,
isLoading,
menu,
resources,
theme,
title,
width,
} = this.props;
const muiTheme = getMuiTheme(theme);
if (!prefixedStyles.main) {
// do this once because user agent never changes
const prefix = autoprefixer(muiTheme);
prefixedStyles.wrapper = prefix(styles.wrapper);
prefixedStyles.main = prefix(styles.main);
prefixedStyles.body = prefix(styles.body);
prefixedStyles.bodySmall = prefix(styles.bodySmall);
prefixedStyles.content = prefix(styles.content);
prefixedStyles.contentSmall = prefix(styles.contentSmall);
}
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div style={prefixedStyles.wrapper}>
<div style={prefixedStyles.main}>
{ width !== 1 && <AppBar title={title} />}
<div className="body" style={width === 1 ? prefixedStyles.bodySmall : prefixedStyles.body}>
<div style={width === 1 ? prefixedStyles.contentSmall : prefixedStyles.content}>
<AdminRoutes
customRoutes={customRoutes}
resources={resources}
authClient={authClient}
dashboard={dashboard}
/>
</div>
<Sidebar theme={theme}>
{menu}
</Sidebar>
</div>
<Notification />
{isLoading && <CircularProgress
className="app-loader"
color="#fff"
size={width === 1 ? 20 : 30}
thickness={2}
style={styles.loader}
/>}
</div>
</div>
</MuiThemeProvider>
);
}
}
Layout.propTypes = {
authClient: PropTypes.func,
customRoutes: PropTypes.array,
dashboard: PropTypes.oneOfType([PropTypes.func, PropTypes.string]),
isLoading: PropTypes.bool.isRequired,
menu: PropTypes.element,
resources: PropTypes.array,
setSidebarVisibility: PropTypes.func.isRequired,
title: PropTypes.node.isRequired,
theme: PropTypes.object.isRequired,
width: PropTypes.number,
};
Layout.defaultProps = {
theme: defaultTheme,
};
function mapStateToProps(state) {
return {
isLoading: state.admin.loading > 0,
};
}
const enhance = compose(
connect(mapStateToProps, {
setSidebarVisibility: setSidebarVisibilityAction,
}),
withWidth(),
);
export default enhance(Layout);
|
views/blocks/QuestPhotos/QuestPhotosContainer.js | dimastark/team5 | import React from 'react';
import QuestPhotos from './QuestPhotos';
import sender from './../Sender/Sender';
import PhotoSender from './PhotoSender';
const QuestPhotosWithSending = sender(QuestPhotos);
export default class QuestPhotosContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
photos: []
};
this.handlePhotosChange = this.handlePhotosChange.bind(this);
this.handleAnswered = this.handleAnswered.bind(this);
}
handlePhotosChange({data}) {
this.setState({
photos: data
});
}
handleAnswered(position, data) {
this.setState(prevState => {
const photos = prevState.photos.slice();
photos[position] = Object.assign({}, photos[position]);
photos[position].status = data.status;
photos[position].title = data.title;
photos[position].description = data.description;
return {photos};
});
if (data.finished) {
this.props.handleFinished();
}
}
render() {
return (
<QuestPhotosWithSending
{...this.state} {...this.props}
getSendOptions={PhotoSender.getPhotos}
onSuccesfulEnd={this.handlePhotosChange}
handleAnswered={this.handleAnswered}
/>
);
}
}
|
docs/src/app/components/pages/components/RaisedButton/ExampleSimple.js | kasra-co/material-ui | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
const style = {
margin: 12,
};
const RaisedButtonExampleSimple = () => (
<div>
<RaisedButton label="Default" style={style} />
<RaisedButton label="Primary" primary={true} style={style} />
<RaisedButton label="Secondary" secondary={true} style={style} />
<RaisedButton label="Disabled" disabled={true} style={style} />
<br />
<br />
<RaisedButton label="Full width" fullWidth={true} />
</div>
);
export default RaisedButtonExampleSimple;
|
app/javascript/mastodon/features/follow_requests/components/account_authorize.js | mimumemo/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Permalink from '../../../components/permalink';
import Avatar from '../../../components/avatar';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
authorize: { id: 'follow_request.authorize', defaultMessage: 'Authorize' },
reject: { id: 'follow_request.reject', defaultMessage: 'Reject' },
});
export default @injectIntl
class AccountAuthorize extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
onAuthorize: PropTypes.func.isRequired,
onReject: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { intl, account, onAuthorize, onReject } = this.props;
const content = { __html: account.get('note_emojified') };
return (
<div className='account-authorize__wrapper'>
<div className='account-authorize'>
<Permalink href={account.get('url')} to={`/accounts/${account.get('id')}`} className='detailed-status__display-name'>
<div className='account-authorize__avatar'><Avatar account={account} size={48} /></div>
<DisplayName account={account} />
</Permalink>
<div className='account__header__content' dangerouslySetInnerHTML={content} />
</div>
<div className='account--panel'>
<div className='account--panel__button'><IconButton title={intl.formatMessage(messages.authorize)} icon='check' onClick={onAuthorize} /></div>
<div className='account--panel__button'><IconButton title={intl.formatMessage(messages.reject)} icon='times' onClick={onReject} /></div>
</div>
</div>
);
}
}
|
src/components/Map.js | Djiit/vgmapper | import React, { Component } from 'react';
import GoogleMapReact from 'google-map-react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import config from '../config';
import Form from './Form';
import * as userActions from '../actions/user';
import './Map.css';
const PlayerMarker = ({ text }) => <span className="tag is-vg"> {text} </span>;
class VainLocatorMap extends Component {
state = {
center: {lat: 48.866667, lng: 2.333333},
zoom: 10
};
componentDidMount() {
navigator.geolocation.getCurrentPosition( pos => {
this.setState({
center: {
lat: pos.coords.latitude,
lng: pos.coords.longitude
}
});
this.props.actions.setUserPosition(pos.coords.latitude, pos.coords.longitude, pos.timestamp);
})
}
// FIXME: needed?
_onChange = ({center, zoom}) => {
this.setState({
center: center,
zoom: zoom,
});
}
_onChildClick = (key, childProps) => {
const player = this.props.user.players.filter((e) => e.id === key)[0];
this.props.actions.setCurrentPlayer(player);
}
render() {
let playersMarkers = [];
if (this.props.user.players !== null) {
playersMarkers = this.props.user.players.map(p => {
if (p.attributes !== undefined) {
return (
<PlayerMarker
key={p.id}
lat={p.location[0]}
lng={p.location[1]}
text={p.attributes.name}
/>
)
}
});
}
return this.props.user.name ? (
<GoogleMapReact
bootstrapURLKeys={{key: config.GM_API_KEY}}
center={this.state.center}
zoom={this.state.zoom}
onChange={this._onChange}
onChildClick={this._onChildClick}
options={{styles: [{"stylers":[{"hue":"#ff1a00"},{"invert_lightness":true},{"saturation":-100},{"lightness":33},{"gamma":0.5}]},{"featureType":"water","elementType":"geometry","stylers":[{"color":"#2D333C"}]}]}}
>
{playersMarkers}
</GoogleMapReact>
) : (
<Form/>
);
}
}
function mapStateToProps(state, props) {
return state;
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(userActions, dispatch)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(VainLocatorMap);
|
src/components/Html.js | veskoy/ridiko | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import serialize from 'serialize-javascript';
/* eslint-disable react/no-danger */
class Html extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
description: PropTypes.string.isRequired,
styles: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string.isRequired,
cssText: PropTypes.string.isRequired,
}).isRequired),
scripts: PropTypes.arrayOf(PropTypes.string.isRequired),
app: PropTypes.object, // eslint-disable-line
children: PropTypes.string.isRequired,
};
static defaultProps = {
styles: [],
scripts: [],
};
render() {
const { title, description, styles, scripts, app, children } = this.props;
return (
<html className="no-js" lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="x-ua-compatible" content="ie=edge" />
<title>{title}</title>
<meta name="description" content={description} />
<meta name="viewport" content="width=device-width, initial-scale=1" />
{scripts.map(script => <link key={script} rel="preload" href={script} as="script" />)}
<link rel="apple-touch-icon" href="apple-touch-icon.png" />
{styles.map(style => (
<style
key={style.id}
id={style.id}
dangerouslySetInnerHTML={{ __html: style.cssText }}
/>
))}
</head>
<body>
<div id="app" dangerouslySetInnerHTML={{ __html: children }} />
<script dangerouslySetInnerHTML={{ __html: `window.App=${serialize(app)}` }} />
{scripts.map(script => <script key={script} src={script} />)}
</body>
</html>
);
}
}
export default Html;
|
site/components/Cover.js | craigklem/react-dnd | import React from 'react';
import './Cover.less';
export default class Cover {
render() {
return (
<div className="Cover">
<div className="Cover-header">
<p className="Cover-description">
Drag and Drop for React
</p>
</div>
</div>
);
}
} |
src/js/pages/GroupContentsPage.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { API_URLS, INVITATIONS_URL } from '../constants/Constants';
import TopNavBar from '../components/ui/TopNavBar';
import FullWidthButton from '../components/ui/FullWidthButton';
import EmptyMessage from '../components/ui/EmptyMessage/EmptyMessage';
import CardContentList from '../components/interests/CardContentList';
import ToolBar from '../components/ui/ToolBar';
import AuthenticatedComponent from '../components/AuthenticatedComponent';
import translate from '../i18n/Translate';
import connectToStores from '../utils/connectToStores';
import * as APIUtils from '../utils/APIUtils';
import * as UserActionCreators from '../actions/UserActionCreators';
import * as GroupActionCreators from '../actions/GroupActionCreators';
import GroupStore from '../stores/GroupStore';
import LoginStore from '../stores/LoginStore';
/**
* Requests data from server for current props.
*/
function requestData(props) {
const groupId = props.params.groupId;
GroupActionCreators.requestGroup(groupId);
GroupActionCreators.requestGroupContents(groupId);
GroupActionCreators.requestGroupMembers(groupId);
}
/**
* Retrieves state from stores for current props.
*/
function getState(props) {
const group = GroupStore.getGroup(props.params.groupId);
const contents = GroupStore.getContents(props.params.groupId);
return {
group,
contents
};
}
@AuthenticatedComponent
@translate('GroupMembersPage')
@connectToStores([GroupStore], getState)
export default class GroupContentsPage extends Component {
static propTypes = {
// Injected by React Router:
params: PropTypes.shape({
groupId: PropTypes.string.isRequired
}).isRequired,
// Injected by @AuthenticatedComponent
user: PropTypes.object,
// Injected by @translate:
strings: PropTypes.object,
// Injected by @connectToStores:
group: PropTypes.object,
members: PropTypes.array
};
static contextTypes = {
router: PropTypes.object.isRequired
};
constructor(props) {
super(props);
}
componentWillMount() {
requestData(this.props);
}
render() {
const {group, contents, strings, user} = this.props;
return (
<div className="views">
<TopNavBar leftMenuIcon={true} centerText={strings.group}/>
{group && contents ?
<ToolBar links={[
{'url': '/groups/'+group.id, 'text': 'Grupo'},
{'url': '/groups/'+group.id+'/members', 'text': 'Miembros'},
{'url': '/groups/'+group.id+'/contents', 'text': 'Intereses'}
]} activeLinkIndex={1} arrowUpLeft={'85%'}/>
: null}
<div className="view view-main">
{group && contents ?
<div>
<div className="page group-page">
<div id="page-content">
Datos de los contenidos consoleados.
</div>
<CardContentList contents={contents} userId={user.id}/>
</div>
</div>
: ''}
</div>
</div>
);
}
}
GroupContentsPage.defaultProps = {
strings: {
group: 'Group'
}
}; |
Realization/frontend/czechidm-core/src/components/advanced/IdentityRoleInfo/IdentityRoleInfo.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../basic';
import { IdentityRoleManager, IdentityContractManager, RoleManager, IdentityManager } from '../../../redux';
import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo';
import DateValue from '../DateValue/DateValue';
import EntityInfo from '../EntityInfo/EntityInfo';
const manager = new IdentityRoleManager();
const identityContractManager = new IdentityContractManager();
const roleManager = new RoleManager();
const identityManager = new IdentityManager();
/**
* Assigned role basic information (info card)
*
* @author Radek Tomiška
*/
export class IdentityRoleInfo extends AbstractEntityInfo {
getManager() {
return manager;
}
getNiceLabel() {
const _entity = this.getEntity();
const { showIdentity } = this.props;
//
return this.getManager().getNiceLabel(_entity, showIdentity);
}
_isNotLoaded(permissions) {
return permissions === undefined || permissions === null || permissions === false;
}
onEnter() {
super.onEnter();
//
const entity = this.getEntity();
if (entity && entity.identityContract) {
const _contractPermissions = identityContractManager.getPermissions(this.context.store.getState(), null, entity.identityContract);
if (this._isNotLoaded(_contractPermissions)) {
this.context.store.dispatch(identityContractManager.fetchPermissions(entity.identityContract));
}
const _rolePermissions = roleManager.getPermissions(this.context.store.getState(), null, entity.role);
if (this._isNotLoaded(_rolePermissions)) {
this.context.store.dispatch(roleManager.fetchPermissions(entity.role));
}
if (entity._embedded && entity._embedded.identityContract) {
const _identityPermissions = identityManager.getPermissions(this.context.store.getState(), null, entity._embedded.identityContract.identity);
if (this._isNotLoaded(_identityPermissions)) {
this.context.store.dispatch(identityManager.fetchPermissions(entity._embedded.identityContract.identity));
}
}
}
}
showLink() {
// TODO: assigned role modal detail should be open automatically ...
return false;
}
/**
* Get link to detail (`url`).
*
* @return {string}
*/
getLink() {
return null;
/* TODO: assigned role modal detail should be open automatically ...
const entity = this.getEntity();
if (!entity._embedded || !entity._embedded.identityContract || !entity._embedded.identityContract._embedded || !entity._embedded.identityContract._embedded.identity) {
return null;
}
//
return `/identity/${encodeURIComponent(entity._embedded.identityContract._embedded.identity.username)}/roles`;
*/
}
/**
* Returns entity icon (null by default - icon will not be rendered)
*
* @param {object} entity
*/
getEntityIcon() {
return 'component:identity-role';
}
/**
* Returns popovers title
*
* @param {object} entity
*/
getPopoverTitle() {
return this.i18n('entity.IdentityRole._type');
}
getTableChildren() {
// component are used in #getPopoverContent => skip default column resolving
return [
<Basic.Column property="label"/>,
<Basic.Column property="value"/>
];
}
/**
* Returns popover info content
*
* @param {array} table data
*/
getPopoverContent(entity) {
const content = [];
content.push(
{
label: this.i18n('entity.Identity._type'),
value: !entity._embedded || !entity._embedded.identityContract || !entity._embedded.identityContract._embedded ||
<EntityInfo
entityType="identity"
entity={ entity._embedded.identityContract._embedded.identity }
entityIdentifier={ entity._embedded.identityContract.identity }
face="link" />
},
{
label: this.i18n('entity.IdentityContract._type'),
value: (
<EntityInfo
entityType="identityContract"
entity={ entity._embedded ? entity._embedded.identityContract : null }
entityIdentifier={ entity.identityContract }
showIdentity={ !entity._embedded }
face="link" />
)
}
);
//
content.push(
{
label: this.i18n('entity.Role._type'),
value: (
<EntityInfo
entityType="role"
entity={ entity._embedded ? entity._embedded.role : null }
entityIdentifier={ entity.role }
face="link" />
)
}
);
//
content.push(
{
label: this.i18n('entity.validFrom'),
value: (<DateValue value={ entity.validFrom }/>)
},
{
label: this.i18n('entity.validTill'),
value: (<DateValue value={ entity.validTill }/>)
}
);
return content;
}
}
IdentityRoleInfo.propTypes = {
...AbstractEntityInfo.propTypes,
/**
* Selected entity - has higher priority
*/
entity: PropTypes.object,
/**
* Selected entity's id - entity will be loaded automatically
*/
entityIdentifier: PropTypes.string,
/**
* Show asigned role's identity
*/
showIdentity: PropTypes.bool,
//
_showLoading: PropTypes.bool,
_permissions: PropTypes.oneOfType([
PropTypes.bool,
PropTypes.arrayOf(PropTypes.string)
])
};
IdentityRoleInfo.defaultProps = {
...AbstractEntityInfo.defaultProps,
entity: null,
face: 'link',
_showLoading: true,
showIdentity: true
};
function select(state, component) {
return {
_entity: manager.getEntity(state, component.entityIdentifier),
_showLoading: manager.isShowLoading(state, null, component.entityIdentifier),
_permissions: manager.getPermissions(state, null, component.entityIdentifier)
};
}
export default connect(select)(IdentityRoleInfo);
|
src/svg-icons/places/all-inclusive.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesAllInclusive = (props) => (
<SvgIcon {...props}>
<path d="M18.6 6.62c-1.44 0-2.8.56-3.77 1.53L12 10.66 10.48 12h.01L7.8 14.39c-.64.64-1.49.99-2.4.99-1.87 0-3.39-1.51-3.39-3.38S3.53 8.62 5.4 8.62c.91 0 1.76.35 2.44 1.03l1.13 1 1.51-1.34L9.22 8.2C8.2 7.18 6.84 6.62 5.4 6.62 2.42 6.62 0 9.04 0 12s2.42 5.38 5.4 5.38c1.44 0 2.8-.56 3.77-1.53l2.83-2.5.01.01L13.52 12h-.01l2.69-2.39c.64-.64 1.49-.99 2.4-.99 1.87 0 3.39 1.51 3.39 3.38s-1.52 3.38-3.39 3.38c-.9 0-1.76-.35-2.44-1.03l-1.14-1.01-1.51 1.34 1.27 1.12c1.02 1.01 2.37 1.57 3.82 1.57 2.98 0 5.4-2.41 5.4-5.38s-2.42-5.37-5.4-5.37z"/>
</SvgIcon>
);
PlacesAllInclusive = pure(PlacesAllInclusive);
PlacesAllInclusive.displayName = 'PlacesAllInclusive';
PlacesAllInclusive.muiName = 'SvgIcon';
export default PlacesAllInclusive;
|
node_modules/react-select/src/Creatable.js | mannyng/ceap | import React from 'react';
import Select from './Select';
import defaultFilterOptions from './utils/defaultFilterOptions';
import defaultMenuRenderer from './utils/defaultMenuRenderer';
const Creatable = React.createClass({
displayName: 'CreatableSelect',
propTypes: {
// Child function responsible for creating the inner Select component
// This component can be used to compose HOCs (eg Creatable and Async)
// (props: Object): PropTypes.element
children: React.PropTypes.func,
// See Select.propTypes.filterOptions
filterOptions: React.PropTypes.any,
// Searches for any matching option within the set of options.
// This function prevents duplicate options from being created.
// ({ option: Object, options: Array, labelKey: string, valueKey: string }): boolean
isOptionUnique: React.PropTypes.func,
// Determines if the current input text represents a valid option.
// ({ label: string }): boolean
isValidNewOption: React.PropTypes.func,
// See Select.propTypes.menuRenderer
menuRenderer: React.PropTypes.any,
// Factory to create new option.
// ({ label: string, labelKey: string, valueKey: string }): Object
newOptionCreator: React.PropTypes.func,
// input change handler: function (inputValue) {}
onInputChange: React.PropTypes.func,
// input keyDown handler: function (event) {}
onInputKeyDown: React.PropTypes.func,
// new option click handler: function (option) {}
onNewOptionClick: React.PropTypes.func,
// See Select.propTypes.options
options: React.PropTypes.array,
// Creates prompt/placeholder option text.
// (filterText: string): string
promptTextCreator: React.PropTypes.func,
// Decides if a keyDown event (eg its `keyCode`) should result in the creation of a new option.
shouldKeyDownEventCreateNewOption: React.PropTypes.func,
},
// Default prop methods
statics: {
isOptionUnique,
isValidNewOption,
newOptionCreator,
promptTextCreator,
shouldKeyDownEventCreateNewOption
},
getDefaultProps () {
return {
filterOptions: defaultFilterOptions,
isOptionUnique,
isValidNewOption,
menuRenderer: defaultMenuRenderer,
newOptionCreator,
promptTextCreator,
shouldKeyDownEventCreateNewOption,
};
},
createNewOption () {
const {
isValidNewOption,
newOptionCreator,
onNewOptionClick,
options = [],
shouldKeyDownEventCreateNewOption
} = this.props;
if (isValidNewOption({ label: this.inputValue })) {
const option = newOptionCreator({ label: this.inputValue, labelKey: this.labelKey, valueKey: this.valueKey });
const isOptionUnique = this.isOptionUnique({ option });
// Don't add the same option twice.
if (isOptionUnique) {
if (onNewOptionClick) {
onNewOptionClick(option);
} else {
options.unshift(option);
this.select.selectValue(option);
}
}
}
},
filterOptions (...params) {
const { filterOptions, isValidNewOption, options, promptTextCreator } = this.props;
// TRICKY Check currently selected options as well.
// Don't display a create-prompt for a value that's selected.
// This covers async edge-cases where a newly-created Option isn't yet in the async-loaded array.
const excludeOptions = params[2] || [];
const filteredOptions = filterOptions(...params) || [];
if (isValidNewOption({ label: this.inputValue })) {
const { newOptionCreator } = this.props;
const option = newOptionCreator({
label: this.inputValue,
labelKey: this.labelKey,
valueKey: this.valueKey
});
// TRICKY Compare to all options (not just filtered options) in case option has already been selected).
// For multi-selects, this would remove it from the filtered list.
const isOptionUnique = this.isOptionUnique({
option,
options: excludeOptions.concat(filteredOptions)
});
if (isOptionUnique) {
const prompt = promptTextCreator(this.inputValue);
this._createPlaceholderOption = newOptionCreator({
label: prompt,
labelKey: this.labelKey,
valueKey: this.valueKey
});
filteredOptions.unshift(this._createPlaceholderOption);
}
}
return filteredOptions;
},
isOptionUnique ({
option,
options
}) {
const { isOptionUnique } = this.props;
options = options || this.select.filterOptions();
return isOptionUnique({
labelKey: this.labelKey,
option,
options,
valueKey: this.valueKey
});
},
menuRenderer (params) {
const { menuRenderer } = this.props;
return menuRenderer({
...params,
onSelect: this.onOptionSelect,
selectValue: this.onOptionSelect
});
},
onInputChange (input) {
const { onInputChange } = this.props;
if (onInputChange) {
onInputChange(input);
}
// This value may be needed in between Select mounts (when this.select is null)
this.inputValue = input;
},
onInputKeyDown (event) {
const { shouldKeyDownEventCreateNewOption, onInputKeyDown } = this.props;
const focusedOption = this.select.getFocusedOption();
if (
focusedOption &&
focusedOption === this._createPlaceholderOption &&
shouldKeyDownEventCreateNewOption({ keyCode: event.keyCode })
) {
this.createNewOption();
// Prevent decorated Select from doing anything additional with this keyDown event
event.preventDefault();
} else if (onInputKeyDown) {
onInputKeyDown(event);
}
},
onOptionSelect (option, event) {
if (option === this._createPlaceholderOption) {
this.createNewOption();
} else {
this.select.selectValue(option);
}
},
render () {
const {
newOptionCreator,
shouldKeyDownEventCreateNewOption,
...restProps
} = this.props;
let { children } = this.props;
// We can't use destructuring default values to set the children,
// because it won't apply work if `children` is null. A falsy check is
// more reliable in real world use-cases.
if (!children) {
children = defaultChildren;
}
const props = {
...restProps,
allowCreate: true,
filterOptions: this.filterOptions,
menuRenderer: this.menuRenderer,
onInputChange: this.onInputChange,
onInputKeyDown: this.onInputKeyDown,
ref: (ref) => {
this.select = ref;
// These values may be needed in between Select mounts (when this.select is null)
if (ref) {
this.labelKey = ref.props.labelKey;
this.valueKey = ref.props.valueKey;
}
}
};
return children(props);
}
});
function defaultChildren (props) {
return (
<Select {...props} />
);
};
function isOptionUnique ({ option, options, labelKey, valueKey }) {
return options
.filter((existingOption) =>
existingOption[labelKey] === option[labelKey] ||
existingOption[valueKey] === option[valueKey]
)
.length === 0;
};
function isValidNewOption ({ label }) {
return !!label;
};
function newOptionCreator ({ label, labelKey, valueKey }) {
const option = {};
option[valueKey] = label;
option[labelKey] = label;
option.className = 'Select-create-option-placeholder';
return option;
};
function promptTextCreator (label) {
return `Create option "${label}"`;
}
function shouldKeyDownEventCreateNewOption ({ keyCode }) {
switch (keyCode) {
case 9: // TAB
case 13: // ENTER
case 188: // COMMA
return true;
}
return false;
};
module.exports = Creatable;
|
react/TwitterIcon/TwitterIcon.js | seek-oss/seek-style-guide | import svgMarkup from './TwitterIcon.svg';
import svgMarkupFilled from './TwitterIconFilled.svg';
import PropTypes from 'prop-types';
import React from 'react';
import Icon from '../private/Icon/Icon';
export default function TwitterIcon({ filled, ...props }) {
const markup = filled ? svgMarkupFilled : svgMarkup;
return <Icon markup={markup} {...props} />;
}
TwitterIcon.displayName = 'TwitterIcon';
TwitterIcon.propTypes = {
filled: PropTypes.bool
};
TwitterIcon.defaultProps = {
filled: false
};
|
src/components/ChatApp/Settings/TextToSpeechSettings.react.js | madhavrathi/chat.susi.ai | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Paper from 'material-ui/Paper';
import UserPreferencesStore from '../../../stores/UserPreferencesStore';
import MessageStore from '../../../stores/MessageStore';
import Slider from 'material-ui/Slider';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
import VoicePlayer from '../MessageListItem/VoicePlayer';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
class TextToSpeechSettings extends Component {
constructor(props) {
super(props);
this.state = {
rate: this.props.rate,
pitch: this.props.pitch,
play: false,
playExample:false,
ttsLanguage: this.props.lang,
voiceList: MessageStore.getTTSVoiceList(),
};
this.speechSynthesisExample = 'This is an example of speech synthesis';
}
onStart = () => {
this.setState({
play: true
});
}
onEnd = () => {
this.setState({
play: false,
playExample: false,
});
}
handleRate = (event, value) => {
this.setState({
rate: value,
});
};
handlePitch = (event, value) => {
this.setState({
pitch: value,
});
};
resetRate = () => {
this.setState({
rate: 1,
});
}
resetPitch = () => {
this.setState({
pitch: 1,
});
}
playDemo = () => {
this.setState({
playExample: true,
play:true,
});
}
handleSubmit = () => {
this.props.ttsSettings({
rate: this.state.rate,
pitch: this.state.pitch,
lang: this.state.ttsLanguage,
});
}
populateVoiceList = () => {
let voices = this.state.voiceList;
let langCodes = [];
let voiceMenu = voices.map((voice,index) => {
if(voice.translatedText === null){
voice.translatedText = this.speechSynthesisExample;
}
langCodes.push(voice.lang);
return(
<MenuItem value={voice.lang} key={index}
primaryText={voice.name+' ('+voice.lang+')'} />
);
});
let currLang = this.state.ttsLanguage;
let voiceOutput = {
voiceMenu: voiceMenu,
voiceLang: currLang,
voiceText: this.speechSynthesisExample,
}
// `-` and `_` replacement check of lang codes
if(langCodes.indexOf(currLang) === -1){
if(currLang.indexOf('-') > -1 && langCodes.indexOf(currLang.replace('-','_')) > -1){
voiceOutput.voiceLang = currLang.replace('-','_');
}
else if(currLang.indexOf('_') > -1 && langCodes.indexOf(currLang.replace('_','-')) > -1){
voiceOutput.voiceLang = currLang.replace('_','-');
}
}
// Get the translated text for TTS in selected lang
let langCodeIndex = langCodes.indexOf(voiceOutput.voiceLang);
if( langCodeIndex > -1){
voiceOutput.voiceText = voices[langCodeIndex].translatedText;
}
return voiceOutput;
}
handleTTSVoices = (event, index, value) => {
this.setState({
ttsLanguage: value,
});
}
render() {
const Buttonstyles = {
marginBottom: 16,
}
const subHeaderStyle = {
color: UserPreferencesStore.getTheme()==='light'
? '#4285f4' : '#19314B'
}
let voiceOutput = this.populateVoiceList();
return (
<div className="settingsForm">
<Paper zDepth={0}>
<h3 style={{textAlign: 'center'}}>Text-To-Speech Settings</h3>
<h4 style={subHeaderStyle}>General</h4>
<div>
<h4 style={{'marginBottom':'0px'}}>Language</h4>
<DropDownMenu
value={voiceOutput.voiceLang}
onChange={this.handleTTSVoices}>
{voiceOutput.voiceMenu}
</DropDownMenu>
</div>
<div>
<h4 style={{'marginBottom':'0px'}}>Speech Rate</h4>
<Slider
min={0.5}
max={2}
value={this.state.rate}
onChange={this.handleRate} />
</div>
<div>
<h4 style={{'marginBottom':'0px'}}>Pitch</h4>
<Slider
min={0}
max={2}
value={this.state.pitch}
onChange={this.handlePitch} />
</div>
<div>
<h4 style={{'marginBottom':'0px'}}>Reset Speech Rate</h4>
<FlatButton
className='settingsBtns'
style={Buttonstyles}
label="Reset the speed at which the text is spoken to normal"
onClick={this.resetRate} />
</div>
<div>
<h4 style={{'marginBottom':'0px'}}>Reset Speech Pitch</h4>
<FlatButton
className='settingsBtns'
style={Buttonstyles}
label="Reset the pitch at which the text is spoken to default"
onClick={this.resetPitch} />
</div>
<div>
<h4 style={{'marginBottom':'0px'}}>Listen to an example</h4>
<FlatButton
className='settingsBtns'
style={Buttonstyles}
label="Play a short demonstration of speech synthesis"
onClick={this.playDemo} />
</div>
<div style={{textAlign: 'center'}}>
<RaisedButton
label="Save"
backgroundColor={
UserPreferencesStore.getTheme()==='light'
? '#4285f4' : '#19314B'}
labelColor="#fff"
onClick={this.handleSubmit}
/>
</div>
</Paper>
{ this.state.playExample &&
(<VoicePlayer
play={this.state.play}
text={voiceOutput.voiceText}
rate={this.state.rate}
pitch={this.state.pitch}
lang={this.state.ttsLanguage}
onStart={this.onStart}
onEnd={this.onEnd}
/>)
}
</div>);
}
}
TextToSpeechSettings.propTypes = {
rate: PropTypes.number,
pitch: PropTypes.number,
lang: PropTypes.string,
ttsSettings: PropTypes.func,
};
export default TextToSpeechSettings;
|
blueocean-material-icons/src/js/components/svg-icons/action/perm-contact-calendar.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionPermContactCalendar = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 3c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H6v-1c0-2 4-3.1 6-3.1s6 1.1 6 3.1v1z"/>
</SvgIcon>
);
ActionPermContactCalendar.displayName = 'ActionPermContactCalendar';
ActionPermContactCalendar.muiName = 'SvgIcon';
export default ActionPermContactCalendar;
|
fields/types/text/TextColumn.js | snowkeeper/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var TextColumn = React.createClass({
displayName: 'TextColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
linkTo: React.PropTypes.string,
},
getValue () {
// cropping text is important for textarea, which uses this column
const value = this.props.data.fields[this.props.col.path];
return value ? value.substr(0, 100) : null;
},
render () {
const value = this.getValue();
const empty = !value && this.props.linkTo ? true : false;
const className = this.props.col.field.monospace ? 'ItemList__value--monospace' : undefined;
return (
<ItemsTableCell>
<ItemsTableValue className={className} to={this.props.linkTo} empty={empty} padded interior field={this.props.col.type}>
{value}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = TextColumn;
|
public/js/components/profile/visitor/MockChat.react.js | IsuruDilhan/Coupley | import React from 'react';
import Avatar from 'material-ui/lib/avatar';
import List from 'material-ui/lib/lists/list';
import ListItem from 'material-ui/lib/lists/list-item';
import Divider from 'material-ui/lib/divider';
import CommunicationChatBubble from 'material-ui/lib/svg-icons/communication/chat-bubble';
const ChatData = [{
"name": "Rajika Imal",
"uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png"
},{
"name": "Stephanie Hwang",
"uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png"
},{
"name": "Anne Hathway",
"uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png"
}]
const ChatData_2 = [{
"name": "Rajika Imal",
"uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png"
},{
"name": "Stephanie Hwang",
"uri": "http://images6.fanpop.com/image/photos/35600000/Tiffany-SNSD-IPKN-tiffany-hwang-35651024-720-720.png"
}]
const MockChat = React.createClass({
_renderPrevList: function() {
return ChatData_2.map((chatitem) => {
return (
<div>
<ListItem
primaryText={chatitem.name}
leftAvatar={<Avatar src={chatitem.uri} />}
rightIcon={<CommunicationChatBubble />} />
<Divider />
</div>
);
});
},
_renderChatList: function() {
return ChatData.map((chatitem) => {
return (
<div>
<ListItem
primaryText={chatitem.name}
leftAvatar={<Avatar src={chatitem.uri} />}
rightIcon={<CommunicationChatBubble />} />
<Divider />
</div>
);
});
},
render: function() {
return (
<div>
<List subheader="Recent chats">
{this._renderChatList()}
</List>
<List subheader="Previous chats">
{this._renderPrevList()}
</List>
</div>
);
}
});
export default MockChat; |
packages/react/src/components/AutoInput.js | wq/wq.app | import React from 'react';
import { useComponents, useInputComponents, useRenderContext } from '../hooks';
import PropTypes from 'prop-types';
import { pascalCase } from 'pascal-case';
export default function AutoInput({ name, choices, type, bind = {}, ...rest }) {
const inputs = useInputComponents(),
{ AutoSubform, AutoSubformArray, Text } = useComponents(),
context = useRenderContext();
if (type === 'group') {
return <AutoSubform name={name} {...rest} />;
} else if (type === 'repeat') {
return <AutoSubformArray name={name} {...rest} />;
}
let inputType,
required = bind.required;
if (rest['wq:ForeignKey']) {
let choicesFn = context[name.replace(/\[\d+\]/, '') + '_list'];
choices = choicesFn ? choicesFn.call(context) : [];
choices = choices.map(({ id, label, outbox }) => ({
name: id,
label: outbox ? `* ${label}` : label
}));
name = `${name}_id`;
inputType = 'select';
} else if (type === 'select1' || type === 'select one') {
if (!choices) {
choices = [];
}
if (choices.length < 5) {
inputType = 'toggle';
} else if (choices.length < 10) {
inputType = 'radio';
} else {
inputType = 'select';
}
} else if (inputs[type]) {
inputType = type;
} else {
if (type === 'picture' || type === 'photo') {
inputType = 'image';
} else if (type === 'video' || type === 'audio') {
inputType = 'file';
} else if (type === 'binary') {
// wq.db <1.3
inputType = 'file';
} else {
inputType = 'input';
}
}
if (rest.control && rest.control.appearance) {
inputType = rest.control.appearance;
}
const Input = inputs[inputType];
if (!Input) {
return (
<Text>
Unknown input type "{inputType}". Perhaps you need to
define inputs.{pascalCase(inputType)} in a plugin?
</Text>
);
}
return (
<Input
name={name}
choices={choices}
type={type}
required={required}
{...rest}
/>
);
}
AutoInput.propTypes = {
name: PropTypes.string,
type: PropTypes.string,
bind: PropTypes.object,
'wq:ForeignKey': PropTypes.string,
choices: PropTypes.arrayOf(PropTypes.object)
};
|
src/templates/index-template.js | Amine-H/Amine-H.github.io | // @flow strict
import React from 'react';
import { graphql } from 'gatsby';
import Layout from '../components/Layout';
import Sidebar from '../components/Sidebar';
import Feed from '../components/Feed';
import Page from '../components/Page';
import Pagination from '../components/Pagination';
import { useSiteMetadata } from '../hooks';
import type { PageContext, AllMarkdownRemark } from '../types';
type Props = {
data: AllMarkdownRemark,
pageContext: PageContext
};
const IndexTemplate = ({ data, pageContext }: Props) => {
const { title: siteTitle, subtitle: siteSubtitle } = useSiteMetadata();
const {
currentPage,
hasNextPage,
hasPrevPage,
prevPagePath,
nextPagePath
} = pageContext;
const { edges } = data.allMarkdownRemark;
const pageTitle = currentPage > 0 ? `Posts - Page ${currentPage} - ${siteTitle}` : siteTitle;
return (
<Layout title={pageTitle} description={siteSubtitle}>
<Sidebar isIndex />
<Page>
<Feed edges={edges} />
<Pagination
prevPagePath={prevPagePath}
nextPagePath={nextPagePath}
hasPrevPage={hasPrevPage}
hasNextPage={hasNextPage}
/>
</Page>
</Layout>
);
};
export const query = graphql`
query IndexTemplate($postsLimit: Int!, $postsOffset: Int!) {
allMarkdownRemark(
limit: $postsLimit,
skip: $postsOffset,
filter: { frontmatter: { template: { eq: "post" }, draft: { ne: true } } },
sort: { order: DESC, fields: [frontmatter___date] }
){
edges {
node {
fields {
slug
categorySlug
}
frontmatter {
title
date
category
description
}
}
}
}
}
`;
export default IndexTemplate;
|
docs/src/app/components/pages/components/AppBar/Page.js | rhaedes/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import appBarReadmeText from './README';
import AppBarExampleIcon from './ExampleIcon';
import appBarExampleIconCode from '!raw!./ExampleIcon';
import AppBarExampleIconButton from './ExampleIconButton';
import appBarExampleIconButtonCode from '!raw!./ExampleIconButton';
import AppBarExampleIconMenu from './ExampleIconMenu';
import appBarExampleIconMenuCode from '!raw!./ExampleIconMenu';
import appBarCode from '!raw!material-ui/AppBar/AppBar';
const descriptions = {
icon: 'A simple example of `AppBar` with an icon on the right. ' +
'By default, the left icon is a navigation-menu.',
iconButton: 'This example uses an [IconButton](/#/components/icon-button) on the left, has a clickable `title` ' +
'through the `onTouchTap` property, and a [FlatButton](/#/components/flat-button) on the right.',
iconMenu: 'This example uses an [IconMenu](/#/components/icon-menu) for `iconElementRight`.',
};
const AppBarPage = () => (
<div>
<Title render={(previousTitle) => `App Bar - ${previousTitle}`} />
<MarkdownElement text={appBarReadmeText} />
<CodeExample
code={appBarExampleIconCode}
title="Simple example"
description={descriptions.icon}
>
<AppBarExampleIcon />
</CodeExample>
<CodeExample
code={appBarExampleIconButtonCode}
title="Buttons"
description={descriptions.iconButton}
>
<AppBarExampleIconButton />
</CodeExample>
<CodeExample
code={appBarExampleIconMenuCode}
title="Icon Menu"
description={descriptions.iconMenu}
>
<AppBarExampleIconMenu />
</CodeExample>
<PropTypeDescription code={appBarCode} />
</div>
);
export default AppBarPage;
|
src/js/routes.js | akornatskyy/sample-blog-react-redux | import React from 'react';
import {Container} from 'react-bootstrap';
import {Route, Switch} from 'react-router';
import AuthInfo from './membership/containers/auth-info';
import Footer from './shared/components/footer';
import Header from './shared/components/header';
import Posts from './posts/containers/posts';
import Post from './posts/containers/post';
import SignIn from './membership/containers/signin';
import SignUp from './membership/containers/signup';
const App = () => (
<Container>
<Header>
<AuthInfo />
</Header>
<Switch>
<Route exact path="/" component={Posts} />
<Route exact path="/posts" component={Posts} />
<Route exact path="/post/:slug" component={Post} />
<Route exact path="/signin" component={SignIn} />
<Route exact path="/signup" component={SignUp} />
</Switch>
<hr />
<Footer />
</Container>
);
export default (<Route path="/" component={App} />);
|
src/scenes/ChildScene.js | teamfa/react-native-starter-app | /**
* @providesModule ChildScene
* @flow
*/
import React from 'react';
import { View, Text, StyleSheet } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Button from 'Button';
function ChildScene() {
return (
<View style={styles.container}>
<Text style={styles.header}>
Example of a child scene...
</Text>
<Button onPress={Actions.pop}>
POP back home
</Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
header: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
export default ChildScene;
|
node_modules/react-bootstrap/es/NavbarToggle.js | firdiansyah/crud-req | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { prefix } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
var propTypes = {
onClick: PropTypes.func,
/**
* The toggle content, if left empty it will render the default toggle (seen above).
*/
children: PropTypes.node
};
var contextTypes = {
$bs_navbar: PropTypes.shape({
bsClass: PropTypes.string,
expanded: PropTypes.bool,
onToggle: PropTypes.func.isRequired
})
};
var NavbarToggle = function (_React$Component) {
_inherits(NavbarToggle, _React$Component);
function NavbarToggle() {
_classCallCheck(this, NavbarToggle);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavbarToggle.prototype.render = function render() {
var _props = this.props,
onClick = _props.onClick,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['onClick', 'className', 'children']);
var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' };
var buttonProps = _extends({
type: 'button'
}, props, {
onClick: createChainedFunction(onClick, navbarProps.onToggle),
className: classNames(className, prefix(navbarProps, 'toggle'), !navbarProps.expanded && 'collapsed')
});
if (children) {
return React.createElement(
'button',
buttonProps,
children
);
}
return React.createElement(
'button',
buttonProps,
React.createElement(
'span',
{ className: 'sr-only' },
'Toggle navigation'
),
React.createElement('span', { className: 'icon-bar' }),
React.createElement('span', { className: 'icon-bar' }),
React.createElement('span', { className: 'icon-bar' })
);
};
return NavbarToggle;
}(React.Component);
NavbarToggle.propTypes = propTypes;
NavbarToggle.contextTypes = contextTypes;
export default NavbarToggle; |
app/javascript/mastodon/components/loading_indicator.js | mhffdq/mastodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
const LoadingIndicator = () => (
<div className='loading-indicator'>
<div className='loading-indicator__figure' />
<FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' />
</div>
);
export default LoadingIndicator;
|
Inspector/js/tree.js | ymin/WebDriverAgent | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import PropTypes from 'prop-types';
import React from 'react';
import TreeView from 'react-treeview';
import classNames from 'classnames';
require('css/tree.css');
require('react-treeview/react-treeview.css');
const CAPTION_HEIGHT = 100;
const CAPTION_PADDING = 20;
const FRESH_BUTTON_PADDING = 20;
class Tree extends React.Component {
render() {
const style = this.styleWithMaxHeight(
this.maxTreeHeight());
return (
<div id="tree" className="section second">
<div className="section-caption">
Tree of Elements
</div>
<div className="section-content-container">
<div className="section-content">
<div className="tree-container" style={style}>
{this.renderTree()}
</div>
<div className="tree-fresh-button">
<button
onClick={this.fetchTree.bind(this)}>
Refresh
</button>
<button
onClick={this.fetchFullTree.bind(this)}>
Fetch Full Tree
</button>
</div>
</div>
</div>
</div>
);
}
fetchTree() {
this.props.treeRefresh();
}
fetchFullTree() {
this.props.fullTreeRefresh();
}
maxTreeHeight() {
return window.innerHeight - CAPTION_HEIGHT + CAPTION_PADDING - FRESH_BUTTON_PADDING * 2;
}
styleWithMaxHeight(height) {
return {
'maxHeight': height,
};
}
renderTree() {
if (this.props.rootNode == null) {
return null;
}
return (
<div>
<div className="tree-header"/>
{this.renderNode(this.props.rootNode)}
</div>
);
}
renderNode(node) {
const isSelected = (this.props.selectedNode != null
&& this.props.selectedNode.key === node.key);
const className = classNames(
'tree-node',
{
'selected' : isSelected,
}
);
const nodeLabelView = (
<span
className={className}
onClick={(event) => this.onNodeClick(node)}
onMouseEnter={(event) => this.onNodeMouseEnter(node)}
onMouseLeave={(event) => this.onNodeMouseLeave(node)}>
{node.name}
</span>
);
var childrenViews = null;
if (node.children != null) {
childrenViews = node.children.map((child) => {
return this.renderNode(child);
});
}
return (
<TreeView
key={node.key}
nodeLabel={nodeLabelView}
defaultCollapsed={false}>
{childrenViews}
</TreeView>
);
}
onNodeClick(node) {
if (this.props.onSelectedNodeChange != null) {
this.props.onSelectedNodeChange(node);
}
}
onNodeMouseEnter(node) {
if (this.props.onHighlightedNodeChange != null) {
this.props.onHighlightedNodeChange(node);
}
}
onNodeMouseLeave(node) {
if (this.props.onHighlightedNodeChange != null) {
this.props.onHighlightedNodeChange(null);
}
}
}
Tree.propTypes = {
onSelectedNodeChange: PropTypes.func,
onHighlightedNodeChange: PropTypes.func,
rootNode: PropTypes.object,
selectedNode: PropTypes.object,
};
module.exports = Tree;
|
src/containers/Page4.js | D4vx/react-template | import React, { Component } from 'react';
//import PropTypes from 'prop-types';
class Page4 extends Component {
render() {
return (
<div>
Page4
</div>
);
}
}
Page4.propTypes = {
};
export default Page4;
|
src/components/Notifier.js | Hylozoic/hylo-redux | import React from 'react'
const { array, func } = React.PropTypes
import { VelocityTransitionGroup } from 'velocity-react'
export default class Notifier extends React.Component {
static propTypes = {
messages: array,
remove: func
}
componentDidMount () {
setInterval(() => {
let now = Date.now()
this.props.messages.filter(m => m.maxage && now > m.id + m.maxage)
.forEach(m => this.props.remove(m.id))
}, 500)
}
render () {
let { messages, remove } = this.props
return <div id='notifier'>
<VelocityTransitionGroup
enter={{animation: {translateX: [0, '120%']}}}
leave={{animation: {translateX: '120%'}}}>
{messages.map(m => <Message key={m.id} message={m} remove={remove} />)}
</VelocityTransitionGroup>
</div>
}
}
const className = messageType => {
switch (messageType) {
case 'error': return 'danger'
}
// bootstrap's standard types: success, info, warning, danger
return messageType
}
const Message = ({ message: { type, id, text, noClose }, remove }) => {
return <div className={`alert alert-${className(type)}`}>
{!noClose && <a className='close' onClick={() => remove(id)}>×</a>}
<div>{text}</div>
</div>
}
|
cloud/dashboard/src/components/MainMenu.js | iotivity/iotivity | /*
* //******************************************************************
* //
* // Copyright 2017 Samsung Electronics All Rights Reserved.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
* //
* // Licensed under the Apache License, Version 2.0 (the "License");
* // you may not use this file except in compliance with the License.
* // You may obtain a copy of the License at
* //
* // http://www.apache.org/licenses/LICENSE-2.0
* //
* // Unless required by applicable law or agreed to in writing, software
* // distributed under the License is distributed on an "AS IS" BASIS,
* // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* // See the License for the specific language governing permissions and
* // limitations under the License.
* //
* //-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=
*/
import React from 'react';
import ReactDOM from 'react-dom';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import {List, ListItem} from 'material-ui/List';
import Divider from 'material-ui/Divider';
import {orange700, white} from 'material-ui/styles/colors';
import ResourceList from './ResourceList';
import ResourceListToolbar from './ResourceListToolbar';
import FirmwareManagement from './FirmwareManagement';
const Client = require('../Client');
const ERROR = 'error';
const style = {
list: {
backgroundColor: orange700,
height: '100%'
},
text: {
color: white,
}
}
function appendChildren(id, numChildren) {
var parent = document.getElementById(id);
while (parent.firstChild) {
parent.removeChild(parent.firstChild);
}
for (var i = 0; parent.childElementCount <= numChildren; i++) {
parent.appendChild(document.createElement('child' + i));
}
};
class MainMenu extends React.Component {
onDiscover = (packet) => {
if(packet.getCode !== 69)
{
Client.event.emit(ERROR, "Resource Discover Failed " + packet.getCode);
return;
}
var resources = Client.getResourceList(packet.getPayloadObject);
appendChildren('body', 2);
ReactDOM.render(
<ResourceListToolbar />,
document.getElementById('body').children[0]
);
ReactDOM.render(
<ResourceList data={resources} />,
document.getElementById('body').children[1]
);
};
onFirmwareResources = (packet) =>{
if(packet.getCode !== 69)
{
Client.event.emit(ERROR, "Firmware Discover Failed " + packet.getCode);
return;
}
var resources = Client.getResourceList(packet.getPayloadObject);
appendChildren('body', 1);
ReactDOM.render(
<FirmwareManagement devices={resources} />,
document.getElementById('body').children[0]
);
};
handleDiscovery = () => {
Client.discoverResource(null, this.onDiscover);
};
handleFirmware = () => {
Client.discoverResource("rt=x.org.iotivity.firmware", this.onFirmwareResources);
};
constructor(props, context) {
super(props, context);
this.state = {
signin: props.signin
}
};
render() {
return (
/* TODO add log page */
<MuiThemeProvider>
<List style={style.list}>
<ListItem primaryText='Resource list' style={style.text} disabled={!this.state.signin} onTouchTap={this.handleDiscovery} />
<Divider />
<ListItem primaryText='Firmware management' style={style.text} disabled={!this.state.signin} onTouchTap={this.handleFirmware} />
<Divider />
<ListItem primaryText='Log view' style={style.text} />
</List>
</MuiThemeProvider>
);
};
};
export default MainMenu;
|
src/scripts/base/Q.js | ButuzGOL/constructor | import React from 'react';
import variables from '../styles/variables';
export default class Q extends React.Component {
getStyles() {
return {
fontStyle: variables.baseQuoteFontStyle
};
}
render() {
return (
<q>
{this.props.children}
</q>
);
}
}
|
app/components/Browse/BrowseHeader.js | cdiezmoran/AlphaStage-desktop | // @flow
import React, { Component } from 'react';
import $ from 'jquery';
class BrowseHeader extends Component {
static handleFilterClick(e: Event) {
e.preventDefault();
const $target = $(event.target);
$target.addClass('active');
$target.siblings().removeClass('active');
}
render() {
return (
<div className="browse-header">
<div id="stars" />
<div id="stars2" />
<div id="stars3" />
<div id="browse-filters">
<div className="filters-div">
{/* <a href="#" className="first active" onClick={this.handleFilterClick}>Popular</a>
<a href="#" onClick={this.handleFilterClick}>Trending</a>
<a href="#" onClick={this.handleFilterClick}>New</a>
<a href="#" className="last" onClick={this.handleFilterClick}>Mac Only</a>*/}
<a href="#all" className="first active">All Games</a>
</div>
</div>
</div>
);
}
}
export default BrowseHeader;
|
src/React/Widgets/CollapsibleWidget/index.js | Kitware/paraviewweb | import React from 'react';
import PropTypes from 'prop-types';
import style from 'PVWStyle/ReactWidgets/CollapsibleWidget.mcss';
export default class CollapsibleWidget extends React.Component {
constructor(props) {
super(props);
this.state = {
open: props.open,
};
// Bind callback
this.toggleOpen = this.toggleOpen.bind(this);
}
toggleOpen() {
if (this.props.disableCollapse && this.state.open) {
return;
}
const newState = !this.state.open;
this.setState({ open: newState });
if (this.props.onChange) {
this.props.onChange(newState);
}
}
isCollapsed() {
return this.state.open === false;
}
isExpanded() {
return this.state.open === true;
}
render() {
const localStyle = {};
if (!this.props.visible) {
localStyle.display = 'none';
}
return (
<section className={style.container} style={localStyle}>
<div className={style.header}>
<div onClick={this.toggleOpen}>
<i className={style[this.state.open ? 'caret' : 'caretClosed']} />
<strong className={style.title}>{this.props.title}</strong>
</div>
<span
className={
this.props.activeSubTitle ? style.subtitleActive : style.subtitle
}
>
{this.props.subtitle}
</span>
</div>
<div
className={
style[this.state.open ? 'visibleContent' : 'hiddenContent']
}
>
{this.props.children}
</div>
</section>
);
}
}
CollapsibleWidget.propTypes = {
children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
onChange: PropTypes.func,
open: PropTypes.bool,
subtitle: PropTypes.oneOfType([
PropTypes.object,
PropTypes.string,
PropTypes.array,
]),
title: PropTypes.string,
visible: PropTypes.bool,
activeSubTitle: PropTypes.bool,
disableCollapse: PropTypes.bool,
};
CollapsibleWidget.defaultProps = {
title: '',
subtitle: '',
open: true,
visible: true,
disableCollapse: false,
activeSubTitle: false,
children: undefined,
onChange: undefined,
};
|
server/sonar-web/src/main/js/components/shared/Organization.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// @flow
import React from 'react';
import { connect } from 'react-redux';
import { getOrganizationByKey, areThereCustomOrganizations } from '../../store/rootReducer';
import OrganizationLink from '../ui/OrganizationLink';
type OwnProps = {
organizationKey: string
};
type Props = {
link?: boolean,
organizationKey: string,
organization: { key: string, name: string } | null,
shouldBeDisplayed: boolean
};
class Organization extends React.Component {
props: Props;
static defaultProps = {
link: true
};
render() {
const { organization, shouldBeDisplayed } = this.props;
if (!shouldBeDisplayed || !organization) {
return null;
}
return (
<span>
{this.props.link
? <OrganizationLink organization={organization}>{organization.name}</OrganizationLink>
: organization.name}
<span className="slash-separator" />
</span>
);
}
}
const mapStateToProps = (state, ownProps: OwnProps) => ({
organization: getOrganizationByKey(state, ownProps.organizationKey),
shouldBeDisplayed: areThereCustomOrganizations(state)
});
export default connect(mapStateToProps)(Organization);
export const UnconnectedOrganization = Organization;
|
components/Footer/Footer.js | guokeke/image-editor | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Link from '../Link';
function Footer() {
return (
<footer className="mdl-mini-footer">
<div className="mdl-mini-footer__left-section">
<div className="mdl-logo">© Company Name</div>
<ul className="mdl-mini-footer__link-list">
<li><Link to="/privacy">Privacy & Terms</Link></li>
<li><Link to="/not-found">Not Found</Link></li>
</ul>
</div>
<div className="mdl-mini-footer__right-section">
<ul className="mdl-mini-footer__link-list">
<li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}>
<a href="https://github.com/kriasoft/react-static-boilerplate" role="button" title="GitHub">
<svg width="36" height="36" viewBox="0 0 24 24">
<path
fill="#fff" d="M12,2A10,10 0 0,0 2,12C2,16.42 4.87,20.17 8.84,21.5C9.34,21.58
9.5,21.27 9.5,21C9.5,20.77 9.5,20.14 9.5,19.31C6.73,19.91 6.14,17.97 6.14,
17.97C5.68,16.81 5.03,16.5 5.03,16.5C4.12,15.88 5.1,15.9 5.1,15.9C6.1,15.97 6.63,
16.93 6.63,16.93C7.5,18.45 8.97,18 9.54,17.76C9.63,17.11 9.89,16.67 10.17,
16.42C7.95,16.17 5.62,15.31 5.62,11.5C5.62,10.39 6,9.5 6.65,8.79C6.55,8.54 6.2,
7.5 6.75,6.15C6.75,6.15 7.59,5.88 9.5,7.17C10.29,6.95 11.15,6.84 12,6.84C12.85,
6.84 13.71,6.95 14.5,7.17C16.41,5.88 17.25,6.15 17.25,6.15C17.8,7.5 17.45,8.54
17.35,8.79C18,9.5 18.38,10.39 18.38,11.5C18.38,15.32 16.04,16.16 13.81,
16.41C14.17,16.72 14.5,17.33 14.5,18.26C14.5,19.6 14.5,20.68 14.5,21C14.5,21.27
14.66,21.59 15.17,21.5C19.14,20.16 22,16.42 22,12A10,10 0 0,0 12,2Z"
/>
</svg>
</a>
</li>
<li className="mdl-mini-footer--social-btn" style={{ backgroundColor: 'transparent' }}>
<a href="https://twitter.com/ReactStatic" role="button" title="Twitter">
<svg width="36" height="36" viewBox="0 0 24 24">
<path
fill="#fff" d="M17.71,9.33C18.19,8.93 18.75,8.45 19,7.92C18.59,8.13 18.1,8.26
17.56,8.33C18.06,7.97 18.47,7.5 18.68,6.86C18.16,7.14 17.63,7.38 16.97,
7.5C15.42,5.63 11.71,7.15 12.37,9.95C9.76,9.79 8.17,8.61 6.85,7.16C6.1,8.38
6.75,10.23 7.64,10.74C7.18,10.71 6.83,10.57 6.5,10.41C6.54,11.95 7.39,12.69
8.58,13.09C8.22,13.16 7.82,13.18 7.44,13.12C7.81,14.19 8.58,14.86 9.9,15C9,15.76
7.34,16.29 6,16.08C7.15,16.81 8.46,17.39 10.28,17.31C14.69,17.11 17.64,13.95
17.71,9.33M12,2A10,10 0 0,1 22,12A10,10 0 0,1 12,22A10,10 0 0,1 2,12A10,10 0 0,1
12,2Z"
/>
</svg>
</a>
</li>
</ul>
</div>
</footer>
);
}
export default Footer;
|
src/client/story_list.js | yelken/hacker-menu | import React from 'react'
import Story from './story.js'
import _ from 'lodash'
export default class StoryList extends React.Component {
render () {
var onUrlClick = this.props.onUrlClick
var onMarkAsRead = this.props.onMarkAsRead
var storyNodes = _.map(this.props.stories, function (story, index) {
return (
<li key={index} className='table-view-cell media'>
<Story story={story} onUrlClick={onUrlClick} onMarkAsRead={onMarkAsRead}/>
</li>
)
})
return (
<ul className='content table-view'>
{storyNodes}
</ul>
)
}
}
StoryList.propTypes = {
onUrlClick: React.PropTypes.func.isRequired,
onMarkAsRead: React.PropTypes.func.isRequired,
stories: React.PropTypes.array.isRequired
}
|
app/static/scripts/user/authView/signupForm/main.js | joshleeb/WordpressPylon | import AuthActions from '../../../auth/actions.js';
import UserActions from '../../actions.js';
import UserStore from '../../store.js';
import UserConstants from '../../constants.js';
import React from 'react';
require('./styles.scss');
export default class UserSignupForm extends React.Component {
constructor() {
super();
this.state = {
email: '',
password: '',
message: ''
};
}
componentWillMount() {
UserStore.on(
UserConstants.SIGNUP_USER_SUCCESS, this.handleSignupSuccess);
UserStore.on(
UserConstants.SIGNUP_USER_FAILURE, this.handleSignupFailure);
}
componentWillUnmount() {
UserStore.removeListener(
UserConstants.SIGNUP_USER_SUCCESS, this.handleSignupSuccess);
UserStore.removeListener(
UserConstants.SIGNUP_USER_FAILURE, this.handleSignupFailure);
}
handleSignupSuccess = () => {
this.setState({message: ''});
AuthActions.logUserIn(this.state.email, this.state.password);
}
handleSignupFailure = () => {
let error = UserStore.getError().response;
if (error && error.status === '400 Bad Request') {
this.setState({message: error.message});
} else {
this.setState({message: 'Something went wrong...'});
}
}
onFormChange = (e) => {
this.setState({[e.target.name]: e.target.value});
}
signup = (e) => {
let form = this.state;
e.preventDefault();
UserActions.signUserUp(form.email, form.password);
}
render() {
let message = <p>{this.state.message}</p>;
if (this.state.message === '') {
message = null;
}
return (
<div id="userSignupForm">
<form onSubmit={this.signup}>
<fieldset class="col-xs-12 form-group">
<input required name="email" type="email" id="email"
className="form-control" placeholder="Email"
onChange={this.onFormChange}
/>
</fieldset>
<fieldset class="col-xs-12 form-group">
<input required name="password" type="password" id="password"
className="form-control" placeholder="Password"
onChange={this.onFormChange}
/>
</fieldset>
<div className="col-xs-12">
<button type="submit"
className="col-xs-12 mdl-button mdl-js-button mdl-button-raised mdl-js-ripple-effect btn-submit"
>Sign up</button>
</div>
</form>
{message}
</div>
);
}
}
|
src/components/lib/AlloyFinger.js | CodingJoker/h5-platform | /* AlloyFinger v0.1.0
* By dntzhang
* Github: https://github.com/AlloyTeam/AlloyFinger
*/
import React from 'react';
export default class AlloyFinger extends React.Component {
constructor(props) {
super(props);
this.preV = { x: null, y: null };
this.pinchStartLen = null;
this.scale = 1;
this.isDoubleTap = false;
this.delta = null;
this.last = null;
this.now = null;
this.tapTimeout = null;
this.longTapTimeout = null;
this.swipeTimeout=null;
this.x1 = this.x2 = this.y1 = this.y2 = null;
this.preTapPosition={x:null,y:null};
}
getLen(v) {
return Math.sqrt(v.x * v.x + v.y * v.y);
}
dot(v1, v2) {
return v1.x * v2.x + v1.y * v2.y;
}
getAngle(v1, v2) {
var mr = getLen(v1) * getLen(v2);
if (mr === 0) return 0;
var r = dot(v1, v2) / mr;
if (r > 1) r = 1;
return Math.acos(r);
}
cross(v1, v2) {
return v1.x * v2.y - v2.x * v1.y;
}
getRotateAngle(v1, v2) {
var angle = getAngle(v1, v2);
if (cross(v1, v2) > 0) {
angle *= -1;
}
return angle * 180 / Math.PI;
}
_resetState() {
this.setState({x: null, y: null, swiping: false, start: 0 });
}
_emitEvent = (name, e) => {
if (this.props[name]) {
this.props[name](e);
}
}
_handleTouchStart (evt) {
this.now = Date.now();
this.x1 = evt.touches[0].pageX;
this.y1 = evt.touches[0].pageY;
this.delta = this.now - (this.last || this.now);
if(this.preTapPosition.x!==null){
this.isDoubleTap = (this.delta > 0 && this.delta <= 250&&Math.abs(this.preTapPosition.x-this.x1)<30&&Math.abs(this.preTapPosition.y-this.y1)<30);
}
this.preTapPosition.x=this.x1;
this.preTapPosition.y=this.y1;
this.last = this.now;
var preV = this.preV,
len = evt.touches.length;
if (len > 1) {
var v = { x: evt.touches[1].pageX - this.x1, y: evt.touches[1].pageY - this.y1 };
preV.x = v.x;
preV.y = v.y;
this.pinchStartLen = getLen(preV);
this._emitEvent('onMultipointStart', evt);
}
this.longTapTimeout = setTimeout(function(){
this._emitEvent('onLongTap', evt);
}.bind(this), 750);
}
_handleTouchMove(evt){
var preV = this.preV,
len = evt.touches.length,
currentX = evt.touches[0].pageX,
currentY = evt.touches[0].pageY;
this.isDoubleTap=false;
if (len > 1) {
var v = { x: evt.touches[1].pageX - currentX, y: evt.touches[1].pageY - currentY };
if (preV.x !== null) {
if (this.pinchStartLen > 0) {
evt.scale = getLen(v) / this.pinchStartLen;
this._emitEvent('onPinch', evt);
}
evt.angle = getRotateAngle(v, preV);
this._emitEvent('onRotate', evt);
}
preV.x = v.x;
preV.y = v.y;
} else {
if (this.x2 !== null) {
evt.deltaX = currentX - this.x2;
evt.deltaY = currentY - this.y2;
}else{
evt.deltaX = 0;
evt.deltaY = 0;
}
this._emitEvent('onPressMove', evt);
}
this._cancelLongTap();
this.x2 = currentX;
this.y2 = currentY;
if(len > 1) {
evt.preventDefault();
}
}
_handleTouchCancel(){
clearInterval(this.tapTimeout);
clearInterval(this.longTapTimeout);
clearInterval(this.swipeTimeout);
}
_handleTouchEnd(evt){
this._cancelLongTap();
var self = this;
if( evt.touches.length<2){
this._emitEvent('onMultipointEnd', evt);
}
if ((this.x2 && Math.abs(this.x1 - this.x2) > 30) ||
(this.y2 && Math.abs(this.preV.y - this.y2) > 30)) {
evt.direction = this._swipeDirection(this.x1, this.x2, this.y1, this.y2);
this.swipeTimeout = setTimeout(function () {
self._emitEvent('onSwipe', evt);
}, 0)
} else {
this.tapTimeout = setTimeout(function () {
self._emitEvent('onTap', evt);
if (self.isDoubleTap) {
self._emitEvent('onDoubleTap', evt);
self.isDoubleTap = false;
}
}, 0)
}
this.preV.x = 0;
this.preV.y = 0;
this.scale = 1;
this.pinchStartLen = null;
this.x1 = this.x2 = this.y1 = this.y2 = null;
}
_cancelLongTap () {
clearTimeout(this.longTapTimeout);
}
_swipeDirection (x1, x2, y1, y2) {
return Math.abs(x1 - x2) >= Math.abs(y1 - y2) ? (x1 - x2 > 0 ? 'Left' : 'Right') : (y1 - y2 > 0 ? 'Up' : 'Down')
}
render() {
return React.cloneElement(React.Children.only(this.props.children), {
onTouchStart: this._handleTouchStart.bind(this),
onTouchMove: this._handleTouchMove.bind(this),
onTouchCancel: this._handleTouchCancel.bind(this),
onTouchEnd: this._handleTouchEnd.bind(this)
});
}
}
|
actor-apps/app-web/src/app/components/dialog/ComposeSection.react.js | xiaotaijun/actor-platform | import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
const {addons: { PureRenderMixin }} = addons;
import ActorClient from 'utils/ActorClient';
import { Styles, FlatButton } from 'material-ui';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import MessageActionCreators from 'actions/MessageActionCreators';
import TypingActionCreators from 'actions/TypingActionCreators';
import DraftActionCreators from 'actions/DraftActionCreators';
import GroupStore from 'stores/GroupStore';
import DraftStore from 'stores/DraftStore';
import AvatarItem from 'components/common/AvatarItem.react';
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
text: DraftStore.getDraft(),
profile: ActorClient.getUser(ActorClient.getUid())
};
};
@ReactMixin.decorate(PureRenderMixin)
class ComposeSection extends React.Component {
static propTypes = {
peer: React.PropTypes.object.isRequired
};
static childContextTypes = {
muiTheme: React.PropTypes.object
};
constructor(props) {
super(props);
this.state = getStateFromStores();
ThemeManager.setTheme(ActorTheme);
GroupStore.addChangeListener(getStateFromStores);
DraftStore.addLoadDraftListener(this.onDraftLoad);
}
componentWillUnmount() {
DraftStore.removeLoadDraftListener(this.onDraftLoad);
GroupStore.removeChangeListener(getStateFromStores);
}
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
onDraftLoad = () => {
this.setState(getStateFromStores());
};
onChange = event => {
TypingActionCreators.onTyping(this.props.peer);
this.setState({text: event.target.value});
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ENTER && !event.shiftKey) {
event.preventDefault();
this.sendTextMessage();
} else if (event.keyCode === 50 && event.shiftKey) {
console.warn('Mention should show now.');
}
};
onKeyUp = () => {
DraftActionCreators.saveDraft(this.state.text);
};
sendTextMessage = () => {
const text = this.state.text;
if (text) {
MessageActionCreators.sendTextMessage(this.props.peer, text);
}
this.setState({text: ''});
DraftActionCreators.saveDraft('', true);
};
onSendFileClick = () => {
const fileInput = document.getElementById('composeFileInput');
fileInput.click();
};
onSendPhotoClick = () => {
const photoInput = document.getElementById('composePhotoInput');
photoInput.accept = 'image/*';
photoInput.click();
};
onFileInputChange = () => {
const files = document.getElementById('composeFileInput').files;
MessageActionCreators.sendFileMessage(this.props.peer, files[0]);
};
onPhotoInputChange = () => {
const photos = document.getElementById('composePhotoInput').files;
MessageActionCreators.sendPhotoMessage(this.props.peer, photos[0]);
};
onPaste = event => {
let preventDefault = false;
_.forEach(event.clipboardData.items, (item) => {
if (item.type.indexOf('image') !== -1) {
preventDefault = true;
MessageActionCreators.sendClipboardPhotoMessage(this.props.peer, item.getAsFile());
}
}, this);
if (preventDefault) {
event.preventDefault();
}
};
render() {
const text = this.state.text;
const profile = this.state.profile;
return (
<section className="compose" onPaste={this.onPaste}>
<AvatarItem image={profile.avatar}
placeholder={profile.placeholder}
title={profile.name}/>
<textarea className="compose__message"
onChange={this.onChange}
onKeyDown={this.onKeyDown}
onKeyUp={this.onKeyUp}
value={text}>
</textarea>
<footer className="compose__footer row">
<button className="button" onClick={this.onSendFileClick}>
<i className="material-icons">attachment</i> Send file
</button>
<button className="button" onClick={this.onSendPhotoClick}>
<i className="material-icons">photo_camera</i> Send photo
</button>
<span className="col-xs"></span>
<FlatButton label="Send" onClick={this.sendTextMessage} secondary={true}/>
</footer>
<div className="compose__hidden">
<input id="composeFileInput"
onChange={this.onFileInputChange}
type="file"/>
<input id="composePhotoInput"
onChange={this.onPhotoInputChange}
type="file"/>
</div>
</section>
);
}
}
export default ComposeSection;
|
app/javascript/mastodon/features/pinned_statuses/index.js | hyuki0000/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchPinnedStatuses } from '../../actions/pin_statuses';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import StatusList from '../../components/status_list';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'column.pins', defaultMessage: 'Pinned toot' },
});
const mapStateToProps = state => ({
statusIds: state.getIn(['status_lists', 'pins', 'items']),
hasMore: !!state.getIn(['status_lists', 'pins', 'next']),
});
@connect(mapStateToProps)
@injectIntl
export default class PinnedStatuses extends ImmutablePureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list.isRequired,
intl: PropTypes.object.isRequired,
hasMore: PropTypes.bool.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchPinnedStatuses());
}
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
render () {
const { intl, statusIds, hasMore } = this.props;
return (
<Column icon='thumb-tack' heading={intl.formatMessage(messages.heading)} ref={this.setRef}>
<ColumnBackButtonSlim />
<StatusList
statusIds={statusIds}
scrollKey='pinned_statuses'
hasMore={hasMore}
/>
</Column>
);
}
}
|
docs/src/pages/discover-more/showcase/Showcase.js | lgollut/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import { withStyles } from '@material-ui/core/styles';
import InputLabel from '@material-ui/core/InputLabel';
import MenuItem from '@material-ui/core/MenuItem';
import FormControl from '@material-ui/core/FormControl';
import Select from '@material-ui/core/Select';
import Card from '@material-ui/core/Card';
import CardMedia from '@material-ui/core/CardMedia';
import Typography from '@material-ui/core/Typography';
import IconButton from '@material-ui/core/IconButton';
import GitHubIcon from '@material-ui/icons/GitHub';
import Link from 'docs/src/modules/components/Link';
import appList from './appList';
const styles = (theme) => ({
root: {
flexGrow: 1,
},
formControl: {
marginBottom: theme.spacing(4),
minWidth: 120,
},
title: {
marginBottom: theme.spacing(2),
},
card: {
marginBottom: theme.spacing(1),
maxWidth: 600,
},
description: {
marginBottom: theme.spacing(6),
maxWidth: 600,
},
cardMedia: {
paddingTop: '75%', // 4:3
},
});
function stableSort(array, cmp) {
const stabilizedThis = array.map((el, index) => [el, index]);
stabilizedThis.sort((a, b) => {
const order = cmp(a[0], b[0]);
if (order !== 0) return order;
return a[1] - b[1];
});
return stabilizedThis.map((el) => el[0]);
}
// Returns a function that sorts reverse numerically by value of `key`
function sortFactory(key) {
return function sortNumeric(a, b) {
if (b[key] < a[key]) {
return -1;
}
if (b[key] > a[key]) {
return 1;
}
return 0;
};
}
const sortFunctions = {
dateAdded: sortFactory('dateAdded'),
similarWebVisits: sortFactory('similarWebVisits'),
stars: sortFactory('stars'),
};
function Showcase(props) {
const { classes } = props;
const [sortFunctionName, setSortFunctionName] = React.useState('dateAdded');
const sortFunction = sortFunctions[sortFunctionName];
const t = useSelector((state) => state.options.t);
const handleChangeSort = (event) => {
setSortFunctionName(event.target.value);
};
return (
<div className={classes.root}>
<FormControl className={classes.formControl}>
<InputLabel htmlFor="sort">Sort by</InputLabel>
<Select value={sortFunctionName} onChange={handleChangeSort} inputProps={{ id: 'sort' }}>
<MenuItem value="dateAdded">{t('newest')}</MenuItem>
<MenuItem value="similarWebVisits">{t('traffic')}</MenuItem>
<MenuItem value="stars">{t('stars')}</MenuItem>
</Select>
</FormControl>
{stableSort(
appList.filter((item) => item[sortFunctionName] !== undefined),
sortFunction,
).map((app) => (
<div key={app.title}>
<Typography component="h2" variant="h4" gutterBottom className={classes.title}>
<span>{app.title}</span>
{app.source ? (
<IconButton
href={app.source}
target="_blank"
aria-label={`${app.title} ${t('sourceCode')}`}
>
<GitHubIcon />
</IconButton>
) : null}
</Typography>
{app.image ? (
<Card className={classes.card}>
<CardMedia
component="a"
href={app.link}
rel="noopener"
target="_blank"
className={classes.cardMedia}
image={`/static/images/showcase/${app.image}`}
title={app.title}
/>
</Card>
) : (
<Link
variant="body2"
target="_blank"
rel="noopener nofollow"
href={app.link}
gutterBottom
>
{t('visit')}
</Link>
)}
<Typography gutterBottom>{app.description}</Typography>
<Typography
variant="caption"
display="block"
color="textSecondary"
className={classes.description}
>
{app.dateAdded}
</Typography>
</div>
))}
</div>
);
}
Showcase.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(Showcase);
|
Paths/React/05.Building Scalable React Apps/3-react-boilerplate-building-scalable-apps-m3-exercise-files/Before/app/containers/NavigationContainer/index.js | phiratio/Pluralsight-materials | /*
*
* NavigationContainer
*
*/
import React from 'react';
import { connect } from 'react-redux';
import selectNavigationContainer from './selectors';
import Navigation from '../../components/Navigation';
export class NavigationContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<Navigation {...this.props} />
);
}
}
const mapStateToProps = selectNavigationContainer();
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(NavigationContainer);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.