path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/client.js | pavlosvos/krifominima | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import 'babel-polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import FastClick from 'fastclick';
import UniversalRouter from 'universal-router';
import queryString from 'query-string';
import { createPath } from 'history/PathUtils';
import history from './core/history';
import App from './components/App';
import { ErrorReporter, deepForceUpdate } from './core/devUtils';
// Global (context) variables that can be easily accessed from any React component
// https://facebook.github.io/react/docs/context.html
const context = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: (...styles) => {
// eslint-disable-next-line no-underscore-dangle
const removeCss = styles.map(x => x._insertCss());
return () => { removeCss.forEach(f => f()); };
},
};
function updateTag(tagName, keyName, keyValue, attrName, attrValue) {
const node = document.head.querySelector(`${tagName}[${keyName}="${keyValue}"]`);
if (node && node.getAttribute(attrName) === attrValue) return;
// Remove and create a new tag in order to make it work with bookmarks in Safari
if (node) {
node.parentNode.removeChild(node);
}
if (typeof attrValue === 'string') {
const nextNode = document.createElement(tagName);
nextNode.setAttribute(keyName, keyValue);
nextNode.setAttribute(attrName, attrValue);
document.head.appendChild(nextNode);
}
}
function updateMeta(name, content) {
updateTag('meta', 'name', name, 'content', content);
}
function updateCustomMeta(property, content) { // eslint-disable-line no-unused-vars
updateTag('meta', 'property', property, 'content', content);
}
function updateLink(rel, href) { // eslint-disable-line no-unused-vars
updateTag('link', 'rel', rel, 'href', href);
}
// Switch off the native scroll restoration behavior and handle it manually
// https://developers.google.com/web/updates/2015/09/history-api-scroll-restoration
const scrollPositionsHistory = {};
if (window.history && 'scrollRestoration' in window.history) {
window.history.scrollRestoration = 'manual';
}
let onRenderComplete = function initialRenderComplete() {
const elem = document.getElementById('css');
if (elem) elem.parentNode.removeChild(elem);
onRenderComplete = function renderComplete(route, location) {
document.title = route.title;
updateMeta('description', route.description);
// Update necessary tags in <head> at runtime here, ie:
// updateMeta('keywords', route.keywords);
// updateCustomMeta('og:url', route.canonicalUrl);
// updateCustomMeta('og:image', route.imageUrl);
// updateLink('canonical', route.canonicalUrl);
// etc.
let scrollX = 0;
let scrollY = 0;
const pos = scrollPositionsHistory[location.key];
if (pos) {
scrollX = pos.scrollX;
scrollY = pos.scrollY;
} else {
const targetHash = location.hash.substr(1);
if (targetHash) {
const target = document.getElementById(targetHash);
if (target) {
scrollY = window.pageYOffset + target.getBoundingClientRect().top;
}
}
}
// Restore the scroll position if it was saved into the state
// or scroll to the given #hash anchor
// or scroll to top of the page
window.scrollTo(scrollX, scrollY);
// Google Analytics tracking. Don't send 'pageview' event after
// the initial rendering, as it was already sent
if (window.ga) {
window.ga('send', 'pageview', createPath(location));
}
};
};
// Make taps on links and buttons work fast on mobiles
FastClick.attach(document.body);
const container = document.getElementById('app');
let appInstance;
let currentLocation = history.location;
let routes = require('./routes').default;
// Re-render the app when window.location changes
async function onLocationChange(location) {
// Remember the latest scroll position for the previous location
scrollPositionsHistory[currentLocation.key] = {
scrollX: window.pageXOffset,
scrollY: window.pageYOffset,
};
// Delete stored scroll position for next page if any
if (history.action === 'PUSH') {
delete scrollPositionsHistory[location.key];
}
currentLocation = location;
try {
// Traverses the list of routes in the order they are defined until
// it finds the first route that matches provided URL path string
// and whose action method returns anything other than `undefined`.
const route = await UniversalRouter.resolve(routes, {
path: location.pathname,
query: queryString.parse(location.search),
});
// Prevent multiple page renders during the routing process
if (currentLocation.key !== location.key) {
return;
}
if (route.redirect) {
history.replace(route.redirect);
return;
}
appInstance = ReactDOM.render(
<App context={context}>{route.component}</App>,
container,
() => onRenderComplete(route, location),
);
} catch (error) {
console.error(error); // eslint-disable-line no-console
// Current url has been changed during navigation process, do nothing
if (currentLocation.key !== location.key) {
return;
}
// Display the error in full-screen for development mode
if (process.env.NODE_ENV !== 'production') {
appInstance = null;
document.title = `Error: ${error.message}`;
ReactDOM.render(<ErrorReporter error={error} />, container);
return;
}
// Avoid broken navigation in production mode by a full page reload on error
window.location.reload();
}
}
// Handle client-side navigation by using HTML5 History API
// For more information visit https://github.com/mjackson/history#readme
history.listen(onLocationChange);
onLocationChange(currentLocation);
// Enable Hot Module Replacement (HMR)
if (module.hot) {
module.hot.accept('./routes', () => {
routes = require('./routes').default; // eslint-disable-line global-require
if (appInstance) {
try {
// Force-update the whole tree, including components that refuse to update
deepForceUpdate(appInstance);
} catch (error) {
appInstance = null;
document.title = `Hot Update Error: ${error.message}`;
ReactDOM.render(<ErrorReporter error={error} />, container);
return;
}
}
onLocationChange(currentLocation);
});
}
|
packages/bonde-admin-canary/src/components/Tutorial/Dialog/index.js | ourcities/rebu-client | import React from 'react'
import PropTypes from 'prop-types'
import Context from '../Context'
import DialogTooltip from './DialogTooltip'
export class RegisterDialog extends React.Component {
componentDidMount () {
const { name, context } = this.props
context.registerStep(name)
}
render () {
const { context, ...props } = this.props
return context.currentStep === props.step ? (
<DialogTooltip
total={context.total}
currentStep={context.currentStep}
onNext={context.onNext}
onClose={context.onClose}
{...props}
/>
) : props.children
}
}
const Dialog = (props) => (
<Context.Consumer>
{context => <RegisterDialog context={context} {...props} />}
</Context.Consumer>
)
Dialog.propTypes = {
name: PropTypes.string.isRequired,
step: PropTypes.number.isRequired
}
export default Dialog
|
src/js/components/icons/base/PlatformFreebsd.js | kylebyerly-hp/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}-platform-freebsd`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'platform-freebsd');
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 fillRule="evenodd" d="M23.7253418,0.403330656 C24.9975688,1.67496208 21.4706794,7.26490597 20.8744345,7.86115088 C20.2781896,8.45650302 18.7637754,7.90875554 17.4918461,6.63682558 C16.2196191,5.36519416 15.6715737,3.85048208 16.2678187,3.25423717 C16.8640636,2.65769514 22.4534125,-0.868896418 23.7253418,0.403330656 L23.7253418,0.403330656 Z M5.88500669,1.74874919 C3.94274831,0.64670772 1.17931401,-0.579104582 0.300120884,0.300088547 C-0.590973233,1.19058772 0.680063246,4.01650237 1.79341076,5.96233113 C2.78417662,4.23935071 4.19415887,2.78890453 5.88500669,1.74874919 L5.88500669,1.74874919 Z M21.785166,7.42259564 C21.9639794,8.02925383 21.9315489,8.53058725 21.6417578,8.81978414 C20.9639901,9.49755113 19.1338994,8.77634479 17.4844083,7.20599597 C17.3689674,7.10275387 17.2550141,6.99564356 17.1428465,6.88317878 C16.5466016,6.28633892 16.0821617,5.65081997 15.785527,5.06617893 C15.2077288,4.02989107 15.0631307,3.11410221 15.4999004,2.67762963 C15.7379223,2.43960776 16.1187574,2.37474692 16.583198,2.45864948 C16.8863778,2.2673395 17.2437081,2.05371455 17.6358493,1.83503223 C16.0414007,1.00344305 14.2288637,0.533647279 12.305647,0.533647279 C5.92785039,0.533647279 0.757122899,5.70348271 0.757122899,12.0821714 C0.757122899,18.4596702 5.92785039,23.6301005 12.305647,23.6301005 C18.683741,23.6301005 23.8544685,18.4596702 23.8544685,12.0821714 C23.8544685,10.0223894 23.313861,8.09084213 22.3692121,6.41635843 C22.1648105,6.78856511 21.9663598,7.12982838 21.785166,7.42259564 L21.785166,7.42259564 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'PlatformFreebsd';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
frontend/containers/form/CaptchaForm.js | datoszs/czech-lawyers | import React from 'react';
import PropTypes from 'prop-types';
import {Form} from 'react-bootstrap';
import {reduxForm, Field} from 'redux-form/immutable';
import Captcha from 'react-google-recaptcha';
import {wrapEventStop} from '../../util';
import {siteKey} from '../../serverAPI';
const CaptchaComponent = ({input, handleSubmit, captchaRef}) => (
<Captcha
onChange={(value) => {
input.onChange(value);
handleSubmit();
}}
sitekey={siteKey}
size="invisible"
ref={captchaRef}
/>
);
CaptchaComponent.propTypes = {
input: PropTypes.shape({
onChange: PropTypes.func.isRequired,
}).isRequired,
handleSubmit: PropTypes.func.isRequired,
captchaRef: PropTypes.func.isRequired,
};
const CaptchaFormComponent = ({inline, children, handleSubmit}) => {
let captcha;
return (
<Form inline={inline} onSubmit={wrapEventStop(() => captcha.execute())}>
{children}
<Field
name="captcha_token"
component={CaptchaComponent}
handleSubmit={handleSubmit}
captchaRef={(component) => {
captcha = component;
}}
/>
</Form>
);
};
CaptchaFormComponent.propTypes = {
inline: PropTypes.bool,
children: PropTypes.node.isRequired,
handleSubmit: PropTypes.func.isRequired,
};
CaptchaFormComponent.defaultProps = {
inline: false,
};
const onSubmit = (values, dispatch, {action}) => dispatch(action(values));
const CaptchaForm = (reduxForm({onSubmit})(CaptchaFormComponent));
CaptchaForm.propTypes = {
form: PropTypes.string.isRequired,
action: PropTypes.func.isRequired,
};
export default CaptchaForm;
|
packages/bonde-admin/src/pages/admin/container.js | ourcities/rebu-client | import React from 'react'
import { Switch } from 'react-router-dom'
import { graphql } from 'react-apollo'
import FetchCurrentUser from '@/account/queries/current-user'
import { connect } from 'react-redux'
import { load } from '@/account/redux/action-creators'
import { Loading } from '@/components/await'
// Routes
import BetaBotPage from './bot'
import CommunityListPage from './communities/list'
import CommunityCreatePage from './communities/create'
import SidebarContainer from './sidebar'
import PrivateRoute from './private-route'
class Logged extends React.Component {
componentDidMount () {
if (this.props.user) {
this.props.load(this.props.user)
}
}
componentWillReceiveProps (nextProps) {
if (!this.props.user && nextProps.user) {
this.props.load(nextProps.user)
}
}
render () {
return this.props.loading ? <Loading /> : (
<Switch>
<PrivateRoute
exact
path='/bot'
component={BetaBotPage}
/>
<PrivateRoute
exact
path='/communities'
component={CommunityListPage}
/>
<PrivateRoute
exact
path='/communities/new'
component={CommunityCreatePage}
/>
<PrivateRoute
path='/'
component={SidebarContainer}
/>
</Switch>
)
}
}
const config = {
options: { fetchPolicy: 'network-only' },
props: ({ ownProps, data: { loading, currentUser } }) => ({
loading,
user: currentUser
})
}
export default graphql(FetchCurrentUser, config)(
connect(undefined, { load })(Logged)
)
|
app/javascript/mastodon/features/public_timeline/index.js | rekif/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandPublicTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import ColumnSettingsContainer from './containers/column_settings_container';
import { connectPublicStream } from '../../actions/streaming';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = (state, { onlyMedia, columnId }) => {
const uuid = columnId;
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === uuid);
return {
hasUnread: state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`, 'unread']) > 0,
onlyMedia: (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']),
};
};
export default @connect(mapStateToProps)
@injectIntl
class PublicTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static defaultProps = {
onlyMedia: false,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasUnread: PropTypes.bool,
onlyMedia: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch, onlyMedia } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('PUBLIC', { other: { onlyMedia } }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, onlyMedia } = this.props;
dispatch(expandPublicTimeline({ onlyMedia }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia }));
}
componentDidUpdate (prevProps) {
if (prevProps.onlyMedia !== this.props.onlyMedia) {
const { dispatch, onlyMedia } = this.props;
this.disconnect();
dispatch(expandPublicTimeline({ onlyMedia }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia }));
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { dispatch, onlyMedia } = this.props;
dispatch(expandPublicTimeline({ maxId, onlyMedia }));
}
handleSettingChanged = (key, checked) => {
const { columnId } = this.props;
if (!columnId && key[0] === 'other' && key[1] === 'onlyMedia') {
this.context.router.history.replace(`/timelines/public${checked ? '/media' : ''}`);
}
}
render () {
const { intl, shouldUpdateScroll, columnId, hasUnread, multiColumn, onlyMedia } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer onChange={this.handleSettingChanged} columnId={columnId} />
</ColumnHeader>
<StatusListContainer
timelineId={`public${onlyMedia ? ':media' : ''}`}
onLoadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other instances to fill it up' />}
shouldUpdateScroll={shouldUpdateScroll}
/>
</Column>
);
}
}
|
src/components/Button/ButtonAnchor.js | GetAmbassador/react-ions | import React from 'react'
import PropTypes from 'prop-types'
import { Link } from 'react-router'
import style from './style.scss'
import classNames from 'classnames/bind'
const ButtonAnchor = props => {
const cx = classNames.bind(style)
const collapseClass = props.collapse ? 'collapse' : null
const btnAnchorClasses = cx(style.btn, props.optClass, props.className, props.size, collapseClass)
let buttonAnchor
const handleClick = e => {
if (props.disabled) {
e.preventDefault()
}
}
if (props.internal) {
buttonAnchor = <Link
to={props.path}
className={btnAnchorClasses}
size={props.size}
disabled={props.disabled}
onClick={handleClick}
style={props.style}>
{props.children}
</Link>
} else {
buttonAnchor = <a href={props.path} className={btnAnchorClasses} target={props.target} disabled={props.disabled} onClick={handleClick}>{props.children}</a>
}
return buttonAnchor
}
ButtonAnchor.propTypes = {
/**
* A string to allow for inline styles
*/
style: PropTypes.string,
/**
* A class name to be used for local styles or integrations (required to support styled-components)
**/
className: PropTypes.string,
/**
* Optional styles to add to the button.
*/
optClass: PropTypes.string,
/**
* The size of button.
*/
size: PropTypes.string,
/**
* Whether the button is disabled.
*/
disabled: PropTypes.bool,
/**
* A path to pass to the anchor tag.
*/
path: PropTypes.string,
/**
* Whether the link it to an internal page, or external (default)
*/
internal: PropTypes.bool,
/**
* Whether to display only an icon on small screens
*/
collapse: PropTypes.bool
}
export default ButtonAnchor
|
src/Card/CardSubtitle.js | kradio3/react-mdc-web | import PropTypes from 'prop-types';
import React from 'react';
import classnames from 'classnames';
const propTypes = {
className: PropTypes.string,
children: PropTypes.node,
};
const CardSubtitle = ({ className, children }) => (
<h2
className={classnames('mdc-card__subtitle', className)}
>
{children}
</h2>
);
CardSubtitle.propTypes = propTypes;
export default CardSubtitle;
|
app/containers/LoginCallback/index.js | belongapp/belong | import React from 'react';
import { connect } from 'react-redux';
import { loginCallbackRequest } from './actions';
export class LoginCallback extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
dispatchLoginCallbackRequest: React.PropTypes.func.isRequired,
};
componentWillMount() {
this.props.dispatchLoginCallbackRequest();
}
render() {
return <span>Welcome back, one moment please...</span>;
}
}
export function mapDispatchToProps(dispatch) {
return {
dispatchLoginCallbackRequest() {
dispatch(loginCallbackRequest());
},
};
}
export default connect(null, mapDispatchToProps)(LoginCallback);
|
test/helpers.js | zerkms/react-bootstrap | import React from 'react';
import { cloneElement } from 'react';
export function shouldWarn(about) {
console.warn.called.should.be.true;
console.warn.calledWithMatch(about).should.be.true;
console.warn.reset();
}
/**
* Helper for rendering and updating props for plain class Components
* since `setProps` is deprecated.
* @param {ReactElement} element Root element to render
* @param {HTMLElement?} mountPoint Optional mount node, when empty it uses an unattached div like `renderIntoDocument()`
* @return {ComponentInstance} The instance, with a new method `renderWithProps` which will return a new instance with updated props
*/
export function render(element, mountPoint){
let mount = mountPoint || document.createElement('div');
let instance = React.render(element, mount);
if (!instance.renderWithProps) {
instance.renderWithProps = function(newProps) {
return render(
cloneElement(element, newProps), mount);
};
}
return instance;
}
|
static/src/components/Layout.js | Termnator/mikebot | // @flow
import React from 'react';
import ReactDOM from 'react-dom';
import AirhornStatsStore from '../stores/AirhornStatsStore';
import Cloud from './Cloud';
import IslandPond from './islands/IslandPond';
import IslandTree from './islands/IslandTree';
import IslandTrees from './islands/IslandTrees';
import IslandTent from './islands/IslandTent';
import IslandDoubleTree from './islands/IslandDoubleTree';
import IslandForest from './islands/IslandForest';
import IslandLog from './islands/IslandLog';
import IslandShrooms from './islands/IslandShrooms';
import IslandSmall from './islands/IslandSmall';
import Content from './Content';
import Footer from './Footer';
import StatsPanel from './StatsPanel';
import Parallax from '../libs/parallax';
import ReactTooltip from 'react-tooltip';
import Browser from 'detect-browser';
import Constants from '../Constants';
import '../style/style.styl';
const REF_PARALLAX = 'PARALLAX_REF';
const REF_SMALL_ISLANDS = "SMALL_ISLANDS_REF";
const REF_LARGE_ISLANDS = "LARGE_ISLANDS_REF";
const REF_FOOTER = "FOOTER_REF";
type State = {
count: number,
uniqueUsers: number,
uniqueGuilds: number,
uniqueChannels: number,
secretCount: number,
showStats: boolean,
statsHasBeenShown: boolean,
changeCount: boolean,
pausedSmallIslands: Array<boolean>,
pausedLargeIslands: Array<boolean>,
footerHeight: number
};
let changeCountTimeout: number;
function isVisible(el, num): boolean {
const rect = el.getBoundingClientRect();
return ((rect.top >= -20 && rect.top <= window.innerHeight) ||
(rect.bottom >= -20 && rect.bottom <= window.innerHeight)) &&
((rect.left >= -20 && rect.left <= window.innerWidth) ||
(rect.right >= -20 && rect.right <= window.innerWidth));
}
const Layout = React.createClass({
getInitialState(): State {
const pausedLargeIslands = [false];
const pausedSmallIslands = [];
for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
pausedSmallIslands.push(false);
}
for (let i = 0; i < Constants.LARGE_ISLAND_COUNT; i++) {
pausedLargeIslands.push(false);
}
return {
count: 0,
uniqueUsers: 0,
uniqueGuilds: 0,
uniqueChannels: 0,
secretCount: 0,
showStats: false,
statsHasBeenShown: false,
changeCount: false,
pausedLargeIslands,
pausedSmallIslands,
footerHeight: 80
};
},
componentWillMount() {
AirhornStatsStore.on('change', this.updateStats);
window.addEventListener('resize', this.resized);
},
componentDidMount() {
new Parallax(this.refs[REF_PARALLAX]);
setTimeout(() => this.resized(), 100);
},
resized() {
const pausedSmallIslands = [];
for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
const visible = isVisible(this.refs[REF_SMALL_ISLANDS].children[i], i);
pausedSmallIslands.push(!visible);
}
const pausedLargeIslands = [];
for (let i = 0; i < Constants.LARGE_ISLAND_COUNT; i++) {
const visible = isVisible(this.refs[REF_LARGE_ISLANDS].children[i], i);
pausedLargeIslands.push(!visible);
}
const footerHeight = ReactDOM.findDOMNode(this.refs[REF_FOOTER]).getBoundingClientRect().height;
this.setState({
pausedSmallIslands,
pausedLargeIslands,
footerHeight
});
},
updateStats() {
this.setState({
count: AirhornStatsStore.getCount(),
uniqueUsers: AirhornStatsStore.getUniqueUsers(),
uniqueGuilds: AirhornStatsStore.getUniqueGuilds(),
uniqueChannels: AirhornStatsStore.getUniqueChannels(),
secretCount: AirhornStatsStore.getSecretCount(),
showStats: AirhornStatsStore.shouldShowStatsPanel(),
statsHasBeenShown: this.state.statsHasBeenShown || AirhornStatsStore.shouldShowStatsPanel(),
changeCount: this.state.count != AirhornStatsStore.getCount()
});
clearTimeout(changeCountTimeout);
changeCountTimeout = setTimeout(
this.finishChangeCountAnimation,
Constants.Animation.COUNT_CHANGE_TIME);
},
finishChangeCountAnimation() {
this.setState({
changeCount: false
});
},
render() {
const smallIslands = [];
for (let i = 0; i < Constants.SMALL_ISLAND_COUNT; i++) {
const type = i % Constants.UNIQUE_SMALL_ISLAND_COUNT;
smallIslands.push(<IslandSmall number={i} type={type} key={i} paused={this.state.pausedSmallIslands[i]} />);
}
const clouds = [];
for (let i = 0; i < Constants.CLOUD_COUNT; i++) {
const type = i % Constants.UNIQUE_CLOUD_COUNT;
clouds.push(<Cloud number={i} type={type} key={i} />);
}
let toolTip;
if (!this.state.showStats) {
toolTip = <ReactTooltip effect="solid" type="light" class="tool-tip" offset={{top: -8}} />;
}
return (
<div className={`container ${Browser.name}`}>
<Content />
<div ref={REF_LARGE_ISLANDS}>
<IslandPond paused={this.state.pausedLargeIslands[0]} />
<IslandTree paused={this.state.pausedLargeIslands[1]} />
<IslandTrees paused={this.state.pausedLargeIslands[2]} />
<IslandTent paused={this.state.pausedLargeIslands[3]} />
<IslandDoubleTree paused={this.state.pausedLargeIslands[4]} />
<IslandForest paused={this.state.pausedLargeIslands[5]} />
<IslandForest paused={this.state.pausedLargeIslands[6]} number="1" />
<IslandLog paused={this.state.pausedLargeIslands[7]} />
<IslandShrooms paused={this.state.pausedLargeIslands[8]} />
<IslandShrooms paused={this.state.pausedLargeIslands[9]} number="1" />
</div>
<div ref={REF_SMALL_ISLANDS}>{smallIslands}</div>
<div id="parallax" ref={REF_PARALLAX}>
{clouds}
</div>
<StatsPanel
show={this.state.showStats}
count={this.state.count}
uniqueUsers={this.state.uniqueUsers}
uniqueGuilds={this.state.uniqueGuilds}
uniqueChannels={this.state.uniqueChannels}
secretCount={this.state.secretCount}
hasBeenShown={this.state.statsHasBeenShown}
bottom={this.state.footerHeight} />
<Footer
ref={REF_FOOTER}
count={this.state.count}
changeCount={this.state.changeCount}
showStatsPanel={this.state.showStats}
statsHasBeenShown={this.state.statsHasBeenShown} />
{toolTip}
</div>
);
}
});
export default Layout;
|
app/javascript/mastodon/features/compose/components/upload.js | danhunsaker/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
export default class Upload extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
onUndo: PropTypes.func.isRequired,
onOpenFocalPoint: PropTypes.func.isRequired,
};
handleUndoClick = e => {
e.stopPropagation();
this.props.onUndo(this.props.media.get('id'));
}
handleFocalPointClick = e => {
e.stopPropagation();
this.props.onOpenFocalPoint(this.props.media.get('id'));
}
render () {
const { media } = this.props;
const focusX = media.getIn(['meta', 'focus', 'x']);
const focusY = media.getIn(['meta', 'focus', 'y']);
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
return (
<div className='compose-form__upload' tabIndex='0' role='button'>
<Motion defaultStyle={{ scale: 0.8 }} style={{ scale: spring(1, { stiffness: 180, damping: 12 }) }}>
{({ scale }) => (
<div className='compose-form__upload-thumbnail' style={{ transform: `scale(${scale})`, backgroundImage: `url(${media.get('preview_url')})`, backgroundPosition: `${x}% ${y}%` }}>
<div className={classNames('compose-form__upload__actions', { active: true })}>
<button className='icon-button' onClick={this.handleUndoClick}><Icon id='times' /> <FormattedMessage id='upload_form.undo' defaultMessage='Delete' /></button>
<button className='icon-button' onClick={this.handleFocalPointClick}><Icon id='pencil' /> <FormattedMessage id='upload_form.edit' defaultMessage='Edit' /></button>
</div>
</div>
)}
</Motion>
</div>
);
}
}
|
react/features/notifications/components/native/Notification.js | bgrozev/jitsi-meet | // @flow
import React from 'react';
import { Text, TouchableOpacity, View } from 'react-native';
import { translate } from '../../../base/i18n';
import { Icon, IconClose } from '../../../base/icons';
import AbstractNotification, {
type Props
} from '../AbstractNotification';
import styles from './styles';
/**
* Implements a React {@link Component} to display a notification.
*
* @extends Component
*/
class Notification extends AbstractNotification<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
isDismissAllowed
} = this.props;
return (
<View
pointerEvents = 'box-none'
style = { styles.notification }>
<View style = { styles.contentColumn }>
<View
pointerEvents = 'box-none'
style = { styles.notificationContent }>
{
this._renderContent()
}
</View>
</View>
{
isDismissAllowed
&& <TouchableOpacity onPress = { this._onDismissed }>
<Icon
src = { IconClose }
style = { styles.dismissIcon } />
</TouchableOpacity>
}
</View>
);
}
/**
* Renders the notification's content. If the title or title key is present
* it will be just the title. Otherwise it will fallback to description.
*
* @returns {Array<ReactElement>}
* @private
*/
_renderContent() {
const { t, title, titleArguments, titleKey } = this.props;
const titleText = title || (titleKey && t(titleKey, titleArguments));
const description = this._getDescription();
if (description && description.length) {
return description.map((line, index) => (
<Text
key = { index }
numberOfLines = { 1 }
style = { styles.contentText }>
{ line }
</Text>
));
}
return (
<Text
numberOfLines = { 1 }
style = { styles.contentText } >
{ titleText }
</Text>
);
}
_getDescription: () => Array<string>;
_onDismissed: () => void;
}
export default translate(Notification);
|
src/svg-icons/hardware/security.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSecurity = (props) => (
<SvgIcon {...props}>
<path d="M12 1L3 5v6c0 5.55 3.84 10.74 9 12 5.16-1.26 9-6.45 9-12V5l-9-4zm0 10.99h7c-.53 4.12-3.28 7.79-7 8.94V12H5V6.3l7-3.11v8.8z"/>
</SvgIcon>
);
HardwareSecurity = pure(HardwareSecurity);
HardwareSecurity.displayName = 'HardwareSecurity';
HardwareSecurity.muiName = 'SvgIcon';
export default HardwareSecurity;
|
src/js/components/ui/Textarea/Textarea.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './Textarea.scss';
export default class Textarea extends Component {
static propTypes = {
placeholder : PropTypes.string,
defaultValue: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
onChange : PropTypes.func
};
constructor(props) {
super(props);
this.state = {
empty: !props.defaultValue,
focused: false
};
this.onChange = this.onChange.bind(this);
this.getValue = this.getValue.bind(this);
}
setValue(value) {
if (this.refs.textarea) {
this.refs.textarea.value = value;
}
}
getValue() {
return this.refs.textarea ? this.refs.textarea.value : null;
}
onChange() {
if (this.props.onChange) {
this.props.onChange(this.getValue());
}
this.setState({empty: !this.getValue()});
}
render() {
const {placeholder, defaultValue} = this.props;
const {empty} = this.state;
return (
<div className={styles.inputWrapper}>
<div className={styles.input}>
<textarea ref="textarea" placeholder={placeholder} value={this.state.value} onChange={this.onChange} defaultValue={defaultValue} />
</div>
</div>
);
}
} |
app/javascript/mastodon/features/compose/components/reply_indicator.js | TheInventrix/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from '../../../components/avatar';
import IconButton from '../../../components/icon_button';
import DisplayName from '../../../components/display_name';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { isRtl } from '../../../rtl';
const messages = defineMessages({
cancel: { id: 'reply_indicator.cancel', defaultMessage: 'Cancel' },
});
export default @injectIntl
class ReplyIndicator extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map,
onCancel: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onCancel();
}
handleAccountClick = (e) => {
if (e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
}
render () {
const { status, intl } = this.props;
if (!status) {
return null;
}
const content = { __html: status.get('contentHtml') };
const style = {
direction: isRtl(status.get('search_index')) ? 'rtl' : 'ltr',
};
return (
<div className='reply-indicator'>
<div className='reply-indicator__header'>
<div className='reply-indicator__cancel'><IconButton title={intl.formatMessage(messages.cancel)} icon='times' onClick={this.handleClick} inverted /></div>
<a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='reply-indicator__display-name'>
<div className='reply-indicator__display-avatar'><Avatar account={status.get('account')} size={24} /></div>
<DisplayName account={status.get('account')} />
</a>
</div>
<div className='reply-indicator__content' style={style} dangerouslySetInnerHTML={content} />
</div>
);
}
}
|
src/svg-icons/notification/time-to-leave.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationTimeToLeave = (props) => (
<SvgIcon {...props}>
<path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/>
</SvgIcon>
);
NotificationTimeToLeave = pure(NotificationTimeToLeave);
NotificationTimeToLeave.displayName = 'NotificationTimeToLeave';
NotificationTimeToLeave.muiName = 'SvgIcon';
export default NotificationTimeToLeave;
|
hops/src/App.js | Hops-401/hops-native | import React, { Component } from 'react';
import { StyleSheet, Text, View, AppRegistry } from 'react-native';
import { NativeRouter, Route, Link, Switch } from 'react-router-native';
import Home from './components/home';
import LoginContainer from './containers/LoginContainer';
import SignUpContainer from './containers/SignUpContainer';
function requireAuth(nextState, replace) {
if (!this.props.isLoggedIn) {
replace({
pathname: '/login'
})
}
}
export default class app extends Component {
render() {
return (
<NativeRouter>
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/login" component={LoginContainer} />
<Route exact path="/signup" component={SignUpContainer} />
</Switch>
</NativeRouter>
);
};
};
AppRegistry.registerComponent('app', () => app); |
docs/app/Examples/modules/Accordion/Variations/AccordionExampleInverted.js | clemensw/stardust | import _ from 'lodash'
import faker from 'faker'
import React from 'react'
import { Accordion, Segment } from 'semantic-ui-react'
const panels = _.times(3, () => ({
title: faker.lorem.sentence(),
content: faker.lorem.paragraphs(),
}))
const AccordionExampleInverted = () => (
<Segment inverted>
<Accordion panels={panels} inverted />
</Segment>
)
export default AccordionExampleInverted
|
miniact3/client/index.js | eliorivero/miniact | import React from 'react';
import ReactDOM from 'react-dom';
class DaleReact extends React.Component {
render() {
return <div>{ this.props.app } listo en React!</div>;
}
}
ReactDOM.render(<DaleReact app="Miniact" />, document.getElementById( 'miniact' ) ); |
modules/pages/client/components/FaqTribes.component.js | Trustroots/trustroots | import React from 'react';
import Faq from '@/modules/pages/client/components/Faq.component.js';
import { Trans, useTranslation } from 'react-i18next';
export default function FaqTribes() {
const { t } = useTranslation('pages');
return (
<Faq category="circles">
<div className="faq-question" id="what-are-circles">
<h3>{t('What are circles?')}</h3>
{t(
'Trustroots circles (previously known as "tribes") are a way for you to immediately find the people you will easily connect with.',
)}
<br />
<br />
<Trans t={t} ns="pages">
You can start now by joining <a href="/circles">circles</a> that you
identify yourself with.
</Trans>
<br />
<br />
{t('When searching for hosts, you can filter members by circles.')}
<br />
<br />
{t(
'Your circles will also show up in your profile, telling others more about you.',
)}
<br />
<br />
{t(
"We'll aim to add ways to the site that will fill your trips and your life with adventure! Imagine walking around in a city you're visiting for the first time and suddently you start receiving invitations from people to stay with them or go to awesome or inspiring events, or just to a dumpster dive dinner. That's the adventure Trustroots wants to enable. And circles is a step towards this.",
)}
<br />
<br />
<Trans t={t} ns="pages">
See also{' '}
<a href="https://ideas.trustroots.org/2016/05/09/introducing-trustroots-tribes/">
the blog post
</a>{' '}
introducing circles.
</Trans>
</div>
<div className="faq-question" id="no-suitable-circles">
<h3>{t("I don't find a circle that suits me")}</h3>
<Trans t={t} ns="pages">
<a href="/support">Send us</a> new circle ideas! In the future you
will be able to create new circles by yourself.
</Trans>
</div>
<div className="faq-question" id="tribes-rename-to-circles">
<h3>{t('Why did you rename "tribes" to "circles"?')}</h3>
{t(
'We found the term be problematic for having connotations of colonialism and wanted to switch to a more inclusive term in August 2020.',
)}
<br />
<br />
<a href="https://ideas.trustroots.org/2020/08/04/introducing-circles/">
{t('Read more')}
</a>
</div>
</Faq>
);
}
FaqTribes.propTypes = {};
|
app/jsx/context_cards/SubmissionProgressBars.js | venturehive/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import I18n from 'i18n!student_context_tray'
import classnames from 'classnames'
import Heading from 'instructure-ui/lib/components/Heading'
import Progress from 'instructure-ui/lib/components/Progress'
import Tooltip from 'instructure-ui/lib/components/Tooltip'
import Typography from 'instructure-ui/lib/components/Typography'
import Link from 'instructure-ui/lib/components/Link'
class SubmissionProgressBars extends React.Component {
static propTypes = {
submissions: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
score: PropTypes.number,
user: PropTypes.shape({
_id: PropTypes.string.isRequired
}).isRequired,
assignment: PropTypes.shape({
html_url: PropTypes.string.isRequired,
points_possible: PropTypes.number,
})
}).isRequired
).isRequired,
}
static displayGrade (submission) {
const {score, grade, excused} = submission
const pointsPossible = submission.assignment.points_possible
let display
if (excused) {
display = 'EX'
} else if (grade.match(/%/)) {
// Grade is a percentage, just show it
display = grade
} else if (grade.match(/complete/)) {
// Grade is complete/incomplete, show icon
display = SubmissionProgressBars.renderIcon(grade)
} else {
// Default to show score out of points possible
display = `${score}/${pointsPossible}`
}
return display
}
static displayScreenreaderGrade (submission) {
const {score, grade, excused} = submission
const pointsPossible = submission.assignment.points_possible
let display
if (excused) {
display = I18n.t('excused')
} else if (grade.match(/%/) || grade.match(/complete/)) {
// Grade is a percentage or in/complete, just show it
display = grade
} else {
// Default to show score out of points possible
display = `${score}/${pointsPossible}`
}
return display
}
static renderIcon (grade) {
const iconClass = classnames({
'icon-check': grade === 'complete',
'icon-x': grade === 'incomplete'
})
return (
<div>
<span className='screenreader-only'>
{I18n.t("%{grade}", {grade: grade})}
</span>
<i className={iconClass}></i>
</div>
)
}
render () {
const {submissions} = this.props
if (submissions.length > 0) {
return (
<section
className="StudentContextTray__Section StudentContextTray-Progress">
<Heading level="h4" as="h3" border="bottom">
{I18n.t("Last %{length} Graded Items", {length: submissions.length})}
</Heading>
{submissions.map((submission) => {
return (
<div key={submission.id} className="StudentContextTray-Progress__Bar">
<Tooltip
tip={submission.assignment.name}
as={Link}
href={`${submission.assignment.html_url}/submissions/${submission.user_id}`}
placement="top"
>
<Progress
size="small"
successColor={false}
label={I18n.t('Grade')}
valueMax={submission.assignment.points_possible}
valueNow={submission.score || 0}
formatValueText={() => SubmissionProgressBars.displayScreenreaderGrade(submission)}
formatDisplayedValue={() => (
<Typography size="x-small" color="secondary">
{SubmissionProgressBars.displayGrade(submission)}
</Typography>
)}
/>
</Tooltip>
</div>
)
})}
</section>
)
} else { return null }
}
}
export default SubmissionProgressBars
|
src/svg-icons/editor/monetization-on.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMonetizationOn = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H14.3c-.05-1.11-.64-1.87-2.22-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z"/>
</SvgIcon>
);
EditorMonetizationOn = pure(EditorMonetizationOn);
EditorMonetizationOn.displayName = 'EditorMonetizationOn';
EditorMonetizationOn.muiName = 'SvgIcon';
export default EditorMonetizationOn;
|
components/BookDetailApp/BookDetailApp.react.js | react-douban/douban-book-web | import React from 'react'
import { render } from 'react-dom'
import request from 'request'
import BookDetail from './BookDetail.react'
import Config from '../Config.react'
const BookDetailApp = React.createClass({
getInitialState() {
return {
book: {},
loading: true
}
},
componentDidMount() {
const bookId = this.props.bookId;
this.fetchBookInfo(bookId);
},
fetchBookInfo(bookId, callback) {
request.get(Config.domain + Config.apiContext + '/search/' + bookId, (err, response, body) => {
if (response.statusCode != 200) {
this.setState({message: body});
if (callback && typeof callback === 'function') {
callback();
}
return;
}
const data = JSON.parse(body);
this.setState({book: data, loading: false});
});
},
render() {
return (
<BookDetail book={this.state.book} loading={this.state.loading} />
);
}
});
export default BookDetailApp;
|
src/containers/Transition/Transition.js | dongxiaofen/react-redux-motion | import React, { Component } from 'react';
import { TransitionDemo } from 'components';
export default class Transition extends Component {
constructor(props) {
super(props);
this.state = {};
}
render() {
return (
<div style={{width: '500px', margin: '0 auto'}}>
<TransitionDemo />
</div>
);
}
}
|
src/components/lists/AddressOutputList.js | openvcash/vcash-electron | import React from 'react'
import List from 'react-list'
import { translate } from 'react-i18next'
import { inject, observer } from 'mobx-react'
/** Component */
import AddressOutputListItem from './AddressOutputListItem.js'
@translate(['common'])
@inject('gui', 'send')
@observer
class AddressOutputList extends React.Component {
constructor(props) {
super(props)
this.t = props.t
this.gui = props.gui
this.send = props.send
}
/**
* Mark or unmark the output for spending.
* @function setOutput
* @param {object} e - Checkbox element event.
*/
setOutput = e => {
this.send.setOutput(e.target.id)
}
render() {
return (
<div>
<div className="flex-sb list-header">
<p>{this.t('txId')}</p>
<p>{this.t('amount')} (XVC)</p>
</div>
<div
className="list-plain"
style={{ maxHeight: this.gui.window.height - 502 }}
>
<List
length={this.send.addrOutputs.length}
itemRenderer={(index, key) => (
<AddressOutputListItem
index={index}
key={key}
gui={this.gui}
send={this.send}
setOutput={this.setOutput}
/>
)}
/>
{this.send.addrOutputs.length === 0 && (
<div className="list-item-plain even">
<div className="flex-center">
<p>{this.t('addrUnused')}</p>
</div>
</div>
)}
</div>
</div>
)
}
}
export default AddressOutputList
|
packages/react-cookie-demo/src/client.js | eXon/react-cookie | import React from 'react';
import ReactDOM from 'react-dom';
import { CookiesProvider } from 'react-cookie';
import App from './components/App';
const appEl = document.getElementById('main-app');
ReactDOM.render(
<CookiesProvider>
<App />
</CookiesProvider>,
appEl
);
|
imports/client/components/About/AboutBand.js | evancorl/skate-scenes | import React from 'react';
import Scroll from 'react-scroll';
const ScrollElement = Scroll.Element;
class AboutBand extends React.Component {
shouldComponentUpdate() {
return false;
}
render() {
const languages = ['HTML', 'CSS', 'JavaScript', 'C#', 'SQL', 'PHP'];
const tools = ['Meteor', 'React', 'Sass', 'ASP.NET', 'MySQL', 'Mongo'];
return (
<ScrollElement name="about" id="about" className="about-band inner-ver">
<div className="inner-hor">
<div className="col-wide">
<h1 className="about-title">About</h1>
<p className="about-text">
I'm a full-stack web and hybrid app developer based in Houston, TX. I made my first
website at age 13 to post skateboarding photos of my friends, and I've been coding
ever since. My experience includes writing core application logic for the back-end,
building REST APIs, database modeling/migration, front-end development using
JavaScript view libraries, and much more. My mission is to continually hone my
coding skills by learning every day and applying best practices.
</p>
<h2 className="about-subtitle">My favorite languages</h2>
<ul className="language-list about-list">
{languages.map((language, i) => (
<li key={i} className="language-item about-item">
{language}
</li>
))}
</ul>
<h2 className="about-subtitle">My favorite tools</h2>
<ul className="tool-list about-list">
{tools.map((tool, i) => (
<li key={i} className="tool-item about-item">
<img className="tool-img" src={`/images/tools/${tool.toLowerCase()}.png`} />
<div className="tool-name">{tool}</div>
</li>
))}
</ul>
</div>
</div>
</ScrollElement>
);
}
}
export default AboutBand;
|
src/interface/report/PlayerSelection/index.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SPECS from 'game/SPECS';
import ROLES from 'game/ROLES';
import PlayerTile from './PlayerTile';
import './PlayerSelection.scss';
const ROLE_SORT_KEY = {
[ROLES.TANK]: 0,
[ROLES.HEALER]: 1,
[ROLES.DPS.MELEE]: 2,
[ROLES.DPS.RANGED]: 2,
};
function sortPlayers(a, b) {
const aSpec = SPECS[a.combatant.specID];
const bSpec = SPECS[b.combatant.specID];
const aRoleSortKey = aSpec ? ROLE_SORT_KEY[aSpec.role] : -1;
const bRoleSortKey = bSpec ? ROLE_SORT_KEY[bSpec.role] : -1;
if (aRoleSortKey !== bRoleSortKey) {
return aRoleSortKey - bRoleSortKey;
}
const aSpecSortKey = aSpec ? aSpec.className : '';
const bSpecSortKey = bSpec ? bSpec.className : '';
if (aSpecSortKey !== bSpecSortKey) {
return aSpecSortKey.localeCompare(bSpecSortKey);
}
return a.name.localeCompare(b.name);
}
const PlayerSelection = ({ players, makeUrl }) => (
<div className="player-selection">
{players.sort(sortPlayers).map(player => (
<PlayerTile key={player.guid} player={player} makeUrl={makeUrl} />
))}
</div>
);
PlayerSelection.propTypes = {
players: PropTypes.arrayOf(PropTypes.object).isRequired,
makeUrl: PropTypes.func.isRequired,
};
export default PlayerSelection;
|
src/client/assets/js/nodes/outputs/export/node.js | me-box/databox-sdk | import React from 'react';
//import composeNode from 'utils/composeNode';
import Textfield from 'components/form/Textfield';
import Select from 'components/form/Select';
import Cell from 'components/Cell';
import Cells from 'components/Cells';
import { formatSchema } from 'utils/utils';
import {configNode} from 'utils/ReactDecorators';
@configNode()
export default class Node extends React.Component {
render() {
const {node,values={},updateNode} = this.props;
const nameprops = {
id: "name",
value: values.name || "",
onChange: (property, event)=>{
updateNode("name", event.target.value);
},
}
const urlsprops = {
id: "urls",
value: values.urls || "",
onChange: (property, event)=>{
updateNode("urls", event.target.value.trim());
},
}
const nameinput = <div className="centered"><Textfield {...nameprops}/></div>
const urlsinput = <div className="centered"><Textfield {...urlsprops}/></div>
return <div>
<Cells>
<Cell title={"name"} content={nameinput}/>
<Cell title={"urls"} content={urlsinput}/>
</Cells>
</div>
}
} |
lib/ui/widgets/notification.js | SignalK/instrumentpanel | import React from 'react';
import { render } from 'react-dom';
import {Bus} from 'baconjs';
import util from 'util'
import BaseWidget from './basewidget';
var notificationLevels = {
"nominal": 0,
"normal": 1,
"alert": 2,
"warn": 3,
"alarm": 4,
"emergency": 5
};
let defaultValue = {
state: 'nominal',
message: 'no alarm',
timestamp: '',
level: 0,
color: notificationLevels["nominal"],
date: null
}
function shortLabel(label) {
return label.replace('notifications.','').replace('.urn:mrn:imo:mmsi:',' ');
}
function Notification(id, options, streamBundle, instrumentPanel) {
BaseWidget.call(this, id, options, streamBundle, instrumentPanel);
this.options.label = shortLabel(this.options.path);
this.notification = {
value: defaultValue
};
this.valueBus = new Bus();
this.valueStream.onValue(value => {
var levelChange = false;
var oldLevel;
if (value === null || typeof value !== 'object'){
value = defaultValue;
}
oldLevel = this.notification.value.level || 0;
this.notification.value = value;
if (!this.notification.value.message) {
this.notification.value.message = '';
}
this.notification.value.level = notificationLevels[this.notification.value.state || 'nominal'];
this.notification.value.color = this.instrumentPanel.notificationColors[this.notification.value.level];
this.notification.value.date = new Date(this.notification.value.timestamp);
this.instrumentPanel.updateNotificationLevel(oldLevel !== this.notification.value.level);
this.valueBus.push(value);
})
this.optionsBundle.optionsStream.onValue(
( ([options,currentvalue]) => {
this.options.label = shortLabel(this.options.label);
})
)
class NotificationComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
message: '',
};
}
componentDidMount() {
if (this.unsubscribe) {
this.unsubscribe();
}
this.setState({message: this.props.notification.value.message});
this.unsubscribe = this.props.valueStream.onValue((value => {
if (value === null) { value = {}; value.message = ''; }
if (this.state.message !== value.message) {
this.setState({message: value.message});
}
}).bind(this));
}
componentWillUnmount() {
if (this.unsubscribe) {
this.unsubscribe();
}
}
render() {
try {
return (
<div style={{marginLeft: '5px'}}>
<p>
[{this.props.options.label + '] ' + this.props.notification.value.state + ': '}
{(typeof this.props.notification.value.timestamp !== 'undefined') ? this.props.notification.value.timestamp + ': ' : ''}
{this.state.message}
</p>
</div>
);
} catch (ex) {console.log(ex)}
return (<div>safety mode</div>)
}
};
this.widget = React.createElement(NotificationComponent,{
key: id,
options: this.options,
instrumentPanel: this.instrumentPanel,
notification: this.notification,
valueStream: this.valueBus.toProperty()
});
}
util.inherits(Notification, BaseWidget);
Notification.prototype.getReactElement = function() {
return this.widget;
}
Notification.prototype.getType = function() {
return "notification";
}
Notification.prototype.getInitialDimensions = function() {
return {h:2, w:100};
}
export default {
constructor: Notification,
type: "notification",
paths: ['notifications.*']
}
|
tests/site2/code/components/projects.js | dominikwilkowski/cuttlebelle | import PropTypes from 'prop-types';
import React from 'react';
/**
* The Projects component for Listing two projects
*/
const Projects = ({ projects }) => (
<table>
<tbody>
<tr><td>
{ projects[ 0 ] }
</td><td>
{ projects[ 1 ] }
</td></tr>
</tbody>
</table>
);
Projects.propTypes = {
/**
* projects:
* - partial4.md # add whatever partial you want
* - partial5.md
*/
projects: PropTypes.array.isRequired,
};
Projects.defaultProps = {};
export default Projects;
|
app/containers/Page/index.js | ZhengRaymond/portfolio | /*** PRESENTATIONAL COMPONENT ***/
import React from 'react';
import styled from 'styled-components';
import Header, { SubHeader } from 'components/header';
import { fadein, fadein2 } from 'styles/animations';
import './page.css';
var FAExternalLink = require('react-icons/lib/fa/external-link');
const PanelGroup = styled.div`
display: flex;
flex-wrap: wrap;
align-items: stretch;
justify-content: center;
text-align: center;
position: relative;
width: 75vw;
margin-bottom: 20vh;
animation: ${fadein2} 3.5s;
`
const PanelBox = styled.div`
position: relative;
min-height: 30vh;
padding-top: 9vh;
margin: 2vh;
background-color: rgba(255, 255, 255, 0.9);
box-shadow: 0 5px 15px 5px #eee;
display: flex;
flex-direction: column;
justify-content: flex-start;
align-items: center;
transition: all 0.5s, padding-top 0.5s 0.3s;
&.open {
box-shadow: 0 0px 25px 10px #e8f0ff;
padding-top: 20px;
transition: all 0.5s;
}
`
const Details = styled.div`
opacity: 0;
max-height: 0;
padding: 0 20px 20px 20px;
overflow-y: hidden;
text-align: left;
font-size: 2vmin;
transition: opacity 1s ease, max-height 1s ease;
&.open {
max-height: 500px;
opacity: 1;
transition: opacity 1s ease 0.2s, max-height 1s ease;
}
@media (max-device-width: 700px) {
padding: 0;
}
`
const Section = styled.div`
margin: 20px;
`
const Link = styled.a`
position: absolute;
right: 35px;
top: 28px;
font-size: 20px;
cursor: pointer;
transition: all 0.5s;
z-index: 2;
color: black;
&:hover {
color: #aaa;
transition: all 0.3s;
}
@media (max-device-width: 700px) {
font-size: 12px;
right: 22px;
top: 18px;
}
`
function formatSubtitle(subtitles) {
var str = '';
var len = subtitles.length - 1;
subtitles.forEach((subtitle, index) => {
str += subtitle;
if (index !== len) {
str += ' | '
}
})
return str;
}
class Panel extends React.Component {
constructor(props) {
super(props);
this.state = {
active: false
}
this.toggle = this.toggle.bind(this);
}
toggle() {
this.setState({ active: !this.state.active })
}
render() {
return (
<div style={{width: "100%", position: "relative"}}>
<Link target="_blank" href={this.props.data.link}><FAExternalLink/></Link>
<PanelBox className={this.state.active ? 'open' : ''} onClick={this.toggle}>
<Header animation={false} size="medium">{this.props.data.title}</Header>
<SubHeader animation={false} size="small">{formatSubtitle(this.props.data.subtitle)}</SubHeader>
<Details className={this.state.active ? 'open' : ''}>
{
_.map(this.props.data.details, (detail, index) => <Section key={index}>{detail}</Section>)
}
{
<div style={{ textAlign: 'center', fontStyle: 'italic' }}>{"Skills used: " + this.props.data.skills.toString()}</div>
}
</Details>
</PanelBox>
</div>
)
}
}
export default class Page extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = {
activePanel: 'null'
}
this.toggle = this.toggle.bind(this);
}
toggle(value) {
this.setState({ activePanel: value })
}
render() {
return (
<PanelGroup>
<Header animation={false}>{this.props.title}</Header>
{
_.map(this.props.data, (piece) => {
return <Panel key={piece.title} data={piece} active={piece.title === this.state.activePanel} onClick={this.toggle}/>
})
}
</PanelGroup>
);
}
}
/*** ***/
|
src/App.js | sombreroEnPuntas/trust-builder | import React, { Component } from 'react';
import reviews from './mocks/reviews';
import Widget from './widget';
import './App.scss';
class App extends Component {
render() {
return (
<div className="App">
<Widget reviews={reviews} totalCards={reviews.length} />
</div>
);
}
}
export default App;
|
until_201803/react/modern/router/src/RouterExample.js | shofujimoto/examples | import React from 'react'
import {
BrowserRouter as Router,
Route,
Link
} from 'react-router-dom'
const RouterApp = () => (
<Router>
<div style={{margin: 20}}>
<Route exact path='/' component={Home} />
<Route path='/easy' component={EasyCourse} />
<Route path='/normal' component={NormalCourse} />
<Route path='/hard' component={HardCourse} />
</div>
</Router>
)
const Home = () => (
<div>
<h1>React Router Lesson</h1>
<p>コースを選択してください。</p>
<ul>
<li><a href='easy'>Easy</a></li>
<li><a href='normal'>Normal</a></li>
<li><a href='hard'>Hard</a></li>
</ul>
</div>
)
const EasyCourse = () => (
<div>
<h1>Easy Course</h1>
<p><a href="/">Back</a></p>
</div>
)
const NormalCourse = () => (
<div>
<h1>Normal Course</h1>
<p><a href="/">Back</a></p>
</div>
)
const HardCourse = () => (
<div>
<h1>Hard Course</h1>
<p><a href="/">Back</a></p>
</div>
)
export default RouterApp
|
src/jsx-render-engine/strategy/react-router/v4.js | yeojz/metalsmith-react-templates | import React from 'react';
import {renderToStaticMarkup, renderToString} from 'react-dom/server';
import {StaticRouter} from 'react-router';
import constants from '../../constants';
import Provider from './Provider';
function getRouter(location, context, defaultProps, routes) {
return (
<StaticRouter location={location} context={context}>
<Provider defaultProps={defaultProps}>
{routes}
</Provider>
</StaticRouter>
);
}
function v4reactRouterTemplates(props = {}, options = {}) {
let context = {};
const router = getRouter(
props.location,
context,
props.defaultProps,
options.routes
);
const markup = (options.isStatic)
? renderToStaticMarkup(router)
: renderToString(router);
if (!markup) {
return Promise.reject(constants.INVALID_MARKUP);
}
if (context.url) {
return Promise.reject(constants.REDIRECT_LOCATION);
}
return Promise.resolve(markup);
}
export default v4reactRouterTemplates;
|
client/index.js | denistakeda/evolution | /**
* Client entry point
*/
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './App';
import { configureStore } from './store';
import transit from "transit-immutable-js";
// Initialize store
const store = configureStore(transit.fromJSON(window.__INITIAL_STATE__));
const mountApp = document.getElementById('root');
render(
<AppContainer>
<App store={store} />
</AppContainer>,
mountApp
);
// For hot reloading of react components
if (module.hot) {
module.hot.accept('./App', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
const NextApp = require('./App').default; // eslint-disable-line global-require
render(
<AppContainer>
<NextApp store={store} />
</AppContainer>,
mountApp
);
});
}
|
client/src/components/Confirmation.js | jeffersonsteelflex69/mytv | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import api from '../lib/api';
class Confirmation extends Component {
componentDidMount(){
if(!Object.keys(this.props.location.query).length > 0)
return
let code = this.props.location.query["code"];
if(typeof code == "undefined")
return
document.getElementById("code").value = code;
}
confirmUser(e){
e.preventDefault();
let userPool = this.props.app.aws.cognito.userPool;
let email = document.getElementById("email").value;
let code = document.getElementById("code").value;
this.props.confirmUser(userPool, email, code);
}
render(){
return (
<div id="login">
<div className="login-container">
<div className="login-brand">
<div className="login-logo">
<img src="/public/img/white-tv.png" alt=""/>
</div>
<div className="login-text">MyTV</div>
</div>
<div className="login-header">Confirm Account</div>
<div id="error"></div>
<div className="login-fields">
<form onSubmit={this.confirmUser.bind(this)}>
<div className="login-field">
<span>Email</span>
<input id="email" type="text" name="email" />
</div>
<div className="login-field">
<span>Code</span>
<input id="code" type="text" name="code" />
</div>
<div className="login-submit">
<input type="submit" onClick={this.confirmUser.bind(this)} value="Confirm Account" />
</div>
</form>
</div>
<div className="login-home-link"><Link to="/">← Go home</Link></div>
</div>
</div>
);
}
}
Confirmation.contextTypes = {
router: PropTypes.object.isRequired
};
export default Confirmation;
|
fields/components/columns/CloudinaryImageSummary.js | pr1ntr/keystone | import React from 'react';
const IMAGE_SIZE = 18;
const linkStyle = {
marginRight: 8,
};
const boxStyle = {
borderRadius: 3,
display: 'inline-block',
height: IMAGE_SIZE,
overflow: 'hidden',
verticalAlign: 'middle',
width: IMAGE_SIZE,
};
const imageStyle = {
display: 'block',
height: IMAGE_SIZE,
left: '50%',
position: 'relative',
WebkitTransform: 'translateX(-50%)',
MozTransform: 'translateX(-50%)',
msTransform: 'translateX(-50%)',
transform: 'translateX(-50%)',
};
const textStyle = {
color: '#888',
display: 'inline-block',
fontSize: '.8rem',
marginLeft: 8,
verticalAlign: 'middle',
};
var CloudinaryImageSummary = React.createClass({
displayName: 'CloudinaryImageSummary',
propTypes: {
image: React.PropTypes.object.isRequired,
label: React.PropTypes.oneOf(['dimensions', 'publicId']),
},
renderLabel () {
if (!this.props.label) return;
const { label, image } = this.props;
let text;
if (label === 'dimensions') {
text = `${image.width} × ${image.height}`;
} else {
text = `${image.public_id}.${image.format}`;
}
return (
<span style={textStyle}>
{text}
</span>
);
},
renderImageThumbnail () {
if (!this.props.image) return;
const url = this.props.image.url.replace(/image\/upload/, `image/upload/c_thumb,g_face,h_${IMAGE_SIZE},w_${IMAGE_SIZE}`);
return <img src={url} style={imageStyle} className="img-load" />;
},
render () {
return (
<span style={linkStyle}>
<span style={boxStyle}>
{this.renderImageThumbnail()}
</span>
{this.renderLabel()}
</span>
);
},
});
module.exports = CloudinaryImageSummary;
|
webpack/components/WithOrganization/withOrganization.js | tstrachota/katello | import React, { Component } from 'react';
import { orgId } from '../../services/api';
import SetOrganization from '../SelectOrg/SetOrganization';
import titleWithCaret from '../../helpers/caret';
function withOrganization(WrappedComponent, redirectPath) {
return class CheckOrg extends Component {
componentDidUpdate(prevProps) {
const { location } = this.props;
// TODO: use topbar react component
const orgTitle = location.state && location.state.orgChanged;
const prevOrgTitle = prevProps.location.state && prevProps.location.state.orgChanged;
if (orgTitle !== prevOrgTitle) {
document.getElementById('organization-dropdown').children[0].innerHTML = titleWithCaret(orgTitle);
}
}
render() {
if (!orgId()) {
return <SetOrganization redirectPath={redirectPath} />;
}
return <WrappedComponent {...this.props} />;
}
};
}
export default withOrganization;
|
src/svg-icons/action/gavel.js | pradel/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionGavel = (props) => (
<SvgIcon {...props}>
<path d="M1 21h12v2H1zM5.245 8.07l2.83-2.827 14.14 14.142-2.828 2.828zM12.317 1l5.657 5.656-2.83 2.83-5.654-5.66zM3.825 9.485l5.657 5.657-2.828 2.828-5.657-5.657z"/>
</SvgIcon>
);
ActionGavel = pure(ActionGavel);
ActionGavel.displayName = 'ActionGavel';
export default ActionGavel;
|
packages/icons/src/md/hardware/Headset.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdHeadset(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M24 5C14.06 5 6 13.06 6 23v14c0 3.31 2.69 6 6 6h6V27h-8v-4c0-7.73 6.27-14 14-14s14 6.27 14 14v4h-8v16h6c3.31 0 6-2.69 6-6V23c0-9.94-8.06-18-18-18z" />
</IconBase>
);
}
export default MdHeadset;
|
example/src/index.js | ryo33/redux-pages | import React from 'react'
import ReactDOM from 'react-dom'
import {
createStore, combineReducers, applyMiddleware
} from 'redux'
import { Provider } from 'react-redux'
import createLogger from 'redux-logger'
import createHistory from 'history/createHashHistory'
import { createPagesReducer } from 'redux-pages'
import App from './App'
import { pages, rootPage } from './pages'
import { reducers } from './reducers'
import middlewares from './middlewares'
// Create a reducer
const pageReducer = createPagesReducer(rootPage.name, {})
const reducer = combineReducers({
...reducers,
page: pageReducer
})
// Define the selector for the page state
const pageSelector = state => state.page
// Define getCurrentPath and pushPath
const history = createHistory({
})
const getCurrentPath = () => history.location.pathname
const pushPath = (path) => history.push(path)
const logger = createLogger()
// Create the pagesMiddleware
const pagesMiddleware = pages
.middleware(pageSelector, getCurrentPath, pushPath)
// Create the store
const store = createStore(
reducer,
applyMiddleware(pagesMiddleware, ...middlewares, logger),
)
// Apply the current path
pages.handleNavigation(store, history.location.pathname)
// Listen for changes
history.listen((location, action) => {
pages.handleNavigation(store, location.pathname)
})
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
src/routes/register/Register.js | foxleigh81/foxweb | /**
* 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 withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Register.css';
class Register extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>
{this.props.title}
</h1>
<p>...</p>
</div>
</div>
);
}
}
export default withStyles(s)(Register);
|
client/admin/settings/inputs/PasswordSettingInput.js | subesokun/Rocket.Chat | import { Box, Field, Flex, PasswordInput } from '@rocket.chat/fuselage';
import React from 'react';
import { ResetSettingButton } from '../ResetSettingButton';
export function PasswordSettingInput({
_id,
label,
value,
placeholder,
readonly,
autocomplete,
disabled,
hasResetButton,
onChangeValue,
onResetButtonClick,
}) {
const handleChange = (event) => {
onChangeValue && onChangeValue(event.currentTarget.value);
};
return <>
<Flex.Container>
<Box>
<Field.Label htmlFor={_id} title={_id}>{label}</Field.Label>
{hasResetButton && <ResetSettingButton data-qa-reset-setting-id={_id} onClick={onResetButtonClick} />}
</Box>
</Flex.Container>
<Field.Row>
<PasswordInput
data-qa-setting-id={_id}
id={_id}
value={value}
placeholder={placeholder}
disabled={disabled}
readOnly={readonly}
autoComplete={autocomplete === false ? 'off' : undefined}
onChange={handleChange}
/>
</Field.Row>
</>;
}
|
packages/material-ui-icons/src/VerticalAlignBottom.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let VerticalAlignBottom = props =>
<SvgIcon {...props}>
<path d="M16 13h-3V3h-2v10H8l4 4 4-4zM4 19v2h16v-2H4z" />
</SvgIcon>;
VerticalAlignBottom = pure(VerticalAlignBottom);
VerticalAlignBottom.muiName = 'SvgIcon';
export default VerticalAlignBottom;
|
frontend/src/Components/Form/AutoCompleteInput.js | lidarr/Lidarr | import jdu from 'jdu';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import AutoSuggestInput from './AutoSuggestInput';
class AutoCompleteInput extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
suggestions: []
};
}
//
// Control
getSuggestionValue(item) {
return item;
}
renderSuggestion(item) {
return item;
}
//
// Listeners
onInputChange = (event, { newValue }) => {
this.props.onChange({
name: this.props.name,
value: newValue
});
}
onInputBlur = () => {
this.setState({ suggestions: [] });
}
onSuggestionsFetchRequested = ({ value }) => {
const { values } = this.props;
const lowerCaseValue = jdu.replace(value).toLowerCase();
const filteredValues = values.filter((v) => {
return jdu.replace(v).toLowerCase().contains(lowerCaseValue);
});
this.setState({ suggestions: filteredValues });
}
onSuggestionsClearRequested = () => {
this.setState({ suggestions: [] });
}
//
// Render
render() {
const {
name,
value,
...otherProps
} = this.props;
const { suggestions } = this.state;
return (
<AutoSuggestInput
{...otherProps}
name={name}
value={value}
suggestions={suggestions}
getSuggestionValue={this.getSuggestionValue}
renderSuggestion={this.renderSuggestion}
onInputBlur={this.onInputBlur}
onSuggestionsFetchRequested={this.onSuggestionsFetchRequested}
onSuggestionsClearRequested={this.onSuggestionsClearRequested}
/>
);
}
}
AutoCompleteInput.propTypes = {
name: PropTypes.string.isRequired,
value: PropTypes.string,
values: PropTypes.arrayOf(PropTypes.string).isRequired,
onChange: PropTypes.func.isRequired
};
AutoCompleteInput.defaultProps = {
value: ''
};
export default AutoCompleteInput;
|
src/mui/input/BooleanInput.js | matteolc/admin-on-rest | import React from 'react';
import PropTypes from 'prop-types';
import Toggle from 'material-ui/Toggle';
import FieldTitle from '../../util/FieldTitle';
const styles = {
block: {
margin: '1rem 0',
maxWidth: 250,
},
label: {
color: 'rgba(0, 0, 0, 0.298039)',
},
toggle: {
marginBottom: 16,
},
};
const BooleanInput = ({ input, label, source, elStyle, resource }) => (
<div style={elStyle || styles.block}>
<Toggle
defaultToggled={!!input.value}
onToggle={input.onChange}
labelStyle={styles.label}
style={styles.toggle}
label={<FieldTitle label={label} source={source} resource={resource} />}
/>
</div>
);
BooleanInput.propTypes = {
addField: PropTypes.bool.isRequired,
elStyle: PropTypes.object,
input: PropTypes.object,
label: PropTypes.string,
resource: PropTypes.string,
source: PropTypes.string,
};
BooleanInput.defaultProps = {
addField: true,
};
export default BooleanInput;
|
src/subscribe.js | DigitalGlobe/jetset | import React from 'react';
import { Map as iMap } from 'immutable';
import store from './store';
import logger, { formatBranchArgs } from './lib/log';
const isObject = item => !Array.isArray( item ) && typeof item === 'object';
function subscribe({ local, paths }) {
return Component => {
const rootPath = local ? [ 'local', Component.name + `_${Math.round(Math.random() * Date.now())}`] : [];
const nPaths = paths.reduce(( memo, item ) => {
if ( isObject( item ) ) {
Object.keys( item ).forEach( key => memo.set( key, item[ key ] ) );
} else {
memo.set( item );
}
return memo;
}, new Map());
return class Subscriber extends React.Component {
subscriptions = null
constructor( props ) {
super( props );
this.state = [ ...nPaths.entries() ].reduce(( memo, [ key, val ] ) => {
if ( val ) {
memo[key] = val;
// TODo this shouldn't happen here
store.setStateQuiet( rootPath.concat( key ), val );
} else {
const storeVal = store.getState( rootPath.concat( key ) );
memo[key] = storeVal && storeVal.toJS ? storeVal.toJS() : storeVal;
}
return memo;
}, {});
}
componentWillMount = () => {
this.subscriptions = [ ...nPaths.keys() ].map( this.subscribeTo );
}
componentWillUnmount = () => this.subscriptions.forEach( store.unsubscribe )
subscribeTo = path => store.subscribeTo( rootPath.concat( path ), this.onChange.bind( this, path ) );
onChange = ( path, state ) => {
/* eslint-disable no-console */
const branch = formatBranchArgs( rootPath.concat( path ) );
logger( `\uD83C\uDF00 <${Component.name || 'StatelessFunction'}> is re-rendering based on changes on branch: ${branch}` );
this.setState({ [path]: state && state.toJS ? state.toJS() : state });
}
merge = ( val, path ) => {
if ( Array.isArray( val ) || typeof val !== 'object' ) {
return this.replace( val, path );
} else {
const fullPath = rootPath.concat( path || [] );
const state = store.getState( fullPath ) || iMap();
return store.setState( fullPath, state.mergeDeep( val ) );
}
}
replace = ( val, path ) => store.setState( rootPath.concat( path || [] ), val )
methods = () => {
const keyState = [ ...nPaths.keys() ].reduce(( memo, path ) => {
const currentState = { ...this.state }[path];
return {
...memo,
[path]: {
get: () => currentState,
set: val => this.merge( val, path ),
replace: val => this.replace( path, val )
}
};
}, {});
const localState = {
get: () => ({ ...this.state }),
set: val => this.merge( val ),
replace: val => this.replace( val )
};
return { ...keyState, localState };
}
render = () => (
<Component
{ ...this.props }
{ ...this.methods() }
/>
)
};
};
}
export function localState( ...paths ) {
return subscribe({ local: true, paths });
}
export function globalState( ...paths ) {
return subscribe({ local: false, paths });
}
|
201601react/许海英/react/app/index.js | zhufengreact/homework | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './container/App';
let root = document.getElementById('app');
ReactDOM.render( <App />, root );
|
src/containers/weather-list.js | 86mattw/weather |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Chart from '../components/chart';
class WeatherList extends Component {
renderWeather(cityData) {
const name = cityData.city.name;
const temps = cityData.list.map(weather => weather.main.temp);
const pressures = cityData.list.map(weather => weather.main.pressure);
const humidities = cityData.list.map(weather => weather.main.humidity);
return (
<tr key={name}>
<td>{name}</td>
<td><Chart color="orange" data={temps} units="K" /></td>
<td><Chart color="green" data={pressures} units="hPa" /></td>
<td><Chart color="black" data={humidities} units="%" /></td>
</tr>
);
}
render() {
return (
<table className="table table-hover">
<thead>
<tr>
<th>City</th>
<th>Temperature (K)</th>
<th>Pressure (hPa)</th>
<th>Humidity (%)</th>
</tr>
</thead>
<tbody>
{this.props.weather.map(this.renderWeather)}
</tbody>
</table>
);
}
}
function mapStateToProps({ weather }) {
return { weather };
}
export default connect(mapStateToProps)(WeatherList);
|
app/containers/NotFoundPage/index.js | mamaracas/MEventsRegistration | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import messages from './messages';
export default function NotFound() {
return (
<article>
<H1>
<FormattedMessage {...messages.header} />
</H1>
</article>
);
}
|
examples/full-example/src/isomorphic/base/components/lazy_content.js | yahoo/mendel | /* Copyright 2015, Yahoo Inc.
Copyrights licensed under the MIT License.
See the accompanying LICENSE file for terms. */
import React from 'react';
class Button extends React.Component {
render() {
return <span style={{ color: 'blue' }}>
Content inside lazy
</span>;
}
}
export default Button;
|
src/parser/priest/shadow/modules/talents/ShadowCrash.js | sMteX/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS/index';
import Analyzer from 'parser/core/Analyzer';
import TalentStatisticBox, { STATISTIC_ORDER } from 'interface/others/TalentStatisticBox';
import ItemDamageDone from 'interface/others/ItemDamageDone';
import { formatNumber } from 'common/format';
import AbilityTracker from 'parser/priest/shadow/modules/core/AbilityTracker';
// Example Log: /report/zgBQ3kr6aAv19MXq/22-Normal+Zul+-+Kill+(2:26)/3-Selur
class ShadowCrash extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
damage = 0;
totalTargetsHit = 0;
get averageTargetsHit() {
return this.totalTargetsHit / this.abilityTracker.getAbility(SPELLS.SHADOW_CRASH_TALENT.id).casts;
}
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.SHADOW_CRASH_TALENT.id);
}
on_byPlayer_damage(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.SHADOW_CRASH_TALENT_DAMAGE.id) {
return;
}
this.totalTargetsHit += 1;
this.damage += event.amount;
}
statistic() {
return (
<TalentStatisticBox
talent={SPELLS.SHADOW_CRASH_TALENT.id}
value={<ItemDamageDone amount={this.damage} />}
tooltip={`Average targets hit: ${formatNumber(this.averageTargetsHit)}`}
position={STATISTIC_ORDER.CORE(5)}
/>
);
}
}
export default ShadowCrash;
|
packages/material-ui-icons/src/AirlineSeatFlat.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M22 11v2H9V7h9c2.21 0 4 1.79 4 4zM2 14v2h6v2h8v-2h6v-2H2zm5.14-1.9c1.16-1.19 1.14-3.08-.04-4.24-1.19-1.16-3.08-1.14-4.24.04-1.16 1.19-1.14 3.08.04 4.24 1.19 1.16 3.08 1.14 4.24-.04z" /></g>
, 'AirlineSeatFlat');
|
packages/veritone-widgets/src/widgets/MediaPlayer/DefaultControlBar.js | veritone/veritone-sdk | import React from 'react';
import { connect } from 'react-redux';
import cx from 'classnames';
import { get } from 'lodash';
import { bindActionCreators } from 'redux';
import {
VolumeMenuButton,
ControlBar,
ReplayControl,
ForwardControl,
PlayToggle,
playerActions,
videoActions,
CurrentTimeDisplay,
TimeDivider,
DurationDisplay,
ProgressControl,
FullscreenToggle
} from 'video-react';
import { shape, objectOf, any, bool, number } from 'prop-types';
import { withStyles } from '@material-ui/styles';
import { RestartMediaButton } from 'veritone-react-common';
import 'video-react/dist/video-react.css';
import styles from './styles';
@withStyles(styles)
@connect(
state => ({
playerState: state.player,
hasStarted: state.player.hasStarted
}),
dispatch => ({
videoReactActions: bindActionCreators(
{ ...playerActions, ...videoActions },
dispatch
)
})
)
export default class DefaultControlBar extends React.Component {
static propTypes = {
playerRef: shape({
current: objectOf(any)
}),
hasStarted: bool,
btnRestart: bool,
btnReplay: bool,
btnForward: bool,
btnPlayToggle: bool,
btnVolume: bool,
btnFullscreenToggle: bool,
ctrlProgress: bool,
displayTime: bool,
autoHide: bool,
autoHideTime: number,
classes: shape({ any })
};
static defaultProps = {
btnRestart: true,
btnReplay: true,
btnForward: true,
btnPlayToggle: true,
btnVolume: true,
btnFullscreenToggle: true,
ctrlProgress: true,
displayTime: true,
autoHide: true,
autoHideTime: 1000
};
render() {
const manager = get(this.props.playerRef, 'current.manager');
let player, actions, store;
if (manager) {
player = manager.getState().player;
actions = manager.getActions();
store = manager.store;
}
if (!manager) {
return null;
}
const {
hasStarted,
btnRestart,
btnReplay,
btnForward,
btnPlayToggle,
btnVolume,
btnFullscreenToggle,
ctrlProgress,
displayTime,
autoHide,
autoHideTime,
classes
} = this.props;
return (
<div
className={cx(
'video-react',
{
'video-react-has-started': hasStarted || get(player, 'hasStarted', false)
},
classes.externalStyles
)}
data-test="DefaultControlBar"
>
<ControlBar
className={cx('mediaPlayerControls')}
// need to provide these manually because ControlBar is
// supposed to be a child of Player and get them automatically
autoHide={autoHide}
autoHideTime={autoHideTime}
player={player}
manager={manager}
actions={actions}
store={store}
disableDefaultControls
>
{btnRestart && <RestartMediaButton order={1.1} />}
{btnReplay && <ReplayControl seconds={10} order={1.2} />}
{btnForward && <ForwardControl seconds={10} order={1.3} />}
{btnPlayToggle && <PlayToggle order={2} />}
{displayTime && <CurrentTimeDisplay player={player} order={3.1} />}
{displayTime && <TimeDivider order={3.2} />}
{displayTime && <DurationDisplay player={player} order={3.3} />}
{ctrlProgress && <ProgressControl order={6} />}
{btnVolume && <VolumeMenuButton vertical={ctrlProgress} order={7} />}
{btnFullscreenToggle && <FullscreenToggle order={8} />}
</ControlBar>
</div>
);
}
}
|
client/modules/comments/components/.stories/create_comment.js | TheAncientGoat/mantra-sample-blog-coffee | import React from 'react';
import { storiesOf, action } from '@kadira/storybook';
const CreateComment = require('../create_comment.coffee');
storiesOf('comments.CreateComment', module)
.add('default view', () => {
return (
<div className='comments'>
<CreateComment postId='the-id' create={action('create comment')}/>
</div>
);
})
.add('with error', () => {
return (
<div className='comments'>
<CreateComment
error='This is the error message'
postId='the-id'
create={action('create comment')}
/>
</div>
);
});
|
admin/client/App/components/Navigation/Mobile/SectionItem.js | frontyard/keystone | /**
* A mobile section
*/
import React from 'react';
import MobileListItem from './ListItem';
import { Link } from 'react-router';
const MobileSectionItem = React.createClass({
displayName: 'MobileSectionItem',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
currentListKey: React.PropTypes.string,
href: React.PropTypes.string.isRequired,
lists: React.PropTypes.array,
},
// Render the lists
renderLists () {
if (!this.props.lists || this.props.lists.length <= 1) return null;
const navLists = this.props.lists.map((item) => {
// Get the link and the classname
const href = item.external ? item.path : `${Keystone.adminPath}/${item.path}`;
const className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item';
return (
<MobileListItem key={item.path} href={href} className={className} onClick={this.props.onClick}>
{item.label}
</MobileListItem>
);
});
return (
<div className="MobileNavigation__lists">
{navLists}
</div>
);
},
render () {
return (
<div className={this.props.className}>
<Link
className="MobileNavigation__section-item"
to={this.props.href}
tabIndex="-1"
onClick={this.props.onClick}
>
{this.props.children}
</Link>
{this.renderLists()}
</div>
);
},
});
module.exports = MobileSectionItem;
|
src/components/charts/charts/svg/path.js | noahehall/udacity-corporate-dashboard | import React from 'react';
export const Path = ({ // eslintignore https://developer.mozilla.org/en-US/docs/Web/SVG/Element/path
chartType = 'pie',
d,
fill = 'blue',
id = '',
stroke = 'gray',
}) => <path
className={`${chartType}-path`}
d={d}
fill={fill}
id={id}
stroke={stroke}
/>;
Path.propTypes = {
chartType: React.PropTypes.string,
d: React.PropTypes.string.isRequired,
fill: React.PropTypes.string,
id: React.PropTypes.string,
stroke: React.PropTypes.string,
};
export default Path;
|
common/components/Header.js | BostonGlobe/elections-2016 | import React from 'react'
import svgs from './../utils/svgs.js'
import Navigation from './Navigation.js'
const Header = () => (
<header className='header' key='header'>
<a href='#content' className='skip-to-main'>Skip to main content</a>
<div className='header__logo'>
<a
href='http://www.bostonglobe.com/'
className='header__logo-link'
dangerouslySetInnerHTML={{ __html: svgs.globeLogo }} />
</div>
<Navigation />
</header>
)
export default Header
|
packages/@lyra/form-builder/src/inputs/BlockEditor/Toolbar/DecoratorButtons.js | VegaPublish/vega-studio | // @flow
import type {
BlockContentFeature,
BlockContentFeatures,
SlateChange,
SlateValue
} from '../typeDefs'
import React from 'react'
import {keyMaps} from '../plugins/SetMarksOnKeyComboPlugin'
import {toggleMark} from '../utils/changes'
import CustomIcon from './CustomIcon'
import FormatBoldIcon from 'part:@lyra/base/format-bold-icon'
import FormatItalicIcon from 'part:@lyra/base/format-italic-icon'
import FormatStrikethroughIcon from 'part:@lyra/base/format-strikethrough-icon'
import FormatUnderlinedIcon from 'part:@lyra/base/format-underlined-icon'
import FormatCodeIcon from 'part:@lyra/base/format-code-icon'
import LyraLogoIcon from 'part:@lyra/base/lyra-logo-icon'
import ToggleButton from 'part:@lyra/components/toggles/button'
import ToolbarClickAction from './ToolbarClickAction'
import styles from './styles/DecoratorButtons.css'
type DecoratorItem = BlockContentFeature & {active: boolean, disabled: boolean}
type Props = {
blockContentFeatures: BlockContentFeatures,
editorValue: SlateValue,
onChange: (change: SlateChange) => void
}
function getIcon(type: string) {
switch (type) {
case 'strong':
return FormatBoldIcon
case 'em':
return FormatItalicIcon
case 'underline':
return FormatUnderlinedIcon
case 'strike-through':
return FormatStrikethroughIcon
case 'code':
return FormatCodeIcon
default:
return LyraLogoIcon
}
}
const NOOP = () => {}
export default class DecoratorButtons extends React.Component<Props> {
hasDecorator(decoratorName: string) {
const {editorValue} = this.props
return editorValue.marks.some(mark => mark.type === decoratorName)
}
getItems() {
const {blockContentFeatures, editorValue} = this.props
const {focusBlock} = editorValue
const disabled = focusBlock ? focusBlock.isVoid : false
return blockContentFeatures.decorators.map(
(decorator: BlockContentFeature) => {
return {
...decorator,
active: this.hasDecorator(decorator.value),
disabled
}
}
)
}
handleClick = (item: DecoratorItem) => {
const {onChange, editorValue} = this.props
const change = editorValue.change()
change.call(toggleMark, item.value)
onChange(change)
}
renderDecoratorButton = (item: DecoratorItem) => {
const {editorValue} = this.props
const icon = item.blockEditor ? item.blockEditor.icon : null
const Icon = icon || getIcon(item.value)
// We must not do a click-event here, because that messes with the editor focus!
const onAction = () => {
this.handleClick(item)
}
const shortCut = keyMaps[item.value] ? `(${keyMaps[item.value]})` : ''
const title = `${item.title} ${shortCut}`
return (
<span className={styles.buttonWrapper} key={item.value}>
<ToolbarClickAction
onAction={onAction}
editorValue={editorValue}
key={`decoratorButton${item.value}`}
>
<ToggleButton
selected={!!item.active}
disabled={item.disabled}
onClick={NOOP}
title={title}
className={styles.button}
icon={Icon}
/>
</ToolbarClickAction>
</span>
)
}
render() {
const items = this.getItems()
return (
<div className={styles.root}>{items.map(this.renderDecoratorButton)}</div>
)
}
}
|
containers/SearchBar/index.js | bmagic/acdh-client | import React from 'react'
import { connect } from 'react-redux'
import { createStructuredSelector } from 'reselect'
import PropTypes from 'prop-types'
import { searchChange } from 'actions/programs'
import { makeSearch } from 'selectors/programs'
export class SearchBar extends React.PureComponent {
render () {
return (
<div className='search-bar field'>
<input type='text' className='input' value={this.props.search} placeholder='Rechercher une émission' onChange={this.props.onChange} />
</div>
)
}
}
SearchBar.propTypes = {
search: PropTypes.string,
onChange: PropTypes.func
}
const mapStateToProps = createStructuredSelector({
search: makeSearch()
})
export function mapDispatchToProps (dispatch) {
return {
onChange: (e) => {
dispatch(searchChange(e.target.value))
}
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar)
|
node_modules/semantic-ui-react/dist/es/views/Statistic/StatisticValue.js | mowbell/clickdelivery-fed-test | import _extends from 'babel-runtime/helpers/extends';
import _isNil from 'lodash/isNil';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly } from '../../lib';
/**
* A statistic can contain a numeric, icon, image, or text value.
*/
function StatisticValue(props) {
var children = props.children,
className = props.className,
text = props.text,
value = props.value;
var classes = cx(useKeyOnly(text, 'text'), 'value', className);
var rest = getUnhandledProps(StatisticValue, props);
var ElementType = getElementType(StatisticValue, props);
return React.createElement(
ElementType,
_extends({}, rest, { className: classes }),
_isNil(children) ? value : children
);
}
StatisticValue.handledProps = ['as', 'children', 'className', 'text', 'value'];
StatisticValue._meta = {
name: 'StatisticValue',
parent: 'Statistic',
type: META.TYPES.VIEW
};
process.env.NODE_ENV !== "production" ? StatisticValue.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** Format the value with smaller font size to fit nicely beside number values. */
text: PropTypes.bool,
/** Primary content of the StatisticValue. Mutually exclusive with the children prop. */
value: customPropTypes.contentShorthand
} : void 0;
export default StatisticValue; |
client/src/components/loader/index.js | commoncode/ontap | import React from 'react';
const Loader = () => (
<div className="loader">
OnTap
</div>
);
export default Loader;
|
src/components/video_detail.js | martezconner/react_vidhub | import React from 'react';
const VideoDetail = ({video}) => {
if (!video) {
return <div>Loading...</div>;
}
const videoId = video.id.videoId;
const url = `https://www.youtube.com/embed/${videoId}`;
return (
<div className="video-detail col-md-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={url}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
);
};
export default VideoDetail;
|
apps/app/src/pages/Repository/BuildDetail/Context.js | argos-ci/argos | import React from 'react'
import gql from 'graphql-tag'
import { useMutation } from '@apollo/react-hooks'
export const BuildContextFragment = gql`
fragment BuildContextFragment on Build {
id
createdAt
number
status
repository {
name
owner {
login
}
}
baseScreenshotBucket {
id
createdAt
updatedAt
name
commit
branch
}
compareScreenshotBucket {
id
createdAt
updatedAt
name
commit
branch
}
screenshotDiffs {
id
createdAt
updatedAt
baseScreenshot {
id
name
url
}
compareScreenshot {
id
name
url
}
url
score
jobStatus
validationStatus
}
}
`
const BuildContext = React.createContext()
export function BuildProvider({ build: initialBuild, children }) {
const [build, setBuild] = React.useState(initialBuild)
const [
setValidationStatus,
{ loading: queryLoading, error: queryError, data },
] = useMutation(gql`
mutation setValidationStatus(
$buildId: ID!
$validationStatus: ValidationStatus!
) {
setValidationStatus(
buildId: $buildId
validationStatus: $validationStatus
) {
...BuildContextFragment
}
}
${BuildContextFragment}
`)
React.useEffect(() => {
if (data && data.setValidationStatus) {
setBuild(data.setValidationStatus)
}
}, [data])
const value = React.useMemo(
() => ({
build,
setValidationStatus,
queryLoading,
queryError,
}),
[build, queryError, queryLoading, setValidationStatus],
)
return <BuildContext.Provider value={value}>{children}</BuildContext.Provider>
}
export function useBuild() {
const { build } = React.useContext(BuildContext)
return build
}
export function useValidationStatusBuild() {
const {
setValidationStatus,
queryLoading: loading,
queryError: error,
} = React.useContext(BuildContext)
return { setValidationStatus, loading, error }
}
|
src/svg-icons/maps/pin-drop.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsPinDrop = (props) => (
<SvgIcon {...props}>
<path d="M18 8c0-3.31-2.69-6-6-6S6 4.69 6 8c0 4.5 6 11 6 11s6-6.5 6-11zm-8 0c0-1.1.9-2 2-2s2 .9 2 2-.89 2-2 2c-1.1 0-2-.9-2-2zM5 20v2h14v-2H5z"/>
</SvgIcon>
);
MapsPinDrop = pure(MapsPinDrop);
MapsPinDrop.displayName = 'MapsPinDrop';
MapsPinDrop.muiName = 'SvgIcon';
export default MapsPinDrop;
|
src/containers/Home/Home.js | dbertella/react-hot-reload-starter | import React, { Component } from 'react';
import { SimpleForm } from 'components';
class Home extends Component {
render() {
return (
<div>
<h1>Home</h1>
<SimpleForm />
</div>
);
}
}
export default Home;
|
html.js | inthegully/steveGillian | import React from 'react'
import Helmet from 'react-helmet'
import { prefixLink } from 'gatsby-helpers'
const BUILD_TIME = new Date().getTime()
module.exports = React.createClass({
propTypes() {
return {
body: React.PropTypes.string,
}
},
render() {
const head = Helmet.rewind()
let css
if (process.env.NODE_ENV === 'production') {
css = (
<style
dangerouslySetInnerHTML={{
__html: require('!raw!./public/styles.css'),
}}
/>
)
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge" />
<meta
name="viewport"
content="width=device-width, initial-scale=1.0"
/>
{head.title.toComponent()}
{head.meta.toComponent()}
{css}
<link href="https://fonts.googleapis.com/css?family=Euphoria+Script|Josefin+Sans:400,700" rel="stylesheet" />
</head>
<body >
<div
id="react-mount"
dangerouslySetInnerHTML={{ __html: this.props.body }}
/>
<script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
</body>
</html>
)
},
})
|
src/components/projects/content/Zune.js | tehfailsafe/portfolio | import React from 'react';
import Section from '../show/Section'
import CopySplitLeft from '../show/CopySplitLeft'
import CopySplitRight from '../show/CopySplitRight'
import Copy from '../show/Copy'
import ImageFull from '../show/ImageFull'
import VideoPlayer from '../show/VideoPlayer'
export default React.createClass({
render(){
var projectPath = this.props.imagePath;
return (
<div>
<Section>
<Copy class="col-sm-9">
<h4>About</h4>
In 2008 the Microsoft Zune team was getting ready to launch the new zuneHD. With new hardware and form factor, the new device needed a new interface to support touch interactions.
<br/><br/>
I worked directly with the team to explore new ideas for interaction models, organization, and content. I focused more on the interaction than the visual design, treating these explorations like interactive wireframes.
</Copy>
<Copy class="col-sm-3">
<b4>Role</b4>
<ul>
<li>Interaction Design</li>
<li>Motion Design</li>
</ul>
</Copy>
</Section>
<Section title="The Challenges">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_gen1.mp4"/>
<Copy class="col-sm-9">
This biggest challenge to address was the transition from a dial pad control to a touch screen device. This meant rethinking the original layout and solving new problems like fitting content in a limited space, promoting browsability and discoverability with more visual cues, and supporting an unknown amount of content.
</Copy>
</Section>
<Section title="Swipe offscreen">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_01.mp4"/>
<Copy class="col-sm-9">
I explored the idea of using swipe to pull things into view from offscreen, leaving a small bit of the next content visible to indicate there is more beyond the frame.
</Copy>
</Section>
<Section title="Filter and sort">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_02.mp4"/>
<Copy class="col-sm-9">
I thought a bit about how to organize and sort content. What if tapping a filter would give you instant feedback on the items that matched, and double tapping would select that group and resort the content, removing the items that don't match. This process could be repeated with a subset of filters to further refine.
</Copy>
</Section>
<Section title="Focused content">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_03.mp4"/>
<Copy class="col-sm-9">
What if I could get more content to fit into a small frame by overlapping in Z space? Switching focus with blur and highlighting the content that is currently being interacted with. Tapping other content would bring it back into focus again.
</Copy>
</Section>
<Section title="Infinite zoom">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_00.mp4"/>
<Copy class="col-sm-9">
What if each category showed a scaled down preview of it's content and you could zoom in on tap? And then you could keep diving futher in getting previews of each next step. This would allow unlimited content.
</Copy>
</Section>
<Section title="Category clustering">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_05.mp4"/>
<Copy class="col-sm-9">
What if the main categories were clusters of content that could be brought into focus? Starting from a zoomed out view you could see them all, and tapping one would zoom in to it. Inside a category you could swipe the content from off screen or pivot along the top list to filter the content like the previous examples. Hitting the home button would zoom back out and give you a quick way to switch back to other sections.
</Copy>
</Section>
<Section title="Galaxy clusters">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_07.mp4"/>
<Copy class="col-sm-9">
What if the category clusters lived in a little galaxy, and the device screen was actually a viewport into that world? Tilting the device would let us peek around corners, revealing a larger space than we can physcially see. Its bigger on the inside...
<br/><br/>
We took this concept a bit further and made an interactive prototype that allowed for quick feedback and iteration.
</Copy>
</Section>
<Section title="Results">
<VideoPlayer scrollPosition={this.props.scrollPosition} path={projectPath} src="zune_demo.mp4"/>
<Copy class="col-sm-9">
The team continued to iterate and really polished up some of the thinking. You can start to see the building blocks that later became the Metro design language, heavily influencing Windows and Windows Mobile.
</Copy>
</Section>
</div>
)
}
})
|
src/components/NavBar.js | anitrack/anitrack-web | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import { Navbar, NavbarBrand, Collapse, Nav, NavItem, NavbarToggler } from 'reactstrap';
import Login from './Login';
class NavBar extends Component {
constructor(props){
super(props);
this.state = {isOpen: false};
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
render() {
let user = "";
if(this.props.isLoggedIn === true){
user = <a href="/logout" style={{color: "white"}}>{this.props.myUserData.name}</a>;
}else if(this.props.isLoggedIn === false){
user = <Login/>
}
return (
<Navbar light toggleable className="fixed-top" style={{backgroundColor: "rgba(0,0,0,.65)", position: "absolute"}}>
<NavbarToggler right onClick={() => {this.toggle()}}>
<i className="fa fa-navicon" style={{color: "white", fontSize: "1.5em"}} />
</NavbarToggler>
<NavbarBrand tag="div"><Link to="/" style={{color: "white", textDecoration: 'none'}}>AniTrack</Link></NavbarBrand>
<Collapse navbar isOpen={this.state.isOpen}>
<Nav className="ml-auto" navbar>
<NavItem>
{user}
</NavItem>
</Nav>
</Collapse>
</Navbar>
);
}
}
const mapStateToProps = (state) => {
return {
isLoggedIn: state.user.isLoggedIn,
myUserData: state.user.myUserData,
};
};
export default connect(mapStateToProps)(NavBar);
|
src/examples/redux/separate-files/index.js | vinogradov/react-starter-kit | import React from 'react';
import ReactDOM from 'react-dom';
import {createStore, applyMiddleware} from 'redux';
import {Provider} from 'react-redux';
import createSagaMiddleware from 'redux-saga';
import 'regenerator-runtime/runtime'; // eslint-disable-line import/no-extraneous-dependencies
import logger from 'redux-logger';
import {reducers} from './reducers';
import {Counter} from './counter';
import {watchDecrementAsync} from './sagas';
const sagaMiddleware = createSagaMiddleware();
const store = createStore(
reducers,
applyMiddleware(sagaMiddleware, logger));
sagaMiddleware.run(watchDecrementAsync);
ReactDOM.render(
<Provider store={store}>
<Counter />
</Provider>,
document.querySelector('#app')
);
|
src/components/source/mediaSource/suggest/PendingSuggestionsContainer.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import Link from 'react-router/lib/Link';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { Grid, Row, Col } from 'react-flexbox-grid/lib';
import { fetchSourceSuggestions, updateSourceSuggestion } from '../../../../actions/sourceActions';
import withAsyncData from '../../../common/hocs/AsyncDataContainer';
import SourceSuggestion from './SourceSuggestion';
import PageTitle from '../../../common/PageTitle';
const localMessages = {
title: { id: 'sources.suggestions.pending.title', defaultMessage: 'Pending Suggestions' },
intro: { id: 'sources.suggestions.pending.intro', defaultMessage: 'Here is a list of media source suggestions made by users. Approve or reject them as you see fit!' },
history: { id: 'sources.suggestions.pending.historyLink', defaultMessage: 'See a full history of suggestions.' },
};
const PendingSuggestionsContainer = ({ suggestions, handleApprove, handleReject }) => (
<Grid>
<Row>
<Col lg={12} md={12} sm={12}>
<PageTitle value={localMessages.title} />
<h1><FormattedMessage {...localMessages.title} /></h1>
<p><FormattedMessage {...localMessages.intro} /></p>
<p>
<Link to="/sources/suggestions/history">
<FormattedMessage {...localMessages.history} />
</Link>
</p>
</Col>
</Row>
<Row>
{ suggestions.map(s => (
<Col key={s.media_suggestions_id} lg={12}>
<SourceSuggestion suggestion={s} markable onApprove={handleApprove} onReject={handleReject} />
</Col>
))}
</Row>
</Grid>
);
PendingSuggestionsContainer.propTypes = {
// from the composition chain
intl: PropTypes.object.isRequired,
// from parent
// from state
fetchStatus: PropTypes.string.isRequired,
suggestions: PropTypes.array.isRequired,
// from dispatch
handleApprove: PropTypes.func,
handleReject: PropTypes.func,
};
const mapStateToProps = state => ({
fetchStatus: state.sources.sources.suggestions.fetchStatus,
suggestions: state.sources.sources.suggestions.list,
});
const mapDispatchToProps = dispatch => ({
handleApprove: (suggestion, reason) => {
dispatch(updateSourceSuggestion({
suggestionId: suggestion.media_suggestions_id,
status: 'approved',
reason,
})).then(() => dispatch(fetchSourceSuggestions({ all: false })));
},
handleReject: (suggestion, reason) => {
dispatch(updateSourceSuggestion({
suggestionId: suggestion.media_suggestions_id,
status: 'rejected',
reason,
})).then(() => dispatch(fetchSourceSuggestions({ all: false })));
},
});
const fetchAsyncData = dispatch => dispatch(fetchSourceSuggestions({ all: false }));
export default
injectIntl(
connect(mapStateToProps, mapDispatchToProps)(
withAsyncData(fetchAsyncData)(
PendingSuggestionsContainer
)
)
);
|
internals/templates/containers/App/index.js | VeloCloud/website-ui | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
src/svg-icons/device/signal-cellular-connected-no-internet-4-bar.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet4Bar = (props) => (
<SvgIcon {...props}>
<path d="M20 18h2v-8h-2v8zm0 4h2v-2h-2v2zM2 22h16V8h4V2L2 22z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet4Bar = pure(DeviceSignalCellularConnectedNoInternet4Bar);
DeviceSignalCellularConnectedNoInternet4Bar.displayName = 'DeviceSignalCellularConnectedNoInternet4Bar';
DeviceSignalCellularConnectedNoInternet4Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet4Bar;
|
docs/src/pages/components/snackbars/CustomizedSnackbars.js | lgollut/material-ui | import React from 'react';
import Button from '@material-ui/core/Button';
import Snackbar from '@material-ui/core/Snackbar';
import MuiAlert from '@material-ui/lab/Alert';
import { makeStyles } from '@material-ui/core/styles';
function Alert(props) {
return <MuiAlert elevation={6} variant="filled" {...props} />;
}
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
'& > * + *': {
marginTop: theme.spacing(2),
},
},
}));
export default function CustomizedSnackbars() {
const classes = useStyles();
const [open, setOpen] = React.useState(false);
const handleClick = () => {
setOpen(true);
};
const handleClose = (event, reason) => {
if (reason === 'clickaway') {
return;
}
setOpen(false);
};
return (
<div className={classes.root}>
<Button variant="outlined" onClick={handleClick}>
Open success snackbar
</Button>
<Snackbar open={open} autoHideDuration={6000} onClose={handleClose}>
<Alert onClose={handleClose} severity="success">
This is a success message!
</Alert>
</Snackbar>
<Alert severity="error">This is an error message!</Alert>
<Alert severity="warning">This is a warning message!</Alert>
<Alert severity="info">This is an information message!</Alert>
<Alert severity="success">This is a success message!</Alert>
</div>
);
}
|
ui/src/main/frontend/src/components/AsyncComponent.js | Dokuro-YH/alice-projects | import React, { Component } from 'react';
export default function asyncComponent(importComponent) {
class AsyncComponent extends Component {
constructor(props) {
super(props);
this.state = {
component: null
};
}
async componentDidMount() {
const { default: component } = await importComponent();
this.setState({
component: component
});
}
render() {
const C = this.state.component;
return C ? <C {...this.props} /> : null;
}
}
return AsyncComponent;
} |
frontend/src/Components/Loading/LoadingMessage.js | geogolem/Radarr | import React from 'react';
import styles from './LoadingMessage.css';
const messages = [
'Downloading more RAM',
'Now in Technicolor',
'Previously on Radarr...',
'Bleep Bloop.',
'Locating the required gigapixels to render...',
'Spinning up the hamster wheel...',
'At least you\'re not on hold',
'Hum something loud while others stare',
'Loading humorous message... Please Wait',
'I could\'ve been faster in Python',
'Don\'t forget to rewind your movies',
'Congratulations! you are the 1000th visitor.',
'HELP! I\'m being held hostage and forced to write these stupid lines!',
'RE-calibrating the internet...',
'I\'ll be here all week',
'Don\'t forget to tip your waitress',
'Apply directly to the forehead',
'Loading Battlestation'
];
let message = null;
function LoadingMessage() {
if (!message) {
const index = Math.floor(Math.random() * messages.length);
message = messages[index];
}
return (
<div className={styles.loadingMessage}>
{message}
</div>
);
}
export default LoadingMessage;
|
platform/viewer/src/routes/CallbackPage.js | OHIF/Viewers | import React, { Component } from 'react';
import { withRouter } from 'react-router-dom';
import PropTypes from 'prop-types';
import { CallbackComponent } from 'redux-oidc';
class CallbackPage extends Component {
static propTypes = {
userManager: PropTypes.object.isRequired,
history: PropTypes.object.isRequired,
};
render() {
return (
<CallbackComponent
userManager={this.props.userManager}
successCallback={() => {
const { pathname, search = '' } = JSON.parse(
sessionStorage.getItem('ohif-redirect-to')
);
this.props.history.push({ pathname, search });
}}
errorCallback={error => {
//this.props.history.push("/");
throw new Error(error);
}}
>
<div>Redirecting...</div>
</CallbackComponent>
);
}
}
export default withRouter(CallbackPage);
|
core/src/plugins/editor.codemirror/res/js/editor.js | huzergackl/pydio-core | /*
* Copyright 2007-2017 Charles du Jeu - Abstrium SAS <team (at) pyd.io>
* This file is part of Pydio.
*
* Pydio is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Pydio is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Pydio. If not, see <http://www.gnu.org/licenses/>.
*
* The latest code can be found at <https://pydio.com>.
*/
import Pydio from 'pydio'
import React from 'react';
import { connect } from 'react-redux';
import { compose } from 'redux';
import CodeMirrorLoader from './CodeMirrorLoader';
const {EditorActions} = Pydio.requireLib('hoc');
class Editor extends React.Component {
constructor(props) {
super(props)
const {node, tab, dispatch} = this.props
const {id} = tab
if (!id) dispatch(EditorActions.tabCreate({id: node.getLabel(), node}))
}
componentDidMount() {
const {pydio, node, tab, dispatch} = this.props
const {id} = tab
pydio.ApiClient.request({
get_action: 'get_content',
file: node.getPath()
}, ({responseText}) => dispatch(EditorActions.tabModify({id: id || node.getLabel(), lineNumbers: true, content: responseText})));
}
render() {
const {node, tab, error, dispatch} = this.props
if (!tab) return null
const {id, codemirror, content, lineWrapping, lineNumbers} = tab
return (
<CodeMirrorLoader
{...this.props}
url={node.getPath()}
content={content}
options={{lineNumbers: lineNumbers, lineWrapping: lineWrapping}}
error={error}
onLoad={codemirror => dispatch(EditorActions.tabModify({id, codemirror}))}
onChange={content => dispatch(EditorActions.tabModify({id, content}))}
onCursorChange={cursor => dispatch(EditorActions.tabModify({id, cursor}))}
/>
)
}
}
export const mapStateToProps = (state, props) => {
const {tabs} = state
const tab = tabs.filter(({editorData, node}) => (!editorData || editorData.id === props.editorData.id) && node.getPath() === props.node.getPath())[0] || {}
return {
id: tab.id,
tab,
...props
}
}
export default connect(mapStateToProps)(Editor)
|
src/TextField/TextFieldUnderline.js | hai-cea/material-ui | import React from 'react';
import PropTypes from 'prop-types';
import transitions from '../styles/transitions';
const propTypes = {
/**
* True if the parent `TextField` is disabled.
*/
disabled: PropTypes.bool,
/**
* Override the inline-styles of the underline when parent `TextField` is disabled.
*/
disabledStyle: PropTypes.object,
/**
* True if the parent `TextField` has an error.
*/
error: PropTypes.bool,
/**
* Override the inline-styles of the underline when parent `TextField` has an error.
*/
errorStyle: PropTypes.object,
/**
* True if the parent `TextField` is focused.
*/
focus: PropTypes.bool,
/**
* Override the inline-styles of the underline when parent `TextField` is focused.
*/
focusStyle: PropTypes.object,
/**
* @ignore
* The material-ui theme applied to this component.
*/
muiTheme: PropTypes.object.isRequired,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
};
const defaultProps = {
disabled: false,
disabledStyle: {},
error: false,
errorStyle: {},
focus: false,
focusStyle: {},
style: {},
};
const TextFieldUnderline = (props) => {
const {
disabled,
disabledStyle,
error,
errorStyle,
focus,
focusStyle,
muiTheme,
style,
} = props;
const {
color: errorStyleColor,
} = errorStyle;
const {
prepareStyles,
textField: {
borderColor,
disabledTextColor,
errorColor,
focusColor,
},
} = muiTheme;
const styles = {
root: {
borderTop: 'none',
borderLeft: 'none',
borderRight: 'none',
borderBottomStyle: 'solid',
borderBottomWidth: 1,
borderColor: borderColor,
bottom: 8,
boxSizing: 'content-box',
margin: 0,
position: 'absolute',
width: '100%',
},
disabled: {
borderBottomStyle: 'dotted',
borderBottomWidth: 2,
borderColor: disabledTextColor,
},
focus: {
borderBottomStyle: 'solid',
borderBottomWidth: 2,
borderColor: focusColor,
transform: 'scaleX(0)',
transition: transitions.easeOut(),
},
error: {
borderColor: errorStyleColor ? errorStyleColor : errorColor,
transform: 'scaleX(1)',
},
};
let underline = Object.assign({}, styles.root, style);
let focusedUnderline = Object.assign({}, underline, styles.focus, focusStyle);
if (disabled) underline = Object.assign({}, underline, styles.disabled, disabledStyle);
if (focus) focusedUnderline = Object.assign({}, focusedUnderline, {transform: 'scaleX(1)'});
if (error) focusedUnderline = Object.assign({}, focusedUnderline, styles.error);
return (
<div>
<hr aria-hidden="true" style={prepareStyles(underline)} />
<hr aria-hidden="true" style={prepareStyles(focusedUnderline)} />
</div>
);
};
TextFieldUnderline.propTypes = propTypes;
TextFieldUnderline.defaultProps = defaultProps;
export default TextFieldUnderline;
|
src/server.js | sallen450/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
const server = global.server = express();
const port = process.env.PORT || 5000;
server.set('port', port);
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
server.use(express.static(path.join(__dirname, 'public')));
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '' };
const css = [];
const context = {
onInsertCss: value => css.push(value),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(port, () => {
/* eslint-disable no-console */
console.log(`The server is running at http://localhost:${port}/`);
});
|
client/src/Logout.js | panter/mykonote | import React, { Component } from 'react';
import { withRouter } from 'react-router';
import { ajax } from './ajax';
import AlertFlash from './AlertFlash';
import { scrollToTop } from './scroll';
import { ReactComponent as LogoutIcon } from './icons/material/logout-24px.svg';
class Logout extends Component {
render() {
return (
<button name="logout" onClick={this.handleClicked.bind(this)} className="icon-lg big pseudo">
<LogoutIcon />
<span className="icon-lg-text">Logout</span>
</button>
);
}
handleClicked(e) {
e.preventDefault();
ajax('/users/sign_out', 'DELETE')
.then(() => {
window.location.reload();
})
.catch(() => {
AlertFlash.show('Apologies, logging out did not happen.')
})
.finally(scrollToTop);
}
}
export default withRouter(Logout);
|
apps/shared/form/RadioList.js | AusDTO/dto-digitalmarketplace-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { Control } from 'react-redux-form'
import StatefulError from './StatefulError'
import styles from './RadioList.scss'
const RadioList = props => {
const { id, label, name, options, model, messages, validators, onChange } = props
return (
<div className="field">
<fieldset>
{label !== '' && <legend>{label}</legend>}
<div>
{options.map(option => {
const fieldId = `${id}-${option.value}`
return (
<div key={fieldId} className="radio-list-container">
<div className={`au-control-input au-control-input--full ${styles.control}`}>
<Control.radio
model={model}
name={name}
id={fieldId}
mapProps={{
className: 'au-control-input__input'
}}
value={option.value}
validators={validators}
onChange={onChange}
/>
<label className="au-control-input__text" htmlFor={fieldId}>
{option.label}
</label>
</div>
</div>
)
})}
</div>
<StatefulError model={model} messages={messages} id={id} showMessagesDuringFocus="false" />
</fieldset>
</div>
)
}
RadioList.defaultProps = {
validators: null,
messages: null
}
RadioList.propTypes = {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
model: PropTypes.oneOfType([PropTypes.func, PropTypes.string]).isRequired,
options: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
})
).isRequired,
validators: PropTypes.object,
messages: PropTypes.object
}
export default RadioList
|
pootle/static/js/auth/components/AccountInactive.js | Avira/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
'use strict';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import AuthContent from './AuthContent';
let AccountInactive = React.createClass({
mixins: [PureRenderMixin],
propTypes: {
onClose: React.PropTypes.func.isRequired,
},
/* Layout */
render() {
return (
<AuthContent>
<p>{gettext('Your account is inactive because an administrator deactivated it.')}</p>
<div className="actions">
<button
className="btn btn-primary"
onClick={this.props.onClose}
>
{gettext('Close')}
</button>
</div>
</AuthContent>
);
}
});
export default AccountInactive;
|
host/Chart.js | xeejp/chicken-race | import React from 'react'
import { connect } from 'react-redux'
import throttle from 'react-throttle-render'
import { addLog } from './actions'
import HighCharts from 'react-highcharts'
import RaisedButton from 'material-ui/RaisedButton'
function usersToData(name, users) {
const data = [[0, 0]]
Object.keys(users).map(key => {
const user = users[key]
if (user && user.prize) {
data.push([user.prize, user.exitedUsers + 1])
}
})
data.sort(([a], [b]) => a - b)
return {
animation: false,
name,
data
}
}
const actionCreators = { addLog }
const mapStateToProps = ({ users, log }) => {
const series = []
series.push(usersToData("現在進行中のゲーム", users))
log.forEach(old => series.push(usersToData("過去のデータ", old)))
const config = {
chart: {
animation: false
},
title: {
text: '退席ゲーム',
},
xAxis: {
title: {
text: '報酬(ポイント)'
},
allowDecimals: false
},
yAxis: {
title: {
text: '人数(人)'
},
allowDecimals: false
},
series
}
return {
config
}
}
const Chart = ({ config, addLog }) => (
<div>
<HighCharts config={config} />
<RaisedButton
label="現在の実験情報を保存する"
onClick={addLog}
/>
</div>
)
export default connect(mapStateToProps, actionCreators)(throttle(Chart, 200))
|
client/src/components/shared/Info/RelationList.js | verejnedigital/verejne.digital | // @flow
import React from 'react'
import {Badge} from 'reactstrap'
import {sortBy} from 'lodash'
import RecursiveInfo from './RecursiveInfo'
import {showRelationType, getRelationTitle, getColor} from '../utilities'
import type {RelatedEntity} from '../../../state'
type RelationListProps = {
data: Array<RelatedEntity>,
name: string,
}
type RelationItemProps = {
related: RelatedEntity,
name: string,
}
type TitleBadgeProps = {
related: RelatedEntity,
name: string,
}
export default ({data, name, useNewApi}: RelationListProps) => (
<ul className="list-unstyled info-button-list">
{sortBy(data, [
'political_entity',
'contact_with_politics',
'trade_with_government',
'edge_types',
]).reverse().map((related: RelatedEntity) => (
<RelationItem key={related.eid} related={related} name={name} />
))}
</ul>
)
const RelationItem = ({related, name}: RelationItemProps) => (
<li key={related.eid} className="">
<RecursiveInfo
related={related}
badge={<TitleBadge key={related.eid} related={related} name={name} />}
/>
</li>
)
const TitleBadge = ({related, name}: TitleBadgeProps) => {
const result = []
related.edge_types.forEach((type: number, i: number) => {
const symmetric: boolean = related.edge_types.includes(-type)
if (type >= 0 || !symmetric) {
result.push(
<Badge
key={type}
color={getColor(type, related.edge_effective_to_dates[i])}
title={getRelationTitle(
type,
name,
related.name,
related.edge_effective_to_dates[i],
symmetric,
)}
className="mr-1 info-badge"
>
{showRelationType(
type,
related.edge_type_texts[i],
related.edge_effective_to_dates[i],
!symmetric
)}
</Badge>
)
}
})
return result
}
|
ngiiedu-client/src/components/courses/create/Step2Work.js | jinifor/branchtest | import React from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
class Step2Work extends React.Component {
constructor() {
super();
this.state = {
items: [],
selectedRows: []
};
this.onSelectionWork = this.onSelectionWork.bind(this);
this.isSelected = this.isSelected.bind(this);
}
componentDidMount() {
console.log('componentDidMount');
const {selectedModule} = this.state;
ajaxJson(
['GET', apiSvr+'/modules/' + this.props.selectedModule + '/moduleWork.json'],
null,
function(res) {
this.setState({
items: res.response.data
});
let workIds = [];
for (let n of this.props.selectedItems) {
this.state.items.map(function(v, i) {
if (n == v.idx) {
console.log(n)
workIds.push(i);
return;
}
});
}
this.setState({
selectedRows: workIds
});
}.bind(this),
function(xhr, status, err) {
alert('Error');
}.bind(this)
);
}
isSelected(index) {
return this.state.selectedRows.indexOf(index) !== -1;
}
onSelectionWork(selectedRows) {
this.setState({
selectedRows: selectedRows
});
let workIds = [];
for (let n of selectedRows) {
this.state.items.map(function(v, i) {
if (n == i) {
workIds.push(v.idx);
return;
}
});
}
console.log(workIds);
this.props.onSelectedWorks(workIds);
}
render() {
return (
<div style={{textAlign: 'center'}}>
{(() => {
const {items} = this.state;
if (items.length > 0) {
let tableRows = (
items.map((item, index) => (
<TableRow
key={index}
selected={this.isSelected(index)}
>
<TableRowColumn checked>{item.moduleWorkCourseType}</TableRowColumn>
<TableRowColumn>{item.moduleWorkName}</TableRowColumn>
</TableRow>
))
);
return (
<Table
selectable
multiSelectable
showCheckboxes
onRowSelection={this.onSelectionWork}
>
<TableBody
displayRowCheckbox
deselectOnClickaway={false}
>
{tableRows}
</TableBody>
</Table>
)
} else {
return(
<div>
<img src="https://react.semantic-ui.com//assets/images/wireframe/paragraph.png" />
</div>
)
}
})()}
</div>
)
}
}
export default Step2Work;
|
client/components/__tests__/Team.spec.js | bjoberg/social-pulse | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import { Team } from '../Team/Team';
test('renders team members information correctly', t => {
const wrapper = shallow(
<Team />
);
t.is(wrapper.find('p').length, 7);
t.is(wrapper.find('h1').length, 1);
t.is(wrapper.find('h2').length, 7);
t.is(wrapper.find('hr').length, 6);
});
|
packages/material-ui-icons/src/CastForEducationSharp.js | lgollut/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path d="M23 3H1v5h2V5h18v14h-7v2h9V3zM1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11zm10 1.09v2L14.5 15l3.5-1.91v-2L14.5 13 11 11.09zM14.5 6L9 9l5.5 3L20 9l-5.5-3z" /></React.Fragment>
, 'CastForEducationSharp');
|
docs/app/Examples/views/Statistic/Types/index.js | vageeshb/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const Types = () => (
<ExampleSection title='Types'>
<ComponentExample
title='Statistic'
description='A statistic can display a value with a label above or below it.'
examplePath='views/Statistic/Types/StatisticExampleBottomLabel'
/>
<ComponentExample examplePath='views/Statistic/Types/StatisticExampleTopLabel' />
<ComponentExample
title='Statistic Group'
description='A group of statistics.'
examplePath='views/Statistic/Types/StatisticExampleGroups'
/>
<ComponentExample
title='Statistic Group Colored'
description='A group of colored statistics.'
examplePath='views/Statistic/Types/StatisticExampleGroupColored'
/>
<ComponentExample
title='Statistic Group Size'
description='A group of statistics can vary in size.'
examplePath='views/Statistic/Types/StatisticExampleGroupSize'
/>
<ComponentExample
title='Statistic Group Inverted'
description='A group of statistics can be formatted to fit on a dark background.'
examplePath='views/Statistic/Types/StatisticExampleGroupInverted'
/>
</ExampleSection>
)
export default Types
|
resources/src/js/components/Finder/components/Header.js | aberon10/thermomusic.com | 'use strict';
// Dependencies
import React from 'react';
import PropTypes from 'prop-types';
const resetInput = (e) => {
e.target.value = '';
};
export default class Header extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="panel-queuelist__header">
<div className="panel-headings">
<div className="form">
<div className="input-group">
<input type="search" className="form-control" placeholder="Buscar..." onKeyUp={this.props.keyUpEventHandler} id="search" autoComplete="off" maxLength="150"/>
</div>
</div>
</div>
<span className="icon-close panel-button panel-button__close" id="close-finder" onClick={this.props.clickEventHandler}></span>
</div>
);
}
}
Header.propTypes = {
clickEventHandler: PropTypes.func,
keyUpEventHandler: PropTypes.func
};
|
public/src/components/Home.js | dolchi21/open-prices-web | import React from 'react';
import LoginForm from '../containers/LoginForm.js';
require('/css/Home.less');
var Home = React.createClass({
render : function render(){
return (
<div id="Home">
<div>
<h1>HOME</h1>
</div>
<div>
<a href="/login">login</a>
</div>
</div>
);
}
});
export default Home;
|
src/index.js | C3-TKO/junkan | import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import configureStore from './stores';
import { IntlProvider } from 'react-intl';
import App from './containers/App';
import messages from './intl/en';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
const store = configureStore();
const MuiTheme = getMuiTheme({
palette: {
primary1Color: '#005e34',
accent1Color: '#ffa800',
textColor: '#005e34'
}
});
render(
<Provider store={store}>
<IntlProvider locale='en' messages={messages}>
<MuiThemeProvider muiTheme={MuiTheme}>
<App />
</MuiThemeProvider>
</IntlProvider>
</Provider>,
document.getElementById('app')
);
|
archimate-frontend/src/main/javascript/components/view/nodes/model_t/device.js | zhuj/mentha-web-archimate | import React from 'react'
import { BaseNodeLikeWidget } from '../_base'
export const TYPE='device';
export class DeviceWidget extends BaseNodeLikeWidget {
getClassName(node) { return 'a-node model_t device'; }
}
|
src/index.js | johnie/jobb.johnie.se | import React from 'react';
import ReactDOM from 'react-dom';
// Your top level component
import App from './App';
// Export your top level component as JSX (for static rendering)
export default App;
// Render your app
if (typeof document !== 'undefined') {
window.addEventListener('load', () => {
const ga = window.ga;
ga('create', 'UA-17365662-21', 'auto');
ga('send', 'pageview');
});
const renderMethod = module.hot
? ReactDOM.render
: ReactDOM.hydrate || ReactDOM.render;
const render = Comp => {
renderMethod(<Comp />, document.getElementById('root'));
};
// Render!
render(App);
}
|
packages/reactor-tests/src/tests/createChild/InsertStart.js | sencha/extjs-reactor | import React, { Component } from 'react';
import { Panel, Button, Container } from '@extjs/ext-react';
export default class InsertStart extends Component {
state = {
showInserted: false
}
insert = () => {
this.setState({ showInserted: true })
}
render() {
const { showInserted } = this.state;
return (
<Panel>
{ showInserted && <Container itemId="inserted">inserted</Container> }
<Container>top</Container>
<Button handler={this.insert} text="Insert" itemId="insert"/>
<Container>bottom</Container>
</Panel>
)
}
}
|
web/app/admin/users.js | seanhess/serials | // @flow
// @flow
import React from 'react'
import {Link} from 'react-router'
import {User, Users, userApiURL} from '../model/user'
import {reloadHandler} from '../data/load'
import {makeUpdate} from '../data/update'
import {toDateString} from '../helpers'
import {clickable} from '../style'
import {sortBy, reverse} from 'lodash'
import {Routes} from '../router'
// should farm them out to other display components
// should have model functions that do all the lifting
// but it needs to reload too ... hmm ...
type UsersProps = {
users: Array<User>
}
export class AdminUsers extends React.Component {
props: UsersProps;
static load(params) {
return {users: Users.loadAll()}
}
delete(id:string) {
Users.delete(id)
.then(reloadHandler)
}
render():React.Element {
var users = sortBy(this.props.users || [], u => u.created).reverse()
return <div>
<h2>Users</h2>
<UsersList users={users}
onDelete={this.delete.bind(this)}
/>
</div>
}
}
export class UsersList extends React.Component {
render():React.Element {
return <table>
<tr>
<th></th>
<th>Name</th>
<th>Email</th>
<th>Books</th>
<th>Created</th>
<th></th>
</tr>
{this.props.users.map(this.renderRow.bind(this))}
</table>
}
renderRow(user:User):React.Element {
return <tr>
<td><a href={userApiURL(user.id)}><span className="fa fa-code"></span></a></td>
<td>{user.firstName} {user.lastName}</td>
<td>{user.email}</td>
<td><Link to={Routes.bookshelf} params={user}><span className="fa fa-book"></span></Link></td>
<td>{toDateString(user.created)}</td>
<td><a onClick={() => this.props.onDelete(user.id)} style={clickable}>
<span className="fa fa-trash"></span>
</a></td>
</tr>
}
}
|
app/javascript/mastodon/features/niconico/components/connect_account.js | masarakki/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePureComponent from 'react-immutable-pure-component';
class ConnectAccount extends ImmutablePureComponent {
static propTypes = {
nico_url: PropTypes.string,
};
connectedLink(nico_url) {
return (
<a
href={nico_url}
target='_blank'
rel='noopener'
>
<span className='nico-connect-account__label'>
niconicoアカウントと連携済み
</span>
</a>
);
}
connectLink() {
return (
<a
className='nico-connect-account__wrapper'
href='/auth/auth/niconico'
>
<span className='nico-connect-account__label nico-connect-account__label--disabled'>
niconicoアカウントと連携する
</span>
</a>
);
}
render() {
const { nico_url } = this.props;
return (
<div className='nico-connect-account'>
{nico_url ? this.connectedLink(nico_url) : this.connectLink()}
</div>
);
}
}
export default ConnectAccount;
|
src/app/components/Groups/Badge.js | sphinxominator/councils-feathers | import React from 'react'
import styled from 'styled-components'
const Badge = ({ name, color, id, onClick, active, showLetter }) =>
<Container
onClick={() => onClick && onClick(id)}
active={active}
color={color}
>
{showLetter &&
<Letter color={color} active={active}>
{name.charAt(0)}
</Letter>}
{name}
</Container>
const Letter = styled.span`
background-color: ${props =>
props.active ? props.color : 'hsla(0,0%,78%,1)'};
border-radius: ${props => props.theme.rounding};
color: white;
display: inline-flex;
height: 1rem;
justify-content: center;
margin-right: .5rem;
padding: .5rem;
text-transform: capitalize;
width: 1rem;
`
const Container = styled.div`
align-items: center;
background-color: ${props =>
props.active ? props.color : 'hsla(0,0%,78%,1)'};
border-radius: ${props => props.theme.rounding};
border: 1px solid #e6e6e6;
color: white;
cursor: pointer;
display: flex;
margin: 0 .5rem .5rem 0;
min-height: 2rem;
min-width: 6rem;
padding-right: .5rem;
position: relative;
text-transform: capitalize;
&:hover {
#background-color: hsla(0, 0%, 78%, 1);
cursor: pointer;
}
`
Badge.defaultProps = {
color: 'green',
showLetter: true
}
export default Badge
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.