path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
server/sonar-web/src/main/js/apps/overview/gate/gate-condition.js | vamsirajendra/sonarqube | import React from 'react';
import { getPeriodLabel, getPeriodDate } from '../helpers/periods';
import { DrilldownLink } from '../../../components/shared/drilldown-link';
import { formatMeasure } from '../../../helpers/measures';
const Measure = React.createClass({
render() {
if (this.props.value == null || isNaN(this.props.value)) {
return null;
}
let formatted = formatMeasure(this.props.value, this.props.type);
return <span>{formatted}</span>;
}
});
export default React.createClass({
render() {
let metricName = window.t('metric', this.props.condition.metric.name, 'name');
let threshold = this.props.condition.level === 'ERROR' ?
this.props.condition.error : this.props.condition.warning;
let period = this.props.condition.period ?
getPeriodLabel(this.props.component.periods, this.props.condition.period) : null;
let periodDate = getPeriodDate(this.props.component.periods, this.props.condition.period);
let classes = 'alert_' + this.props.condition.level.toUpperCase();
return (
<li className="overview-gate-condition">
<div className="little-spacer-bottom">{period}</div>
<div style={{ display: 'flex', alignItems: 'center' }}>
<div className="overview-gate-condition-value">
<DrilldownLink component={this.props.component.key} metric={this.props.condition.metric.name}
period={this.props.condition.period} periodDate={periodDate}>
<span className={classes}>
<Measure value={this.props.condition.actual} type={this.props.condition.metric.type}/>
</span>
</DrilldownLink>
</div>
<div className="overview-gate-condition-metric">
<div>{metricName}</div>
<div>
{window.t('quality_gates.operator', this.props.condition.op, 'short')}
{' '}
<Measure value={threshold} type={this.props.condition.metric.type}/>
</div>
</div>
</div>
</li>
);
}
});
|
examples/simple/src/App.js | treyhoover/react-greedy-text | import React, { Component } from 'react';
import GreedyText from 'react-greedy-text';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header>
<GreedyText>
Greedy Text!
</GreedyText>
</header>
<main style={{ flex: 1, display: 'flex' }}>
<div style={{ flex: 1 }}>
<GreedyText>
Greedy Text does a binary search to quickly maximize the font-size that will fill
its parent container without overflowing.
</GreedyText>
</div>
<div style={{ flex: 1, padding: '0px 40px' }}>
<GreedyText>
“I mean I guess if you had no other option...”
</GreedyText>
</div>
</main>
</div>
);
}
}
export default App;
|
components/User/UserProfile/PrivatePublicUserProfile/PrivatePublicUserProfile.js | slidewiki/slidewiki-platform | import PropTypes from 'prop-types';
import React from 'react';
import { List, Segment, Checkbox, Header } from 'semantic-ui-react';
import PublicUserData from '../PublicUserData';
import UserDecks from './UserDecks';
import UserCollections from '../../../DeckCollection/UserCollections';
import UserMenu from './UserMenu';
import UserRecommendations from '../UserRecommendations';
import classNames from 'classnames/bind';
import { FormattedMessage, defineMessages } from 'react-intl';
import fetchUserDecks from '../../../../actions/user/userprofile/fetchUserDecks';
class PrivatePublicUserProfile extends React.Component {
constructor(props) {
super(props);
}
showUserDecks() {
return <UserDecks decks={this.props.decks} decksMeta={this.props.decksMeta} deckListType={this.props.categoryItem} loadMoreLoading={this.props.loadMoreLoading} loadMoreError={this.props.loadMoreError} user={this.props.user} loggedinuser={this.props.loggedinuser} />;
}
showUserCollections() {
return <UserCollections user={this.props.user} loggedinuser={this.props.loggedinuser} loggedinUserId={this.props.loggedinUserId} />;
}
showUserRecommendactions() {
return <UserRecommendations loggedinuser={this.props.loggedinuser} loggedinUserId={this.props.loggedinUserId} />;
}
chooseView() {
switch (this.props.category) {
case 'playlists':
return this.showUserCollections();
case 'recommendations':
return this.showUserRecommendactions();
case 'deck':
default:
return this.showUserDecks();
}
}
handleFilterChange(event, { value }) {
this.context.executeAction(fetchUserDecks, {
deckListType: this.props.categoryItem,
params: {
username: this.props.user.uname,
sort: this.props.decksMeta.sort,
status: value,
}
});
}
render() {
let meta = this.props.decksMeta;
let profileClasses = classNames({
'tablet': this.props.loggedinuser && this.props.user.uname === this.props.loggedinuser,
'computer': this.props.loggedinuser && this.props.user.uname === this.props.loggedinuser,
'only': this.props.loggedinuser && this.props.user.uname === this.props.loggedinuser,
'sixteen': true,
'wide': true,
'column': true
});
let messages = defineMessages({
anyText: {
id: 'user.userProfile.privatePublicProfile.allStatus',
defaultMessage: 'All'
},
publicText: {
id: 'user.userProfile.privatePublicProfile.publicStatus',
defaultMessage: 'Published'
},
hiddenText: {
id: 'user.userProfile.privatePublicProfile.hiddenStatus',
defaultMessage: 'Unlisted'
}
});
return (
<div className="ui vertically padded stackable grid container" >
<div className="four wide column" >
<div className="ui stackable grid ">
<div className={profileClasses}>
<PublicUserData user={this.props.user} loggedinuser={this.props.loggedinuser} />
</div>
<div className="sixteen wide column">
<UserMenu user={this.props.user} loggedinuser={this.props.loggedinuser} choice={this.props.category} />
{this.props.user.uname === this.props.loggedinuser && this.props.category !== 'playlists' && this.props.category !== 'recommendations' &&
<Segment>
<Header size='small' dividing ><FormattedMessage id='user.userProfile.privatePublicProfile.publicationStatus' defaultMessage='Publication status' /></Header>
<List>{
[
{ value: 'any', text: this.context.intl.formatMessage(messages.anyText) },
{ value: 'public', text: this.context.intl.formatMessage(messages.publicText) },
{ value: 'hidden', text: this.context.intl.formatMessage(messages.hiddenText) },
].map((opt, index) => (
<List.Item key={index}>
<Checkbox radio name='published_status' value={opt.value} disabled={!meta.status}
aria-labelledby={`published_${opt.value}_label`} label={<label id={`published_${opt.value}_label`}>{opt.text}</label>}
checked={meta.status === opt.value} onChange={this.handleFilterChange.bind(this)} />
</List.Item>
))
}
</List>
</Segment>
}
</div>
</div>
</div>
<div className="twelve wide column" >
{this.chooseView()}
</div>
<div className="ui tab" data-tab="activity"></div>
</div>
);
}
}
PrivatePublicUserProfile.contextTypes = {
executeAction: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired
};
export default PrivatePublicUserProfile;
|
packages/core/upload/admin/src/components/EditAssetDialog/RemoveAssetDialog.js | wistityhq/strapi | import React from 'react';
import PropTypes from 'prop-types';
import { ConfirmDialog } from '@strapi/helper-plugin';
import { useRemoveAsset } from '../../hooks/useRemoveAsset';
export const RemoveAssetDialog = ({ onClose, asset }) => {
const { isLoading, removeAsset } = useRemoveAsset(onClose);
const handleConfirm = () => {
removeAsset(asset.id);
};
return (
<ConfirmDialog
isConfirmButtonLoading={isLoading}
isOpen
onToggleDialog={onClose}
onConfirm={handleConfirm}
/>
);
};
RemoveAssetDialog.propTypes = {
onClose: PropTypes.func.isRequired,
asset: PropTypes.shape({
id: PropTypes.number,
height: PropTypes.number,
width: PropTypes.number,
size: PropTypes.number,
createdAt: PropTypes.string,
ext: PropTypes.string,
name: PropTypes.string,
url: PropTypes.string,
}).isRequired,
};
|
src/parser/shaman/restoration/modules/spells/HealingRain.js | fyruna/WoWAnalyzer | import React from 'react';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import SPELLS from 'common/SPELLS';
import { TooltipElement } from 'common/Tooltip';
import Analyzer from 'parser/core/Analyzer';
import Combatants from 'parser/shared/modules/Combatants';
// 50 was too low, 100 was too high
// had no issues with 85ms
const BUFFER_MS = 85;
class HealingRain extends Analyzer {
static dependencies = {
combatants: Combatants,
};
healingRainTicks = [];
get averageHitsPerTick() {
const totalHits = this.healingRainTicks.reduce((total, tick) => total + tick.hits, 0);
return totalHits / this.healingRainTicks.length;
}
suggestions(when) {
const suggestionThreshold = this.suggestionThreshold;
when(suggestionThreshold.actual).isLessThan(suggestionThreshold.isLessThan.minor)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Try to always cast <SpellLink id={SPELLS.HEALING_RAIN_CAST.id} /> in areas where players stack. This allows the spell to consitantly hit all 6 possible targets.</span>)
.icon(SPELLS.HEALING_RAIN_CAST.icon)
.actual(`${suggestionThreshold.actual.toFixed(2)} average targets healed`)
.recommended(`${suggestionThreshold.isLessThan.minor} average targets healed`)
.regular(suggestionThreshold.isLessThan.average).major(suggestionThreshold.isLessThan.average);
});
}
get suggestionThreshold() {
return {
actual: this.averageHitsPerTick,
isLessThan: {
minor: 5,
average: 3,
major: 2,
},
style: 'number',
};
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.HEALING_RAIN_HEAL.id) {
return;
}
// Filter out pets, but only if it fully overhealed as Rain will prioritize injured pets over non-injured players
// fully overhealing guarantees that there are not enough players in the healing rain
const combatant = this.combatants.players[event.targetID];
if (!combatant && event.overheal && event.amount === 0) {
return;
}
const healingRainTick = this.healingRainTicks.find(tick => event.timestamp - BUFFER_MS <= tick.timestamp);
if (!healingRainTick) {
this.healingRainTicks.push({
timestamp: event.timestamp,
hits: 1,
});
} else {
// dirty fix for partial ticks happening at the same time as a real tick
healingRainTick.hits = healingRainTick.hits + 1 > 6 ? healingRainTick.hits = 6 : healingRainTick.hits + 1;
}
}
statistic() {
if (isNaN(this.averageHitsPerTick)) {
return false;
}
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.HEALING_RAIN_HEAL.id} />}
value={`${this.averageHitsPerTick.toFixed(2)}`}
position={STATISTIC_ORDER.OPTIONAL()}
label={(
<TooltipElement content="The average number of targets healed by Healing Rain out of the maximum amount of 6 targets.">
Average Healing Rain Targets
</TooltipElement>
)}
/>
);
}
}
export default HealingRain;
|
WebApp/wwwroot/ReactApp/src/components/codecamp/speakers/SpeakerListItem.js | pkellner/svcc-react4 | import React from 'react';
import PropTypes from 'prop-types';
export default function SpeakerListItem(props) {
const { id, firstName, lastName, company, imageUrl } = props;
const img = () => {
if (process.env.NODE_ENV === 'development') {
return (
<img
src={`assets/images/speakers/Speaker-${id}.jpg`}
alt="{this.props.firstName} {this.props.lastName}"
/>
);
}
return (
<img src={imageUrl} alt="{this.props.firstName} {this.props.lastName}" />
);
};
return (
<div className="col-12 col-sm-6 speakers-list-item">
<div className="events-speaker d-flex align-items-center">
<div className="events-speaker-photo">{img()}</div>
<div className="events-speaker-description">
<div className="name">
{firstName} {lastName}
</div>
<div className="profession">{company}</div>
</div>
</div>
</div>
);
}
SpeakerListItem.propTypes = {
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]),
firstName: PropTypes.string,
lastName: PropTypes.string,
company: PropTypes.string,
imageUrl: PropTypes.string,
};
|
docs/src/pages/landing/Sponsors.js | lgollut/material-ui | import React from 'react';
import * as PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import { makeStyles } from '@material-ui/core/styles';
import NoSsr from '@material-ui/core/NoSsr';
import MarkdownElement from 'docs/src/modules/components/MarkdownElement';
import Container from '@material-ui/core/Container';
import Divider from '@material-ui/core/Divider';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const useStyles = makeStyles(
(theme) => ({
'@global': {
'.anchor-link-style': {
position: 'absolute',
top: -9999,
left: -9999,
},
},
root: {
minHeight: 600,
textAlign: 'center',
},
markdownElement: {
padding: theme.spacing(4, 0),
},
}),
{ name: 'Sponsors' },
);
export default function Sponsors({ docs }) {
const classes = useStyles();
const userLanguage = useSelector((state) => state.options.userLanguage);
const { rendered } = docs[userLanguage];
return (
<div className={classes.root}>
<NoSsr defer>
<Container maxWidth="md">
<Divider />
{rendered.map((renderedMarkdown, index) => {
return (
<MarkdownElement
key={index}
className={classes.markdownElement}
renderedMarkdown={renderedMarkdown}
/>
);
})}
</Container>
</NoSsr>
</div>
);
}
Sponsors.propTypes = {
docs: PropTypes.object.isRequired,
};
const requireRaw = require.context('./', false, /\.md$/);
export async function getInitialProps() {
const { docs } = prepareMarkdown({ pageFilename: '/', requireRaw });
return { docs };
}
|
app/components/Home.js | albertmejia/empire_room | import React from 'react';
import {home} from '../styles/home.scss';
import Carousel from './Carousel';
import UpcomingEvents from './UpcomingEvents';
import axios from 'axios';
import { WP_DOMAIN } from '../../wp.config';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
eventsList: [],
carouselImages: []
};
}
componentWillMount() {
axios.get(`${WP_DOMAIN}/wp-json/wp/v2/events`)
.then((res) => {
this.setState({eventsList: res.data});
})
.catch((err) => {
console.log(err, 'there was an error');
});
axios.get(`${WP_DOMAIN}/wp-json/wp/v2/carousel_images`)
.then((res) => {
const carouselImagesArray = res.data.map((image) => {
return image.acf.carousel_image;
});
this.setState({carouselImages: carouselImagesArray});
})
.catch((err) => {
console.log(err, 'there was an error');
});
}
componentDidMount() {
window.scrollTo(0, 0);
}
render() {
return (
<div className={home}>
<Carousel carouselImages={this.state.carouselImages}/>
<UpcomingEvents eventsList={this.state.eventsList} isHomepage={true}/>
</div>
);
}
}
export default Home;
|
todo-list/src/List.js | Nodewarrior/react-examples | import React, { Component } from 'react';
const List = props => (
<ul>
{props.items.map((item, index) => <li key={index}>{item}</li>)}
</ul>
);
export default List; |
src/components/App.js | tanykim/julie-and-julia | import React, { Component } from 'react';
import Script from './../data/data.json';
import SearchForm from './SearchForm';
import Visualization from './Visualization';
import SecretStory from './SecretStory';
import TextLineList from './TextLineList';
class App extends Component {
constructor(props) {
super(props);
this.state = {
data: Script,
searchedLines: [],
highlighted: [],
lineNo: null,
story: ''
};
this.handleScroll = this.handleScroll.bind(this);
this.onHighlight = this.onHighlight.bind(this);
this.onReceiveResult = this.onReceiveResult.bind(this);
this.onResetResult = this.onResetResult.bind(this);
this.showSecretStory = this.showSecretStory.bind(this);
this.textHovered = this.textHovered.bind(this);
}
//scroll
componentDidMount() {
window.addEventListener('scroll', this.handleScroll);
}
handleScroll(event) {
const scrollTop = event.srcElement.body.scrollTop;
const resultH = document.getElementById('result-container').clientHeight;
//220 is roughly the height of the bottom part, with some buffer
//show the default when scoll is over
if (scrollTop > 220 && window.innerHeight - resultH < -scrollTop) {
this.setState({isHidden: true});
} else {
this.setState({isHidden: false});
}
}
//highlight lines in sync with text enter
onHighlight(tempResult) {
this.setState({highlighted: tempResult});
}
//when text input submitted (return key pressed)
onReceiveResult(result, searchStr) {
let searchedLines = result.map((id) => [id, this.state.data[id]]);
this.setState({
searchedLines: searchedLines,
searchStr: searchStr,
story: ''
});
}
//secret message
showSecretStory(story) {
this.setState({story: story});
}
//when Backspace is pressed after results are shown
onResetResult() {
this.setState({
searchedLines: []
})
}
textHovered(lineNo) {
this.setState({linkedLineNo: lineNo});
}
render() {
return (
<div className="container-fluid">
{/* visualization */}
<div className="row vis-container" id="vis-width">
<div className="col-xs-12 hidden-xs hidden-sm vis">
<Visualization
data={this.state.data}
highlighted={this.state.highlighted}
linkedLineNo={this.state.linkedLineNo}
searchedLines={this.state.searchedLines}
/>
</div>
</div>
{/* result */}
<div className="row result-container" id="result-container">
<div className="col-xs-12 col-md-6 col-md-offset-3 story">
<SecretStory story={this.state.story} />
</div>
<div className="col-xs-12 col-md-10 col-md-offset-1 col-lg-6 col-lg-offset-3 result">
<TextLineList
searchedLines={this.state.searchedLines}
searchStr={this.state.searchStr}
onHovered={this.textHovered}
/>
</div>
</div>
{/* default bottom */}
<div className="default-container">
<div className="row">
<div className={this.state.isHidden ? 'col-xs-12 title small' : 'col-xs-12 title'}>
Julie <span className="amp">&</span> Julia
</div>
</div>
<div className={this.state.isHidden ? 'hide' : 'show'}>
<SearchForm
data={this.state.data}
onHighlight={this.onHighlight}
onReceiveResult={this.onReceiveResult}
onResetResult={this.onResetResult}
onSecretStory={this.showSecretStory}
/>
<div className="row">
<div className="col-xs-12 footer">
<ul>
<li>Inspired by <a href="https://twitter.com/pencilpenbrush/status/803756815225909248" target="_blacnk">@pencilpenbrush</a></li>
<li>View on <a href="https://github.com/tanykim/julie-and-julia" target="_blacnk">GitHub</a></li>
<li><a href="http://www.script-o-rama.com/movie_scripts/j/julie-and-julia-script-transcript.html" target="_blacnk">Original Script</a></li>
</ul>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default App;
|
src/backward/Widgets/Container.js | sampsasaarela/NativeBase | /* @flow */
import React from 'react';
import { View, Image, ScrollView } from 'react-native';
import { connectStyle } from 'native-base-shoutem-theme';
import { Footer } from '../../basic/Footer';
import { Fab } from '../../basic/Fab';
import _ from 'lodash';
import mapPropsToStyleNames from '../../Utils/mapPropsToStyleNames';
import { ViewNB } from './View';
import { Header } from './Header';
import { Content } from './Content';
import NativeBaseComponent from '../Base/NativeBaseComponent';
import computeProps from '../../Utils/computeProps';
class Container extends NativeBaseComponent {
propTypes: {
style : React.PropTypes.object
}
renderHeader() {
if (Array.isArray(this.props.children)) {
return _.find(this.props.children, (item) => {
if (item && (item.type.displayName === 'Styled(Header)' || item.type.displayName === 'Styled(SHeader)')) {
return true;
}
});
} else if (this.props.children && (this.props.children.type.displayName === 'Styled(Header)' || this.props.children.type.displayName === 'Styled(SHeader)')) {
return this.props.children;
}
}
renderContent() {
if (Array.isArray(this.props.children)) {
return _.filter(this.props.children, (item) => {
if (item && (item.type.displayName === 'Styled(ViewNB)' || item.type.displayName ===
'Styled(Content)' || item.type === Image || item.type === View ||
item.type === ScrollView || item.type.displayName === 'Styled(Fab)')) {
return true;
}
});
} else if (this.props.children && (this.props.children.type.displayName === 'Styled(Content)' ||
this.props.children.type.displayName === 'Styled(ViewNB)' ||
this.props.children.type === View || this.props.children.type === Image ||
this.props.children.type === ScrollView)) {
return this.props.children;
}
}
renderFooter() {
if (Array.isArray(this.props.children)) {
return _.find(this.props.children, (item) => {
if (item && item.type.displayName === 'Styled(Footer)') {
return true;
}
});
} else if (this.props.children && this.props.children.type.displayName === 'Styled(Footer)') {
return this.props.children;
}
}
prepareRootProps() {
const type = {
flex: 1,
};
const defaultProps = {
style: type,
};
return computeProps(this.props, defaultProps);
}
render() {
return (
<View ref={c => this._root = c} {...this.prepareRootProps()}>
{this.renderHeader()}
{this.renderContent()}
{this.renderFooter()}
</View>
);
}
}
Container.propTypes = {
...View.propTypes,
style: React.PropTypes.object,
};
const StyledContainer = connectStyle('NativeBase.Container', {}, mapPropsToStyleNames)(Container);
export {
StyledContainer as Container,
};
|
index.js | toubou91/react-lorem | import React from 'react';
import { render } from 'react-dom';
import Lorem from './Lorem';
render(
<div>
<Lorem />
<Lorem reps={{ times: 4, lineBreak: true }} color={'yellow'} fontSize={'medium'} />
<Lorem color={'blue'} fontSize={30} />
<Lorem color={'rgb(154,67,123)'} fontSize={'large'} />
</div>,
document.getElementById('root')
);
|
client/app/components/IssueIcon/index.js | Kielan/onDemanager | import React from 'react';
class IssueIcon extends React.Component {
render() {
return (
<svg
height="1em"
width="0.875em"
className={ this.props.className }
>
<path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" />
</svg>
);
}
}
export default IssueIcon;
|
test/helpers/shallowRenderHelper.js | jc784999074/study-react | /**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
app/javascript/mastodon/components/button.js | rekif/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class Button extends React.PureComponent {
static propTypes = {
text: PropTypes.node,
onClick: PropTypes.func,
disabled: PropTypes.bool,
block: PropTypes.bool,
secondary: PropTypes.bool,
size: PropTypes.number,
className: PropTypes.string,
style: PropTypes.object,
children: PropTypes.node,
};
static defaultProps = {
size: 36,
};
handleClick = (e) => {
if (!this.props.disabled) {
this.props.onClick(e);
}
}
setRef = (c) => {
this.node = c;
}
focus() {
this.node.focus();
}
render () {
const style = {
padding: `0 ${this.props.size / 2.25}px`,
height: `${this.props.size}px`,
lineHeight: `${this.props.size}px`,
...this.props.style,
};
const className = classNames('button', this.props.className, {
'button-secondary': this.props.secondary,
'button--block': this.props.block,
});
return (
<button
className={className}
disabled={this.props.disabled}
onClick={this.handleClick}
ref={this.setRef}
style={style}
>
{this.props.text || this.props.children}
</button>
);
}
}
|
app/index.js | AidanNichol/stedwards-booking-system | import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { AppContainer } from 'react-hot-loader';
import {configureStore} from 'store';
import Root from 'containers/Root';
// import './styles/main.scss';
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
if (module.hot) {
module.hot.accept('containers/Root', () => {
const NewRoot = require('containers/Root').default;
render(
<AppContainer>
<NewRoot store={store} history={history} />
</AppContainer>,
document.getElementById('root')
);
});
}
|
src/product.js | slx-dev/react-testing | import React from 'react';
import {Row,Col} from 'reactstrap';
import PRODUCTS from './products.json';
// import Gallery from './gallery';
var $ = require ('jquery');
export default class Product extends React.Component {
render() {
var getProductData = id => $.grep(PRODUCTS, function(e){
return e.id === id
});
var productData = getProductData(this.props.params.id)[0];
return (
<div>
<Row>
<Col className="col-md-7">
<Row id="icon">
<Col className="col-md-3 app-title">
<img alt="{productData.name}" src={productData.iconUrl} />
</Col>
<Col className="col-md-9">
<h3 className="applicationName">
{productData.name}
</h3>
<p>{productData.shortDescription}</p>
</Col>
</Row>
<div id="product-box">
<img alt="{productData.name}" src={"../" + productData.imageUrl} className="modal-content" id="img01"/>
</div>
<p/>
{productData.description}
<p/><h5 className="lead">Support</h5>
<hr/>
We provide support for this product without any charges. If you have any problems just submit a <a href="">ticket</a>.
<p/>
<h5 className="lead">Release notes</h5>
<hr/>
<b>VER. {productData.versionNo} ({productData.releaseDate.substring(0,10)})</b><br/>
<p/><pre>Important bug fixes and interface improvements</pre>
</Col>
<Col className="col-md-4 sidebar-l sidebar-right hentry">
<div className="sidebar-right-box small">
<div className="price">
<b><span className="lead pull-left">Regular License</span></b>
<span className=" amount lead">€180</span>
</div>
<p/>
✓ Quality control
<br/>
✓ Future updates
<br/>✓ 6 months support from HausTech
<br /><a href=""><span className="small">What does support include?</span></a>
<form action="">
<p/><input type="checkbox" name="extend-support" value="extend-yes"/> Extend support to 12 months
<p/>
<a role="button" className="btn btn-info btn-md btn-block btn-success" href={"/dl/" + productData.name + ".application"}>Launch</a>
<button className="btn btn-info btn-md btn-block btn-primary"><span className="glyphicon glyphicon-shopping-cart"/> Buy Now</button>
</form>
</div>
<div>
<hr/>
<table className="small">
<tbody>
<tr>
<td><b>Last Update</b></td>
<td>23 August, 2016</td>
</tr>
<tr>
<td><b>Created</b></td>
<td>{productData.releaseDate.substring(0,10)}</td>
</tr>
<tr>
<td><b>Compatible Platforms</b></td>
<td>Microsoft Windows 9, 10<br/>OSX 10.10+</td>
</tr>
</tbody>
</table>
</div>
</Col>
</Row>
</div>
);
}
}
|
analysis/demonhuntervengeance/src/modules/talents/SpiritBombSoulsConsume.js | anom0ly/WoWAnalyzer | import { t } from '@lingui/macro';
import { formatPercentage } from 'common/format';
import SPELLS from 'common/SPELLS';
import { SpellLink } from 'interface';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Events from 'parser/core/Events';
import BoringSpellValueText from 'parser/ui/BoringSpellValueText';
import Statistic from 'parser/ui/Statistic';
import STATISTIC_CATEGORY from 'parser/ui/STATISTIC_CATEGORY';
import STATISTIC_ORDER from 'parser/ui/STATISTIC_ORDER';
import React from 'react';
const MS_BUFFER = 100;
class SpiritBombSoulsConsume extends Analyzer {
get totalGoodCasts() {
return this.soulsConsumedByAmount[4] + this.soulsConsumedByAmount[5];
}
get totalCasts() {
return Object.values(this.soulsConsumedByAmount).reduce((total, casts) => total + casts, 0);
}
get percentGoodCasts() {
return this.totalGoodCasts / this.totalCasts;
}
get suggestionThresholdsEfficiency() {
return {
actual: this.percentGoodCasts,
isLessThan: {
minor: 0.9,
average: 0.85,
major: 0.8,
},
style: 'percentage',
};
}
castTimestamp = 0;
castSoulsConsumed = 0;
cast = 0;
soulsConsumedByAmount = Array.from({ length: 6 }, (x) => 0);
/* Feed The Demon talent is taken in defensive builds. In those cases you want to generate and consume souls as quickly
as possible. So how you consume your souls down matter. If you dont take that talent your taking a more balanced
build meaning you want to consume souls in a way that boosts your dps. That means feeding the souls into spirit
bomb as efficiently as possible (cast at 4+ souls) for a dps boost and have soul cleave absorb souls as little as
possible since it provides no extra dps.
*/
constructor(...args) {
super(...args);
this.active =
this.selectedCombatant.hasTalent(SPELLS.SPIRIT_BOMB_TALENT.id) &&
!this.selectedCombatant.hasTalent(SPELLS.FEED_THE_DEMON_TALENT.id);
this.addEventListener(
Events.cast.by(SELECTED_PLAYER).spell(SPELLS.SPIRIT_BOMB_TALENT),
this.onCast,
);
this.addEventListener(
Events.changebuffstack.by(SELECTED_PLAYER).spell(SPELLS.SOUL_FRAGMENT_STACK),
this.onChangeBuffStack,
);
this.addEventListener(Events.fightend, this.onFightend);
}
onCast(event) {
if (this.cast > 0) {
this.countHits();
}
this.castTimestamp = event.timestamp;
this.cast += 1;
}
onChangeBuffStack(event) {
if (event.oldStacks < event.newStacks) {
return;
}
if (event.timestamp - this.castTimestamp < MS_BUFFER) {
const soulsConsumed = event.oldStacks - event.newStacks;
this.castSoulsConsumed += soulsConsumed;
}
}
countHits() {
if (!this.soulsConsumedByAmount[this.castSoulsConsumed]) {
this.soulsConsumedByAmount[this.castSoulsConsumed] = 1;
this.castSoulsConsumed = 0;
return;
}
this.soulsConsumedByAmount[this.castSoulsConsumed] += 1;
this.castSoulsConsumed = 0;
}
onFightend() {
this.countHits();
}
suggestions(when) {
when(this.suggestionThresholdsEfficiency).addSuggestion((suggest, actual, recommended) =>
suggest(
<>
Try to cast <SpellLink id={SPELLS.SPIRIT_BOMB_TALENT.id} /> at 4 or 5 souls.
</>,
)
.icon(SPELLS.SPIRIT_BOMB_TALENT.icon)
.actual(
t({
id: 'demonhunter.vengeance.suggestions.spiritBomb.soulsConsumed',
message: `${formatPercentage(this.percentGoodCasts)}% of casts at 4+ souls.`,
}),
)
.recommended(`>${formatPercentage(recommended)}% is recommended`),
);
}
statistic() {
return (
<Statistic
position={STATISTIC_ORDER.CORE(6)}
category={STATISTIC_CATEGORY.TALENTS}
size="flexible"
dropdown={
<>
<table className="table table-condensed">
<thead>
<tr>
<th>Stacks</th>
<th>Casts</th>
</tr>
</thead>
<tbody>
{Object.values(this.soulsConsumedByAmount).map((castAmount, stackAmount) => (
<tr key={stackAmount}>
<th>{stackAmount}</th>
<td>{castAmount}</td>
</tr>
))}
</tbody>
</table>
</>
}
>
<BoringSpellValueText spell={SPELLS.SPIRIT_BOMB_TALENT}>
<>
{formatPercentage(this.percentGoodCasts)}% <small>good casts</small>
</>
</BoringSpellValueText>
</Statistic>
);
}
}
export default SpiritBombSoulsConsume;
|
docs/src/Routes.js | wjb12/react-bootstrap | import React from 'react';
import Root from './Root';
import HomePage from './HomePage';
import IntroductionPage from './IntroductionPage';
import GettingStartedPage from './GettingStartedPage';
import ComponentsPage from './ComponentsPage';
import SupportPage from './SupportPage';
import NotFoundPage from './NotFoundPage';
import {Route, DefaultRoute, NotFoundRoute} from 'react-router';
export default (
<Route name="home" path="/" handler={Root}>
<DefaultRoute handler={HomePage}/>
<NotFoundRoute handler={NotFoundPage} />
<Route name="introduction" path="introduction.html" handler={IntroductionPage} />
<Route name="getting-started" path="getting-started.html" handler={GettingStartedPage} />
<Route name="components" path="components.html" handler={ComponentsPage} />
<Route name="support" path="support.html" handler={SupportPage} />
</Route>
);
|
src/routes/Recover/components/EmailForm/EmailForm.js | ronihcohen/magic-vote | import React from 'react'
import PropTypes from 'prop-types'
import { Field, reduxForm } from 'redux-form'
import { TextField } from 'redux-form-material-ui'
import RaisedButton from 'material-ui/RaisedButton'
import { required, email } from 'utils/forms'
import { RECOVER_EMAIL_FORM_NAME } from 'constants'
import classes from './EmailForm.scss'
export const EmailForm = ({
account,
handleSubmit,
submitting,
pristine,
valid
}) => (
<form className={classes.container} onSubmit={handleSubmit}>
<h4>Send Recovery Code To Email</h4>
<Field
name="email"
component={TextField}
label="Email"
validate={[required, email]}
/>
<div className={classes.submit}>
<RaisedButton label="Send" primary type="submit" disabled={submitting} />
</div>
</form>
)
EmailForm.propTypes = {
account: PropTypes.shape({
providerData: PropTypes.array
}),
pristine: PropTypes.bool, // added by redux-form
valid: PropTypes.bool, // added by redux-form
handleSubmit: PropTypes.func.isRequired, // added by redux-form
submitting: PropTypes.bool // added by redux-form
}
export default reduxForm({
form: RECOVER_EMAIL_FORM_NAME
})(EmailForm)
|
src/articles/Single.js | NewSpring/Apollos | import React from 'react';
import { ScrollView } from 'react-native';
import { compose, mapProps, pure } from 'recompose';
import withArticle from '@data/withArticle';
import withCachedContent from '@data/withCachedContent';
import BackgroundView from '@ui/BackgroundView';
import Header from '@ui/Header';
import ContentView, { Title, ByLine, HTMLView } from '@ui/ContentView';
import RelatedContent from '@ui/RelatedContent';
import SecondaryNav, { Like, Share } from '@ui/SecondaryNav';
const enhance = compose(
pure,
mapProps(({ match: { params: { id } } }) => ({ id })),
withArticle,
withCachedContent,
);
const ShareLink = withArticle(Share);
const ArticleSingle = enhance(
({
content: {
authors = [],
title = '',
content: {
isLiked, body, tags, ...otherContentProps
} = {},
} = {},
id,
isLoading,
}) => (
<BackgroundView>
<Header titleText="Article" backButton />
<ScrollView>
<ContentView isLoading={isLoading} {...otherContentProps}>
<Title>{title}</Title>
<ByLine authors={authors} />
<HTMLView>{body}</HTMLView>
</ContentView>
{// Don't render till data is ready.
// Consider adding placeholder views for the content above.
!isLoading && <RelatedContent tags={tags} excludedIds={[id]} />}
</ScrollView>
<SecondaryNav isLoading={isLoading} fullWidth>
<ShareLink id={id} />
<Like id={id} isLiked={isLiked} />
</SecondaryNav>
</BackgroundView>
),
);
export default ArticleSingle;
|
frontend/app/js/components/settings/plugins/index.js | serverboards/serverboards | import React from 'react'
import rpc from 'app/rpc'
import Flash from 'app/flash'
import PluginDetails from './details'
import plugin from 'app/utils/plugin'
import {merge, object_list_to_map} from 'app/utils'
import event from 'app/utils/event'
import i18n from 'app/utils/i18n'
import {set_modal, goto} from 'app/utils/store'
import store from 'app/utils/store'
import cache from 'app/utils/cache'
import PropTypes from 'prop-types'
import {SectionMenu} from 'app/components'
require('sass/cards.sass')
import PluginCard from './card'
class Plugins extends React.Component{
constructor(props){
super(props)
this.state = {
plugins: [],
updates: {},
settings: {}
}
this.reload_plugin_list = this.reload_plugin_list.bind(this)
}
componentDidMount(){
event.on("plugins.reloaded", this.reload_plugin_list)
this.load_plugin_list()
}
load_plugin_list(){
cache.plugins().then( pluginsd => {
let plugins = Object.values(pluginsd)
plugins = plugins.sort( (a,b) => (a.name || "").localeCompare(b.name || "") )
this.setState({plugins})
}).catch((e) => {
Flash.error(`Could not load plugin list.\n ${e}`)
})
plugin.call("serverboards.core.update/marketplace", "check_updates", [])
.then( orig => {
let updates = {}
for (let o of orig){
updates[o.id] = o.updated
}
this.setState({updates})
})
rpc.call("plugin.component.catalog", {type: "settings"})
.then( formlist => {
let settings = {}
for (let f of formlist){
settings[f.plugin]=(settings[f.plugin] || []).concat(f)
}
this.setState({settings})
})
}
reload_plugin_list(){
cache.invalidate("plugins") // ensure invalidated. May happen later too. Needed at the cache side too.
this.load_plugin_list()
}
componentWillUnmount(){
event.off("plugins.reloaded", this.reload_plugin_list)
}
handleUpdate(id){
let updates = {...this.state.updates}
updates[id] = "updating"
this.setState({updates})
rpc.call("action.trigger", ["serverboards.core.update/update_plugin", {"plugin_id": id}])
.then( () => {
this.reload_plugin_list.bind(this)
Flash.success(i18n("Plugin updated successfully."))
})
.catch( Flash.error )
}
render(){
const {plugins, settings, updates} = this.state
return (
<div className="expand with scroll and padding">
<div className="ui container">
<div className="ui cards">
{plugins.map((p) => (
<PluginCard
key={p.id}
plugin={{...p, updated: updates[p.id]}}
onUpdate={() => this.handleUpdate(p.id)}
onOpenDetails={() => {set_modal('plugin.details',{plugin: p})}}
onOpenSettings={settings[p.id] ? (
() => set_modal('plugin.settings',{plugin: p, settings: settings[p.id] })
) : null }
/>
))}
</div>
</div>
</div>
)
}
}
Plugins.contextTypes = {
router: PropTypes.object
}
export default Plugins
|
1m_Redux_Lynda/Ex_Files_Learning_Redux/Exercise Files/Ch05/05_03/finished/src/index.js | yevheniyc/C | import C from './constants'
import React from 'react'
import { render } from 'react-dom'
import routes from './routes'
import sampleData from './initialState'
import storeFactory from './store'
import { Provider } from 'react-redux'
import { addError } from './actions'
const initialState = (localStorage["redux-store"]) ?
JSON.parse(localStorage["redux-store"]) :
sampleData
const saveState = () =>
localStorage["redux-store"] = JSON.stringify(store.getState())
const handleError = error => {
store.dispatch(
addError(error.message)
)
}
const store = storeFactory(initialState)
store.subscribe(saveState)
window.React = React
window.store = store
window.addEventListener("error", handleError)
render(
<Provider store={store}>
{routes}
</Provider>,
document.getElementById('react-container')
)
|
src/react.js | joshblack/redux | import React from 'react';
import createAll from './components/createAll';
export const { Provider, Connector, provide, connect } = createAll(React);
|
src/components/about.js | MichaelMansourati/earCamera | import React from 'react'
import { Helmet } from 'react-helmet'
import '../styles/about.css'
const About = () => (
<div className="page-goes-here" id="about">
<Helmet>
<link
href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css"
rel="stylesheet"
integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN"
crossorigin="anonymous"
/>
</Helmet>
<div className="textArea">
<p>
Ear Camera is a collective of bodies creating cochlear art. We are a
capillary community, a neural network, an ear that listens, a camerata
of peers. Our concerts are a living snapshot of our inner chambers
developed in dark rooms and focused onto vibrating membranes. We are a
lens that reflects the society in which we live. We believe that all
human experience, rendered in photorealistic detail, is worthy of
amplification.
</p>
<p>
<span>Ear Camera is: </span>
<a target="_blank" href="http://www.tommysaxophone.com">
Tommy Davis
</a>
<span> // </span>
<a target="_blank" href="https://www.indiayeshe.com">
India Gailey
</a>
<span> // </span>
<a target="_blank" href="http://www.jglasermusic.com">
Joseph Glaser
</a>
<span> // </span>
<a target="_blank" href="https://soundcloud.com/noa-haran">
Noa Haran
</a>
<span> // </span>
<a target="_blank" href="https://soundcloud.com/justin-jaramillo-7">
Justin Jaramillo
</a>
<span> // </span>
<a target="_blank" href="https://soundcloud.com/michaelkimsheng">
Michael Kim-Sheng
</a>
<span> // </span>
<a target="_blank" href="http://michaelmansourati.com">
Michael Mansourati
</a>
<span> // </span>
<a target="_blank" href="http://www.jamesrubinomusic.com">
James Rubino
</a>
<span> // </span>
<a target="_blank" href="https://www.soundcloud.com/keithstratton">
Keith Stratton
</a>
</p>
<p>
<a target="_blank" href="https://www.facebook.com/EarCamera/">
<i className="fa fa-facebook-official" aria-hidden="true" />
</a>
<span className="faSlash"> // </span>
<a target="_blank" href="https://www.instagram.com/ear_camera">
<i className="fa fa-instagram" aria-hidden="true" />
</a>
<span className="faSlash"> // </span>
<a target="_blank" href="https://twitter.com/earCamera">
<i className="fa fa-twitter" aria-hidden="true" />
</a>
<span className="faSlash"> // </span>
<a href="mailto:[email protected]">
<i className="fa fa-envelope-o" aria-hidden="true" />
</a>
</p>
<p>
Logo by <a href="https://www.kasiasuro.com">Kasia Suro</a>.
</p>
</div>
<div className="yt-container">
<iframe
className="youtube"
id="about-yt"
width="560px"
height="315px"
src="https://www.youtube.com/embed/65dl6LzR1ec"
frameBorder="0"
allowFullScreen
/>
</div>
</div>
)
export default About
|
fixtures/kitchensink/src/features/webpack/UnknownExtInclusion.js | saschatimme/reason-react-scripts | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react'
import aFileWithExtUnknown from './assets/aFileWithExt.unknown'
const text = aFileWithExtUnknown.includes('base64')
? atob(aFileWithExtUnknown.split('base64,')[1]).trim()
: aFileWithExtUnknown
export default () => (
<p id="feature-unknown-ext-inclusion">{text}.</p>
)
|
frontend/sections/timeline/explore/explore.js | apostolidhs/wiregoose | import isEmpty from 'lodash/isEmpty';
import React from 'react';
import PropTypes from 'prop-types';
import CSSModules from 'react-css-modules';
import { LinkContainer } from 'react-router-bootstrap';
import Nav from 'react-bootstrap/lib/Nav';
import NavItem from 'react-bootstrap/lib/NavItem';
import Panel from 'react-bootstrap/lib/Panel';
import Row from 'react-bootstrap/lib/Row';
import Col from 'react-bootstrap/lib/Col';
import FontAwesome from 'react-fontawesome';
import { Link } from 'react-router';
import styles from '../timeline.less';
import { publish } from '../../../components/events/events.js';
import Header from '../../../components/timeline/header.js';
import Timeline from '../../../components/timeline/timeline.js';
import TimelinePage from '../../../components/timeline/page.js';
import InfiniteScrollPage from '../../../components/infinite-scroll/page.js';
import * as WiregooseApi from '../../../components/services/wiregoose-api.js';
import {createResponseHandler, composeCachedResponse}
from '../../../components/offline-mode/cached-explore-timeline.js';
import BrowserLanguageDetection from '../../../components/utilities/browser-language-detection.js';
import tr from '../../../components/localization/localization.js';
@CSSModules(styles, {
allowMultiple: true,
})
export default class Explore extends InfiniteScrollPage {
static page = new TimelinePage();
state = {}
timeline = undefined // ref
componentDidMount() {
this.cachedResponseHandler = createResponseHandler();
Explore.page.componentDidMount(this);
super.componentDidMount();
}
componentWillUnmount() {
super.componentWillUnmount();
Explore.page.componentWillUnmount();
if (this.state.cachedResponsePromise) {
Explore.page.invalidateCache();
}
}
retrieveTimeline = () => {
if (this.state.cachedResponsePromise) {
return Promise.resolve({data: { data: {} }});;
}
return WiregooseApi.timeline.explore(
Explore.page.lastFeeds,
BrowserLanguageDetection(),
{
onOffline: () => {
if (isEmpty(Explore.page.virtualList)) {
const cachedResp = composeCachedResponse();
const cachedResponsePromise = cachedResp && Promise.resolve(cachedResp);
this.setState({cachedResponsePromise});
return cachedResponsePromise;
}
}
}
)
.then(resp => this.cachedResponseHandler(resp));
}
handleMetaData = () => {
publish('page-ready', {
title: tr.timelineExploreTitle,
keywords: tr.timelineExploreKeywords,
description: tr.timelineExploreDescription
// image:
// time:
// lang:
});
}
onScroll = () => {
Explore.page.onScroll(this);
}
renderCachedContentNotification() {
return (
<Panel>
<Row>
<Col sm={1}>
<h1 className="text-center w-m-0">
<FontAwesome name="wifi" className="text-warning" />
</h1>
</Col>
<Col sm={11}>
<strong>{tr.offlineModeTitle}</strong>
<p>
{tr.offlineModeDescription}
{' '}
{tr.or}
{' '}
<a href="#" title={tr.refresh} onClick={evt => {evt.preventDefault(); location.reload()}}>
{tr.refresh}
</a>
</p>
</Col>
</Row>
</Panel>
);
}
render() {
return (
<div>
<Header>
<Nav bsStyle="pills" activeKey={1}>
<LinkContainer to="/">
<NavItem eventKey={1}>{tr.explore}</NavItem>
</LinkContainer>
</Nav>
</Header>
{this.state.cachedResponsePromise &&
this.renderCachedContentNotification()
}
<Timeline ref={(ref) => this.timeline = ref} />
</div>
);
}
}
|
docs/src/sections/ReferListSection.js | tigerandgirl/ssc-refer | import React from 'react';
import PropTable from '../PropTable';
import Anchor from '../Anchor';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function ReferListSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="referlist">参照组件(列表参照组件)</Anchor> <small><code><ReferList></code></small>
</h2>
<h3><Anchor id="refer-list">列表参照组件</Anchor></h3>
<p>使用<code>referDataUrl</code>设置数据源地地。</p>
<p>使用<code>referConditions</code>设置数据请求的参数,详见属性说明</p>
<p>使用<code>defaultSelected</code>设置默认值,值为一个json数组,当是单选时只有一个item,设置为多选时为多个</p>
<p>需要引用本模块样式,如<code>import 'ssc-refer/css/referStyle.css';</code></p>
<ReactPlayground codeText={Samples.ReferList} />
</div>
);
}
|
src/containers/search_result_list.js | etchoi/theTenSpot | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import axios from 'axios';
import { showItem } from '../actions';
class SearchResultList extends Component {
formatPrice(str) {
let price = parseInt(str);
return (price/100).toFixed(2);
}
renderResult(resultData) {
return _.map(resultData, data => {
const id = data.ASIN[0];
return (
<li key={data.ASIN[0]} onClick={this.showItem.bind(this, id)} className="search-list-item">
<div className="row">
<img className="col s3" src={data.SmallImage[0].URL[0]} />
<h6 className="col s9">{data.ItemAttributes[0].Title[0]}</h6>
{ data.ItemAttributes[0].ListPrice[0].Amount[0] ? (
<p>{'$'+this.formatPrice(data.ItemAttributes[0].ListPrice[0].Amount[0])}</p>
) : (
<p>No Price</p>
)}
<p>{data.SalesRank}</p>
</div>
</li>
);
})
}
render() {
return (
<ul className="search-list col s4">
{this.renderResult(this.props.search_result)}
</ul>
)
}
showItem(id) {
this.props.dispatch(showItem(id))
}
renderImage() {
// HERE HERE HERE
}
}
function mapStateToProps({ search_result }) {
return { search_result };
}
export default connect(mapStateToProps)(SearchResultList);
|
webpack/scenes/Subscriptions/components/SubscriptionsToolbar/SubscriptionsToolbar.js | mccun934/katello | import React from 'react';
import PropTypes from 'prop-types';
import { Row, Col, Form, FormGroup, Button } from 'patternfly-react';
import { LinkContainer } from 'react-router-bootstrap';
import { noop } from 'foremanReact/common/helpers';
import { translate as __ } from 'foremanReact/common/I18n';
import Search from '../../../../components/Search/index';
import TooltipButton from '../../../../move_to_pf/TooltipButton';
import OptionTooltip from '../../../../move_to_pf/OptionTooltip';
const SubscriptionsToolbar = ({
canManageSubscriptionAllocations,
disableManifestActions,
disableManifestReason,
disableDeleteButton,
disableDeleteReason,
disableAddButton,
getAutoCompleteParams,
updateSearchQuery,
onDeleteButtonClick,
onSearch,
onManageManifestButtonClick,
onExportCsvButtonClick,
tableColumns,
toolTipOnChange,
toolTipOnclose,
}) => (
<Row className="toolbar-pf table-view-pf-toolbar-external">
<Col sm={12}>
<Form className="toolbar-pf-actions">
<FormGroup className="toolbar-pf-filter">
<Search
onSearch={onSearch}
getAutoCompleteParams={getAutoCompleteParams}
updateSearchQuery={updateSearchQuery}
/>
</FormGroup>
<div className="option-tooltip-container">
<OptionTooltip options={tableColumns} icon="fa-columns" id="subscriptionTableTooltip" onChange={toolTipOnChange} onClose={toolTipOnclose} />
</div>
<div className="toolbar-pf-action-right">
<FormGroup>
{canManageSubscriptionAllocations &&
<LinkContainer
to="subscriptions/add"
disabled={disableManifestActions || disableAddButton}
>
<TooltipButton
tooltipId="add-subscriptions-button-tooltip"
tooltipText={disableManifestReason}
tooltipPlacement="top"
title={__('Add Subscriptions')}
disabled={disableManifestActions}
bsStyle="primary"
/>
</LinkContainer>
}
<Button onClick={onManageManifestButtonClick}>
{__('Manage Manifest')}
</Button>
<Button
onClick={onExportCsvButtonClick}
>
{__('Export CSV')}
</Button>
{canManageSubscriptionAllocations &&
<TooltipButton
bsStyle="danger"
onClick={onDeleteButtonClick}
tooltipId="delete-subscriptions-button-tooltip"
tooltipText={disableDeleteReason}
tooltipPlacement="top"
title={__('Delete')}
disabled={disableManifestActions || disableDeleteButton}
/>
}
</FormGroup>
</div>
</Form>
</Col>
</Row>
);
SubscriptionsToolbar.propTypes = {
...Search.propTypes,
tableColumns: OptionTooltip.propTypes.options,
canManageSubscriptionAllocations: PropTypes.bool,
disableManifestActions: PropTypes.bool,
disableManifestReason: PropTypes.string,
disableDeleteButton: PropTypes.bool,
disableDeleteReason: PropTypes.string,
disableAddButton: PropTypes.bool,
onDeleteButtonClick: PropTypes.func,
onManageManifestButtonClick: PropTypes.func,
onExportCsvButtonClick: PropTypes.func,
toolTipOnChange: PropTypes.func,
toolTipOnclose: PropTypes.func,
};
SubscriptionsToolbar.defaultProps = {
...Search.defaultProps,
tableColumns: [],
disableManifestActions: false,
disableManifestReason: '',
disableDeleteButton: false,
disableDeleteReason: '',
disableAddButton: false,
onDeleteButtonClick: noop,
onManageManifestButtonClick: noop,
onExportCsvButtonClick: noop,
toolTipOnChange: noop,
toolTipOnclose: noop,
};
export default SubscriptionsToolbar;
|
src/components/Home/break.js | pritchardtw/ReactPersonalSite | import React, { Component } from 'react';
export default class Break extends Component {
render() {
return (
<div className="break">
</div>
);
}
}
|
frontend/src/clue.js | wadobo/socializa | import React from 'react';
import { withRouter } from 'react-router';
import Purifier from 'html-purify';
import { user, getIcon } from './auth';
import Bucket from './bucket';
import Loading from './loading';
import API from './api';
import { EventSolveOpt } from './eventsolve';
import { ResolvableComponent } from './eventsolve';
import { translate } from 'react-i18next';
class ClueItemB extends ResolvableComponent {
state = {
clue: null,
state: 'normal',
solution: null,
step: 0,
}
clueChange = (e) => {
this.setState({solution: e.target.value});
}
componentDidMount() {
var clue = this.props.clue;
this.setState({ clue: clue });
}
solve = (solution) => {
const { t } = this.props;
var self = this;
this.setState({ state: 'solving' });
API.solve_clue(this.state.clue.pk, solution)
.then(function(resp) {
if (resp.status == 'correct') {
var c = self.state.clue;
alert(t('events::Conglatulations!'));
if (resp.clues.length) {
self.props.newClues(resp.clues);
} else {
c.status = 'solved';
c.solution = solution;
self.setState({ clue: c, state: 'normal' });
}
} else {
self.setState({ state: 'normal' });
alert(t('events::Wrong answer. Try again'));
}
}).catch(function(err) {
self.setState({ state: 'normal' });
alert(t('common::Unknown error'));
});
}
getField = () => {
return this.state.clue;
}
render() {
const { t } = this.props;
var self = this;
function createMarkup() {
var purifier = new Purifier();
var input = self.state.clue.challenge.desc;
var result = purifier.purify(input);
return {__html: result };
}
return (
<div>
{ this.state.clue ?
<div className="clue">
<h1>{ this.state.clue.challenge.name }</h1>
<div dangerouslySetInnerHTML={ createMarkup() } />
{ this.state.clue.status == 'solved' ?
<p className="text-success">{ this.state.clue.solution }</p>
:
<div>
{ this.state.clue.solution ?
this.renderState()
:
<span></span> }
{ this.state.state == 'solving' ? <Loading /> : <span></span> }
</div>
}
</div>
:
<Loading />
}
</div>
);
}
}
export let ClueItem = translate(['event', 'clue'], { wait: true })(withRouter(ClueItemB));
class Clue extends React.Component {
state = {
clues: [],
}
componentDidMount() {
this.setState({clues: Bucket.clues});
}
goBack = () => {
this.props.history.push('/map');
}
viewEvent = () => {
this.props.history.push('/event/' + user.activeEvent.pk);
}
newClues = (clues) => {
this.setState({'clues': clues});
}
render() {
const { t } = this.props;
var self = this;
return (
<div id="clue" className="container mbottom">
{ this.state.clues.map(function(c, i) {
return <ClueItem key={c.pk} clue={c} newClues={self.newClues.bind(self)}/>;
}) }
<button className="btn btn-primary btn-fixed-bottom-left" onClick={ this.goBack }>{t('clue::Map')}</button>
<button className="btn btn-success btn-fixed-bottom-right" onClick={ this.viewEvent }>{t('clue::Event')}</button>
</div>
);
}
}
export default Clue = translate(['event', 'clue'], { wait: true })(withRouter(Clue));
|
src/index.js | spirosikmd/reflow | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const root = document.getElementById('root');
ReactDOM.render(<App />, root);
if (module.hot) {
module.hot.accept('./App', () => {
const NextApp = require('./App').default;
ReactDOM.render(<NextApp />, root);
});
}
|
src/give/AddAccount/Failure.js | NewSpring/Apollos | import React from 'react';
import PropTypes from 'prop-types';
import styled from '@ui/styled';
import PaddedView from '@ui/PaddedView';
import Icon from '@ui/Icon';
import { H3, H4, BodyText } from '@ui/typography';
import { withTheme } from '@ui/theme';
import Button, { ButtonLink } from '@ui/Button';
import WebBrowser from '@ui/WebBrowser';
import Paragraph from '@ui/Paragraph';
import { Link } from '@ui/NativeWebRouter';
const contact = () => WebBrowser.openBrowserAsync('https://rock.newspring.cc/workflows/152?Topic=Stewardship');
const BackgroundView = styled(({ theme }) => ({
backgroundColor: theme.colors.background.paper,
justifyContent: 'center',
alignItems: 'center',
paddingTop: theme.sizing.baseUnit * 3,
}))(PaddedView);
const ThemedIcon = withTheme(({ theme }) => ({
size: theme.sizing.baseUnit * 3,
fill: theme.colors.alert,
}))(Icon);
const Heading = styled(({ theme }) => ({
color: theme.colors.alert,
paddingTop: theme.sizing.baseUnit,
}))(H3);
const SubHeading = styled(({ theme }) => ({
color: theme.colors.text.secondary,
paddingBottom: theme.sizing.baseUnit,
textAlign: 'center',
}))(H4);
const Failure = ({ paymentFailedMessage }) => (
<BackgroundView>
<ThemedIcon name="circle-outline-x-mark" />
<Heading>Uh Oh!</Heading>
<SubHeading>Looks like there was a problem adding your payment method.</SubHeading>
{paymentFailedMessage ? (
<Paragraph><BodyText>{paymentFailedMessage}</BodyText></Paragraph>
) : null}
<Paragraph>
<Link pop>
<Button title="Try Again" />
</Link>
</Paragraph>
<Paragraph>
<BodyText italic>
If you would like a member of our customer support team to follow up with you regarding
this error, please{' '}
<ButtonLink onPress={contact}>contact us</ButtonLink>
{' '}and someone will be happy to assist you.
</BodyText>
</Paragraph>
</BackgroundView>
);
Failure.propTypes = {
paymentFailedMessage: PropTypes.string,
};
export default Failure;
|
server/sonar-web/src/main/js/apps/overview/main/main.js | vamsirajendra/sonarqube | import _ from 'underscore';
import moment from 'moment';
import React from 'react';
import { GeneralDebt } from './debt';
import { GeneralCoverage } from './coverage';
import { GeneralDuplications } from './duplications';
import { GeneralStructure } from './structure';
import { CoverageSelectionMixin } from '../components/coverage-selection-mixin';
import { getPeriodLabel, getPeriodDate } from './../helpers/periods';
import { getMeasuresAndVariations } from '../../../api/measures';
import { getIssuesCount } from '../../../api/issues';
import { getTimeMachineData } from '../../../api/time-machine';
const METRICS_LIST = [
'sqale_rating',
'overall_coverage',
'new_overall_coverage',
'coverage',
'new_coverage',
'it_coverage',
'new_it_coverage',
'tests',
'duplicated_lines_density',
'duplicated_blocks',
'ncloc',
'ncloc_language_distribution'
];
const HISTORY_METRICS_LIST = [
'sqale_index',
'duplicated_lines_density',
'ncloc'
];
export default React.createClass({
propTypes: {
leakPeriodIndex: React.PropTypes.string.isRequired
},
mixins: [CoverageSelectionMixin],
getInitialState() {
return {
ready: false,
history: {},
leakPeriodLabel: getPeriodLabel(this.props.component.periods, this.props.leakPeriodIndex),
leakPeriodDate: getPeriodDate(this.props.component.periods, this.props.leakPeriodIndex)
};
},
componentDidMount() {
Promise.all([
this.requestMeasures(),
this.requestIssuesAndDebt(),
this.requestLeakIssuesAndDebt()
]).then(responses => {
let measures = this.getMeasuresValues(responses[0], 'value');
measures.issues = responses[1].issues;
measures.debt = responses[1].debt;
let leak;
if (this.state.leakPeriodDate) {
leak = this.getMeasuresValues(responses[0], 'var' + this.props.leakPeriodIndex);
leak.issues = responses[2].issues;
leak.debt = responses[2].debt;
}
this.setState({
ready: true,
measures: measures,
leak: leak,
coverageMetricPrefix: this.getCoverageMetricPrefix(measures)
}, this.requestHistory);
});
},
requestMeasures () {
return getMeasuresAndVariations(this.props.component.key, METRICS_LIST);
},
getMeasuresValues (measures, fieldKey) {
let values = {};
Object.keys(measures).forEach(measureKey => {
values[measureKey] = measures[measureKey][fieldKey];
});
return values;
},
requestIssuesAndDebt() {
// FIXME requesting severities facet only to get debtTotal
return getIssuesCount({
componentUuids: this.props.component.id,
resolved: 'false',
facets: 'severities'
});
},
requestLeakIssuesAndDebt() {
if (!this.state.leakPeriodDate) {
return Promise.resolve();
}
let createdAfter = moment(this.state.leakPeriodDate).format('YYYY-MM-DDTHH:mm:ssZZ');
// FIXME requesting severities facet only to get debtTotal
return getIssuesCount({
componentUuids: this.props.component.id,
createdAfter: createdAfter,
resolved: 'false',
facets: 'severities'
});
},
requestHistory () {
let coverageMetric = this.state.coverageMetricPrefix + 'coverage';
let metrics = [].concat(HISTORY_METRICS_LIST, coverageMetric).join(',');
return getTimeMachineData(this.props.component.key, metrics).then(r => {
let history = {};
r[0].cols.forEach((col, index) => {
history[col.metric] = r[0].cells.map(cell => {
let date = moment(cell.d).toDate();
let value = cell.v[index] || 0;
return { date, value };
});
});
let historyStartDate = history[HISTORY_METRICS_LIST[0]][0].date;
this.setState({ history, historyStartDate });
});
},
renderLoading () {
return <div className="text-center">
<i className="spinner spinner-margin"/>
</div>;
},
render() {
if (!this.state.ready) {
return this.renderLoading();
}
let coverageMetric = this.state.coverageMetricPrefix + 'coverage';
let props = _.extend({}, this.props, this.state);
return <div className="overview-domains-list">
<GeneralDebt {...props} history={this.state.history['sqale_index']}/>
<GeneralCoverage {...props} coverageMetricPrefix={this.state.coverageMetricPrefix}
history={this.state.history[coverageMetric]}/>
<GeneralDuplications {...props} history={this.state.history['duplicated_lines_density']}/>
<GeneralStructure {...props} history={this.state.history['ncloc']}/>
</div>;
}
});
|
src/routes/contact/Contact.js | stanxii/laiico | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Contact.css';
class Contact extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
};
render() {
return (
<div className={s.root}>
<div className={s.container}>
<h1>{this.props.title}</h1>
<p>...</p>
</div>
</div>
);
}
}
export default withStyles(s)(Contact);
|
src/main.js | EragonJ/Kaku | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Electron, {
ipcRenderer as IpcRenderer,
shell as Shell,
remote as Remote,
} from 'electron';
const Dialog = Remote.dialog;
const App = Remote.app;
import ReactTooltip from 'react-tooltip';
// general modules
import ErrorMonitor from './modules/ErrorMonitor';
ErrorMonitor.init();
import PreferenceManager from './modules/PreferenceManager';
import TrackInfoFetcher from 'kaku-core/modules/TrackInfoFetcher';
import PlaylistManager from './modules/PlaylistManager';
import L10nManager from './modules/L10nManager';
import TopRanking from 'kaku-core/modules/TopRanking';
import AppCore from './modules/AppCore';
import Searcher from './modules/Searcher';
import AutoUpdater from './modules/AutoUpdater';
import Tracker from './modules/Tracker';
const _ = L10nManager.get.bind(L10nManager);
// views > components
import ToolbarComponent from './views/components/toolbar';
import TopRankingComponent from './views/components/topranking';
import NewsComponent from './views/components/news';
import AllTracksComponent from './views/components/alltracks';
import PlayerComponent from './views/components/player';
import MenusComponent from './views/components/menus';
import HistoryComponent from './views/components/history';
import PlayQueueComponent from './views/components/play-queue';
import PlaylistComponent from './views/components/playlist';
import SettingsComponent from './views/components/settings';
import OnlineDJComponent from './views/components/online-dj';
import AboutComponent from './views/components/about';
import ChatroomComponent from './views/components/chatroom';
import ConnectionCheckComponent from './views/components/connection-check';
// views > modules
import TabManager from './views/modules/TabManager';
import RemotePlayer from './views/modules/RemotePlayer';
import CastingManager from './views/modules/CastingManager';
import KonamiCodeManager from './views/modules/KonamiCodeManager';
import EasterEggs from './views/modules/EasterEggs';
import AppTouchBar from './views/modules/AppTouchBar';
import AppMenus from './views/modules/AppMenus';
import AppTray from './views/modules/AppTray';
import Player from './views/modules/Player';
import Notifier from './views/modules/Notifier';
const loadingPageDOM = document.querySelector('.loading-page');
const contentPageDOM = document.querySelector('.content-page');
class KakuApp extends Component {
componentWillMount() {
AppMenus.build();
AppTray.build();
AppTouchBar.build();
window.addEventListener('beforeunload', () => {
AppTray.destroy();
AppTouchBar.destroy();
});
// this should be run first
this._initializeDefaultTopRanking();
// TODO
// Need to figure out why `Loading` showing up so slowly
setTimeout(() => {
this._hideLoadingPage();
this._triggerAutoUpdater();
}, 3000);
}
componentDidMount() {
this._bindShortcutEvents();
this._bindTrayEvents();
this._bindPlayerEvents();
this._initializeAppTitle();
this._initializeDefaultAlwaysOnTop();
this._initializeDefaultChatroom();
this._initializeDefaultLanguage();
this._initializeDefaultSearcher();
this._initializeDefaultTrackFormat();
this._initializeDefaultVolume();
this._initializeKonamiCode();
// Initialize these after Player.js has been setup
CastingManager.init();
RemotePlayer.init();
// Say hi :)
Tracker.pageview('/').send();
}
_bindShortcutEvents() {
IpcRenderer.on('key-MediaNextTrack', () => {
Player.playNextTrack();
});
IpcRenderer.on('key-MediaPreviousTrack', () => {
Player.playPreviousTrack();
});
IpcRenderer.on('key-MediaPlayPause', () => {
Player.playOrPause();
});
IpcRenderer.on('key-Escape', () => {
Player.exitFullscreen();
});
}
_bindTrayEvents() {
IpcRenderer.on('tray-MediaPreviousTrack', () => {
Player.playPreviousTrack();
});
IpcRenderer.on('tray-MediaNextTrack', () => {
Player.playNextTrack();
});
IpcRenderer.on('tray-MediaPlayPause', () => {
Player.playOrPause();
});
}
_bindPlayerEvents() {
Player.on('play', () => {
let playingTrack = Player.playingTrack;
if (playingTrack) {
let title = playingTrack.title;
let maxLength = 40;
let translatedTitle = _('app_title_playing', {
name: title
});
if (translatedTitle.length > maxLength) {
translatedTitle = translatedTitle.substr(0, maxLength) + ' ...';
}
AppCore.title = translatedTitle;
}
});
Player.on('ended', () => {
AppCore.title = _('app_title_normal');
});
}
_initializeDefaultTopRanking() {
var defaultCountryCode =
PreferenceManager.getPreference('default.topRanking.countryCode');
if (defaultCountryCode) {
TopRanking.changeCountry(defaultCountryCode);
}
}
_initializeAppTitle() {
AppCore.title = _('app_title_normal');
}
_initializeDefaultAlwaysOnTop() {
var defaultAlwaysOnTop =
PreferenceManager.getPreference('default.alwaysOnTop.enabled');
if (defaultAlwaysOnTop) {
Remote.getCurrentWindow().setAlwaysOnTop(defaultAlwaysOnTop);
}
}
_initializeDefaultChatroom() {
var defaultChatroom =
PreferenceManager.getPreference('default.chatroom.enabled');
if (typeof defaultChatroom === 'undefined') {
PreferenceManager.setPreference('default.chatroom.enabled', true);
}
}
_initializeDefaultLanguage() {
var defaultLanguage =
PreferenceManager.getPreference('default.language');
// For new users, there is no `defaultLanguage` in DB yet.
if (defaultLanguage) {
L10nManager.changeLanguage(defaultLanguage);
}
}
_initializeDefaultSearcher() {
var defaultSearcher =
PreferenceManager.getPreference('default.searcher');
if (defaultSearcher) {
Searcher.changeSearcher(defaultSearcher);
}
}
_initializeDefaultTrackFormat() {
var defaultFormat =
PreferenceManager.getPreference('default.track.format') || 'best';
TrackInfoFetcher.changeFormat(defaultFormat);
}
_initializeDefaultVolume() {
var defaultVolume =
PreferenceManager.getPreference('default.volume') || 'default';
Player.setVolume(defaultVolume);
}
_initializeKonamiCode() {
KonamiCodeManager.attach(document.body, () => {
EasterEggs.show();
});
}
_triggerAutoUpdater() {
AutoUpdater.updateApp();
Notifier.alert(_('main_autoupdate_ytdl'));
AutoUpdater.updateYoutubeDl().then(() => {
Notifier.alert(_('main_autoupdate_ytdl_success'));
console.log('updated youtube-dl successfully');
}).catch(() => {
Notifier.alert(_('main_autoupdate_ytdl_error'));
console.log('failed to update youtube-dl');
});
}
_hideLoadingPage() {
loadingPageDOM.hidden = true;
}
render() {
return (
<div className="root">
<ConnectionCheckComponent/>
<ChatroomComponent/>
<div className="row row-no-padding top-row">
<div className="col-md-12">
<div className="toolbar-slot">
<ToolbarComponent/>
</div>
</div>
</div>
<div className="row row-no-padding bottom-row">
<div className="left">
<div className="sidebar">
<MenusComponent/>
<PlayerComponent/>
</div>
</div>
<div className="right">
<div className="tab-content">
<div
role="tabpanel"
className="tab-pane active"
id="tab-home">
<TopRankingComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-news">
<NewsComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-search">
<AllTracksComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-settings">
<SettingsComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-online-dj">
<OnlineDJComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-about">
<AboutComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-history">
<HistoryComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-play-queue">
<PlayQueueComponent/>
</div>
<div
role="tabpanel"
className="tab-pane"
id="tab-playlist">
<PlaylistComponent/>
</div>
</div>
</div>
</div>
<ReactTooltip/>
</div>
);
}
}
ReactDOM.render(<KakuApp/>, contentPageDOM);
|
src/components/MinimapZoom/Minimap.js | vogelino/design-timeline | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createScaleFunction, getLanes } from '../../helpers/timelineHelper';
import { SIDEBAR_WIDTH, TOPICS_LIST_WIDTH, MINIMAP_MARGIN } from '../../redux/constants/uiConstants';
import EventsLane from '../EventsLane/EventsLane';
export const MinimapComponent = ({
events,
categories,
ui: { windowWidth },
mainTimeline: { minDate, maxDate },
}) => {
const totalWidth = windowWidth - SIDEBAR_WIDTH -
TOPICS_LIST_WIDTH - (2 * MINIMAP_MARGIN);
const scaleFunc = createScaleFunction({ totalWidth, minDate, maxDate });
const lanes = getLanes({ categories, events, scaleFunc });
const getFutureZone = (date, classPrefix) => (
<div
className={`events-lanes_${classPrefix}`}
style={{
width: windowWidth - SIDEBAR_WIDTH - scaleFunc(date) -
TOPICS_LIST_WIDTH - MINIMAP_MARGIN,
}}
/>
);
return (
<div className="minimap">
{getFutureZone(new Date('2017-06-28'), 'publication')}
{getFutureZone(new Date(), 'future')}
{lanes.map(({ laneSlug, laneEvents }) => (
<EventsLane
key={laneSlug}
classNamePrefix="minimap"
className={laneSlug}
events={laneEvents}
width={totalWidth}
/>
))}
</div>
);
};
MinimapComponent.propTypes = {
events: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.string.isRequired,
data: PropTypes.shape({
title: PropTypes.string.isRequired,
}).isRequired,
state: PropTypes.shape({
selected: PropTypes.bool.isRequired,
hovered: PropTypes.bool.isRequired,
}).isRequired,
}),
).isRequired,
categories: PropTypes.arrayOf(
PropTypes.shape({
slug: PropTypes.string.isRequired,
title: PropTypes.string.isRequired,
color: PropTypes.string.isRequired,
}),
).isRequired,
ui: PropTypes.shape({
windowWidth: PropTypes.number.isRequired,
}),
mainTimeline: PropTypes.shape({
minDate: PropTypes.instanceOf(Date).isRequired,
maxDate: PropTypes.instanceOf(Date).isRequired,
}),
};
const mapStateToProps = ({ events, categories, ui, mainTimeline }) =>
({ events, categories, ui, mainTimeline });
export default connect(mapStateToProps)(MinimapComponent);
|
js/jqwidgets/demos/react/app/tabs/defaultfunctionality/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxTabs from '../../../jqwidgets-react/react_jqxtabs.js';
import JqxCheckBox from '../../../jqwidgets-react/react_jqxcheckbox.js';
class App extends React.Component {
componentDidMount() {
this.refs.animation.on('change', (event) => {
let checked = event.args.checked;
this.refs.myTabs.selectionTracker(checked);
});
this.refs.contentAnimation.on('change', (event) => {
let checked = event.args.checked;
if (checked) {
this.refs.myTabs.animationType('fade');
}
else {
this.refs.myTabs.animationType('none');
}
});
}
render () {
let tabsHTML = `
<ul>
<li style="margin-left: 30px;">Node.js</li>
<li>JavaServer Pages</li>
<li>Active Server Pages</li>
<li>Python</li>
<li>Perl</li>
</ul>
<div>
Node.js is an event-driven I/O server-side JavaScript environment based on V8. It
is intended for writing scalable network programs such as web servers. It was created
by Ryan Dahl in 2009, and its growth is sponsored by Joyent, which employs Dahl.
Similar environments written in other programming languages include Twisted for
Python, Perl Object Environment for Perl, libevent for C and EventMachine for Ruby.
Unlike most JavaScript, it is not executed in a web browser, but is instead a form
of server-side JavaScript. Node.js implements some CommonJS specifications. Node.js
includes a REPL environment for interactive testing.
</div>
<div>
JavaServer Pages (JSP) is a Java technology that helps software developers serve
dynamically generated web pages based on HTML, XML, or other document types. Released
in 1999 as Sun's answer to ASP and PHP,[citation needed] JSP was designed to address
the perception that the Java programming environment didn't provide developers with
enough support for the Web. To deploy and run, a compatible web server with servlet
container is required. The Java Servlet and the JavaServer Pages (JSP) specifications
from Sun Microsystems and the JCP (Java Community Process) must both be met by the
container.
</div>
<div>
ASP.NET is a web application framework developed and marketed by Microsoft to allow
programmers to build dynamic web sites, web applications and web services. It was
first released in January 2002 with version 1.0 of the .NET Framework, and is the
successor to Microsoft's Active Server Pages (ASP) technology. ASP.NET is built
on the Common Language Runtime (CLR), allowing programmers to write ASP.NET code
using any supported .NET language. The ASP.NET SOAP extension framework allows ASP.NET
components to process SOAP messages.
</div>
<div>
Python is a general-purpose, high-level programming language[5] whose design philosophy
emphasizes code readability. Python claims to "[combine] remarkable power with very
clear syntax",[7] and its standard library is large and comprehensive. Its use of
indentation for block delimiters is unique among popular programming languages.
Python supports multiple programming paradigms, primarily but not limited to object-oriented,
imperative and, to a lesser extent, functional programming styles. It features a
fully dynamic type system and automatic memory management, similar to that of Scheme,
Ruby, Perl, and Tcl. Like other dynamic languages, Python is often used as a scripting
language, but is also used in a wide range of non-scripting contexts.
</div>
<div>
Perl is a high-level, general-purpose, interpreted, dynamic programming language.
Perl was originally developed by Larry Wall in 1987 as a general-purpose Unix scripting
language to make report processing easier. Since then, it has undergone many changes
and revisions and become widely popular amongst programmers. Larry Wall continues
to oversee development of the core language, and its upcoming version, Perl 6. Perl
borrows features from other programming languages including C, shell scripting (sh),
AWK, and sed.[5] The language provides powerful text processing facilities without
the arbitrary data length limits of many contemporary Unix tools, facilitating easy
manipulation of text files.
</div>
`;
return (
<div>
<JqxTabs ref='myTabs' template={tabsHTML}
width={'90%'} height={200} position={'top'}
/>
<div id='settings' style={{ marginTop: 5 }}>
<JqxCheckBox ref='animation' style={{ marginTop: 10 }} value='Enable Select Animation'/>
<JqxCheckBox ref='contentAnimation' style={{ marginTop: 10 }} value='Enable Content Animation'/>
</div>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/counts/ShortCountVol.js | availabs/avail_app_bootstrap | import React from 'react';
import StackedBarGraph from '../graphs/StackedBarGraph';
import directionCodes from '../utils/directionCodes';
class ShortCountVol extends React.Component {
render() {
var data = this.props.data;
var countDate = `${data.month}/${data.dayOfFirstData}/${data.year}`;
var infoTable = (
<table style={{ width: '100%' }}>
<tr>
<th>Count Id</th>
<td>{data.countId}</td>
<th>Date</th>
<td>{countDate}</td>
</tr>
<tr>
<th>Functional Class</th>
<td>{data.functionalClass}</td>
<th>Factor Group</th>
<td>{data.factorGroup}</td>
</tr>
<tr>
<th>Recorder Placement</th>
<td colSpan={7}>{data.specificRecorderPlacement}</td>
</tr>
</table>
);
var chartData = Object.keys(data.counts).map(countDate => {
return Object.keys(data.counts[countDate]).map(dir => {
return data.counts[countDate][dir].data.map((value, index) => {
var xValue =
data.counts[countDate][dir].data.length > 24
? (index / 4).toFixed(2)
: index + 1;
return { name: dir, x: +xValue, y: value };
});
});
});
// let aadtData = Object.keys(data.federalDirection)
// .sort((a, b) => b - a)
// .map(dir => {
// return (
// <div className="col-4">
// <div className="el-tablo highlight">
// <div className="label">{directionCodes[dir]} AADT</div>
// <div className="value">
// {data.federalDirection[dir].aadt.toLocaleString()}
// </div>
// </div>
// </div>
// );
// });
// let legendData = Object.keys(data.federalDirection)
// .filter(dir => dir !== '0' && dir !== '9')
// .map(dir => {
// return { name: directionCodes[dir] };
// });
return (
<div>
<div className="element-box">
{chartData.map((currentData, i) => {
const currentCount = data.counts[Object.keys(data.counts)[i]];
const legendData = Object.keys(currentCount).map(dir => {
return { name: directionCodes[dir] };
});
const countInfo = currentCount[Object.keys(currentCount)[0]];
return (
<div className="row">
<div className="project-info">
<div className="row align-items-center">
<div className="col-sm-12">
<div className="project-title">
<h5>
Short Count
<span style={{ fontWeight: 100 }}>
{countInfo.dayOfWeek} {countInfo.date}
</span>
</h5>
</div>
</div>
</div>
</div>
<div className="col-md-12 col-xl-12">
<StackedBarGraph data={currentData} legendData={legendData} />
</div>
</div>
);
})}
<div className="row">
<div className="col-md-12 col-xl-12">
<div className="padded b-l b-r">
<div className="element-info-with-icon smaller">
<div className="element-info-icon">
<div className="os-icon os-icon-bar-chart-stats-up" />
</div>
<div className="element-info-text">
<h5 className="element-inner-header">Metadata</h5>
<div className="element-inner-desc" />
</div>
</div>
{infoTable}
</div>
</div>
</div>
</div>
</div>
);
}
}
export default ShortCountVol;
|
test/fixtures/stateless-assignment/expected.js | layershifter/babel-plugin-transform-react-handled-props | import PropTypes from 'prop-types';
import React from 'react';
const Example = function () {
return <div />;
};
Example.handledProps = ["active", "children", "className"];
Example.defaultProps = {
active: true
};
Example.propTypes = {
children: PropTypes.node,
className: PropTypes.string
};
export default Example;
|
node_modules/semantic-ui-react/src/modules/Popup/PopupContent.js | mowbell/clickdelivery-fed-test | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
createShorthandFactory,
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A PopupContent displays the content body of a Popover.
*/
export default function PopupContent(props) {
const { children, className } = props
const classes = cx('content', className)
const rest = getUnhandledProps(PopupContent, props)
const ElementType = getElementType(PopupContent, props)
return <ElementType {...rest} className={classes}>{children}</ElementType>
}
PopupContent.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** The content of the Popup */
children: PropTypes.node,
/** Classes to add to the Popup content className. */
className: PropTypes.string,
}
PopupContent._meta = {
name: 'PopupContent',
type: META.TYPES.MODULE,
parent: 'Popup',
}
PopupContent.create = createShorthandFactory(PopupContent, children => ({ children }))
|
src/client/index.js | playnogames/stacks | import React from 'react';
import ReactDom from 'react-dom';
import App from './components/App';
import './scss/index.scss';
ReactDom.render(
<App />,
document.getElementById('app')
);
|
client/components/requestUApproved.js | marhyorh/booktrade | import React from 'react';
export default (props) => {
const onRemove = (book, event) => {
event.preventDefault();
Meteor.call('book.unApprove', book);
}
const reqApproved = () => {
return props.books.map(book => {
return (
<li className="list-group-item" key={book._id}>
{book.title} <i className="glyphicon glyphicon-remove" onClick={onRemove.bind(this, book)} />
</li>
);
});
}
return (
<div className="requestUApproved">
{props.books.length >= 1 && <h3>Requests you approved:</h3>}
<ul className="list-group">
{ reqApproved() }
</ul>
</div>
)
};
|
src/components/VenueList.js | mgaebler/kicknow-client-web | import React from 'react'
export default class VenueList extends React.Component {
render () {
function generateVenueButton (venue){
return (
<a
className="list-group-item"
href={`/location/add/${venue.id}`}
key={venue.id}
>
<h4 className="list-group-item-heading">
{venue.name}
</h4>
<p className="list-group-item-text">
{venue.location.address}
</p>
</a>
)
}
return (
<div className="list-group">
{this.props.venues.map(generateVenueButton)}
</div>
)
}
}
|
node_modules/react-bootstrap/es/MediaHeading.js | soniacq/LearningReact | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'h4'
};
var MediaHeading = function (_React$Component) {
_inherits(MediaHeading, _React$Component);
function MediaHeading() {
_classCallCheck(this, MediaHeading);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaHeading.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaHeading;
}(React.Component);
MediaHeading.propTypes = propTypes;
MediaHeading.defaultProps = defaultProps;
export default bsClass('media-heading', MediaHeading); |
client/views/admin/oauthApps/OAuthAppsRoute.js | VoiSmart/Rocket.Chat | import React from 'react';
import NotAuthorizedPage from '../../../components/NotAuthorizedPage';
import { usePermission } from '../../../contexts/AuthorizationContext';
import OAuthAppsPage from './OAuthAppsPage';
export default function MailerRoute() {
const canAccessOAuthApps = usePermission('manage-oauth-apps');
if (!canAccessOAuthApps) {
return <NotAuthorizedPage />;
}
return <OAuthAppsPage />;
}
|
web/src/layout/Breadcrumb.js | caicloud/cyclone | import React from 'react';
import { Link } from 'react-router-dom';
import { Breadcrumb } from 'antd';
import PropTypes from 'prop-types';
const mainModules = [
'overview',
'projects',
'stageTemplate',
'resource',
'integration',
'workflows',
];
const operations = ['update', 'add'];
/**
* define the route rules
* list page => /projects
* project detail => /projects/:projectId
* update project => /projects/:projectId/update
* add project => /projects/add
*/
const BreadcrumbComponent = ({ location }) => {
const pathSnippets = location.pathname.split('/').filter(i => i);
const extraBreadcrumbItems = pathSnippets.map((path, index) => {
const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
let text = path;
if (_.includes(mainModules, path)) {
text = <Link to={url}>{intl.get(`sideNav.${path}`)}</Link>;
} else if (_.includes(operations, path)) {
text = intl.get(`operation.${path}`);
} else if (_.includes(mainModules, pathSnippets[index - 1])) {
text = <Link to={url}>{path}</Link>;
}
return <Breadcrumb.Item key={url}>{text}</Breadcrumb.Item>;
});
return (
<Breadcrumb style={{ marginBottom: '12px' }}>
{extraBreadcrumbItems}
</Breadcrumb>
);
};
BreadcrumbComponent.propTypes = {
location: PropTypes.object,
};
export default BreadcrumbComponent;
|
roguelike-dungeon-crawler-game/src/App.js | mstoyanovca/front-end | import React, { Component } from 'react';
import Dungeon from './Dungeon';
import Header from './Header';
import LossModal from './LossModal';
import WinModal from './WinModal';
const weapons = ["stick", "brass knuckles", "serrated dagger", "katana", "reaper's scythe", "large trout"];
//tune the game here; you need 240 health points to beet the boss:
const attackValues = [7, 26, 64, 88, 200, 300]; // per dungeon/weapon
// board size in cells:
const boardWidth = 80;
const boardHeight = 80;
// 20 gives good board density:
const numberOfChambers = 20;
// nextLevelPoints = 60, add 60 for each level;
export default class App extends Component {
constructor(props) {
super(props);
this.state = {health: 100, weapon: weapons[0], attack: attackValues[0], level: 0, nextLevelPoints: 60, dungeon: 0, cells: [], cursor: {},
showLossModal: false, showWinModal: false, dark: false};
this.updateCells = this.updateCells.bind(this);
this.move = this.move.bind(this);
this.updateHealth = this.updateHealth.bind(this);
this.updateWeapon = this.updateWeapon.bind(this);
this.updateAttack = this.updateAttack.bind(this);
this.updateLevel = this.updateLevel.bind(this);
this.updateNextLevelPoints = this.updateNextLevelPoints.bind(this);
this.updateDungeon = this.updateDungeon.bind(this);
this.updateShowLossModal = this.updateShowLossModal.bind(this);
this.updateShowWinModal = this.updateShowWinModal.bind(this);
this.startNewDungeon = this.startNewDungeon.bind(this);
this.startNewGame = this.startNewGame.bind(this);
this.updateDark = this.updateDark.bind(this);
}
componentDidMount() {
let cells = this.createEmptyBoard();
cells = this.createDungeon(cells);
let cellsWithCursor = this.createContent(cells, this.state.dungeon);
this.setState({cells: cellsWithCursor.cells, cursor: cellsWithCursor.cursor});
}
createEmptyBoard() {
let cells = [];
for (let i = 0; i < boardHeight; i++) {
cells[i] = [];
for (let j = 0; j < boardWidth; j++) {
cells[i][j] = {id: j + i * boardWidth, row: i, column: j, className: "cell"};
}
}
return cells;
}
createDungeon(cells) {
let chambers = [];
let doors = [];
for (let i = 0; i < numberOfChambers; i++) {
if(i === 0) {
let chamber = this.createChamber(true);
chambers.push(chamber);
cells = this.drawChamber(chamber, {x: chamber.x, y: chamber.y}, cells);
} else {
let chamber = this.createChamber(false);
for(let j = 0; j < i; j++) {
let chamberWithDoor = this.attachToTheRight(chambers[j], chamber, cells);
if(chamberWithDoor.chamber.x >= 0) {
chambers.push(chamberWithDoor.chamber);
doors.push(chamberWithDoor.door);
cells = this.drawChamber(chamberWithDoor.chamber, chamberWithDoor.door, cells);
break;
}
chamberWithDoor = this.attachToTheBottom(chambers[j], chamber, cells);
if(chamberWithDoor.chamber.y >= 0) {
chambers.push(chamberWithDoor.chamber);
doors.push(chamberWithDoor.door);
cells = this.drawChamber(chamberWithDoor.chamber, chamberWithDoor.door, cells);
break;
}
}
}
}
return cells;
}
createChamber(isFirst) {
// random size from 6 to 18 by 6 to 18 cells:
let width = Math.floor(Math.random() * 13) + 6;
let height = Math.floor(Math.random() * 13) + 6;
// chambers 2 and up to be positioned later:
let x = -1;
let y = -1;
if(isFirst) {
// position the first chamber randomly in the top left corner:
x = Math.floor(Math.random() * 21);
y = Math.floor(Math.random() * 11);
}
return {x: x, y: y, width: width, height: height};
}
attachToTheRight(previousChamber, chamber, cells) {
// try to attach to the right of an existing chamber:
chamber.x = previousChamber.x + previousChamber.width + 1;
let possibleYs = [];
for (let i = previousChamber.y - chamber.height + 1; i < previousChamber.y + previousChamber.height; i++) {
if (this.checkAvailability(chamber.x, i, chamber.width, chamber.height, cells)) {
possibleYs.push(i);
}
}
if (possibleYs.length > 0) {
let index = Math.floor(Math.random() * possibleYs.length);
chamber.y = possibleYs[index];
} else {
chamber.x = -1;
return {chamber, undefined};
}
// create a door between the chambers:
let overlappingYs = [];
for (let i = chamber.y; i < chamber.y + chamber.height; i++) {
if (i >= previousChamber.y && i < previousChamber.y + previousChamber.height) {
overlappingYs.push(i);
}
}
let index = Math.floor(Math.random() * overlappingYs.length);
let door = { x: chamber.x - 1, y: overlappingYs[index] };
return {chamber, door};
}
attachToTheBottom(previousChamber, chamber, cells) {
// try to attach to the bottom of an existing chamber:
chamber.y = previousChamber.y + previousChamber.height + 1;
let possibleXs = [];
for (let i = previousChamber.x - chamber.width + 1; i < previousChamber.x + previousChamber.width; i++) {
if (this.checkAvailability(i, chamber.y, chamber.width, chamber.height, cells)) {
possibleXs.push(i);
}
}
if (possibleXs.length > 0) {
let index = Math.floor(Math.random() * possibleXs.length);
chamber.x = possibleXs[index];
} else {
chamber.y = -1;
return {chamber, undefined};
}
// create a door between the chambers:
let overlappingXs = [];
for (let i = chamber.x; i < chamber.x + chamber.width; i++) {
if (i >= previousChamber.x && i < previousChamber.x + previousChamber.width) {
overlappingXs.push(i);
}
}
let index = Math.floor(Math.random() * overlappingXs.length);
let door = { x: overlappingXs[index], y: chamber.y - 1 };
return {chamber, door};
}
checkAvailability(x, y, width, height, cells) {
// make sure the new chamber is within the board:
if (x < 0 || x + width > boardWidth || y < 0 || y + height > boardHeight) return false;
// check if the cells that are going to be taken are free:
for (let i = y; i < y + height; i++) {
for (let j = x; j < x + width; j++) {
if (cells[i][j].className.includes("empty")) return false;
}
}
return true;
}
drawChamber(chamber, door, cells) {
for (let i = chamber.y; i < chamber.y + chamber.height; i++) {
for (let j = chamber.x; j < chamber.x + chamber.width; j++) {
if(cells[i][j].className === "cell") cells[i][j].className += " empty";
}
}
if(cells[door.y][door.x].className === "cell") cells[door.y][door.x].className += " empty"
return cells;
}
createContent(cells, dungeon) {
let emptyCells = [];
for (let i = 0; i < boardHeight; i++) {
for (let j = 0; j < boardWidth; j++) {
if (cells[i][j].className.includes("empty")) emptyCells.push(cells[i][j]);
}
}
// create the cursor:
let index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "cursor");
let cursor = {x: emptyCells[index].column, y: emptyCells[index].row};
emptyCells.splice(index, 1);
// create the weapon:
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "weapon");
emptyCells.splice(index, 1);
// create the stairs to the next dungeon:
if (dungeon < 4) {
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "stairs");
emptyCells.splice(index, 1);
}
// create the health items:
for (let i = 0; i < 5; i++) {
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "health");
emptyCells.splice(index, 1);
}
// create the enemies:
for (let i = 0; i < 5; i++) {
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "enemy");
emptyCells.splice(index, 1);
}
// create the boss:
if (dungeon === 4) {
let bosses = [{}];
for (let i = 0; i < boardHeight - 1; i++) {
for (let j = 0; j < boardWidth - 1; j++) {
if (cells[i][j].className.includes("empty") &&
cells[i][j + 1].className.includes("empty") &&
cells[i + 1][j].className.includes("empty") &&
cells[i + 1][j + 1].className.includes("empty")) {
bosses.push([cells[i][j], cells[i][j + 1], cells[i + 1][j], cells[i + 1][j + 1]]);
}
}
}
// pick a square randomly:
index = Math.floor(Math.random() * bosses.length);
for (let i = 0; i < bosses[index].length; i++) {
cells[bosses[index][i].row][bosses[index][i].column].className = "cell boss";
}
}
return {cells: cells, cursor: cursor};
}
updateCells(cells) {
this.setState({cells: cells});
}
move(cells, cursor) {
this.setState({cells: cells, cursor: cursor});
}
updateHealth(health) {
this.setState({health: health});
}
updateWeapon(weapon, attack) {
this.setState({weapon: weapon, attack: attack});
}
updateAttack(attack) {
this.setState({attack: attack});
}
updateLevel(level) {
this.setState({level: level});
}
updateNextLevelPoints(nextLevelPoints) {
this.setState({nextLevelPoints: nextLevelPoints});
}
updateDungeon(dungeon) {
this.setState({dungeon: dungeon});
}
updateDark(dark) {
this.setState({dark: dark});
}
updateShowLossModal(show) {
this.setState({showLossModal: show});
}
updateShowWinModal(show) {
this.setState({showWinModal: show});
}
startNewDungeon() {
let cells = this.createEmptyBoard();
cells = this.createDungeon(cells);
let cellsWithCursor = this.createContent(cells, this.state.dungeon);
this.setState({cells: cellsWithCursor.cells, cursor: cellsWithCursor.cursor, showLossModal: false, showWinModal: false});
}
startNewGame() {
let cells = this.createEmptyBoard();
cells = this.createDungeon(cells);
let cellsWithCursor = this.createContent(cells, 0);
this.setState({health: 100, weapon: weapons[0], attack: attackValues[0], level: 0, nextLevelPoints: 60, dungeon: 0, cells: cellsWithCursor.cells, cursor: cellsWithCursor.cursor,
showLossModal: false, showWinModal: false, dark: false});
}
render() {
return (
<div>
<Header health={this.state.health} weapon={this.state.weapon} attack={this.state.attack} level={this.state.level} nextLevelPoints={this.state.nextLevelPoints}
dungeon={this.state.dungeon} cells={this.state.cells} cursor={this.state.cursor} dark={this.state.dark} updateCells={this.updateCells} updateDark={this.updateDark} />
<Dungeon boardWidth={boardWidth} boardHeight={boardHeight} health={this.state.health} weapons={weapons} weapon={this.state.weapon} attackValues={attackValues}
attack={this.state.attack} level={this.state.level} nextLevelPoints={this.state.nextLevelPoints} dungeon={this.state.dungeon} cells={this.state.cells}
cursor={this.state.cursor} dark={this.state.dark} move={this.move} updateHealth={this.updateHealth} updateWeapon={this.updateWeapon} updateAttack={this.updateAttack}
updateLevel={this.updateLevel} updateNextLevelPoints={this.updateNextLevelPoints} updateDungeon={this.updateDungeon} updateShowLossModal={this.updateShowLossModal}
updateShowWinModal={this.updateShowWinModal} startNewDungeon={this.startNewDungeon} />
<LossModal show={this.state.showLossModal} startNewGame={this.startNewGame} />
<WinModal show={this.state.showWinModal} startNewGame={this.startNewGame} />
</div>
);
}
}
|
packages/react-scripts/fixtures/kitchensink/src/features/env/ShellEnvVariables.js | RobzDoom/frame_trap | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react';
export default () => (
<span id="feature-shell-env-variables">
{process.env.REACT_APP_SHELL_ENV_MESSAGE}.
</span>
);
|
src/ContractRows.js | simoneas02/contracts-list | import React, { Component } from 'react';
import update from 'immutability-helper';
import edit from './icons/edit.svg'
import save from './icons/save.svg'
import close from './icons/close.svg'
class ContractRows extends Component {
constructor(props) {
super(props);
this.state = {
contract: [],
isEditable: false,
isVisible: false
};
};
showContract(contractNumber) {
const contract = this.props.list.filter((contract) => {
return (contractNumber === contract.codigo);
});
this.setState({ contract: contract[0] });
this.setState({ isVisible: true });
};
updateInput(columnName) {
const contract = this.state.contract;
const value = this.refs[columnName];
const contractUpdated = update(contract, { $merge: {[columnName]: value.value }} );
this.setState({ contract: contractUpdated })
};
editList() {
this.setState({ isEditable: true });
};
closeList() {
this.setState({ isVisible: false });
this.setState({ isEditable: false });
};
render() {
const contractsList = this.props.list.map((contract)=> {
const columns = this.props.columns;
const columnsList = columns.map((column) => {
if(column.isActive && column.name !== "key") {
return (
<td className="column-cell" key = { contract[column.name] }>{ contract[column.name] }</td>
);
}
return null;
});
return (
<tr className="contract-row" key = { contract.codigo } onClick={ this.showContract.bind(this, contract.codigo) }>{ columnsList }</tr>
)
});
const itemsList = this.props.columns.map((item) => {
if(!this.state.isEditable){
return (
<tr>
<td>{ item.name }</td>
<td>{ this.state.contract[item.name] }</td>
</tr>
)
} else {
return (
<tr>
<td>
{ item.name }:
</td>
<td>
<input type="text"
ref={ item.name }
value={ this.state.contract[item.name] }
onChange={ this.updateInput.bind(this, item.name) } />
</td>
</tr>
);
};
});
const contractDialog = () => {
if(this.state.isVisible) {
return (
<div className="contract-dialog">
<div className="controlDialog">
<button className="buttom-icon" onClick={ this.editList.bind(this) }>
<img src={ edit }/>
</button>
<button className="buttom-icon" onClick={ this.closeList.bind(this) }>
<img src={ close }/>
</button>
<button className="buttom-icon" onClick={ this.props.updatelist.bind(this, this.state.contract) }>
<img src={ save }/>
</button>
</div>
<table>
{ itemsList }
</table>
</div>
);
};
};
return(
<tbody>
{ contractsList }
{ contractDialog() }
</tbody>
);
}
}
export default ContractRows; |
components/utils/PositionCard.js | Mudano/m-dash-ui | import React from 'react'
import className from 'classnames'
export default class PositionCard extends React.Component {
static defaultProps = {
}
constructor(props){
super(props)
this.state = {
isOpen : this.props.isOpen,
isReady : !this.props.isOpen,
}
}
componentWillReceiveProps(nextProps){
if(nextProps.isOpen !== this.state.isOpen){
if(nextProps.isOpen){
this.showCard()
}else{
this.hideCard()
}
}
}
showCard(){
this.setState({isOpen:true})
setTimeout(()=>{
this.setState({isReady:true})
},100)
}
hideCard(){
this.setState({isReady:true})
setTimeout(()=>{
this.setState({isOpen:false})
},500)
}
render() {
const cn = className("m-card m-position-card",{
"m-position-card":this.state.isReady
})
return (
<span>
{this.props.children}
{this.state.isOpen &&
<div className="m-card m-position-card">{this.props.comp}</div>
}
</span>
);
}
}
|
src/Label.js | roderickwang/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Label = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render() {
let classes = this.getBsClassSet();
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Label;
|
packages/demos/demo/src/components/Project/Input.js | yusufsafak/cerebral | import React from 'react'
import { connect } from 'cerebral/react'
import { props, signal, state } from 'cerebral/tags'
import translations from '../../common/compute/translations'
export default connect(
{
// autoFocus
enterPressed: signal`projects.enterPressed`,
escPressed: signal`projects.escPressed`,
// field
// placeholderKey
value: state`projects.$draft.${props`field`}`,
valueChanged: signal`projects.formValueChanged`,
t: translations,
},
function Input({
autoFocus,
enterPressed,
escPressed,
field,
placeholderKey,
value,
valueChanged,
t,
}) {
const onKeyDown = e => {
switch (e.key) {
case 'Enter':
enterPressed()
break
case 'Escape':
escPressed()
break
default:
break // noop
}
}
const onChange = e => {
valueChanged({ key: field, value: e.target.value })
}
return (
<input
className="input"
type="text"
autoFocus={autoFocus}
placeholder={t[placeholderKey]}
onKeyDown={onKeyDown}
onChange={onChange}
value={value || ''}
name={field}
/>
)
}
)
|
src/www/js/index.js | training4developers/bootcamp_04112016 | import React from 'react';
import Relay from 'react-relay';
import ReactDOM from 'react-dom';
import WidgetToolContainer from './containers/widget-tool-container';
import ViewerRoute from './routes/viewer-route';
ReactDOM.render(
<Relay.RootContainer Component={WidgetToolContainer} route={new ViewerRoute()} />,
document.querySelector('main')
);
|
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/Modal.js | Akkuma/npm-cache-benchmark | import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import classNames from 'classnames';
import events from 'dom-helpers/events';
import ownerDocument from 'dom-helpers/ownerDocument';
import canUseDOM from 'dom-helpers/util/inDOM';
import getScrollbarSize from 'dom-helpers/util/scrollbarSize';
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import BaseModal from 'react-overlays/lib/Modal';
import isOverflowing from 'react-overlays/lib/utils/isOverflowing';
import elementType from 'react-prop-types/lib/elementType';
import Fade from './Fade';
import Body from './ModalBody';
import ModalDialog from './ModalDialog';
import Footer from './ModalFooter';
import Header from './ModalHeader';
import Title from './ModalTitle';
import { bsClass, bsSizes, prefix } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import splitComponentProps from './utils/splitComponentProps';
import { Size } from './utils/StyleConfig';
var propTypes = _extends({}, BaseModal.propTypes, ModalDialog.propTypes, {
/**
* Include a backdrop component. Specify 'static' for a backdrop that doesn't
* trigger an "onHide" when clicked.
*/
backdrop: PropTypes.oneOf(['static', true, false]),
/**
* Close the modal when escape key is pressed
*/
keyboard: PropTypes.bool,
/**
* Open and close the Modal with a slide and fade animation.
*/
animation: PropTypes.bool,
/**
* A Component type that provides the modal content Markup. This is a useful
* prop when you want to use your own styles and markup to create a custom
* modal component.
*/
dialogComponentClass: elementType,
/**
* When `true` The modal will automatically shift focus to itself when it
* opens, and replace it to the last focused element when it closes.
* Generally this should never be set to false as it makes the Modal less
* accessible to assistive technologies, like screen-readers.
*/
autoFocus: PropTypes.bool,
/**
* When `true` The modal will prevent focus from leaving the Modal while
* open. Consider leaving the default value here, as it is necessary to make
* the Modal work well with assistive technologies, such as screen readers.
*/
enforceFocus: PropTypes.bool,
/**
* When `true` The modal will restore focus to previously focused element once
* modal is hidden
*/
restoreFocus: PropTypes.bool,
/**
* When `true` The modal will show itself.
*/
show: PropTypes.bool,
/**
* A callback fired when the header closeButton or non-static backdrop is
* clicked. Required if either are specified.
*/
onHide: PropTypes.func,
/**
* Callback fired before the Modal transitions in
*/
onEnter: PropTypes.func,
/**
* Callback fired as the Modal begins to transition in
*/
onEntering: PropTypes.func,
/**
* Callback fired after the Modal finishes transitioning in
*/
onEntered: PropTypes.func,
/**
* Callback fired right before the Modal transitions out
*/
onExit: PropTypes.func,
/**
* Callback fired as the Modal begins to transition out
*/
onExiting: PropTypes.func,
/**
* Callback fired after the Modal finishes transitioning out
*/
onExited: PropTypes.func,
/**
* @private
*/
container: BaseModal.propTypes.container
});
var defaultProps = _extends({}, BaseModal.defaultProps, {
animation: true,
dialogComponentClass: ModalDialog
});
var childContextTypes = {
$bs_modal: PropTypes.shape({
onHide: PropTypes.func
})
};
var Modal = function (_React$Component) {
_inherits(Modal, _React$Component);
function Modal(props, context) {
_classCallCheck(this, Modal);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleEntering = _this.handleEntering.bind(_this);
_this.handleExited = _this.handleExited.bind(_this);
_this.handleWindowResize = _this.handleWindowResize.bind(_this);
_this.handleDialogClick = _this.handleDialogClick.bind(_this);
_this.state = {
style: {}
};
return _this;
}
Modal.prototype.getChildContext = function getChildContext() {
return {
$bs_modal: {
onHide: this.props.onHide
}
};
};
Modal.prototype.componentWillUnmount = function componentWillUnmount() {
// Clean up the listener if we need to.
this.handleExited();
};
Modal.prototype.handleEntering = function handleEntering() {
// FIXME: This should work even when animation is disabled.
events.on(window, 'resize', this.handleWindowResize);
this.updateStyle();
};
Modal.prototype.handleExited = function handleExited() {
// FIXME: This should work even when animation is disabled.
events.off(window, 'resize', this.handleWindowResize);
};
Modal.prototype.handleWindowResize = function handleWindowResize() {
this.updateStyle();
};
Modal.prototype.handleDialogClick = function handleDialogClick(e) {
if (e.target !== e.currentTarget) {
return;
}
this.props.onHide();
};
Modal.prototype.updateStyle = function updateStyle() {
if (!canUseDOM) {
return;
}
var dialogNode = this._modal.getDialogElement();
var dialogHeight = dialogNode.scrollHeight;
var document = ownerDocument(dialogNode);
var bodyIsOverflowing = isOverflowing(ReactDOM.findDOMNode(this.props.container || document.body));
var modalIsOverflowing = dialogHeight > document.documentElement.clientHeight;
this.setState({
style: {
paddingRight: bodyIsOverflowing && !modalIsOverflowing ? getScrollbarSize() : undefined,
paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? getScrollbarSize() : undefined
}
});
};
Modal.prototype.render = function render() {
var _this2 = this;
var _props = this.props,
backdrop = _props.backdrop,
animation = _props.animation,
show = _props.show,
Dialog = _props.dialogComponentClass,
className = _props.className,
style = _props.style,
children = _props.children,
onEntering = _props.onEntering,
onExited = _props.onExited,
props = _objectWithoutProperties(_props, ['backdrop', 'animation', 'show', 'dialogComponentClass', 'className', 'style', 'children', 'onEntering', 'onExited']);
var _splitComponentProps = splitComponentProps(props, BaseModal),
baseModalProps = _splitComponentProps[0],
dialogProps = _splitComponentProps[1];
var inClassName = show && !animation && 'in';
return React.createElement(
BaseModal,
_extends({}, baseModalProps, {
ref: function ref(c) {
_this2._modal = c;
},
show: show,
onEntering: createChainedFunction(onEntering, this.handleEntering),
onExited: createChainedFunction(onExited, this.handleExited),
backdrop: backdrop,
backdropClassName: classNames(prefix(props, 'backdrop'), inClassName),
containerClassName: prefix(props, 'open'),
transition: animation ? Fade : undefined,
dialogTransitionTimeout: Modal.TRANSITION_DURATION,
backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION
}),
React.createElement(
Dialog,
_extends({}, dialogProps, {
style: _extends({}, this.state.style, style),
className: classNames(className, inClassName),
onClick: backdrop === true ? this.handleDialogClick : null
}),
children
)
);
};
return Modal;
}(React.Component);
Modal.propTypes = propTypes;
Modal.defaultProps = defaultProps;
Modal.childContextTypes = childContextTypes;
Modal.Body = Body;
Modal.Header = Header;
Modal.Title = Title;
Modal.Footer = Footer;
Modal.Dialog = ModalDialog;
Modal.TRANSITION_DURATION = 300;
Modal.BACKDROP_TRANSITION_DURATION = 150;
export default bsClass('modal', bsSizes([Size.LARGE, Size.SMALL], Modal)); |
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch07/07_01/finish/src/index.js | yevheniyc/C | import React from 'react'
import { render } from 'react-dom'
// import routes from './routes'
import Member from './components/ui/Member'
window.React = React
render(
<Member admin={true}
name="Edna Welch"
email="[email protected]"
thumbnail="https://randomuser.me/api/portraits/women/90.jpg"
makeAdmin={(email) => console.log(email)}/>,
document.getElementById('react-container'))
|
src/routes/tool/index.js | chunkiat82/rarebeauty-ui | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Tool from './Tool';
import Layout from '../../components/Layout';
function listFreeSlots(fetch) {
return async () => {
const slotsResponse = await fetch('/graphql', {
body: JSON.stringify({
query: `{slots{
start,
end,
durationInMinutes,
amp,
}
}`,
}),
});
const { data } = await slotsResponse.json();
return (data && data.slots) || [];
};
}
function show(store) {
return () => {
store.dispatch({ type: 'SHOW_LOADER' });
};
}
function hide(store) {
return () => {
store.dispatch({ type: 'HIDE_LOADER' });
};
}
async function action({ fetch, store }) {
show(store)();
const freeSlots = await listFreeSlots(fetch)();
hide(store)();
return {
chunks: ['tool'],
title: 'Rare Beauty Professional',
component: (
<Layout>
<Tool rows={freeSlots} />
</Layout>
),
};
}
export default action;
|
src/containers/NewRoutineForm.js | snsavage/timer-react | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import RoutineForm from './RoutineForm';
import { createRoutine } from '../actions/routineFormActions';
import { clearCurrentRoutine } from '../actions/routineActions';
export class NewRoutineForm extends Component {
componentWillMount() {
const { saved, clearCurrentRoutine } = this.props;
if(saved) { clearCurrentRoutine() };
}
render () {
return (
<RoutineForm
onSubmit={createRoutine}
formTitle={"New Routine"}
submitValue={"Create Routine"} />
);
}
}
function mapStateToProps(state) {
return {
saved: state.currentRoutine.saved,
}
}
function mapDispatchToProps(dispatch) {
return {
clearCurrentRoutine: bindActionCreators(clearCurrentRoutine, dispatch),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(NewRoutineForm);
|
client/components/Common/ListItem.js | Mignon-han/issue-processing | import React from 'react';
import './css/style.css';
import { hexToRgb } from '../../utils/utils';
const ListItem = ({ selected, label, value, color, onClick, visible }) => (
<div className="common-list-item">
<div className='item-container bgStyle' data-value={value}
onClick={() => onClick()} style={selected ? { backgroundColor: color ? hexToRgb(color, 0.5) : hexToRgb("#A8A8A8", 0.4) ,display:visible?'':'none'} : {display:visible?'':'none'}}>
<div className="item-color" style={{background:color}}></div>
<div className="item-label textOver">{label}</div>
</div>
</div>
);
export default ListItem; |
components/TimePickerSelect.js | hellobrian/carbon-components-react | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import Icon from './Icon';
export default class TimePickerSelect extends Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
id: PropTypes.string.isRequired,
inline: PropTypes.bool,
disabled: PropTypes.bool,
defaultValue: PropTypes.any,
iconDescription: PropTypes.string,
hideLabel: PropTypes.bool,
labelText: PropTypes.string,
};
static defaultProps = {
disabled: false,
inline: true,
iconDescription: 'open list of options',
hideLabel: true,
labelText: 'Provide label text',
};
render() {
const {
id,
disabled,
children,
iconDescription,
className,
hideLabel,
labelText,
inline, // eslint-disable-line
...other
} = this.props;
const selectClasses = classNames({
'bx--select': true,
'bx--time-picker__select': true,
'bx--select--inline': true,
[className]: className,
});
const labelClasses = classNames('bx--label', {
'bx--visually-hidden': hideLabel,
});
const label = labelText ? (
<label htmlFor={id} className={labelClasses}>
{labelText}
</label>
) : null;
return (
<div className={selectClasses}>
{label}
<select
{...other}
id={id}
className="bx--select-input"
disabled={disabled}>
{children}
</select>
<Icon
name="caret--down"
className="bx--select__arrow"
description={iconDescription}
/>
</div>
);
}
}
|
docs-ui/components/checkboxFancy.stories.js | beeftornado/sentry | import React from 'react';
import {withInfo} from '@storybook/addon-info';
import {number, boolean} from '@storybook/addon-knobs';
import styled from '@emotion/styled';
import CheckboxFancy from 'app/components/checkboxFancy/checkboxFancy';
export default {
title: 'Core/Style/Icons',
};
export const _CheckboxFancy = withInfo('A fancy looking checkbox')(() => {
return (
<Container>
<CheckboxFancy
size={`${number('Size', 100)}px`}
isChecked={boolean('Checked', true)}
/>
</Container>
);
});
_CheckboxFancy.story = {
name: 'CheckboxFancy',
};
const Container = styled('div')`
display: flex;
flex-direction: column;
padding: 20px;
`;
|
src/js/components/Employees/New.js | appdev-academy/appdev.academy-react | import React from 'react'
import { browserHistory } from 'react-router'
import { inject, observer } from 'mobx-react'
import Form from './Form'
@inject('employeesStore')
@observer
export default class New extends React.Component {
constructor(props) {
super(props)
this.state = {
errors: []
}
}
handleSubmit(employeeParams) {
this.props.employeesStore.create(employeeParams).then((response) => {
if (response.status == 201) {
browserHistory.push('/employees')
}
}).catch((error) => {
if (error.response && error.response.data && error.response.data.errors) {
this.setState({
errors: error.response.data.errors
})
}
})
}
render() {
return (
<Form
errors={ this.state.errors }
handleSubmit={ this.handleSubmit.bind(this) }
ref='employeeForm'
/>
)
}
}
|
src/components/Header/index.js | frintjs/frint.js.org | import React from 'react';
import Link from "gatsby-link";
import SearchForm from '../SearchForm';
const Header = () => (
<div className="container">
<div className="nav-left">
<Link activeClassName="is-active" className="nav-item brand" to="/">
<img alt="Frint" className="dark" src="/img/frint-logo-7a7a7a.png" />
<img alt="Frint" className="light" src="/img/frint-logo-fff.png" />
</Link>
<Link activeClassName="is-active" className="nav-item is-tab" to="/docs">
Documentation
</Link>
<a className="nav-item is-tab" href="https://medium.com/frintjs">
Blog
</a>
<Link activeClassName="is-active" className="nav-item is-tab" to="/repl">
REPL
</Link>
<Link activeClassName="is-active" className="nav-item is-tab" to="/about">
About
</Link>
</div>
<div className="nav-right">
<div className="field nav-item">
<SearchForm />
</div>
</div>
</div>
);
export default Header;
|
src/components/common/FeedbackBlock/index.js | goodjoblife/GoodJobShare | import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import ReactGA from 'react-ga';
import { Heading } from 'common/base';
import Button from 'common/button/Button';
import ButtonGroupImage from 'common/button/ButtonGroupImage';
import Checked from 'common/icons/Checked';
import Close from 'common/icons/Close';
import styles from './FeedbackBlock.module.css';
class FeedbackBlock extends React.Component {
static propTypes = {
category: PropTypes.string.isRequired,
question: PropTypes.string,
placeholders: PropTypes.shape({
yes: PropTypes.string,
no: PropTypes.string,
}),
className: PropTypes.string,
};
static defaultProps = {
question: '請問您是否覺得以上的資訊實用? 感到滿意?',
placeholders: {
yes: '說說為什麼你覺得很實用?',
no: '說說為什麼你覺得不實用? 或是有任何其他的回饋?',
},
className: '',
};
constructor(props) {
super(props);
this.state = {
polarity: null,
feedback: '',
done: false,
};
}
onSubmit = () => {
ReactGA.event({
category: this.props.category,
action: this.state.polarity,
label: this.state.feedback,
});
this.setState({ done: true });
};
render() {
const { polarity, feedback, done } = this.state;
const { question, placeholders, className } = this.props;
if (done) {
return (
<div className={cn(styles.doneBlock, className)}>
<Checked className={styles.icon} style={{ marginRight: 20 }} />
<Heading size="sm" Tag="h4">
感謝您的回饋!
</Heading>
</div>
);
}
return (
<div className={cn(styles.feedbackBlock, className)}>
<Heading size="sm" Tag="h4">
{question}
</Heading>
<ButtonGroupImage
className={styles.btnGroup}
value={this.state.polarity}
onChange={v => {
this.setState({ polarity: v });
}}
options={[
{
value: 'yes',
label: '是',
icon: <Checked className={styles.icon} />,
},
{
value: 'no',
label: '否',
icon: <Close className={styles.icon} />,
},
]}
theme="yellow"
/>
{polarity === null ? null : (
<textarea
className={styles.feedback}
placeholder={
polarity === 'yes' ? placeholders.yes : placeholders.no
}
onChange={e => {
e.preventDefault();
this.setState({ feedback: e.target.value });
}}
value={feedback}
/>
)}
{polarity === null ? null : (
<Button
btnStyle="submit"
onClick={this.onSubmit}
className={styles.submitBtn}
>
送出
</Button>
)}
</div>
);
}
}
export default FeedbackBlock;
|
pootle/static/js/admin/components/ItemTableRow.js | JohnnyKing94/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import cx from 'classnames';
import React from 'react';
const ItemTableRow = React.createClass({
propTypes: {
fields: React.PropTypes.array.isRequired,
item: React.PropTypes.object.isRequired,
index: React.PropTypes.number.isRequired,
selectedItem: React.PropTypes.object,
onSelectItem: React.PropTypes.func.isRequired,
},
render() {
const { item } = this.props;
const { selectedItem } = this.props;
const { index } = this.props;
const values = item.toJSON();
values.index = index + 1;
function createColumn(field, i) {
return <td key={i}>{values[field]}</td>;
}
const classNames = cx({
'is-selected': selectedItem && item.id === selectedItem.id,
// FIXME: this is too coupled to certain item types
'is-disabled': item.get('disabled'),
'row-divider': index !== 0 && index % 10 === 0,
});
return (
<tr
className={classNames}
key={item.id}
onClick={() => this.props.onSelectItem(item.id)}
>
{this.props.fields.map(createColumn)}
</tr>
);
},
});
export default ItemTableRow;
|
docs/website/src/templates/package.js | adaltas/node-nikita | // React
import React from 'react'
// Gatsby
import { graphql, Link } from 'gatsby'
// MDX
import { MDXProvider } from "@mdx-js/react"
import { MDXRenderer } from "gatsby-plugin-mdx"
// Local
import Layout from '../components/Layout'
const Template = ({
data
}) => {
const { page } = data
return (
<Layout page={{
keywords: page.keywords,
description: page.description,
...page.parent.frontmatter,
slug: page.slug,
version: page.version.alias,
edit_url: page.edit_url}}>
<>
<MDXProvider>
<MDXRenderer>{page.parent.body}</MDXRenderer>
</MDXProvider>
{page.actions && (
<>
<h2>Actions</h2>
<ul>
{page.actions
.sort((p1, p2) => p1.slug > p2.slug)
.map( item => (
<li key={item.slug}>
<Link to={item.slug}>{item.name}</Link>
</li>
)
)}
</ul>
</>
)}
</>
</Layout>
)
}
export default Template
export const pageQuery = graphql`
query($path: String!) {
page: nikitaPackage(slug: { eq: $path }) {
slug
edit_url
description
keywords
version {
alias
}
parent {
... on Mdx {
frontmatter {
title
titleHtml
}
body
}
}
actions {
name
slug
}
}
}
`
|
app/javascript/mastodon/components/admin/Retention.js | abcang/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import api from 'mastodon/api';
import { FormattedMessage, FormattedNumber, FormattedDate } from 'react-intl';
import classNames from 'classnames';
import { roundTo10 } from 'mastodon/utils/numbers';
const dateForCohort = cohort => {
switch(cohort.frequency) {
case 'day':
return <FormattedDate value={cohort.period} month='long' day='2-digit' />;
default:
return <FormattedDate value={cohort.period} month='long' year='numeric' />;
}
};
export default class Retention extends React.PureComponent {
static propTypes = {
start_at: PropTypes.string,
end_at: PropTypes.string,
frequency: PropTypes.string,
};
state = {
loading: true,
data: null,
};
componentDidMount () {
const { start_at, end_at, frequency } = this.props;
api().post('/api/v1/admin/retention', { start_at, end_at, frequency }).then(res => {
this.setState({
loading: false,
data: res.data,
});
}).catch(err => {
console.error(err);
});
}
render () {
const { loading, data } = this.state;
const { frequency } = this.props;
let content;
if (loading) {
content = <FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' />;
} else {
content = (
<table className='retention__table'>
<thead>
<tr>
<th>
<div className='retention__table__date retention__table__label'>
<FormattedMessage id='admin.dashboard.retention.cohort' defaultMessage='Sign-up month' />
</div>
</th>
<th>
<div className='retention__table__number retention__table__label'>
<FormattedMessage id='admin.dashboard.retention.cohort_size' defaultMessage='New users' />
</div>
</th>
{data[0].data.slice(1).map((retention, i) => (
<th key={retention.date}>
<div className='retention__table__number retention__table__label'>
{i + 1}
</div>
</th>
))}
</tr>
<tr>
<td>
<div className='retention__table__date retention__table__average'>
<FormattedMessage id='admin.dashboard.retention.average' defaultMessage='Average' />
</div>
</td>
<td>
<div className='retention__table__size'>
<FormattedNumber value={data.reduce((sum, cohort, i) => sum + ((cohort.data[0].value * 1) - sum) / (i + 1), 0)} maximumFractionDigits={0} />
</div>
</td>
{data[0].data.slice(1).map((retention, i) => {
const average = data.reduce((sum, cohort, k) => cohort.data[i + 1] ? sum + (cohort.data[i + 1].rate - sum)/(k + 1) : sum, 0);
return (
<td key={retention.date}>
<div className={classNames('retention__table__box', 'retention__table__average', `retention__table__box--${roundTo10(average * 100)}`)}>
<FormattedNumber value={average} style='percent' />
</div>
</td>
);
})}
</tr>
</thead>
<tbody>
{data.slice(0, -1).map(cohort => (
<tr key={cohort.period}>
<td>
<div className='retention__table__date'>
{dateForCohort(cohort)}
</div>
</td>
<td>
<div className='retention__table__size'>
<FormattedNumber value={cohort.data[0].value} />
</div>
</td>
{cohort.data.slice(1).map(retention => (
<td key={retention.date}>
<div className={classNames('retention__table__box', `retention__table__box--${roundTo10(retention.rate * 100)}`)}>
<FormattedNumber value={retention.rate} style='percent' />
</div>
</td>
))}
</tr>
))}
</tbody>
</table>
);
}
let title = null;
switch(frequency) {
case 'day':
title = <FormattedMessage id='admin.dashboard.daily_retention' defaultMessage='User retention rate by day after sign-up' />;
break;
default:
title = <FormattedMessage id='admin.dashboard.monthly_retention' defaultMessage='User retention rate by month after sign-up' />;
};
return (
<div className='retention'>
<h4>{title}</h4>
{content}
</div>
);
}
}
|
client/src/index.js | medelbou/react-redux-express | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
examples/react-application/index.js | alexeyraspopov/actor-system | import React from 'react';
import ReactDOM from 'react-dom';
import { ActorSystem } from 'actor-system';
import Application from './modules/Application.react';
import Wrapper from './modules/Wrapper.react';
import Storage from './modules/Storage';
import Main from './modules/Main.actor';
const system = ActorSystem.fromDefaults();
const storage = new Storage();
ReactDOM.render((
<Application system={system} storage={storage}>
<Wrapper />
</Application>
), document.querySelector('main'));
system.spawn(Main);
|
tp-3/euge/src/components/pages/alumnos/components/form/AlumnoForm.js | jpgonzalezquinteros/sovos-reactivo-2017 | import React from 'react';
import './alumnoForm.scss';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import TextField from 'material-ui/TextField';
import {orange500, blue500} from 'material-ui/styles/colors';
import RaisedButton from 'material-ui/RaisedButton';
const styles = {
errorStyle: {
color: '#283593',
},
underlineStyle: {
borderColor: '#283593',
},
floatingLabelStyle: {
color: '#283593',
},
floatingLabelFocusStyle: {
color: blue500,
},
buttonStyle: {
margin: 12,
}
};
class AlumnoForm extends React.Component{
constructor(){
super();
this.alumno = {
nombre: "",
dni: "",
direccion: "",
fechanac: "",
estado: ""
};
}
compomentDidUpdate(){
this.alumno = {};
}
handleNombreChange =(evt)=>{
this.alumno.nombre = evt.target.value;
}
handleDniChange =(evt)=>{
this.alumno.dni = evt.target.value;
}
handleDireccionChange =(evt)=>{
this.alumno.direccion = evt.target.value;
}
handleFechanacChange =(evt)=>{
this.alumno.fechanac = evt.target.value;
}
handleEstadoChange =(evt)=>{
this.alumno.estado = evt.target.value;
}
handleSaveClick =(evt)=>{
console.log(this.alumno);
this.props.onNewAlumno(this.alumno);
document.getElementById("alumno-form").reset();
this.alumno={};
}
render(){
return (
<MuiThemeProvider>
<div>
<h2 className="alumnoForm">Nuevo Alumno</h2>
<form className="alumnoForm" id="alumno-form">
<TextField
floatingLabelText="Nombre"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleNombreChange}
/><br/>
<TextField
floatingLabelText="DNI"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleDniChange}
/><br/>
<TextField
floatingLabelText="Fecha de Nacimiento"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleFechanacChange}
/><br/>
<TextField
floatingLabelText="Direccion"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleDireccionChange}
/><br/>
<TextField
floatingLabelText="Estado"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleEstadoChange}
/><br/><br/>
<RaisedButton label="Guardar" style={styles.buttonStyle} onClick={this.handleSaveClick} />
</form>
</div>
</MuiThemeProvider>
);
}
};
export default AlumnoForm;
|
src/commons/title.js | jessy1092/react-semantify |
import React from 'react';
import filter from '../filter';
import Div from './div';
const stateArray = ['active'];
const defaultClassName = 'title';
const componentName = 'Title';
const Title = new filter(Div)
.stateFilter(stateArray)
.classGenerator(defaultClassName)
.getComposeComponent(componentName);
export default Title;
|
mobile/mock ups/tech_stack/App.js | parammehta/TravLendar | import React from 'react';
import { View } from 'react-native';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './src/reducers';
import { Header } from './src/components/common';
import LibraryList from './src/components/LibraryList';
const App = () => (
<Provider store={createStore(reducers)}>
<View style={{ flex: 1 }}>
<Header headerText="Tech Stack" />
<LibraryList />
</View>
</Provider>
);
export default App;
|
src/components/CardsList/cardsList.js | VitaliiK91/AlramRN | import React from 'react';
import PropTypes from 'prop-types';
import {
ScrollView,
} from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { cards as actions } from '../../store/actions';
import Card from '../Card';
const CardList = props => (
<ScrollView>
{
props.cards.map(
card => (
<Card
key={card.id}
onToggle={() => props.toggleCard(card.id)}
text={card.text}
enabled={card.enabled}
/>
),
)
}
</ScrollView>
);
CardList.defaultProps = {
cards: [],
};
CardList.propTypes = {
cards: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
text: PropTypes.string,
enabled: PropTypes.bool,
})),
};
export default connect(
null,
dispatch => ({
toggleCard: bindActionCreators(actions.toggleCard, dispatch),
}),
)(CardList);
|
src/components/atoms/Paragraph/index.stories.js | SIB-Colombia/dataportal_v2_frontend | import React from 'react'
import { storiesOf } from '@kadira/storybook'
import Paragraph from '.'
storiesOf('Paragraph', module)
.add('default', () => (
<Paragraph>
Nisi eu eiusmod cupidatat aute laboris commodo excepteur esse dolore incididunt incididunt aliquip pariatur est minim officia sit. Nulla pariatur duis duis quis commodo cupidatat voluptate enim culpa elit adipisicing do cupidatat sint anim. Cillum elit magna occaecat proident sit cupidatat ad quis sunt id culpa culpa. Ad duis nulla in incididunt amet consequat officia ad voluptate voluptate. Pariatur eiusmod ullamco cupidatat non magna officia aute magna deserunt qui aute dolor eu. Qui amet non ex cillum sunt ad velit consequat ipsum velit.
</Paragraph>
))
.add('reverse', () => (
<Paragraph reverse>
Nisi eu eiusmod cupidatat aute laboris commodo excepteur esse dolore incididunt incididunt aliquip pariatur est minim officia sit. Nulla pariatur duis duis quis commodo cupidatat voluptate enim culpa elit adipisicing do cupidatat sint anim. Cillum elit magna occaecat proident sit cupidatat ad quis sunt id culpa culpa. Ad duis nulla in incididunt amet consequat officia ad voluptate voluptate. Pariatur eiusmod ullamco cupidatat non magna officia aute magna deserunt qui aute dolor eu. Qui amet non ex cillum sunt ad velit consequat ipsum velit.
</Paragraph>
))
|
src/svg-icons/action/flight-land.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFlightLand = (props) => (
<SvgIcon {...props}>
<path d="M2.5 19h19v2h-19zm7.18-5.73l4.35 1.16 5.31 1.42c.8.21 1.62-.26 1.84-1.06.21-.8-.26-1.62-1.06-1.84l-5.31-1.42-2.76-9.02L10.12 2v8.28L5.15 8.95l-.93-2.32-1.45-.39v5.17l1.6.43 5.31 1.43z"/>
</SvgIcon>
);
ActionFlightLand = pure(ActionFlightLand);
ActionFlightLand.displayName = 'ActionFlightLand';
ActionFlightLand.muiName = 'SvgIcon';
export default ActionFlightLand;
|
src/Tab.js | thealjey/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const Tab = React.createClass({
propTypes: {
/**
* @private
*/
active: React.PropTypes.bool,
animation: React.PropTypes.bool,
/**
* It is used by 'Tabs' - parent component
* @private
*/
onAnimateOutEnd: React.PropTypes.func,
disabled: React.PropTypes.bool,
title: React.PropTypes.node
},
getDefaultProps() {
return {
animation: true
};
},
getInitialState() {
return {
animateIn: false,
animateOut: false
};
},
componentWillReceiveProps(nextProps) {
if (this.props.animation) {
if (!this.state.animateIn && nextProps.active && !this.props.active) {
this.setState({
animateIn: true
});
} else if (!this.state.animateOut && !nextProps.active && this.props.active) {
this.setState({
animateOut: true
});
}
}
},
componentDidUpdate() {
if (this.state.animateIn) {
setTimeout(this.startAnimateIn, 0);
}
if (this.state.animateOut) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.stopAnimateOut
);
}
},
startAnimateIn() {
if (this.isMounted()) {
this.setState({
animateIn: false
});
}
},
stopAnimateOut() {
if (this.isMounted()) {
this.setState({
animateOut: false
});
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd();
}
}
},
render() {
let classes = {
'tab-pane': true,
'fade': true,
'active': this.props.active || this.state.animateOut,
'in': this.props.active && !this.state.animateIn
};
return (
<div {...this.props}
title={undefined}
role="tabpanel"
aria-hidden={!this.props.active}
className={classNames(this.props.className, classes)}
>
{this.props.children}
</div>
);
}
});
export default Tab;
|
example/app.js | snario/react-mapbox-gl | import React from 'react';
import SimpleExample from './simple';
import EventsExample from './events';
import VectorLayersExample from './vector-layers';
const examples = <div>
<h1>React-Leaflet examples</h1>
<h2>Popup with Marker</h2>
<SimpleExample />
<h2>Events</h2>
<p>Click the map to show a marker at your detected location</p>
<EventsExample />
<h2>Vector layers</h2>
<VectorLayersExample />
</div>;
React.render(examples, document.getElementById('app'));
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-auto-complete.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import {BaseMixin, ElementaryMixin, ContentMixin} from './../common/common.js';
import {Link, Backdrop} from './../bricks/bricks.js';
import $ from 'jquery';
import './auto-complete.less';
export default React.createClass({
mixins: [
BaseMixin,
ElementaryMixin,
ContentMixin
],
statics: {
tagName: 'UU5.Forms.AutoComplete',
classNames: {
main: 'uu5-forms-auto-complete',
open: 'uu5-forms-auto-complete-opened',
menu: 'uu5-forms-auto-complete-menu list-group',
item: 'uu5-forms-auto-complete-item list-group-item',
selected: 'uu5-forms-auto-complete-selected'
}
},
propTypes: {
items: React.PropTypes.arrayOf(
React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
params: React.PropTypes.object,
content: React.PropTypes.any
})
),
onClick: React.PropTypes.func
},
// Setting defaults
getDefaultProps: function () {
return {
items: null,
onClick: null
};
},
getInitialState: function () {
return {
items: null,
selectedIndex: null
};
},
// Interface
find: function (foundValue, setStateCallback) {
var values = { first: [], last: [] };
this.props.items.forEach(function (item) {
if (foundValue !== '') {
if (new RegExp('^' + foundValue, 'i').exec(item.value)) {
values.first.push(item);
} else if (new RegExp(foundValue, 'gi').exec(item.value)) {
values.last.push(item);
}
}
});
var allValues = values.first.concat(values.last);
this.setState({ items: allValues.length ? allValues : null, selectedIndex: null }, setStateCallback);
return this;
},
close: function (setStateCallback) {
this.setState({ items: null, selectedIndex: null }, setStateCallback);
return this;
},
isOpened: function () {
return !!this.state.items;
},
selectUp: function (setStateCallback) {
var autoComplete = this;
this.setState(function (state) {
var index = null;
if (autoComplete.state.items) {
if (state.selectedIndex == null || state.selectedIndex === 0) {
index = autoComplete.state.items.length - 1;
} else {
index = state.selectedIndex - 1;
}
}
var offset = index > autoComplete.state.items.length - 3 ?
$('#' + autoComplete.getId() + '-item-' + (autoComplete.state.items.length - 1))[0].offsetTop :
index - 1 > 0 ? $('#' + autoComplete.getId() + '-item-' + (index - 1))[0].offsetTop : 0;
$('#' + this.getId() + '-menu').animate({ scrollTop: offset }, 0);
return { selectedIndex: index };
}, setStateCallback);
return this;
},
selectDown: function (setStateCallback) {
var autoComplete = this;
this.setState(function (state) {
var index = null;
var newState;
if (autoComplete.state.items) {
if (state.selectedIndex == null || state.selectedIndex === autoComplete.state.items.length - 1) {
index = 0;
} else {
index = state.selectedIndex + 1;
}
var offset = index > 1 ? $('#' + autoComplete.getId() + '-item-' + (index - 1))[0].offsetTop : 0;
$('#' + autoComplete.getId() + '-menu').animate({ scrollTop: offset }, 0);
newState = { selectedIndex: index };
} else {
newState = {
items: autoComplete.props.items.sort(function (a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}), selectedIndex: 0
};
}
return newState;
}, setStateCallback);
return this;
},
confirmSelected: function (setStateCallback) {
this.state.items && this._confirm(this.state.items[this.state.selectedIndex], this.state.selectedIndex, setStateCallback);
return this;
},
// Overriding Functions
// Component Specific Helpers
_getBackdropProps: function () {
var backdropId = this.getId() + "-backdrop";
return {
hidden: !this.isOpened(),
id: backdropId,
onClick: function (backdrop, event) {
event.target.id === backdropId && this.close();
}.bind(this)
};
},
_onClick: function (value, i) {
this._confirm(value, i);
return this;
},
_confirm: function (item, i, setStateCallback) {
if (typeof this.props.onClick === 'function') {
this.props.onClick({ value: item.value, item: item, index: i, component: this });
}
this.close(setStateCallback);
return this;
},
_getChildren: function () {
var autoComplete = this;
return this.state.items && this.state.items.map(function (item, i) {
var className = autoComplete.getClassName().item;
autoComplete.state.selectedIndex === i && (className += ' ' + autoComplete.getClassName().selected);
return (
<Link
className={className}
key={i}
content={item.content || item.value}
onClick={autoComplete._onClick.bind(autoComplete, item, i)}
mainAttrs={{ id: autoComplete.getId() + '-item-' + i }}
/>
);
});
},
_getMainAttrs: function () {
var mainAttrs = this.buildMainAttrs();
this.state.items && (mainAttrs.className += ' ' + this.getClassName().open);
return mainAttrs;
},
// Render
render: function () {
return (
<div {...this._getMainAttrs()}>
<Backdrop {...this._getBackdropProps()} />
<div className={this.getClassName().menu} id={this.getId() + '-menu'}>
{this._getChildren()}
</div>
</div>
);
}
}); |
app/screens/gold/gold.container.js | it-surya/hack-jeninvest | import React from 'react';
import {
View,
Image,
Keyboard
} from 'react-native';
import {
RkButton,
RkText,
RkTextInput,
RkStyleSheet,
RkTheme,
RkAvoidKeyboard,
RkChoice
} from 'react-native-ui-kitten';
import {GradientButton} from '../../components/';
import {scale, scaleModerate, scaleVertical} from '../../utils/scale';
export class GoldForm extends React.Component {
static navigationOptions = {
title: 'Gold Investment'.toUpperCase()
};
constructor(props) {
super(props);
this._renderPtName = this._renderPtName.bind(this);
}
_renderPtName = () => {
return (
<View style={styles.ptName}>
<Image style={styles.image} source={require('../../assets/images/logo.png')}/>
<RkText style={styles.ptNameTitle}>fds</RkText>
</View>
);
}
render() {
let renderIcon = () => {
if (RkTheme.current.name === 'light')
return <Image style={styles.image} source={require('../../assets/images/logo.png')}/>;
return <Image style={styles.image} source={require('../../assets/images/logoDark.png')}/>
};
return (
<RkAvoidKeyboard
style={styles.screen}
onStartShouldSetResponder={ (e) => true}
onResponderRelease={ (e) => Keyboard.dismiss()}>
{this._renderPtName()}
<View style={styles.content}>
<View>
<RkChoice rkType='posNeg' selected={false}/>
<RkTextInput rkType='topLabel' placeholder='Email'/>
<RkTextInput rkType='bordered' placeholder='Name'/>
<RkTextInput rkType='form' placeholder='Email'/>
<RkTextInput rkType='rounded' placeholder='Password' secureTextEntry={true}/>
<RkTextInput placeholder='Confirm Password' secureTextEntry={true}/>
</View>
<RkButton style={{backgroundColor: '#8fbc5a'}} rkType='stretch' onPress={() => this.props.navigation.navigate('Login1')}>
<RkText style={{color: '#ffffff'}} rkType='header6'> Sign in now </RkText>
</RkButton>
<View style={styles.footer}>
<View style={styles.textRow}>
<RkText rkType='primary3'>Already have an account?</RkText>
</View>
</View>
</View>
</RkAvoidKeyboard>
)
}
}
let styles = RkStyleSheet.create(theme => ({
screen: {
padding: 16,
flex: 1,
justifyContent: 'space-around',
backgroundColor: theme.colors.screen.base
},
ptName: {
flexDirection: 'row',
paddingBottom: 10,
borderBottomWidth: 1,
borderColor: '#d1d1d1'
},
ptNameTitle: {
paddingLeft: 10
},
image: {
width: scale(30),
height:scaleVertical(30),
resizeMode:'contain',
paddingRight: 10
},
content: {
justifyContent: 'space-between'
},
save: {
//marginVertical: 20
},
buttons: {
flexDirection: 'row',
marginBottom: 24,
marginHorizontal: 24,
justifyContent: 'space-around'
},
footer:{
justifyContent:'flex-end'
},
textRow: {
flexDirection: 'row',
justifyContent: 'center'
},
})); |
src/px-modal/index.js | jonniespratley/px-components-react | import React from 'react';
import Overlay from '../px-overlay';
import Button from '../px-button';
import classnames from 'classnames';
import stylesheet from './style.scss';
/**
* px-modal component
*/
export default ({
style,
modalHeading = 'Modal',
btnModalNegative,
onBtnModalNegativeClick,
btnModalPositive,
onBtnModalPositiveClick,
visible,
isOpen,
onBackdropClick,
btnModalPositiveDisabled = false,
children
}) => {
const modalClassnames = classnames(
'modal',
'flex',
'flex--middle',
'flex--center',
'full-height',
{'invisible' : !visible}
);
return (
<div className='px-modal'>
<Overlay visible={visible} onOverlayClick={(e) => onBackdropClick(e)}/>
<div className={modalClassnames} role="dialog">
<section className="modal__content" role='region'>
<h3 className="modal__title epsilon weight--normal">{modalHeading}</h3>
<div>
{children}
</div>
<div className="modal__buttons flex flex--right">
<div className='flex'>
{btnModalNegative && <Button id="btnModalNegative"
label={btnModalNegative}
onClick={(e) => onBtnModalNegativeClick(e)}/>}
{btnModalPositive && <Button primary
disabled={btnModalPositiveDisabled}
id="btnModalPositive"
label={btnModalPositive}
onClick={(e) => onBtnModalPositiveClick(e)}/>}
</div>
</div>
</section>
</div>
<style jsx>{stylesheet}</style>
</div>);
}
|
src/svg-icons/av/recent-actors.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvRecentActors = (props) => (
<SvgIcon {...props}>
<path d="M21 5v14h2V5h-2zm-4 14h2V5h-2v14zM14 5H2c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM8 7.75c1.24 0 2.25 1.01 2.25 2.25S9.24 12.25 8 12.25 5.75 11.24 5.75 10 6.76 7.75 8 7.75zM12.5 17h-9v-.75c0-1.5 3-2.25 4.5-2.25s4.5.75 4.5 2.25V17z"/>
</SvgIcon>
);
AvRecentActors = pure(AvRecentActors);
AvRecentActors.displayName = 'AvRecentActors';
AvRecentActors.muiName = 'SvgIcon';
export default AvRecentActors;
|
app/javascript/mastodon/features/hashtag_timeline/components/column_settings.js | cybrespace/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { injectIntl, FormattedMessage } from 'react-intl';
import Toggle from 'react-toggle';
import AsyncSelect from 'react-select/lib/Async';
export default @injectIntl
class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onLoad: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
open: this.hasTags(),
};
hasTags () {
return ['all', 'any', 'none'].map(mode => this.tags(mode).length > 0).includes(true);
}
tags (mode) {
let tags = this.props.settings.getIn(['tags', mode]) || [];
if (tags.toJSON) {
return tags.toJSON();
} else {
return tags;
}
};
onSelect = (mode) => {
return (value) => {
this.props.onChange(['tags', mode], value);
};
};
onToggle = () => {
if (this.state.open && this.hasTags()) {
this.props.onChange('tags', {});
}
this.setState({ open: !this.state.open });
};
modeSelect (mode) {
return (
<div className='column-settings__section'>
{this.modeLabel(mode)}
<AsyncSelect
isMulti
autoFocus
value={this.tags(mode)}
settings={this.props.settings}
settingPath={['tags', mode]}
onChange={this.onSelect(mode)}
loadOptions={this.props.onLoad}
classNamePrefix='column-settings__hashtag-select'
name='tags'
/>
</div>
);
}
modeLabel (mode) {
switch(mode) {
case 'any': return <FormattedMessage id='hashtag.column_settings.tag_mode.any' defaultMessage='Any of these' />;
case 'all': return <FormattedMessage id='hashtag.column_settings.tag_mode.all' defaultMessage='All of these' />;
case 'none': return <FormattedMessage id='hashtag.column_settings.tag_mode.none' defaultMessage='None of these' />;
}
return '';
};
render () {
return (
<div>
<div className='column-settings__row'>
<div className='setting-toggle'>
<Toggle
id='hashtag.column_settings.tag_toggle'
onChange={this.onToggle}
checked={this.state.open}
/>
<span className='setting-toggle__label'>
<FormattedMessage id='hashtag.column_settings.tag_toggle' defaultMessage='Include additional tags in this column' />
</span>
</div>
</div>
{this.state.open &&
<div className='column-settings__hashtags'>
{this.modeSelect('any')}
{this.modeSelect('all')}
{this.modeSelect('none')}
</div>
}
</div>
);
}
}
|
extension/panel/src/components/app-view.js | capacitorjs/capacitor | 'use strict';
import React from 'react';
import {RouteHandler} from 'react-router';
import Locator from 'capacitor-locator';
import PluginList from 'src/components/plugin-list';
import PluginStore from 'src/stores/plugin';
/**
* Display the current list of plugins and the currently-selected plugin
*/
export default class AppView extends React.Component {
constructor(props) {
super(props);
this._pluginStore = Locator.get(PluginStore);
this.state = {plugins: this._pluginStore.data};
const listener = this._updatePlugins.bind(this);
this._pluginStore.emitter.on('change', listener);
this._dispose = () => {
this._pluginStore.emitter.removeListener('change', listener);
};
}
_updatePlugins() {
this.setState({plugins: this._pluginStore.data});
}
componentWillUnmount() {
this._dispose();
}
render() {
return (
<div className='app-view'>
<PluginList plugins={this.state.plugins}/>
<RouteHandler/>
</div>
);
}
}
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-bricks-camera.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import {BaseMixin, ElementaryMixin, Tools} from '../common/common.js';
import './camera.less';
// TODO
// quality of picture -> jpg, png, ...
// choice of camera devices if pc has more cameras
export const Camera = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Bricks.Camera',
classNames: {
main: 'uu5-bricks-camera',
video: 'uu5-bricks-camera-video',
canvas: 'uu5-bricks-camera-canvas'
},
errors: {
videoError: 'Video can not be loaded.'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
componentWillMount: function () {
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia
|| navigator.msGetUserMedia
|| navigator.oGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ video: true }, this._handleVideo, this._videoError);
}
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
getScreenShot: function () {
var img = null;
if (this.localMediaStream) {
var canvas = this.canvas;
canvas.width = Tools.getWidth(this);
canvas.height = Tools.getHeight(this);
var ctx = canvas.getContext('2d');
ctx.drawImage(this.video, 0, 0, Tools.getWidth(this), Tools.getHeight(this));
img = canvas.toDataURL('image/png');
}
return img;
},
//@@viewOff:interface
//@@viewOn:overridingMethods
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_handleVideo: function (stream) {
var video = this.video;
video.src = window.URL.createObjectURL(stream);
this.localMediaStream = stream;
return this;
},
_videoError: function (e) {
this.showError('videoError', null, { context: { event: e, src: this.video.src } });
return this;
},
_refVideo: function (video) {
this.video = video;
return this;
},
_refCanvas: function (canvas) {
this.canvas = canvas;
return this;
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render: function () {
return (
<div {...this.getMainAttrs()}>
<video autoPlay="true" ref={this._refVideo} className={this.getClassName().video} />
<canvas ref={this._refCanvas} className={this.getClassName().canvas} />
{this.getDisabledCover()}
</div>
);
}
//@@viewOff:render
});
export default Camera; |
shared/app/Tms/config/components/TmsConfig.js | pebie/react-universally-node-config | import React from 'react';
import PropTypes from 'prop-types';
import serialize from 'serialize-javascript';
import filterWithRules from '../../../../../shared/utils/objects/filterWithRules';
import { getConfig } from '../../config';
const values = getConfig();
// Filter the config down to the properties that are allowed to be included
// in the HTML response.
const clientConfig = filterWithRules(
// These are the rules used to filter the config.
values.clientConfigFilter,
// The config values to filter.
values,
);
const serializedClientConfig = serialize(clientConfig);
/**
* A react component that generates a script tag that binds the allowed
* values to the window so that config values can be read within the
* browser.
*
* They get bound to window.__CLIENT_CONFIG__
*/
function TmsConfig({ nonce, children }) {
return (
<div>
<script
type="text/javascript"
nonce={nonce}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `window.__TMS_CONFIG__=${serializedClientConfig}`,
}}
/>
{children}
</div>
);
}
TmsConfig.propTypes = {
nonce: PropTypes.string.isRequired,
children: PropTypes.node,
};
TmsConfig.defaultProps = {
children: null,
};
export default TmsConfig;
|
src/common/EmptyView/EmptyViewDouble.js | Syncano/syncano-dashboard | import React from 'react';
import { FontIcon, RaisedButton } from 'material-ui';
const EmptyViewDouble = ({
title,
description,
iconClassName,
iconColor,
leftIconType,
rightIconType,
handleClickRightButton,
handleClickLeftButton,
labelButtonLeft,
labelButtonRight
}) => {
const styles = {
container: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
height: '100%',
textAlign: 'center',
padding: '70px 50px'
},
mainContainer: {
color: '#000',
width: 680,
height: 500,
border: '2px #dedede dashed',
borderRadius: 5,
margin: '50px auto 0 auto'
},
icon: {
fontSize: 72
},
title: {
marginTop: 40,
fontSize: 26,
fontWeight: 400,
lineHeight: '34px',
hyphens: 'none',
'-webkit-hyphens': 'none', /* Saf 5.1+ */
'-moz-hyphens': 'none', /* Fx 6.0+ */
'-ms-hyphens': 'none' /* IE 10+ */
},
description: {
lineHeight: '26px',
fontSize: 16,
padding: 40,
textAlign: 'center'
},
url: {
display: 'block',
fontSize: 16,
marginBottom: 20
},
box: {
width: 250
},
flexContainer: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'flex-start'
}
};
return (
<div style={styles.mainContainer}>
<div
data-e2e="push-notifications-empty-view"
style={styles.container}
>
<FontIcon
className={iconClassName}
color={iconColor}
style={styles.icon}
/>
<div style={styles.title}>
{title}
</div>
<div style={styles.description}>
{description}
</div>
<div style={styles.flexContainer}>
<div style={styles.box}>
<RaisedButton
label={labelButtonLeft}
primary={true}
onTouchTap={handleClickLeftButton}
icon={leftIconType}
/>
</div>
<div style={styles.box}>
<RaisedButton
label={labelButtonRight}
primary={true}
onTouchTap={handleClickRightButton}
icon={rightIconType}
/>
</div>
</div>
</div>
</div>
);
};
export default EmptyViewDouble;
|
src/components/exercises/LetterRotated.stories.js | cognostics/serlo-abc | import React from 'react';
import { storiesOf } from '@storybook/react-native';
import LetterRotated from './LetterRotated';
storiesOf('exercises/LetterRotated', module)
.add('difficulty level 1', () => (
<LetterRotated
letters={['a', 'N', 'E']}
rotated={[4]}
angles={['50deg']}
difficulty={0.1}
/>
))
.add('difficulty level 2', () => (
<LetterRotated
letters={['a', 'N', 'E', 's', 'T']}
rotated={[4]}
angles={['50deg']}
difficulty={0.3}
/>
))
.add('difficulty level 3', () => (
<LetterRotated
letters={['a', 'N', 'E', 's', 'T']}
rotated={[3, 4]}
angles={['50deg', '-30deg']}
difficulty={0.5}
/>
));
|
src/ModalBody.js | PeterDaveHello/react-bootstrap | import React from 'react';
import classnames from 'classnames';
class ModalBody extends React.Component {
render() {
return (
<div {...this.props} className={classnames(this.props.className, this.props.modalClassName)}>
{this.props.children}
</div>
);
}
}
ModalBody.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string
};
ModalBody.defaultProps = {
modalClassName: 'modal-body'
};
export default ModalBody;
|
src/EmptyRadar.js | shauns/react-d3-radar | // @flow
import React from 'react';
import RadarAxis from './RadarAxis';
import RadarRings from './RadarRings';
import type {RadarVariable} from './types';
import {radiusScales, forEachArray} from './utils';
type Props = {
width: number,
height: number,
padding: number,
variables: Array<RadarVariable>,
domainMax: number,
style?: {},
};
const defaultRadarStyle = {
numRings: 4,
axisColor: '#cdcdcd',
ringColor: '#cdcdcd',
};
export default function EmptyRadar(props: Props) {
const {width, height, padding, variables, domainMax, style} = props;
const {axisColor, ringColor, numRings} = {...defaultRadarStyle, ...style};
const innerHeight = height - padding * 2;
const innerWidth = width - padding * 2;
const radius = Math.min(innerWidth / 2, innerHeight / 2);
const diameter = radius * 2;
const scales = radiusScales(variables, domainMax, radius);
const angleSliceRadians = Math.PI * 2 / variables.length;
const offsetAngles = {};
forEachArray(variables, ({key}, i) => {
offsetAngles[key] = angleSliceRadians * i;
});
const backgroundScale = scales[variables[0].key];
const ticks = backgroundScale.ticks(numRings).slice(1);
const tickFormat = backgroundScale.tickFormat(numRings);
return (
<svg width={width} height={height}>
<g transform={`translate(${padding}, ${padding})`}>
<rect
width={diameter}
height={diameter}
fill={'transparent'}
transform={
`translate(${(innerWidth - diameter) / 2}, ${(innerHeight -
diameter) /
2})`
}
/>
<g transform={`translate(${innerWidth / 2}, ${innerHeight / 2})`}>
<RadarRings
ticks={ticks}
scale={backgroundScale}
color={ringColor}
format={tickFormat}
/>
{variables.map(({key, label}) => {
return (
<RadarAxis
key={key}
scale={scales[key]}
offsetAngle={offsetAngles[key]}
label={label}
domainMax={domainMax}
color={axisColor}
/>
);
})}
</g>
</g>
</svg>
);
}
|
src/views/Blocks/Clock.js | abachman/my-new-tab | import React from 'react'
import PropTypes from 'prop-types'
import { GridBlockWrapper } from './Base'
import formatDate from '../../lib/formatDate'
import '../../stylesheets/Clock.css'
class Clock extends React.Component {
static propTypes = {
block: PropTypes.object.isRequired
}
state = {
time: new Date()
}
componentDidMount() {
this._tick = setInterval(() => {
this.setState({time: new Date()})
}, 2000)
}
componentWillUnmount() {
if (this._tick)
clearInterval(this._tick)
}
formattedTime() {
const { size, block } = this.props
const { fontFamily } = block
const now = this.state.time,
bigFont = {fontSize: Math.floor(size.width / 6) + 'px'},
smallFont = {fontSize: Math.floor(size.width / 14) + 'px'}
return (
<div className='clock-time' style={{fontFamily: fontFamily}}>
<div className='time' style={bigFont}>{formatDate(now, 'h:mm TT')}</div>
<div className='date' style={smallFont}>{formatDate(now, 'dddd, d MMM yyyy')}</div>
</div>
)
}
render() {
return (
<div className='item-container'>
{this.formattedTime()}
</div>
)
}
}
export default GridBlockWrapper(Clock)
|
src/components/common/svg-icons/editor/format-shapes.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatShapes = (props) => (
<SvgIcon {...props}>
<path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z"/>
</SvgIcon>
);
EditorFormatShapes = pure(EditorFormatShapes);
EditorFormatShapes.displayName = 'EditorFormatShapes';
EditorFormatShapes.muiName = 'SvgIcon';
export default EditorFormatShapes;
|
fields/types/date/DateColumn.js | asifiqbal84/keystone | import React from 'react';
import moment from 'moment';
import ItemsTableCell from '../../../admin/src/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/src/components/ItemsTableValue';
var DateColumn = React.createClass({
displayName: 'DateColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
let value = this.props.data.fields[this.props.col.path];
if (!value) return null;
let format = (this.props.col.path === 'dateTime') ? 'MMMM Do YYYY, h:mm:ss a' : 'MMMM Do YYYY';
let formattedValue = moment(value).format(format);
return (
<ItemsTableValue title={formattedValue} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
}
});
module.exports = DateColumn;
|
examples/huge-apps/routes/Grades/components/Grades.js | nhunzaker/react-router | import React from 'react'
class Grades extends React.Component {
render() {
return (
<div>
<h2>Grades</h2>
</div>
)
}
}
export default Grades
|
app/containers/App/index.js | nguyenduong127/kong-dashboard | /**
*
* App
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*/
import React from 'react';
import Helmet from 'react-helmet';
import styled from 'styled-components';
import Header from 'components/Header';
import Footer from 'components/Footer';
import withProgressBar from 'components/ProgressBar';
const AppWrapper = styled.div`
min-height: 100%;
`;
export function App(props) {
return (
<AppWrapper>
<Helmet
titleTemplate="%s - Kong Dashboard"
defaultTitle="Kong Dashboard"
meta={[
{ name: 'description', content: 'A Kong Dashboard application' },
]}
/>
<Header />
{React.Children.toArray(props.children)}
<Footer />
</AppWrapper>
);
}
App.propTypes = {
children: React.PropTypes.node,
};
export default withProgressBar(App);
|
js/components/blankPage/index.js | laurar07/onMy6 |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Text, Button, Icon } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import { popRoute } from '../../actions/route';
import styles from './styles';
class BlankPage extends Component {
static propTypes = {
popRoute: React.PropTypes.func,
openDrawer: React.PropTypes.func,
name: React.PropTypes.string,
index: React.PropTypes.number,
list: React.PropTypes.arrayOf(React.PropTypes.string),
}
popRoute() {
this.props.popRoute();
}
render() {
const { props: { name, index, list } } = this;
return (
<Container style={styles.container}>
<Header>
<Button transparent onPress={() => this.popRoute()}>
<Icon name="ios-arrow-back" />
</Button>
<Title>{(name) ? this.props.name : 'Blank Page'}</Title>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="ios-menu" />
</Button>
</Header>
<Content padder>
<Text>
{(!isNaN(index)) ? list[index] : 'Create Something Awesome . . .'}
</Text>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: () => dispatch(popRoute()),
};
}
function mapStateToProps(state) {
return {
name: state.user.name,
index: state.list.selectedIndex,
list: state.list.list,
};
}
export default connect(mapStateToProps, bindAction)(BlankPage);
|
src/entypo/Foursquare.js | cox-auto-kc/react-entypo | import React from 'react';
import EntypoIcon from '../EntypoIcon';
const iconClass = 'entypo-svgicon entypo--Foursquare';
let EntypoFoursquare = (props) => (
<EntypoIcon propClass={iconClass} {...props}>
<path d="M4.92,1C4.412,1,4,1.412,4,1.92v16.516c0,0.625,0.765,0.926,1.192,0.47l4.471-4.79C9.731,14.042,9.826,14,9.927,14h3.237c0.486,0,0.905-0.343,1.001-0.82l2.111-10.514C16.449,1.804,15.79,1,14.911,1H4.92z M8.838,12.19L6,15.527V3.343C6,3.154,6.154,3,6.343,3h7.14c0.342,0,0.598,0.313,0.53,0.648l-0.413,2.055C13.566,5.876,13.414,6,13.238,6h-3.71C9.236,6,9,6.236,9,6.528v1.22C9,7.887,9.113,8,9.253,8h3.294c0.306,0,0.536,0.28,0.476,0.581l-0.614,3.058C12.366,11.849,12.181,12,11.967,12H9.25C9.091,12,8.941,12.069,8.838,12.19z"/>
</EntypoIcon>
);
export default EntypoFoursquare;
|
src/components/Notification/Notification.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import Close16 from '@carbon/icons-react/lib/close/16';
import ErrorFilled20 from '@carbon/icons-react/lib/error--filled/20';
import CheckmarkFilled20 from '@carbon/icons-react/lib/checkmark--filled/20';
import WarningFilled20 from '@carbon/icons-react/lib/warning--filled/20';
const { prefix } = settings;
export class NotificationButton extends Component {
static propTypes = {
/**
* Specify an optional className to be applied to the notification button
*/
className: PropTypes.string,
/**
* Specify a label to be read by screen readers on the notification button
*/
ariaLabel: PropTypes.string,
/**
* Optional prop to specify the type of the Button
*/
type: PropTypes.string,
/**
* Provide a description for "close" icon that can be read by screen readers
*/
iconDescription: PropTypes.string,
/**
* Optional prop to allow overriding the icon rendering.
* Can be a React component class
*/
renderIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* Specify an optional icon for the Button through a string,
* if something but regular "close" icon is desirable
*/
name: PropTypes.string,
/**
* Specify the notification type
*/
notificationType: PropTypes.oneOf(['toast', 'inline']),
};
static defaultProps = {
ariaLabel: 'close notification', // TODO: deprecate this prop
notificationType: 'toast',
type: 'button',
iconDescription: 'close icon',
renderIcon: Close16,
};
render() {
const {
ariaLabel,
className,
iconDescription,
type,
renderIcon: IconTag,
name,
notificationType,
...other
} = this.props;
const buttonClasses = classNames(
{
[`${prefix}--toast-notification__close-button`]:
notificationType === 'toast',
[`${prefix}--inline-notification__close-button`]:
notificationType === 'inline',
},
className
);
const iconClasses = classNames({
[`${prefix}--toast-notification__close-icon`]:
notificationType === 'toast',
[`${prefix}--inline-notification__close-icon`]:
notificationType === 'inline',
});
const NotificationButtonIcon = (() => {
if (Object(IconTag) === IconTag) {
return (
<IconTag aria-label={ariaLabel} className={iconClasses} name={name} />
);
}
return null;
})();
return (
<button
{...other}
type={type}
aria-label={iconDescription}
title={iconDescription}
className={buttonClasses}>
{NotificationButtonIcon}
</button>
);
}
}
export class NotificationTextDetails extends Component {
static propTypes = {
/**
* Pass in the children that will be rendered in NotificationTextDetails
*/
children: PropTypes.node,
/**
* Specify the title
*/
title: PropTypes.string,
/**
* Specify the sub-title
*/
subtitle: PropTypes.node,
/**
* Specify the caption
*/
caption: PropTypes.node,
/**
* Specify the notification type
*/
notificationType: PropTypes.oneOf(['toast', 'inline']),
};
static defaultProps = {
title: 'title',
subtitle: 'subtitle',
caption: 'caption',
notificationType: 'toast',
};
render() {
const { title, subtitle, caption, notificationType, ...other } = this.props;
if (notificationType === 'toast') {
return (
<div {...other} className={`${prefix}--toast-notification__details`}>
<h3 className={`${prefix}--toast-notification__title`}>{title}</h3>
<div className={`${prefix}--toast-notification__subtitle`}>
{subtitle}
</div>
<div className={`${prefix}--toast-notification__caption`}>
{caption}
</div>
{this.props.children}
</div>
);
}
if (notificationType === 'inline') {
return (
<div
{...other}
className={`${prefix}--inline-notification__text-wrapper`}>
<p className={`${prefix}--inline-notification__title`}>{title}</p>
<div className={`${prefix}--inline-notification__subtitle`}>
{subtitle}
</div>
{this.props.children}
</div>
);
}
}
}
const useIcon = kindProp =>
({
error: ErrorFilled20,
success: CheckmarkFilled20,
warning: WarningFilled20,
}[kindProp]);
const NotificationIcon = ({ notificationType, kind, iconDescription }) => {
const NotificationIconX = useIcon(kind);
return !NotificationIconX ? null : (
<NotificationIconX
className={`${prefix}--${notificationType}-notification__icon`}>
<title>{iconDescription}</title>
</NotificationIconX>
);
};
export class ToastNotification extends Component {
static propTypes = {
/**
* Pass in the children that will be rendered within the ToastNotification
*/
children: PropTypes.node,
/**
* Specify an optional className to be applied to the notification box
*/
className: PropTypes.string,
/**
* Specify what state the notification represents
*/
kind: PropTypes.oneOf(['error', 'info', 'success', 'warning']).isRequired,
/**
* Specify the title
*/
title: PropTypes.string.isRequired,
/**
* Specify the sub-title
*/
subtitle: PropTypes.node.isRequired,
/**
* By default, this value is "alert". You can also provide an alternate
* role if it makes sense from the accessibility-side
*/
role: PropTypes.string.isRequired,
/**
* Specify the caption
*/
caption: PropTypes.node,
/**
* Provide a function that is called when menu is closed
*/
onCloseButtonClick: PropTypes.func,
/**
* Provide a description for "close" icon that can be read by screen readers
*/
iconDescription: PropTypes.string.isRequired,
/**
* By default, this value is "toast". You can also provide an alternate type
* if it makes sense for the underlying `<NotificationTextDetails>` and `<NotificationButton>`
*/
notificationType: PropTypes.string,
/**
* Specify the close button should be disabled, or not
*/
hideCloseButton: PropTypes.bool,
/**
* Specify an optional duration the notification should be closed in
*/
timeout: PropTypes.number,
};
static defaultProps = {
kind: 'error',
title: 'provide a title',
subtitle: 'provide a subtitle',
caption: 'provide a caption',
role: 'alert',
notificationType: 'toast',
iconDescription: 'closes notification',
onCloseButtonClick: () => {},
hideCloseButton: false,
timeout: 0,
};
state = {
open: true,
};
componentDidMount() {
if (this.props.timeout) {
setTimeout(() => {
this.handleCloseButtonClick();
}, this.props.timeout);
}
}
handleCloseButtonClick = evt => {
this.setState({ open: false });
this.props.onCloseButtonClick(evt);
};
render() {
if (!this.state.open) {
return null;
}
const {
role,
notificationType,
onCloseButtonClick, // eslint-disable-line
iconDescription, // eslint-disable-line
className,
caption,
subtitle,
title,
kind,
hideCloseButton,
...other
} = this.props;
const classes = classNames(
`${prefix}--toast-notification`,
{
[`${prefix}--toast-notification--${this.props.kind}`]: this.props.kind,
},
className
);
return (
<div {...other} role={role} kind={kind} className={classes}>
<NotificationIcon
notificationType={notificationType}
kind={kind}
iconDescription={iconDescription}
/>
<NotificationTextDetails
title={title}
subtitle={subtitle}
caption={caption}
notificationType={notificationType}>
{this.props.children}
</NotificationTextDetails>
{!hideCloseButton && (
<NotificationButton
iconDescription={iconDescription}
notificationType={notificationType}
onClick={this.handleCloseButtonClick}
/>
)}
</div>
);
}
}
export class InlineNotification extends Component {
static propTypes = {
/**
* Pass in the children that will be rendered within the InlineNotification
*/
children: PropTypes.node,
/**
* Specify an optional className to be applied to the notification box
*/
className: PropTypes.string,
/**
* Specify what state the notification represents
*/
kind: PropTypes.oneOf(['error', 'info', 'success', 'warning']).isRequired,
/**
* Specify the title
*/
title: PropTypes.string.isRequired,
/**
* Specify the sub-title
*/
subtitle: PropTypes.node.isRequired,
/**
* By default, this value is "alert". You can also provide an alternate
* role if it makes sense from the accessibility-side
*/
role: PropTypes.string.isRequired,
/**
* Provide a function that is called when menu is closed
*/
onCloseButtonClick: PropTypes.func,
/**
* Provide a description for "close" icon that can be read by screen readers
*/
iconDescription: PropTypes.string.isRequired,
/**
* By default, this value is "inline". You can also provide an alternate type
* if it makes sense for the underlying `<NotificationTextDetails>` and `<NotificationButton>`
*/
notificationType: PropTypes.string,
/**
* Specify the close button should be disabled, or not
*/
hideCloseButton: PropTypes.bool,
};
static defaultProps = {
role: 'alert',
notificationType: 'inline',
iconDescription: 'closes notification',
onCloseButtonClick: () => {},
hideCloseButton: false,
};
state = {
open: true,
};
handleCloseButtonClick = evt => {
this.setState({ open: false });
this.props.onCloseButtonClick(evt);
};
render() {
if (!this.state.open) {
return null;
}
const {
role,
notificationType,
onCloseButtonClick, // eslint-disable-line
iconDescription, // eslint-disable-line
className,
subtitle,
title,
kind,
hideCloseButton,
...other
} = this.props;
const classes = classNames(
`${prefix}--inline-notification`,
{
[`${prefix}--inline-notification--${this.props.kind}`]: this.props.kind,
},
className
);
return (
<div {...other} role={role} kind={kind} className={classes}>
<div className={`${prefix}--inline-notification__details`}>
<NotificationIcon
notificationType={notificationType}
kind={kind}
iconDescription={iconDescription}
/>
<NotificationTextDetails
title={title}
subtitle={subtitle}
notificationType={notificationType}>
{this.props.children}
</NotificationTextDetails>
</div>
{!hideCloseButton && (
<NotificationButton
iconDescription={iconDescription}
notificationType={notificationType}
onClick={this.handleCloseButtonClick}
/>
)}
</div>
);
}
}
|
example/react-todo/index.js | justinjung04/treeful | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Treeful from '../../src/treeful';
import './index.scss';
import TodoController from './components/todo-controller';
import Todo from './components/todo';
class App extends Component {
constructor () {
super();
Treeful.dev();
Treeful.add('todos', []);
this.state = {
todos: Treeful.get('todos')
};
}
componentDidMount() {
this.unsubscribe = Treeful.subscribe('todos', this.updateTodos.bind(this));
}
componentWillUnmount() {
this.unsubscribe();
}
updateTodos(todos) {
this.setState({ todos });
}
render() {
return (
<div className='react'>
<TodoController />
<hr/>
<div className='todos'>
{ this.state.todos.map((item, index) => <Todo data={item} key={index}/>) }
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/app.js | jvstrpv/reactredux_2 | import React, { Component } from 'react';
import SearchBar from '../containers/search_bar';
export default class App extends Component {
render() {
return (
<div>
<SearchBar />
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.