path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
packages/benchmarks/reshadow/client/index.js | A-gambit/CSS-IN-JS-Benchmarks | import ReactDOM from 'react-dom';
import React from 'react';
import App from 'benchmarks-utils';
import Table from './Table';
import './index.html';
ReactDOM.render(<App table={Table} />, document.getElementById('root'));
|
src/routes/about/index.js | niketpathak/npk-website | /**
* @author Niket Pathak. (http://www.niketpathak.com/)
*
* Copyright © 2014-present. 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 Layout from '../../components/Layout';
import Page from '../../components/Page';
import about from './about.md';
function action() {
return {
chunks: ['about'],
title: about.title,
component: <Layout><Page {...about} /></Layout>,
};
}
export default action;
|
app/containers/Home/HomePage.js | DenQ/electron-react-lex | // @flow
import React, { Component } from 'react';
import Home from '../../components/Home/Home';
export default class HomePage extends Component {
render() {
return (
<Home />
);
}
}
|
app/components/TodoEntry.js | ernieturner/webpack-redux-boilerplate | import React from 'react';
class TodoEntry extends React.Component {
constructor(props, context){
super(props, context);
this.state = {
todoText: ""
};
}
onTextChange(evt){
this.setState({
todoText: event.target.value
});
}
addTodo(){
if(this.state.todoText === ""){
return;
}
this.props.addTodo(this.state.todoText);
this.setState({
todoText: ""
});
}
render() {
return (
<div className="todo-entry">
<input type="text" onChange={this.onTextChange.bind(this)} value={this.state.todoText}/>
<button onClick={this.addTodo.bind(this)}><i className="fa fa-plus-circle"/>Add Todos</button>
</div>
);
}
}
TodoEntry.propTypes = {
addTodo: React.PropTypes.func.isRequired
};
module.exports = TodoEntry; |
Libraries/Text/Text.js | Ehesp/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Text
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheetPropType = require('StyleSheetPropType');
const TextStylePropTypes = require('TextStylePropTypes');
const Touchable = require('Touchable');
const createReactNativeComponentClass = require('createReactNativeComponentClass');
const mergeFast = require('mergeFast');
const processColor = require('processColor');
const stylePropType = StyleSheetPropType(TextStylePropTypes);
const viewConfig = {
validAttributes: mergeFast(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
numberOfLines: true,
ellipsizeMode: true,
allowFontScaling: true,
disabled: true,
selectable: true,
selectionColor: true,
adjustsFontSizeToFit: true,
minimumFontScale: true,
textBreakStrategy: true,
}),
uiViewClassName: 'RCTText',
};
/**
* A React component for displaying text.
*
* `Text` supports nesting, styling, and touch handling.
*
* In the following example, the nested title and body text will inherit the `fontFamily` from
*`styles.baseText`, but the title provides its own additional styles. The title and body will
* stack on top of each other on account of the literal newlines:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, Text, StyleSheet } from 'react-native';
*
* export default class TextInANest extends Component {
* constructor(props) {
* super(props);
* this.state = {
* titleText: "Bird's Nest",
* bodyText: 'This is not really a bird nest.'
* };
* }
*
* render() {
* return (
* <Text style={styles.baseText}>
* <Text style={styles.titleText} onPress={this.onPressTitle}>
* {this.state.titleText}{'\n'}{'\n'}
* </Text>
* <Text numberOfLines={5}>
* {this.state.bodyText}
* </Text>
* </Text>
* );
* }
* }
*
* const styles = StyleSheet.create({
* baseText: {
* fontFamily: 'Cochin',
* },
* titleText: {
* fontSize: 20,
* fontWeight: 'bold',
* },
* });
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('TextInANest', () => TextInANest);
* ```
*/
// $FlowFixMe(>=0.41.0)
const Text = React.createClass({
propTypes: {
/**
* When `numberOfLines` is set, this prop defines how text will be truncated.
* `numberOfLines` must be set in conjunction with this prop.
*
* This can be one of the following values:
*
* - `head` - The line is displayed so that the end fits in the container and the missing text
* at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz"
* - `middle` - The line is displayed so that the beginning and end fit in the container and the
* missing text in the middle is indicated by an ellipsis glyph. "ab...yz"
* - `tail` - The line is displayed so that the beginning fits in the container and the
* missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..."
* - `clip` - Lines are not drawn past the edge of the text container.
*
* The default is `tail`.
*
* > `clip` is working only for iOS
*/
ellipsizeMode: PropTypes.oneOf(['head', 'middle', 'tail', 'clip']),
/**
* Used to truncate the text with an ellipsis after computing the text
* layout, including line wrapping, such that the total number of lines
* does not exceed this number.
*
* This prop is commonly used with `ellipsizeMode`.
*/
numberOfLines: PropTypes.number,
/**
* Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`
* The default value is `highQuality`.
* @platform android
*/
textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']),
/**
* Invoked on mount and layout changes with
*
* `{nativeEvent: {layout: {x, y, width, height}}}`
*/
onLayout: PropTypes.func,
/**
* This function is called on press.
*
* e.g., `onPress={() => console.log('1st')}`
*/
onPress: PropTypes.func,
/**
* This function is called on long press.
*
* e.g., `onLongPress={this.increaseSize}>`
*/
onLongPress: PropTypes.func,
/**
* When the scroll view is disabled, this defines how far your touch may
* move off of the button, before deactivating the button. Once deactivated,
* try moving it back and you'll see that the button is once again
* reactivated! Move it back and forth several times while the scroll view
* is disabled. Ensure you pass in a constant to reduce memory allocations.
*/
pressRetentionOffset: EdgeInsetsPropType,
/**
* Lets the user select text, to use the native copy and paste functionality.
*/
selectable: PropTypes.bool,
/**
* The highlight color of the text.
* @platform android
*/
selectionColor: ColorPropType,
/**
* When `true`, no visual change is made when text is pressed down. By
* default, a gray oval highlights the text on press down.
* @platform ios
*/
suppressHighlighting: PropTypes.bool,
style: stylePropType,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
/**
* Used to locate this view from native code.
* @platform android
*/
nativeID: PropTypes.string,
/**
* Specifies whether fonts should scale to respect Text Size accessibility settings. The
* default is `true`.
*/
allowFontScaling: PropTypes.bool,
/**
* When set to `true`, indicates that the view is an accessibility element. The default value
* for a `Text` element is `true`.
*
* See the
* [Accessibility guide](docs/accessibility.html#accessible-ios-android)
* for more information.
*/
accessible: PropTypes.bool,
/**
* Specifies whether font should be scaled down automatically to fit given style constraints.
* @platform ios
*/
adjustsFontSizeToFit: PropTypes.bool,
/**
* Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0).
* @platform ios
*/
minimumFontScale: PropTypes.number,
/**
* Specifies the disabled state of the text view for testing purposes
* @platform android
*/
disabled: PropTypes.bool,
},
getDefaultProps(): Object {
return {
accessible: true,
allowFontScaling: true,
ellipsizeMode: 'tail',
disabled: false,
};
},
getInitialState: function(): Object {
return mergeFast(Touchable.Mixin.touchableGetInitialState(), {
isHighlighted: false,
});
},
mixins: [NativeMethodsMixin],
viewConfig: viewConfig,
getChildContext(): Object {
return {isInAParentText: true};
},
childContextTypes: {
isInAParentText: PropTypes.bool
},
contextTypes: {
isInAParentText: PropTypes.bool
},
/**
* Only assigned if touch is needed.
*/
_handlers: (null: ?Object),
_hasPressHandler(): boolean {
return !!this.props.onPress || !!this.props.onLongPress;
},
/**
* These are assigned lazily the first time the responder is set to make plain
* text nodes as cheap as possible.
*/
touchableHandleActivePressIn: (null: ?Function),
touchableHandleActivePressOut: (null: ?Function),
touchableHandlePress: (null: ?Function),
touchableHandleLongPress: (null: ?Function),
touchableGetPressRectOffset: (null: ?Function),
render(): React.Element<any> {
let newProps = this.props;
if (this.props.onStartShouldSetResponder || this._hasPressHandler()) {
if (!this._handlers) {
this._handlers = {
onStartShouldSetResponder: (): bool => {
const shouldSetFromProps = this.props.onStartShouldSetResponder &&
// $FlowFixMe(>=0.41.0)
this.props.onStartShouldSetResponder();
const setResponder = shouldSetFromProps || this._hasPressHandler();
if (setResponder && !this.touchableHandleActivePressIn) {
// Attach and bind all the other handlers only the first time a touch
// actually happens.
for (const key in Touchable.Mixin) {
if (typeof Touchable.Mixin[key] === 'function') {
(this: any)[key] = Touchable.Mixin[key].bind(this);
}
}
this.touchableHandleActivePressIn = () => {
if (this.props.suppressHighlighting || !this._hasPressHandler()) {
return;
}
this.setState({
isHighlighted: true,
});
};
this.touchableHandleActivePressOut = () => {
if (this.props.suppressHighlighting || !this._hasPressHandler()) {
return;
}
this.setState({
isHighlighted: false,
});
};
this.touchableHandlePress = (e: SyntheticEvent) => {
this.props.onPress && this.props.onPress(e);
};
this.touchableHandleLongPress = (e: SyntheticEvent) => {
this.props.onLongPress && this.props.onLongPress(e);
};
this.touchableGetPressRectOffset = function(): RectOffset {
return this.props.pressRetentionOffset || PRESS_RECT_OFFSET;
};
}
// $FlowFixMe(>=0.41.0)
return setResponder;
},
onResponderGrant: function(e: SyntheticEvent, dispatchID: string) {
// $FlowFixMe(>=0.41.0)
this.touchableHandleResponderGrant(e, dispatchID);
this.props.onResponderGrant &&
// $FlowFixMe(>=0.41.0)
this.props.onResponderGrant.apply(this, arguments);
}.bind(this),
onResponderMove: function(e: SyntheticEvent) {
// $FlowFixMe(>=0.41.0)
this.touchableHandleResponderMove(e);
this.props.onResponderMove &&
// $FlowFixMe(>=0.41.0)
this.props.onResponderMove.apply(this, arguments);
}.bind(this),
onResponderRelease: function(e: SyntheticEvent) {
// $FlowFixMe(>=0.41.0)
this.touchableHandleResponderRelease(e);
this.props.onResponderRelease &&
// $FlowFixMe(>=0.41.0)
this.props.onResponderRelease.apply(this, arguments);
}.bind(this),
onResponderTerminate: function(e: SyntheticEvent) {
// $FlowFixMe(>=0.41.0)
this.touchableHandleResponderTerminate(e);
this.props.onResponderTerminate &&
// $FlowFixMe(>=0.41.0)
this.props.onResponderTerminate.apply(this, arguments);
}.bind(this),
onResponderTerminationRequest: function(): bool {
// Allow touchable or props.onResponderTerminationRequest to deny
// the request
// $FlowFixMe(>=0.41.0)
var allowTermination = this.touchableHandleResponderTerminationRequest();
if (allowTermination && this.props.onResponderTerminationRequest) {
// $FlowFixMe(>=0.41.0)
allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments);
}
return allowTermination;
}.bind(this),
};
}
newProps = {
...this.props,
...this._handlers,
isHighlighted: this.state.isHighlighted,
};
}
if (newProps.selectionColor != null) {
newProps = {
...newProps,
selectionColor: processColor(newProps.selectionColor)
};
}
if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) {
newProps = {
...newProps,
style: [this.props.style, {color: 'magenta'}],
};
}
if (this.context.isInAParentText) {
return <RCTVirtualText {...newProps} />;
} else {
return <RCTText {...newProps} />;
}
},
});
type RectOffset = {
top: number,
left: number,
right: number,
bottom: number,
}
var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
var RCTText = createReactNativeComponentClass(viewConfig);
var RCTVirtualText = RCTText;
if (Platform.OS === 'android') {
RCTVirtualText = createReactNativeComponentClass({
validAttributes: mergeFast(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
}),
uiViewClassName: 'RCTVirtualText',
});
}
module.exports = Text;
|
boilerplates/project/mobileWeb/src/components/Async/Async.js | FuluUE/vd-generator | import React from 'react';
import PropTypes from 'prop-types';
class Async extends React.Component {
static propTypes = {
}
static defaultProps = {
}
constructor(props) {
super(props);
}
componentWillMount() {
const { props: { dispatch } } = this;
dispatch({ type: 'async/tests' });
}
render() {
return (
<div>
Async
{ console.log(this.props) }
</div>
);
}
}
export default Async;
|
actor-apps/app-web/src/app/utils/require-auth.js | hardikamal/actor-platform | import React from 'react';
import LoginStore from 'stores/LoginStore';
export default (Component) => {
return class Authenticated extends React.Component {
static willTransitionTo(transition) {
if (!LoginStore.isLoggedIn()) {
transition.redirect('/auth', {}, {'nextPath': transition.path});
}
}
render() {
return <Component {...this.props}/>;
}
};
};
|
src/svg-icons/navigation/expand-more.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationExpandMore = (props) => (
<SvgIcon {...props}>
<path d="M16.59 8.59L12 13.17 7.41 8.59 6 10l6 6 6-6z"/>
</SvgIcon>
);
NavigationExpandMore = pure(NavigationExpandMore);
NavigationExpandMore.displayName = 'NavigationExpandMore';
NavigationExpandMore.muiName = 'SvgIcon';
export default NavigationExpandMore;
|
docs/lib/Components/ControlBarPage.js | video-react/video-react | /* eslint react/no-multi-comp: 0, react/prop-types: 0 */
import React from 'react';
import { PrismCode } from 'react-prism';
import { Button } from 'reactstrap';
import Helmet from 'react-helmet';
import ControlBarExample from '../examples/ControlBar';
const ControlBarExampleSource = require('!!raw-loader!../examples/ControlBar');
export default class ControlBarPage extends React.Component {
render() {
return (
<div>
<Helmet title="ControlBar" />
<h3>ControlBar</h3>
<p>
The Html5 video's control bar is hidden, the player offers a
customizable control bar to allow the user to control video playback,
including volume, seeking, and pause/resume playback.
</p>
<div className="docs-example">
<ControlBarExample />
</div>
<pre>
<PrismCode className="language-jsx">
{ControlBarExampleSource}
</PrismCode>
</pre>
<h4>Properties</h4>
<pre>
<PrismCode className="language-jsx">
{`ControlBar.propTypes = {
// Hide the control bar automatically after the player is inactive
// default: true
autoHide: PropTypes.bool,
// The waiting time for auto hide after player is inactive (in milliseconds)
// default: 3000
autoHideTime: PropType.number,
// Do not render default controls, only use custom ones provided as children of <ControlBar>
// default: false
disableDefaultControls: PropTypes.bool,
// Do not render the control bar if set it to true
// default: false
disableCompletely: PropTypes.bool,
}`}
</PrismCode>
</pre>
</div>
);
}
}
|
docs/app/Examples/collections/Breadcrumb/Content/BreadcrumbExampleIconDivider.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Breadcrumb } from 'semantic-ui-react'
const BreadcrumbExampleIconDivider = () => (
<Breadcrumb>
<Breadcrumb.Section link>Home</Breadcrumb.Section>
<Breadcrumb.Divider icon='right chevron' />
<Breadcrumb.Section link>Registration</Breadcrumb.Section>
<Breadcrumb.Divider icon='right arrow' />
<Breadcrumb.Section active>Personal Information</Breadcrumb.Section>
</Breadcrumb>
)
export default BreadcrumbExampleIconDivider
|
app/javascript/mastodon/features/explore/tags.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { ImmutableHashtag as Hashtag } from 'mastodon/components/hashtag';
import LoadingIndicator from 'mastodon/components/loading_indicator';
import { connect } from 'react-redux';
import { fetchTrendingHashtags } from 'mastodon/actions/trends';
const mapStateToProps = state => ({
hashtags: state.getIn(['trends', 'tags', 'items']),
isLoadingHashtags: state.getIn(['trends', 'tags', 'isLoading']),
});
export default @connect(mapStateToProps)
class Tags extends React.PureComponent {
static propTypes = {
hashtags: ImmutablePropTypes.list,
isLoading: PropTypes.bool,
dispatch: PropTypes.func.isRequired,
};
componentDidMount () {
const { dispatch } = this.props;
dispatch(fetchTrendingHashtags());
}
render () {
const { isLoading, hashtags } = this.props;
return (
<div className='explore__links'>
{isLoading ? (<LoadingIndicator />) : hashtags.map(hashtag => (
<Hashtag key={hashtag.get('name')} hashtag={hashtag} />
))}
</div>
);
}
}
|
packages/@sanity/dashboard/src/components/WidgetGroup.js | sanity-io/sanity | /* eslint-disable react/prop-types */
import React from 'react'
import styled, {css} from 'styled-components'
import {Grid} from '@sanity/ui'
import {WidgetContainer} from '../legacyParts'
const media = {
small: (...args) =>
css`
@media (min-width: ${({theme}) => theme.sanity.media[0]}px) {
${css(...args)}
}
`,
medium: (...args) =>
css`
@media (min-width: ${({theme}) => theme.sanity.media[2]}px) {
${css(...args)}
}
`,
}
const Root = styled(Grid)`
grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
& > div {
overflow: hidden;
}
& > div[data-width='medium'] {
${media.small`
grid-column: span 2;
`}
}
& > div[data-width='large'] {
${media.small`
grid-column: span 2;
`}
${media.medium`
grid-column: span 3;
`}
}
& > div[data-width='full'] {
${media.small`
grid-column: 1 / -1;
`}
}
& > div[data-height='medium'] {
${media.small`
grid-row: span 2;
`}
}
& > div[data-height='large'] {
${media.small`
grid-row: span 2;
`}
${media.medium`
grid-row: span 3;
`}
}
& > div[data-height='full'] {
${media.medium`
grid-row: 1 / -1;
`}
}
`
function WidgetGroup(props) {
const config = props.config || {}
const widgets = config.widgets || []
const layout = config.layout || {}
return (
<Root
autoFlow="dense"
data-width={layout.width || 'auto'}
data-height={layout.height || 'auto'}
gap={4}
>
{widgets.map((widgetConfig, index) => {
if (widgetConfig.type === '__experimental_group') {
return <WidgetGroup key={String(index)} config={widgetConfig} />
}
return <WidgetContainer key={String(index)} config={widgetConfig} />
})}
</Root>
)
}
export default WidgetGroup
|
spec/components/font_icon.js | react-toolbox/react-toolbox | import React from 'react';
import FontIcon from '../../components/font_icon';
const FontIconTest = () => (
<section>
<h5>Font Icons</h5>
<p>lorem ipsum...</p>
<FontIcon value="add" alt="add icon" />
<FontIcon value="access_alarm" />
<FontIcon value="explore" alt="explore icon" />
<FontIcon value="zoom_in" alt="zoom icon" />
<FontIcon alt="input icon">input</FontIcon>
</section>
);
export default FontIconTest;
|
src/routes/CoinFlip/components/CoinView.js | dontexpectanythingsensible/random-utils | import React from 'react';
import { getRandomInt } from 'services/utils';
import Coin from 'components/Coin';
import Slider from 'components/Slider';
import Ad from 'components/Ad';
export default class CoinView extends React.Component {
state = {
coins: [],
amount: 1
}
flip = () => {
const coins = [];
for (let i = 0; i < this.state.amount; i++) {
coins.push(getRandomInt(0, 1) === 1 ? 'heads' : 'tails');
}
this.setState({ coins });
}
componentWillMount () {
this.flip();
}
handleChange = e => {
let val = +e.target.value;
if (e && e.target && e.target.name) {
// sync
this.state[e.target.name] = +val;
this.flip();
}
}
renderCoin (val, i) {
return (
<Coin value={ val } key={ i } />
);
}
render () {
const headCount = this.state.coins.reduce(function (count, coin) {
// console.log(prev, curr);
if (coin === 'heads') {
return count + 1;
}
return count;
}, 0);
return (
<div className='coin__view'>
<Ad />
<Slider
label='Amount'
step='1'
min='1'
max='20'
value={ this.state.amount }
onChange={ this.handleChange } />
<button className='button' onClick={ this.flip }>Again</button>
{ this.state.amount > 3
? <div className='coin__count'>
{ `heads: ${ headCount }, tails: ${ this.state.coins.length - headCount }` }
</div>
: null
}
<div className='coins__wrapper'>{ this.state.coins.map(this.renderCoin) }</div>
</div>
);
}
}
|
packages/mineral-ui-icons/src/IconLibraryAdd.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconLibraryAdd(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M4 6H2v14c0 1.1.9 2 2 2h14v-2H4V6zm16-4H8c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 9h-4v4h-2v-4H9V9h4V5h2v4h4v2z"/>
</g>
</Icon>
);
}
IconLibraryAdd.displayName = 'IconLibraryAdd';
IconLibraryAdd.category = 'av';
|
packages/icons/src/md/image/Colorize.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdColorize(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M41.41 11.255c.79.78.79 2.04 0 2.82l-6.25 6.25 3.84 3.84-2.83 2.83-2.83-2.84-17.84 17.84H6v-9.5l17.84-17.83-2.84-2.84 2.83-2.83 3.83 3.84 6.25-6.25c.78-.78 2.05-.78 2.83 0l4.67 4.67zm-27.57 26.74l16.13-16.13-3.84-3.84L10 34.155l3.84 3.84z" />
</IconBase>
);
}
export default MdColorize;
|
src/svg-icons/device/screen-lock-landscape.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceScreenLockLandscape = (props) => (
<SvgIcon {...props}>
<path d="M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-2 12H5V7h14v10zm-9-1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2v1h-2.4v-1z"/>
</SvgIcon>
);
DeviceScreenLockLandscape = pure(DeviceScreenLockLandscape);
DeviceScreenLockLandscape.displayName = 'DeviceScreenLockLandscape';
DeviceScreenLockLandscape.muiName = 'SvgIcon';
export default DeviceScreenLockLandscape;
|
src/components/SearchForPeople/SearchForPeople.js | worknation/client.work.nation | import {d} from 'lightsaber/lib/log'
import React from 'react'
import isPresent from 'is-present'
import {Avatar, Profile, SkillAutosuggest} from '..'
import Auth from '../../models/Authentication'
import server from '../../models/Server'
export default class SearchForPeople extends React.Component {
constructor(props) {
super(props)
this.state = {
skill: null,
people: [],
profileUportAddress: null,
}
}
componentDidMount() {
// this.setState({skill: 'Ruby'}, () => this.search())
}
updateSkill = (skill) => this.setState({skill})
search = () => {
document.querySelector('.loading-spinner').style.display = 'block'
const projectsApiUrl = `${process.env.REACT_APP_API_SERVER}/users/?perspective=${Auth.getUportAddress()}&skill=${this.state.skill}&depth=3`
server.get(projectsApiUrl).then(response => {
// d({results: response.data})
this.setState({people: response.data})//, () => d(this.state))
document.querySelector('.loading-spinner').style.display = 'none'
if (isPresent(response.data)) {
document.querySelector('.project-body-list').style.display = 'block'
} else {
console.log('No Results') // TODO show in UI
}
})
}
handleCancel = () => {
this.props.history.push('/')
}
render() {
return (
<div>
<div className="float-right">
{this.renderProfile()}
</div>
<div className="row search-for-people-container">
<div className="small-12 columns">
<div className="claim-skill-container">
<h1 className="project-name">work.nation</h1>
</div>
<div className="project-container">
<div className="project-header">
<h2 className="">{this.props.title}</h2>
</div>
<div className="project-body">
<div className="project-body-subheader">
<div className="row">
<div className="small-6 columns no-right-padding">
<h3>{this.props.subtitle}</h3>
<div className="skill-search">
<SkillAutosuggest onValueUpdate={this.updateSkill} />
</div>
</div>
<div className="small-1 columns no-padding skill-search-button-outside">
<div className="skill-search-button-inside">
<img src="/static/images/button_search.svg" onClick={this.search} className="skill-search-button" />
</div>
</div>
<div className="small-2 columns no-padding loading-spinner-outside">
<div className="loading-spinner-inside">
<img src="/static/images/loading.gif" className="loading-spinner" />
</div>
</div>
<div className="small-2 columns" />
</div>
</div>
<div className="project-body-list">
<div className="project-body-list-subheader">
<div className="row">
<div className="small-3 columns">Candidate</div>
<div className="small-3 columns">Contribution</div>
<div className="small-1 columns text-center">Confirmations</div>
<div className="small-2 columns text-center"># of projects</div>
<div className="small-3 columns">Invite</div>
</div>
</div>
<div className="project-body-list-scroll">
{this.state.people.map(person => this.showPerson(person))}
</div>
</div>
</div>
<div className="project-footer">
{this.props.cancelButton ? this.cancelButton() : null}
</div>
</div>
</div>
</div>
</div>
)
}
showPerson = (person) => {
return <div className="project-body-list-row" key={person.uportAddress}>
<div className="row">
<div className="small-3 columns">
<Avatar avatarImageIpfsKey={person.avatarImageIpfsKey} name={person.name} />
<a href="#" onClick={this.showProfile}>
<span className="name" data-uport-address={person.uportAddress}>{person.name}</span>
</a>
</div>
<div className="small-3 columns">
<ul className="skills">
{person.skills.map(skill => <li key={skill.name}>{skill.name}</li>) }
</ul>
</div>
<div className="small-1 columns text-center">
<ul className="confirmation-count">
{person.skills.map(skill => <li key={skill.name}>{skill.confirmationsCount}</li>) }
</ul>
</div>
<div className="small-2 columns text-center">
<ul className="project-count">
{person.skills.map(skill => <li key={skill.name}>{skill.projectCount}</li>) }
</ul>
</div>
<div className="small-3 columns text-right">
<textarea placeholder="Note: messaging is not enabled for this demo" />
<img className="icon-message" src="/static/images/icon_message.svg" />
</div>
</div>
</div>
}
renderProfile = () => {
if (this.state.profileUportAddress) {
return <Profile {...this.props} uportAddress={this.state.profileUportAddress} />
} else {
return <div className="profile-placeholder" />
}
}
showProfile = (event) => {
event.preventDefault()
this.setState({profileUportAddress: event.target.dataset.uportAddress}, () => d({'this.state.profileUportAddress': this.state.profileUportAddress}))
}
cancelButton = () =>
<input type="submit" onClick={this.handleCancel} value={this.props.cancelButton}
className="button button-lt-blue" />
}
|
app/routes.js | phosphene/react-fullstack-d3-demo | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './modules';
import Timer from './modules/Timer';
import Notes from './modules/Notes';
import ParaCoD3 from './modules/ParaCoD3';
import StreamGraph from './modules/StreamGraph';
import ThrashDash from './modules/ThrashDash';
import NOAADash from './modules/NOAADash';
import ReductDash from './modules/ReductDash';
import NasDash from './modules/NasDash';
export default (
<Route path="/" component={App}>
<IndexRoute component={Timer} />
<Route path="parallel" component={ParaCoD3} />
<Route path="streamgraph" component={StreamGraph} />
<Route path="nasdash" component={NasDash} />
<Route path="thrashdash" component={ThrashDash} />
<Route path="noaadash" component={NOAADash} />
</Route>
);
|
client/modules/core/components/footer.js | LikeJasper/mantra-plus | import React from 'react';
import { Paper } from 'material-ui';
const Footer = () => (
<footer>
<Paper>
<p>
<small>Built with <a href="https://github.com/kadirahq/mantra">Mantra</a> & Meteor.</small>
</p>
</Paper>
</footer>
);
export default Footer;
|
src/svg-icons/action/accessible.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAccessible = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="4" r="2"/><path d="M19 13v-2c-1.54.02-3.09-.75-4.07-1.83l-1.29-1.43c-.17-.19-.38-.34-.61-.45-.01 0-.01-.01-.02-.01H13c-.35-.2-.75-.3-1.19-.26C10.76 7.11 10 8.04 10 9.09V15c0 1.1.9 2 2 2h5v5h2v-5.5c0-1.1-.9-2-2-2h-3v-3.45c1.29 1.07 3.25 1.94 5 1.95zm-6.17 5c-.41 1.16-1.52 2-2.83 2-1.66 0-3-1.34-3-3 0-1.31.84-2.41 2-2.83V12.1c-2.28.46-4 2.48-4 4.9 0 2.76 2.24 5 5 5 2.42 0 4.44-1.72 4.9-4h-2.07z"/>
</SvgIcon>
);
ActionAccessible = pure(ActionAccessible);
ActionAccessible.displayName = 'ActionAccessible';
ActionAccessible.muiName = 'SvgIcon';
export default ActionAccessible;
|
app/components/posts/PostSingle.js | ramsaylanier/ApolloPress | import React from 'react';
import { connect } from 'react-apollo';
import PostContent from './PostContent.js';
import CSSModules from 'react-css-modules';
import styles from './post.scss';
@CSSModules(styles, {allowMultiple: true})
class PostSingle extends React.Component{
componentDidMount(){
const post = this._post;
TweenMax.fromTo(post, 0.5, {
opacity: 0
}, {
opacity: 1
});
}
render(){
console.log(this.props);
const { loading} = this.props.post;
if (loading){
return <div></div>
} else {
const { post_title, post_content, thumbnail } = this.props.post.viewer.page;
const { settings } = this.props.post.viewer;
const { uploads, amazonS3 } = settings;
let bg = {
backgroundImage: 'url("' + thumbnail + '")'
}
return(
<div ref={(c) => this._post = c} styleName="base">
<div styleName="header" style={bg}>
</div>
<div styleName="main">
<div styleName="wrapper">
<h1 styleName="title">{post_title}</h1>
<PostContent post_content={post_content}/>
</div>
</div>
</div>
)
}
}
}
const PostSingleWithData = connect({
mapQueriesToProps({ ownProps, state}) {
return {
post: {
query: `
query getPost($post: String){
viewer{
page(post_name:$post){
id
post_title
post_content
thumbnail
},
settings{
id
uploads
amazonS3
}
}
}
`,
variables: {
post: ownProps.params.post
}
}
}
}
})(PostSingle);
export default PostSingleWithData;
|
examples/huge-apps/routes/Course/routes/Grades/components/Grades.js | hgezim/react-router | import React from 'react';
class Grades extends React.Component {
render () {
var assignments = COURSES[this.props.params.courseId].assignments;
return (
<div>
<h3>Grades</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>{assignment.grade} - {assignment.title}</li>
))}
</ul>
</div>
);
}
}
export default Grades;
|
src/App.js | dkozar/react-wrappy-text | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import WrappyText from './components/WrappyText.js';
import TextRotator from './components/TextRotator.js';
import ScrollListener from './components/ScrollListener.js';
const BUTTON_TEXT = 'Do it again!';
require('./styles/main.css');
const texts = [
'This is the wrappy text.',
'Wrappy text is the next <h1>.',
'Because UI is show business.',
'Throwing dice for each letter...'
],
longTexts = [
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In ut turpis urna. Aliquam erat volutpat. Fusce vehicula ipsum a ligula placerat scelerisque. Praesent iaculis erat sapien, vel dictum sem tincidunt id. Vestibulum luctus porttitor porttitor. Pellentesque erat ex, fermentum sit amet arcu non, imperdiet condimentum magna. Donec finibus, leo nec cursus tristique, mauris nisi tempor nisl, in condimentum erat metus non tellus. Praesent suscipit diam nec purus mattis, eget ornare mi tempor.',
'Donec consequat sagittis nibh vitae mollis. Nullam sagittis augue eu vehicula imperdiet. Donec aliquet, velit nec molestie vehicula, erat felis convallis eros, vitae euismod lectus felis ac lectus. Aliquam dictum leo non ex mollis, non viverra elit condimentum. Cras sit amet dictum lectus. Fusce ornare metus odio, ut lacinia ligula egestas lobortis. Aliquam condimentum vulputate sem id tempor. Vestibulum congue euismod justo. Donec quis erat vitae urna ultricies fermentum non suscipit lacus. Sed ac mollis nunc, egestas malesuada velit. Etiam sed eleifend tortor, ut blandit ex. Nulla non neque quis turpis tristique placerat in vel nisi.',
'In pretium vel lorem id pellentesque. Nullam quis eros ut urna pharetra tristique vel et quam. Vivamus sit amet velit in erat aliquet suscipit. Suspendisse bibendum magna tellus, ac rutrum lorem facilisis at. Phasellus eget tellus tincidunt, ullamcorper metus non, consectetur risus. Interdum et malesuada fames ac ante ipsum primis in faucibus. Cras sagittis lorem lobortis, bibendum nunc vel, rutrum leo. Nulla convallis maximus lorem quis interdum. Sed posuere tincidunt mi sit amet aliquet. Vivamus bibendum nisl risus, in condimentum dui luctus id. Vivamus ullamcorper ante eu lectus porta venenatis. Vivamus consectetur dui porta ipsum tristique dictum.'
];
export class App extends Component {
constructor(props) {
super(props);
this.state = {
text: texts[0],
longText: longTexts[0]
};
this.changeText = this.changeText.bind(this);
this.changeLongText = this.changeLongText.bind(this);
this.onProgress = this.onProgress.bind(this);
this.count = 0;
this.count2 = 0;
}
changeText() {
this.count ++;
this.setState({
text: texts[this.count % texts.length]
});
}
changeLongText() {
this.count2 ++;
this.setState({
longText: longTexts[this.count2 % longTexts.length]
});
}
onProgress(ref, info) {
var progress = info.done / info.total;
ReactDOM.findDOMNode(this.refs[ref]).style['width'] = 100 * progress + '%';
}
render() {
return (
<div>
<div className='separator' />
{/* title */}
<TextRotator texts={texts}>
<WrappyText className='reveal wrappy title-text red title' ref='title'></WrappyText>
</TextRotator>
<div className='separator' />
{/* shuffle */}
<ScrollListener text='Whenever the text changes, I shuffle'>
<WrappyText className='reveal wrappy small-text green'></WrappyText>
</ScrollListener>
<ScrollListener text={this.state.text}>
<WrappyText className='reveal wrappy big-text green'></WrappyText>
</ScrollListener>
<button className='reveal button green' onClick={this.changeText}>{BUTTON_TEXT}</button><div className='separator' />
<div className='separator' />
{/* progress */}
<ScrollListener text='I dispatch progress events'>
<WrappyText className='reveal wrappy small-text blue'></WrappyText>
</ScrollListener>
<ScrollListener text={this.state.text}>
<WrappyText className='reveal wrappy big-text blue' onProgress={this.onProgress.bind(this, 'progress-progress')}></WrappyText>
<div ref='progress-progress' className='reveal progress blue' />
</ScrollListener>
<button className='reveal button blue' onClick={this.changeText}>{BUTTON_TEXT}</button><div className='separator' />
<div className='separator' />
{/* big */}
<ScrollListener text='I can handle long texts'>
<WrappyText className='reveal wrappy small-text purple'></WrappyText>
</ScrollListener>
<ScrollListener className='huge-parent' text={this.state.longText}>
<WrappyText className='reveal wrappy small-text huge purple' onProgress={this.onProgress.bind(this, 'progress-big')} factor={0.1}></WrappyText>
</ScrollListener>
<div ref='progress-big' className='reveal progress purple' />
<button className='reveal button purple' onClick={this.changeLongText}>{BUTTON_TEXT}</button><div className='separator' />
<div className='separator' />
{/* slower */}
<ScrollListener text='I can animate slower'>
<WrappyText className='reveal wrappy small-text green'></WrappyText>
</ScrollListener>
<ScrollListener text={this.state.text}>
<WrappyText className='reveal wrappy big-text green' fps={10} onProgress={this.onProgress.bind(this, 'progress-slower')}></WrappyText>
</ScrollListener>
<div ref='progress-slower' className='reveal progress green' />
<button className='reveal button green' onClick={this.changeText}>{BUTTON_TEXT}</button><div className='separator' />
<div className='separator' />
{/* faster */}
<ScrollListener text='I can animate faster'>
<WrappyText className='reveal wrappy small-text yellow'></WrappyText>
</ScrollListener>
<ScrollListener text={this.state.text}>
<WrappyText className='reveal wrappy big-text yellow' fps={120} onProgress={this.onProgress.bind(this, 'progress-faster')}></WrappyText>
</ScrollListener>
<div ref='progress-faster' className='reveal progress yellow' />
<button className='reveal button yellow' onClick={this.changeText}>{BUTTON_TEXT}</button><div className='separator' />
<div className='separator' />
{/* probability */}
<ScrollListener text='I can use different probability'>
<WrappyText className='reveal wrappy small-text red'></WrappyText>
</ScrollListener>
<ScrollListener text={this.state.text}>
<WrappyText className='reveal wrappy big-text red' factor={10} onProgress={this.onProgress.bind(this, 'progress-probability')}></WrappyText>
</ScrollListener>
<div ref='progress-probability' className='reveal progress red' />
<button className='reveal button red' onClick={this.changeText}>{BUTTON_TEXT}</button><div className='separator' />
<div className='separator' />
{/* custom replacements */}
<ScrollListener text='I can use custom replacement characters'>
<WrappyText className='reveal wrappy small-text orange'></WrappyText>
</ScrollListener>
<ScrollListener text={this.state.text}>
<WrappyText className='reveal wrappy big-text orange' replacements='$$$$$$$$$$$$$$$$$$$**********'></WrappyText>
</ScrollListener>
<button className='reveal button orange' onClick={this.changeText}>{BUTTON_TEXT}</button><div className='separator' />
<div className='separator' />
{/* (C) Danko Kozar */}
<ScrollListener text='Brought to you by:'>
<WrappyText className='reveal wrappy small-text purple'></WrappyText>
</ScrollListener>
<ScrollListener text='Danko Kozar'>
<WrappyText className='reveal wrappy big-text purple' fps={120} factor={20} replacements='$$$$$$$$$$$$$$$$$$$DKDKDKDKDK'></WrappyText>
</ScrollListener>
<div className='separator' />
</div>
);
}
componentDidMount() {
// a touch of reveal animation
window.sr = new ScrollReveal();
sr.reveal('.reveal');
}
}
/* Let's get serious :). This is actually the learning example, containing all the important things about React and DOM interaction. */ |
src/index.js | algernon/mad-tooter | // @flow
/* The Mad Tooter -- A Mastodon client
* Copyright (C) 2017 Gergely Nagy
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU 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 { HashRouter, Route, Switch, Redirect } from 'react-router-dom';
import { Provider } from 'react-redux';
import { render } from 'react-dom';
import AuthorizedRoute from './routers/AuthorizedRoute';
import store from './store';
import { loadConfiguration } from './common/actions/client';
import withRoot from './styles/withRoot';
import UnauthorizedLayout from './layouts/UnauthorizedLayout';
import PrimaryLayout from './layouts/PrimaryLayout';
class App extends React.Component {
constructor(props) {
super(props);
loadConfiguration();
}
render() {
return (
<Provider store={store}>
<HashRouter>
<Switch>
<Route path="/auth" component={UnauthorizedLayout} />
<AuthorizedRoute path="/" component={PrimaryLayout} />
<Redirect to="/auth" />
</Switch>
</HashRouter>
</Provider>
);
}
}
App = withRoot(App);
render(<App />, document.querySelector('#root'));
|
node_modules/semantic-ui-react/src/views/Statistic/StatisticGroup.js | SuperUncleCat/ServerMonitoring | import cx from 'classnames'
import _ from 'lodash'
import PropTypes from 'prop-types'
import React from 'react'
import {
childrenUtils,
customPropTypes,
getElementType,
getUnhandledProps,
META,
SUI,
useKeyOnly,
useWidthProp,
} from '../../lib'
import Statistic from './Statistic'
/**
* A group of statistics.
*/
function StatisticGroup(props) {
const {
children,
className,
color,
horizontal,
inverted,
items,
size,
widths,
} = props
const classes = cx(
'ui',
color,
size,
useKeyOnly(horizontal, 'horizontal'),
useKeyOnly(inverted, 'inverted'),
useWidthProp(widths),
'statistics',
className,
)
const rest = getUnhandledProps(StatisticGroup, props)
const ElementType = getElementType(StatisticGroup, props)
if (!childrenUtils.isNil(children)) return <ElementType {...rest} className={classes}>{children}</ElementType>
const itemsJSX = _.map(items, item => (
<Statistic key={item.childKey || [item.label, item.title].join('-')} {...item} />
))
return <ElementType {...rest} className={classes}>{itemsJSX}</ElementType>
}
StatisticGroup._meta = {
name: 'StatisticGroup',
type: META.TYPES.VIEW,
parent: 'Statistic',
}
StatisticGroup.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** A statistic group can be formatted to be different colors. */
color: PropTypes.oneOf(SUI.COLORS),
/** A statistic group can present its measurement horizontally. */
horizontal: PropTypes.bool,
/** A statistic group can be formatted to fit on a dark background. */
inverted: PropTypes.bool,
/** Array of props for Statistic. */
items: customPropTypes.collectionShorthand,
/** A statistic group can vary in size. */
size: PropTypes.oneOf(_.without(SUI.SIZES, 'big', 'massive', 'medium')),
/** A statistic group can have its items divided evenly. */
widths: PropTypes.oneOf(SUI.WIDTHS),
}
export default StatisticGroup
|
src/Card.js | lyallsv/react-solitaire | import React, { Component } from 'react';
import CardMeta from './CardMeta';
import CardUtils from './CardUtils';
class Card extends Component {
render() {
let {isVisible, card} = this.props;
let meta = CardUtils.getMeta(card);
return (
<div className={"card " + (isVisible ? '' : 'flipped')}>
<div className={"detail " + (meta.color)}>
{meta.abbreviation}
{meta.icon}
</div>
<CardMeta meta={meta} />
</div>
);
}
}
export default Card;
|
src/mui/field/BooleanField.js | marmelab/admin-on-rest | import React from 'react';
import PropTypes from 'prop-types';
import get from 'lodash.get';
import pure from 'recompose/pure';
import FalseIcon from 'material-ui/svg-icons/content/clear';
import TrueIcon from 'material-ui/svg-icons/action/done';
export const BooleanField = ({ source, record = {}, elStyle }) => {
if (get(record, source) === false) {
return <FalseIcon style={elStyle} />;
}
if (get(record, source) === true) {
return <TrueIcon style={elStyle} />;
}
return <span style={elStyle} />;
};
BooleanField.propTypes = {
addLabel: PropTypes.bool,
elStyle: PropTypes.object,
label: PropTypes.string,
record: PropTypes.object,
source: PropTypes.string.isRequired,
};
const PureBooleanField = pure(BooleanField);
PureBooleanField.defaultProps = {
addLabel: true,
elStyle: {
display: 'block',
margin: 'auto',
},
};
export default PureBooleanField;
|
src/svg-icons/hardware/speaker-group.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareSpeakerGroup = (props) => (
<SvgIcon {...props}>
<path d="M18.2 1H9.8C8.81 1 8 1.81 8 2.8v14.4c0 .99.81 1.79 1.8 1.79l8.4.01c.99 0 1.8-.81 1.8-1.8V2.8c0-.99-.81-1.8-1.8-1.8zM14 3c1.1 0 2 .89 2 2s-.9 2-2 2-2-.89-2-2 .9-2 2-2zm0 13.5c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/><circle cx="14" cy="12.5" r="2.5"/><path d="M6 5H4v16c0 1.1.89 2 2 2h10v-2H6V5z"/>
</SvgIcon>
);
HardwareSpeakerGroup = pure(HardwareSpeakerGroup);
HardwareSpeakerGroup.displayName = 'HardwareSpeakerGroup';
HardwareSpeakerGroup.muiName = 'SvgIcon';
export default HardwareSpeakerGroup;
|
src/components/VideoItem/index.js | PalmasLab/palmasplay | import React from 'react'
import moment from 'moment'
import styles from './styles.css'
let formatRuntime = (runtime) => (moment.utc(runtime*1000).format("mm:ss"))
let formatPublished = (published) => (moment(published).fromNow())
let prettyNumber = (num) => (
// hackish, we probably can do that with a single replace
num.toString()
.replace(/(\d{3})$/g, ', $&') // 1k
.replace(/(\d)(\d{3}),/, '$1, $2,') // 1M
.replace(/(\d)(\d{3}),/, '$1, $2,') // 1G
.replace(/(\d)(\d{3}),/, '$1, $2,') // 1T
.replace(/(\d)(\d{3}),/, '$1, $2,') // 1P
)
export const BigVideo = ({views, runtime, cover, published, title}) => (
<div className={styles.bigVideo}>
<a href="#">
<div className={styles.videoContainer}
style={{backgroundImage: `url("${cover.high}")`}}>
<div className={styles.vrh}>
<span className={styles.views}>{prettyNumber(views)} views</span>
<span className={styles.runtime}>{formatRuntime(runtime)}</span>
</div>
<div className={styles.dno}>
<h1>{title}</h1>
<p>Published {formatPublished(published)}</p>
</div>
<div className={styles.overlay}>
<i className="fa fa-play fa-5x"></i>
<h1>Play video</h1>
</div>
</div>
</a>
</div>
)
export const VideoItem = ({id, views, runtime, cover, published, title}) => (
<li>
<div className={styles.video}>
<div className={styles.videoInfo}
style={{backgroundImage: `url("${cover.med}")`}}>
<span className={styles.views}>{prettyNumber(views)} views</span>
<span className={styles.runtime}>{formatRuntime(runtime)}</span>
</div>
<a href="#"><h2>{title}</h2></a>
<span className={styles.published}>Published {formatPublished(published)}</span>
</div>
</li>
)
|
static/programming-tutorials-backup/src/projects/frontend/lessons/HTMLCSSJSDifferences.js | EdwardRees/EdwardRees.github.io | import React from 'react';
const HTMLCSSJSDifferences = () => (
<div><h2>HTML, CSS, JS Differences</h2></div>
)
export { HTMLCSSJSDifferences }; |
client/src/components/EditAbhanga/index.js | mohandere/tukaram-gatha | import React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import { Link } from 'react-router-dom';
import { Row, Col, Form, FormGroup, FormControl, ControlLabel, Button } from 'react-bootstrap';
import { AlertList } from "react-bs-notifier";
import axios from 'axios';
class EditAbhanga extends Component {
constructor(props) {
super(props);
this.state = {
abhangaNumber: '',
abhangaTitle: '',
abhangaContent: '',
abhangaAuthor: 'mohandere'
};
this.handleSubmit = this.handleSubmit.bind(this);
this.handleChange = this.handleChange.bind(this);
}
handleSubmit(event) {
event.preventDefault();
axios.post('/abhanga/edit', {
index: this.state.abhangaNumber,
title: this.state.abhangaTitle,
content: this.state.abhangaContent,
author: this.state.abhangaAuthor
})
.then(function (response) {
console.log(response);
})
}
handleChange(event) {
const target = event.target;
const value = target.type === 'checkbox' ? target.checked : target.value;
const name = target.name;
this.setState({
[name]: value
});
}
render() {
return (
<div className="text-left">
<Form horizontal onSubmit={this.handleSubmit}>
<FormGroup>
<Col sm={2}>
Index
</Col>
<Col sm={10}>
<FormControl type="number" name="abhangaNumber" componentClass="input" onChange={this.handleChange} value={this.state.abhangaNumber} placeholder="Abhanga Number" />
</Col>
</FormGroup>
<FormGroup>
<Col sm={2}>
Title
</Col>
<Col sm={10}>
<FormControl type="text" name="abhangaTitle" componentClass="input" onChange={this.handleChange} value={this.state.abhangaTitle} placeholder="Abhanga" />
</Col>
</FormGroup>
<FormGroup>
<Col sm={2}>
Content
</Col>
<Col sm={10}>
<FormControl rows={15} name="abhangaContent" componentClass="textarea" onChange={this.handleChange} value={this.state.abhangaContent} placeholder="Abhanga Content" />
</Col>
</FormGroup>
<FormGroup>
<Col sm={2}>
Author
</Col>
<Col sm={10}>
<FormControl name="abhangaAuthor" componentClass="select">
<option value="mohandere">Mohan Dere</option>
</FormControl>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button type="submit" bsStyle="primary">
Save
</Button>
</Col>
</FormGroup>
</Form>
</div>
);
}
}
export default EditAbhanga;
|
src/components/BackArrow.js | carlyleec/cc-react | import React from 'react';
import styled from 'styled-components';
import { browserHistory } from 'react-router';
const BackArrowButton = styled.button`
display: ${props => (props.hasHistory > 1 ? 'inline-block' : 'none')};
border: none;
background: none;
vertical-align: middle;
cursor: pointer;
outline: none;
`;
const BackArrow = props => (
<BackArrowButton hasHistory={window.history.length} onClick={browserHistory.goBack}>
<svg width={props.size} height={props.size} viewBox="0 0 120 120" version="1.1">
<g id="graphics" stroke="none" strokeWidth="1" fill="none" fillRule="evenodd">
<g id="back-arrow" fill="#2196F3">
<path d="M13.136273,55.8967356 C12.6161591,56.2602716 12.1687667,56.7204914 11.8197687,57.2513825 C10.2642089,58.823669 10.2733515,61.3444193 11.8325357,62.9036035 L59.2004729,110.271541 C60.7613965,111.832464 63.3024293,111.834656 64.8683392,110.268746 L66.2687458,108.868339 C67.8399112,107.297174 67.835907,104.764839 66.2715407,103.200473 L28.0710678,65 L107.002676,65 C109.20047,65 111,63.204768 111,60.990237 L111,59.009763 C111,56.7877996 109.210337,55 107.002676,55 L28.1751442,55 L66.2715407,16.9036035 C67.8324643,15.3426799 67.8346556,12.8016471 66.2687458,11.2357372 L64.8683392,9.83533061 C63.2971738,8.26416522 60.7648391,8.26816944 59.2004729,9.83253573 L13.136273,55.8967356 Z" id="Combined-Shape"></path>
</g>
</g>
</svg>
</BackArrowButton>
);
BackArrow.propTypes = {
size: React.PropTypes.string,
};
export default BackArrow;
|
src/components/commonComponents/footer.js | toffee7/ReactStarterComponents | import React, { Component } from 'react';
const Footer = (props) => {
return (
<footer className="footer-class">
<i className="fa fa-copyright fa-lg" aria-hidden="true"></i>2017 Syed Tauseef Tanweer
</footer>
);
}
export default Footer; |
src/components/settings/SetRates.js | whphhg/vcash-ui | import React from 'react'
import { translate } from 'react-i18next'
import { inject, observer } from 'mobx-react'
import { join } from 'path'
import moment from 'moment'
/** Ant Design */
import Button from 'antd/lib/button'
import Switch from 'antd/lib/switch'
import Tooltip from 'antd/lib/tooltip'
/** Component */
import { SwitchIcon } from '../utilities/Common.js'
@translate(['common'])
@inject('gui', 'rates')
@observer
class SetRates extends React.Component {
constructor(props) {
super(props)
this.t = props.t
this.gui = props.gui
this.rates = props.rates
}
render() {
const imgDir = join(__dirname, '..', '..', 'assets', 'images')
return (
<div>
<div className="flex-sb" style={{ alignItems: 'flex-start' }}>
<div style={{ flex: 0.5, margin: '0 25px 0 0' }}>
<div className="flex">
<i className="material-icons md-16">swap_horiz</i>
<p style={{ fontWeight: '500' }}>{this.t('exchanges')}</p>
</div>
<hr />
<div>
<div className="flex-sb" style={{ margin: '0 0 5px 0' }}>
<div className="flex">
<img src={join(imgDir, 'exchangeBittrex.png')} />
<p style={{ margin: '0 0 0 5px' }}>Bittrex</p>
</div>
<div className="flex">
<Tooltip
placement="left"
title={
this.rates.bittrex.updated > 0
? ''.concat(
this.t('lastUpdated'),
' ',
moment(this.rates.bittrex.updated).format('LTS')
)
: this.t('exchangeDisabled')
}
>
<p style={{ margin: '0 15px 0 0' }}>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 8,
maximumFractionDigits: 8
}).format(this.rates.bittrex.Last)}
</span>{' '}
BTC
</p>
</Tooltip>
<Switch
checked={this.rates.exchanges.bittrex === true}
checkedChildren={<SwitchIcon icon="done" />}
onChange={() => this.rates.setExchange('bittrex')}
size="small"
unCheckedChildren={<SwitchIcon icon="clear" />}
/>
</div>
</div>
<div className="flex-sb">
<div className="flex">
<img src={join(imgDir, 'exchangePoloniex.png')} />
<p style={{ margin: '0 0 0 5px' }}>Poloniex</p>
</div>
<div className="flex">
<Tooltip
placement="left"
title={
this.rates.poloniex.updated > 0
? ''.concat(
this.t('lastUpdated'),
' ',
moment(this.rates.poloniex.updated).format('LTS')
)
: this.t('exchangeDisabled')
}
>
<p style={{ margin: '0 15px 0 0' }}>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 8,
maximumFractionDigits: 8
}).format(this.rates.poloniex.last)}
</span>{' '}
BTC
</p>
</Tooltip>
<Switch
checked={this.rates.exchanges.poloniex === true}
checkedChildren={<SwitchIcon icon="done" />}
onChange={() => this.rates.setExchange('poloniex')}
size="small"
unCheckedChildren={<SwitchIcon icon="clear" />}
/>
</div>
</div>
</div>
</div>
<div style={{ flex: 0.5, margin: '0 0 0 24px' }}>
<div className="flex" style={{ fontWeight: '500' }}>
<i className="material-icons md-16">monetization_on</i>
<p>{this.t('bitcoinAverage')}</p>
</div>
<hr />
<div className="flex-sb" style={{ alignItems: 'flex-end' }}>
<div>
<p>
{this.rates.localCurrencies.length} {this.t('currencies')}
</p>
<p style={{ margin: '5px 10px 0 0' }}>
{this.t('lastUpdated')}{' '}
{moment(this.rates.bitcoinAverage.updated).format('LTS')}
</p>
</div>
<div>
<Button
onClick={() => this.rates.fetchBitcoinAverage(true)}
size="small"
type="dashed"
>
{this.t('manualRefresh')}
</Button>
</div>
</div>
</div>
</div>
</div>
)
}
}
export default SetRates
|
src/components/ChatList/Items/index.js | saitodisse/md-list | import React from 'react';
import {connect} from 'cerebral-view-react';
// import itensKeysComputed from '~/computed/itensKeysComputed';
import styles from './styles';
import Item from './Item';
import _ from 'lodash/fp';
export default connect({
is_ready: 'chatList.is_ready',
// itemsKeys: itensKeysComputed(),
},
class Items extends React.Component {
constructor(props) {
super(props);
this.state = {
srollToCalled: false,
};
}
_getSortedItems = () => {
const sorted = _.sortBy(['created_at'], this.props.items);
const sorted_keys = _.keyBy('id', sorted);
return Object.keys(sorted_keys);
}
render() {
let itemsContainerStyle;
if (this.props.is_ready) {
itemsContainerStyle = _.merge(styles.itemsContainer, {opacity: 1});
} else {
itemsContainerStyle = _.merge(styles.itemsContainer, {opacity: 0.3});
}
return (
<div style={itemsContainerStyle} id="itemsContainer">
{this._getSortedItems().map((itemKey) => (
<Item {...this.props} key={itemKey} item={this.props.items[itemKey]} />
))}
</div>
);
}
}
);
|
client/components/favorite/Searches.js | howardlykim/ruby-gem-search | import React from 'react'
import FavoriteSearchesStore from '../../stores/FavoriteSearches'
import { Link } from 'react-router-dom'
class FavoriteSearches extends React.Component {
constructor (props) {
super(props)
this.state = { favoriteSearches: FavoriteSearchesStore.getData() }
}
editFavoriteSearch (action, searchText) {
const updated = FavoriteSearchesStore[action](searchText)
this.setState({ favoriteSearches: updated })
}
render () {
const results = [...this.state.favoriteSearches.values()].sort().map(searchResult => {
return (
<div className='ui label' key={searchResult}>
{searchResult}
<i onClick={this.editFavoriteSearch.bind(this, 'delete', searchResult)} className='delete icon' />
</div>
)
})
const header = results.length === 0
? <Link to='/'>Looks like you don't have any saved! Try searching for a gem first?</Link>
: 'Favorite Searches'
return (
<div className='ui container'>
<h1 className='ui red center aligned header'>{header}</h1>
<div className='ui three column centered grid'>
{results}
</div>
</div>
)
}
}
export default FavoriteSearches
|
node_modules/react-router/es6/IndexLink.js | mrjkc/react-redux | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import React from 'react';
import Link from './Link';
/**
* An <IndexLink> is used to link to an <IndexRoute>.
*/
var IndexLink = React.createClass({
displayName: 'IndexLink',
render: function render() {
return React.createElement(Link, _extends({}, this.props, { onlyActiveOnIndex: true }));
}
});
export default IndexLink; |
src/components/CommentForm.js | s83/react-comments | import React from 'react';
import { connectReduxForm } from 'redux-form';
import { validateComment } from 'utils';
import { FORM_COMMENT_ID } from 'constants';
import { Input } from 'react-bootstrap';
import Spaces from 'components/Spaces';
import { Glyphicon, Button, ButtonToolbar, Panel } from 'react-bootstrap';
import { PATH_COMMENT_LIST } from 'constants';
@connectReduxForm({
form: FORM_COMMENT_ID,
fields: ['username', 'email', 'link', 'content'],
validate: validateComment
})
export class CommentsItemForm extends React.Component {
static propTypes = {
fields: React.PropTypes.object.isRequired,
handleSubmit: React.PropTypes.func.isRequired,
handleReset: React.PropTypes.func.isRequired
}
constructor () {
super();
}
/**
* Evaluate field status based on errors and touch event
* @param {object} field
* @return {Boolean|null} returns null when not ready
*/
hasError (field) {
return field.touched ? field.error !== null : null;
}
renderError (field) {
return (
<div className="comment-error">
<Glyphicon glyph="glyphicon glyphicon-exclamation-sign"/>
<Spaces/>
{field.error}
</div>
);
}
renderBsStyle () {
const keys = Object.keys(this.props.fields);
/* eslint-disable prefer-const */
let output = {};
/* eslint-enable prefer-const */
keys.forEach((key) => {
const error = this.hasError(this.props.fields[key]);
output[key] = error === null ? {} : { 'bsStyle': error ? 'error' : 'success' };
});
return output;
}
render () {
const { fields: {username, email, link, content}, handleSubmit, handleReset } = this.props;
const disabledSubmit = !!( username.error || email.error || link.error || content.error );
const bsStyle = this.renderBsStyle();
return (
<form onSubmit={handleSubmit.bind(this)}>
<Panel className="comment-panel box-shadow">
<Input
type="text"
label="Full Name *"
required
{...bsStyle.username}
{...username}
/>
{ this.hasError(username) ? this.renderError(username) : ''}
<Input
type="email"
label="E-mail *"
required
{...bsStyle.email}
{...email}
/>
{ this.hasError(email) ? this.renderError(email) : ''}
<Input
type="textarea"
label="Message *"
{...bsStyle.content}
{...content}
/>
{ this.hasError(content) ? this.renderError(content) : ''}
<Input
type="text"
label="Site"
{...bsStyle.link}
{...link}
/>
{ this.hasError(link) ? this.renderError(link) : ''}
</Panel>
<ButtonToolbar>
<Button
href={PATH_COMMENT_LIST}
onClick={handleReset.bind(this)}
>
Cancel</Button>
<Button
type="submit"
bsStyle={disabledSubmit ? 'warning' : 'success'}
bsSize="large"
className="pull-right"
disabled={disabledSubmit}
title={ disabledSubmit ? 'Please fill required fields or enter correct values' : 'Submit changes' }
onClick={handleSubmit.bind(this)}>
Save {disabledSubmit ? '' : <Glyphicon glyph="glyphicon glyphicon-ok"/>}
</Button>
</ButtonToolbar>
</form>
);
}
}
export default CommentsItemForm;
|
cmd/elwinator/src/components/NewChoiceView.js | 13scoobie/choices | import React from 'react';
import { Link } from 'react-router';
import NavSection from './NavSection';
import { namespaceURL, experimentURL, paramURL } from '../urls';
import NewChoice from '../connectors/NewChoice';
const NewChoiceView = ({ params }) => {
return (
<div className="container">
<div className="row"><h1>Create a new experiment</h1></div>
<div className="row">
<NavSection>
<Link
to={ namespaceURL(params.namespace) }
className="nav-link"
>{params.namespace} - Namespace</Link>
<Link
to={ experimentURL(params.experiment) }
className="nav-link"
>{params.experiment} - Experiment </Link>
<Link
to={ paramURL(params.param) }
className="nav-link"
>{params.param} - Param </Link>
</NavSection>
<div className="col-sm-9">
<NewChoice params={params}/>
</div>
</div>
</div>
);
}
export default NewChoiceView;
|
src/App.js | kriml76/react-try | import React, { Component } from 'react';
import { Layout } from 'antd';
import './style/index.less';
import SiderCustom from './components/SiderCustom';
import HeaderCustom from './components/HeaderCustom';
import { receiveData } from './action';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
const { Content, Footer } = Layout;
class App extends Component {
state = {
collapsed: false,
};
componentWillMount() {
const { receiveData } = this.props;
const user = JSON.parse(localStorage.getItem('user'));
user && receiveData(user, 'auth');
// receiveData({a: 213}, 'auth');
// fetchData({funcName: 'admin', stateName: 'auth'});
this.getClientWidth();
window.onresize = () => {
console.log('屏幕变化了');
this.getClientWidth();
// console.log(document.body.clientWidth);
}
}
getClientWidth = () => { // 获取当前浏览器宽度并设置responsive管理响应式
const { receiveData } = this.props;
const clientWidth = document.body.clientWidth;
console.log(clientWidth);
receiveData({isMobile: clientWidth <= 992}, 'responsive');
};
toggle = () => {
this.setState({
collapsed: !this.state.collapsed,
});
};
render() {
console.log(this.props.auth);
console.log(this.props.responsive);
const { auth, router, responsive } = this.props;
return (
<Layout className="ant-layout-has-sider">
{!responsive.data.isMobile && <SiderCustom path={this.props.location.pathname} collapsed={this.state.collapsed} />}
<Layout>
<HeaderCustom toggle={this.toggle} user={auth.data || {}} router={router} path={this.props.location.pathname} />
<Content style={{ margin: '0 16px', overflow: 'initial' }}>
{this.props.children}
</Content>
<Footer style={{ textAlign: 'center' }}>
React-Admin ©2017 Created by 865470087@qq.com
</Footer>
</Layout>
{
responsive.data.isMobile && ( // 手机端对滚动很慢的处理
<style>
{`
#root{
height: auto;
}
`}
</style>
)
}
</Layout>
);
}
}
const mapStateToProps = state => {
const { auth = {data: {}}, responsive = {data: {}} } = state.httpData;
return {auth, responsive};
};
const mapDispatchToProps = dispatch => ({
receiveData: bindActionCreators(receiveData, dispatch)
});
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
app/javascript/mastodon/features/ui/components/modal_root.js | alarky/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import MediaModal from './media_modal';
import OnboardingModal from './onboarding_modal';
import VideoModal from './video_modal';
import BoostModal from './boost_modal';
import ConfirmationModal from './confirmation_modal';
import ReportModal from './report_modal';
import TransitionMotion from 'react-motion/lib/TransitionMotion';
import spring from 'react-motion/lib/spring';
const MODAL_COMPONENTS = {
'MEDIA': MediaModal,
'ONBOARDING': OnboardingModal,
'VIDEO': VideoModal,
'BOOST': BoostModal,
'CONFIRM': ConfirmationModal,
'REPORT': ReportModal,
};
export default class ModalRoot extends React.PureComponent {
static propTypes = {
type: PropTypes.string,
props: PropTypes.object,
onClose: PropTypes.func.isRequired,
};
handleKeyUp = (e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!this.props.type) {
this.props.onClose();
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
}
willEnter () {
return { opacity: 0, scale: 0.98 };
}
willLeave () {
return { opacity: spring(0), scale: spring(0.98) };
}
render () {
const { type, props, onClose } = this.props;
const visible = !!type;
const items = [];
if (visible) {
items.push({
key: type,
data: { type, props },
style: { opacity: spring(1), scale: spring(1, { stiffness: 120, damping: 14 }) },
});
}
return (
<TransitionMotion
styles={items}
willEnter={this.willEnter}
willLeave={this.willLeave}
>
{interpolatedStyles =>
<div className='modal-root'>
{interpolatedStyles.map(({ key, data: { type, props }, style }) => {
const SpecificComponent = MODAL_COMPONENTS[type];
return (
<div key={key} style={{ pointerEvents: visible ? 'auto' : 'none' }}>
<div role='presentation' className='modal-root__overlay' style={{ opacity: style.opacity }} onClick={onClose} />
<div className='modal-root__container' style={{ opacity: style.opacity, transform: `translateZ(0px) scale(${style.scale})` }}>
<SpecificComponent {...props} onClose={onClose} />
</div>
</div>
);
})}
</div>
}
</TransitionMotion>
);
}
}
|
src/components/TextareaBox/TextareaBox.stories.js | InsideSalesOfficial/insidesales-components | import React from 'react';
import {
storiesOf,
action
} from '@storybook/react';
import TextareaBox from './TextareaBox';
import {
wrapComponentWithContainerAndTheme,
colors,
} from "../styles";
function renderChapterWithTheme(theme) {
return {
info: `
Usage
~~~
import React from 'react';
import {TextareaBox} from 'insidesales-components';
~~~
`,
chapters: [
{
sections: [
{
title: 'Example: textarea default empty',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
name="first"
onChange={action('value')}
/>
)
},
{
title: 'Example: textarea with existing text',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
name="firstz"
onChange={action('value')}
value="This text was hardcoded into stories. The structure of this component follows how a `TextareaBox` should look."
/>
)
},
{
title: 'Example: textarea with error text',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
helper="Helper text."
error="Errors will override helper text."
name="third"
onChange={action('value')}
value="This text was hardcoded into stories."
/>
)
},
{
title: 'Example: textarea disabled',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
helper="Helper text."
disabled
name="fourth"
onChange={action('value')}
/>
)
},
{
title: 'Example: textarea disabled with text',
sectionFn: () => wrapComponentWithContainerAndTheme(theme,
<TextareaBox
label="Label"
helper="Helper text."
disabled
name="fifth"
value="this is some example text"
onChange={action('value')}/>
)
},
]
}
]
};
}
storiesOf('Form', module)
.addWithChapters("Default TextareaBox", renderChapterWithTheme({}))
.addWithChapters(
"TextareaBox w/ BlueYellow Theme",
renderChapterWithTheme(colors.blueYellowTheme)
);
|
src/svg-icons/navigation/check.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationCheck = (props) => (
<SvgIcon {...props}>
<path d="M9 16.17L4.83 12l-1.42 1.41L9 19 21 7l-1.41-1.41z"/>
</SvgIcon>
);
NavigationCheck = pure(NavigationCheck);
NavigationCheck.displayName = 'NavigationCheck';
NavigationCheck.muiName = 'SvgIcon';
export default NavigationCheck;
|
packages/wix-style-react/stories/Colors/index.story.js | wix/wix-style-react | import React from 'react';
import { description } from 'wix-storybook-utils/Sections';
import { storySettings } from './storySettings';
import { Layout, Cell } from '../../src/Layout';
import colors from '../../src/colors.scss';
import Text from '../../src/Text';
import Box from '../../src/Box';
import rgba_to_hex8 from '../../src/Foundation/stylable/mixins/rgba_to_hex8';
const empty = {};
const lightText = true;
const darkBorder = true;
const colorsTable = [
{
name: 'General',
units: [
empty,
empty,
{
name: 'D10',
description: 'Text',
lightText,
},
{
name: 'D20',
description: 'Secondary Text',
lightText,
},
{
name: 'D30',
},
{
name: 'D40',
description: 'Placeholder Text',
lightText,
},
{
name: 'D50',
darkBorder,
},
{
name: 'D55',
darkBorder,
},
{
name: 'D60',
description: 'Divider',
darkBorder,
},
{
name: 'D70',
description: 'Background',
darkBorder,
},
{
name: 'D80',
description: 'card',
darkBorder,
},
],
},
{
name: 'Primary',
units: [
{
name: 'B00',
description: 'Loader, ProgressBar',
lightText,
},
{
name: 'B05',
},
{
name: 'B10',
description: 'Button, Text Link (Default; Click)',
lightText,
},
{
name: 'B20',
description: 'Button (Hover), Notification Bar',
},
{
name: 'B30',
description: 'Tag (Hover), Floating Notification Border',
},
{
name: 'B40',
description: 'Tag(Default), Badge',
},
{
name: 'B50',
description: 'Floating Notification',
darkBorder,
},
empty,
{
name: 'B60',
darkBorder,
},
],
},
{
name: 'Destructive',
units: [
{
name: 'R00',
},
{
name: 'R05',
},
{
name: 'R10',
description: 'Button, Text Link (Default; Click)',
lightText,
},
{
name: 'R20',
description: 'Button (Hover), Notification Bar',
},
{
name: 'R30',
description: 'Tag (Hover), Floating Notification Border',
},
{
name: 'R40',
description: 'Tag(Default), Badge',
},
{
name: 'R50',
description: 'Floating Notification',
darkBorder,
},
empty,
{
name: 'R60',
darkBorder,
},
],
},
{
name: 'Premium',
units: [
{
name: 'P00',
},
empty,
{
name: 'P10',
description: 'Button, Text Link (Default; Click)',
lightText,
},
{
name: 'P20',
description: 'Button (Hover), Notification Bar',
},
{
name: 'P30',
description: 'Notification Border',
},
{
name: 'P40',
description: 'Badge',
},
{
name: 'P50',
description: 'Floating Notification',
darkBorder,
},
empty,
{
name: 'P60',
darkBorder,
},
],
},
{
name: 'Success',
units: [
{
name: 'G00',
},
{
name: 'G05',
},
{
name: 'G10',
description: 'Badge',
lightText,
},
{
name: 'G20',
description: 'Notification Bar',
},
{
name: 'G30',
description: 'Tag (Hover), Notification Border',
},
{
name: 'G40',
description: 'Tag(Default), Badge',
},
{
name: 'G50',
description: 'Floating Notification',
darkBorder,
},
empty,
{
name: 'G60',
darkBorder,
},
],
},
{
name: 'Warning',
units: [
{
name: 'Y00',
},
{
name: 'Y05',
},
{
name: 'Y10',
description: 'Notification Bar, Badge',
lightText,
},
{
name: 'Y20',
},
{
name: 'Y30',
description: 'Tag (Hover), Floating Notification Border',
},
{
name: 'Y40',
description: 'Tag(Default), Badge',
},
{
name: 'Y50',
description: 'Floating Notification',
darkBorder,
},
empty,
{
name: 'Y60',
darkBorder,
},
],
},
{
name: 'Urgent',
units: [
{
name: 'O00',
},
empty,
{
name: 'O10',
description: 'Badge',
lightText,
},
{
name: 'O20',
},
],
},
// TODO - Colors with opacity will have a page of their own.
// {
// name: 'Opacity',
// units: [
// empty,
// empty,
// empty,
// empty,
// empty,
// empty,
// {
// name: 'D10-05',
// darkBorder,
// rgba_to_hex8,
// },
// {
// name: 'D10-10',
// darkBorder,
// rgba_to_hex8,
// },
// {
// name: 'D10-20',
// darkBorder,
// rgba_to_hex8,
// },
// {
// name: 'D10-30',
// darkBorder,
// rgba_to_hex8,
// },
// ],
// },
{
name: 'Misc',
units: [
{
name: 'F00',
description: 'Focus',
},
],
},
];
export default {
category: storySettings.category,
storyName: storySettings.storyName,
sections: [
description({
title: 'Wix Style design system color palette',
}),
<Layout cols={9}>
{colorsTable.map((category, c_index) => (
<Cell key={c_index} span={1}>
<Box margin={1}>
<Text>{category.name}</Text>
</Box>
<Layout>
{category.units.map((unit, u_index) => (
<Cell key={u_index}>
<Box height="140px" direction="vertical">
<Box
height="80px"
width="80px"
borderRadius="8px"
padding="10px"
backgroundColor={colors[unit.name]}
borderColor="D30"
border={unit.darkBorder ? '1px solid transparent' : ''}
>
<Text light={unit.lightText} size="small">
{unit.description}
</Text>
</Box>
<Box marginTop={1}>
<Text size="small">{unit.name}</Text>
</Box>
<Box>
{unit.rgba_to_hex8 && (
<Text size="small">
{rgba_to_hex8(colors[unit.name])}
</Text>
)}
</Box>
<Box>
<Text size="small">{colors[unit.name]}</Text>
</Box>
</Box>
</Cell>
))}
</Layout>
</Cell>
))}
</Layout>,
],
};
|
src/routes/notFound/NotFound.js | quyetvv/react-starter-kit | /**
* 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 './NotFound.css';
class NotFound 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>Sorry, the page you were trying to view does not exist.</p>
</div>
</div>
);
}
}
export default withStyles(s)(NotFound);
|
app/javascript/mastodon/features/ui/components/actions_modal.js | masarakki/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import StatusContent from '../../../components/status_content';
import Avatar from '../../../components/avatar';
import RelativeTimestamp from '../../../components/relative_timestamp';
import DisplayName from '../../../components/display_name';
import IconButton from '../../../components/icon_button';
import classNames from 'classnames';
export default class ActionsModal extends ImmutablePureComponent {
static propTypes = {
status: ImmutablePropTypes.map,
actions: PropTypes.array,
onClick: PropTypes.func,
};
renderAction = (action, i) => {
if (action === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { icon = null, text, meta = null, active = false, href = '#' } = action;
return (
<li key={`${text}-${i}`}>
<a href={href} target='_blank' rel='noopener' onClick={this.props.onClick} data-index={i} className={classNames({ active })}>
{icon && <IconButton title={text} icon={icon} role='presentation' tabIndex='-1' inverted />}
<div>
<div className={classNames({ 'actions-modal__item-label': !!meta })}>{text}</div>
<div>{meta}</div>
</div>
</a>
</li>
);
}
render () {
const status = this.props.status && (
<div className='status light'>
<div className='boost-modal__status-header'>
<div className='boost-modal__status-time'>
<a href={this.props.status.get('url')} className='status__relative-time' target='_blank' rel='noopener'>
<RelativeTimestamp timestamp={this.props.status.get('created_at')} />
</a>
</div>
<a href={this.props.status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
<Avatar account={this.props.status.get('account')} size={48} />
</div>
<DisplayName account={this.props.status.get('account')} />
</a>
</div>
<StatusContent status={this.props.status} />
</div>
);
return (
<div className='modal-root__modal actions-modal'>
{status}
<ul>
{this.props.actions.map(this.renderAction)}
</ul>
</div>
);
}
}
|
src/svg-icons/toggle/radio-button-checked.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ToggleRadioButtonChecked = (props) => (
<SvgIcon {...props}>
<path d="M12 7c-2.76 0-5 2.24-5 5s2.24 5 5 5 5-2.24 5-5-2.24-5-5-5zm0-5C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8z"/>
</SvgIcon>
);
ToggleRadioButtonChecked = pure(ToggleRadioButtonChecked);
ToggleRadioButtonChecked.displayName = 'ToggleRadioButtonChecked';
ToggleRadioButtonChecked.muiName = 'SvgIcon';
export default ToggleRadioButtonChecked;
|
tmeister/static/src/release-notes/delete/delete-note.component.js | CanopyTax/toggle-meister | import React from 'react'
import ScrollModal from 'common/modal/scroll-modal.component.js'
import { makeStyles } from '@material-ui/core/styles'
import { Icon, Typography } from '@material-ui/core'
import Button from 'commonButton'
import { useDeleteReleaseNote } from '../release-notes.hooks.js'
const useStyles = makeStyles(theme => ({
warningText: {
color: theme.palette.error.main,
}
}))
export default function DeleteReleaseNote (props) {
const { note, close, refetch } = props
const c = useStyles()
const [ deleteNote, deletePending, deleted ] = useDeleteReleaseNote()
if (deleted) {
close()
refetch()
}
return (
<ScrollModal
closeAction={close}
headerText={`Confirm Delete`}
>
<ScrollModal.Body>
<div>
<Typography variant='body1'>
This is a HARD delete. Deleting a release note will immediately stop it from being returned in the API.
You should consider if you really want to PERMANENTLY remove this release note.
</Typography>
<Typography variant='body1' className={c.warningText}>
There is no way to recover deleted notes.
</Typography>
</div>
</ScrollModal.Body>
<ScrollModal.BottomRow>
<div className={'tm-flex-apart'}>
<Button
variant='contained'
color='primary'
onClick={() => {
deleteNote(note)
}}
showLoader={deletePending}
disabled={deletePending}
type={'button'}
>
<Icon>
warning
</Icon>
Delete
</Button>
<Button
variant='contained'
type={'button'}
onClick={close}
>
Cancel
</Button>
</div>
</ScrollModal.BottomRow>
</ScrollModal>
)
}
|
demo/Container.js | akofman/react-puppet | import React from 'react';
export default class Container extends React.Component {
render() {
console.log('Container render');
return (
<div>
{ this.props.children }
</div>
);
}
}
|
src/MediaLeft.js | apkiernan/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import Media from './Media';
import { bsClass, getClassSet, prefix, splitBsProps }
from './utils/bootstrapUtils';
const propTypes = {
/**
* Align the media to the top, middle, or bottom of the media object.
*/
align: React.PropTypes.oneOf(['top', 'middle', 'bottom']),
};
class MediaLeft extends React.Component {
render() {
const { align, className, ...props } = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = getClassSet(bsProps);
if (align) {
// The class is e.g. `media-top`, not `media-left-top`.
classes[prefix(Media.defaultProps, align)] = true;
}
return (
<div
{...elementProps}
className={classNames(className, classes)}
/>
);
}
}
MediaLeft.propTypes = propTypes;
export default bsClass('media-left', MediaLeft);
|
fields/types/relationship/RelationshipColumn.js | creynders/keystone | import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
const moreIndicatorStyle = {
color: '#bbb',
fontSize: '.8rem',
fontWeight: 500,
marginLeft: 8,
};
var RelationshipColumn = React.createClass({
displayName: 'RelationshipColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderMany (value) {
if (!value || !value.length) return;
const refList = this.props.col.field.refList;
const items = [];
for (let i = 0; i < 3; i++) {
if (!value[i]) break;
if (i) {
items.push(<span key={'comma' + i}>, </span>);
}
items.push(
<ItemsTableValue interior truncate={false} key={'anchor' + i} to={Keystone.adminPath + '/' + refList.path + '/' + value[i].id}>
{value[i].name}
</ItemsTableValue>
);
}
if (value.length > 3) {
items.push(<span key="more" style={moreIndicatorStyle}>[...{value.length - 3} more]</span>);
}
return (
<ItemsTableValue field={this.props.col.type}>
{items}
</ItemsTableValue>
);
},
renderValue (value) {
if (!value) return;
const refList = this.props.col.field.refList;
return (
<ItemsTableValue to={Keystone.adminPath + '/' + refList.path + '/' + value.id} padded interior field={this.props.col.type}>
{value.name}
</ItemsTableValue>
);
},
render () {
const value = this.props.data.fields[this.props.col.path];
const many = this.props.col.field.many;
return (
<ItemsTableCell>
{many ? this.renderMany(value) : this.renderValue(value)}
</ItemsTableCell>
);
},
});
module.exports = RelationshipColumn;
|
public/js/7B.js | ritchieanesco/frontendmastersreact | /* Routing Urls */
import React from 'react'
const Landing = React.createClass({
render () {
return (
<div className='landing'>
<h1>My Landing</h1>
<input type='text' placeholder='Search' />
<a>or Browse all</a>
</div>
)
}
})
export default Landing
|
server/sonar-web/src/main/js/app/components/GlobalContainer.js | Builders-SonarSource/sonarqube-bis | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
// @flow
import React from 'react';
import GlobalNav from './nav/global/GlobalNav';
import GlobalFooter from './GlobalFooter';
import GlobalMessagesContainer from './GlobalMessagesContainer';
export default class GlobalContainer extends React.Component {
render () {
// it is important to pass `location` down to `GlobalNav` to trigger render on url change
return (
<div className="global-container">
<div className="page-wrapper page-wrapper-global" id="container">
<div className="page-container">
<GlobalNav location={this.props.location}/>
<GlobalMessagesContainer/>
{this.props.children}
</div>
</div>
<GlobalFooter/>
</div>
);
}
}
|
packages/material-ui-icons/src/AddShoppingCart.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let AddShoppingCart = props =>
<SvgIcon {...props}>
<path d="M11 9h2V6h3V4h-3V1h-2v3H8v2h3v3zm-4 9c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zm10 0c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2zm-9.83-3.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.86-7.01L19.42 4h-.01l-1.1 2-2.76 5H8.53l-.13-.27L6.16 6l-.95-2-.94-2H1v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.13 0-.25-.11-.25-.25z" />
</SvgIcon>;
AddShoppingCart = pure(AddShoppingCart);
AddShoppingCart.muiName = 'SvgIcon';
export default AddShoppingCart;
|
src/components/SocialLoginLink.js | react-auth/react-auth | import React from 'react';
import utils from '../utils';
import context from './../context';
export default class SocialLoginLink extends React.Component {
state = {
disabled: false
};
_onClick(e) {
e.preventDefault();
if (!this.state.disabled) {
this.setState({ disabled: true });
context.authProvider.loginWithSocialProvider({
providerId: this.props.providerId
}, () => {
this.setState({ disabled: false });
});
}
}
render() {
var providerId = this.props.providerId;
return (
<a {...this.props} href='#' onClick={this._onClick.bind(this)} disabled={this.state.disabled}>
{ this.props.children ? this.props.children : 'Login with ' + utils.translateProviderIdToName(providerId)}
</a>
);
}
}
|
lib/components/App.js | iryan2/mash | import React, { Component } from 'react';
import LoginRegister from './LoginRegister';
let style = {
alignItems: 'center',
display: 'flex',
height: '100%',
justifyContent: 'center'
};
class App extends Component {
render() {
return <div style={style}>
<LoginRegister />
</div>
}
}
export default App;
|
src/index.js | cdelaorden/redux-ecs-game | import babelPolyfill from 'babel-polyfill'
import ReactDOM from 'react-dom'
import React from 'react'
import gameStore from './create_store'
import App from './containers/app'
import { Provider } from 'react-redux'
import { createSphereBody } from './engine/components/sphere_body'
console.log(gameStore)
//Create the ball
gameStore.engine.createEntity('ball', {
'position': { x: 600, y: 20 },
'velocity2D': { vx: 3, vy: 0 },
'sphereBody': createSphereBody(20),
'tag': { tag: 'ball' }
})
if(__DEV__){
window.debugGameState = function(){
const state = gameStore.getState()
console.log('GAME STATE')
Object.keys(state).forEach(k => {
if(state.hasOwnProperty(k) && typeof state[k] === 'object' && typeof state[k].toJS === 'function')
console.log(k, state[k].toJS())
else
console.log(k, state[k])
})
}
}
window.debugGameState()
ReactDOM.render(<Provider store={gameStore}><App /></Provider>, document.getElementById('app')) |
src/PaginationButton.js | simonliubo/react-ui | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import createSelectedEvent from './utils/createSelectedEvent';
import CustomPropTypes from './utils/CustomPropTypes';
const PaginationButton = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
className: React.PropTypes.string,
eventKey: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool,
active: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
buttonComponentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
active: false,
disabled: false
};
},
handleClick(event) {
if (this.props.onSelect) {
let selectedEvent = createSelectedEvent(this.props.eventKey);
this.props.onSelect(event, selectedEvent);
}
},
render() {
let classes = {
active: this.props.active,
disabled: this.props.disabled,
...this.getBsClassSet()
};
let {
className,
...anchorProps
} = this.props;
let ButtonComponentClass = this.props.buttonComponentClass;
return (
<li className={classNames(className, classes)}>
<ButtonComponentClass
{...anchorProps}
onClick={this.handleClick} />
</li>
);
}
});
export default PaginationButton;
|
docs/app/Examples/elements/Label/Groups/LabelExampleGroupSize.js | vageeshb/Semantic-UI-React | import React from 'react'
import { Label } from 'semantic-ui-react'
const LabelExampleGroupSize = () => (
<Label.Group size='huge'>
<Label>Fun</Label>
<Label>Happy</Label>
<Label>Smart</Label>
<Label>Witty</Label>
</Label.Group>
)
export default LabelExampleGroupSize
|
src/components/waste-water/sidebar-layers/search/search-bar.js | impact-initiatives/reach-jor-zaatari-webmap | import React from 'react';
import messages from '../../../../translations/waste-water.js';
import store from '../../../../store/index.js';
import styles from '../../../../styles/index.js';
function onChange({ target }) {
const { value } = target;
store.dispatch({ type: (state) => ({
...state,
search: {
...state.search,
wasteWater: value,
},
}) });
}
function onKeyUp({ keyCode, target }) {
if (keyCode === 13) {
target.blur();
store.dispatch({ type: (state) => ({
...state,
sidebarLayers: {
...state.sidebarLayers,
open: false,
},
}) });
}
}
export default ({ state }) => (
<div className={styles.flex.verticalLeft}>
<div className={styles.inline.height6} />
<input className={styles.form.searchBar}
onChange={onChange}
onKeyUp={onKeyUp}
placeholder={messages.search.searchBar[state.lang]}
value={state.search.wasteWater} />
</div>
);
|
src/components/NotFound.js | kunal-mandalia/reactnd-project-readable | import React from 'react'
import '../styles/NotFound.css'
const getDisplayMessage = filterBy => {
switch (filterBy) {
case 'none':
return `Lucky number one. Be the first poster!`
case 'category':
return `That category isn't looking very popular. Create a post for it to get it started.`
case 'post':
return `We couldn't find that post.`
default:
return `404. We couldn't find what you requested.`
}
}
export const NotFound = ({ filterBy }) => {
const displayMessage = getDisplayMessage(filterBy)
return (
<div className='not-found'>
{displayMessage}
</div>
)
}
export default NotFound
|
game-of-life-react-parcel/src/index.js | LandRover/gym | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
if (module.hot) {
module.hot.accept()
} |
src/index.js | Jazmon/TESK-app | import 'core-js/fn/object/assign';
import 'materialize-css/sass/materialize.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
src/Parser/Hunter/Shared/Modules/Items/RootsOfShaladrassil.js | hasseboulen/WoWAnalyzer | import React from 'react';
import ITEMS from 'common/ITEMS';
import SPELLS from 'common/SPELLS';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import ItemHealingDone from 'Main/ItemHealingDone';
/**
* Roots of Shaladrassil
* Equip: Standing still causes you to send deep roots into the ground, healing you for 3% of your maximum health every 1 sec.
*/
class RootsOfShaladrassil extends Analyzer {
static dependencies = {
combatants: Combatants,
};
healing = 0;
on_initialized() {
this.active = this.combatants.selected.hasLegs(ITEMS.ROOTS_OF_SHALADRASSIL.id);
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.ROOTS_OF_SHALADRASSIL_HEAL.id) {
this.healing += event.amount;
}
}
item() {
return {
item: ITEMS.ROOTS_OF_SHALADRASSIL,
result: <ItemHealingDone amount={this.healing} />,
};
}
}
export default RootsOfShaladrassil;
|
src/components/panel/panel-block.js | bokuweb/re-bulma | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../../build/styles';
import { getCallbacks } from '../../helper/helper';
export default class PanelBlock extends Component {
static propTypes = {
children: PropTypes.any,
className: PropTypes.string,
isActive: PropTypes.bool,
icon: PropTypes.string,
style: PropTypes.object,
};
static defaultProps = {
className: '',
style: {},
};
createClassName() {
return [
styles.panelBlock,
this.props.isActive ? styles.isActive : '',
this.props.className,
].join(' ').trim();
}
renderIcon() {
return (
<span className={styles.panelIcon}>
<i className={[styles.fa, this.props.icon].join(' ')} />
</span>
);
}
render() {
return (
<span
{...getCallbacks(this.props)}
style={this.props.style}
className={this.createClassName()}
>
{this.props.icon ? this.renderIcon() : null}
{this.props.children}
</span>
);
}
}
|
src/static/index.js | AdrienAgnel/testDjangoApp | import React from 'react';
import ReactDOM from 'react-dom';
import createHistory from 'history/createBrowserHistory';
import { authLoginUserSuccess } from './actions/auth';
import Root from './containers/Root/Root';
import configureStore from './store/configureStore';
const initialState = {};
const target = document.getElementById('root');
const history = createHistory();
const store = configureStore(initialState, history);
const node = (
<Root store={store} history={history} />
);
const token = sessionStorage.getItem('token');
let user = {};
try {
user = JSON.parse(sessionStorage.getItem('user'));
} catch (e) {
// Failed to parse
}
if (token !== null) {
store.dispatch(authLoginUserSuccess(token, user));
}
ReactDOM.render(node, target);
|
src/svg-icons/action/alarm-add.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAlarmAdd = (props) => (
<SvgIcon {...props}>
<path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/>
</SvgIcon>
);
ActionAlarmAdd = pure(ActionAlarmAdd);
ActionAlarmAdd.displayName = 'ActionAlarmAdd';
ActionAlarmAdd.muiName = 'SvgIcon';
export default ActionAlarmAdd;
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/DefaultProps.js | JonathanUsername/flow | // @flow
import React from 'react';
class MyComponent extends React.Component {
static defaultProps: DefaultProps = {};
props: Props;
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
const expression = () =>
class extends React.Component {
static defaultProps: DefaultProps = {};
props: Props;
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
|
stories/containers/channels/channel-create-summary.stories.js | LN-Zap/zap-desktop | import React from 'react'
import { storiesOf } from '@storybook/react'
import { ChannelCreateSummary } from 'components/Channels'
import { Provider } from '../../Provider'
storiesOf('Containers.Channels', module)
.addDecorator(story => <Provider story={story()} />)
.addWithChapters('ChannelCreateSummary', {
chapters: [
{
sections: [
{
sectionFn: () => {
const stateProps = {
amount: 1487005,
fee: {
slow: 5,
medium: 50,
fast: 100,
},
speed: 'TRANSACTION_SPEED_SLOW',
nodePubkey: '03cf5a37ed661e3c61c7943941834771631cd880985340ed7543ad79a968cea454',
nodeDisplayName: 'Sparky',
}
return <ChannelCreateSummary {...stateProps} />
},
},
],
},
],
})
|
src/utils/defaultArrowRenderer.js | Khan/react-select | import React from 'react';
export default function arrowRenderer ({ onMouseDown }) {
return (
<span
className="Select-arrow"
onMouseDown={onMouseDown}
/>
);
};
|
investninja-web-ui-admin/src/server.js | InvestNinja/InvestNinja-web-ui | import 'babel-polyfill';
import path from 'path';
import express from 'express';
import cookieParser from 'cookie-parser';
import bodyParser from 'body-parser';
import expressJwt from 'express-jwt';
// import expressGraphQL from 'express-graphql';
// import jwt from 'jsonwebtoken';
import React from 'react';
import ReactDOM from 'react-dom/server';
import UniversalRouter from 'universal-router';
import PrettyError from 'pretty-error';
import Html from './components/Html';
import { ErrorPageWithoutStyle } from './routes/error/ErrorPage';
import errorPageStyle from './routes/error/ErrorPage.css';
// import passport from './core/passport';
// import models from './data/models';
// import schema from './data/schema';
import routes from './routes';
import assets from './assets'; // eslint-disable-line import/no-unresolved
import { port, auth } from './config';
const app = express();
//
// Tell any CSS tooling (such as Material UI) to use all vendor prefixes if the
// user agent is not known.
// -----------------------------------------------------------------------------
global.navigator = global.navigator || {};
global.navigator.userAgent = global.navigator.userAgent || 'all';
//
// Register Node.js middleware
// -----------------------------------------------------------------------------
app.use(express.static(path.join(__dirname, 'public')));
app.use(cookieParser());
app.use(bodyParser.urlencoded({ extended: true }));
app.use(bodyParser.json());
//
// Authentication
// -----------------------------------------------------------------------------
app.use(expressJwt({
secret: auth.jwt.secret,
credentialsRequired: false,
getToken: req => req.cookies.id_token,
}));
// app.use(passport.initialize());
//
// app.get('/login/facebook',
// passport.authenticate('facebook', { scope: ['email', 'user_location'], session: false })
// );
// app.get('/login/facebook/return',
// passport.authenticate('facebook', { failureRedirect: '/login', session: false }),
// (req, res) => {
// const expiresIn = 60 * 60 * 24 * 180; // 180 days
// const token = jwt.sign(req.user, auth.jwt.secret, { expiresIn });
// res.cookie('id_token', token, { maxAge: 1000 * expiresIn, httpOnly: true });
// res.redirect('/');
// }
// );
//
// Register API middleware
// -----------------------------------------------------------------------------
// app.use('/graphql', expressGraphQL(req => ({
// schema,
// graphiql: true,
// rootValue: { request: req },
// pretty: process.env.NODE_ENV !== 'production',
// })));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
app.get('*', async (req, res, next) => {
try {
let css = new Set();
let statusCode = 200;
const data = { title: '', description: '', style: '', script: assets.main.js, children: '' };
await UniversalRouter.resolve(routes, {
path: req.path,
query: req.query,
context: {
insertCss: (...styles) => {
styles.forEach(style => css.add(style._getCss())); // eslint-disable-line no-underscore-dangle, max-len
},
setTitle: value => (data.title = value),
setMeta: (key, value) => (data[key] = value),
},
render(component, status = 200) {
// console.log('inside render of UniversalRouter', component);
css = new Set();
statusCode = status;
data.children = ReactDOM.renderToString(component);
data.style = [...css].join('');
return true;
},
});
// console.log('outside render func of UniversalRouter with statusCode', statusCode);
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode);
res.send(`<!doctype html>${html}`);
} catch (err) {
// console.log('some error occured', err);
next(err);
}
});
//
// Error handling
// -----------------------------------------------------------------------------
const pe = new PrettyError();
pe.skipNodeFiles();
pe.skipPackage('express');
app.use((err, req, res, next) => { // eslint-disable-line no-unused-vars
console.log(pe.render(err)); // eslint-disable-line no-console
const statusCode = err.status || 500;
const html = ReactDOM.renderToStaticMarkup(
<Html
title="Internal Server Error"
description={err.message}
style={errorPageStyle._getCss()} // eslint-disable-line no-underscore-dangle
>
{ReactDOM.renderToString(<ErrorPageWithoutStyle error={err} />)}
</Html>
);
res.status(statusCode);
res.send(`<!doctype html>${html}`);
});
app.listen(port, () => {
console.log(`The server is running at http://localhost:${port}/`);
});
//
// Launch the server
// -----------------------------------------------------------------------------
/* eslint-disable no-console */
// models.sync().catch(err => console.error(err.stack)).then(() => {
// app.listen(port, () => {
// console.log(`The server is running at http://localhost:${port}/`);
// });
// });
/* eslint-enable no-console */
|
components/Application.js | jeffhandley/fluxible-context | /*globals document*/
import React from 'react';
import Nav from './Nav';
import Home from './Home';
import About from './About';
import ApplicationStore from '../stores/ApplicationStore';
import provideContext from 'fluxible/addons/provideContext';
import connectToStores from 'fluxible/addons/connectToStores';
import { handleHistory } from 'fluxible-router';
// @TODO Upgrade to ES6 class when RouterMixin is replaced
var Application = React.createClass({
propTypes: {
context: React.PropTypes.object.isRequired
},
render: function () {
// Returns the expected componentContext.demonstrate value
console.log('Application', 'this.props.context.demonstrate', this.props.context.demonstrate);
var Handler = this.props.currentRoute.get('handler');
return (
<div>
<Nav selected={this.props.currentPageName} links={this.props.pages} />
<Handler />
</div>
);
},
componentDidUpdate: function(prevProps, prevState) {
const newProps = this.props;
if (newProps.pageTitle === prevProps.pageTitle) {
return;
}
document.title = newProps.pageTitle;
}
});
export default handleHistory(provideContext(connectToStores(
Application,
[ApplicationStore],
function (stores, props) {
var appStore = stores.ApplicationStore;
return {
currentPageName: appStore.getCurrentPageName(),
pageTitle: appStore.getPageTitle(),
pages: appStore.getPages()
};
}
), { // child context types
demonstrate: React.PropTypes.func.isRequired
}));
|
src/components/ChatApp/MessageSection/MessageSection.react.js | isuruAb/chat.susi.ai | import MessageComposer from '../MessageComposer.react';
import Snackbar from 'material-ui/Snackbar';
import MessageListItem from '../MessageListItem/MessageListItem.react';
import MessageStore from '../../../stores/MessageStore';
import React, { Component } from 'react';
import ThreadStore from '../../../stores/ThreadStore';
import UserPreferencesStore from '../../../stores/UserPreferencesStore';
import PropTypes from 'prop-types';
import { addUrlProps, UrlQueryParamTypes } from 'react-url-query';
import loadingGIF from '../../../images/loading.gif';
import DialogSection from './DialogSection';
import RaisedButton from 'material-ui/RaisedButton';
import { CirclePicker } from 'react-color';
import $ from 'jquery';
import { Scrollbars } from 'react-custom-scrollbars';
import TopBar from '../TopBar.react';
import TextField from 'material-ui/TextField';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import NavigateDown from 'material-ui/svg-icons/navigation/expand-more';
import * as Actions from '../../../actions/';
import Translate from '../../Translate/Translate.react';
import Cookies from 'universal-cookie';
const cookies=new Cookies();
function getStateFromStores() {
var themeValue=[];
var backgroundValue = [];
// get Theme data from server
if(UserPreferencesStore.getThemeValues()){
themeValue=UserPreferencesStore.getThemeValues().split(',');
}
if(UserPreferencesStore.getBackgroundImage()){
backgroundValue=UserPreferencesStore.getBackgroundImage().split(',');
}
return {
SnackbarOpen: false,
SnackbarOpenBackground: false,
messages: MessageStore.getAllForCurrentThread(),
thread: ThreadStore.getCurrent(),
currTheme: UserPreferencesStore.getTheme(),
tour:true,
search: false,
showLoading: MessageStore.getLoadStatus(),
showLogin: false,
openForgotPassword:false,
showSignUp: false,
showThemeChanger: false,
showHardwareChangeDialog: false,
showHardware: false,
showServerChangeDialog: false,
header: themeValue.length>5?'#'+themeValue[0]:'#4285f4',
pane: themeValue.length>5?'#'+themeValue[1]:'#f5f4f6',
body: themeValue.length>5?'#'+themeValue[2]:'#fff',
composer: themeValue.length>5?'#'+themeValue[3]:'#f5f4f6',
textarea: themeValue.length>5?'#'+themeValue[4]:'#fff',
button: themeValue.length>5? '#'+themeValue[5]:'#4285f4',
bodyBackgroundImage : backgroundValue.length>1 ? backgroundValue[0] : '',
snackopen: false,
snackMessage: 'It seems you are offline!',
SnackbarOpenSearchResults:false,
messageBackgroundImage : backgroundValue.length>1 ? backgroundValue[1] : '',
showScrollBottom: false,
searchState: {
markedMsgs: [],
markedIDs: [],
markedIndices: [],
scrollLimit: 0,
scrollIndex: -1,
scrollID: null,
caseSensitive: false,
open: false,
searchIndex: 0,
searchText:'',
}
};
}
function getMessageListItem(messages, showLoading, markID) {
// markID indicates search mode on
if(markID){
return messages.map((message) => {
return (
<MessageListItem
key={message.id}
message={message}
markID={markID}
/>
);
});
}
// Get message ID waiting for server response
let latestUserMsgID = null;
if(showLoading && messages){
let msgCount = messages.length;
if(msgCount>0){
let latestUserMsg = messages[msgCount-1];
latestUserMsgID = latestUserMsg.id;
}
}
// return the list of messages
return messages.map((message) => {
return (
<MessageListItem
key={message.id}
message={message}
latestUserMsgID={latestUserMsgID}
/>
);
});
}
// markdown search results
function searchMsgs(messages, matchString, isCaseSensitive) {
let markingData = {
allmsgs: [],
markedIDs: [],
markedIndices: [],
};
messages.forEach((msg, id) => {
let orgMsgText = msg.text;
let msgCopy = $.extend(true, {}, msg);
let msgText = orgMsgText;
if (orgMsgText) {
if (!isCaseSensitive) {
matchString = matchString.toLowerCase();
msgText = msgText.toLowerCase();
}
let match = msgText.indexOf(matchString);
if (match !== -1) {
msgCopy.mark = {
matchText: matchString,
isCaseSensitive: isCaseSensitive
};
markingData.markedIDs.unshift(msgCopy.id);
markingData.markedIndices.unshift(id);
}
}
markingData.allmsgs.push(msgCopy);
});
return markingData;
}
function getLoadingGIF() {
let messageContainerClasses = 'message-container SUSI';
const LoadingComponent = (
<li className='message-list-item'>
<section className={messageContainerClasses}>
<img src={loadingGIF}
style={{ height: '10px', width: 'auto' }}
alt='please wait..' />
</section>
</li>
);
return LoadingComponent;
}
const urlPropsQueryConfig = {
dream: { type: UrlQueryParamTypes.string }
};
class MessageSection extends Component {
static propTypes = {
dream: PropTypes.string
};
static defaultProps = {
dream: ''
};
state = {
showLogin: false
};
constructor(props) {
super(props);
this.state = getStateFromStores();
this.customTheme={
'header':this.state.header.substring(1),
'pane':this.state.pane.substring(1),
'body':this.state.body.substring(1),
'composer':this.state.composer.substring(1),
'textarea':this.state.textarea.substring(1),
'button':this.state.button.substring(1)
};
}
handleColorChange = (name,color) => {
// Current Changes
}
// Add Image as a background image
handleChangeBodyBackgroundImage = (backImage) => {
this.setState({bodyBackgroundImage:backImage});
}
handleChangeMessageBackgroundImage = (backImage) => {
this.setState({messageBackgroundImage:backImage});
}
// get the selected custom colour
handleChangeComplete = (name, color) => {
this.setState({currTheme : 'custom'})
let currSettings = UserPreferencesStore.getPreferences();
let settingsChanged = {};
if(currSettings.Theme !=='custom'){
settingsChanged.theme = 'custom';
Actions.settingsChanged(settingsChanged);
}
// Send these Settings to Server
let state = this.state;
if(name === 'header'){
state.header = color.hex;
this.customTheme.header=state.header.substring(1);
}
else if(name === 'body'){
state.body= color.hex;
this.customTheme.body=state.body.substring(1);
}
else if(name === 'pane'){
state.pane = color.hex;
this.customTheme.pane=state.pane.substring(1);
}
else if(name === 'composer'){
state.composer = color.hex;
this.customTheme.composer=state.composer.substring(1);
}
else if(name === 'textarea'){
state.textarea = color.hex;
this.customTheme.textarea=state.textarea.substring(1);
}
else if(name === 'button'){
state.button = color.hex;
this.customTheme.button=state.button.substring(1);
}
this.setState(state);
document.body.style.setProperty('background-color', this.state.body);
}
// Open Login Dialog
handleOpen = () => {
this.setState({
showLogin: true,
showSignUp: false,
openForgotPassword: false
});
this.child.closeOptions();
}
// Open Sign Up Dialog
handleSignUp = () => {
this.setState({
showSignUp: true,
showLogin: false
});
this.child.closeOptions();
}
handleRemoveUrlBody = () => {
if(!this.state.bodyBackgroundImage){
this.setState({SnackbarOpenBackground: true});
setTimeout(() => {
this.setState({
SnackbarOpenBackground: false
});
}, 2500);
}
else{
this.setState({
bodyBackgroundImage: ''
});
}
}
handleRemoveUrlMessage = () => {
if(!this.state.messageBackgroundImage){
this.setState({SnackbarOpenBackground: true});
setTimeout(() => {
this.setState({
SnackbarOpenBackground: false
});
}, 2500);
}
else{
this.setState({
messageBackgroundImage:''
});
}
}
handleRemoveUrlBody = () => {
if(!this.state.bodyBackgroundImage){
this.setState({SnackbarOpenBackground: true});
setTimeout(() => {
this.setState({
SnackbarOpenBackground: false
});
}, 2500);
}
else{
this.setState({
bodyBackgroundImage: ''
});
this.handleChangeBodyBackgroundImage('');
}
}
handleRemoveUrlMessage = () => {
if(!this.state.messageBackgroundImage){
this.setState({SnackbarOpenBackground: true});
setTimeout(() => {
this.setState({
SnackbarOpenBackground: false
});
}, 2500);
}
else{
this.setState({
messageBackgroundImage:''
});
}
}
// Close all dialog boxes
handleClose = () => {
var prevThemeSettings=this.state.prevThemeSettings;
this.setState({
showLogin: false,
showSignUp: false,
showThemeChanger: false,
openForgotPassword: false,
});
if(prevThemeSettings && prevThemeSettings.hasOwnProperty('currTheme') && prevThemeSettings.currTheme==='custom'){
this.setState({
currTheme:prevThemeSettings.currTheme,
body:prevThemeSettings.bodyColor,
header:prevThemeSettings.TopBarColor,
composer:prevThemeSettings.composerColor,
pane:prevThemeSettings.messagePane,
textarea:prevThemeSettings.textArea,
button:prevThemeSettings.buttonColor,
bodyBackgroundImage:prevThemeSettings.bodyBackgroundImage,
messageBackgroundImage:prevThemeSettings.messageBackgroundImage,
})
}
else{
// default theme
this.setState({
body : '#fff',
header : '#4285f4',
composer : '#f3f2f4',
pane : '#f3f2f4',
textarea: '#fff',
button: this.state.prevThemeSettings.currTheme==='light'?'#4285f4':'#19314B',
});
let customData='';
Object.keys(this.customTheme).forEach((key) => {
customData=customData+this.customTheme[key]+','
});
let settingsChanged = {};
settingsChanged.theme = this.state.prevThemeSettings.currTheme;
settingsChanged.customThemeValue = customData;
if(this.state.bodyBackgroundImage || this.state.messageBackgroundImage) {
settingsChanged.backgroundImage = this.state.bodyBackgroundImage + ',' + this.state.messageBackgroundImage;
}
Actions.settingsChanged(settingsChanged);
this.setState({currTheme : this.state.prevThemeSettings.currTheme});
this.setState({
showLogin: false,
showSignUp: false,
showThemeChanger: false,
openForgotPassword: false,
});
}
}
handleCloseTour = ()=>{
this.setState({
showLogin: false,
showSignUp: false,
showThemeChanger: false,
openForgotPassword: false,
tour:false
});
cookies.set('visited', true, { path: '/' });
}
// Save Custom Theme settings on server
saveThemeSettings = () => {
let customData='';
Object.keys(this.customTheme).forEach((key) => {
customData=customData+this.customTheme[key]+','
});
let settingsChanged = {};
settingsChanged.theme = 'custom';
settingsChanged.customThemeValue = customData;
if(this.state.bodyBackgroundImage || this.state.messageBackgroundImage) {
settingsChanged.backgroundImage = this.state.bodyBackgroundImage + ',' + this.state.messageBackgroundImage;
}
Actions.settingsChanged(settingsChanged);
this.setState({currTheme : 'custom'})
this.setState({
showLogin: false,
showSignUp: false,
showThemeChanger: false,
openForgotPassword: false,
});
}
handleRestoreDefaultThemeClick = () => {
this.setState({
showLogin: false,
showSignUp: false,
showThemeChanger: false,
openForgotPassword: false,
});
this.applyLightTheme();
}
applyLightTheme = () =>{
this.setState({
prevThemeSettings:null,
body : '#fff',
header : '#4285f4',
composer : '#f3f2f4',
pane : '#f3f2f4',
textarea: '#fff',
button: '#4285f4',
currTheme : 'light'
});
let customData='';
Object.keys(this.customTheme).forEach((key) => {
customData=customData+this.customTheme[key]+','
});
let settingsChanged = {};
settingsChanged.theme = 'light';
settingsChanged.customThemeValue = customData;
if(this.state.bodyBackgroundImage || this.state.messageBackgroundImage) {
settingsChanged.backgroundImage = this.state.bodyBackgroundImage + ',' + this.state.messageBackgroundImage;
}
Actions.settingsChanged(settingsChanged);
}
handleThemeChanger = () => {
this.setState({showThemeChanger: true});
// save the previous theme settings
if(this.state.currTheme==='light'){
// remove the previous custom theme memory
this.applyLightTheme();
}
var prevThemeSettings={};
var state=this.state;
prevThemeSettings.currTheme=state.currTheme;
if(state.currTheme==='custom'){
prevThemeSettings.bodyColor = state.body;
prevThemeSettings.TopBarColor = state.header;
prevThemeSettings.composerColor = state.composer;
prevThemeSettings.messagePane = state.pane;
prevThemeSettings.textArea = state.textarea;
prevThemeSettings.buttonColor= state.button;
prevThemeSettings.bodyBackgroundImage=state.bodyBackgroundImage;
prevThemeSettings.messageBackgroundImage=state.messageBackgroundImage;
}
this.setState({prevThemeSettings});
this.child.closeOptions();
}
// Show forgot password dialog
forgotPasswordChanged = () => {
this.setState({
showLogin:false,
openForgotPassword: true
});
this.child.closeOptions();
}
handleActionTouchTap = () => {
this.setState({
SnackbarOpen: false,
});
switch(this.state.currTheme){
case 'light': {
this.settingsChanged({
Theme: 'dark'
});
break;
}
case 'dark': {
this.settingsChanged({
Theme: 'light'
});
break;
}
default: {
// do nothing
}
}
}
handleRequestClose = () => {
this.setState({
SnackbarOpen: false,
});
}
// Executes on search text changes
searchTextChanged = (event) => {
let matchString = event.target.value;
let messages = this.state.messages;
let markingData = searchMsgs(messages, matchString,
this.state.searchState.caseSensitive);
// to make the snackbar hide by default
this.setState({
SnackbarOpenSearchResults: false
})
if(matchString){
let searchState = {
markedMsgs: markingData.allmsgs,
markedIDs: markingData.markedIDs,
markedIndices: markingData.markedIndices,
scrollLimit: markingData.markedIDs.length,
scrollIndex: 0,
scrollID: markingData.markedIDs[0],
caseSensitive: this.state.searchState.caseSensitive,
open: false,
searchIndex: 1,
searchText: matchString
};
if(markingData.markedIDs.length===0 && matchString.trim().length>0){
// if no Messages are marked(i.e no result) and the search query is not empty
searchState.searchIndex = 0;
this.setState({
SnackbarOpenSearchResults: true
})
}
this.setState({
searchState: searchState
});
}
else {
let searchState = {
markedMsgs: markingData.allmsgs,
markedIDs: markingData.markedIDs,
markedIndices: markingData.markedIndices,
scrollLimit: 0,
scrollIndex: -1,
scrollID: null,
caseSensitive: this.state.searchState.caseSensitive,
open: false,
searchIndex: 0,
searchText: ''
}
this.setState({
searchState: searchState
});
}
}
componentDidMount() {
this._scrollToBottom();
MessageStore.addChangeListener(this._onChange.bind(this));
ThreadStore.addChangeListener(this._onChange.bind(this));
window.addEventListener('offline', this.handleOffline.bind(this));
window.addEventListener('online', this.handleOnline.bind(this));
// let state=this.state;
}
// Show a snackbar If user offline
handleOffline() {
this.setState({
snackopen: true,
snackMessage: 'It seems you are offline!'
})
}
// Show a snackbar If user online
handleOnline() {
this.setState({
snackopen: true,
snackMessage: 'Welcome back!'
})
}
// Scroll to bottom feature goes here
onScroll = () => {
let scrollarea = this.scrollarea;
if(scrollarea){
let scrollValues = scrollarea.getValues();
if(scrollValues.top === 1){
this.setState({
showScrollBottom: false,
});
}
else if(!this.state.showScrollBottom){
this.setState({
showScrollBottom: true,
});
}
}
}
renderThumb = ({ style, ...props }) => {
const finalThumbStyle = {
...style,
cursor: 'pointer',
borderRadius: 'inherit',
backgroundColor: 'rgba(200, 200, 200, 0.4)'
};
return <div style={finalThumbStyle} {...props} />;
}
componentWillUnmount() {
MessageStore.removeChangeListener(this._onChange.bind(this));
ThreadStore.removeChangeListener(this._onChange.bind(this));
}
componentWillMount() {
if (this.props.location) {
if (this.props.location.state) {
if (this.props.location.state.hasOwnProperty('showLogin')) {
let showLogin = this.props.location.state.showLogin;
this.setState({ showLogin: showLogin });
}
}
}
switch(this.state.currTheme){
case 'light':{
document.body.className = 'white-body';
break;
}
case 'dark':{
document.body.className = 'dark-body';
break;
}
default: {
// do nothing
}
}
UserPreferencesStore.on('change', () => {
this.setState({
currTheme: UserPreferencesStore.getTheme()
})
switch(this.state.currTheme){
case 'light':{
document.body.className = 'white-body';
break;
}
case 'dark':{
document.body.className = 'dark-body';
break;
}
default: {
// do nothing
}
}
})
}
invertColorTextArea =() => {
// get the text are code
var hex = this.state.textarea;
hex = hex.slice(1);
// convert 3-digit hex to 6-digits.
if (hex.length === 3) {
hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
}
if (hex.length !== 6) {
throw new Error('Invalid HEX color.');
}
var r = parseInt(hex.slice(0, 2), 16),
g = parseInt(hex.slice(2, 4), 16),
b = parseInt(hex.slice(4, 6), 16);
return (r * 0.299 + g * 0.587 + b * 0.114) > 186
? '#000000'
: '#FFFFFF';
}
render() {
var bodyColor;
var TopBarColor;
var composerColor;
var messagePane;
var textArea;
var buttonColor;
var textColor;
switch(this.state.currTheme){
case 'custom':{
bodyColor = this.state.body;
TopBarColor = this.state.header;
composerColor = this.state.composer;
messagePane = this.state.pane;
textArea = this.state.textarea;
textColor= this.invertColorTextArea();
buttonColor= this.state.button;
break;
}
case 'light':{
bodyColor = '#fff';
TopBarColor = '#4285f4';
composerColor = '#f3f2f4';
messagePane = '#f3f2f4';
textArea = '#fff';
buttonColor = '#4285f4';
break;
}
default:{
break;
}
}
document.body.style.setProperty('background-color', bodyColor);
document.body.style.setProperty('background-image', 'url("'+this.state.bodyBackgroundImage+'")');
document.body.style.setProperty('background-repeat', 'no-repeat');
document.body.style.setProperty('background-size', 'cover');
const bodyStyle = {
padding: 0,
textAlign: 'center',
}
const {
dream
} = this.props;
const scrollBottomStyle = {
button : {
float: 'right',
marginRight: '5px',
marginBottom: '10px',
boxShadow:'none',
},
backgroundColor: '#fcfcfc',
icon : {
fill: UserPreferencesStore.getTheme()==='light' ? '#90a4ae' : '#7eaaaf'
}
}
var backgroundCol;
let topBackground = this.state.currTheme;
switch(topBackground){
case 'light':{
backgroundCol = '#4285f4';
break;
}
case 'dark':{
backgroundCol = '#19324c';
break;
}
default: {
// do nothing
}
}
const actions = <RaisedButton
label={<Translate text="Cancel" />}
backgroundColor={
UserPreferencesStore.getTheme()==='light' ? '#4285f4' : '#19314B'}
labelColor="#fff"
width='200px'
keyboardFocused={true}
onTouchTap={this.handleClose}
/>;
const customSettingsDone = <div>
<RaisedButton
label={<Translate text="Save" />}
backgroundColor={buttonColor?buttonColor:'#4285f4'}
labelColor="#fff"
width='200px'
keyboardFocused={true}
onTouchTap={this.saveThemeSettings}
style={{margin:'0 5px'}}
/>
<RaisedButton
label={<Translate text="Reset" />}
backgroundColor={buttonColor?buttonColor:'#4285f4'}
labelColor="#fff"
width='200px'
keyboardFocused={true}
onTouchTap={this.handleRestoreDefaultThemeClick}
style={{margin:'0 5px'}}
/>
</div>;
// Custom Theme feature Component
const componentsList = [
{'id':1, 'component':'header', 'name': 'Header'},
{'id':2, 'component': 'pane', 'name': 'Message Pane'},
{'id':3, 'component':'body', 'name': 'Body'},
{'id':4, 'component':'composer', 'name': 'Composer'},
{'id':5, 'component':'textarea', 'name': 'Textarea'},
{'id':6, 'component':'button', 'name': 'Button'}
];
const components = componentsList.map((component) => {
return <div key={component.id} className='circleChoose'>
<h4><Translate text="Color of"/> <Translate text={component.name}/>:</h4>
<CirclePicker color={component} width={'100%'}
colors={['#f44336', '#e91e63', '#9c27b0', '#673ab7', '#3f51b5', '#2196f3', '#03a9f4', '#00bcd4',
'#009688', '#4caf50', '#8bc34a', '#cddc39', '#ffeb3b', '#ffc107', '#ff9800', '#ff5722', '#795548', '#607d8b',
'#0f0f0f','#ffffff',]}
onChangeComplete={ this.handleChangeComplete.bind(this,
component.component) }
onChange={this.handleColorChange.bind(this,component.id)}>
</CirclePicker>
<TextField
name="backgroundImg"
style={{display:component.component==='body'?'block':'none'}}
onChange={
(e,value)=>
this.handleChangeBodyBackgroundImage(value) }
value={this.state.bodyBackgroundImage}
floatingLabelText={<Translate text="Body Background Image URL" />} />
<RaisedButton
name="removeBackgroundBody"
key={'RemoveBody'}
label={<Translate text="Remove URL" />}
style={{
display:component.component==='body'?'block':'none',
width: '150px'
}}
backgroundColor={buttonColor?buttonColor:'#4285f4'}
labelColor="#fff"
keyboardFocused={true}
onTouchTap={this.handleRemoveUrlBody} />
<TextField
name="messageImg"
style={{display:component.component==='pane'?'block':'none'}}
onChange={
(e,value)=>
this.handleChangeMessageBackgroundImage(value) }
value={this.state.messageBackgroundImage}
floatingLabelText={<Translate text="Message Background Image URL"/>} />
<RaisedButton
name="removeBackgroundMessage"
key={'RemoveMessage'}
label={<Translate text="Remove URL" />}
style={{
display:component.component==='pane'?'block':'none',
width: '150px'
}}
backgroundColor={buttonColor?buttonColor:'#4285f4'}
labelColor="#fff"
keyboardFocused={true}
onTouchTap={this.handleRemoveUrlMessage} />
</div>
})
let speechOutput = UserPreferencesStore.getSpeechOutput();
let speechOutputAlways = UserPreferencesStore.getSpeechOutputAlways();
var body = this.state.body;
let messageListItems = [];
if(this.state.search){
let markID = this.state.searchState.scrollID;
let markedMessages = this.state.searchState.markedMsgs;
messageListItems = getMessageListItem(markedMessages,false,markID);
}
else{
messageListItems = getMessageListItem(this.state.messages,
this.state.showLoading);
}
if (this.state.thread) {
const messageBackgroundStyles = { backgroundColor: messagePane,
backgroundImage: `url(${this.state.messageBackgroundImage})`,
backgroundRepeat: 'no-repeat',
backgroundSize: '100% 100%'
}
return (
<div className={topBackground} style={{background:body}}>
<header className='message-thread-heading'
style={{ backgroundColor: backgroundCol }}>
<TopBar
header={TopBarColor}
{...this.props}
ref={instance => { this.child = instance; }}
handleThemeChanger={this.handleThemeChanger}
handleOpen={this.handleOpen}
handleSignUp={this.handleSignUp}
handleOptions={this.handleOptions}
handleRequestClose={this.handleRequestClose}
handleToggle={this.handleToggle}
searchTextChanged={this.searchTextChanged}
_onClickSearch={this._onClickSearch}
_onClickExit={this._onClickExit}
_onClickRecent={this._onClickRecent}
_onClickPrev={this._onClickPrev}
search={this.state.search}
searchState={this.state.searchState}
/>
</header>
{!this.state.search ? (
<div>
<div className='message-pane'>
<div className='message-section'>
<ul
className='message-list'
ref={(c) => { this.messageList = c; }}
style={messageBackgroundStyles}>
<Scrollbars
renderThumbHorizontal={this.renderThumb}
renderThumbVertical={this.renderThumb}
ref={(ref) => { this.scrollarea = ref; }}
autoHide
onScroll={this.onScroll}
autoHideTimeout={1000}
autoHideDuration={200}>
{messageListItems}
{this.state.showLoading && getLoadingGIF()}
</Scrollbars>
</ul>
{this.state.showScrollBottom &&
<div className='scrollBottom'>
<FloatingActionButton mini={true}
style={scrollBottomStyle.button}
backgroundColor={scrollBottomStyle.backgroundColor}
iconStyle={scrollBottomStyle.icon}
onTouchTap={this.forcedScrollToBottom}>
<NavigateDown />
</FloatingActionButton>
</div>
}
<div className='compose' style={{backgroundColor:composerColor}}>
<MessageComposer
focus={true}
threadID={this.state.thread.id}
dream={dream}
textarea={textArea}
textcolor={textColor}
speechOutput={speechOutput}
speechOutputAlways={speechOutputAlways}
micColor={this.state.button} />
</div>
</div>
</div>
{/* All Dialogs are handled by this components */}
<DialogSection
{...this.props}
openLogin={this.state.showLogin}
openSignUp={this.state.showSignUp}
openForgotPassword={this.state.openForgotPassword}
openThemeChanger={this.state.showThemeChanger}
ThemeChangerComponents={components}
bodyStyle={bodyStyle}
actions={actions}
handleSignUp={this.handleSignUp}
customSettingsDone={customSettingsDone}
onRequestClose={()=>this.handleClose}
onRequestCloseTour={()=>this.handleCloseTour}
onSaveThemeSettings={()=>this.handleSaveTheme}
onLoginSignUp={()=>this.handleOpen}
onForgotPassword={()=>this.forgotPasswordChanged}
tour={!cookies.get('visited')}
/>
</div>)
: (
<div className='message-pane'>
<div className='message-section'>
<ul
className="message-list"
ref={(c) => { this.messageList = c; }}
style={this.messageBackgroundStyle}>
<Scrollbars
renderThumbHorizontal={this.renderThumb}
renderThumbVertical={this.renderThumb}
ref={(ref) => { this.scrollarea = ref; }}
autoHide
autoHideTimeout={1000}
autoHideDuration={200}>
{messageListItems}
</Scrollbars>
</ul>
<div className='compose' style={{backgroundColor:composerColor}}>
<MessageComposer
focus={false}
threadID={this.state.thread.id}
dream={dream}
textarea={textArea}
textcolor={textColor}
speechOutput={speechOutput}
speechOutputAlways={speechOutputAlways}
micColor={this.state.button} />
</div>
</div>
</div>
)}
<Snackbar
open={this.state.SnackbarOpenBackground}
message={<Translate text='Please enter a valid URL first'/>}
autoHideDuration={4000}
/>
<Snackbar
open={this.state.SnackbarOpen}
message={<Translate text='Theme Changed'/>}
action="undo"
autoHideDuration={4000}
onActionTouchTap={this.handleActionTouchTap}
onRequestClose={this.handleRequestClose}
/>
<Snackbar
autoHideDuration={4000}
open={this.state.snackopen}
message={<Translate text={this.state.snackMessage} />}
/>
<Snackbar
autoHideDuration={4000}
open={this.state.SnackbarOpenSearchResults && !this.state.snackopen}
message={<Translate text='No Results!' />}
/>
</div>
);
}
return <div className='message-section'></div>;
}
componentDidUpdate() {
switch (this.state.currTheme) {
case 'light':{
document.body.className = 'white-body';
break;
}
case 'dark':{
document.body.className = 'dark-body';
break;
}
default: {
// do nothing
}
}
if(this.state.search){
if (this.state.searchState.scrollIndex === -1
|| this.state.searchState.scrollIndex === null) {
this._scrollToBottom();
}
else {
let markedIDs = this.state.searchState.markedIDs;
let markedIndices = this.state.searchState.markedIndices;
let limit = this.state.searchState.scrollLimit;
let ul = this.messageList;
if (markedIDs && ul && limit > 0) {
let currentID = markedIndices[this.state.searchState.scrollIndex];
this.scrollarea.view.childNodes[currentID].scrollIntoView();
}
}
}
else{
this._scrollToBottom();
}
}
_scrollToBottom = () => {
let ul = this.scrollarea;
if (ul && !this.state.showScrollBottom) {
ul.scrollTop(ul.getScrollHeight());
}
}
forcedScrollToBottom = () => {
let ul = this.scrollarea;
if (ul) {
ul.scrollTop(ul.getScrollHeight());
}
}
_onClickPrev = () => {
let newIndex = this.state.searchState.scrollIndex + 1;
let newSearchCount = this.state.searchState.searchIndex + 1;
let indexLimit = this.state.searchState.scrollLimit;
let markedIDs = this.state.searchState.markedIDs;
let ul = this.messageList;
if (markedIDs && ul && newIndex < indexLimit) {
let currState = this.state.searchState;
currState.scrollIndex = newIndex;
currState.searchIndex = newSearchCount;
currState.scrollID = markedIDs[newIndex];
this.setState({
searchState: currState
});
}
}
_onClickRecent = () => {
let newIndex = this.state.searchState.scrollIndex - 1;
let newSearchCount = this.state.searchState.searchIndex - 1;
let markedIDs = this.state.searchState.markedIDs;
let ul = this.messageList;
if (markedIDs && ul && newIndex >= 0) {
let currState = this.state.searchState;
currState.scrollIndex = newIndex;
currState.searchIndex = newSearchCount;
currState.scrollID = markedIDs[newIndex];
this.setState({
searchState: currState
});
}
}
_onClickSearch = () => {
let searchState = this.state.searchState;
searchState.markedMsgs = this.state.messages;
this.setState({
search: true,
searchState: searchState,
});
}
_onClickExit = () => {
let searchState = this.state.searchState;
searchState.searchText = '';
searchState.searchIndex = 0;
searchState.scrollLimit = 0;
this.setState({
search: false,
searchState: searchState,
});
}
handleOptions = (event) => {
event.preventDefault();
let searchState = this.state.searchState;
searchState.open = true;
searchState.anchorEl = event.currentTarget;
this.setState({
searchState: searchState,
});
}
handleToggle = (event, isInputChecked) => {
let searchState = {
markedMsgs: this.state.messages,
markedIDs: [],
markedIndices: [],
scrollLimit: 0,
scrollIndex: -1,
scrollID: null,
caseSensitive: isInputChecked,
open: true,
searchText: ''
}
this.setState({
searchState: searchState
});
}
handleRequestClose = () => {
let searchState = this.state.searchState;
searchState.open = false;
this.setState({
searchState: searchState,
});
};
/**
* Event handler for 'change' events coming from the MessageStore
*/
_onChange() {
this.setState(getStateFromStores());
}
};
MessageSection.propTypes = {
location: PropTypes.object,
history: PropTypes.object
};
export default addUrlProps({ urlPropsQueryConfig })(MessageSection);
|
step7-flux/node_modules/react-router/modules/Lifecycle.js | jintoppy/react-training | import warning from './routerWarning'
import React from 'react'
import invariant from 'invariant'
const { object } = React.PropTypes
/**
* The Lifecycle mixin adds the routerWillLeave lifecycle method to a
* component that may be used to cancel a transition or prompt the user
* for confirmation.
*
* On standard transitions, routerWillLeave receives a single argument: the
* location we're transitioning to. To cancel the transition, return false.
* To prompt the user for confirmation, return a prompt message (string).
*
* During the beforeunload event (assuming you're using the useBeforeUnload
* history enhancer), routerWillLeave does not receive a location object
* because it isn't possible for us to know the location we're transitioning
* to. In this case routerWillLeave must return a prompt message to prevent
* the user from closing the window/tab.
*/
const Lifecycle = {
contextTypes: {
history: object.isRequired,
// Nested children receive the route as context, either
// set by the route component using the RouteContext mixin
// or by some other ancestor.
route: object
},
propTypes: {
// Route components receive the route object as a prop.
route: object
},
componentDidMount() {
warning(false, 'the `Lifecycle` mixin is deprecated, please use `context.router.setRouteLeaveHook(route, hook)`. http://tiny.cc/router-lifecyclemixin')
invariant(
this.routerWillLeave,
'The Lifecycle mixin requires you to define a routerWillLeave method'
)
const route = this.props.route || this.context.route
invariant(
route,
'The Lifecycle mixin must be used on either a) a <Route component> or ' +
'b) a descendant of a <Route component> that uses the RouteContext mixin'
)
this._unlistenBeforeLeavingRoute = this.context.history.listenBeforeLeavingRoute(
route,
this.routerWillLeave
)
},
componentWillUnmount() {
if (this._unlistenBeforeLeavingRoute)
this._unlistenBeforeLeavingRoute()
}
}
export default Lifecycle
|
app/javascript/mastodon/features/status/index.js | ikuradon/mastodon | import Immutable from 'immutable';
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { createSelector } from 'reselect';
import { fetchStatus } from '../../actions/statuses';
import MissingIndicator from '../../components/missing_indicator';
import DetailedStatus from './components/detailed_status';
import ActionBar from './components/action_bar';
import Column from '../ui/components/column';
import {
favourite,
unfavourite,
bookmark,
unbookmark,
reblog,
unreblog,
pin,
unpin,
} from '../../actions/interactions';
import {
replyCompose,
quoteCompose,
mentionCompose,
directCompose,
} from '../../actions/compose';
import {
muteStatus,
unmuteStatus,
deleteStatus,
hideStatus,
revealStatus,
hideQuote,
revealQuote,
} from '../../actions/statuses';
import {
unblockAccount,
unmuteAccount,
} from '../../actions/accounts';
import {
blockDomain,
unblockDomain,
} from '../../actions/domain_blocks';
import { initMuteModal } from '../../actions/mutes';
import { initBlockModal } from '../../actions/blocks';
import { initBoostModal } from '../../actions/boosts';
import { initReport } from '../../actions/reports';
import { makeGetStatus, makeGetPictureInPicture } from '../../selectors';
import ScrollContainer from 'mastodon/containers/scroll_container';
import ColumnBackButton from '../../components/column_back_button';
import ColumnHeader from '../../components/column_header';
import StatusContainer from '../../containers/status_container';
import { openModal } from '../../actions/modal';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { HotKeys } from 'react-hotkeys';
import { boostModal, deleteModal } from '../../initial_state';
import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../ui/util/fullscreen';
import { textForScreenReader, defaultMediaVisibility } from '../../components/status';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
redraftConfirm: { id: 'confirmations.redraft.confirm', defaultMessage: 'Delete & redraft' },
redraftMessage: { id: 'confirmations.redraft.message', defaultMessage: 'Are you sure you want to delete this status and re-draft it? Favourites and boosts will be lost, and replies to the original post will be orphaned.' },
revealAll: { id: 'status.show_more_all', defaultMessage: 'Show more for all' },
hideAll: { id: 'status.show_less_all', defaultMessage: 'Show less for all' },
detailedStatus: { id: 'status.detailed_status', defaultMessage: 'Detailed conversation view' },
replyConfirm: { id: 'confirmations.reply.confirm', defaultMessage: 'Reply' },
replyMessage: { id: 'confirmations.reply.message', defaultMessage: 'Replying now will overwrite the message you are currently composing. Are you sure you want to proceed?' },
quoteConfirm: { id: 'confirmations.quote.confirm', defaultMessage: 'Quote' },
quoteMessage: { id: 'confirmations.quote.message', defaultMessage: 'Quoting now will overwrite the message you are currently composing. Are you sure you want to proceed?' },
blockDomainConfirm: { id: 'confirmations.domain_block.confirm', defaultMessage: 'Hide entire domain' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const getPictureInPicture = makeGetPictureInPicture();
const getAncestorsIds = createSelector([
(_, { id }) => id,
state => state.getIn(['contexts', 'inReplyTos']),
], (statusId, inReplyTos) => {
let ancestorsIds = Immutable.List();
ancestorsIds = ancestorsIds.withMutations(mutable => {
let id = statusId;
while (id && !mutable.includes(id)) {
mutable.unshift(id);
id = inReplyTos.get(id);
}
});
return ancestorsIds;
});
const getDescendantsIds = createSelector([
(_, { id }) => id,
state => state.getIn(['contexts', 'replies']),
state => state.get('statuses'),
], (statusId, contextReplies, statuses) => {
let descendantsIds = [];
const ids = [statusId];
while (ids.length > 0) {
let id = ids.pop();
const replies = contextReplies.get(id);
if (statusId !== id) {
descendantsIds.push(id);
}
if (replies) {
replies.reverse().forEach(reply => {
if (!ids.includes(reply) && !descendantsIds.includes(reply) && statusId !== reply) ids.push(reply);
});
}
}
let insertAt = descendantsIds.findIndex((id) => statuses.get(id).get('in_reply_to_account_id') !== statuses.get(id).get('account'));
if (insertAt !== -1) {
descendantsIds.forEach((id, idx) => {
if (idx > insertAt && statuses.get(id).get('in_reply_to_account_id') === statuses.get(id).get('account')) {
descendantsIds.splice(idx, 1);
descendantsIds.splice(insertAt, 0, id);
insertAt += 1;
}
});
}
return Immutable.List(descendantsIds);
});
const mapStateToProps = (state, props) => {
const status = getStatus(state, { id: props.params.statusId });
let ancestorsIds = Immutable.List();
let descendantsIds = Immutable.List();
if (status) {
ancestorsIds = getAncestorsIds(state, { id: status.get('in_reply_to_id') });
descendantsIds = getDescendantsIds(state, { id: status.get('id') });
}
return {
status,
ancestorsIds,
descendantsIds,
askReplyConfirmation: state.getIn(['compose', 'text']).trim().length !== 0,
domain: state.getIn(['meta', 'domain']),
pictureInPicture: getPictureInPicture(state, { id: props.params.statusId }),
};
};
return mapStateToProps;
};
export default @injectIntl
@connect(makeMapStateToProps)
class Status extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
status: ImmutablePropTypes.map,
ancestorsIds: ImmutablePropTypes.list,
descendantsIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
askReplyConfirmation: PropTypes.bool,
multiColumn: PropTypes.bool,
domain: PropTypes.string.isRequired,
pictureInPicture: ImmutablePropTypes.contains({
inUse: PropTypes.bool,
available: PropTypes.bool,
}),
};
state = {
fullscreen: false,
showMedia: defaultMediaVisibility(this.props.status),
showQuoteMedia: defaultMediaVisibility(this.props.status ? this.props.status.get('quote', null) : null),
loadedStatusId: undefined,
};
componentWillMount () {
this.props.dispatch(fetchStatus(this.props.params.statusId));
}
componentDidMount () {
attachFullscreenListener(this.onFullScreenChange);
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this._scrolledIntoView = false;
this.props.dispatch(fetchStatus(nextProps.params.statusId));
}
if (nextProps.status && nextProps.status.get('id') !== this.state.loadedStatusId) {
this.setState({ showMedia: defaultMediaVisibility(nextProps.status), loadedStatusId: nextProps.status.get('id'),
showQuoteMedia: defaultMediaVisibility(nextProps.status.get('quote', null)) });
}
}
handleToggleMediaVisibility = () => {
this.setState({ showMedia: !this.state.showMedia });
}
handleToggleQuoteMediaVisibility = () => {
this.setState({ showQuoteMedia: !this.state.showQuoteMedia });
}
handleFavouriteClick = (status) => {
if (status.get('favourited')) {
this.props.dispatch(unfavourite(status));
} else {
this.props.dispatch(favourite(status));
}
}
handlePin = (status) => {
if (status.get('pinned')) {
this.props.dispatch(unpin(status));
} else {
this.props.dispatch(pin(status));
}
}
handleReplyClick = (status) => {
let { askReplyConfirmation, dispatch, intl } = this.props;
if (askReplyConfirmation) {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.replyMessage),
confirm: intl.formatMessage(messages.replyConfirm),
onConfirm: () => dispatch(replyCompose(status, this.context.router.history)),
}));
} else {
dispatch(replyCompose(status, this.context.router.history));
}
}
handleModalReblog = (status, privacy) => {
this.props.dispatch(reblog(status, privacy));
}
handleReblogClick = (status, e) => {
if (status.get('reblogged')) {
this.props.dispatch(unreblog(status));
} else {
if ((e && e.shiftKey) || !boostModal) {
this.handleModalReblog(status);
} else {
this.props.dispatch(initBoostModal({ status, onReblog: this.handleModalReblog }));
}
}
}
handleBookmarkClick = (status) => {
if (status.get('bookmarked')) {
this.props.dispatch(unbookmark(status));
} else {
this.props.dispatch(bookmark(status));
}
}
handleQuoteClick = (status) => {
let { askReplyConfirmation, dispatch, intl } = this.props;
if (askReplyConfirmation) {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.quoteMessage),
confirm: intl.formatMessage(messages.quoteConfirm),
onConfirm: () => dispatch(quoteCompose(status, this.context.router.history)),
}));
} else {
dispatch(quoteCompose(status, this.context.router.history));
}
}
handleDeleteClick = (status, history, withRedraft = false) => {
const { dispatch, intl } = this.props;
if (!deleteModal) {
dispatch(deleteStatus(status.get('id'), history, withRedraft));
} else {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage),
confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'), history, withRedraft)),
}));
}
}
handleDirectClick = (account, router) => {
this.props.dispatch(directCompose(account, router));
}
handleMentionClick = (account, router) => {
this.props.dispatch(mentionCompose(account, router));
}
handleOpenMedia = (media, index) => {
this.props.dispatch(openModal('MEDIA', { statusId: this.props.status.get('id'), media, index }));
}
handleOpenVideo = (media, options) => {
this.props.dispatch(openModal('VIDEO', { statusId: this.props.status.get('id'), media, options }));
}
handleHotkeyOpenMedia = e => {
const { status } = this.props;
e.preventDefault();
if (status.get('media_attachments').size > 0) {
if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
this.handleOpenVideo(status.getIn(['media_attachments', 0]), { startTime: 0 });
} else {
this.handleOpenMedia(status.get('media_attachments'), 0);
}
}
}
handleMuteClick = (account) => {
this.props.dispatch(initMuteModal(account));
}
handleConversationMuteClick = (status) => {
if (status.get('muted')) {
this.props.dispatch(unmuteStatus(status.get('id')));
} else {
this.props.dispatch(muteStatus(status.get('id')));
}
}
handleToggleHidden = (status) => {
if (status.get('hidden')) {
this.props.dispatch(revealStatus(status.get('id')));
} else {
this.props.dispatch(hideStatus(status.get('id')));
}
}
handleQuoteToggleHidden = (status) => {
if (status.get('quote_hidden')) {
this.props.dispatch(revealQuote(status.get('id')));
} else {
this.props.dispatch(hideQuote(status.get('id')));
}
}
handleToggleAll = () => {
const { status, ancestorsIds, descendantsIds } = this.props;
const statusIds = [status.get('id')].concat(ancestorsIds.toJS(), descendantsIds.toJS());
if (status.get('hidden')) {
this.props.dispatch(revealStatus(statusIds));
} else {
this.props.dispatch(hideStatus(statusIds));
}
}
handleBlockClick = (status) => {
const { dispatch } = this.props;
const account = status.get('account');
dispatch(initBlockModal(account));
}
handleReport = (status) => {
this.props.dispatch(initReport(status.get('account'), status));
}
handleEmbed = (status) => {
this.props.dispatch(openModal('EMBED', { url: status.get('url') }));
}
handleUnmuteClick = account => {
this.props.dispatch(unmuteAccount(account.get('id')));
}
handleUnblockClick = account => {
this.props.dispatch(unblockAccount(account.get('id')));
}
handleBlockDomainClick = domain => {
this.props.dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.domain_block.message' defaultMessage='Are you really, really sure you want to block the entire {domain}? In most cases a few targeted blocks or mutes are sufficient and preferable. You will not see content from that domain in any public timelines or your notifications. Your followers from that domain will be removed.' values={{ domain: <strong>{domain}</strong> }} />,
confirm: this.props.intl.formatMessage(messages.blockDomainConfirm),
onConfirm: () => this.props.dispatch(blockDomain(domain)),
}));
}
handleUnblockDomainClick = domain => {
this.props.dispatch(unblockDomain(domain));
}
handleHotkeyMoveUp = () => {
this.handleMoveUp(this.props.status.get('id'));
}
handleHotkeyMoveDown = () => {
this.handleMoveDown(this.props.status.get('id'));
}
handleHotkeyReply = e => {
e.preventDefault();
this.handleReplyClick(this.props.status);
}
handleHotkeyFavourite = () => {
this.handleFavouriteClick(this.props.status);
}
handleHotkeyBoost = () => {
this.handleReblogClick(this.props.status);
}
handleHotkeyMention = e => {
e.preventDefault();
this.handleMentionClick(this.props.status.get('account'));
}
handleHotkeyOpenProfile = () => {
this.context.router.history.push(`/@${this.props.status.getIn(['account', 'acct'])}`);
}
handleHotkeyToggleHidden = () => {
this.handleToggleHidden(this.props.status);
}
handleHotkeyToggleSensitive = () => {
this.handleToggleMediaVisibility();
}
handleMoveUp = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size - 1, true);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index, true);
} else {
this._selectChild(index - 1, true);
}
}
}
handleMoveDown = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size + 1, false);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index + 2, false);
} else {
this._selectChild(index + 1, false);
}
}
}
_selectChild (index, align_top) {
const container = this.node;
const element = container.querySelectorAll('.focusable')[index];
if (element) {
if (align_top && container.scrollTop > element.offsetTop) {
element.scrollIntoView(true);
} else if (!align_top && container.scrollTop + container.clientHeight < element.offsetTop + element.offsetHeight) {
element.scrollIntoView(false);
}
element.focus();
}
}
renderChildren (list) {
return list.map(id => (
<StatusContainer
key={id}
id={id}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
contextType='thread'
/>
));
}
setRef = c => {
this.node = c;
}
componentDidUpdate () {
if (this._scrolledIntoView) {
return;
}
const { status, ancestorsIds } = this.props;
if (status && ancestorsIds && ancestorsIds.size > 0) {
const element = this.node.querySelectorAll('.focusable')[ancestorsIds.size - 1];
window.requestAnimationFrame(() => {
element.scrollIntoView(true);
});
this._scrolledIntoView = true;
}
}
componentWillUnmount () {
detachFullscreenListener(this.onFullScreenChange);
}
onFullScreenChange = () => {
this.setState({ fullscreen: isFullscreen() });
}
render () {
let ancestors, descendants;
const { status, ancestorsIds, descendantsIds, intl, domain, multiColumn, pictureInPicture } = this.props;
const { fullscreen } = this.state;
if (status === null) {
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<MissingIndicator />
</Column>
);
}
if (ancestorsIds && ancestorsIds.size > 0) {
ancestors = <div>{this.renderChildren(ancestorsIds)}</div>;
}
if (descendantsIds && descendantsIds.size > 0) {
descendants = <div>{this.renderChildren(descendantsIds)}</div>;
}
const handlers = {
moveUp: this.handleHotkeyMoveUp,
moveDown: this.handleHotkeyMoveDown,
reply: this.handleHotkeyReply,
favourite: this.handleHotkeyFavourite,
boost: this.handleHotkeyBoost,
mention: this.handleHotkeyMention,
openProfile: this.handleHotkeyOpenProfile,
toggleHidden: this.handleHotkeyToggleHidden,
toggleSensitive: this.handleHotkeyToggleSensitive,
openMedia: this.handleHotkeyOpenMedia,
};
return (
<Column bindToDocument={!multiColumn} label={intl.formatMessage(messages.detailedStatus)}>
<ColumnHeader
showBackButton
multiColumn={multiColumn}
extraButton={(
<button className='column-header__button' title={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} aria-label={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} onClick={this.handleToggleAll} aria-pressed={status.get('hidden') ? 'false' : 'true'}><Icon id={status.get('hidden') ? 'eye-slash' : 'eye'} /></button>
)}
/>
<ScrollContainer scrollKey='thread'>
<div className={classNames('scrollable', { fullscreen })} ref={this.setRef}>
{ancestors}
<HotKeys handlers={handlers}>
<div className={classNames('focusable', 'detailed-status__wrapper')} tabIndex='0' aria-label={textForScreenReader(intl, status, false)}>
<DetailedStatus
key={`details-${status.get('id')}`}
status={status}
onOpenVideo={this.handleOpenVideo}
onOpenMedia={this.handleOpenMedia}
onToggleHidden={this.handleToggleHidden}
domain={domain}
showMedia={this.state.showMedia}
onToggleMediaVisibility={this.handleToggleMediaVisibility}
pictureInPicture={pictureInPicture}
onQuoteToggleHidden={this.handleQuoteToggleHidden}
showQuoteMedia={this.state.showQuoteMedia}
onToggleQuoteMediaVisibility={this.handleToggleQuoteMediaVisibility}
/>
<ActionBar
key={`action-bar-${status.get('id')}`}
status={status}
onReply={this.handleReplyClick}
onFavourite={this.handleFavouriteClick}
onReblog={this.handleReblogClick}
onBookmark={this.handleBookmarkClick}
onQuote={this.handleQuoteClick}
onDelete={this.handleDeleteClick}
onDirect={this.handleDirectClick}
onMention={this.handleMentionClick}
onMute={this.handleMuteClick}
onUnmute={this.handleUnmuteClick}
onMuteConversation={this.handleConversationMuteClick}
onBlock={this.handleBlockClick}
onUnblock={this.handleUnblockClick}
onBlockDomain={this.handleBlockDomainClick}
onUnblockDomain={this.handleUnblockDomainClick}
onReport={this.handleReport}
onPin={this.handlePin}
onEmbed={this.handleEmbed}
/>
</div>
</HotKeys>
{descendants}
</div>
</ScrollContainer>
</Column>
);
}
}
|
stories/components/Accordion.js | g-script/react-be-blaze | import { storiesOf } from '@kadira/storybook'
import React from 'react'
import { Accordion, AccordionItem } from '../../src'
storiesOf('components/Accordion.js', module)
.add('Accordion & AccordionItem', () => (
<div className='wrapper c-text'>
<Accordion>
<AccordionItem id='accordion-1' label='Item 1'>
Pane 1
</AccordionItem>
<AccordionItem id='accordion-2' label='Item 2'>
Pane 2
</AccordionItem>
</Accordion>
</div>
))
|
app/javascript/mastodon/features/notifications/components/clear_column_button.js | riku6460/chikuwagoddon | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
export default class ClearColumnButton extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func.isRequired,
};
render () {
return (
<button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><i className='fa fa-eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button>
);
}
}
|
examples/crna-kitchen-sink/storybook/stories/Button/index.android.js | rhalff/storybook | import React from 'react';
import PropTypes from 'prop-types';
import { TouchableNativeFeedback } from 'react-native';
export default function Button(props) {
return (
<TouchableNativeFeedback onPress={props.onPress}>{props.children}</TouchableNativeFeedback>
);
}
Button.defaultProps = {
children: null,
onPress: () => {},
};
Button.propTypes = {
children: PropTypes.node,
onPress: PropTypes.func,
};
|
app/javascript/mastodon/components/loading_indicator.js | honpya/taketodon | import React from 'react';
import { FormattedMessage } from 'react-intl';
const LoadingIndicator = () => (
<div className='loading-indicator'>
<div className='loading-indicator__figure' />
<FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' />
</div>
);
export default LoadingIndicator;
|
app/components/HeaderButton.js | jastkand/vk-notifications | import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import styles from './HeaderButton.css'
export default (props) => {
if (props.hidden) {
return null
}
return (
<a onClick={ props.onClick } className={ styles.button } title={ props.title }>
<FontAwesomeIcon icon={ props.icon } size='lg' />
</a>
)
}
|
src/components/Share/index.js | quran/quran.com-frontend | import React from 'react';
import { ShareButtons, generateShareIcon } from 'react-share';
import * as customPropTypes from 'customPropTypes';
const styles = require('./style.scss');
const { FacebookShareButton, TwitterShareButton } = ShareButtons;
const FacebookIcon = generateShareIcon('facebook');
const TwitterIcon = generateShareIcon('twitter');
const Share = ({ chapter, verse }) => {
// Fallback to Surah Id
let path;
if (verse) {
const translations = (verse.translations || [])
.map(translation => translation.resourceId)
.join(',');
path = `${verse.chapterId}/${verse.verseNumber}?translations=${translations}`;
} else {
path = chapter.chapterNumber;
}
const shareUrl = `https://quran.com/${path}`;
const title = verse
? `Surah ${chapter.nameSimple} [${verse.verseKey}]`
: `Surah ${chapter.nameSimple}`;
const iconProps = verse ? { iconBgStyle: { fill: '#d1d0d0' } } : {};
return (
<div className={`${styles.shareContainer}`}>
<FacebookShareButton
url={shareUrl}
title={title}
windowWidth={670}
windowHeight={540}
className={`${styles.iconContainer}`}
>
<FacebookIcon size={24} round {...iconProps} />
</FacebookShareButton>
<TwitterShareButton
url={shareUrl}
title={title}
className={`${styles.iconContainer}`}
>
<TwitterIcon size={24} round {...iconProps} />
</TwitterShareButton>
</div>
);
};
Share.propTypes = {
chapter: customPropTypes.surahType.isRequired,
verse: customPropTypes.verseType
};
export default Share;
|
packages/bonde-admin-canary/src/scenes/Logged/scenes/Tags/CreateUserTagsForm/CreateUserTagsForm.js | ourcities/rebu-client | import React from 'react'
import { Button, Flexbox2 as Flexbox } from 'bonde-styleguide'
import { Field, FormGraphQL } from 'components/Form'
import UserTagsField from './UserTagsField'
import CreateUserTags from './createUserTags.graphql'
import updateCurrentUserTags from './updateCurrentUserTags'
const CreateUserTagsForm = ({ t, user }) => {
return (
<FormGraphQL
initialValues={{ tags: user.tags.join(';') }}
mutation={CreateUserTags}
update={updateCurrentUserTags}
onSubmit={({ tags }, mutation) => {
const jsonTags = JSON.stringify({
tags: tags.split(';')
})
return mutation({ variables: { data: jsonTags } })
}}
>
<Field name='tags' component={UserTagsField} />
<Flexbox horizontal end margin={{ top: 55 }}>
<Button
type='submit'
title={t('buttons.submit')}
>
{t('buttons.submit')}
</Button>
</Flexbox>
</FormGraphQL>
)
}
export default CreateUserTagsForm
|
packages/react-error-overlay/src/components/Footer.js | appier/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
/* @flow */
import React from 'react';
import { darkGray } from '../styles';
const footerStyle = {
fontFamily: 'sans-serif',
color: darkGray,
marginTop: '0.5rem',
flex: '0 0 auto',
};
type FooterPropsType = {|
line1: string,
line2?: string,
|};
function Footer(props: FooterPropsType) {
return (
<div style={footerStyle}>
{props.line1}
<br />
{props.line2}
</div>
);
}
export default Footer;
|
app/containers/NewStreamPage.js | lhall-adexos/LogSwarm | // @flow
import React, { Component } from 'react';
import NewStream from '../components/NewStream';
export default class NewStreamPage extends Component {
render() {
return (
<NewStream />
);
}
}
|
src/routes/dashboard/components/weather.js | liuweiGL/eastcoal_mgr_react | import React from 'react'
import PropTypes from 'prop-types'
import styles from './weather.less'
function Weather ({ city, icon, dateTime, temperature, name }) {
return (<div className={styles.weather}>
<div className={styles.left}>
<div className={styles.icon} style={{
backgroundImage: `url(${icon})`,
}} />
<p>{name}</p>
</div>
<div className={styles.right}>
<h1 className={styles.temperature}>{`${temperature}°`}</h1>
<p className={styles.description}>{city},{dateTime}</p>
</div>
</div>)
}
Weather.propTypes = {
city: PropTypes.string,
icon: PropTypes.string,
dateTime: PropTypes.string,
temperature: PropTypes.string,
name: PropTypes.string,
}
export default Weather
|
src/components/NavigationConfirmationModal/index.js | mareklibra/userportal | import React from 'react'
import PropTypes from 'prop-types'
import { Modal, Button, Alert } from 'patternfly-react'
import { msg } from '_/intl'
const NavigationConfirmationModal = ({ show, onYes, onNo }) => {
const idPrefix = 'close-dialog-confim'
return (
<Modal show={show}>
<Modal.Header>
<Modal.Title id={`${idPrefix}-title`}>{msg.unsavedChangesTitle()}</Modal.Title>
</Modal.Header>
<Modal.Body>
<Alert type='warning' id={`${idPrefix}-body-text`}>{msg.unsavedChangesConfirmMessage()}</Alert>
</Modal.Body>
<Modal.Footer>
<Button id={`${idPrefix}-button-no`} onClick={onNo} bsStyle='default'>No</Button>
<Button id={`${idPrefix}-button-yes`} onClick={onYes} bsStyle='primary'>Yes</Button>
</Modal.Footer>
</Modal>
)
}
NavigationConfirmationModal.propTypes = {
show: PropTypes.bool,
onYes: PropTypes.func.isRequired,
onNo: PropTypes.func.isRequired,
}
NavigationConfirmationModal.defaultProps = {
show: false,
}
export default NavigationConfirmationModal
|
src/svg-icons/social/person-add.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPersonAdd = (props) => (
<SvgIcon {...props}>
<path d="M15 12c2.21 0 4-1.79 4-4s-1.79-4-4-4-4 1.79-4 4 1.79 4 4 4zm-9-2V7H4v3H1v2h3v3h2v-3h3v-2H6zm9 4c-2.67 0-8 1.34-8 4v2h16v-2c0-2.66-5.33-4-8-4z"/>
</SvgIcon>
);
SocialPersonAdd = pure(SocialPersonAdd);
SocialPersonAdd.displayName = 'SocialPersonAdd';
SocialPersonAdd.muiName = 'SvgIcon';
export default SocialPersonAdd;
|
src/parser/priest/shadow/modules/items/HeartOfTheVoid.js | FaideWW/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import ITEMS from 'common/ITEMS';
import Analyzer from 'parser/core/Analyzer';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import ItemDamageDone from 'interface/others/ItemDamageDone';
import ItemHealingDone from 'interface/others/ItemHealingDone';
const HEART_OF_THE_VOID_DAMAGE_INCREASE = 0.75;
class HeartOfTheVoid extends Analyzer {
bonusDamage = 0;
bonusHealing = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasChest(ITEMS.HEART_OF_THE_VOID.id);
}
on_byPlayer_damage(event) {
const spellID = event.ability.guid;
if (spellID === SPELLS.VOID_ERUPTION_DAMAGE_1.id || spellID === SPELLS.VOID_ERUPTION_DAMAGE_2.id) {
this.bonusDamage += calculateEffectiveDamage(event, HEART_OF_THE_VOID_DAMAGE_INCREASE);
}
}
on_byPlayer_heal(event) {
const spellID = event.ability.guid;
if (spellID === SPELLS.HEART_OF_THE_VOID_HEAL.id) {
this.bonusHealing += event.amount;
}
}
item() {
return {
item: ITEMS.HEART_OF_THE_VOID,
result: (
<>
<ItemDamageDone amount={this.bonusDamage} /><br />
<ItemHealingDone amount={this.bonusHealing} />
</>
),
};
}
}
export default HeartOfTheVoid;
|
node_modules/react-icons/io/ios-personadd-outline.js | bairrada97/festival |
import React from 'react'
import Icon from 'react-icon-base'
const IoIosPersonaddOutline = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m32.5 12v1h-2v2h-1v-2h-2v-1h2v-2h1v2h2z m-16.7 3.8z m12.6 12.6c1 0.4 4.1 1.6 4.1 4.1h-25c0-2.5 3.1-3.7 4.1-4.1s2.5-0.4 3.4-0.7c0.5-0.1 1.3-0.4 1.6-0.7s0-3.2 0-3.2-0.4-0.8-0.7-1.4-0.5-2.5-0.5-2.5-0.6 0-0.7-0.9c-0.2-1-0.5-1.3-0.5-2.1 0-0.7 0.4-0.8 0.4-0.8s-0.3-1-0.4-3.3c-0.1-2.6 2-5.3 5.8-5.3s5.9 2.7 5.8 5.3c-0.1 2.3-0.4 3.3-0.4 3.3s0.4 0.1 0.4 0.8c0 0.8-0.3 1.1-0.5 2.2-0.1 0.9-0.7 0.9-0.7 0.9s-0.3 1.8-0.5 2.4-0.7 1.4-0.7 1.4-0.2 2.9 0 3.2 1.1 0.6 1.6 0.7c0.9 0.3 2.3 0.3 3.4 0.7z m-8.4 2.9h10.7c-0.2-0.3-0.3-0.5-0.6-0.7-0.6-0.4-1.3-0.7-2.1-1-0.6-0.1-1.4-0.3-2.1-0.4-0.4-0.1-0.7-0.1-1.1-0.2-0.3-0.1-1.7-0.4-2.3-1.2-0.3-0.4-0.5-0.9-0.5-2.5 0-0.8 0.1-1.6 0.1-1.6v-0.3l0.2-0.3c0-0.1 0.4-0.7 0.6-1.2 0.1-0.3 0.4-1.4 0.5-2.1 0 0 0 0 0-0.4s0.7-0.3 0.7-0.6 0.3-0.5 0.4-1.4-0.4-0.9-0.4-1.3c0-0.3 0.1-0.4 0.1-0.4 0-0.1 0.3-1.1 0.3-3 0-1-0.4-2-1.1-2.7-0.8-0.9-1.9-1.3-3.4-1.3-1.4 0-2.7 0.4-3.5 1.3-0.7 0.7-1 1.7-1 2.7 0 1.9 0.3 2.9 0.3 3s0.1 0.2 0 0.5c-0.1 0.4-0.5 0.4-0.3 1.2s0.3 1.1 0.4 1.4 0.6 0.3 0.7 0.6 0 0.4 0 0.4c0.1 0.7 0.4 1.8 0.5 2.1 0.2 0.5 0.5 1.1 0.6 1.2l0.2 0.3v0.3s0.1 0.8 0.1 1.6c0 1.6-0.2 2.1-0.5 2.5-0.6 0.8-2 1.1-2.3 1.2-0.4 0.1-0.7 0.1-1.2 0.2-0.7 0.1-1.4 0.3-2 0.4-0.8 0.3-1.5 0.6-2.1 1-0.3 0.2-0.5 0.4-0.6 0.6h10.7z"/></g>
</Icon>
)
export default IoIosPersonaddOutline
|
src/containers/Playground/Board/index.js | mmazzarolo/tap-the-number | /* @flow */
/**
* This components just renders the tiles in their correct positions.
*/
import React, { Component } from 'react';
import { View } from 'react-native-animatable';
import type { Tile } from 'src/types';
import { observer } from 'mobx-react/native';
import BoardTile from 'src/containers/Playground/BoardTile';
import styles from './index.style';
type Props = {
tiles: Array<Tile>,
onTilePress: (tileId: any) => any,
isEnabled: boolean,
};
@observer
export default class TilesCarousel extends Component<void, Props, void> {
_tileRefs = [];
animateFailure = () => {
this._tileRefs.forEach(ref => {
if (ref) {
ref.animateFailure();
}
});
};
render() {
this._tileRefs = [];
return (
<View style={styles.container}>
{this.props.tiles.map((tile, index) => (
<BoardTile
ref={ref => this._tileRefs[index] = ref}
key={`board_tile_${tile.id}`}
left={tile.x}
bottom={tile.y}
backgroundColor={tile.color}
text={tile.number}
onTilePress={() => this.props.onTilePress(tile.id)}
isEnabled={this.props.isEnabled}
isVisible={tile.isVisible}
/>
))}
</View>
);
}
}
|
app/app.js | anneback/react-quiz | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { ThemeProvider } from 'nordnet-ui-kit';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import FontFaceObserver from 'fontfaceobserver';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-webpack-loader-syntax */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess'; // eslint-disable-line import/extensions
/* eslint-enable import/no-webpack-loader-syntax */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import routes
import createRoutes from './routes';
// Observe loading of Open Sans (to remove open sans, remove the <link> tag in
// the index.html file and this observer)
const openSansObserver = new FontFaceObserver('Open Sans', {});
// When Open Sans is loaded, add a font-family using Open Sans to the body
openSansObserver.load().then(() => {
document.body.classList.add('fontLoaded');
}, () => {
document.body.classList.remove('fontLoaded');
});
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<ThemeProvider>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</ThemeProvider>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
src/plugins/NetworkPlugin/components/Table.js | whinc/xConsole | import React from 'react'
import PropTypes from 'prop-types'
import './Table.css'
export default class Table extends React.Component {
static propTyps = {
entryies: PropTypes.arrayOf(PropTypes.any),
// 点击条目的回调函数
// enrty => void
onClickEntry: PropTypes.func
}
static defaultProps = {
entries: [],
onClickEntry: () => {}
}
parseUrl (url) {
if (typeof url !== 'string') return String(url)
const lastSlashIndex = url.lastIndexOf('/')
const name = url.substr(lastSlashIndex + 1)
return {name}
}
render () {
const {entries, onClickEntry} = this.props
return (
<div className='Table'>
<div className='Table__header'>
<span className='Table__item Table__item--grow'>
Name{entries.length > 0 ? `(${entries.length})` : ''}
</span>
<span className='Table__item'>Method</span>
<span className='Table__item'>Status</span>
</div>
<div className='Table__content'>
{entries.map(entry => {
const { name } = this.parseUrl(entry.url)
return (
<div className='Table__row' key={entry.id} onClick={() => onClickEntry(entry)}>
<span className='Table__item Table__item--grow'>{name}</span>
<span className='Table__item'>{entry.method}</span>
<span className='Table__item'>{entry.status !== undefined ? entry.status : '--'}</span>
</div>
)
})}
</div>
</div >
)
}
}
|
examples/counter/src/App.js | Annevo/redux-eventually | /* eslint immutable/no-this: 0 */
/* eslint immutable/no-mutation: 0 */
/* eslint no-console: 0 */
import React from 'react';
import { createCounterMergeAction } from 'redux-eventually';
import Node from './Containers/Node';
import './App.css';
const syncAction = createCounterMergeAction('DEMO');
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
// online keeps a record of all nodes
online: [],
};
this.sync = this.sync.bind(this);
this.registerNode = this.registerNode.bind(this);
this.toggleOnline = this.toggleOnline.bind(this);
}
// sync propagates dispatches to all registered nodes that are online
sync(nodeId, pnstate) {
this.state.online.forEach((id) => {
if (id !== nodeId) {
this.state[id](syncAction(pnstate));
}
});
}
// registerNode registers the node for further dispatch propagation
registerNode(nodeId, dispatch) {
console.log(`register node ${nodeId}`);
const { state: { online } } = this;
online.push(nodeId);
this.setState(Object.assign({}, { [nodeId]: dispatch, online }));
}
// toggleOnline adds nodeId to the array of currently online nodes
toggleOnline(nodeId) {
if (this.state.online.indexOf(nodeId) >= 0) {
console.log(`Node ${nodeId} has come online`);
this.setState({
online: this.state.online.filter(id => nodeId !== id),
});
} else {
console.log(`Node ${nodeId} has gone offline`);
this.setState({
online: this.state.online.concat(nodeId),
});
}
}
render() {
return (
<div
className="App"
style={{ display: 'flex', width: '100%', justifyContent: 'space-around' }}
>
<Node
name="Vancouver"
onSync={this.sync}
register={this.registerNode}
toggleOnline={this.toggleOnline}
/>
<Node
name="Stockholm"
onSync={this.sync}
register={this.registerNode}
toggleOnline={this.toggleOnline}
/>
<Node
name="Tokyo"
onSync={this.sync}
register={this.registerNode}
toggleOnline={this.toggleOnline}
/>
<Node
name="Oslo"
onSync={this.sync}
register={this.registerNode}
toggleOnline={this.toggleOnline}
/>
</div>
);
}
}
export default App;
|
lib/Main.js | applegrain/enzyme-playground | import React from 'react';
import Buttons from './Buttons';
export default React.createClass({
getInitialState() {
return { counter: 0 }
},
handleClick(value = 1) {
this.setState({ counter: this.state.counter + value })
},
render() {
return (
<div className='hello-world'>
<h1>Enzyme</h1>
<Buttons onButtonClick={this.handleClick} />
</div>
);
},
});
|
src/components/app.js | mesqfel/react-blog | import React, { Component } from 'react';
import Navbar from './navbar';
import Footer from './footer';
export default class App extends Component {
render() {
return (
<div>
<Navbar />
{this.props.children}
<Footer />
</div>
);
}
}
|
themes/genius/Genius 2.3.1 Bootstrap 4/React_Starter/src/components/Footer/Footer.js | davidchristie/kaenga-housing-calculator | import React, { Component } from 'react';
class Footer extends Component {
render() {
return (
<footer className="app-footer">
<a href="https://genesisui.com">Genius</a> © 2017 creativeLabs.
<span className="float-right">Powered by <a href="https://genesisui.com">GenesisUI</a></span>
</footer>
)
}
}
export default Footer;
|
src/svg-icons/image/filter.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilter = (props) => (
<SvgIcon {...props}>
<path d="M15.96 10.29l-2.75 3.54-1.96-2.36L8.5 15h11l-3.54-4.71zM3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/>
</SvgIcon>
);
ImageFilter = pure(ImageFilter);
ImageFilter.displayName = 'ImageFilter';
ImageFilter.muiName = 'SvgIcon';
export default ImageFilter;
|
src/components/DismissKeyboardView.js | madtaras/reds | import React from 'react';
import {
View,
TouchableWithoutFeedback,
Keyboard,
} from 'react-native';
const DismissKeyboardHOC = Comp => ({ children, ...props }) => (
<TouchableWithoutFeedback onPress={Keyboard.dismiss}>
<Comp {...props}>
{children}
</Comp>
</TouchableWithoutFeedback>
);
const DismissKeyboardView = DismissKeyboardHOC(View);
export default DismissKeyboardView;
|
markbin/client/components/bins/bins_share.js | tpechacek/learn-react-native | import React, { Component } from 'react';
class BinsShare extends Component {
onShareClick () {
const email = this.refs.email.value;
Meteor.call('bins.share', this.props.bin, email);
}
renderShareList() {
return this.props.bin.sharedWith.map(email => {
return (<button
key={email}
className="btn btn-default">
{email}
</button>
)
});
}
render() {
return (
<footer className="bins-share">
<div className="input-group">
<input ref="email" className="form-control" />
<div className="input-group-btn">
<button
onClick={this.onShareClick.bind(this)}
className="btn btn-default">
Share Bin
</button>
</div>
</div>
<div>
Shared With:
</div>
<div className="btn-group">
{this.renderShareList()}
</div>
</footer>
);
}
}
export default BinsShare;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.