path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
core/src/plugins/gui.ajax/res/js/ui/HOCs/animations/make-staggered.js | ChuckDaniels87/pydio-core | /**
* Copyright (c) 2013-present, Facebook, Inc. All rights reserved.
*
* This file provided by Facebook is for non-commercial testing and evaluation
* purposes only. Facebook reserves all rights not expressly granted.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import shallowCompare from 'react/lib/shallowCompare';
import { StaggeredMotion } from 'react-motion';
import stripStyle from 'react-motion/lib/stripStyle';
import {springify, buildTransform} from './utils';
let counter=0
const DEFAULT_ANIMATION={stiffness: 200, damping: 22, precision: 0.1}
const makeStaggered = (originStyles, targetStyles, animation) => {
return (Target) => {
class StaggeredGroup extends React.PureComponent {
constructor(props) {
super(props)
this.state = {
styles: this.buildStyles(props)
}
}
componentWillReceiveProps(nextProps) {
this.setState({
styles: this.buildStyles(nextProps)
});
}
buildStyles(props) {
return React.Children
.toArray(props.children)
.filter(child => child) // Removing null values
.map(child => {
return originStyles
});
}
getStyles(prevStyles) {
const endValue = React.Children
.toArray(this.props.children)
.filter(child => child) // Removing null values
.map((_, i) => {
return !this.props.ready
? originStyles
: i === 0
? springify(targetStyles, animation || DEFAULT_ANIMATION)
: prevStyles[i - 1]
? springify(prevStyles[i - 1], animation || DEFAULT_ANIMATION)
: originStyles
})
return endValue;
}
render() {
// Making sure we fliter out properties
const {ready, ...props} = this.props
return (
<StaggeredMotion
defaultStyles={this.state.styles}
styles={(styles) => this.getStyles(styles)}
>
{styles =>
<Target {...props}>
{React.Children.toArray(props.children).filter(child => child).map((Child, i) => {
let style = styles[i] || {}
const itemProps = Child.props
const transform = buildTransform(style, {
length: 'px', angle: 'deg'
});
return React.cloneElement(Child, {style: {
...itemProps.style,
...style,
transform,
transition: "none"
}})
})}
</Target>
}
</StaggeredMotion>
);
}
}
StaggeredGroup.propTypes = {
ready: React.PropTypes.bool.isRequired
}
StaggeredGroup.defaultProps = {
ready: true
}
return StaggeredGroup
}
}
export default makeStaggered;
|
src/parser/druid/balance/CONFIG.js | sMteX/WoWAnalyzer | import React from 'react';
import { Gebuz } from 'CONTRIBUTORS';
import retryingPromise from 'common/retryingPromise';
import SPECS from 'game/SPECS';
import CHANGELOG from './CHANGELOG';
export default {
// The people that have contributed to this spec recently. People don't have to sign up to be long-time maintainers to be included in this list. If someone built a large part of the spec or contributed something recently to that spec, they can be added to the contributors list. If someone goes MIA, they may be removed after major changes or during a new expansion.
contributors: [Gebuz],
// The WoW client patch this spec was last updated to be fully compatible with.
patchCompatibility: '8.0.1',
// If set to false`, the spec will show up as unsupported.
isSupported: true,
// Explain the status of this spec's analysis here. Try to mention how complete it is, and perhaps show links to places users can learn more.
// If this spec's analysis does not show a complete picture please mention this in the `<Warning>` component.
description: (
<>
Hello Moonkins! This tool is intended to show major statistics and potential issues in your rotation. Please mind that it can always be improved upon, so if you see anything that you disagree with or think is missing please let us know!<br /><br />
As a rule of thumb: Never overcap Astral Power, don't overcap empowerments and keep your dots up on the target(s) at all times. Remember to pool Astral Power prior to movement.<br /><br />
If you want to learn more about how to play Moonkin, visit <a href="https://discordapp.com/invite/0dWu0WkuetF87H9H" target="_blank" rel="noopener noreferrer">DreamGrove, the Druid's Discord</a> or <a href="https://dreamgrove.gg/" target="_blank" rel="noopener noreferrer">DreamGrove.gg</a>.
</>
),
// A recent example report to see interesting parts of the spec. Will be shown on the homepage.
exampleReport: '/report/TGzmk4bXDZJndpj7/6-Heroic+Opulence+-+Kill+(8:12)/2-Chushpajz',
// Don't change anything below this line;
// The current spec identifier. This is the only place (in code) that specifies which spec this parser is about.
spec: SPECS.BALANCE_DRUID,
// The contents of your changelog.
changelog: CHANGELOG,
// The CombatLogParser class for your spec.
parser: () => retryingPromise(() => import('./CombatLogParser' /* webpackChunkName: "BalanceDruid" */).then(exports => exports.default)),
// The path to the current directory (relative form project root). This is used for generating a GitHub link directly to your spec's code.
path: __dirname,
};
|
src/js/visuals/App.js | CT-Data-Collaborative/edi-v2 | import React, { Component } from 'react';
import StackedBarChart from './components/StackedBar';
import EdiMap from './components/Maps';
import Select from 'react-select';
class App extends Component {
constructor(props) {
super(props);
const mainElement = document.getElementById('main');
this.state = {
mapData: window.data.domain_map_data,
vulData: window.data.vulnerable_map_data,
chartData: window.data.chart_data,
domainColors: window.domainColorScale,
vulColors: window.vulnerableColorScale,
selectedMapData: 'language',
selectedVulMapData: 'vulnerable_one',
city: window.city,
height: mainElement.clientHeight,
width: mainElement.clientWidth
}
this.updateSelected = this.updateSelected.bind(this);
this.updateVulSelected = this.updateVulSelected.bind(this);
}
updateSelected(val) {
this.setState({'selectedMapData': val.value});
}
updateVulSelected(val) {
this.setState({'selectedVulMapData': val.value});
}
render() {
let choices = Object.keys(this.state.mapData);
const dropdownChoices = choices.map((c) => {
return { value: c, label: this.state.mapData[c].label }
});
let vulChoices = Object.keys(this.state.vulData);
const vulDropdownChoices = vulChoices.map((c) => {
return { value: c, label: this.state.vulData[c].label }
});
const selectedVulMap = this.state.selectedVulMapData;
const vulData = this.state.vulData[selectedVulMap];
const selectedMapData = this.state.selectedMapData;
const mapData = this.state.mapData[selectedMapData];
const mapWidth = this.state.width > 850 ? '800px' : this.state.width*.9 + 'px';
return (
<div style={{paddingTop: '20px'}}>
<h1>Visualize the results for {this.state.city}</h1>
<p>The Early Development Instrument (EDI) looks at five domains that cover the academic, social, physical, and emotional development children need to thrive and be ready for school:</p>
<ul>
<li>Physical Health & Well-being</li>
<li>Social Competence</li>
<li>Emotional Maturity</li>
<li>Language & Cognitive Development</li>
<li>Communication Skills & General Knowledge</li>
</ul>
<p>Explore results in the following <a href="#maps">maps</a> and <a href="#charts">charts</a>.</p>
<h4 id="maps">Maps</h4>
<p>The following maps display the results for each neighborhood (census tract). The first map displays the results by domains. Use the dropdown menu to change which domain is displayed. Click on a neighborhood to see the displayed values. The second map displays the results by the % of children vulnerable on one domain or vulnerable on one or more domains. A student is considered vulnerable if their score is in the lowest 10th percentile of results.</p>
<h5>Select Neighborhood EDI Results by Domain</h5>
<Select
name="map-data-select"
value={selectedMapData}
options={dropdownChoices}
onChange={this.updateSelected}
style={{width: mapWidth}}
/>
<EdiMap geojson={window.geojson} data={mapData} colors={this.state.domainColors} width={mapWidth}/>
<hr style={{width: mapWidth, textAlign: "left", marginLeft: 0}}/>
<h5>View Neighborhoods Where Kids are Vulnerable</h5>
<Select
name="vul-map-data-select"
value={selectedVulMap}
options={vulDropdownChoices}
onChange={this.updateVulSelected}
style={{width: mapWidth}}
/>
<EdiMap geojson={window.geojson} data={vulData} colors={this.state.vulColors} width={mapWidth}/>
<hr/>
<h4 id="charts">Charts</h4>
<StackedBarChart
chartTitle="Who is considered vulnerable?"
data={this.state.chartData.vulnerable.data}
columns={this.state.chartData.vulnerable.columns}
open={true}
dataKey="geography"
width={this.state.width}
/>
<StackedBarChart
chartTitle={this.state.chartData.physical.label}
intro={this.state.chartData.physical.intro}
findings={this.state.chartData.physical.findings}
data={this.state.chartData.physical.components}
columns={this.state.chartData.physical.columns}
open={false}
dataKey="component"
width={this.state.width}
/>
<StackedBarChart
chartTitle={this.state.chartData.emotional.label}
intro={this.state.chartData.emotional.intro}
findings={this.state.chartData.emotional.findings}
data={this.state.chartData.emotional.components}
columns={this.state.chartData.emotional.columns}
open={false}
dataKey="component"
width={this.state.width}
/>
<StackedBarChart
chartTitle={this.state.chartData.social.label}
intro={this.state.chartData.social.intro}
findings={this.state.chartData.social.findings}
data={this.state.chartData.social.components}
columns={this.state.chartData.social.columns}
open={false}
dataKey="component"
width={this.state.width}
/>
<StackedBarChart
chartTitle={this.state.chartData.language.label}
intro={this.state.chartData.language.intro}
findings={this.state.chartData.language.findings}
data={this.state.chartData.language.components}
columns={this.state.chartData.language.columns}
open={false}
dataKey="component"
width={this.state.width}
/>
<StackedBarChart
chartTitle={this.state.chartData.communication.label}
intro={this.state.chartData.communication.intro}
findings={this.state.chartData.communication.findings}
data={this.state.chartData.communication.components}
columns={this.state.chartData.communication.columns}
open={false}
dataKey="component"
width={this.state.width}
/>
</div>
);
}
}
export default App;
|
src/js/components/icons/base/SocialGithub.js | odedre/grommet-final | /**
* @description SocialGithub SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M11.9989871,1 C5.92550416,1 1,5.92482888 1,12.0003376 C1,16.8603395 4.15153934,20.9829338 8.52263728,22.4374904 C9.0729918,22.5387827 9.27355045,22.199116 9.27355045,21.9073943 C9.27355045,21.6467356 9.2640965,20.954572 9.25869425,20.0368642 C6.19899322,20.7013414 5.55342398,18.5620492 5.55342398,18.5620492 C5.0530403,17.2911692 4.33183953,16.9528531 4.33183953,16.9528531 C3.33309801,16.2708186 4.40747107,16.2843243 4.40747107,16.2843243 C5.51155652,16.3619816 6.09229872,17.4181221 6.09229872,17.4181221 C7.07348292,19.0988981 8.66714755,18.6133706 9.2938089,18.3317781 C9.39375058,17.6213819 9.67804414,17.1365297 9.99205009,16.86169 C7.54955646,16.5841493 4.98146045,15.6401056 4.98146045,11.4249977 C4.98146045,10.224347 5.41026428,9.24181221 6.11390773,8.47334172 C6.00046042,8.19512569 5.62297799,7.07618404 6.22195279,5.56220265 C6.22195279,5.56220265 7.14506277,5.26642929 9.24653918,6.68992296 C10.12373,6.44547101 11.0650726,6.32392032 12.0003376,6.31919335 C12.9349274,6.32392032 13.8755947,6.44547101 14.7541361,6.68992296 C16.8542619,5.26642929 17.7760214,5.56220265 17.7760214,5.56220265 C18.3763467,7.07618404 17.9988643,8.19512569 17.8860923,8.47334172 C18.5910863,9.24181221 19.0165137,10.224347 19.0165137,11.4249977 C19.0165137,15.6509101 16.444366,16.5807729 13.9944443,16.8529114 C14.3888087,17.192578 14.7406305,17.863808 14.7406305,18.890236 C14.7406305,20.3603241 14.7271248,21.5467939 14.7271248,21.9073943 C14.7271248,22.2018171 14.9256576,22.5441849 15.4834403,22.4368151 C19.8511618,20.9788821 23,16.8589889 23,12.0003376 C23,5.92482888 18.0744958,1 11.9989871,1" stroke="none"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-social-github`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'social-github');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="#333" fillRule="evenodd" d="M11.9989871,1 C5.92550416,1 1,5.92482888 1,12.0003376 C1,16.8603395 4.15153934,20.9829338 8.52263728,22.4374904 C9.0729918,22.5387827 9.27355045,22.199116 9.27355045,21.9073943 C9.27355045,21.6467356 9.2640965,20.954572 9.25869425,20.0368642 C6.19899322,20.7013414 5.55342398,18.5620492 5.55342398,18.5620492 C5.0530403,17.2911692 4.33183953,16.9528531 4.33183953,16.9528531 C3.33309801,16.2708186 4.40747107,16.2843243 4.40747107,16.2843243 C5.51155652,16.3619816 6.09229872,17.4181221 6.09229872,17.4181221 C7.07348292,19.0988981 8.66714755,18.6133706 9.2938089,18.3317781 C9.39375058,17.6213819 9.67804414,17.1365297 9.99205009,16.86169 C7.54955646,16.5841493 4.98146045,15.6401056 4.98146045,11.4249977 C4.98146045,10.224347 5.41026428,9.24181221 6.11390773,8.47334172 C6.00046042,8.19512569 5.62297799,7.07618404 6.22195279,5.56220265 C6.22195279,5.56220265 7.14506277,5.26642929 9.24653918,6.68992296 C10.12373,6.44547101 11.0650726,6.32392032 12.0003376,6.31919335 C12.9349274,6.32392032 13.8755947,6.44547101 14.7541361,6.68992296 C16.8542619,5.26642929 17.7760214,5.56220265 17.7760214,5.56220265 C18.3763467,7.07618404 17.9988643,8.19512569 17.8860923,8.47334172 C18.5910863,9.24181221 19.0165137,10.224347 19.0165137,11.4249977 C19.0165137,15.6509101 16.444366,16.5807729 13.9944443,16.8529114 C14.3888087,17.192578 14.7406305,17.863808 14.7406305,18.890236 C14.7406305,20.3603241 14.7271248,21.5467939 14.7271248,21.9073943 C14.7271248,22.2018171 14.9256576,22.5441849 15.4834403,22.4368151 C19.8511618,20.9788821 23,16.8589889 23,12.0003376 C23,5.92482888 18.0744958,1 11.9989871,1" stroke="none"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'SocialGithub';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
stories/Tooltip/Core/index.js | skyiea/wix-style-react | import React from 'react';
import {storiesOf} from '@storybook/react';
import Markdown from '../../utils/Components/Markdown';
import CodeExample from '../../utils/Components/CodeExample';
import Readme from '../../../src/Tooltip/README.md';
import ExamplePlacement from './ExamplePlacement';
import ExamplePlacementRaw from '!raw-loader!./ExamplePlacement';
import ExampleBounce from './ExampleBounce';
import ExampleBounceRaw from '!raw-loader!./ExampleBounce';
import ExampleTheme from './ExampleTheme';
import ExampleThemeRaw from '!raw-loader!./ExampleTheme';
import ExampleCustomContent from './ExampleCustomContent';
import ExampleCustomContentRaw from '!raw-loader!./ExampleCustomContent';
import ExampleMove from './ExampleMove';
import ExampleMoveRaw from '!raw-loader!./ExampleMove';
storiesOf('Core', module)
.add('Tooltip', () => (
<div>
<Markdown source={Readme}/>
<CodeExample title="Tooltip Placement" code={ExamplePlacementRaw}>
<ExamplePlacement/>
</CodeExample>
<CodeExample title="Tooltip Bounce" code={ExampleBounceRaw}>
<ExampleBounce/>
</CodeExample>
<CodeExample title="Tooltip Theme" code={ExampleThemeRaw}>
<ExampleTheme/>
</CodeExample>
<CodeExample title="Tooltip Custom Content" code={ExampleCustomContentRaw}>
<ExampleCustomContent/>
</CodeExample>
<CodeExample title="Custom tooltip adjustment" code={ExampleMoveRaw}>
<ExampleMove/>
</CodeExample>
</div>
));
|
client/modules/App/__tests__/Components/Footer.spec.js | aksm/refactored-palm-tree | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import { Footer } from '../../components/Footer/Footer';
test('renders the footer properly', t => {
const wrapper = shallow(
<Footer />
);
t.is(wrapper.find('p').length, 2);
t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.');
});
|
src/components/Layout.js | douglascorrea/react-hot-redux-firebase-starter | import React from 'react';
import Header from './common/Header';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {signOut} from '../actions/authActions';
class Layout extends React.Component {
constructor(props, context) {
super(props, context);
}
render() {
const {auth, actions, loading, user} = this.props;
return (
<div className="container-fluid">
<Header signOut={actions.signOut} auth={auth} loading={loading} user={user} />
{this.props.children}
</div>
);
}
}
Layout.propTypes = {
children: React.PropTypes.object,
actions: React.PropTypes.object.isRequired,
auth: React.PropTypes.object.isRequired,
user: React.PropTypes.object.isRequired,
loading: React.PropTypes.bool.isRequired
};
function mapStateToProps(state, ownProps) {
return {
auth: state.auth,
user: state.user,
loading: state.ajaxCallsInProgress > 0
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({signOut}, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(Layout);
|
src/routes/employee/index.js | uptive/react-starter-kit | import React from 'react';
import Employee from './Employee';
export default {
path: '/employee/:id',
async action(context) {
return {
title: 'Employee',
component: <Employee id={ context.params.id } />,
};
},
};
|
crowdpact/static/js/apps/landing/components/LandingHeader.js | joshmarlow/crowdpact | import debounce from 'lodash/function/debounce';
import React from 'react';
import LandingActions from '../actions/LandingActions';
class LandingHeader extends React.Component {
constructor(...args) {
super(...args);
this.onClickLogin = this.onClickLogin.bind(this);
this.onSearch = debounce(this.onSearch.bind(this), 400);
}
render() {
return (
<div className="landing-header">
<div className="container">
<div className="landing-title">
<a href="/">CrowdPact</a>
</div>
<div className="landing-search">
<input onChange={this.onSearch} placeholder="Find pacts" type="text" />
</div>
<div className="landing-buttons">
<button onClick={this.onClickLogin}>{this.getButtonText()}</button>
</div>
</div>
</div>
);
}
onSearch() {
console.log('onSearch');
}
onClickLogin() {
LandingActions.toggleShowLogin()
}
getButtonText() {
return this.props.data.get('showLogin') ? 'Signup' : 'Login';
}
}
export default LandingHeader;
|
rojak-ui-web/src/app/kit/SocialMedia.js | CodeRiderz/rojak | import React from 'react'
import { Link } from 'react-router'
import styles from './SocialMedia.css'
class SocialMedia extends React.Component {
static propTypes = {
instagram: React.PropTypes.string,
twitter: React.PropTypes.string,
facebook: React.PropTypes.string,
style: React.PropTypes.object
}
render () {
const { instagram, twitter, facebook, style } = this.props
return (
<div className={styles.socialMedia} style={style}>
<Link
to={`//instagram.com/${instagram}`}
target="_blank"
className={`ion-social-instagram-outline ${styles.socialIcon}`} />
<Link
to={`//twitter.com/${twitter}`}
target="_blank"
className={`ion-social-twitter-outline ${styles.socialIcon}`}
/>
<Link
to={`//facebook.com/${facebook}`}
target="_blank"
className={`ion-social-facebook-outline ${styles.socialIcon}`}
/>
</div>
)
}
}
export default SocialMedia
|
examples/counter/index.js | jquense/redux | import React from 'react';
import App from './containers/App';
React.render(
<App />,
document.getElementById('root')
);
|
app/app/index.js | natecavanaugh/github-pulls | import React from 'react';
import {render} from 'react-dom';
import {Provider} from 'react-redux';
import routes from './routes';
import configureStore from './store/configureStore';
import {loginSuccess, loginComplete} from './actions/login';
import {loadConfig} from './actions/config';
import {updateCheck} from './actions/update';
import settings from './utils/settings';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
const electron = require('electron');
const currentVersion = electron.ipcRenderer.sendSync('currentVersion');
import './scss/main.scss';
const store = configureStore(
{
currentVersion
}
);
let {username, token, avatar, lastUpdateCheck} = settings.load();
const history = syncHistoryWithStore(hashHistory, store);
if (username && token) {
store.dispatch(loginSuccess(username, token));
store.dispatch(loginComplete(avatar));
store.dispatch(loadConfig(username));
store.dispatch(updateCheck(lastUpdateCheck));
}
if (process.env.NODE_ENV === 'development') {
var windowConfig = {
height: window.screen.availHeight,
width: 800
};
windowConfig.width = Math.min(1400, window.screen.availWidth);
window.resizeTo(windowConfig.width, windowConfig.height);
}
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
); |
frontend/src/index.js | rayyildiz/twitter-streaming | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
website/Home.js | sahat/boilerplate | import haikunate from 'haikunator';
import React from 'react';
import Header from './Header';
import Footer from './Footer';
import Platform from './sections/Platform';
import StaticSiteGenerator from './sections/StaticSiteGenerator';
import JsLibrary from './sections/JsLibrary';
import Framework from './sections/Framework';
import TemplateEngine from './sections/TemplateEngine';
import CssFramework from './sections/CssFramework';
import CssPreprocessor from './sections/CssPreprocessor';
import BuildTool from './sections/BuildTool';
import Testing from './sections/Testing'
import Database from './sections/Database';
import Authentication from './sections/Authentication';
import JsFramework from './sections/JsFramework';
import Deployment from './sections/Deployment';
import NextSteps from './sections/NextSteps';
import { VelocityComponent } from 'velocity-react';
class Home extends React.Component {
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleGenerateLibraryName = this.handleGenerateLibraryName.bind(this);
this.handleDisableAutoScroll = this.handleDisableAutoScroll.bind(this);
this.clickDownload = this.clickDownload.bind(this);
this.state = {};
}
componentDidMount() {
// require it here to avoid "window is not defined" error during server-side rendering
const swal = require('sweetalert');
try {
const disableAutoScroll = localStorage.getItem('disableAutoScroll');
this.setState({
beginner: false,
disableAutoScroll: disableAutoScroll === 'true',
copyClipboardText: 'Copy to clipboard',
isDownloadLoading: false
});
} catch (e) {
console.warn(e);
}
}
clickDownload(options = {}) {
const state = this.state;
if (!state.platform) {
console.info('Please select a platform.');
return this.setState({
platformValidationError: 'Please select a platform.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'html5' && !state.staticSiteGenerator) {
console.info('Please select a static site generator.');
return this.setState({
staticSiteGeneratorValidationError: 'Please select a static site generator.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'library' && !state.jsLibraryName) {
console.info('Please enter a library name.');
return this.setState({
jsLibraryValidationError: 'Please enter a library name.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.framework) {
console.info('Please select a framework.');
return this.setState({
frameworkValidationError: 'Please select a framework.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.cssFramework) {
console.info('Please select a CSS framework.');
return this.setState({
cssFrameworkValidationError: 'Please select a CSS framework.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.cssPreprocessor) {
console.info('Please select a CSS preprocessor.');
return this.setState({
cssPreprocessorValidationError: 'Please select a CSS preprocessor.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.jsFramework) {
console.info('Please make a selection.');
return this.setState({
jsFrameworkValidationError: 'Please make a selection.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.templateEngine && state.jsFramework !== 'angularjs') {
console.info('Please select a template engine.');
return this.setState({
templateEngineValidationError: 'Please select a template engine.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && state.jsFramework !== 'none' && !state.buildTool) {
console.info('Please select a build tool.');
return this.setState({
buildToolValidationError: 'Please select a build tool.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.testing) {
console.info('Please select a testing framework.');
return this.setState({
testingValidationError: 'Please select a testing framework.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.database) {
console.info('Please select a database.');
return this.setState({
databaseValidationError: 'Please select a database.',
generateDownloadLinkInProgress: false
});
} else if (state.platform === 'node' && !state.authentication && state.database !== 'none') {
console.info('Please check all that apply.');
return this.setState({
authenticationValidationError: 'Please check all that apply.',
generateDownloadLinkInProgress: false
});
}
// Show download button spinner
if (!options.generateDownloadLink) {
this.setState({ isDownloadLoading: true });
}
// Show next steps component
this.setState({ showNextSteps: true });
if (!state.disableAutoScroll) {
if (options.generateDownloadLink) {
$(this.refs.download).velocity('scroll');
} else {
$(this.refs.nextSteps).velocity('scroll');
}
}
const data = Object.assign({}, state);
data.appName = haikunate({ tokenLength: 0 });
if (data.jsFramework === 'none') {
data.jsFramework = null;
}
if (options.generateDownloadLink) {
data.generateDownloadLink = true;
}
// Convert ES6 set to array
data.authentication = data.authentication ? Array.from(data.authentication) : [];
data.frameworkOptions = data.frameworkOptions ? Array.from(data.frameworkOptions) : [];
data.cssPreprocessorOptions = data.cssPreprocessorOptions ? Array.from(data.cssPreprocessorOptions) : [];
data.reactOptions = data.reactOptions ? Array.from(data.reactOptions) : [];
data.jsLibraryOptions = data.jsLibraryOptions ? Array.from(data.jsLibraryOptions) : [];
ga('send', 'event', 'Mega Boilerplate', 'Download', 'Downloads');
if (options.generateDownloadLink) {
ga('send', 'event', 'Mega Boilerplate', 'Download', 'Generated Links');
$.ajax({
url: '/download',
method: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done((response, status, request) => {
this.setState({
downloadLinkInputValue: response.link,
generateDownloadLinkSuccess: true,
generateDownloadLinkInProgress: false
});
$(this.refs.downloadLinkInput).focus();
}).fail((jqXHR) => {
this.setState({
generateDownloadLinkSuccess: false,
generateDownloadLinkInProgress: false
});
const title = encodeURIComponent(jqXHR.responseJSON.message);
const body = encodeURIComponent('\n##### :boom: Error Stack Trace\n' + '\`\`\`js\n' + jqXHR.responseJSON.stack + '\n\`\`\`');
swal({
title: 'Server Error',
text: `${jqXHR.responseJSON.message}<br><strong><a href='https://github.com/sahat/megaboilerplate/issues/new?title=${title}&body=${body}' target="_blank">Report a bug</a></strong>`,
type: 'error',
html: true
});
});
} else {
$.ajax({
url: '/download',
method: 'POST',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(data)
}).done((response, status, request) => {
const disp = request.getResponseHeader('Content-Disposition');
if (disp && disp.search('attachment') !== -1) {
this.setState({ isDownloadLoading: false });
const form = $('<form method="POST" action="/download">');
$.each(data, (k, v) => {
if (v) {
form.append($(`<input type="hidden" name="${k}" value="${v}">`));
}
});
$('body').append(form);
form.submit();
}
}).fail((jqXHR) => {
const title = encodeURIComponent(jqXHR.responseJSON.message);
const body = encodeURIComponent('\n##### :boom: Error Stack Trace\n' + '\`\`\`js\n' + jqXHR.responseJSON.stack + '\n\`\`\`');
swal({
title: 'Server Error',
text: `${jqXHR.responseJSON.message}<br><strong><a href='https://github.com/sahat/megaboilerplate/issues/new?title=${title}&body=${body}' target="_blank">Report a bug</a></strong>`,
type: 'error',
html: true
});
this.setState({ isDownloadLoading: false });
});
}
}
handleGenerateLibraryName() {
const newState = Object.assign({}, this.state);
newState.jsLibraryName = haikunate({ tokenLength: 0 });
newState.jsLibraryValidationError = null;
this.setState(newState);
}
handleChange(event) {
const name = event.target.name;
const value = event.target.value;
const isChecked = event.target.checked;
const state = Object.assign({}, this.state);
const refs = this.refs;
switch (name) {
case 'beginner':
state.beginner = isChecked;
if (isChecked) {
ga('send', 'event', 'Mega Boilerplate', 'Site Options', 'Beginner');
}
break;
case 'platformRadios':
const whitelist = ['beginner', 'disableAutoScroll', 'copyClipboardText', 'isDownloadLoading'];
for (const key in state) {
if (state.hasOwnProperty(key)) {
if (whitelist.indexOf(key) === -1) {
state[key] = null;
}
}
}
ga('send', 'event', 'Mega Boilerplate', 'Platform', value);
state.platform = value;
if (!state.disableAutoScroll) {
$(refs.platform).velocity('scroll');
}
state.platformValidationError = null;
break;
case 'staticSiteGeneratorRadios':
if (!state.staticSiteGenerator && !state.disableAutoScroll) {
$(refs.staticSiteGenerator).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'Static Site', value);
state.staticSiteGenerator = value;
state.staticSiteGeneratorValidationError = null;
break;
case 'jsLibraryOptionsCheckboxes':
state.jsLibraryOptions = state.jsLibraryOptions || new Set();
if (isChecked) {
state.jsLibraryOptions.add(value);
ga('send', 'event', 'Mega Boilerplate', 'JS Library', value);
} else {
state.jsLibraryOptions.delete(value);
}
break;
case 'jsLibraryName':
state.jsLibraryName = value;
state.jsLibraryValidationError = null;
break;
case 'jsLibraryAuthor':
state.jsLibraryAuthor = value;
break;
case 'jsLibraryGithubUsername':
state.jsLibraryGithubUsername = value;
break;
case 'jsLibraryLicenseRadios':
state.jsLibraryLicense = value;
ga('send', 'event', 'Mega Boilerplate', 'JS Library', value);
break;
case 'frameworkRadios':
if (!state.framework && !state.disableAutoScroll) {
$(refs.framework).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'Framework', value);
state.framework = value;
state.frameworkValidationError = null;
break;
case 'frameworkOptionsCheckboxes':
state.frameworkOptions = state.frameworkOptions || new Set();
if (isChecked) {
state.frameworkOptions.add(value);
ga('send', 'event', 'Mega Boilerplate', 'Framework', value);
} else {
state.frameworkOptions.delete(value);
}
break;
case 'templateEngineRadios':
if (!state.templateEngine && !state.disableAutoScroll) {
$(refs.templateEngine).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'Template Engine', value);
state.templateEngine = value;
state.templateEngineValidationError = null;
break;
case 'cssFrameworkRadios':
if (!state.cssFramework && !state.disableAutoScroll) {
$(refs.cssFramework).velocity('scroll');
}
if (state.cssPreprocessor) {
state.cssPreprocessor = null;
}
ga('send', 'event', 'Mega Boilerplate', 'CSS Framework', value);
state.cssFramework = value;
state.cssFrameworkValidationError = null;
break;
case 'cssPreprocessorRadios':
if (!state.cssPreprocessor && !state.disableAutoScroll) {
$(refs.cssPreprocessor).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'CSS Preprocessor', value);
state.cssPreprocessor = value;
state.cssPreprocessorValidationError = null;
state.buildTool = null;
break;
case 'cssPreprocessorOptionsCheckboxes':
state.cssPreprocessorOptions = state.cssPreprocessorOptions || new Set();
if (isChecked) {
state.cssPreprocessorOptions.add(value);
ga('send', 'event', 'Mega Boilerplate', 'CSS Preprocessor', value);
} else {
state.cssPreprocessorOptions.delete(value);
}
break;
case 'jsFrameworkRadios':
if (!state.jsFramework && !state.disableAutoScroll) {
$(refs.jsFramework).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'JS Framework', value);
state.jsFramework = value;
state.jsFrameworkValidationError = null;
state.testing = null;
state.buildTool = null;
break;
case 'reactOptionsCheckboxes':
state.reactOptions = state.reactOptions || new Set();
if (isChecked) {
state.reactOptions.add(value);
ga('send', 'event', 'Mega Boilerplate', 'JS Framework', value);
} else {
state.reactOptions.delete(value);
}
break;
case 'buildToolRadios':
if (!state.buildTool && !state.disableAutoScroll) {
$(refs.buildTool).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'Build Tool', value);
state.buildTool = value;
state.buildToolValidationError = null;
break;
case 'testingRadios':
if (!state.testing && !state.disableAutoScroll) {
$(refs.testing).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'Testing', value);
state.testing = value;
state.testingValidationError = null;
break;
case 'databaseRadios':
if (!state.database && !state.disableAutoScroll) {
$(refs.database).velocity('scroll');
}
if (value === 'none' && state.authentication) {
state.authentication.clear();
}
ga('send', 'event', 'Mega Boilerplate', 'Database', value);
state.database = value;
state.authenticationValidationError = null;
state.databaseValidationError = null;
break;
case 'authenticationCheckboxes':
state.authentication = state.authentication || new Set();
const requiresEmail = (
state.authentication.has('facebook') ||
state.authentication.has('google') ||
state.authentication.has('twitter') ||
state.authentication.has('github')
);
if (isChecked) {
ga('send', 'event', 'Mega Boilerplate', 'Authentication', value);
if (value === 'none') {
state.authentication.clear();
} else {
state.authentication.add(value);
if (value === 'facebook' || value === 'google' || value === 'twitter' || value === 'github') {
state.authentication.add('email');
}
}
state.authenticationValidationError = null;
} else {
if (value === 'email' && requiresEmail) {
return;
}
state.authentication.delete(value);
}
break;
case 'deploymentRadios':
if (!state.deployment && !state.disableAutoScroll) {
$(refs.deployment).velocity('scroll');
}
ga('send', 'event', 'Mega Boilerplate', 'Deployment', value);
state.deployment = value;
break;
default:
// Handle default case
}
// reset download link state
state.generateDownloadLinkSuccess = false;
this.setState(state);
}
handleDisableAutoScroll(event) {
if (event.target.checked) {
ga('send', 'event', 'Mega Boilerplate', 'Site Options', 'Disable Auto-Scroll');
}
this.setState({ disableAutoScroll: event.target.checked });
try {
localStorage.setItem('disableAutoScroll', event.target.checked);
} catch (e) {
console.warn(e);
}
}
handleGenerateDownloadLink(event) {
event.preventDefault();
this.setState({ generateDownloadLinkInProgress: true });
this.clickDownload({ generateDownloadLink: true });
}
handleClickDownloadLink(event) {
const input = this.refs.downloadLinkInput;
$(input).focus();
input.setSelectionRange(0, 9999);
}
copyDownloadLink(event) {
const input = this.refs.downloadLinkInput;
// select all text in the input
$(input).focus();
input.setSelectionRange(0, 9999);
try {
document.execCommand('copy');
this.setState({ copyClipboardText: 'Copied!' });
} catch (e) {
this.setState({ copyClipboardText: 'Press ⌘ + C to copy' });
console.warn('Copy to clipboard is not supported in Safari.')
}
}
copyDownloadLinkMouseOut() {
setTimeout(() => {
this.setState({ copyClipboardText: 'Copy to clipboard' });
}, 300)
}
render() {
const state = this.state;
const settingsCheckboxes = (
<ul className="list-inline list-unstyled clearfix">
<li>
<div className="checkbox">
<label>
<input type="checkbox" name="beginner" value="beginner" onChange={this.handleChange} checked={state.beginner}/>
<span>Beginner</span>
</label>
</div>
</li>
<li>
<div className="checkbox">
<label>
<input type="checkbox" name="disableAutoScroll" value="disableAutoScroll" onChange={this.handleDisableAutoScroll} checked={state.disableAutoScroll}/>
<span>Disable auto-scroll</span>
</label>
</div>
</li>
<li className="pull-right">
<div className="checkbox">
<a href="https://www.codementor.io/sahatyalkabov?utm_source=github&utm_medium=button&utm_term=sahatyalkabov&utm_campaign=github" target="_blank"><img src="https://cdn.codementor.io/badges/book_session_github.svg" alt="Book session on Codementor"/></a>
</div>
</li>
</ul>
);
const platform = (
<Platform {...state} handleChange={this.handleChange}/>
);
const staticSiteGenerator = state.platform === 'html5' ? (
<StaticSiteGenerator {...state} handleChange={this.handleChange}/>
) : null;
const jsLibrary = state.platform === 'library' ? (
<JsLibrary {...state} handleChange={this.handleChange} handleGenerateLibraryName={this.handleGenerateLibraryName}/>
) : null;
const framework = state.platform === 'node' ? (
<Framework {...state} handleChange={this.handleChange}/>
) : null;
const cssFramework = state.framework ? (
<CssFramework {...state} handleChange={this.handleChange}/>
) : null;
const cssPreprocessor = state.cssFramework ? (
<CssPreprocessor {...state} handleChange={this.handleChange}/>
) : null;
const jsFramework = state.cssPreprocessor && state.platform === 'node' ? (
<JsFramework {...state} handleChange={this.handleChange}/>
) : null;
const templateEngine = state.jsFramework && state.jsFramework !== 'angularjs' ? (
<TemplateEngine {...state} handleChange={this.handleChange}/>
) : null;
const buildTool = (state.jsFramework || (state.jsFramework && state.cssPreprocessor)) && state.platform === 'node' ? (
<BuildTool {...state} handleChange={this.handleChange}/>
) : null;
const testing = (state.buildTool || state.cssPreprocessor === 'css' && state.jsFramework === 'none') && state.platform === 'node' ? (
<Testing {...state} handleChange={this.handleChange}/>
) : null;
const database = state.testing ? (
<Database {...state} handleChange={this.handleChange}/>
) : null;
const authentication = state.database ? (
<Authentication {...state} handleChange={this.handleChange}/>
) : null;
const deployment = (state.authentication || state.database === 'none') ? (
<Deployment {...state} handleChange={this.handleChange}/>
) : null;
let generateDownloadLink;
const loadingSvgColor = state.isDownloadLoading ? '#fff' : '#000';
const loadingSvg = (
<svg version="1.1" id="loader-1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="28px" height="28px" viewBox="0 0 40 40">
<path opacity="0.2" fill={loadingSvgColor} d="M20.201,5.169c-8.254,0-14.946,6.692-14.946,14.946c0,8.255,6.692,14.946,14.946,14.946
s14.946-6.691,14.946-14.946C35.146,11.861,28.455,5.169,20.201,5.169z M20.201,31.749c-6.425,0-11.634-5.208-11.634-11.634
c0-6.425,5.209-11.634,11.634-11.634c6.425,0,11.633,5.209,11.633,11.634C31.834,26.541,26.626,31.749,20.201,31.749z"/>
<path fill={loadingSvgColor} d="M26.013,10.047l1.654-2.866c-2.198-1.272-4.743-2.012-7.466-2.012h0v3.312h0
C22.32,8.481,24.301,9.057,26.013,10.047z">
<animateTransform attributeType="xml"
attributeName="transform"
type="rotate"
from="0 20 20"
to="360 20 20"
dur="0.5s"
repeatCount="indefinite"/>
</path>
</svg>
);
if (this.state.generateDownloadLinkSuccess) {
generateDownloadLink = (
<div className="row">
<div className="col-sm-8 col-sm-offset-2">
<div className="input-group">
<input type="text" ref="downloadLinkInput" onClick={this.handleClickDownloadLink.bind(this)} className="form-control" defaultValue={state.downloadLinkInputValue} readOnly/>
<span className="input-group-btn">
<button onClick={this.copyDownloadLink.bind(this)} onMouseOut={this.copyDownloadLinkMouseOut.bind(this)} className="btn btn-default hint--bottom hint--rounded" type="button" data-hint={this.state.copyClipboardText}>
<img className="clipboard" src="https://megaboilerplate.blob.core.windows.net/megaboilerplate/img/svg/clippy.svg" width="13" alt="Copy to clipboard"/>
</button>
</span>
</div>
<p className="small text-muted text-right">This link will stay active for 24 hours</p>
</div>
<br/>
</div>
);
} else if (this.state.generateDownloadLinkInProgress) {
generateDownloadLink = (
<div className="text-center">
<div className="loader">
{loadingSvg}
<span>Please wait...</span>
</div>
</div>
);
} else {
generateDownloadLink = (
<div>
<p onClick={this.handleGenerateDownloadLink.bind(this)} className="text-center">or <a href="#" type="button">Generate Download Link</a></p>
</div>
);
}
const downloadText = state.isDownloadLoading ? loadingSvg : (
<span><i className="fa fa-download"></i> Compile and Download</span>
);
const download = state.deployment || state.staticSiteGenerator || state.platform === 'library' || state.platform === 'electron' ? (
<div>
<button ref="downloadBtn" className="btn btn-block btn-mega btn-success" onClick={this.clickDownload}>{downloadText}</button>
{generateDownloadLink}
</div>
) : null;
const nextSteps = state.showNextSteps ? (
<NextSteps {...state}/>
) : null;
return (
<div ref="wrapper">
<Header />
<main className="container">
{settingsCheckboxes}
<div ref="platform">{platform}</div>
<div ref="framework">{framework}</div>
<div ref="staticSiteGenerator">{staticSiteGenerator}</div>
<div ref="jsLibrary">{jsLibrary}</div>
<div ref="cssFramework">{cssFramework}</div>
<div ref="cssPreprocessor">{cssPreprocessor}</div>
<div ref="jsFramework">{jsFramework}</div>
<div ref="templateEngine">{templateEngine}</div>
<div ref="buildTool">{buildTool}</div>
<div ref="testing">{testing}</div>
<div ref="database">{database}</div>
<div ref="authentication">{authentication}</div>
<div ref="deployment">{deployment}</div>
<div ref="download">{download}</div>
<div ref="nextSteps">{nextSteps}</div>
</main>
<Footer />
<div className="modal" id="demosModal" tabIndex="-1" role="dialog">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal"><span aria-hidden="true">×</span>
</button>
<h4 className="modal-title" id="myModalLabel"><i className="fa fa-globe"></i> Live Demos</h4>
</div>
<div className="modal-body">
<a href="http://megaboilerplate-demo1.azurewebsites.net/" className="demo-container demo1" target="_blank">
<p><span><strong>Demo 1</strong> - Traditional Express web app</span>
<img src="https://megaboilerplate.blob.core.windows.net/megaboilerplate/img/svg/recommended.svg" alt="Recommended"/>
</p>
<span className="text-normal">Node - Jade - Bootstrap - Sass - Mocha - MongoBD - Facebook - Google - Twitter - VK</span>
</a>
<a href="http://megaboilerplate-demo2.azurewebsites.net/" className="demo-container demo2" target="_blank">
<p><span><strong>Demo 2</strong> - MEAN stack</span></p>
<span className="text-normal">Node - Handlebars - Foundation - AngularJS - Gulp - Jasmine - MongoDB - Facebook - Google</span>
</a>
<a href="http://megaboilerplate-demo3.azurewebsites.net/ " className="demo-container demo3" target="_blank">
<p><span><strong>Demo 3</strong> - Full-stack React app (unstyled)</span></p>
<span className="text-normal">Node - Nunjucks - CSSNext - PostCSS - React - Webpack - Mocha - SQLite - Twitter</span>
</a>
<a href="https://github.com/sahat/megaboilerplate/tree/master/examples/jekyll#mega-boilerplate-jekyll-blog-example" className="demo-container demo4" target="_blank">
<p><span><strong>Demo 4</strong> - Jekyll blo</span>g</p>
<span className="text-normal">Ruby - Jekyll</span>
</a>
<a href="https://github.com/sahat/megaboilerplate/tree/master/examples/middleman#mega-boilerplate-middleman-site-example" className="demo-container demo5" target="_blank">
<p><span><strong>Demo 5</strong> - Middleman static site</span></p>
<span className="text-normal">Ruby - Middleman</span>
</a>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default Home;
|
src/Parser/Druid/Guardian/Modules/Sets/Tier21_2P.js | hasseboulen/WoWAnalyzer | import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
// Formats a number to display in seconds with millisecond precision, but remove trailing zeros if applicable
function formatTimer(timeInMs) {
return Number((timeInMs / 1000).toFixed(3));
}
class Tier21_2P extends Analyzer {
static dependencies = {
combatants: Combatants,
spellUsable: SpellUsable,
};
BARKSKIN_REDUCTION_MS = 1000;
_totalReductionMs = 0;
get totalReductionMs() {
return this._totalReductionMs;
}
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.GUARDIAN_TIER_21_2P_SET_BONUS.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.MANGLE_BEAR.id) {
const hasGoreBuff = this.combatants.selected.hasBuff(SPELLS.GORE_BEAR.id);
const isOnCooldown = this.spellUsable.isOnCooldown(SPELLS.BARKSKIN.id);
if (hasGoreBuff && isOnCooldown) {
this._totalReductionMs += this.spellUsable.reduceCooldown(SPELLS.BARKSKIN.id, this.BARKSKIN_REDUCTION_MS);
}
}
}
item() {
return {
id: `spell-${SPELLS.GUARDIAN_TIER_21_2P_SET_BONUS.id}`,
icon: <SpellIcon id={SPELLS.BARKSKIN.id} />,
title: <SpellLink id={SPELLS.GUARDIAN_TIER_21_2P_SET_BONUS.id} />,
result: `Total reduction: ${formatTimer(this.totalReductionMs)} seconds`,
};
}
}
export default Tier21_2P;
|
src/@ui/Icon/icons/LeafSolid.js | NewSpring/Apollos | import React from 'react';
import PropTypes from 'prop-types';
import { Svg } from '../../Svg';
import makeIcon from './makeIcon';
const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => (
<Svg width={size} height={size} viewBox="0 0 24 24" {...otherProps}>
<Svg.Path
d="M12 22C5.2 22 2 17.52 2 12S6.48 2 12 2s10 3.33 10 10v10H12"
fill={fill}
/>
</Svg>
));
Icon.propTypes = {
size: PropTypes.number,
fill: PropTypes.string,
};
export default Icon;
|
index.ios.js | lukewalt/buzzpoint | 'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
Text,
View,
NavigatorIOS,
} from 'react-native';
import styles from './styles/styles'
import LoginRegister from './components/signInRegister'
import Rating from './components/rating'
export default class buzzpoint extends Component {
constructor(){
super();
this.state = {
loggedIn: true
}
}
render() {
return (
<NavigatorIOS
initialRoute={{
component: this.state.loggedIn ? Rating : LoginRegister,
title: '',
translucent: false,
shadowHidden: true,
passProps: {
loggedIn: this.state.loggedIn
}
}}
style={{flex: 1}}
/>
)
}
}
AppRegistry.registerComponent('buzzpoint', () => buzzpoint);
|
components/Icon/Icon.js | iest/loggins | import React, { Component } from 'react';
import invariant from 'invariant';
import styles from './Icon.css';
import icons from './icons';
export default class Icon extends Component {
constructor(props) {
super(props);
invariant(
icons[props.name],
`Icon(): No icon exists for "${props.name}"`
);
}
render() {
const css = [
styles.root,
styles[this.props.name],
this.props.className || '',
].join(' ');
return (
<span
{...this.props}
className={css}
dangerouslySetInnerHTML={{ __html: icons[this.props.name] }}
/>
);
}
}
Icon.propTypes = {
name: React.PropTypes.string.isRequired,
className: React.PropTypes.string,
};
|
jqwidgets/jqwidgets-react/react_jqxwindow.js | UCF/IKM-APIM | /*
jQWidgets v5.6.0 (2018-Feb)
Copyright (c) 2011-2017 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxWindow extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['autoOpen','animationType','collapsed','collapseAnimationDuration','content','closeAnimationDuration','closeButtonSize','closeButtonAction','cancelButton','dragArea','draggable','disabled','height','initContent','isModal','keyboardCloseKey','keyboardNavigation','minHeight','maxHeight','minWidth','maxWidth','modalOpacity','modalZIndex','modalBackgroundZIndex','okButton','position','rtl','resizable','showAnimationDuration','showCloseButton','showCollapseButton','theme','title','width','zIndex'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxWindow(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxWindow('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxWindow(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
autoOpen(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('autoOpen', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('autoOpen');
}
};
animationType(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('animationType', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('animationType');
}
};
collapsed(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('collapsed', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('collapsed');
}
};
collapseAnimationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('collapseAnimationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('collapseAnimationDuration');
}
};
content(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('content', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('content');
}
};
closeAnimationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('closeAnimationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('closeAnimationDuration');
}
};
closeButtonSize(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('closeButtonSize', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('closeButtonSize');
}
};
closeButtonAction(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('closeButtonAction', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('closeButtonAction');
}
};
cancelButton(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('cancelButton', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('cancelButton');
}
};
dragArea(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('dragArea', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('dragArea');
}
};
draggable(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('draggable', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('draggable');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('disabled');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('height', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('height');
}
};
initContent(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('initContent', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('initContent');
}
};
isModal(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('isModal', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('isModal');
}
};
keyboardCloseKey(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('keyboardCloseKey', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('keyboardCloseKey');
}
};
keyboardNavigation(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('keyboardNavigation', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('keyboardNavigation');
}
};
minHeight(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('minHeight', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('minHeight');
}
};
maxHeight(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('maxHeight', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('maxHeight');
}
};
minWidth(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('minWidth', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('minWidth');
}
};
maxWidth(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('maxWidth', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('maxWidth');
}
};
modalOpacity(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('modalOpacity', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('modalOpacity');
}
};
modalZIndex(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('modalZIndex', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('modalZIndex');
}
};
modalBackgroundZIndex(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('modalBackgroundZIndex', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('modalBackgroundZIndex');
}
};
okButton(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('okButton', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('okButton');
}
};
position(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('position', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('position');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('rtl');
}
};
resizable(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('resizable', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('resizable');
}
};
showAnimationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('showAnimationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('showAnimationDuration');
}
};
showCloseButton(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('showCloseButton', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('showCloseButton');
}
};
showCollapseButton(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('showCollapseButton', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('showCollapseButton');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('theme');
}
};
title(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('title', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('title');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('width', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('width');
}
};
zIndex(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxWindow('zIndex', arg)
} else {
return JQXLite(this.componentSelector).jqxWindow('zIndex');
}
};
bringToFront() {
JQXLite(this.componentSelector).jqxWindow('bringToFront');
};
close() {
JQXLite(this.componentSelector).jqxWindow('close');
};
collapse() {
JQXLite(this.componentSelector).jqxWindow('collapse');
};
closeAll() {
JQXLite(this.componentSelector).jqxWindow('closeAll');
};
disable() {
JQXLite(this.componentSelector).jqxWindow('disable');
};
destroy() {
JQXLite(this.componentSelector).jqxWindow('destroy');
};
enable() {
JQXLite(this.componentSelector).jqxWindow('enable');
};
expand() {
JQXLite(this.componentSelector).jqxWindow('expand');
};
focus() {
JQXLite(this.componentSelector).jqxWindow('focus');
};
isOpen() {
return JQXLite(this.componentSelector).jqxWindow('isOpen');
};
move(top, left) {
JQXLite(this.componentSelector).jqxWindow('move', top, left);
};
open() {
JQXLite(this.componentSelector).jqxWindow('open');
};
hide() {
JQXLite(this.componentSelector).jqxWindow('hide');
};
resize(top, left) {
JQXLite(this.componentSelector).jqxWindow('resize', top, left);
};
setTitle(title) {
JQXLite(this.componentSelector).jqxWindow('setTitle', title);
};
setContent(content) {
JQXLite(this.componentSelector).jqxWindow('setContent', content);
};
render() {
let id = 'jqxWindow' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
src/components/d3components/Node.js | nbuechler/studious-display | import React from 'react';
import ReactDOM from 'react-dom';
import d3 from 'd3';
import _ from 'underscore';
export default class Node extends React.Component {
constructor (props) {
super(props);
this.state = { };
}
_handleOver(d) {
var shifter = 30; // This gets the whole tooltip away from the node
var forceTipDOM = ReactDOM.findDOMNode(this).parentElement.parentElement.children[3]; //DOM Element
//These transformations apply to each case
forceTipDOM.children[1].innerHTML = d.nodeType.charAt(0).toUpperCase() + d.nodeType.slice(1);
forceTipDOM.children[0].setAttribute('visibility', 'visible');
forceTipDOM.children[1].setAttribute('visibility', 'visible');
switch (d.nodeType) {
case 'log':
// Change Rectangle Element
forceTipDOM.children[0].setAttribute('x', d.cx + shifter);
forceTipDOM.children[0].setAttribute('y', d.cy + shifter);
forceTipDOM.children[0].setAttribute('width', 60);
// Change Text Title
forceTipDOM.children[1].setAttribute('x', d.cx + 20 + shifter);
forceTipDOM.children[1].setAttribute('y', d.cy + 30 + shifter);
// Pie Variables
var nodePiePaths = forceTipDOM.children[2].children[0].children; //piePaths
var nodePieData = [d.physicArrayLength, d.emotionArrayLength, d.academicArrayLength, d.communeArrayLength, d.etherArrayLength]; //data
var nodePie = d3.layout.pie()(nodePieData); //pie layout
var arcGen = d3.svg.arc() //arcGeneration of pie slices paths
.innerRadius(25 * 0.0)
.outerRadius(25 * 0.9);
// Change MiniPieChart Element
forceTipDOM.children[2].setAttribute('visibility', 'visible');
forceTipDOM.children[2].setAttribute('x', d.cx + 5);
forceTipDOM.children[2].setAttribute('y', d.cy + 5);
forceTipDOM.children[2].setAttribute('visibility', 'visible');
nodePiePaths[0].setAttribute('d', arcGen(nodePie[0]));
nodePiePaths[1].setAttribute('d', arcGen(nodePie[1]));
nodePiePaths[2].setAttribute('d', arcGen(nodePie[2]));
nodePiePaths[3].setAttribute('d', arcGen(nodePie[3]));
nodePiePaths[4].setAttribute('d', arcGen(nodePie[4]));
break;
case 'word':
// Change Rectangle Element
forceTipDOM.children[0].setAttribute('x', d.cx + shifter);
forceTipDOM.children[0].setAttribute('y', d.cy + shifter);
forceTipDOM.children[0].setAttribute('width', 100);
// Change Text Title
forceTipDOM.children[1].setAttribute('x', d.cx + 20 + shifter);
forceTipDOM.children[1].setAttribute('y', d.cy + 30 + shifter);
forceTipDOM.children[1].innerHTML += '(' + d.characters + ')';
break;
case 'experience':
// Change Rectangle Element
forceTipDOM.children[0].setAttribute('x', d.cx + shifter);
forceTipDOM.children[0].setAttribute('y', d.cy + shifter);
forceTipDOM.children[0].setAttribute('width', 113);
// Change Text Title
forceTipDOM.children[1].setAttribute('x', d.cx + 20 + shifter);
forceTipDOM.children[1].setAttribute('y', d.cy + 30 + shifter);
break;
case 'activity':
// Change Rectangle Element
forceTipDOM.children[0].setAttribute('x', d.cx + shifter);
forceTipDOM.children[0].setAttribute('y', d.cy + shifter);
forceTipDOM.children[0].setAttribute('width', 93);
// Change Text Title
forceTipDOM.children[1].setAttribute('x', d.cx + 20 + shifter);
forceTipDOM.children[1].setAttribute('y', d.cy + 30 + shifter);
break;
default:
break;
}
}
_handleOut(d) {
var forceTipDOM = ReactDOM.findDOMNode(this).parentElement.parentElement.children[3];
// Change Rectangle Element
forceTipDOM.children[0].setAttribute('visibility', 'hidden');
// Change Text Title
forceTipDOM.children[1].setAttribute('visibility', 'hidden');
switch (d.nodeType) {
case 'log':
// Change MiniPieChart Element
forceTipDOM.children[2].setAttribute('visibility', 'hidden');
break;
case 'word':
break;
case 'experience':
break;
case 'activity':
break;
default:
break;
}
}
render () {
var node = '';
var nodeColor = '#111';
if (this.props.privacy) {
nodeColor = 'white';
}
switch (this.props.nodeType) {
case 'log': //draw a log node
node = <circle fill={nodeColor}
r={this.props.r + 'px'}
cx={this.props.cx}
cy={this.props.cy}
stroke={nodeColor}
style={{strokeWidth: '3px'}}
onMouseOver={this._handleOver.bind(this, this.props)}
onMouseOut={this._handleOut.bind(this, this.props)}
/>
break;
case 'word': //draw a word node
node = <circle fill={this.props.fillColor}
r={this.props.r * ('.' + this.props.characters) + 'px'}
cx={this.props.cx}
cy={this.props.cy}
stroke={this.props.stroke}
style={{strokeWidth: '3px'}}
onMouseOver={this._handleOver.bind(this, this.props)}
onMouseOut={this._handleOut.bind(this, this.props)}
/>
break;
case 'experience': //draw a word node
node = <circle fill={nodeColor}
r={this.props.r + 'px'}
cx={this.props.cx}
cy={this.props.cy}
stroke={nodeColor}
style={{strokeWidth: '3px'}}
onMouseOver={this._handleOver.bind(this, this.props)}
onMouseOut={this._handleOut.bind(this, this.props)}
/>
break;
case 'activity': //draw a word node
node = <circle fill={nodeColor}
r={this.props.r + 'px'}
cx={this.props.cx}
cy={this.props.cy}
stroke={'red'}
style={{strokeWidth: '3px'}}
onMouseOver={this._handleOver.bind(this, this.props)}
onMouseOut={this._handleOut.bind(this, this.props)}
/>
break;
default:
break;
}
return (
node
);
}
}
|
demo/component/TextDemo.js | sdoomz/recharts | import React, { Component } from 'react';
import { Text } from 'recharts';
class TextDemo extends Component {
state = {
exampleText: 'This is really long text',
x: 0,
y: 0,
width: 300,
height: 200,
angle: 0,
scaleToFit: false,
textAnchor: 'start',
verticalAnchor: 'start',
fontSize: '1em',
fontFamily: 'Arial',
lineHeight: '1em',
showAnchor: true,
resizeSvg: true,
};
render() {
const styles = {
exampleText: {
width: 200,
},
range: {
marginLeft: 25,
width: 275,
},
svg: {
height: 200,
display: 'block',
border: '1px solid #aaa',
marginBottom: 10,
},
};
return (
<div>
<h2>Demo</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text
x={this.state.x}
y={this.state.y}
width={this.state.width}
textAnchor={this.state.textAnchor}
verticalAnchor={this.state.verticalAnchor}
lineHeight={this.state.lineHeight}
scaleToFit={this.state.scaleToFit}
angle={this.state.angle}
style={{ fontSize: this.state.fontSize, fontFamily: this.state.fontFamily }}
>
{this.state.exampleText}
</Text>
{ this.state.showAnchor && <circle cx={this.state.x} cy={this.state.y} r="2" fill="red" /> }
</svg>
<div>
text:
<input
type="text"
style={styles.exampleText}
value={this.state.exampleText}
onChange={e => this.setState({ exampleText: e.target.value })}
/>
</div>
<div>
x: <input type="text" value={this.state.x} onChange={e => this.setState({ x: Number(e.target.value) })} />
y: <input type="text" value={this.state.y} onChange={e => this.setState({ y: Number(e.target.value) })} />
</div>
<div>
width:
<input
type="range"
style={styles.range}
min="25" max="300"
value={this.state.width}
onChange={e => this.setState({ width: Number(e.target.value) })}
/> {this.state.width}
</div>
<div>
textAnchor:
<label>
<input
type="radio"
value="start"
onChange={e => this.setState({ textAnchor: e.target.value })}
checked={this.state.textAnchor === 'start'}
/> start
</label>
<label>
<input
type="radio"
value="middle"
onChange={e => this.setState({ textAnchor: e.target.value })}
checked={this.state.textAnchor === 'middle'}
/> middle
</label>
<label>
<input
type="radio"
value="end"
onChange={e => this.setState({ textAnchor: e.target.value })}
checked={this.state.textAnchor === 'end'}
/> end
</label>
</div>
<div>
verticalAnchor:
<label>
<input
type="radio"
value="start"
onChange={e => this.setState({ verticalAnchor: e.target.value })}
checked={this.state.verticalAnchor === 'start'}
/> start
</label>
<label>
<input
type="radio"
value="middle"
onChange={e => this.setState({ verticalAnchor: e.target.value })}
checked={this.state.verticalAnchor === 'middle'}
/> middle
</label>
<label>
<input
type="radio"
value="end"
onChange={e => this.setState({ verticalAnchor: e.target.value })}
checked={this.state.verticalAnchor === 'end'}
/> end
</label>
</div>
<div>
fontSize:
<input
type="text"
value={this.state.fontSize}
onChange={e => this.setState({ fontSize: e.target.value })}
/>
</div>
<div>
fontFamily:
<input
type="text"
value={this.state.fontFamily}
onChange={e => this.setState({ fontFamily: e.target.value })}
/>
</div>
<div>
lineHeight:
<input
type="text"
value={this.state.lineHeight}
onChange={e => this.setState({ lineHeight: e.target.value })}
/>
</div>
<div>
angle:
<input
type="range"
min="0" max="360"
value={this.state.angle}
onChange={e => this.setState({ angle: Number(e.target.value) })}
/>
</div>
<div>
<label>
scaleToFit:
<input
type="checkbox"
onChange={e => this.setState({ scaleToFit: !this.state.scaleToFit })}
checked={this.state.scaleToFit}
/>
</label>
</div>
<div>
<label>
show anchor:
<input
type="checkbox"
onChange={e => this.setState({ showAnchor: !this.state.showAnchor })}
checked={this.state.showAnchor}
/>
</label>
</div>
<div>
<label>
resize svg (container):
<input
type="checkbox"
onChange={e => this.setState({ resizeSvg: !this.state.resizeSvg })}
checked={this.state.resizeSvg}
/>
</label>
</div>
<hr />
<h2>Simple</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start">
{this.state.exampleText}
</Text>
</svg>
<h2>Centered</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={this.state.width / 2} width={this.state.width} verticalAnchor="start" textAnchor="middle">
{this.state.exampleText}
</Text>
</svg>
<h2>Right-aligned</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={this.state.width} width={this.state.width} verticalAnchor="start" textAnchor="end">
{this.state.exampleText}
</Text>
</svg>
<h2>Line height</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" lineHeight="2em">
{this.state.exampleText}
</Text>
</svg>
<h2>Styled text (fontWeight)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontWeight: 900 }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize px)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '24px' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize em)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '1.5em' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize rem)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '1.5rem' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Styled (fontSize %)</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text x={0} width={this.state.width} verticalAnchor="start" style={{ fontSize: '150%' }}>
{this.state.exampleText}
</Text>
</svg>
<h2>Fit</h2>
<svg width={this.state.resizeSvg ? this.state.width : 300} style={styles.svg}>
<Text width={this.state.width} verticalAnchor="start" scaleToFit>
{this.state.exampleText}
</Text>
</svg>
</div>
);
}
}
export default TextDemo;
|
src/components/Feedback/Feedback.js | Batname/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import styles from './Feedback.less';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Feedback {
render() {
return (
<div className="Feedback">
<div className="Feedback-container">
<a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className="Feedback-spacer">|</span>
<a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
examples/huge-apps/routes/Course/components/Course.js | kurayama/react-router | /*globals COURSES:true */
import React from 'react'
import Dashboard from './Dashboard'
import Nav from './Nav'
const styles = {}
styles.sidebar = {
float: 'left',
width: 200,
padding: 20,
borderRight: '1px solid #aaa',
marginRight: 20
}
class Course extends React.Component {
render() {
let { children, params } = this.props
let course = COURSES[params.courseId]
return (
<div>
<h2>{course.name}</h2>
<Nav course={course} />
{children && children.sidebar && children.main ? (
<div>
<div className="Sidebar" style={styles.sidebar}>
{children.sidebar}
</div>
<div className="Main" style={{ padding: 20 }}>
{children.main}
</div>
</div>
) : (
<Dashboard />
)}
</div>
)
}
}
export default Course
|
src/svg-icons/notification/airline-seat-recline-normal.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatReclineNormal = (props) => (
<SvgIcon {...props}>
<path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/>
</SvgIcon>
);
NotificationAirlineSeatReclineNormal = pure(NotificationAirlineSeatReclineNormal);
NotificationAirlineSeatReclineNormal.displayName = 'NotificationAirlineSeatReclineNormal';
NotificationAirlineSeatReclineNormal.muiName = 'SvgIcon';
export default NotificationAirlineSeatReclineNormal;
|
actor-apps/app-web/src/app/components/dialog/TypingSection.react.js | ketoo/actor-platform | import React from 'react';
import { PureRenderMixin } from 'react/addons';
import classNames from 'classnames';
import DialogStore from 'stores/DialogStore';
export default React.createClass({
mixins: [PureRenderMixin],
getInitialState() {
return {
typing: null,
show: false
};
},
componentDidMount() {
DialogStore.addTypingListener(this.onTypingChange);
},
componentWillUnmount() {
DialogStore.removeTypingListener(this.onTypingChange);
},
onTypingChange() {
const typing = DialogStore.getSelectedDialogTyping();
if (typing === null) {
this.setState({show: false});
} else {
this.setState({typing: typing, show: true});
}
},
render() {
const typing = this.state.typing;
const show = this.state.show;
const typingClassName = classNames('typing', {
'typing--hidden': show === false
});
return (
<div className={typingClassName}>
<i className="material-icons">more_horiz</i>
<span>{typing}</span>
</div>
);
}
});
|
src/components/Developer/DeveloperList.js | iamraphson/mernmap | /**
* Created by Raphson on 10/14/16.
*/
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Link } from 'react-router';
export default class DeveloperList extends Component {
constructor() {
super();
}
render(){
return (
<div className="col-lg-2 col-md-3 col-sm-4 col-xs-5 team-profile">
<div style={{textAlign: 'center'}}>
<Link to={ `/mern-developers/${this.props.developer.username}`}>
<img height={150} width={150} alt={this.props.developer.fullname}
src={this.props.developer.user_avi} />
</Link>
</div>
<div className="profile-name grid3">{this.props.developer.username}</div>
<ul className="profile-social-icons">
<li>
<a target="_blank" href={this.props.developer.twitter_handle || '#'}>
<i className="fa fa-twitter-square" />
</a>
</li>
<div style={{display: 'inline-block', width: 10, height: 4}}></div>
<li>
<a target="_blank" href={this.props.developer.github_profile || '#'}>
<i className="fa fa-github-square" />
</a>
</li>
</ul>
</div>
);
}
} |
src/parser/warrior/fury/modules/spells/RampageCancelled.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import Analyzer from 'parser/core/Analyzer';
const RAMPAGE_HITS_PER_CAST = 4;
class RampageCancelled extends Analyzer {
// Rampage is in fact 5 separate spells cast in this sequence
rampage = [SPELLS.RAMPAGE_1.id, SPELLS.RAMPAGE_2.id, SPELLS.RAMPAGE_3.id, SPELLS.RAMPAGE_4.id];
counter = {};
constructor(...args) {
super(...args);
for (let i = 0; i < this.rampage.length; i++) {
this.counter[this.rampage[i]] = 0;
}
}
on_byPlayer_damage(event) {
if (!this.rampage.includes(event.ability.guid)) {
return;
}
this.counter[event.ability.guid] += 1;
}
get suggestionThresholdsFrothingBerserker() {
return {
isGreaterThan: {
minor: 0,
average: 0.02,
major: 0.05,
},
style: 'percentage',
};
}
suggestions(when) {
const {
isGreaterThan: {
minor,
average,
major,
},
} = this.suggestionThresholdsFrothingBerserker;
const max = Object.values(this.counter).reduce((max, current) => current > max ? current : max, 0);
const wasted = Object.keys(this.counter).reduce((acc, current) => acc + max - this.counter[current], 0);
when(wasted / (max * RAMPAGE_HITS_PER_CAST)).isGreaterThan(minor)
.addSuggestion((suggest, actual) => {
return suggest(<>Your <SpellLink id={SPELLS.RAMPAGE.id} /> cast are being cancelled prematurely. Be sure to be facing the target within melee distance to avoid this.</>)
.icon(SPELLS.RAMPAGE.icon)
.actual(`${formatPercentage(actual)}% (${wasted} out of ${max * RAMPAGE_HITS_PER_CAST}) of your Rampage hits were cancelled.`)
.recommended(`0% is recommended`)
.regular(average).major(major);
});
}
}
export default RampageCancelled;
|
todo-iflux-es6/assets/js/components/footer.react.js | hufeng/todomvc | import React from 'react';
import PureComponent from './pure-component';
/**
* footer
*/
export default class Footer extends PureComponent {
render() {
console.log('footer rendering....');
return (
<footer id="info">
<p>Double-click to edit a todo</p>
<p>Created by <a href="http://sindresorhus.com">Sindre Sorhus</a></p>
<p>Part of <a href="http://todomvc.com">TodoMVC</a></p>
</footer>
);
}
}
|
src/svg-icons/maps/local-airport.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalAirport = (props) => (
<SvgIcon {...props}>
<path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>
</SvgIcon>
);
MapsLocalAirport = pure(MapsLocalAirport);
MapsLocalAirport.displayName = 'MapsLocalAirport';
MapsLocalAirport.muiName = 'SvgIcon';
export default MapsLocalAirport;
|
docs/app/Examples/collections/Table/Variations/TableExampleColumnWidth.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Table } from 'semantic-ui-react'
const TableExampleColumnWidth = () => {
return (
<Table>
<Table.Header>
<Table.Row>
<Table.HeaderCell width={10}>Name</Table.HeaderCell>
<Table.HeaderCell width='six'>Status</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>John</Table.Cell>
<Table.Cell>Approved</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie</Table.Cell>
<Table.Cell>Approved</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jill</Table.Cell>
<Table.Cell>Denied</Table.Cell>
</Table.Row>
</Table.Body>
<Table.Footer>
<Table.Row>
<Table.HeaderCell>3 People</Table.HeaderCell>
<Table.HeaderCell>2 Approved</Table.HeaderCell>
</Table.Row>
</Table.Footer>
</Table>
)
}
export default TableExampleColumnWidth
|
src/svg-icons/image/switch-video.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageSwitchVideo = (props) => (
<SvgIcon {...props}>
<path d="M18 9.5V6c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-3.5l4 4v-13l-4 4zm-5 6V13H7v2.5L3.5 12 7 8.5V11h6V8.5l3.5 3.5-3.5 3.5z"/>
</SvgIcon>
);
ImageSwitchVideo = pure(ImageSwitchVideo);
ImageSwitchVideo.displayName = 'ImageSwitchVideo';
ImageSwitchVideo.muiName = 'SvgIcon';
export default ImageSwitchVideo;
|
blueprints/dumb/files/__root__/components/__name__/__name__.js | nicolas-amabile/counter | import React from 'react'
type Props = {
};
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render () {
return (
<div></div>
)
}
}
export default <%= pascalEntityName %>
|
stories/Popover.stories.js | reactstrap/reactstrap | import React from 'react';
export default {
title: 'Components/Popover',
parameters: {
docs: {
description: {
component: '[Bootstrap Popovers](https://getbootstrap.com/docs/5.1/components/popovers/)'
}
}
}
};
export { default as Popover } from './examples/Popover';
export { default as Focus } from './examples/PopoverFocus';
export { default as Multi } from './examples/PopoverMulti';
export { default as Uncontrolled } from './examples/PopoverUncontrolled';
export { default as Update } from './examples/PopoverUpdate';
export { default as Props } from './examples/PopoverProps'; |
src/routes/Async/components/Async.js | janoist1/universal-react-redux-starter-kit | import React from 'react'
import Helmet from 'react-helmet'
import { resolve } from 'react-resolver'
@resolve('fetchedData', function(props) {
const { fetchData } = props
return fetchData().then(action => action.payload)
})
export class Async extends React.Component {
render() {
const { fetchedData } = this.props
return (
<div>
<Helmet title='Async' />
{ JSON.stringify(fetchedData) }
</div>
)
}
}
Async.propTypes = {
fetchData: React.PropTypes.func.isRequired
}
export default Async
|
stories/CardContent.stories.js | nekuno/client | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links'
import CardContent from '../src/js/components/ui/CardContent/CardContent.js';
storiesOf('CardContent', module)
.add('with text', () => (
<CardContent onClickHandler={action('clicked')}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam et elit ante.
</CardContent>
))
.add('with HTML', () => (
<CardContent onClickHandler={action('clicked')}>
<div>Lorem ipsum</div>
<br/>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam et elit ante.</div>
</CardContent>
)); |
examples/passing-props-to-children/app.js | batmanimal/react-router | import React from 'react';
import { Router, Route, Link, History } from 'react-router';
var App = React.createClass({
mixins: [ History ],
getInitialState() {
return {
tacos: [
{ name: 'duck confit' },
{ name: 'carne asada' },
{ name: 'shrimp' }
]
};
},
addTaco() {
var name = prompt('taco name?');
this.setState({
tacos: this.state.tacos.concat({name: name})
});
},
handleRemoveTaco(removedTaco) {
var tacos = this.state.tacos.filter(function (taco) {
return taco.name != removedTaco;
});
this.setState({tacos: tacos});
this.history.pushState(null, '/');
},
render() {
var links = this.state.tacos.map(function (taco, i) {
return (
<li key={i}>
<Link to={`/taco/${taco.name}`}>{taco.name}</Link>
</li>
);
});
return (
<div className="App">
<button onClick={this.addTaco}>Add Taco</button>
<ul className="Master">
{links}
</ul>
<div className="Detail">
{this.props.children && React.cloneElement(this.props.children, {
onRemoveTaco: this.handleRemoveTaco
})}
</div>
</div>
);
}
});
var Taco = React.createClass({
remove() {
this.props.onRemoveTaco(this.props.params.name);
},
render() {
return (
<div className="Taco">
<h1>{this.props.params.name}</h1>
<button onClick={this.remove}>remove</button>
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route path="taco/:name" component={Taco} />
</Route>
</Router>
), document.getElementById('example'));
|
webpack/containers/Application/index.js | Katello/katello | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { BrowserRouter as Router } from 'react-router-dom';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { orgId } from '../../services/api';
import * as actions from '../../scenes/Organizations/OrganizationActions';
import reducer from '../../scenes/Organizations/OrganizationReducer';
import Routes from './Routes';
import './overrides.scss';
const mapStateToProps = state => ({ organization: state.organization });
const mapDispatchToProps = dispatch => bindActionCreators(actions, dispatch);
export const organization = reducer;
class Application extends Component {
componentDidMount() {
this.loadData();
}
loadData() {
if (orgId()) {
this.props.loadOrganization();
}
}
render() {
return (
<Router>
<Routes />
</Router>
);
}
}
Application.propTypes = {
loadOrganization: PropTypes.func.isRequired,
};
export default connect(mapStateToProps, mapDispatchToProps)(Application);
|
src/esm/components/graphics/icons/lock-icon/index.js | KissKissBankBank/kitten | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title", "width", "height"];
import React from 'react';
import PropTypes from 'prop-types';
import COLORS from '../../../../constants/colors-config';
import { computeFromRatio } from '../../../../helpers/utils/ratio';
var DEFAULT_WIDTH = 14;
var DEFAULT_HEIGHT = 18;
export var LockIcon = function LockIcon(_ref) {
var color = _ref.color,
title = _ref.title,
width = _ref.width,
height = _ref.height,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
var computed = computeFromRatio({
defaultWidth: DEFAULT_WIDTH,
defaultHeight: DEFAULT_HEIGHT,
width: width,
height: height
});
return /*#__PURE__*/React.createElement("svg", _extends({
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 14 18",
width: computed.width,
height: computed.height,
fill: color
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", {
d: "M5,6 L9,6 L9,4 C9,2.8954305 8.1045695,2 7,2 C5.8954305,2 5,2.8954305 5,4 L5,6 Z M11,6 L14,6 L14,18 L0,18 L0,6 L3,6 L3,4 C3,1.790861 4.790861,0 7,0 C9.209139,0 11,1.790861 11,4 L11,6 Z M6.5,11.9146471 L6.5,14.5 C6.5,14.7761424 6.72385763,15 7,15 C7.27614237,15 7.5,14.7761424 7.5,14.5 L7.5,11.9146471 C8.08259619,11.7087289 8.5,11.1531094 8.5,10.5 C8.5,9.67157288 7.82842712,9 7,9 C6.17157288,9 5.5,9.67157288 5.5,10.5 C5.5,11.1531094 5.91740381,11.7087289 6.5,11.9146471 Z"
}));
};
LockIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string])
};
LockIcon.defaultProps = {
color: COLORS.background1
}; |
source/common/components/HomePage/HomePage.js | shery15/react | import React from 'react';
import { Link } from 'react-router';
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
const HomePage = ({
userId,
onSubmitUserId,
onChangeUserId
}) => {
return (
<div>
<TextField
hintText="Please Key in your Github User Id."
onChange={onChangeUserId}
/>
<RaisedButton label="Submit" onClick={onSubmitUserId(userId)} primary />
<Link
to={{
pathname: '/result',
query: { userId }
}}
/>
</div>
);
// return (
// <div>
// </div>
// );
};
export default HomePage;
|
stories/Popover.js | propertybase/react-lds | import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { boolean, text, select } from '@storybook/addon-knobs';
import { Popover, MediaObject, Icon } from '../src';
import { getThemesWithoutTexture } from './utils/helpers';
const stories = storiesOf('Popover', module);
const icon = <Icon sprite="standard" size="small" icon="account" />;
const sampleHeader = (<p className="slds-text-heading--medium slds-hyphenate"><a href="#anchor">Sample Account</a></p>);
const sampleText = (
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat minus molestias
reprehenderit consequuntur sapiente. Modi veritatis totam accusantium numquam assumenda.</p>
);
const header = (
<div>
<MediaObject figureLeft={icon} className="slds-m-bottom--small">{sampleHeader}</MediaObject>
{sampleText}
</div>
);
const icon2 = <Icon sprite="standard" size="small" icon="opportunity" />;
const sampleHeader2 = (<p className="slds-text-heading--small slds-hyphenate">Sample Opportunity</p>);
const sampleText2 = (<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Fugiat minus molestias
reprehenderit consequuntur sapiente. Modi veritatis totam accusantium numquam assumenda.</p>);
const body = (
<div>
<div className="slds-popover__body-list">
<MediaObject figureLeft={icon2} className="slds-m-bottom--small">{sampleHeader2}</MediaObject>
{sampleText2}
</div>
<div className="slds-popover__body-list">
<MediaObject figureLeft={icon2} className="slds-m-bottom--small">{sampleHeader2}</MediaObject>
{sampleText2}
</div>
</div>
);
stories
.add('Default', () => (
<Popover
open={boolean('Open', true)}
closeable={boolean('Closeable', true)}
onClose={action('Clicked close!')}
header={text('Header', 'Header can be element or string')}
body={text('Body', 'Body can be element or string')}
footer={text('Footer', '')}
nubbin={select('Nubbin', [
'',
'left',
'left-top',
'left-bottom',
'top-left',
'top-right',
'right-top',
'right-bottom',
'bottom-left',
'bottom-right',
], '') || undefined}
customHeaderTheme={select('CustomHeaderTheme', [
'',
'warning',
'error',
'success',
'info'
], '') || undefined}
theme={getThemesWithoutTexture()}
/>
))
.add('Panels', () => (
<Popover
open
closeable
onClose={action('Clicked close!')}
header={header}
body={body}
nubbin={select('Nubbin', [
'',
'left',
'left-top',
'left-bottom',
'top-left',
'top-right',
'right-top',
'right-bottom',
'bottom-left',
'bottom-right',
], '') || undefined}
panels
/>
));
|
src/components/article/HeaderOne.js | garfieldduck/twreporter-react | 'use strict'
import commonStyles from './Common.scss'
import styles from './HeaderOne.scss'
import classNames from 'classnames'
import React from 'react' // eslint-disable-next-line
// lodash
import get from 'lodash/get'
export const HeaderOne = ({ content }) => {
return <h1 className={classNames(commonStyles['inner-block'],
styles['title'], 'text-justify')} dangerouslySetInnerHTML={{ __html: get(content, [ 0 ], '') }}></h1>
}
|
src/component/component.js | APSL/redux-i18n | /*
* Project: redux-i18n
* File: component/component.js
*/
import React from 'react'
import {PropTypes} from 'prop-types'
import {setForceRefresh, setLanguage} from '../actions'
import getTranslateFunction from '../getTranslateFunction';
class I18n extends React.Component {
getChildContext() {
const {lang, fallbackLang, useReducer, translations_reducer, translations, newFallbackLang} = this.props;
return {
t: getTranslateFunction(
useReducer ? translations_reducer : translations,
lang,
newFallbackLang ? newFallbackLang : fallbackLang
)
};
}
shouldComponentUpdate(nextProps, nextState) {
if (this.props.forceRefresh && !nextProps.forceRefresh) {
return false
}
return true
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.lang !== this.props.lang || (!prevProps.forceRefresh && this.props.forceRefresh)) {
this.forceUpdate();
if (this.props.forceRefresh) {
this.props.dispatch(setForceRefresh(false))
}
}
}
UNSAFE_componentWillMount() {
if (!this.props.initialized) {
this.props.dispatch(setLanguage(this.props.initialLang))
}
}
render() {
return this.props.children
}
}
I18n.childContextTypes = {
t: PropTypes.func.isRequired
}
I18n.propTypes = {
translations: PropTypes.object.isRequired,
useReducer: PropTypes.bool,
initialLang: PropTypes.string,
fallbackLang: PropTypes.string,
initialized: PropTypes.bool
}
I18n.defaultProps = {
useReducer: false,
initialLang: 'en',
fallbackLang: null
}
export default I18n
|
docs/src/pages/component-demos/progress/LinearQuery.js | dsslimshaddy/material-ui | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import { LinearProgress } from 'material-ui/Progress';
const styles = theme => ({
root: {
width: '100%',
marginTop: theme.spacing.unit * 3,
},
});
function LinearQuery(props) {
const classes = props.classes;
return (
<div className={classes.root}>
<LinearProgress mode="query" />
<br />
<LinearProgress color="accent" mode="query" />
</div>
);
}
LinearQuery.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(LinearQuery);
|
src/components/home/HomeView.js | ahonn/v2exRN | import React, { Component } from 'react';
import {
Text,
View,
ToolbarAndroid,
DrawerLayoutAndroid,
StyleSheet
} from 'react-native';
import { connect } from 'react-redux';
import SplashScreen from 'react-native-splash-screen';
import Icon from 'react-native-vector-icons/Ionicons';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import defaultTabs from '../../constants/Tabs';
import TopicList from '../topicList/TopicList';
import SimpleTabBar from './SimpleTabBar';
const toolBarConfig = {
title: '浏览'
};
class HomeView extends Component {
componentDidMount() {
SplashScreen.hide();
}
_renderTopicList() {
return defaultTabs.map(item => {
return (
<TopicList
key={item.tab}
tab={item.tab}
tabLabel={item.name}
navigator={this.props.navigator}
/>
);
});
}
render() {
return (
<View style={styles.container}>
<Icon.ToolbarAndroid
title={toolBarConfig.title}
titleColor="#fff"
style={styles.toolbar}
navIconName="md-menu"
onIconClicked={() => this.props.openDrawer()} />
<ScrollableTabView
renderTabBar={() => <SimpleTabBar />}
tabBarBackgroundColor="#334"
tabBarActiveTextColor="#FFF"
tabBarInactiveTextColor="#EEE"
tabBarUnderlineStyle={styles.tabbar}
>
{ this._renderTopicList() }
</ScrollableTabView>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'transparent',
flexDirection: 'column',
},
toolbar: {
height: 56,
backgroundColor: '#334',
},
tabbar: {
backgroundColor: '#FFF',
}
});
const mapStateToProps = (state) => {
return {
topic: state.topic,
};
};
export default connect(mapStateToProps)(HomeView); |
webapp/app/components/Users/Table/index.js | EIP-SAM/SAM-Solution-Server | //
// Table page save
//
import React from 'react';
import { Table } from 'react-bootstrap';
import ButtonPopover from 'components/ButtonPopover';
import UserDeletionModal from 'containers/Users/Table/ModalDeletionUser';
import Tr from 'components/Tr';
import Th from 'components/Th';
import Td from 'components/Td';
import styles from './styles.css';
/* eslint-disable react/prefer-stateless-function */
export default class UserTable extends React.Component {
handleDeleteClick(user) {
this.props.showInstantDeleteModal();
this.props.userToDelete(user.id);
this.props.getUsername(user.name);
}
render() {
const names = ['#', 'Name', 'Email', 'Group(s)', 'Actions'];
return (
<div>
<Table responsive hover striped>
<thead>
<Tr items={names} component={Th} />
</thead>
<tbody>
{this.props.users.map((user, index) => {
const action = [];
let groupName = '';
user.groups.map((group, index2) => {
if (index2 > 0) {
groupName += ', ';
}
groupName += group.name;
return true;
});
action.push(<ButtonPopover key={`action-${0}`} id="edit_user" trigger={['focus', 'hover']} placement="bottom" popoverContent="Edit User" buttonType="link" icon="pencil" link={`/edit-user/${user.id}`} />);
action.push(<ButtonPopover key={`action-${1}`} id="delete_user" trigger={['focus', 'hover']} placement="bottom" popoverContent="Delete User" buttonType="link" icon="trash" onClick={() => this.handleDeleteClick(user)} buttonStyle={styles.trash} />);
return (
<Tr
key={`row-${index}`} items={[
{ isLink: false, value: user.id },
{ isLink: true, link: `/dashboard/${user.name}/${user.id}`, value: user.name },
{ isLink: false, value: user.email },
{ isLink: false, value: groupName },
{ isLink: false, value: action }]} component={Td}
/>
);
})}
</tbody>
</Table>
<UserDeletionModal />
</div>
);
}
}
UserTable.propTypes = {
users: React.PropTypes.arrayOf(React.PropTypes.object),
showInstantDeleteModal: React.PropTypes.func,
userToDelete: React.PropTypes.func,
getUsername: React.PropTypes.func,
};
UserTable.defaultProps = {
users: [],
};
|
springboot/GReact/src/main/resources/static/app/routes/graphs/containers/EasyPieCharts.js | ezsimple/java | import React from 'react'
import {Stats, BigBreadcrumbs, WidgetGrid, JarvisWidget} from '../../../components'
import EasyPieChartContainer from '../../../components/graphs/inline/EasyPieChartContainer'
export default () => (
<div id="content">
<div className="row">
<BigBreadcrumbs items={["Easy Pie Charts"]} icon="fa fa-fw fa-bar-chart-o" className="col-xs-12 col-sm-7 col-md-7 col-lg-4"/>
<Stats />
</div>
<div className="row">
<EasyPieChartContainer className="col-sm-12">
<div className="well">
<h1>Easy <span className="semi-bold">Pie Charts</span>
<small>Simplified for faster production</small>
</h1>
<p>Easy Pie Charts gives you a nice animation twist to your pie charts - they are also dynamic,
which will make it a really nice ajax based live charts for your project</p>
<p className="note"><div class="easy-pie-chart txt-color-blue easyPieChart"
data-percent="36" data-size="180"> data-pie-size="50">
<span class="percent percent-sign txt-color-blue font-xl semi-bold">36<
/span>
</div></p>
<ul className="list-inline">
<li>
<div className="easy-pie-chart txt-color-red easyPieChart" data-percent="50" data-size="180"
data-pie-size="50">
<span className="percent percent-sign txt-color-red font-xl semi-bold">49</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-blue easyPieChart" data-percent="36"
data-pie-size="180">
<span className="percent percent-sign txt-color-blue font-xl semi-bold">36</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-pinkDark easyPieChart" data-percent="46"
data-pie-size="160">
<span className="percent percent-sign txt-color-pinkDark font-lg semi-bold">46</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-greenLight easyPieChart" data-percent="56"
data-pie-size="110">
<span className="percent percent-sign txt-color-greenLight font-md">56</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-orange easyPieChart" data-percent="66"
data-pie-size="60">
<span className="percent percent-sign txt-color-orange">66</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-darken easyPieChart" data-percent="76"
data-pie-size="45">
<span className="percent percent-sign font-sm">76</span>
</div>
</li>
<li>
<div className="easy-pie-chart txt-color-blue easyPieChart" data-percent="86"
data-pie-size="35">
<span className="percent percent-sign font-xs">86</span>
</div>
</li>
</ul>
</div>
</EasyPieChartContainer>
</div>
</div>
) |
app/js/containers/CircleContainer.js | sgt39007/waji_redux | import React from 'react';
import {
Container,
List,
Group,
View,
} from 'amazeui-touch';
import {
Link,
} from 'react-router';
import { connect } from 'react-redux';
import * as AppActions from '../redux/actions/AppActions';
import { Login } from '../components';
class CircleContainer extends React.Component {
componentWillMount() {
const { dispatch } = this.props;
dispatch(AppActions.hideTabbar(false));
dispatch(AppActions.hideNavLeft(true));
dispatch(AppActions.setNavTitle('世界圈'));
}
renderItems() {
const { login, dispatch } = this.props;
if (login.loadState.success) {
// 如果登录 -> Circle -> CircleDetail
return (
<Group noPadded>
<List>
<List.Item
linkComponent={Link}
linkProps={{to: {pathname: '/circle/world'}}}
title="世界圈"
key="sj"
/>
<List.Item
linkComponent={Link}
linkProps={{to: {pathname: '/circle/friend'}}}
title="朋友圈"
key="py"
/>
</List>
</Group>
);
} else {
// 没登录-> login的内容
return (
<Login dispatch={dispatch}/>
);
}
}
render() {
return (
<View>
<Container scrollable>
{this.renderItems()}
</Container>
</View>
);
}
}
function mapStateToProps(state) {
return {
login: state.login
}
}
export default connect(mapStateToProps)(CircleContainer)
|
web/src/server/components/charts/time-vs-commits-chart.js | opendaylight/spectrometer | /**
# @License EPL-1.0 <http://spdx.org/licenses/EPL-1.0>
##############################################################################
# Copyright (c) 2016 The Linux Foundation and others.
#
# All rights reserved. This program and the accompanying materials
# are made available under the terms of the Eclipse Public License v1.0
# which accompanies this distribution, and is available at
# http://www.eclipse.org/legal/epl-v10.html
##############################################################################
*/
/**
* React component to display Timeline of Commits chart
* Used in TimelineCard
* Uses ChartLayout
*
* @author: Vasu Srinivasan
* @since: 0.0.1
*/
import React, { Component } from 'react';
import ReactHighcharts from 'react-highcharts'
import * as DataReducers from '../../api/data-reducers'
import ChartLayout from '../chart-layout'
const buttonActions = [
{type: 'chartType', option: 'line', icon: 'multiline_chart', tooltip: 'Area chart'}
]
const lineChart = (dataSeries) => {
const config = {
chart: { type: 'line' },
title: { text: '' },
xAxis: [{ title: { text: 'Time' }, categories: _.map(dataSeries, "name") }],
yAxis: [{ title: { text: 'Commits' }}, { title: { text: 'LoC Modified' }, opposite: true}],
series: [
{ name: 'Commits', type: 'area', data: _.map(dataSeries, "commitCount") },
{ name: 'LoC Modified', type: 'spline', yAxis: 1, data: _.map(dataSeries, "loc") }
],
tooltip: {
pointFormat: '{series.name}: {point.y}'
},
plotOptions: {
line: {
allowPointSelect: true, cursor: 'pointer',
dataLabels: { enabled: true },
enableMouseTracking: false
}
}
}
return (<ReactHighcharts config={config} />)
}
export default class TimeVsCommitsChart extends Component {
constructor(props) {
super(props)
this.state = {
view: _.assign({}, DEFAULT_VIEW, props.view)
}
this.handleButtonActions = this.handleButtonActions.bind(this)
}
handleButtonActions = (type, value) => {
const newView = _.merge(this.state.view, {[type]: value})
this.setState({ view: newView })
}
render() {
if (_.isEmpty(this.props.projects)) return null;
logger.info("time-vs-commits-chart:render", this.state.view)
const { name, ref1, ref2, author } = this.state.view
const dataSeries = DataReducers.timeVsCommitCount(this.props.projects, {name, ref1, ref2, author, sortBy: 'x'})
return (
<ChartLayout id="time-vs-loc-chart" title="Commits by Timeline"
buttonActions={buttonActions} currentView={this.state.view}
handleButtonActions={this.handleButtonActions}>
{lineChart(dataSeries)}
</ChartLayout>
)
}
}
const DEFAULT_VIEW = {
chartType: 'line',
sortBy: 'x'
}
TimeVsCommitsChart.propTypes = {
projects: React.PropTypes.array,
view: React.PropTypes.object
}
|
src/js/view/DrawerLists.js | yoichiro/chromeos-filesystem-sftp | import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from '@material-ui/core/styles';
import classNames from 'classnames';
import Drawer from '@material-ui/core/Drawer';
import IconButton from '@material-ui/core/IconButton'
import List from '@material-ui/core/List';
import ListSubheader from '@material-ui/core/ListSubheader';
import FavoritesItem from './FavoritesItem';
import ChevronLeftIcon from '@material-ui/icons/ChevronRight';
import Divider from '@material-ui/core/Divider';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import Switch from '@material-ui/core/Switch';
const drawerWidth = 240;
const styles = theme => ({
drawerPaper: {
position: 'relative',
height: '100%',
width: drawerWidth,
},
drawerHeader: {
display: 'flex',
alignItems: 'center',
justifyContent: 'flex-end',
padding: '0 8px',
...theme.mixins.toolbar,
},
list: {
width: '100%',
maxWidth: 360,
backgroundColor: theme.palette.background.paper,
},
nested: {
paddingLeft: theme.spacing.unit * 4,
},
hide: {
visibility: 'hidden',
}
});
class FavoritesList extends React.Component {
render() {
const { classes, favorites, open, selectedFavorite='', keepCredentials=false,
onToggleDrawer, onShowFavorite, onRemoveFavorite, onToggleKeepCredentials } = this.props;
// Generate list items, based on the items within
// the favorites array in the state of the main app
const items = favorites.map((favorite) =>
<FavoritesItem
key={favorite.key}
favorite={favorite}
selected={selectedFavorite===favorite.key}
onShowFavorite={onShowFavorite}
onRemoveFavorite={onRemoveFavorite}
/>
);
const noItems = (
<ListItem dense disabled>
<ListItemText primary={chrome.i18n.getMessage("noFavorites")} />
</ListItem>
);
return (
<Drawer
variant="persistent"
anchor="right"
className={classNames(!open && classes.hide)}
classes={{
paper: classes.drawerPaper,
}}
open={open}>
<div className={classes.drawerInner}>
<div className={classes.drawerHeader}>
<IconButton onClick={onToggleDrawer}>
<ChevronLeftIcon />
</IconButton>
</div>
<Divider />
<div className={classes.list}>
<List
component="nav"
subheader={<ListSubheader component="div">{chrome.i18n.getMessage("favorites")}</ListSubheader>}>
{items.length > 0 ? items : noItems}
</List>
<List
component="nav"
subheader={<ListSubheader component="div">{chrome.i18n.getMessage("settings")}</ListSubheader>}>
<ListItem dense>
<ListItemText primary={chrome.i18n.getMessage("storeCredentials")} />
<ListItemSecondaryAction>
<Switch
onClick={onToggleKeepCredentials}
checked={keepCredentials}
/>
</ListItemSecondaryAction>
</ListItem>
</List>
</div>
</div>
</Drawer>
);
}
}
FavoritesList.propTypes = {
classes: PropTypes.object.isRequired,
favorites: PropTypes.array.isRequired,
open: PropTypes.bool.isRequired,
selectedFavorite: PropTypes.string,
keepCredentials: PropTypes.bool,
onToggleDrawer: PropTypes.func.isRequired,
onShowFavorite: PropTypes.func.isRequired,
onRemoveFavorite: PropTypes.func.isRequired,
onToggleKeepCredentials: PropTypes.func.isRequired
};
export default withStyles(styles)(FavoritesList); |
admin/client/components/Toolbar.js | codevlabs/keystone | import React from 'react';
import { Container } from 'elemental';
module.exports = React.createClass({
displayName: 'Toolbar',
render () {
return (
<div {...this.props} className="Toolbar">
<Container clearfix >
{this.props.children}
</Container>
</div>
);
}
});
// expose the children to the top level export
module.exports.Section = require('./ToolbarSection');
|
webpack/components/surveys/SurveyEdit.js | CDCgov/SDP-Vocabulary-Service | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router';
import { Row, Col, Button } from 'react-bootstrap';
import TagsInput from 'react-tagsinput';
import { surveyProps } from '../../prop-types/survey_props';
import { sectionsProps } from '../../prop-types/section_props';
import { surveillanceSystemsProps } from '../../prop-types/surveillance_system_props';
import { surveillanceProgramsProps } from '../../prop-types/surveillance_program_props';
import { questionsProps } from "../../prop-types/question_props";
import currentUserProps from "../../prop-types/current_user_props";
import SurveySectionList from './SurveySectionList';
import CodedSetTableEditContainer from '../../containers/CodedSetTableEditContainer';
import Errors from '../Errors';
import ModalDialog from '../ModalDialog';
import InfoModal from '../InfoModal';
import ProgSysEditModal from './ProgSysEditModal';
class SurveyEdit extends Component {
stateForNew(currentUser) {
return {
id: null,
comment: '',
name: '',
version: 1,
conceptsAttributes: [],
tagList: [],
description: '',
surveySections: [],
controlNumber: null,
ombApprovalDate : '',
versionIndependentId: null,
showModal: false,
showInfo: false,
showInfoOMBApproval: false,
showInfoTags: false,
showInfoProgram: false,
showInfoSystem: false,
showInfoSelectedSections: false,
showInfoSearchandSelectSections: false,
progSysModalOpen: false,
surveillanceProgramId: currentUser.lastProgramId || null,
surveillanceSystemId: currentUser.lastSystemId || null
};
}
stateForExtend(survey, currentUser) {
var state = this.stateForEdit(survey, currentUser);
state.id = null;
state.versionIndependentId = null;
state.version = 1;
state.parentId = survey.id;
state.controlNumber = '';
state.ombApprovalDate = '';
state.groups = [];
return state;
}
stateForEdit(survey, currentUser) {
var newState = this.stateForNew(currentUser);
newState.id = survey.id;
newState.name = survey.name || '';
newState.version = survey.version;
newState.description = survey.description || '';
newState.surveySections = survey.surveySections || [];
newState.controlNumber = survey.controlNumber;
newState.ombApprovalDate = survey.ombApprovalDate;
newState.parentId = survey.parent ? survey.parent.id : '';
newState.surveillanceProgramId = survey.surveillanceProgramId || newState.surveillanceProgramId;
newState.surveillanceSystemId = survey.surveillanceSystemId || newState.surveillanceSystemId;
newState.versionIndependentId = survey.versionIndependentId;
newState.conceptsAttributes = filterConcepts(survey.concepts);
newState.tagList = survey.tagList || [];
newState.groups = survey.groups || [];
return newState;
}
stateForRevise(survey, currentUser) {
var newState = this.stateForEdit(survey, currentUser);
newState.version += 1;
return newState;
}
constructor(props) {
super(props);
switch (this.props.action) {
case 'revise':
this.state = this.stateForRevise(props.survey, props.currentUser);
break;
case 'extend':
this.state = this.stateForExtend(props.survey, props.currentUser);
break;
case 'edit':
this.state = this.stateForEdit(props.survey, props.currentUser);
break;
default:
this.state = this.stateForNew(props.currentUser);
}
this.unsavedState = false;
this.associationChanges = {};
this.lastSectionCount = this.state.surveySections.length;
this.handleTagChange = this.handleTagChange.bind(this);
}
componentDidMount() {
this.unbindHook = this.props.router.setRouteLeaveHook(this.props.route, this.routerWillLeave.bind(this));
window.onbeforeunload = this.windowWillUnload.bind(this);
if(this.props.sections && !this.associationChanges['sections']) {
this.associationChanges['sections'] = {original: this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.id, name: ssName};
}), updated: this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.sectionId, name: ssName};
})};
}
}
componentDidUpdate(prevProps, prevState) {
if(this.lastSectionCount !== prevState.surveySections.length) {
this.unsavedState = true;
if (this.associationChanges['sections']) {
this.associationChanges['sections']['updated'] = this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.sectionId, name: ssName};
});
} else {
this.associationChanges['sections'] = {original: prevState.surveySections.map((ss) => {
let ssName = prevProps.sections[ss.sectionId].name || '';
return {id: ss.id, name: ssName};
}), updated: this.state.surveySections.map((ss) => {
let ssName = this.props.sections[ss.sectionId].name || '';
return {id: ss.sectionId, name: ssName};
})};
}
this.lastSectionCount = prevState.surveySections.length;
}
}
componentWillUnmount() {
this.unsavedState = false;
this.associationChanges = {};
this.unbindHook();
}
routerWillLeave(nextLocation) {
this.setState({ showModal: this.unsavedState });
this.nextLocation = nextLocation;
return !this.unsavedState;
}
handleConceptsChange(newConcepts) {
if (this.associationChanges['mappings']) {
this.associationChanges['mappings']['updated'] = newConcepts;
} else {
this.associationChanges['mappings'] = {original: this.state.conceptsAttributes, updated: newConcepts};
}
this.setState({conceptsAttributes: filterConcepts(newConcepts)});
this.unsavedState = true;
}
handleTagChange(tagList) {
this.setState({tagList});
this.unsavedState = true;
}
handleModalResponse(leavePage){
this.setState({ showModal: false });
if(leavePage){
this.unsavedState = false;
this.associationChanges = {};
this.props.router.push(this.nextLocation.pathname);
}else{
let survey = Object.assign({}, this.state);
// Because we were saving SurveySections with null positions for a while, we need to explicitly set position here to avoid sending a null position back to the server
// At some point, we can remove this code
survey.linkedSections = this.state.surveySections.map((sect, i) => ({id: sect.id, surveyId: sect.surveyId, sectionId: sect.sectionId, position: i}));
this.props.surveySubmitter(survey, this.state.comment, this.unsavedState, this.associationChanges, (response) => {
// TODO: Handle when the saving survey fails.
this.unsavedState = false;
this.associationChanges = {};
if (response.status === 201) {
this.props.router.push(this.nextLocation.pathname);
}
});
}
}
windowWillUnload() {
return (this.unsavedState || null);
}
handleChange(field) {
return (event) => {
let newState = {};
newState[field] = event.target.value;
this.setState(newState);
this.unsavedState = true;
};
}
handleSubmit(event) {
event.preventDefault();
// Because of the way we have to pass the current sections in we have to manually sync props and state for submit
let survey = Object.assign({}, this.state);
survey.linkedSections = this.state.surveySections;
this.props.surveySubmitter(survey, this.state.comment, this.unsavedState, this.associationChanges, (response) => {
this.unsavedState = false;
this.associationChanges = {};
if (this.props.action === 'new') {
let stats = Object.assign({}, this.props.stats);
stats.surveyCount = this.props.stats.surveyCount + 1;
stats.mySurveyCount = this.props.stats.mySurveyCount + 1;
this.props.setStats(stats);
}
this.props.router.push(`/surveys/${response.data.id}`);
}, (failureResponse) => {
this.setState({errors: failureResponse.response.data});
});
}
cancelButton() {
if(this.props.survey && this.props.survey.id) {
return(<Link tabIndex="3" className="btn btn-default pull-right" to={`/surveys/${this.props.survey.id}`}>Cancel</Link>);
}
return(<Link tabIndex="3" className="btn btn-default pull-right" to='/'>Cancel</Link>);
}
render() {
if(!this.props.sections){
return ('Loading');
}
return (
<Col md={7} className="survey-edit-details">
<div id='survey-div'>
<ModalDialog show ={this.state.showModal}
title="Warning"
subTitle="Unsaved Changes"
warning ={true}
message ="You are about to leave a page with unsaved changes. How would you like to proceed?"
secondaryButtonMessage="Continue Without Saving"
primaryButtonMessage="Save & Leave"
cancelButtonMessage="Cancel"
primaryButtonAction={() => this.handleModalResponse(false)}
cancelButtonAction ={() => {
this.props.router.push(this.props.route.path);
this.setState({ showModal: false });
}}
secondaryButtonAction={() => this.handleModalResponse(true)} />
<form onSubmit={(e) => this.handleSubmit(e)}>
<Errors errors={this.state.errors} />
<div className="survey-inline">
<input tabIndex="3" className='btn btn-default pull-right' name="Save Survey" type="submit" value={`Save`}/>
{this.cancelButton()}
</div>
<br/>
<hr />
<div className="survey-group">
<label htmlFor="survey-name">Survey Name</label>
<input tabIndex="3" className="input-format" placeholder="Survey Name" type="text" value={this.state.name} name="survey-name" id="survey-name" onChange={this.handleChange('name')}/>
</div>
<Row>
<Col md={8} className="survey-group">
<label htmlFor="survey-description">Description</label>
<input tabIndex="3" className="input-format" placeholder="Enter a description here..." type="text" value={this.state.description || ''} name="survey-description" id="survey-description" onChange={this.handleChange('description')}/>
</Col>
<Col md={4} className="survey-group">
<InfoModal show={this.state.showInfoOMBApproval} header="OMB Approval" body={<p>Provide the OMB Control Number associated with this data collection instrument (if applicable). <br/><br/>This attribute is optional but completion allows other users to find vocabulary that has been used on an OMB-approved data collection instrument. Reuse of vocabulary that has been part of one or more OMB approved Paperwork Reduction Act (PRA) packages in the past can help expedite the review process. There is an advanced search filter that is based off of this attribute.
</p>} hideInfo={()=>this.setState({showInfoOMBApproval: false})} />
<label htmlFor="controlNumber">OMB Approval<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoOMBApproval: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<input tabIndex="3" className="input-format" placeholder="XXXX-XXXX" type="text" value={this.state.controlNumber || ''} name="controlNumber" id="controlNumber" onChange={this.handleChange('controlNumber')}/>
{ this.state.controlNumber !== '' && this.state.controlNumber !== null &&
<div>
<br/>
<label htmlFor="ombApprovalDate">OMB Approval Date</label>
<input tabIndex="3" className="input-format" type="date" placeholder="mm/dd/yyyy" value={this.state.ombApprovalDate || ''} name ="ombApprovalDate" id="ombApprovalDate" onChange={this.handleChange('ombApprovalDate')}/>
</div>
}
</Col>
</Row>
<Row>
<Col md={12} className="survey-group">
<InfoModal show={this.state.showInfoTags} header="Tags" body={<p>Tags are text strings that are either keywords or short phrases created by users to facilitate content discovery, organization, and reuse. Tags are weighted in the dashboard search result algorithm so users are presented with search results that have been tagged with the same keyword(s) entered in the dashboard search bar. <br/><br/>Keyword tags can be changed (added or deleted) at any time by the author(s) to meet user needs and to optimize search results. The history of tags is not saved on the change history tab; tags are not versioned.</p>} hideInfo={()=>this.setState({showInfoTags: false})} />
<label className="input-label" htmlFor="survey-tags">Tags<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoTags: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<p>Press 'Tab' or 'Enter' after typing a tag to add it to the list. Press 'Backspace' or click the 'x' icon to remove a tag.</p>
<TagsInput value={this.state.tagList} onChange={this.handleTagChange} inputProps={{tabIndex: '3', id: 'survey-tags'}} />
</Col>
</Row>
<Row>
<ProgSysEditModal closer={() => this.setState({progSysModalOpen: false})}
show={this.state.progSysModalOpen}
update={(sid, pid) => this.setState({surveillanceSystemId: sid, surveillanceProgramId: pid, progSysModalOpen: false})}
programId={this.state.surveillanceProgramId}
systemId={this.state.surveillanceSystemId}
currentUser={this.props.currentUser}
surveillanceSystems={this.props.surveillanceSystems}
surveillancePrograms={this.props.surveillancePrograms} />
<Col md={6} className="survey-group">
<InfoModal show={this.state.showInfoProgram} header="Program" body={<p>Identify the program that will maintain and use this vocabulary to support public health activities.<br/><br/>The default value is populated from the author’s profile. The value can be changed by selecting the pencil icon.</p>} hideInfo={()=>this.setState({showInfoProgram: false})} />
<label htmlFor="program"><strong>Program</strong><Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoProgram: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button>:</label>
<a className="tag-modal-link" href="#" onClick={(e) => {
e.preventDefault();
this.setState({ progSysModalOpen: true });
}}> {this.props.surveillancePrograms && this.props.surveillancePrograms[this.state.surveillanceProgramId] && this.props.surveillancePrograms[this.state.surveillanceProgramId].name} <i className="fa fa-pencil-square-o" aria-hidden="true"><text className='sr-only'>Click to edit program</text></i></a>
</Col>
<Col md={6} className="survey-group">
<InfoModal show={this.state.showInfoSystem} header="System" body={<p>Identify the surveillance system that will use this vocabulary to support public health activities.<br/><br/>The default value is populated from the author’s profile. The value can be changed by selecting the pencil icon.</p>} hideInfo={()=>this.setState({showInfoSystem: false})} />
<label htmlFor="system"><strong>System</strong><Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoSystem: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button>: </label>
<a className="tag-modal-link" href="#" onClick={(e) => {
e.preventDefault();
this.setState({ progSysModalOpen: true });
}}> {this.props.surveillanceSystems && this.props.surveillanceSystems[this.state.surveillanceSystemId] && this.props.surveillanceSystems[this.state.surveillanceSystemId].name} <i className="fa fa-pencil-square-o" aria-hidden="true"><text className='sr-only'>Click to edit system</text></i></a>
</Col>
</Row>
<h2 className="code-system-mappings-table-header"><strong>Code System Mappings</strong></h2>
<CodedSetTableEditContainer itemWatcher={(r) => this.handleConceptsChange(r)}
initialItems={this.state.conceptsAttributes}
parentName={'survey'}
childName={'Code System Mapping'} />
{this.props.action === 'edit' && <div className="survey-group">
<label htmlFor="save-with-comment">Notes / Comments About Changes Made (Optional)</label>
<textarea className="input-format" tabIndex="3" placeholder="Add notes about the changes here..." type="text" value={this.state.comment || ''} name="save-with-comment" id="save-with-comment" onChange={this.handleChange('comment')}/>
</div>}
<br/>
<InfoModal show={this.state.showInfoSelectedSections} header="Selected Sections" body={<p>The “Selected Sections” panel displays the selected Sections for this Survey.</p>} hideInfo={()=>this.setState({showInfoSelectedSections: false})} />
<label className="pull-left">Selected Sections<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfoSelectedSections: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<InfoModal show={this.state.showInfo} header="Position" body="This column displays the order of the sections. To change position, enter the desired position and hit the 'Enter' key on your keyboard." hideInfo={()=>this.setState({showInfo: false})} />
<label className="pull-right">Position<Button bsStyle='link' style={{ padding: 3 }} onClick={() => this.setState({showInfo: true})}><i className="fa fa-info-circle" aria-hidden="true"></i><text className="sr-only">Click for info about this item</text></Button></label>
<br/>
<SurveySectionList survey={this.state}
sections ={this.props.sections}
questions ={this.props.questions}
reorderSection={this.props.reorderSection}
removeSection ={this.props.removeSection} />
</form>
</div>
</Col>
);
}
}
function filterConcepts(concepts) {
if(!concepts){
return [];
}
return concepts.filter((nc) => {
return (nc.value !=='' || nc.codeSystem !== '' || nc.displayName !=='');
}).map((nc) => {
return {value: nc.value, codeSystem: nc.codeSystem, displayName: nc.displayName};
});
}
SurveyEdit.propTypes = {
survey: surveyProps,
currentUser: currentUserProps,
surveillanceSystems: surveillanceSystemsProps,
surveillancePrograms: surveillanceProgramsProps,
sections: sectionsProps.isRequired,
questions: questionsProps.isRequired,
action: PropTypes.string.isRequired,
setStats: PropTypes.func,
stats: PropTypes.object,
surveySubmitter: PropTypes.func.isRequired,
removeSection: PropTypes.func.isRequired,
reorderSection: PropTypes.func.isRequired,
route: PropTypes.object.isRequired,
router: PropTypes.object.isRequired
};
export default SurveyEdit;
|
wrappers/md.js | adjohnson916/site-gatsby | import React from 'react'
import 'css/markdown-styles.css'
module.exports = React.createClass({
propTypes () {
return {
router: React.PropTypes.object,
}
},
render () {
const post = this.props.route.page.data
return (
<div className="markdown">
<h1>{post.title}</h1>
<div dangerouslySetInnerHTML={{ __html: post.body }} />
</div>
)
},
})
|
src/modules/CardsGrid.js | maizy/kanbanrum-cards | /**
* Copyright (c) Nikita Kovaliov, maizy.ru, 2017
* See LICENSE.txt for details.
*/
import React from 'react';
import SmallCard from './SmallCard';
function CardsGrid(props) {
const cards = props.cards.map(card => <SmallCard card={card} key={card.get('id')} />);
return (
<div>
<h1>Kanbanrum™ Cards</h1>
<div className="cards-grid">
{cards}
</div>
</div>
);
}
CardsGrid.propTypes = {
// FIXME: immutable list
cards: React.PropTypes.object,
};
export default CardsGrid;
|
src/svg-icons/communication/voicemail.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationVoicemail = (props) => (
<SvgIcon {...props}>
<path d="M18.5 6C15.46 6 13 8.46 13 11.5c0 1.33.47 2.55 1.26 3.5H9.74c.79-.95 1.26-2.17 1.26-3.5C11 8.46 8.54 6 5.5 6S0 8.46 0 11.5 2.46 17 5.5 17h13c3.04 0 5.5-2.46 5.5-5.5S21.54 6 18.5 6zm-13 9C3.57 15 2 13.43 2 11.5S3.57 8 5.5 8 9 9.57 9 11.5 7.43 15 5.5 15zm13 0c-1.93 0-3.5-1.57-3.5-3.5S16.57 8 18.5 8 22 9.57 22 11.5 20.43 15 18.5 15z"/>
</SvgIcon>
);
CommunicationVoicemail = pure(CommunicationVoicemail);
CommunicationVoicemail.displayName = 'CommunicationVoicemail';
export default CommunicationVoicemail;
|
packages/material-ui-icons/src/Landscape.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z" /></g>
, 'Landscape');
|
project/react-redux/src/pages/index/index.js | FFF-team/generator-earth | // //import base&&tools
import 'whatwg-fetch'
import 'scss_mixin/reset.scss' //reset 样式
import 'tools/polyfill'
import React from 'react'
import ReactDOM from 'react-dom'
import store from './store/index'
import {Provider} from 'react-redux'
import {
HashRouter as Router,
} from 'react-router-dom'
// import containers
import App from './containers/App'
import MainRouter from './containers/MainRouter'
const rootElement = document.getElementById('root');
ReactDOM.render(
<Provider store={store}>
<Router>
<div>
<App/>
<MainRouter/>
</div>
</Router>
</Provider>,
rootElement
)
|
src/Parser/Rogue/Common/Resources/EnergyDetails.js | hasseboulen/WoWAnalyzer | import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Tab from 'Main/Tab';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Icon from 'common/Icon';
import ResourceBreakdown from 'Parser/Core/Modules/ResourceTracker/ResourceBreakdown';
import EnergyTracker from './EnergyTracker';
class EnergyDetails extends Analyzer {
static dependencies = {
energyTracker: EnergyTracker,
};
statistic() {
const energyWasted = this.energyTracker.wasted;
const pointsWastedPerMinute = (energyWasted / this.owner.fightDuration) * 1000 * 60;
return (
<StatisticBox
icon={<Icon icon="ability_warrior_decisivestrike" alt="Waisted Energy" />}
value={`${pointsWastedPerMinute.toFixed(2)}`}
label="Wasted Energy per minute"
tooltip={`You wasted a total of ${energyWasted} energy. Some waste is expected due to the random nature of some generation abilities.`}
/>
);
}
tab() {
return {
title: 'Energy usage',
url: 'energy-usage',
render: () => (
<Tab title="Energy usage breakdown">
<ResourceBreakdown
tracker={this.energyTracker}
/>
</Tab>
),
};
}
statisticOrder = STATISTIC_ORDER.CORE(5);
}
export default EnergyDetails;
|
blueocean-material-icons/src/js/components/svg-icons/maps/directions-transit.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsDirectionsTransit = (props) => (
<SvgIcon {...props}>
<path d="M12 2c-4.42 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h12v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zM7.5 17c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm3.5-6H6V6h5v5zm5.5 6c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm1.5-6h-5V6h5v5z"/>
</SvgIcon>
);
MapsDirectionsTransit.displayName = 'MapsDirectionsTransit';
MapsDirectionsTransit.muiName = 'SvgIcon';
export default MapsDirectionsTransit;
|
app/components/team/Show.js | buildkite/frontend | import React from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import DocumentTitle from 'react-document-title';
import PageHeader from 'app/components/shared/PageHeader';
import Emojify from 'app/components/shared/Emojify';
import permissions from 'app/lib/permissions';
import TabControl from 'app/components/shared/TabControl';
import TeamLabels from './Labels';
import Pipelines from './Pipelines';
import Members from './Members';
class TeamShow extends React.Component {
static propTypes = {
team: PropTypes.shape({
name: PropTypes.string.isRequired,
description: PropTypes.string,
slug: PropTypes.string.isRequired,
members: PropTypes.shape({
count: PropTypes.number
}).isRequired,
pipelines: PropTypes.shape({
count: PropTypes.number
}).isRequired,
organization: PropTypes.shape({
name: PropTypes.string.isRequired,
slug: PropTypes.string.isRequired
}).isRequired,
permissions: PropTypes.shape({
teamUpdate: PropTypes.object.isRequired
}).isRequired
}),
children: PropTypes.node.isRequired
};
static contextTypes = {
router: PropTypes.object.isRequired
};
state = {
removing: false,
selectedTab: 0
};
render() {
// If the team doesn't exist, that means that it's just been deleted. And
// since we require all the team to render this component, we'll just
// short-circut the re-render when it's gone. This isn't great, maybe
// there's a beter way?
if (!this.props.team) {
return null;
}
return (
<DocumentTitle title={`${this.props.team.name} · ${this.props.team.organization.name} Team`}>
<div>
<PageHeader followedByTabs={true}>
<div className="flex items-center">
<h1 className="h1 m0 p0 block"><Emojify text={this.props.team.name} /></h1>
<TeamLabels team={this.props.team} />
</div>
<PageHeader.Description><Emojify text={this.props.team.description || "No description"} /></PageHeader.Description>
</PageHeader>
{this.renderTabs()}
{this.props.children}
</div>
</DocumentTitle>
);
}
renderTabs() {
const tabContent = permissions(this.props.team.permissions).collect(
{
always: true,
render: (idx) => (
<TabControl.Tab
key={idx}
to={`/organizations/${this.props.team.organization.slug}/teams/${this.props.team.slug}/members`}
badge={this.props.team.members.count}
>
Members
</TabControl.Tab>
)
},
{
always: true,
render: (idx) => (
<TabControl.Tab
key={idx}
to={`/organizations/${this.props.team.organization.slug}/teams/${this.props.team.slug}/pipelines`}
badge={this.props.team.pipelines.count}
>
Pipelines
</TabControl.Tab>
)
},
{
allowed: "teamUpdate",
render: (idx) => (
<TabControl.Tab
key={idx}
to={`/organizations/${this.props.team.organization.slug}/teams/${this.props.team.slug}/settings`}
>
Settings
</TabControl.Tab>
)
}
);
return (
<TabControl>
{tabContent}
</TabControl>
);
}
}
export default Relay.createContainer(TeamShow, {
fragments: {
team: () => Relay.QL`
fragment on Team {
${Pipelines.getFragment('team')}
${Members.getFragment('team')}
members {
count
}
pipelines {
count
}
name
description
slug
${TeamLabels.getFragment('team')}
organization {
name
slug
}
permissions {
teamUpdate {
allowed
}
}
}
`
}
});
|
curator-web/src/js/components/frame/header.js | rajeshnaroth/curator | import React from 'react'
import { Link } from 'react-router'
const Header = () => (
<nav className="navbar navbar-default navbar-fixed-top">
<section className="userMenu">
<li><Link to='/curate'><span>Curate</span></Link></li>
</section>
<Link to='/'><h1>Tube2Flix</h1></Link>
</nav>
)
export default Header |
components/GameGrid.js | turntwogg/esports-aggregator | import React from 'react';
import Link from 'next/link';
import LazyLoad from 'react-lazyload';
import idx from 'idx';
import { useTheme } from '@turntwo/react-ui';
import Heading from './Heading';
import CornerBox from './CornerBox';
import api from '../utils/api';
const GameCard = ({ game }) => {
const image = idx(game, _ => _.fieldGameTeaserImage.attributes.url);
return (
<div className="game-card">
<Link
href={`/game?slug=${game.attributes.field_game_slug}`}
as={`/games/${game.attributes.field_game_slug}`}
>
<a className="game-card__main-link">
<LazyLoad height={233} offset={100}>
<img alt={game.attributes.name} src={`${api.formatImg(image)}`} />
</LazyLoad>
<Heading element="h4" className="game-card__title" center>
{game.attributes.name}
</Heading>
</a>
</Link>
<style jsx>{`
.game-card {
max-width: 100%;
}
.game-card__main-link {
position: relative;
display: flex;
flex: 1 1 auto;
flex-flow: column nowrap;
background-color: rgba(0, 0, 0, 0.7);
}
:global(.game-card__title) {
position: absolute;
bottom: 24px;
left: 0;
width: 100%;
margin-bottom: 0;
color: #fff;
font-size: 16px;
font-weight: 700;
line-height: 1.2;
text-align: center;
text-transform: uppercase;
}
`}</style>
</div>
);
};
const GameGrid = ({ games }) => {
const theme = useTheme();
const homeGames = games.data.filter(
game => game.attributes.field_game_home_grid,
);
return (
<div className="game-grid">
{homeGames.map(game => (
<div className="game-grid__item" key={game.id}>
<GameCard game={game} />
</div>
))}
<div className="game-grid__item">
<CornerBox>
<Link href="/games">
<a>See all games</a>
</Link>
</CornerBox>
</div>
<style jsx>{`
.game-grid {
display: grid;
grid-template-columns: 1fr 1fr;
max-width: 750px;
margin: auto;
}
.game-grid__item:last-child {
display: flex;
flex-flow: column;
padding: 16px;
background: linear-gradient(
45deg,
rgba(4, 19, 59, 1) 0%,
rgba(113, 2, 68, 1) 100%
);
}
.game-grid__item:last-child > :global(div) {
display: flex;
flex: 1 auto;
}
.game-grid__item:last-child a {
margin: auto;
color: #fff;
font-size: 16px;
font-weight: 700;
text-transform: uppercase;
}
@media (max-width: ${theme.breakpoints.m + 1}px) {
.game-grid__item:last-child {
grid-column: 1 / span 2;
}
}
@media (min-width: ${theme.breakpoints.m}px) {
.game-grid {
grid-template-columns: 1fr 1fr 1fr;
}
}
`}</style>
</div>
);
};
export default GameGrid;
|
app/javascript/mastodon/features/status/index.js | anon5r/mastonon | 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 { 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,
reblog,
unreblog,
pin,
unpin,
} from '../../actions/interactions';
import {
replyCompose,
mentionCompose,
directCompose,
} from '../../actions/compose';
import { blockAccount } from '../../actions/accounts';
import {
muteStatus,
unmuteStatus,
deleteStatus,
hideStatus,
revealStatus,
} from '../../actions/statuses';
import { initMuteModal } from '../../actions/mutes';
import { initReport } from '../../actions/reports';
import { makeGetStatus } from '../../selectors';
import { ScrollContainer } from 'react-router-scroll-4';
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 '../../features/ui/util/fullscreen';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
revealAll: { id: 'status.show_more_all', defaultMessage: 'Show more for all' },
hideAll: { id: 'status.show_less_all', defaultMessage: 'Show less for all' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => {
const status = getStatus(state, props.params.statusId);
let ancestorsIds = Immutable.List();
let descendantsIds = Immutable.List();
if (status) {
ancestorsIds = ancestorsIds.withMutations(mutable => {
let id = status.get('in_reply_to_id');
while (id) {
mutable.unshift(id);
id = state.getIn(['contexts', 'inReplyTos', id]);
}
});
descendantsIds = descendantsIds.withMutations(mutable => {
const ids = [status.get('id')];
while (ids.length > 0) {
let id = ids.shift();
const replies = state.getIn(['contexts', 'replies', id]);
if (replies) {
replies.forEach(reply => {
mutable.push(reply);
ids.unshift(reply);
});
}
}
});
}
return {
status,
ancestorsIds,
descendantsIds,
};
};
return mapStateToProps;
};
@injectIntl
@connect(makeMapStateToProps)
export default 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,
};
state = {
fullscreen: false,
};
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));
}
}
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) => {
this.props.dispatch(replyCompose(status, this.context.router.history));
}
handleModalReblog = (status) => {
this.props.dispatch(reblog(status));
}
handleReblogClick = (status, e) => {
if (status.get('reblogged')) {
this.props.dispatch(unreblog(status));
} else {
if (e.shiftKey || !boostModal) {
this.handleModalReblog(status);
} else {
this.props.dispatch(openModal('BOOST', { status, onReblog: this.handleModalReblog }));
}
}
}
handleDeleteClick = (status) => {
const { dispatch, intl } = this.props;
if (!deleteModal) {
dispatch(deleteStatus(status.get('id')));
} else {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.deleteMessage),
confirm: intl.formatMessage(messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'))),
}));
}
}
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', { media, index }));
}
handleOpenVideo = (media, time) => {
this.props.dispatch(openModal('VIDEO', { media, time }));
}
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')));
}
}
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 = (account) => {
const { dispatch, intl } = this.props;
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
}
handleReport = (status) => {
this.props.dispatch(initReport(status.get('account'), status));
}
handleEmbed = (status) => {
this.props.dispatch(openModal('EMBED', { url: status.get('url') }));
}
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);
}
handleHotkeyOpenProfile = () => {
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
handleHotkeyToggleHidden = () => {
this.handleToggleHidden(this.props.status);
}
handleMoveUp = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size - 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index);
} else {
this._selectChild(index - 1);
}
}
}
handleMoveDown = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size + 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index + 2);
} else {
this._selectChild(index + 1);
}
}
}
_selectChild (index) {
const element = this.node.querySelectorAll('.focusable')[index];
if (element) {
element.focus();
}
}
renderChildren (list) {
return list.map(id => (
<StatusContainer
key={id}
id={id}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
/>
));
}
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];
element.scrollIntoView(true);
this._scrolledIntoView = true;
}
}
componentWillUnmount () {
detachFullscreenListener(this.onFullScreenChange);
}
onFullScreenChange = () => {
this.setState({ fullscreen: isFullscreen() });
}
render () {
let ancestors, descendants;
const { status, ancestorsIds, descendantsIds, intl } = this.props;
const { fullscreen } = this.state;
if (status === null) {
return (
<Column>
<ColumnBackButton />
<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,
};
return (
<Column>
<ColumnHeader
showBackButton
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'}><i className={`fa fa-${status.get('hidden') ? 'eye-slash' : 'eye'}`} /></button>
)}
/>
<ScrollContainer scrollKey='thread'>
<div className={classNames('scrollable', 'detailed-status__wrapper', { fullscreen })} ref={this.setRef}>
{ancestors}
<HotKeys handlers={handlers}>
<div className='focusable' tabIndex='0'>
<DetailedStatus
status={status}
onOpenVideo={this.handleOpenVideo}
onOpenMedia={this.handleOpenMedia}
onToggleHidden={this.handleToggleHidden}
/>
<ActionBar
status={status}
onReply={this.handleReplyClick}
onFavourite={this.handleFavouriteClick}
onReblog={this.handleReblogClick}
onDelete={this.handleDeleteClick}
onDirect={this.handleDirectClick}
onMention={this.handleMentionClick}
onMute={this.handleMuteClick}
onMuteConversation={this.handleConversationMuteClick}
onBlock={this.handleBlockClick}
onReport={this.handleReport}
onPin={this.handlePin}
onEmbed={this.handleEmbed}
/>
</div>
</HotKeys>
{descendants}
</div>
</ScrollContainer>
</Column>
);
}
}
|
app/containers/CatKitDemo/SimpleAdsorbateInput.js | mhoffman/CatAppBrowser | import React from 'react';
import PropTypes, { instanceOf } from 'prop-types';
import { withCookies, Cookies } from 'react-cookie';
import { Link } from 'react-router';
import { compose } from 'recompose';
import _ from 'lodash';
import Grid from 'material-ui/Grid';
import Paper from 'material-ui/Paper';
import Button from 'material-ui/Button';
import { withStyles } from 'material-ui/styles';
import Switch from 'material-ui/Switch';
import { MenuItem } from 'material-ui/Menu';
import Select from 'material-ui/Select';
import { LinearProgress } from 'material-ui/Progress';
import { FormGroup, FormControl, FormControlLabel } from 'material-ui/Form';
import { InputLabel } from 'material-ui/Input';
import { MdLoop, MdChevronLeft, MdChevronRight, MdCheckCircle } from 'react-icons/lib/md';
import {
IoCube,
} from 'react-icons/lib/io';
import { FaList } from 'react-icons/lib/fa';
import Tooltip from 'material-ui/Tooltip';
import GeometryCanvasWithOptions from 'components/GeometryCanvasWithOptions';
import axios from 'axios';
import { apiRoot } from 'utils/constants';
import { styles } from './styles';
const backendRoot = `${apiRoot}/apps/catKitDemo`;
const siteUrl = `${backendRoot}/get_adsorption_sites`;
const defaultOccupation = 'empty';
const initialState = {
siteOccupation: {},
adsorptionSitesLoading: true,
loading: false,
siteType: 'all',
placeHolder: 'empty',
adsorbate: 'O',
activeImage: 0,
siteNames: [],
siteTypes: [],
checkedCatLearn: false,
};
const siteNames = [
'gas',
'top',
'bridge',
'hollow',
'4fold',
];
class AdsorbateInput extends React.Component { // eslint-disable-line react/prefer-stateless-function
constructor(props) {
super(props);
this.state = initialState;
this.updateAdsorptionSites = this.updateAdsorptionSites.bind(this);
this.handleChange = this.handleChange.bind(this);
this.saveCalculation = this.saveCalculation.bind(this);
}
componentDidMount() {
this.updateAdsorptionSites();
}
handlePageFlip(delta) {
const n = this.props.images.length;
this.setState({
activeImage: (((this.state.activeImage + delta) % n) + n) % n,
// javascript version of modulo that works for positive and negative
// input.
});
}
handleSwitch(name) {
return (event, checked) => {
this.setState({ [name]: checked });
this.updateAdsorptionSites({ callCatLearn: event.target.value });
};
}
resetPageFlip() {
this.setState({
activeImage: 0,
});
}
updateAdsorptionSites(options = {}) {
this.setState({
loading: true,
});
const adsorbateParams = {
siteType: options.siteType || this.state.siteType,
placeHolder: options.placeHolder || this.state.placeHolder,
adsorbate: options.adsorbate || this.state.adsorbate,
format: this.props.cookies.get('preferredFormat'),
callCatLearn: this.state.checkedCatLearn,
};
const params = { params: {
bulk_cif: this.props.bulkCif,
bulkParams: _.omit(this.props.bulkParams, ['cif', 'input', 'wyckoff.cif']),
slabParams: _.omit(this.props.slabParams, ['cif', 'input']),
adsorbateParams,
} };
axios.get(siteUrl, params).then((response) => {
if (response.data.error) {
this.props.openSnackbar(response.data.error);
}
const siteOccupation = [];
this.props.saveAdsorbateParams({
...adsorbateParams,
cifs: response.data.cifImages,
equations: response.data.equations,
molecules: response.data.molecules,
inputs: response.data.inputImages,
mean: response.data.mean,
uncertainty: response.data.uncertainty,
references: response.data.references,
});
this.props.saveAdsorptionSites(response.data.data);
this.setState({
siteNames: response.data.site_names,
siteTypes: response.data.site_types,
});
response.data.data.map((imageSites, i) => {
siteOccupation[i] = {};
return Object.keys(imageSites).map((siteName) => {
siteOccupation[i][siteName] = [];
return imageSites[siteName][0].map(() => siteOccupation[i][siteName].push(defaultOccupation));
});
});
this.props.receiveSlabCifs(response.data.cifImages);
this.props.saveAltLabels(response.data.altLabels);
this.setState({
siteOccupation,
adsorptionSitesLoading: false,
});
this.props.saveSiteOccupations(siteOccupation);
this.setState({
loading: false,
});
});
}
handleChange(name) {
return (event) => {
this.setState({
[name]: event.target.value,
});
if (name === 'placeHolder') {
this.updateAdsorptionSites({ placeHolder: event.target.value });
} else if (name === 'siteType') {
this.updateAdsorptionSites({ siteType: event.target.value });
} else if (name === 'adsorbate') {
this.updateAdsorptionSites({ adsorbate: event.target.value });
}
};
}
saveCalculation() {
this.props.saveCalculation({
bulkParams: this.props.bulkParams,
slabParams: this.props.slabParams,
siteOccupations: this.props.siteOccupations,
adsorbateParams: this.props.adsorbateParams,
dftParams: {
calculator: this.state.calculator,
functional: this.state.functional,
},
});
this.props.clearBulkParams();
this.props.clearBulkCif();
this.props.clearSlabParams();
this.props.clearSlabCifs();
}
render() {
return (
<div>
{ this.props.bulkCif === '' ? null :
<div>
{(typeof this.props.adsorptionSites === 'undefined' ||
!_.isFunction(this.props.adsorptionSites.map)) ?
null
:
<div>
<Paper className={this.props.classes.paper}>
<Grid container direction="row" justify="space-between">
<Grid item>
<h2>Configure Adsorbates</h2>
</Grid>
<Grid item>
<Grid container direction="row" justify="space-between">
<Grid item>
<FormGroup row className={this.props.classes.formGroup} >
<FormControl >
<InputLabel>Adsorbate</InputLabel>
<Select
className={this.props.classes.select}
value={this.state.adsorbate}
onChange={this.handleChange('adsorbate')}
>
<MenuItem value="C">C</MenuItem>
<MenuItem value="CH">CH</MenuItem>
<MenuItem value="CHH">CHH</MenuItem>
<MenuItem value="CHHH">CHHH</MenuItem>
<MenuItem value="CO">CO</MenuItem>
<MenuItem value="COH">COH</MenuItem>
<MenuItem value="COO">COO</MenuItem>
<MenuItem value="H">H</MenuItem>
<MenuItem value="N">N</MenuItem>
<MenuItem value="NH">NH</MenuItem>
<MenuItem value="NHH">NHH</MenuItem>
<MenuItem value="NO">NO</MenuItem>
<MenuItem value="O">O</MenuItem>
<MenuItem value="OCHO">OCHO</MenuItem>
<MenuItem value="OH">OH</MenuItem>
<MenuItem value="OOH">OOH</MenuItem>
<MenuItem value="S">S</MenuItem>
<MenuItem value="SH">SH</MenuItem>
</Select>
</FormControl>
</FormGroup>
</Grid>
<Grid item>
<FormGroup row className={this.props.classes.formGroup} >
<FormControl >
<InputLabel>Site Type</InputLabel>
<Select
className={this.props.classes.select}
value={this.state.siteType}
onChange={this.handleChange('siteType')}
>
<MenuItem value="all">all</MenuItem>
{this.state.siteTypes.map((siteType) => (
<MenuItem key={`siteType_${siteType}`} value={siteType}>{`${siteType} (${_.get(siteNames, siteType, 'all')})`}</MenuItem>
)
)}
</Select>
</FormControl>
</FormGroup>
</Grid>
<Grid item>
<FormGroup row className={this.props.classes.formGroup} >
<FormControl >
<InputLabel>Placeholder</InputLabel>
<Select
className={this.props.classes.select}
value={this.state.placeHolder}
onChange={this.handleChange('placeHolder')}
>
<MenuItem value="empty">empty</MenuItem>
<MenuItem value="Cl">Cl</MenuItem>
<MenuItem value="F">F</MenuItem>
<MenuItem value="B">B</MenuItem>
<MenuItem value="H">H</MenuItem>
<MenuItem value="Ne">Ne</MenuItem>
<MenuItem value="Br">Br</MenuItem>
</Select>
</FormControl>
</FormGroup>
</Grid>
<Grid item>
<Tooltip title="Powered by CatLearn">
<FormControlLabel
control={
<Switch
checked={this.state.checkedCatLearn}
onChange={this.handleSwitch('checkedCatLearn')}
/>
}
label="Estimate energies"
/>
</Tooltip>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
{this.state.loading ? <LinearProgress /> : null }
</div>
}
{ _.isEmpty(this.props.adsorbateParams) || _.isEmpty(this.props.adsorbateParams.mean) ? null :
<Paper className={this.props.classes.paper}>
<Grid item>
<Grid container direction="row" justify="space-between">
<Grid item>
<h4> Estimated adsorbate energy </h4>
<div>
{Number((this.props.adsorbateParams.mean[this.state.activeImage]).toFixed(2))}{' eV \xb1 '}{Number((this.props.adsorbateParams.uncertainty[this.state.activeImage]).toFixed(2))}{' eV'}
</div>
</Grid>
<Grid item>
<h4>versus</h4>
<div>{this.props.adsorbateParams.references[this.state.activeImage]}</div>
</Grid>
</Grid>
</Grid>
</Paper>
}
<Paper className={this.props.classes.paper}>
<Grid container justify="center" direction="row">
<Grid item >
<Grid container direction="column" justify="space-around" className={this.props.classes.flipButton}>
<Grid item >
<Button
fab
mini
onClick={() => this.handlePageFlip(-1)}
>
<MdChevronLeft size={30} />
</Button>
</Grid>
</Grid>
</Grid>
<Grid item key={`item_${this.state.activeImage}`}>
<h4>{this.state.siteType !== 'all' ?
`Site "${this.state.siteType} (${siteNames[this.state.siteType]})"`
: `Site "${this.state.siteNames[this.state.activeImage]} (${_.get(siteNames, this.state.siteNames[this.state.activeImage], '')})"`}{` \u2014 (${this.state.activeImage + 1}/${this.props.images.length}).`}</h4>
<GeometryCanvasWithOptions
cifdata={this.props.images[this.state.activeImage]}
uniqueId={`slab_preview_${this.state.activeImage}`}
key={`slab_preview_${this.state.activeImage}`}
id={`slab_preview_${this.state.activeImage}`}
x={1} y={1} z={1}
altLabels={this.props.altLabels[0]}
/>
</Grid>
<Grid item >
<Grid container direction="column" justify="center" className={this.props.classes.flipButton}>
<Grid item>
<Button
fab
mini
onClick={() => this.handlePageFlip(+1)}
>
<MdChevronRight size={30} />
</Button>
</Grid>
</Grid>
</Grid>
</Grid>
</Paper>
</div>
}
{!_.isEmpty(this.props.slabParams) ? null :
<Grid container justify="center" direction="row">
<Grid item>
<Grid container direction="column" justify="space-between">
<Grid item className={this.props.classes.finish}>
{'And that\'s a wrap.\u00A0\u00A0\u00A0'} <MdCheckCircle size={92} color="green" />
</Grid>
<Grid item>
<div>Start new structure from scratch:
<Button
onClick={this.props.stepperHandleReset}
raised
className={this.props.classes.button}
><MdLoop />{'\u00A0'} Start Over </Button> </div>
</Grid>
<Grid item>
Find and start from an existing structure
<Link to="/prototypeSearch" className={this.props.classes.buttonLink}>
<Button raised onClick={this.props.stepperHandleReset} className={this.props.classes.button}><IoCube /> {'\u00A0'} Prototype Search </Button>
</Link>
</Grid>
</Grid>
</Grid>
</Grid>
}
<Grid container justify="flex-end" direction="row">
<Grid item>
<Button
raised
disabled={_.isEmpty(this.props.slabParams)}
onClick={this.saveCalculation}
color="primary"
><FaList /> {'\u00A0\u00A0'}Store Calculation</Button>
</Grid>
</Grid>
</div>
);
}
}
AdsorbateInput.defaultProps = {
altLabels: [],
};
AdsorbateInput.propTypes = {
adsorbateParams: PropTypes.object,
adsorptionSites: PropTypes.array,
altLabels: PropTypes.array,
bulkCif: PropTypes.string,
bulkParams: PropTypes.object,
classes: PropTypes.object,
clearBulkCif: PropTypes.func,
clearBulkParams: PropTypes.func,
clearSlabCifs: PropTypes.func,
clearSlabParams: PropTypes.func,
cookies: instanceOf(Cookies),
images: PropTypes.array,
openSnackbar: PropTypes.func,
receiveSlabCifs: PropTypes.func,
saveAdsorbateParams: PropTypes.func.isRequired,
saveAdsorptionSites: PropTypes.func,
saveAltLabels: PropTypes.func,
saveCalculation: PropTypes.func,
saveSiteOccupations: PropTypes.func,
siteOccupations: PropTypes.object,
slabParams: PropTypes.object,
stepperHandleReset: PropTypes.func,
};
export default compose(
withStyles(styles, { withTheme: true }),
withCookies,
)((AdsorbateInput));
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/SassModulesInclusion.js | ConnectedHomes/create-react-web-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import styles from './assets/sass-styles.module.sass';
import indexStyles from './assets/index.module.sass';
export default () => (
<div>
<p className={styles.sassModulesInclusion}>SASS Modules are working!</p>
<p className={indexStyles.sassModulesIndexInclusion}>
SASS Modules with index are working!
</p>
</div>
);
|
Docker/KlusterKiteMonitoring/klusterkite-web/src/components/Form/Modal.js | KlusterKite/KlusterKite | import React from 'react';
import { Modal, Button } from 'react-bootstrap';
import './styles.css';
export default class ModalBlock extends React.Component {
static propTypes = {
title: React.PropTypes.string.isRequired,
cancelText: React.PropTypes.string,
confirmText: React.PropTypes.string,
confirmClass: React.PropTypes.string,
onCancel: React.PropTypes.func.isRequired,
onConfirm: React.PropTypes.func.isRequired
};
render() {
return (
<div>
<div className="static-modal static-modal-center">
<Modal.Dialog>
<Modal.Header>
<Modal.Title>{this.props.title}</Modal.Title>
</Modal.Header>
<Modal.Body>
{this.props.children}
</Modal.Body>
<Modal.Footer>
<Button onClick={this.props.onCancel}>{this.props.cancelText || "Cancel"}</Button>
<Button onClick={this.props.onConfirm} bsStyle={this.props.confirmClass || "danger"}>{this.props.confirmText || "Confirm"}</Button>
</Modal.Footer>
</Modal.Dialog>
</div>
</div>
);
}
}
|
docs/app/Examples/modules/Dimmer/States/DimmerExampleActive.js | ben174/Semantic-UI-React | import React from 'react'
import { Dimmer, Segment } from 'semantic-ui-react'
const DimmerExampleActive = () => (
<Segment>
<Dimmer active />
<p>
<img src='http://semantic-ui.com/images/wireframe/short-paragraph.png' />
</p>
<p>
<img src='http://semantic-ui.com/images/wireframe/short-paragraph.png' />
</p>
</Segment>
)
export default DimmerExampleActive
|
src/dumb/editor/NotificationMap.js | jeckhummer/wf-constructor | import React from 'react';
import {Table, Checkbox} from "semantic-ui-react";
export const NotificationMap = ({map, teams, statuses, onChange}) => {
return (
<Table definition>
<Table.Header>
<Table.Row textAlign='center'>
<Table.HeaderCell />
{
statuses.map((status, i) => (
<Table.HeaderCell key={i} content={status}/>
))
}
</Table.Row>
</Table.Header>
<Table.Body>
{
teams.map((team, teamIndex) => (
<Table.Row textAlign='center' key={teamIndex}>
<Table.Cell content={team}/>
{
map[teamIndex].map((checked, statusIndex) => (
<Table.Cell key={statusIndex}>
<Checkbox
checked={checked}
onChange={(_, {checked}) => onChange(teamIndex, statusIndex, checked)}
/>
</Table.Cell>
))
}
</Table.Row>
))
}
</Table.Body>
</Table>
);
}; |
src/svg-icons/editor/drag-handle.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorDragHandle = (props) => (
<SvgIcon {...props}>
<path d="M20 9H4v2h16V9zM4 15h16v-2H4v2z"/>
</SvgIcon>
);
EditorDragHandle = pure(EditorDragHandle);
EditorDragHandle.displayName = 'EditorDragHandle';
EditorDragHandle.muiName = 'SvgIcon';
export default EditorDragHandle;
|
docs/app/Examples/elements/List/Variations/ListExampleDivided.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Image, List } from 'semantic-ui-react'
const ListExampleDivided = () => (
<List divided verticalAlign='middle'>
<List.Item>
<Image avatar src='/assets/images/avatar/small/daniel.jpg' />
<List.Content>
<List.Header as='a'>Daniel Louise</List.Header>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='/assets/images/avatar/small/stevie.jpg' />
<List.Content>
<List.Header as='a'>Stevie Feliciano</List.Header>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='/assets/images/avatar/small/elliot.jpg' />
<List.Content>
<List.Header as='a'>Elliot Fu</List.Header>
</List.Content>
</List.Item>
</List>
)
export default ListExampleDivided
|
src/index.js | hlgbls/ReduxSimpleStarter | import _ from 'lodash';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import YTSearch from 'youtube-api-search';
import SearchBar from './components/search_bar';
import VideoList from './components/video_list';
import VideoDetail from './components/video_detail'
const API_KEY = 'AIzaSyDU2RsXS53i3yrCheiuqu2LVQxHVCmWCIE';
class App extends Component {
constructor(props) {
super(props);
this.state = {
videos: [],
selectedVideo: null
};
this.videoSearch('');
}
videoSearch(term) {
YTSearch({ key: API_KEY, term: term }, (videos) => {
this.setState({
videos: videos,
selectedVideo: videos[0]
});
});
}
render() {
const videoSearch = _.debounce((term) => { this.videoSearch(term)}, 500 );
return (
<div>
<SearchBar onSearchTermChange={videoSearch} />
<VideoDetail video={this.state.selectedVideo} />
<VideoList
onVideoSelect={selectedVideo => this.setState({ selectedVideo })}
videos={this.state.videos} />
</div>
);
}
}
ReactDOM.render(<App />, document.querySelector('.container')) |
node_modules/react-router/es/Route.js | Rabbit884/reactapp | import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement } from './RouteUtils';
import { component, components } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
func = _React$PropTypes.func;
/**
* A <Route> is used to declare which components are rendered to the
* page when the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is
* requested, the tree is searched depth-first to find a route whose
* path matches the URL. When one is found, all routes in the tree
* that lead to it are considered "active" and their components are
* rendered into the DOM, nested in the same order as in the tree.
*/
/* eslint-disable react/require-render-return */
var Route = React.createClass({
displayName: 'Route',
statics: {
createRouteFromReactElement: createRouteFromReactElement
},
propTypes: {
path: string,
component: component,
components: components,
getComponent: func,
getComponents: func
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Route> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default Route; |
src/svg-icons/action/polymer.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPolymer = (props) => (
<SvgIcon {...props}>
<path d="M19 4h-4L7.11 16.63 4.5 12 9 4H5L.5 12 5 20h4l7.89-12.63L19.5 12 15 20h4l4.5-8z"/>
</SvgIcon>
);
ActionPolymer = pure(ActionPolymer);
ActionPolymer.displayName = 'ActionPolymer';
ActionPolymer.muiName = 'SvgIcon';
export default ActionPolymer;
|
app/private/indexerApp/imports/ui/pages/Ingest.js | ericvrp/GameCollie | import React from 'react';
import { Link } from 'react-router';
import { Row, Col, FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap';
export default class Ingest extends React.Component {
componentDidMount() {
}
ingestFiles(event) {
event.preventDefault();
const itemHashes = [
{"path":"./gba/0001 - F-Zero for GameBoy Advance (J)(Mr. Lee)/0001 - F-Zero for GameBoy Advance (J)(Mr. Lee).gba", "sha256":"0x86C5E12E6C9C946A2E3FDA7BDDAC25455C2CF0C6E78D4AF9108714A5BBADEE4E", "md5":"0x0915AC62D58A160028EB47141657013F", "crc32":"0x25E3FC9A"},
{"path":"./n64/Banjo-Tooie (U) [!].v64", "sha256":"0x9EC37FBA6890362EBA86FB855697A9CFF1519275531B172083A1A6A045483583", "md5":"0x40E98FAA24AC3EBE1D25CB5E5DDF49E4", "crc32":"0xBAB803EF"},
{"path":"./n64/Banjo-Tooie (U) [!].z64", "sha256":"0x9EC37FBA6890362EBA86FB855697A9CFF1519275531B172083A1A6A045483583", "md5":"0x40E98FAA24AC3EBE1D25CB5E5DDF49E4", "crc32":"0xBAB803EF"},
{"path":"./n64/Donkey Kong 64 (U) [!].v64", "sha256":"0x5778C9EF72EF269CDCC52333710A79961A343B1F01D12189D1DBE94DF3CBABED", "md5":"0xB71A88BA73E141FA2D355A6A72F46F6C", "crc32":"0x96972D67"},
{"path":"./n64/Donkey Kong 64 (U) [!].z64", "sha256":"0xB6347D9F1F75D38A88D829B4F80B1ACF0D93344170A5FBE9546C484DAE416CE3", "md5":"0x9EC41ABF2519FC386CADD0731F6E868C", "crc32":"0xD44B4FC6"},
{"path":"./n64/Dr. Mario 64 (U) [!].v64", "sha256":"0x613778B244784492A881C0D72D6017F82C39026706A406BD7EF95C6F33E53B89", "md5":"0x30EC4F3E1C435ED8B1D1FD3788B6A407", "crc32":"0xF7C44B5B"},
{"path":"./psx/Crash Bandicoot 2/Crash 2.bin", "sha256":"0xA2E2AB37CD6E0D5180876BF7786AC699B3B691208EFE8DE66AFE7779BF4D1605", "md5":"0x3C31B5E038F025098A2FDFA70C8213F2", "crc32":"0x395C0916"},
{"path":"./psx/Crash Bandicoot 2/Crash 2.cue", "sha256":"0xBE5587C93CB4180FE6156DCB931EFC81F2DBBFE491018E5E8F7C9F81DC15A93B", "md5":"0xCAFB479A95A1F2880C1C61B4796A665C", "crc32":"0xA0BE515F"},
];
for(i=0;i<itemHashes.length;i++) {
var item = itemHashes[i];
var data = {
path:item.path,
hash_sha256:item.sha256,
hash_md5:item.md5,
hash_crc32:item.crc32
};
Meteor.call('files.upsert', data);
}
}
render() {
return (
<div className="IngestFiles">
<Row>
<Col xs={ 12 } sm={ 6 } md={ 4 }>
<h4 className="page-header">Import File</h4>
<Button type="submit" bsStyle="success" onClick={this.ingestFiles}>Ingest</Button>
</Col>
</Row>
</div>
);
}
}
|
docs/src/app/components/pages/components/List/ExampleSettings.js | w01fgang/material-ui | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import Subheader from 'material-ui/Subheader';
import Divider from 'material-ui/Divider';
import Checkbox from 'material-ui/Checkbox';
import Toggle from 'material-ui/Toggle';
const styles = {
root: {
display: 'flex',
flexWrap: 'wrap',
},
};
const ListExampleSettings = () => (
<div style={styles.root}>
<MobileTearSheet>
<List>
<Subheader>General</Subheader>
<ListItem
primaryText="Profile photo"
secondaryText="Change your Google+ profile photo"
/>
<ListItem
primaryText="Show your status"
secondaryText="Your status is visible to everyone you use with"
/>
</List>
<Divider />
<List>
<Subheader>Hangout Notifications</Subheader>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Notifications"
secondaryText="Allow notifications"
/>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Sounds"
secondaryText="Hangouts message"
/>
<ListItem
leftCheckbox={<Checkbox />}
primaryText="Video sounds"
secondaryText="Hangouts video call"
/>
</List>
</MobileTearSheet>
<MobileTearSheet>
<List>
<ListItem
primaryText="When calls and notifications arrive"
secondaryText="Always interrupt"
/>
</List>
<Divider />
<List>
<Subheader>Priority Interruptions</Subheader>
<ListItem primaryText="Events and reminders" rightToggle={<Toggle />} />
<ListItem primaryText="Calls" rightToggle={<Toggle />} />
<ListItem primaryText="Messages" rightToggle={<Toggle />} />
</List>
<Divider />
<List>
<Subheader>Hangout Notifications</Subheader>
<ListItem primaryText="Notifications" leftCheckbox={<Checkbox />} />
<ListItem primaryText="Sounds" leftCheckbox={<Checkbox />} />
<ListItem primaryText="Video sounds" leftCheckbox={<Checkbox />} />
</List>
</MobileTearSheet>
</div>
);
export default ListExampleSettings;
|
src/components/topic/snapshots/foci/builder/FocusForm2ConfigureContainer.js | mitmedialab/MediaCloud-Web-Tools | import PropTypes from 'prop-types';
import React from 'react';
import { formValueSelector } from 'redux-form';
import { FormattedMessage, injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import EditSearchContainer from './search/EditSearchContainer';
import EditRetweetPartisanshipContainer from './retweetPartisanship/EditRetweetPartisanshipContainer';
import EditTopCountriesContainer from './topCountries/EditTopCountriesContainer';
import EditNytThemeContainer from './nyttheme/EditNytThemeContainer';
import EditMediaTypeContainer from './mediaType/EditMediaTypeContainer';
import { goToCreateFocusStep } from '../../../../../actions/topicActions';
import { FOCAL_TECHNIQUE_BOOLEAN_QUERY, FOCAL_TECHNIQUE_RETWEET_PARTISANSHIP, FOCAL_TECHNIQUE_TOP_COUNTRIES, FOCAL_TECHNIQUE_NYT_THEME, FOCAL_TECHNIQUE_MEDIA_TYPE } from '../../../../../lib/focalTechniques';
import messages from '../../../../../resources/messages';
const formSelector = formValueSelector('snapshotFocus');
const FocusForm2ConfigureContainer = (props) => {
const { topicId, initialValues, handleNextStep, currentFocalTechnique, handlePreviousStep, location } = props;
let content = null;
switch (currentFocalTechnique) {
case FOCAL_TECHNIQUE_BOOLEAN_QUERY:
content = (
<EditSearchContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_RETWEET_PARTISANSHIP:
content = (
<EditRetweetPartisanshipContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_TOP_COUNTRIES:
content = (
<EditTopCountriesContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_NYT_THEME:
content = (
<EditNytThemeContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
case FOCAL_TECHNIQUE_MEDIA_TYPE:
content = (
<EditMediaTypeContainer
topicId={topicId}
initialValues={initialValues}
onPreviousStep={handlePreviousStep}
onNextStep={handleNextStep}
location={location}
/>
);
break;
default:
content = <FormattedMessage {...messages.unimplemented} />;
}
return (
<div>
{ content }
</div>
);
};
FocusForm2ConfigureContainer.propTypes = {
// from parent
topicId: PropTypes.number.isRequired,
initialValues: PropTypes.object,
// form context
intl: PropTypes.object.isRequired,
// from dipatch
handlePreviousStep: PropTypes.func.isRequired,
handleNextStep: PropTypes.func.isRequired,
// from state:
currentFocalTechnique: PropTypes.string.isRequired,
location: PropTypes.object,
};
const mapStateToProps = (state, ownProps) => ({
currentFocalTechnique: formSelector(state, 'focalTechnique'),
params: ownProps.params,
});
const mapDispatchToProps = dispatch => ({
handlePreviousStep: () => {
dispatch(goToCreateFocusStep(0));
},
handleNextStep: () => {
dispatch(goToCreateFocusStep(2));
},
});
export default
connect(mapStateToProps, mapDispatchToProps)(
injectIntl(
FocusForm2ConfigureContainer
)
);
|
src/client/assets/javascripts/app/routes.js | nicksp/redux-webpack-es6-boilerplate | import React from 'react';
import { Route, IndexRoute, Redirect } from 'react-router';
import App from './App';
import FriendsView from 'features/friends/components/FriendsView';
import NotFoundView from 'components/NotFound';
export default (
<Route path="/" component={App}>
<IndexRoute component={FriendsView} />
<Route path="404" component={NotFoundView} />
<Redirect from="*" to="404" />
</Route>
);
|
src/components/const/addedVideoUser.js | motion123/mbookmakerUI | /**
* Created by tomino on 17/03/14.
*/
import React from 'react';
import {List,ListItem} from 'material-ui/List';
import InfiniteScroll from 'react-infinite-scroller';
import CircularProgress from 'material-ui/CircularProgress';
import style from './boardList.css';
import {grey500, darkBlack, lightBlack} from 'material-ui/styles/colors';
export default class AddVideoUser extends React.Component {
render() {
const {
boardInfo,
loadMore,
hasMore,
} = this.props;
const loader = <div className={style.loader}>
<CircularProgress
size={20}
/>
</div>;
let item = [];
boardInfo.map((info) =>
item.push(
<ListItem
key={info._id}
primaryText={info._user.name}
secondaryText={
<p>
<span style={{color: darkBlack}}>{info.board_title}</span>
へ追加しました。
</p>
}
/>
)
);
return (
<InfiniteScroll
loadMore={loadMore}
loader={loader}
hasMore={hasMore}
useWindow={false}
>
<List>
{item}
</List>
</InfiniteScroll>
);
}
}
|
Realization/frontend/czechidm-acc/src/content/provisioning/ProvisioningOperationTable.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import _ from 'lodash';
import { Link } from 'react-router-dom';
//
import { Basic, Advanced, Enums, Utils, Managers } from 'czechidm-core';
import SystemEntityTypeEnum from '../../domain/SystemEntityTypeEnum';
import ProvisioningOperationTypeEnum from '../../domain/ProvisioningOperationTypeEnum';
import EmptyProvisioningTypeEnum from '../../domain/EmptyProvisioningTypeEnum';
import { SystemManager } from '../../redux';
const systemManager = new SystemManager();
/**
* Provisioning operation and archive table.
*
* @author Radk Tomiška
*/
export class ProvisioningOperationTable extends Advanced.AbstractTableContent {
constructor(props, context) {
super(props, context);
this.state = {
filterOpened: this.props.filterOpened,
operationState: this._getOperationState(props._searchParameters)
};
}
UNSAFE_componentWillReceiveProps(nextProps) {
// filters from redux
if (nextProps._searchParameters) {
const newOperationState = this._getOperationState(nextProps._searchParameters);
if (newOperationState && this.state.operationState !== newOperationState) {
this.setState({
operationState: newOperationState
}, () => {
//
const filterData = {};
nextProps._searchParameters.getFilters().forEach((v, k) => {
filterData[k] = v;
});
this.refs.filterForm.setData(filterData);
this.refs.table.useFilterData(filterData);
});
}
}
}
_getOperationState(searchParameters) {
if (!searchParameters || !searchParameters.getFilters().has('resultState')) {
return null;
}
return searchParameters.getFilters().get('resultState');
}
getContentKey() {
return 'acc:content.provisioningOperations';
}
getManager() {
return this.props.manager;
}
clearSelectedRows() {
this.refs.table.clearSelectedRows();
}
reload() {
this.refs.table.reload();
}
useFilter(event) {
if (event) {
event.preventDefault();
}
this.refs.table.useFilterForm(this.refs.filterForm);
}
cancelFilter(event) {
if (event) {
event.preventDefault();
}
this.setState({
operationState: null
}, () => {
if (this.refs.emptyProvisioning) {
this.refs.emptyProvisioning.setValue(null);
}
this.refs.table.cancelFilter(this.refs.filterForm);
});
}
getDefaultSearchParameters() {
let searchParameters = this.getManager().getDefaultSearchParameters();
//
if (this.props.isArchive) {
searchParameters = searchParameters.setFilter('emptyProvisioning',
Utils.Config.getConfig('provisioning-archive.table.filter.emptyProvisioning', null));
}
//
return searchParameters;
}
_deleteAll() {
const { uiKey, manager, isArchive } = this.props;
if (isArchive) {
// not supported for archive
return;
}
//
this.refs['confirm-deleteAll'].show(
this.i18n(`action.deleteAll.message`),
this.i18n(`action.deleteAll.header`),
(result) => {
if (result === 'reject') {
return true;
}
if (result === 'confirm' && this.refs['delete-form'].isFormValid()) {
return true;
}
return false;
}
).then(() => {
const systemField = this.refs['delete-system'];
if (systemField.isValid()) {
//
this.context.store.dispatch(manager.deleteAll(systemField.getValue(), uiKey, (entity, error) => {
if (!error) {
this.addMessage({ level: 'success', message: this.i18n('action.deleteAll.success')});
} else {
this.addError(error);
}
this.reload();
}));
}
}, () => {
// nothing
});
}
render() {
const {
uiKey,
manager,
showRowSelection,
showDetail,
forceSearchParameters,
columns,
isArchive,
showDeleteAllButton,
showTransactionId
} = this.props;
const { filterOpened } = this.state;
let systemId = null;
if (forceSearchParameters && forceSearchParameters.getFilters().has('systemId')) {
systemId = forceSearchParameters.getFilters().get('systemId');
}
//
return (
<Basic.Div>
<Basic.Confirm ref="confirm-deleteAll" level="danger">
<Basic.Div style={{ marginTop: 20 }}>
<Basic.AbstractForm ref="delete-form" uiKey="confirm-deleteAll" >
<Basic.SelectBox
ref="delete-system"
label={ this.i18n('action.deleteAll.system.label') }
placeholder={ this.i18n('action.deleteAll.system.placeholder') }
manager={ systemManager }
value={ systemId }
readOnly={ systemId !== null }/>
</Basic.AbstractForm>
</Basic.Div>
</Basic.Confirm>
<Advanced.Table
ref="table"
uiKey={ uiKey }
manager={ manager }
showRowSelection={ showRowSelection }
forceSearchParameters={ forceSearchParameters }
filterOpened={ filterOpened }
filter={
<Advanced.Filter onSubmit={ this.useFilter.bind(this) }>
<Basic.AbstractForm ref="filterForm">
<Basic.Row>
<Basic.Col lg={ 8 }>
<Advanced.Filter.FilterDate ref="fromTill" placeholder="TODO"/>
</Basic.Col>
<Basic.Col lg={ 4 } className="text-right">
<Advanced.Filter.FilterButtons cancelFilter={ this.cancelFilter.bind(this) }/>
</Basic.Col>
</Basic.Row>
<Basic.Row>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="resultState"
placeholder={ this.i18n('acc:entity.ProvisioningOperation.resultState') }
enum={ Enums.OperationStateEnum }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="operationType"
placeholder={ this.i18n('acc:entity.ProvisioningOperation.operationType') }
enum={ ProvisioningOperationTypeEnum }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
{
!_.includes(columns, 'system')
||
<Advanced.Filter.SelectBox
ref="systemId"
placeholder={ this.i18n('acc:entity.System._type') }
multiSelect={ false }
manager={ systemManager }/>
}
</Basic.Col>
</Basic.Row>
<Basic.Row rendered={ _.includes(columns, 'entityIdentifier') }>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="entityType"
placeholder={ this.i18n('acc:entity.SystemEntity.entityType') }
enum={ SystemEntityTypeEnum }/>
</Basic.Col>
<Basic.Col lg={ 8 }>
<Basic.Row>
<Basic.Col lg={ showTransactionId ? 4 : 6 }>
<Advanced.Filter.TextField
ref="entityIdentifier"
placeholder={ this.i18n('acc:entity.ProvisioningOperation.entityIdentifier') }/>
</Basic.Col>
<Basic.Col lg={ showTransactionId ? 4 : 6 }>
<Advanced.Filter.TextField
ref="systemEntityUid"
placeholder={ this.i18n('acc:entity.SystemEntity.uid') }/>
</Basic.Col>
<Basic.Col lg={ 4 } rendered={ showTransactionId }>
<Advanced.Filter.TextField
ref="transactionId"
placeholder={ this.i18n('filter.transactionId.placeholder') }/>
</Basic.Col>
</Basic.Row>
</Basic.Col>
</Basic.Row>
<Basic.Row className="last">
<Basic.Col lg={ 4 }>
<Advanced.Filter.CreatableSelectBox
ref="attributeUpdated"
placeholder={ this.i18n('filter.attributeUpdated.placeholder') }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
<Advanced.Filter.CreatableSelectBox
ref="attributeRemoved"
placeholder={ this.i18n('filter.attributeRemoved.placeholder') }/>
</Basic.Col>
<Basic.Col lg={ 4 }>
<Advanced.Filter.EnumSelectBox
ref="emptyProvisioningType"
placeholder={ this.i18n('filter.emptyProvisioning.placeholder') }
enum={ EmptyProvisioningTypeEnum }
rendered={ !isArchive }/>
<Advanced.Filter.BooleanSelectBox
ref="emptyProvisioning"
placeholder={ this.i18n('filter.emptyProvisioning.placeholder') }
options={ [
{ value: 'true', niceLabel: this.i18n('filter.emptyProvisioning.yes') },
{ value: 'false', niceLabel: this.i18n('filter.emptyProvisioning.no') }
]}
rendered={ isArchive }/>
</Basic.Col>
</Basic.Row>
</Basic.AbstractForm>
</Advanced.Filter>
}
buttons={
[
<Basic.Button
level="danger"
key="delete-all-button"
className="btn-xs"
onClick={ this._deleteAll.bind(this) }
rendered={ showDeleteAllButton && Managers.SecurityManager.hasAnyAuthority(['PROVISIONINGOPERATION_DELETE']) && !isArchive }
title={ this.i18n('action.deleteAll.button.title') }
titlePlacement="bottom"
icon="fa:trash">
{ this.i18n('action.deleteAll.button.label') }
</Basic.Button>
]
}
_searchParameters={ this.getSearchParameters() }>
{
!showDetail
||
<Advanced.Column
property=""
header=""
className="detail-button"
cell={
({ rowIndex, data }) => (
<Advanced.DetailButton
title={this.i18n('button.detail')}
onClick={() => showDetail(data[rowIndex], isArchive)}/>
)
}/>
}
<Advanced.Column
property="resultState"
width={75}
header={this.i18n('acc:entity.ProvisioningOperation.resultState')}
face="text"
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
return (
<Advanced.OperationResult value={ entity.result } detailLink={ !showDetail ? null : () => showDetail(data[rowIndex], isArchive) }/>
);
}
}
rendered={_.includes(columns, 'resultState')}/>
<Advanced.Column
property="created"
width={ 100 }
header={ this.i18n('acc:entity.ProvisioningOperation.created.short') }
title={ this.i18n('acc:entity.ProvisioningOperation.created.title') }
sort
face="datetime"
rendered={ _.includes(columns, 'created') }/>
<Advanced.Column
property="modified"
width={ 100 }
header={ isArchive ? this.i18n('acc:entity.ProvisioningArchive.modified.short') : this.i18n('entity.modified.short') }
title={
isArchive
?
this.i18n('acc:entity.ProvisioningArchive.modified.title')
:
this.i18n('acc:entity.ProvisioningOperation.modified.label')
}
sort
face="datetime"
rendered={ _.includes(columns, 'modified') }/>
<Advanced.Column
property="operationType"
width={ 75 }
header={ this.i18n('acc:entity.ProvisioningOperation.operationType') }
sort
face="enum"
enumClass={ ProvisioningOperationTypeEnum }
rendered={ _.includes(columns, 'operationType') }/>
<Advanced.Column
property="entityType"
width={ 75 }
header={ this.i18n('acc:entity.SystemEntity.entityType') }
sort
face="enum"
enumClass={ SystemEntityTypeEnum }
rendered={ _.includes(columns, 'entityType') } />
<Advanced.Column
property="entityIdentifier"
header={ this.i18n('acc:entity.ProvisioningOperation.entity') }
face="text"
cell={
/* eslint-disable react/no-multi-comp */
({ rowIndex, data }) => {
const entity = data[rowIndex];
//
if (!data[rowIndex]._embedded || !data[rowIndex]._embedded.entity) {
return (
<Advanced.UuidInfo value={ entity.entityIdentifier } />
);
}
//
return (
<Advanced.EntityInfo
entityType={ entity.entityType }
entityIdentifier={ entity.entityIdentifier }
entity={ entity._embedded.entity }
face="popover"
showIcon/>
);
}
}
rendered={ _.includes(columns, 'entityIdentifier') }/>
<Advanced.Column
property="system.name"
header={ this.i18n('acc:entity.System.name') }
sort
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
return (
<Advanced.EntityInfo
entityType="system"
entityIdentifier={ entity.system }
entity={ entity._embedded.system }
face="popover"
showIcon/>
);
}
}
rendered={ _.includes(columns, 'system') } />
<Advanced.Column
property="systemEntityUid"
header={ this.i18n('acc:entity.SystemEntity.uid') }
sort
sortProperty="systemEntityUid"
face="text"
rendered={ isArchive && _.includes(columns, 'systemEntityUid') }/>
<Advanced.Column
property="_embedded.systemEntity.uid"
header={ this.i18n('acc:entity.SystemEntity.uid') }
sort
sortProperty="systemEntity"
face="text"
rendered={ !isArchive && _.includes(columns, 'systemEntityUid') }/>
<Advanced.Column
property="roleRequestId"
header={ this.i18n('acc:entity.ProvisioningOperation.roleRequestId.label') }
sort
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
if (!entity || !entity.roleRequestId) {
return null;
}
return (
<Link
to={ `/role-requests/${ encodeURIComponent(entity.roleRequestId) }/detail` }
title={ this.i18n('acc:entity.ProvisioningOperation.roleRequestId.help') }>
<Basic.Icon value="fa:key" style={{ marginLeft: 25 }}/>
</Link>
);
}
}
rendered={ _.includes(columns, 'roleRequestId') } />
</Advanced.Table>
</Basic.Div>
);
}
}
ProvisioningOperationTable.propTypes = {
uiKey: PropTypes.string.isRequired,
manager: PropTypes.object.isRequired,
/**
* Enable row selection - checkbox in first cell
*/
showRowSelection: PropTypes.oneOfType([PropTypes.bool, PropTypes.func]),
/**
* Bulk actions e.g. { value: 'activate', niceLabel: this.i18n('content.identities.action.activate.action'), action: this.onActivate.bind(this) }
*/
actions: PropTypes.arrayOf(PropTypes.object),
/**
* Detail callback
*/
showDetail: PropTypes.func,
/**
* "Hard filters"
*/
forceSearchParameters: PropTypes.object,
/**
* Rendered columns
*/
columns: PropTypes.arrayOf(PropTypes.string),
/**
* Show delete all button
*/
showDeleteAllButton: PropTypes.bool
};
ProvisioningOperationTable.defaultProps = {
showRowSelection: false,
forceSearchParameters: null,
columns: ['resultState', 'created', 'modified', 'operationType', 'entityType', 'entityIdentifier', 'system', 'systemEntityUid', 'roleRequestId'],
showDeleteAllButton: true
};
function select(state, component) {
return {
showTransactionId: Managers.ConfigurationManager.showTransactionId(state),
_searchParameters: Utils.Ui.getSearchParameters(state, component.uiKey)
};
}
export default connect(select, null, null, { forwardRef: true })(ProvisioningOperationTable);
|
src/components/app.js | RaulEscobarRivas/React-Redux-High-Order-Components | import React, { Component } from 'react';
import Header from './header';
import Content from './content';
export default class App extends Component {
render() {
return (
<div>
<Header />
<Content />
</div>
);
}
}
|
src/containers/auth/AuthenticateView.js | OlivierVillequey/hackathon | /**
* Authenticate Screen
* - Entry screen for all authentication
* - User can tap to login, forget password, signup...
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import {
View,
Image,
StyleSheet,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles, AppSizes, AppColors } from '@theme/';
// Components
import { Spacer, Text, Button } from '@ui/';
/* state ===================================================================== */
const state = {
user: {
firstName: '',
lastName: '',
email: '',
nickname: '',
id: '',
}
};
/* Styles ==================================================================== */
const styles = StyleSheet.create({
background: {
backgroundColor: AppColors.brand.secondary,
height: AppSizes.screen.height,
width: AppSizes.screen.width,
},
logo: {
width: AppSizes.screen.width * 0.85,
resizeMode: 'contain',
},
whiteText: {
color: '#FFF',
},
});
/* Component ==================================================================== */
class Authenticate extends Component {
static componentName = 'Authenticate';
render = () => (
<View style={[AppStyles.containerCentered, AppStyles.container, styles.background]}>
<Image
source={require('../../images/logo.png')}
style={[styles.logo]}
/>
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Login'}
icon={{ name: 'lock' }}
onPress={Actions.login}
backgroundColor={'#000000'}
/>
</View>
</View>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Sign up'}
icon={{ name: 'face' }}
onPress={Actions.signUp}
backgroundColor={'#000000'}
/>
</View>
</View>
<Spacer size={15} />
<Text p style={[AppStyles.textCenterAligned, styles.blackText]}>
- or -
</Text>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]} />
<View style={[AppStyles.flex2]}>
<Button
small
title={'Skip'}
onPress={Actions.app}
raised={false}
backgroundColor={'#5a5a5a'}
/>
</View>
<View style={[AppStyles.flex1]} />
</View>
<Spacer size={40} />
</View>
)
}
/* Export Component ==================================================================== */
export default Authenticate;
|
src/svg-icons/device/signal-cellular-connected-no-internet-0-bar.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet0Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M20 22h2v-2h-2v2zm0-12v8h2v-8h-2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet0Bar = pure(DeviceSignalCellularConnectedNoInternet0Bar);
DeviceSignalCellularConnectedNoInternet0Bar.displayName = 'DeviceSignalCellularConnectedNoInternet0Bar';
DeviceSignalCellularConnectedNoInternet0Bar.muiName = 'SvgIcon';
export default DeviceSignalCellularConnectedNoInternet0Bar;
|
app/javascript/mastodon/containers/mastodon.js | salvadorpla/mastodon | import React from 'react';
import { Provider, connect } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { INTRODUCTION_VERSION } from '../actions/onboarding';
import { BrowserRouter, Route } from 'react-router-dom';
import { ScrollContext } from 'react-router-scroll-4';
import UI from '../features/ui';
import Introduction from '../features/introduction';
import { fetchCustomEmojis } from '../actions/custom_emojis';
import { hydrateStore } from '../actions/store';
import { connectUserStream } from '../actions/streaming';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import initialState from '../initial_state';
import ErrorBoundary from '../components/error_boundary';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
export const store = configureStore();
const hydrateAction = hydrateStore(initialState);
store.dispatch(hydrateAction);
store.dispatch(fetchCustomEmojis());
const mapStateToProps = state => ({
showIntroduction: state.getIn(['settings', 'introductionVersion'], 0) < INTRODUCTION_VERSION,
});
@connect(mapStateToProps)
class MastodonMount extends React.PureComponent {
static propTypes = {
showIntroduction: PropTypes.bool,
};
render () {
const { showIntroduction } = this.props;
if (showIntroduction) {
return <Introduction />;
}
return (
<BrowserRouter basename='/web'>
<ScrollContext>
<Route path='/' component={UI} />
</ScrollContext>
</BrowserRouter>
);
}
}
export default class Mastodon extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
};
componentDidMount() {
this.disconnect = store.dispatch(connectUserStream());
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
render () {
const { locale } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<ErrorBoundary>
<MastodonMount />
</ErrorBoundary>
</Provider>
</IntlProvider>
);
}
}
|
modules/Redirect.js | chrisirhc/react-router | import React from 'react'
import invariant from 'invariant'
import { createRouteFromReactElement } from './RouteUtils'
import { formatPattern } from './PatternUtils'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* A <Redirect> is used to declare another URL path a client should be sent
* to when they request a given URL.
*
* Redirects are placed alongside routes in the route configuration and are
* traversed in the same manner.
*/
const Redirect = React.createClass({
statics: {
createRouteFromReactElement(element) {
const route = createRouteFromReactElement(element)
if (route.from)
route.path = route.from
// TODO: Handle relative pathnames, see #1658
invariant(
route.to.charAt(0) === '/',
'<Redirect to> must be an absolute path. This should be fixed in the future'
)
route.onEnter = function (nextState, replaceState) {
const { location, params } = nextState
const pathname = route.to ? formatPattern(route.to, params) : location.pathname
replaceState(
route.state || location.state,
pathname,
route.query || location.query
)
}
return route
}
},
propTypes: {
path: string,
from: string, // Alias for path
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
render() {
invariant(
false,
'<Redirect> elements are for router configuration only and should not be rendered'
)
}
})
export default Redirect
|
actor-apps/app-web/src/app/components/common/Text.react.js | stonegithubs/actor-platform | import _ from 'lodash';
import React from 'react';
import memoize from 'memoizee';
import emojify from 'emojify.js';
import hljs from 'highlight.js';
import marked from 'marked';
import emojiCharacters from 'emoji-named-characters';
emojify.setConfig({
mode: 'img',
img_dir: 'assets/img/emoji' // eslint-disable-line
});
const mdRenderer = new marked.Renderer();
// target _blank for links
mdRenderer.link = function(href, title, text) {
let external, newWindow, out;
external = /^https?:\/\/.+$/.test(href);
newWindow = external || title === 'newWindow';
out = '<a href=\"' + href + '\"';
if (newWindow) {
out += ' target="_blank"';
}
if (title && title !== 'newWindow') {
out += ' title=\"' + title + '\"';
}
return (out + '>' + text + '</a>');
};
const markedOptions = {
sanitize: true,
breaks: true,
highlight: function (code) {
return hljs.highlightAuto(code).value;
},
renderer: mdRenderer
};
const inversedEmojiCharacters = _.invert(_.mapValues(emojiCharacters, (e) => e.character));
const emojiVariants = _.map(Object.keys(inversedEmojiCharacters), function(name) {
return name.replace(/\+/g, '\\+');
});
const emojiRegexp = new RegExp('(' + emojiVariants.join('|') + ')', 'gi');
const processText = function(text) {
let markedText = marked(text, markedOptions);
// need hack with replace because of https://github.com/Ranks/emojify.js/issues/127
const noPTag = markedText.replace(/<p>/g, '<p> ');
let emojifiedText = emojify
.replace(noPTag.replace(emojiRegexp, (match) => ':' + inversedEmojiCharacters[match] + ':'));
return emojifiedText;
};
const memoizedProcessText = memoize(processText, {
length: 1000,
maxAge: 60 * 60 * 1000,
max: 10000
});
class Text extends React.Component {
static propTypes = {
content: React.PropTypes.object.isRequired,
className: React.PropTypes.string
};
constructor(props) {
super(props);
}
render() {
const { content, className } = this.props;
return (
<div className={className}
dangerouslySetInnerHTML={{__html: memoizedProcessText(content.text)}}>
</div>
);
}
}
export default Text;
|
week3/react/counter-app/src/App.js | jfhinchcliffe/Coderfactory_Term3_Notes | //import React, { Component } from 'react';
// import logo from './logo.svg';
import React from 'react';
import './App.css';
import 'whatwg-fetch'; // Polyfills window.fetch
import Counter from './components/Counter';
import fetchAPI from './api/fetchAPI';
import replaceItemWithID from './utils/replaceItemWithId';
class App extends React.Component {
constructor(props) {
super(props);
this.state = {
counters: [],
};
fetchAPI('/counters')
.then(counters => {
console.log('counters', counters);
this.setState({
counters: counters
})
})
.catch(error => {
console.error('Error loading counter API', error.message)
})
}
onChangeCount(id, change) {
fetchAPI(`/counters/${ id }`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
change: change,
})
})
.then(newCounter => {
this.setState(({ counters }) => ({
counters: replaceItemWithID(counters, id, newCounter)
}))
})
}
render() {
const {counters} = this.state;
return (
<main className="app">
{
counters.map((counter, index) => {
return (
<Counter
key={ index }
count={ counter.count }
onIncrement={ this.onChangeCount.bind(this, counter._id, 1 )}
onDecrement={ this.onChangeCount.bind(this, counter._id, -1 )}
/>
)
})
}
</main>
);
}
}
export default App; |
app/containers/WorkSpace/index.js | Zurico/t7 | /*
* WorkSpacePage
*
* This is the first thing users see of our App, at the '/' route
*/
import React from 'react';
import Helmet from 'react-helmet';
import styles from './styles.css';
import { selectWorkSpace } from './selectors';
import { connect } from 'react-redux';
import { mouseTrap } from 'react-mousetrap';
import { createStructuredSelector } from 'reselect';
import { splitPane } from './actions';
// https://github.com/primer/octicons/tree/v2.1.2
import Octicon from 'react-octicon';
import HotKeys from 'utils/hotkeys';
import WorkSpacePane from 'containers/WorkSpacePane';
class WorkSpace extends React.Component {
constructor(props, context){
super(props, context);
}
componentWillMount() {
// Subscribe to hotkeys
this.props.bindShortcut(HotKeys.SPLIT_WORKSPACE_VERTICALLY.keys, this.splitWorkSpaceVerticallyShortcut.bind(this));
}
splitWorkSpaceVerticallyShortcut(){
this.splitWorkSpaceVertically();
return HotKeys.ADD_NOTEBOOK.default;
}
splitWorkSpaceVertically(){
this.props.splitPane();
}
render(){
return (
<article className={styles.container}>
<Helmet
title="Workspace Page"
meta={[
{ name: 'description', content: 'Talo Workspace' },
]}
/>
{
this.props.workspace.panes.map((pane, num) => <WorkSpacePane key={num} id={num} pane={pane} />)
}
</article>
);
}
}
WorkSpace.propTypes = {
workspace: React.PropTypes.object
};
const mapStateToProps = createStructuredSelector({
workspace: selectWorkSpace()
});
const mapDispatchToProps = dispatch => ({
splitPane: () => dispatch(splitPane())
});
// Wrap the component to inject dispatch and state into it
export default connect(mapStateToProps, mapDispatchToProps)(mouseTrap(WorkSpace));
|
components/image/index.js | voylinux/voylinux.com-frontend | import React from 'react';
class Image extends React.Component {
render() {
return (
<img src={this.props.src} className={this.props.class} alt={this.props.alt} />
)
}
}
export default Image;
|
components/dash-core-components/src/components/LogoutButton.react.js | plotly/dash | import React from 'react';
import PropTypes from 'prop-types';
import './css/logout.css';
/**
* Logout button to submit a form post request to the `logout_url` prop.
* Usage is intended for dash-deployment-server authentication.
*
* DDS usage:
*
* `dcc.LogoutButton(logout_url=os.getenv('DASH_LOGOUT_URL'))`
*
* Custom usage:
*
* - Implement a login mechanism.
* - Create a flask route with a post method handler.
* `@app.server.route('/logout', methods=['POST'])`
* - The logout route should perform what's necessary for the user to logout.
* - If you store the session in a cookie, clear the cookie:
* `rep = flask.Response(); rep.set_cookie('session', '', expires=0)`
*
* - Create a logout button component and assign it the logout_url
* `dcc.LogoutButton(logout_url='/logout')`
*
* See https://dash.plotly.com/dash-core-components/logout_button
* for more documentation and examples.
*/
export default class LogoutButton extends React.Component {
render() {
const {id, logout_url, label, className, style, method, loading_state} =
this.props;
let url, submitMethod;
if (!logout_url) {
url =
logout_url ||
'https://dash.plotly.com/dash-core-components/logout_button';
submitMethod = 'get';
} else {
url = logout_url;
submitMethod = method;
}
return (
<form
data-dash-is-loading={
(loading_state && loading_state.is_loading) || undefined
}
action={url}
method={submitMethod}
className="dash-logout-frame"
>
<button
className={`dash-logout-btn ${className || ''}`}
style={style}
id={id}
type="submit"
>
{label}
</button>
</form>
);
}
}
LogoutButton.defaultProps = {
label: 'Logout',
method: 'post',
};
LogoutButton.propTypes = {
/**
* Id of the button.
*/
id: PropTypes.string,
/**
* Text of the button
*/
label: PropTypes.string,
/**
* Url to submit a post logout request.
*/
logout_url: PropTypes.string,
/**
* Style of the button
*/
style: PropTypes.object,
/**
* Http method to submit the logout form.
*/
method: PropTypes.string,
/**
* CSS class for the button.
*/
className: PropTypes.string,
/**
* Dash-assigned callback that gets fired when the value changes.
*/
setProps: PropTypes.func,
/**
* Object that holds the loading state object coming from dash-renderer
*/
loading_state: PropTypes.shape({
/**
* Determines if the component is loading or not
*/
is_loading: PropTypes.bool,
/**
* Holds which property is loading
*/
prop_name: PropTypes.string,
/**
* Holds the name of the component that is loading
*/
component_name: PropTypes.string,
}),
};
|
app/javascript/mastodon/features/hashtag_timeline/index.js | cobodo/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import ColumnSettingsContainer from './containers/column_settings_container';
import { expandHashtagTimeline, clearTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { FormattedMessage } from 'react-intl';
import { connectHashtagStream } from '../../actions/streaming';
import { isEqual } from 'lodash';
const mapStateToProps = (state, props) => ({
hasUnread: state.getIn(['timelines', `hashtag:${props.params.id}${props.params.local ? ':local' : ''}`, 'unread']) > 0,
});
export default @connect(mapStateToProps)
class HashtagTimeline extends React.PureComponent {
disconnects = [];
static propTypes = {
params: PropTypes.object.isRequired,
columnId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('HASHTAG', { id: this.props.params.id }));
}
}
title = () => {
let title = [this.props.params.id];
if (this.additionalFor('any')) {
title.push(' ', <FormattedMessage key='any' id='hashtag.column_header.tag_mode.any' values={{ additional: this.additionalFor('any') }} defaultMessage='or {additional}' />);
}
if (this.additionalFor('all')) {
title.push(' ', <FormattedMessage key='all' id='hashtag.column_header.tag_mode.all' values={{ additional: this.additionalFor('all') }} defaultMessage='and {additional}' />);
}
if (this.additionalFor('none')) {
title.push(' ', <FormattedMessage key='none' id='hashtag.column_header.tag_mode.none' values={{ additional: this.additionalFor('none') }} defaultMessage='without {additional}' />);
}
return title;
}
additionalFor = (mode) => {
const { tags } = this.props.params;
if (tags && (tags[mode] || []).length > 0) {
return tags[mode].map(tag => tag.value).join('/');
} else {
return '';
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
_subscribe (dispatch, id, tags = {}, local) {
let any = (tags.any || []).map(tag => tag.value);
let all = (tags.all || []).map(tag => tag.value);
let none = (tags.none || []).map(tag => tag.value);
[id, ...any].map(tag => {
this.disconnects.push(dispatch(connectHashtagStream(id, tag, local, status => {
let tags = status.tags.map(tag => tag.name);
return all.filter(tag => tags.includes(tag)).length === all.length &&
none.filter(tag => tags.includes(tag)).length === 0;
})));
});
}
_unsubscribe () {
this.disconnects.map(disconnect => disconnect());
this.disconnects = [];
}
componentDidMount () {
const { dispatch } = this.props;
const { id, tags, local } = this.props.params;
this._subscribe(dispatch, id, tags, local);
dispatch(expandHashtagTimeline(id, { tags, local }));
}
componentWillReceiveProps (nextProps) {
const { dispatch, params } = this.props;
const { id, tags, local } = nextProps.params;
if (id !== params.id || !isEqual(tags, params.tags) || !isEqual(local, params.local)) {
this._unsubscribe();
this._subscribe(dispatch, id, tags, local);
dispatch(clearTimeline(`hashtag:${id}${local ? ':local' : ''}`));
dispatch(expandHashtagTimeline(id, { tags, local }));
}
}
componentWillUnmount () {
this._unsubscribe();
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { id, tags, local } = this.props.params;
this.props.dispatch(expandHashtagTimeline(id, { maxId, tags, local }));
}
render () {
const { hasUnread, columnId, multiColumn } = this.props;
const { id, local } = this.props.params;
const pinned = !!columnId;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={`#${id}`}>
<ColumnHeader
icon='hashtag'
active={hasUnread}
title={this.title()}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
showBackButton
>
{columnId && <ColumnSettingsContainer columnId={columnId} />}
</ColumnHeader>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`hashtag_timeline-${columnId}`}
timelineId={`hashtag:${id}${local ? ':local' : ''}`}
onLoadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.hashtag' defaultMessage='There is nothing in this hashtag yet.' />}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
imports/components/TabNav.js | tampham47/nau-jukebox | /* © 2017
* @author Tu Nguyen
*/
/* eslint-disable react/no-array-index-key */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Container } from 'flux/utils';
import { withTracker } from 'meteor/react-meteor-data';
import ReactGA from 'react-ga';
import AppStore from '../events/AppStore';
import UserStore from '../events/UserStore';
import AccountsUIWrapper from './AccountUIWrapper';
import { changeTab, toggleSearch } from '../events/AppActions';
class TabNav extends Component {
static propTypes = {
isSignedIn: PropTypes.bool,
};
static defaultProps = {
isSignedIn: false,
};
static getStores() {
return [AppStore, UserStore];
}
static calculateState(/*prevState*/) {
return {
errorSignIn: UserStore.getState()['errorSignIn'],
toggleBtnNav: AppStore.getState()['toggleBtnNav'],
tabIndex: AppStore.getState()['tabIndex'],
};
}
state = {
navbarIsShown: false,
};
componentDidUpdate(prevProps, prevState) {
if (prevState.tabIndex !== this.state.tabIndex) {
ReactGA.event({
category: 'Navigation',
action: 'Switched tab',
label: this.tabList[this.state.tabIndex],
});
}
}
onTabClick = e => {
const index = parseInt(e.currentTarget.dataset.index, 10);
changeTab(index);
if (this.state.navbarIsShown) {
this.toggleNavbar();
}
};
tabList = ['Play List', 'Yesterday', 'Last 7 day', 'Top Lists', 'Users', 'My Bookings'];
_renderTabNav = () => {
const lst = this.tabList.map((item, index) => {
const listItem = (
<li
key={index}
data-index={index}
className={`tab__nav__list-item ${this.state.tabIndex === index ? 'tab__nav__list-item--active' : ''}`}
onClick={this.onTabClick}
>
<a href="#">{item}</a>
</li>
);
if (index !== 5) {
return listItem;
} else if (this.props.isSignedIn) {
return listItem;
}
return '';
});
return lst;
};
toggleNavbar = () => {
this.setState({
navbarIsShown: !this.state.navbarIsShown,
});
};
render() {
return (
<nav className="tab__nav noselect">
<div className="container tab__nav__container tab__nav--mobile-no-pd">
<ul className={`tab__nav__playlist ${this.state.navbarIsShown ? 'tab__nav__playlist--active' : ''}`}>
{this._renderTabNav()}
</ul>
<div className="tab__nav__login-outter login-block">
<AccountsUIWrapper />
<div className="tab__nav__buttons-wrapper">
<i
className="fa fa-search tab__nav__search nau--hidden-md nau--hidden-lg"
aria-hidden="true"
onClick={toggleSearch}
/>
<button
className={`tab__nav__button tab__collapse nau--hidden-md nau--hidden-lg`}
onClick={this.toggleNavbar}
>
<i className="fa fa-bars tab__nav__icon" aria-hidden="true" />
</button>
</div>
{this.state.errorSignIn && !this.props.isSignedIn ? (
<div className="login-block__error">
<p>Please login first!</p>
</div>
) : null}
</div>
</div>
</nav>
);
}
}
export default withTracker(() => ({
isSignedIn: !!Meteor.userId(),
}))(Container.create(TabNav));
|
src/client/now/components/phone-number-input.js | michigan-com/nova | 'use strict';
import React from 'react';
import { findDOMNode } from 'react-dom';
import xr from 'xr';
import Store from '../store';
import { showInput, dismissInput, hideInputForever, expandInput } from '../actions/phone-number';
import { getTopArticleStyle } from './top-article';
export default class PhoneNumberInput extends React.Component {
constructor(props) {
super(props);
this.state = {
error: '',
sendingMessage: false,
messageSent: false,
phoneNumber: ''
}
}
componentDidMount() {
if (this.shouldShowInput) {
//setTimeout(() => { Store.dispatch(showInput()); }, 2500);
Store.dispatch(showInput());
}
}
componentDidUpdate(lastProps, lastState) {
if (this.props.expandInput && !lastProps.expandInput) {
findDOMNode(this.refs['phone-number']).focus();
}
}
submitNumber(e) {
e.preventDefault();
e.stopPropagation();
if (!this.props.expandInput) {
return Store.dispatch(expandInput());
}
let _csrf = document.getElementById('_csrf').value;
let phoneNumber = this.state.phoneNumber;
if (phoneNumber.length != 10) {
return this.setState({ error: 'Please include area code and phone number (10 numbers total)' })
} else if (isNaN(phoneNumber)) {
return this.setState({ error: 'Only numbers, please' });
}
this.setState({
error: '',
sendingMessage: true
});
xr.post('/text-mobile-link/', { phoneNumber, _csrf }).then(
(resp) => {
this.setState({
error: '',
sendingMessage: false,
messageSent: true,
});
setTimeout(() => { Store.dispatch(hideInputForever()); }, 2000);
},
(err) => {
let resp = JSON.parse(err.response);
this.setState({
error: resp.error
});
}
)
}
checkKeyValue(e) {
let keyCode = e.which || e.keyCode;
if (keyCode === 13) return;
e.stopPropagation();
e.preventDefault();
if ((keyCode > 57 || keyCode < 48) && keyCode !== 8) {
this.setState(this.state);
return;
}
let newState = { ...this.state }
let newVal = String.fromCharCode(keyCode);
let oldNumber = this.state.phoneNumber
if (keyCode == 8) {
newState.phoneNumber = oldNumber.slice(0, oldNumber.length - 1)
} else if (oldNumber.length < 10) {
newState.phoneNumber += newVal;
}
this.setState(newState);
}
dismissInput() {
Store.dispatch(dismissInput());
}
hideForever(e) {
e.preventDefault();
e.stopPropagation();
Store.dispatch(hideInputForever());
}
renderContent() {
let content = null;
let submitClass = 'submit';
let submitValue = 'Text Me';
if (!this.props.expandInput) submitValue = 'Sure!';
if (this.state.sendingMessage) {
submitClass += ' disabled';
submitValue = 'Texting...'
} else if (this.state.messageSent) {
submitClass += ' disabled';
submitValue = 'Sent!';
}
if (this.props.expandInput) {
let phoneNumberInputClass = 'phone-number-input';
if (this.state.error) phoneNumberInputClass += ' error';
content = (
<input type='text'
ref='phone-number'
className={ phoneNumberInputClass }
placeholder='3135550123'
value={ this.state.phoneNumber }
onKeyDown={ this.checkKeyValue.bind(this) }/>
);
} else {
content = (
<p className='blurb'>We tailored this experience for mobile phones. Can we text you a link?</p>
);
}
let formContentClass = 'form-content';
if (this.props.expandInput) formContentClass += ' expand';
let style = {};
style.animationDelay = `${this.props.rank * 50}ms`;
return (
<div className='phone-number-input-content' style={ style }>
<form onSubmit={ this.submitNumber.bind(this) }>
<div className={ formContentClass }>
<div className='errors'>{ this.state.error || ' '}</div>
{ content }
<p className='blurb'>We will never spam or share your number.</p>
</div>
<div className='form-submit'>
<input type='submit' className={ submitClass } value={ submitValue } onClick={ this.submitNumber.bind(this) }/>
</div>
</form>
</div>
)
}
render() {
let className = 'phone-number-input-container';
let style = getTopArticleStyle(this.props.rank);
if (this.props.expandInput) style.height *= 2;
return (
<div className={ className } style={ style }>
{ this.renderContent() }
</div>
)
}
}
|
src/views/ChannelForm/index.js | chad-ding/koala | /**
*@Author: chad.ding
*@Copyright: 2017-2018 DMF
*@Date: 2017-05-18 16:22:05
*/
import React, { Component } from 'react';
import { Form, Input, Switch, Button, Checkbox, Select, Radio, Slider, InputNumber, Breadcrumb, Icon } from 'antd';
import { connect } from 'react-redux';
import { Link } from 'react-router';
import SelectInput from '../../components/SelectInput';
import RangeInput from '../../components/RangeInput';
import './style.less';
@connect(state => ({
...state.ChannelFormReducer
}))
@Form.create()
export default class ChannelForm extends Component {
constructor(props) {
super(props);
this.handleSubmit = this.handleSubmit.bind(this);
this.checkFlow = this.checkFlow.bind(this);
}
handleSubmit = async(e) => {
e.preventDefault();
let invalid = false;
await this.props.form.validateFields((err, values) => {
if (!err) {
invalid = true;
}
});
if (invalid) {
console.log('form is invalid');
return;
}
}
checkFlow(rule, value, callback) {
if (value.number > 0) {
callback();
return;
}
callback('总流量预估必须大于0!');
}
render() {
let FormItem = Form.Item;
let { getFieldDecorator } = this.props.form;
let { Option, OptGroup } = Select;
let RadioGroup = Radio.Group;
let formItemLayout = {
labelCol: {
xs: { span: 14 },
sm: { span: 6 }
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 14 }
}
};
let tailFormItemLayout = {
wrapperCol: {
xs: {
span: 24,
offset: 0
},
sm: {
span: 14,
offset: 6
}
}
};
let marks = {
1: {
style: {
color: '#f50'
},
label: <strong>1KB</strong>
},
900: {
style: {
color: '#f50'
},
label: <strong>900KB</strong>
}
};
let unitMap = [
{ value: '1', text: 'QPS(请求/秒)' },
{ value: '2', text: 'QPM(请求/分)' },
{ value: '3', text: 'QPH(请求/小时)' },
{ value: '4', text: 'QPD(请求/天)' }
];
return (
<div className="container">
<Breadcrumb>
<Breadcrumb.Item>
<Icon type="home" />
</Breadcrumb.Item>
<Breadcrumb.Item>
<span>
<Link to="/application/list">接入申请</Link>
</span>
</Breadcrumb.Item>
<Breadcrumb.Item>
申请频道
</Breadcrumb.Item>
</Breadcrumb>
<br/><br/>
<Form onSubmit={this.handleSubmit}>
<FormItem {...formItemLayout} label="频道名称" hasFeedback>
{getFieldDecorator('channelName', {
rules: [{
type: 'string', message: '输入不合法!',
pattern: /^channel.\w+/
}, {
required: true, message: '请输入频道名称!'
}]
})(
<Input placeholder="必须以channel开头,包含数字,字母,'_'和'.',如channel.cfg_2d" />
)}
</FormItem>
<FormItem {...formItemLayout} label="区间" hasFeedback>
{getFieldDecorator('range', {
rules: [{
required: true, message: '请输入区间范围!'
}, {
validator: function(rule, value, callback){
if (value.min <= value.max) {
callback();
return;
}
callback('请输入正确的数据范围');
}
}],
initialValue: {min: 5, max: 340}
})(
<RangeInput unit="msg/s"></RangeInput>
)}
</FormItem>
<FormItem {...formItemLayout} label="存储引擎" hasFeedback>
{getFieldDecorator('cluster', {
rules: [{
required: true, message: '请选择存储引擎!'
}],
initialValue: '消息堆积(Kafka)'
})(
<Select>
<Option value="消息堆积(Kafka)">消息堆积(Kafka)</Option>
<Option value="任务事件(RabbitMQ)">任务事件(RabbitMQ)</Option>
</Select>
)}
</FormItem>
<FormItem {...formItemLayout} label="路由策略" hasFeedback>
{getFieldDecorator('mode', {
rules: [{
type: 'string', message: '输入不合法!'
}, {
required: true, message: '请输入环境名称!'
}],
initialValue: 'direct'
})(
<RadioGroup>
<Radio value="direct">direct</Radio>
<Radio value="topic">topic</Radio>
</RadioGroup>
)}
</FormItem>
<FormItem {...formItemLayout} label="是否分片" hasFeedback>
{getFieldDecorator('sharding', {
rules: [{
required: true, message: '请选择是否分片!'
}],
valuePropName: 'checked',
initialValue: false
})(
<Switch checkedChildren={'是'} unCheckedChildren={'否'} />
)}
</FormItem>
<FormItem {...formItemLayout} label="项目名称" hasFeedback>
{getFieldDecorator('project', {
rules: [{
type: 'string', message: '输入不合法!'
}, {
required: true, message: '请输入项目名称名称!'
}]
})(
<Input />
)}
</FormItem>
<FormItem {...formItemLayout} label="App ID" hasFeedback>
{getFieldDecorator('appId', {
rules: [{
type: 'string', message: '输入不合法!'
}, {
required: true, message: '请输入App ID!'
}]
})(
<Input />
)}
</FormItem>
<FormItem {...formItemLayout} label="用途" hasFeedback>
{getFieldDecorator('purpose', {
rules: [{
required: true, message: '请选择用途!'
}],
initialValue: '1'
})(
<Select>
<OptGroup label="线上">
<Option value="1">数据统计</Option>
<Option value="2">数据同步</Option>
<Option value="3">任务处理</Option>
<Option value="4">事件广播</Option>
</OptGroup>
</Select>
)}
</FormItem>
<FormItem {...formItemLayout} label="存活时间" hasFeedback>
{getFieldDecorator('liveTime', {
rules: [{
required: true, message: '请选择存活时间!'
}],
initialValue: '1'
})(
<Select>
<Option value="1">1天</Option>
<Option value="2">5天</Option>
<Option value="3">1周</Option>
<Option value="4">2周</Option>
<Option value="5">1月</Option>
<Option value="6">半年</Option>
<Option value="7">1年</Option>
<Option value="8">永久</Option>
</Select>
)}
</FormItem>
<FormItem {...formItemLayout} label="开发语言" hasFeedback>
{getFieldDecorator('language', {
valuePropName: 'checked'
})(
<div>
<Checkbox>Java</Checkbox>
<Checkbox>PHP</Checkbox>
<Checkbox>C++</Checkbox>
</div>
)}
</FormItem>
<FormItem {...formItemLayout} label="消息体预估" hasFeedback>
{getFieldDecorator('message', {
initialValue: [1, 500]
})(
<Slider marks={marks} range min={1} max={900} />
)}
</FormItem>
<FormItem {...formItemLayout} label="应用规划数" hasFeedback>
{getFieldDecorator('program', {
rules: [{
type: 'number', message: '只能输入数字!'
},{
required: true, message: '请输入应用规划数!'
}],
initialValue: 30
})(
<InputNumber min={1} max={10} className="full-width" />
)}
</FormItem>
<FormItem {...formItemLayout} label="总流量预估" hasFeedback>
{getFieldDecorator('flow', {
rules: [{
required: true, message: '请输入总流量预估'
},{
validator: this.checkFlow
}],
initialValue: { number: 1, unit: '1' }
})(
<SelectInput unitMap={unitMap}></SelectInput>
)}
</FormItem>
<FormItem {...formItemLayout} label="用途说明" hasFeedback>
{getFieldDecorator('useage', {
rules: [{
required: true, message: '请输入用途说明'
}]
})(
<Input type="textarea" rows={10}></Input>
)}
</FormItem>
<FormItem {...tailFormItemLayout}>
<Link to="/application/list">
<Button type="default" htmlType="button" size="large">取消</Button>
</Link>
<Button type="primary" htmlType="submit" size="large">保存</Button>
</FormItem>
</Form>
</div>
);
}
}; |
sms_sponsorship/webapp/src/App.js | eicher31/compassion-modules | import React from 'react';
import TopAppBar from './components/TopAppBar';
import ChildCard from './components/ChildCard';
import { translate } from 'react-i18next';
import i18n from './i18n';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import CenteredLoading from './components/CenteredLoading';
import jsonRPC from './components/jsonRPC';
import getRequestId from './components/getRequestId';
import Message from './components/Message';
import SuccessMessage from './components/SuccessMessage';
import Button from "@material-ui/core/Button";
const theme = createMuiTheme({
palette: {
primary: {
main: '#0054A6'
},
},
overrides: {
// Name of the component ⚛️ / style sheet
MuiTypography: {
// Name of the rule
headline: {
color: '#555555'
},
title: {
color: '#555555'
}
},
MuiCardHeader: {
title: {
textAlign: 'center',
fontSize: '30px',
// textTransform: 'uppercase'
}
},
MuiSnackbarContent: {
root: {
backgroundColor: "darkred"
}
}
},
});
window.pageLoaded = false;
window.getChildTimeout = false;
class Main extends React.Component {
state = {
child: false,
partner: false,
success: false,
langDialog: false,
langChanged: false,
};
count_try = 0;
parseResult = (res) => {
let child;
try {
child = JSON.parse(res.responseText).result
}
catch(e) {
child = false;
}
return child;
};
getChild = (forceLang) => {
let data = {};
if (forceLang || this.state.langChanged) {
data.lang = i18n.language
}
let requestId = getRequestId();
if (!requestId) {
return;
}
let url = "/sms_sponsorship/step1/" + requestId + "/get_child_data";
jsonRPC(url, data, (res) => {
let child = this.parseResult(res);
let partner = (typeof(child.partner) === 'undefined') ? false:child.partner[0];
this.setState({
child: child,
partner: partner,
});
// Set the language as the request
i18n.changeLanguage(child.lang);
});
};
changeChild = () => {
let requestId = getRequestId();
let lang = i18n.language;
let url = "/sms_sponsorship/step1/" + requestId + "/change_child";
let form = document.forms.other_child_form;
let data = {
gender: form.gender.value,
age: form.age.value,
country: form.country.value,
lang: lang,
};
this.setState({
child: {
'has_a_child': true,
'loading_other_child': true
},
dialogOpen: false
});
jsonRPC(url, data, (res) => {
this.getChild();
});
};
changeLanguage = () => {
let form = document.forms.lang_form;
let lang = form.lang.value;
i18n.changeLanguage(lang);
this.setState({
langDialog: false,
langChanged: true,
});
this.getChild(lang);
};
componentDidMount() {
if (!window.pageLoaded) {
window.pageLoaded = true;
this.getChild();
}
}
reload() {
window.location.reload();
}
redirectToWebsite(url) {
window.location.href = url;
}
render() {
const { t } = this.props;
document.title = t("cardTitle");
let image_url = '';
let child = this.state.child;
if (child && child.image_url) {
image_url = child.image_url.replace('/w_150', '').replace('media.ci.org/', 'media.ci.org/g_face,c_thumb,w_150,h_150,r_max/');
}
let topAppBar = <TopAppBar title="Compassion" t={t} appContext={this}/>;
if (!getRequestId()) {
return (
<div>
{topAppBar}
<div>
<Message text={t("error_noRequestID")}/>
</div>
</div>
)
}
if (!child.has_a_child && !this.state.success && !child.sponsorship_confirmed && !child.invalid_sms_child_request) {
clearTimeout(window.getChildTimeout);
if(this.count_try > 40){
return (
<div>
{topAppBar}
<Message text={t("error_noService")} style={{marginBottom: '20px'}}/>
<div style={{textAlign: 'center', marginTop: '20px'}}>
<Button variant="contained"
onClick={this.reload}
color="primary"
size="medium"
>
{t("error_refresh")}
</Button>
<br/>
<br/>
<Button variant="outlined"
onClick={() => this.redirectToWebsite(t('error_websiteUrl'))}
color="primary"
size="medium"
>
{t("error_sponsorFromWebsite")}
</Button>
</div>
</div>
)
}else{
window.getChildTimeout = setTimeout(() => {
this.getChild();
}, 1000);
++this.count_try;
}
}
return (
<MuiThemeProvider theme={theme}>
<div>
{topAppBar}
{this.state.success ? (
<SuccessMessage preferred_name={this.state.success.preferred_name}
gender={this.state.success.gender}
image_url={this.state.success.image_url.replace('/w_150', '').replace('media.ci.org/', 'media.ci.org/g_face,c_thumb,w_150,h_150,r_max/')} t={t}
/>
):(
<div>
{child ? (
<div>
{child.sponsorship_confirmed ? (
<div>
<Message text={t('error_sponsorshipAlreadyMade')}/>
</div>
):(
<div>
{!child.invalid_sms_child_request ? (
<div>
{!child.loading_other_child ? (
<div>
{child.has_a_child ? (
<ChildCard centered
name={child.name}
preferredName={child.preferred_name}
country={child.country}
age={child.age + ' ' + t('ageYears')}
gender={child.gender === 'M' ? 'Male':'Female'}
image_url={image_url}
appContext={this}
t={t}
/>
):(
<CenteredLoading text={t("waitingForChild")}/>
)}
</div>
):(
<div>
<CenteredLoading text={t("waitingForOtherChild")}/>
</div>
)}
</div>
):(
<div>
<Message text={t("error_noRequestID")}/>
</div>
)}
</div>
)}
</div>
):(
<div>
<CenteredLoading text={t("waitingForChild")}/>
</div>
)}
</div>
)}
</div>
</MuiThemeProvider>
)
}
}
// extended main view with translate hoc
export default translate('translations')(Main); |
client/src/components/CountryDetails.js | mandrive/CountriesApp | import React from 'react';
import cssmodules from 'react-css-modules';
import styles from './styles/countrydetails.cssmodule.scss';
@cssmodules(styles)
class CountryDetails extends React.Component {
render() {
var countryDetails = this.props.selectedCountry && this.props.selectedCountry.Id
? (<div className="card">
<div className="card-block">
<h2>Country name: {this.props.selectedCountry.Name}</h2>
<h4>Capital name: {this.props.selectedCountry.Capital.Name}</h4>
</div>
</div>)
: (<h3>Select a country from list on the left</h3>)
return (
<div className="countrydetails-component">
{countryDetails}
</div>
);
}
}
export default CountryDetails;
|
dynamic/react/api-models/index.js | balasuar/developer-dot | import 'babel-polyfill';
import Model from './model';
import React from 'react';
import {render} from 'react-dom';
const model = window.PAGE_MODEL;
const name = window.MODEL_NAME;
render(<Model m={model} name={name} />, document.getElementById('react-root'));
|
front/src/components/App.js | litleleprikon/ds_chat | import React from 'react';
import Header from './header/Header';
import Body from './body/Body';
const App = () => (
<div className="App">
<Header/>
<Body/>
</div>
);
export default App;
|
app/javascript/mastodon/containers/status_container.js | summoners-riftodon/mastodon | import React from 'react';
import { connect } from 'react-redux';
import Status from '../components/status';
import { makeGetStatus } from '../selectors';
import {
replyCompose,
mentionCompose,
directCompose,
} from '../actions/compose';
import {
reblog,
favourite,
unreblog,
unfavourite,
pin,
unpin,
} from '../actions/interactions';
import { blockAccount } from '../actions/accounts';
import {
muteStatus,
unmuteStatus,
deleteStatus,
hideStatus,
revealStatus,
} from '../actions/statuses';
import { initMuteModal } from '../actions/mutes';
import { initReport } from '../actions/reports';
import { openModal } from '../actions/modal';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { boostModal, deleteModal } from '../initial_state';
import { showAlertForError } from '../actions/alerts';
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.' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => ({
status: getStatus(state, props),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onReply (status, router) {
dispatch(replyCompose(status, router));
},
onModalReblog (status) {
dispatch(reblog(status));
},
onReblog (status, e) {
if (status.get('reblogged')) {
dispatch(unreblog(status));
} else {
if (e.shiftKey || !boostModal) {
this.onModalReblog(status);
} else {
dispatch(openModal('BOOST', { status, onReblog: this.onModalReblog }));
}
}
},
onFavourite (status) {
if (status.get('favourited')) {
dispatch(unfavourite(status));
} else {
dispatch(favourite(status));
}
},
onPin (status) {
if (status.get('pinned')) {
dispatch(unpin(status));
} else {
dispatch(pin(status));
}
},
onEmbed (status) {
dispatch(openModal('EMBED', {
url: status.get('url'),
onError: error => dispatch(showAlertForError(error)),
}));
},
onDelete (status, history, withRedraft = false) {
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)),
}));
}
},
onDirect (account, router) {
dispatch(directCompose(account, router));
},
onMention (account, router) {
dispatch(mentionCompose(account, router));
},
onOpenMedia (media, index) {
dispatch(openModal('MEDIA', { media, index }));
},
onOpenVideo (media, time) {
dispatch(openModal('VIDEO', { media, time }));
},
onBlock (account) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
},
onReport (status) {
dispatch(initReport(status.get('account'), status));
},
onMute (account) {
dispatch(initMuteModal(account));
},
onMuteConversation (status) {
if (status.get('muted')) {
dispatch(unmuteStatus(status.get('id')));
} else {
dispatch(muteStatus(status.get('id')));
}
},
onToggleHidden (status) {
if (status.get('hidden')) {
dispatch(revealStatus(status.get('id')));
} else {
dispatch(hideStatus(status.get('id')));
}
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Status));
|
src/js/pages/ProfessionalProfileIndustryPage.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import connectToStores from '../utils/connectToStores';
import translate from '../i18n/Translate';
import LoginActionCreators from '../actions/LoginActionCreators';
import LocaleStore from '../stores/LocaleStore';
import ProfileStore from '../stores/ProfileStore';
import RegisterStore from '../stores/RegisterStore';
import InputSelectText from '../components/RegisterFields/InputSelectText/InputSelectText.js';
import StepsBar from '../components/ui/StepsBar/StepsBar.js';
import TopNavBar from '../components/TopNavBar/TopNavBar.js';
import * as UserActionCreators from '../actions/UserActionCreators';
import '../../scss/pages/professional-profile-industry.scss';
function requestData(props) {
if (!props.metadata) {
UserActionCreators.requestMetadata();
}
}
function getState() {
const interfaceLanguage = LocaleStore.locale;
const metadata = ProfileStore.getMetadata();
const choices = metadata && metadata.industry ? metadata.industry.choices : [];
const user = RegisterStore.user;
const username = user && user.username ? user.username : null;
const profile = RegisterStore.profile;
return {
interfaceLanguage,
choices,
profile,
username
};
}
@translate('ProfessionalProfileIndustryPage')
@connectToStores([LocaleStore, ProfileStore, RegisterStore], getState)
export default class ProfessionalProfileIndustryPage extends Component {
static propTypes = {
// Injected by @translate:
strings : PropTypes.object,
// Injected by @connectToStores:
choices : PropTypes.array,
profile : PropTypes.object,
username : PropTypes.string,
interfaceLanguage: PropTypes.string
};
static contextTypes = {
router: PropTypes.object.isRequired
};
constructor(props) {
super(props);
this.onChange = this.onChange.bind(this);
this.goToProfessionalProfileSkillsPage = this.goToProfessionalProfileSkillsPage.bind(this);
}
componentDidMount() {
if (!this.props.username) {
this.context.router.push('/answer-username');
}
requestData(this.props);
}
goToProfessionalProfileSkillsPage() {
this.context.router.push('/professional-profile-skills');
}
onChange(choices) {
const {profile} = this.props;
LoginActionCreators.preRegisterProfile({...profile, ...{industry: choices}});
}
render() {
const {choices, profile, strings} = this.props;
const canContinue = profile && profile.industry && profile.industry.length > 0;
return (
<div className="views">
<div className="view view-main professional-profile-industry-view">
<TopNavBar iconLeft={'arrow-left'} textCenter={strings.workAndIdeas} textSize={'small'}/>
<div className="professional-profile-industry-wrapper">
<h2>{strings.title}</h2>
<InputSelectText options={choices}
placeholder={strings.searchIndustry}
searchIcon={true}
size={'small'}
chipsColor={'blue'}
onClickHandler={this.onChange}
selectedLabel={strings.selected}/>
</div>
</div>
<StepsBar color={'blue'} canContinue={canContinue} cantContinueText={strings.addIndustry} continueText={strings.continue} currentStep={0} totalSteps={2} onClickHandler={this.goToProfessionalProfileSkillsPage}/>
</div>
);
}
}
ProfessionalProfileIndustryPage.defaultProps = {
strings: {
workAndIdeas : 'Work, Ideas & Projects',
title : 'What are your professional industry?',
selected : 'Your professional industries',
searchIndustry: 'Search industry (e.g. Internet)',
addIndustry : 'Add an industry to continue',
continue : 'Continue'
}
}; |
app/main.js | laynemcnish/walksafely-react | import 'babel/register';
import React from 'react';
import Root from './containers';
import $ from 'jquery';
if(__DEV__) {
const devAjaxDebug = require('./util/dev_ajax_debug');
devAjaxDebug.initializeAjaxDebuggingUtils();
}
function renderReactApp () {
const mountPoint = document.getElementById('root');
React.render(<Root />, mountPoint);
}
$(document).ready(renderReactApp);
|
Paths/React/05.Building Scalable React Apps/8-react-boilerplate-building-scalable-apps-m8-exercise-files/Before/app/containers/LoginContainer/index.js | phiratio/Pluralsight-materials | /*
*
* LoginContainer
*
*/
import React from 'react';
import { connect } from 'react-redux';
import selectLoginContainer from './selectors';
import Login from '../../components/Login';
import { login, cancelLogin } from './actions';
export class LoginContainer extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<div>
<Login {...this.props} />
</div>
);
}
}
const mapStateToProps = selectLoginContainer();
function mapDispatchToProps(dispatch) {
return {
login: (email) => dispatch(login(email)),
cancelLogin: () => dispatch(cancelLogin()),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LoginContainer);
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.