path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
packages/react/src/components/Menu/_storybook-utils.js | carbon-design-system/carbon-components | import React from 'react';
import { action } from '@storybook/addon-actions';
import { InlineNotification } from '../Notification';
import {
MenuDivider,
MenuGroup,
MenuItem,
MenuRadioGroup,
MenuSelectableItem,
} from '../Menu';
const InfoBanner = () => (
<InlineNotification
kind="info"
title="Experimental component"
subtitle="This component is considered experimental. Its API may change until the stable version is released."
lowContrast
hideCloseButton
/>
);
// eslint-disable-next-line react/prop-types
export const StoryFrame = ({ children }) => (
<div style={{ height: 'calc(100vh - 6.25rem)' }}>
<InfoBanner />
{children}
</div>
);
function renderItem(item, i) {
switch (item.type) {
case 'item':
return (
<MenuItem
key={i}
label={item.label}
shortcut={item.shortcut}
disabled={item.disabled}
kind={item.kind}
onClick={!item.children ? action('onClick') : null}>
{item.children && item.children.map(renderItem)}
</MenuItem>
);
case 'divider':
return <MenuDivider key={i} />;
case 'selectable':
return (
<MenuSelectableItem
key={i}
label={item.label}
initialChecked={item.initialChecked}
onChange={action('onChange')}
/>
);
case 'radiogroup':
return (
<MenuRadioGroup
key={i}
label={item.label}
items={item.items}
initialSelectedItem={item.initialSelectedItem}
onChange={action('onChange')}
/>
);
case 'group':
return (
<MenuGroup key={i} label={item.label}>
{item.children && item.children.map(renderItem)}
</MenuGroup>
);
}
}
export const buildMenu = (items) => items.map(renderItem);
|
src/components/Stat/Stat.js | eunvanz/handpokemon2 | import React from 'react'
import PropTypes from 'prop-types'
import keygen from 'keygenerator'
import ProgressBar from 'components/ProgressBar'
import Info from 'components/Info'
import { colors } from 'constants/colors'
class Stat extends React.Component {
render () {
const { value, label, addedValue1, addedValue2, preValue } = this.props
const renderStatStack = () => {
return [value, preValue, addedValue1, addedValue2].map((val, idx) => {
if (val === 0) return null
let textColor = 'c-gray'
if (idx === 1) textColor = 'c-green'
else if (idx === 2) textColor = 'c-orange'
else if (idx === 3) textColor = 'c-lightblue'
return <span key={idx} className={textColor}>{`${idx > 0 ? ' +' : ''}${val}`}</span>
})
}
const renderInfo = () => {
let content
if (label === '체력' || label === '평균 체력') {
content = '포켓몬의 HP를 결정짓는 능력치입니다.'
} else if (label === '공격' || label === '평균 공격') {
content = '포켓몬의 일반공격 데미지를 결정짓는 능력치입니다.'
} else if (label === '방어' || label === '평균 방어') {
content = '일반공격 피격시 데미지를 줄여주는 능력치입니다. 이 수치가 높을 수록 일반공격에 대한 완벽방어의 확률도 높아집니다.'
} else if (label === '특수공격' || label === '평균 특수공격') {
content = '포켓몬의 특수공격 데미지를 결정짓는 능력치입니다. 특수공격은 일반공격보다 데미지가 큽니다.'
} else if (label === '특수방어' || label === '평균 특수방어') {
content = '특수공격 피격시 데미지를 줄여주는 능력치입니다. 이 수치가 높을 수록 특수공격에 대한 완벽방어의 확률도 높아집니다.'
} else if (label === '민첩' || label === '평균 민첩') {
content = '피격시 회피확률을 결정짓습니다. 또한 공격력과 방어력에도 미세하게 영향을 미칩니다.'
}
return (
<Info id={keygen._()} title={label} content={content} />
)
}
return (
<div className='row' style={{ marginBottom: '10px' }}>
<p className='col-xs-12 f-700' style={{ marginBottom: '0px' }}>{label} : {renderStatStack()} {renderInfo()}</p>
<div className='col-xs-10' style={{ paddingTop: '9px' }}>
<ProgressBar max={300} value={[preValue, value, addedValue1, addedValue2]} color={[colors.green, colors.amber, colors.orange, colors.lightBlue]} />
</div>
<div className='col-xs-2 f-700'><span className='c-blue'>{preValue + value + addedValue1 + addedValue2}</span></div>
</div>
)
}
}
Stat.propTypes = {
label: PropTypes.string,
value: PropTypes.number,
addedValue1: PropTypes.number,
addedValue2: PropTypes.number,
preValue: PropTypes.number
}
export default Stat
|
src/components/Nav/Nav.js | Chewser/chewser_react | import React, { Component } from 'react';
export default class Nav extends Component {
constructor() {
super()
}
render() {
return(
<div>
<div className="header">
<h1>Chewser</h1>
</div>
</div>
)
}
}
|
src/Parser/UnsupportedSpec/Modules/NotImplementedYet.js | mwwscott0/WoWAnalyzer | import React from 'react';
import Module from 'Parser/Core/Module';
class NotImplementedYet extends Module {
statistic() {
return (
<div className="col-lg-12">
<div className="panel statistic-box">
<div className="panel-heading" style={{ color: 'red' }}>
<h2>This spec is not yet supported</h2>
</div>
<div className="panel-body" style={{ padding: '16px 22px 14px' }}>
You don't need to to do anything special to add a spec. The real issue preventing specs from being added is that in order to add a spec, you need to have the following 3 properties:<br />
1. Know the spec well enough to actually create something useful<br />
2. Know how to program well enough to implement the analysis<br />
3. Have the time and motivation to actually do it<br /><br />
If you want to give it a try you can find documentation here:{' '}
<a href="https://github.com/MartijnHols/WoWAnalyzer/blob/master/README.md">https://github.com/MartijnHols/WoWAnalyzer/blob/master/README.md</a>
</div>
</div>
</div>
);
}
}
export default NotImplementedYet;
|
examples/auth-with-shared-root/components/App.js | nvartolomei/react-router | import React from 'react'
import { Link } from 'react-router'
import auth from '../utils/auth'
const App = React.createClass({
getInitialState() {
return {
loggedIn: auth.loggedIn()
}
},
updateAuth(loggedIn) {
this.setState({
loggedIn: !!loggedIn
})
},
componentWillMount() {
auth.onChange = this.updateAuth
auth.login()
},
render() {
return (
<div>
<ul>
<li>
{this.state.loggedIn ? (
<Link to="/logout">Log out</Link>
) : (
<Link to="/login">Sign in</Link>
)}
</li>
<li><Link to="/about">About</Link></li>
<li><Link to="/">Home</Link> (changes depending on auth status)</li>
<li><Link to="/page2">Page Two</Link> (authenticated)</li>
<li><Link to="/user/foo">User: Foo</Link> (authenticated)</li>
</ul>
{this.props.children}
</div>
)
}
})
export default App
|
src/webapp/components/_containers/BrowseContainer.js | nus-mtp/cubist | import React from 'react';
import _ from 'lodash';
import { connect } from 'react-redux';
import PureComponent from 'react-pure-render/component';
import Immutable from 'immutable';
import { ModelCard } from '../model';
import { BrowseActions } from 'webapp/actions';
import { Constants } from 'common';
import { pushState } from 'redux-router';
import qs from 'qs';
const CLASS_NAME = 'cb-ctn-browse';
const SEARCH_FIELD = 'search-field';
const TITLE_CHECKBOX = 'title-checkbox';
const TAG_CHECKBOX = 'tag-checkbox';
const USER_CHECKBOX = 'user-checkbox';
const RESULT_CATEGORY = 'category-dropmenu';
const PAGE = 'page';
const RESULT_SORT = 'sort-dropmenu';
const ALL_CATEGORIES_FILTER = 'all';
class BrowseContainer extends PureComponent {
static fetchData({ dispatch, query }) {
return dispatch(BrowseActions.browse(query));
}
static propTypes = {
resultsModels: React.PropTypes.instanceOf(Immutable.List),
hasNextPage: React.PropTypes.bool,
location: React.PropTypes.object
};
constructor(props) {
super(props);
const query = qs.parse(props.location.search.substring(1));
let pageNum = parseInt(query.page, 10);
if (isNaN(pageNum) || pageNum < 1) {
pageNum = 1;
}
this.state = {
formData: {
[SEARCH_FIELD]: query.searchString,
[TITLE_CHECKBOX]: query.searchTitle !== '0',
[TAG_CHECKBOX]: query.searchTag !== '0',
[USER_CHECKBOX]: query.searchUser !== '0',
[PAGE]: pageNum,
[RESULT_CATEGORY]: query.category || ALL_CATEGORIES_FILTER,
[RESULT_SORT]: query.sort || '0'
}
};
}
render() {
return (
<div className={ CLASS_NAME }>
<div className={ `${CLASS_NAME}-header cb-text-center` }>
<h3>{ this._getPageTitle() }</h3>
{ this._renderExtendedSearchForm() }
</div>
<br /><br />
<div className={ `${CLASS_NAME}-filter-row cb-text-center` }>
{ this._renderPrevButton() }
{ this._renderFilterAndSortDropdown() }
{ this._renderNextButton() }
</div>
<br /><br /><br /><br />
{ this._renderResultsModels() }
</div>
);
}
_getPageTitle() {
const { location } = this.props;
const query = qs.parse(location.search.substring(1));
if (query.searchString) {
return 'Search Results';
}
if (query.category) {
for (let i = 0; i < Constants.MODEL_CATEGORIES.length; i++) {
if (Constants.MODEL_CATEGORIES[i].toLowerCase() === query.category.toLowerCase()) {
return 'Category: ' + query.category.charAt(0).toUpperCase() + query.category.slice(1);
}
}
}
return 'Search All of Cubist!';
}
_renderExtendedSearchForm() {
return (
<form className="form" onSubmit={ this._onSearchFormSubmit }>
<div className="form-inline">
<input id={ SEARCH_FIELD }
type="text"
className="form-control"
defaultValue={ this.state.formData[SEARCH_FIELD] }
placeholder="Search"
onChange={ (e) => this._onSearchFieldChange(SEARCH_FIELD, e.target.value) }/>
<button className={ `${CLASS_NAME}-search btn` } type="submit">
<i className="fa fa-search" />
</button>
</div>
<div className="form-inline centered-60-div">
<label className="label-25">Search by:</label>
<label className="label-15">
<input id={ TITLE_CHECKBOX }
type="checkbox"
defaultChecked={ this.state.formData[TITLE_CHECKBOX] }
onClick={ () => this._onCheckboxClick(TITLE_CHECKBOX) }/>
Title
</label>
<label className="label-15">
<input id={ TAG_CHECKBOX }
type="checkbox"
defaultChecked={ this.state.formData[TAG_CHECKBOX] }
onClick={ () => this._onCheckboxClick(TAG_CHECKBOX) }/>
Tag
</label>
<label className="label-15">
<input id={ USER_CHECKBOX }
type="checkbox"
defaultChecked={ this.state.formData[USER_CHECKBOX] }
onClick={ () => this._onCheckboxClick(USER_CHECKBOX) }/>
User
</label>
</div>
</form>
);
}
_onPageButtonClick(isForward) {
if (!isForward) { // Backwards
this.state.formData[PAGE] -= 1;
if (this.state.formData[PAGE] < 1) {
this.state.formData[PAGE] = 1;
}
} else {
this.state.formData[PAGE] += 1;
}
const { dispatch } = this.props;
dispatch(pushState(null,
'/browse?' + this.reuseSearchQuery(PAGE, this.state.formData[PAGE])));
}
_onCheckboxClick = (fieldId) => {
const formData = _.cloneDeep(this.state.formData);
formData[fieldId] = !formData[fieldId];
this.setState({ formData });
};
_onSearchFieldChange = (fieldId, input) => {
const formData = _.cloneDeep(this.state.formData);
const trimmedText = input.trim();
formData[fieldId] = input.length === 0 ? undefined : trimmedText;
this.setState({ formData });
};
_onSearchFormSubmit = (e) => {
e.preventDefault();
const { dispatch } = this.props;
this.state.formData[PAGE] = 1;
dispatch(pushState(null, '/browse?' + this.convertStateToQuery()));
};
_renderPrevButton() {
if (this.state.formData[PAGE] > 1) {
return (
<div className="pull-left component-div">
<button className="btn btn-primary"
onClick={ () => this._onPageButtonClick(false) }>
{ '< PREV' }
</button>
</div>
);
}
}
_renderNextButton() {
const { hasNextPage } = this.props;
if (hasNextPage) {
return (
<div className="pull-right component-div">
<button className="btn btn-primary"
onClick={ () => this._onPageButtonClick(true) }>
{ 'NEXT >' }
</button>
</div>
);
}
}
_renderFilterAndSortDropdown() {
return (
<div className="pull-left" id="dropdown-div">
{ 'Category: ' }
<select onChange={ e => this._onDropdownChange(RESULT_CATEGORY, e.target.value) }
value={ this.state.formData[RESULT_CATEGORY] }
className={ `${CLASS_NAME}-filter-menu drop-menu` }
id={ `model-${RESULT_CATEGORY}` }>
<option value={ ALL_CATEGORIES_FILTER }>All</option>
{
Constants.MODEL_CATEGORIES.map((c, i) => (
<option key={ i } value={ c.toLowerCase() }>{ c }</option>
))
}
</select>
{ ' Sort By: ' }
<select onChange={ e => this._onDropdownChange(RESULT_SORT, e.target.value) }
value={ this.state.formData[RESULT_SORT] }
className={ `${CLASS_NAME}-filter-menu drop-menu` }
id={ `model-${RESULT_SORT}` }>
<option value="0">Latest Uploads</option>
<option value="1">Number of Views</option>
<option value="2">Alphabetically</option>
</select>
</div>
);
}
_onDropdownChange(fieldId, value) {
this.state.formData[fieldId] = value;
this.state.formData[PAGE] = 1;
const { dispatch } = this.props;
dispatch(pushState(null, '/browse?' + this.reuseSearchQuery(fieldId)));
}
reuseSearchQuery(fieldToChange) {
const { location } = this.props;
const query = qs.parse(location.search.substring(1));
if (fieldToChange === RESULT_CATEGORY) {
query.category =
this.state.formData[RESULT_CATEGORY] !== ALL_CATEGORIES_FILTER ?
this.state.formData[RESULT_CATEGORY] : undefined;
query.page = undefined;
} else if (fieldToChange === RESULT_SORT) {
query.sort =
this.state.formData[RESULT_SORT] !== '0' ? this.state.formData[RESULT_SORT] : undefined;
query.page = undefined;
} else if (fieldToChange === PAGE) {
query.page = this.state.formData[PAGE] > 1 ? this.state.formData[PAGE] : undefined;
}
return qs.stringify(query);
}
convertStateToQuery() {
const query = {};
if (this.state.formData[SEARCH_FIELD]) {
query.searchString = this.state.formData[SEARCH_FIELD];
if (this.state.formData[TITLE_CHECKBOX] === false) {
query.searchTitle = 0;
}
if (this.state.formData[TAG_CHECKBOX] === false) {
query.searchTag = 0;
}
if (this.state.formData[USER_CHECKBOX] === false) {
query.searchUser = 0;
}
}
if (this.state.formData[PAGE] > 1) {
query.page = this.state.formData[PAGE];
}
if (this.state.formData[RESULT_CATEGORY] !== ALL_CATEGORIES_FILTER) {
query.category = this.state.formData[RESULT_CATEGORY];
}
if (this.state.formData[RESULT_SORT] !== '0') {
query.sort = this.state.formData[RESULT_SORT];
}
return qs.stringify(query);
}
_renderResultsModels() {
const { resultsModels } = this.props;
if (resultsModels.size === 0) {
return (
<div className={ `${CLASS_NAME}-results component-div` }>
No results found... try changing your search?
</div>
);
}
return resultsModels.map((model, i) => (
<div className={ `${CLASS_NAME}-results col-md-3 col-sm-6 col-xs-12 card-div` } key={ i }>
<ModelCard model={ model } />
</div>
));
}
}
export default connect(state => {
return {
resultsModels: state.BrowseStore.get('resultsModels'),
hasNextPage: state.BrowseStore.get('hasNextPage')
};
})(BrowseContainer);
|
jsx/app/index.js | NickTaporuk/webpack_starterkit_project | import React, { Component } from 'react';
import { render } from 'react-dom'
require('es6-promise').polyfill();
import fetch from 'isomorphic-fetch'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import MyAwesomeReactComponent from './MyAwesomeReactComponent';
export default class App extends Component {
constructor(props) {
super(props);
this.state = {token: { signature :"",header:{alg:"",typ:""}}};
}
componentDidMount() {
/*fetch('http://www.lua_nginx.com/verify', {
method: 'GET',
mode: 'CORS'
}).then(res => res.json())
.then(data => {
this.setState({
token : data
})
}).catch(err => err);*/
fetch("http://www.lua_nginx.com/sign", {
method: 'POST',
headers: {
'Accept': 'application/json, application/xml, text/plain, text/html, *.*',
'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8'
},
body: JSON.stringify({
email: 'foo',
pass: 'bar'
})
}).then(response => console.log('response:',response))
}
sendPost() {
fetch("http://www.lua_nginx.com/verify", {
method: "GET",
mode: "CORS"
}).then(res => res.json())
.then(data => {
this.setState({
token : data
})
}).catch(err => err);
}
render() {
let token = this.state.token;
// let id = token.id;
// let name = token.name;
// let password = token.password;
// console.log('this.state.token:',token);
return (
<div>
<h1>Hello, World!</h1>
<table className="table table-hover table-responsive">
<thead>
<tr>
<th>id</th>
<th>name</th>
<th>password</th>
</tr>
</thead>
<tbody>
{ /*allTokenData*/ }
{/*this.state.token && this.state.token.map(post => {
{console.log('post:', post)}
return (
<tr key="1">
<td></td>
<td></td>
<td>
<a href="#" className="btn btn-default btn-sm">Edit</a>
<a href="#" className="btn btn-danger btn-sm">Delete</a>
</td>
</tr>
);
})
*/}
</tbody>
</table>
</div>
);
}
}
render(
<App />,
document.getElementById('root')
); |
src/packages/@ncigdc/modern_components/GenesTable/SsmsAggregations.relay.js | NCI-GDC/portal-ui | import React from 'react';
import { graphql } from 'react-relay';
import { compose, withPropsOnChange } from 'recompose';
import { makeFilter, addInFilters } from '@ncigdc/utils/filters';
import Query from '@ncigdc/modern_components/Query';
export default (Component: ReactClass<*>) =>
compose(
withPropsOnChange(
['genesTableViewer'],
({ genesTableViewer, defaultFilters = null }) => {
const { hits } = genesTableViewer.explore.genes;
const geneIds = hits.edges.map(e => e.node.gene_id);
return {
variables: {
ssmCountsfilters: geneIds.length
? addInFilters(
defaultFilters,
makeFilter([
{
field: 'consequence.transcript.gene.gene_id',
value: geneIds,
},
]),
)
: null,
},
};
},
),
)((props: mixed) => {
return (
<Query
parentProps={props}
minHeight={387}
variables={props.variables}
Component={Component}
query={graphql`
query SsmsAggregations_relayQuery(
$ssmCountsfilters: FiltersArgument
) {
ssmsAggregationsViewer: viewer {
explore {
ssms {
aggregations(
filters: $ssmCountsfilters
aggregations_filter_themselves: true
) {
consequence__transcript__gene__gene_id {
buckets {
key
doc_count
}
}
}
}
}
}
}
`}
/>
);
});
|
app/scripts/components/matched-text.js | hustbill/autorender-js | import React from 'react';
const TRUNCATE_CONTEXT = 6;
const TRUNCATE_ELLIPSIS = '…';
/**
* Returns an array with chunks that cover the whole text via {start, length}
* objects.
*
* `('text', {start: 2, length: 1}) => [{text: 'te'}, {text: 'x', match: true}, {text: 't'}]`
*/
function chunkText(text, { start, length }) {
if (text && !isNaN(start) && !isNaN(length)) {
const chunks = [];
// text chunk before match
if (start > 0) {
chunks.push({text: text.substr(0, start)});
}
// matching chunk
chunks.push({match: true, text: text.substr(start, length)});
// text after match
const remaining = start + length;
if (remaining < text.length) {
chunks.push({text: text.substr(remaining)});
}
return chunks;
}
return [{ text }];
}
/**
* Truncates chunks with ellipsis
*
* First chunk is truncated from left, second chunk (match) is truncated in the
* middle, last chunk is truncated at the end, e.g.
* `[{text: "...cation is a "}, {text: "useful...or not"}, {text: "tool..."}]`
*/
function truncateChunks(chunks, text, maxLength) {
if (chunks && chunks.length === 3 && maxLength && text && text.length > maxLength) {
const res = chunks.map(c => Object.assign({}, c));
let needToCut = text.length - maxLength;
// trucate end
const end = res[2];
if (end.text.length > TRUNCATE_CONTEXT) {
needToCut -= end.text.length - TRUNCATE_CONTEXT;
end.text = `${end.text.substr(0, TRUNCATE_CONTEXT)}${TRUNCATE_ELLIPSIS}`;
}
if (needToCut) {
// truncate front
const start = res[0];
if (start.text.length > TRUNCATE_CONTEXT) {
needToCut -= start.text.length - TRUNCATE_CONTEXT;
start.text = `${TRUNCATE_ELLIPSIS}`
+ `${start.text.substr(start.text.length - TRUNCATE_CONTEXT)}`;
}
}
if (needToCut) {
// truncate match
const middle = res[1];
if (middle.text.length > 2 * TRUNCATE_CONTEXT) {
middle.text = `${middle.text.substr(0, TRUNCATE_CONTEXT)}`
+ `${TRUNCATE_ELLIPSIS}`
+ `${middle.text.substr(middle.text.length - TRUNCATE_CONTEXT)}`;
}
}
return res;
}
return chunks;
}
/**
* Renders text with highlighted search match.
*
* A match object is of shape `{text, label, match}`.
* `match` is a text match object of shape `{start, length}`
* that delimit text matches in `text`. `label` shows the origin of the text.
*/
export default class MatchedText extends React.PureComponent {
render() {
const { match, text, truncate, maxLength } = this.props;
const showFullValue = !truncate || (match && (match.start + match.length) > truncate);
const displayText = showFullValue ? text : text.slice(0, truncate);
if (!match) {
return <span>{displayText}</span>;
}
const chunks = chunkText(displayText, match);
return (
<span className="matched-text" title={text}>
{truncateChunks(chunks, displayText, maxLength).map((chunk, index) => {
if (chunk.match) {
return (
<span className="match" key={index}>
{chunk.text}
</span>
);
}
return chunk.text;
})}
</span>
);
}
}
|
generators/app/templates/components/home.js | mattdennewitz/generator-mdtz-fluxible | import React from 'react';
export default class Home extends React.Component {
render() {
return <div>Home</div>;
}
}
|
react-flux-mui/js/material-ui/src/svg-icons/action/lock.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLock = (props) => (
<SvgIcon {...props}>
<path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z"/>
</SvgIcon>
);
ActionLock = pure(ActionLock);
ActionLock.displayName = 'ActionLock';
ActionLock.muiName = 'SvgIcon';
export default ActionLock;
|
src/svg-icons/action/exit-to-app.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionExitToApp = (props) => (
<SvgIcon {...props}>
<path d="M10.09 15.59L11.5 17l5-5-5-5-1.41 1.41L12.67 11H3v2h9.67l-2.58 2.59zM19 3H5c-1.11 0-2 .9-2 2v4h2V5h14v14H5v-4H3v4c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
ActionExitToApp = pure(ActionExitToApp);
ActionExitToApp.displayName = 'ActionExitToApp';
ActionExitToApp.muiName = 'SvgIcon';
export default ActionExitToApp;
|
src/components/Response.js | OpenCollective/frontend | import React from 'react';
import PropTypes from 'prop-types';
import colors from '../constants/colors';
import { defineMessages, injectIntl } from 'react-intl';
import { pickAvatar } from '../lib/collective.lib';
const star = '/static/images/icons/star.svg';
class Response extends React.Component {
static propTypes = {
response: PropTypes.object.isRequired,
};
constructor(props) {
super(props);
this.messages = defineMessages({
INTERESTED: {
id: 'response.status.interested',
defaultMessage: '{name} is interested',
},
YES: { id: 'response.status.yes', defaultMessage: '{name} is going' },
});
}
render() {
const { intl, response } = this.props;
const { user, description, status } = response;
const name =
(user.name && user.name.match(/^null/) ? null : user.name) ||
(user.email && user.email.substr(0, user.email.indexOf('@')));
if (!name) return <div />;
const image = user.image || pickAvatar(name);
const linkTo = `/${user.slug}`;
const title = intl.formatMessage(this.messages[status], { name });
return (
<a href={linkTo} title={title}>
<div>
<style jsx>
{`
.Response {
display: flex;
align-items: flex-start;
width: 100%;
margin: 10px;
max-width: 300px;
min-height: 90px;
float: left;
position: relative;
}
img {
float: left;
width: 45px;
border-radius: 50%;
margin-top: 1rem;
}
.bubble {
padding: 1rem;
}
.name {
font-size: 1.7rem;
}
.description {
font-size: 1.4rem;
}
.star {
width: 14px;
height: 14px;
position: absolute;
top: 45px;
left: 0;
}
`}
</style>
<div className="Response">
{status === 'INTERESTED' && <object title={title} type="image/svg+xml" data={star} className="star" />}
<img src={image} />
<div className="bubble">
<div className="name">{name}</div>
<div className="description" style={{ color: colors.darkgray }}>
{description || user.description}
</div>
</div>
</div>
</div>
</a>
);
}
}
export default injectIntl(Response);
|
trash/agentsSearchResults.js | nypl-registry/browse | import React from 'react';
import { Router, Route, Link } from 'react-router'
import { connect } from 'react-redux'
import { debounce, searchAgentByName, randomColor } from '../../utils.js';
import HeaderNav from '../shared/headerNav.js';
var rowColor = "white"
const AgentsSearchResultsItem = React.createClass({
render() {
var image = {position:"relative"}
var styleLionColor = { color: randomColor() }
if (this.props.data.depiction){
image = { background: "url("+this.props.data.depiction+")", position:"relative"}
styleLionColor = { display: "none"}
}
var rowColorStyle = (rowColor==='white') ? { background: "whitesmoke"} : { background: "white"}
rowColor = rowColorStyle.background
var resourcesNoun = (this.props.data.useCount===1) ? "resource" : "resources"
var desc = <span>{this.props.data.useCount} {resourcesNoun}</span>
if (this.props.data.topFiveRolesString.length>0) desc = <span>{this.props.data.topFiveRolesString.join(", ")} ({this.props.data.useCount} resources)</span>
if (this.props.data.description && this.props.data.topFiveRolesString.length>0) desc = <span>{this.props.data.description}<br/>{this.props.data.topFiveRolesString.join(", ")} ({this.props.data.useCount} resources)</span>
var topFiveTermsString = []
this.props.data.topFiveTermsString.forEach(t=> { topFiveTermsString.push(<span key={`top-five-id-${topFiveTermsString.length}`}>{t}<br/></span>) })
return (
<Link className="agent-listing-item-link" to={`/agents/${this.props.data['@id'].split(":")[1]}`}>
<div className="row agent-listing-item" style={rowColorStyle}>
<div className="three columns agent-listing-image" style={image} >
<span style={styleLionColor} className="lg-icon nypl-icon-logo-mark agent-listing-image-placeholder"></span>
</div>
<div className="five columns">
<div className="agent-listing-title">{this.props.data.prefLabel}</div>
<div className="agent-listing-desc">{desc}</div>
</div>
<div className="four columns agent-listing-terms-aligner">
<div className="agent-listing-terms">
{topFiveTermsString}
</div>
</div>
</div>
</Link>
)
}
})
const AgentsSearchResults = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState: function(){
return {
results: []
}
},
componentDidMount: function(){
let q = "" || (this.props.location.query.q) ? this.props.location.query.q : ""
let self = this
searchAgentByName(q,function(results){
var rAry = []
results.data.itemListElement.forEach(r =>{
rAry.push(<AgentsSearchResultsItem key={r.result['@id']} data={r.result}/>)
})
self.setState({results:rAry})
})
this._input.focus()
var val = this._input.value
this._input.value = ''
this._input.value = val
},
handleKeyUp: function(event){
if ((event.keyCode >= 48 && event.keyCode <= 57) || (event.keyCode >= 65 && event.keyCode <= 90) || event.keyCode == 13 || event.keyCode == 8 || event.keyCode == 46 ){
var self = this;
//window.browseHistory.replace('/agents/search/?q='+event.target.value)
this.context.router.push('/agents/search/?q='+event.target.value)
//this.setSate({ results : this.state.results})
self.setState({results:[]})
searchAgentByName(event.target.value,function(results){
var rAry = []
results.data.itemListElement.forEach(r =>{
rAry.push(<AgentsSearchResultsItem key={r.result['@id']} data={r.result}/>)
})
self.setState({results:rAry})
})
}
},
// componentDidMount: function(){
// this.handleKeyUp = debounce(this.handleKeyUp,400)
// },
handleFocus: function(event){
event.target.value = event.target.value
},
render() {
var results = []
this.state.results.forEach(function(result) {
results.push(result)
})
let q = "" || (this.props.location.query.q) ? this.props.location.query.q : ""
return (
<div style={{position: "relative"}}>
<HeaderNav title="data.nypl / Agents / Search" link="/agents"/>
<div className="container">
<div className="row">
<div className="tweleve columns">
<input ref={(c) => this._input = c} type="text" className="agents-search-small" onKeyUp={this.handleKeyUp} onFocus={this.handleFocus} autoFocus="autofocus" defaultValue={q} placeholder="Search" autofocus="autofocus"/>
</div>
</div>
</div>
<div className="container">
{results}
</div>
</div>
)
}
})
function mapStateToProps(state) {
return {
whatever: state.counter,
history: state.history
}
}
// Which action creators does it want to receive by props?
function mapDispatchToProps(dispatch) {
return {
onIncrement: () => dispatch(increment())
}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(AgentsSearchResults);
|
client/src/components/atomic/InputList.js | kfirprods/tpp | import React from 'react';
import InteractiveList from "react-interactive-list";
// IMPORTANT: This style is responsible for the basic formation
import "react-interactive-list/lib/styles/react-interactive-list.css";
// Some extra styling for the input and the delete button
import "react-interactive-list/lib/styles/react-input-list.css";
import '../../styles/input-list.css';
export default class InputList extends React.Component {
constructor() {
super();
this.renderInput = this.renderInput.bind(this);
}
renderInput(props, removable, uniqueId, index, onChangeCallback) {
let inputClasses = "interactive-list-input";
if (removable) {
inputClasses += " interactive-list-input--removable";
}
return (
<input
type="text"
className={inputClasses}
onChange={e => onChangeCallback(e.target.value)}
placeholder={props.placeholder}
/>
);
}
render() {
return (
<InteractiveList {...this.props}
renderItem={this.renderInput} />
);
}
}
|
node_modules/react-router/es/StaticRouter.js | together-web-pj/together-web-pj | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import invariant from 'invariant';
import React from 'react';
import PropTypes from 'prop-types';
import { addLeadingSlash, createPath, parsePath } from 'history/PathUtils';
import Router from './Router';
var normalizeLocation = function normalizeLocation(object) {
var _object$pathname = object.pathname,
pathname = _object$pathname === undefined ? '/' : _object$pathname,
_object$search = object.search,
search = _object$search === undefined ? '' : _object$search,
_object$hash = object.hash,
hash = _object$hash === undefined ? '' : _object$hash;
return {
pathname: pathname,
search: search === '?' ? '' : search,
hash: hash === '#' ? '' : hash
};
};
var addBasename = function addBasename(basename, location) {
if (!basename) return location;
return _extends({}, location, {
pathname: addLeadingSlash(basename) + location.pathname
});
};
var stripBasename = function stripBasename(basename, location) {
if (!basename) return location;
var base = addLeadingSlash(basename);
if (location.pathname.indexOf(base) !== 0) return location;
return _extends({}, location, {
pathname: location.pathname.substr(base.length)
});
};
var createLocation = function createLocation(location) {
return typeof location === 'string' ? parsePath(location) : normalizeLocation(location);
};
var createURL = function createURL(location) {
return typeof location === 'string' ? location : createPath(location);
};
var staticHandler = function staticHandler(methodName) {
return function () {
invariant(false, 'You cannot %s with <StaticRouter>', methodName);
};
};
var noop = function noop() {};
/**
* The public top-level API for a "static" <Router>, so-called because it
* can't actually change the current location. Instead, it just records
* location changes in a context object. Useful mainly in testing and
* server-rendering scenarios.
*/
var StaticRouter = function (_React$Component) {
_inherits(StaticRouter, _React$Component);
function StaticRouter() {
var _temp, _this, _ret;
_classCallCheck(this, StaticRouter);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.createHref = function (path) {
return addLeadingSlash(_this.props.basename + createURL(path));
}, _this.handlePush = function (location) {
var _this$props = _this.props,
basename = _this$props.basename,
context = _this$props.context;
context.action = 'PUSH';
context.location = addBasename(basename, createLocation(location));
context.url = createURL(context.location);
}, _this.handleReplace = function (location) {
var _this$props2 = _this.props,
basename = _this$props2.basename,
context = _this$props2.context;
context.action = 'REPLACE';
context.location = addBasename(basename, createLocation(location));
context.url = createURL(context.location);
}, _this.handleListen = function () {
return noop;
}, _this.handleBlock = function () {
return noop;
}, _temp), _possibleConstructorReturn(_this, _ret);
}
StaticRouter.prototype.getChildContext = function getChildContext() {
return {
router: {
staticContext: this.props.context
}
};
};
StaticRouter.prototype.render = function render() {
var _props = this.props,
basename = _props.basename,
context = _props.context,
location = _props.location,
props = _objectWithoutProperties(_props, ['basename', 'context', 'location']);
var history = {
createHref: this.createHref,
action: 'POP',
location: stripBasename(basename, createLocation(location)),
push: this.handlePush,
replace: this.handleReplace,
go: staticHandler('go'),
goBack: staticHandler('goBack'),
goForward: staticHandler('goForward'),
listen: this.handleListen,
block: this.handleBlock
};
return React.createElement(Router, _extends({}, props, { history: history }));
};
return StaticRouter;
}(React.Component);
StaticRouter.propTypes = {
basename: PropTypes.string,
context: PropTypes.object.isRequired,
location: PropTypes.oneOfType([PropTypes.string, PropTypes.object])
};
StaticRouter.defaultProps = {
basename: '',
location: '/'
};
StaticRouter.childContextTypes = {
router: PropTypes.object.isRequired
};
export default StaticRouter; |
src/pages/cryptography/Caesar/Caesar.js | hyy1115/react-redux-webpack3 | import React from 'react'
class Caesar extends React.Component {
render() {
return (
<div>Caesar</div>
)
}
}
export default Caesar |
public/src/js/components/tool-settings/components/filters-settings/filters-settings.js | Robertmw/imagistral | /**
*
* Filters Settings Component
* @parent ToolSettings
* @author Robert P.
*
*/
import React from 'react';
import BaseComponent from '../../../base-component/base-component';
import {branch} from 'baobab-react/higher-order';
import * as actions from '../../actions';
class FiltersSettings extends BaseComponent {
constructor(props) {
super(props);
this._bind('_changeFilter');
}
_changeFilter(event) {
this.props.actions.changeFilter(event.target.value);
}
render() {
const props = this.props;
const filterTypes = ['None', 'Greyscale', 'Invert', 'Sepia'];
const renderFilters = filterTypes.map((el, index) => {
return (
<div
className="radioBtn"
key={el}
>
<input
checked = {props.filter === el}
name="filter"
onChange = {this._changeFilter}
type="radio"
value={el}
/>
<label>
<span className="radio--placeholder"></span>
{el}
</label>
</div>
);
});
return (
<aside>
<p className="settingsTitle">Filters settings</p>
<section className="setting">
<h3>Filter type</h3>
<div className="setting--wrapper">
{renderFilters}
</div>
</section>
</aside>
);
}
}
FiltersSettings.displayName = 'Filters Settings';
export default branch(FiltersSettings, {
cursors: {
filter: ['toolSettings', 'filter']
},
actions: {
changeFilter: actions.changeFilter
}
});
|
fixtures/packaging/systemjs-builder/dev/input.js | pyitphyoaung/react | import React from 'react';
import ReactDOM from 'react-dom';
ReactDOM.render(
React.createElement('h1', null, 'Hello World!'),
document.getElementById('container')
);
|
docs/app/Examples/addons/Confirm/Variations/index.js | clemensw/stardust | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ConfirmVariationsExamples = () => (
<ExampleSection title='Variations'>
<ComponentExample
title='Header'
description='A confirm can define a header.'
examplePath='addons/Confirm/Variations/ConfirmExampleHeader'
/>
<ComponentExample
title='Content'
description='A confirm can define content.'
examplePath='addons/Confirm/Variations/ConfirmExampleContent'
/>
<ComponentExample
title='Button Text'
description='A confirm can customize button text.'
examplePath='addons/Confirm/Variations/ConfirmExampleButtons'
/>
</ExampleSection>
)
export default ConfirmVariationsExamples
|
frontend/src/components/artist/album.js | Kilte/scrobbler | import React from 'react';
import {Link} from 'react-router';
import ProgressBar from '../shared/progress-bar';
class Album extends React.Component {
render() {
let data = this.props.data;
return <div className="artist-album">
<div className="artist-album-icon">
<img src="/images/album.png" />
</div>
<div className="artist-album-data">
<div className="artist-album-data-name" title={data.get('name')}>
<Link to={`/artist/${data.get('artist_id')}/album/${data.get('id')}`}>
{data.get('name')}
</Link>
</div>
<div className="artist-album-data-streak">
<span title="First play">{data.get('first_play')}</span>
<span> — </span>
<span title="Last play">{data.get('last_play')}</span>
</div>
</div>
<div className="artist-album-plays">
<ProgressBar percent={this.props.playsPercent}>{data.get('plays')}</ProgressBar>
</div>
</div>;
}
}
Album.propTypes = {
data: React.PropTypes.object.isRequired,
playsPercent:React.PropTypes.number.isRequired
};
export default Album;
|
public/js/components/Results.js | Vabrins/CadernetaDoIdoso | import React from 'react';
import ChartWeightControl from './ChartWeightControl';
import ChartGlucoseControl from './ChartGlucoseControl';
import ChartPressureControl from './ChartPressureControl';
class Results extends React.Component {
constructor (props) {
super(props)
this.state = {
lastUpdate: ''
}
}
render () {
return (
<div>
<div className="card mb-3">
<div className="card-header">
<i className="fa fa-area-chart"></i> Controle de peso
</div>
<div className="card-body">
<ChartWeightControl />
</div>
{/*<div className="card-footer small text-muted">Atualizado ontem às 11:59</div>*/}
</div>
<div className="card mb-3">
<div className="card-header">
<i className="fa fa-bar-chart"></i> Glicose
</div>
<div className="card-body">
<ChartGlucoseControl />
</div>
{/*<div className="card-footer small text-muted">Updated yesterday at 11:59 PM</div>*/}
</div>
<div className="card mb-3">
<div className="card-header">
<i className="fa fa-area-chart"></i> Controle de pressão
</div>
<div className="card-body">
<ChartPressureControl />
</div>
{/*<div className="card-footer small text-muted">Updated yesterday at 11:59 PM</div>*/}
</div>
</div>
)
}
}
export default Results; |
packages/starter-scripts/fixtures/kitchensink/template/src/features/syntax/ArraySpread.js | chungchiehlun/create-starter-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load(users) {
return [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
...users,
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load([{ id: 42, name: '42' }]);
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-array-spread">
{this.state.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
}
|
app/demo/render-react/Button.js | vivaxy/gt-node-server | /**
* @since 2019-11-25 08:22
* @author vivaxy
*/
import { connect } from 'react-redux';
import React, { Component } from 'react';
import { click, reset } from './actions';
import './index.css';
class Button extends Component {
handleClick = () => {
this.props.click();
setTimeout(() => {
this.props.reset();
}, 1000);
};
render() {
return (
<div className="render-react-root" onClick={this.handleClick}>
{this.props.text}
</div>
);
}
}
const mapStateToProps = (state) => {
return {
text: state.text,
};
};
const mapDispatchToProps = { click, reset };
export default connect(mapStateToProps, mapDispatchToProps)(Button);
|
client/node_modules/uu5g03/doc/main/server/public/data/source/uu5-common-lsi-mixin.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import Tools from './tools.js';
import $ from 'jquery';
export const LsiMixin = {
//@@viewOn:statics
statics: {
UU5_Common_LsiMixin: {
requiredMixins: ['UU5_Common_BaseMixin'],
lsiEvent: Tools.events.lsi
}
},
//@@viewOff:statics
//@@viewOn:propTypes
propTypes: {
language: React.PropTypes.string
},
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
getDefaultProps: function () {
return {
language: null
};
},
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
getInitialState: function () {
// initialize
this.registerMixin('UU5_Common_LsiMixin');
// state
return {
language: this.props.language || this.getEnvironmentLanguages()[0].location || this.getEnvironmentLanguages()[0].language
};
},
componentDidMount: function () {
$(window).on(this.constructor.UU5_Common_LsiMixin.lsiEvent, this._changeLanguage);
},
componentWillUnmount: function () {
$(window).off(this.constructor.UU5_Common_LsiMixin.lsiEvent, this._changeLanguage);
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
hasUU5_Common_LsiMixin: function () {
return this.hasMixin('UU5_Common_LsiMixin');
},
getUU5_Common_LsiMixinProps: function () {
return {
language: this.props.language
};
},
getUU5_Common_LsiMixinPropsToPass: function () {
return this.getUU5_Common_LsiMixinProps();
},
getLanguages: function () {
return this.getEnvironmentLanguages();
},
getLanguage: function () {
return this.state.language;
},
// component gets languages from global environment
getLSIItem: function (lsi) {
return this.getLSIItemByLanguage(lsi, this.getLanguages());
},
//@@viewOff:interface
//@@viewOn:overridingMethods
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
// TODO: 'cs-CZ,en;q=0.8...' is set to state and never will be used, necessary is doing setState and render the component
_setLanguage: function (language, setStateCallback) {
this.setState({ language: language }, setStateCallback);
return this;
},
_changeLanguage: function (e, language) {
if (this.getLanguage() !== language) {
if (typeof this.onChangeLanguage_ === 'function') {
this.onChangeLanguage_(language, e);
} else {
this._setLanguage(language);
}
}
}
//@@viewOff:componentSpecificHelpers
};
export default LsiMixin;
|
information/blendle-frontend-react-source/app/components/Cover.js | BramscoChill/BlendleParser | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Analytics from 'instances/analytics';
import Auth from 'controllers/auth';
import Image from 'components/Image';
import Button from 'components/Button';
import classNames from 'classnames';
import { providerById, prefillSelector } from 'selectors/providers';
import ProviderManager from 'managers/provider';
import BrowserEnvironment from 'instances/browser_environment';
import Link from 'components/Link';
export default class Cover extends Component {
static propTypes = {
issue: PropTypes.object.isRequired,
onClick: PropTypes.func,
onLoad: PropTypes.func,
};
state = {
ready: false,
};
_toggleFavourite(e) {
e.preventDefault();
const providerId = this.props.issue.get('provider').id;
const statsPayload = {
type: 'kiosk',
issue_id: this.props.issue.id,
provider: prefillSelector(providerById)(providerId).name,
};
const toggle = !this.props.issue.get('favourite');
ProviderManager.favorite(Auth.getUser().id, providerId, toggle).then(() => {
const eventName = toggle ? 'Add Favorite' : 'Remove favorite';
Analytics.track(eventName, statsPayload);
this.props.issue.set('favourite', toggle);
this.forceUpdate();
});
}
_onCoverLoad(ev) {
this.setState({ ready: true });
if (this.props.onLoad) {
this.props.onLoad(ev);
}
}
render() {
let favourite;
let className;
const issue = this.props.issue;
if (Auth.getUser() && this.state.ready) {
className = classNames('favourite', {
'l-favourite': issue.get('favourite'),
});
favourite = <Button className={className} onClick={e => this._toggleFavourite(e)} />;
}
return (
<div className="v-cover cover-image">
<Link onClick={this.props.onClick} href={`/issue/${issue.get('provider').id}/${issue.id}`}>
<Image
animate={BrowserEnvironment.isDesktop()}
src={issue.getCoverURL()}
width={issue.getCoverWidth()}
height={issue.getCoverHeight()}
onLoad={this._onCoverLoad.bind(this)}
/>
</Link>
{favourite}
</div>
);
}
}
// WEBPACK FOOTER //
// ./src/js/app/components/Cover.js |
src/components/forms/NewItemInput.js | reichert621/log-book | import React from 'react'
import styles from '../../styles/main.scss'
export class NewItemInput extends React.Component {
constructor (props) {
super(props)
}
handleKeyDown (e) {
if (e.which === 13) {
this.handleSubmit()
}
}
handleSubmit () {
const text = this.refs.itemText.value
if (text && text.length) {
this.props.onSubmit({ text: text })
this.refs.itemText.value = ''
}
}
render () {
return (
<div className={styles['input-add-item']}>
<input type='text' className='form-control' ref='itemText'
placeholder='Enter new item...'
onKeyDown={this.handleKeyDown.bind(this)} />
<button className='btn'
onClick={this.handleSubmit.bind(this)}>
Add
</button>
</div>
)
}
}
NewItemInput.propTypes = {
onSubmit: React.PropTypes.func.isRequired
}
export default NewItemInput
|
createAnimatableComponent.js | oblador/react-native-animatable | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Animated, Easing } from 'react-native';
import wrapStyleTransforms from './wrapStyleTransforms';
import getStyleValues from './getStyleValues';
import flattenStyle from './flattenStyle';
import createAnimation from './createAnimation';
import { getAnimationByName, getAnimationNames } from './registry';
import EASING_FUNCTIONS from './easing';
// These styles are not number based and thus needs to be interpolated
const INTERPOLATION_STYLE_PROPERTIES = [
// Transform styles
'rotate',
'rotateX',
'rotateY',
'rotateZ',
'skewX',
'skewY',
'transformMatrix',
// View styles
'backgroundColor',
'borderColor',
'borderTopColor',
'borderRightColor',
'borderBottomColor',
'borderLeftColor',
'shadowColor',
// Text styles
'color',
'textDecorationColor',
// Image styles
'tintColor',
];
const ZERO_CLAMPED_STYLE_PROPERTIES = ['width', 'height'];
// Create a copy of `source` without `keys`
function omit(keys, source) {
const filtered = {};
Object.keys(source).forEach(key => {
if (keys.indexOf(key) === -1) {
filtered[key] = source[key];
}
});
return filtered;
}
// Yes it's absurd, but actually fast
function deepEquals(a, b) {
return a === b || JSON.stringify(a) === JSON.stringify(b);
}
// Determine to what value the animation should tween to
function getAnimationTarget(iteration, direction) {
switch (direction) {
case 'reverse':
return 0;
case 'alternate':
return iteration % 2 ? 0 : 1;
case 'alternate-reverse':
return iteration % 2 ? 1 : 0;
case 'normal':
default:
return 1;
}
}
// Like getAnimationTarget but opposite
function getAnimationOrigin(iteration, direction) {
return getAnimationTarget(iteration, direction) ? 0 : 1;
}
function getCompiledAnimation(animation) {
if (typeof animation === 'string') {
const compiledAnimation = getAnimationByName(animation);
if (!compiledAnimation) {
throw new Error(`No animation registred by the name of ${animation}`);
}
return compiledAnimation;
}
return createAnimation(animation);
}
function makeInterpolatedStyle(compiledAnimation, animationValue) {
const style = {};
Object.keys(compiledAnimation).forEach(key => {
if (key === 'style') {
Object.assign(style, compiledAnimation.style);
} else if (key !== 'easing') {
style[key] = animationValue.interpolate(compiledAnimation[key]);
}
});
return wrapStyleTransforms(style);
}
function transitionToValue(
property,
transitionValue,
toValue,
duration,
easing,
useNativeDriver = false,
delay,
onTransitionBegin,
onTransitionEnd,
) {
const animation =
duration || easing || delay
? Animated.timing(transitionValue, {
toValue,
delay,
duration: duration || 1000,
easing:
typeof easing === 'function'
? easing
: EASING_FUNCTIONS[easing || 'ease'],
useNativeDriver,
})
: Animated.spring(transitionValue, { toValue, useNativeDriver });
setTimeout(() => onTransitionBegin(property), delay);
animation.start(() => onTransitionEnd(property));
}
// Make (almost) any component animatable, similar to Animated.createAnimatedComponent
export default function createAnimatableComponent(WrappedComponent) {
const wrappedComponentName =
WrappedComponent.displayName || WrappedComponent.name || 'Component';
const Animatable = Animated.createAnimatedComponent(WrappedComponent);
return class AnimatableComponent extends Component {
static displayName = `withAnimatable(${wrappedComponentName})`;
static propTypes = {
animation: PropTypes.oneOfType([PropTypes.string, PropTypes.object]),
duration: PropTypes.number,
direction: PropTypes.oneOf([
'normal',
'reverse',
'alternate',
'alternate-reverse',
]),
delay: PropTypes.number,
easing: PropTypes.oneOfType([
PropTypes.oneOf(Object.keys(EASING_FUNCTIONS)),
PropTypes.func,
]),
iterationCount(props, propName) {
const val = props[propName];
if (val !== 'infinite' && !(typeof val === 'number' && val >= 1)) {
return new Error(
'iterationCount must be a positive number or "infinite"',
);
}
return null;
},
iterationDelay: PropTypes.number,
onAnimationBegin: PropTypes.func,
onAnimationEnd: PropTypes.func,
onTransitionBegin: PropTypes.func,
onTransitionEnd: PropTypes.func,
style: PropTypes.oneOfType([
PropTypes.number,
PropTypes.array,
PropTypes.object,
]),
transition: PropTypes.oneOfType([
PropTypes.string,
PropTypes.arrayOf(PropTypes.string),
]),
useNativeDriver: PropTypes.bool,
isInteraction: PropTypes.bool,
};
static defaultProps = {
animation: undefined,
delay: 0,
direction: 'normal',
duration: undefined,
easing: undefined,
iterationCount: 1,
iterationDelay: 0,
onAnimationBegin() {},
onAnimationEnd() {},
onTransitionBegin() {},
onTransitionEnd() {},
style: undefined,
transition: undefined,
useNativeDriver: false,
isInteraction: undefined,
};
constructor(props) {
super(props);
const animationValue = new Animated.Value(
getAnimationOrigin(0, this.props.direction),
);
let animationStyle = {};
let compiledAnimation = {};
if (props.animation) {
compiledAnimation = getCompiledAnimation(props.animation);
animationStyle = makeInterpolatedStyle(
compiledAnimation,
animationValue,
);
}
this.state = {
animationValue,
animationStyle,
compiledAnimation,
transitionStyle: {},
transitionValues: {},
currentTransitionValues: {},
};
if (props.transition) {
this.state = {
...this.state,
...this.initializeTransitionState(props.transition),
};
}
this.delayTimer = null;
// Alias registered animations for backwards compatibility
getAnimationNames().forEach(animationName => {
if (!(animationName in this)) {
this[animationName] = this.animate.bind(this, animationName);
}
});
}
initializeTransitionState(transitionKeys) {
const transitionValues = {};
const styleValues = {};
const currentTransitionValues = getStyleValues(
transitionKeys,
this.props.style,
);
Object.keys(currentTransitionValues).forEach(key => {
const value = currentTransitionValues[key];
if (
INTERPOLATION_STYLE_PROPERTIES.indexOf(key) !== -1 ||
typeof value !== 'number'
) {
transitionValues[key] = new Animated.Value(0);
styleValues[key] = value;
} else {
const animationValue = new Animated.Value(value);
transitionValues[key] = animationValue;
styleValues[key] = animationValue;
}
});
return {
currentTransitionValues,
transitionStyle: styleValues,
transitionValues,
};
}
getTransitionState(keys) {
const transitionKeys = typeof keys === 'string' ? [keys] : keys;
let {
transitionValues,
currentTransitionValues,
transitionStyle,
} = this.state;
const missingKeys = transitionKeys.filter(
key => !this.state.transitionValues[key],
);
if (missingKeys.length) {
const transitionState = this.initializeTransitionState(missingKeys);
transitionValues = {
...transitionValues,
...transitionState.transitionValues,
};
currentTransitionValues = {
...currentTransitionValues,
...transitionState.currentTransitionValues,
};
transitionStyle = {
...transitionStyle,
...transitionState.transitionStyle,
};
}
return { transitionValues, currentTransitionValues, transitionStyle };
}
ref = null;
handleRef = ref => {
this.ref = ref;
};
setNativeProps(nativeProps) {
if (this.ref) {
this.ref.setNativeProps(nativeProps);
}
}
componentDidMount() {
const {
animation,
duration,
delay,
onAnimationBegin,
iterationDelay,
} = this.props;
if (animation) {
const startAnimation = () => {
onAnimationBegin();
this.startAnimation(duration, 0, iterationDelay, endState =>
this.props.onAnimationEnd(endState),
);
this.delayTimer = null;
};
if (delay) {
this.delayTimer = setTimeout(startAnimation, delay);
} else {
startAnimation();
}
}
}
// eslint-disable-next-line camelcase
UNSAFE_componentWillReceiveProps(props) {
const {
animation,
delay,
duration,
easing,
iterationDelay,
transition,
onAnimationBegin,
} = props;
if (transition) {
const values = getStyleValues(transition, props.style);
this.transitionTo(values, duration, easing, delay);
} else if (!deepEquals(animation, this.props.animation)) {
if (animation) {
if (this.delayTimer) {
this.setAnimation(animation);
} else {
onAnimationBegin();
this.animate(animation, duration, iterationDelay).then(endState =>
this.props.onAnimationEnd(endState),
);
}
} else {
this.stopAnimation();
}
}
}
componentWillUnmount() {
if (this.delayTimer) {
clearTimeout(this.delayTimer);
}
}
setAnimation(animation, callback) {
const compiledAnimation = getCompiledAnimation(animation);
this.setState(
state => ({
animationStyle: makeInterpolatedStyle(
compiledAnimation,
state.animationValue,
),
compiledAnimation,
}),
callback,
);
}
animate(animation, duration, iterationDelay) {
return new Promise(resolve => {
this.setAnimation(animation, () => {
this.startAnimation(duration, 0, iterationDelay, resolve);
});
});
}
stopAnimation() {
this.setState({
scheduledAnimation: false,
animationStyle: {},
});
this.state.animationValue.stopAnimation();
if (this.delayTimer) {
clearTimeout(this.delayTimer);
this.delayTimer = null;
}
}
startAnimation(duration, iteration, iterationDelay, callback) {
const { animationValue, compiledAnimation } = this.state;
const { direction, iterationCount, useNativeDriver, isInteraction } = this.props;
let easing = this.props.easing || compiledAnimation.easing || 'ease';
let currentIteration = iteration || 0;
const fromValue = getAnimationOrigin(currentIteration, direction);
const toValue = getAnimationTarget(currentIteration, direction);
animationValue.setValue(fromValue);
if (typeof easing === 'string') {
easing = EASING_FUNCTIONS[easing];
}
// Reverse easing if on the way back
const reversed =
direction === 'reverse' ||
(direction === 'alternate' && !toValue) ||
(direction === 'alternate-reverse' && !toValue);
if (reversed) {
easing = Easing.out(easing);
}
const config = {
toValue,
easing,
isInteraction: typeof isInteraction !== "undefined" ? isInteraction : iterationCount <= 1,
duration: duration || this.props.duration || 1000,
useNativeDriver,
delay: iterationDelay || 0,
};
Animated.timing(animationValue, config).start(endState => {
currentIteration += 1;
if (
endState.finished &&
this.props.animation &&
(iterationCount === 'infinite' || currentIteration < iterationCount)
) {
this.startAnimation(
duration,
currentIteration,
iterationDelay,
callback,
);
} else if (callback) {
callback(endState);
}
});
}
transition(fromValues, toValues, duration, easing) {
const fromValuesFlat = flattenStyle(fromValues);
const toValuesFlat = flattenStyle(toValues);
const transitionKeys = Object.keys(toValuesFlat);
const {
transitionValues,
currentTransitionValues,
transitionStyle,
} = this.getTransitionState(transitionKeys);
transitionKeys.forEach(property => {
const fromValue = fromValuesFlat[property];
const toValue = toValuesFlat[property];
let transitionValue = transitionValues[property];
if (!transitionValue) {
transitionValue = new Animated.Value(0);
}
const needsInterpolation =
INTERPOLATION_STYLE_PROPERTIES.indexOf(property) !== -1 ||
typeof value !== 'number';
const needsZeroClamping =
ZERO_CLAMPED_STYLE_PROPERTIES.indexOf(property) !== -1;
if (needsInterpolation) {
transitionValue.setValue(0);
transitionStyle[property] = transitionValue.interpolate({
inputRange: [0, 1],
outputRange: [fromValue, toValue],
});
currentTransitionValues[property] = toValue;
toValuesFlat[property] = 1;
} else {
if (needsZeroClamping) {
transitionStyle[property] = transitionValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 1],
extrapolateLeft: 'clamp',
});
currentTransitionValues[property] = toValue;
} else {
transitionStyle[property] = transitionValue;
}
transitionValue.setValue(fromValue);
}
});
this.setState(
{ transitionValues, transitionStyle, currentTransitionValues },
() => {
this.transitionToValues(
toValuesFlat,
duration || this.props.duration,
easing,
this.props.delay,
);
},
);
}
transitionTo(toValues, duration, easing, delay) {
const { currentTransitionValues } = this.state;
const toValuesFlat = flattenStyle(toValues);
const transitions = {
from: {},
to: {},
};
Object.keys(toValuesFlat).forEach(property => {
const toValue = toValuesFlat[property];
const needsInterpolation =
INTERPOLATION_STYLE_PROPERTIES.indexOf(property) !== -1 ||
typeof value !== 'number';
const needsZeroClamping =
ZERO_CLAMPED_STYLE_PROPERTIES.indexOf(property) !== -1;
const transitionStyle = this.state.transitionStyle[property];
const transitionValue = this.state.transitionValues[property];
if (
!needsInterpolation &&
!needsZeroClamping &&
transitionStyle &&
transitionStyle === transitionValue
) {
transitionToValue(
property,
transitionValue,
toValue,
duration,
easing,
this.props.useNativeDriver,
delay,
prop => this.props.onTransitionBegin(prop),
prop => this.props.onTransitionEnd(prop),
);
} else {
let currentTransitionValue = currentTransitionValues[property];
if (
typeof currentTransitionValue === 'undefined' &&
this.props.style
) {
const style = getStyleValues(property, this.props.style);
currentTransitionValue = style[property];
}
transitions.from[property] = currentTransitionValue;
transitions.to[property] = toValue;
}
});
if (Object.keys(transitions.from).length) {
this.transition(transitions.from, transitions.to, duration, easing);
}
}
transitionToValues(toValues, duration, easing, delay) {
Object.keys(toValues).forEach(property => {
const transitionValue = this.state.transitionValues[property];
const toValue = toValues[property];
transitionToValue(
property,
transitionValue,
toValue,
duration,
easing,
this.props.useNativeDriver,
delay,
prop => this.props.onTransitionBegin(prop),
prop => this.props.onTransitionEnd(prop),
);
});
}
render() {
const { style, animation, transition } = this.props;
if (animation && transition) {
throw new Error('You cannot combine animation and transition props');
}
const restProps = omit(
[
'animation',
'duration',
'direction',
'delay',
'easing',
'iterationCount',
'iterationDelay',
'onAnimationBegin',
'onAnimationEnd',
'onTransitionBegin',
'onTransitionEnd',
'style',
'transition',
'useNativeDriver',
'isInteraction',
],
this.props,
);
return (
<Animatable
ref={this.handleRef}
style={[
style,
this.state.animationStyle,
wrapStyleTransforms(this.state.transitionStyle),
]}
{...restProps}
/>
);
}
};
}
|
flow_auth/src/user/ui/logoutbutton/LogoutButton.js | Spreadway/core | import React from 'react'
const LogoutButton = ({ onLogoutUserClick }) => {
return(
<li className="pure-menu-item">
<a href="#" className="pure-menu-link" onClick={(event) => onLogoutUserClick(event)}>Logout</a>
</li>
)
}
export default LogoutButton
|
src/components/extensions/overview/blocks/about.js | vFujin/HearthLounge | import React from 'react';
import _ from 'lodash';
import PropTypes from 'prop-types';
const About = ({about}) => {
const {announce_date, release_date, no_cards, description} = about;
const Li = ({label, value}) =>{
return (
<li>
<p>{_.startCase(label)} <span>{value}</span></p>
</li>
)
};
return (
<ul className="container__blocks--block-content about">
<Li label="announced" value={announce_date}/>
<Li label="released" value={release_date}/>
<Li label="number of cards" value={no_cards}/>
<li className="description">
<p><span>{description}</span></p>
</li>
</ul>
)
};
export default About;
About.propTypes = {
about: PropTypes.object.isRequired
}; |
componentes/Banner.js | yomi-network/app | /* @flow */
import React from 'react';
import {
Image,
Platform,
StyleSheet,
Text,
View,
} from 'react-native';
const Banner = () => (
<View style={styles.banner}>
<Image
source={require('../imagenes/logo-yomi-positivo.png')}
style={styles.image}
/>
<Text style={styles.title}>Yomi!!!</Text>
</View>
);
export default Banner;
const styles = StyleSheet.create({
banner: {
backgroundColor: 'rgb(255,170,77)',
flexDirection: 'row',
alignItems: 'center',
padding: 0,
marginTop: Platform.OS === 'ios' ? 20 : 0,
},
image: {
width: 36,
height: 36,
resizeMode: 'contain',
margin: 8,
},
title: {
fontSize: 18,
fontWeight: '200',
color: '#fff',
margin: 8,
marginLeft: 110,
},
});
|
src/library/searchSuggestions/index.js | zdizzle6717/tree-machine-records | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import {Input} from '../../library/validations';
import {scrollUp, scrollDown} from '../utilities/scrollHelpers';
export default function(Service, method) {
let _keyChart = {
9: 'tab',
13: 'enter',
27: 'escape',
38: 'up',
40: 'down'
};
let _skipSearch = false;
let _selectedSuggestion = null;
function configureSuggestion(displayKeys, suggestion) {
let formattedSuggestion = '';
displayKeys.forEach((key, i) => {
formattedSuggestion += suggestion[key];
if (i < displayKeys.length -1) {
formattedSuggestion += ', '
}
})
return formattedSuggestion;
}
const SearchSuggestions = class SearchSuggestions extends React.Component {
constructor() {
super();
this.state = {
'element': null,
'inputString': '',
'results': [],
'selectedIndex': -1,
'showSuggestions': false,
'storedInputString': '',
'suggestions': []
};
this.handleInputChange = this.handleInputChange.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
this.handleClickSelect = this.handleClickSelect.bind(this);
this.handleClickAway = this.handleClickAway.bind(this);
this.toggleSuggestions = this.toggleSuggestions.bind(this);
}
componentDidMount() {
let element = ReactDOM.findDOMNode(this);
this.setState({
'element': element
})
}
handleClickAway() {
this.setState({
'inputString': this.state.storedInputString,
'selectedIndex': -1,
'selectedSuggesetion': null,
'showSuggestions': false,
'suggestions': []
});
}
handleInputChange(e) {
let value = e.target.value;
this.setState({
'inputString': value,
'storedInputString': value
});
if (!_skipSearch) {
if (!Service[method]) {
throw new Error('Library searchSuggestions: No service was found with the supplied method name');
}
Service[method]({"searchQuery": value, "maxResults": this.props.maxResults}).then((response) => {
let showSuggestions = false;
let suggestions = [];
if (response.results.length > 0 && value.length >= this.props.minCharacters) {
suggestions = response.results;
showSuggestions = true;
};
this.setState({
'showSuggestions': showSuggestions,
'suggestions': suggestions
})
});
} else {
_skipSearch = false;
}
e.target.value = e.target.value;
e.target.suggestionObject = _selectedSuggestion || null;
this.props.handleInputChange(e);
}
handleClickSelect(e) {
let suggestion = this.state.suggestions[e.target.getAttribute('data-index')];
_selectedSuggestion = suggestion;
let value = configureSuggestion(this.props.displayKeys, suggestion);
_skipSearch = true;
let event = new Event('input', { bubbles: true });
let elem = ReactDOM.findDOMNode(this);
let input = elem.getElementsByTagName('input')[0];
input.value = configureSuggestion(this.props.displayKeys, suggestion);
input.dispatchEvent(event);
this.setState({
'inputString': value,
'selectedIndex': -1,
'showSuggestions': false,
'storedInputString': configureSuggestion(this.props.displayKeys, suggestion),
'suggestions': []
});
}
onKeyDown(e) {
let key = _keyChart[e.keyCode];
let inputString = this.state.inputString;
let suggestions = this.state.suggestions;
let selectedIndex = this.state.selectedIndex;
let showSuggestions = this.state.showSuggestions;
let storedInputString = this.state.storedInputString;
if (!key) {
_selectedSuggestion = null;
this.setState({
'selectedIndex': -1
})
return;
}
if (key !== 'tab') {
e.preventDefault();
}
if (key === 'enter') {
if (selectedIndex > -1) {
storedInputString = configureSuggestion(this.props.displayKeys, suggestions[selectedIndex]);
_selectedSuggestion = suggestions[selectedIndex];
} else {
_selectedSuggestion = null;
}
_skipSearch = true;
let event = new Event('input', { bubbles: true });
let elem = ReactDOM.findDOMNode(this);
let input = elem.getElementsByTagName('input')[0];
input.value = configureSuggestion(this.props.displayKeys, suggestions[selectedIndex]);
input.dispatchEvent(event);
selectedIndex = -1;
showSuggestions = false;
suggestions = [];
}
if (key === 'escape') {
inputString = storedInputString;
selectedIndex = -1;
showSuggestions = false;
suggestions = [];
}
if (key === 'down') {
if (suggestions.length > 0) {
scrollDown(this.props.rowCount, this.state.element, selectedIndex, suggestions.length);
}
selectedIndex = selectedIndex < this.state.suggestions.length - 1 ? selectedIndex + 1 : selectedIndex;
}
if (key === 'tab') {
if (selectedIndex < this.state.suggestions.length - 1) {
e.preventDefault();
if (suggestions.length > 0) {
scrollDown(this.props.rowCount, this.state.element, selectedIndex, suggestions.length);
}
selectedIndex++;
} else {
selectedIndex = -1;
suggestions = [];
inputString = storedInputString;
}
}
if (key === 'up') {
if (suggestions.length > 0) {
scrollUp(this.props.rowCount, this.state.element, selectedIndex, suggestions.length);
}
selectedIndex = selectedIndex > -1 ? selectedIndex - 1 : selectedIndex;
if (selectedIndex === -1) {
inputString = storedInputString;
}
}
if (selectedIndex > -1 && key !== 'escape') {
inputString = configureSuggestion(this.props.displayKeys, suggestions[selectedIndex]) ;
}
this.setState({
'inputString': inputString,
'selectedIndex': selectedIndex,
'showSuggestions': showSuggestions,
'storedInputString': storedInputString,
'suggestions': suggestions
});
}
toggleSuggestions() {
this.setState({
'showSuggestions': !this.state.showSuggestions
})
}
render() {
let suggestionClasses = classNames({
'search-suggestions': true,
'active': this.state.showSuggestions && this.state.suggestions.length > 0
});
return (
<div className={suggestionClasses} onKeyDown={this.onKeyDown}>
<Input type="text" name={this.props.name} value={this.state.inputString} handleInputChange={this.handleInputChange} validate={this.props.validate} autoComplete="off" required={this.props.required}/>
{
this.state.showSuggestions && this.state.suggestions.length > 0 &&
<div className="suggestions">
<ul>
{
this.state.suggestions.map((suggestion, i) =>
<li key={i} data-index={i} className={i === this.state.selectedIndex ? 'selected' : ''} onClick={this.handleClickSelect}>{configureSuggestion(this.props.displayKeys, suggestion)}</li>
)
}
</ul>
</div>
}
{
this.state.showSuggestions && this.state.suggestions.length > 0 &&
<div className="clickaway-backdrop" onClick={this.handleClickAway}></div>
}
</div>
)
}
}
SearchSuggestions.propTypes = {
'displayKeys': React.PropTypes.array.isRequired,
'handleInputChange': React.PropTypes.func.isRequired,
'maxResults': React.PropTypes.number,
'minCharacters': React.PropTypes.number,
'name': React.PropTypes.string.isRequired,
'required': React.PropTypes.bool,
'rowCount': React.PropTypes.number,
'validate': React.PropTypes.string
}
SearchSuggestions.defaultProps = {
'maxResults': 10,
'minCharacters': 3,
'required': false,
'rowCount': 4
}
return SearchSuggestions;
}
|
jenkins-design-language/src/js/components/material-ui/svg-icons/action/search.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionSearch = (props) => (
<SvgIcon {...props}>
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14z"/>
</SvgIcon>
);
ActionSearch.displayName = 'ActionSearch';
ActionSearch.muiName = 'SvgIcon';
export default ActionSearch;
|
react-native-event-bridge-enhance.js | maicki/react-native-event-bridge | /**
* react-native-event-bridge-enhance
* @flow
*
*/
// Mixin to provide the boilerplate that is needed for a event listener component
// as well as also supports automatic removing of subscription for event listeners
// if the listener is registered via the registerEventListener method.
import React from 'react';
import type EmitterSubscription from 'EmitterSubscription';
import EventBridge from './index';
const enhanceForEventsSupport = (ComposedComponent: React.Component<any>) => {
const _key = 'EventsBridgeEnhance_Listeners';
return class extends (ComposedComponent: any) {
static contextTypes = {
rootTag: React.PropTypes.number,
};
componentWillUnmount() {
if (super.componentWillUnmount) {
super.componentWillUnmount();
}
const { [_key]: listeners } = this;
if (listeners) {
listeners.forEach(listener => {
listener.remove();
});
}
this[_key] = null;
}
registerEventListener(...listeners: Array<EmitterSubscription>) {
const { [_key]: listenerList } = this;
if (!listenerList) {
this[_key] = listeners;
} else {
listenerList.push(...listeners);
}
return this;
}
};
};
export default enhanceForEventsSupport;
/* Experimental
/********************************/
const enhanceForEventsSupportEnhanced = (ComposedComponent: any) =>
class extends (ComposedComponent: any) {
_subscribableSubscriptions: ?Array<EmitterSubscription>;
static contextTypes = {
rootTag: React.PropTypes.number,
};
componentWillMount() {
this._subscribableSubscriptions = [];
}
componentWillUnmount() {
if (this._subscribableSubscriptions) {
this._subscribableSubscriptions.forEach(subscription =>
subscription.remove()
);
}
this._subscribableSubscriptions = null;
}
registerEventListener(callback: any) {
if (this._subscribableSubscriptions) {
this._subscribableSubscriptions.push(
EventBridge.addEventListener(this, callback)
);
}
}
};
function enhanceForEventsSupportDecorator() {
// eslint-disable-next-line func-names
return function(DecoratedComponent: React.Component<any>) {
const _key = 'ViewControllerEventsListenerEnhance_listeners';
return class extends (DecoratedComponent: any) {
static contextTypes = {
rootTag: React.PropTypes.number,
};
componentWillUnmount() {
if (super.componentWillUnmount) {
super.componentWillUnmount();
}
const { [_key]: listeners } = this;
if (listeners) {
listeners.forEach(listener => {
listener.remove();
});
}
this[_key] = null;
}
registerEventListener(...listeners: Array<EmitterSubscription>) {
const { [_key]: listenerList } = this;
if (!listenerList) {
this[_key] = listeners;
} else {
listenerList.push(...listeners);
}
return this;
}
};
};
}
export { enhanceForEventsSupportDecorator, enhanceForEventsSupportEnhanced };
|
app/components/MusicNoteMeterRing.js | BinaryNate/voxophone-react-native | import React, { Component } from 'react';
import { View, StyleSheet } from 'react-native';
/**
* A ring used in the MusicNoteMeter display, which animates when a note is played.
*/
export default class MusicNoteMeterRing extends Component {
render() {
const { diameter } = this.props;
let dynamicStyle = {
width: diameter,
height: diameter,
borderRadius: diameter / 2
};
return (
<View
style={[ styles.ring, dynamicStyle ]}
backgroundColor={this.props.backgroundColor}
>
{this.props.children}
</View>
);
}
}
const styles = StyleSheet.create({
ring: {
justifyContent: 'center',
alignItems: 'center'
}
});
|
src/routes/Devices/components/nodes/Country.js | KozlovDmitriy/Pos.Hierarchy.Net | import React from 'react'
import PropTypes from 'prop-types'
import { Group } from '@vx/group'
import Plus from './Plus'
import NodeLabel from './NodeLabel'
import CollapsedNode from './CollapsedNode'
class Country extends CollapsedNode {
static propTypes = {
node: PropTypes.object.isRequired,
errors: PropTypes.array.isRequired,
warnings: PropTypes.array.isRequired,
setPopoverIsOpen: PropTypes.func.isRequired,
collapseNodeAndRewriteTree: PropTypes.func.isRequired
}
state = { value: 0 }
handleChange = (event, value) => {
this.setState({ value })
}
render () {
const { node } = this.props
const loading = this.getLoading(22, 12)
const plus = node.collapsed ?
this.state.loading ? loading :
(
<Plus
color={this.statusColor || '#00afa3'}
onDoubleClick={this.handleDoubleClick}
/>
) : void 0
const label = (
<NodeLabel
x={0}
y={-21}
fontSize={15}
color={this.statusColor || '#00afa3'}
text={node.name}
onClick={this.onClick}
/>
)
return (
<Group y={node.y} x={node.x} style={{ cursor: 'pointer' }}>
<polygon
ref={this.refCallback}
points={'-1, -10, -8, 11, 9, -2, -11, -2, 6, 11'}
fill={this.statusColor || '#00afa3'}
stroke={this.statusColor || '#00afa3'}
strokeWidth={2.5}
strokeOpacity={0.8}
/>
{plus}
{label}
{this.badge}
</Group>
)
}
}
export default Country
|
src/Controls/Log.js | rpominov/react-demo | import React from 'react'
import createReactClass from 'create-react-class'
import T from 'prop-types'
import Group from './Group'
const style = {
background: '#fff',
borderTop: 'solid 1px #e5e5e5',
borderRight: 'solid 1px #e5e5e5',
borderLeft: 'solid 1px #e5e5e5',
fontSize: '10px',
lineHeight: '1.2',
overflow: 'auto',
}
const styleItem = {
padding: '0.3em',
borderBottom: 'solid 1px #e5e5e5',
}
export default createReactClass({
displayName: 'Demo.Controls.Log',
propTypes: {
name: T.string.isRequired,
items: T.arrayOf(T.string).isRequired,
},
render() {
const {name, items} = this.props
return <Group name={name}>
<div style={style} className="react-demo__log">
{items.map((x, i) =>
<div key={i} style={styleItem} className="react-demo__log-item">
{x || '<no arguments>'}
</div>
)}
</div>
</Group>
},
})
|
src/components/common/svg-icons/av/skip-previous.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvSkipPrevious = (props) => (
<SvgIcon {...props}>
<path d="M6 6h2v12H6zm3.5 6l8.5 6V6z"/>
</SvgIcon>
);
AvSkipPrevious = pure(AvSkipPrevious);
AvSkipPrevious.displayName = 'AvSkipPrevious';
AvSkipPrevious.muiName = 'SvgIcon';
export default AvSkipPrevious;
|
src/svg-icons/places/rv-hookup.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesRvHookup = (props) => (
<SvgIcon {...props}>
<path d="M20 17v-6c0-1.1-.9-2-2-2H7V7l-3 3 3 3v-2h4v3H4v3c0 1.1.9 2 2 2h2c0 1.66 1.34 3 3 3s3-1.34 3-3h8v-2h-2zm-9 3c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm7-6h-4v-3h4v3zM17 2v2H9v2h8v2l3-3z"/>
</SvgIcon>
);
PlacesRvHookup = pure(PlacesRvHookup);
PlacesRvHookup.displayName = 'PlacesRvHookup';
PlacesRvHookup.muiName = 'SvgIcon';
export default PlacesRvHookup;
|
Realization/frontend/czechidm-core/src/components/advanced/CodeListValue/CodeListValue.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../basic';
import { CodeListManager, CodeListItemManager } from '../../../redux';
const codeListManager = new CodeListManager();
const codeListItemManager = new CodeListItemManager();
/**
* Code list Value
* - code decorator only
*
* Look out: code list has to be loaded externally: this.context.store.dispatch(codeListManager.fetchCodeListIfNeeded(code));
*
* TODO: show loading from data
* TODO: multi value
*
* @author Radek Tomiška
* @since 9.4.0
*/
export class CodeListValue extends Basic.AbstractContextComponent {
renderItem(value, options) {
if (!options || !value) {
return value;
}
const item = options.find(i => i.code === value);
if (!item) {
return value;
}
return codeListItemManager.getNiceLabel(item);
}
render() {
const { rendered, showLoading, _showLoading, value, options } = this.props;
//
if (!rendered) {
return null;
}
if (showLoading || _showLoading) {
return (
<Basic.Icon icon="refresh" showLoading />
);
}
//
return (
<span>
{ this.renderItem(value, options) }
</span>
);
}
}
CodeListValue.propTypes = {
...Basic.AbstractContextComponent.propTypes,
/**
* CodeList code
*/
code: PropTypes.string.isRequired
};
CodeListValue.defaultProps = {
...Basic.AbstractContextComponent.defaultProps
};
function select(state, component) {
//
return {
options: codeListManager.getCodeList(state, component.code),
_showLoading: codeListManager.isShowLoading(state, component.code),
};
}
export default connect(select)(CodeListValue);
|
app/src/components/SignUp.js | tom-s/3d-ears | import React from 'react'
import SignUpForm from './signUp/form'
const SignUp = (props) => {
const { onSubmit } = props
return (
<section className="SignUp">
<div className="container">
<h3 className="text-center">Sign up</h3>
<SignUpForm onSubmit={onSubmit} />
</div>
</section>
)
}
export default SignUp |
demo/tile-bounding-box.js | joelburget/d4 | // see https://bl.ocks.org/mbostock/eb0c48375fcdcdc00c54a92724733d0d
import React from 'react';
import {geoMercator, geoPath} from 'd3-geo';
import {tile} from 'd3-tile';
import topojson from 'topojson';
import us from '../data/us.json';
const pi = Math.PI;
const tau = 2 * pi;
const width = 960;
const height = 600;
const projection = geoMercator()
.scale(1 / tau)
.translate([0, 0]);
const bounds = [[-124.408585, 32.534291], [-114.138271, 42.007768]];
const p0 = projection([bounds[0][0], bounds[1][1]]);
const p1 = projection([bounds[1][0], bounds[0][1]]);
function floor(k) {
return Math.pow(2, Math.floor(Math.log(k) / Math.LN2));
}
const k = floor(0.95 / Math.max((p1[0] - p0[0]) / width, (p1[1] - p0[1]) / height));
const tx = (width - k * (p1[0] + p0[0])) / 2;
const ty = (height - k * (p1[1] + p0[1])) / 2;
projection
.scale(k / tau)
.translate([tx, ty]);
const tiles = tile()
.size([width, height])
.scale(k)
.translate([tx, ty])
();
const path = geoPath().projection(projection);
export default function TileMap() {
const states = topojson.feature(us, us.objects.states).features;
const imgs = tiles.map(tile => {
const style = {
position: 'absolute',
left: (tile[0] + tiles.translate[0]) * tiles.scale + "px",
top: (tile[1] + tiles.translate[1]) * tiles.scale + "px",
};
const src = "http://" + "abc"[tile[1] % 3] + ".tile.openstreetmap.org/" + tile[2] + "/" + tile[0] + "/" + tile[1] + ".png";
return (
<img
style={style}
src={src}
width={tiles.scale}
height={tiles.scale}
/>
);
});
const paths = states.map(state => (
<path
key={state.id}
fill='none'
stroke='#000'
d={path(state)}
/>
));
const style = {width, height, position: 'absolute', overflow: 'hidden'};
return (
<div style={{position: 'relative', width, height}}>
<div style={style}>
{imgs}
</div>
<svg width={width} height={height} style={style}>
{paths}
</svg>
</div>
);
}
|
plugins/Hosting/js/components/fileslist.js | NebulousLabs/Sia-UI | import PropTypes from 'prop-types'
import React from 'react'
import { List } from 'immutable'
import Modal from './warningmodal.js'
import Path from 'path'
const FilesList = ({ folders, folderPathToRemove, actions }) => {
const addStorageLocation = () => actions.addFolderAskPathSize()
const removeStorageLocation = folder => () => {
actions.removeFolder(folder)
actions.updateFolderToRemove()
}
const onResizeStorageLocationClick = folder => () =>
actions.resizeFolder(folder)
const onRemoveStorageLocationClick = folder => () =>
actions.updateFolderToRemove(folder.get('path'))
const hideRemoveStorageModal = () => actions.updateFolderToRemove()
// sort folders by their name
const sortedFolders = folders.sortBy(folder => folder.get('path'))
const FileList = sortedFolders.map((folder, key) => (
<div className='property pure-g' key={key}>
<div className='pure-u-3-4'>
<div className='name'>{folder.get('path')}</div>
</div>
<div className='pure-u-1-12'>
<div>{Math.floor(folder.get('free')).toString()} GB</div>
</div>
<div className='pure-u-1-12'>
<div>{Math.floor(folder.get('size')).toString()} GB</div>
</div>
<div
className='pure-u-1-24'
onClick={onResizeStorageLocationClick(folder)}
>
<div>
<i className='fa fa-edit button' />
</div>
</div>
<div
className='pure-u-1-24'
onClick={onRemoveStorageLocationClick(folder)}
>
<div>
<i className='fa fa-remove button' />
</div>
</div>
{folderPathToRemove && folderPathToRemove === folder.get('path') ? (
<Modal
title={`Remove "${Path.basename(folder.get('path'))}"?`}
message='No longer use this folder for storage? You may lose collateral if you do not have enough space to fill all contracts.'
actions={{
acceptModal: removeStorageLocation(folder),
declineModal: hideRemoveStorageModal
}}
/>
) : null}
</div>
))
return (
<div className='files section'>
<div className='property row'>
<div className='title' />
<div className='controls full'>
<div className='button left' id='edit' onClick={addStorageLocation}>
<i className='fa fa-folder-open' />
Add Storage Folder
</div>
<div className='pure-u-1-12' style={{ textAlign: 'left' }}>
Free
</div>
<div className='pure-u-1-12' style={{ textAlign: 'left' }}>
Max
</div>
<div className='pure-u-1-12' />
</div>
</div>
{FileList}
</div>
)
}
FilesList.propTypes = {
folderPathToRemove: PropTypes.string,
folders: PropTypes.instanceOf(List).isRequired
}
export default FilesList
|
imports/ui/components/SupplierOrderDetailsView/SupplierOrderDetailsView.js | haraneesh/mydev | import React from 'react';
import {
Panel, Label, Row, Col,
} from 'react-bootstrap';
import { dateSettings } from '../../../modules/settings';
import constants from '../../../modules/constants';
import { getDisplayShortDate, displayUnitOfSale } from '../../../modules/helpers';
function SupplierOrderDetailsView(args) {
const { supplierOrder } = args;
return (
<Panel style={{ textAlign: 'left' }}>
<Col xs={6} style={{ marginBottom: '3rem' }}>
<Label bsStyle={constants.OrderStatus[supplierOrder.order_status].label}>
{constants.OrderStatus[supplierOrder.order_status].display_value}
</Label>
</Col>
<Col xs={6} style={{ textAlign: 'right' }}>
{getDisplayShortDate(supplierOrder.createdAt, dateSettings.timeZone)}
</Col>
{ supplierOrder.products.map((product) => (
<Row key={product._id}>
<Col xs={8}>{product.name}</Col>
<Col xs={4} className="text-right">
{displayUnitOfSale(product.quantity, product.unitOfSale)}
</Col>
</Row>
))}
</Panel>
);
}
export default SupplierOrderDetailsView;
|
web-server/v0.4/src/pages/Explore/index.js | gurbirkalsi/pbench | import React, { Component } from 'react';
import { connect } from 'dva';
import { routerRedux } from 'dva/router';
import { Card, Button, Popconfirm } from 'antd';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import Table from '@/components/Table';
@connect(({ datastore, explore, loading }) => ({
sharedSessions: explore.sharedSessions,
datastoreConfig: datastore.datastoreConfig,
loadingSharedSessions: loading.effects['explore/fetchSharedSessions'],
}))
class Explore extends Component {
constructor(props) {
super(props);
this.state = {
sharedSessions: props.sharedSessions,
};
}
componentDidMount() {
this.fetchDatastoreConfig();
}
componentWillReceiveProps(nextProps) {
const { sharedSessions } = this.props;
if (nextProps.sharedSessions !== sharedSessions) {
this.setState({ sharedSessions: nextProps.sharedSessions });
}
}
fetchDatastoreConfig = () => {
const { dispatch } = this.props;
dispatch({
type: 'datastore/fetchDatastoreConfig',
}).then(() => {
this.fetchSharedSessions();
});
};
fetchSharedSessions = () => {
const { dispatch, datastoreConfig } = this.props;
dispatch({
type: 'explore/fetchSharedSessions',
payload: { datastoreConfig },
});
};
startSharedSession = record => {
const { dispatch } = this.props;
const parsedConfig = JSON.parse(record.config);
window.localStorage.setItem('persist:root', parsedConfig);
dispatch(routerRedux.push(parsedConfig.routing.location.pathname));
};
render() {
const { sharedSessions } = this.state;
const { loadingSharedSessions } = this.props;
const sharedSessionColumns = [
{
title: 'Session ID',
dataIndex: 'id',
key: 'id',
},
{
title: 'Date Created',
dataIndex: 'createdAt',
key: 'createdAt',
defaultSortOrder: 'descend',
sorter: (a, b) => Date.parse(a.createdAt) - Date.parse(b.createdAt),
},
{
title: 'Description',
dataIndex: 'description',
key: 'description',
},
{
title: 'Action',
dataIndex: '',
key: 'action',
render: (text, record) => (
<Popconfirm
title="Start a new dashboard session?"
cancelText="No"
okText="Yes"
onConfirm={() => this.startSharedSession(record)}
>
<Button type="link">Start Session</Button>
</Popconfirm>
),
},
];
return (
<PageHeaderLayout title="Explore">
<Card title="Shared Sessions" bordered={false}>
<Table
columns={sharedSessionColumns}
dataSource={sharedSessions}
loading={loadingSharedSessions}
/>
</Card>
</PageHeaderLayout>
);
}
}
export default Explore;
|
src/drive/lib/confirm.js | enguerran/cozy-drive | import React from 'react'
import ReactDOM from 'react-dom'
const createWrapper = () =>
document.body.appendChild(document.createElement('div'))
const confirm = component =>
new Promise((resolve, reject) => {
const wrapper = createWrapper()
const abort = () => {
ReactDOM.unmountComponentAtNode(wrapper)
reject(new Error('abort'))
}
const confirm = () => {
ReactDOM.unmountComponentAtNode(wrapper)
resolve()
}
ReactDOM.render(React.cloneElement(component, { confirm, abort }), wrapper)
})
export default confirm
export const alert = component => {
const wrapper = createWrapper()
const close = () => {
ReactDOM.unmountComponentAtNode(wrapper)
}
ReactDOM.render(React.cloneElement(component, { close }), wrapper)
}
|
examples/huge-apps/routes/Profile/components/Profile.js | jwaltonmedia/react-router | import React from 'react'
class Profile extends React.Component {
render() {
return (
<div>
<h2>Profile</h2>
</div>
)
}
}
export default Profile
|
src/App.js | bcbcb/react-hot-boilerplate | import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<h1>Hello, world.</h1>
);
}
}
|
src/js/components/icons/base/Favorite.js | odedre/grommet-final | /**
* @description Favorite SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M2,8.4 C2,4 5,3 7,3 C9,3 11,5 12,6.5 C13,5 15,3 17,3 C19,3 22,4 22,8.4 C22,15 12,21 12,21 C12,21 2,15 2,8.4 Z"/></svg>
*/
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-favorite`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'favorite');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M2,8.4 C2,4 5,3 7,3 C9,3 11,5 12,6.5 C13,5 15,3 17,3 C19,3 22,4 22,8.4 C22,15 12,21 12,21 C12,21 2,15 2,8.4 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Favorite';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
docs/src/pages/components/transitions/SimpleCollapse.js | lgollut/material-ui | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Switch from '@material-ui/core/Switch';
import Paper from '@material-ui/core/Paper';
import Collapse from '@material-ui/core/Collapse';
import FormControlLabel from '@material-ui/core/FormControlLabel';
const useStyles = makeStyles((theme) => ({
root: {
height: 180,
},
container: {
display: 'flex',
},
paper: {
margin: theme.spacing(1),
},
svg: {
width: 100,
height: 100,
},
polygon: {
fill: theme.palette.common.white,
stroke: theme.palette.divider,
strokeWidth: 1,
},
}));
export default function SimpleCollapse() {
const classes = useStyles();
const [checked, setChecked] = React.useState(false);
const handleChange = () => {
setChecked((prev) => !prev);
};
return (
<div className={classes.root}>
<FormControlLabel
control={<Switch checked={checked} onChange={handleChange} />}
label="Show"
/>
<div className={classes.container}>
<Collapse in={checked}>
<Paper elevation={4} className={classes.paper}>
<svg className={classes.svg}>
<polygon points="0,100 50,00, 100,100" className={classes.polygon} />
</svg>
</Paper>
</Collapse>
<Collapse in={checked} collapsedHeight={40}>
<Paper elevation={4} className={classes.paper}>
<svg className={classes.svg}>
<polygon points="0,100 50,00, 100,100" className={classes.polygon} />
</svg>
</Paper>
</Collapse>
</div>
</div>
);
}
|
client/views/admin/settings/inputs/CodeSettingInput.js | VoiSmart/Rocket.Chat | import { Box, Button, Field, Flex } from '@rocket.chat/fuselage';
import { useToggle } from '@rocket.chat/fuselage-hooks';
import React from 'react';
import { useTranslation } from '../../../../contexts/TranslationContext';
import ResetSettingButton from '../ResetSettingButton';
import CodeMirror from './CodeMirror';
function CodeSettingInput({
_id,
label,
value = '',
code,
placeholder,
readonly,
autocomplete,
disabled,
hasResetButton,
onChangeValue,
onResetButtonClick,
}) {
const t = useTranslation();
const [fullScreen, toggleFullScreen] = useToggle(false);
const handleChange = (value) => {
onChangeValue(value);
};
return (
<>
<Flex.Container>
<Box>
<Field.Label htmlFor={_id} title={_id}>
{label}
</Field.Label>
{hasResetButton && (
<ResetSettingButton data-qa-reset-setting-id={_id} onClick={onResetButtonClick} />
)}
</Box>
</Flex.Container>
<div
className={[
'code-mirror-box',
fullScreen && 'code-mirror-box-fullscreen content-background-color',
]
.filter(Boolean)
.join(' ')}
>
<div className='title'>{label}</div>
<CodeMirror
data-qa-setting-id={_id}
id={_id}
mode={code}
value={value}
placeholder={placeholder}
disabled={disabled}
readOnly={readonly}
autoComplete={autocomplete === false ? 'off' : undefined}
onChange={handleChange}
/>
<div className='buttons'>
<Button primary onClick={() => toggleFullScreen()}>
{fullScreen ? t('Exit_Full_Screen') : t('Full_Screen')}
</Button>
</div>
</div>
</>
);
}
export default CodeSettingInput;
|
examples/counter/containers/CounterApp.js | wbecker/redux | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'redux/react';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';
@connect(state => ({
counter: state.counter
}))
export default class CounterApp extends Component {
render() {
const { counter, dispatch } = this.props;
return (
<Counter counter={counter}
{...bindActionCreators(CounterActions, dispatch)} />
);
}
}
|
src/Collapse.js | pivotal-cf/react-bootstrap | import React from 'react';
import Transition from 'react-overlays/lib/Transition';
import domUtils from './utils/domUtils';
import CustomPropTypes from './utils/CustomPropTypes';
import deprecationWarning from './utils/deprecationWarning';
import createChainedFunction from './utils/createChainedFunction';
let capitalize = str => str[0].toUpperCase() + str.substr(1);
// reading a dimension prop will cause the browser to recalculate,
// which will let our animations work
let triggerBrowserReflow = node => node.offsetHeight;
const MARGINS = {
height: ['marginTop', 'marginBottom'],
width: ['marginLeft', 'marginRight']
};
function getDimensionValue(dimension, elem){
let value = elem[`offset${capitalize(dimension)}`];
let margins = MARGINS[dimension];
return (value +
parseInt(domUtils.css(elem, margins[0]), 10) +
parseInt(domUtils.css(elem, margins[1]), 10)
);
}
class Collapse extends React.Component {
constructor(props, context){
super(props, context);
this.onEnterListener = this.handleEnter.bind(this);
this.onEnteringListener = this.handleEntering.bind(this);
this.onEnteredListener = this.handleEntered.bind(this);
this.onExitListener = this.handleExit.bind(this);
this.onExitingListener = this.handleExiting.bind(this);
}
render() {
let enter = createChainedFunction(this.onEnterListener, this.props.onEnter);
let entering = createChainedFunction(this.onEnteringListener, this.props.onEntering);
let entered = createChainedFunction(this.onEnteredListener, this.props.onEntered);
let exit = createChainedFunction(this.onExitListener, this.props.onExit);
let exiting = createChainedFunction(this.onExitingListener, this.props.onExiting);
return (
<Transition
ref='transition'
{...this.props}
aria-expanded={this.props.role ? this.props.in : null}
className={this._dimension() === 'width' ? 'width' : ''}
exitedClassName='collapse'
exitingClassName='collapsing'
enteredClassName='collapse in'
enteringClassName='collapsing'
onEnter={enter}
onEntering={entering}
onEntered={entered}
onExit={exit}
onExiting={exiting}
onExited={this.props.onExited}
>
{ this.props.children }
</Transition>
);
}
/* -- Expanding -- */
handleEnter(elem){
let dimension = this._dimension();
elem.style[dimension] = '0';
}
handleEntering(elem){
let dimension = this._dimension();
elem.style[dimension] = this._getScrollDimensionValue(elem, dimension);
}
handleEntered(elem){
let dimension = this._dimension();
elem.style[dimension] = null;
}
/* -- Collapsing -- */
handleExit(elem){
let dimension = this._dimension();
elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px';
}
handleExiting(elem){
let dimension = this._dimension();
triggerBrowserReflow(elem);
elem.style[dimension] = '0';
}
_dimension(){
return typeof this.props.dimension === 'function'
? this.props.dimension()
: this.props.dimension;
}
//for testing
_getTransitionInstance(){
return this.refs.transition;
}
_getScrollDimensionValue(elem, dimension){
return elem[`scroll${capitalize(dimension)}`] + 'px';
}
}
// Explicitly copied from Transition for doc generation.
// TODO: Remove duplication once #977 is resolved.
Collapse.propTypes = {
/**
* Show the component; triggers the expand or collapse animation
*/
in: React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is collapsed
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the expand animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the collapse animation in milliseconds, to ensure that
* finishing callbacks are fired even if the original browser transition end
* events are canceled
*/
timeout: React.PropTypes.number,
/**
* duration
* @private
*/
duration: CustomPropTypes.all([
React.PropTypes.number,
(props)=> {
if (props.duration != null){
deprecationWarning('Collapse `duration`', 'the `timeout` prop');
}
return null;
}
]),
/**
* Callback fired before the component expands
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the component starts to expand
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the component has expanded
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the component collapses
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the component starts to collapse
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the component has collapsed
*/
onExited: React.PropTypes.func,
/**
* The dimension used when collapsing, or a function that returns the
* dimension
*
* _Note: Bootstrap only partially supports 'width'!
* You will need to supply your own CSS animation for the `.width` CSS class._
*/
dimension: React.PropTypes.oneOfType([
React.PropTypes.oneOf(['height', 'width']),
React.PropTypes.func
]),
/**
* Function that returns the height or width of the animating DOM node
*
* Allows for providing some custom logic for how much the Collapse component
* should animate in its specified dimension. Called with the current
* dimension prop value and the DOM node.
*/
getDimensionValue: React.PropTypes.func,
/**
* ARIA role of collapsible element
*/
role: React.PropTypes.string
};
Collapse.defaultProps = {
in: false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false,
dimension: 'height',
getDimensionValue
};
export default Collapse;
|
example/examples/OnPoiClick.js | wannyk/react-native-maps | import React from 'react';
import { StyleSheet, View, Text, Dimensions } from 'react-native';
import MapView, { Callout, Marker, ProviderPropType } from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
class OnPoiClick extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
poi: null,
};
this.onPoiClick = this.onPoiClick.bind(this);
}
onPoiClick(e) {
const poi = e.nativeEvent;
this.setState({
poi,
});
}
render() {
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
initialRegion={this.state.region}
onPoiClick={this.onPoiClick}
>
{this.state.poi && (
<Marker coordinate={this.state.poi.coordinate}>
<Callout>
<View>
<Text>Place Id: {this.state.poi.placeId}</Text>
<Text>Name: {this.state.poi.name}</Text>
</View>
</Callout>
</Marker>
)}
</MapView>
</View>
);
}
}
OnPoiClick.propTypes = {
provider: ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
});
export default OnPoiClick;
|
frontend/src/components/Navigation/TooltipControlled.js | loicbaron/nutrition | import React from 'react';
import PropTypes from 'prop-types';
import Tooltip from '@mui/material/Tooltip';
import { Typography } from '@mui/material';
import { withStyles } from '@mui/styles';
import { anyNumberOfChildren } from '../miscellaneousProps';
export default function TooltipControlled({ children, title, text }) {
const [open, setOpen] = React.useState(true);
const handleClose = () => {
setOpen(false);
};
const handleOpen = () => {
setOpen(true);
};
const HtmlTooltip = withStyles((theme) => ({
tooltip: {
backgroundColor: '#f50057',
color: 'white',
maxWidth: 220,
fontSize: theme.typography.pxToRem(12),
border: '1px solid #dadde9',
},
}))(Tooltip);
return (
<HtmlTooltip
title={
<React.Fragment>
<Typography color="inherit">{title}</Typography>
{text}
</React.Fragment>
}
open={open}
onClose={handleClose}
onOpen={handleOpen}
arrow
>
{children}
</HtmlTooltip>
);
}
TooltipControlled.propTypes = {
children: anyNumberOfChildren.isRequired,
title: PropTypes.string.isRequired,
text: PropTypes.string,
};
TooltipControlled.defaultProps = {
text: null,
};
|
blueocean-material-icons/src/js/components/svg-icons/file/file-upload.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const FileFileUpload = (props) => (
<SvgIcon {...props}>
<path d="M9 16h6v-6h4l-7-7-7 7h4zm-4 2h14v2H5z"/>
</SvgIcon>
);
FileFileUpload.displayName = 'FileFileUpload';
FileFileUpload.muiName = 'SvgIcon';
export default FileFileUpload;
|
js/actions/JSCompileActions.js | Sable/McLab-Web | import AT from '../constants/AT';
import request from 'superagent';
import React from 'react';
import OnLoadActions from './OnLoadActions';
import FileExplorerActions from './FileExplorerActions';
import TerminalActions from './TerminalActions';
import Dispatcher from '../Dispatcher';
import FileContentsStore from '../stores/FileContentsStore';
import OpenFileStore from '../stores/OpenFileStore';
function sendCompilationRequest(){
const fileName = OpenFileStore.getFilePath();
const postBody = {fileName: fileName.substring(10)}; // workspace hack
const baseURL = window.location.origin;
const sessionID = OnLoadActions.getSessionID();
// POST request to compile the javascript and print to terminal based on the result
request.post(baseURL + '/compile/mcvmjs')
.set({'SessionID': sessionID})
.send(postBody)
.end((err, res) =>{
if(!err){
TerminalActions.println(
<div>
File {fileName} was successfully compiled to JavaScript.
</div>);
FileExplorerActions.fetchFileTree(sessionID);
}
else{
TerminalActions.printerrln(
<div>
McVM did not successfully compile the file {fileName}.
</div>
);
}
});
}
// Run the compiled Javascript in a webworker
function runCompiledJS(){
let filename = OpenFileStore.getFilePath();
let filenameWithoutPath = filename.split('/').slice(-1)[0]; // used later to print output more nicely
if(filename){
// Create blob with the contents of the open file
const contents = FileContentsStore.get(filename).text;
const finalContents = `console.log = function(text){ postMessage(JSON.stringify(text)); }\n\ntry {\n${contents}} \ncatch(err){\n postMessage({err: err.toString()});\n}`;
var blob = new Blob([
finalContents
]);
// Create a URL reference to the blob file and create/start the worker using this blob
var blobURL = window.URL.createObjectURL(blob);
var worker = new Worker(blobURL);
// On message from the worker, check if is in error or not and print correspondingly
worker.onmessage = (message) => {
let data = message.data;
if (typeof data === 'object' && 'err' in data){
TerminalActions.printerrln('Running ' + filenameWithoutPath + ' failed. The error was: ');
TerminalActions.printerrln(data.err);
}
else{
TerminalActions.println(filenameWithoutPath + ' output: ' + data);
}
};
}
}
const openPanel = function() {
Dispatcher.dispatch({
action: AT.JS_COMPILE_PANEL.OPEN_PANEL
});
};
export default{
sendCompilationRequest,
runCompiledJS,
openPanel
} |
src/components/common/HomePage.js | minaz912/book-store | import React from 'react';
const Home = () => {
return(
<div>
<h1>Home Page</h1>
<p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. A aliquam architecto at exercitationem ipsa iste molestiae nobis odit! Error quo reprehenderit velit! Aperiam eius non odio optio, perspiciatis suscipit vel?</p>
</div>
);
};
export default Home;
|
src/svg-icons/maps/person-pin-circle.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsPersonPinCircle = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm0 2c1.1 0 2 .9 2 2 0 1.11-.9 2-2 2s-2-.89-2-2c0-1.1.9-2 2-2zm0 10c-1.67 0-3.14-.85-4-2.15.02-1.32 2.67-2.05 4-2.05s3.98.73 4 2.05c-.86 1.3-2.33 2.15-4 2.15z"/>
</SvgIcon>
);
MapsPersonPinCircle = pure(MapsPersonPinCircle);
MapsPersonPinCircle.displayName = 'MapsPersonPinCircle';
MapsPersonPinCircle.muiName = 'SvgIcon';
export default MapsPersonPinCircle;
|
DemoApp/src/containers/root.js | andyfen/react-native-UIKit | import React, { Component } from 'react';
import {
StyleSheet,
View,
TabBarIOS,
StatusBar
} from 'react-native';
import NavigationBar from 'react-native-navbar';
import NewsFeed from './news-feed';
import ArticlesTab from './articles-tab';
import MessagesTab from './messages-tab';
import Profile from './profile';
import AllComponents from './all-components';
const base64Icon = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEsAAABLCAQAAACSR7JhAAADtUlEQVR4Ac3YA2Bj6QLH0XPT1Fzbtm29tW3btm3bfLZtv7e2ObZnms7d8Uw098tuetPzrxv8wiISrtVudrG2JXQZ4VOv+qUfmqCGGl1mqLhoA52oZlb0mrjsnhKpgeUNEs91Z0pd1kvihA3ULGVHiQO2narKSHKkEMulm9VgUyE60s1aWoMQUbpZOWE+kaqs4eLEjdIlZTcFZB0ndc1+lhB1lZrIuk5P2aib1NBpZaL+JaOGIt0ls47SKzLC7CqrlGF6RZ09HGoNy1lYl2aRSWL5GuzqWU1KafRdoRp0iOQEiDzgZPnG6DbldcomadViflnl/cL93tOoVbsOLVM2jylvdWjXolWX1hmfZbGR/wjypDjFLSZIRov09BgYmtUqPQPlQrPapecLgTIy0jMgPKtTeob2zWtrGH3xvjUkPCtNg/tm1rjwrMa+mdUkPd3hWbH0jArPGiU9ufCsNNWFZ40wpwn+62/66R2RUtoso1OB34tnLOcy7YB1fUdc9e0q3yru8PGM773vXsuZ5YIZX+5xmHwHGVvlrGPN6ZSiP1smOsMMde40wKv2VmwPPVXNut4sVpUreZiLBHi0qln/VQeI/LTMYXpsJtFiclUN+5HVZazim+Ky+7sAvxWnvjXrJFneVtLWLyPJu9K3cXLWeOlbMTlrIelbMDlrLenrjEQOtIF+fuI9xRp9ZBFp6+b6WT8RrxEpdK64BuvHgDk+vUy+b5hYk6zfyfs051gRoNO1usU12WWRWL73/MMEy9pMi9qIrR4ZpV16Rrvduxazmy1FSvuFXRkqTnE7m2kdb5U8xGjLw/spRr1uTov4uOgQE+0N/DvFrG/Jt7i/FzwxbA9kDanhf2w+t4V97G8lrT7wc08aA2QNUkuTfW/KimT01wdlfK4yEw030VfT0RtZbzjeMprNq8m8tnSTASrTLti64oBNdpmMQm0eEwvfPwRbUBywG5TzjPCsdwk3IeAXjQblLCoXnDVeoAz6SfJNk5TTzytCNZk/POtTSV40NwOFWzw86wNJRpubpXsn60NJFlHeqlYRbslqZm2jnEZ3qcSKgm0kTli3zZVS7y/iivZTweYXJ26Y+RTbV1zh3hYkgyFGSTKPfRVbRqWWVReaxYeSLarYv1Qqsmh1s95S7G+eEWK0f3jYKTbV6bOwepjfhtafsvUsqrQvrGC8YhmnO9cSCk3yuY984F1vesdHYhWJ5FvASlacshUsajFt2mUM9pqzvKGcyNJW0arTKN1GGGzQlH0tXwLDgQTurS8eIQAAAABJRU5ErkJggg==';
const messages = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAAAG7AAABuwE67OPiAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAVNQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA34LqhQAAAHB0Uk5TAAEDBQgJCgsOERIUFRYXHB4hJygrLjA5PUBDREhJS01PUltfYGJkZWZnbW5ydHZ3eHp9foCJjI2PkJGSk5SVlpeYmp+gpaepqqusrbGytLe4vMHFy8zO0NHT1NXX2Nnb3d7g4eXn6u/w8fP1+fr9/iBpASwAAAHESURBVFjD7ZZnU8JAEIYPpAgiCho7KpZYwRYVAcESQVGxoIJiw4og5f9/MpuENk5y3OE4jsP7aWfnnmfmcsuwCP1IGDbAEyY4xZRxc6hIlXCbzD8XKfNiEQWhInX2xfsXGwh8BxaKzAZHGF8GOFYQBKDwkb/cOnABoeCh4MgFi8DxTcFfFTD9imHqEDBxtdGNM1gBrz78PFaQUBcksAKXusCFFejY2J1iYqyuOYlNQV0CE5dKKybFmbACTn2UOawgqS5IYgWb6gI/VmCL5pXxfNRWxytYuxRjbU7ivxX4oNghFwRLq9EEFLnDbTH+MW3VGcvcruKmepwDblw4Za+d1u0KP/KBXfPscG6rpvWuKfFLeSwv3dx4XdOUF2BDGL9m3rZKZ/WeQqWZlXqdV1i84DWUb9s+5BaWzwi0b8RG35u8DyhuqgsO67eHmQfkCKqZnMQfGIleVlx6PQi1yJ+1sKwhG41ToGaR5VziM6Oks/UA2HDPk8Q/dpPyWvHiK1mJPzMTD7et+o28WvJfx0AF/5xEFJku86+9NDxaLfEXHVQ8isj8no6OR5fSn48b0eYE+LSDmkdO4fd/b0cNZHDNqUe/ni+rzlTP4cWlVQAAAABJRU5ErkJggg==';
const news = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABABAMAAABYR2ztAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAAAG7AAABuwE67OPiAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAACFQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA3XBkVwAAAAp0Uk5TAAEaH2Wns7/m8PZU7q8AAABZSURBVEjHY2AYBWCwCg+gnwLcrhsMCsAOpZMC7IFEXwWDKxwQ7IFUQNCRdFAwGg4oTqO7Apom+xWEFCxj6FqFFyxhiMKvoJDBEq/8cgUG5gg88m2ODKMAAgDSxVncwQhqHgAAAABJRU5ErkJggg==';
const profile = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAAAH6AAAB+gEXikRvAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAQtQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA17MN4QAAAFh0Uk5TAAECBQkLDA0OEBUYGiAjJSYoKi0vMjg6PkFLTlVWWl9iaGxveXyEhpWWnqKlpqeora6vsLG1usLDxsfJzM3O1NXY2tzd3uLj5ujq7e/w8fLz9fb4+fz9/m7JgK8AAAGgSURBVBgZtcEJNwJhFAbglyikkm1QIUuW7EtokTUkWeP9/7+E4zjOjJk7c7/meB7g/8Sn5wsb5fJGYX46DnMjxQ5/dYojMJPcfKfD+2YSBhK3dLlNQG3ogh4uhqDUU6GnSg90ZiiYgU6JghJU0hSloZGnKA+NNYrWoHFM0TE0GhQ1oNGkqAmNR4oeodGmqA2NS4ouoXFC0Qk09inah0aZojIUMvSRQbBT+jhFsBv6uEGwK/q4QrAqfVQRbIE+FhAs2qaoHYVC5oGChwxUInV6qkegtEJPK9Cy6MmCVm+THpq9UFulh1XoxZ/o8hSHgWW6LMNEX4N/NPpgxHqjw5sFQ3k65GFsnTbrMDdHmzmYW6LNEsxt0WYLxgZbtGkNwkx/7owOZ7l+qMVmd1/o8rI7G4PG1MErBa8HUwgyWaKv0iT8TBwy0OEEJGN7VNkbg5fh7Q8qfWwPwyV7TwP3WTgNFGmoOACb1DWNXafwa/yOXbgbxw+rxa60LHwbfWaXnkfxJVJj12oRAAWGUADSHYbQSWORoSxih6Hs4Og8lCOE9QnnxX9VGgkyFQAAAABJRU5ErkJggg==';
const bars = 'data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAEAAAABACAMAAACdt4HsAAAAA3NCSVQICAjb4U/gAAAACXBIWXMAAAbeAAAG3gG6t8riAAAAGXRFWHRTb2Z0d2FyZQB3d3cuaW5rc2NhcGUub3Jnm+48GgAAAIRQTFRF////AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAvSgy4QAAACt0Uk5TAAMFBggLDhAVGystMzg6O0JESVFUWV1gcIGHio6ZnZ+w1tvg6u7x9PX4+wIY4ZgAAAB/SURBVBgZ7cEHAoJADATAjYIFO1ZExXa2/P9/viDJPWBnQERkknpvqgUhuanj3kdkqa41IsOPOn5jhKbnq+kyB1EmKUyCDE1SUzoiVKlrhkilrgVCTVLT64QMUpgERJmqtjO1E4QGb3V8R4is1LVBpPdQx7NEqNgeTLsSRESWP5FzP3mQfaekAAAAAElFTkSuQmCC';
const primary = '#3E364D';
export default class Root extends Component {
constructor(props) {
super(props);
this.state = {
selectedTab: 'newsFeed',
// selectedTab: 'allTab',
};
StatusBar.setBarStyle('light-content');
}
render() {
const rightButtonConfig = {
title: 'Next',
handler: () => console.log('hello!'),
tintColor: '#fff',
};
const titleConfig = {
title: 'UIKit',
tintColor: '#fff',
};
return (
<View style={styles.container}>
<NavigationBar
tintColor={primary}
title={titleConfig}
rightButton={rightButtonConfig}
/>
<TabBarIOS
translucent={false}
tintColor={primary}
barTintColor="#fff"
>
<TabBarIOS.Item
title="News Feed"
icon={{uri: news, scale: 3}}
selected={this.state.selectedTab === 'newsFeed'}
onPress={() => {
this.setState({
selectedTab: 'newsFeed',
});
}}
>
<NewsFeed/>
</TabBarIOS.Item>
<TabBarIOS.Item
icon={{ uri: messages, scale: 3 }}
badge={this.state.notifCount > 0 ? this.state.notifCount : undefined}
selected={this.state.selectedTab === 'redTab'}
title="Messages"
onPress={() => {
this.setState({
selectedTab: 'redTab'
});
}}
>
<MessagesTab />
</TabBarIOS.Item>
<TabBarIOS.Item
icon={{ uri: profile, scale: 3 }}
title="Profile"
selected={this.state.selectedTab === 'greenTab'}
onPress={() => {
this.setState({
selectedTab: 'greenTab',
});
}}
>
<Profile />
</TabBarIOS.Item>
<TabBarIOS.Item
icon={{ uri: bars, scale: 3 }}
title="Articles"
selected={this.state.selectedTab === 'articlesTab'}
onPress={() => {
this.setState({
selectedTab: 'articlesTab',
});
}}
>
<ArticlesTab />
</TabBarIOS.Item>
<TabBarIOS.Item
icon={{ uri: bars, scale: 3 }}
title="All Components"
selected={this.state.selectedTab === 'allTab'}
onPress={() => {
this.setState({
selectedTab: 'allTab',
});
}}
>
<AllComponents />
</TabBarIOS.Item>
</TabBarIOS>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
|
components/question/PendingQuestionsList.js | hustlzp/react-redux-example | import React from 'react'
import Radium from 'radium'
import { Link } from 'react-router'
import { friendlyTimeWithLineBreak, truncate } from '../../filters'
@Radium
export default class PendingQuestionsList extends React.Component {
static propTypes = {
questions: React.PropTypes.array.isRequired,
deleteQuestion: React.PropTypes.func.isRequired,
openUpdateQuestionModal: React.PropTypes.func.isRequired,
openQuestionDetailsModal: React.PropTypes.func.isRequired,
}
render() {
const { questions, deleteQuestion, openUpdateQuestionModal, openQuestionDetailsModal } = this.props
const rows = questions.map(question => {
const asker = question.get('asker')
return (
<tr key={question.id}>
<td style={styles.titleCell}>
<strong>
{asker ? (<Link to={`/user/${asker.id}`}>{asker.get('name')}</Link>) : "游客"}
</strong>
:
{question.get('title')}
</td>
<td style={styles.draftCell}>
{question.get('drafted') ? truncate(question.get('draft'), 60) : null}
</td>
<td>{friendlyTimeWithLineBreak(question.createdAt)}</td>
<td>
<div className="btn-group btn-group-sm">
<button type="button" className="btn btn-default"
onClick={() => openUpdateQuestionModal(question)}>编辑
</button>
<button type="button" className="btn btn-default"
onClick={() => deleteQuestion(question)}>删除
</button>
<button type="button" className="btn btn-default"
onClick={() => openQuestionDetailsModal(question)}>详情
</button>
</div>
</td>
</tr>
)
})
return (
<table className="table table-hover">
<thead>
<tr>
<th>问题</th>
<th>草稿</th>
<th>提问于</th>
<th>操作</th>
</tr>
</thead>
<tbody>{rows}</tbody>
</table>
)
}
}
const styles = {
titleCell: {
maxWidth: '200px'
},
draftCell: {
maxWidth: '200px'
}
}
|
src/App.js | SimoNonnis/react-long-form | // @flow
import React, { Component } from 'react';
import TagsDemo from './Tags/demo.js';
import styled from 'styled-components';
import './app.css';
const options1 = ['orange', 'banana', 'mango', 'pear'];
const options2 = ['dog', 'tiger', 'cat'];
const names = ['fruits', 'animals'];
// App component
export default class App extends Component {
render() {
return (
<StyledForm />
);
}
}
// Form component
class Form extends Component {
constructor(props) {
super(props)
this.state = {
data: {},
completedFields: [],
missingFields: [],
isValid: false
}
this.onFormSubmit = this.onFormSubmit.bind(this);
this.onSelection = this.onSelection.bind(this);
}
onFormSubmit(event) {
event.preventDefault();
const { completedFields } = this.state;
const namesSet = new Set(names);
const completedFieldsSet = new Set(completedFields);
const notCompletedSections = new Set(
[...namesSet].filter(x => !completedFieldsSet.has(x))
);
this.setState({
missingFields: [...notCompletedSections]
})
if (notCompletedSections.size === 0) {
this.setState({
isValid: true,
missingFields: []
})
console.log('ALL GOOD, FORM SUBMITTED!');
}
}
onSelection(event) {
const { name, value } = event.target;
let { data, completedFields } = this.state;
data[name] = value;
if (!completedFields.includes(name)) {
completedFields.push(name);
}
this.setState({
data: data,
completedFields: completedFields,
missingFields: []
})
}
render() {
const { missingFields } = this.state;
const { className } = this.props;
return (
<form className={className} onSubmit={this.onFormSubmit}>
<h1>React Long Form</h1>
<RadioGroup
optionsAvailable={options1}
name={names[0]}
onSelection={this.onSelection}
missingFields={missingFields}
/>
<RadioGroup
optionsAvailable={options2}
name={names[1]}
onSelection={this.onSelection}
missingFields={missingFields}
/>
<TagsDemo />
<button >Save</button>
</form>
)
}
}
const StyledForm = styled(Form)`
color: tomato;
`;
// RadioGroup1 component
class RadioGroup extends Component {
constructor(props) {
super(props);
this.state = {
isEmpty: null
}
this.handleChange = this.handleChange.bind(this);
}
componentWillReceiveProps({ missingFields, name }) {
if ([...missingFields].includes(name)) {
this.setState({
isEmpty: true
})
}
}
handleChange (event) {
this.setState({
isEmpty: false
})
this.props.onSelection(event);
}
render() {
const { optionsAvailable, name } = this.props;
const { isEmpty } = this.state;
const optionsGroup = optionsAvailable.map((option, i) => {
return (
<div key={i} >
<input
type="radio"
name={name}
value={option}
onChange={this.handleChange}
/>
<label>{option}</label>
</div>
)
});
return (
<div className="section" >
{optionsGroup}
{isEmpty && <p className="isEmpty" >Please, choose an option</p>}
</div>
)
}
}
|
src/App.js | dixitc/cherry-web-portal | import React, { Component } from 'react';
import SmartMessage from './components/components';
import { Link } from 'react-router';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MyRawTheme from './Themes/cherryTheme';
import Snackbar from 'material-ui/Snackbar';
import Footer from './components/Footer';
import backGroundImg from './images/geometry2.png';
/*
NOTES :
-can enable app wide theme here
*/
export default class App extends Component {
getChildContext () {
return { muiTheme: getMuiTheme(MyRawTheme),};
}
render() {
//console.log(this.props);
return (
<div style={{height:'100%',width:'100%'}}>
{this.props.children}
<Footer>
</Footer>
</div>
);
}
componentDidMount() {
console.log('App initialized. (App component mounted , do some fetching data)');
}
}
App.childContextTypes = {
muiTheme: React.PropTypes.object
};
|
src/containers/NotFound/NotFound.js | fforres/coworks | import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
src/containers/ProfileListFilters.js | JustPeople/app | import React from 'react'
import { connect } from 'react-redux'
import { Menu } from 'antd'
import * as API from '../api'
import Text from './Text'
import NameFilter from './ProfileListFilters/NameFilter'
import GenderFilter from './ProfileListFilters/GenderFilter'
import LocationSelector from './ProfileListFilters/LocationSelector'
function makeLocationFilter(locationId) {
return connect(state => {
var location = (state.data.locations || []).find(l => l.id === locationId) || {}
return { name: location.name }
}, dispatch => ({
async onClick() {
var ids = [locationId];
var children = []
for (var i in ids) {
var id = ids[i]
children = children.concat(await API.getChildLocations(id))
}
var locations = ids.concat(children).filter((e, i, arr) => arr.indexOf(e) === i).sort()
return dispatch({
type: 'FILTERS/SET',
payload: {
locations
}
})
}
}))(props => <span {...props} children={props.name} />)
}
var LocationSubMenu = connect((state, ownProps) => {
var children = (state.data.locations || [])
.filter(l => l.LocationId === ownProps.id)
.sort((l1, l2) => l1.name.localeCompare(l2.name))
.map(l => l.id)
return { children }
})(props => {
var Filter = makeLocationFilter(props.id)
if (!props.children.length) {
return (
<Menu>
<Menu.Item children={<Filter />} />
</Menu>
)
}
return (
<Menu>
<Menu.SubMenu title={<Filter />}>
{props.children.map(id => <LocationSubMenu key={id} id={id} />)}
</Menu.SubMenu>
</Menu>
)
})
var Filters = props => {
return (
<Menu>
<Menu.ItemGroup title={<Text code="MENU_FILTER_TITLE_NAME" />}>
<Menu.Item>
<NameFilter />
</Menu.Item>
</Menu.ItemGroup>
<Menu.ItemGroup title={<Text code="MENU_FILTER_TITLE_GENDER" />}>
<Menu.Item>
<GenderFilter />
</Menu.Item>
</Menu.ItemGroup>
<Menu.ItemGroup title={<Text code="MENU_FILTER_TITLE_LOCATION" />}>
<div style={{ padding: '0.5rem' }}>
<LocationSelector />
</div>
<LocationSubMenu id={2} />
<LocationSubMenu id={6} />
</Menu.ItemGroup>
</Menu>
)
}
export default connect()(Filters)
|
src/v2/components/UI/ModalDialog/index.js | aredotna/ervell | import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { width, height, maxHeight, maxWidth } from 'styled-system'
import { preset } from 'v2/styles/functions'
import constants from 'v2/styles/constants'
const Dialog = styled.div`
display: flex;
box-sizing: border-box;
padding: 5px; // Fake border
overflow: hidden;
border-radius: 0.25em;
background-color: ${x => x.theme.colors.gray.semiLight};
${preset(width, { width: '90%' })}
${preset(height, { height: '90%' })}
${preset(maxWidth, { maxWidth: '40em' })}
${preset(maxHeight, { maxHeight: '60em' })}
${constants.media.mobile`
width: 95%;
height: 95%;
max-width: 100%;
max-height: 100%;
border-radius: 0;
padding: 0;
`}
`
const Content = styled.div`
box-sizing: border-box;
display: flex;
flex-direction: column;
flex-grow: 1;
overflow-y: auto;
-webkit-overflow-scrolling: touch;
background-color: ${props => props.theme.colors.background};
border: 1px solid ${x => x.theme.colors.gray.regular};
`
const ModalDialog = ({ children, ...rest }) => (
<Dialog {...rest}>
<Content>{children}</Content>
</Dialog>
)
ModalDialog.propTypes = {
children: PropTypes.node.isRequired,
}
export default ModalDialog
|
app/modules/pages/components/NotFoundPage/index.js | anton-drobot/frontend-starter | import React, { Component } from 'react';
import { observer } from 'mobx-react';
import { Helmet } from 'react-helmet';
import { bem } from 'app/libs/bem';
import DefaultLayout from 'app/modules/layout/components/DefaultLayout';
const b = bem('NotFoundPage');
@observer
export default class NotFoundPage extends Component {
render() {
return (
<DefaultLayout>
<Helmet>
<title>404 — Page Not Found</title>
</Helmet>
<section className={b()}>
Not Found — 404
</section>
</DefaultLayout>
);
}
}
|
packages/ndla-icons/src/editor/Paragraph.js | netliferesearch/frontend-packages | /**
* Copyright (c) 2017-present, NDLA.
*
* This source code is licensed under the GPLv3 license found in the
* LICENSE file in the root directory of this source tree.
*
*/
// N.B! AUTOGENERATED FILE. DO NOT EDIT
import React from 'react';
import Icon from '../Icon';
const Paragraph = props => (
<Icon
viewBox="0 0 27 4"
data-license="CC-BY 4.0"
data-source="Knowit"
{...props}>
<g>
<path
fillRule="evenodd"
d="M1.929 3.408c.612 0 1.224-.476 1.224-1.292 0-.884-.612-1.36-1.224-1.36S.705 1.232.705 2.116c0 .816.612 1.292 1.224 1.292zm11.492 0c.612 0 1.224-.476 1.224-1.292 0-.884-.612-1.36-1.224-1.36s-1.224.476-1.224 1.36c0 .816.612 1.292 1.224 1.292zm11.492 0c.612 0 1.224-.476 1.224-1.292 0-.884-.612-1.36-1.224-1.36s-1.224.476-1.224 1.36c0 .816.612 1.292 1.224 1.292z"
/>
</g>
</Icon>
);
export default Paragraph;
|
app/components/square_grid.js | AlienStream/experimental-frontend | import React from 'react';
import SquareItem from './square_item'
class SquareGrid extends React.Component {
render() {
var items = this.props.items;
var squareItems = items.map(function(item, key) {
return (
<SquareItem
key={key}
{...item}
/>
);
});
return (
<section className="vbox square-grid">
<section className="scrollable padder-lg">
<h2 className="font-thin m-b">{this.props.title}</h2>
<div className="row row-sm">
{squareItems}
</div>
</section>
</section>
);
}
}
export default SquareGrid
|
src/containers/Marketing/Marketing.js | kingpowerclick/kpc-web-backend | import React, { Component } from 'react';
import classNames from 'classnames';
import { FilterPage,
FilterActionSelect,
FilterId,
MarketingCampaign,
} from 'components';
import { Tabs, Tab } from 'react-bootstrap';
export default class Marketing extends Component {
render() {
const styles = require('./marketing.scss');
return (
<div className="container-fluid">
<div className="row">
<div className={ classNames(styles['product-view']) }>
<header className={ styles['page-header']}>
<div className={ styles['page-title']}>
<h1 className={ styles.header }><strong>Marketing</strong></h1>
<div className={ styles['page-breadcrumb']}>
<span>Marketing</span>
</div>
</div>
<div className={ styles['page-filter']}>
<ul className={ styles['list-filter']}>
<li className={ classNames( styles.filter, styles['add-product'])}>
<div className="dropdown">
<button className={ classNames(styles['btn-blue'], 'btn', 'btn-default', 'dropdown-toggle')} type="button" id="dropdownMenu1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="true">
Add Products
<span className="caret"></span>
</button>
<ul className="dropdown-menu" aria-labelledby="dropdownMenu1">
<li><a href="#">Action</a></li>
<li><a href="#">Another action</a></li>
<li><a href="#">Something else here</a></li>
<li role="separator" className="divider"></li>
<li><a href="#">Separated link</a></li>
</ul>
</div>
</li>
</ul>
</div>
</header>
<section className={ styles['wrapper-content']}>
<Tabs defaultActiveKey={1} id="uncontrolled-tab-example">
<Tab eventKey={1} title="Campaign">
<div className={ styles.content}>
<div className={ classNames(styles['filter-product'])}>
<div className={ classNames(styles['wrapper-filter'])}>
<div className={ styles['filter-left']}>
<FilterActionSelect title={ "Action" } selectOption={ ['Active', 'In-Active'] }/>
<FilterId title={ "Product ID" } selectOption={ ['Name', 'Promo code', 'Status(Active)', 'Status(In-Active)'] }/>
</div>
<div className={ classNames(styles['filter-right']) }>
<FilterPage/>
</div>
</div>
</div>
<div className={ styles['table-detail'] }>
<MarketingCampaign/>
<div className="row">
<div className={ classNames(styles['filter-bottom'])}>
<FilterPage/>
</div>
</div>
</div>
</div>
</Tab>
<Tab eventKey={2} title="Cart Rule">
<div className={ styles.content}>
<div className={ classNames(styles['filter-product'])}>
<div className={ classNames(styles['wrapper-filter'])}>
<div className={ styles['filter-left']}>
<FilterActionSelect title={ "Action" } selectOption={ ['Delete Product'] }/>
<FilterId title={ "Product ID" } selectOption={ ['Product ID', 'SKU No.', 'Product Name', 'Brandname', 'Batch No.'] }/>
</div>
<div className={ classNames(styles['filter-right']) }>
<FilterPage/>
</div>
</div>
</div>
<div className={ styles['table-detail'] }>
<MarketingCampaign/>
<div className="row">
<div className={ classNames(styles['filter-bottom'])}>
<FilterPage/>
</div>
</div>
</div>
</div>
</Tab>
<Tab eventKey={3} title="GWP Global">
<div className={ styles.content}>
<div className={ classNames(styles['filter-product'])}>
<div className={ classNames(styles['wrapper-filter'])}>
<div className={ styles['filter-left']}>
<FilterActionSelect title={ "Action" } selectOption={ ['Delete Product'] }/>
<FilterId title={ "Product ID" } selectOption={ ['Product ID', 'SKU No.', 'Product Name', 'Brandname', 'Batch No.'] }/>
</div>
<div className={ classNames(styles['filter-right']) }>
<FilterPage/>
</div>
</div>
</div>
<div className={ styles['table-detail'] }>
<MarketingCampaign/>
<div className="row">
<div className={ classNames(styles['filter-bottom'])}>
<FilterPage/>
</div>
</div>
</div>
</div>
</Tab>
<Tab eventKey={4} title="Shipping Global">
<div className={ styles.content}>
<div className={ classNames(styles['filter-product'])}>
<div className={ classNames(styles['wrapper-filter'])}>
<div className={ styles['filter-left']}>
<FilterActionSelect title={ "Action" } selectOption={ ['Delete Product'] }/>
<FilterId title={ "Product ID" } selectOption={ ['Product ID', 'SKU No.', 'Product Name', 'Brandname', 'Batch No.'] }/>
</div>
<div className={ classNames(styles['filter-right']) }>
<FilterPage/>
</div>
</div>
</div>
<div className={ styles['table-detail'] }>
<MarketingCampaign/>
<div className="row">
<div className={ classNames(styles['filter-bottom'])}>
<FilterPage/>
</div>
</div>
</div>
</div>
</Tab>
</Tabs>
</section>
</div>
</div>
</div>
);
}
}
|
src/routes/charts/lineChart/index.js | liufulin90/react-admin | import React from 'react'
import PropTypes from 'prop-types'
import { Row, Col, Card, Button } from 'antd'
import Container from '../Container'
import {
LineChart,
Line,
XAxis,
YAxis,
CartesianGrid,
Tooltip,
Legend,
} from 'recharts'
const data = [
{
name: 'Page A',
uv: 4000,
pv: 2400,
amt: 2400,
}, {
name: 'Page B',
uv: 3000,
pv: 1398,
amt: 2210,
}, {
name: 'Page C',
uv: 2000,
pv: 9800,
amt: 2290,
}, {
name: 'Page D',
uv: 2780,
pv: 3908,
amt: 2000,
}, {
name: 'Page E',
uv: 1890,
pv: 4800,
amt: 2181,
}, {
name: 'Page F',
uv: 2390,
pv: 3800,
amt: 2500,
}, {
name: 'Page G',
uv: 3490,
pv: 4300,
amt: 2100,
},
]
const colProps = {
lg: 12,
md: 24,
}
const SimpleLineChart = () => (
<Container>
<LineChart data={data} margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="pv" stroke="#8884d8" activeDot={{
r: 8,
}} />
<Line type="monotone" dataKey="uv" stroke="#82ca9d" />
</LineChart>
</Container>
)
const VerticalLineChart = () => (
<Container>
<LineChart layout="vertical" width={600} height={300} data={data} margin={{
top: 20,
right: 30,
left: 20,
bottom: 5,
}}>
<XAxis type="number" />
<YAxis dataKey="name" type="category" />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line dataKey="pv" stroke="#8884d8" />
<Line dataKey="uv" stroke="#82ca9d" />
</LineChart>
</Container>
)
const DashedLineChart = () => (
<Container>
<LineChart width={600} height={300} data={data} margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="pv" stroke="#8884d8" strokeDasharray="5 5" />
<Line type="monotone" dataKey="uv" stroke="#82ca9d" strokeDasharray="3 4 5 2" />
</LineChart>
</Container>
)
// CustomizedDotLineChart
const CustomizedDot = ({ cx, cy, payload }) => {
if (payload.value > 2500) {
return (
<svg x={cx - 10} y={cy - 10} width={20} height={20} fill="red" viewBox="0 0 1024 1024">
<path d="M512 1009.984c-274.912 0-497.76-222.848-497.76-497.76s222.848-497.76 497.76-497.76c274.912 0 497.76 222.848 497.76 497.76s-222.848 497.76-497.76 497.76zM340.768 295.936c-39.488 0-71.52 32.8-71.52 73.248s32.032 73.248 71.52 73.248c39.488 0 71.52-32.8 71.52-73.248s-32.032-73.248-71.52-73.248zM686.176 296.704c-39.488 0-71.52 32.8-71.52 73.248s32.032 73.248 71.52 73.248c39.488 0 71.52-32.8 71.52-73.248s-32.032-73.248-71.52-73.248zM772.928 555.392c-18.752-8.864-40.928-0.576-49.632 18.528-40.224 88.576-120.256 143.552-208.832 143.552-85.952 0-164.864-52.64-205.952-137.376-9.184-18.912-31.648-26.592-50.08-17.28-18.464 9.408-21.216 21.472-15.936 32.64 52.8 111.424 155.232 186.784 269.76 186.784 117.984 0 217.12-70.944 269.76-186.784 8.672-19.136 9.568-31.2-9.12-40.096z" />
</svg>
)
}
return (
<svg x={cx - 10} y={cy - 10} width={20} height={20} fill="green" viewBox="0 0 1024 1024">
<path d="M517.12 53.248q95.232 0 179.2 36.352t145.92 98.304 98.304 145.92 36.352 179.2-36.352 179.2-98.304 145.92-145.92 98.304-179.2 36.352-179.2-36.352-145.92-98.304-98.304-145.92-36.352-179.2 36.352-179.2 98.304-145.92 145.92-98.304 179.2-36.352zM663.552 261.12q-15.36 0-28.16 6.656t-23.04 18.432-15.872 27.648-5.632 33.28q0 35.84 21.504 61.44t51.2 25.6 51.2-25.6 21.504-61.44q0-17.408-5.632-33.28t-15.872-27.648-23.04-18.432-28.16-6.656zM373.76 261.12q-29.696 0-50.688 25.088t-20.992 60.928 20.992 61.44 50.688 25.6 50.176-25.6 20.48-61.44-20.48-60.928-50.176-25.088zM520.192 602.112q-51.2 0-97.28 9.728t-82.944 27.648-62.464 41.472-35.84 51.2q-1.024 1.024-1.024 2.048-1.024 3.072-1.024 8.704t2.56 11.776 7.168 11.264 12.8 6.144q25.6-27.648 62.464-50.176 31.744-19.456 79.36-35.328t114.176-15.872q67.584 0 116.736 15.872t81.92 35.328q37.888 22.528 63.488 50.176 17.408-5.12 19.968-18.944t0.512-18.944-3.072-7.168-1.024-3.072q-26.624-55.296-100.352-88.576t-176.128-33.28z" />
</svg>
)
}
CustomizedDot.propTypes = {
cx: PropTypes.number,
cy: PropTypes.number,
payload: PropTypes.object,
}
const CustomizedDotLineChart = () => (
<Container>
<LineChart width={600} height={300} data={data} margin={{
top: 5,
right: 30,
left: 20,
bottom: 5,
}}>
<XAxis dataKey="name" />
<YAxis />
<CartesianGrid strokeDasharray="3 3" />
<Tooltip />
<Legend />
<Line type="monotone" dataKey="pv" stroke="#8884d8" dot={< CustomizedDot />} />
<Line type="monotone" dataKey="uv" stroke="#82ca9d" />
</LineChart>
</Container>
)
const EditorPage = () => (
<div className="content-inner">
<Row gutter={32}>
<Col {...colProps}>
<Card title="SimpleLineChart">
<SimpleLineChart />
</Card>
</Col>
<Col {...colProps}>
<Card title="DashedLineChart">
<DashedLineChart />
</Card>
</Col>
<Col {...colProps}>
<Card title="CustomizedDotLineChart">
<CustomizedDotLineChart />
</Card>
</Col>
<Col {...colProps}>
<Card title="VerticalLineChart">
<VerticalLineChart />
</Card>
</Col>
</Row>
</div>
)
export default EditorPage
|
src/js/components/icons/base/UserFemale.js | kylebyerly-hp/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-user-female`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'user-female');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M20,24 L20,19 C19.9999999,15 15.9403581,14 15,14 C18.9475,14 20,12 20,12 C20,12 16.942739,10.031 17,6 C16.942739,3 14.8497684,1 12,1 C9.01190309,1 6.91893246,3 7,6 C6.91893246,9.969 4,12 4,12 C4,12 4.91417116,14 9,14 C7.92131306,14 4,15 4,19 L4,24 M16,19 L16,24 M8,19 L8,24"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'UserFemale';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
RNApp/app/config/routes.js | spencercarli/react-native-meteor-boilerplate | /* eslint-disable react/prop-types */
import React from 'react';
import { Image } from 'react-native';
import { StackNavigator, TabNavigator } from 'react-navigation';
import Home from '../screens/Home';
import Details from '../screens/Details';
import Profile from '../screens/Profile';
import SignIn from '../screens/SignIn';
import homeIcon from '../images/home-icon.png';
import profileIcon from '../images/user-icon.png';
export const AuthStack = StackNavigator({
SignIn: {
screen: SignIn,
},
}, {
headerMode: 'none',
});
export const HomeStack = StackNavigator({
Home: {
screen: Home,
navigationOptions: {
headerTitle: 'Home',
},
},
Details: {
screen: Details,
navigationOptions: {
headerTitle: 'Details',
},
},
});
export const ProfileStack = StackNavigator({
Profile: {
screen: Profile,
},
}, {
headerMode: 'none',
});
const styles = {
icon: {
height: 30,
width: 30,
},
};
export const Tabs = TabNavigator({
Home: {
screen: HomeStack,
navigationOptions: {
tabBarLabel: 'Home',
tabBarIcon: ({ tintColor }) => (
<Image
style={[styles.icon, { tintColor }]}
source={homeIcon}
/>
),
},
},
Profile: {
screen: ProfileStack,
navigationOptions: {
tabBarLabel: 'Profile',
tabBarIcon: ({ tintColor }) => (
<Image
style={[styles.icon, { tintColor }]}
source={profileIcon}
/>
),
},
},
});
|
client/src/components/rowMenu.js | ungs-pp1g2/delix | import React from 'react';
import IconButton from 'material-ui/IconButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
const RowMenu = (editFunc, deleteFunc) => (
<IconMenu
iconButtonElement={
<IconButton
touch
tooltip="Opciones"
tooltipPosition="bottom-left"
>
<MoreVertIcon />
</IconButton>
}
>
<MenuItem onTouchTap={editFunc}>Edit</MenuItem>
<MenuItem onTouchTap={deleteFunc}>Delete</MenuItem>
</IconMenu>
);
export default RowMenu;
|
react/features/remote-video-menu/components/web/VolumeSlider.js | bgrozev/jitsi-meet | /* @flow */
import React, { Component } from 'react';
import { Icon, IconVolume } from '../../../base/icons';
/**
* Used to modify initialValue, which is expected to be a decimal value between
* 0 and 1, and converts it to a number representable by an input slider, which
* recognizes whole numbers.
*/
const VOLUME_SLIDER_SCALE = 100;
/**
* The type of the React {@code Component} props of {@link VolumeSlider}.
*/
type Props = {
/**
* The value of the audio slider should display at when the component first
* mounts. Changes will be stored in state. The value should be a number
* between 0 and 1.
*/
initialValue: number,
/**
* The callback to invoke when the audio slider value changes.
*/
onChange: Function
};
/**
* The type of the React {@code Component} state of {@link VolumeSlider}.
*/
type State = {
/**
* The volume of the participant's audio element. The value will
* be represented by a slider.
*/
volumeLevel: number
};
/**
* Implements a React {@link Component} which displays an input slider for
* adjusting the local volume of a remote participant.
*
* @extends Component
*/
class VolumeSlider extends Component<Props, State> {
/**
* Initializes a new {@code VolumeSlider} instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props: Props) {
super(props);
this.state = {
volumeLevel: (props.initialValue || 0) * VOLUME_SLIDER_SCALE
};
// Bind event handlers so they are only bound once for every instance.
this._onVolumeChange = this._onVolumeChange.bind(this);
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
return (
<li className = 'popupmenu__item'>
<div className = 'popupmenu__contents'>
<span className = 'popupmenu__icon'>
<Icon src = { IconVolume } />
</span>
<div className = 'popupmenu__slider_container'>
<input
className = 'popupmenu__slider'
max = { VOLUME_SLIDER_SCALE }
min = { 0 }
onChange = { this._onVolumeChange }
type = 'range'
value = { this.state.volumeLevel } />
</div>
</div>
</li>
);
}
_onVolumeChange: (Object) => void;
/**
* Sets the internal state of the volume level for the volume slider.
* Invokes the prop onVolumeChange to notify of volume changes.
*
* @param {Object} event - DOM Event for slider change.
* @private
* @returns {void}
*/
_onVolumeChange(event) {
const volumeLevel = event.currentTarget.value;
this.props.onChange(volumeLevel / VOLUME_SLIDER_SCALE);
this.setState({ volumeLevel });
}
}
export default VolumeSlider;
|
src/svg-icons/image/switch-video.js | hwo411/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageSwitchVideo = (props) => (
<SvgIcon {...props}>
<path d="M18 9.5V6c0-.55-.45-1-1-1H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h14c.55 0 1-.45 1-1v-3.5l4 4v-13l-4 4zm-5 6V13H7v2.5L3.5 12 7 8.5V11h6V8.5l3.5 3.5-3.5 3.5z"/>
</SvgIcon>
);
ImageSwitchVideo = pure(ImageSwitchVideo);
ImageSwitchVideo.displayName = 'ImageSwitchVideo';
ImageSwitchVideo.muiName = 'SvgIcon';
export default ImageSwitchVideo;
|
src/parser/shaman/enhancement/modules/talents/ForcefulWinds.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS/index';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import Analyzer from 'parser/core/Analyzer';
import StatisticBox from 'interface/others/StatisticBox';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
const FORCEFUL_WINDS = {
INCREASE: 1,
};
class ForcefulWinds extends Analyzer {
damageGained=0;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.FORCEFUL_WINDS_TALENT.id);
}
on_byPlayer_damage(event) {
const buff = this.selectedCombatant.getBuff(SPELLS.FORCEFUL_WINDS_BUFF.id);
if(!buff){
return;
}
if(event.ability.guid!==SPELLS.WINDFURY_ATTACK.id){
return;
}
const stacks = buff.stacks || 0;
this.damageGained += calculateEffectiveDamage(event, stacks*FORCEFUL_WINDS.INCREASE);
}
get damagePercent() {
return this.owner.getPercentageOfTotalDamageDone(this.damageGained);
}
get damagePerSecond() {
return this.damageGained / (this.owner.fightDuration / 1000);
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.FORCEFUL_WINDS_TALENT.id} />}
value={`${formatPercentage(this.damagePercent)} %`}
label="Of total damage"
tooltip={`Contributed ${formatNumber(this.damagePerSecond)} DPS (${formatNumber(this.damageGained)} total damage).`}
/>
);
}
}
export default ForcefulWinds;
|
tests/site6/src/cards/cards_category.js | dominikwilkowski/cuttlebelle | import PropTypes from 'prop-types';
import React from 'react';
// LOCAL
import Card from './card';
/**
* The partial component
*/
const CardsCategory = ( page ) => (
<div className={`uikit-body uikit-grid cards cards--category`}>
<div className="container">
<ul className="cards__list">
{
page.cards.map( ( card, i ) => (
<li key={ i } className="col-sm-6 col-md-4 col-lg-3 cards__list__item">
<Card
link={ card.link }
background={ card.background }
image={ card.image }
headline={ card.headline }
text={ card.text }
cta={ card.cta }
/>
</li>
))
}
</ul>
{ page.cardsLink && <a className="cards__link uikit-cta-link" href={ `${ page.cardsLink.url }` }>{ page.cardsLink.text }</a> }
</div>
</div>
);
CardsCategory.propTypes = {
/**
* cards:
* - image: http://via.placeholder.com/350x150
* headline: Agile delivery
* text: How to work in an agile way: principles, tools and governance.
* link: '#url'
* background: rebeccapurple
* - image: http://via.placeholder.com/350x150
* headline: Agile delivery
* text: How to work in an agile way: principles, tools and governance.
* link: '#url'
* background: rebeccapurple
* - image: http://via.placeholder.com/350x150
* headline: Agile delivery
* text: How to work in an agile way: principles, tools and governance.
* link: '#url'
* cta: Blah!
* background: rebeccapurple
*/
cards: PropTypes.array.isRequired,
/**
* cardsLink:
* text: View more
* url: /content-strategy/content-auditing
*/
cardsLink: PropTypes.shape({
/**
* text: View more
*/
text: PropTypes.string.isRequired,
/**
* url: /content-strategy/content-auditing
*/
url: PropTypes.string.isRequired
})
};
CardsCategory.defaultProps = {};
export default CardsCategory;
|
packages/app/app/components/SearchResults/AllResults/index.js | nukeop/nuclear | import React from 'react';
import _ from 'lodash';
import { Card } from '@nuclear/ui';
import artPlaceholder from '../../../../resources/media/art_placeholder.png';
import PlaylistResults from '../PlaylistResults';
import TracksResults from '../TracksResults';
import styles from './styles.scss';
import { withTranslation } from 'react-i18next';
@withTranslation('search')
class AllResults extends React.Component {
constructor(props) {
super(props);
}
renderResults(collection, onClick) {
const selectedProvider = _.find(this.props.metaProviders, { sourceName: this.props.selectedPlugins.metaProviders });
return collection.slice(0, 5).map((el, i) => {
const id = _.get(el, `ids.${selectedProvider.searchName}`, el.id);
return (
<Card
small
header={el.title || el.name}
image={
el.coverImage ||
el.thumb ||
el.thumbnail ||
artPlaceholder
}
content={el.artist}
onClick={() => onClick(id, el.type, el)}
key={'item-' + i}
/>
);
});
}
renderTracks(arr = [], limit = 5) {
return (<TracksResults
clearQueue={this.props.clearQueue}
addToQueue={this.props.addToQueue}
startPlayback={this.props.startPlayback}
selectSong={this.props.selectSong}
tracks={arr}
limit={limit}
streamProviders={this.props.streamProviders}
/>);
}
renderPlaylistSection = () =>
<div className={styles.column}>
<h3>{this.props.t('playlist', { count: this.props.playlistSearchResults.length })}</h3>
<div className={styles.row}>
<PlaylistResults
playlistSearchStarted={this.props.playlistSearchStarted}
playlistSearchResults={this.props.playlistSearchResults}
addToQueue={this.props.addToQueue}
clearQueue={this.props.clearQueue}
startPlayback={this.props.startPlayback}
selectSong={this.props.selectSong}
streamProviders={this.props.streamProviders}
/>
</div>
</div>
renderSection(title, collection, onClick) {
return (<div className={styles.column}>
<h3>{title}</h3>
<div className={styles.row}>
{this.renderResults(
collection,
onClick
)}
</div>
</div>);
}
renderArtistsSection() {
const { t, artistSearchResults, artistInfoSearch } = this.props;
return this.renderSection(t('artist', { count: artistSearchResults.length }), artistSearchResults, artistInfoSearch);
}
renderAlbumsSection() {
const { t, albumSearchResults, albumInfoSearch } = this.props;
return this.renderSection(t('album', { count: albumSearchResults.length }), albumSearchResults, albumInfoSearch);
}
renderTracksSection() {
return (<div className={styles.column}>
<h3>{this.props.t('track_plural')}</h3>
<div className={styles.row}>
{this.renderTracks(this.props.trackSearchResults.info)}
</div>
</div>);
}
render() {
const tracksLength = _.get(this.props.trackSearchResults, ['info', 'length'], 0);
const artistsLength = _.get(this.props.artistSearchResults, ['length'], 0);
const albumsLength = _.get(this.props.albumSearchResults, ['length'], 0);
const playlistsLength = _.get(this.props.playlistSearchResults, ['info', 'length'], 0);
if (tracksLength + artistsLength + albumsLength + playlistsLength === 0) {
return <div>{this.props.t('empty')}</div>;
}
return (
<div className={styles.all_results_container}>
{artistsLength > 0 && this.renderArtistsSection()}
{albumsLength > 0 && this.renderAlbumsSection()}
{tracksLength > 0 && this.renderTracksSection()}
{playlistsLength > 0 && this.renderPlaylistSection()}
</div>
);
}
}
export default AllResults;
|
src/svg-icons/file/cloud-queue.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let FileCloudQueue = (props) => (
<SvgIcon {...props}>
<path d="M19.35 10.04C18.67 6.59 15.64 4 12 4 9.11 4 6.6 5.64 5.35 8.04 2.34 8.36 0 10.91 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.96zM19 18H6c-2.21 0-4-1.79-4-4s1.79-4 4-4h.71C7.37 7.69 9.48 6 12 6c3.04 0 5.5 2.46 5.5 5.5v.5H19c1.66 0 3 1.34 3 3s-1.34 3-3 3z"/>
</SvgIcon>
);
FileCloudQueue = pure(FileCloudQueue);
FileCloudQueue.displayName = 'FileCloudQueue';
FileCloudQueue.muiName = 'SvgIcon';
export default FileCloudQueue;
|
src/adapter/material/MaterialExportOptionsView.js | flexicious/react-redux-datagrid | /**
* Flexicious
* Copyright 2011, Flexicious LLC
*/
import { UIUtils, Constants, UIComponent, ComboBox, ReactDataGrid, ReactDataGridColumn, ToolbarAction } from '../../js/library'
import React from 'react'
import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton'
import TextField from 'material-ui/TextField'
/**
* A ExportOptionsView that which can be used within the filtering/binding infrastructure.
* @constructor
* @class ExportOptionsView
* @namespace flexiciousNmsp
* @extends Label
*/
export default class MaterialExportOptionsView extends UIComponent {
constructor() {
super({}, "div")
this.attachClass("flexiciousGrid");
this.cbxColumns = new flexiciousNmsp.MultiSelectComboBox();
this.cbxColumns.alwaysVisible = true;
this.cbxExporters = new flexiciousNmsp.ComboBox();
this.cbxExporters.ignoreAllItem = true;
this.cbxExporters.setAddAllItem(false);
this.setWidth(500);
this.exportOptions = new flexiciousNmsp.ExportOptions();
}
/**
*
* @return {Array}
*/
getClassNames() {
return ["ExportOptionsView", "UIComponent"];
}
setGrid(val) {
this.grid = val;
this.enablePaging = val.getEnablePaging();
this.pageCount = val.getPageSize() > 0 ? Math.ceil(val.getTotalRecords() / val.getPageSize()) : 1;
this.selectedObjectsCount = val.getSelectedObjectsTopLevel().length;
const items = this.grid.getExportableColumnsAtAllLevel(this.exportOptions);
this.itemsToShow = [];
for (const col of items) {
if (col.getVisible()) {
this.itemsToShow.push(col);
}
}
}
onOK(domElement) {
this.exportOptions.printExportOption = this.pageSelection;
const pgFrom = this.pageFrom;
const pgTo = this.pageTo;
if (this.pageSelection == flexiciousNmsp.PrintExportOptions.PRINT_EXPORT_SELECTED_PAGES) {
if (pgFrom >= 1 && pgTo >= 1 && pgFrom <= (this.pageCount) && pgTo <= (this.pageCount) && pgFrom <= pgTo) {
this.exportOptions.pageFrom = pgFrom;
this.exportOptions.pageTo = pgTo;
this.close(Constants.ALERT_OK);
} else {
window.alert("Please ensure that the 'page from' is less than or equal to 'page to'");
}
}
else {
this.close(Constants.ALERT_OK);
}
}
close(dialogResult) {
const closeEvent = new flexiciousNmsp.BaseEvent(Constants.EVENT_CLOSE);
closeEvent.detail = dialogResult;
this.dispatchEvent(closeEvent);
this.grid.removePopup(this.popup);
//UIUtils.removePopUp(this);
}
onCancel(evt) {
this.grid.removePopup(this.popup);
}
showDialog() {
const actions = [ToolbarAction.create((this.exportOptions.openNewWindow ? Constants.PRT_BTN_PRINT_LABEL : Constants.EXP_BTN_EXPORT_LABEL), this.onOK.bind(this), true),
ToolbarAction.create(Constants.EXP_BTN_CANCEL_LABEL, this.onCancel.bind(this), true),
];
this.popup = UIUtils.addPopUp(this.render(), this.grid, false, null, Constants.SETTINGS_POPUP_TITLE, actions);
this.grid.addPopup(this.popup);
}
/**
* Initializes the auto complete and watermark plugins
*/
render() {
return <div key="exportdiv">
<div key="columnsDiv" className={"columnsLabel"} style={{ float: "left" }}>{Constants.EXP_LBL_COLS_TO_EXPORT_TEXT}
<ReactDataGrid key="columnsGrid" width={300} height={300} selectedKeyField={"name"} dataProvider={this.exportOptions.availableColumns} enableActiveCellHighlight={false}
selectedKeys={this.itemsToShow.length ? UIUtils.extractPropertyValues(this.itemsToShow, "uniqueIdentifier")
: UIUtils.extractPropertyValues(this.availableColumns, "name")}
onChange={(evt) => {
this.exportOptions.columnsToExport = (evt.grid.getSelectedObjects());
if (this.exportOptions.columnsToExport.length == 1 && this.exportOptions.columnsToExport[0].name == "All") {
this.exportOptions.columnsToExport = [];
}
} }>
<ReactDataGridColumn type={"checkbox"} />
<ReactDataGridColumn dataField={"headerText"} headerText={Constants.EXP_LBL_COLS_TO_EXPORT_TEXT} />
</ReactDataGrid>
</div>
<div key="optionsDiv" className={"options flexiciousGrid"} style={{ float: "right" }}>
<RadioButtonGroup name="pageSelection" onChange={(evt, newValue) => { this.pageSelection = newValue; } } defaultSelected={flexiciousNmsp.PrintExportOptions.PRINT_EXPORT_CURRENT_PAGE}>
<RadioButton name="currentPage" label={Constants.EXP_RBN_CURRENT_PAGE_LABEL} className={"flxsExportpaging RBN_CURRENT_PAGE"} value={flexiciousNmsp.PrintExportOptions.PRINT_EXPORT_CURRENT_PAGE} />
<RadioButton name="allPages" label={Constants.EXP_RBN_ALL_PAGES_LABEL} className={"flxsExportpaging RBN_ALL_PAGES"} value={flexiciousNmsp.PrintExportOptions.PRINT_EXPORT_ALL_PAGES} />
<RadioButton disabled={this.selectedObjectsCount == 0} className={"flxsExportpaging rbnSelectedRecords"}
value={flexiciousNmsp.PrintExportOptions.PRINT_EXPORT_SELECTED_RECORDS} label={Constants.SELECTED_RECORDS + " (" + (this.selectedObjectsCount == 0 ? 'None Selected)' : this.selectedObjectsCount + " selected)")} />
<RadioButton name="selectedPage" label={Constants.EXP_RBN_SELECT_PGS_LABEL} className={"flxsExportpaging RBN_SELECT_PGS"}
value={flexiciousNmsp.PrintExportOptions.PRINT_EXPORT_SELECTED_PAGES} />
</RadioButtonGroup>
<TextField style={{ width: 'auto' }} key="fromPage" name="fromPage" className={"flxsExportpaging txtPageFrom"} onChange={(evt, newValue) => { this.pageTo = newValue; } } />
<label> {Constants.PGR_TO} </label>
<TextField style={{ width: 'auto' }} key="toPage" name="toPage" className={"flxsExportpaging txtPageTo"} onChange={(evt, newValue) => { this.pageFrom = newValue; } } />
<label>{this.pageCount}</label>
<div>
<label className={"LBL_EXPORT_FORMAT"}> {Constants.EXP_LBL_EXPORT_FORMAT_TEXT}</label>
<select defaultValue={this.exportOptions.getExporterName()} onChange={(evt) => {
this.exportOptions.exporter = this.exportOptions.exporters[evt.currentTarget.selectedIndex];
} }>
{this.exportOptions.exporters.map((exporter, i) => {
return <option key={"option" + i} value={exporter.getName()}>{exporter.getName()}</option>
})}
</select>
</div>
</div>
</div>;
}
}
flexiciousNmsp.MaterialExportOptionsView = MaterialExportOptionsView; //add to name space
MaterialExportOptionsView.prototype.typeName = MaterialExportOptionsView.typeName = 'MaterialExportOptionsView';//for quick inspection |
examples/with-svelte/src/client.js | jaredpalmer/razzle | import React from 'react';
import { hydrate } from 'react-dom';
import App from './App';
hydrate(<App />, document.getElementById('root'));
if (module.hot) {
module.hot.accept();
}
|
react-redux-tutorial/redux-examples/todomvc/index.js | react-scott/react-learn | import 'babel-core/polyfill'
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import App from './containers/App'
import configureStore from './store/configureStore'
import 'todomvc-app-css/index.css'
const store = configureStore()
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
app/containers/Root.js | yianL/focus-group-tool | // @flow
import React from 'react';
import { Provider } from 'react-redux';
import { Router } from 'react-router';
import routes from '../routes';
type RootType = {
store: {},
history: {}
};
export default function Root({ store, history }: RootType) {
return (
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
);
}
|
app/javascript/mastodon/features/status/index.js | cybrespace/mastodon | import Immutable from 'immutable';
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchStatus } from '../../actions/statuses';
import MissingIndicator from '../../components/missing_indicator';
import DetailedStatus from './components/detailed_status';
import ActionBar from './components/action_bar';
import Column from '../ui/components/column';
import {
favourite,
unfavourite,
reblog,
unreblog,
pin,
unpin,
} from '../../actions/interactions';
import {
replyCompose,
mentionCompose,
directCompose,
} from '../../actions/compose';
import { blockAccount } from '../../actions/accounts';
import {
muteStatus,
unmuteStatus,
deleteStatus,
hideStatus,
revealStatus,
} from '../../actions/statuses';
import { initMuteModal } from '../../actions/mutes';
import { initReport } from '../../actions/reports';
import { makeGetStatus } from '../../selectors';
import { ScrollContainer } from 'react-router-scroll-4';
import ColumnBackButton from '../../components/column_back_button';
import ColumnHeader from '../../components/column_header';
import StatusContainer from '../../containers/status_container';
import { openModal } from '../../actions/modal';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { HotKeys } from 'react-hotkeys';
import { boostModal, deleteModal } from '../../initial_state';
import { attachFullscreenListener, detachFullscreenListener, isFullscreen } from '../ui/util/fullscreen';
import { textForScreenReader } from '../../components/status';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
redraftConfirm: { id: 'confirmations.redraft.confirm', defaultMessage: 'Delete & redraft' },
redraftMessage: { id: 'confirmations.redraft.message', defaultMessage: 'Are you sure you want to delete this status and re-draft it? Favourites and boosts will be lost, and replies to the original post will be orphaned.' },
blockConfirm: { id: 'confirmations.block.confirm', defaultMessage: 'Block' },
revealAll: { id: 'status.show_more_all', defaultMessage: 'Show more for all' },
hideAll: { id: 'status.show_less_all', defaultMessage: 'Show less for all' },
detailedStatus: { id: 'status.detailed_status', defaultMessage: 'Detailed conversation view' },
replyConfirm: { id: 'confirmations.reply.confirm', defaultMessage: 'Reply' },
replyMessage: { id: 'confirmations.reply.message', defaultMessage: 'Replying now will overwrite the message you are currently composing. Are you sure you want to proceed?' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => {
const status = getStatus(state, { id: props.params.statusId });
let ancestorsIds = Immutable.List();
let descendantsIds = Immutable.List();
if (status) {
ancestorsIds = ancestorsIds.withMutations(mutable => {
let id = status.get('in_reply_to_id');
while (id) {
mutable.unshift(id);
id = state.getIn(['contexts', 'inReplyTos', id]);
}
});
descendantsIds = descendantsIds.withMutations(mutable => {
const ids = [status.get('id')];
while (ids.length > 0) {
let id = ids.shift();
const replies = state.getIn(['contexts', 'replies', id]);
if (status.get('id') !== id) {
mutable.push(id);
}
if (replies) {
replies.reverse().forEach(reply => {
ids.unshift(reply);
});
}
}
});
}
return {
status,
ancestorsIds,
descendantsIds,
askReplyConfirmation: state.getIn(['compose', 'text']).trim().length !== 0,
domain: state.getIn(['meta', 'domain']),
};
};
return mapStateToProps;
};
export default @injectIntl
@connect(makeMapStateToProps)
class Status extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
status: ImmutablePropTypes.map,
ancestorsIds: ImmutablePropTypes.list,
descendantsIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
askReplyConfirmation: PropTypes.bool,
domain: PropTypes.string.isRequired,
};
state = {
fullscreen: false,
};
componentWillMount () {
this.props.dispatch(fetchStatus(this.props.params.statusId));
}
componentDidMount () {
attachFullscreenListener(this.onFullScreenChange);
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this._scrolledIntoView = false;
this.props.dispatch(fetchStatus(nextProps.params.statusId));
}
}
handleFavouriteClick = (status) => {
if (status.get('favourited')) {
this.props.dispatch(unfavourite(status));
} else {
this.props.dispatch(favourite(status));
}
}
handlePin = (status) => {
if (status.get('pinned')) {
this.props.dispatch(unpin(status));
} else {
this.props.dispatch(pin(status));
}
}
handleReplyClick = (status) => {
let { askReplyConfirmation, dispatch, intl } = this.props;
if (askReplyConfirmation) {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.replyMessage),
confirm: intl.formatMessage(messages.replyConfirm),
onConfirm: () => dispatch(replyCompose(status, this.context.router.history)),
}));
} else {
dispatch(replyCompose(status, this.context.router.history));
}
}
handleModalReblog = (status) => {
this.props.dispatch(reblog(status));
}
handleReblogClick = (status, e) => {
if (status.get('reblogged')) {
this.props.dispatch(unreblog(status));
} else {
if ((e && e.shiftKey) || !boostModal) {
this.handleModalReblog(status);
} else {
this.props.dispatch(openModal('BOOST', { status, onReblog: this.handleModalReblog }));
}
}
}
handleDeleteClick = (status, history, withRedraft = false) => {
const { dispatch, intl } = this.props;
if (!deleteModal) {
dispatch(deleteStatus(status.get('id'), history, withRedraft));
} else {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(withRedraft ? messages.redraftMessage : messages.deleteMessage),
confirm: intl.formatMessage(withRedraft ? messages.redraftConfirm : messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'), history, withRedraft)),
}));
}
}
handleDirectClick = (account, router) => {
this.props.dispatch(directCompose(account, router));
}
handleMentionClick = (account, router) => {
this.props.dispatch(mentionCompose(account, router));
}
handleOpenMedia = (media, index) => {
this.props.dispatch(openModal('MEDIA', { media, index }));
}
handleOpenVideo = (media, time) => {
this.props.dispatch(openModal('VIDEO', { media, time }));
}
handleMuteClick = (account) => {
this.props.dispatch(initMuteModal(account));
}
handleConversationMuteClick = (status) => {
if (status.get('muted')) {
this.props.dispatch(unmuteStatus(status.get('id')));
} else {
this.props.dispatch(muteStatus(status.get('id')));
}
}
handleToggleHidden = (status) => {
if (status.get('hidden')) {
this.props.dispatch(revealStatus(status.get('id')));
} else {
this.props.dispatch(hideStatus(status.get('id')));
}
}
handleToggleAll = () => {
const { status, ancestorsIds, descendantsIds } = this.props;
const statusIds = [status.get('id')].concat(ancestorsIds.toJS(), descendantsIds.toJS());
if (status.get('hidden')) {
this.props.dispatch(revealStatus(statusIds));
} else {
this.props.dispatch(hideStatus(statusIds));
}
}
handleBlockClick = (account) => {
const { dispatch, intl } = this.props;
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.block.message' defaultMessage='Are you sure you want to block {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.blockConfirm),
onConfirm: () => dispatch(blockAccount(account.get('id'))),
}));
}
handleReport = (status) => {
this.props.dispatch(initReport(status.get('account'), status));
}
handleEmbed = (status) => {
this.props.dispatch(openModal('EMBED', { url: status.get('url') }));
}
handleHotkeyMoveUp = () => {
this.handleMoveUp(this.props.status.get('id'));
}
handleHotkeyMoveDown = () => {
this.handleMoveDown(this.props.status.get('id'));
}
handleHotkeyReply = e => {
e.preventDefault();
this.handleReplyClick(this.props.status);
}
handleHotkeyFavourite = () => {
this.handleFavouriteClick(this.props.status);
}
handleHotkeyBoost = () => {
this.handleReblogClick(this.props.status);
}
handleHotkeyMention = e => {
e.preventDefault();
this.handleMentionClick(this.props.status.get('account'));
}
handleHotkeyOpenProfile = () => {
this.context.router.history.push(`/accounts/${this.props.status.getIn(['account', 'id'])}`);
}
handleHotkeyToggleHidden = () => {
this.handleToggleHidden(this.props.status);
}
handleMoveUp = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size - 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index);
} else {
this._selectChild(index - 1);
}
}
}
handleMoveDown = id => {
const { status, ancestorsIds, descendantsIds } = this.props;
if (id === status.get('id')) {
this._selectChild(ancestorsIds.size + 1);
} else {
let index = ancestorsIds.indexOf(id);
if (index === -1) {
index = descendantsIds.indexOf(id);
this._selectChild(ancestorsIds.size + index + 2);
} else {
this._selectChild(index + 1);
}
}
}
_selectChild (index) {
const element = this.node.querySelectorAll('.focusable')[index];
if (element) {
element.focus();
}
}
renderChildren (list) {
return list.map(id => (
<StatusContainer
key={id}
id={id}
onMoveUp={this.handleMoveUp}
onMoveDown={this.handleMoveDown}
contextType='thread'
/>
));
}
setRef = c => {
this.node = c;
}
componentDidUpdate () {
if (this._scrolledIntoView) {
return;
}
const { status, ancestorsIds } = this.props;
if (status && ancestorsIds && ancestorsIds.size > 0) {
const element = this.node.querySelectorAll('.focusable')[ancestorsIds.size - 1];
window.requestAnimationFrame(() => {
element.scrollIntoView(true);
});
this._scrolledIntoView = true;
}
}
componentWillUnmount () {
detachFullscreenListener(this.onFullScreenChange);
}
onFullScreenChange = () => {
this.setState({ fullscreen: isFullscreen() });
}
render () {
let ancestors, descendants;
const { shouldUpdateScroll, status, ancestorsIds, descendantsIds, intl, domain } = this.props;
const { fullscreen } = this.state;
if (status === null) {
return (
<Column>
<ColumnBackButton />
<MissingIndicator />
</Column>
);
}
if (ancestorsIds && ancestorsIds.size > 0) {
ancestors = <div>{this.renderChildren(ancestorsIds)}</div>;
}
if (descendantsIds && descendantsIds.size > 0) {
descendants = <div>{this.renderChildren(descendantsIds)}</div>;
}
const handlers = {
moveUp: this.handleHotkeyMoveUp,
moveDown: this.handleHotkeyMoveDown,
reply: this.handleHotkeyReply,
favourite: this.handleHotkeyFavourite,
boost: this.handleHotkeyBoost,
mention: this.handleHotkeyMention,
openProfile: this.handleHotkeyOpenProfile,
toggleHidden: this.handleHotkeyToggleHidden,
};
return (
<Column label={intl.formatMessage(messages.detailedStatus)}>
<ColumnHeader
showBackButton
extraButton={(
<button className='column-header__button' title={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} aria-label={intl.formatMessage(status.get('hidden') ? messages.revealAll : messages.hideAll)} onClick={this.handleToggleAll} aria-pressed={status.get('hidden') ? 'false' : 'true'}><i className={`fa fa-${status.get('hidden') ? 'eye-slash' : 'eye'}`} /></button>
)}
/>
<ScrollContainer scrollKey='thread' shouldUpdateScroll={shouldUpdateScroll}>
<div className={classNames('scrollable', { fullscreen })} ref={this.setRef}>
{ancestors}
<HotKeys handlers={handlers}>
<div className={classNames('focusable', 'detailed-status__wrapper')} tabIndex='0' aria-label={textForScreenReader(intl, status, false, !status.get('hidden'))}>
<DetailedStatus
status={status}
onOpenVideo={this.handleOpenVideo}
onOpenMedia={this.handleOpenMedia}
onToggleHidden={this.handleToggleHidden}
domain={domain}
/>
<ActionBar
status={status}
onReply={this.handleReplyClick}
onFavourite={this.handleFavouriteClick}
onReblog={this.handleReblogClick}
onDelete={this.handleDeleteClick}
onDirect={this.handleDirectClick}
onMention={this.handleMentionClick}
onMute={this.handleMuteClick}
onMuteConversation={this.handleConversationMuteClick}
onBlock={this.handleBlockClick}
onReport={this.handleReport}
onPin={this.handlePin}
onEmbed={this.handleEmbed}
/>
</div>
</HotKeys>
{descendants}
</div>
</ScrollContainer>
</Column>
);
}
}
|
packages/material-ui-icons/src/KeyboardArrowUp.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z" /></g>
, 'KeyboardArrowUp');
|
dumb/files/__root__/components/__topic__/__name__/__name__.js | CurtisHumphrey/redux_blueprints | import React from 'react'
// import PropTypes from 'prop-types'
import './<%= pascalEntityName %>.scss'
export class <%= pascalEntityName %> extends React.PureComponent {
static propTypes = {
};
static defaultProps = {
};
render () {
return (
<div>Content</div>
)
}
}
export default <%= pascalEntityName %>
|
common/components/post.js | hackersync/HackerSync | /**
* A post component
* @flow
*/
import React, { Component } from 'react';
import Time from '../utils/time.js';
import {
StyleSheet,
Text,
TouchableHighlight,
View
} from 'react-native';
export class Post extends Component {
constructor(props){
super(props);
let rowData = this.props.data;
let currentTime = this.props.currentTime;
let timeAgo = Time.getTimeAgo(currentTime, rowData.time*1000);
this.state = {
data: rowData,
timeAgo: timeAgo,
}
}
render() {
return (
<View style={styles.listItem}>
<View style={[
styles.scoreContainer,
this.state.data.type == 'job' ? {borderRightColor: 'green'} : {}
]}>
<Text style={styles.score}>
{this.state.data.score}
</Text>
</View>
<View style={styles.post}>
<View>
<Text style={styles.title}>
{this.state.data.title}
</Text>
</View>
<View style={styles.postData}>
{this.state.data.descendants != null
? (<View style={{flexDirection: 'row'}}>
<Text style={[styles.info, styles.comments]}>
{this.state.data.descendants} comments
</Text>
<Text style={styles.infoDivider}> • </Text>
</View>)
: null}
{this.state.data.type == 'job'
? (<View style={{flexDirection: 'row'}}>
<Text style={styles.job}>
[Job]
</Text>
<Text style={styles.infoDivider}> • </Text>
</View>)
: null}
<View>
<Text style={[styles.info, styles.author]}>
{this.state.data.by}
</Text>
</View>
<View>
<Text style={styles.info}> submitted {this.state.timeAgo}</Text>
</View>
</View>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
listItem: {
padding: 10,
paddingLeft: 10,
paddingRight: 20,
marginTop: 5,
marginBottom: 5,
flexDirection: 'row',
},
infoDivider: {
color: 'gray',
fontSize: 10,
},
post: {
flex: 1,
},
scoreContainer: {
flex: 0,
width: 50,
paddingRight: 8,
marginRight: 10,
alignItems: 'flex-end',
justifyContent: 'center',
borderRightColor: 'orange',
borderRightWidth: 2,
},
score: {
color: 'black',
fontSize: 16
},
job: {
color: 'green',
fontSize: 10,
},
title: {
fontSize: 12,
},
postData: {
flexDirection: 'row',
},
comments: {
fontWeight: 'bold',
},
author: {
color: '#cc8400',
},
info: {
color: 'gray',
fontSize: 10,
}
});
module.exports = Post;
|
app/components/admin/submissions.js | bigappleinsider/auth-client-prod | import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions';
import { Link } from 'react-router';
class Submissions extends Component {
componentWillMount() {
this.props.fetchSubmissions(this.props.params.id);
}
renderSingleSubmission(submission) {
return (
<div key={submission._id}>
<h3>{submission.user.email}</h3>
{this.renderSubmissionGrid(submission)}
</div>
)
}
renderSubmissionGrid(submission) {
return submission.questions.map((item, key) => {
return (
<div className="panel panel-default" key={item._id}>
<div className="panel-heading">{item.questionText}</div>
<div className="panel-body">{item.answer}</div>
</div>
);
});
}
renderSubmissions() {
return (
<div>
<div className="btn-group">
<Link to="/questionaire" className="btn btn-default tt">
<i className="fa fa-long-arrow-left"></i> Back to questionaires
</Link>
</div>
{this.props.submissions.length > 0 &&
<h2>Submissions for {this.props.submissions[0].questionaire.name}</h2>
}
{this.props.submissions.map((item) => this.renderSingleSubmission(item))}
{this.props.submissions.length === 0 &&
<h3>No submissions found</h3>
}
</div>
);
}
render() {
return (
<div>
{this.props.submissions && this.renderSubmissions()}
</div>
);
}
}
function mapStateToProps(state) {
return { submissions: state.submissions.submissions };
}
export default connect(mapStateToProps, actions)(Submissions);
|
node_modules/react-router/es/withRouter.js | rralian/steckball-react | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import hoistStatics from 'hoist-non-react-statics';
import { ContextSubscriber } from './ContextUtils';
import { routerShape } from './PropTypes';
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export default function withRouter(WrappedComponent, options) {
var withRef = options && options.withRef;
var WithRouter = React.createClass({
displayName: 'WithRouter',
mixins: [ContextSubscriber('router')],
contextTypes: { router: routerShape },
propTypes: { router: routerShape },
getWrappedInstance: function getWrappedInstance() {
!withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0;
return this.wrappedInstance;
},
render: function render() {
var _this = this;
var router = this.props.router || this.context.router;
var params = router.params,
location = router.location,
routes = router.routes;
var props = _extends({}, this.props, { router: router, params: params, location: location, routes: routes });
if (withRef) {
props.ref = function (c) {
_this.wrappedInstance = c;
};
}
return React.createElement(WrappedComponent, props);
}
});
WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')';
WithRouter.WrappedComponent = WrappedComponent;
return hoistStatics(WithRouter, WrappedComponent);
} |
docs/app/Examples/elements/Header/Variations/HeaderExampleFloating.js | shengnian/shengnian-ui-react | import React from 'react'
import { Header, Segment } from 'shengnian-ui-react'
const HeaderExampleFloating = () => (
<Segment clearing>
<Header as='h2' floated='right'>
Float Right
</Header>
<Header as='h2' floated='left'>
Float Left
</Header>
</Segment>
)
export default HeaderExampleFloating
|
admin/client/components/InvalidFieldType.js | riyadhalnur/keystone | import React from 'react';
module.exports = React.createClass({
displayName: 'InvalidFieldType',
propTypes: {
path: React.PropTypes.string,
type: React.PropTypes.string,
},
render () {
return <div className="alert alert-danger">Invalid field type <strong>{this.props.type}</strong> at path <strong>{this.props.path}</strong></div>;
},
});
|
src/utils/CustomPropTypes.js | tannewt/react-bootstrap | import React from 'react';
const ANONYMOUS = '<<anonymous>>';
const CustomPropTypes = {
isRequiredForA11y(propType){
return function(props, propName, componentName){
if (props[propName] === null) {
return new Error(
'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' +
'for users using assistive technologies such as screen readers `'
);
}
return propType(props, propName, componentName);
};
},
/**
* Checks whether a prop provides a DOM element
*
* The element can be provided in two forms:
* - Directly passed
* - Or passed an object that has a `render` method
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
mountable: createMountableChecker(),
/**
* Checks whether a prop provides a type of element.
*
* The type of element can be provided in two forms:
* - tag name (string)
* - a return value of React.createClass(...)
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
elementType: createElementTypeChecker(),
/**
* Checks whether a prop matches a key of an associated object
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
keyOf: createKeyOfChecker,
/**
* Checks if only one of the listed properties is in use. An error is given
* if multiple have a value
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
singlePropFrom: createSinglePropFromChecker,
all
};
function errMsg(props, propName, componentName, msgContinuation) {
return `Invalid prop '${propName}' of value '${props[propName]}'` +
` supplied to '${componentName}'${msgContinuation}`;
}
/**
* Create chain-able isRequired validator
*
* Largely copied directly from:
* https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94
*/
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName) {
componentName = componentName || ANONYMOUS;
if (props[propName] == null) {
if (isRequired) {
return new Error(
`Required prop '${propName}' was not specified in '${componentName}'.`
);
}
} else {
return validate(props, propName, componentName);
}
}
let chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createMountableChecker() {
function validate(props, propName, componentName) {
if (typeof props[propName] !== 'object' ||
typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) {
return new Error(
errMsg(props, propName, componentName,
', expected a DOM element or an object that has a `render` method')
);
}
}
return createChainableTypeChecker(validate);
}
function createKeyOfChecker(obj) {
function validate(props, propName, componentName) {
let propValue = props[propName];
if (!obj.hasOwnProperty(propValue)) {
let valuesString = JSON.stringify(Object.keys(obj));
return new Error(
errMsg(props, propName, componentName, `, expected one of ${valuesString}.`)
);
}
}
return createChainableTypeChecker(validate);
}
function createSinglePropFromChecker(arrOfProps) {
function validate(props, propName, componentName) {
const usedPropCount = arrOfProps
.map(listedProp => props[listedProp])
.reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0);
if (usedPropCount > 1) {
const [first, ...others] = arrOfProps;
const message = `${others.join(', ')} and ${first}`;
return new Error(
`Invalid prop '${propName}', only one of the following ` +
`may be provided: ${message}`
);
}
}
return validate;
}
function all(propTypes) {
if (propTypes === undefined) {
throw new Error('No validations provided');
}
if (!(propTypes instanceof Array)) {
throw new Error('Invalid argument must be an array');
}
if (propTypes.length === 0) {
throw new Error('No validations provided');
}
return function(props, propName, componentName) {
for(let i = 0; i < propTypes.length; i++) {
let result = propTypes[i](props, propName, componentName);
if (result !== undefined && result !== null) {
return result;
}
}
};
}
function createElementTypeChecker() {
function validate(props, propName, componentName) {
let errBeginning = errMsg(props, propName, componentName,
'. Expected an Element `type`');
if (typeof props[propName] !== 'function') {
if (React.isValidElement(props[propName])) {
return new Error(errBeginning + ', not an actual Element');
}
if (typeof props[propName] !== 'string') {
return new Error(errBeginning +
' such as a tag name or return value of React.createClass(...)');
}
}
}
return createChainableTypeChecker(validate);
}
export default CustomPropTypes;
|
src/Main/CastEfficiency.js | mwwscott0/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
const CastEfficiency = ({ categories, abilities }) => {
if (!abilities) {
return <div>Loading...</div>;
}
return (
<div style={{ marginTop: -10, marginBottom: -10 }}>
<table className="data-table" style={{ marginTop: 10, marginBottom: 10 }}>
{Object.keys(categories)
.filter(key => abilities.some(item => item.ability.category === categories[key])) // filters out categories without any abilities in it
.map(key => (
<tbody key={key}>
<tr>
<th>{categories[key]}</th>
<th className="text-center"><dfn data-tip="Casts Per Minute">CPM</dfn></th>
<th colSpan="3"><dfn data-tip="The max possible casts is a super simplified calculation based on the Haste you get from your gear alone. Any Haste increasers such as from talents, Bloodlust and boss abilities are not taken into consideration, so this is <b>always</b> lower than actually possible for abilities affected by Haste.">Cast efficiency</dfn></th>
<th>Overhealing</th>
<th />
</tr>
{abilities
.filter(item => item.ability.category === categories[key])
.map(({ ability, cpm, maxCpm, casts, maxCasts, castEfficiency, overhealing, canBeImproved }) => {
const name = ability.name || ability.spell.name;
return (
<tr key={name}>
<td style={{ width: '35%' }}>
<SpellLink id={ability.spell.id} style={{ color: '#fff' }}>
<SpellIcon id={ability.spell.id} noLink /> {name}
</SpellLink>
</td>
<td className="text-center" style={{ minWidth: 80 }}>
{cpm.toFixed(2)}
</td>
<td className="text-right" style={{ minWidth: 100 }}>
{casts}{maxCasts === Infinity ? '' : `/${Math.floor(maxCasts)}`} casts
</td>
<td style={{ width: '20%' }}>
{maxCasts === Infinity ? '' : (
<div
className="performance-bar"
style={{ width: `${castEfficiency * 100}%`, backgroundColor: canBeImproved ? '#ff8000' : '#70b570' }}
/>
)}
</td>
<td className="text-right" style={{ minWidth: 50, paddingRight: 5 }}>
{maxCpm !== null ? `${(castEfficiency * 100).toFixed(2)}%` : ''}
</td>
<td className="text-center" style={{ minWidth: 80 }}>
{overhealing !== null ? `${(overhealing * 100).toFixed(2)}%` : '-'}
</td>
<td style={{ width: '25%', color: 'orange' }}>
{canBeImproved && !ability.noCanBeImproved && 'Can be improved.'}
</td>
</tr>
);
})}
</tbody>
))}
</table>
</div>
);
};
CastEfficiency.propTypes = {
abilities: PropTypes.arrayOf(PropTypes.shape({
ability: PropTypes.shape({
name: PropTypes.string,
category: PropTypes.string.isRequired,
spell: PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
}).isRequired,
}),
cpm: PropTypes.number.isRequired,
maxCpm: PropTypes.number,
casts: PropTypes.number.isRequired,
maxCasts: PropTypes.number.isRequired,
castEfficiency: PropTypes.number,
canBeImproved: PropTypes.bool.isRequired,
})).isRequired,
categories: PropTypes.object,
};
export default CastEfficiency;
|
src/media/js/addon/containers/versionListing.js | mozilla/marketplace-submission | /*
Version listing as a smart component since it involves binding a lot of
actions.
*/
import classnames from 'classnames';
import React from 'react';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import {fetchVersions} from '../actions/addon';
import {del as deleteVersion} from '../actions/version';
import {publish, reject} from '../actions/review';
import {fetchThreads, submitNote} from '../actions/comm';
import AddonVersion from '../components/version';
import {versionListSelector} from '../selectors/version';
import {PageSection} from '../../site/components/page';
export class AddonVersionListing extends React.Component {
static propTypes = {
className: React.PropTypes.string,
deleteVersion: React.PropTypes.func,
fetchThreads: React.PropTypes.func.isRequired,
fetchVersions: React.PropTypes.func.isRequired,
publish: React.PropTypes.func.isRequired,
reject: React.PropTypes.func.isRequired,
showDeveloperActions: React.PropTypes.bool,
showReviewActions: React.PropTypes.bool,
slug: React.PropTypes.func.isRequired,
versions: React.PropTypes.array.isRequired,
};
constructor(props) {
super(props);
this.props.fetchThreads(this.props.slug);
this.props.fetchVersions(this.props.slug);
}
renderVersion = version => {
return (
<li>
<AddonVersion key={version.id} {...this.props} {...version}
{...this.props.threads[version.id]}/>
</li>
);
}
render() {
const pageStyle = {
display: this.props.versions.length ? 'block' : 'none'
};
return (
<PageSection className={this.props.className} title="Versions"
style={pageStyle}>
<p className="version-listing-helptext">
Click on a version below to see its details or to send a message.
</p>
<ul>{this.props.versions.map(this.renderVersion)}</ul>
</PageSection>
);
}
}
export default connect(
state => ({
slug: state.router.params.slug,
threads: state.addonThread.threads,
versions: versionListSelector(
(state.addon.addons[state.router.params.slug] || {}).versions
)
}),
dispatch => bindActionCreators({
deleteVersion,
fetchThreads,
fetchVersions,
publish,
reject,
submitNote
}, dispatch)
)(AddonVersionListing);
|
renderer/components/Icon/Padlock.js | LN-Zap/zap-desktop | import React from 'react'
const SvgPadlock = props => (
<svg height="1em" viewBox="0 0 8 11" width="1em" {...props}>
<path
d="M7.805 5.219a.609.609 0 0 0-.472-.22h-.222V3.5c0-.958-.305-1.78-.916-2.467C5.583.344 4.852 0 4 0c-.852 0-1.584.344-2.195 1.032C1.195 1.719.89 2.542.89 3.5V5H.667a.61.61 0 0 0-.473.219A.773.773 0 0 0 0 5.75v4.5c0 .208.065.385.194.531A.61.61 0 0 0 .667 11h6.666a.61.61 0 0 0 .473-.219A.773.773 0 0 0 8 10.25v-4.5a.772.772 0 0 0-.195-.531zm-2.027-.22H2.222V3.5c0-.551.174-1.023.521-1.413C3.09 1.696 3.51 1.5 4 1.5c.49 0 .91.195 1.257.586.347.39.52.862.52 1.414V5z"
fill="currentColor"
fillRule="evenodd"
/>
</svg>
)
export default SvgPadlock
|
src/js/components/icons/base/Bus.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-bus`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'bus');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M3,12 L21,12 L21,20 L3,20 L3,12 Z M3,3.99961498 C3,2.89525812 3.8926228,2 4.99508929,2 L19.0049107,2 C20.1067681,2 21,2.88743329 21,3.99961498 L21,12 L3,12 L3,3.99961498 Z M3,20 L6,20 L6,22.0010434 C6,22.5527519 5.55733967,23 5.00104344,23 L3.99895656,23 C3.44724809,23 3,22.5573397 3,22.0010434 L3,20 Z M18,20 L21,20 L21,22.0010434 C21,22.5527519 20.5573397,23 20.0010434,23 L18.9989566,23 C18.4472481,23 18,22.5573397 18,22.0010434 L18,20 Z M7,17 C7.55228475,17 8,16.5522847 8,16 C8,15.4477153 7.55228475,15 7,15 C6.44771525,15 6,15.4477153 6,16 C6,16.5522847 6.44771525,17 7,17 Z M17,17 C17.5522847,17 18,16.5522847 18,16 C18,15.4477153 17.5522847,15 17,15 C16.4477153,15 16,15.4477153 16,16 C16,16.5522847 16.4477153,17 17,17 Z M12,6 L12,12 M1,5 L1,13 M23,5 L23,13 M10,16 L14,16 M3,5.99975586 L21,6"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Bus';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/components/LeftMenu/LeftMenu.js | k2data/k2-react-components | import React from 'react'
import PropTypes from 'prop-types'
const itemStyle = {
position: 'relative',
}
const LeftMenu = (props) => {
const lightThem = {
background: '#FAFAFA',
color: '#555555',
}
const darkThem = {
background: '#1E2A4D',
color: '#FFFFFF',
}
const them = props.them || 'light'
const raperStyle = them === 'light' ? lightThem : darkThem
return (
<div className={`k2-${them}`} style={{...raperStyle, overflow: 'auto'}}>
{props.children}
</div>
)
}
LeftMenu.propTypes = {
them: PropTypes.string,
children: PropTypes.array,
}
const SubMenu = (props) => (
<div style={itemStyle}>
<div className={'menu_title'}>{props.name}</div>
{props.children}
</div>
)
SubMenu.propTypes = {
name: PropTypes.string,
children: PropTypes.array,
}
const MenuItem = (props) => {
return (
<div style={itemStyle}>
{props.icon}
<span
className={'menulist_name'} >
{props.name}
</span>
</div>
)
}
MenuItem.propTypes = {
icon: PropTypes.node,
name: PropTypes.string,
}
export { SubMenu, MenuItem, LeftMenu }
|
src/Interpolate.js | pivotal-cf/react-bootstrap | // https://www.npmjs.org/package/react-interpolate-component
// TODO: Drop this in favor of es6 string interpolation
import React from 'react';
import ValidComponentChildren from './utils/ValidComponentChildren';
const REGEXP = /\%\((.+?)\)s/;
const Interpolate = React.createClass({
displayName: 'Interpolate',
propTypes: {
component: React.PropTypes.node,
format: React.PropTypes.string,
unsafe: React.PropTypes.bool
},
getDefaultProps() {
return {
component: 'span',
unsafe: false
};
},
render() {
let format = (ValidComponentChildren.hasValidComponent(this.props.children) ||
(typeof this.props.children === 'string')) ?
this.props.children : this.props.format;
let parent = this.props.component;
let unsafe = this.props.unsafe === true;
let props = {...this.props};
delete props.children;
delete props.format;
delete props.component;
delete props.unsafe;
if (unsafe) {
let content = format.split(REGEXP).reduce(function(memo, match, index) {
let html;
if (index % 2 === 0) {
html = match;
} else {
html = props[match];
delete props[match];
}
if (React.isValidElement(html)) {
throw new Error('cannot interpolate a React component into unsafe text');
}
memo += html;
return memo;
}, '');
props.dangerouslySetInnerHTML = { __html: content };
return React.createElement(parent, props);
} else {
let kids = format.split(REGEXP).reduce(function(memo, match, index) {
let child;
if (index % 2 === 0) {
if (match.length === 0) {
return memo;
}
child = match;
} else {
child = props[match];
delete props[match];
}
memo.push(child);
return memo;
}, []);
return React.createElement(parent, props, kids);
}
}
});
export default Interpolate;
|
test/test_helper.js | oldirony/react-router-playground | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.