path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
step7-unittest/app/js/components/Main.js | jintoppy/react-training | import React from 'react';
import Profile from './Profile';
import {Link} from 'react-router';
class Main extends React.Component {
constructor(props) {
super(props);
this.state = {
name: "guest"
};
}
render() {
return (
<div className="main-container">
<nav className="navbar navbar-default" role="navigation">
<div className="col-sm-7 col-sm-offset-2" style={{marginTop: 15}}>
<Profile name = { this.state.name } />
<Link to="/">Home</Link>
<Link to="/page1">Page1</Link>
<Link to="/contact">Contact</Link>
</div>
</nav>
<div className="container">
{this.props.children}
</div>
</div>
)
}
}
export default Main;
|
utilities/warning/render-function-return-contents-lack-display-name.js | salesforce/design-system-react | /* Copyright (c) 2015-present, salesforce.com, inc. All rights reserved */
/* Licensed under BSD 3-Clause - see LICENSE.txt or git.io/sfdc-license */
/* eslint-disable import/no-mutable-exports */
import React from 'react';
// This function will deliver an error message to the browser console when all of the props passed in are undefined (falsey).
import warning from 'warning';
let renderFunctionReturnContentsLackDisplayName = function renderFunctionReturnContentsLackDisplayNameFunction() {};
if (process.env.NODE_ENV !== 'production') {
const hasWarned = {};
renderFunctionReturnContentsLackDisplayName = function renderFunctionReturnContentsLackDisplayNameFunction(
control,
propName,
renderFunctionReturnContents,
displayNames, // array of allowed displayName strings
checkChildren, // if true children of the render function return main node will be checked for displayNames matches
comment
) {
const additionalComment = comment ? ` ${comment}` : '';
const displayNamesJoined = displayNames.join(',');
let foundDiscrepancy = false;
if (
!renderFunctionReturnContents.type ||
!renderFunctionReturnContents.type.displayName ||
!displayNamesJoined.match(renderFunctionReturnContents.type.displayName)
) {
if (
checkChildren &&
renderFunctionReturnContents.props &&
renderFunctionReturnContents.props.children
) {
React.Children.forEach(
renderFunctionReturnContents.props.children,
(child) => {
if (
!child ||
!child.type ||
!child.type.displayName ||
!displayNamesJoined.match(child.type.displayName)
) {
foundDiscrepancy = true;
}
}
);
} else {
foundDiscrepancy = true;
}
}
if (foundDiscrepancy && !hasWarned[control]) {
let allowedDisplayNames = '';
displayNames.forEach((displayName, index) => {
allowedDisplayNames += displayName;
if (displayNames.length > index + 2) {
allowedDisplayNames += ', ';
} else if (displayNames.length > index + 1) {
allowedDisplayNames += displayNames.length > 2 ? ', or ' : ' or ';
}
});
/* eslint-disable max-len */
warning(
false,
`[Design System React] Content provided by \`${propName}\` for ${control} must have a \`displayName\` property value of ${allowedDisplayNames}${
checkChildren
? ` or be an element/fragment with children all having the \`displayName\` property value of ${allowedDisplayNames}.`
: '.'
} Please review ${propName} prop documentation.${additionalComment}`
);
/* eslint-enable max-len */
hasWarned[control] = true;
}
};
}
export default renderFunctionReturnContentsLackDisplayName;
|
index.windows.js | jiriKuba/Calculatic | import React from 'react';
import {AppRegistry} from 'react-native';
import Root from './src/root';
AppRegistry.registerComponent('calculatic', () => Root) |
local-cli/templates/HelloWorld/App.js | jevakallio/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
Platform,
StyleSheet,
Text,
View
} from 'react-native';
const instructions = Platform.select({
ios: 'Press Cmd+R to reload,\n' +
'Cmd+D or shake for dev menu',
android: 'Double tap R on your keyboard to reload,\n' +
'Shake or press menu button for dev menu',
});
type Props = {};
export default class App extends Component<Props> {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit App.js
</Text>
<Text style={styles.instructions}>
{instructions}
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
|
src/js/components/page/index.js | Arlefreak/arlefreakClient | import PropTypes from 'prop-types';
import React from 'react';
import { Helmet } from 'react-helmet';
import Loading from '../loading';
import Id from '../id';
const Page = ({
id,
title,
isFetching,
children,
className,
meta_url,
meta_title,
meta_description,
meta_preview,
meta_audio,
}) => {
let child;
if (isFetching) {
child = (
<div>
<Loading />
<Id index={id} />
</div>
);
} else {
child = (
<div className={className}>
{title != null && <h1 className="title-text box shadow">{title}</h1>}
{children}
<Id index={id} />
</div>
);
}
let description = meta_description;
if (meta_description.length > 140)
description = `${description.substring(0, 140)} ...`;
let meta = [
{ property: 'og:title', content: meta_title },
{ name: 'twitter:title', content: meta_title },
{ property: 'og:url', content: meta_url },
{ name: 'twitter:url', content: meta_url },
{ property: 'og:image', content: meta_preview },
{ name: 'twitter:image', content: meta_preview },
{ name: 'description', content: description },
{ property: 'og:description', content: description },
{ name: 'twitter:description', content: description },
];
if (meta_audio) meta.push({ property: 'og:audio', content: meta_audio });
return (
<div>
<Helmet title={meta_title} meta={meta} />
{child}
</div>
);
};
Page.propTypes = {
id: PropTypes.string.isRequired,
title: PropTypes.string,
isFetching: PropTypes.bool.isRequired,
children: PropTypes.node.isRequired,
className: PropTypes.string,
meta_description: PropTypes.string.isRequired,
meta_url: PropTypes.string.isRequired,
meta_title: PropTypes.string.isRequired,
meta_preview: PropTypes.string.isRequired,
meta_audio: PropTypes.string,
};
export default Page;
|
src/templates/tags.js | zccz14/blog | import React from 'react'
import PropTypes from 'prop-types'
import { graphql } from 'gatsby'
import SEO from '../components/seo'
import Layout from '../components/layout'
import Post from '../components/post'
import Navigation from '../components/navigation'
import '../styles/layout.css'
const Tags = ({
data,
pageContext: { nextPagePath, previousPagePath, tag },
}) => {
const {
allMarkdownRemark: { edges: posts },
} = data
return (
<>
<SEO />
<Layout>
<div className="infoBanner">
Posts with tag: <span>#{tag}</span>
</div>
{posts.map(({ node }) => {
const {
id,
excerpt: autoExcerpt,
frontmatter: {
title,
date,
path,
author,
coverImage,
excerpt,
tags,
},
} = node
return (
<Post
key={id}
title={title}
date={date}
path={path}
author={author}
tags={tags}
coverImage={coverImage}
excerpt={excerpt || autoExcerpt}
/>
)
})}
<Navigation
previousPath={previousPagePath}
previousLabel="Newer posts"
nextPath={nextPagePath}
nextLabel="Older posts"
/>
</Layout>
</>
)
}
Tags.propTypes = {
data: PropTypes.object.isRequired,
pageContext: PropTypes.shape({
nextPagePath: PropTypes.string,
previousPagePath: PropTypes.string,
}),
}
export const postsQuery = graphql`
query($limit: Int!, $skip: Int!, $tag: String!) {
allMarkdownRemark(
filter: { frontmatter: { tags: { in: [$tag] } } }
sort: { fields: [frontmatter___date], order: DESC }
limit: $limit
skip: $skip
) {
edges {
node {
id
excerpt
frontmatter {
title
date(formatString: "DD MMMM YYYY")
path
author
excerpt
tags
coverImage {
childImageSharp {
fluid(maxWidth: 800) {
...GatsbyImageSharpFluid
}
}
}
}
}
}
}
}
`
export default Tags
|
component/NavLink.js | Lucifier129/react-imvc | import React from 'react'
import classnames from 'classnames'
import connect from '../hoc/connect'
import Link from './Link'
const withLocation = connect(({ state }) => {
return {
location: state.location
}
})
export default withLocation(NavLink)
function NavLink({
isActive: getIsActive,
location,
className,
activeClassName,
style,
activeStyle,
to,
...rest
}) {
let isActive = checkActive(getIsActive, to, location)
let finalClassName = classnames(className, isActive && activeClassName)
let finalStyle = isActive ? { ...style, ...activeStyle } : style
return <Link to={to} className={finalClassName} style={finalStyle} {...rest} />
}
function checkActive(getIsActive, path, location) {
return getIsActive
? !!getIsActive(path, location)
: path === location.raw
}
|
webapp/src/components/ActionMenu.js | gcallah/Indra | import React, { Component } from 'react';
import ListGroup from 'react-bootstrap/ListGroup';
import axios from 'axios';
import autoBind from 'react-autobind';
import PageLoader from './PageLoader';
import PopulationGraph from './PopulationGraph';
import ScatterPlot from './ScatterPlot';
import Debugger from './Debugger';
import ModelStatusBox from './ModelStatusBox';
import SourceCodeViewer from './SourceCodeViewer';
import RunModelButton from './RunModelButton';
import './styles.css';
import config from '../config';
import LogsViewer from './LogsViewer';
const POP = 2;
const SCATTER = 3;
const DATA = 4;
const SOURCE = 5;
const LOG = 6;
const API_SERVER = `${config.API_URL}models/menu/`;
class ActionMenu extends Component {
constructor(props) {
super(props);
autoBind(this);
this.state = {
menu: {},
loadingData: true,
envFile: {},
source: '',
periodNum: 10,
errorMessage: '',
disabledButton: false,
loadingSourceCode: false,
loadingDebugger: false,
loadingPopulation: false,
loadingScatter: false,
loadingLogs: false,
activeDisplay: null,
};
}
async componentDidMount() {
try {
document.title = 'Indra | Menu';
const m = await axios.get(API_SERVER);
this.setState({
menu: m.data,
name: localStorage.getItem('name'),
source: localStorage.getItem('source'),
envFile: JSON.parse(localStorage.getItem('envFile')),
msg: JSON.parse(localStorage.getItem('envFile')).user.user_msgs,
loadingData: false,
});
} catch (error) {
return false;
}
const defaultGraph = localStorage.getItem('graph');
if (defaultGraph === 'scatter') {
this.setState({
loadingScatter: true,
activeDisplay: SCATTER,
});
} else {
this.setState({
loadingPopulation: true,
activeDisplay: POP,
});
}
try {
const code = await this.viewSource();
this.setState({
sourceCode: code,
});
} catch (error) {
return false;
}
return true;
}
viewSource = async () => {
try {
const { source } = this.state;
const splitSource = source.split('/');
const filename = splitSource[splitSource.length - 1];
const res = await axios.get(
`https://raw.githubusercontent.com/gcallah/indras_net/master/models/${filename}`,
);
return res.data;
} catch (error) {
return 'Something has gone wrong.';
}
};
handleRunPeriod = (e) => {
this.setState({
periodNum: e.target.value,
});
const valid = this.checkValidity(e.target.value);
if (valid === 0) {
this.setState({
errorMessage: '**Please input an integer',
disabledButton: true,
});
} else {
this.setState({
errorMessage: '',
disabledButton: false,
});
}
};
checkValidity = (data) => {
if (data % 1 === 0) {
return 1;
}
return 0;
};
handleClick = (e) => {
this.setState({
loadingData: false,
loadingSourceCode: false,
loadingDebugger: false,
loadingScatter: false,
loadingPopulation: false,
loadingLogs: false,
});
this.setState({
activeDisplay: e,
});
switch (e) {
case POP:
this.setState({ loadingPopulation: true });
break;
case SCATTER:
this.setState({ loadingScatter: true });
break;
case DATA:
this.setState({ loadingDebugger: true });
break;
case SOURCE:
this.setState({ loadingSourceCode: true });
break;
case LOG:
this.setState({ loadingLogs: true });
break;
default:
break;
}
};
sendNumPeriods = async () => {
const { periodNum, envFile } = this.state;
this.setState({ loadingData: true });
try {
const res = await axios.put(
`${API_SERVER}run/${String(periodNum)}`,
envFile,
periodNum,
);
this.setState({
envFile: res.data,
loadingData: false,
msg: res.data.user.user_msgs,
});
return true;
} catch (e) {
return false;
}
};
renderHeader = () => {
const { name } = this.state;
return <h1 className="header">{name}</h1>;
};
MenuItem = (i, action, text, key) => {
/**
* All models will have all the menu items appear on the page.
* However, we keep one of the graphs (Population graph or Scatter plot)
* disabled based on "graph" field from models.json
*/
const defaultGraph = localStorage.getItem('graph');
const { activeDisplay } = this.state;
return (
<ListGroup.Item
className="w-50 p-3 list-group-item list-group-item-action"
as="li"
active={activeDisplay === action}
disabled={
(action === SCATTER && defaultGraph === 'line')
|| (action === POP && defaultGraph === 'scatter')
}
key={key}
onClick={() => this.handleClick(action)}
>
{text}
</ListGroup.Item>
);
};
renderMenuItem = () => {
const {
envFile,
loadingDebugger,
loadingSourceCode,
sourceCode,
loadingPopulation,
loadingScatter,
loadingLogs,
} = this.state;
return (
<div className="mt-5">
<Debugger loadingData={loadingDebugger} envFile={envFile} />
<SourceCodeViewer loadingData={loadingSourceCode} code={sourceCode} />
<PopulationGraph loadingData={loadingPopulation} envFile={envFile} />
<ScatterPlot loadingData={loadingScatter} envFile={envFile} />
<LogsViewer loadingData={loadingLogs} envFile={envFile} />
</div>
);
};
renderMapItem = () => {
const { menu } = this.state;
return (
<div className="row margin-bottom-80">
<div className="col w-25">
<ListGroup>
{Object.keys(menu).map((item, i) => (menu[item].id > 1
? this.MenuItem(
i,
menu[item].id,
menu[item].question,
menu[item].func,
)
: null))}
</ListGroup>
</div>
</div>
);
};
render() {
const {
loadingData, msg, disabledButton, errorMessage,
} = this.state;
if (loadingData) {
return <PageLoader />;
}
return (
<div>
{this.renderHeader()}
<div>
<ModelStatusBox
title="Model Status"
msg={msg}
ref={this.modelStatusBoxElement}
/>
</div>
<ul className="list-group">
<div className="row">
<div>
<RunModelButton
disabledButton={disabledButton}
errorMessage={errorMessage}
sendNumPeriods={this.sendNumPeriods}
handleRunPeriod={this.handleRunPeriod}
/>
<h3 className="margin-top-50 mb-4">Model Analysis:</h3>
</div>
</div>
{this.renderMapItem()}
</ul>
{this.renderMenuItem()}
</div>
);
}
}
ActionMenu.propTypes = {};
ActionMenu.defaultProps = {
history: {},
};
export default ActionMenu;
|
src/components/MainPage/MainPage.js | ggdiam/storia | import React, { Component } from 'react';
import styles from './MainPage.css';
import withStyles from '../../decorators/withStyles';
import Link from '../Link';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
import dataClient from '../../core/DataClient';
import cachedDataClient from '../../core/CachedDataClient';
import apiUrls from '../../constants/ApiUrls';
import localStorageHelper from '../../core/LocalStorageHelper';
import delayedLikeClient from '../../core/DelayedLikeClient';
import MomentsList from '../MomentsList';
import FilterType from '../../constants/FilterType';
@withStyles(styles) class MainPage extends Component {
constructor(props) {
super(props);
this.loadMoreInProgress = false;
this.loadedPages = 0;
var filteredData = null;
var data = props && props.data ? props.data : null;
var filterType = this.loadFilterState();
if (data) {
this.loadedPages = 1;
//фильтруем данные
filteredData = this.filterData(data, filterType);
}
//if (canUseDOM) {
// console.log('MainPage ctor', data, filteredData, filterType);
//}
//начальное состояние
this.state = {
data: data,
filteredData: filteredData,
filterType: filterType
};
//колбек на перезагрузку данных
//не очень красиво, пока не придумал куда перенести
delayedLikeClient.setReloadDataCallback(this.reloadData.bind(this));
}
//нужно перезагрузить данные после лайка / unlike, чтобы синхронизировать состояние
reloadData() {
console.log('MainPage data reloading...');
if (this.loadedPages <= 1) {
this.getFeedContent();
}
else {
var maxPages = this.loadedPages;
var curPage = 0;
function res(data) {
curPage += 1;
if (curPage < maxPages) {
console.log('loadNextPage data loaded, curPage', curPage, 'loading more...');
this.loadNextPage(data).then(res.bind(this));
}
else {
//фильтруем данные
var filteredData = this.filterData(data, this.state.filterType);
//записываем в стейт
this.setState({
data: data,
filteredData: filteredData
});
console.log('loadNextPage data loaded, curPage', curPage, 'reload finished');
}
}
this.loadNextPage(null, null, true).then(res.bind(this))
}
}
//загружает данные следующей страницы
loadNextPage(currentData, minId, first) {
return new Promise((resolve, reject) => {
var url = '';
if (first) {
url = apiUrls.FeedContent;
}
else {
var min = minId ? minId : currentData.minId;
url = `${apiUrls.FeedContent}?limit=20&until=${currentData.minId}`;
}
//получаем ленту
cachedDataClient.get(url).then((data) => {
if (currentData) {
//мерджим данные item'ов с уже имеющимися
data.items = currentData.items.concat(data.items);
}
currentData = data;
//обновляем кэш
cachedDataClient.saveDataForRequest(apiUrls.FeedContent, null, currentData);
resolve(currentData);
}).catch((err) => {
console.error('loadNextPage err', err);
reject(err);
})
})
}
//загрузить следующие страницы
loadMore() {
console.log('loadMore click');
if (this.state.data && !this.loadMoreInProgress) {
this.loadMoreInProgress = true;
this.loadNextPage(this.state.data).then((data) => {
this.loadedPages += 1;
console.log('loadMore, loadedPages', this.loadedPages);
//фильтруем данные
var filteredData = this.filterData(data, this.state.filterType);
//записываем в стейт
this.setState({
data: data,
filteredData: filteredData
});
this.loadMoreInProgress = false;
}).catch((err) => {
console.log('load more err', err);
})
}
}
componentDidMount() {
var data = this.state.data;
if (!data) {
//получаем данные
this.getFeedContent();
}
}
loadFilterState() {
if (canUseDOM) {
//если в браузере - получаем фильтр
var filter = localStorageHelper.getItem('filter');
if (filter) {
return filter;
}
}
//по-умолчанию - выводим все
return FilterType.All;
}
setFilter(filterType) {
//сохраняем фильтр в localStorage
localStorageHelper.setItem('filter', filterType);
var data = this.state.data ? this.state.data : null;
//фильтруем данные
var filteredData = this.filterData(data, filterType);
//записываем в стейт
this.setState({
filterType: filterType,
filteredData: filteredData
})
}
//Фильтрует список моментов согласно фильтру
filterData(data, filterType) {
//deep copy
var filteredData = JSON.parse(JSON.stringify(data));
var items = filteredData.items;
//console.log('filterData before count:', items.length);
if (filterType == FilterType.WithPictures) {
//фильтруем с каритнками
filteredData.items = items.filter((item, ix)=> {
return item.objectPreview.attachments.length > 0;
});
}
else if (filterType == FilterType.WithOutPictures) {
//фильтруем без каритнок
filteredData.items = items.filter((item, ix)=> {
return item.objectPreview.attachments.length == 0;
});
}
//console.log('filterData after count:', filteredData.items.length);
return filteredData;
}
//Получает данные
getFeedContent() {
//получаем ленту
cachedDataClient.get(apiUrls.FeedContent).then((data) => {
//console.log(data);
//ToDo: debug
//data.items[1].objectPreview.attachments = [
// {file: {title: 'my_fav_img.png'}},
// {file: {title: 'my_fav_img_two.png'}},
// {file: {title: 'my_fav_img_3.png'}}
//];
//фильтруем данные
var filteredData = this.filterData(data, this.state.filterType);
//записываем в стейт
this.setState({
data: data,
filteredData: filteredData
})
}).catch((err) => {
console.error('getFeedContent err', err);
})
}
renderFilter() {
var data = this.state ? this.state.data : null;
var filterType = this.state.filterType;
var defaultClassName = "btn btn-default";
var activeClassName = "btn btn-default active";
if (data) {
return (
<div className="MainPage-toolbar btn-toolbar" role="toolbar">
<div className="btn-group">
<button title="Все моменты" type="button"
onClick={(e)=>this.setFilter(FilterType.All)}
className={filterType == FilterType.All ? activeClassName : defaultClassName}>
<span className="glyphicon glyphicon-asterisk"></span>
</button>
<button title="Моменты с картинками" type="button"
onClick={(e)=>this.setFilter(FilterType.WithPictures)}
className={filterType == FilterType.WithPictures ? activeClassName : defaultClassName}>
<span className="glyphicon glyphicon-picture"></span>
</button>
<button title="Моменты без картинок" type="button"
onClick={(e)=>this.setFilter(FilterType.WithOutPictures)}
className={filterType == FilterType.WithOutPictures ? activeClassName : defaultClassName}>
<span className="glyphicon glyphicon-th-list"></span>
</button>
</div>
</div>
)
}
return null;
}
render() {
var data = this.state ? this.state.filteredData : null;
if (data) {
var filterType = this.state.filterType;
console.log('render', filterType, 'data items length', data.items.length);
}
if (data) {
//флаг загрузки еще
var loadMoreAvailable = data.moreAvailable;
return (
<div className="MainPage">
<div className="container">
{ this.renderFilter() }
<MomentsList data={data} reloadData={this.reloadData.bind(this)}/>
{
loadMoreAvailable ?
<button onClick={this.loadMore.bind(this)} className="btn btn-default">Load More</button>
: null
}
</div>
</div>
);
}
else {
return (
<div className="MainPage">
<div className="container">
<br />
<br />
Loading...
<br />
<br />
</div>
</div>
)
}
}
}
export default MainPage;
|
imports/ui/components/resident-details/accounts/transaction/transaction-mc.js | gagpmr/app-met | import React from 'react';
import * as Styles from '/imports/modules/styles.js';
import { UpdateResident } from '/imports/api/residents/methods.js';
export class TransactionMc extends React.Component {
constructor(props) {
super(props);
}
removeBill(e) {
e.preventDefault();
var resid = e.currentTarget.dataset.resid;
var billId = e.currentTarget.dataset.billid;
var data = {
ResidentId: resid,
DeleteTransactionMcBill: true,
BillId: billId
}
UpdateResident.call({
data: data
}, (error, result) => {
if (error) {
Bert.alert(error, 'danger');
}
});
}
render() {
if (this.props.resident.TxnMcBills) {
return (
<table style={ Styles.TableHeader } className="table table-bordered table-condensed table-striped">
<thead>
<tr>
<td style={ Styles.PaddingThreeCenterBold }>
Sr
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Span
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Mess-1
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Mess-2
</td>
<td style={ Styles.PaddingThreeCenterBold }>
M-Fine
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Canteen
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Can-Fine
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Amenity
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Total
</td>
<td style={ Styles.PaddingThreeCenterBold }>
Actions
</td>
</tr>
</thead>
<tbody>
{ this.props.resident.TxnMcBills.map((doc) => <tr key={ doc._id }>
<td style={ Styles.PaddingThreeCenter }>
{ doc.SrNo }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.Month }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.MessOne }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.MessTwo }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.MessFine }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.Canteen }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.CanteenFine }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.Amenity }
</td>
<td style={ Styles.PaddingThreeCenter }>
{ doc.Total }
</td>
<td style={ Styles.PaddingThreeCenterBold }>
<a onClick={ this.removeBill } data-resid={ this.props.resident._id } data-billid={ doc._id } data-toggle="tooltip" title="Delete From Transaction" href="">
<i className="fa fa-trash-o" aria-hidden="true"></i>
</a>
</td>
</tr>) }
</tbody>
</table>
);
} else {
return null;
}
}
};
TransactionMc.propTypes = {
resident: React.PropTypes.object
};
|
node_modules/react-bootstrap/es/PagerItem.js | NickingMeSpace/questionnaire | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import SafeAnchor from './SafeAnchor';
import createChainedFunction from './utils/createChainedFunction';
var propTypes = {
disabled: PropTypes.bool,
previous: PropTypes.bool,
next: PropTypes.bool,
onClick: PropTypes.func,
onSelect: PropTypes.func,
eventKey: PropTypes.any
};
var defaultProps = {
disabled: false,
previous: false,
next: false
};
var PagerItem = function (_React$Component) {
_inherits(PagerItem, _React$Component);
function PagerItem(props, context) {
_classCallCheck(this, PagerItem);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleSelect = _this.handleSelect.bind(_this);
return _this;
}
PagerItem.prototype.handleSelect = function handleSelect(e) {
var _props = this.props,
disabled = _props.disabled,
onSelect = _props.onSelect,
eventKey = _props.eventKey;
if (onSelect || disabled) {
e.preventDefault();
}
if (disabled) {
return;
}
if (onSelect) {
onSelect(eventKey, e);
}
};
PagerItem.prototype.render = function render() {
var _props2 = this.props,
disabled = _props2.disabled,
previous = _props2.previous,
next = _props2.next,
onClick = _props2.onClick,
className = _props2.className,
style = _props2.style,
props = _objectWithoutProperties(_props2, ['disabled', 'previous', 'next', 'onClick', 'className', 'style']);
delete props.onSelect;
delete props.eventKey;
return React.createElement(
'li',
{
className: classNames(className, { disabled: disabled, previous: previous, next: next }),
style: style
},
React.createElement(SafeAnchor, _extends({}, props, {
disabled: disabled,
onClick: createChainedFunction(onClick, this.handleSelect)
}))
);
};
return PagerItem;
}(React.Component);
PagerItem.propTypes = propTypes;
PagerItem.defaultProps = defaultProps;
export default PagerItem; |
demo/component/Sankey.js | thoqbk/recharts | import React, { Component } from 'react';
import { Sankey, Tooltip } from 'recharts';
import _ from 'lodash';
import DemoSankeyLink from './DemoSankeyLink';
import DemoSankeyNode from './DemoSankeyNode';
const data0 = {
nodes: [
{ name: 'Agricultural waste' },
{ name: 'Bio-conversion' },
{ name: 'Liquid' },
{ name: 'Losses' },
{ name: 'Solid' },
{ name: 'Gas' },
{ name: 'Biofuel imports' },
{ name: 'Biomass imports' },
{ name: 'Coal imports' },
{ name: 'Coal' },
{ name: 'Coal reserves' },
{ name: 'District heating' },
{ name: 'Industry' },
{ name: 'Heating and cooling - commercial' },
{ name: 'Heating and cooling - homes' },
{ name: 'Electricity grid' },
{ name: 'Over generation / exports' },
{ name: 'H2 conversion' },
{ name: 'Road transport' },
{ name: 'Agriculture' },
{ name: 'Rail transport' },
{ name: 'Lighting & appliances - commercial' },
{ name: 'Lighting & appliances - homes' },
{ name: 'Gas imports' },
{ name: 'Ngas' },
{ name: 'Gas reserves' },
{ name: 'Thermal generation' },
{ name: 'Geothermal' },
{ name: 'H2' },
{ name: 'Hydro' },
{ name: 'International shipping' },
{ name: 'Domestic aviation' },
{ name: 'International aviation' },
{ name: 'National navigation' },
{ name: 'Marine algae' },
{ name: 'Nuclear' },
{ name: 'Oil imports' },
{ name: 'Oil' },
{ name: 'Oil reserves' },
{ name: 'Other waste' },
{ name: 'Pumped heat' },
{ name: 'Solar PV' },
{ name: 'Solar Thermal' },
{ name: 'Solar' },
{ name: 'Tidal' },
{ name: 'UK land based bioenergy' },
{ name: 'Wave' },
{ name: 'Wind' },
],
links: [
{ source: 0, target: 1, value: 124.729 },
{ source: 1, target: 2, value: 0.597 },
{ source: 1, target: 3, value: 26.862 },
{ source: 1, target: 4, value: 280.322 },
{ source: 1, target: 5, value: 81.144 },
{ source: 6, target: 2, value: 35 },
{ source: 7, target: 4, value: 35 },
{ source: 8, target: 9, value: 11.606 },
{ source: 10, target: 9, value: 63.965 },
{ source: 9, target: 4, value: 75.571 },
{ source: 11, target: 12, value: 10.639 },
{ source: 11, target: 13, value: 22.505 },
{ source: 11, target: 14, value: 46.184 },
{ source: 15, target: 16, value: 104.453 },
{ source: 15, target: 14, value: 113.726 },
{ source: 15, target: 17, value: 27.14 },
{ source: 15, target: 12, value: 342.165 },
{ source: 15, target: 18, value: 37.797 },
{ source: 15, target: 19, value: 4.412 },
{ source: 15, target: 13, value: 40.858 },
{ source: 15, target: 3, value: 56.691 },
{ source: 15, target: 20, value: 7.863 },
{ source: 15, target: 21, value: 90.008 },
{ source: 15, target: 22, value: 93.494 },
{ source: 23, target: 24, value: 40.719 },
{ source: 25, target: 24, value: 82.233 },
{ source: 5, target: 13, value: 0.129 },
{ source: 5, target: 3, value: 1.401 },
{ source: 5, target: 26, value: 151.891 },
{ source: 5, target: 19, value: 2.096 },
{ source: 5, target: 12, value: 48.58 },
{ source: 27, target: 15, value: 7.013 },
{ source: 17, target: 28, value: 20.897 },
{ source: 17, target: 3, value: 6.242 },
{ source: 28, target: 18, value: 20.897 },
{ source: 29, target: 15, value: 6.995 },
{ source: 2, target: 12, value: 121.066 },
{ source: 2, target: 30, value: 128.69 },
{ source: 2, target: 18, value: 135.835 },
{ source: 2, target: 31, value: 14.458 },
{ source: 2, target: 32, value: 206.267 },
{ source: 2, target: 19, value: 3.64 },
{ source: 2, target: 33, value: 33.218 },
{ source: 2, target: 20, value: 4.413 },
{ source: 34, target: 1, value: 4.375 },
{ source: 24, target: 5, value: 122.952 },
{ source: 35, target: 26, value: 839.978 },
{ source: 36, target: 37, value: 504.287 },
{ source: 38, target: 37, value: 107.703 },
{ source: 37, target: 2, value: 611.99 },
{ source: 39, target: 4, value: 56.587 },
{ source: 39, target: 1, value: 77.81 },
{ source: 40, target: 14, value: 193.026 },
{ source: 40, target: 13, value: 70.672 },
{ source: 41, target: 15, value: 59.901 },
{ source: 42, target: 14, value: 19.263 },
{ source: 43, target: 42, value: 19.263 },
{ source: 43, target: 41, value: 59.901 },
{ source: 4, target: 19, value: 0.882 },
{ source: 4, target: 26, value: 400.12 },
{ source: 4, target: 12, value: 46.477 },
{ source: 26, target: 15, value: 525.531 },
{ source: 26, target: 3, value: 787.129 },
{ source: 26, target: 11, value: 79.329 },
{ source: 44, target: 15, value: 9.452 },
{ source: 45, target: 1, value: 182.01 },
{ source: 46, target: 15, value: 19.013 },
{ source: 47, target: 15, value: 289.366 },
],
};
const data1 = {
nodes: [
{ name: 'Visit' },
{ name: 'Direct-Favourite' },
{ name: 'Page-Click' },
{ name: 'Detail-Favourite' },
{ name: 'Lost' },
],
links: [
{ source: 0, target: 1, value: 3728.3 },
{ source: 0, target: 2, value: 354170 },
{ source: 2, target: 3, value: 62429 },
{ source: 2, target: 4, value: 291741 },
],
};
function SankeyDemo() {
return (
<div className="sankey-charts">
<div>
<pre>1. Simple Sankey</pre>
<Sankey width={960} height={500} data={data0}>
<Tooltip />
</Sankey>
</div>
<br />
<div>
<pre>2. Customized Sankey.</pre>
<Sankey
width={960}
height={500}
data={data0}
node={{ fill: '#8a52b6' }}
link={{ stroke: '#77c878' }}
>
{/* <Tooltip /> */}
</Sankey>
</div>
<br />
<div>
<pre>2. Sankey with gradient color, name and value, and use margin to avoid outer-clip.</pre>
<Sankey
width={960} height={500}
margin={{ top: 20, bottom: 20 }}
data={data1}
nodeWidth={10} nodePadding={60}
linkCurvature={0.61}
iterations={64}
link={<DemoSankeyLink />}
node={<DemoSankeyNode containerWidth={960} />}
>
<defs>
<linearGradient id={'linkGradient'}>
<stop offset="0%" stopColor="rgba(0, 136, 254, 0.5)" />
<stop offset="100%" stopColor="rgba(0, 197, 159, 0.3)" />
</linearGradient>
</defs>
</Sankey>
</div>
</div>
);
}
export default SankeyDemo;
|
public/js/entry.js | 2cats/webserial | import React from 'react'
import Root from './Root'
import ReactDOM from 'react-dom'
ReactDOM.render(
<Root/>,document.getElementById('root')
); |
docs/src/app/components/pages/components/List/ExampleSimple.js | pomerantsev/material-ui | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import ContentInbox from 'material-ui/svg-icons/content/inbox';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import ContentSend from 'material-ui/svg-icons/content/send';
import ContentDrafts from 'material-ui/svg-icons/content/drafts';
import Divider from 'material-ui/Divider';
import ActionInfo from 'material-ui/svg-icons/action/info';
const ListExampleSimple = () => (
<MobileTearSheet>
<List>
<ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
<ListItem primaryText="Starred" leftIcon={<ActionGrade />} />
<ListItem primaryText="Sent mail" leftIcon={<ContentSend />} />
<ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} />
<ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
</List>
<Divider />
<List>
<ListItem primaryText="All mail" rightIcon={<ActionInfo />} />
<ListItem primaryText="Trash" rightIcon={<ActionInfo />} />
<ListItem primaryText="Spam" rightIcon={<ActionInfo />} />
<ListItem primaryText="Follow up" rightIcon={<ActionInfo />} />
</List>
</MobileTearSheet>
);
export default ListExampleSimple;
|
app/server/index.js | ShandyClub/shandy-club | import 'regenerator-runtime/runtime'
import express from 'express'
import path from 'path'
import httpProxy from 'http-proxy'
import bodyParser from 'body-parser'
import compression from 'compression'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { match, RouterContext } from 'react-router'
import configureStore from '../universal/shared/store/configureStore'
import rootSaga from '../universal/shared/sagas'
import routes from '../universal/routes'
import ApiRoutes from './routes'
import './database'
// critical CSS - temp fix for https://github.com/styled-components/styled-components/issues/124
import styles from './styles'
// setup express
const app = express()
const PORT = process.env.PORT || 8000
const isApiRoute = path => path.match(/^\/api/)
const isDevelopment = process.env.NODE_ENV === 'development'
// construct static assets path
const staticPath = isDevelopment ? path.join(__dirname, '../../public') : './'
// layout method
// TODO - abstract this template
const renderPage = (html, initialState) => `
<!DOCTYPE html>
<html>
<meta charset="utf-8">
<title>Shandy Club</title>
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1, minimum-scale=1, user-scalable=no" media="(device-height: 568px)" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/10up-sanitize.css/4.1.0/sanitize.min.css">
<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Lato:700|Karla">
<link rel="stylesheet" href="https://fonts.googleapis.com/icon?family=Material+Icons">
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/leaflet.css" />
<link rel="shortcut icon" href="/favicon.png">
${styles}
<div id="Root">${html}</div>
<script>window.__INITIAL_STATE__ = ${initialState}</script>
<script src="/bundle.js"></script>
`
// compress static assets in production
if (!isDevelopment) app.use(compression())
// serve static assets
app.use(express.static(staticPath))
// parser
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))
// API routes
app.use('/api', ApiRoutes)
// development env
if (isDevelopment) {
// proxy non-API requests to webpack-dev-server
const proxy = httpProxy.createProxyServer()
app.all('/*', function (req, res, next) {
if (isApiRoute(req.path)) return next()
proxy.web(req, res, {
target: 'http://localhost:3000'
})
})
}
// send all non-API requests to index.html so browserHistory works
app.use((req, res, next) => {
if (isApiRoute(req.path)) return next()
// create Redux store
const store = configureStore()
match({ routes, location: req.url }, (err, redirect, props) => {
if (err) return res.status(500).send(err.message)
else if (redirect) return res.redirect(redirect.pathname + redirect.search)
else if (props) {
// start sagas
store.runSaga(rootSaga).done.then( () => {
// Render the component to a string
const html = renderToString(
<Provider store={store}>
<RouterContext {...props}/>
</Provider>
)
// Grab the initial state from our Redux store
const initialState = JSON.stringify(store.getState())
// Send the rendered page back to the client
res.send(renderPage(html, initialState))
}).catch( e => res.status(500).send(e.message) )
// terminate sagas
store.close()
}
else return res.status(404).send('Not Found')
})
})
/* eslint-disable no-unused-vars */
// error handling
app.use( (err, req, res, next) => {
console.error(err.stack)
res.status(500).send(err.message)
})
/* eslint-enable no-unused-vars */
const server = app.listen(PORT, () => {
console.log(`🍺 Production server running on port ${server.address().port}`)
})
|
app/components/Sidebar.js | chehitskenniexd/Archiver | import React, { Component } from 'react';
import { Link, hashHistory } from 'react-router';
import { connect } from 'react-redux';
import styles from './Sidebar.css';
import Project_List from './Project_List';
import { fetchUserProjects } from '../reducers/projects_list';
import { logUserOut } from '../reducers/login';
import * as fs from 'fs';
import * as FEActions from '../../utilities/vcfrontend';
import { setCurrentProject } from '../reducers/currentsReducer';
import { clearProjects } from '../reducers/projects_list';
import { clearInvs } from '../reducers/invitations';
import axios from 'axios';
export class Sidebar extends Component {
constructor(props) {
super(props)
this.localLogUserOut = this.localLogUserOut.bind(this);
this.linkToHomeView = this.linkToHomeView.bind(this);
}
componentDidUpdate() {
if (this.props.loginUser.id && !Object.keys(this.props.projects).length) {
this.props.onLoadProjects(this.props.loginUser.id);
}
// Re-set the current project to the updated one (THIS IS NOT THE BEST WAY)
const numCurrentCommits = this.props.currents && this.props.currents.currentProject ? this.props.currents.currentProject.commits.length : 0;
const numProjectCommits = this.props.currents && this.props.currents.currentProject
&& this.props.projects ? this.props.projects.projects
.filter(project => project.id === this.props.currents.currentProject.id)[0].commits.length : 0;
this.props.currents && numCurrentCommits != numProjectCommits &&
axios.get(`http://localhost:3000/api/vcontrol/${this.props.currents.currentProject.id}`)
.then(project => {
const oldProject = project.data[0];
const newProject = Object.assign({}, oldProject, { commits: oldProject.commits.reverse() })
this.props.setCurrentProject(newProject);
});
}
linkToHomeView() {
hashHistory.push('/mainHome');
}
localLogUserOut() {
this.props.logMeOut();
}
linkToHomeView() {
hashHistory.push('/mainHome');
}
localLogUserOut() {
// clear projects state and my invitations state after logout for next user login
if (this.props.projects.id) {
this.props.nullProjects();
this.props.nullInvs();
}
// then log user out
this.props.logMeOut();
}
render() {
return (
<div className={styles.container} >
<div className="row">
<div className="col s12">
<Link>
<span onClick={() => hashHistory.push('/info')}>
<i className="small material-icons icon-light pull-right">info</i>
</span>
</Link>
<br />
<br />
<Link onClick={this.linkToHomeView}>
<div className="welcome-name light-text">Welcome, {this.props.loginUser.first_name}</div>
<i className="material-icons large icon-light">person_pin</i>
</Link>
</div>
<div>
<Link to={'/'}>
<h6 onClick={this.localLogUserOut} className="light-text">Logout</h6>
</Link>
</div>
<div>
<Project_List />
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
return {
loginUser: state.login,
projects: state.projects,
currents: state.currents
}
}
function mapDispatchToProps(dispatch) {
return {
onLoadProjects: function (user) {
dispatch(fetchUserProjects(user));
},
fetchProjects: (userId) => {
dispatch(fetchUserProjects(userId))
},
setCurrentProject: (project) => {
dispatch(setCurrentProject(project));
},
logMeOut: function () {
dispatch(logUserOut());
},
nullProjects: () => {
dispatch(clearProjects());
},
nullInvs: () => {
dispatch(clearInvs());
}
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(Sidebar);
|
src/docs/examples/RegistrationForm/ExampleRegistrationForm.js | dryzhkov/ps-react-dr | import React from 'react';
import RegistrationForm from 'ps-react/RegistrationForm';
/** Registration from with email and password inputs */
export default class ExampleRegistrationForm extends React.Component {
onSubmit = (user) => {
console.log(user);
}
render() {
return <RegistrationForm
confirmationMessage="Success!!!"
onSubmit={this.onSubmit}
minPasswordLength={8}
/>
}
} |
src/routes/UIElement/dropOption/index.js | yunqiangwu/kmadmin | import React from 'react'
import { DropOption } from 'components'
import { Table, Row, Col, Card, message } from 'antd'
const DropOptionPage = () => (<div className="content-inner">
<Row gutter={32}>
<Col lg={8} md={12}>
<Card title="默认">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="样式">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} buttonStyle={{ border: 'solid 1px #eee', width: 60 }} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="事件">
<DropOption
menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]}
buttonStyle={{ border: 'solid 1px #eee', width: 60 }}
onMenuClick={({ key }) => {
switch (key) {
case '1':
message.success('点击了编辑')
break
case '2':
message.success('点击了删除')
break
default:
break
}
}}
/>
</Card>
</Col>
</Row>
<h2 style={{ margin: '16px 0' }}>Props</h2>
<Row>
<Col lg={18} md={24}>
<Table
rowKey={(record, key) => key}
pagination={false}
bordered
scroll={{ x: 800 }}
columns={[
{
title: '参数',
dataIndex: 'props',
},
{
title: '说明',
dataIndex: 'desciption',
},
{
title: '类型',
dataIndex: 'type',
},
{
title: '默认值',
dataIndex: 'default',
},
]}
dataSource={[
{
props: 'menuOptions',
desciption: '下拉操作的选项,格式为[{name:string,key:string}]',
type: 'Array',
default: '必选',
},
{
props: 'onMenuClick',
desciption: '点击 menuitem 调用此函数,参数为 {item, key, keyPath}',
type: 'Function',
default: '-',
},
{
props: 'buttonStyle',
desciption: '按钮的样式',
type: 'Object',
default: '-',
},
{
props: 'dropdownProps',
desciption: '下拉菜单的参数,可参考antd的【Dropdown】组件',
type: 'Object',
default: '-',
},
]}
/>
</Col>
</Row>
</div>)
export default DropOptionPage
|
packages/reactor-kitchensink/src/examples/Tabs/TabBar/TabBar.js | dbuhrman/extjs-reactor | import React, { Component } from 'react';
import { TabBar, Tab, Panel, Container } from '@extjs/ext-react';
export default class TabBarExample extends Component {
state = {
activeTab: "download"
}
render() {
const { activeTab } = this.state;
return (
<Container layout={{ type: 'vbox', align: 'center' }} padding="10">
<Panel ui="instructions" margin="0 0 20 0" shadow >
<div>To acheive the look and feel of tabs without using a <code>TabPanel</code>, you can use <code>TabBar</code> and <code>Tab</code> as standalone components.</div>
</Panel>
<TabBar width="400" shadow onActiveTabChange={this.onTabChange} activeTab={activeTab}>
<Tab itemId="info" title="Info" iconCls="x-fa fa-info-circle" onActivate={this.onActivateTab}/>
<Tab itemId="download" title="Download" iconCls="x-fa fa-download" badgeText="2" onActivate={this.onActivateTab}/>
<Tab itemId="favorites" title="Favorites" iconCls="x-fa fa-star" onActivate={this.onActivateTab}/>
<Tab itemId="bookmarks" title="Bookmarks" iconCls="x-fa fa-bookmark" onActivate={this.onActivateTab}/>
</TabBar>
<Panel ui="instructions" margin="20 0 0 0" shadow >
<div>Active Tab: {activeTab}</div>
</Panel>
</Container>
)
}
onTabChange = (bar, tab) => {
this.setState({ activeTab: tab.getItemId() })
}
} |
Libraries/Modal/Modal.js | formatlos/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Modal
* @flow
*/
'use strict';
const AppContainer = require('AppContainer');
const I18nManager = require('I18nManager');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const StyleSheet = require('StyleSheet');
const View = require('View');
const deprecatedPropType = require('deprecatedPropType');
const requireNativeComponent = require('requireNativeComponent');
const RCTModalHostView = requireNativeComponent('RCTModalHostView', null);
/**
* The Modal component is a simple way to present content above an enclosing view.
*
* _Note: If you need more control over how to present modals over the rest of your app,
* then consider using a top-level Navigator._
*
* ```javascript
* import React, { Component } from 'react';
* import { Modal, Text, TouchableHighlight, View } from 'react-native';
*
* class ModalExample extends Component {
*
* state = {
* modalVisible: false,
* }
*
* setModalVisible(visible) {
* this.setState({modalVisible: visible});
* }
*
* render() {
* return (
* <View style={{marginTop: 22}}>
* <Modal
* animationType="slide"
* transparent={false}
* visible={this.state.modalVisible}
* onRequestClose={() => {alert("Modal has been closed.")}}
* >
* <View style={{marginTop: 22}}>
* <View>
* <Text>Hello World!</Text>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(!this.state.modalVisible)
* }}>
* <Text>Hide Modal</Text>
* </TouchableHighlight>
*
* </View>
* </View>
* </Modal>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(true)
* }}>
* <Text>Show Modal</Text>
* </TouchableHighlight>
*
* </View>
* );
* }
* }
* ```
*/
class Modal extends React.Component {
static propTypes = {
/**
* The `animationType` prop controls how the modal animates.
*
* - `slide` slides in from the bottom
* - `fade` fades into view
* - `none` appears without an animation
*
* Default is set to `none`.
*/
animationType: PropTypes.oneOf(['none', 'slide', 'fade']),
/**
* The `presentationStyle` prop controls how the modal appears (generally on larger devices such as iPad or plus-sized iPhones).
* See https://developer.apple.com/reference/uikit/uimodalpresentationstyle for details.
* @platform ios
*
* - `fullScreen` covers the screen completely
* - `pageSheet` covers portrait-width view centered (only on larger devices)
* - `formSheet` covers narrow-width view centered (only on larger devices)
* - `overFullScreen` covers the screen completely, but allows transparency
*
* Default is set to `overFullScreen` or `fullScreen` depending on `transparent` property.
*/
presentationStyle: PropTypes.oneOf(['fullScreen', 'pageSheet', 'formSheet', 'overFullScreen']),
/**
* The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background.
*/
transparent: PropTypes.bool,
/**
* The `hardwareAccelerated` prop controls whether to force hardware acceleration for the underlying window.
* @platform android
*/
hardwareAccelerated: PropTypes.bool,
/**
* The `visible` prop determines whether your modal is visible.
*/
visible: PropTypes.bool,
/**
* The `onRequestClose` callback is called when the user taps the hardware back button.
* @platform android
*/
onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func,
/**
* The `onShow` prop allows passing a function that will be called once the modal has been shown.
*/
onShow: PropTypes.func,
animated: deprecatedPropType(
PropTypes.bool,
'Use the `animationType` prop instead.'
),
/**
* The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations.
* On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.
* When using `presentationStyle` of `pageSheet` or `formSheet`, this property will be ignored by iOS.
* @platform ios
*/
supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right'])),
/**
* The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed.
* The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation.
* @platform ios
*/
onOrientationChange: PropTypes.func,
};
static defaultProps = {
visible: true,
hardwareAccelerated: false,
};
static contextTypes = {
rootTag: PropTypes.number,
};
constructor(props: Object) {
super(props);
Modal._confirmProps(props);
}
componentWillReceiveProps(nextProps: Object) {
Modal._confirmProps(nextProps);
}
static _confirmProps(props: Object) {
if (props.presentationStyle && props.presentationStyle !== 'overFullScreen' && props.transparent) {
console.warn(`Modal with '${props.presentationStyle}' presentation style and 'transparent' value is not supported.`);
}
}
render(): ?React.Element<any> {
if (this.props.visible === false) {
return null;
}
const containerStyles = {
backgroundColor: this.props.transparent ? 'transparent' : 'white',
};
let animationType = this.props.animationType;
if (!animationType) {
// manually setting default prop here to keep support for the deprecated 'animated' prop
animationType = 'none';
if (this.props.animated) {
animationType = 'slide';
}
}
let presentationStyle = this.props.presentationStyle;
if (!presentationStyle) {
presentationStyle = 'fullScreen';
if (this.props.transparent) {
presentationStyle = 'overFullScreen';
}
}
const innerChildren = __DEV__ ?
( <AppContainer rootTag={this.context.rootTag}>
{this.props.children}
</AppContainer>) :
this.props.children;
return (
<RCTModalHostView
animationType={animationType}
presentationStyle={presentationStyle}
transparent={this.props.transparent}
hardwareAccelerated={this.props.hardwareAccelerated}
onRequestClose={this.props.onRequestClose}
onShow={this.props.onShow}
style={styles.modal}
onStartShouldSetResponder={this._shouldSetResponder}
supportedOrientations={this.props.supportedOrientations}
onOrientationChange={this.props.onOrientationChange}
>
<View style={[styles.container, containerStyles]}>
{innerChildren}
</View>
</RCTModalHostView>
);
}
// We don't want any responder events bubbling out of the modal.
_shouldSetResponder(): boolean {
return true;
}
}
const side = I18nManager.isRTL ? 'right' : 'left';
const styles = StyleSheet.create({
modal: {
position: 'absolute',
},
container: {
position: 'absolute',
[side] : 0,
top: 0,
}
});
module.exports = Modal;
|
src/svg-icons/social/notifications.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialNotifications = (props) => (
<SvgIcon {...props}>
<path d="M12 22c1.1 0 2-.9 2-2h-4c0 1.1.89 2 2 2zm6-6v-5c0-3.07-1.64-5.64-4.5-6.32V4c0-.83-.67-1.5-1.5-1.5s-1.5.67-1.5 1.5v.68C7.63 5.36 6 7.92 6 11v5l-2 2v1h16v-1l-2-2z"/>
</SvgIcon>
);
SocialNotifications = pure(SocialNotifications);
SocialNotifications.displayName = 'SocialNotifications';
export default SocialNotifications;
|
app/app/components/Dashboard/ProgramLogo.js | lycha/masters-thesis | import React from 'react';
class ProgramLogo extends React.Component {
constructor(props) {
super(props);
this.displayName = 'ProgramLogo';
}
render() {
return (
<div className="col-lg-4 col-md-4 col-sm-4 mb">
<div className="darkblue-panel pn">
<div id="profile-program">
<div className="user">
<img className="img-circle" width="200" src="../public/assets/img/gt-logo.png" />
</div>
</div>
</div>
</div>
);
}
}
export default ProgramLogo;
|
src/svg-icons/places/child-friendly.js | tan-jerene/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesChildFriendly = (props) => (
<SvgIcon {...props}>
<path d="M13 2v8h8c0-4.42-3.58-8-8-8zm6.32 13.89C20.37 14.54 21 12.84 21 11H6.44l-.95-2H2v2h2.22s1.89 4.07 2.12 4.42c-1.1.59-1.84 1.75-1.84 3.08C4.5 20.43 6.07 22 8 22c1.76 0 3.22-1.3 3.46-3h2.08c.24 1.7 1.7 3 3.46 3 1.93 0 3.5-1.57 3.5-3.5 0-1.04-.46-1.97-1.18-2.61zM8 20c-.83 0-1.5-.67-1.5-1.5S7.17 17 8 17s1.5.67 1.5 1.5S8.83 20 8 20zm9 0c-.83 0-1.5-.67-1.5-1.5S16.17 17 17 17s1.5.67 1.5 1.5S17.83 20 17 20z"/>
</SvgIcon>
);
PlacesChildFriendly = pure(PlacesChildFriendly);
PlacesChildFriendly.displayName = 'PlacesChildFriendly';
PlacesChildFriendly.muiName = 'SvgIcon';
export default PlacesChildFriendly;
|
dev/test-studio/parts/tools/test-intent-tool.js | sanity-io/sanity | import React from 'react'
import {route, withRouterHOC} from '@sanity/base/router'
export default {
router: route('/:type/:id'),
canHandleIntent(intentName, params) {
return (intentName === 'edit' && params.id) || (intentName === 'create' && params.type)
},
getIntentState(intentName, params) {
return {
type: params.type || '*',
id: params.id,
}
},
title: 'Test intent',
name: 'test-intent',
component: withRouterHOC((props) => (
<div style={{padding: 10}}>
<h2>Test intent precedence</h2>
If you click an intent link (e.g. from search results) while this tool is open, it should be
opened here.
<pre>{JSON.stringify(props.router.state, null, 2)}</pre>
</div>
)),
}
|
components/game-listing/component.js | kalle-manninen/veikkaaja | import React, { Component } from 'react';
import { View, FlatList, Text } from 'react-native';
import PropTypes from 'prop-types';
import { Game } from '../game';
import { styles } from './style';
class GameListing extends Component {
constructor(props) {
super(props);
this.state = {
refresh: this.props.refreshGameListing
};
}
_keyExtractor = (item, index) => item.id;
_renderItem = ({ item }) => {
const homeTeam = item.outcome.home;
const awayTeam = item.outcome.away;
return (<Game
id={item.id}
homeTeam={homeTeam}
awayTeam={awayTeam}
popularity={item.outcome.popularity}
selectResult={(id, result) => {
this.props.selectResult(id, result);
this.setState({ refresh: !this.state.refresh });
}}
selection={item.outcome.selection}
/>);
};
render() {
return (
<View style={styles.gameList}>
<View style={styles.title}>
<Text style={styles.titleText}>Home</Text><Text style={styles.titleText}>1 X 2</Text>
<Text style={styles.titleText}>Away</Text>
</View>
{ this.props.gamesList.length > 0 ?
<FlatList
data={this.props.gamesList[this.props.selectedGamesList].rows}
renderItem={this._renderItem}
keyExtractor={this._keyExtractor}
extraData={this.state.refresh}
/> : null }
</View>
);
}
}
GameListing.propTypes = {
gamesList: PropTypes.array.isRequired,
selectResult: PropTypes.func.isRequired,
selectedGamesList: PropTypes.number,
refreshGameListing: PropTypes.bool
};
GameListing.defaultProps = {
refreshGameListing: false
};
export {
GameListing
};
|
app/components/instagram/HashTagPicsContainer.js | alexko13/block-and-frame | import React from 'react';
import HashTagPic from './HashTagPicComponent';
const HashTagPicsContainer = (props) => {
return (
<div>
<p>
<i className="icon small instagram"></i>Tag your grams for this Spread with {props.hashtag} <i className="icon small arrow circle down"></i>
</p>
{props.hashTagPics.map((pic, index) =>
<HashTagPic
key={index}
id={index}
pic = {pic}
/>
)}
</div>
);
};
export default HashTagPicsContainer;
|
src/components/Link/Link.js | kuao775/mandragora | /**
* 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 history from '../../history';
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
class Link extends React.Component {
static propTypes = {
to: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
onClick: PropTypes.func,
};
static defaultProps = {
onClick: null,
};
handleClick = event => {
if (this.props.onClick) {
this.props.onClick(event);
}
if (isModifiedEvent(event) || !isLeftClickEvent(event)) {
return;
}
if (event.defaultPrevented === true) {
return;
}
event.preventDefault();
history.push(this.props.to);
};
render() {
const { to, children, ...props } = this.props;
return (
<a href={to} {...props} onClick={this.handleClick}>
{children}
</a>
);
}
}
export default Link;
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentSimplifyTypeArgs/__tests__/fixtures/DefaultPropsInferred.js | ylu1317/flow | // @flow
import React from 'react';
class MyComponent extends React.Component<*, Props> {
static defaultProps = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
const expression = () =>
class extends React.Component<*, Props> {
static defaultProps = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
|
app/components/SecondScene.js | ethan605/react-native-zero | /**
* @providesModule ZeroProj.Components.SecondScene
*/
/* eslint-disable no-unused-vars */
import React from 'react';
/* eslint-enable no-unused-vars */
import { StyleSheet, View } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Button from 'react-native-button';
// Utils
import FontUtils from 'app/utils/FontUtils';
export default function SecondScene() {
return (
<View style={styles.container}>
<Button onPress={Actions.pop} style={styles.buttonText}>
Back to FirstScene
</Button>
</View>
);
}
const styles = StyleSheet.create({
container: {
alignItems: 'center',
flex: 1,
justifyContent: 'center',
},
buttonText: FontUtils.build({
color: '#3b5998',
size: 20,
weight: FontUtils.weights.semibold,
}),
});
|
app/components/Toolbar.js | nantaphop/redd | import React from 'react'
import AppBar from 'material-ui/AppBar'
import Toolbar from 'material-ui/Toolbar'
import styled from 'styled-components'
const _AppBar = styled(AppBar)`
margin-bottom: 2px;
`
export default (props) => {
return (
<_AppBar position="static" color="white" elevation={2} square>
<Toolbar>
{props.children}
</Toolbar>
</_AppBar>
)
} |
src/index.js | jiaolongchao/gallery-Picture | import 'core-js/fn/object/assign';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/Main';
// Render the main component into the dom
ReactDOM.render(<App />, document.getElementById('app'));
|
gadget-system-teamwork/src/components/users/LoginForm.js | TeodorDimitrov89/JS-Web-Teamwork-2017 | import React from 'react'
import Input from '../common/forms/Input'
const LoginForm = (props) => (
<div className='container'>
<form>
<div className='error'>{props.error}</div>
<Input
type='email'
name='email'
value={props.user.email}
placeholder='E-mail'
onChange={props.onChange} />
<br />
<Input
type='password'
name='password'
value={props.user.password}
placeholder='Password'
onChange={props.onChange} />
<input className='btn btn-primary' type='submit' value='login' onClick={props.onSave} />
<br />
</form>
</div>
)
export default LoginForm
|
src/CarouselCaption.js | dozoisch/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
const propTypes = {
componentClass: elementType,
};
const defaultProps = {
componentClass: 'div',
};
class CarouselCaption extends React.Component {
render() {
const { componentClass: Component, className, ...props } = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = getClassSet(bsProps);
return (
<Component
{...elementProps}
className={classNames(className, classes)}
/>
);
}
}
CarouselCaption.propTypes = propTypes;
CarouselCaption.defaultProps = defaultProps;
export default bsClass('carousel-caption', CarouselCaption);
|
src/scripts/views/components/avatar.js | DBozz/IronPong | import React from 'react'
import ACTIONS from '../../actions.js'
import STORE from '../../store.js'
var Avatar = React.createClass({
render: function(){
return(<div className = 'avatar-wrapper'>
</div>)
}
})
export default Avatar |
actor-apps/app-web/src/app/components/modals/invite-user/ContactItem.react.js | ruikong/actor-platform | import React from 'react';
import { PureRenderMixin } from 'react/addons';
import AvatarItem from 'components/common/AvatarItem.react';
var ContactItem = React.createClass({
displayName: 'ContactItem',
propTypes: {
contact: React.PropTypes.object,
onSelect: React.PropTypes.func
},
mixins: [PureRenderMixin],
_onSelect() {
this.props.onSelect(this.props.contact);
},
render() {
let contact = this.props.contact;
return (
<li className="contacts__list__item row">
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
<div className="controls">
<a className="material-icons" onClick={this._onSelect}>add</a>
</div>
</li>
);
}
});
export default ContactItem;
|
js/customer/HaircutHistoryItem.js | BarberHour/barber-hour | import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
Image,
} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import HaircutDetails from './HaircutDetails';
import Touchable from '../common/Touchable';
export default class HaircutHistoryItem extends Component {
_openDetails() {
this.props.navigator.push({
component: HaircutDetails,
passProps: {appointment: this.props.appointment}
});
}
_iconForStatus(status) {
switch (status) {
case 'finished':
return 'alarm-on';
case 'canceled':
return 'alarm-off';
case 'scheduled':
return 'alarm';
}
}
render() {
const { appointment } = this.props;
const { schedule, barber } = appointment;
return(
<Touchable style={styles.card} onPress={this._openDetails.bind(this)}>
<View>
<View>
<Text style={styles.date} numberOfLines={1}>{schedule.day_number} de {schedule.month_name} às {schedule.hour}</Text>
<Text style={styles.barber} numberOfLines={1}>{barber.name}</Text>
<View style={styles.statusContainer}>
<Icon name={this._iconForStatus(appointment.status)} size={24} color='#003459' style={styles.icon} />
<Text>{appointment.translated_status}</Text>
</View>
</View>
</View>
</Touchable>
);
}
}
var styles = StyleSheet.create({
card: {
flexDirection: 'column',
backgroundColor: 'white',
borderColor: '#E8E8E8',
borderWidth: 1,
padding: 10,
marginBottom: 10,
borderRadius: 2,
elevation: 2,
flex: 1
},
date: {
fontWeight: 'bold',
color: '#292929',
fontSize: 18
},
barber: {
color: '#A2A2A2',
fontSize: 18
},
icon: {
marginRight: 5
},
statusContainer: {
flexDirection: 'row',
marginTop: 5,
alignItems: 'center'
}
});
|
src/docs/examples/ProgressBar/Example10Percent.js | wsherman67/UBA | import React from 'react';
import ProgressBar from 'ps-react/ProgressBar';
/** 10% progress */
export default function Example10Percent() {
return <ProgressBar percent={10} width={150} />
}
|
src/components/Switch/demo/basic/index.js | lebra/lebra-components | import React, { Component } from 'react';
import Switch from '../../index';
import { render } from 'react-dom';
import './index.less';
export default class SwitchDemo extends Component{
handleChange = (e) => {
alert("切换")
}
render() {
return (
<div className="switch-demo">
<div className="lebra-cells__title">Switch Demo</div>
<div className="lebra-cells lebra-cells_form">
<div className="lebra-cell lebra-cell_switch">
<div className="lebra-cell__bd">默认选中状态,可切换</div>
<div className="lebra-cell__ft">
<Switch defaultChecked={true} />
</div>
</div>
<div className="lebra-cell lebra-cell_switch">
<div className="lebra-cell__bd">默认未选中状态,可切换</div>
<div className="lebra-cell__ft">
<Switch defaultChecked={false} handleChange={this.handleChange}/>
</div>
</div>
<div className="lebra-cell lebra-cell_switch">
<div className="lebra-cell__bd">默认未选中状态,不可切换</div>
<div className="lebra-cell__ft">
<Switch defaultChecked={false} disabled={true}/>
</div>
</div>
</div>
</div>
)
}
}
let root = document.getElementById('app');
render(<SwitchDemo />, root);
|
src/client/components/message/chatMessageShortcut.js | uuchat/uuchat | import React, { Component } from 'react';
import { Modal, Input } from 'antd';
import '../../static/css/shortcut.css';
class ChatMessageShortcut extends Component{
constructor(){
super();
this.state={
isSetShow: false
};
}
setShortcut = () => {
this.toggleSet(true);
};
shortcutFetch = () => {
let _self = this;
let shortKey = this.refs.shortKey.input.value;
let shortValue = this.refs.shortValue.textAreaRef.value;
let bodyData = 'csid='+(localStorage.getItem('uuchat.csid') || '')+'&shortcut='+shortKey+'&msg='+shortValue;
if (shortKey.replace(/^\s$/g, '') === '') {
_self.toggleSet(false);
return false;
}
fetch('/shortcuts', {
credentials: 'include',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
body: bodyData
}).then(d=>d.json()).then(data=>{
localStorage.setItem('newShortcut', '{"shortcut": "'+shortKey+'","msg": "'+shortValue+'", "action":"INSERT"}');
_self.toggleSet(false);
}).catch((e)=>{});
};
shortcutCancel = () => {
this.toggleSet(false);
};
toggleSet = (flag) => {
this.setState({
isSetShow: flag
});
};
render(){
let { content } = this.props;
content = content.replace(/ /g, ' ').replace(/(^\s*)/g, '').replace(/>/g, '>').replace(/</g, '<');
return (
<div className="short-item-setting" onClick={this.setShortcut}>
<Modal
title="Add a Personal Shortcut"
visible={this.state.isSetShow}
cancelText="Cancel"
okText="Save"
onCancel={this.shortcutCancel}
onOk={this.shortcutFetch}
>
<div>
<div className="set-item">
Add a personal shortcut for the text you want to expand then type <i>;</i> in chat to search for the shortcut.
</div>
<div className="set-item">
<p className="set-item-label">Shortcut</p>
<Input defaultValue="" addonBefore=";" ref="shortKey" />
<p className="set-item-label">Expanded Message</p>
<Input.TextArea defaultValue={content} ref="shortValue" />
</div>
</div>
</Modal>
</div>
);
}
}
export default ChatMessageShortcut; |
app/containers/Preschool/Preschool.js | klpdotorg/tada-frontend | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import isEmpty from 'lodash.isempty';
import get from 'lodash.get';
import {
getBoundariesEntities,
getLanguages,
getInstitutionCategories,
getManagements,
openTeachers,
toggleClassModal,
} from '../../actions';
import { PreschoolView } from '../../components/Preschool';
import { checkPermissions, getEntitiesPath } from '../../utils';
class FetchPreschoolEntity extends Component {
componentDidMount() {
const { params, institution, parentId } = this.props;
const { districtNodeId, projectNodeId, circleNodeId, institutionNodeId } = params;
if (isEmpty(institution)) {
const entities = [
parentId,
districtNodeId,
projectNodeId,
circleNodeId,
institutionNodeId,
].map((id, i) => {
return { depth: i, uniqueId: id };
});
this.props.getBoundariesEntities(entities);
}
this.props.getLanguages();
this.props.getInstitutionCats();
this.props.getManagements();
}
render() {
const { params } = this.props;
const { blockNodeId, districtNodeId, clusterNodeId, institutionNodeId } = params;
const path = [districtNodeId, blockNodeId, clusterNodeId, institutionNodeId];
return <PreschoolView {...this.props} depth={path.length} />;
}
}
FetchPreschoolEntity.propTypes = {
params: PropTypes.object,
institution: PropTypes.object,
getBoundariesEntities: PropTypes.func,
getLanguages: PropTypes.func,
getInstitutionCats: PropTypes.func,
getManagements: PropTypes.func,
parentId: PropTypes.string,
};
const mapStateToProps = (state, ownProps) => {
const { districtNodeId, projectNodeId, circleNodeId, institutionNodeId } = ownProps.params;
const { isAdmin } = state.profile;
const district = get(state.boundaries.boundaryDetails, districtNodeId, {});
const project = get(state.boundaries.boundaryDetails, projectNodeId, {});
const circle = get(state.boundaries.boundaryDetails, circleNodeId, {});
const institution = get(state.boundaries.boundaryDetails, institutionNodeId, {});
const hasPermissions = checkPermissions(
isAdmin,
state.userPermissions,
[district.id, project.id, circle.id],
institution.id,
);
const pathname = get(ownProps, ['location', 'pathname'], '');
const paths = getEntitiesPath(pathname, [districtNodeId, projectNodeId, circleNodeId]);
return {
district,
project,
circle,
institution,
isLoading: state.appstate.loadingBoundary,
isAdmin,
paths,
hasPermissions,
parentId: state.profile.parentNodeId,
};
};
const Preschool = connect(mapStateToProps, {
toggleClassModal,
showTeachers: openTeachers,
getBoundariesEntities,
getLanguages,
getInstitutionCats: getInstitutionCategories,
getManagements,
})(FetchPreschoolEntity);
export default Preschool;
|
app/javascript/mastodon/features/account_gallery/components/media_item.js | codl/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Permalink from '../../../components/permalink';
export default class MediaItem extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
};
render () {
const { media } = this.props;
const status = media.get('status');
let content, style;
if (media.get('type') === 'gifv') {
content = <span className='media-gallery__gifv__label'>GIF</span>;
}
if (!status.get('sensitive')) {
style = { backgroundImage: `url(${media.get('preview_url')})` };
}
return (
<div className='account-gallery__item'>
<Permalink
to={`/statuses/${status.get('id')}`}
href={status.get('url')}
style={style}
>
{content}
</Permalink>
</div>
);
}
}
|
src/NavItem.js | simonliubo/react-ui | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import SafeAnchor from './SafeAnchor';
const NavItem = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
linkId: React.PropTypes.string,
onSelect: React.PropTypes.func,
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
href: React.PropTypes.string,
role: React.PropTypes.string,
title: React.PropTypes.node,
eventKey: React.PropTypes.any,
target: React.PropTypes.string,
'aria-controls': React.PropTypes.string
},
render() {
let {
role,
linkId,
disabled,
active,
href,
title,
target,
children,
'aria-controls': ariaControls,
...props } = this.props;
let classes = {
active,
disabled
};
let linkProps = {
role,
href,
title,
target,
id: linkId,
onClick: this.handleClick
};
if (!role && href === '#') {
linkProps.role = 'button';
}
return (
<li {...props} role='presentation' className={classNames(props.className, classes)}>
<SafeAnchor {...linkProps} aria-selected={active} aria-controls={ariaControls}>
{ children }
</SafeAnchor>
</li>
);
},
handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
export default NavItem;
|
fixtures/packaging/systemjs-builder/prod/input.js | maxschmeling/react | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
|
js/Player/Players.js | olegk101/test | import React from 'react'
import { connect } from 'react-redux'
// import io from 'socket.io-client'
import Radium, { StyleRoot } from 'radium'
import style from '../style/liveplayer'
class Players extends React.Component {
constructor(props) {
super(props)
this.state = {
playing: false,
song: '',
loaded: false,
}
this.audio = null;
this.togglePlay = this.togglePlay.bind(this)
}
togglePlay () {
if (this.state.playing) {
this.audio.pause()
} else {
this.audio.play()
}
this.setState({ playing: !this.state.playing })
}
componentDidMount () {
this.audio = document.createElement('audio');
this.audio.preload = 'metadata';
// this.audio.addEventListener('play', console.log);
// this.audio.addEventListener('pause', this.audioPauseListener);
// this.audio.addEventListener('ended', this.audioEndListener);
this.audio.addEventListener('loadedmetadata', this.audioMetadataLoadedListener);
this.audio.addEventListener('canplay', this.setState({ loaded: true }), false);
this.audio.src = 'http://46.32.69.199:8000/live96';
this.togglePlay = this.togglePlay.bind(this)
}
render () {
let element
if (this.state.playing) {
element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg">
<path d="M6 19h4V5H6v14zm8-14v14h4V5h-4z"/>
<path d="M0 0h24v24H0z" fill="none"/>
</svg>)
} else {
element = (<svg fill="#fff" viewBox="0 0 24 24" height="100%" xmlns="http://www.w3.org/2000/svg">
<path d="M8 5v14l11-7z"/>
<path d="M0 0h24v24H0z" fill="none"/>
</svg>)
}
return (
<StyleRoot>
<div style={style.button}
onClick={this.togglePlay}
>
{element}
</div>
</StyleRoot>
)
}
}
const mapStateToProps = (state) => {
return {
fuck: state.searchTerm
}
}
Players = Radium(Players)
export default connect(mapStateToProps)(Players)
|
app/components/AudioPlayer.js | jrhalchak/BeatsPM | import React, { Component } from 'react';
import styles from './AudioPlayer.css';
export default class AudioPlayer extends Component {
handleRangeChange(e) {
this.props.timeChange(e.target.value / e.target.max);
}
render() {
const {
toggleAudio,
pauseAudio,
isPlaying,
audioSrc,
currentTime,
duration,
audioChange,
fileName,
isDetecting,
} = this.props;
const toggleText = isPlaying ? 'Stop' : 'Play';
const toggleClass = isPlaying ? styles.stopButton : null;
const currentVal = (currentTime / duration) * 100;
const detecting = isDetecting ? <Detecting /> : null;
if (!audioSrc) {
return (
<div className="pad-v">
<FileInput audioChange={audioChange} isAlone={true} />
</div>
);
}
return (
<div className={styles.audioContainer}>
{detecting}
<div className={styles.audioControls}>
<div className="pad-h-half float-right">
<button className={`${styles.audioButton} ${toggleClass}`} onClick={toggleAudio}>{toggleText}</button>
<button className={styles.audioButton} onClick={pauseAudio}>Pause</button>
</div>
<FileInput audioChange={audioChange} fileName={fileName} isAlone={false} />
</div>
<div className={styles.waveContainer}>
{this.props.children}
<progress className={styles.progressOverlay} value={currentVal} max="100" />
<input type="range" min="0" max="100" className={styles.slider} onChange={this.handleRangeChange.bind(this)} value={currentVal} />
</div>
</div>
);
}
}
function Detecting() {
return (
<div className={styles.detectingMessage}>Attempting BPM Auto-Detect...</div>
);
}
function FileInput({ audioChange, fileName, isAlone }) {
const divAlignment = isAlone ? 'text-center' : 'text-left';
const labelClass = isAlone ? styles.audioInputLabelBig : '';
return (
<div className={`pad-h-half ${divAlignment}`}>
<label htmlFor="audio_input">
<span className={`${styles.audioInputLabel} ${labelClass}`}>
{fileName ? 'Change Song' : 'Open a Song' }
</span>
{fileName ? <small className={styles.fileName}>- {fileName}</small> : ''}
</label>
<input id="audio_input" className={styles.audioInput} type="file" accept="audio/*" onChange={audioChange} />
</div>
);
}
|
12-route-to-modal-gallery/components/Gallery/Gallery.js | nodeyu/jason-react-router-demos-v4 | import React from 'react';
import { Link } from 'react-router-dom';
import IMAGES from '../../images/images';
import Thumbnail from '../Thumbnail/Thumbnail';
class Gallery extends React.Component {
render() {
return (
<div>
<h2>Gallery</h2>
{
IMAGES.map((img) => (
<Link
key={img.id}
to={{
pathname: `/img/${img.id}`,
state: { modal: true }
}}
>
<Thumbnail color={img.color}/>
<p style={{ marginTop: 0 }}>{img.title}</p>
</Link>
))
}
</div>
);
}
}
export default Gallery;
|
BUILD/js/components_js/product-card.js | kevincaicedo/MyStore-Front-end | import React from 'react'
export default class CardProduct extends React.Component {
render(){
return <div className="col-sm-4 col-lg-4 col-md-4 card-product">
<div className="thumbnail">
<img src={this.props.urlimg} alt="" />
<div className="caption">
<h4 className="pull-right price">$ {this.props.price}</h4>
<h4><a href="#">{this.props.name}</a></h4>
<p>{this.props.despcription}</p>
</div>
<div className="ratings">
<p className="pull-right fechap">{this.props.fecha}</p>
<p>
<a href="#about" className="btn btn-primary btn-xl page-scroll verbtn">ver</a>
</p>
</div>
</div>
</div>
}
} |
src/svg-icons/content/add-box.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentAddBox = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
</SvgIcon>
);
ContentAddBox = pure(ContentAddBox);
ContentAddBox.displayName = 'ContentAddBox';
ContentAddBox.muiName = 'SvgIcon';
export default ContentAddBox;
|
src/index.js | amsb/storybook_styled-components_example | import 'core-js/es6/symbol';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
client/src/components/Listing/ListingsContainer.js | wolnewitz/raptor-ads | import React, { Component } from 'react';
import { Container, Search } from 'semantic-ui-react';
class ListingsContainer extends Component {
constructor(props) {
super(props);
}
handleSearchChange(e) {
// dispatch controlled input update searchValue
}
render() {
<Container>
<Search
loading={isLoading}
onSearchChange={() => this.handleSearchChange()}
value={searchValue}
{...this.props}
/>
</Container>
}
}
|
client/share_trader/js/components/share_trader.js | bigchaindb/bigchaindb-examples | import React from 'react';
import { Navbar, Row, Col, Button } from 'react-bootstrap/lib';
import AccountList from '../../../lib/js/react/components/account_list';
import AccountDetail from '../../../lib/js/react/components/account_detail';
import Assets from './assets';
import AssetMatrix from './asset_matrix';
import AssetActions from '../../../lib/js/react/actions/asset_actions';
import BigchainDBConnection from '../../../lib/js/react/components/bigchaindb_connection';
const ShareTrader = React.createClass({
propTypes: {
// Injected through BigchainDBConnection
accountList: React.PropTypes.array,
activeAccount: React.PropTypes.object,
activeAsset: React.PropTypes.object,
assetList: React.PropTypes.object,
handleAccountChange: React.PropTypes.func,
handleAssetChange: React.PropTypes.func,
resetActiveAccount: React.PropTypes.func
},
fetchAssetList({ account }) {
AssetActions.fetchAssetList({
account,
blockWhenFetching: false
});
},
mapAccountsOnStates(accountList) {
const states = {
'default': 'available'
};
if (!accountList) {
return states;
}
for (let i = 0; i < accountList.length; i++) {
states[accountList[i].vk] = `state${i}`;
}
return states;
},
flattenAssetList(assetList) {
return [].concat(...Object.values(assetList));
},
render() {
const {
activeAccount,
accountList,
activeAsset,
assetList,
handleAccountChange,
handleAssetChange,
resetActiveAccount
} = this.props;
const states = this.mapAccountsOnStates(accountList);
const assetListForAccount =
activeAccount && assetList.hasOwnProperty(activeAccount.vk) ?
assetList[activeAccount.vk] : this.flattenAssetList(assetList);
return (
<div>
<Navbar fixedTop inverse>
<h1 style={{ textAlign: 'center', color: 'white' }}>Share Trader</h1>
</Navbar>
<div id="wrapper">
<div id="sidebar-wrapper">
<div className="sidebar-nav">
<div style={{ textAlign: 'center' }}>
<Button
onClick={resetActiveAccount}>
Select All
</Button>
</div>
<br />
<AccountList
activeAccount={activeAccount}
appName="sharetrader"
handleAccountClick={handleAccountChange}>
<AccountDetail />
</AccountList>
</div>
</div>
<div id="page-content-wrapper">
<div className="page-content">
<Row>
<Col className="asset-matrix" md={8} xs={6}>
<div className="vertical-align-outer">
<div className="vertical-align-inner">
<AssetMatrix
assetList={assetListForAccount}
cols={8}
handleAssetClick={handleAssetChange}
rows={8}
states={states} />
</div>
</div>
</Col>
<Col className="asset-history" md={4} xs={6}>
<Assets
accountList={accountList}
activeAccount={activeAccount}
activeAsset={activeAsset}
assetClasses={states}
assetList={assetListForAccount}
handleAssetClick={handleAssetChange} />
</Col>
</Row>
</div>
</div>
</div>
</div>
);
}
});
export default BigchainDBConnection(ShareTrader);
|
docs/app/Examples/modules/Dropdown/Variations/DropdownExampleMenuDirection.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Dropdown } from 'semantic-ui-react'
const DropdownExampleMenuDirection = () => (
<Dropdown text='Menu' floating labeled button className='icon'>
{/* <i class="dropdown icon"></i> */}
<Dropdown.Menu>
<Dropdown.Item>
<i className='left dropdown icon'></i>
<span className='text'>Left</span>
<div className='left menu'>
<Dropdown.Item>1</Dropdown.Item>
<Dropdown.Item>2</Dropdown.Item>
<Dropdown.Item>3</Dropdown.Item>
</div>
</Dropdown.Item>
<Dropdown.Item>
<i className='dropdown icon'></i>
<span className='text'>Right</span>
<div className='right menu'>
<Dropdown.Item>1</Dropdown.Item>
<Dropdown.Item>2</Dropdown.Item>
<Dropdown.Item>3</Dropdown.Item>
</div>
</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
)
export default DropdownExampleMenuDirection
|
examples/wrapper/index.js | sskyy/react-lego | import React from 'react'
import ReactDom from 'react-dom'
import { wrap } from '@cicada/react-lego'
import Case from '../Case'
import Card from './Card'
const Root = Card.Root.extend`
border: 1px dashed black;
`
const Text = ({children}) => {
return <div>{children.map(child => {
if (/^name:/.test(child) ) return '姓名: '
if (/^age:/.test(child)) return '年龄: '
return child
})}</div>
}
ReactDom.render((
<div>
<Case title="普通 Card">
<Card name="jim" age={11} />
</Case>
<Case title="传入了 Root, 简单演示替换样式">
<Card name="jim" age={11} Root={Root}/>
</Case>
<Case title="传入了 Text, 简单演示替换文案">
<Card name="jim" age={11} Text={Text}/>
</Case>
</div>
), document.getElementById('root'))
|
src/index.js | vikramarka/contacts | import React from 'react';
import ReactDOM from 'react-dom';
import {BrowserRouter} from 'react-router-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<BrowserRouter><App /></BrowserRouter>,
document.getElementById('root')
);
|
src/index.js | tasking/firebase-react-paginated | // react
import React, { Component } from 'react';
// utils
import getRef from './utils/getFirebaseRef';
import getDisplayName from './utils/getComponentDisplayName';
import getItems from './utils/getSnapshotItems';
const withFirebasePages = (firebase) => {
const ref = getRef(firebase);
return (options) => {
if (!options || !options.path) {
throw new Error('withFirebasePages - must receive an options object with a valid path prop.');
}
return (WrappedComponent) => {
return class extends Component {
static displayName = `withFirebasePages(${getDisplayName(WrappedComponent)})`
baseRef = null
onNewItemCallStack = {}
mounted = true
front = true
anchor = null
listeners = {}
options = {}
state = {
items: [],
pageItems: [],
hasNextPage: false,
hasPrevPage: false
}
componentDidMount() {
this.setupOptions();
this.setupRef();
this.goToNextPage();
}
componentWillUnmount() {
this.mounted = false;
this.unbindListeners();
}
setupOptions = () => {
this.options = { ...options };
if (typeof this.options.path === 'function') this.options.path = this.options.path(this.props);
if (typeof this.options.orderBy === 'function') this.options.orderBy = this.options.orderBy(this.props);
if (!this.options.orderBy) this.options.orderBy = '.value';
if (!this.options.length) this.options.length = 10;
if (this.options.onNewItem) this.options.onNewItem = this.options.onNewItem(this.props);
if (this.options.onNewPage) this.options.onNewPage = this.options.onNewPage(this.props);
}
setupRef = () => {
switch (this.options.orderBy) {
case '.value':
this.baseRef = ref.child(this.options.path).orderByValue();
break;
case '.priority':
this.baseRef = ref.child(this.options.path).orderByPriority();
break;
default:
this.baseRef = ref.child(this.options.path).orderByChild(this.options.orderBy);
break;
}
}
getAnchorValue = (idx) => {
const anchorItem = this.state.items[idx];
switch (this.options.orderBy) {
case '.value':
return anchorItem.value;
case '.priority':
return anchorItem.priority;
default:
return anchorItem.value[this.options.orderBy];
}
}
preBindListeners = () => {
const items = this.state.items;
if (!items.length) {
this.anchor = null;
return;
}
this.anchor = (
this.front
? this.getAnchorValue(items.length - 1)
: items.length > this.options.length + 1
? this.getAnchorValue(1)
: this.getAnchorValue(0)
);
}
bindListeners = () => {
this.setState({ isLoading: true });
const curRef = (
this.front
? this.anchor !== null
? this.baseRef.endAt(this.anchor).limitToLast(this.options.length + 1)
: this.baseRef.limitToLast(this.options.length + 1)
: this.baseRef.startAt(this.anchor).limitToFirst(this.options.length + 2)
);
const curListener = curRef.on('value', (snap) => {
if (!this.mounted) return;
let newState = {
items: getItems(snap, this.options.onNewItem, this.onNewItemCallStack),
isLoading: false
};
if (this.front) {
newState.hasNextPage = newState.items.length > this.options.length;
newState.pageItems = newState.items.slice(0, this.options.length);
} else {
newState.hasPrevPage = newState.items.length > this.options.length + 1;
newState.pageItems = newState.items.slice(-1 + (this.options.length * -1), -1);
}
this.options.onNewPage && this.options.onNewPage(newState.pageItems);
this.setState(newState);
});
this.listeners.current = { ref: curRef, listener: curListener };
if (this.anchor !== null) {
const tailRef = (
this.front
? this.baseRef.startAt(this.anchor).limitToFirst(2)
: this.baseRef.endAt(this.anchor).limitToLast(2)
);
const tailListener = tailRef.on('value', (snap) => {
if (!this.mounted) return;
let newState = {};
if (this.front) {
newState.hasPrevPage = snap.numChildren() === 2;
} else {
newState.hasNextPage = snap.numChildren() === 2;
}
this.setState(newState);
});
this.listeners.tail = { ref: tailRef, listener: tailListener };
}
}
unbindListeners = () => {
Object.keys(this.listeners).forEach((key) => {
if (this.listeners[key]) {
this.listeners[key].ref.off('value', this.listeners[key].listener);
this.listeners[key] = null;
}
});
}
goToNextPage = () => {
this.front = true;
this.unbindListeners();
this.preBindListeners();
this.bindListeners();
}
goToPrevPage = () => {
this.front = false;
this.unbindListeners();
this.preBindListeners();
this.bindListeners();
}
render() {
return (
<WrappedComponent
{...this.props}
pageItems={this.state.pageItems}
isLoading={this.state.isLoading}
hasNextPage={this.state.hasNextPage}
hasPrevPage={this.state.hasPrevPage}
onNextPage={this.goToNextPage}
onPrevPage={this.goToPrevPage} />
);
}
};
};
};
}
export default withFirebasePages;
|
test/integration/Table/MultiSelectTable.js | mmrtnz/material-ui | import React from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'src/Table';
const tableData = [
{
name: 'John Smith',
selected: true,
},
{
name: 'Randal White',
selected: true,
},
{
name: 'Olivier',
},
];
function TableMutliSelect() {
return (
<Table
selectable={true}
multiSelectable={true}
>
<TableHeader
displaySelectAll={true}
adjustForCheckbox={true}
enableSelectAll={true}
>
<TableRow>
<TableHeaderColumn>
Name
</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody displayRowCheckbox={true}>
{tableData.map( (row, index) => (
<TableRow key={index} selected={row.selected}>
<TableRowColumn>
{row.name}
</TableRowColumn>
</TableRow>
))}
</TableBody>
</Table>
);
}
export default TableMutliSelect;
|
client/src/components/AlbumsGrid.js | HoussamOtarid/fb-photos-downloader | import React from 'react';
import _ from 'lodash';
import Album from './Album';
import Pagination from '../components/Pagination';
import Spinner from 'react-spinner-material';
export default props => {
const { albums, paging } = props;
if (_.isEmpty(albums)) {
return (
<div className="spinner-container">
<Spinner size={80} spinnerColor={'#868e96'} spinnerWidth={2} visible={true} />
</div>
);
}
return (
<div className="container">
<Pagination paging={paging} onPaginationClick={props.onPaginationClick} />
<div className="row albums">
{_.map(albums, album => <Album album={album} key={album.id} onDownloadClick={props.onDownloadClick} />)}
</div>
</div>
);
};
|
examples/with-jsxstyle/src/server.js | jaredpalmer/react-production-starter | import { cache } from 'jsxstyle';
import App from './App';
import React from 'react';
import { StaticRouter } from 'react-router-dom';
import express from 'express';
import { renderToString } from 'react-dom/server';
const assets = require(process.env.RAZZLE_ASSETS_MANIFEST);
const server = express();
server
.disable('x-powered-by')
.use(express.static(process.env.RAZZLE_PUBLIC_DIR))
.get('/*', (req, res) => {
cache.reset();
let styles = '';
cache.injectOptions({
onInsertRule(css) {
styles += css;
},
});
const context = {};
const markup = renderToString(
<StaticRouter context={context} location={req.url}>
<App />
</StaticRouter>
);
if (context.url) {
res.redirect(context.url);
} else {
res.send(
`<!doctype html>
<html lang="">
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta charSet='utf-8' />
<title>Welcome to Razzle</title>
<meta name="viewport" content="width=device-width, initial-scale=1">
${
assets.client.css
? `<link rel="stylesheet" href="${assets.client.css}">`
: ''
}
${styles ? `<style type="text/css">${styles}</style>` : ''}
${
process.env.NODE_ENV === 'production'
? `<script src="${assets.client.js}" defer></script>`
: `<script src="${assets.client.js}" defer crossorigin></script>`
}
</head>
<body>
<div id="root">${markup}</div>
</body>
</html>`
);
}
});
export default server;
|
test/test_helper.js | Ridou/ReactTutorials | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/svg-icons/device/battery-charging-60.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBatteryCharging60 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V11h3.87L13 7v4h4V5.33C17 4.6 16.4 4 15.67 4z"/><path d="M13 12.5h2L11 20v-5.5H9l1.87-3.5H7v9.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V11h-4v1.5z"/>
</SvgIcon>
);
DeviceBatteryCharging60 = pure(DeviceBatteryCharging60);
DeviceBatteryCharging60.displayName = 'DeviceBatteryCharging60';
DeviceBatteryCharging60.muiName = 'SvgIcon';
export default DeviceBatteryCharging60;
|
modules/RouteUtils.js | joeyates/react-router | import React from 'react'
import warning from 'warning'
function isValidChild(object) {
return object == null || React.isValidElement(object)
}
export function isReactChildren(object) {
return isValidChild(object) || (Array.isArray(object) && object.every(isValidChild))
}
function checkPropTypes(componentName, propTypes, props) {
componentName = componentName || 'UnknownComponent'
for (const propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
const error = propTypes[propName](props, propName, componentName)
if (error instanceof Error)
warning(false, error.message)
}
}
}
function createRoute(defaultProps, props) {
return { ...defaultProps, ...props }
}
export function createRouteFromReactElement(element) {
const type = element.type
const route = createRoute(type.defaultProps, element.props)
if (type.propTypes)
checkPropTypes(type.displayName || type.name, type.propTypes, route)
if (route.children) {
const childRoutes = createRoutesFromReactChildren(route.children, route)
if (childRoutes.length)
route.childRoutes = childRoutes
delete route.children
}
return route
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router'
*
* const routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* )
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
export function createRoutesFromReactChildren(children, parentRoute) {
const routes = []
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
const route = element.type.createRouteFromReactElement(element, parentRoute)
if (route)
routes.push(route)
} else {
routes.push(createRouteFromReactElement(element))
}
}
})
return routes
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
export function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes)
} else if (!Array.isArray(routes)) {
routes = [ routes ]
}
return routes
}
|
app/containers/NotFoundPage/index.js | tzibur/site | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
/* eslint-disable react/prefer-stateless-function */
export default class NotFound extends React.Component {
render() {
return (
<h1>Page Not Found</h1>
);
}
}
|
test/test_helper.js | PhyrionX/ReactJS2 | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/components/App/routes.js | Cloudoki/hackforgood-paar |
import React from 'react'
import { Route, Switch } from 'react-router'
import requireAuth from 'containers/Auth'
import Login from 'containers/Auth/Login'
import HomePage from 'containers/HomePage'
import Filter from 'containers/Filter'
import Protected from 'components/Protected'
import NotFound from '../NotFound'
export default () => (
<Switch>
<Route path='/' exact component={HomePage} />
<Route path='/login' component={Login} />
<Route path='/filter' component={Filter} />
<Route path='/protected' component={requireAuth(Protected, 'user')} />
<Route component={NotFound} />
</Switch>
)
|
src/skeletons/SkeletonGroup.js | Bandwidth/shared-components | import React from 'react';
import PulseGroup from 'skeletons/PulseGroup';
import createArray from 'extensions/createArray';
const SkeletonGroup = ({ count = 1, children, ...rest }) => (
<React.Fragment>
{createArray(count).map(rowIdx => (
<PulseGroup {...rest} key={rowIdx}>
{children}
</PulseGroup>
))}
</React.Fragment>
);
/**
* @component
*/
export default SkeletonGroup;
|
examples/todomvc/src/Root/modules/Todo/UI.js | homkai/deef | import React from 'react';
import Header from './components/Header';
import Main from './components/Main';
import './style.less';
export default () => <div className="todo-app">
<Header />
<Main />
</div>; |
src/parser/mage/arcane/modules/features/RuleOfThrees.js | sMteX/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import { formatPercentage } from 'common/format';
import AbilityTracker from 'parser/shared/modules/AbilityTracker';
import Analyzer from 'parser/core/Analyzer';
const debug = false;
class RuleOfThrees extends Analyzer {
static dependencies = {
abilityTracker: AbilityTracker,
};
barrageWithRuleOfThrees = 0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.RULE_OF_THREES_TALENT.id);
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.ARCANE_BARRAGE.id) {
return;
}
if (this.selectedCombatant.hasBuff(SPELLS.RULE_OF_THREES_BUFF.id,event.timestamp + 1)) {
debug && this.log("Arcane Barrage with Rule of Threes Buff");
this.barrageWithRuleOfThrees += 1;
}
}
get utilization() {
return 1 - (this.barrageWithRuleOfThrees / this.abilityTracker.getAbility(SPELLS.ARCANE_BARRAGE.id).casts);
}
get suggestionThresholds() {
return {
actual: this.utilization,
isLessThan: {
minor: 0.95,
average: 0.90,
major: 0.80,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<>You cast <SpellLink id={SPELLS.ARCANE_BARRAGE.id} /> {this.barrageWithRuleOfThrees} times while you had the <SpellLink id={SPELLS.RULE_OF_THREES_BUFF.id} /> buff. This buff makes your next <SpellLink id={SPELLS.ARCANE_BLAST.id} /> or <SpellLink id={SPELLS.ARCANE_MISSILES.id} /> free after you gain your third Arcane Charge, so you should ensure that you use the buff before clearing your charges.</>)
.icon(SPELLS.RULE_OF_THREES_TALENT.icon)
.actual(`${formatPercentage(this.utilization)}% Utilization`)
.recommended(`${formatPercentage(recommended)}% is recommended`);
});
}
}
export default RuleOfThrees;
|
src/interface/report/Results/Timeline/Cooldowns.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import Abilities from 'parser/core/modules/Abilities';
import './Cooldowns.scss';
import Lane from './Lane';
class Cooldowns extends React.PureComponent {
static propTypes = {
start: PropTypes.number.isRequired,
end: PropTypes.number.isRequired,
secondWidth: PropTypes.number.isRequired,
eventsBySpellId: PropTypes.instanceOf(Map).isRequired,
abilities: PropTypes.instanceOf(Abilities).isRequired,
};
getSortIndex([spellId, events]) {
const ability = this.props.abilities.getAbility(spellId);
if (!ability || ability.timelineSortIndex === undefined) {
return 1000 - events.length;
} else {
return ability.timelineSortIndex;
}
}
renderLanes(eventsBySpellId, growUp) {
return Array.from(eventsBySpellId)
.sort((a, b) => this.getSortIndex(growUp ? b : a) - this.getSortIndex(growUp ? a : b))
.map(item => this.renderLane(item));
}
renderLane([spellId, events]) {
return (
<Lane
key={spellId}
spellId={spellId}
fightStartTimestamp={this.props.start}
fightEndTimestamp={this.props.end}
secondWidth={this.props.secondWidth}
>
{events}
</Lane>
);
}
render() {
const { eventsBySpellId } = this.props;
return (
<div className="cooldowns">
{this.renderLanes(eventsBySpellId, false)}
</div>
);
}
}
export default Cooldowns;
|
wp-content/plugins/download-monitor/assets/blocks/src/components/DownloadInput/index.js | mandino/www.bloggingshakespeare.com | const {Component} = wp.element;
import apiFetch from '@wordpress/api-fetch';
import React from 'react';
import Select from 'react-select';
export default class DownloadInput extends Component {
constructor( props ) {
super( props );
this.state = { downloads: [] };
}
componentDidMount() {
apiFetch( { url: dlmBlocks.ajax_getDownloads } ).then( results => {
this.setState({downloads: results });
} );
}
render() {
const valueFromId = (opts, id) => opts.find(o => o.value === id);
return (
<div>
<Select
value={valueFromId( this.state.downloads, this.props.selectedDownloadId )}
onChange={(selectedOption) => this.props.onChange(selectedOption.value)}
options={this.state.downloads}
isSearchable="true"
/>
</div>
);
}
}
|
share/components/LogIn/LogIn.js | caojs/password-manager-server | import React from 'react';
import classNames from 'classnames';
import { Field } from 'redux-form/immutable';
import { Link } from 'react-router';
import FaUser from 'react-icons/lib/fa/user';
import FaLock from 'react-icons/lib/fa/lock';
import Button from '../Common/Button';
import ErrorMessages from '../Common/ErrorMessages';
import { injectProps } from '../../helpers/decorators';
import style from './LogIn.css';
function Form({ hasErrors, handleSubmit }) {
return (
<form onSubmit={handleSubmit}>
<div className={style.fieldArea}>
<label className={style.label}>
<FaUser className="icon"/>
<Field
className="input"
name="username"
component="input"
placeholder="Username"/>
</label>
<label className={style.label}>
<FaLock className="icon"/>
<Field
className="input"
name="password"
component="input"
type="password"
placeholder="Password"/>
</label>
</div>
<Button
className={classNames({ error: hasErrors })}
type="submit">
Sign In
</Button>
</form>
);
}
export default class LogIn extends React.Component {
@injectProps
render({ errors, handleSubmit }) {
const hasErrors = !!(errors && errors.size);
let errorMessages = hasErrors ?
<ErrorMessages errors={errors}/> :
null;
return (
<div className={style.main}>
{errorMessages}
<Form
hasErrors={hasErrors}
handleSubmit={handleSubmit}/>
<div className={style.links}>
<Link className="link" to="/signup">Sign up</Link>
</div>
</div>
);
}
}
|
fields/types/select/SelectField.js | andrewlinfoot/keystone | import Field from '../Field';
import React from 'react';
import Select from 'react-select';
import { FormInput } from '../../../admin/client/App/elemental';
/**
* TODO:
* - Custom path support
*/
module.exports = Field.create({
displayName: 'SelectField',
statics: {
type: 'Select',
},
valueChanged (newValue) {
// TODO: This should be natively handled by the Select component
if (this.props.numeric && typeof newValue === 'string') {
newValue = newValue ? Number(newValue) : undefined;
}
this.props.onChange({
path: this.props.path,
value: newValue,
});
},
renderValue () {
const { ops, value } = this.props;
const selected = ops.find(opt => opt.value === value);
return (
<FormInput noedit>
{selected ? selected.label : null}
</FormInput>
);
},
renderField () {
const { numeric, ops, path, value: val } = this.props;
// TODO: This should be natively handled by the Select component
const options = (numeric)
? ops.map(function (i) {
return { label: i.label, value: String(i.value) };
})
: ops;
const value = (typeof val === 'number')
? String(val)
: val;
return (
<div>
{/* This input element fools Safari's autocorrect in certain situations that completely break react-select */}
<input type="text" style={{ position: 'absolute', width: 1, height: 1, zIndex: -1, opacity: 0 }} tabIndex="-1"/>
<Select
simpleValue
name={this.getInputName(path)}
value={value}
options={options}
onChange={this.valueChanged}
/>
</div>
);
},
});
|
app/components/NowPlaying.js | robcalcroft/edison | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import moment from 'moment';
import {
Button,
Image,
Modal,
StyleSheet,
TouchableHighlight,
View,
} from 'react-native';
import Slider from 'react-native-slider';
import Text from './Text';
import TouchableIcon from './TouchableIcon';
const styles = StyleSheet.create({
nowPlayingBar: {
backgroundColor: 'lightgray',
justifyContent: 'space-between',
flexDirection: 'row',
paddingLeft: 10,
paddingRight: 10,
borderTopColor: 'grey',
borderTopWidth: 1,
},
nowPlayingBar__inner: {
flexDirection: 'row',
alignItems: 'center',
},
nowPlayingBar__inner__title: {
paddingLeft: 10,
fontSize: 18,
},
nowPlayingBar__inner__image: {
height: 40,
width: 40,
},
nowPlayingModal: {
marginTop: 20,
alignItems: 'center',
justifyContent: 'space-around',
flex: 1,
},
nowPlayingImage: {
flex: 0.85,
width: '100%',
},
nowPlayingSliderContainer: {
width: '100%',
paddingLeft: 15,
paddingRight: 15,
},
nowPlayingSliderInfo: {
flexDirection: 'row',
justifyContent: 'space-between',
},
nowPlayingActions: {
width: '100%',
justifyContent: 'space-around',
flexDirection: 'row',
},
nowPlayingInfo: {
fontSize: 22,
},
});
// TODO convert to normal class to allow no updating of the value of the slider until the
// onSlidingComplete has been called
class NowPlaying extends Component {
showNativePlayer() {
this.props.setNowPlayingState({ modalVisible: false }, () => {
this.props.performPlayerAction('presentFullscreenPlayer');
});
}
render() {
const {
modalVisible,
showModal,
hideModal,
activePathOrUri,
paused,
muted,
title,
author,
artwork,
setNowPlayingState,
seekableDuration,
currentTime,
performPlayerAction,
} = this.props;
const formattedCurrentTime = moment(moment.duration(currentTime, 's').asMilliseconds()).format('HH:mm:ss');
const formattedSeekableDuration = moment(moment.duration(seekableDuration - currentTime, 's').asMilliseconds()).format('HH:mm:ss');
return [
activePathOrUri ? (
<TouchableHighlight key={1} onPress={showModal}>
<View style={[styles.nowPlayingBar, { height: modalVisible ? 0 : 60 }]}>
<View style={styles.nowPlayingBar__inner}>
<Image source={{ uri: artwork }} style={styles.nowPlayingBar__inner__image} />
<Text style={styles.nowPlayingBar__inner__title}>{title}</Text>
</View>
<View style={styles.nowPlayingBar__inner}>
<Button
onPress={() => setNowPlayingState({ paused: !paused })}
title={paused ? 'Play' : 'Pause'}
/>
</View>
</View>
</TouchableHighlight>
) : null,
<Modal
animationType="slide"
onRequestClose={hideModal}
visible={modalVisible}
key={2}
>
<View style={styles.nowPlayingModal}>
<Image resizeMode="contain" source={{ uri: artwork }} style={styles.nowPlayingImage} />
<Text style={styles.nowPlayingInfo}>{title} by {author}</Text>
<View style={styles.nowPlayingSliderContainer}>
<Slider
value={currentTime}
maximumValue={seekableDuration}
onSlidingComplete={value => performPlayerAction('seek', value)}
style={styles.nowPlayingSlider}
/>
<View style={styles.nowPlayingSliderInfo}>
<Text>{formattedCurrentTime}</Text>
<Text>-{formattedSeekableDuration}</Text>
</View>
</View>
{/* We are not using this as you can use the phone's volume control */}
{/* <Slider onValueChange={value => setNowPlayingState({ volume: value })} /> */}
<View style={styles.nowPlayingActions}>
<TouchableIcon
name={muted ? 'ios-volume-off' : 'ios-volume-up'}
onPress={() => setNowPlayingState({ muted: !muted })}
/>
<TouchableIcon
name="ios-skip-backward"
onPress={() => performPlayerAction('seek', 0)}
/>
<TouchableIcon
name={`ios-${paused ? 'play' : 'pause'}`}
onPress={() => setNowPlayingState({ paused: !paused })}
/>
<TouchableIcon name="ios-contract" onPress={hideModal} />
<TouchableIcon
name="ios-expand"
onPress={() => this.showNativePlayer()}
/>
</View>
</View>
</Modal>,
];
}
}
NowPlaying.propTypes = {
modalVisible: PropTypes.bool.isRequired,
paused: PropTypes.bool.isRequired,
muted: PropTypes.bool.isRequired,
title: PropTypes.string.isRequired,
author: PropTypes.string.isRequired,
artwork: PropTypes.string.isRequired,
showModal: PropTypes.func.isRequired,
hideModal: PropTypes.func.isRequired,
activePathOrUri: PropTypes.string.isRequired,
seekableDuration: PropTypes.number.isRequired,
currentTime: PropTypes.number.isRequired,
setNowPlayingState: PropTypes.func.isRequired,
performPlayerAction: PropTypes.func.isRequired,
};
export default NowPlaying;
|
src/home/root.component.js | joeldenning/single-spa-examples | import React from 'react';
import Technology from './technology.component.js';
import Walkthroughs from './walkthroughs.component.js';
import {getBorder, showFrameworkObservable} from 'src/common/colored-border.js';
export default class HomeRoot extends React.Component {
constructor() {
super();
this.state = {
frameworkInspector: false,
};
}
componentWillMount() {
this.subscription = showFrameworkObservable.subscribe(newValue => this.setState({frameworkInspector: newValue}));
}
render() {
return (
<div style={this.state.frameworkInspector ? {border: getBorder('react')} : {}}>
{this.state.frameworkInspector &&
<div>(built with React)</div>
}
<div className="container">
<div className="row">
<h4 className="light">
Introduction
</h4>
<p className="caption">
Single-spa is a javascript libary that allows for many small applications to coexist in one single page application.
This website is a demo application that shows off what single-spa can do.
For more information about single-spa, go to the <a href="https://github.com/CanopyTax/single-spa" target="_blank">single-spa Github page</a>.
Additionally, this website's code can be found at the <a href="https://github.com/CanopyTax/single-spa-examples" target="_blank">single-spa-examples Github</a>.
While you're here, check out the following features:
</p>
<Walkthroughs />
</div>
<div className="row">
<h4 className="light">
Framework examples
</h4>
<p className="caption">
Single-spa allows for multiple frameworks to coexist in the same single page application.
</p>
<div className="row">
<Technology
imgSrc="data:image/svg+xml;base64,PHN2ZyBpZD0iTGF5ZXJfMSIgZGF0YS1uYW1lPSJMYXllciAxIiB4bWxucz0iaHR0cDovL3d3dy53My5vcmcvMjAwMC9zdmciIHZpZXdCb3g9IjAgMCAyMyAyMC40NjM0OCI+PHRpdGxlPmxvZ288L3RpdGxlPjxwYXRoIGQ9Ik0xOC45MTA3LDYuNjMyNTdoMHEtLjM2NzIxLS4xMjYtLjc0MDQyLS4yMzMzLjA2MTg3LS4yNTE0MS4xMTQ0MS0uNTA1Yy41NjA0NS0yLjcyMDY0LjE5NC00LjkxMjM3LTEuMDU3MzktNS42MzM4Ni0xLjE5OTgtLjY5Mi0zLjE2MjEuMDI5NTItNS4xNDM5NCwxLjc1NDE0cS0uMjkyOTMuMjU1NS0uNTcyNjcuNTI1NTQtLjE4NzI3LS4xNzk1MS0uMzgxMS0uMzUyQzkuMDUyNTcuMzQzOSw2Ljk3MDY2LS40MzMxNiw1LjcyMDU4LjI5MDQ2LDQuNTIxOTEuOTg0MzYsNC4xNjY4NiwzLjA0NDg5LDQuNjcxNDQsNS42MjMyMnEuMDc1My4zODMuMTcuNzYxNzljLS4yOTQ1OC4wODM2Ny0uNTc5MDguMTcyODQtLjg1MTI3LjI2NzcxQzEuNTU1MTQsNy41MDE2NSwwLDguODMyMjUsMCwxMC4yMTIzMWMwLDEuNDI1NDYsMS42NjkzNSwyLjg1NTIsNC4yMDU3NSwzLjcyMnEuMzA4NS4xMDQ5NC42MjE5My4xOTQ0Mi0uMTAxNzkuNDA4LS4xODA2OC44MjExNGMtLjQ4MTA2LDIuNTMzNTQtLjEwNTM1LDQuNTQ1MjEsMS4wOTAxNyw1LjIzNDg0LDEuMjM0ODEuNzEyLDMuMzA3MjUtLjAxOTg1LDUuMzI1MzMtMS43ODM4N3EuMjM5MjYtLjIwOTE3LjQ3OTk0LS40NDIzOC4zMDI5LjI5MjI1LjYyMTczLjU2NzI3YzEuOTU0NzcsMS42ODIwNywzLjg4NTMxLDIuMzYxMzIsNS4wNzk4MiwxLjY2OTg2LDEuMjMzNjktLjcxNDE2LDEuNjM0NTQtMi44NzUyNSwxLjExNC01LjUwNDU5cS0uMDU5NTUtLjMwMTI0LS4xMzc5Mi0uNjE0ODEuMjE4MzQtLjA2NDQzLjQyNzcyLS4xMzM1NUMyMS4yODQ1NCwxMy4wNjkxNSwyMywxMS42NTY4MSwyMywxMC4yMTIzMiwyMyw4LjgyNzI2LDIxLjM5NDc4LDcuNDg3NzEsMTguOTEwNyw2LjYzMjU3Wk0xMi43Mjg0LDIuNzU1ODFDMTQuNDI2NDYsMS4yNzgsMTYuMDEzNDYuNjk0NTcsMTYuNzM2NTcsMS4xMTE2aDBjLjc3MDE0LjQ0NDIxLDEuMDY5NzEsMi4yMzU0LjU4NTgsNC41ODQ0MXEtLjA0NzU4LjIyOTUzLS4xMDM0Mi40NTcyNGEyMy41Mzc1MiwyMy41Mzc1MiwwLDAsMC0zLjA3NTI3LS40ODU4NEEyMy4wODEyOCwyMy4wODEyOCwwLDAsMCwxMi4xOTk1LDMuMjQwOTRRMTIuNDU3ODgsMi45OTE4NCwxMi43Mjg0LDIuNzU1ODFaTTYuNzkxMTEsMTEuMzkxMjRxLjMxMi42MDI2NS42NTIwNywxLjE5MDEzLjM0NjkyLjU5OTExLjcyMjEsMS4xODExN2EyMC45MjE2OCwyMC45MjE2OCwwLDAsMS0yLjExOTY3LS4zNDA4QzYuMjQ4NjcsMTIuNzY2LDYuNDk4ODcsMTIuMDg0NDMsNi43OTExMSwxMS4zOTEyNFpNNi43OSw5LjA4MDQxYy0uMjg2MTMtLjY3ODYzLS41MzA5My0xLjM0NTg2LS43MzA4NS0xLjk5MDE5LjY1NjI0LS4xNDY4OCwxLjM1Ni0uMjY2ODksMi4wODUxNi0uMzU4cS0uMzY2MTEuNTcxLS43MDUxLDEuMTU4NzdRNy4xMDA3Niw4LjQ3OCw2Ljc5LDkuMDgwNDFabS41MjIyOCwxLjE1NTUycS40NTQxMS0uOTQ1MTcuOTc4My0xLjg1NDJ2LjAwMDJxLjUyMzY5LS45MDg1NywxLjExNTIxLTEuNzc1NDJjLjY4NC0uMDUxNzEsMS4zODUzNi0uMDc4NzksMi4wOTQzMi0uMDc4NzkuNzEyMTIsMCwxLjQxNDM3LjAyNzI4LDIuMDk4MTkuMDc5NHEuNTg1MTQuODY0ODcsMS4xMDgxOCwxLjc2OTQxLjUyNTY1LjkwNjM1Ljk5MTUzLDEuODQ1NDUtLjQ2MDgzLjk0ODE3LS45ODgyOCwxLjg2MTczaC0uMDAwMXEtLjUyMjYxLjkwNzg2LTEuMTAzNCwxLjc4MDNjLS42ODI0LjA0ODc2LTEuMzg3Ni4wNzM5LTIuMTA2MjMuMDczOS0uNzE1NjgsMC0xLjQxMTkzLS4wMjIyOS0yLjA4MjQxLS4wNjU3NXEtLjU5NTU1LS44Njk5NS0xLjEyNDA2LTEuNzgzMDVRNy43Njc4OSwxMS4xODE0OCw3LjMxMjI3LDEwLjIzNTkzWm04LjI0ODUzLDIuMzM4NjJxLjM0Ny0uNjAxODIuNjY3LTEuMjE4NjNoMGEyMC44NjY3MSwyMC44NjY3MSwwLDAsMSwuNzcyMzgsMi4wMjMyNywyMC44NTE2NCwyMC44NTE2NCwwLDAsMS0yLjE0NTUyLjM2NTczUTE1LjIxOTM1LDEzLjE2NjgyLDE1LjU2MDgsMTIuNTc0NTVabS42NTc2Ny0zLjQ5MzQzcS0uMzE4ODMtLjYwNS0uNjYxNjMtMS4xOTY4NGgwcS0uMzM3MjctLjU4MjU4LS42OTk0LTEuMTUwMjJjLjczMzkuMDkyNjMsMS40MzcuMjE1NzksMi4wOTcxNy4zNjY1NEEyMC45NTkwOSwyMC45NTkwOSwwLDAsMSwxNi4yMTg0Nyw5LjA4MTEyWk0xMS41MTEsMy45NDM1OWEyMS4wMTI4OCwyMS4wMTI4OCwwLDAsMSwxLjM1MzUsMS42MzM5M3EtMS4zNTg0My0uMDY0MTktMi43MTg0LS4wMDA2MUMxMC41OTMsNC45ODc2NSwxMS4wNTA3LDQuNDQwMjIsMTEuNTExLDMuOTQzNTlaTTYuMjEyODQsMS4xNDA4MWMuNzY5NTMtLjQ0NTQzLDIuNDcwOTUuMTg5NzMsNC4yNjQyOCwxLjc4Mi4xMTQ2MS4xMDE3OS4yMjk3NC4yMDgzNi4zNDUwNy4zMTg2QTIzLjU0NTQyLDIzLjU0NTQyLDAsMCwwLDguODYyOTQsNS42NjYwOGEyNC4wMDgsMjQuMDA4LDAsMCwwLTMuMDY5MTYuNDc3cS0uMDg4LS4zNTIyOC0uMTU4MDgtLjcwODY2di4wMDAxQzUuMjAzMzksMy4yMjUzNiw1LjQ5MDQ0LDEuNTU5LDYuMjEyODQsMS4xNDA4MVpNNS4wOTEzMiwxMy4xODIzM3EtLjI4Ni0uMDgxODctLjU2Nzc4LS4xNzc3M0E4LjMyMzcxLDguMzIzNzEsMCwwLDEsMS44NDEsMTEuNTc5NTVhMi4wMzA3MiwyLjAzMDcyLDAsMCwxLS44NTg0OS0xLjM2NzI0YzAtLjgzNzQyLDEuMjQ4NjUtMS45MDU3MSwzLjMzMTE3LTIuNjMxNzhxLjM5MjA4LS4xMzYxLjc5MTYyLS4yNDkwOGEyMy41NjQ1NSwyMy41NjQ1NSwwLDAsMCwxLjEyMSwyLjkwNDc4QTIzLjkyMjQ3LDIzLjkyMjQ3LDAsMCwwLDUuMDkxMzIsMTMuMTgyMzNaTTEwLjQxNTk0LDE3LjY2MWE4LjMyMTYxLDguMzIxNjEsMCwwLDEtMi41NzQ2NywxLjYxMTg0aC0uMDAwMWEyLjAzMDQyLDIuMDMwNDIsMCwwLDEtMS42MTMwNi4wNjA2N2MtLjcyNTU2LS40MTgzNi0xLjAyNzA2LTIuMDMzNzYtLjYxNTczLTQuMjAwMzVxLjA3MzM3LS4zODQwNy4xNjgtLjc2MzYzYTIzLjEwNDQ0LDIzLjEwNDQ0LDAsMCwwLDMuMDk5NS40NDg2OSwyMy45MDk1NCwyMy45MDk1NCwwLDAsMCwxLjk3NDMxLDIuNDM5MjlRMTAuNjQsMTcuNDY0NTksMTAuNDE1OTQsMTcuNjYxWm0xLjEyMjIzLTEuMTEwNTNjLS40NjU2OS0uNTAyNTMtLjkzMDE1LTEuMDU4MzEtMS4zODM4My0xLjY1NjEycS42NjA1MS4wMjYsMS4zNDU2Ni4wMjYwNi43MDMyNiwwLDEuMzg4NDEtLjAzMDg0QTIwLjg5NDI1LDIwLjg5NDI1LDAsMCwxLDExLjUzODE3LDE2LjU1MDQ1Wm01Ljk2NjUxLDEuMzY3YTIuMDMwMzksMi4wMzAzOSwwLDAsMS0uNzUzLDEuNDI3OGMtLjcyNDg1LjQxOTU4LTIuMjc1LS4xMjU4MS0zLjk0NjU5LTEuNTY0MzFxLS4yODc1LS4yNDczNS0uNTc4MzctLjUyNzI3YTIzLjA4OTE0LDIzLjA4OTE0LDAsMCwwLDEuOTI3OS0yLjQ0OCwyMi45MzY0NywyMi45MzY0NywwLDAsMCwzLjExNTA3LS40ODAxNHEuMDcwMjQuMjg0LjEyNDQ5LjU1NjM4aDBBOC4zMiw4LjMyLDAsMCwxLDE3LjUwNDY4LDE3LjkxNzQ5Wm0uODM0MTctNC45MDczOWgtLjAwMDFjLS4xMjU3MS4wNDE2My0uMjU0NzguMDgxODQtLjM4NjI5LjEyMDgyYTIzLjA2MTIxLDIzLjA2MTIxLDAsMCwwLTEuMTY0NjgtMi45MTM3MywyMy4wNTExMiwyMy4wNTExMiwwLDAsMCwxLjExOTM4LTIuODcxMjhjLjIzNTI0LjA2ODIuNDYzNjUuMTQuNjgzNzIuMjE1NzksMi4xMjg0Mi43MzI1OCwzLjQyNjY1LDEuODE1OTMsMy40MjY2NSwyLjY1MDYxQzIyLjAxNzUzLDExLjEwMTQ1LDIwLjYxNTM4LDEyLjI1NTc0LDE4LjMzODg1LDEzLjAxMDFaIiBmaWxsPSIjNjFkYWZiIi8+PHBhdGggZD0iTTExLjUsOC4xNTg1YTIuMDUzODYsMi4wNTM4NiwwLDEsMS0yLjA1MzgxLDIuMDUzODFBMi4wNTM4MSwyLjA1MzgxLDAsMCwxLDExLjUsOC4xNTg1IiBmaWxsPSIjNjFkYWZiIi8+PC9zdmc+"
imgBackgroundColor="#222222"
cardTitle="React"
href="/react"
explanation={`Yep we've got a React example. We actually just borrowed it from the react-router examples, to show how easy it is to migrate an existing app into single-spa`}
/>
<Technology
imgSrc="https://angularjs.org/img/ng-logo.png"
cardTitle="AngularJS"
href="/angularjs"
explanation={`AngularJS has some quirks, but works just fine when you use the single-spa-angularjs npm library to help you set up your app`}
/>
<Technology
imgSrc="/images/angular.svg"
imgBackgroundColor="#1976D2"
cardTitle="Angular"
href="/angular"
explanation={`Angular is compatible with single-spa, check out a simple 'Hello World' in the example.`}
/>
<Technology
imgSrc="https://vuejs.org/images/logo.png"
cardTitle="Vue.js"
href="/vue"
explanation={`Vue.js is compatible with single-spa. Easily get started with the single-spa-vue plugin.`}
/>
<Technology
imgSrc="/images/svelte.jpg"
cardTitle="Svelte"
href="/svelte"
explanation={`Svelte is compatible with single-spa. Easily get started with the single-spa-svelte plugin.`}
/>
<Technology
imgSrc="https://cycle.js.org/img/cyclejs_logo.svg"
cardTitle="CycleJS"
href="/cyclejs"
explanation={`CycleJS is compatible with single-spa. Easily get started with the single-spa-cycle plugin.`}
/>
<Technology
imgSrc="https://camo.githubusercontent.com/31415a8c001234dbf4875c2c5a44b646fb9338b4/68747470733a2f2f63646e2e7261776769742e636f6d2f646576656c6f7069742f62343431366435633932623734336462616563316536386263346332376364612f7261772f333233356463353038663765623833346562663438343138616561323132613035646631336462312f7072656163742d6c6f676f2d7472616e732e737667"
cardTitle="Preact"
href="/preact"
explanation={`Preact is compatible with single-spa. Easily get started with the single-spa-preact plugin.`}
/>
<Technology
imgSrc="http://xitrus.es/blog/imgs/vnll.jpg"
cardTitle="Vanilla"
href="/vanilla"
explanation={`
If you want to write single-spa applications in vanilla javascript, that's fine too.
`}
/>
<Technology
imgSrc="/images/inferno-logo.png"
cardTitle="Inferno"
href="/inferno"
explanation={`
Inferno is compatible with single-spa. Easily get started with the single-spa-inferno plugin.
`}
/>
</div>
</div>
<div className="row">
<h4 className="light">
Build system examples
</h4>
<p className="caption">
Each application chooses it's own build system, which will fit into the root single-spa application at runtime.
</p>
<div className="row">
<Technology
imgSrc="https://avatars0.githubusercontent.com/webpack?&s=256"
cardTitle="Webpack"
href="/react"
explanation={`The React example is built with Webpack, and even uses require.ensure for extra lazy loading.`}
/>
<Technology
imgSrc="https://avatars3.githubusercontent.com/u/3802108?v=3&s=200"
cardTitle="SystemJS"
href="/angularjs"
explanation={`The navbar app, home app, and AngularJS app are all built with JSPM / SystemJS.`}
/>
<Technology
imgSrc="http://4.bp.blogspot.com/-rI6g4ZgVqBA/Uv8fPnl9TLI/AAAAAAAAMZU/tbylo5ngisg/s1600/iFrame+Generator.jpg"
cardTitle="Iframe"
href="/vanilla"
explanation={`
Putting things in iframes is the wrong thing to do many times, but there are valid use cases for it.
If you put a single-spa application into an iframe, you get a whole new DOM and global namespace for variables.
But the cons include degraded performance and trickier inter-app communication.
`}
/>
</div>
</div>
</div>
</div>
);
}
componentWillUnmount() {
this.subscription.dispose();
}
}
|
src/js/components/privKey/PrivKeyBox.js | safexio/safexweb | import React from 'react';
var PrivKeyImport = require('./PrivKeyImport');
var PrivKeyTable = require('./PrivKeyTable');
var privKeyActions = require('actions/privKeyActions');
var PrivKeyBox = React.createClass({
_generateNewKeypair: function() {
privKeyActions.addPrivKey();
},
render: function() {
var button = <button onClick={this._generateNewKeypair} className="btn btn-warning btn-xs pull-right" type="input">Generate <span className="hidden-xs">New </span>Keypair</button>;
return (
<div className="panel panel-default">
<div className="panel-heading"><span className="hidden-xs">Bitcoin </span>Private Keys {button}</div>
<div className="panel-body">
<PrivKeyImport />
<PrivKeyTable />
</div>
</div>
);
}
});
module.exports = PrivKeyBox; |
src/stories/2017-12-15-cretan-sunsets.js | danpersa/remindmetolive-react | import React from 'react';
import PostImageResp from '../components/story/PostImageResp';
import TwoPostImageResp from '../components/story/TwoPostImageResp';
import StoryPage from '../components/story/StoryPage';
import StoryTextBlock from '../components/story/StoryTextBlock';
import StoryImages from '../components/story/StoryImages';
import StoryIntro from '../components/story/StoryIntro';
import FullImageResp from '../components/story/FullImageResp';
const imgDirPath = "stories/2017-12-15-cretan-sunsets";
class CretanSunsetsStory extends React.Component {
constructor() {
super();
}
render() {
return (
<StoryPage logoDirPath={imgDirPath}
logoPrefix="wide"
logoNumber="11"
altLogo="Sunset in Crete"
title="Cretan Sunsets"
author="Dan"
location="Crete, Greece"
tags="travel, island, Greece">
<StoryIntro>
We traveled to Crete this summer. The island is like a paradise, it has everything
tourists like us want: great beaches, nice mountains, great towns. We were really
impressed by the island, but one thing is for sure:
<br/><br/>
<blockquote>In Crete we've seen the best sunsets of our lives!</blockquote>
Let's try to recreate our trip and remember all of our favorite places here.
</StoryIntro>
<StoryTextBlock title="Chania">
<a href="https://en.wikipedia.org/wiki/Chania" trget="_blank">Chania</a> is
a must visit place. It's the second largest city in Crete, it has a nice shopping
area in the Old Town and a harbor with a Lighthouse. From the pier we were able
to watch an amazing sunset.
</StoryTextBlock>
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="01"
alt="Sunset, Lighthouse in Chania"/>
<PostImageResp dirPath={imgDirPath} number="02"
alt="Chania Port"/>
<PostImageResp dirPath={imgDirPath} number="03"
alt="Buildings in Chania"/>
</StoryImages>
<FullImageResp dirPath={imgDirPath}
prefix="image"
number="04"
alt="Chania Pier and Lighthouse" />
<StoryImages>
<TwoPostImageResp dirPath={imgDirPath}
number1="05"
alt1="Chania Horse Carrige"
number2="06"
alt2="Old Man in Crete" />
<TwoPostImageResp dirPath={imgDirPath}
number1="07"
alt1="Cretan Painter"
number2="08"
alt2="Cretan Painter" />
<PostImageResp dirPath={imgDirPath} number="09"
alt="Watching the Chania sunset"/>
</StoryImages>
<StoryTextBlock title="Heraklion">
Heraklion is the largest city in Crete and the administrative capital of the
island. The first thing we visited here was the Knossos Palace. Then we
headed to the center of the city and had lunch at a nice restaurant
near the Koules Fortress, near the seaside. We also liked the Saint Minas Cathedral and
the Church of Saint Titus.
</StoryTextBlock>
<FullImageResp dirPath={imgDirPath}
prefix="wide"
number="05"
alt="Knossos Palace" />
<StoryImages>
<TwoPostImageResp dirPath={imgDirPath}
number1="11"
alt1="Knossos Palace"
number2="12"
alt2="Knossos Palace" />
<PostImageResp dirPath={imgDirPath} number="13"
alt="Koules Fortress"/>
<TwoPostImageResp dirPath={imgDirPath}
number1="14"
alt1="Saint Minas Cathedral, Heraklion"
number2="15"
alt2="Church of Saint Titus, Heraklion" />
</StoryImages>
<StoryTextBlock title="Rethimno">
Rethimno is one of the smaller but really animated cities. There are lots
of really nice sea food restaurants here. In the center there is a fortress.
We witnessed an amazing sunset from the fortress.
</StoryTextBlock>
<FullImageResp dirPath={imgDirPath}
prefix="wide"
number="06"
alt="Rethimno Lighthouse, Crete" />
<StoryTextBlock title="Agia Galini">
Agia Galini is another nice town. It has a nice harbor with lots of
ships and a pier. It's been built on hill which gives an interesting
view when photographed from the pier.
</StoryTextBlock>
<FullImageResp dirPath={imgDirPath}
prefix="image"
number="17"
alt="Agia Galini, Crete" />
<StoryTextBlock title="Seitan Limania Beach">
It was really challenging to reach to the Seitan Limania Beach. You have to
get down on a rocky way which looks really dangerous. We put some effort into
getting there. But it's totally worth it.
The water and sand are amazing and you can see goats doing jumps on the rocks around.
</StoryTextBlock>
<FullImageResp dirPath={imgDirPath}
prefix="image"
number="18"
alt="Mountains in Crete" />
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="19"
alt="The Road to Seitan Limania Beach"/>
<PostImageResp dirPath={imgDirPath} number="20"
alt="Seitan Limania Beach, Crete"/>
<PostImageResp dirPath={imgDirPath} number="21"
alt="Seitan Limania Beach, Crete"/>
<PostImageResp dirPath={imgDirPath} number="22"
alt="Cretan Goat"/>
</StoryImages>
<StoryTextBlock title="Matala Beach">
The Matala Beach is really accessible, there is a big parking lot right next to it.
I did some snorkeling here and I've seen lots of colorful fishes. The view with the
yellow rocks is amazing.
</StoryTextBlock>
<FullImageResp dirPath={imgDirPath}
prefix="image"
number="23"
alt="Matala Beach, Crete" />
<StoryTextBlock title="Praveli Beach">
Praveli Beach is special because it has lots of palm trees, directly on the beach.
So you can enjoy the shade during the really hot summer days.
</StoryTextBlock>
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="24"
alt="Preveli Beach, Crete"/>
</StoryImages>
<StoryTextBlock title="Balos Beach">
The Balos beach is one of the most amazing places I've seen! The lagoon
has white sand and turquoise water. The contrast is amazing!
<br/><br/>
Getting to the beach was not easy, we had to go on a rocky way. Another way
of getting there is by boat. I still recommend the rocky path, as from the hills
there, you get the best view of the lagoon.
</StoryTextBlock>
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="25" alt="Rocky Landscape, Crete" />
</StoryImages>
<FullImageResp dirPath={imgDirPath}
prefix="image"
number="26"
alt="Balos Beach, Crete" />
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="27" alt="Balos Beach, Crete" />
</StoryImages>
<StoryTextBlock title="Other Beaches">
Crete has lots of other beaches: small ones, cute one, rocky ones, also
private ones.
</StoryTextBlock>
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="28" alt="Cretan Beach" />
<PostImageResp dirPath={imgDirPath} number="29" alt="Royal Blue Resort Beach, Crete" />
<PostImageResp dirPath={imgDirPath} number="30" alt="Cretan Beach" />
<PostImageResp dirPath={imgDirPath} number="31" alt="Rocky Cretan Beach" />
<PostImageResp dirPath={imgDirPath} number="32" alt="Cretan Beach and Mountains" />
</StoryImages>
<StoryTextBlock title="The Mountains">
Crete is not only about beaches, and urban landscapes: it has amazing
hills and mountains as well. The combination and richness of colors is
just breathtaking.
<br/><br/>
<blockquote>
Seeing both mountains and sea in the same place makes me think about
how paradise can look like!
</blockquote>
</StoryTextBlock>
<FullImageResp dirPath={imgDirPath}
prefix="image"
number="33"
alt="Crete Sea and Mountains" />
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="34" alt="Mountains in Crete" />
<PostImageResp dirPath={imgDirPath} number="35" alt="Cretan Mountains" />
<PostImageResp dirPath={imgDirPath} number="36" alt="Sunset in Cretan Mountains" />
</StoryImages>
<StoryTextBlock title="The Sunsets">
I kept the best for the end. The sunsets! Every evening we watched one
and every time it got better! Enjoy!
</StoryTextBlock>
<FullImageResp dirPath={imgDirPath}
prefix="image"
number="37"
alt="Sunset, Crete" />
<StoryImages>
<PostImageResp dirPath={imgDirPath} number="38" alt="Cretan sunset" />
<PostImageResp dirPath={imgDirPath} number="39" alt="Fortezza Castle, Rethimno" />
<PostImageResp dirPath={imgDirPath} number="40" alt="Santa Maria delle Grazie, Milan" />
</StoryImages>
</StoryPage>);
}
}
export default CretanSunsetsStory;
|
imports/ui/pages/profile.js | irvinlim/free4all | import { Meteor } from 'meteor/meteor';
import React from 'react';
import ProfileComponent from '../containers/profile/profile';
export class Profile extends React.Component {
render() {
return (
<div id="page-profile" className="page-container profile" style={{ overflow: "hidden" }}>
<div className="container">
<div className="flex-row nopad" style={{ padding: "0 0 5px" }}>
<div className="col col-xs-12">
<ProfileComponent userId={ this.props.params.userId ? this.props.params.userId : Meteor.userId() } />
</div>
</div>
</div>
</div>
);
}
}
|
src/components/user/auth/login/Login.js | huyhoangtb/reactjs | /**
* Created by Peter Hoang Nguyen on 3/31/2017.
*/
import * as css from './stylesheet.scss';
import React from 'react'
import {Field, reduxForm} from 'redux-form'
import InputText from 'components/forms/elements/input-text';
import CheckBox from 'components/forms/elements/check-box';
import AuthPanel from 'components/user/auth/AuthPanel';
import RaisedButton from 'material-ui/RaisedButton';
import {injectI18N, t, t1, t2, t3, t4} from "utils/I18nUtils";
/**
* Created by Peter Hoang Nguyen
* Email: [email protected]
* Tel: 0966298666
* created date 30/03/2017
**/
class LoginForm extends React.Component {
constructor(props) {
super(props);
this.state = {}
}
render() {
let {intl} =this.props;
return (
<AuthPanel>
<div className="ui-auth-panel">
<div className="ui-auth-header">
<a className="active">
{ t1(intl, 'Login')}
<span>/</span>
</a>
<a>
<span>/</span>
{ t1(intl, 'Logout') }
</a>
</div>
<InputText fullWidth={true} name="username" label={ t1(intl, 'Username')}/>
<InputText fullWidth={true} name="password" label={ t1(intl, 'Password')}/>
<div className="remember-me-panel">
<CheckBox labelStyle={{color: "#9d9d9d"}}
iconStyle={{fill: "#9d9d9d"}}
name="remember_me" label={ t1(intl, 'remember_me')}/>
</div>
<div className="ui-button-group clearfix center-block">
<div className="pull-left">
<RaisedButton label={t1(intl,"Đăng nhập")} className="button" primary={true} />
</div>
<div className="pull-right">
<a className="forgot-password"> { t1(intl, 'Forgot password?') }</a>
</div>
<div className="login-by-another-tools">
HaHAaaaaaaaaa
</div>
</div>
</div>
</AuthPanel>
);
}
}
export default reduxForm({
form: 'LoginForm', // a unique identifier for this form
})(injectI18N(LoginForm))
|
public/products/src/components/UI.js | dolchi21/open-prices | import React from 'react'
export function List(props){
return <div {...props} className="list-group"></div>
}
export function ListItem(props){
return <div {...props} className="list-group-item"></div>
}
|
components/ui/dropdown/dropdown.js | bannik/hole | import React from 'react';
import ReactDOM from 'react-dom';
class Dropdown extends React.Component{
constructor(props){
super(props);
let selectedItem = props.selectedItem ? props.selectedItem : null;
this.state = {
active: false,
items: [],
selectedItem: selectedItem,
hcontent: {}
};
}
// Toggle functionality of the dropdown menu
_handleDropToggle(){
if(this.state.active){
this.setState({
active: false
});
}else {
this.setState({
active: true
});
}
}
// Handles sending the data of the selected menu item back to
// parent component
_handleClick(data){
if(this.props.onSelect){
this.props.onSelect(data);
}
}
componentWillMount(){
let onClick;
let self = this;
for (var i = 0; i < this.props.items.length; i++) {
// Setting onClick for each item of the menu
if(self.props.items[i].exData){
onClick = self.onClick.bind(self, self.props.items[i].exData);
}else{
onClick = self.onClick.bind(self, self.props.items[i].label);
}
// Checks if you have setted an image and a holder in your array
// and sets them as header
if(self.props.items[i].type === 'image' && !self.state.hcontent.image){
self.setState({
hcontent:{
image: self.props.items[i].src
}
});
}if(self.props.items[i].type === 'holder' && !self.state.hcontent.holder) {
self.setState({
hcontent:{
holder: self.props.items[i].label
}
});
}
// Here We take all the items of the
if(self.props.items[i].type === 'item' && self.props.items[i].label != self.state.selectedItem){
self.state.items.push(<li onClick={onClick} key={i}>{self.props.items[i].label}</li>);
}
}
}
componentDidMount(){
if(!this.state.selectedItem && !this.state.hcontent.image && !this.state.hcontent.holder){
this.setState({
selectedItem: this.state.items[0].props.children
});
}
}
render(){
let hcontent = {};
let items = [];
let holder = [];
let styles = this.props.styles ? this.props.styles : {};
let onClick;
let menuClass = ['dropContent', this.props.className];
let arrowClass = this.state.active ? 'fa fa-angle-up' : 'fa fa-angle-down';
if(this.state.active){
menuClass.push('dropActive');
}
menuClass = menuClass.join(' ');
for (var i = 0; i < this.state.items.length; i++) {
if(this.state.items[i].props.children != this.state.selectedItem){
items.push(this.state.items[i]);
}
}
// Here we check if there was something in our array to add to header of
// the menu
if(!this.state.selectedItem){
if(!this.state.hcontent.holder && this.state.hcontent.image || this.props.hidden === "holder"){
let imageClass = 'fa ' + this.state.hcontent.image;
holder = [
<span style={styles.title ? styles.title : {}}>
<i className={imageClass}/>
</span>
];
}else if(!this.state.hcontent.image && this.state.hcontent.holder || this.props.hidden === "image"){
holder = [
<span style={styles.title ? styles.title : {}}>
{this.state.hcontent['holder']}
</span>
];
}else if(this.state.hcontent.image && this.state.hcontent.holder && !this.props.hidden){
let imageClass = 'fa ' + hcontent.image;
holder = [
<span>
<i className={imageClass}/>{hcontent['holder']}
</span>
];
}
}else{
holder = [
<span>
{this.state.selectedItem}
</span>
];
}
return(
<div className="dropWrap">
{this.props.label ? (
<span className="dropLabel">{this.props.label}</span>
): null}
<div onMouseEnter={this.onDropToggle} onMouseLeave={this.onDropToggle} className="dropdown">
<div className="dropHead">
{holder}
<i className={arrowClass}></i>
</div>
<ul className={menuClass} style={styles.body ? styles.body : {}}>
{items}
</ul>
</div>
</div>
);
}
}
module.exports = Dropdown;
|
web/src/js/components/Search/ErrorBoundarySearchResults.js | gladly-team/tab | import React from 'react'
import logger from 'js/utils/logger'
import { getUrlParameters } from 'js/utils/utils'
import SearchResultErrorMessage from 'js/components/Search/SearchResultErrorMessage'
class ErrorBoundary extends React.Component {
constructor(props) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError(error) {
return { hasError: true }
}
componentDidCatch(error, info) {
logger.error(error)
}
render() {
if (this.state.hasError) {
const query = getUrlParameters().q || null
return <SearchResultErrorMessage query={query} />
}
return this.props.children
}
}
ErrorBoundary.propTypes = {}
ErrorBoundary.defaultProps = {}
export default ErrorBoundary
|
Study/Udemy Docker and Kubernetes/Section09/deployment-09-finished/frontend/src/components/UI/Card.js | tarsoqueiroz/Docker | import React from 'react';
import './Card.css';
function Card(props) {
return <div className='card'>{props.children}</div>;
}
export default Card;
|
docs/app/Examples/elements/Button/Types/ButtonExampleLabeled.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Button } from 'semantic-ui-react'
const ButtonExampleLabeled = () => (
<div>
<Button
content='Like'
icon='heart'
label={{ as: 'a', basic: true, content: '2,048' }}
labelPosition='right'
/>
<Button
content='Like'
icon='heart'
label={{ as: 'a', basic: true, pointing: 'right', content: '2,048' }}
labelPosition='left'
/>
<Button
icon='fork'
label={{ as: 'a', basic: true, content: '2,048' }}
labelPosition='left'
/>
</div>
)
export default ButtonExampleLabeled
|
src/svg-icons/editor/short-text.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorShortText = (props) => (
<SvgIcon {...props}>
<path d="M4 9h16v2H4zm0 4h10v2H4z"/>
</SvgIcon>
);
EditorShortText = pure(EditorShortText);
EditorShortText.displayName = 'EditorShortText';
EditorShortText.muiName = 'SvgIcon';
export default EditorShortText;
|
src/redux/utils/createDevToolsWindow.js | mleonard87/merknera-ui | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import DevTools from '../../containers/DevToolsWindow';
export default function createDevToolsWindow (store) {
const win = window.open(
null,
'redux-devtools', // give it a name so it reuses the same window
`width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no`
);
// reload in case it's reusing the same window with the old content
win.location.reload();
// wait a little bit for it to reload, then render
setTimeout(() => {
// Wait for the reload to prevent:
// "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element."
win.document.write('<div id="react-devtools-root"></div>');
win.document.body.style.margin = '0';
ReactDOM.render(
<Provider store={store}>
<DevTools />
</Provider>
, win.document.getElementById('react-devtools-root')
);
}, 10);
}
|
app/client/modules/App/__tests__/Components/Footer.spec.js | nittmurugan/finddriver | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import { Footer } from '../../components/Footer/Footer';
test('renders the footer properly', t => {
const wrapper = shallow(
<Footer />
);
t.is(wrapper.find('p').length, 2);
t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.');
});
|
src/components/loading/LoadingHome/LoadingHome.js | CtrHellenicStudies/Commentary | import React from 'react';
const LoadingHome = () => (
<div className="loading home">
<div className="loading-mock home-filler home-filler-header" />
<div className="content primary">
<section className="header cover fullscreen parallax">
<div
className="container v-align-transform wow fadeIn"
data-wow-duration="1s"
data-wow-delay="0.1s"
>
<div className="grid inner">
<div className="center-content">
<div className="site-title-wrap">
<div className="loading-mock home-filler home-filler-1" />
<div className="loading-mock home-filler home-filler-1" />
<div className="loading-mock home-filler home-filler-2" />
<div>
<div className="loading-mock home-filler home-filler-3" />
<div className="loading-mock home-filler home-filler-3" />
</div>
</div>
</div>
</div>
</div>
</section>
</div>
<div className="loading-mock home-filler home-filler-scroll-down" />
</div>
);
export default LoadingHome;
|
es/components/MediaList/Row.js | welovekpop/uwave-web-welovekpop.club | import _jsx from "@babel/runtime/helpers/builtin/jsx";
import _assertThisInitialized from "@babel/runtime/helpers/builtin/assertThisInitialized";
import _inheritsLoose from "@babel/runtime/helpers/builtin/inheritsLoose";
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { DragSource } from 'react-dnd';
import { getEmptyImage } from 'react-dnd-html5-backend';
import formatDuration from 'format-duration';
import { MEDIA } from '../../constants/DDItemTypes';
import MediaLoadingIndicator from './MediaLoadingIndicator';
import MediaThumbnail from './MediaThumbnail';
import Actions from './Actions';
var inSelection = function inSelection(selection, media) {
return selection.some(function (item) {
return item._id === media._id;
});
};
var mediaSource = {
beginDrag: function beginDrag(_ref) {
var selection = _ref.selection,
media = _ref.media;
return {
media: inSelection(selection, media) ? selection : [media]
};
}
};
var collect = function collect(connect) {
return {
connectDragSource: connect.dragSource(),
connectDragPreview: connect.dragPreview()
};
};
var enhance = DragSource(MEDIA, mediaSource, collect);
var _ref2 =
/*#__PURE__*/
_jsx(MediaLoadingIndicator, {
className: "MediaListRow-loader"
});
var Row =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(Row, _React$Component);
function Row() {
var _temp, _this;
for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return (_temp = _this = _React$Component.call.apply(_React$Component, [this].concat(args)) || this, _this.handleKeyPress = function (event) {
if (event.code === 'Space') {
_this.props.onClick();
}
}, _this.handleDoubleClick = function () {
_this.props.onOpenPreviewMediaDialog(_this.props.media);
}, _temp) || _assertThisInitialized(_this);
}
var _proto = Row.prototype;
_proto.componentDidMount = function componentDidMount() {
this.props.connectDragPreview(getEmptyImage());
};
_proto.render = function render() {
var _this$props = this.props,
className = _this$props.className,
media = _this$props.media,
selection = _this$props.selection,
selected = _this$props.selected,
connectDragSource = _this$props.connectDragSource,
makeActions = _this$props.makeActions,
onClick = _this$props.onClick;
var selectedClass = selected ? 'is-selected' : '';
var loadingClass = media.loading ? 'is-loading' : '';
var duration = 'start' in media // playlist item
? media.end - media.start // search result
: media.duration;
return connectDragSource( // Bit uneasy about this, but turning the entire row into a button seems
// wrong as well! Since we nest media action <button>s inside it, too.
//
// eslint-disable-next-line jsx-a11y/no-static-element-interactions
_jsx("div", {
className: cx('MediaListRow', className, selectedClass, loadingClass),
onDoubleClick: this.handleDoubleClick,
onKeyPress: this.handleKeyPress,
onClick: onClick
}, void 0, media.loading ? _ref2 : _jsx(MediaThumbnail, {
url: media.thumbnail
}), _jsx("div", {
className: "MediaListRow-artist",
title: media.artist
}, void 0, media.artist), _jsx("div", {
className: "MediaListRow-title",
title: media.title
}, void 0, media.title), _jsx("div", {
className: "MediaListRow-duration"
}, void 0, formatDuration(duration * 1000)), _jsx(Actions, {
className: cx('MediaListRow-actions', selectedClass),
selection: selection,
media: media,
makeActions: makeActions
})));
};
return Row;
}(React.Component);
Row.defaultProps = {
selected: false
};
Row.propTypes = process.env.NODE_ENV !== "production" ? {
className: PropTypes.string,
connectDragSource: PropTypes.func.isRequired,
connectDragPreview: PropTypes.func.isRequired,
media: PropTypes.object,
selected: PropTypes.bool,
selection: PropTypes.array,
onOpenPreviewMediaDialog: PropTypes.func,
onClick: PropTypes.func,
makeActions: PropTypes.func
} : {};
export default enhance(Row);
//# sourceMappingURL=Row.js.map
|
fields/components/columns/IdColumn.js | suryagh/keystone | import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var IdColumn = React.createClass({
displayName: 'IdColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
list: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.id;
if (!value) return null;
return (
<ItemsTableValue padded interior title={value} href={Keystone.adminPath + '/' + this.props.list.path + '/' + value} field={this.props.col.type}>
{value}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = IdColumn;
|
src/components/App.js | franciskim722/crypy | import React from 'react';
import PropTypes from 'prop-types';
import { Switch, NavLink, Route } from 'react-router-dom';
import LandingPage from '../containers/Landing/LandingPage';
import RegisterPage from '../containers/Auth/RegisterPage';
import HomePage from '../containers/Home/HomePage';
import LoginPage from '../containers/Login/LoginPage';
import PortfolioPage from '../containers/Portfolio/PortfolioPage';
import { MuiThemeProvider } from 'material-ui/styles';
const isLoggedIn = () => {
if(!sessionStorage.jwt_token){
return browserHistory.push('/login');
}
};
class App extends React.Component {
render() {
return (
<MuiThemeProvider>
<div className={"crypy-app"}>
<Switch>
<Route exact path="/" component={LandingPage}/>
<Route path="login" component={LoginPage}/>
<Route path="register" component={RegisterPage}/>
<Route path="home" component={HomePage} onEnter={isLoggedIn}/>
<Route path="portfolio" component={PortfolioPage}/>
</Switch>
</div>
</MuiThemeProvider>
);
}
}
App.propTypes = {
children: PropTypes.element
};
export default App;
|
app/containers/Steps/Thanks/index.js | nypl-spacetime/where | /* global __CONFIG__ */
import React from 'react'
import { connect } from 'react-redux'
import { createSelector } from 'reselect'
import Button from 'components/Button'
import Flex from 'components/Flex'
import {
selectLoggedIn
} from 'containers/App/selectors'
import { TextStep, Animal, TimerBarContainer, TimerBar } from '../styles'
const configAnimals = __CONFIG__.animals
const animalsByUuid = {}
configAnimals.forEach((animal) => {
animalsByUuid[animal.uuid] = animal
})
function requireAll (r) {
return r.keys().map((filename) => {
const uuid = filename.match(/\.\/(.*)\.small\.png$/)[1]
return {
src: r(filename),
...animalsByUuid[uuid]
}
})
}
const animals = requireAll(require.context('images/public-domain-animals/', false, /\.small\.png$/))
export class Step extends React.Component {
intitialTimeout = null
timerBarTimeout = null
constructor (props) {
super(props)
this.state = {
timerStarted: false,
duration: 4,
animal: this.randomAnimal()
}
}
randomAnimal () {
const animal = animals[Math.floor(Math.random() * animals.length)]
return {
src: animal.src,
name: animal.name
}
}
render () {
const timerBarStyle = {
width: this.state.timerStarted ? '100%' : 0,
transitionDuration: `${this.state.duration}s`
}
let oauthQuestion
if (!this.props.loggedIn) {
oauthQuestion = (
<p>
To save your score, please log in with Google, Facebook, Twitter or GitHub.
</p>
)
}
const thanks = `The ${this.state.animal.name} says thanks!`
return (
<TextStep>
<div>
<h2>Thank you!</h2>
<p>
Your submission has been recorded.
</p>
{oauthQuestion}
<Animal src={this.state.animal.src} alt={thanks} />
</div>
<div>
<TimerBarContainer>
<TimerBar style={timerBarStyle} />
</TimerBarContainer>
<Flex justifyContent='flex-end'>
<Button type='submit' onClick={this.next.bind(this)}>Next image</Button>
</Flex>
</div>
</TextStep>
)
}
componentDidMount () {
this.intitialTimeout = setTimeout(() => {
this.setState({
timerStarted: true
})
// Initialize timer which proceeds to first step
this.timerBarTimeout = setTimeout(this.next.bind(this), this.state.duration * 1000)
}, 100)
}
next () {
if (this.intitialTimeout) {
clearTimeout(this.intitialTimeout)
}
if (this.timerBarTimeout) {
clearTimeout(this.timerBarTimeout)
}
this.props.next()
}
}
export default connect(createSelector(
selectLoggedIn(),
(loggedIn) => ({
loggedIn
})
))(Step)
|
js/components/list/basic-list.js | soltrinox/MarketAuth.ReactNative |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, List, ListItem, Text } from 'native-base';
import styles from './styles';
const {
replaceAt,
} = actions;
class NHBasicList extends Component {
static propTypes = {
replaceAt: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
replaceAt(route) {
this.props.replaceAt('basicList', { key: route }, this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Button transparent onPress={() => this.replaceAt('list')}>
<Icon name="ios-arrow-back" />
</Button>
<Title>Basic List</Title>
</Header>
<Content>
<List>
<ListItem >
<Text>Simon Mignolet</Text>
</ListItem>
<ListItem>
<Text>Nathaniel Clyne</Text>
</ListItem>
<ListItem>
<Text>Dejan Lovren</Text>
</ListItem>
<ListItem>
<Text>Mama Sakho</Text>
</ListItem>
<ListItem>
<Text>Alberto Moreno</Text>
</ListItem>
<ListItem>
<Text>Emre Can</Text>
</ListItem>
<ListItem>
<Text>Joe Allen</Text>
</ListItem>
<ListItem>
<Text>Phil Coutinho</Text>
</ListItem>
</List>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
replaceAt: (routeKey, route, key) => dispatch(replaceAt(routeKey, route, key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
});
export default connect(mapStateToProps, bindAction)(NHBasicList);
|
local-cli/templates/HelloNavigation/views/chat/ChatListScreen.js | Maxwell2022/react-native | 'use strict';
import React, { Component } from 'react';
import {
ActivityIndicator,
Image,
ListView,
Platform,
StyleSheet,
View,
} from 'react-native';
import ListItem from '../../components/ListItem';
import Backend from '../../lib/Backend';
export default class ChatListScreen extends Component {
static navigationOptions = {
title: 'Chats',
header: {
visible: Platform.OS === 'ios',
},
tabBar: {
icon: ({ tintColor }) => (
<Image
// Using react-native-vector-icons works here too
source={require('./chat-icon.png')}
style={[styles.icon, {tintColor: tintColor}]}
/>
),
},
}
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
isLoading: true,
dataSource: ds,
};
}
async componentDidMount() {
const chatList = await Backend.fetchChatList();
this.setState((prevState) => ({
dataSource: prevState.dataSource.cloneWithRows(chatList),
isLoading: false,
}));
}
// Binding the function so it can be passed to ListView below
// and 'this' works properly inside renderRow
renderRow = (name) => {
return (
<ListItem
label={name}
onPress={() => {
// Start fetching in parallel with animating
this.props.navigation.navigate('Chat', {
name: name,
});
}}
/>
);
}
render() {
if (this.state.isLoading) {
return (
<View style={styles.loadingScreen}>
<ActivityIndicator />
</View>
);
}
return (
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderRow}
style={styles.listView}
/>
);
}
}
const styles = StyleSheet.create({
loadingScreen: {
backgroundColor: 'white',
paddingTop: 8,
flex: 1,
},
listView: {
backgroundColor: 'white',
},
icon: {
width: 30,
height: 26,
},
});
|
js/src/dapps/dappreg.js | jesuscript/parity | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React from 'react';
import ReactDOM from 'react-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import Application from './dappreg/Application';
import '../../assets/fonts/Roboto/font.css';
import '../../assets/fonts/RobotoMono/font.css';
import './style.css';
ReactDOM.render(
<Application />,
document.querySelector('#container')
);
|
react-app/src/components/Results.js | tanykim/swimmers-history | import React, { Component } from 'react';
import scrollToComponent from 'react-scroll-to-component';
import Countries from '../data/countries.json';
class ResultsComponent extends Component {
scroll() {
//scroll to the result when a swimmer is selected
scrollToComponent(this.refs.results, {
offset: 0,
align: 'top',
duration: 400
});
}
componentDidMount() {
this.scroll();
}
componentWillReceiveProps(nextProps) {
if (nextProps.clicked && this.props.clickedIds !== nextProps.clickedIds) {
this.scroll();
}
}
render() {
const { clickedIds, sharedRaces, clickedObjs, sharedRacesWinner } = this.props;
return (<div className="results" id="results">
<div className="remove-all" ref="results">
<a onClick={() => this.props.removeAllAthletes()}>
<span className="typcn typcn-delete"></span> Remove all swimmers
</a>
</div>
<div className="table-wrapper">
{ sharedRaces.length === 0 && <div className="no-races">
These { clickedIds.length } swimmers did not compete with each other
</div> }
<table className="race-athlete-table">
{ sharedRaces.length > 0 && <thead>
<tr className="thead">
<th colSpan="2" className="result-summary">
<span className="result-number">{ clickedIds.length }</span> swimmer{ clickedIds.length > 1 ? 's' : '' } & <span className="result-number">{ sharedRaces.length }</span> race{ sharedRaces.length > 1 ? 's' : '' }
</th>
{ sharedRaces.map((r, i) => (<th className="record" key={i}>
<span className="race-meet">{ r.split('-')[0].slice(1) }</span>
{ r.split('-')[1].slice(1) }
<span className="dash">-</span>
{ r.split('-')[4].slice(1) }
</th>))}
</tr>
</thead> }
<tbody>
{ clickedObjs.map((a, i) => (<tr key={i}>
<td className="close-icon">
<a onClick={() => this.props.removeAthlete(a)}>
<span className="typcn typcn-delete"></span>
</a>
</td>
<td className="athlete">
<div>{ a.name }</div>
<div>
<span className={`${Countries[a.country] ? `fl-icon flag-icon-${Countries[a.country].toLowerCase()}`: ''}`} />
<span className="country">{ a.country }</span>
</div>
</td>
{ sharedRaces.map((r, j) => (<td key={j} className={`record${sharedRacesWinner && sharedRacesWinner[j].indexOf(i) > -1 ? ' winner' : ''}`}>
<div className="place-wrapper">
<span className={`place place${a.records[r].place}`}>
{ a.records[r].place }
</span>
</div>
<div className="swimtime">{ a.records[r].swimtime }</div>
</td>))}
</tr>))}
</tbody>
</table>
</div>
</div>);
}
}
export default ResultsComponent; |
src/modules/items/containers/ItemEmbedContainer/ItemEmbedContainer.js | CtrHellenicStudies/Commentary | import React from 'react';
import PropTypes from 'prop-types';
import { compose } from 'react-apollo';
import _ from 'underscore';
import ItemEmbed from '../../components/ItemEmbed';
import itemDetailQuery from '../../graphql/queries/detail';
class ItemEmbedContainer extends React.Component {
render() {
let item = null;
console.log(this.props);
console.log(this.props);
console.log(this.props);
console.log(this.props);
if (
this.props.itemDetailQuery
&& this.props.itemDetailQuery.ORPHEUS_project
) {
item = this.props.itemDetailQuery.ORPHEUS_project.item;
}
if (!item) {
return null;
}
return (
<ItemEmbed
{...item}
/>
);
}
}
ItemEmbedContainer.propTypes = {
itemDetailQuery: PropTypes.object,
};
export default compose(
itemDetailQuery,
)(ItemEmbedContainer);
|
frontend-admin/src/pendingNum/index.js | OptimusCrime/youkok2 | import React from 'react';
import ReactDOM from 'react-dom';
import { fetchAdminPendingNumRest } from "./api";
export const run = () => {
// This is lazy
fetchAdminPendingNumRest()
.then(response => response.json())
.then(response => {
ReactDOM.render((
`${response.num}`
), document.getElementById('admin-pending-num')
);
})
};
|
src/PilotPhase.js | qiubit/wason-selection-parallel | import _ from 'lodash';
import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import Markdown from 'react-markdown';
import './PilotPhase.css';
import SelectionExercise from './SelectionExercise';
class PilotPhase extends Component {
constructor(props) {
super(props);
const experimentExercisesMap = props.settings.pilotPhase.experimentExercises;
let experimentExercisesArr = [];
for (var key in experimentExercisesMap) {
if (Object.prototype.hasOwnProperty.call(experimentExercisesMap, key))
experimentExercisesArr.push(experimentExercisesMap[key]);
}
this.state = {
helpMessageShown: true,
experimentFinished: false,
trainingExerciseShown: false,
experimentExerciseInProgress: false,
currentExercise: -1,
experimentExercises: _.shuffle(experimentExercisesArr),
experimentStats: [],
};
this.onTrainingExerciseFinish = this.onTrainingExerciseFinish.bind(this);
this.onCloseHelpMsg = this.onCloseHelpMsg.bind(this);
this.onExerciseFinish = this.onExerciseFinish.bind(this);
this.prepareExerciseStats = this.prepareExerciseStats.bind(this);
}
onTrainingExerciseFinish(stats) {
this.setState({
trainingExerciseShown: false,
experimentExerciseInProgress: true,
currentExercise: 0,
});
}
onExerciseFinish(stats) {
let experimentStats = this.state.experimentStats.slice();
experimentStats.push(this.prepareExerciseStats(stats));
this.setState({ experimentStats: experimentStats });
if (this.state.currentExercise + 1 < this.state.experimentExercises.length) {
this.setState({ currentExercise: this.state.currentExercise + 1 });
} else {
this.setState({ experimentExerciseInProgress: false });
if (this.props.onPhaseFinish) {
this.props.onPhaseFinish(experimentStats);
}
}
}
prepareExerciseStats(exerciseStats) {
// First calculate chosen cards (and their order based on choice time)
let chosenCardsTstamps = new Map();
let cardsToChoose = ["P", "nP", "Q", "nQ"];
let chosenCards = [];
for (var i = 0; i < cardsToChoose.length; i++) {
let currentCard = cardsToChoose[i];
if (exerciseStats[currentCard]) {
let cardClickTstamps = exerciseStats[currentCard + "tstamps"]
chosenCardsTstamps.set(currentCard, cardClickTstamps[cardClickTstamps.length-1]);
chosenCards.push(currentCard);
}
}
chosenCards.sort(function(cardA, cardB) {
return chosenCardsTstamps.get(cardA) - chosenCardsTstamps.get(cardB);
});
let finalChoiceTstamp = chosenCardsTstamps.get(chosenCards[chosenCards.length-1]);
// Now calculate finalStats object
let finalStats = {
phase: "pilot",
chosenCards: chosenCards,
cardsOrder: exerciseStats.cardsOrder,
completionTime: exerciseStats.completionTime,
solvingTime: exerciseStats.solvingTime,
exerciseRelativeId: exerciseStats.exerciseRelativeId,
exerciseAbsoluteId: exerciseStats.exerciseAbsoluteId,
Ptstamps: exerciseStats.Ptstamps,
nPtstamps: exerciseStats.nPtstamps,
Qtstamps: exerciseStats.Qtstamps,
nQtstamps: exerciseStats.nQtstamps,
finalChoiceTstamp: finalChoiceTstamp,
}
return finalStats;
}
onCloseHelpMsg() {
this.setState({ helpMessageShown: false, trainingExerciseShown: true });
}
render() {
let helpMsg = "";
if (this.props.settings.pilotPhase && this.props.settings.pilotPhase.helpMsg)
helpMsg = this.props.settings.pilotPhase.helpMsg;
return (
<div>
{this.state.helpMessageShown &&
<div className="display">
<Markdown source={helpMsg}/>
<Button className="pull-right" bsSize="large" onClick={this.onCloseHelpMsg}>Next</Button>
</div>
}
{this.state.trainingExerciseShown &&
<SelectionExercise
exerciseRelativeId={1}
exerciseAbsoluteId={this.props.settings.pilotPhase.trainingExercise}
exercises={this.props.exercises}
onExerciseFinish={this.onTrainingExerciseFinish}
trainingMode={true}
/>
}
{this.state.experimentExerciseInProgress &&
<SelectionExercise
key={this.state.currentExercise}
exerciseRelativeId={this.state.currentExercise + 1}
exerciseAbsoluteId={this.state.experimentExercises[this.state.currentExercise]}
exercises={this.props.exercises}
onExerciseFinish={this.onExerciseFinish}
/>
}
</div>
);
}
}
PilotPhase.propTypes = {
exercises: React.PropTypes.array.isRequired,
settings: React.PropTypes.object.isRequired,
onPhaseFinish: React.PropTypes.func,
};
export default PilotPhase;
|
shared/containers/Common/ContentContainer.js | kizzlebot/music_dev | import React from 'react';
import {NavLeft, NavRight} from '../../components/Common/Content';
export default class ContentContainer extends React.Component{
render(){
return (
<section className={'content'}>
<NavLeft {...this.props} />
<div className={'content__middle'}>
{this.props.children}
</div>
<NavRight {...this.props}/>
</section>
)
}
}
|
src/components/posts_new.js | monsteronfire/redux-learning-blog | import React from 'react';
import { Field, reduxForm } from 'redux-form';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import { createPost } from '../actions';
class PostsNew extends React.Component {
renderField(field) {
const className = `form-group ${field.meta.touched && field.meta.error ? 'has-danger' : ''}`
return (
<div className={className}>
<label>{field.label}</label>
<input
className='form-control'
type='text'
{...field.input}
/>
<div className='text-help'>
{field.meta.touched ? field.meta.error : ''}
</div>
</div>
);
}
onSubmit(values) {
this.props.createPost(values, () => {
this.props.history.push('/');
});
}
render() {
const { handleSubmit } = this.props;
return (
<form onSubmit={handleSubmit(this.onSubmit.bind(this))} className='posts-new'>
<Field
label='Title'
name='title'
component={this.renderField}
/>
<Field
label='Categories'
name='categories'
component={this.renderField}
/>
<Field
label='Post Content'
name='content'
component={this.renderField}
/>
<button type='submit' className='btn btn-primary'>Submit</button>
<Link to='/' className='btn btn-danger'>Cancel</Link>
</form>
);
}
}
function validate(values) {
const errors = {};
if (!values.title) {
errors.title = "Enter a title";
}
if (!values.categories) {
errors.categories = "Enter categories";
}
if (!values.content) {
errors.content = "Enter content";
}
return errors;
}
export default reduxForm({
validate: validate,
form: 'PostsNewForm'
})(
connect(null, { createPost })(PostsNew)
);
|
client/modules/core/components/options_dropdown/options_dropdown.js | bompi88/grand-view | // //////////////////////////////////////////////////////////////////////////////
// Document Table Dropdown Component
// //////////////////////////////////////////////////////////////////////////////
//
// Copyright 2015 Concept
//
// Licensed under the Apache License, Version 2.0 (the 'License');
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an 'AS IS' BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// //////////////////////////////////////////////////////////////////////////////
import React from 'react';
class OptionsDropdown extends React.Component {
handleClick(func, e) {
const f = this.props[func];
f(e);
}
renderItem(item, index) {
if (item.divider) {
return <li key={index} role="presentation" className="divider" />;
}
const disabled = item.disabled;
return (
<li role="presentation" key={index} className={disabled ? 'disabled' : null}>
<a
role="menuitem"
tabIndex="-1"
href="#"
onClick={disabled ? null : this.handleClick.bind(this, item.func)}
>
<span className={item.icon} aria-hidden="true" /> {item.label}
</a>
</li>
);
}
renderItems() {
const { items } = this.props;
return items.map((item, index) => this.renderItem(item, index));
}
render() {
return (
<div className="pull-right btn-group" role="group">
<button
aria-expanded="false"
className="btn btn-default dropdown-toggle menu-button"
data-toggle="dropdown"
type="button"
>
<span className="glyphicon glyphicon-option-horizontal" />
</button>
<ul className="dropdown-menu" role="menu">
{this.renderItems()}
</ul>
</div>
);
}
}
OptionsDropdown.propTypes = {
items: React.PropTypes.arrayOf(React.PropTypes.shape({
label: React.PropTypes.string,
icon: React.PropTypes.string,
func: React.PropTypes.string,
disabledOn: React.PropTypes.string,
divider: React.PropTypes.bool,
})),
};
export default OptionsDropdown;
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.