path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/app/homelessness/HomelessnessData.js | cityofasheville/simplicity2 | import React from 'react';
import { browserHistory } from 'react-router';
import PageHeader from '../../shared/PageHeader';
import ButtonGroup from '../../shared/ButtonGroup';
import Button from '../../shared/Button';
import Icon from '../../shared/Icon';
import { IM_BED } from '../../shared/iconConstants';
const HomelessnessData = () => (
<div>
<PageHeader h1="Understand the homelessness data" icon={<Icon path={IM_BED} size={50} />}>
<ButtonGroup alignment="">
<Button onClick={browserHistory.goBack}>Back</Button>
</ButtonGroup>
</PageHeader>
<div className="row">
<div className="col-sm-12">
<h2>Overview page data sources</h2>
<p>
The primary source of information for the Homelessness Data Dashboard is the North Carolina Homeless Management Information System (NC HMIS). The Asheville-Buncombe Continuum of Care participates in this statewide database to measure the needs of homeless persons, coordinate their care and report the outcome of these services.
</p>
<p>
Several local non-profits maintain service records of homeless clients in NC HMIS. These records include emergency shelter stays, housing placement data, and basic demographic details, as well as, sensitive personal information like social security number, date of birth, and diagnosed medical conditions. Agencies are not allowed to collect or share this information without client consent and the data is essential to providing services. For this reason, only aggregate data is reported on this dashboard.
</p>
<p>
Not all homeless service programs in the community use NC HMIS, so the data on this dashboard is currently limited to the organizations who use the database. Additional data and links to other organizations will be included in future dashboard updates with the goal of understanding homelessness and help people secure safe and affordable housing.
</p>
<hr />
<h2>Veterans page data sources</h2>
<p>The primary source of information for the Homelessness Data Dashboard’s Veteran Page is the Veteran By-Name List. The Veteran By-Name List is a comprehensive list of homeless Veterans in the community.</p>
<p>The list ensures that service providers and key partners are working together to achieve ‘Functional Zero’ and have identified all Veterans who require housing and/or services in the community. This list is populated through information from street and VA outreach, the Homeless Management Information System (HMIS), community shelters, VA-funded programs including GPD providers, and any other provider who may work with Veterans experiencing homelessness. The Asheville-Buncombe Continuum of Care participates in the statewide database (NC HMIS) to measure the needs of homeless persons, coordinate their care and report the outcome of these services.</p>
<p>Agencies are not allowed to collect or share this information without client consent and the data is essential to providing services. For this reason, only aggregate data is reported on this dashboard.</p>
</div>
</div>
</div>
);
export default HomelessnessData;
|
src/app/templates/InfoIconsBandBase.js | lili668668/lili668668.github.io | import React from 'react'
import PropTypes from 'prop-types'
function InfoIconsBandBase (props) {
const {
children,
frameComponent: Frame
} = props
return (
<Frame>
{children}
</Frame>
)
}
InfoIconsBandBase.propTypes = {
children: PropTypes.any,
frameComponent: PropTypes.oneOfType([PropTypes.func, PropTypes.object]).isRequired
}
InfoIconsBandBase.components = {
frameComponent: 'Frame'
}
export default InfoIconsBandBase
|
src/layouts/PageLayout/PageLayout.js | roslaneshellanoo/react-redux-tutorial | import React from 'react'
import PropTypes from 'prop-types'
import Header from '../../components/Header'
import BranchSelect from '../../components/BranchSelect'
import './PageLayout.scss'
class PageLayout extends React.Component {
constructor (props) {
super(props)
this.state = {
branchState: '1'
}
}
render () {
return (
<div className='wrap-app'>
<Header />
<div className='container text-center'>
<div className='page-layout__viewport'>
{this.props.children}
</div>
</div>
</div>
)
}
}
PageLayout.propTypes = {
children: PropTypes.node
}
export default PageLayout
|
src/svg-icons/action/done-all.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDoneAll = (props) => (
<SvgIcon {...props}>
<path d="M18 7l-1.41-1.41-6.34 6.34 1.41 1.41L18 7zm4.24-1.41L11.66 16.17 7.48 12l-1.41 1.41L11.66 19l12-12-1.42-1.41zM.41 13.41L6 19l1.41-1.41L1.83 12 .41 13.41z"/>
</SvgIcon>
);
ActionDoneAll = pure(ActionDoneAll);
ActionDoneAll.displayName = 'ActionDoneAll';
ActionDoneAll.muiName = 'SvgIcon';
export default ActionDoneAll;
|
src/components/BundleItem.js | akonwi/bundles | import React from 'react'
import {StyleSheet, css} from 'aphrodite'
import BundleLink from './BundleLink'
import * as BundleStore from '../bundle-store'
import {DeleteBundle, AddLink} from '../commands'
const styles = StyleSheet.create({
bundles: {
borderBottom: '.1rem solid grey',
padding: '.4rem'
},
anchors: {
margin: '0 .2rem'
},
conrols: {
float: 'right'
},
bundleRow: {
display: 'flex',
justifyContent: 'space-between'
},
icons: {
fontFamily: 'Material Icons',
fontWeight: 'normal',
fontStyle: 'normal',
fontSize: '1rem',
display: 'inline-block',
width: '1em',
height: '1em',
lineHeight: 1,
textTransform: 'none',
letterSpacing: 'normal',
wordWrap: 'normal',
WebkitFontSmoothing: 'antialiased',/* Support for all WebKit browsers. */
textRendering: 'optimizeLegibility'/* Support for Safari and Chrome. */
},
h4Style: {
margin: '0 .2rem',
':hover': {
cursor: 'pointer'
}
},
title: {
display: 'flex',
alignItems: 'center'
},
triangle: {
content: "",
borderColor: 'transparent #111',
borderStyle: 'solid',
borderWidth: '0.35em 0 0.35em 0.45em',
height: 0,
width: 0
},
down: {
transform: 'rotate(90deg)'
},
links: {
paddingLeft: '1.5rem',
transition: 'all .2s ease-in-out',
maxHeight: 0,
width: '100%',
overflowX: 'hidden',
},
'links.open': {
maxHeight: '100%',
overflowY: 'scroll'
}
})
export default React.createClass({
getInitialState() {
return { open: false }
},
openLinks(e) {
this.props.links.forEach(({url}) => { chrome.tabs.create({url}) })
},
addLink(e) {
chrome.tabs.getSelected(null, ({url, title}) => {
let existing = this.props.links.find(link => url === link.url && title === link.title)
if (existing === undefined)
this.props.dispatch(AddLink({id: this.props.id, title, url}))
})
},
deleteBundle(e) { this.props.dispatch(DeleteBundle({id: this.props.id})) },
toggle(e) {
this.setState({open: !this.state.open})
},
render() {
const linksClasses = css(
styles.links,
this.state.open && styles['links.open']
)
const triangleClasses = css(
styles.triangle,
this.state.open && styles.down
)
const anchorsStyles = css(styles.anchors)
const icons = css(styles.icons)
const bundleLinks = this.props.links.map(({url, title}) => {
return <BundleLink url={url} title={title}/>
})
return (
<li className={css(styles.bundles)}>
<div className={css(styles.bundleRow)}>
<div className={css(styles.title)}>
<div id='triangle' className={triangleClasses}></div>
<h4 className={css(styles.h4Style)} onClick={this.toggle}>{ this.props.name }</h4>
</div>
<div>
<div id='controls' className={css(styles.conrols)}>
<a href='#' className={anchorsStyles} title='Open all'>
<i className={icons} onClick={this.openLinks}>launch</i>
</a>
<a href='#' className={anchorsStyles} title='Add current page'>
<i className={icons} onClick={this.addLink}>add</i>
</a>
<a href='#' className={anchorsStyles} title='Edit'>
<i className={icons} onClick={() => this.props.toggleEditing({name: this.props.name, id: this.props.id})}>edit</i>
</a>
<a href='#' className={anchorsStyles} title='Delete'>
<i className={icons} onClick={this.deleteBundle}>delete</i>
</a>
</div>
</div>
</div>
<ul id='links' className={linksClasses}>
{ bundleLinks }
</ul>
</li>
)
}
})
|
examples/src/components/Creatable.js | hannahsquier/react-select | import React from 'react';
import Select from 'react-select';
var CreatableDemo = React.createClass({
displayName: 'CreatableDemo',
propTypes: {
hint: React.PropTypes.string,
label: React.PropTypes.string
},
getInitialState () {
return {
multi: true,
multiValue: [],
options: [
{ value: 'R', label: 'Red' },
{ value: 'G', label: 'Green' },
{ value: 'B', label: 'Blue' }
],
value: undefined
};
},
handleOnChange (value) {
const { multi } = this.state;
if (multi) {
this.setState({ multiValue: value });
} else {
this.setState({ value });
}
},
render () {
const { multi, multiValue, options, value } = this.state;
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select.Creatable
multi={multi}
options={options}
onChange={this.handleOnChange}
value={multi ? multiValue : value}
/>
<div className="hint">{this.props.hint}</div>
<div className="checkbox-list">
<label className="checkbox">
<input
type="radio"
className="checkbox-control"
checked={multi}
onChange={() => this.setState({ multi: true })}
/>
<span className="checkbox-label">Multiselect</span>
</label>
<label className="checkbox">
<input
type="radio"
className="checkbox-control"
checked={!multi}
onChange={() => this.setState({ multi: false })}
/>
<span className="checkbox-label">Single Value</span>
</label>
</div>
</div>
);
}
});
module.exports = CreatableDemo;
|
examples/js/sort/custom-caret-sort-table.js | powerhome/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
function getCaret(direction) {
if (direction === 'asc') {
return (
<span> up</span>
);
}
if (direction === 'desc') {
return (
<span> down</span>
);
}
return (
<span> up/down</span>
);
}
export default class CustomSortTable extends React.Component {
render() {
return (
<BootstrapTable data={ products }>
<TableHeaderColumn dataField='id' dataSort={ true } isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' dataSort={ true } caretRender = { getCaret } >Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price' dataSort={ true } >Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
example/examples/AnimatedPriceMarker.js | pjamrozowicz/react-native-maps | import React from 'react';
import PropTypes from 'prop-types';
import {
StyleSheet,
Text,
Animated,
} from 'react-native';
class AnimatedPriceMarker extends React.Component {
render() {
const { amount, selected, style } = this.props;
const background = selected.interpolate({
inputRange: [0, 1],
outputRange: ['#FF5A5F', '#4da2ab'],
});
const border = selected.interpolate({
inputRange: [0, 1],
outputRange: ['#D23F44', '#007a87'],
});
return (
<Animated.View style={[styles.container, style]}>
<Animated.View
style={[
styles.bubble,
{
backgroundColor: background,
borderColor: border,
},
]}
>
<Text style={styles.dollar}>$</Text>
<Text style={styles.amount}>{amount}</Text>
</Animated.View>
<Animated.View
style={[styles.arrowBorder, { borderTopColor: border }]}
/>
<Animated.View
style={[styles.arrow, { borderTopColor: background }]}
/>
</Animated.View>
);
}
}
AnimatedPriceMarker.propTypes = {
amount: PropTypes.number.isRequired,
selected: PropTypes.object.isRequired,
style: PropTypes.any,
};
const styles = StyleSheet.create({
container: {
flexDirection: 'column',
alignSelf: 'flex-start',
},
bubble: {
flex: 0,
flexDirection: 'row',
alignSelf: 'flex-start',
backgroundColor: '#FF5A5F',
paddingVertical: 2,
paddingHorizontal: 4,
borderRadius: 3,
borderColor: '#D23F44',
borderWidth: 0.5,
},
dollar: {
color: '#fff',
fontSize: 10,
},
amount: {
color: '#fff',
fontSize: 13,
},
arrow: {
backgroundColor: 'transparent',
borderColor: 'transparent',
borderWidth: 4,
borderTopColor: '#FF5A5F',
alignSelf: 'center',
marginTop: -9,
},
arrowBorder: {
backgroundColor: 'transparent',
borderColor: 'transparent',
borderWidth: 4,
borderTopColor: '#D23F44',
alignSelf: 'center',
marginTop: -0.5,
},
selectedBubble: {
backgroundColor: '#4da2ab',
borderColor: '#007a87',
},
selectedArrow: {
borderTopColor: '#4da2ab',
},
selectedArrowBorder: {
borderTopColor: '#007a87',
},
});
module.exports = AnimatedPriceMarker;
|
examples/huge-apps/app.js | joeyates/react-router | import React from 'react';
import { Router } from 'react-router';
import stubbedCourses from './stubs/COURSES';
var rootRoute = {
component: 'div',
childRoutes: [{
path: '/',
component: require('./components/App'),
childRoutes: [
require('./routes/Calendar'),
require('./routes/Course'),
require('./routes/Grades'),
require('./routes/Messages'),
require('./routes/Profile'),
]
}]
};
React.render(
<Router routes={rootRoute} />,
document.getElementById('example')
);
// I've unrolled the recursive directory loop that is happening above to get a
// better idea of just what this huge-apps Router looks like
//
// import { Route } from 'react-router'
// import App from './components/App';
// import Course from './routes/Course/components/Course';
// import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar';
// import Announcements from './routes/Course/routes/Announcements/components/Announcements';
// import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement';
// import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar';
// import Assignments from './routes/Course/routes/Assignments/components/Assignments';
// import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment';
// import CourseGrades from './routes/Course/routes/Grades/components/Grades';
// import Calendar from './routes/Calendar/components/Calendar';
// import Grades from './routes/Grades/components/Grades';
// import Messages from './routes/Messages/components/Messages';
// React.render(
// <Router>
// <Route path="/" component={App}>
// <Route path="calendar" component={Calendar} />
// <Route path="course/:courseId" component={Course}>
// <Route path="announcements" components={{
// sidebar: AnnouncementsSidebar,
// main: Announcements
// }}>
// <Route path=":announcementId" component={Announcement} />
// </Route>
// <Route path="assignments" components={{
// sidebar: AssignmentsSidebar,
// main: Assignments
// }}>
// <Route path=":assignmentId" component={Assignment} />
// </Route>
// <Route path="grades" component={CourseGrades} />
// </Route>
// <Route path="grades" component={Grades} />
// <Route path="messages" component={Messages} />
// <Route path="profile" component={Calendar} />
// </Route>
// </Router>,
// document.getElementById('example')
// );
|
src/app/components/fetch_demo/fetch.js | ROZ32/react-example | import React from 'react';
import image from '../../images/cloud-upload-download-data-transfer.svg';
import Collapsible from '../collapsible_demo/collapsible';
import '../../styles/basic_demos.scss';
import '../../styles/collapsible_demo.scss';
// const Contact = (props) => {
// return (
// <div>test {props.test}</div>
// );
// };
// Contact.propTypes = {
// title: PropTypes.string,
// prop: PropTypes.node,
// };
export class Fetch extends React.Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
contacts: [],
error: ''
};
}
componentWillMount() {
const contacts = localStorage.getItem('contacts');
if(contacts) {
this.setState({
contacts: JSON.parse(contacts),
isLoading: false
})
}
}
componentWillUpdate(nextProps, nextState) {
localStorage.setItem('contacts', JSON.stringify(nextState.contacts));
localStorage.setItem('contactsDate', JSON.stringify(Date.now()));
}
componentDidMount() {
const contactsDate = localStorage.getItem('contactsDate');
if (contactsDate) {
let dateDiff = Math.round((Date.now() - parseInt(contactsDate)) / (1000 * 60));
if(dateDiff > 15) this.fetchData();
} else {
this.fetchData();
}
}
fetchData() {
this.setState({
contacts: [],
isLoading: true
});
fetch(
'https://randomuser.me/api/?results=3&nat=us,dk,fr,gb'
).then(response => response.json()
).then(parsedJson => parsedJson.results.map(contact => (
{
name: `${contact.name.title}. ${contact.name.first} ${contact.name.last}`,
username: contact.login.username,
email: contact.email,
location: `${contact.location.street}, ${contact.location.city}`
}
)
)
).then(contacts => {
this.setState({
contacts,
isLoading: false,
error: ''
});
}).catch(error => {
this.setState({
error
})
});
}
render() {
const {isLoading, contacts, error} = this.state;
return (
<div>
<header>
<img src={image} />
<h1>Contacts Information <button className="btn btn-danger" onClick={() => {this.fetchData()}}>Fetch Now</button></h1>
</header>
<div className={`content ${isLoading ? 'is-loading' : ''}`}>
{
error !== '' && <p className="text-danger">{error}</p>
}
<div id="accordion" role="tablist" aria-multiselectable="true">
{
!isLoading && contacts.length > 0 ? contacts.map((contact, key) => {
return (
<Collapsible key={key}
title={contact.name}>
<ul>
<li>{`Username: ${contact.username}`}</li>
<li>{`Email: ${contact.email}`}</li>
<li>{`Location: ${contact.location}`}</li>
</ul>
</Collapsible>
)
}) : null
}
</div>
{
isLoading &&
<div className="loader">
<div className="icon"></div>
</div>
}
</div>
</div>
);
}
}
|
src/scenes/userProfile/components/ProfileHeader.js | niekert/soundify | import React from 'react';
import { number, string, func, bool } from 'prop-types';
import abbreviateNumber from 'number-abbreviate';
import styled from 'styled-components';
import { prop } from 'styled-tools';
import { H1, Paragraph } from 'components/styles/Typography';
import FollowButton from './FollowButton';
import ProfileDropdown from './ProfileDropdown';
const Wrapper = styled.div`
padding: ${prop('theme.spacing.space3')} 10px;
display: flex;
`;
const UserAvatar = styled.div`
border-radius: 50%;
height: 150px;
width: 150px;
background-size: cover;
background-image: url(${prop('url')});
flex-shrink: 0;
`;
const InfoContainer = styled.div`
padding: 20px;
display: flex;
flex-direction: column;
justify-content: space-between;
`;
const Description = styled(Paragraph)`
max-height: 75px;
display: -webkit-box;
overflow: hidden;
overflow: hidden;
text-overflow: ellipsis;
-webkit-line-clamp: 3;
-webkit-box-orient: vertical;
`;
const UserRow = styled.div`display: flex;`;
const Stat = styled.li`margin-right: 40px;`;
const Bold = styled.span`font-weight: 600;`;
const StatsContainer = styled.ul`display: flex;`;
function ProfileHeader({
username,
isFollowing,
userId,
toggleFollowing,
followersCount,
followingCount,
toggleSidebarPin,
isPinned,
fullName, // eslint-disable-line
avatarUrl,
city, // eslint-disable-line
tracksCount,
description,
}) {
return (
<Wrapper>
<UserAvatar url={avatarUrl} />
<InfoContainer>
<UserRow>
<H1>
{username}
</H1>
<FollowButton
toggleFollowing={toggleFollowing}
userId={userId}
isFollowing={isFollowing}
/>
<ProfileDropdown
userId={userId}
userName={username}
isPinned={isPinned}
togglePinSidebar={toggleSidebarPin}
/>
</UserRow>
<StatsContainer>
<Stat>
<Bold>{tracksCount}</Bold> tracks
</Stat>
<Stat>
<Bold>{abbreviateNumber(followersCount)}</Bold> followers
</Stat>
<Stat>
<Bold>{abbreviateNumber(followingCount)}</Bold> following
</Stat>
</StatsContainer>
<Description>
{description}
</Description>
</InfoContainer>
</Wrapper>
);
}
ProfileHeader.propTypes = {
username: string.isRequired,
toggleFollowing: func.isRequired,
toggleSidebarPin: func.isRequired,
isFollowing: bool,
isPinned: bool,
userId: number.isRequired,
followersCount: number.isRequired,
followingCount: number.isRequired,
tracksCount: number.isRequired,
fullName: string,
avatarUrl: string,
city: string,
description: string,
};
export default ProfileHeader;
|
liferay-gsearch-workspace/modules/gsearch-react-web/src/main/resources/META-INF/resources/lib/containers/Sort/SortField.js | peerkar/liferay-gsearch | import React from 'react'
import config from 'react-global-configuration';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { Dropdown } from "semantic-ui-react";
import { ConfigKeys } from '../../constants/configkeys';
import { RequestParameterNames } from '../../constants/requestparameters';
import { search } from '../../store/actions/search';
import { getItems, getSortField } from '../../store/reducers/search';
/**
* Redux mapping.
*
* @param {Object} dispatch
*/
function mapDispatchToProps(dispatch) {
const getSearchResults = search.request;
return bindActionCreators({ getSearchResults }, dispatch);
}
/**
* Redux mapping.
*
* @param {Object} state
*/
function mapStateToProps(state, ownProps) {
return {
shouldRender: (getItems(state) && getItems(state).length),
sortField: getSortField(state)
};
}
/**
* Sort field component.
*/
class SortField extends React.Component {
constructor(props) {
super(props);
// Component configuration.
this.sortFieldConfig = config.get(ConfigKeys.SORT);
// Bind functions to this instance.
this.handleItemSelect = this.handleItemSelect.bind(this);
}
/**
* Handle item selection event.
*
* @param {Object} event
* @param {String} value
*/
handleItemSelect(event, { value }) {
this.props.getSearchResults({ [RequestParameterNames.SORT_FIELD]: value })
}
render() {
const { shouldRender, sortField } = this.props;
if (!shouldRender) {
return null;
}
return (
<div className="gsearch-sort-field-menu">
<span className="gsearch-label">Sort by: {' '}</span>
<Dropdown
button
defaultValue={this.sortFieldConfig.defaultValue}
floating
labeled
onChange={this.handleItemSelect}
options={this.sortFieldConfig.options}
value={sortField}
/>
</div>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(SortField);
|
src/js/components/RegisterFields/InputSelectText/InputSelectText.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Input from '../../ui/Input/Input.js';
import Chip from '../../ui/Chip/Chip.js';
import styles from './InputSelectText.scss';
export default class InputSelectText extends Component {
static propTypes = {
placeholder : PropTypes.string,
options : PropTypes.array,
selectedLabel : PropTypes.string,
chipsColor : PropTypes.oneOf(['purple', 'blue', 'pink', 'green']),
onChangeHandler: PropTypes.func,
onClickHandler : PropTypes.func,
selectedValues : PropTypes.array,
};
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleClick = this.handleClick.bind(this);
let selected = [];
if (props.selectedValues) {
selected = props.selectedValues;
}
this.state = {
selected: selected,
suggested: []
}
}
handleChange(text) {
const {options} = this.props;
const {selected} = this.state;
this.setState({suggested: options.filter(
option => text && option.text
&& option.text.toLowerCase().indexOf(text.toLowerCase()) !== -1
&& !selected.some(item => item.id === option.id)
)});
if (this.props.onChangeHandler) {
this.props.onChangeHandler(text);
}
}
handleClick(id) {
const {options} = this.props;
const {selected} = this.state;
let newSelected = selected.slice(0);
const index = selected.findIndex(option => option.value === id);
if (index !== -1) {
newSelected.splice(index, 1);
} else {
const option = options.find(option => option.id === id);
const newOption = {
value: option.id,
image: null,
};
// newSelected.push(options.find(option => option.id === id));
newSelected.push(newOption);
}
this.setState({selected: newSelected, suggested: []});
this.refs["input"].clearValue();
if (this.props.onClickHandler) {
this.props.onClickHandler(newSelected.map(option => option.value));
}
}
render() {
const {placeholder, options, selectedLabel, chipsColor, selectedValues} = this.props;
const {selected, suggested} = this.state;
return (
<div className={styles.inputSelectText}>
<Input ref="input" placeholder={placeholder} searchIcon={true} size={'small'} onChange={this.handleChange} doNotScroll={true}/>
{suggested.map((item, index) =>
<div key={index} className={styles.suggestedChip}>
<Chip onClickHandler={this.handleClick}
text={item.text}
value={item.id}
color={chipsColor}
/>
</div>
)}
{selected.length > 0 ?
<div className={styles.selectedLabel + " small"}>{selectedLabel}</div> : null
}
{options.length > 0 ?
selected.map((item, index) =>
<div key={index} className={styles.selectedChip}>
<Chip onClickHandler={this.handleClick}
text={options.find(x => x.id === item.value).text}
value={options.find(x => x.id === item.value).id}
color={chipsColor}
selected={true}
/>
</div>
)
: null
}
</div>
);
}
} |
src/svg-icons/image/filter-hdr.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilterHdr = (props) => (
<SvgIcon {...props}>
<path d="M14 6l-3.75 5 2.85 3.8-1.6 1.2C9.81 13.75 7 10 7 10l-6 8h22L14 6z"/>
</SvgIcon>
);
ImageFilterHdr = pure(ImageFilterHdr);
ImageFilterHdr.displayName = 'ImageFilterHdr';
ImageFilterHdr.muiName = 'SvgIcon';
export default ImageFilterHdr;
|
Veo/node_modules/react-native/Libraries/Utilities/throwOnWrongReactAPI.js | JGMorgan/Veo | /**
* 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 throwOnWrongReactAPI
* @flow
*/
'use strict';
function throwOnWrongReactAPI(key: string) {
throw new Error(
`Seems you're trying to access 'ReactNative.${key}' from the 'react-native' package. Perhaps you meant to access 'React.${key}' from the 'react' package instead?
For example, instead of:
import React, { Component, View } from 'react-native';
You should now do:
import React, { Component } from 'react';
import { View } from 'react-native';
Check the release notes on how to upgrade your code - https://github.com/facebook/react-native/releases/tag/v0.25.1
`);
}
module.exports = throwOnWrongReactAPI;
|
client/app.js | Troop18/mytroop.site | "use strict";
import 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import Relay from 'react-relay';
import injectTapEventPlugin from 'react-tap-event-plugin';
import {Router, Route, IndexRoute} from 'react-router';
import {RelayRouter} from 'react-router-relay';
import createBrowserHistory from 'history/lib/createBrowserHistory'
import RootQuery from './queries/root-query';
import TroopQuery from './queries/troop-query';
import CurrentUserQuery from './queries/current-user-query';
import AppLayout from './components/AppLayout';
import App from './components/App';
import Troop from './components/Troop';
import Login from './components/Login';
import Profile from './components/Profile';
//Needed for onTouchTap
//Can go away when react 1.0 release
//Check this repo:
//https://github.com/zilverline/react-tap-event-plugin
injectTapEventPlugin();
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
credentials: 'same-origin',
})
);
setTimeout(() => {
ReactDOM.render(
<RelayRouter
history={createBrowserHistory()}>
<Route path='/' component={AppLayout}>
<IndexRoute
component={App}
queries={RootQuery} />
<Route queries={RootQuery} component={App}>
<Route path='login'
component={Login}
queries={RootQuery} />
</Route>
<Route
path='troop/:id'
component={Troop}
queries={TroopQuery} />
<Route
path='profile'
component={Profile}
queries={CurrentUserQuery} />
</Route>
</RelayRouter>,
document.getElementById('root')
);
}, 0);
|
src/app.js | mDinner/musicansAssistant | import React from 'react';
import ReactDOM from 'react-dom';
import { IndexRoute, Route } from 'react-router';
import injectTapEventPlugin from 'react-tap-event-plugin';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import ReactStormpath, { Router, HomeRoute, LoginRoute, LogoutRoute, AuthenticatedRoute } from 'react-stormpath';
import { MasterPage, IndexPage, LoginPage, RegisterPage, ResetPasswordPage, VerifyEmailPage, ProfilePage, MemberHomePage } from './pages';
ReactStormpath.init();
ReactDOM.render(
<Router history={createBrowserHistory()}>
<HomeRoute path='/' component={MasterPage}>
<IndexRoute component={IndexPage} />
<LoginRoute path='/login' component={LoginPage} />
<LogoutRoute path='/logout' />
<Route path='/verify' component={VerifyEmailPage} />
<Route path='/register' component={RegisterPage} />
<Route path='/forgot' component={ResetPasswordPage} />
<AuthenticatedRoute>
<HomeRoute path='/profile' component={ProfilePage} />
<Route path='/member' component={MemberHomePage} />
</AuthenticatedRoute>
</HomeRoute>
</Router>,
document.getElementById('app-container')
); |
src/Form.js | change-soft8/cs-validation | import React from 'react';
import Utils from './js/utils';
import Button from './button';
export default class Form extends React.Component{
static propTypes = {
config: React.PropTypes.object.isRequired
};
componentDidMount(){
// 页面new时,表单验证初始化
this.initFormValidation();
}
componentDidUpdate(){
// 页面重构时,表单验证初始化
this.initFormValidation();
}
// ========================================= 自定义方法 =================================================
/**
* [initForm 表单数据初始化]
* @return {[type]} [description]
*/
initForm(){
let datas = {};
let checkValue = [];
let pname;
let len = this.refs.form && this.refs.form.length || 0;
for (let i = 0; i < len; i++) {
let input = this.refs.form[i];
let name = input.name;
let val = input.value;
let data;
if(name){
if(input.type == 'checkbox'){
if(pname != name){
checkValue = [];
pname = name;
}
if(input.checked){
checkValue.push(val);
data = {
[name]: checkValue.toString()
};
}else{
continue;
}
}else if (input.type == 'radio') {
checkValue = [];
if(input.checked){
data = {
[name]: val
};
}else{
continue;
}
}else{
checkValue = [];
data = {
[name]: val
};
}
Object.assign(datas, data);
}
}
// 绑定回车事件
this.keyEnter(this.refs.form, ()=>{
this.validator.form();
});
return datas;
}
/**
* [initFormValidation 表单验证初始化]
* @return {[type]} [description]
*/
initFormValidation(){
// 实体 和 操作
if(this.props.entityOper){
// 判断能不能直接发布事件
this.ifUseConfig = true;
let entityOper = this.props.entityOper;
// 获取实体
this.entity = entityOper.split('-')[0];
// 获取操作
this.operation = entityOper.split('-')[1];
}else{
// 判断能不能直接发布事件
this.ifUseConfig = false;
}
const config = this.props.config;
// 初始化验证规则
// 获取实体的 所有 验证规则
let rulesAll = config.rules;
// 获取实体的 所有 报错信息
let msgAll = config.messages;
// 表单初始数据
let datas = this.initForm();
// 获得表单的数据key
let filter = Object.keys(datas);
// 根据表单数据key获取 所需 验证
let rules = Utils.getKeyObj(rulesAll, filter);
// 根据表单数据key获取 所需 报错信息
let messages = Utils.getKeyObj(msgAll, filter);
// 验证实体
let validator = {
// 获得焦点报错信息清除
focusCleanup: true,
// 提交表单验证时不自动聚焦错误表单组件
focusInvalid: false,
// 验证规则
rules,
// 验证报错信息
messages,
// 失去焦点自动验证
onfocusout: (element) => {
element.value = element.value.trim();
$(element).valid();
},
// 验证通过
submitHandler: (form, event) => {
console.log("Submitted!");
this.formSubmit();
},
// 验证错误
errorPlacement: (error, element) => {
// 指定错误信息位置
// 如果是radio或checkbox或select
if (element.is(':radio') || element.is(':checkbox') || element.is('select')) {
// 将错误信息添加当前元素的父结点后面
error.appendTo(element.parent());
} else if(element.is(':input') && element.parent().hasClass('input-group')){
// 将错误信息添加当前元素的父结点后面
error.insertAfter(element.parent());
}else {
// 将错误信息直接添加在后面
error.insertAfter(element);
}
}
};
// 初始化验证
this.validator = $(this.refs.form).validate(validator);
}
/**
* [formSubmit 表单验证成功之后的操作]
* @return {[type]} [description]
*/
async formSubmit(){
// 如果按钮 disabled装填,点击无效果
if(this.refs.button.state.disabled){
return false;
}
// 获取表单数据
let datas = this.initForm();
// 按钮 disabled
console.log('disabled');
this.refs.button.setState({disabled: true});
if(this.ifUseConfig){
// 表单数据操作
await this.formOperation(datas);
}else{
await this.props.callback(datas);
}
// 按钮 enabled
console.log('enabled');
this.refs.button.setState({disabled: false});
// 表单重置
this.setState({});
}
/**
* [formOperation 表单数据接口操作]
* @return {[type]} [description]
*/
formOperation(datas){
// return new Promise((resolve, reject) => {
// setTimeout(() => {
// console.log('ajax ajax...');
// resolve();
// }, 5000);
// });
// debugger;
return window.db[entity][this.operation](datas);
}
/**
* [keyEnter description]
* @param {[type]} select [表单选择器]
* @param {[type]} func [回调方法]
* @return {[type]} [description]
*/
keyEnter(select, func) {
let uuid = Utils.uuid();
$(select).attr('id', uuid);
let ips = $(select).find('input:checked,input:selected,[name][type!=checkbox][type!=radio]');
let l = ips.length;
if (l < 1) {
ips = $(select);
l = 1;
}
ips.each(function(i) {
let end = false;
if (i == ips.length - 1) end = true;
$(this).attr({
'enter_index': i,
'enter_end': end
});
$(this).keyup((event) => {
if (13 == event.keyCode) {
let e = $(this).attr('enter_end');
let a = $(this).attr('enter_finish');
let ei = parseInt($(this).attr('enter_index'));
if (a || e == 'true') {
func();
} else {
$('#' + uuid + ' [enter_index="' + (ei + 1) + '"]')[0].focus();
}
}
});
});
}
/**
* [clear 表单验证清除]
* @return {[type]} [description]
*/
clear(){
this.validator.resetForm();
}
render(){
const {disabled, ...others} = this.props;
return(
<form ref="form" key={Utils.getKey('form')}>
{React.Children.map(this.props.children, (element, i) => {
// 设置 disabled 属性
if(element){
let props = Object.assign({}, element.props);
props.disabled = props.enabled ? '' : (props.disabled || disabled);
if(props.type == 'submit'){
const {...othersb} = props;
return (<Button ref="button" {...othersb} />);
}else{
let ele = Object.assign({}, element);
ele.props = props;
return ele;
}
}
})}
</form>
)
}
} |
src/scenes/home/landing/emailSignup/emailSignup.js | NestorSegura/operationcode_frontend | import React, { Component } from 'react';
import Section from 'shared/components/section/section';
import axios from 'axios';
import PropTypes from 'prop-types';
import config from 'config/environment';
import Form from 'shared/components/form/form';
import FormEmail from 'shared/components/form/formEmail/formEmail';
import FormButton from 'shared/components/form/formButton/formButton';
import styles from './emailSignup.css';
class EmailSignup extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
emailValid: false,
success: false,
isLoading: false,
};
}
onEmailChange = (value, valid) => {
this.setState({ email: value.toLowerCase(), emailValid: valid });
};
/* eslint-disable */
handleOnClick = e => {
e.preventDefault();
this.setState({ isLoading: true });
if (this.isFormValid()) {
const { email } = this.state;
axios
.post(`${config.backendUrl}/email_list_recipients`, `email=${email}`)
.then(() => {
this.setState({
isLoading: false,
success: true,
});
this.props.sendNotification('success', 'Success', 'Welcome to our E-mail list!');
})
.catch(() => {
this.props.sendNotification(
'error',
'Error',
'Please try signing up again. Contact one of our staff if this problem persists.'
);
this.setState({ isLoading: false });
});
} else {
this.setState({ error: 'Missing required field(s)', isLoading: false });
}
};
isFormValid = () => this.state.emailValid;
render() {
return (
<Section
title="Sign Up For Our Mailing List"
className={styles.emailSignup}
theme="white"
headingLines={false}
>
<p className={styles.emailSignupText}>
Keep up to date with everything Operation Code. We promise we won't spam you or sell
your information.
</p>
<Form className={styles.emailListForm}>
<div className={styles.emailInput}>
<FormEmail id="email" placeholder="Email" onChange={this.onEmailChange} />
</div>
{this.state.error && (
<ul className={styles.errorList}>
There was an error joining the mailing list:
<li className={styles.errorMessage}>{this.state.error}</li>
</ul>
)}
{this.state.isLoading ? (
<FormButton className={styles.joinButton} text="Loading..." disabled theme="grey" />
) : (
<FormButton
className={styles.joinButton}
text="Sign Up"
onClick={this.handleOnClick}
theme="blue"
/>
)}
</Form>
</Section>
);
}
}
EmailSignup.propTypes = {
sendNotification: PropTypes.func.isRequired,
};
export default EmailSignup;
|
src/scripts/components/button.js | uncinc/layer-notes | 'use strict';
/* Setup ==================================================================== */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
/* Component ==================================================================== */
class Button extends Component {
static defaultProps = {
class: 'ln-btn-secondary', // the primary button
text: '', // the text
icon: null, // the icon. > you can chouse one form the ../../images/sprite his name will be a class
title: '',
onclick: () => {}
};
/**
* RENDER
*/
renderInnerButton = () => {
if (this.props.icon !== null) {
return <span className={`ln-icon ${this.props.icon}`} />;
}
return this.props.text;
};
// render the page
render = () => {
return (
<button
className={`ln-btn ${this.props.class}`}
title={this.props.title}
onClick={this.props.onclick}
>
{this.renderInnerButton()}
</button>
);
};
}
/* Export Component ==================================================================== */
export default Button; |
website/src/components/common/SliderRange/index.js | jwngr/notreda.me | import React from 'react';
import Slider from 'rc-slider';
import PropTypes from 'prop-types';
import {darken, lighten} from 'polished';
import {SliderWrapper} from './index.styles';
import theme from '../../../resources/theme.json';
import 'rc-slider/assets/index.css';
const createSliderWithTooltip = Slider.createSliderWithTooltip;
const Range = createSliderWithTooltip(Slider.Range);
class SliderRange extends React.Component {
constructor(props) {
super(props);
const {min, max, initialValue} = props;
this.state = {
value: initialValue || [min, max],
};
}
handleChange = (value) => {
const {onChange} = this.props;
onChange && onChange(value);
this.setState({
value,
});
};
render() {
const {min, max, width = 200, widthSm = 140, className} = this.props;
return (
<SliderWrapper className={className} width={width} widthSm={widthSm}>
<Range
min={min}
max={max}
marks={{
[min]: {
style: {fontFamily: 'Inter UI', fontSize: '14px'},
label: min,
},
[max]: {
style: {fontFamily: 'Inter UI', fontSize: '14px'},
label: max,
},
}}
onChange={this.handleChange}
defaultValue={[min, max]}
trackStyle={[{backgroundColor: theme.colors.green}]}
handleStyle={[
{backgroundColor: theme.colors.green, borderColor: darken(0.2, theme.colors.green)},
]}
railStyle={{backgroundColor: lighten(0.2, theme.colors.gray)}}
dotStyle={{
backgroundColor: lighten(0.2, theme.colors.gray),
borderColor: theme.colors.gray,
}}
activeDotStyle={{
backgroundColor: 'red',
borderColor: 'red',
color: 'red',
}}
/>
</SliderWrapper>
);
}
}
SliderRange.propTypes = {
min: PropTypes.number.isRequired,
max: PropTypes.number.isRequired,
width: PropTypes.number,
widthSm: PropTypes.number,
onChange: PropTypes.func,
className: PropTypes.string,
initialValue: PropTypes.array,
};
export default SliderRange;
|
src/Header.js | georgaleos/react-continuous-deployment | import React, { Component } from 'react';
import { Link, NavLink } from 'react-router-dom';
class Header extends Component {
render() {
return (
<header>
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<Link to="/" className="navbar-brand">
Elefth
</Link>
</div>
<div className="collapse navbar-collapse" id="navbar-collapse">
<ul className="nav navbar-nav">
<li>
<NavLink to="/" exact activeClassName="active">
Home
</NavLink>
</li>
<li>
<NavLink to="/roster" activeClassName="active">
Roster
</NavLink>
</li>
<li>
<NavLink to="/schedule" activeClassName="active">
Schedule
</NavLink>
</li>
<li>
<NavLink to="/products" activeClassName="active">
Products
</NavLink>
</li>
<li>
<NavLink to="/products/form" activeClassName="active">
Products Form
</NavLink>
</li>
<li>
<NavLink to="/login" activeClassName="active">
Login
</NavLink>
</li>
<li>
<NavLink to="/wizard" activeClassName="active">
Wizard
</NavLink>
</li>
<li>
<NavLink to="/search" activeClassName="active">
Search
</NavLink>
</li>
</ul>
</div>
</div>
</nav>
</header>
);
}
}
export default Header;
|
src/main/web/app/components/NavigationMenu.js | dhbw-timetable/rablabla | import React, { Component } from 'react';
import IconButton from 'material-ui/IconButton';
import Menu, { MenuItem } from 'material-ui/Menu';
import PropTypes from 'prop-types';
export default class NavigationMenu extends Component {
constructor(props) {
super(props);
this.state = {
anchorEl: null,
open: false,
};
}
handleRequestOpen = (event) => {
this.setState({ open: true, anchorEl: event.currentTarget });
};
handleRequestClose = (event, el) => {
this.setState({ open: false });
if (el) el.onClick(event);
};
render() {
const { iconColor, iconStyle, menuItems } = this.props;
const { open, anchorEl } = this.state;
return (
<div>
<IconButton
aria-owns={open ? 'nav-menu' : null}
aria-haspopup="true"
color={iconColor}
style={iconStyle}
onClick={this.handleRequestOpen}
>
more_horiz
</IconButton>
<Menu
id="nav-menu"
anchorEl={anchorEl}
open={open}
onRequestClose={this.handleRequestClose}
>
{menuItems.map((el, i) => {
const opt = {};
// Decide if it is either link or button
if (el.href) {
opt.href = el.href;
opt.target = '_blank';
opt.component = 'a';
} else if (el.onClick) {
opt.onClick = event => this.handleRequestClose(event, el);
}
return (
<MenuItem key={i} {...opt}>
{el.text}
</MenuItem>
);
})}
</Menu>
</div>
);
}
}
NavigationMenu.propTypes = {
menuItems: PropTypes.arrayOf(PropTypes.object).isRequired,
iconColor: PropTypes.string,
iconStyle: PropTypes.object,
};
NavigationMenu.defaultProps = {
iconColor: 'contrast',
iconStyle: {},
};
|
src/svg-icons/action/bookmark-border.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionBookmarkBorder = (props) => (
<SvgIcon {...props}>
<path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2zm0 15l-5-2.18L7 18V5h10v13z"/>
</SvgIcon>
);
ActionBookmarkBorder = pure(ActionBookmarkBorder);
ActionBookmarkBorder.displayName = 'ActionBookmarkBorder';
export default ActionBookmarkBorder;
|
b_stateMachine/complex_templates/jsx/wizard/body/body_customvar.js | Muzietto/react-playground | 'use strict';
import React from 'react';
export default function body_customvar(props) {
return (
<div className="body">
{props.core.core_renderer(props)}
</div>
);
}
|
docs/src/app/components/pages/components/TextField/ExampleDisabled.js | rhaedes/material-ui | import React from 'react';
import TextField from 'material-ui/TextField';
const TextFieldExampleDisabled = () => (
<div>
<TextField
disabled={true}
hintText="Disabled Hint Text"
/><br />
<TextField
disabled={true}
id="text-field-disabled"
defaultValue="Disabled Value"
/><br />
<TextField
disabled={true}
hintText="Disabled Hint Text"
floatingLabelText="Floating Label Text"
/><br />
<TextField
disabled={true}
hintText="Disabled Hint Text"
defaultValue="Disabled With Floating Label"
floatingLabelText="Floating Label Text"
/>
</div>
);
export default TextFieldExampleDisabled;
|
src/TextArea/TextArea.js | skyiea/wix-style-react | import React from 'react';
import {children, optional, once} from '../Composite';
import Label from '../Label';
import InputArea from '../InputArea';
import InputAreaWithLabelComposite from '../Composite/InputAreaWithLabelComposite/InputAreaWithLabelComposite';
const TextArea = ({...props, children}) => (
<InputAreaWithLabelComposite {...props}>
{children}
</InputAreaWithLabelComposite>
);
TextArea.propTypes = {
children: children(optional(Label), once(InputArea))
};
TextArea.displayName = 'TextArea';
export default TextArea;
|
App/components/material-ui/Checkbox.js | araneforseti/caretaker-app | import React from 'react';
import { ThemeProvider } from 'react-native-material-ui';
import { Checkbox as MaterialUiCheckbox } from 'react-native-material-ui';
import theme from '../../config/theme';
export default class Checkbox extends React.Component {
render() {
return <ThemeProvider uiTheme={theme}><MaterialUiCheckbox {...this.props} /></ThemeProvider>;
}
}
|
src/svg-icons/action/alarm-off.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAlarmOff = (props) => (
<SvgIcon {...props}>
<path d="M12 6c3.87 0 7 3.13 7 7 0 .84-.16 1.65-.43 2.4l1.52 1.52c.58-1.19.91-2.51.91-3.92 0-4.97-4.03-9-9-9-1.41 0-2.73.33-3.92.91L9.6 6.43C10.35 6.16 11.16 6 12 6zm10-.28l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM2.92 2.29L1.65 3.57 2.98 4.9l-1.11.93 1.42 1.42 1.11-.94.8.8C3.83 8.69 3 10.75 3 13c0 4.97 4.02 9 9 9 2.25 0 4.31-.83 5.89-2.2l2.2 2.2 1.27-1.27L3.89 3.27l-.97-.98zm13.55 16.1C15.26 19.39 13.7 20 12 20c-3.87 0-7-3.13-7-7 0-1.7.61-3.26 1.61-4.47l9.86 9.86zM8.02 3.28L6.6 1.86l-.86.71 1.42 1.42.86-.71z"/>
</SvgIcon>
);
ActionAlarmOff = pure(ActionAlarmOff);
ActionAlarmOff.displayName = 'ActionAlarmOff';
ActionAlarmOff.muiName = 'SvgIcon';
export default ActionAlarmOff;
|
node_modules/@material-ui/core/esm/IconButton/IconButton.js | pcclarke/civ-techs | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { chainPropTypes } from '@material-ui/utils';
import withStyles from '../styles/withStyles';
import { fade } from '../styles/colorManipulator';
import ButtonBase from '../ButtonBase';
import { capitalize } from '../utils/helpers';
export var styles = function styles(theme) {
return {
/* Styles applied to the root element. */
root: {
textAlign: 'center',
flex: '0 0 auto',
fontSize: theme.typography.pxToRem(24),
padding: 12,
borderRadius: '50%',
overflow: 'visible',
// Explicitly set the default value to solve a bug on IE 11.
color: theme.palette.action.active,
transition: theme.transitions.create('background-color', {
duration: theme.transitions.duration.shortest
}),
'&:hover': {
backgroundColor: fade(theme.palette.action.active, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
},
'&$disabled': {
backgroundColor: 'transparent',
color: theme.palette.action.disabled
}
},
/* Styles applied to the root element if `edge="start"`. */
edgeStart: {
marginLeft: -12,
'$sizeSmall&': {
marginLeft: -3
}
},
/* Styles applied to the root element if `edge="end"`. */
edgeEnd: {
marginRight: -12,
'$sizeSmall&': {
marginRight: -3
}
},
/* Styles applied to the root element if `color="inherit"`. */
colorInherit: {
color: 'inherit'
},
/* Styles applied to the root element if `color="primary"`. */
colorPrimary: {
color: theme.palette.primary.main,
'&:hover': {
backgroundColor: fade(theme.palette.primary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
/* Styles applied to the root element if `color="secondary"`. */
colorSecondary: {
color: theme.palette.secondary.main,
'&:hover': {
backgroundColor: fade(theme.palette.secondary.main, theme.palette.action.hoverOpacity),
// Reset on touch devices, it doesn't add specificity
'@media (hover: none)': {
backgroundColor: 'transparent'
}
}
},
/* Styles applied to the root element if `disabled={true}`. */
disabled: {},
/* Styles applied to the root element if `size="small"`. */
sizeSmall: {
padding: 3,
fontSize: theme.typography.pxToRem(18)
},
/* Styles applied to the children container element. */
label: {
width: '100%',
display: 'flex',
alignItems: 'inherit',
justifyContent: 'inherit'
}
};
};
/**
* Refer to the [Icons](/components/icons/) section of the documentation
* regarding the available icon options.
*/
var IconButton = React.forwardRef(function IconButton(props, ref) {
var _props$edge = props.edge,
edge = _props$edge === void 0 ? false : _props$edge,
children = props.children,
classes = props.classes,
className = props.className,
_props$color = props.color,
color = _props$color === void 0 ? 'default' : _props$color,
_props$disabled = props.disabled,
disabled = _props$disabled === void 0 ? false : _props$disabled,
_props$disableFocusRi = props.disableFocusRipple,
disableFocusRipple = _props$disableFocusRi === void 0 ? false : _props$disableFocusRi,
_props$size = props.size,
size = _props$size === void 0 ? 'medium' : _props$size,
other = _objectWithoutProperties(props, ["edge", "children", "classes", "className", "color", "disabled", "disableFocusRipple", "size"]);
return React.createElement(ButtonBase, _extends({
className: clsx(classes.root, color !== 'default' && classes["color".concat(capitalize(color))], disabled && classes.disabled, size !== 'medium' && classes["size".concat(capitalize(size))], edge === 'start' && classes.edgeStart, edge === 'end' && classes.edgeEnd, className),
centerRipple: true,
focusRipple: !disableFocusRipple,
disabled: disabled,
ref: ref
}, other), React.createElement("span", {
className: classes.label
}, children));
});
process.env.NODE_ENV !== "production" ? IconButton.propTypes = {
/**
* The icon element.
*/
children: chainPropTypes(PropTypes.node, function (props) {
var found = React.Children.toArray(props.children).some(function (child) {
return React.isValidElement(child) && child.props.onClick;
});
if (found) {
return new Error(['Material-UI: you are providing an onClick event listener ' + 'to a child of a button element.', 'Firefox will never trigger the event.', 'You should move the onClick listener to the parent button element.', 'https://github.com/mui-org/material-ui/issues/13957'].join('\n'));
}
return null;
}),
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* The color of the component. It supports those theme colors that make sense for this component.
*/
color: PropTypes.oneOf(['default', 'inherit', 'primary', 'secondary']),
/**
* If `true`, the button will be disabled.
*/
disabled: PropTypes.bool,
/**
* If `true`, the keyboard focus ripple will be disabled.
* `disableRipple` must also be true.
*/
disableFocusRipple: PropTypes.bool,
/**
* If `true`, the ripple effect will be disabled.
*/
disableRipple: PropTypes.bool,
/**
* If given, uses a negative margin to counteract the padding on one
* side (this is often helpful for aligning the left or right
* side of the icon with content above or below, without ruining the border
* size and shape).
*/
edge: PropTypes.oneOf(['start', 'end', false]),
/**
* The size of the button.
* `small` is equivalent to the dense button styling.
*/
size: PropTypes.oneOf(['small', 'medium'])
} : void 0;
export default withStyles(styles, {
name: 'MuiIconButton'
})(IconButton); |
react/features/base/dialog/components/DialogContent.js | bgrozev/jitsi-meet | // @flow
import React, { Component } from 'react';
import { Container, Text } from '../../react';
import { type StyleType } from '../../styles';
import styles from './styles';
type Props = {
/**
* Children of the component.
*/
children: string | React$Node,
style: ?StyleType
};
/**
* Generic dialog content container to provide the same styling for all custom
* dialogs.
*/
export default class DialogContent extends Component<Props> {
/**
* Implements {@code Component#render}.
*
* @inheritdoc
*/
render() {
const { children, style } = this.props;
const childrenComponent = typeof children === 'string'
? <Text style = { style }>{ children }</Text>
: children;
return (
<Container style = { styles.dialogContainer }>
{ childrenComponent }
</Container>
);
}
}
|
example/screens/NavigationViewExample.js | ardaogulcan/react-native-keyboard-accessory | import React, { Component } from 'react';
import {
StyleSheet,
View,
TextInput,
ScrollView,
Switch,
Text,
} from 'react-native';
import { KeyboardAccessoryNavigation } from '../react-native-keyboard-accessory';
let inputs = [
{
placeholder: 'Dummy Text Input',
},
{
keyboardType: 'email-address',
placeholder: 'Dummy Text Input Email',
},
{
keyboardType: 'numeric',
placeholder: 'Dummy Text Input Numeric',
},
{
placeholder: 'Dummy Text Input',
},
{
keyboardType: 'email-address',
placeholder: 'Dummy Text Input Email',
},
{
keyboardType: 'numeric',
placeholder: 'Dummy Text Input Numeric',
},
];
class NavigationViewExample extends Component {
constructor(props) {
super(props);
inputs = inputs.map(input => ({
ref: React.createRef(),
...input,
}));
this.state = {
activeInputIndex: 0,
nextFocusDisabled: false,
previousFocusDisabled: false,
buttonsDisabled: false,
buttonsHidden: false,
};
}
handleFocus = index => () => {
this.setState({
nextFocusDisabled: index === inputs.length - 1,
previousFocusDisabled: index === 0,
activeInputIndex: index,
});
}
handleFocusNext = () => {
const { nextFocusDisabled, activeInputIndex } = this.state;
if (nextFocusDisabled) {
return;
}
inputs[activeInputIndex + 1].ref.current.focus();
}
handleFocusPrevious = () => {
const { previousFocusDisabled, activeInputIndex } = this.state;
if (previousFocusDisabled) {
return;
}
inputs[activeInputIndex - 1].ref.current.focus();
}
render() {
return (
<View style={styles.container}>
<ScrollView contentContainerStyle={styles.contentContainer}>
<View style={styles.switchInput}>
<Switch
value={this.state.buttonsHidden}
onValueChange={() => {
this.setState({
buttonsHidden: !this.state.buttonsHidden
})
}}
/>
<Text style={styles.switchInputText}>
Hide arrows
</Text>
</View>
{ inputs.map(({ placeholder, keyboardType, ref }, index) =>
<TextInput
key={`input_${index}`}
ref={ref}
style={styles.textInput}
underlineColorAndroid="transparent"
placeholder={placeholder}
keyboardType={keyboardType}
blurOnSubmit={false}
onFocus={this.handleFocus(index)}
/>
)}
</ScrollView>
<KeyboardAccessoryNavigation
nextDisabled={this.state.nextFocusDisabled}
previousDisabled={this.state.previousFocusDisabled}
nextHidden={this.state.buttonsHidden}
previousHidden={this.state.buttonsHidden}
onNext={this.handleFocusNext}
onPrevious={this.handleFocusPrevious}
avoidKeyboard
androidAdjustResize
/>
</View>
);
}
}
NavigationViewExample.navigationOptions = {
title: 'Navigation View Example',
}
const styles = StyleSheet.create({
container: {
flex: 1
},
contentContainer: {
padding: 30,
},
textInput: {
flexGrow: 1,
borderWidth: 1,
borderRadius: 10,
borderColor: '#CCC',
padding: 10,
fontSize: 16,
marginBottom: 10,
},
switchInput: {
flex: 1,
flexDirection: 'row',
marginBottom: 10,
},
switchInputText: {
alignSelf: 'center',
fontSize: 16,
marginLeft: 10,
},
});
export default NavigationViewExample;
|
src/Glyphicon.js | leozdgao/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import styleMaps from './styleMaps';
const Glyphicon = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
glyph: React.PropTypes.oneOf(styleMaps.GLYPHS).isRequired
},
getDefaultProps() {
return {
bsClass: 'glyphicon'
};
},
render() {
let classes = this.getBsClassSet();
classes['glyphicon-' + this.props.glyph] = true;
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Glyphicon;
|
src/Button.js | HPate-Riptide/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, bsSizes, bsStyles, getClassSet, prefix, splitBsProps }
from './utils/bootstrapUtils';
import { Size, State, Style } from './utils/StyleConfig';
import SafeAnchor from './SafeAnchor';
const propTypes = {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
block: React.PropTypes.bool,
onClick: React.PropTypes.func,
componentClass: elementType,
href: React.PropTypes.string,
/**
* Defines HTML button type attribute
* @defaultValue 'button'
*/
type: React.PropTypes.oneOf(['button', 'reset', 'submit']),
};
const defaultProps = {
active: false,
block: false,
disabled: false,
};
class Button extends React.Component {
renderAnchor(elementProps, className) {
return (
<SafeAnchor
{...elementProps}
className={classNames(
className, elementProps.disabled && 'disabled'
)}
/>
);
}
renderButton({ componentClass, ...elementProps }, className) {
const Component = componentClass || 'button';
return (
<Component
{...elementProps}
type={elementProps.type || 'button'}
className={className}
/>
);
}
render() {
const { active, block, className, ...props } = this.props;
const [bsProps, elementProps] = splitBsProps(props);
const classes = {
...getClassSet(bsProps),
active,
[prefix(bsProps, 'block')]: block,
};
const fullClassName = classNames(className, classes);
if (elementProps.href) {
return this.renderAnchor(elementProps, fullClassName);
}
return this.renderButton(elementProps, fullClassName);
}
}
Button.propTypes = propTypes;
Button.defaultProps = defaultProps;
export default bsClass('btn',
bsSizes([Size.LARGE, Size.SMALL, Size.XSMALL],
bsStyles(
[...Object.values(State), Style.DEFAULT, Style.PRIMARY, Style.LINK],
Style.DEFAULT,
Button
)
)
);
|
app/pages/NoMatch/NoMatch.js | altiore/webpack_config_example | import React from 'react'
import PropTypes from 'prop-types'
const NoMatchPagePresenter = ({ styles, location }) => (
<div className={styles.wrapper}>
<h1>No Match for <code>{location.pathname}</code></h1>
</div>
)
NoMatchPagePresenter.propTypes = {
styles: PropTypes.object,
location: PropTypes.shape({
pathname: PropTypes.string.isRequired,
}).isRequired,
}
export default NoMatchPagePresenter
|
Rate.UI/app/components/Posts.js | jcnavarro/rateflicks | import React from 'react';
import ReviewStore from "../stores/ReviewStore";
import styled from 'styled-components';
export default class Posts extends React.Component {
constructor(props) {
super(props)
this.state = {
reviews: ReviewStore.getAll()
};
}
componentWillMount () {
ReviewStore.addChangeListener(this.getReviews);
}
getReviews(){
this.setState({
reviews : ReviewStore.getAll()
});
}
handleChange(e) {
const searchText = e.target.value;
this.props.SearchFlick(searchText);
}
render() {
const {reviews} = this.state;
const posts = reviews.map((review)=>
<div key={review.Title}>
<Movie movie={review}/>
</div>
);
return (
<div class="well">
{posts}
</div>
);
}
}
const Image = styled.img`
transform: scale(0.5);
`;
|
src/components/ButtonList.js | jakedeichert/react-starter | import React from 'react';
import pt from 'prop-types';
import { connect } from 'react-redux';
import styled from 'styled-components';
import {
actions as counterActions,
selectors as counterSelectors,
} from 'store/counter';
import { selectors as dataSelectors } from 'store/data';
import * as keyboard from 'utils/keyboard';
const Wrapper = styled.div`
color: black;
`;
const ClickCount = styled.p`
font-family: Monaco, monospace;
font-size: 13px;
padding: 0 0 10px;
text-align: center;
`;
const ListItem = styled.li`
background: #0fdfff;
color: white;
cursor: pointer;
list-style: none;
margin: 0 auto 20px;
padding: 20px;
max-width: 300px;
`;
export class ButtonList extends React.Component {
static propTypes = {
data: pt.array.isRequired,
counter: pt.number.isRequired,
incrementCounter: pt.func,
};
render() {
const { counter } = this.props;
return (
<Wrapper>
{this.renderList()}
<ClickCount>Click Count: {counter}</ClickCount>
</Wrapper>
);
}
renderList() {
const { data } = this.props;
return (
<ul>
{data.map(v => (
<ListItem
key={v.id}
role="button"
tabIndex={0}
onClick={this.handleClick}
onKeyUp={keyboard.onFocusKeyUp(this.handleClick)}>
{v.value}
</ListItem>
))}
</ul>
);
}
handleClick = () => {
this.props.incrementCounter();
};
}
export default connect(
state => ({
data: dataSelectors.getAllValues(state),
counter: counterSelectors.get(state),
}),
dispatch => ({
incrementCounter: () => dispatch(counterActions.incrementCounter()),
})
)(ButtonList);
|
src/@ui/Icon/icons/ArrowUp.js | NewSpring/Apollos | import React from 'react';
import PropTypes from 'prop-types';
import { Svg } from '../../Svg';
import makeIcon from './makeIcon';
const Icon = makeIcon(({ size = 32, fill, ...otherProps } = {}) => (
<Svg width={size} height={size} viewBox="0 0 24 24" {...otherProps}>
<Svg.Path
d="M20.1 16L12 8.28 3.9 16 3 14.35l8.54-8.15c.28-.27.64-.27.92 0L21 14.35 20.1 16z"
fill={fill}
/>
</Svg>
));
Icon.propTypes = {
size: PropTypes.number,
fill: PropTypes.string,
};
export default Icon;
|
src/utils/createContextWrapper.js | chrishoage/react-bootstrap | import React from 'react';
/**
* Creates new trigger class that injects context into overlay.
*/
export default function createContextWrapper(Trigger, propName) {
return function(contextTypes) {
class ContextWrapper extends React.Component {
getChildContext() {
return this.props.context;
}
render() {
// Strip injected props from below.
const {wrapped, context, ...props} = this.props;
return React.cloneElement(wrapped, props);
}
}
ContextWrapper.childContextTypes = contextTypes;
class TriggerWithContext {
render() {
const props = {...this.props};
props[propName] = this.getWrappedOverlay();
return (
<Trigger {...props}>
{this.props.children}
</Trigger>
);
}
getWrappedOverlay() {
return (
<ContextWrapper
context={this.context}
wrapped={this.props[propName]}
/>
);
}
}
TriggerWithContext.contextTypes = contextTypes;
return TriggerWithContext;
};
}
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | simonasdev/afloat | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
packages/reactor-kitchensink/src/examples/Layouts/resizable/resizable.js | dbuhrman/extjs-reactor | import React from 'react';
import { Panel, Container } from '@extjs/ext-react';
import colors from '../../colors';
Ext.require('Ext.panel.Resizable');
export default function ResizableExample() {
return (
<Panel shadow layout="fit">
<Panel
title="Dock Left"
docked="left"
width={200}
layout="center"
resizable={{
split: true,
edges: 'east',
dynamic: true
}}
>
<code>dynamic: true</code>
</Panel>
<Panel title="Unresizable region" flex={1}/>
<Panel
docked="right"
title="Dock Right"
width={200}
collapsible="right"
layout="center"
resizable={{
split: true,
edges: 'west'
}}
>
<code>collapsible</code>
</Panel>
<Panel
docked="top"
title="Dock Top"
height={150}
resizable={{
split: true,
edges: 'south'
}}
/>
<Panel
docked="bottom"
title="Dock Bottom"
height={150}
layout="center"
resizable={{
split: true,
edges: 'north',
snap: 50
}}
>
<code>snap: 50</code>
</Panel>
</Panel>
)
}
const styles = {
panelBody: {
fontSize: '18px',
color: '#777'
}
} |
examples/todos/components/Footer.js | doerme/redux | import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="SHOW_ALL">
All
</FilterLink>
{", "}
<FilterLink filter="SHOW_ACTIVE">
Active
</FilterLink>
{", "}
<FilterLink filter="SHOW_COMPLETED">
Completed
</FilterLink>
</p>
)
export default Footer
|
app/index.js | i8wu/Converrency | import React, { Component } from 'react';
import {
View
} from 'react-native';
import { Provider } from 'react-redux';
import RNExitApp from 'react-native-exit-app';
import { setJSExceptionHandler } from 'react-native-exception-handler';
import configureStore from './store/configureStore';
import Home from './scenes/Home';
export default class Converrency extends Component {
constructor(props) {
super(props);
this.state = {
store: configureStore({}, this.finishLoading),
isLoading: true,
};
}
finishLoading = () => {
this.setState({ isLoading: false });
// Handle unexpected error and help app recover by clearing storage
// TODO: Only clear rates?
const errorHandler = (e, isFatal) => {
if (isFatal) {
AsyncStorage.clear();
var errorStr = 'Crash: ' + e.name + ': ' + e.message,
errorStack;
try {
errorStack = e.stack.replace(/.*\n/,'').replace(/\n.*/g, '').trim();
errorStr += ' ' + errorStack;
} catch (stackErr) {
logger.log('Error: ' + stackErr);
}
Alert.alert(
'Unexpected error occurred',
'Please try restarting the app. If the app is still crashing, please keep an eye out for an update or try again later.',
[{
text: 'Okay',
onPress: () => {
RNExitApp.exitApp();
}
}]
);
} else {
console.log(e); // So that we can see it in the ADB logs in case of Android if needed
}
};
setJSExceptionHandler(errorHandler, true, true);
}
render() {
let mainApp;
if (!this.state.isLoading) {
mainApp = (
<Home />
);
} else {
mainApp = <View />;
}
return (
<Provider store={this.state.store}>
{mainApp}
</Provider>
);
}
}
|
src/components/ItemCreator/index.js | muhanad40/Todo-Test | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { addItem } from '../../logic/actions';
import './styles.css';
export const ItemCreator = ({ onAdd }) => {
let inputField;
return (
<div className={'itemCreator'}>
<input
ref={input => {
inputField = input;
}}
className={'itemCreator-input'}
type="text"
placeholder={'What do you need to do?'}
/>
<input
className={'itemCreator-button'}
type="button"
value={'Add Task'}
onClick={() => {
inputField.value && onAdd(inputField.value);
inputField.value = '';
}}
/>
</div>
);
};
ItemCreator.propTypes = {
onAdd: PropTypes.func.isRequired,
};
const mapDispatchToProps = dispatch => ({
onAdd: newItem => dispatch(addItem(newItem)),
});
export default connect(null, mapDispatchToProps)(ItemCreator);
|
frontend/app/blog/components/LatestArticles.js | briancappello/flask-react-spa | import React from 'react'
import { compose } from 'redux'
import { connect } from 'react-redux'
import { bindRoutineCreators } from 'actions'
import { injectReducer, injectSagas } from 'utils/async'
import { listArticles } from 'blog/actions'
import { selectArticlesList } from 'blog/reducers/articles'
import ArticlePreview from './ArticlePreview'
class LatestArticles extends React.Component {
componentWillMount() {
this.props.listArticles.maybeTrigger()
}
render() {
const { articles } = this.props
if (articles.length === 0) {
return <p>No articles have been published yet.</p>
}
return (
<div>
{articles.map((article, i) =>
<ArticlePreview article={article} key={i} />
)}
</div>
)
}
}
const withReducer = injectReducer(require('blog/reducers/articles'))
const withSaga = injectSagas(require('blog/sagas/articles'))
const withConnect = connect(
(state) => ({ articles: selectArticlesList(state) }),
(dispatch) => bindRoutineCreators({ listArticles }, dispatch),
)
export default compose(
withReducer,
withSaga,
withConnect,
)(LatestArticles)
|
src/App.js | scarescrow/react-resource-center | import React, { Component } from 'react';
import './styles/App.css';
import './styles/materialize/css/materialize.css';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import injectTapEventPlugin from 'react-tap-event-plugin';
/* Material UI */
import { MuiThemeProvider } from 'material-ui/styles';
import fusTheme from './fusTheme';
import SideNav from './SideNavItem';
/* Views */
import Glossary from './views/Glossary';
import Home from './views/Home';
import Letterhead from './views/Letterhead';
import Logos from './views/Logos';
import LogosPosters from './views/LogosPosters';
import PlanningGuide from './views/PlanningGuide';
import Posters from './views/Posters';
import ServiceRequest from './views/ServiceRequest';
import Services from './views/Services';
import Story from './views/Story';
import Tutorial from './views/Tutorial';
import NotFound from './views/NotFound';
injectTapEventPlugin();
class App extends Component {
constructor(props) {
super(props);
this.state = {
open: false
};
};
handleClose = () => this.setState({open: false});
render() {
return (
<BrowserRouter>
<MuiThemeProvider theme={fusTheme}>
<div>
<SideNav />
<Switch>
<Route exact path="/" component={Home} />
<Route path='/logos-posters' component={LogosPosters} />
<Route path='/logos' component={Logos} />
<Route path='/posters' component={Posters} />
<Route path='/letterhead' component={Letterhead} />
<Route path='/share-a-story' component={Story} />
<Route path='/planning-guide' component={PlanningGuide} />
<Route path='/services' component={Services} />
<Route path='/glossary' component={Glossary} />
<Route path='/service-request-form' component={ServiceRequest} />
<Route path='/tutorial' component={Tutorial} />
<Route component={NotFound} />
</Switch>
</div>
</MuiThemeProvider>
</BrowserRouter>
);
}
}
export default App;
|
src/svg-icons/device/add-alarm.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceAddAlarm = (props) => (
<SvgIcon {...props}>
<path d="M7.88 3.39L6.6 1.86 2 5.71l1.29 1.53 4.59-3.85zM22 5.72l-4.6-3.86-1.29 1.53 4.6 3.86L22 5.72zM12 4c-4.97 0-9 4.03-9 9s4.02 9 9 9c4.97 0 9-4.03 9-9s-4.03-9-9-9zm0 16c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7zm1-11h-2v3H8v2h3v3h2v-3h3v-2h-3V9z"/>
</SvgIcon>
);
DeviceAddAlarm = pure(DeviceAddAlarm);
DeviceAddAlarm.displayName = 'DeviceAddAlarm';
DeviceAddAlarm.muiName = 'SvgIcon';
export default DeviceAddAlarm;
|
src/routes/Character/components/CharacterView.js | warcraftlfg/warcrafthub-client | import React from 'react'
import { Col, Row } from 'react-bootstrap'
import ErrorMessages from '../../../containers/ErrorMessages'
import CharacterTitle from './CharacterTitle'
import UpdateButton from '../../../containers/UpdateButton'
import CharacterNav from './CharacterNav'
import './CharacterView.scss'
class CharacterView extends React.Component {
render () {
if (this.props.character.isLoading === false &&
this.props.character.hasError === false &&
this.props.character.data) {
document.title = this.props.character.data.name + ' @ ' + this.props.character.data.realm + ' | Warcrafthub'
return (
<div className='character-view'>
<CharacterTitle
region={this.props.character.data.region}
realm={this.props.character.data.realm}
name={this.props.character.data.name}
faction={this.props.character.data.faction}
class_={this.props.character.data.class}
level={this.props.character.data.level}
/>
<div className='container content'>
<ErrorMessages />
<Row>
<Col md={12}>
<UpdateButton type='character' region={this.props.character.data.region}
realm={this.props.character.data.realm}
name={this.props.character.data.name}>
<i className='fa fa-refresh' aria-hidden='true' /> Update character
</UpdateButton>
</Col>
</Row>
<Row>
<Col md={12}>
<CharacterNav region={this.props.character.data.region} realm={this.props.character.data.realm}
name={this.props.character.data.name} />
</Col>
</Row>
{this.props.children}
</div>
</div>
)
} else if (this.props.character.hasError === true) {
return (
<div className='character-view'>
<CharacterTitle
region={this.props.params.region}
realm={this.props.params.realm}
name={this.props.params.name}
faction={-1}
class_={-1} />
<div className='container content'>
<ErrorMessages />
<Row>
<Col md={12}>
<p>Oops, this character is missing. Click on the button below to import him.</p>
<UpdateButton type='character' region={this.props.params.region} realm={this.props.params.realm}
name={this.props.params.name}>
<i className='fa fa-download' aria-hidden='true' /> Import Character</UpdateButton>
</Col>
</Row>
</div>
</div>
)
} else {
return null
}
}
}
CharacterView.propTypes = {
character: React.PropTypes.shape({
isLoading: React.PropTypes.bool.isRequired,
hasError: React.PropTypes.bool.isRequired,
data: React.PropTypes.object
}),
params: React.PropTypes.object,
children: React.PropTypes.element
}
export default CharacterView
|
src/components/Sidebar/Sidebar.js | lkostrowski/cv | import React from 'react';
import PropTypes from 'prop-types';
import Photo from '../Photo/Photo';
const Sidebar = () => (
<div>
<Photo/>
</div>
);
Sidebar.propTypes = {}
export default Sidebar;
|
judge/client/src/index.js | istamenov/NodeJS_Judge | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App/>,
document.getElementById('root')
);
|
vendor/htmlburger/carbon-fields/assets/js/fields/components/media-gallery/index.js | FolsomCreative/storynav | /**
* The external dependencies.
*/
import $ from 'jquery';
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import {
compose,
withHandlers,
setStatic,
withProps
} from 'recompose';
import {
without,
sortBy,
isNumber
} from 'lodash';
/**
* The internal dependencies.
*/
import Field from 'fields/components/field';
import MediaGalleryList from 'fields/components/media-gallery/list';
import EditAttachment from 'fields/components/media-gallery/edit-attachment';
import withStore from 'fields/decorators/with-store';
import withSetup from 'fields/decorators/with-setup';
import { setupMediaBrowser, openMediaBrowser } from 'fields/actions';
import { TYPE_MEDIA_GALLERY, VALIDATION_BASE } from 'fields/constants';
/**
* Render a file upload field with a preview thumbnail of the uploaded file.
*
* @param {Object} props
* @param {String} props.name
* @param {Object} props.field
* @param {Function} props.openBrowser
* @param {Function} props.handleRemoveItem
* @return {React.Element}
*/
export const MediaGalleryField = ({
name,
field,
openBrowser,
sortableOptions,
handleSortItems,
handleRemoveItem,
openEditAttachment,
closeEditAttachment,
updateField,
}) => {
return <Field field={field}>
<div className="carbon-media-gallery">
<MediaGalleryList
prefix={name}
items={field.value}
itemsMeta={field.value_meta}
handleOpenBrowser={openBrowser}
handleEditItem={openEditAttachment}
handleRemoveItem={handleRemoveItem}
openBrowser={openBrowser}
field={field}
sortableOptions={sortableOptions}
onSort={handleSortItems}
/>
{
(field.editMode === 'inline' && field.selected) ?
<EditAttachment
field={field}
attachment={field.selected}
attachmentMeta={field.value_meta[ field.selected ]}
updateField={updateField}
handleCancelEdit={closeEditAttachment}
/> : ''
}
</div>
</Field>;
};
/**
* Validate the props.
*
* @type {Object}
*/
MediaGalleryField.propTypes = {
name: PropTypes.string,
field: PropTypes.shape({
value: PropTypes.array,
value_meta: PropTypes.oneOfType([
PropTypes.array,
PropTypes.object,
]),
value_type: PropTypes.string,
duplicates_allowed: PropTypes.boolean,
selected: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
editMode: PropTypes.string,
edit: PropTypes.shape({
id: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
title: PropTypes.string,
caption: PropTypes.string,
alt: PropTypes.string,
description: PropTypes.string,
artist: PropTypes.string,
album: PropTypes.string,
}),
}),
openBrowser: PropTypes.func,
handleRemoveItem: PropTypes.func,
};
/**
* The enhancer.
*
* @type {Function}
*/
export const enhance = compose(
/**
* Connect to the Redux store.
*/
withStore(undefined, {
setupMediaBrowser,
openMediaBrowser,
}),
/**
* Attach the setup hooks.
*/
withSetup({
componentDidMount() {
const {
field,
ui,
setupField,
setupValidation,
setupMediaBrowser,
} = this.props;
setupField(field.id, field.type, ui);
setupMediaBrowser(field.id);
if (field.required) {
setupValidation(field.id, VALIDATION_BASE);
}
},
}),
/**
* Component Handlers.
*/
withHandlers({
resetCurrentlyEditedAttachment: ({ field, updateField }) => () => {
updateField(field.id, {
selected: null,
edit: {
id: '',
title: '',
alt: '',
caption: '',
description: '',
artist: '',
album: '',
}
})
},
}),
/**
* Pass some handlers to the component.
*/
withHandlers({
openBrowser: ({ field, openMediaBrowser }) => (index) => {
if (isNumber(index)) {
field.selected = index;
}
openMediaBrowser(field.id);
},
handleSortItems: ({ field, setFieldValue }) => newItems => {
newItems = newItems.map(item => parseInt(item, 10));
let index = -1;
let newValue = sortBy(field.value, (item) => {
index++;
return newItems.indexOf(index);
});
setFieldValue(field.id, newValue);
},
handleRemoveItem: ({ field, setFieldValue, resetCurrentlyEditedAttachment }) => (index) => {
field.value.splice(index, 1);
setFieldValue(field.id, field.value);
resetCurrentlyEditedAttachment();
},
openEditAttachment: ({ field, updateField, openMediaBrowser }) => (item) => {
const $container = $(`#${field.parent}`);
// For big containers and non-mobile devices, use the inline edit
// Otherwise, fallback to Media Browser
if ( $container.outerWidth() > 767 ) {
const attachmentMeta = field.value_meta[ item ];
updateField(field.id, {
selected: item,
editMode: 'inline',
edit: {
id: parseInt(item, 10),
title: attachmentMeta.title,
alt: attachmentMeta.alt,
caption: attachmentMeta.caption,
description: attachmentMeta.description,
artist: attachmentMeta.artist || '',
album: attachmentMeta.album || '',
}
});
} else {
updateField(field.id, {
selected: item,
editMode: 'modal',
});
openMediaBrowser(field.id);
}
},
closeEditAttachment: ({ resetCurrentlyEditedAttachment }) => () => {
resetCurrentlyEditedAttachment();
}
}),
/**
* Pass some props to the component.
*/
withProps(({ field, collapseComplexGroup }) => {
const sortableOptions = {
handle: '.carbon-description',
items: '.carbon-media-gallery-list-item',
placeholder: 'carbon-media-gallery-list-item ui-placeholder-highlight',
forcePlaceholderSize: true,
};
return {
sortableOptions,
};
}),
);
export default setStatic('type', [
TYPE_MEDIA_GALLERY,
])(enhance(MediaGalleryField));
|
src/components/mixins/ViewBoxMixin.js | ahoiin/binocular-webapp | import React from 'react'
export default {
propTypes: {
viewBox: React.PropTypes.string,
viewBoxObject: React.PropTypes.object
},
getViewBox(t) { console.log(t,this);
if (this.props.viewBoxObject) {
var v = this.props.viewBoxObject;
return [v.x, v.y, v.width, v.height].join(' ');
} else if (this.props.viewBox) {
return this.props.viewBox;
}
},
getDimensions() {
var props = this.props;
var {horizontal, margins, viewBoxObject, xOrient, xAxisOffset, yAxisOffset} = props;
var yOrient = this.getYOrient();
var width, height;
if (viewBoxObject) {
width = viewBoxObject.width,
height = viewBoxObject.height
} else {
width = props.width,
height = props.height
}
var svgWidth, svgHeight;
var xOffset, yOffset;
var svgMargins;
var trans;
if (horizontal) {
var center = width / 2;
trans = `rotate(90 ${ center } ${ center }) `;
svgWidth = height;
svgHeight = width;
svgMargins = {
left: margins.top,
top: margins.right,
right: margins.bottom,
bottom: margins.left
};
} else {
trans = '';
svgWidth = width;
svgHeight = height;
svgMargins = margins;
}
var xAxisOffset = Math.abs(props.xAxisOffset || 0);
var yAxisOffset = Math.abs(props.yAxisOffset || 0);
var xOffset = svgMargins.left + (yOrient === 'left' ? yAxisOffset : 0);
var yOffset = svgMargins.top + (xOrient === 'top' ? xAxisOffset : 0);
trans += `translate(${ xOffset }, ${ yOffset })`;
return {
innerHeight: svgHeight - svgMargins.top - svgMargins.bottom - xAxisOffset,
innerWidth: svgWidth - svgMargins.left - svgMargins.right - yAxisOffset,
trans: trans,
svgMargins: svgMargins
};
}
} |
src/scripts/vendors.js | kodokojo/kodokojo-ui | /**
* Kodo Kojo - Software factory done right
* Copyright © 2017 Kodo Kojo (infos@kodokojo.io)
*
* This program 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.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// core
import React from 'react'
import { compose } from 'redux'
import { Provider, connect } from 'react-redux'
// router
import { Router, Route, IndexRoute, browserHistory } from 'react-router'
import { syncHistoryWithStore } from 'react-router-redux'
// intl
import { intlShape, injectIntl, addLocaleData } from 'react-intl'
// ui
import { themr } from 'react-css-themr'
// DOM, browser
import ReactDOM from 'react-dom'
import injectTapEventPlugin from 'react-tap-event-plugin'
// form
import { reduxForm } from 'redux-form'
// other
import Promise from 'bluebird'
|
src/app.js | inooid/react-redux-card-game | import React from 'react';
import ReactDOM from 'react-dom';
import socketClient from 'socket.io-client';
import configureStore from 'redux/configureStore';
import {
dispatchNewGameAction,
dispatchServerActions,
getInitialState,
} from 'redux/utils';
import { Root } from './containers';
import './styles/app.scss';
if (module.hot) {
module.hot.accept();
}
const socket = socketClient('http://localhost:3000');
const store = configureStore(getInitialState(), socket);
dispatchServerActions(store, socket);
dispatchNewGameAction(store, socket);
ReactDOM.render(
<Root store={store} socket={socket} />,
document.getElementById('app')
);
|
src/svg-icons/action/rowing.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRowing = (props) => (
<SvgIcon {...props}>
<path d="M8.5 14.5L4 19l1.5 1.5L9 17h2l-2.5-2.5zM15 1c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm6 20.01L18 24l-2.99-3.01V19.5l-7.1-7.09c-.31.05-.61.07-.91.07v-2.16c1.66.03 3.61-.87 4.67-2.04l1.4-1.55c.19-.21.43-.38.69-.5.29-.14.62-.23.96-.23h.03C15.99 6.01 17 7.02 17 8.26v5.75c0 .84-.35 1.61-.92 2.16l-3.58-3.58v-2.27c-.63.52-1.43 1.02-2.29 1.39L16.5 18H18l3 3.01z"/>
</SvgIcon>
);
ActionRowing = pure(ActionRowing);
ActionRowing.displayName = 'ActionRowing';
ActionRowing.muiName = 'SvgIcon';
export default ActionRowing;
|
src/routes.js | mrholek/CoreUI-React | import React from 'react'
const Dashboard = React.lazy(() => import('./views/dashboard/Dashboard'))
const Colors = React.lazy(() => import('./views/theme/colors/Colors'))
const Typography = React.lazy(() => import('./views/theme/typography/Typography'))
// Base
const Accordion = React.lazy(() => import('./views/base/accordion/Accordion'))
const Breadcrumbs = React.lazy(() => import('./views/base/breadcrumbs/Breadcrumbs'))
const Cards = React.lazy(() => import('./views/base/cards/Cards'))
const Carousels = React.lazy(() => import('./views/base/carousels/Carousels'))
const Collapses = React.lazy(() => import('./views/base/collapses/Collapses'))
const ListGroups = React.lazy(() => import('./views/base/list-groups/ListGroups'))
const Navs = React.lazy(() => import('./views/base/navs/Navs'))
const Paginations = React.lazy(() => import('./views/base/paginations/Paginations'))
const Placeholders = React.lazy(() => import('./views/base/placeholders/Placeholders'))
const Popovers = React.lazy(() => import('./views/base/popovers/Popovers'))
const Progress = React.lazy(() => import('./views/base/progress/Progress'))
const Spinners = React.lazy(() => import('./views/base/spinners/Spinners'))
const Tables = React.lazy(() => import('./views/base/tables/Tables'))
const Tooltips = React.lazy(() => import('./views/base/tooltips/Tooltips'))
// Buttons
const Buttons = React.lazy(() => import('./views/buttons/buttons/Buttons'))
const ButtonGroups = React.lazy(() => import('./views/buttons/button-groups/ButtonGroups'))
const Dropdowns = React.lazy(() => import('./views/buttons/dropdowns/Dropdowns'))
//Forms
const ChecksRadios = React.lazy(() => import('./views/forms/checks-radios/ChecksRadios'))
const FloatingLabels = React.lazy(() => import('./views/forms/floating-labels/FloatingLabels'))
const FormControl = React.lazy(() => import('./views/forms/form-control/FormControl'))
const InputGroup = React.lazy(() => import('./views/forms/input-group/InputGroup'))
const Layout = React.lazy(() => import('./views/forms/layout/Layout'))
const Range = React.lazy(() => import('./views/forms/range/Range'))
const Select = React.lazy(() => import('./views/forms/select/Select'))
const Validation = React.lazy(() => import('./views/forms/validation/Validation'))
const Charts = React.lazy(() => import('./views/charts/Charts'))
// Icons
const CoreUIIcons = React.lazy(() => import('./views/icons/coreui-icons/CoreUIIcons'))
const Flags = React.lazy(() => import('./views/icons/flags/Flags'))
const Brands = React.lazy(() => import('./views/icons/brands/Brands'))
// Notifications
const Alerts = React.lazy(() => import('./views/notifications/alerts/Alerts'))
const Badges = React.lazy(() => import('./views/notifications/badges/Badges'))
const Modals = React.lazy(() => import('./views/notifications/modals/Modals'))
const Toasts = React.lazy(() => import('./views/notifications/toasts/Toasts'))
const Widgets = React.lazy(() => import('./views/widgets/Widgets'))
const routes = [
{ path: '/', exact: true, name: 'Home' },
{ path: '/dashboard', name: 'Dashboard', element: Dashboard },
{ path: '/theme', name: 'Theme', element: Colors, exact: true },
{ path: '/theme/colors', name: 'Colors', element: Colors },
{ path: '/theme/typography', name: 'Typography', element: Typography },
{ path: '/base', name: 'Base', element: Cards, exact: true },
{ path: '/base/accordion', name: 'Accordion', element: Accordion },
{ path: '/base/breadcrumbs', name: 'Breadcrumbs', element: Breadcrumbs },
{ path: '/base/cards', name: 'Cards', element: Cards },
{ path: '/base/carousels', name: 'Carousel', element: Carousels },
{ path: '/base/collapses', name: 'Collapse', element: Collapses },
{ path: '/base/list-groups', name: 'List Groups', element: ListGroups },
{ path: '/base/navs', name: 'Navs', element: Navs },
{ path: '/base/paginations', name: 'Paginations', element: Paginations },
{ path: '/base/placeholders', name: 'Placeholders', element: Placeholders },
{ path: '/base/popovers', name: 'Popovers', element: Popovers },
{ path: '/base/progress', name: 'Progress', element: Progress },
{ path: '/base/spinners', name: 'Spinners', element: Spinners },
{ path: '/base/tables', name: 'Tables', element: Tables },
{ path: '/base/tooltips', name: 'Tooltips', element: Tooltips },
{ path: '/buttons', name: 'Buttons', element: Buttons, exact: true },
{ path: '/buttons/buttons', name: 'Buttons', element: Buttons },
{ path: '/buttons/dropdowns', name: 'Dropdowns', element: Dropdowns },
{ path: '/buttons/button-groups', name: 'Button Groups', element: ButtonGroups },
{ path: '/charts', name: 'Charts', element: Charts },
{ path: '/forms', name: 'Forms', element: FormControl, exact: true },
{ path: '/forms/form-control', name: 'Form Control', element: FormControl },
{ path: '/forms/select', name: 'Select', element: Select },
{ path: '/forms/checks-radios', name: 'Checks & Radios', element: ChecksRadios },
{ path: '/forms/range', name: 'Range', element: Range },
{ path: '/forms/input-group', name: 'Input Group', element: InputGroup },
{ path: '/forms/floating-labels', name: 'Floating Labels', element: FloatingLabels },
{ path: '/forms/layout', name: 'Layout', element: Layout },
{ path: '/forms/validation', name: 'Validation', element: Validation },
{ path: '/icons', exact: true, name: 'Icons', element: CoreUIIcons },
{ path: '/icons/coreui-icons', name: 'CoreUI Icons', element: CoreUIIcons },
{ path: '/icons/flags', name: 'Flags', element: Flags },
{ path: '/icons/brands', name: 'Brands', element: Brands },
{ path: '/notifications', name: 'Notifications', element: Alerts, exact: true },
{ path: '/notifications/alerts', name: 'Alerts', element: Alerts },
{ path: '/notifications/badges', name: 'Badges', element: Badges },
{ path: '/notifications/modals', name: 'Modals', element: Modals },
{ path: '/notifications/toasts', name: 'Toasts', element: Toasts },
{ path: '/widgets', name: 'Widgets', element: Widgets },
]
export default routes
|
packages/mineral-ui-icons/src/IconBackup.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconBackup(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M19.35 10.04A7.49 7.49 0 0 0 12 4C9.11 4 6.6 5.64 5.35 8.04A5.994 5.994 0 0 0 0 14c0 3.31 2.69 6 6 6h13c2.76 0 5-2.24 5-5 0-2.64-2.05-4.78-4.65-4.96zM14 13v4h-4v-4H7l5-5 5 5h-3z"/>
</g>
</Icon>
);
}
IconBackup.displayName = 'IconBackup';
IconBackup.category = 'action';
|
stores/SearchStore.js | arpith/hamelin | import React from 'react';
import { EventEmitter } from 'events';
import assign from 'object-assign';
import AppDispatcher from '../dispatcher/AppDispatcher';
const CHANGE_EVENT = 'change';
const API_KEY = 'AIzaSyCk47VXnNZ5BcR1_kO84-BS7My2j0G5PAc';
let _query = '';
let _resultIDs = [];
let _results = {};
function parseResult(result) {
return {
id: result.id.videoId,
title: result.snippet.title,
thumbnail: result.snippet.thumbnails.medium.url,
score: 1
};
}
function addResult(result) {
if (result.id in _results) {
_results[result.id].score += 1;
} else {
_resultIDs.push(result.id);
_results[result.id] = result;
}
}
function API(query, type) {
const baseURL = 'https://www.googleapis.com/youtube/v3/search?part=snippet&maxResults=50';
const url = baseURL + '&key=' + API_KEY + '&q=' + query + '&type=' + type;
return fetch(url).then(res => res.json()).then((res) => {
return res.items.map(parseResult);
});
}
function searchPlaylists(query) {
_query = query;
API(query, 'playlists').then((results) => {
results.forEach(addResult);
_resultIDs.sort((a, b) => a.score - b.score);
SearchStore.emitChange();
});
}
function searchVideos(query) {
_query = query;
API(query, 'videos').then((results) => {
_resultIDs = results.map(res => res.id);
_results = {};
results.forEach((res) => {
_results[res.id] = res;
});
SearchStore.emitChange();
});
}
const SearchStore = assign({}, EventEmitter.prototype, {
getQuery: function() {
return _query;
},
getResults: function() {
return _resultIDs.map(id => _results[id]);
},
emitChange: function() {
this.emit(CHANGE_EVENT);
},
addChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
},
removeChangeListener: function(callback) {
this.on(CHANGE_EVENT, callback);
}
});
AppDispatcher.register(function(action) {
switch (action.actionType) {
case 'search-videos':
searchVideos(action.query);
break;
case 'search-playlists':
searchPlaylists(action.query);
break;
}
});
export default SearchStore;
|
src/components/common/Confirm.js | dougsleite/talk2go | import React from 'react';
import { Text, View, Modal } from 'react-native';
import { CardSection } from './CardSection';
import { Button } from './Button';
const Confirm = ({ children, onAccept, onDecline, visible }) => {
const { containerStyle, textStyle, cardSectionStyle } = styles;
return (
<Modal
visible={visible}
transparent
animationType="slide"
onRequestClose={() => {}} // required by Android API
>
<View style={containerStyle}>
<CardSection style={cardSectionStyle}>
<Text style={textStyle}>{children}</Text>
</CardSection>
<CardSection>
<Button onPress={onAccept}>Yes</Button>
<Button onPress={onDecline}>No</Button>
</CardSection>
</View>
</Modal>
);
};
const styles = {
cardSectionStyle: {
justifyContent: 'center'
},
textStyle: {
flex: 1,
fontSize: 18,
textAlign: 'center',
lineHeight: 40
},
containerStyle: {
backgroundColor: 'rgba(0, 0, 0, 0.75)',
position: 'relative',
flex: 1,
justifyContent: 'center'
}
};
export { Confirm };
|
components/LibraryList.js | react-community/native-directory | import React from 'react';
import PropTypes from 'prop-types';
import LibraryListEmptyState from '../components/LibraryListEmptyState';
import LibraryListItem from '../components/LibraryListItem';
import { StyleSheet, css } from 'glamor/aphrodite';
export default class LibraryList extends React.PureComponent {
static propTypes = {
libraries: PropTypes.array,
isMobile: PropTypes.bool,
};
render() {
const elements =
this.props.libraries.length < 1 ? (
<LibraryListEmptyState />
) : (
this.props.libraries.map((item, index) => (
<LibraryListItem
key={`list-item-${index}-${item.github.name}`}
isMobile={this.props.isMobile}
library={item}
/>
))
);
return <div className={css(styles.list)}>{elements}</div>;
}
}
let styles = StyleSheet.create({
list: {
width: '100%',
},
});
|
app/admin/post/PostView.js | ecellju/internship-portal | import React from 'react';
import axios from 'axios';
import _ from 'lodash';
import { Button, Menu, Container } from 'semantic-ui-react';
import PropTypes from 'prop-types';
import DisplayPost from '../../common/post/DisplayPost';
import EditPost from '../components/post/EditPost';
import Auth from '../../auth/modules/Auth';
import browserHistory from '../../history';
const fetchPostById = postId =>
(axios.get(`/api/admin/posts/${postId}`, {
headers: {
Authorization: `bearer ${Auth.getToken()}`,
},
})
.then((resp) => {
console.log('response is ', resp);
const post = resp.data;
post.stipend = `${post.stipend}`;
post.duration = `${post.duration}`;
return post;
})
.catch(console.error));
const handleViewApplicants = (event) => {
console.log('View Applicants :', event);
browserHistory.push('/admin/students');
};
class PostView extends React.Component {
constructor(props) {
super(props);
this.state = { post: null, editable: false, errors: {} };
this.handleChange = (e, { name, value }) =>
this.setState({ post: { ...this.state.post, [name]: value } });
this.changeInternshipDetails = this.changeInternshipDetails.bind(this);
this.saveChanges = this.saveChanges.bind(this);
this.toggleEditability = () => {
console.log('edit/save');
this.setState(
{ editable: !this.state.editable },
() => {
console.log(this.state);
},
);
};
}
componentWillMount() {
fetchPostById(this.props.match.params.id)
.then(post => this.setState({ ...this.state, post }));
// console.log('hiii', this.state);
}
saveChanges(event) {
event.preventDefault();
this.setState({
errors: {},
});
const data = _.cloneDeep(this.state.post);
data.startDate = new Date(data.startDate).getTime().toString();
data.applyBy = new Date(data.applyBy).getTime().toString();
this.toggleEditability();
axios.put(`/api/admin/posts/${this.state.post._id}`, data, {
headers: {
Authorization: `bearer ${Auth.getToken()}`,
},
})
.then(() => {
this.props.history.goBack();
})
.catch((error) => {
console.error(error);
if (_.has(error, 'response')) {
if (error.response.status === 401 || error.response.status === 403) {
this.props.history.replace('/login');
} else if (error.response.status === 500) {
const errors = {};
errors.summary = 'There is a problem with the server. Try once again.';
this.setState({
errors,
});
} else {
const { errors } = error.response.data;
errors.summary = 'Check the form for errors.';
this.setState({
errors,
});
}
}
});
return null;
}
changeInternshipDetails(event) {
const field = event.target.name;
const internshipDetails = _.cloneDeep(this.state.post);
if (field === 'position') {
internshipDetails.position = event.target.value;
} else if (field === 'company') {
internshipDetails.company = event.target.value;
} else if (field === 'location') {
internshipDetails.location = event.target.value;
} else if (field === 'start-date') {
internshipDetails.startDate = event.target.value;
} else if (field === 'duration') {
internshipDetails.duration = event.target.value;
} else if (field === 'stipend') {
internshipDetails.stipend = event.target.value;
} else if (field === 'apply-by') {
internshipDetails.applyBy = event.target.value;
} else if (field === 'description-about') {
internshipDetails.description.about = event.target.value;
} else if (field === 'description-who-can-apply') {
internshipDetails.description.whoCanApply = event.target.value;
} else if (field === 'description-perks') {
internshipDetails.description.perks = event.target.value;
}
this.setState({ post: internshipDetails });
}
render() {
const { editable } = this.state;
if (!this.state.post) {
return <div>Loading...</div>;
}
return (
<Container text className="main" textAlign="justified">
{!editable &&
<div>
<Button
primary
floated="right"
content="Edit"
onClick={this.toggleEditability}
/>
<DisplayPost
internshipDetails={this.state.post}
/>
<Menu>
<Menu.Menu position="right">
<Menu.Item>
<Button onClick={handleViewApplicants} >View Applicants</Button>
</Menu.Item>
</Menu.Menu>
</Menu>
</div>
}
{editable &&
<EditPost
onSave={this.saveChanges}
onChange={this.changeInternshipDetails}
errors={this.state.errors}
internshipDetails={this.state.post}
/>
}
</Container>
);
}
}
/* const SubmitPostPage = () => (
<SubmitPostForm />
); */
PostView.propTypes = {
match: PropTypes.shape({
params: PropTypes.shape({
id: PropTypes.string.isRequired,
}).isRequired,
}).isRequired,
history: PropTypes.shape({
goBack: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired,
}).isRequired,
};
export default PostView;
/* SubmitPostPage.propTypes = {
history: PropTypes.shape({
goBack: PropTypes.func.isRequired,
replace: PropTypes.func.isRequired,
}).isRequired,
};
*/
|
javascript/AddOn/ShareStory.js | AppStateESS/stories | 'use strict'
import React from 'react'
import PropTypes from 'prop-types'
const ShareStory = ({shareList, shareStory, changeHost, hostId}) => {
if (shareList.length === 0) {
return null
}
let options = shareList.map((value, key) => {
return <option key={key} value={value.value}>{value.label}</option>
})
return (
<div className="row mb-2">
<div className="col-8">
<select className="form-control" onChange={changeHost} value={hostId}>
<option value="0"> </option>
{options}
</select>
</div>
<div className="col-4">
<button className="btn btn-primary" onClick={shareStory}>
<i className="fas fa-share"></i> Share</button>
</div>
</div>
)
}
ShareStory.propTypes = {
shareList: PropTypes.array,
changeHost: PropTypes.func,
shareStory: PropTypes.func,
hostId : PropTypes.oneOfType([PropTypes.string,PropTypes.number,]),
}
export default ShareStory
|
react-components/src/library/components/portal-classes/copy-dialog.js | concord-consortium/rigse | import React from 'react'
import css from './style.scss'
export default class CopyDialog extends React.Component {
constructor (props) {
super(props)
const { name, classWord, description } = props.clazz
this.state = {
name: `Copy of ${name}`,
classWord: `Copy of ${classWord}`,
description
}
this.handleUpdateName = this.handleUpdateName.bind(this)
this.handleUpdateClassWord = this.handleUpdateClassWord.bind(this)
this.handleUpdateDescription = this.handleUpdateDescription.bind(this)
this.handleSave = this.handleSave.bind(this)
}
handleUpdateName (e) {
this.setState({ name: e.target.value })
}
handleUpdateClassWord (e) {
this.setState({ classWord: e.target.value })
}
handleUpdateDescription (e) {
this.setState({ description: e.target.value })
}
handleSave () {
const { name, classWord, description } = this.state
this.props.handleSave({ name, classWord, description })
}
render () {
const { handleCancel, saving } = this.props
const { name, classWord, description } = this.state
const cancelSubmit = (e) => {
e.preventDefault()
e.stopPropagation()
}
const saveDisabled = saving || name.trim().length === 0 || classWord.trim().length === 0
return (
<div className={css.copyDialogLightbox}>
<div className={css.copyDialogBackground} />
<div className={css.copyDialog}>
<div className={css.copyTitle}>Copy Class</div>
<form onSubmit={cancelSubmit}>
<table>
<tbody>
<tr>
<td><label htmlFor='name'>Name</label></td>
<td><input name='name' value={name} onChange={this.handleUpdateName} /></td>
</tr>
<tr>
<td><label htmlFor='class_word'>Class Word</label></td>
<td><input name='class_word' value={classWord} onChange={this.handleUpdateClassWord} /></td>
</tr>
<tr>
<td className={css.description}><label htmlFor='description'>Description</label></td>
<td><textarea name='description' value={description} onChange={this.handleUpdateDescription} /></td>
</tr>
<tr>
<td colSpan='2' className={css.buttons}>
<button disabled={saveDisabled} onClick={this.handleSave}>{saving ? 'Saving ...' : 'Save'}</button>
<button onClick={handleCancel}>Cancel</button>
</td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
)
}
}
|
local-cli/templates/HelloNavigation/views/welcome/WelcomeText.ios.js | thotegowda/react-native | 'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
} from 'react-native';
export default class WelcomeText extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
This app shows the basics of navigating between a few screens,
working with ListView and handling text input.
</Text>
<Text style={styles.instructions}>
Modify any files to get started. For example try changing the
file{'\n'}views/welcome/WelcomeText.ios.js.
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu.
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: 'white',
padding: 20,
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 16,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 12,
},
});
|
docs/src/sections/PaginationSection.js | egauci/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function PaginationSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="pagination">Pagination</Anchor> <small>Pagination</small>
</h2>
<p>Provide pagination links for your site or app with the multi-page pagination component. Set <code>items</code> to the number of pages. <code>activePage</code> prop dictates which page is active</p>
<ReactPlayground codeText={Samples.PaginationBasic} />
<h4><Anchor id="pagination-more">More options</Anchor></h4>
<p>such as <code>first</code>, <code>last</code>, <code>previous</code>, <code>next</code>, <code>boundaryLinks</code> and <code>ellipsis</code>.</p>
<ReactPlayground codeText={Samples.PaginationAdvanced} />
<h3><Anchor id="pagination-props">Props</Anchor></h3>
<PropTable component="Pagination"/>
</div>
);
}
|
js/jqwidgets/demos/react/app/datatable/rowselectionhover/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxDataTable from '../../../jqwidgets-react/react_jqxdatatable.js';
import JqxDropDownList from '../../../jqwidgets-react/react_jqxdropdownlist.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
import JqxInput from '../../../jqwidgets-react/react_jqxinput.js';
class App extends React.Component {
componentDidMount() {
this.refs.selectionMode.on('change', (event) => {
switch (event.args.index) {
case 0:
// disable multiple rows selection with Shift or Ctrl.
this.refs.myDataTable.selectionMode('singleRow');
break;
case 1:
// enable multiple rows selection with Shift or Ctrl.
this.refs.myDataTable.selectionMode('multipleRows');
break;
}
});
this.refs.rowSelect.on('click', (event) => {
let index = parseInt(this.refs.rowInput.val());
this.refs.myDataTable.selectRow(index);
});
// clear selection.
this.refs.clearSelection.on('click', (event) => {
this.refs.myDataTable.clearSelection();
});
this.refs.myDataTable.on('rowSelect', (event) => {
// event arguments
let args = event.args;
// row index
let index = args.index;
// row data
let rowData = args.row;
// row key
let rowKey = args.key;
this.selectionInfo();
});
this.refs.myDataTable.on('rowUnselect', (event) => {
// event arguments
let args = event.args;
// row index
let index = args.index;
// row data
let rowData = args.row;
// row key
let rowKey = args.key;
this.selectionInfo();
});
}
selectionInfo() {
// gets selected row indexes. The method returns an Array of indexes.
let selection = this.refs.myDataTable.getSelection();
let selectedRows = '<br/>Selected Row Indexes:<br/>';
if (selection && selection.length > 0) {
let rows = this.refs.myDataTable.getRows();
for (let i = 0; i < selection.length; i++) {
let rowData = selection[i];
selectedRows += rows.indexOf(rowData);
if (i < selection.length - 1) {
selectedRows += ', ';
}
if (i > 1 && i % 8 === 0) {
selectedRows += '<br/>';
}
}
}
document.getElementById('selectedRows').innerHTML = selectedRows;
}
render() {
let columns =
[
{ text: 'First Name', dataField: 'First Name', width: 150 },
{ text: 'Last Name', dataField: 'Last Name', width: 150 },
{ text: 'Product', dataField: 'Product', width: 180 },
{ text: 'Unit Price', dataField: 'Price', width: 90, align: 'right', cellsAlign: 'right', cellsFormat: 'c2' },
{ text: 'Quantity', dataField: 'Quantity', width: 80, align: 'right', cellsAlign: 'right' }
];
return (
<div>
<JqxDataTable ref='myDataTable'
width={650} columns={columns} altRows={true}
>
<table border='1'>
<thead>
<tr>
<th align='left'>First Name</th>
<th align='left'>Last Name</th>
<th align='left'>Product</th>
<th align='right'>Price</th>
<th align='right'>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td>Ian</td>
<td>Devling</td>
<td>Espresso Truffle</td>
<td>$1.75</td>
<td>8</td>
</tr>
<tr>
<td>Nancy</td>
<td>Wilson</td>
<td>Cappuccino</td>
<td>$5.00</td>
<td>3</td>
</tr>
<tr>
<td>Cheryl</td>
<td>Nodier</td>
<td>Caffe Americano</td>
<td>$2.50</td>
<td>4</td>
</tr>
<tr>
<td>Martin</td>
<td>Saavedra</td>
<td>Caramel Latte</td>
<td>$3.80</td>
<td>11</td>
</tr>
<tr>
<td>Guylene</td>
<td>Bjorn</td>
<td>Green Tea</td>
<td>$1.50</td>
<td>8</td>
</tr>
<tr>
<td>Andrew</td>
<td>Burke</td>
<td>Caffe Espresso</td>
<td>$3.00</td>
<td>2</td>
</tr>
<tr>
<td>Regina</td>
<td>Murphy</td>
<td>White Chocolate Mocha</td>
<td>$3.60</td>
<td>6</td>
</tr>
<tr>
<td>Michael</td>
<td>Murphy</td>
<td>Caramel Latte</td>
<td>$3.80</td>
<td>2</td>
</tr>
<tr>
<td>Petra</td>
<td>Bein</td>
<td>Caffe Americano</td>
<td>$2.50</td>
<td>7</td>
</tr>
<tr>
<td>Nancy</td>
<td>Nodier</td>
<td>Caffe Latte</td>
<td>$4.50</td>
<td>10</td>
</tr>
<tr>
<td>Peter</td>
<td>Devling</td>
<td>Green Tea</td>
<td>$1.50</td>
<td>1</td>
</tr>
<tr>
<td>Beate</td>
<td>Saylor</td>
<td>Espresso con Panna</td>
<td>$3.25</td>
<td>3</td>
</tr>
<tr>
<td>Shelley</td>
<td>Nodier</td>
<td>Peppermint Mocha Twist</td>
<td>$4.00</td>
<td>7</td>
</tr>
<tr>
<td>Nancy</td>
<td>Murphy</td>
<td>Peppermint Mocha Twist</td>
<td>$4.00</td>
<td>1</td>
</tr>
<tr>
<td>Lars</td>
<td>Wilson</td>
<td>Caffe Espresso</td>
<td>$3.00</td>
<td>11</td>
</tr>
</tbody>
</table>
</JqxDataTable>
<div style={{ float: 'left', marginTop: 10 }}>
<div><strong>Settings</strong></div>
Select Row:
<JqxInput ref='rowInput' value='0'
width={60} height={30}
/>
<br />
<br />
<JqxButton ref='rowSelect' style={{ float: 'left' }}
width={105} height={30} value='Select'
/>
<JqxButton ref='clearSelection' style={{ float: 'left', marginLeft: 5 }}
width={105} height={30} value='Clear Selection'
/>
<div id='selectedRows'></div>
<br />
<div>Selection Mode:</div>
<JqxDropDownList ref='selectionMode'
height={30} source={['Single Row', 'Multiple Rows']}
selectedIndex={1} autoDropDownHeight={true}
/>
</div>
</div >
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/app/app.js | bolshchikov/notifications | import Relay from 'react-relay';
import React, { Component } from 'react';
import './app.css';
import Badge from '../badge/badge';
import Notifications from '../notifications/notifications';
class App extends Component {
componentWillMount() {
this.setState({
isOpened: false
});
}
toggle() {
this.setState({
isOpened: !this.state.isOpened
});
}
render() {
return (
<div className="app">
<Badge onClick={() => this.toggle() }/>
{this.state.isOpened && <Notifications />}
</div>
);
}
}
export default Relay.createContainer(App, {
fragments: {
unread: () => Relay.QL`
fragment on Unread {
unread
}
`
}
});
|
src/Header.js | AndrewCMartin/idb | import React from 'react'
import { Link } from 'react-router-dom'
import { Navbar, NavItem, Button, Container, Nav, MenuItem, NavDropdown, FormGroup, FormControl } from 'react-bootstrap'
import {LinkContainer} from 'react-router-bootstrap'
import './Header.css'
import SearchBar from "./SearchBar.js"
// The Header creates links that can be used to navigate
// between routes.
//Got the basic outline for the navbar from https://react-bootstrap.github.io/components.html#navigation
class Header extends React.Component {
constructor(props) {
super(props);
this.handleSearchPage = this.handleSearchPage.bind(this);
}
handleSearchPage() {
return (
<Link to="/about">
</Link>
);
}
render(){
return(
<Navbar className="navbar-default" inverse collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<a href="/">MARVELUS</a>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Nav pullRight>
<SearchBar />
</Nav>
<Navbar.Collapse>
<Nav>
<LinkContainer to="/about">
<NavItem eventKey={1}>About</NavItem>
</LinkContainer>
<LinkContainer to="/characters">
<NavItem eventKey={2}>Characters</NavItem>
</LinkContainer>
<LinkContainer to="/movies">
<NavItem eventKey={3}>Movies</NavItem>
</LinkContainer>
<LinkContainer to="/tvshows">
<NavItem eventKey={4}>TV Shows</NavItem>
</LinkContainer>
<LinkContainer to="/comicseries">
<NavItem eventKey={5}>Comic Series</NavItem>
</LinkContainer>
<LinkContainer to="/actors">
<NavItem eventKey={6}>Actors</NavItem>
</LinkContainer>
<LinkContainer to="/events">
<NavItem eventKey={7}>Events</NavItem>
</LinkContainer>
</Nav>
</Navbar.Collapse>
</Navbar>
)
}
}
export default Header
|
lib-module/browser.js | turacojs/fody | /* eslint react/no-render-return-value: "off" */
import React from 'react';
import ReactDOM from 'react-dom';
import DefaultApp from './App';
export { unmountComponentAtNode } from 'react-dom';
import _Helmet from 'react-helmet';
export { _Helmet as Helmet };
import _App from './App';
export { _App as App };
export default function render(_ref) {
var _ref$App = _ref.App,
App = _ref$App === undefined ? DefaultApp : _ref$App,
appProps = _ref.appProps,
View = _ref.View,
props = _ref.props,
element = _ref.element;
var app = React.createElement(
App,
appProps,
React.createElement(View, props)
);
return ReactDOM.render(app, element);
}
//# sourceMappingURL=browser.js.map |
templates/example/react/index.js | IveChen/saber-cli | /**
* @author chenjiancai
* @time 2017-07-18
*/
import './index.less';
import ReactDom from 'react-dom';
import React from 'react';
class HelloWorld extends React.Component{
render (){
return <h1>hello world ,i'm react components</h1>
}
}
ReactDom.render(<div>
<HelloWorld></HelloWorld>
</div>,document.getElementById('app')); |
src/svg-icons/editor/format-align-justify.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatAlignJustify = (props) => (
<SvgIcon {...props}>
<path d="M3 21h18v-2H3v2zm0-4h18v-2H3v2zm0-4h18v-2H3v2zm0-4h18V7H3v2zm0-6v2h18V3H3z"/>
</SvgIcon>
);
EditorFormatAlignJustify = pure(EditorFormatAlignJustify);
EditorFormatAlignJustify.displayName = 'EditorFormatAlignJustify';
EditorFormatAlignJustify.muiName = 'SvgIcon';
export default EditorFormatAlignJustify;
|
src/svg-icons/communication/call-missed.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationCallMissed = (props) => (
<SvgIcon {...props}>
<path d="M19.59 7L12 14.59 6.41 9H11V7H3v8h2v-4.59l7 7 9-9z"/>
</SvgIcon>
);
CommunicationCallMissed = pure(CommunicationCallMissed);
CommunicationCallMissed.displayName = 'CommunicationCallMissed';
CommunicationCallMissed.muiName = 'SvgIcon';
export default CommunicationCallMissed;
|
src/container/Home/index.js | jcxk/ethercity | import aframe from 'aframe';
import {Entity, Scene} from 'aframe-react';
import React from 'react';
import {connect} from 'react-redux';
import {AppBar} from "material-ui";
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import Drawer from 'material-ui/Drawer';
import Form from './Form';
import * as AppActions from "../../actions/app";
//truffle test
import truffleConfig from '../../../truffle.js';
import Web3 from 'web3';
import MetaCoin from '../../../contracts/MetaCoin.sol';
if (typeof window !== 'undefined' &&
typeof window.web3 !== 'undefined') {
// Use Mist/MetaMask's provider
web3 = new Web3(window.web3.currentProvider)
} else {
// fallback - use your fallback strategy (local node / hosted node + in-dapp id mgmt / fail)
web3 = new Web3(new Web3.providers.HttpProvider('http://localhost:8545'))
}
export class Home extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
this.handleToggle = this.handleToggle.bind(this);
this.handleClose = this.handleClose.bind(this);
this.addHouse = this.addHouse.bind(this);
console.log(this.props);
}
handleToggle() {
this.setState({open: !this.state.open});
}
handleClose() {
this.setState({open: true});
}
componentDidMount() {
//const { dispatch } = this.props;
var web3Location = `http://${truffleConfig.rpc.host}:${truffleConfig.rpc.port}`;
if (typeof web3 !== 'undefined') {
web3Provided = new Web3(web3.currentProvider);
} else {
web3Provided = new Web3(new Web3.providers.HttpProvider(web3Location))
}
MetaCoin.setProvider(web3Provided.currentProvider);
var meta = MetaCoin.deployed()
return new Promise((resolve, reject) => {
meta.getBalance.call(account, {from: account}).then(function (value) {
resolve({ account: value.valueOf() })
}).catch(function (e) {
console.log(e)
reject()
})
});
this.props.dispatch(AppActions.fetchCity());
}
addHouse(values) {
console.log(values);
this.props.dispatch(AppActions.addHouse(values));
}
render() {
if (this.props.city !== undefined) {
return (
<div>
<MuiThemeProvider>
<div>
<AppBar
onLeftIconButtonTouchTap={this.handleToggle}
title="ETHereum City"
/>
<Drawer width="20%"
docked={true}
open={this.state.open}
onRequestChange={(open) => this.setState({open})}
>
<Form onSubmit={this.addHouse}/>
</Drawer>
</div>
</MuiThemeProvider>
<Scene>
<a-assets>
<a-asset-item id="road_asset_obj" src="/assets/obj/base_street1.obj"/>
<a-asset-item id="road_asset_mtl" src="/assets/obj/base_street1.mtl"/>
<a-asset-item id="house1_obj" src="/assets/obj/bld_house1.obj"/>
<a-asset-item id="house1_mtl" src="/assets/obj/bld_house1.mtl"/>
<a-asset-item id="grass_obj" src="/assets/obj/base_grass1.obj"/>
<a-asset-item id="grass_mtl" src="/assets/obj/base_grass1.mtl"/>
<img alt="ground" id="groundTexture"
src="https://cdn.aframe.io/a-painter/images/floor.jpg"/>
<img alt="sky" id="skyTexture" src="https://cdn.aframe.io/a-painter/images/sky.jpg"/>
</a-assets>
<Entity primitive="a-plane" src="#groundTexture" rotation="-90 0 0" height="100" width="100"/>
<Entity primitive="a-light" type="ambient" color="#445451"/>
<Entity primitive="a-light" type="point" intensity="2" position="2 4 4"/>
<Entity primitive="a-sky" height="2048" radius="30" src="#skyTexture" theta-length="90"
width="2048"/>
<Entity particle-system={{preset: 'snow', particleCount: 2000}}/>
<Entity text={{value: 'Hello, A-Frame React!', align: 'center'}}
position={{x: 0, y: 2, z: -1}}/>
<Entity id="city" position={{x: 0, y: 0, z: 0}}>
{this.props.city.map((item) => {
let objModel = `obj: #${item.asset_name}_obj; mtl: #${item.asset_name}_mtl;`;
return [
<Entity position="0 0 0.4" scale="0.01 0.01 0.01"
obj-model="obj: #road_asset_obj; mtl: #road_asset_mtl;"></Entity>,
<Entity position={item.pos} scale="0.01 0.01 0.01"
obj-model="obj: #grass_obj; mtl: #grass_mtl;"></Entity>,
<Entity click-drag position={item.pos} scale="0.004 0.004 0.004"
obj-model={objModel}></Entity>
]
})}
</Entity>
<a-entity id="cameraWrapper" position="-1.4 1.41 2.92"
rotation="-12.834254610930437 -16.844959176846217 0">
<a-entity id="camera" touch-controls camera look-controls wasd-controls="fly: true"></a-entity>
</a-entity>
</Scene>
</div>
);
}
else {
return <p>Loading</p>
}
}
}
function mapStateToProps(state) {
return {
city: state.app.objects
};
}
export default connect(mapStateToProps)(Home); |
client/reduxstagram.js | phattranky/LearnRedux_ReactD3 | import React from 'react';
import { render } from 'react-dom';
import css from './styles/style.styl';
import App from './components/App';
import Single from './components/Single';
import PhotoGrid from './components/PhotoGrid';
import ChartContainer from './components/ChartContainer';
// import react router deps
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import store, { history } from './store';
const router = (
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={PhotoGrid}></IndexRoute>
<Route path="/view/:postId" component={Single}></Route>
<Route path="/chart" component={ChartContainer}></Route>
</Route>
</Router>
</Provider>
)
//render(<Main><p>Hello Children of Main</p></Main>, document.getElementById('root'));
render(router, document.getElementById('root')); |
pages/people/seramirezra.js | pcm-ca/pcm-ca.github.io | import React from 'react'
import { Link } from 'react-router'
import Helmet from 'react-helmet'
import { config } from 'config'
import { prefixLink } from 'gatsby-helpers'
import bib from './bib'
import info from './info'
import PersonPage from '../../components/PersonPage'
export default class Index extends React.Component {
render() {
return (
<div>
<Helmet title={config.siteTitle + ' | people | seramirezra'} />
<PersonPage
{...info.seramirezra}
picture="../images/seramirezra.jpg"
/>
</div>
)
}
}
|
src/sentry/static/sentry/app/icons/icon-open.js | looker/sentry | import React from 'react';
import Icon from 'react-icon-base';
function IconOpen(props) {
return (
<Icon viewBox="0 0 15 15" {...props}>
<g stroke="currentColor" fill="none" strokeLinecap="round" strokeLinejoin="round">
<path
d="M14.5,8.5 L14.5,13.1823525 C14.5,13.9100691 13.9162615,14.5 13.182914,14.5 L1.81708601,14.5 C1.08967949,14.5 0.5,13.9162615 0.5,13.182914 L0.5,1.81708601 C0.5,1.08967949 1.09439142,0.5 1.80585884,0.5 L6.5,0.5"
id="outer-path"
/>
<path d="M7.5,7.5 L14.5,0.5" id="line" />
<polyline id="arrow" points="9.5 0.5 14.5 0.5 14.5 5.5" />
</g>
</Icon>
);
}
export default IconOpen;
|
packages/react/src/Login.js | js-accounts/react | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import isString from 'lodash/isString';
import { Form, FormInput } from 'react-form';
class Login extends Component {
static propTypes = {
accounts: PropTypes.object,
setFormType: PropTypes.func,
Avatar: PropTypes.func,
LoginFields: PropTypes.func,
LoginUserField: PropTypes.func,
LoginPasswordField: PropTypes.func,
RecoverButton: PropTypes.func,
LoginButton: PropTypes.func,
SignupButton: PropTypes.func,
Header: PropTypes.func,
Footer: PropTypes.func,
Container: PropTypes.func,
Content: PropTypes.func,
FormError: PropTypes.func,
}
static defaultProps = {
Container: () => <div />,
Header: () => <div />,
Content: () => <div />,
Footer: () => <div />,
};
constructor(props, context) {
super(props, context);
this.state = {
formError: '',
};
}
onSubmit = async (values) => {
const { accounts } = this.props;
this.setState({
formError: '',
});
try {
await accounts.loginWithPassword(values.user, values.password);
} catch (err) {
this.setState({
formError: err.message,
});
}
}
validate = ({
user,
password,
}) => ({
user: !user ? 'Username or Email is required' : undefined,
password: !password ? 'Password is required' : undefined,
})
render() {
const {
Container,
Content,
Header,
Footer,
Avatar,
LoginFields,
LoginUserField,
LoginPasswordField,
LoginButton,
RecoverButton,
FormError,
...otherProps
} = this.props;
return (
<Container>
<Header />
<Content {...otherProps}>
<Avatar {...otherProps} />
<Form
onSubmit={this.onSubmit}
validate={this.validate}
>
{form =>
<LoginFields>
<FormInput field="user" showErrors={false}>
{() =>
<LoginUserField
{...form}
label="Username or email"
value={form.getValue('user', '')}
onChange={e => form.setValue('user', e.target.value)}
errorText={form.getTouched('user') && isString(form.getError('user')) ? form.getError('user') : ''}
/>
}
</FormInput>
<FormInput field="password" showErrors={false}>
{() =>
<LoginPasswordField
{...form}
label="Password"
onChange={e => form.setValue('password', e.target.value)}
value={form.getValue('password', '')}
errorText={form.getTouched('password') && isString(form.getError('password')) ? form.getError('password') : ''}
/>
}
</FormInput>
<LoginButton
label="Sign in"
onClick={form.submitForm}
{...otherProps}
/>
</LoginFields>
}
</Form>
<RecoverButton {...otherProps} />
<FormError errorText={this.state.formError} />
</Content>
<Footer />
</Container>
);
}
}
export default Login;
|
frontend/src/index.js | omidfi/moro | import React from 'react';
import ReactDOM from 'react-dom';
import { App } from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root'),
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
server/sonar-web/src/main/js/apps/overview/components/EmptyOverview.js | Builders-SonarSource/sonarqube-bis | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import { translate } from '../../../helpers/l10n';
const EmptyOverview = ({ component }) => {
return (
<div className="page page-limited">
<div className="alert alert-warning">
{translate('provisioning.no_analysis')}
</div>
<div className="big-spacer-top">
<h4>{translate('key')}</h4>
<code>{component.key}</code>
</div>
</div>
);
};
export default EmptyOverview;
|
src/components/progress/Progress.js | ProAI/react-essentials | import React from 'react';
import PropTypes from 'prop-types';
import BaseView from '../../utils/rnw-compat/BaseView';
import ProgressBar from './ProgressBar';
import ProgressContext from './ProgressContext';
import useProgress from './useProgress';
const propTypes = {
children: PropTypes.node.isRequired,
min: PropTypes.number,
max: PropTypes.number,
// eslint-disable-next-line react/forbid-prop-types
style: PropTypes.any,
};
const Progress = React.forwardRef((props, ref) => {
const { min = 0, max = 100, style, ...elementProps } = props;
const progress = useProgress(min, max);
return (
<ProgressContext.Provider value={progress}>
<BaseView
{...elementProps}
ref={ref}
style={[style, { flexDirection: 'row' }]}
essentials={{ className: 'progress' }}
/>
</ProgressContext.Provider>
);
});
Progress.displayName = 'Progress';
Progress.propTypes = propTypes;
Progress.Bar = ProgressBar;
export default Progress;
|
packages/material-ui-icons/src/Polymer.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Polymer = props =>
<SvgIcon {...props}>
<path d="M19 4h-4L7.11 16.63 4.5 12 9 4H5L.5 12 5 20h4l7.89-12.63L19.5 12 15 20h4l4.5-8z" />
</SvgIcon>;
Polymer = pure(Polymer);
Polymer.muiName = 'SvgIcon';
export default Polymer;
|
views/topic_page.js | SpaceyRezum/react-trivia-game | import React from 'react';
import { Link } from 'react-router';
import firebase from 'firebase';
import Quiz from '../components/quiz';
import TopScores from '../components/top_scores';
class TopicPage extends React.Component {
constructor(props) {
super(props);
this.state = {
quizName: '',
category: '',
questions: [],
perfectScore: 'a',
userHighestScore: 0
}
this.setUserHighestScore = this.setUserHighestScore.bind(this);
this.setPerfectScore = this.setPerfectScore.bind(this);
}
componentDidMount() {
this.getQuizInfo();
}
render() {
return (
<div className="col-12">
<div className="row">
<aside className="quiz-title col-xs-12 col-sm-12 col-md-3 col-lg-3">
<h2 className="trivia--game">
{ (this.props.params.topic).replace(/-/g, " ") }
</h2>
<TopScores
userHighestScore={ this.state.userHighestScore }
perfectScore={ this.state.perfectScore }
quizName={ this.state.quizName }
/>
</aside>
<Quiz
questions={ this.state.questions }
userHighestScore={ this.state.userHighestScore }
setPerfectScore={ this.setPerfectScore }
setUserHighestScore={ this.setUserHighestScore }
/>
</div>
</div>
)
}
getQuizInfo() {
const quizName = (this.props.params.topic).replace(/-/g, " ");
const firebaseRef = firebase.database().ref("/quizzes/" + quizName);
firebaseRef.once('value', (snapshot) => {
let category = snapshot.val().category;
let questions = [];
for (let i = 0; i < snapshot.val().questionList.length; i++) {
questions.push(snapshot.val().questionList[i]);
}
this.setState({
quizName: quizName,
category: category,
questions: questions });
// once the app retrieves which quiz the user is on,
// it checks whether user already has a score stored for this quiz
this.getUserHighestScore(this.props.userID, quizName);
});
}
setPerfectScore(perfectScore) {
this.setState({
perfectScore: perfectScore
});
}
setUserHighestScore(highestScore) {
let userID = this.props.userID;
let userAvatar = this.props.user.photoURL;
let userName = this.props.user.displayName;
let quizName = this.state.quizName;
let score = highestScore;
const firebaseRef = firebase.database().ref("/quizzes/" + quizName + "/scores/" + userID);
// create an object as userID : score and pushes it to firebase
let update = {
name: userName,
avatar: userAvatar,
score: score
};
firebaseRef.set(update);
}
getUserHighestScore(userID, quizName) {
const firebaseRef = firebase.database().ref("/quizzes/" + quizName + "/scores/" + userID);
firebaseRef.on('value', (snapshot) => {
if (snapshot.val()) {
let userScore = snapshot.val().score;
let userHighestScore;
if (!userScore) {
userHighestScore = 0;
} else {
userHighestScore = userScore;
}
this.setState({
userHighestScore: userHighestScore
});
}
});
}
}
export default TopicPage; |
src/organisms/cards/FeaturedPolicyCard/index.js | policygenius/athenaeum | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import accounting from 'accounting';
import Text from 'atoms/Text';
import Spacer from 'atoms/Spacer';
import styles from './featured_policy_card.module.scss';
import ButtonGroup from './ButtonGroup';
import PolicyInformation from './PolicyInformation';
function FeaturedPolicyCard(props) {
const {
carrierLogo,
className,
continueCTAText,
discount,
header,
information,
onContinue,
onDetails,
onCompare,
policyHat,
premium,
} = props;
const classes = [
styles['featured-policy-card'],
className,
];
const contentClasses = classnames(
styles['content'],
policyHat && styles['policy-hat'],
);
const premiumValues = accounting.toFixed(premium.price, 2).split('.');
const dollars = premiumValues[0];
const cents = premiumValues[1];
return (
<div className={classnames(...classes)}>
<div className={contentClasses}>
{ header && header }
<Spacer small />
{ premium.price ? (
<div className={styles['premium']}>
<div className={styles['value']}>
<Text
size={6}
font='a'
className={styles['value-small']}
>
$
</Text>
<Text
size={2}
font='a'
className={styles['value-dollars']}
>
{dollars}
</Text>
<Text
size={6}
font='a'
className={styles['value-small']}
>
.
{cents}
</Text>
<Text
tag='span'
size={11}
font='a'
spaced
color='neutral-2'
className={styles['value-format']}
>
{`/${premium.format.toUpperCase()}`}
</Text>
</div>
<Spacer spacer={1} />
{discount && discount}
</div>
)
:
<Text size={7} color='neutral-2' className={styles['default-text']}>{premium.defaultText}</Text>}
<Spacer spacer={6} />
<div className={styles['carrier-logo']}>
{ carrierLogo }
</div>
<Spacer spacer={6} />
{ information && <PolicyInformation information={information} /> }
<ButtonGroup
onContinue={onContinue}
onDetails={onDetails}
onCompare={onCompare}
continueCTAText={continueCTAText}
/>
</div>
</div>
);
}
FeaturedPolicyCard.propTypes = {
/**
* This prop will add a new className to any inherent classNames
* provided in the component's index.js file.
*/
className: PropTypes.string,
/**
* Array of nodes to display in header
*/
header: PropTypes.arrayOf(PropTypes.node),
/**
* Displays premium value
*
* `defaultText` replaces `price` is `price` is not available
*/
premium: PropTypes.shape({
price: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
format: PropTypes.string,
defaultText: PropTypes.string,
}),
/**
* Displays discount message below premium
*/
discount: PropTypes.node,
/**
* Image for carrier logo
*/
carrierLogo: PropTypes.node,
/**
* Text displayed for the main action button
*/
continueCTAText: PropTypes.string,
/**
* Function supplied to details link below CTA
*/
onContinue: PropTypes.func.isRequired,
/**
* Function supplied to details link below CTA
*/
onDetails: PropTypes.func,
/**
* Function supplied to compare CTA on mobile only
*/
onCompare: PropTypes.func,
/**
* Supplies information about policy to card. Examples would include type, financial strength or total customers
*/
information: PropTypes.arrayOf(PropTypes.shape({
label: PropTypes.string.isRequired,
value: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]).isRequired,
hoverMessage: PropTypes.node.isRequired,
})),
/**
* Setting this to true will add a 'hat' to the policy card
*/
policyHat: PropTypes.bool,
detailsCTAText: PropTypes.string
};
FeaturedPolicyCard.defaultProps = {
continueCTAText: 'Continue',
detailsCTAText: 'Details & Review',
policyHat: false
};
export default FeaturedPolicyCard;
|
test-client/src/App.js | synapsestudios/oidc-platform | import React, { Component } from 'react';
import queryString from 'query-string';
import localstorage from 'store2';
import { createBrowserHistory as createHistory } from 'history';
import config from './config';
import './App.css';
import { getLoginUrl } from './oidc-url-builders';
import InviteUserForm from './components/InviteUserForm';
import UserProfileForm from './components/UserProfileForm';
const history = createHistory();
class App extends Component {
constructor(props) {
super(props);
this.state = {
email: '',
password: '',
};
}
login = () => {
fetch(`${config.testServer}token`, {
method: 'POST',
body: JSON.stringify({ grant_type: 'password', username: this.state.email, password: this.state.password }),
})
.then(res => res.json())
.then(json => {
if (json.statusCode >= 300) {
console.error(json)
} else {
localstorage({
accessToken: json.access_token,
expiresIn: json.expires_in,
idToken: json.id_token,
tokenType: json.token_type,
});
this.setState(localstorage());
}
})
.catch(e => console.error(e));
}
componentWillMount() {
if (location.pathname === '/logout') {
localstorage.clear();
history.replace('/');
} else {
this.checkForCode();
}
}
checkForCode() {
const query = queryString.parse(location.hash.substr(1));
if (query.id_token && !localstorage('accessToken')) {
localstorage({
accessToken: query.access_token,
expiresIn: query.expires_in,
idToken: query.id_token,
tokenType: query.token_type,
});
this.setState(localstorage());
history.replace('/');
} else if (localstorage('accessToken')) {
this.setState(localstorage());
}
}
renderLoggedOutContent() {
return (
<div>
<span>
<a href={getLoginUrl()}>Log In</a>
<span> | </span>
<a href={`https://sso-client.test:9000/user/register?client_id=${config.clientId}&response_type=id_token token&scope=${config.scope}&redirect_uri=${config.redirectUri}&nonce=nonce`}>Sign Up</a>
</span>
<div>
<input type="text" id="email" value={this.state.email} onChange={({ target }) => this.setState(() => ({ email: target.value }))} />
<input type="password" id="password" value={this.state.password} onChange={({ target }) => this.setState(() => ({ password: target.value }))}/>
<button onClick={this.login}>login with password grant</button>
</div>
</div>
);
}
renderLoggedInContent() {
return (
<div>
<p>Logged In</p>
<div>
<h2>Access Token</h2>
<p>{this.state.accessToken}</p>
<h2>Expires In</h2>
<p>{this.state.expiresIn}</p>
<h2>Id Token</h2>
<p>{this.state.idToken}</p>
<h2>Token Type</h2>
<p>{this.state.tokenType}</p>
</div>
<div>
<InviteUserForm />
<UserProfileForm />
<div><a href={`https://sso-client.test:9000/user/profile?client_id=${config.clientId}&redirect_uri=${config.redirectUri}&access_token=${this.state.accessToken}`}>Edit Profile</a></div>
<div><a href={`https://sso-client.test:9000/user/password?client_id=${config.clientId}&redirect_uri=${config.redirectUri}`}>Change Password</a></div>
<div><a href={`https://sso-client.test:9000/user/email-settings?client_id=${config.clientId}&redirect_uri=${config.redirectUri}`}>Email Settings</a></div>
<div><a href={`https://sso-client.test:9000/op/session/end?id_token_hint=${this.state.idToken}&post_logout_redirect_uri=${config.postLogoutRedirectUri}`}>Log Out</a></div>
<div><a href={`https://sso-client.test:9000/user/logout?post_logout_redirect_uri=${config.postLogoutRedirectUri}`}>One-click log Out</a></div>
</div>
</div>
);
}
render() {
return (
<div className="App">
<div className="App-header">
<h2>Synapse Identity Platform</h2>
</div>
{!this.state.accessToken ? this.renderLoggedOutContent() : this.renderLoggedInContent()}
</div>
);
}
}
export default App;
|
contact/components/Footer.js | linuxing3/electron-react | import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="SHOW_ALL">
All
</FilterLink>
{", "}
<FilterLink filter="SHOW_ACTIVE">
Active
</FilterLink>
{", "}
<FilterLink filter="SHOW_COMPLETED">
Completed
</FilterLink>
</p>
)
export default Footer |
src/svg-icons/hardware/desktop-windows.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareDesktopWindows = (props) => (
<SvgIcon {...props}>
<path d="M21 2H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h7v2H8v2h8v-2h-2v-2h7c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H3V4h18v12z"/>
</SvgIcon>
);
HardwareDesktopWindows = pure(HardwareDesktopWindows);
HardwareDesktopWindows.displayName = 'HardwareDesktopWindows';
HardwareDesktopWindows.muiName = 'SvgIcon';
export default HardwareDesktopWindows;
|
src/features/common/LoginPage.js | thehig/arpggio-firebase-client | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { firebaseConnect } from 'react-redux-firebase';
import { browserHistory } from 'react-router';
import FlatButton from 'material-ui/FlatButton';
import * as actions from './redux/actions';
import { globalSelectors } from '../../common/rootReducer';
import { LoginForm } from './';
@firebaseConnect()
export class LoginPage extends Component {
static propTypes = {
common: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired,
firebase: PropTypes.object.isRequired,
logged: PropTypes.bool.isRequired,
next: PropTypes.string,
};
static defaultProps = {
next: null,
}
constructor(props) {
super(props);
this.onLoginClick = ::this.onLoginClick;
this.onLoginSubmit = ::this.onLoginSubmit;
this.redirectIfLoggedIn = ::this.redirectIfLoggedIn;
}
componentWillMount() {
// User enters page when logged in
this.redirectIfLoggedIn({
logged: this.props.logged,
next: this.props.next,
});
}
componentWillReceiveProps(nextProps) {
// User was on this page, but their auth state changed
// This can happen when you refresh the app and
// Firebase takes a second to auth you
this.redirectIfLoggedIn({
logged: nextProps.logged,
next: nextProps.next,
});
}
onLoginClick() {
this.props.actions.firebaseLogin(this.props.firebase);
}
onLoginSubmit(submitForm) {
// SubmitForm can be an Immutable map, or a basic JSON obj
console.log('onLoginSubmit', submitForm);
}
redirectIfLoggedIn({ logged, next }) {
if (logged) {
browserHistory.replace(next || '/home');
}
}
render() {
return (
<div className="common-login">
Page Content: common/Login
<FlatButton onTouchTap={this.onLoginClick} label="Login With Google" />
<LoginForm onSubmit={this.onLoginSubmit} />
</div>
);
}
}
function nextRoute(ownProps) {
if (
ownProps &&
ownProps.location &&
ownProps.location.query &&
ownProps.location.query.next) {
return ownProps.location.query.next;
}
return undefined;
}
/* istanbul ignore next */
function mapStateToProps(state, ownProps) {
return {
common: state.get('common'),
logged: globalSelectors.logged(state),
next: nextRoute(ownProps),
};
}
/* istanbul ignore next */
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({ ...actions }, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(LoginPage);
|
src/components/Sections/SectionText.js | demisto/sane-reports | import './SectionText.less';
import React from 'react';
import PropTypes from 'prop-types';
const SectionText = ({ text, style }) =>
<div className="section-text" style={style}>
{text}
</div>;
SectionText.propTypes = {
text: PropTypes.string,
style: PropTypes.object
};
export default SectionText;
|
app/components/IssueIcon/index.js | simon-johansson/PB-labz | import React from 'react';
function IssueIcon(props) {
return (
<svg
height="1em"
width="0.875em"
className={props.className}
>
<path d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7S10.14 13.7 7 13.7 1.3 11.14 1.3 8s2.56-5.7 5.7-5.7m0-1.3C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7S10.86 1 7 1z m1 3H6v5h2V4z m0 6H6v2h2V10z" />
</svg>
);
}
IssueIcon.propTypes = {
className: React.PropTypes.string,
};
export default IssueIcon;
|
app/javascript/mastodon/components/button.js | unarist/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class Button extends React.PureComponent {
static propTypes = {
text: PropTypes.node,
onClick: PropTypes.func,
disabled: PropTypes.bool,
block: PropTypes.bool,
secondary: PropTypes.bool,
size: PropTypes.number,
className: PropTypes.string,
style: PropTypes.object,
children: PropTypes.node,
};
static defaultProps = {
size: 36,
};
handleClick = (e) => {
if (!this.props.disabled) {
this.props.onClick(e);
}
}
setRef = (c) => {
this.node = c;
}
focus() {
this.node.focus();
}
render () {
const style = {
padding: `0 ${this.props.size / 2.25}px`,
height: `${this.props.size}px`,
lineHeight: `${this.props.size}px`,
...this.props.style,
};
const className = classNames('button', this.props.className, {
'button-secondary': this.props.secondary,
'button--block': this.props.block,
});
return (
<button
className={className}
disabled={this.props.disabled}
onClick={this.handleClick}
ref={this.setRef}
style={style}
>
{this.props.text || this.props.children}
</button>
);
}
}
|
src/admin/client/modules/products/edit/additional/components/productCategoryMultiSelect.js | cezerin/cezerin | import React from 'react';
import { Field, FieldArray, reduxForm } from 'redux-form';
import messages from 'lib/text';
import style from './style.css';
import CategoryMultiselect from 'modules/productCategories/components/multiselectList';
import FontIcon from 'material-ui/FontIcon';
import Dialog from 'material-ui/Dialog';
import FlatButton from 'material-ui/FlatButton';
import RaisedButton from 'material-ui/RaisedButton';
const Fragment = React.Fragment;
const CategoryItemActions = ({ fields, index }) => (
<a
title={messages.actions_delete}
onClick={() => fields.remove(index)}
className="react-tagsinput-remove"
/>
);
const CategoryItem = ({ categoryName, actions }) => (
<span className="react-tagsinput-tag">
{categoryName}
{actions}
</span>
);
export default class ProductCategoryMultiSelect extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
close = () => {
this.setState({ open: false });
};
open = () => {
this.setState({ open: true });
};
handleCheck = categoryId => {
const selectedIds = this.props.fields.getAll();
if (selectedIds && selectedIds.includes(categoryId)) {
// remove
this.props.fields.forEach((name, index, fields) => {
if (fields.get(index) === categoryId) {
fields.remove(index);
return;
}
});
} else {
// add
this.props.fields.push(categoryId);
}
};
render() {
const {
categories,
fields,
meta: { touched, error, submitFailed }
} = this.props;
const { open } = this.state;
const selectedIds = fields.getAll();
const dialogButtons = [
<FlatButton
label={messages.cancel}
onClick={this.close}
style={{ marginRight: 10 }}
/>,
<FlatButton
label={messages.save}
primary={true}
keyboardFocused={true}
onClick={this.close}
/>
];
return (
<div className="react-tagsinput">
<span>
{fields.map((field, index) => {
const categoryId = fields.get(index);
const category = categories.find(item => item.id === categoryId);
const categoryName = category ? category.name : '-';
const actions = (
<CategoryItemActions fields={fields} index={index} />
);
return (
<CategoryItem
key={index}
categoryName={categoryName}
actions={actions}
/>
);
})}
<Dialog
title={messages.additionalCategories}
actions={dialogButtons}
modal={false}
open={open}
onRequestClose={this.close}
autoScrollBodyContent={true}
>
<CategoryMultiselect
items={categories}
selectedIds={selectedIds}
opened={false}
onCheck={this.handleCheck}
/>
</Dialog>
<FlatButton
style={{ minWidth: 52 }}
onClick={this.open}
icon={
<FontIcon color="#333" className="material-icons">
add
</FontIcon>
}
/>
</span>
</div>
);
}
}
|
src/app/entry.js | JoeKarlsson1/bechdel-test | import React from 'react';
import ReactDOM from 'react-dom';
import { BrowserRouter as Router } from 'react-router-dom';
import PrimaryLayout from './shared/PrimaryLayout/PrimaryLayout';
import ErrorBoundary from './shared/ErrorBoundary/ErrorBoundary';
ReactDOM.render(
<ErrorBoundary>
<Router>
<PrimaryLayout />
</Router>
</ErrorBoundary>,
document.getElementById('root')
);
|
src/demos/building-a-geospatial-app/4-basic-charts/src/app.js | uber-common/vis-academy | /* global window */
import React, { Component } from 'react';
import { StaticMap } from 'react-map-gl';
import { LayerControls, MapStylePicker, HEXAGON_CONTROLS } from './controls';
import { tooltipStyle } from './style';
import DeckGL from 'deck.gl';
import taxiData from '../../../data/taxi';
import { renderLayers } from './deckgl-layers';
import Charts from './charts';
const INITIAL_VIEW_STATE = {
longitude: -74,
latitude: 40.7,
zoom: 11,
minZoom: 5,
maxZoom: 16,
pitch: 0,
bearing: 0
};
export default class App extends Component {
state = {
hover: {
x: 0,
y: 0,
hoveredObject: null
},
points: [],
settings: Object.keys(HEXAGON_CONTROLS).reduce(
(accu, key) => ({
...accu,
[key]: HEXAGON_CONTROLS[key].value
}),
{}
),
style: 'mapbox://styles/mapbox/light-v9'
};
componentDidMount() {
this._processData();
}
_processData = () => {
const data = taxiData.reduce(
(accu, curr) => {
const pickupHour = new Date(curr.pickup_datetime).getUTCHours();
const dropoffHour = new Date(curr.dropoff_datetime).getUTCHours();
const pickupLongitude = Number(curr.pickup_longitude);
const pickupLatitude = Number(curr.pickup_latitude);
if (!isNaN(pickupLongitude) && !isNaN(pickupLatitude)) {
accu.points.push({
position: [pickupLongitude, pickupLatitude],
hour: pickupHour,
pickup: true
});
}
const dropoffLongitude = Number(curr.dropoff_longitude);
const dropoffLatitude = Number(curr.dropoff_latitude);
if (!isNaN(dropoffLongitude) && !isNaN(dropoffLatitude)) {
accu.points.push({
position: [dropoffLongitude, dropoffLatitude],
hour: dropoffHour,
pickup: false
});
}
const prevPickups = accu.pickupObj[pickupHour] || 0;
const prevDropoffs = accu.dropoffObj[dropoffHour] || 0;
accu.pickupObj[pickupHour] = prevPickups + 1;
accu.dropoffObj[dropoffHour] = prevDropoffs + 1;
return accu;
},
{
points: [],
pickupObj: {},
dropoffObj: {}
}
);
data.pickups = Object.entries(data.pickupObj).map(([hour, count]) => {
return { hour: Number(hour), x: Number(hour) + 0.5, y: count };
});
data.dropoffs = Object.entries(data.dropoffObj).map(([hour, count]) => {
return { hour: Number(hour), x: Number(hour) + 0.5, y: count };
});
this.setState(data);
};
_onHover({ x, y, object }) {
const label = object
? object.points
? `${object.points.length} pickups or dropoffs here`
: object.pickup
? 'Pickup'
: 'Dropoff'
: null;
this.setState({ hover: { x, y, hoveredObject: object, label } });
}
onStyleChange = style => {
this.setState({ style });
};
_onWebGLInitialize = gl => {
gl.enable(gl.DEPTH_TEST);
gl.depthFunc(gl.LEQUAL);
};
_updateLayerSettings(settings) {
this.setState({ settings });
}
render() {
const data = this.state.points;
if (!data.length) {
return null;
}
const { hover, settings } = this.state;
return (
<div>
{hover.hoveredObject && (
<div
style={{
...tooltipStyle,
transform: `translate(${hover.x}px, ${hover.y}px)`
}}
>
<div>{hover.label}</div>
</div>
)}
<MapStylePicker
onStyleChange={this.onStyleChange}
currentStyle={this.state.style}
/>
<LayerControls
settings={this.state.settings}
propTypes={HEXAGON_CONTROLS}
onChange={settings => this._updateLayerSettings(settings)}
/>
<DeckGL
{...this.state.settings}
onWebGLInitialized={this._onWebGLInitialize}
layers={renderLayers({
data: this.state.points,
onHover: hover => this._onHover(hover),
settings: this.state.settings
})}
initialViewState={INITIAL_VIEW_STATE}
controller
>
<StaticMap mapStyle={this.state.style} />
</DeckGL>
<Charts {...this.state} />
</div>
);
}
}
|
app/javascript/mastodon/features/favourites/index.js | pointlessone/mastodon | import React from 'react';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import { fetchFavourites } from '../../actions/interactions';
import { FormattedMessage } from 'react-intl';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import ColumnBackButton from '../../components/column_back_button';
import ScrollableList from '../../components/scrollable_list';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'favourited_by', props.params.statusId]),
});
export default @connect(mapStateToProps)
class Favourites extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
accountIds: ImmutablePropTypes.list,
};
componentWillMount () {
this.props.dispatch(fetchFavourites(this.props.params.statusId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchFavourites(nextProps.params.statusId));
}
}
render () {
const { shouldUpdateScroll, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.favourites' defaultMessage='No one has favourited this toot yet. When someone does, they will show up here.' />;
return (
<Column>
<ColumnBackButton />
<ScrollableList
scrollKey='favourites'
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
>
{accountIds.map(id =>
<AccountContainer key={id} id={id} withNote={false} />
)}
</ScrollableList>
</Column>
);
}
}
|
fields/types/url/UrlField.js | ratecity/keystone | import React from 'react';
import Field from '../Field';
import { GlyphButton, FormInput } from '../../../admin/client/App/elemental';
module.exports = Field.create({
displayName: 'URLField',
statics: {
type: 'Url',
},
openValue () {
var href = this.props.value;
if (!href) return;
if (!/^(mailto\:)|(\w+\:\/\/)/.test(href)) {
href = 'http://' + href;
}
window.open(href);
},
renderLink () {
if (!this.props.value) return null;
return (
<GlyphButton
className="keystone-relational-button"
glyph="link"
onClick={this.openValue}
title={'Open ' + this.props.value + ' in a new tab'}
variant="link"
/>
);
},
renderField () {
return (
<FormInput
autoComplete="off"
name={this.getInputName(this.props.path)}
onChange={this.valueChanged}
ref="focusTarget"
type="url"
value={this.props.value}
/>
);
},
wrapField () {
return (
<div style={{ position: 'relative' }}>
{this.renderField()}
{this.renderLink()}
</div>
);
},
renderValue () {
const { value } = this.props;
return (
<FormInput noedit onClick={value && this.openValue}>
{value}
</FormInput>
);
},
});
|
packages/react-scripts/fixtures/kitchensink/src/features/env/ShellEnvVariables.js | Antontsyk/react_vk | import React from 'react'
export default () => (
<span id="feature-shell-env-variables">{process.env.REACT_APP_SHELL_ENV_MESSAGE}.</span>
)
|
stories/Tag/index.js | nirhart/wix-style-react | import React from 'react';
import {storiesOf} from '@kadira/storybook';
import Markdown from '../utils/Components/Markdown';
import CodeExample from '../utils/Components/CodeExample';
import Readme from '../../src/Tag/README.md';
import ExampleStandard from './ExampleStandard';
import ExampleStandardRaw from '!raw!./ExampleStandard';
storiesOf('Core', module)
.add('Tag', () => (
<div>
<Markdown source={Readme}/>
<h1>Usage examples</h1>
<CodeExample title="Standard" code={ExampleStandardRaw}>
<ExampleStandard/>
</CodeExample>
</div>
));
|
src/components/search_bar.js | bryanbuitrago/reactVideoApp | import React, { Component } from 'react';
class SearchBar extends Component {
constructor(props) {
super(props);
this.state = { term: ''};
}
render(){
return (
<div className="search-bar">
<input
value={this.state.term}
onChange={ event => this.onInputChange(event.target.value)} />
</div>
);
}
onInputChange(term) {
this.setState({term});
this.props.onSearchTermChange(term);
}
}
export default SearchBar;
|
components/pages/docs.js | ccheever/expo-docs | import React from 'react'
import Router from 'next/router'
import Head from '~/components/base/head'
import Page from '~/components/base/page'
import Header from '~/components/custom/header'
import Navbar from '~/components/custom/navbar'
import FreezePageScroll from '~/components/custom/freeze-page-scroll'
import { replaceVersionInUrl } from '~/lib/url'
import { VERSIONS, NEW_DOC_VERSIONS } from '~/data/versions'
class DocsPage extends React.Component {
state = {
isMobileOverlayVisible: false
}
render() {
let version = (this.props.url.asPath || this.props.url.pathname)
.split(`/`)[2]
if (!version || VERSIONS.indexOf(version) === -1) {
version = VERSIONS[0]
}
this.version = version
const setVersion = version_ => {
if (NEW_DOC_VERSIONS.indexOf(version_) !== -1) {
this.version = version_
// TODO: Support `latest` URLs with an `asPath`
Router.push('/versions/' + version_)
} else {
// Redirect to old docs
window.location.href = `https://docs.expo.io/versions/${version_}/index.html`
}
}
const canonicalUrl =
'https://docs.expo.io' +
replaceVersionInUrl(this.props.url.pathname, 'latest')
const tippyScript = `
tippy('.code-annotation', {
theme: 'light',
arrow: true,
interactive: true,
});
`
return (
<Page>
<Head titlePrefix="" title={`${this.props.title} - Expo Documentation`}>
{version === 'unversioned' &&
<meta name="robots" content="noindex" />}
<link rel="canonical" href={canonicalUrl} />
</Head>
<div
className="header"
style={{
display: this.state.isMobileOverlayVisible ? 'none' : 'block'
}}
>
<Header
clean={true}
inverse={true}
user={this.props.user}
pathname={this.props.url.pathname}
onLogout={() => {
this.props.onUser(null)
this.props.url.push('/login')
}}
onLogoRightClick={() => this.props.url.push('/logos')}
activeVersion={this.version}
setVersion={setVersion}
toggleMobileOverlay={() =>
this.setState({
isMobileOverlayVisible: !this.state.isMobileOverlayVisible
})}
/>
</div>
<FreezePageScroll>
<div
className="sidebar"
ref={sidebar => {
this.sidebar = sidebar
}}
>
<Navbar
url={this.props.url}
activeVersion={this.version}
getSidebarScrollPosition={() => this.sidebar.scrollTop}
setSidebarScrollPosition={val => (this.sidebar.scrollTop = val)}
/>
</div>
</FreezePageScroll>
{this.state.isMobileOverlayVisible &&
<Navbar
mobile={true}
className="mobile-overlay"
url={this.props.url}
activeVersion={this.version}
toggleMobileOverlay={() =>
this.setState({
isMobileOverlayVisible: !this.state.isMobileOverlayVisible
})}
setVersion={setVersion}
/>}
<div style={{ height: '100vh', overflow: 'auto' }}>
<div className="doc-layout">
{this.props.children}
<div />
</div>
</div>
<style jsx>{`
.doc-layout {
display: flex;
margin: 130px 30px 50px 320px;
padding: 0 20px;
justify-content: left;
-webkit-font-smoothing: antialiased;
}
.header {
position: fixed;
top: 0;
left: 0;
right: 0;
z-index: 99;
}
.sidebar {
position: fixed;
width: 280px;
margin-top: 0;
bottom: 0;
left: 0;
top: 130px;
padding-left: 30px;
overflow: auto;
-webkit-font-smoothing: antialiased;
}
.topbar {
display: none;
}
.content {
flex: 1;
max-width: 600px;
}
.content h1 {
color: #000;
font-size: 26px;
line-height: 20px;
font-weight: 400;
margin: 0 0 30px 0;
padding: 0;
}
@media screen and (max-width: 950px) {
.header {
position: relative;
}
.doc-layout {
display: block;
margin: 0;
margin-top: 160px;
}
.content {
width: 100%;
margin-left: 0;
}
.sidebar {
display: none;
}
.topbar {
display: block;
}
}
`}</style>
<script dangerouslySetInnerHTML={{ __html: tippyScript }} />
</Page>
)
}
}
export default DocsPage
|
example/examples/PanController.js | wannyk/react-native-maps | import React from 'react';
import PropTypes from 'prop-types';
import { View, Animated, PanResponder } from 'react-native';
const ModePropType = PropTypes.oneOf(['decay', 'snap', 'spring-origin']);
const OvershootPropType = PropTypes.oneOf(['spring', 'clamp']);
const AnimatedPropType = PropTypes.any;
class PanController extends React.Component {
static propTypes = {
// Component Config
lockDirection: PropTypes.bool,
horizontal: PropTypes.bool,
vertical: PropTypes.bool,
overshootX: OvershootPropType,
overshootY: OvershootPropType,
xBounds: PropTypes.arrayOf(PropTypes.number),
yBounds: PropTypes.arrayOf(PropTypes.number),
xMode: ModePropType,
yMode: ModePropType,
snapSpacingX: PropTypes.number, // TODO: also allow an array of values?
snapSpacingY: PropTypes.number,
// Animated Values
panX: AnimatedPropType,
panY: AnimatedPropType,
// Animation Config
overshootSpringConfig: PropTypes.any,
momentumDecayConfig: PropTypes.any,
springOriginConfig: PropTypes.any,
directionLockDistance: PropTypes.number,
overshootReductionFactor: PropTypes.number,
// Events
onOvershoot: PropTypes.func,
onDirectionChange: PropTypes.func,
onReleaseX: PropTypes.func,
onReleaseY: PropTypes.func,
onRelease: PropTypes.func,
//...PanResponderPropTypes,
};
// getInitialState() {
// //TODO:
// // it's possible we want to move some props over to state.
// // For example, xBounds/yBounds might need to be
// // calculated/updated automatically
// //
// // This could also be done with a higher-order component
// // that just massages props passed in...
// return {
//
// };
// },
_responder = null;
_listener = null;
_direction = null;
constructor(props) {
super(props);
this.deceleration = 0.997;
if (
props.momentumDecayConfig &&
this.props.momentumDecayConfig.deceleration
) {
this.deceleration = this.props.momentumDecayConfig.deceleration;
}
}
componentWillMount() {
this._responder = PanResponder.create({
onStartShouldSetPanResponder: this.props.onStartShouldSetPanResponder,
onMoveShouldSetPanResponder: this.props.onMoveShouldSetPanResponder,
onPanResponderGrant: (...args) => {
if (this.props.onPanResponderGrant) {
this.props.onPanResponderGrant(...args);
}
let { panX, panY, horizontal, vertical, xMode, yMode } = this.props;
this.handleResponderGrant(panX, xMode);
this.handleResponderGrant(panY, yMode);
this._direction =
horizontal && !vertical ? 'x' : vertical && !horizontal ? 'y' : null;
},
onPanResponderMove: (_, { dx, dy, x0, y0 }) => {
let {
panX,
panY,
xBounds,
yBounds,
overshootX,
overshootY,
horizontal,
vertical,
lockDirection,
directionLockDistance,
} = this.props;
if (!this._direction) {
const dx2 = dx * dx;
const dy2 = dy * dy;
if (dx2 + dy2 > directionLockDistance) {
this._direction = dx2 > dy2 ? 'x' : 'y';
if (this.props.onDirectionChange) {
this.props.onDirectionChange(this._direction, { dx, dy, x0, y0 });
}
}
}
const dir = this._direction;
if (this.props.onPanResponderMove) {
this.props.onPanResponderMove(_, { dx, dy, x0, y0 });
}
if (horizontal && (!lockDirection || dir === 'x')) {
let [xMin, xMax] = xBounds;
this.handleResponderMove(panX, dx, xMin, xMax, overshootX);
}
if (vertical && (!lockDirection || dir === 'y')) {
let [yMin, yMax] = yBounds;
this.handleResponderMove(panY, dy, yMin, yMax, overshootY);
}
},
onPanResponderRelease: (_, { vx, vy, dx, dy }) => {
let {
panX,
panY,
xBounds,
yBounds,
overshootX,
overshootY,
horizontal,
vertical,
lockDirection,
xMode,
yMode,
snapSpacingX,
snapSpacingY,
} = this.props;
let cancel = false;
const dir = this._direction;
if (this.props.onRelease) {
cancel = this.props.onRelease({ vx, vy, dx, dy }) === false;
}
if (!cancel && horizontal && (!lockDirection || dir === 'x')) {
let [xMin, xMax] = xBounds;
if (this.props.onReleaseX) {
cancel = this.props.onReleaseX({ vx, vy, dx, dy }) === false;
}
!cancel &&
this.handleResponderRelease(
panX,
xMin,
xMax,
vx,
overshootX,
xMode,
snapSpacingX
);
}
if (!cancel && vertical && (!lockDirection || dir === 'y')) {
let [yMin, yMax] = yBounds;
if (this.props.onReleaseY) {
cancel = this.props.onReleaseY({ vx, vy, dx, dy }) === false;
}
!cancel &&
this.handleResponderRelease(
panY,
yMin,
yMax,
vy,
overshootY,
yMode,
snapSpacingY
);
}
this._direction =
horizontal && !vertical ? 'x' : vertical && !horizontal ? 'y' : null;
},
});
}
handleResponderMove(anim, delta, min, max, overshoot) {
let val = anim._offset + delta;
if (val > max) {
switch (overshoot) {
case 'spring':
val = max + (val - max) / this.props.overshootReductionFactor;
break;
case 'clamp':
val = max;
break;
}
}
if (val < min) {
switch (overshoot) {
case 'spring':
val = min - (min - val) / this.props.overshootReductionFactor;
break;
case 'clamp':
val = min;
break;
}
}
val = val - anim._offset;
anim.setValue(val);
}
handleResponderRelease(
anim,
min,
max,
velocity,
overshoot,
mode,
snapSpacing
) {
anim.flattenOffset();
if (anim._value < min) {
if (this.props.onOvershoot) {
this.props.onOvershoot(); // TODO: what args should we pass to this
}
switch (overshoot) {
case 'spring':
Animated.spring(anim, {
...this.props.overshootSpringConfig,
toValue: min,
velocity,
}).start();
break;
case 'clamp':
anim.setValue(min);
break;
}
} else if (anim._value > max) {
if (this.props.onOvershoot) {
this.props.onOvershoot(); // TODO: what args should we pass to this
}
switch (overshoot) {
case 'spring':
Animated.spring(anim, {
...this.props.overshootSpringConfig,
toValue: max,
velocity,
}).start();
break;
case 'clamp':
anim.setValue(min);
break;
}
} else {
switch (mode) {
case 'snap':
this.handleSnappedScroll(
anim,
min,
max,
velocity,
snapSpacing,
overshoot
);
break;
case 'decay':
this.handleMomentumScroll(anim, min, max, velocity, overshoot);
break;
case 'spring-origin':
Animated.spring(anim, {
...this.props.springOriginConfig,
toValue: 0,
velocity,
}).start();
break;
}
}
}
handleResponderGrant(anim, mode) {
switch (mode) {
case 'spring-origin':
anim.setValue(0);
break;
case 'snap':
case 'decay':
anim.setOffset(anim._value + anim._offset);
anim.setValue(0);
break;
}
}
handleMomentumScroll(anim, min, max, velocity, overshoot) {
Animated.decay(anim, {
...this.props.momentumDecayConfig,
velocity,
}).start(() => {
anim.removeListener(this._listener);
});
this._listener = anim.addListener(({ value }) => {
if (value < min) {
anim.removeListener(this._listener);
if (this.props.onOvershoot) {
this.props.onOvershoot(); // TODO: what args should we pass to this
}
switch (overshoot) {
case 'spring':
Animated.spring(anim, {
...this.props.overshootSpringConfig,
toValue: min,
velocity,
}).start();
break;
case 'clamp':
anim.setValue(min);
break;
}
} else if (value > max) {
anim.removeListener(this._listener);
if (this.props.onOvershoot) {
this.props.onOvershoot(); // TODO: what args should we pass to this
}
switch (overshoot) {
case 'spring':
Animated.spring(anim, {
...this.props.overshootSpringConfig,
toValue: max,
velocity,
}).start();
break;
case 'clamp':
anim.setValue(min);
break;
}
}
});
}
handleSnappedScroll(anim, min, max, velocity, spacing) {
let endX = this.momentumCenter(anim._value, velocity, spacing);
endX = Math.max(endX, min);
endX = Math.min(endX, max);
const bounds = [endX - spacing / 2, endX + spacing / 2];
const endV = this.velocityAtBounds(anim._value, velocity, bounds);
this._listener = anim.addListener(({ value }) => {
if (value > bounds[0] && value < bounds[1]) {
Animated.spring(anim, {
toValue: endX,
velocity: endV,
}).start();
}
});
Animated.decay(anim, {
...this.props.momentumDecayConfig,
velocity,
}).start(() => {
anim.removeListener(this._listener);
});
}
closestCenter(x, spacing) {
const plus = x % spacing < spacing / 2 ? 0 : spacing;
return Math.round(x / spacing) * spacing + plus;
}
momentumCenter(x0, vx, spacing) {
let t = 0;
let x1 = x0;
let x = x1;
while (true) {
t += 16;
x =
x0 +
(vx / (1 - this.deceleration)) *
(1 - Math.exp(-(1 - this.deceleration) * t));
if (Math.abs(x - x1) < 0.1) {
x1 = x;
break;
}
x1 = x;
}
return this.closestCenter(x1, spacing);
}
velocityAtBounds(x0, vx, bounds) {
let t = 0;
let x1 = x0;
let x = x1;
let vf;
while (true) {
t += 16;
x =
x0 +
(vx / (1 - this.deceleration)) *
(1 - Math.exp(-(1 - this.deceleration) * t));
vf = (x - x1) / 16;
if (x > bounds[0] && x < bounds[1]) {
break;
}
if (Math.abs(vf) < 0.1) {
break;
}
x1 = x;
}
return vf;
}
// componentDidMount() {
// //TODO: we may need to measure the children width/height here?
// },
//
// componentWillUnmount() {
//
// },
//
// componentDidUnmount() {
//
// },
render() {
return <View {...this.props} {...this._responder.panHandlers} />;
}
}
export default PanController;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.