path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
---|---|---|
src/app/pages/Home.js | skratchdot/audio-links | import React, { Component } from 'react';
import { Row, Col, Button, Input, Jumbotron, Label, Glyphicon } from 'react-bootstrap';
import { connect } from 'react-redux';
import { setFilterText } from '../actions/filterText';
import { addTag, deleteTag, clearTags } from '../actions/tags';
import allTags from '../../../data/tags.json';
import urlData from '../../../data/urls.json';
class Home extends Component {
toggleTag(tag) {
const { dispatch, tags } = this.props;
if (tags.indexOf(tag) === -1) {
dispatch(addTag(tag));
} else {
dispatch(deleteTag(tag));
}
}
render() {
const self = this;
const { dispatch, filterText, tags } = this.props;
const clearTagButton = (
<small>
<a href="#" onClick={(e) => {
e.preventDefault();
dispatch(clearTags());
}}>
clear all
</a>
</small>
);
let extraTag;
if (tags.length === 0) {
extraTag = (<small>No tags selected</small>);
}
// populate results
const searchText = filterText.replace(/ +/g, ' ').toLowerCase();
const results = urlData.filter(function (data) {
if (tags.length === 0) {
return true;
} else {
for (let i = 0; i < tags.length; i++) {
if (data.tags.indexOf(tags[i]) > -1) {
return true;
}
}
}
return false;
}).filter(function (data) {
const props = ['title', 'description', 'tags', 'url'];
if (filterText === '') {
return true;
}
for (let i = 0; i < props.length; i++) {
const text = data[props[i]].toString().replace(/\s+/g, ' ').toLowerCase();
if (text.indexOf(searchText) !== -1) {
return true;
}
}
return false;
});
return (
<div>
<Row>
<Col md={8}>
<Jumbotron>
<div>
<strong>
Filter:
<small><a href="#" onClick={(e) => {
e.preventDefault();
dispatch(setFilterText(''));
}}>clear text</a></small>
<br />
</strong>
<Input
type="text"
placeholder="Filter results..."
value={filterText}
onInput={(e) => {
dispatch(setFilterText(e.target.value));
}}
/>
<div>
<strong>
Tags:
{clearTagButton}
<br />
</strong>
<div>
{tags.map(function (tag, i) {
return (
<Label
key={`tag${i}`}
onClick={() => {
dispatch(deleteTag(tag));
}}
style={{
marginRight: 10,
display: 'inline-block',
cursor: 'pointer'
}}>
<Glyphicon glyph="remove" />
{tag}
</Label>
);
})}
{extraTag}
</div>
</div>
</div>
</Jumbotron>
<hr />
<div style={{marginBottom: 40}}>
<h2>Results <small>({results.length})</small>:</h2>
{results.map(function (data, i) {
const title = data.title || data.url;
const color = i % 2 === 0 ? '#efefef' : '#fafafa';
return (
<div
key={`url${i}`}
style={{
backgroundColor: color,
padding: 20,
borderTop: '1px solid #aaa'
}}>
<a href={data.url} target="_blank">{title}</a>
-
{data.description}
<div> </div>
<div>
<small>
Tags:
{data.tags.map(function (tag, i) {
const comma = i > 0 ? ',' : '';
return (
<span key={`tagLink${i}`}>
{comma}
<a href="#" onClick={(e) => {
e.preventDefault();
if (tags.indexOf(tag) === -1) {
dispatch(addTag(tag));
}
window.scrollTo(0, 0);
}}>
{tag}
</a>
</span>
);
})}
</small>
</div>
</div>
);
})}
</div>
</Col>
<Col md={4}>
<Jumbotron>
<h2 style={{marginTop: 0}}>Tags: {clearTagButton}</h2>
{allTags.map(function (tag, i) {
return (
<Button
key={`tag${i}`}
bsSize="xsmall"
active={tags.indexOf(tag) > -1}
onClick={self.toggleTag.bind(self, tag)}>
{tag}
</Button>
);
})}
</Jumbotron>
</Col>
</Row>
</div>
);
}
}
export default connect(function (state) {
return {
filterText: state.filterText,
tags: state.tags
};
})(Home);
|
src/routes/HelloWorld/Component.js | bryanmartin82/react-starter | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as ActionCreators from './actions';
import styles from './styles.css';
import checkmark from 'svg/icons/checkmark.svg';
import Icon from 'components/Icon/Component';
class HelloWorldContainer extends Component {
render() {
const { msg, color } = this.props.helloWorld;
const { changeColor } = this.props;
return (
<div className={styles.root}>
<div className={styles.content} style={{backgroundColor: color}}>
<Icon svg={checkmark} className={styles.interactive} onClick={changeColor} size="64" style={{color}} />
<h1 className={styles.element}>{msg}</h1>
</div>
</div>
);
}
}
const mapState = state => ({
helloWorld: state.get('helloWorld')
});
const mapDispatch = (dispatch) => ({
changeColor() {
dispatch(ActionCreators.changeColor())
}
});
export default connect(mapState, mapDispatch)(HelloWorldContainer); |
src/components/InnerLayout/ImageUpload/ImageUpload.js | Venumteam/loafer-front | import React from 'react'
// styles
import classNames from 'classnames/bind'
import styles from './ImageUpload.scss'
// constants
const avatarPlaceholder = require('../../../../static/user.svg')
const cx = classNames.bind(styles)
export default class ImageUpload extends React.Component {
static propTypes = {
user: React.PropTypes.object.isRequired,
uploadImage: React.PropTypes.func.isRequired
};
render () {
const { uploadImage, user } = this.props
return (
<div className="text-center">
<img className="img-rounded block-center img-responsive" role="presentation"
src={user.avatar_url || avatarPlaceholder} style={{ maxWidth: '150px' }} />
<div className={cx('btn btn-default mt-10', 'upload-button-wrapper')}>
<input className={cx('fa fa-upload mr', 'upload')} type="file" onChange={uploadImage} />
<span className="icon-span-filestyle fa fa-upload mr" />
<span className="buttonText">Обновить аватар</span>
</div>
</div>
)
}
}
|
fields/types/boolean/BooleanFilter.js | dryna/keystone-twoje-urodziny | import React from 'react';
import { SegmentedControl } from '../../../admin/client/App/elemental';
const VALUE_OPTIONS = [
{ label: 'Is Checked', value: true },
{ label: 'Is NOT Checked', value: false },
];
function getDefaultValue () {
return {
value: true,
};
}
var BooleanFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
value: React.PropTypes.bool,
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
updateValue (value) {
this.props.onChange({ value });
},
render () {
return <SegmentedControl equalWidthSegments options={VALUE_OPTIONS} value={this.props.filter.value} onChange={this.updateValue} />;
},
});
module.exports = BooleanFilter;
|
js/components/Nav.js | ShadowZheng/CodingLife | import React from 'react';
import {Link} from 'react-router';
import NavAction from '../actions/NavAction';
import NavStore from '../stores/NavStore';
import $ from '../jquery';
function openNav() {
$('#app').addClass('show-nav');
$('#nav-toggle').addClass('uac-close')
$('#nav-toggle').addClass('uac-dark');
}
function closeNav() {
$('#app').removeClass('show-nav');
$('#nav-toggle').removeClass('uac-close')
$('#nav-toggle').removeClass('uac-dark');
}
export default class Nav extends React.Component {
constructor(args) {
super(args);
}
componentDidMount() {
NavStore.addChangeListener(this._onChange);
// store dom elements here
this.ele = {
app:document.getElementById('app'),
navSvgPoints : {
from: [115,800,115,800,115,1,115,1 ],
to: [115,800,5 , 800,115,1,115,1 ],
}
}
this.ele.navSvg = Snap( document.getElementById('nav-svg') );//;
this.ele.navSvgPolygon = this.ele.navSvg.polygon( this.ele.navSvgPoints.from );
this.ele.navSvgPolygon.attr({
id:"nav-svg-poly",
fill: "#ffffff",
});
this.ele.isNavSvgOpen = false;
// -----create a backdrop overlay ------
this.ele.backdrop = document.createElement('div');
this.ele.backdrop.id = 'nav-backdrop';
this.ele.app.appendChild( this.ele.backdrop );
// add event listener to close nav
this.ele.backdrop.addEventListener('click',function(e){
NavAction.toggle('close');
});
this._onChange();
}
componentWillUnmount() {
NavStore.removeChangeListener(this._onChange);
}
_onChange() {
NavStore.getState().isNavOpen ? openNav() : closeNav();
}
onToggle() {
NavAction.toggle();
}
render() {
let svgString = '<svg version="1.1" xmlns="http://www.w3.org/2000/svg" x="0px" y="0px" width="64px" height="64px" viewBox="0 0 64 64" enable-background="new 0 0 64 64" xmlns:xlink="http://www.w3.org/1999/xlink" xml:space="preserve"> \
<path class="uac-circle" fill="none" stroke-width="2" stroke-miterlimit="10" d="M16,32h32c0,0,11.723-0.306,10.75-11c-0.25-2.75-1.644-4.971-2.869-7.151C50.728,7.08,42.767,2.569,33.733,2.054C33.159,2.033,32.599,2,32,2C15.432,2,2,15.432,2,32c0,16.566,13.432,30,30,30c16.566,0,30-13.434,30-30C62,15.5,48.5,2,32,2S1.875,15.5,1.875,32"></path> \
</svg> ';
let navSvg = '<svg data-points-hover="114.9,800.5 20,800.5 114.9,0 114.9,0 " id="nav-svg" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 115.9 800" style="enable-background:new 0 0 115.9 800;" xml:space="preserve"> \
</svg>';
return (
<div>
<nav id="nav">
<ul>
<li><Link to="home">Home</Link></li>
<li><Link to="projectList">Projects</Link></li>
<li><a href="http://blog.codinglife.in">Blog</a></li>
<li><Link to="about">About</Link></li>
</ul>
<div id="nav-bottom">
<ul id="gf-nav-social-link">
<li><a href="http://github.com/shadowzheng" target="_blank">Github</a></li>
<li><a href="http://weibo.com/" target="_blank">Weibo</a></li>
<li><a href="http://www.zhihu.com/" target="_blank">知乎</a></li>
</ul>
</div>
<div id="nav-svg-wrap" dangerouslySetInnerHTML={{__html: navSvg }}></div>
</nav>
<div id="nav-toggle" className="uac-toggle-barcircle" onClick={this.onToggle}>
<div className="uac-top"></div>
<div dangerouslySetInnerHTML={{__html: svgString }}></div>
<div className="uac-bottom"></div>
</div>
</div>
)
}
} |
__tests__/collection.js | arjunkomath/mjuzik | import 'react-native';
import React from 'react';
import Collection from '../app/components/collection';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Collection />
);
});
|
jqwidgets/jqwidgets-react/react_jqxtabs.js | UCF/IKM-APIM | /*
jQWidgets v5.6.0 (2018-Feb)
Copyright (c) 2011-2017 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxTabs extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['animationType','autoHeight','closeButtonSize','collapsible','contentTransitionDuration','disabled','enabledHover','enableScrollAnimation','enableDropAnimation','height','initTabContent','keyboardNavigation','next','previous','position','reorder','rtl','scrollAnimationDuration','selectedItem','selectionTracker','scrollable','scrollPosition','scrollStep','showCloseButtons','toggleMode','theme','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxTabs(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxTabs('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxTabs(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
animationType(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('animationType', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('animationType');
}
};
autoHeight(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('autoHeight', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('autoHeight');
}
};
closeButtonSize(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('closeButtonSize', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('closeButtonSize');
}
};
collapsible(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('collapsible', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('collapsible');
}
};
contentTransitionDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('contentTransitionDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('contentTransitionDuration');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('disabled');
}
};
enabledHover(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('enabledHover', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('enabledHover');
}
};
enableScrollAnimation(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('enableScrollAnimation', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('enableScrollAnimation');
}
};
enableDropAnimation(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('enableDropAnimation', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('enableDropAnimation');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('height', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('height');
}
};
initTabContent(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('initTabContent', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('initTabContent');
}
};
keyboardNavigation(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('keyboardNavigation', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('keyboardNavigation');
}
};
next(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('next', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('next');
}
};
previous(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('previous', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('previous');
}
};
position(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('position', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('position');
}
};
reorder(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('reorder', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('reorder');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('rtl');
}
};
scrollAnimationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('scrollAnimationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('scrollAnimationDuration');
}
};
selectedItem(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('selectedItem', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('selectedItem');
}
};
selectionTracker(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('selectionTracker', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('selectionTracker');
}
};
scrollable(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('scrollable', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('scrollable');
}
};
scrollPosition(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('scrollPosition', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('scrollPosition');
}
};
scrollStep(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('scrollStep', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('scrollStep');
}
};
showCloseButtons(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('showCloseButtons', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('showCloseButtons');
}
};
toggleMode(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('toggleMode', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('toggleMode');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('theme');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxTabs('width', arg)
} else {
return JQXLite(this.componentSelector).jqxTabs('width');
}
};
addAt(index, title, content) {
JQXLite(this.componentSelector).jqxTabs('addAt', index, title, content);
};
addFirst(htmlElement) {
JQXLite(this.componentSelector).jqxTabs('addFirst', htmlElement);
};
addLast(htmlElement1, htmlElemen2t) {
JQXLite(this.componentSelector).jqxTabs('addLast', htmlElement1, htmlElemen2t);
};
collapse() {
JQXLite(this.componentSelector).jqxTabs('collapse');
};
disable() {
JQXLite(this.componentSelector).jqxTabs('disable');
};
disableAt(index) {
JQXLite(this.componentSelector).jqxTabs('disableAt', index);
};
destroy() {
JQXLite(this.componentSelector).jqxTabs('destroy');
};
ensureVisible(index) {
JQXLite(this.componentSelector).jqxTabs('ensureVisible', index);
};
enableAt(index) {
JQXLite(this.componentSelector).jqxTabs('enableAt', index);
};
expand() {
JQXLite(this.componentSelector).jqxTabs('expand');
};
enable() {
JQXLite(this.componentSelector).jqxTabs('enable');
};
focus() {
JQXLite(this.componentSelector).jqxTabs('focus');
};
getTitleAt(index) {
return JQXLite(this.componentSelector).jqxTabs('getTitleAt', index);
};
getContentAt(index) {
return JQXLite(this.componentSelector).jqxTabs('getContentAt', index);
};
getDisabledTabsCount() {
return JQXLite(this.componentSelector).jqxTabs('getDisabledTabsCount');
};
hideCloseButtonAt(index) {
JQXLite(this.componentSelector).jqxTabs('hideCloseButtonAt', index);
};
hideAllCloseButtons() {
JQXLite(this.componentSelector).jqxTabs('hideAllCloseButtons');
};
length() {
return JQXLite(this.componentSelector).jqxTabs('length');
};
removeAt(index) {
JQXLite(this.componentSelector).jqxTabs('removeAt', index);
};
removeFirst() {
JQXLite(this.componentSelector).jqxTabs('removeFirst');
};
removeLast() {
JQXLite(this.componentSelector).jqxTabs('removeLast');
};
select(index) {
JQXLite(this.componentSelector).jqxTabs('select', index);
};
setContentAt(index, htmlElement) {
JQXLite(this.componentSelector).jqxTabs('setContentAt', index, htmlElement);
};
setTitleAt(index, htmlElement) {
JQXLite(this.componentSelector).jqxTabs('setTitleAt', index, htmlElement);
};
showCloseButtonAt(index) {
JQXLite(this.componentSelector).jqxTabs('showCloseButtonAt', index);
};
showAllCloseButtons() {
JQXLite(this.componentSelector).jqxTabs('showAllCloseButtons');
};
val(value) {
if (value !== undefined) {
JQXLite(this.componentSelector).jqxTabs('val', value)
} else {
return JQXLite(this.componentSelector).jqxTabs('val');
}
};
render() {
let id = 'jqxTabs' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
src/components/PaginationControls/PaginationControls.stories.js | austinknight/ui-components | import React from "react";
import styled from "styled-components";
import { storiesOf, action } from "@storybook/react";
import PaginationControls from "./PaginationControls";
import {
renderThemeIfPresentOrDefault,
wrapComponentWithContainerAndTheme,
colors
} from "../styles";
const Wrapper = styled.div`
background-color: ${renderThemeIfPresentOrDefault({
key: "primary01",
defaultValue: "black"
})};
padding: 10px;
`;
class StatefulWrapper extends React.Component {
constructor() {
super();
this.state = { page: 1 };
}
render = () => {
console.log(this.state.page);
return (
<PaginationControls
currentPage={this.state.page}
totalPages={100}
advanceAPage={e => {
this.setState({ page: this.state.page + 1 });
action("advanceAPage")(e);
}}
goBackAPage={e => {
this.setState({ page: this.state.page - 1 });
action("goBackAPage")(e);
}}
isRequestPageValid={e => {
action("isRequestPageValid")(e);
return true;
}}
requestPage={page => {
this.setState({ page });
action("requestPage")(page);
}}
/>
);
};
}
function renderChapterWithTheme(theme) {
return {
info: `
Usage
~~~
import React from 'react';
import {PaginationControls} from 'insidesales-components';
~~~
`,
chapters: [
{
sections: [
{
title: "Basic PaginationControls",
sectionFn: () =>
wrapComponentWithContainerAndTheme(
theme,
<Wrapper>
<StatefulWrapper />
</Wrapper>
)
},
{
title: "PaginationControls with one page",
sectionFn: () =>
wrapComponentWithContainerAndTheme(
theme,
<Wrapper>
<PaginationControls
currentPage={1}
totalPages={1}
advanceAPage={action("advanceAPage")}
goBackAPage={action("goBackAPage")}
isRequestPageValid={action("isRequestPageValid")}
requestPage={action("requestPage")}
/>
</Wrapper>
)
}
]
}
]
};
}
storiesOf("Components", module)
.addWithChapters("Default PaginationControls", renderChapterWithTheme({}))
.addWithChapters(
"PaginationControls w/ BlueYellow Theme",
renderChapterWithTheme(colors.blueYellowTheme)
);
|
containers/SetupScreenContainer.js | sayakbiswas/Git-Blogger | import React from 'react';
import globalVars from '../config/globalVars';
import SetupScreen from '../components/SetupScreen';
import GitHubAPIUtils from '../utils/GitHubAPIUtils';
class SetupScreenContainer extends React.Component {
constructor(props) {
super(props);
}
render() {
console.log('rendering');
return(
<SetupScreen />
);
}
}
module.exports = SetupScreenContainer;
|
src/components/chat/Chat.js | mBeierl/Better-Twitch-Chat | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
import firebase from 'firebase';
import ReactCSSTransitionGroup from 'react-addons-css-transition-group';
import { Card, CardTitle, CardText, CardActions } from 'material-ui/Card';
import TextField from 'material-ui/TextField';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import RaisedButton from 'material-ui/RaisedButton';
import IconMessage from 'material-ui/svg-icons/communication/message';
import Popover from 'material-ui/Popover';
import Twitch from '../../api/Twitch';
import NeuralNet from '../../api/NeuralNet';
import Message from './Message';
import MessagesContainer from './MessagesContainer';
import { uiActions, chatActions } from '../../redux/actions';
import './Chat.css';
class Chat extends Component {
constructor(props) {
super(props);
this.messagesRef = null;
this.numMsgsShowing = 10;
this.state = {
open: false
};
}
_connectToTwitch(identity) {
const { dispatch } = this.props;
const channel = this.props.match.params.channel;
dispatch(uiActions.setCurrentChannel(channel));
if (identity) Twitch.login(identity);
Twitch.join(channel);
}
componentDidMount() {
this._connectToTwitch();
}
componentDidUpdate() {
const { user } = this.props;
if (!this.messagesRef && user.firebaseUser) {
this.messagesRef = firebase
.database()
.ref(`messages/${user.firebaseUser.uid}/`);
}
if (
(!Twitch || !Twitch.client.getOptions().identity.password) &&
user.twitchToken &&
user.twitchUser &&
Twitch.client.readyState() === 'OPEN'
) {
this._connectToTwitch({
username: user.twitchUser.name,
password: user.twitchToken
});
}
}
showSendMessageInterface = event => {
// This prevents ghost click.
event.preventDefault();
this.setState({
...this.state,
open: true,
anchorEl: event.currentTarget
});
};
handleRequestClose = () => {
this.setState({
...this.state,
open: false
});
};
sendMessage = () => {
const { dispatch, ui } = this.props;
if (ui.messageInput) {
dispatch(uiActions.setMessageInput(''));
Twitch.client.say(`${this.props.match.params.channel}`, ui.messageInput);
}
};
_renderMessageInterface() {
const { user, ui, dispatch } = this.props;
const isLoggedIn =
user.firebaseUser && !user.firebaseUser.isAnonymous && user.twitchUser;
return (
<div>
<FloatingActionButton
onTouchTap={this.showSendMessageInterface}
disabled={!isLoggedIn}
style={{
position: 'fixed',
bottom: '1rem',
right: '1rem',
zIndex: '9999'
}}
>
<IconMessage />
</FloatingActionButton>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}
targetOrigin={{ horizontal: 'left', vertical: 'top' }}
onRequestClose={this.handleRequestClose}
style={{ width: '300px', height: '200px', padding: '1rem' }}
>
<TextField
autoFocus={true}
className="Message-Input"
disabled={!isLoggedIn}
hintText="Kappa"
floatingLabelText="Send Chat-Message"
onChange={(event, newVal) =>
dispatch(uiActions.setMessageInput(newVal))}
value={ui.messageInput}
onKeyPress={event => {
if (event.charCode === 13) {
event.preventDefault();
this.sendMessage();
}
}}
/>
<RaisedButton
label="Send"
fullWidth={true}
primary={true}
disabled={!isLoggedIn || !ui.messageInput}
onTouchTap={this.sendMessage}
/>
</Popover>
</div>
);
}
render() {
const { ui, user, dispatch } = this.props;
return (
<div className="container-center">
<Card className="container">
<CardTitle
title={`Chat: ${ui.currentChannel}`}
subtitle="Vote up or down to further train your model"
/>
<CardText>
<div className="Chat">
{NeuralNet.isTrained()
? ''
: <Link to="/train">
<RaisedButton
label="Train Neural Network"
fullWidth={true}
secondary={true}
onTouchTap={this.onRetrainModelClick}
/>
</Link>}
<ReactCSSTransitionGroup
component={MessagesContainer}
transitionName="example"
transitionEnterTimeout={400}
transitionLeaveTimeout={300}
>
{ui.messages.map((msg, idx) =>
<Message
key={msg.user['tmi-sent-ts'] + msg.user['user-id']}
message={msg.text}
user={msg.user}
channel={msg.channel}
voted={msg.voted}
showVote={user.training}
onLikeMsg={msg => {
dispatch(uiActions.votedOnMessage(idx));
if (this.messagesRef)
this.messagesRef
.push({ message: msg, liked: true })
.once('value')
.then(snapshot =>
dispatch(
uiActions.setVotedMessage(
snapshot.key,
snapshot.val()
)
)
);
}}
onDislikeMsg={msg => {
// TODO add to votedMessages accordingly
dispatch(uiActions.votedOnMessage(idx));
if (this.messagesRef)
this.messagesRef
.push({ message: msg, liked: false })
.once('value')
.then(snapshot =>
dispatch(
uiActions.setVotedMessage(
snapshot.key,
snapshot.val()
)
)
);
}}
/>
)}
</ReactCSSTransitionGroup>
{this._renderMessageInterface()}
</div>
</CardText>
</Card>
{this._renderMessageInterface()}
</div>
);
}
}
export default connect(state => ({
ui: state.ui,
user: state.user
}))(Chat);
|
src/svg-icons/av/explicit.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvExplicit = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-4 6h-4v2h4v2h-4v2h4v2H9V7h6v2z"/>
</SvgIcon>
);
AvExplicit = pure(AvExplicit);
AvExplicit.displayName = 'AvExplicit';
AvExplicit.muiName = 'SvgIcon';
export default AvExplicit;
|
app/javascript/client_messenger/gdprView.js | michelson/chaskiq | import React from 'react'
import styled from '@emotion/styled'
import tw from 'twin.macro'
export const Wrapper = styled.div`
top: 0px;
z-index: 999999;
position: fixed;
width: 100%;
height: 100vh;
background: white;
//font-size: .92em;
//line-height: 1.5em;
//color: #eee;
`
export const Padder = tw.div`px-4 py-5 sm:p-6 overflow-auto h-full`
export const Title = tw.div`text-lg leading-6 font-medium text-gray-900`
export const TextContent = tw.div`space-y-4 mt-2 max-w-xl text-sm text-gray-800`
export const ButtonWrapped = tw.div`my-3 text-sm flex justify-between items-center`
export const Link = tw.a`font-medium text-gray-600 hover:text-gray-500`
export const Button = tw.button`inline-flex items-center justify-center px-4
py-2 border border-transparent font-medium rounded-md text-green-700 bg-green-100
hover:bg-green-200 focus:outline-none focus:ring-2 focus:ring-offset-2
focus:ring-green-500 sm:text-sm`
export const ButtonCancel = tw.button`inline-flex items-center justify-center px-4
py-2 border border-transparent font-medium rounded-md text-gray-700 bg-gray-100
hover:bg-gray-200 focus:outline-none focus:ring-2 focus:ring-offset-2
focus:ring-gray-500 sm:text-sm`
export default function View ({ confirm, cancel, t, app }) {
return (
<Wrapper>
<Padder>
<Title>
{t('gdpr_title')}
</Title>
<TextContent dangerouslySetInnerHTML={
{ __html: t('gdpr', { name: app.name }) }
}>
</TextContent>
<ButtonWrapped>
<Button onClick={confirm}>
{t('gdpr_ok')}
</Button>
<ButtonCancel onClick={cancel}>
{t('gdpr_nok')}
</ButtonCancel>
</ButtonWrapped>
{/* <Link href="#">
View our privacy police here <span aria-hidden="true">→</span>
</Link> */}
</Padder>
</Wrapper>
)
}
|
frontend/src/Components/Menu/FilterMenuContent.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import FilterMenuItem from './FilterMenuItem';
import MenuContent from './MenuContent';
import MenuItem from './MenuItem';
import MenuItemSeparator from './MenuItemSeparator';
class FilterMenuContent extends Component {
//
// Render
render() {
const {
selectedFilterKey,
filters,
customFilters,
showCustomFilters,
onFilterSelect,
onCustomFiltersPress,
...otherProps
} = this.props;
return (
<MenuContent {...otherProps}>
{
filters.map((filter) => {
return (
<FilterMenuItem
key={filter.key}
filterKey={filter.key}
selectedFilterKey={selectedFilterKey}
onPress={onFilterSelect}
>
{filter.label}
</FilterMenuItem>
);
})
}
{
customFilters.map((filter) => {
return (
<FilterMenuItem
key={filter.id}
filterKey={filter.id}
selectedFilterKey={selectedFilterKey}
onPress={onFilterSelect}
>
{filter.label}
</FilterMenuItem>
);
})
}
{
showCustomFilters &&
<MenuItemSeparator />
}
{
showCustomFilters &&
<MenuItem onPress={onCustomFiltersPress}>
Custom Filters
</MenuItem>
}
</MenuContent>
);
}
}
FilterMenuContent.propTypes = {
selectedFilterKey: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
filters: PropTypes.arrayOf(PropTypes.object).isRequired,
customFilters: PropTypes.arrayOf(PropTypes.object).isRequired,
showCustomFilters: PropTypes.bool.isRequired,
onFilterSelect: PropTypes.func.isRequired,
onCustomFiltersPress: PropTypes.func.isRequired
};
FilterMenuContent.defaultProps = {
showCustomFilters: false
};
export default FilterMenuContent;
|
src/svg-icons/action/payment.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPayment = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4v-6h16v6zm0-10H4V6h16v2z"/>
</SvgIcon>
);
ActionPayment = pure(ActionPayment);
ActionPayment.displayName = 'ActionPayment';
ActionPayment.muiName = 'SvgIcon';
export default ActionPayment;
|
docs/src/app/components/pages/components/DatePicker/ExampleControlled.js | hwo411/material-ui | import React from 'react';
import DatePicker from 'material-ui/DatePicker';
/**
* `DatePicker` can be implemented as a controlled input,
* where `value` is handled by state in the parent component.
*/
export default class DatePickerExampleControlled extends React.Component {
constructor(props) {
super(props);
this.state = {
controlledDate: null,
};
}
handleChange = (event, date) => {
this.setState({
controlledDate: date,
});
};
render() {
return (
<DatePicker
hintText="Controlled Date Input"
value={this.state.controlledDate}
onChange={this.handleChange}
/>
);
}
}
|
test/specs/table/table_row.spec.js | rafaelfbs/realizejs | import React from 'react';
import { TableRow } from 'components/table';
import { assert } from 'chai';
import { mount } from 'enzyme';
describe('<TableRow/>', () => {
it('exists', () => {
assert(TableRow);
});
it('renders with the default props', () => {
const renderedTableRow = mount(
<table>
<tbody>
<TableRow />
</tbody>
</table>
);
assert(renderedTableRow.find('TableRow'));
});
});
|
examples/example2.js | gabrielbull/react-tether2 | import React, { Component } from 'react';
import Target from './example2/target';
const style = {
position: 'fixed',
top: '0px',
left: '0px',
width: '100%',
height: '50px',
display: 'flex',
justifyContent: 'center'
};
class Example2 extends Component {
render() {
return (
<div style={style}>
<Target/>
</div>
);
}
}
export default Example2;
|
packages/icons/src/md/content/LowPriority.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdLowPriority(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M28 9h16v4H28V9zm0 11h16v4H28v-4zm0 11h16v4H28v-4zM4 22c0 7.17 5.83 13 13 13h1v4l6-6-6-6v4h-1c-4.96 0-9-4.04-9-9s4.04-9 9-9h7V9h-7C9.83 9 4 14.83 4 22z" />
</IconBase>
);
}
export default MdLowPriority;
|
app/javascript/mastodon/components/column.js | musashino205/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { supportsPassiveEvents } from 'detect-passive-events';
import { scrollTop } from '../scroll';
export default class Column extends React.PureComponent {
static propTypes = {
children: PropTypes.node,
label: PropTypes.string,
bindToDocument: PropTypes.bool,
};
scrollTop () {
const scrollable = this.props.bindToDocument ? document.scrollingElement : this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = c => {
this.node = c;
}
componentDidMount () {
if (this.props.bindToDocument) {
document.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false);
} else {
this.node.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false);
}
}
componentWillUnmount () {
if (this.props.bindToDocument) {
document.removeEventListener('wheel', this.handleWheel);
} else {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
render () {
const { label, children } = this.props;
return (
<div role='region' aria-label={label} className='column' ref={this.setRef}>
{children}
</div>
);
}
}
|
src/svg-icons/communication/chat-bubble.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationChatBubble = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
CommunicationChatBubble = pure(CommunicationChatBubble);
CommunicationChatBubble.displayName = 'CommunicationChatBubble';
CommunicationChatBubble.muiName = 'SvgIcon';
export default CommunicationChatBubble;
|
src/layouts/PageLayout/PageLayout.js | larsdolvik/portfolio | import React from 'react'
import {IndexLink, Link} from 'react-router'
import PropTypes from 'prop-types'
import './PageLayout.scss'
export const PageLayout = ({children}) => (
<div className='container text-center'>
<h1>Lars Bendik Dølvik</h1>
<IndexLink to='/' activeClassName='page-layout__nav-item--active'>
<button className="button">Home</button>
</IndexLink>
{' · '}
<Link to='/projects' activeClassName='page-layout__nav-item--active'>
<button className="button">Projects</button>
</Link>
{' · '}
<Link to='/aboutme' activeClassName='page-layout__nav-item--active'>
<button className="button">About me</button>
</Link>
{/* <Link to='/counter' activeClassName='page-layout__nav-item--active'><button className="button">Counter</button></Link> */}
<div className='page-layout__viewport'>
{children}
</div>
<footer>
Made by Lars Dølvik
</footer>
</div>
)
PageLayout.propTypes = {
children: PropTypes.node
}
export default PageLayout
|
test/CarouselSpec.js | blue68/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Carousel from '../src/Carousel';
import CarouselItem from '../src/CarouselItem';
describe('Carousel', () => {
it('Should show the correct item', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={1}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
<CarouselItem ref="item2">Item 2 content</CarouselItem>
</Carousel>
);
assert.equal(instance.refs.item1.props.active, false);
assert.equal(instance.refs.item2.props.active, true);
instance = ReactTestUtils.renderIntoDocument(
<Carousel defaultActiveIndex={1}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
<CarouselItem ref="item2">Item 2 content</CarouselItem>
</Carousel>
);
assert.equal(instance.refs.item1.props.active, false);
assert.equal(instance.refs.item2.props.active, true);
assert.equal(
ReactTestUtils.scryRenderedDOMComponentsWithTag(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'carousel-indicators'), 'li'
).length, 2
);
});
it('Should handle null children', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={1}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
{null}
{false}
<CarouselItem ref="item2">Item 2 content</CarouselItem>
</Carousel>
);
assert.equal(instance.refs.item1.props.active, false);
assert.equal(instance.refs.item2.props.active, true);
assert.equal(
ReactTestUtils.scryRenderedDOMComponentsWithTag(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'carousel-indicators'), 'li'
).length, 2
);
});
it('Should call onSelect when indicator selected', (done) => {
function onSelect(index, direction) {
assert.equal(index, 0);
assert.equal(direction, 'prev');
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={1} onSelect={onSelect}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
<CarouselItem ref="item2">Item 2 content</CarouselItem>
</Carousel>
);
ReactTestUtils.Simulate.click(
ReactTestUtils.scryRenderedDOMComponentsWithTag(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'carousel-indicators'), 'li'
)[0]
);
});
it('Should show all controls on the first/last image if wrap is true', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={0} controls={true} wrap={true}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
<CarouselItem ref="item2">Item 2 content</CarouselItem>
</Carousel>
);
let backButton = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'left');
assert.ok(backButton);
assert.equal(backButton.props.href, '#prev');
instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={1} controls={true} wrap={true}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
<CarouselItem ref="item2">Item 2 content</CarouselItem>
</Carousel>
);
let nextButton = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'right');
assert.ok(nextButton);
assert.equal(nextButton.props.href, '#next');
});
it('Should not show the prev button on the first image if wrap is false', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={0} controls={true} wrap={false}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
<CarouselItem ref="item2">Item 2 content</CarouselItem>
</Carousel>
);
let backButtons = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'left');
let nextButtons = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'right');
assert.equal(backButtons.length, 0);
assert.equal(nextButtons.length, 1);
});
it('Should allow user to specify a previous and next icon', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Carousel activeIndex={1} controls={true} wrap={false}
prevIcon={<span className='ficon ficon-left'/>}
nextIcon={<span className='ficon ficon-right'/>}>
<CarouselItem ref="item1">Item 1 content</CarouselItem>
<CarouselItem ref="item2">Item 2 content</CarouselItem>
<CarouselItem ref="item3">Item 3 content</CarouselItem>
</Carousel>
);
let backButtons = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'ficon-left');
let nextButtons = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'ficon-right');
assert.equal(backButtons.length, 1);
assert.equal(nextButtons.length, 1);
});
});
|
src/components/stories/Gallery.js | neontribe/spool | import React from 'react';
import { storiesOf } from '@kadira/storybook';
import { Gallery } from '../Gallery';
import { entries } from './fixtures';
const initialData = {
role: {
entries: {
edges: []
}
}
};
const entriesData = {
role: {
entries: {
edges: entries.map((e) => { return {node: e}; })
}
}
};
storiesOf('Gallery', module)
.add('Initial View', () => (
<Gallery viewer={initialData} />
))
.add('With entries', () => (
<Gallery viewer={entriesData} />
));
|
client/components/icons/icon-components/instagram-white.js | HelpAssistHer/help-assist-her | import React from 'react'
export default function InstagramWhite(props) {
return (
<svg
version="1.1"
id="Layer_1"
xmlns="http://www.w3.org/2000/svg"
xmlnsXlink="http://www.w3.org/1999/xlink"
x="0px"
y="0px"
viewBox="-6 -8 229 232"
enableBackground="new -6 -8 229 232"
xmlSpace="preserve"
width={229}
height={232}
{...props}
>
<g id="Symbols">
<g id="Instagram_White_Mobile">
<g id="Group">
<path
fill="#FFFFFF"
d="M108,218.7C47,218.7-2.7,169-2.7,108S47-2.7,108-2.7S218.7,47,218.7,108S169,218.7,108,218.7z M108,2.7C49.7,2.7,2.7,49.7,2.7,108s47,105.3,105.3,105.3s105.3-47,105.3-105.3S166.3,2.7,108,2.7z"
/>
<path
fill="#FFFFFF"
d="M108,88c-10.8,0-20,8.6-20,20c0,10.8,8.6,20,20,20s20-8.6,20-20C128,97.2,118.8,88,108,88L108,88zM108,82.6c14,0,25.4,11.3,25.4,25.4S122,133.4,108,133.4S82.6,122,82.6,108C82.6,94,94,82.6,108,82.6L108,82.6z M136.1,71.3c3.2,0,5.4,2.7,5.4,5.4c0,3.2-2.7,5.4-5.4,5.4c-3.2,0-5.4-2.7-5.4-5.4C130.7,74,132.8,71.3,136.1,71.3L136.1,71.3z M85.3,62.6c-12.4,0-22.7,10.3-22.7,22.7v45.4c0,12.4,10.3,22.7,22.7,22.7h45.4c12.4,0,22.7-10.3,22.7-22.7V85.3c0-12.4-10.3-22.7-22.7-22.7H85.3L85.3,62.6z M85.3,57.2h45.4c15.7,0,28.1,12.4,28.1,28.1v45.4c0,15.7-12.4,28.1-28.1,28.1H85.3c-15.7,0-28.1-12.4-28.1-28.1V85.3C57.2,69.7,69.7,57.2,85.3,57.2L85.3,57.2z M78.3,45.9c-17.8,0-32.4,14.6-32.4,32.4v59.4c0,17.8,14.6,32.4,32.4,32.4h59.4c17.8,0,32.4-14.6,32.4-32.4V78.3c0-17.8-14.6-32.4-32.4-32.4H78.3L78.3,45.9z"
/>
</g>
</g>
</g>
</svg>
)
}
|
packages/react-instantsearch-dom/src/components/SearchBox.js | algolia/react-instantsearch | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { translatable } from 'react-instantsearch-core';
import { createClassNames } from '../core/utils';
const cx = createClassNames('SearchBox');
const defaultLoadingIndicator = (
<svg
width="18"
height="18"
viewBox="0 0 38 38"
xmlns="http://www.w3.org/2000/svg"
stroke="#444"
className={cx('loadingIcon')}
>
<g fill="none" fillRule="evenodd">
<g transform="translate(1 1)" strokeWidth="2">
<circle strokeOpacity=".5" cx="18" cy="18" r="18" />
<path d="M36 18c0-9.94-8.06-18-18-18">
<animateTransform
attributeName="transform"
type="rotate"
from="0 18 18"
to="360 18 18"
dur="1s"
repeatCount="indefinite"
/>
</path>
</g>
</g>
</svg>
);
const defaultReset = (
<svg
className={cx('resetIcon')}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 20 20"
width="10"
height="10"
>
<path d="M8.114 10L.944 2.83 0 1.885 1.886 0l.943.943L10 8.113l7.17-7.17.944-.943L20 1.886l-.943.943-7.17 7.17 7.17 7.17.943.944L18.114 20l-.943-.943-7.17-7.17-7.17 7.17-.944.943L0 18.114l.943-.943L8.113 10z" />
</svg>
);
const defaultSubmit = (
<svg
className={cx('submitIcon')}
xmlns="http://www.w3.org/2000/svg"
width="10"
height="10"
viewBox="0 0 40 40"
>
<path d="M26.804 29.01c-2.832 2.34-6.465 3.746-10.426 3.746C7.333 32.756 0 25.424 0 16.378 0 7.333 7.333 0 16.378 0c9.046 0 16.378 7.333 16.378 16.378 0 3.96-1.406 7.594-3.746 10.426l10.534 10.534c.607.607.61 1.59-.004 2.202-.61.61-1.597.61-2.202.004L26.804 29.01zm-10.426.627c7.323 0 13.26-5.936 13.26-13.26 0-7.32-5.937-13.257-13.26-13.257C9.056 3.12 3.12 9.056 3.12 16.378c0 7.323 5.936 13.26 13.258 13.26z" />
</svg>
);
class SearchBox extends Component {
static propTypes = {
currentRefinement: PropTypes.string,
className: PropTypes.string,
refine: PropTypes.func.isRequired,
translate: PropTypes.func.isRequired,
loadingIndicator: PropTypes.node,
reset: PropTypes.node,
submit: PropTypes.node,
focusShortcuts: PropTypes.arrayOf(
PropTypes.oneOfType([PropTypes.string, PropTypes.number])
),
autoFocus: PropTypes.bool,
searchAsYouType: PropTypes.bool,
onSubmit: PropTypes.func,
onReset: PropTypes.func,
onChange: PropTypes.func,
isSearchStalled: PropTypes.bool,
showLoadingIndicator: PropTypes.bool,
inputRef: PropTypes.oneOfType([
PropTypes.func,
PropTypes.exact({ current: PropTypes.object }),
]),
inputId: PropTypes.string,
};
static defaultProps = {
currentRefinement: '',
className: '',
focusShortcuts: ['s', '/'],
autoFocus: false,
searchAsYouType: true,
showLoadingIndicator: false,
isSearchStalled: false,
loadingIndicator: defaultLoadingIndicator,
reset: defaultReset,
submit: defaultSubmit,
};
constructor(props) {
super();
this.state = {
query: props.searchAsYouType ? null : props.currentRefinement,
};
}
componentDidMount() {
document.addEventListener('keydown', this.onKeyDown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.onKeyDown);
}
componentDidUpdate(prevProps) {
if (
!this.props.searchAsYouType &&
prevProps.currentRefinement !== this.props.currentRefinement
) {
this.setState({
query: this.props.currentRefinement,
});
}
}
getQuery = () =>
this.props.searchAsYouType
? this.props.currentRefinement
: this.state.query;
onInputMount = (input) => {
this.input = input;
if (!this.props.inputRef) return;
if (typeof this.props.inputRef === 'function') {
this.props.inputRef(input);
} else {
this.props.inputRef.current = input;
}
};
// From https://github.com/algolia/autocomplete.js/pull/86
onKeyDown = (e) => {
if (!this.props.focusShortcuts) {
return;
}
const shortcuts = this.props.focusShortcuts.map((key) =>
typeof key === 'string' ? key.toUpperCase().charCodeAt(0) : key
);
const elt = e.target || e.srcElement;
const tagName = elt.tagName;
if (
elt.isContentEditable ||
tagName === 'INPUT' ||
tagName === 'SELECT' ||
tagName === 'TEXTAREA'
) {
// already in an input
return;
}
const which = e.which || e.keyCode;
if (shortcuts.indexOf(which) === -1) {
// not the right shortcut
return;
}
this.input.focus();
e.stopPropagation();
e.preventDefault();
};
onSubmit = (e) => {
e.preventDefault();
e.stopPropagation();
this.input.blur();
const { refine, searchAsYouType } = this.props;
if (!searchAsYouType) {
refine(this.getQuery());
}
return false;
};
onChange = (event) => {
const { searchAsYouType, refine, onChange } = this.props;
const value = event.target.value;
if (searchAsYouType) {
refine(value);
} else {
this.setState({ query: value });
}
if (onChange) {
onChange(event);
}
};
onReset = (event) => {
const { searchAsYouType, refine, onReset } = this.props;
refine('');
this.input.focus();
if (!searchAsYouType) {
this.setState({ query: '' });
}
if (onReset) {
onReset(event);
}
};
render() {
const {
className,
inputId,
translate,
autoFocus,
loadingIndicator,
submit,
reset,
} = this.props;
const query = this.getQuery();
const searchInputEvents = Object.keys(this.props).reduce((props, prop) => {
if (
['onsubmit', 'onreset', 'onchange'].indexOf(prop.toLowerCase()) ===
-1 &&
prop.indexOf('on') === 0
) {
return { ...props, [prop]: this.props[prop] };
}
return props;
}, {});
const isSearchStalled =
this.props.showLoadingIndicator && this.props.isSearchStalled;
return (
<div className={classNames(cx(''), className)}>
<form
noValidate
onSubmit={this.props.onSubmit ? this.props.onSubmit : this.onSubmit}
onReset={this.onReset}
className={cx('form', isSearchStalled && 'form--stalledSearch')}
action=""
role="search"
>
<input
ref={this.onInputMount}
id={inputId}
type="search"
placeholder={translate('placeholder')}
autoFocus={autoFocus}
autoComplete="off"
autoCorrect="off"
autoCapitalize="off"
spellCheck="false"
required
maxLength="512"
value={query}
onChange={this.onChange}
{...searchInputEvents}
className={cx('input')}
/>
<button
type="submit"
title={translate('submitTitle')}
className={cx('submit')}
>
{submit}
</button>
<button
type="reset"
title={translate('resetTitle')}
className={cx('reset')}
hidden={!query || isSearchStalled}
>
{reset}
</button>
{this.props.showLoadingIndicator && (
<span hidden={!isSearchStalled} className={cx('loadingIndicator')}>
{loadingIndicator}
</span>
)}
</form>
</div>
);
}
}
export default translatable({
resetTitle: 'Clear the search query.',
submitTitle: 'Submit your search query.',
placeholder: 'Search here…',
})(SearchBox);
|
docs/app/Examples/modules/Checkbox/States/CheckboxExampleChecked.js | mohammed88/Semantic-UI-React | import React from 'react'
import { Checkbox } from 'semantic-ui-react'
const CheckboxExampleChecked = () => (
<Checkbox label='This checkbox comes pre-checked' defaultChecked />
)
export default CheckboxExampleChecked
|
src/components/Loading/Loading.js | MinisterioPublicoRJ/inLoco-2.0 | import React from 'react'
const Loading = ({ layers, showLoader, downloadLoader }) => {
let loadingClass = 'module-loading'
if (!showLoader && showLoader !== undefined) {
loadingClass += ' hidden'
}
if (downloadLoader && downloadLoader === true) {
loadingClass = 'module-loading'
}
return (
<div className={loadingClass}>
<div className="spinner">
<i className="fa fa-spinner fa-spin" aria-hidden="true"></i><br />
Carregando...</div>
</div>
)
}
export default Loading
|
node_modules/react-bootstrap/es/MediaRight.js | Technaesthetic/ua-tools | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import Media from './Media';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
/**
* Align the media to the top, middle, or bottom of the media object.
*/
align: React.PropTypes.oneOf(['top', 'middle', 'bottom'])
};
var MediaRight = function (_React$Component) {
_inherits(MediaRight, _React$Component);
function MediaRight() {
_classCallCheck(this, MediaRight);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaRight.prototype.render = function render() {
var _props = this.props,
align = _props.align,
className = _props.className,
props = _objectWithoutProperties(_props, ['align', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
if (align) {
// The class is e.g. `media-top`, not `media-right-top`.
classes[prefix(Media.defaultProps, align)] = true;
}
return React.createElement('div', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaRight;
}(React.Component);
MediaRight.propTypes = propTypes;
export default bsClass('media-right', MediaRight); |
app/javascript/components/RoundMap/Map/ReferencePoints/index.js | skyderby/skyderby | import React from 'react'
import { useSelector } from 'react-redux'
import { selectAssignedReferencePoints } from 'redux/events/round/selectors'
import Marker from './Marker'
const ReferencePoints = () => {
const referencePoints = useSelector(selectAssignedReferencePoints)
return (
<>
{referencePoints.map(el => (
<Marker key={el.id} {...el} />
))}
</>
)
}
export default ReferencePoints
|
test/components/counter.spec.js | TYRONEMICHAEL/recompose | import test from 'tape';
import sinon from 'sinon';
import createDocument from '../utils/createDocument';
import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-addons-test-utils';
import counterFactory from '../../src/components/counter';
function setup() {
const document = createDocument();
const Counter = counterFactory(React);
const container = document.createElement('div');
const actions = {
increment: sinon.spy(),
incrementIfOdd: sinon.spy(),
incrementAsync: sinon.spy(),
decrement: sinon.spy()
};
ReactDOM.render(<Counter counter={1} {...actions} />, container);
return {
actions: actions,
container: container
};
};
test('Counter component', (t) => {
t.test('should display count', (t) => {
const { container } = setup();
const count = container.getElementsByClassName('counter__value')[0];
t.equal(count.innerHTML, '1');
t.end();
});
t.test('increment button should call increment action', (t) => {
const { actions, container } = setup();
const btn = container.getElementsByClassName('counter__increment')[0];
ReactTestUtils.Simulate.click(btn);
t.equal(actions.increment.calledOnce, true, );
t.end();
});
t.test('decrement button should call decrement action', (t) => {
const { actions, container } = setup();
const btn = container.getElementsByClassName('counter__decrement')[0];
ReactTestUtils.Simulate.click(btn);
t.equal(actions.decrement.calledOnce, true, );
t.end();
});
t.test('odd button should call incrementIfOdd action', (t) => {
const { actions, container } = setup();
const btn = container.getElementsByClassName('counter__odd')[0];
ReactTestUtils.Simulate.click(btn);
t.equal(actions.incrementIfOdd.calledOnce, true, );
t.end();
});
t.end();
});
|
test/dummy/client/components/posts/record-expanded-content.js | factore/tenon | import React from 'react';
module.exports = (props) => {
const editPath = props.record.edit_path;
const onDelete = props.onDelete;
return (
<div className="record__expanded-content">
<div dangerouslySetInnerHTML={{ __html: props.record.excerpt }} />
<div className="record__expanded-actions">
<div className="record__expanded-action-text">
<a
className="action-text"
href={editPath}
title="Edit">
Edit
</a>
</div>
<div className="record__expanded-action-text">
<a
className="action-text"
onClick={onDelete}
href="#!"
title="Delete">
Delete
</a>
</div>
</div>
</div>
);
};
|
docs/app/Examples/collections/Table/States/TableExampleWarningShorthand.js | shengnian/shengnian-ui-react | import React from 'react'
import { Table } from 'shengnian-ui-react'
const tableData = [
{ name: undefined, status: undefined, notes: undefined },
{ name: 'Jimmy', status: 'Requires Action', notes: undefined },
{ name: 'Jamie', status: undefined, notes: 'Hostile' },
{ name: 'Jill', status: undefined, notes: undefined },
]
const headerRow = [
'Name',
'Status',
'Notes',
]
const renderBodyRow = ({ name, status, notes }, i) => ({
key: name || `row-${i}`,
warning: !!(status && status.match('Requires Action')),
cells: [
name || 'No name specified',
status
? { key: 'status', icon: 'attention', content: status }
: 'Unknown',
notes
? { key: 'notes', icon: 'attention', content: notes, warning: true }
: 'None',
],
})
const TableExampleWarningShorthand = () => (
<Table
celled
headerRow={headerRow}
renderBodyRow={renderBodyRow}
tableData={tableData}
/>
)
export default TableExampleWarningShorthand
|
src/components/Gauge/Gauge.js | Zoomdata/nhtsa-dashboard-2.2 | import styles from './Gauge.css';
import React from 'react';
import GaugeChart from '../GaugeChart/GaugeChart';
const Gauge = ({
name,
id,
data,
max
}) => {
return (
<div
className={styles.root}
id={id}
>
<GaugeChart
name={name}
data={data}
max={max}
/>
</div>
)
};
export default Gauge; |
src/components/Player/extensions/playerEvents.js | Magics-Group/throw-client | import {
throttle
}
from 'lodash';
import {
EventEmitter
}
from 'events';
import dns from 'dns'
import os from 'os'
import Promise from 'bluebird'
import {
remote
}
from 'electron'
import React from 'react'
import ReactQR from 'react-qr'
import socketIO from 'socket.io'
import getPort from 'get-port'
const getInternalIP = () => {
return new Promise((resolve, reject) => dns.lookup(os.hostname(), (err, add, fam) => {
if (err) return reject(err)
resolve(add)
}))
}
export default class PlayerEvents extends EventEmitter {
constructor(title) {
super()
this.title = title
this.on('wcjsLoaded', wcjs => {
this._wcjs = wcjs
this._wcjs.onPositionChanged = throttle(pos => this.emit('position', pos), 500)
this._wcjs.onOpening = () => this.emit('opening')
this._wcjs.onTimeChanged = time => this.emit('time', time)
this._wcjs.onBuffering = throttle(buf => this.emit('buffering', buf), 500)
this._wcjs.onLengthChanged = length => this.emit('length', length)
this._wcjs.onSeekableChanged = Seekable => this.emit('seekable', Seekable)
this._wcjs.onFrameRendered = (width, height) => {
const win = remote.getCurrentWindow()
win.setSize(width, height + 30)
win.center()
}
this._wcjs.onPlaying = () => this.emit('playing', true)
this._wcjs.onPaused = () => this.emit('playing', false)
this._wcjs.onStopped = () => this.emit('playing', false)
this._wcjs.onEndReached = () => this.emit('ended')
this._wcjs.onEncounteredError = err => this.emit('error', err)
this._wcjs.onMediaChanged = () => this.emit('changed')
})
this.on('scrobble', time => this._wcjs.time = time)
this.on('togglePause', () => this._wcjs.togglePause())
this.on('skipForward', () => this._wcjs.time += 30000)
this.on('skipBackward', () => this._wcjs.time -= 30000)
this.on('play', url => this._wcjs.play(url));
this.on('toggleMute', () => this._wcjs.toggleMute())
this.on('volumeChange', volume => {
this._wcjs.volume = volume
this.emit('volume', volume)
})
this.on('close', () => {
this._wcjs.stop()
const events = ['opening', 'position', 'qrCode', 'time', 'volume', 'buffering', 'length', 'seekable', 'playing', 'togglePause', 'ended', 'changed', 'mouseMove', 'closed']
events.forEach(event => this.removeAllListeners(event))
const win = remote.getCurrentWindow()
win.setKiosk(false)
win.setSize(575, 350)
win.setTitle(`Throw Player`)
win.center()
this.emit('closed')
})
this.PIN = parseInt(('0' + Math.floor(Math.random() * (9999 - 0 + 1)) + 0).substr(-4))
Promise.all([getInternalIP(), getPort()])
.spread((ip, port) => {
this.ioServer = socketIO()
this.ioServer.on('connection', socket => {
let authed = false
socket.on('pin', pin => {
authed = parseInt(pin) === parseInt(this.PIN)
})
socket.emit('title', this.title)
socket.on('position', percent => {
if (!authed) return
const scrobbleTime = this._wcjs.totalTime * percent
console.log(scrobbleTime)
})
socket.on('playing', () => {
if (authed) this.emit('togglePause')
})
socket.on('muted', () => {
if (authed) this.emit('toggleMute')
})
socket.on('forward', () => {
if (authed) this.emit('skipForward')
})
socket.on('backward', () => {
if (authed) this.emit('skipBackward')
})
this.on('position', position => socket.emit('position', position))
this.on('time', time => socket.emit('time', time))
this.on('length', length => socket.emit('length', length))
this.on('playing', playing => returnsocket.emit('playing', playing))
this.on('ended', () => socket.emit('ended'))
this.on('closed', () => {
socket.emit('ended')
socket.disconnect()
})
})
this.ioServer.listen(port)
console.log(`PlayerAPI socket server running @ ${ip}:${port} w/ PIN of ${this.PIN}`)
this.emit('qrCode', <ReactQR text={JSON.stringify({pin: this.PIN,ip,port})} />)
})
}
} |
src/index.js | hofnarwillie/weather-demo | /* eslint-disable import/default */
import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import {getWeather} from './actions/weatherActions';
import configureStore from './store/configureStore';
import { syncHistoryWithStore } from 'react-router-redux';
//styles
import './scss/index.scss';
//setup Redux
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
//initial data load
store.dispatch(getWeather());
//create React entry point
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>, document.getElementById('app')
);
|
docs/src/app/components/pages/components/DatePicker/ExampleInternational.js | w01fgang/material-ui | import React from 'react';
import DatePicker from 'material-ui/DatePicker';
import areIntlLocalesSupported from 'intl-locales-supported';
let DateTimeFormat;
/**
* Use the native Intl.DateTimeFormat if available, or a polyfill if not.
*/
if (areIntlLocalesSupported(['fr', 'fa-IR'])) {
DateTimeFormat = global.Intl.DateTimeFormat;
} else {
const IntlPolyfill = require('intl');
DateTimeFormat = IntlPolyfill.DateTimeFormat;
require('intl/locale-data/jsonp/fr');
require('intl/locale-data/jsonp/fa-IR');
}
/**
* `DatePicker` can be localised using the `locale` property. The first example is localised in French.
* Note that the buttons must be separately localised using the `cancelLabel` and `okLabel` properties.
*
* The second example shows `firstDayOfWeek` set to `0`, (Sunday), and `locale` to `en-US` which matches the
* behavior of the Date Picker prior to 0.15.0. Note that the 'en-US' locale is built in, and so does not require
* `DateTimeFormat` to be supplied.
*
* The final example displays the resulting date in a custom format using the `formatDate` property.
*/
const DatePickerExampleInternational = () => (
<div>
<DatePicker
hintText="fr locale"
DateTimeFormat={DateTimeFormat}
okLabel="OK"
cancelLabel="Annuler"
locale="fr"
/>
<DatePicker
hintText="fa-IR locale"
DateTimeFormat={DateTimeFormat}
okLabel="تایید"
cancelLabel="لغو"
locale="fa-IR"
/>
<DatePicker
hintText="en-US locale"
locale="en-US"
firstDayOfWeek={0}
/>
<DatePicker
hintText="Custom date format"
firstDayOfWeek={0}
formatDate={new DateTimeFormat('en-US', {
day: 'numeric',
month: 'long',
year: 'numeric',
}).format}
/>
</div>
);
export default DatePickerExampleInternational;
|
src/svg-icons/image/slideshow.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageSlideshow = (props) => (
<SvgIcon {...props}>
<path d="M10 8v8l5-4-5-4zm9-5H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/>
</SvgIcon>
);
ImageSlideshow = pure(ImageSlideshow);
ImageSlideshow.displayName = 'ImageSlideshow';
ImageSlideshow.muiName = 'SvgIcon';
export default ImageSlideshow;
|
src/ModalDialog.js | andrew-d/react-bootstrap | /*eslint-disable react/prop-types */
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const ModalDialog = React.createClass({
mixins: [ BootstrapMixin ],
propTypes: {
/**
* A Callback fired when the header closeButton or non-static backdrop is clicked.
* @type {function}
* @required
*/
onHide: React.PropTypes.func.isRequired,
/**
* A css class to apply to the Modal dialog DOM node.
*/
dialogClassName: React.PropTypes.string
},
getDefaultProps() {
return {
bsClass: 'modal',
closeButton: true
};
},
render() {
let modalStyle = { display: 'block'};
let bsClass = this.props.bsClass;
let dialogClasses = this.getBsClassSet();
delete dialogClasses.modal;
dialogClasses[`${bsClass}-dialog`] = true;
return (
<div
{...this.props}
title={null}
tabIndex="-1"
role="dialog"
style={modalStyle}
className={classNames(this.props.className, bsClass)}
>
<div className={classNames(this.props.dialogClassName, dialogClasses)}>
<div className={`${bsClass}-content`} role='document'>
{ this.props.children }
</div>
</div>
</div>
);
}
});
export default ModalDialog;
|
react16-feature/src/App.js | wefine/reactjs-guide | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Overlay extends Component {
constructor(props) {
super(props);
this.container = document.createElement('div');
document.body.appendChild(this.container);
}
componentWillUnmount() {
document.body.removeChild(this.container);
}
render() {
return ReactDOM.createPortal(
<div className="overlay">
<span className="overlay__close" onClick={this.props.onClose}>
×
</span>
{this.props.children}
</div>,
this.container
);
}
}
class App extends Component {
constructor(props) {
super(props);
this.state = { overlayActive: true };
}
closeOverlay() {
this.setState({ overlayActive: false });
}
render() {
return (
<div>
<h2>Dashboard</h2>
{this.state.overlayActive && <Overlay onClose={this.closeOverlay.bind(this)}>overlay content</Overlay>}
</div>
);
}
}
export default App;
|
src/components/DeviceCardComponent.js | hzburki/innexiv-front-end | import React, { Component } from 'react';
import { Panel, Col } from 'react-bootstrap';
import { Link } from 'react-router';
class DeviceCardComponent extends Component {
state = {
id: this.props.device.id,
}
onDeviceClick() {
this.props.deviceClick(this.state.id);
}
render() {
const { enteries, device } = this.props;
return (
<Col md={4} sm={6} xs={12} onClick={this.onDeviceClick.bind(this)}>
<Panel header={device.location}>
<h4>Device ID: {device.id}</h4>
<span style={{ fontSize: 12 }}>Total Number of Enteries: {enteries}</span>
</Panel>
</Col>
);
}
}
export default DeviceCardComponent;
|
src/js/components/Camera.js | deluxe-pig/Aquila | import {Entity} from 'aframe-react';
import React from 'react';
export default props => (
<Entity>
<Entity camera="" look-controls="" wasd-controls="" {...props}/>
</Entity>
);
|
react/src/SpinnerDonut.js | Chalarangelo/react-mini.css | import React from 'react';
// Module constants (change according to your flavor file)
var spinnerDonutClassName = 'spinner-donut';
// Donut Spinner component.
export function SpinnerDonut (props){
var outProps = Object.assign({}, props);
if (typeof outProps.children !== 'undefined') throw "Error: A 'SpinnerDonut' component must not have any children.";
if (typeof outProps.progressBar === 'undefined') outProps.progressBar = false;
if (typeof outProps.elementType === 'undefined') outProps.elementType = 'div';
if (typeof outProps.className === 'undefined')
outProps.className = spinnerDonutClassName;
else
outProps.className += ' ' + spinnerDonutClassName;
if (outProps.progressBar)
outProps.role = 'progressbar';
delete outProps.progressBar;
var elementType = outProps.elementType == 'span' ? 'span' : 'div';
delete outProps.elementType;
return React.createElement(
elementType, outProps, outProps.children
);
}
|
web/src/js/__tests__/components/ContentView/DownloadContentButtonSpec.js | StevenVanAcker/mitmproxy | import React from 'react'
import renderer from 'react-test-renderer'
import DownloadContentButton from '../../../components/ContentView/DownloadContentButton'
import { TFlow } from '../../ducks/tutils'
let tflow = new TFlow()
describe('DownloadContentButton Component', () => {
it('should render correctly', () => {
let downloadContentButton = renderer.create(
<DownloadContentButton flow={tflow} message={tflow.response}/>
),
tree = downloadContentButton.toJSON()
expect(tree).toMatchSnapshot()
})
})
|
src/svg-icons/toggle/star-border.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ToggleStarBorder = (props) => (
<SvgIcon {...props}>
<path d="M22 9.24l-7.19-.62L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27 18.18 21l-1.63-7.03L22 9.24zM12 15.4l-3.76 2.27 1-4.28-3.32-2.88 4.38-.38L12 6.1l1.71 4.04 4.38.38-3.32 2.88 1 4.28L12 15.4z"/>
</SvgIcon>
);
ToggleStarBorder = pure(ToggleStarBorder);
ToggleStarBorder.displayName = 'ToggleStarBorder';
ToggleStarBorder.muiName = 'SvgIcon';
export default ToggleStarBorder;
|
main.js | FindEarth/app | import Expo from 'expo'
import React from 'react'
import { Platform, StatusBar, View } from 'react-native'
import { NavigationProvider, StackNavigation } from '@expo/ex-navigation'
import { FontAwesome } from '@expo/vector-icons'
import Router from './navigation/Router'
import cacheAssetsAsync from './utilities/cacheAssetsAsync'
import styles from './styles/AppContainer'
import { Provider } from 'react-redux'
import store from './store'
class AppContainer extends React.Component {
state = {
appIsReady: false,
}
componentWillMount() {
this._loadAssetsAsync()
}
async _loadAssetsAsync() {
try {
await cacheAssetsAsync({
images: [
require('./assets/images/userM.png'),
require('./assets/images/userF.png'),
],
fonts: [
FontAwesome.font,
{ 'space-mono': require('./assets/fonts/SpaceMono-Regular.ttf') },
],
})
} catch (e) {
console.warn(
'There was an error caching assets (see: main.js), perhaps due to a ' +
'network timeout, so we skipped caching. Reload the app to try again.'
)
console.log(e.message)
} finally {
this.setState({ appIsReady: true })
}
}
render() {
if (!this.state.appIsReady) {
return <Expo.AppLoading />
}
return (
<Provider store={store}>
<View style={styles.container}>
<NavigationProvider router={Router}>
<StackNavigation
id="root"
initialRoute={Router.getRoute('rootNavigation')}
/>
</NavigationProvider>
{Platform.OS === 'ios' && <StatusBar barStyle='dark-content' />}
</View>
</Provider>
)
}
}
Expo.registerRootComponent(AppContainer)
|
webpack/scenes/Subscriptions/Details/SubscriptionDetailInfo.js | Katello/katello | import React from 'react';
import PropTypes from 'prop-types';
import { Table } from 'react-bootstrap';
import { translate as __ } from 'foremanReact/common/I18n';
import subscriptionAttributes from './SubscriptionAttributes';
import subscriptionPurposeAttributes from './SubscriptionPurposeAttributes';
const SubscriptionDetailInfo = ({ subscriptionDetails }) => {
const subscriptionLimits = (subDetails) => {
const limits = [];
if (subDetails.sockets) {
limits.push(__('Sockets: %s').replace('%s', subDetails.sockets));
}
if (subDetails.cores) {
limits.push(__('Cores: %s').replace('%s', subDetails.cores));
}
if (subDetails.ram) {
limits.push(__('RAM: %s GB').replace('%s', subDetails.ram));
}
if (limits.length > 0) {
return limits.join(', ');
}
return '';
};
const subscriptionDetailValue = (subDetails, key) => (subDetails[key] == null ? '' : String(subDetails[key]));
const formatInstanceBased = (subDetails) => {
if (subDetails.instance_multiplier == null ||
subDetails.instance_multiplier === '' ||
subDetails.instance_multiplier === 0) {
return __('No');
}
return __('Yes');
};
return (
<div>
<h2>{__('Subscription Info')}</h2>
<Table>
<tbody>
{Object.keys(subscriptionAttributes).map(key => (
<tr key={key}>
<td><b>{__(subscriptionAttributes[key])}</b></td>
<td>{subscriptionDetailValue(subscriptionDetails, key)}</td>
</tr>
))}
<tr>
<td><b>{__('Limits')}</b></td>
<td>{subscriptionLimits(subscriptionDetails)}</td>
</tr>
<tr>
<td><b>{__('Instance-based')}</b></td>
<td>{formatInstanceBased(subscriptionDetails)}</td>
</tr>
</tbody>
</Table>
<h2>{__('System Purpose')}</h2>
<Table>
<tbody>
{Object.keys(subscriptionPurposeAttributes).map(key => (
<tr key={key}>
<td><b>{__(subscriptionPurposeAttributes[key])}</b></td>
<td>{subscriptionDetailValue(subscriptionDetails, key)}</td>
</tr>
))}
</tbody>
</Table>
</div>
);
};
SubscriptionDetailInfo.propTypes = {
subscriptionDetails: PropTypes.shape({}).isRequired,
};
export default SubscriptionDetailInfo;
|
examples/with-relay-modern/lib/RelayProvider.js | arunoda/next.js | import React from 'react'
import PropTypes from 'prop-types'
// Thank you https://github.com/robrichard
// https://github.com/robrichard/relay-context-provider
class RelayProvider extends React.Component {
getChildContext () {
return {
relay: {
environment: this.props.environment,
variables: this.props.variables
}
}
}
render () {
return this.props.children
}
}
RelayProvider.childContextTypes = {
relay: PropTypes.object.isRequired
}
RelayProvider.propTypes = {
environment: PropTypes.object.isRequired,
variables: PropTypes.object.isRequired,
children: PropTypes.node
}
export default RelayProvider
|
src/components/AddProduct.js | ValentinAlexandrovGeorgiev/iStore | import React, { Component } from 'react';
import ajax from 'superagent';
import SERVER_URL from '../config';
class AddProduct extends Component {
constructor(props) {
super(props);
this.state = {
message: '',
quantity: this.props.quantity
};
this.addToBasket = this.addToBasket.bind(this);
}
deleteMessage() {
let that = this;
setTimeout(() => {
that.setState({
message: ''
});
}, 3000)
}
addToBasket() {
let product = this.props.product;
let currentUserId = window.localStorage.getItem('profile-id');
let total_price = parseFloat(product.price.slice(0, product.price.length - 1));
total_price *= parseFloat(this.props.quantity);
total_price = total_price.toString();
if (!currentUserId) {
this.setState({
message: "Please, try to login first!"
});
this.deleteMessage();
return;
}
ajax.post(SERVER_URL + '/basket/')
.send({
user_id: currentUserId,
product: product._id,
color: product.color,
quantity: this.props.quantity,
price: total_price,
ordered_by_current_user: false
})
.end((err, product) => {
if(!err && product) {
this.setState({
message: "This product is added successfully!"
})
this.deleteMessage();
}
else {
this.setState({
message: "There is something wrong! Please, try again after page reload"
})
}
});
}
render() {
return (
<div className="pdp-add-wrapper">
<input className="pdp-product-quantity" type="text"
value={this.props.quantity} onChange={this.props.handleQuantityChange} />
<button data-id={this.props.product._id} onClick={this.addToBasket} className="pdp-add-product">Add Product</button>
<p className="product-message">{this.state.message}</p>
</div>
)
}
}
export default AddProduct;
|
lib/ui/components/Settings/Settings.js | 500tech/bdsm | import React from 'react';
import Frame from 'ui/components/common/Frame';
import { trackEvent } from 'ui/Analytics';
import SettingsState from 'ui/states/SettingsState';
import { connectToState } from 'ui/states/connector';
import ImportSection from 'ui/components/Settings/ImportSection';
import ExportSection from 'ui/components/Settings/ExportSection';
import SettingsSection from 'ui/components/Settings/SettingsSection';
import { SettingsContainer } from 'ui/components/Settings/styled';
class Settings extends React.Component {
componentDidMount() {
trackEvent('open settings');
}
render() {
return (
<Frame>
<SettingsContainer>
<ImportSection
importSuccess={ SettingsState.importSuccess }
importFailed={ SettingsState.importFailed }
error={ SettingsState.error }/>
<ExportSection/>
<SettingsSection/>
</SettingsContainer>
</Frame>
);
}
}
export default connectToState(SettingsState, Settings);
|
src/components/Helmet.js | radubrehar/evanghelic.ro | import React from 'react';
import Helmet from 'react-helmet';
const TITLE = 'Biserica Cluj - Biserica Creștină după Evanghelie';
const TheHelmet = ({ title, description } = {}) => (
<Helmet>
<html lang="ro-RO" />
<title>{title ? title + ' - ' + TITLE : TITLE}</title>
<meta name="theme-color" content="#00BCD4" />
<meta
name="google-site-verification"
content="IWAaY8Sro5jqdm-xp7TsoXt3Lvklx4w7536lsO21Jdw"
/>
<meta
name="description"
content={
description ||
'Vino să îl cunoști pe Dumnezeu alături de noi! Biserica Cluj'
}
/>
<meta
name="keywords"
content="cluj, biserica, creștină, evanghelie, Dumnezeu, Isus, cluj-napoca"
/>
</Helmet>
);
export default TheHelmet;
|
UI/Fields/ListPicker.js | Datasilk/Dedicate | import React from 'react';
import {View, FlatList, StyleSheet, Dimensions, Alert, TouchableHighlight} from 'react-native';
import Text from 'text/Text';
import AppStyles from 'dedicate/AppStyles';
import Textbox from 'fields/Textbox';
import Picker from 'fields/Picker';
import ButtonEdit from 'buttons/ButtonEdit';
import ButtonClose from 'buttons/ButtonClose';
import ButtonSearch from 'buttons/ButtonSearch';
import ButtonCheck from 'buttons/ButtonCheck';
import ButtonAddListItem from 'buttons/ButtonAddListItem';
import DbLists from 'db/DbLists';
import Plural from 'utility/Plural';
export default class ListPicker extends React.Component{
constructor(props){
super(props);
this.state = {
searchlist:'',
list:{
items:null,
start:0,
nomore:false
},
total:0,
searchable:false,
refresh:1,
refreshing:false,
editing:null,
editingLabel:null,
editingValue:null
};
//bind methods
this.getList = this.getList.bind(this);
this.onPressShowListModal = this.onPressShowListModal.bind(this);
this.onShowListModal = this.onShowListModal.bind(this);
this.onSearchListChangeText = this.onSearchListChangeText.bind(this);
this.onPressSearchList = this.onPressSearchList.bind(this);
this.onEndListReached = this.onEndListReached.bind(this);
this.editItem = this.editItem.bind(this);
this.saveItem = this.saveItem.bind(this);
this.removeList = this.removeList.bind(this);
this.onAddListItem = this.onAddListItem.bind(this);
this.removeItem = this.removeItem.bind(this);
this.onEditingChangeText = this.onEditingChangeText.bind(this);
this.onEditingChangeValue = this.onEditingChangeValue.bind(this);
}
componentDidUpdate(prevProps){
if(this.props.refresh != prevProps.refresh){
this.setState({refresh:this.state.refresh + 1, list:{items:null, start:0, nomore:false}, refreshing:false}, () => {
this.getList();
});
}
}
// Get List Items from Database ////////////////////////////////////////////////////////////////////////////////////////////////////
paging =20
Name(){
return this.props.input != null ? this.props.input.name : this.props.name;
}
getList(callback){
const dbLists = new DbLists();
//get events from database
if(this.state.list.nomore == true || this.state.refreshing == true){return;}
this.setState({refreshing:true}, () => {
//get results for list items
let list = this.state.list;
//first, get count of total list items
const total = dbLists.GetListItems({listId:this.props.listId}).length;
//next, get filtered list of items
const items = dbLists.GetListItems({
start:list.start,
length:this.paging,
sorted:'label',
descending:false,
listId:this.props.listId,
filtered:this.state.searchlist != '' ? 'label contains[c] "' + this.state.searchlist + '"' : null
});
//mutate realm object into generic array of objects
let results = items.map(item => {
return {id:item.id, listId:item.listId, label:item.label, value:item.value}
});
//check state for search results
if(this.state.searchlist != '' && this.props.state != null && this.props.state.update != null){
const uresults = this.props.state.update.filter(a => a.label.toLowerCase().indexOf(this.state.searchlist.toLowerCase()) >= 0);
if(uresults.length > 0){
//found matching items in update list
const resultIds = results.map(a => a.id);
for(let x = 0; x < uresults.length; x++){
//add items to results that don't already exist
const item = uresults[x];
if(resultIds.indexOf(item.id) < 0){
results.push(item);
}
}
}
}
//concatenate results to existing list
if(list.items == null){ list.items = []; }
let removeIds = [];
if(this.props.state != null && this.props.state.remove != null){
removeIds = this.props.state.remove.map(a => a.id);
}
const allitems = list.items.concat(results).map(item => {
if(this.props.state != null){
//filter out any items that exist in the state.remove array
if(removeIds.indexOf(item.id) >= 0){return null;}
//check for updated item in state object and replace item with updated item
if(this.props.state.update != null){
const index = this.props.state.update.map(a => a.id).indexOf(item.id);
if(index >= 0){
return this.props.state.update[index];
}
}
if(this.props.state.add != null){
const index = this.props.state.add.map(a => a.id).indexOf(item.id);
if(index >= 0){
return null;
}
}
}
return item;
}).filter(a => a != null);
//update list settings
list.items = allitems;
list.start += this.paging;
list.nomore = results.length < this.paging;
this.setState({ list:list, refreshing:false, refresh:this.state.refresh+1, total:total, searchable:total >= this.paging }, () => {
//exeute callback
if(typeof callback != 'undefined'){
callback();
}
});
});
}
// Show Modal Window ///////////////////////////////////////////////////////////////////////////////////////////////////////////////
onPressShowListModal(){
let list = this.state.list;
list.start = 0;
list.items = [];
list.nomore = false;
this.setState({list:list}, () => {
this.getList(this.onShowListModal);
});
}
onShowListModal(){
if(this.state.list.items == null){
//get initial list items
this.getList(this.onShowListModal);
return;
}
//load modal window
let data = (this.props.state != null && this.props.state.add != null ? this.props.state.add.concat(this.state.list.items) : this.state.list.items);
if(this.state.searchlist != ''){
const search = this.state.searchlist.toLowerCase();
data = data.filter(a => a.label.toLowerCase().indexOf(search) >= 0);
}
const {height} = Dimensions.get('window');
global.Modal.setContent('Available ' + Plural(this.Name()), (
<View style={{minWidth:300}}>
{this.state.searchable == true &&
<View style={this.styles.searchListForm}>
<View style={this.styles.searchListTextbox}>
<Textbox
defaultValue={this.state.searchlist}
style={this.styles.inputField}
placeholder="Search"
returnKeyType={'done'}
onChangeText={this.onSearchListChangeText}
maxLength={25}
/>
</View>
<View style={this.styles.searchListButton}>
<ButtonSearch onPress={this.onPressSearchList} size="smaller" color={AppStyles.textColor}/>
</View>
</View>
}
<View style={this.styles.listResults}>
{data.length > 0 ?
<FlatList
style={{maxHeight:height - 200}}
data={data}
keyExtractor={item => item.label}
onEndReached={this.onEndListReached}
onEndReachedThreshold={0.5}
extraData={this.state.refresh}
renderItem={
({item}) => {
if(this.state.editing != null && this.state.editing.label == item.label){
return (
<View style={this.styles.listItemEditingContainer}>
<View style={this.styles.listItemTextboxContainer}>
<Textbox
defaultValue={this.state.editingLabel}
style={[this.styles.inputField, this.styles.editingTextbox]}
returnKeyType={'done'}
onChangeText={this.onEditingChangeText}
maxLength={25}
/>
<ButtonCheck style={this.styles.buttonSave} size="xsmall" color={AppStyles.color} onPress={this.saveItem}/>
</View>
<View style={this.styles.listItemTextboxContainer}>
<Textbox
defaultValue={this.state.editingValue}
style={[this.styles.inputField, this.styles.editingTextbox]}
placeholder="0"
returnKeyType={'done'}
onChangeText={this.onEditingChangeValue}
maxLength={10}
/>
</View>
</View>
);
}else{
const listItem = (
<View style={this.styles.listItemContainer}>
<Text style={this.styles.listItemText}>{item.label}</Text>
{this.props.editable == true &&
<View style={this.styles.editableContainer}>
<View style={this.styles.buttonEdit}><ButtonEdit size="xxsmall" color={AppStyles.color} onPress={() => {this.editItem(item)}}/></View>
<View style={this.styles.buttonRemove}><ButtonClose size="xxsmall" color={AppStyles.color} onPress={() => {this.removeItem(item)}}/></View>
</View>
}
</View>
);
if(this.props.onValueChange != null){
//selectable list item
return (
<TouchableHighlight underlayColor={AppStyles.listItemPressedColor} onPress={() => {this.props.onValueChange(item); global.Modal.hide();}}>
{listItem}
</TouchableHighlight>
);
}else{
//non-selectable list item
return listItem;
}
}
}
}
></FlatList>
:
(this.state.total > 0 ?
<View style={this.styles.noitems}>
<Text style={this.styles.noitemsText}>Your search returned no results</Text>
</View>
:
<View style={this.styles.noitems}>
<Text style={this.styles.noitemsText}>This list doesn't contain any items yet</Text>
</View>
)
}
</View>
</View>
), false, true); //scrollable = false, close button = true
global.Modal.show();
}
// Search List Items ////////////////////////////////////////////////////////////////////////////////////////////////////
onSearchListChangeText = (text) => {
this.setState({searchlist:text});
}
onPressSearchList(){
let list = this.state.list;
list.start = 0;
list.items = [];
list.nomore = false;
this.setState({list:list}, () => {
this.getList(this.onShowListModal);
});
}
onEndListReached(){
this.getList(this.onShowListModal);
}
// Edit Item //////////////////////////////////////////////////////////////////////////////
editItem(item){
this.setState({editing:item, editingLabel:item.label, editingValue:item.value, refresh:this.state.refresh+1}, () => {
this.onShowListModal();
});
}
onEditingChangeText(text){
this.setState({editingLabel:text});
}
onEditingChangeValue(text){
this.setState({editingValue:text != '' ? parseFloat(text) : null});
}
// Save Edits to List Item ////////////////////////////////////////////////////////////////////////////////////////////////////
saveItem(){
//save edits to list item
let index = -1;
let item = this.state.editing;
let state = this.props.state || {add:[], update:[], remove:[]};
const value = this.state.editingValue != null ? parseFloat(this.state.editingValue) : null;
if(state.add == null){state.add = [];}
if(state.update == null){state.update = [];}
if(state.remove == null){state.remove = [];}
if(this.props.state != null && this.props.state.add != null){
//check add array first to see if this is a new item that hasn't been added to the database yet
index = this.props.state.add.map(a => a.label).indexOf(this.state.editing.label);
}
if(index >= 0){
//item exists in add array
state.add[index] = {label:this.state.editingLabel, value:value};
this.props.onUpdateListState(state);
this.setState({editing:null, editingLabel:null, editingValue:null, refresh:this.state.refresh+1}, () => {
this.onShowListModal();
});
}else{
//item exists in database
let list = this.state.list;
index = list.items.map(a => a.label).indexOf(this.state.editing.label);
item = list.items[index];
item = {id:item.id, listId:item.listId, label:this.state.editingLabel, value:value};
list.items[index] = item;
//make changes to props.state for update command
const x = 0;
if(state.update != null){
x = state.update.map(a => a.id).indexOf(item.id);
if(x < 0){
x = state.update.length;
}
}else{
state.update = [];
}
if(x < state.update.length){
//found item within update array
state.update[x] = item;
}else{
//item isn't in update array yet
state.update.push(item);
}
this.props.onUpdateListState(state);
//update list
this.setState({list:list, editing:null, editingLabel:null, editingValue:null, refresh:this.state.refresh+1}, () => {
this.onShowListModal();
});
}
}
// Remove List //////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
removeList(){
Alert.alert(
'Delete List',
'Do you really want to permanently delete the list "' + this.Name() + '"? This cannot be undone! All tasks that use this list will instead use an empty list, all events that use the list will display an empty value, and all charts that filter by this list will no longer use the filter.',
[
{text: 'Cancel', onPress: () => {}, style: 'cancel'},
{text: 'Delete', onPress: () => {
const dbLists = new DbLists();
dbLists.DeleteList(this.props.listId);
if(typeof this.props.onRemoveList == 'function'){
this.props.onRemoveList();
}
}}
],
{ cancelable: true }
);
}
// Add List Item ////////////////////////////////////////////////////////////////////////////////////////////////////////////////////
onAddListItem(item){
const dbLists = new DbLists();
const newitem = {listId:this.props.listId, label:item.label, value:item.value};
dbLists.CreateListItem(newitem);
if(typeof this.props.onAddListItem == 'function'){
this.props.onAddListItem(newitem);
}
}
// Remove List Item /////////////////////////////////////////////////////////////////////////////////////////////////////////////////
removeItem(item){
Alert.alert(
'Delete List Item?',
'Do you really want to delete the list item "' + item.label + '"? This will take effect only after you save changes to this task.',
[
{text: 'Cancel', style: 'cancel'},
{text: 'Delete List Item', onPress: () => {
let list = this.state.list;
let state = this.props.state || {add:[], update:[], remove:[]};
if(state.add == null){state.add = [];}
if(state.update == null){state.update = [];}
if(state.remove == null){state.remove = [];}
//delete item in state.add array
let index = state.add.map(a => a.label.toLowerCase()).indexOf(item.label.toLowerCase());
if(index >= 0){
state.add.splice(index, 1);
}
if(item.id != null){
//delete item in state.update array
index = state.update.map(a => a.id).indexOf(item.id);
if(index >= 0){
state.add.splice(index, 1);
}
//check for duplicate in state.remove array
index = state.remove.map(a => a.id).indexOf(item.id);
if(index < 0){
state.remove.push(item);
index = list.items.map(a => a.id).indexOf(item.id);
if(index >= 0){
list.items.splice(index, 1);
}
}
}
this.props.onUpdateListState(state);
//update list
this.setState({list:list, editing:null, editingLabel:null, editingValue:null, refresh:this.state.refresh+1}, () => {
this.onShowListModal();
});
}}
],
{ cancelable: true }
)
}
// Render Component ////////////////////////////////////////////////////////////////////////////////////////////////////
render(){
switch(this.props.view){
case 'list':
return (
<TouchableHighlight underlayColor={AppStyles.listItemPressedColor} onPress={this.onPressShowListModal}>
<View style={[this.styles.listItem, this.props.style]}>
<Text style={[this.styles.listItemText, this.props.textStyle]}>{this.props.selectedText}</Text>
{this.props.editable == true &&
<View style={this.styles.listItemButtons}>
<View style={this.styles.listItemButton}>
<ButtonAddListItem size="xxsmall" list={{name:this.Name()}} onAddListItem={this.onAddListItem} />
</View>
<View style={this.styles.listItemButton}><ButtonClose size="xxsmall" color={AppStyles.color} onPress={this.removeList}/></View>
</View>
}
</View>
</TouchableHighlight>
);
default:
return (
<Picker
{...this.props}
items={['']}
selectedText={this.props.selectedText || 'Select...'}
onShowModal={this.onPressShowListModal}
/>
);
}
}
styles = StyleSheet.create({
//list items
listItem:{flexDirection:'row', justifyContent:'space-between', padding:AppStyles.padding},
listItemText:{fontSize:AppStyles.titleFontSize},
listItemButtons:{flexDirection:'row'},
listItemButton:{paddingLeft:AppStyles.paddingLarge},
//modal window
inputField: {fontSize:AppStyles.titleFontSize},
noitems:{flexDirection:'row', justifyContent:'center'},
noitemsText:{opacity:0.5, padding:AppStyles.paddingLarge},
//list items modal window
searchListForm:{flexDirection:'row', justifyContent:'space-between', paddingVertical:AppStyles.padding, paddingHorizontal:AppStyles.paddingLarger},
searchListTextbox:{width:200},
searchListButton:{width:AppStyles.iconSmaller + AppStyles.padding, paddingTop:AppStyles.padding, paddingLeft:AppStyles.padding},
listItemContainer:{flexDirection:'row', justifyContent:'space-between', paddingVertical:AppStyles.padding, paddingHorizontal:AppStyles.paddingLarger, borderBottomColor: AppStyles.separatorColor, borderBottomWidth:1},
listItemEditingContainer:{paddingBottom:AppStyles.padding, borderBottomColor: AppStyles.separatorColor, borderBottomWidth:1},
listItemTextboxContainer:{flexDirection:'row', justifyContent:'space-between', paddingTop:AppStyles.paddingSmaller, paddingHorizontal:AppStyles.paddingLarger},
listItemText:{},
editableContainer:{flexDirection:'row'},
buttonEdit:{paddingRight:15},
buttonRemove:{},
buttonSave:{paddingTop:AppStyles.padding},
editingTextbox:{width:200}
})
}
|
app/react-icons/fa/chain-broken.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaChainBroken extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m11.3 28.4l-5.7 5.7q-0.2 0.2-0.5 0.2-0.3 0-0.5-0.2-0.2-0.2-0.2-0.5t0.2-0.5l5.7-5.8q0.2-0.2 0.5-0.2t0.5 0.2q0.2 0.3 0.2 0.6t-0.2 0.5z m3.8 0.9v7.1q0 0.3-0.2 0.5t-0.5 0.2-0.6-0.2-0.2-0.5v-7.1q0-0.3 0.2-0.5t0.6-0.2 0.5 0.2 0.2 0.5z m-5-5q0 0.3-0.2 0.5t-0.5 0.2h-7.2q-0.3 0-0.5-0.2t-0.2-0.5 0.2-0.5 0.5-0.2h7.2q0.3 0 0.5 0.2t0.2 0.5z m28.2 2.8q0 2.7-1.9 4.6l-3.3 3.2q-1.8 1.9-4.5 1.9-2.7 0-4.6-1.9l-7.4-7.5q-0.5-0.5-1-1.2l5.4-0.4 6.1 6.1q0.6 0.6 1.5 0.6t1.5-0.6l3.3-3.3q0.6-0.6 0.6-1.5 0-0.9-0.6-1.5l-6.1-6.1 0.4-5.4q0.7 0.5 1.2 1l7.5 7.5q1.9 1.9 1.9 4.5z m-13.8-16.1l-5.3 0.4-6.1-6.1q-0.6-0.7-1.5-0.7-0.9 0-1.6 0.6l-3.2 3.3q-0.7 0.6-0.7 1.5 0 0.9 0.7 1.5l6.1 6.1-0.4 5.4q-0.8-0.5-1.3-0.9l-7.5-7.5q-1.8-2-1.8-4.6 0-2.7 1.9-4.5l3.2-3.3q1.9-1.8 4.6-1.8 2.7 0 4.5 1.9l7.5 7.4q0.4 0.5 0.9 1.3z m14.1 1.9q0 0.3-0.2 0.5t-0.5 0.2h-7.1q-0.3 0-0.5-0.2t-0.2-0.5 0.2-0.6 0.5-0.2h7.1q0.3 0 0.5 0.2t0.2 0.6z m-12.1-12.2v7.2q0 0.3-0.2 0.5t-0.5 0.2-0.5-0.2-0.2-0.5v-7.2q0-0.3 0.2-0.5t0.5-0.2 0.5 0.2 0.2 0.5z m9.1 3.4l-5.7 5.7q-0.3 0.2-0.5 0.2t-0.6-0.2q-0.2-0.2-0.2-0.5t0.2-0.5l5.8-5.7q0.2-0.2 0.5-0.2t0.5 0.2q0.2 0.2 0.2 0.5t-0.2 0.5z"/></g>
</IconBase>
);
}
}
|
go-betz/src/components/Bet/index.js | FabioFischer/go-betz | import React from 'react';
import { Card, CardTitle, CardText } from 'material-ui';
class Bet extends React.Component {
state = {
expanded: false
};
render() {
const { match, pick, value } = this.props;
const { description, teamA, teamB, winner } = match;
let expandedDescription = `I bet ${value} credits on ${pick.name}. `;
if (winner) {
if (winner.id === teamA.id) teamA.name = `👑 ${teamA.name} 👑`;
if (winner.id === teamB.id) teamB.name = `👑 ${teamB.name} 👑`;
if (winner.id === pick.id) expandedDescription = expandedDescription.concat('I won the bet 🤑');
else expandedDescription = expandedDescription.concat(`I lost the bet 😔`);
}
return (
<Card>
<CardTitle title={`${teamA.name} vs. ${teamB.name}`} subtitle={description} actAsExpander={true} showExpandableButton={true} />
<CardText expandable={true}>
<CardTitle title={expandedDescription} />
</CardText>
</Card>
);
}
}
export default Bet; |
node_modules/react-router/es/IndexRedirect.js | ProjectSunday/rooibus | import React from 'react';
import warning from './routerWarning';
import invariant from 'invariant';
import Redirect from './Redirect';
import { falsy } from './InternalPropTypes';
var _React$PropTypes = React.PropTypes,
string = _React$PropTypes.string,
object = _React$PropTypes.object;
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
/* eslint-disable react/require-render-return */
var IndexRedirect = React.createClass({
displayName: 'IndexRedirect',
statics: {
createRouteFromReactElement: function createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = Redirect.createRouteFromReactElement(element);
} else {
process.env.NODE_ENV !== 'production' ? warning(false, 'An <IndexRedirect> does not make sense at the root of your route config') : void 0;
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render: function render() {
!false ? process.env.NODE_ENV !== 'production' ? invariant(false, '<IndexRedirect> elements are for router configuration only and should not be rendered') : invariant(false) : void 0;
}
});
export default IndexRedirect; |
newclient/scripts/components/config/general/disclosure-type/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import React from 'react';
import EditLink from '../../edit-link';
import DoneLink from '../../done-link';
import ConfigActions from '../../../../actions/config-actions';
export default class DisclosureType extends React.Component {
constructor() {
super();
this.state = {
editing: false
};
this.editType = this.editType.bind(this);
this.doneEditing = this.doneEditing.bind(this);
this.keyUp = this.keyUp.bind(this);
this.toggle = this.toggle.bind(this);
}
toggle() {
const checkbox = this.refs.checkbox;
if (checkbox.checked) {
ConfigActions.enableDisclosureType(this.props.type.typeCd);
}
else {
ConfigActions.disableDisclosureType(this.props.type.typeCd);
}
}
keyUp(evt) {
if (evt.keyCode === 13) {
this.doneEditing();
}
}
editType() {
this.setState({
editing: true
});
}
doneEditing() {
const textbox = this.refs.label;
ConfigActions.updateDisclosureType(this.props.type.typeCd, textbox.value);
this.setState({
editing: false
});
}
render() {
let jsx;
if (this.state.editing) {
jsx = (
<span className={styles.dynamicSpan}>
<input type="text" ref="label" className={styles.textbox} defaultValue={this.props.type.description} onKeyUp={this.keyUp} />
<DoneLink onClick={this.doneEditing} className={`${styles.override} ${styles.editLink}`} />
</span>
);
}
else {
jsx = (
<span className={styles.dynamicSpan}>
<label
htmlFor={`${this.props.type.typeCd}disctype`}
className={styles.label}
>
{this.props.type.description}
</label>
<EditLink onClick={this.editType} className={`${styles.override} ${styles.editLink}`} />
</span>
);
}
let checkbox;
if (this.props.canToggle) {
checkbox = (
<input
ref="checkbox"
id={`${this.props.type.typeCd}disctype`}
type="checkbox"
className={styles.checkbox}
checked={this.props.type.enabled === 1}
onChange={this.toggle}
/>
);
}
return (
<span className={`fill ${this.props.className}`}>
{checkbox}
{jsx}
</span>
);
}
}
|
node_modules/rc-table/es/TableCell.js | yhx0634/foodshopfront | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
import get from 'lodash.get';
var TableCell = function (_React$Component) {
_inherits(TableCell, _React$Component);
function TableCell() {
var _ref;
var _temp, _this, _ret;
_classCallCheck(this, TableCell);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, (_ref = TableCell.__proto__ || Object.getPrototypeOf(TableCell)).call.apply(_ref, [this].concat(args))), _this), _this.handleClick = function (e) {
var _this$props = _this.props,
record = _this$props.record,
onCellClick = _this$props.column.onCellClick;
if (onCellClick) {
onCellClick(record, e);
}
}, _temp), _possibleConstructorReturn(_this, _ret);
}
_createClass(TableCell, [{
key: 'isInvalidRenderCellText',
value: function isInvalidRenderCellText(text) {
return text && !React.isValidElement(text) && Object.prototype.toString.call(text) === '[object Object]';
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
record = _props.record,
indentSize = _props.indentSize,
prefixCls = _props.prefixCls,
indent = _props.indent,
index = _props.index,
expandIcon = _props.expandIcon,
column = _props.column;
var dataIndex = column.dataIndex,
render = column.render,
_column$className = column.className,
className = _column$className === undefined ? '' : _column$className;
// We should return undefined if no dataIndex is specified, but in order to
// be compatible with object-path's behavior, we return the record object instead.
var text = void 0;
if (typeof dataIndex === 'number') {
text = get(record, dataIndex);
} else if (!dataIndex || dataIndex.length === 0) {
text = record;
} else {
text = get(record, dataIndex);
}
var tdProps = void 0;
var colSpan = void 0;
var rowSpan = void 0;
if (render) {
text = render(text, record, index);
if (this.isInvalidRenderCellText(text)) {
tdProps = text.props || {};
colSpan = tdProps.colSpan;
rowSpan = tdProps.rowSpan;
text = text.children;
}
}
// Fix https://github.com/ant-design/ant-design/issues/1202
if (this.isInvalidRenderCellText(text)) {
text = null;
}
var indentText = expandIcon ? React.createElement('span', {
style: { paddingLeft: indentSize * indent + 'px' },
className: prefixCls + '-indent indent-level-' + indent
}) : null;
if (rowSpan === 0 || colSpan === 0) {
return null;
}
return React.createElement(
'td',
_extends({
className: className
}, tdProps, {
onClick: this.handleClick
}),
indentText,
expandIcon,
text
);
}
}]);
return TableCell;
}(React.Component);
TableCell.propTypes = {
record: PropTypes.object,
prefixCls: PropTypes.string,
index: PropTypes.number,
indent: PropTypes.number,
indentSize: PropTypes.number,
column: PropTypes.object,
expandIcon: PropTypes.node
};
export default TableCell; |
lib/editor/containers/ImageManagerApp.js | jirokun/survey-designer-js | /* eslint-env browser */
import React, { Component } from 'react';
import $ from 'jquery';
import classNames from 'classnames';
import { List } from 'immutable';
import Spinner from 'react-spinkit';
import ImageManager from '../components/editors/ImageManager';
import '../css/bootstrap.less';
/**
* ImageManagerのアプリ
*
* TinyMCEからも画像管理からも使うので、プレーンなReactコンポーネントとして実装する。Reduxは使わない
*/
export default class ImageManagerApp extends Component {
constructor(props) {
super(props);
this.state = {
imageList: List(), // 画像のリスト
loading: false, // ロード中
};
}
componentDidMount() {
this.loadImages();
}
loadImages() {
const { options } = this.props;
this.setState({ loading: true });
$.ajax({
url: options.imageListUrl,
dataType: 'json',
}).done((json) => {
this.setState({ imageList: List(json) });
}).fail((error) => {
console.log(error);
alert('画像の一覧取得に失敗しました');
}).always(() => {
this.setState({ loading: false });
});
}
uploadImages(formData) {
const { options } = this.props;
this.setState({ loading: true });
$.ajax({
url: options.uploadImageUrl,
method: 'POST',
data: formData,
processData: false,
contentType: false,
dataType: 'json',
}).done((res) => {
if (res.error) {
alert(res.message);
} else {
res.imageList.forEach(image => this.setState({ imageList: this.state.imageList.unshift(image) }));
}
}).fail(() => {
alert('ファイルのアップロードに失敗しました');
}).always(() => {
this.setState({ loading: false });
});
}
deleteImage(image) {
if (!confirm('本当に削除しますか?')) return;
const { options } = this.props;
const imageId = image._id;
this.setState({ loading: true });
$.ajax({
url: `${options.deleteImageUrl}?docId=${imageId}`,
method: 'POST',
data: { imageId },
dataType: 'json',
}).done(() => {
this.setState({ imageList: this.state.imageList.filter(img => img.id !== image.id) });
}).fail(() => {
alert('ファイルの削除に失敗しました');
}).always(() => {
this.setState({ loading: false });
});
}
handleInsertImage(params) {
window.parent.postMessage({ type: 'insertImage', value: JSON.stringify(params) }, '*');
}
render() {
return (
<div className="image-manager" style={{ paddingLeft: '8px' }}>
<ImageManager
uploadImagesFunc={formData => this.uploadImages(formData)}
insertImageFunc={params => this.handleInsertImage(params)}
deleteImageFunc={image => this.deleteImage(image)}
imageList={this.state.imageList}
/>
<div className={classNames({ hidden: !this.state.loading })}>
<div className="image-manager-block-layer" />
<div className="image-manager-spinner">
<Spinner name="ball-triangle-path" color="aqua" />
</div>
</div>
</div>
);
}
}
|
src/App.js | GuillaumeRahbari/react-website | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<p>
Edit <code>src/App.js</code> and save to reload.
</p>
<a
className="App-link"
href="https://reactjs.org"
target="_blank"
rel="noopener noreferrer"
>
Learn React
</a>
</header>
</div>
);
}
}
export default App;
|
webpack/scenes/ModuleStreams/Details/Profiles/ModuleStreamDetailProfiles.js | mccun934/katello | import React from 'react';
import PropTypes from 'prop-types';
import { Table } from 'patternfly-react';
import TableSchema from './TableSchema';
const ModuleStreamDetailProfiles = ({ profiles }) => (
<div>
<Table.PfProvider columns={TableSchema}>
<Table.Header />
<Table.Body rows={profiles} rowKey="id" />
</Table.PfProvider>
</div>
);
ModuleStreamDetailProfiles.propTypes = {
profiles: PropTypes.arrayOf(PropTypes.shape({})).isRequired,
};
export default ModuleStreamDetailProfiles;
|
src/routes/BusinessPage/UDingHuo/index.js | janeluck/red | /**
* Created by janeluck on 17/6/19.
*/
import React from 'react'
import {Steps, Button, Form, Input} from 'antd';
import _ from 'lodash'
import styles from './index.less'
import MappingTable from '../MappingTable'
const Step = Steps.Step;
const FormItem = Form.Item;
const steps = ['企业', '人员', '客户']
// 企业的对应表单项
const corporationItems = [
{
label: 'U订货平台的企业名称',
name: 'U'
}, {
label: 'Key',
name: 'K'
}, {
label: 'Secret',
name: 'S'
}, {
label: 'Token',
name: 'T'
}
]
export default class extends React.Component {
constructor(props) {
super(props)
this.state = {
current: 0,
}
}
prev = () => {
let current = this.state.current - 1;
this.setState({current});
}
next = () => {
let current = this.state.current + 1;
this.setState({current});
}
render() {
const {current} = this.state;
const that = this
let First = class extends React.Component {
constructor(props) {
super(props)
}
handleSubmit = (e) => {
e.preventDefault();
this.props.form.validateFields((err, values) => {
console.log('Received values of form: ', values);
if (!err) {
console.log('Received values of form: ', values);
that.next()
}
});
}
render() {
const formItemLayout = {
labelCol: {span: 6},
wrapperCol: {span: 18},
};
const {getFieldDecorator} = this.props.form;
// attrType 可为String, Number类型。 传入的时候统一处理为Number
return (<div>
<Form onSubmit={this.handleSubmit} className={styles.corporationForm}>
{
_.map(corporationItems, item => {
return <FormItem
{...formItemLayout}
key={item.name}
label={item.label}
>
{getFieldDecorator(item.name, {
rules: [{required: true, message: `${item.name}不能为空`}],
})(
<Input style={{width: "300px"}}/>
)}
</FormItem>
})
}
<FormItem
wrapperCol={{span: 12, offset: 6}}
>
<Button type="primary" htmlType="submit">下一步</Button>
</FormItem>
</Form>
</div>
)
}
}
return (
<div>
<div style={{marginBottom: 24}}>当前正在执行第 {current + 1} 步</div>
<Steps current={current}>
{_.map(steps, (s, i) => <Step key={i} title={`${s}的对应`}/>)}
</Steps>
{current == 0 && React.createElement(Form.create()(First))}
{current == 1 && <MappingTable />}
{current == 2 && <MappingTable />}
<div style={{marginTop: 24}}>
{current > 0 && <Button onClick={this.prev} disabled={current == 0}>上一步</Button>}
{current < steps.length - 1 && <Button onClick={this.next}>下一步</Button>}
</div>
</div>
);
}
}
|
src/components/Input/__tests__/Input-test.js | birkir/react-typescript-iso-kit | 'use strict';
jest.unmock('../Input.js');
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Input from '../Input';
describe('Input', () => {
const input = TestUtils.renderIntoDocument(
<Input value="test" />
);
const inputNode = ReactDOM.findDOMNode(input);
it('renders input', () => {
expect(inputNode).not.toBeNull();
});
});
|
app/javascript/components/collections/list/ButtonCollectionListShowAll.js | avalonmediasystem/avalon | /*
* Copyright 2011-2022, The Trustees of Indiana University and Northwestern
* University. Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
*
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed
* under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
* --- END LICENSE_HEADER BLOCK ---
*/
import React from 'react';
import PropTypes from 'prop-types';
const ButtonCollectionListShowAll = ({
collectionsLength,
maxItems,
handleShowAll,
showAll
}) => {
if (collectionsLength > maxItems) {
return (
<button
aria-controls="collections-list-remaining-collections"
aria-expanded={showAll}
onClick={handleShowAll}
className="btn btn-link show-all"
role="button"
>
<i
className={`fa ${showAll ? 'fa-chevron-down' : 'fa-chevron-right'}`}
/>
{` Show ${showAll ? `less` : `${collectionsLength} items`}`}
</button>
);
}
return null;
};
ButtonCollectionListShowAll.propTypes = {
collectionsLength: PropTypes.number,
maxItems: PropTypes.number,
handleShowAll: PropTypes.func,
showAll: PropTypes.bool
};
export default ButtonCollectionListShowAll;
|
src/frontend/src/components/counters/RoundCount.js | ziroby/dmassist | import React from 'react';
import './RoundCount.css';
function RoundCount(props) {
return (
<div className="RoundCount">
round: {props.round}
</div>
);
}
export default RoundCount;
|
src/routes.js | transmute-industries/eth-faucet | import React from 'react'
import { Route, IndexRoute, Redirect } from 'react-router'
import {
DEBUG_PATH as DebugRoute,
CREATE_FAUCET_PATH as CreateFaucetRoute,
NAME_FAUCET_PATH as FaucetRoute,
AUTHORIZE_FAUCET_PATH as AuthorizeFaucetRoute
} from './constants/paths'
import CoreLayout from './layouts/CoreLayout/CoreLayout'
import HomePage from './components/HomePage'
import DebugFormContainer from './containers/DebugFormContainer'
import CreateFaucetPage from './components/CreateFaucetPage'
import FaucetPage from './components/FaucetPage'
import AuthorizeFaucetPage from './components/AuthorizeFaucetPage'
import { getFaucetByName } from './store/ethereum/faucet/actions'
const routes = (store) => {
const fetchFaucet = () => {
let faucetName = getFaucetNameFromPath(window.location.pathname)
if (faucetName) {
store.dispatch(getFaucetByName(faucetName))
}
}
const getFaucetNameFromPath = (path) => {
if (pathContainsFaucet(path)) {
var parts = decodeURI(path).split('/')
let cleanName = parts[2].toLowerCase().replace(/\s+/g, '-')
return cleanName
}
return null
}
const pathContainsFaucet = (pathname) => {
return pathname.indexOf('/faucets/') !== -1
}
return (
<Route path='/' component={CoreLayout}>
<IndexRoute component={HomePage} />
<Route path={DebugRoute} component={DebugFormContainer} />
<Route path={CreateFaucetRoute} component={CreateFaucetPage} />
<Route path={FaucetRoute} component={FaucetPage} onEnter={fetchFaucet} />
<Route path={AuthorizeFaucetRoute} component={AuthorizeFaucetPage} />
<Redirect from='*' to='/' />
</Route>
)
}
export default routes
|
services/web/client/containers/search.js | apparatus/mu-app | 'use strict'
import React from 'react'
import {connect} from 'react-redux'
import {search} from '../actions/search'
import {SearchResult} from '../components/search-result'
import { Row, Col, RowCol } from '../components/layout'
export const Home = React.createClass({
propTypes: {
dispatch: React.PropTypes.func.isRequired
},
handleSearch (event) {
event.preventDefault()
const {query} = this.refs
const {dispatch} = this.props
dispatch(search(query.value))
},
render () {
let query = this.props.query
let items = this.props.result
let body = null
if (!items || items.length <= 0) {
body = (
query ? <div className="alert alert-info alert-has-icon txt-left">
<p className="m0">No results found for: {query}</p>
</div> : ''
)
}
else {
body = items.map((item) => {
return <SearchResult key={item.name} data={item} />
})
}
return (
<Col xs={12}>
<RowCol rowClass="center-xs" colElement='form' id="query-form" xs={12} md={8} className="panel" onSubmit={this.handleSearch}>
<Row>
<Col xs={12} sm={8}>
<input ref="query" type="search" placeholder="Module Name" id="query-term" className="input-large" />
</Col>
<Col xs={12} sm={4}>
<button id="query-submit" type="submit" className="btn btn-large">Search</button>
</Col>
</Row>
</RowCol>
<Row className="center-xs">
{body}
</Row>
</Col>
)
}
})
function mapStatesToProps (state) {
return {
query: state.search.query,
result: state.search.result
}
}
export default connect(mapStatesToProps)(Home)
|
src/routes.js | SWTPAIN/react-redux-universal-hot-example | import React from 'react';
import {Route} from 'react-router';
import {
App,
Home,
Widgets,
About,
Login,
RequireLogin,
LoginSuccess,
Survey,
NotFound,
} from 'containers';
export default function(store) {
return (
<Route component={App}>
<Route path="/" component={Home}/>
<Route path="/widgets" component={Widgets}/>
<Route path="/about" component={About}/>
<Route path="/login" component={Login}/>
<Route component={RequireLogin} onEnter={RequireLogin.onEnter(store)}>
<Route path="/loginSuccess" component={LoginSuccess}/>
</Route>
<Route path="/survey" component={Survey}/>
<Route path="*" component={NotFound}/>
</Route>
);
}
|
src/svg-icons/maps/local-convenience-store.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalConvenienceStore = (props) => (
<SvgIcon {...props}>
<path d="M19 7V4H5v3H2v13h8v-4h4v4h8V7h-3zm-8 3H9v1h2v1H8V9h2V8H8V7h3v3zm5 2h-1v-2h-2V7h1v2h1V7h1v5z"/>
</SvgIcon>
);
MapsLocalConvenienceStore = pure(MapsLocalConvenienceStore);
MapsLocalConvenienceStore.displayName = 'MapsLocalConvenienceStore';
MapsLocalConvenienceStore.muiName = 'SvgIcon';
export default MapsLocalConvenienceStore;
|
src/components/Header.js | amit-kulkarni/react-food-order | import React from 'react';
export default function Header(props) {
return (
<div className="container header">
<div className="row align-items-center py-3">
<div className="col-md-10">
<h3>
<i className="fa fa-cutlery mr-3" aria-hidden="true"></i>
<span>Order Food</span>
</h3>
</div>
<div className="col-md-2">
<i className="fa fa-shopping-cart mr-1"></i>
<span style={{ fontSize: "0.75rem" }}>{props.orderCount}</span>
</div>
</div>
</div >
);
} |
src/core/scenes.js | CharlesMangwa/Chloe | /* @flow */
import React from 'react'
import { Actions, Scene } from 'react-native-router-flux'
import { AdvertScene } from '@Advert/scenes'
import { ThemesScene } from '@Themes/scenes'
import { ChaptersScene } from '@Chapters/scenes'
import { StoryOverviewScene } from '@StoryOverview/scenes'
import { StoryScene } from '@Story/scenes'
export default Actions.create(
<Scene key="root" hideNavBar={true}>
<Scene key="themes" component={ThemesScene} title="Themes" />
<Scene key="advert" component={AdvertScene} title="Advert" />
<Scene key="chapters" component={ChaptersScene} title="Chapters" />
<Scene key="storyOverview" component={StoryOverviewScene} title="Story Overview" />
<Scene key="story" component={StoryScene} title="Story" />
</Scene>
)
|
react/src/components/ThumbnailSizes/index.js | sinfin/folio | import React from 'react'
import ThumbnailSize from './ThumbnailSize'
function ThumbnailSizes ({ file, updateThumbnail }) {
const thumbnailSizes = file.attributes.thumbnail_sizes
if (!thumbnailSizes) return null
const keys = Object.keys(thumbnailSizes)
if (keys.length === 0) return null
return (
<React.Fragment>
<h4 className='mt-0'>{window.FolioConsole.translations.thumbnailSizes}</h4>
<div className='d-flex flex-wrap'>
{keys.map((key) => <ThumbnailSize key={key} thumbKey={key} thumb={thumbnailSizes[key]} file={file} updateThumbnail={updateThumbnail} />)}
</div>
</React.Fragment>
)
}
export default ThumbnailSizes
|
examples/03 - Basic auth/components/Dashboard.js | Kureev/browserify-react-live | import React from 'react';
import auth from '../vendor/auth';
export default class Dashboard extends React.Component {
render() {
var token = auth.getToken();
return (
<div>
<h1>Dashboard</h1>
<p>You made it!</p>
<p>{token}</p>
</div>
);
}
}
|
ext/lib/site/auth-facebook/confirm/component.js | RosarioCiudad/democracyos | import React from 'react'
export default () => {
const user = window.initialState.authFacebookConfirmUser
return (
<div className='container-simple ext-auth-facebook-confirm'>
<p className='title'>Ingresar como:</p>
<div className='avatar'>
<img src={user.avatar} alt={user.displayName} />
<i className='icon-social-facebook' />
</div>
<h3 className='name'>{user.displayName}</h3>
<a
href='/auth/facebook'
className='confirm btn btn-block btn-success'>
Ingresar
</a>
</div>
)
}
|
test/lists/list-item-spec.js | Syncano/material-ui | import React from 'react';
import ListItem from 'lists/list-item';
import Checkbox from 'checkbox';
import injectTheme from '../fixtures/inject-theme';
import TestUtils from 'react-addons-test-utils';
describe('ListItem', () => {
let ThemedListItem;
beforeEach(() => {
ThemedListItem = injectTheme(ListItem);
});
it('should display a list-item', () => {
let render = TestUtils.renderIntoDocument(
<ThemedListItem />
);
let nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
let itemSpan = nodeTree[0].firstChild;
expect(itemSpan.tagName).to.equal('SPAN');
});
it('should display a list-item with text if primaryText is specified', () => {
let testText = 'Primary Text';
let render = TestUtils.renderIntoDocument(
<ThemedListItem
primaryText={testText}
/>
);
let nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
let itemSpan = nodeTree[0].firstChild;
expect(itemSpan.childNodes[0].innerText).to.equal(testText);
});
it('should display a list-item elment with a class if specified', () => {
let testClass = 'test-class';
let render = TestUtils.renderIntoDocument(
<ThemedListItem
className={testClass}
/>
);
let nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
let itemSpan = nodeTree[0].firstChild;
expect(itemSpan.hasAttribute('class')).to.be.true;
expect(itemSpan.getAttribute('class')).to.equal(testClass);
});
it('should display a disabled list-item if specified.', () => {
let render = TestUtils.renderIntoDocument(
<ThemedListItem
disabled={true}
/>
);
let nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
let itemDiv = nodeTree[0].firstChild;
expect(itemDiv.tagName).to.equal('DIV');
});
it('should display a disabled list-item with a class if specified.', () => {
let testClass = 'test-class';
let render = TestUtils.renderIntoDocument(
<ThemedListItem
className={testClass}
disabled={true}
/>
);
let nodeTree = TestUtils.scryRenderedDOMComponentsWithTag(render, 'div');
let itemDiv = nodeTree[0].firstChild;
expect(itemDiv.tagName).to.equal('DIV');
expect(itemDiv.hasAttribute('class')).to.be.true;
expect(itemDiv.getAttribute('class')).to.equal(testClass);
});
it('should display a checkbox in the list-item if specified.', () => {
let render = TestUtils.renderIntoDocument(
<ThemedListItem
leftCheckbox={<Checkbox />}
/>
);
let input = TestUtils.findRenderedDOMComponentWithTag(render, 'input');
expect(input.parentElement.tagName).to.equal('DIV');
expect(input.hasAttribute('checked')).to.be.false;
});
it('should have a class if specified with a checkbox.', () => {
let testClass = 'test-class';
let render = TestUtils.renderIntoDocument(
<ThemedListItem
leftCheckbox={<Checkbox />}
className={testClass}
/>
);
let input = TestUtils.findRenderedDOMComponentWithTag(render, 'input');
let listItemDiv = input.parentElement.parentElement;
expect(listItemDiv.tagName).to.equal('LABEL');
expect(listItemDiv.hasAttribute('class')).to.be.true;
expect(listItemDiv.getAttribute('class')).to.equal(testClass);
});
});
|
node_modules/react-router/es6/RoutingContext.js | superKaigon/TheCave | import React from 'react';
import RouterContext from './RouterContext';
import warning from './routerWarning';
var RoutingContext = React.createClass({
displayName: 'RoutingContext',
componentWillMount: function componentWillMount() {
process.env.NODE_ENV !== 'production' ? warning(false, '`RoutingContext` has been renamed to `RouterContext`. Please use `import { RouterContext } from \'react-router\'`. http://tiny.cc/router-routercontext') : void 0;
},
render: function render() {
return React.createElement(RouterContext, this.props);
}
});
export default RoutingContext; |
JotunheimenPlaces/src/components/Button.js | designrad/Jotunheimen-tracking | import React, { Component } from 'react';
import ReactNative from 'react-native';
const {
StyleSheet,
Text,
View,
TouchableOpacity
} = ReactNative;
/**
* Button component
*/
export default class Button extends Component {
/**
* Render a Button
* @return {jsxresult} result in jsx format
*/
render() {
return (
<TouchableOpacity style={styles.button} onPress={this.props.onPress}>
<Text style={styles.whiteFont}>{this.props.children}</Text>
</TouchableOpacity>
);
}
}
const styles = StyleSheet.create({
button: {
backgroundColor: '#01743D',
padding: 15,
alignItems: 'center',
borderWidth: 0
},
whiteFont: {
color: '#fff',
fontFamily: 'Roboto-Light',
fontSize: 20
}
}); |
lib/ui/src/containers/preview.js | storybooks/react-storybook | import { PREVIEW_URL } from 'global';
import React from 'react';
import { Consumer } from '@storybook/api';
import { Preview } from '../components/preview/preview';
const nonAlphanumSpace = /[^a-z0-9 ]/gi;
const doubleSpace = /\s\s/gi;
const replacer = match => ` ${match} `;
const addExtraWhiteSpace = input =>
input.replace(nonAlphanumSpace, replacer).replace(doubleSpace, ' ');
const getDescription = (storiesHash, storyId) => {
const storyInfo = storiesHash[storyId];
return storyInfo ? addExtraWhiteSpace(`${storyInfo.kind} - ${storyInfo.name}`) : '';
};
const mapper = ({ api, state: { layout, location, customQueryParams, storiesHash, storyId } }) => {
const story = storiesHash[storyId];
return {
api,
getElements: api.getElements,
options: layout,
description: getDescription(storiesHash, storyId),
...api.getUrlState(),
queryParams: customQueryParams,
docsOnly: story && story.parameters && story.parameters.docsOnly,
location,
};
};
function getBaseUrl() {
try {
return PREVIEW_URL || 'iframe.html';
} catch (e) {
return 'iframe.html';
}
}
const PreviewConnected = React.memo(props => (
<Consumer filter={mapper}>
{fromState => {
return (
<Preview
{...props}
baseUrl={getBaseUrl()}
{...fromState}
customCanvas={fromState.api.renderPreview}
/>
);
}}
</Consumer>
));
PreviewConnected.displayName = 'PreviewConnected';
export default PreviewConnected;
|
examples/huge-apps/app.js | axross/react-router | /*eslint-disable no-unused-vars */
import React from 'react'
import { createHistory, useBasename } from 'history'
import { Router } from 'react-router'
import stubbedCourses from './stubs/COURSES'
const history = useBasename(createHistory)({
basename: '/huge-apps'
})
const rootRoute = {
component: 'div',
childRoutes: [ {
path: '/',
component: require('./components/App'),
childRoutes: [
require('./routes/Calendar'),
require('./routes/Course'),
require('./routes/Grades'),
require('./routes/Messages'),
require('./routes/Profile')
]
} ]
}
React.render(
<Router history={history} routes={rootRoute} />,
document.getElementById('example')
)
// I've unrolled the recursive directory loop that is happening above to get a
// better idea of just what this huge-apps Router looks like
//
// import { Route } from 'react-router'
// import App from './components/App'
// import Course from './routes/Course/components/Course'
// import AnnouncementsSidebar from './routes/Course/routes/Announcements/components/Sidebar'
// import Announcements from './routes/Course/routes/Announcements/components/Announcements'
// import Announcement from './routes/Course/routes/Announcements/routes/Announcement/components/Announcement'
// import AssignmentsSidebar from './routes/Course/routes/Assignments/components/Sidebar'
// import Assignments from './routes/Course/routes/Assignments/components/Assignments'
// import Assignment from './routes/Course/routes/Assignments/routes/Assignment/components/Assignment'
// import CourseGrades from './routes/Course/routes/Grades/components/Grades'
// import Calendar from './routes/Calendar/components/Calendar'
// import Grades from './routes/Grades/components/Grades'
// import Messages from './routes/Messages/components/Messages'
// React.render(
// <Router>
// <Route path="/" component={App}>
// <Route path="calendar" component={Calendar} />
// <Route path="course/:courseId" component={Course}>
// <Route path="announcements" components={{
// sidebar: AnnouncementsSidebar,
// main: Announcements
// }}>
// <Route path=":announcementId" component={Announcement} />
// </Route>
// <Route path="assignments" components={{
// sidebar: AssignmentsSidebar,
// main: Assignments
// }}>
// <Route path=":assignmentId" component={Assignment} />
// </Route>
// <Route path="grades" component={CourseGrades} />
// </Route>
// <Route path="grades" component={Grades} />
// <Route path="messages" component={Messages} />
// <Route path="profile" component={Calendar} />
// </Route>
// </Router>,
// document.getElementById('example')
// )
|
routes/Statistic/components/DotInfo.js | YongYuH/Ludo | import React from 'react';
import styled from 'styled-components';
import { translate } from 'react-i18next';
import Card from './Card';
import Button from '../../../components/Button';
const ButtonWrapper = styled.div`
margin-top: 10px;
`;
const Wrapper = styled.div`
`;
const DotInfo = ({
t,
}) => (
<Wrapper>
<Card />
<ButtonWrapper>
<Button
backgroundColor="#2fa0dd"
label={t('show reportList')}
/>
</ButtonWrapper>
</Wrapper>
);
export default translate(['statistic'])(DotInfo);
|
client/components/Layout/Layout.js | kriasoft/FSharp-Server-Template | /**
* ASP.NET Core Starter Kit
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Header from './Header';
import s from './Layout.css';
class Layout extends React.Component {
componentDidMount() {
window.componentHandler.upgradeElement(this.refs.root);
}
componentWillUnmount() {
window.componentHandler.downgradeElements(this.refs.root);
}
render() {
return (
<div className="mdl-layout mdl-js-layout" ref="root">
<div className="mdl-layout__inner-container">
<div className={s.ribbon}>
<Header />
<div className={s.container}>
<h1 className={`mdl-typography--title ${s.tagline}`}>ASP.NET Core Starter Kit</h1>
<p className={`mdl-typography--body-1 ${s.summary}`}>
Single-page application boilerplate powered by .NET Core and React
</p>
</div>
</div>
<main {...this.props} className={s.content} />
</div>
</div>
);
}
}
export default Layout;
|
src/components/Lottery/Lottery.js | febobo/react-redux-start | import React from 'react'
import dynamicIco from '../../static/images/dynamicIco.png'
import aboutIco from '../../static/images/aboutIco.png'
import classes from '../Lottery/Lottery.scss'
import {i18n} from '../../util/i18n'
import { getBtcWebsocket , btcWebsocket } from '../../actions/Websocket'
import { connect } from 'react-redux'
import { Alert , Table ,Tag } from 'antd'
import moment from 'moment'
type Props = {
};
export class Lottery extends React.Component {
props: Props;
componentWillMount (){
// this._stream()
const { getBtcWebsocket , btcWebsocket } = this.props;
getBtcWebsocket()
// btcWebsocket({name : 1})
}
componentDidMount (){
// let warp = document.getElementById('listScroll');
// console.log(warp.scrollTop)
// setInterval( () =>{
// if(warp.scrollTop >= 105){
// warp.scrollTop =0;
// }else {
// warp.scrollTop ++ ;
// }
// },100)
}
render () {
const { users_online , latest_incomes } = this.props.lottery;
const { isDynamic , style } = this.props;
// const list = latest_incomes && latest_incomes.length && latest_incomes.map( (v, k) => {
// return (
// <div key={'lottery' + k }>
// <div>{v.address}</div>
// <div>{v.amount}</div>
// <div>{moment(v.time).format("YYYY-MM-DD hh:mm:ss")}</div>
// </div>
// )
// })
const columns = [{
title: i18n.t('common.btcAddress'),
dataIndex: 'address',
render(text) {
return <a href="#">{text}</a>;
}
}, {
title: i18n.t('common.amount'),
dataIndex: 'amount'
}, {
title: i18n.t('common.time'),
dataIndex: 'time'
}];
const data = [];
latest_incomes && latest_incomes.length && latest_incomes.map( (v, k) => {
data.push({
key: `${k}`,
address: `${v.address}`,
amount: <Tag color="blue">{v.amount.toFixed(8)}</Tag>,
time: moment(Date.parse(`${v.time}`)).format("YYYY-MM-DD HH:mm:ss"),
});
})
return (
<div className={classes.dynamic} style={style}>
{
isDynamic ?
null :
<div className={classes.dynamicTitle}><img src={dynamicIco.png} /><span><b>{i18n.t('common.dynamic')}</b></span></div>
}
<Table
columns={columns}
dataSource={data}
bordered={true}
pagination={false}
size="small"
ref="box"
rowClassName={(v,k) =>{
return 'lottery' + k
}}
/>
</div>
)
}
}
// <div className={classes.lotteryTable}>
// <div className={classes.lotteryTitle}>
// <div>Address</div>
// <div>Amount</div>
// <div>Time</div>
// </div>
// <div className={classes.lotterybody} id="listScroll">
// // {
// // list ?
// // list :
// // null
// // }
// </div>
// </div>
export default Lottery;
const mapActionCreators = {
getBtcWebsocket,
btcWebsocket
}
const mapStateToProps = (state)=>
({
lottery : state.lottery,
})
export default connect(mapStateToProps, mapActionCreators)(Lottery)
|
src/components/views/globals/NewVersionBar.js | aperezdc/matrix-react-sdk | /*
Copyright 2015, 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
import React from 'react';
import sdk from '../../../index';
import Modal from '../../../Modal';
import PlatformPeg from '../../../PlatformPeg';
import { _t } from '../../../languageHandler';
/**
* Check a version string is compatible with the Changelog
* dialog ([vectorversion]-react-[react-sdk-version]-js-[js-sdk-version])
*/
function checkVersion(ver) {
const parts = ver.split('-');
return parts.length == 5 && parts[1] == 'react' && parts[3] == 'js';
}
export default React.createClass({
propTypes: {
version: React.PropTypes.string.isRequired,
newVersion: React.PropTypes.string.isRequired,
releaseNotes: React.PropTypes.string,
},
displayReleaseNotes: function(releaseNotes) {
const QuestionDialog = sdk.getComponent('dialogs.QuestionDialog');
Modal.createTrackedDialog('Display release notes', '', QuestionDialog, {
title: _t("What's New"),
description: <div className="mx_MatrixToolbar_changelog">{releaseNotes}</div>,
button: _t("Update"),
onFinished: (update) => {
if(update && PlatformPeg.get()) {
PlatformPeg.get().installUpdate();
}
}
});
},
displayChangelog: function() {
const ChangelogDialog = sdk.getComponent('dialogs.ChangelogDialog');
Modal.createTrackedDialog('Display Changelog', '', ChangelogDialog, {
version: this.props.version,
newVersion: this.props.newVersion,
onFinished: (update) => {
if(update && PlatformPeg.get()) {
PlatformPeg.get().installUpdate();
}
}
});
},
onUpdateClicked: function() {
PlatformPeg.get().installUpdate();
},
render: function() {
let action_button;
// If we have release notes to display, we display them. Otherwise,
// we display the Changelog Dialog which takes two versions and
// automatically tells you what's changed (provided the versions
// are in the right format)
if (this.props.releaseNotes) {
action_button = (
<button className="mx_MatrixToolbar_action" onClick={this.displayReleaseNotes}>
{ _t("What's new?") }
</button>
);
} else if (checkVersion(this.props.version) && checkVersion(this.props.newVersion)) {
action_button = (
<button className="mx_MatrixToolbar_action" onClick={this.displayChangelog}>
{ _t("What's new?") }
</button>
);
} else if (PlatformPeg.get()) {
action_button = (
<button className="mx_MatrixToolbar_action" onClick={this.onUpdateClicked}>
{ _t("Update") }
</button>
);
}
return (
<div className="mx_MatrixToolbar">
<img className="mx_MatrixToolbar_warning" src="img/warning.svg" width="24" height="23" alt="Warning"/>
<div className="mx_MatrixToolbar_content">
{_t("A new version of Riot is available.")}
</div>
{action_button}
</div>
);
}
});
|
test/TableSpec.js | apisandipas/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Table from '../src/Table';
describe('Table', function () {
it('Should be a table', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Table />
);
assert.equal(React.findDOMNode(instance).nodeName, 'TABLE');
assert.ok(React.findDOMNode(instance).className.match(/\btable\b/));
});
it('Should have correct class when striped', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Table striped />
);
assert.ok(React.findDOMNode(instance).className.match(/\btable-striped\b/));
});
it('Should have correct class when hover', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Table hover />
);
assert.ok(React.findDOMNode(instance).className.match(/\btable-hover\b/));
});
it('Should have correct class when bordered', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Table bordered />
);
assert.ok(React.findDOMNode(instance).className.match(/\btable-bordered\b/));
});
it('Should have correct class when condensed', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Table condensed />
);
assert.ok(React.findDOMNode(instance).className.match(/\btable-condensed\b/));
});
it('Should have responsive wrapper', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Table responsive />
);
assert.ok(React.findDOMNode(instance).className.match(/\btable-responsive\b/));
assert.ok(React.findDOMNode(instance).firstChild.className.match(/\btable\b/));
});
});
|
frontend/components/indexComponent.js | yograterol/viperid | import React from 'react';
import { connect } from 'react-redux';
import CodeMirror from './codemirror';
import ViperidPanel from './panel';
import Head from './head';
import configureStore from '../store';
class IndexComponent extends React.Component {
render() {
return (
<div>
<Head />
<div className="wrapper">
<CodeMirror {...this.props} />
<ViperidPanel {...this.props} />
</div>
</div>
);
}
}
function mapStateToProps(state) {
const { currentSourceCode, compileCode } = state;
let { isCompiling, result, error } = compileCode || {
isCompiling: false,
result: {}
};
if (!currentSourceCode) {
isCompiling = false;
}
return {
currentSourceCode,
result,
isCompiling,
error
};
}
export default connect(mapStateToProps)(IndexComponent);
|
app/javascript/mastodon/features/compose/components/poll_button.js | yukimochi/mastodon | import React from 'react';
import IconButton from '../../../components/icon_button';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
add_poll: { id: 'poll_button.add_poll', defaultMessage: 'Add a poll' },
remove_poll: { id: 'poll_button.remove_poll', defaultMessage: 'Remove poll' },
});
const iconStyle = {
height: null,
lineHeight: '27px',
};
export default
@injectIntl
class PollButton extends React.PureComponent {
static propTypes = {
disabled: PropTypes.bool,
unavailable: PropTypes.bool,
active: PropTypes.bool,
onClick: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onClick();
}
render () {
const { intl, active, unavailable, disabled } = this.props;
if (unavailable) {
return null;
}
return (
<div className='compose-form__poll-button'>
<IconButton
icon='tasks'
title={intl.formatMessage(active ? messages.remove_poll : messages.add_poll)}
disabled={disabled}
onClick={this.handleClick}
className={`compose-form__poll-button-icon ${active ? 'active' : ''}`}
size={18}
inverted
style={iconStyle}
/>
</div>
);
}
}
|
app/components/FormInput/index.js | JSSolutions/Perfi | import React from 'react';
import T from 'prop-types';
import { ViewPropTypes } from 'react-native';
import Input from '../Input';
import TouchableItem from '../TouchableItem';
import Text from '../Text';
import s from './styles';
import { colors, dimensions } from '../../styles';
const renderIcon = (icon) => {
if (icon.name) {
return {
...icon,
size: dimensions.iconSize,
};
}
return null;
};
const FormInput = (props) => {
const {
isDropped,
onPress,
value,
placeholder,
disabledPlaceholder,
style,
containerStyle,
isSelected,
icon,
label,
labelStyle,
disabled = false,
} = props;
return (
<TouchableItem onPress={onPress} style={containerStyle}>
{!!label && <Text style={[s.label, labelStyle]}>{label}</Text>}
<Input
editable={false}
containerStyle={style}
secondContainerStyle={[s.secondInputContainer, disabled && {
backgroundColor: colors.grey,
}, isSelected && s.selectedSecondInputContainer]}
style={[s.inputStyle, isSelected && s.selectedInputStile]}
isValid
icon={renderIcon(icon, isDropped)}
iconRight={{
name: isDropped ? 'chevron-up' : 'chevron-down',
size: dimensions.iconSize - 4,
color: isSelected ? colors.green : colors.grey,
}}
leftIconStyle={s.leftIconStyle}
rightIconStyle={s.rightIconStyle}
multiline={false}
pointerEvents="none"
value={value}
placeholder={disabled ? disabledPlaceholder : placeholder}
placeholderColor={disabled ? colors.green : null}
/>
</TouchableItem>
);
};
FormInput.propTypes = {
isDropped: T.bool,
onPress: T.func,
placeholder: T.string,
disabledPlaceholder: T.string,
style: ViewPropTypes.style,
containerStyle: ViewPropTypes.style,
value: T.string,
isSelected: T.any,
icon: T.object,
label: T.string,
labelStyle: Text.propTypes.style,
disabled: T.bool,
};
export default FormInput;
|
_theme/template/Articles.js | ElemeFE/react-amap | import React from 'react';
import Layout from './Layout';
import SideMenu from './Menu/SideMenu';
import PureArticle from './Content/PureArticle';
export default function Article(props) {
const pageData = props.pageData;
return <Layout route={props.route}>
<div id="doc">
<aside id="aside">
<SideMenu
type="articles"
defaultSelectedKey={props.routeParams.doc}
data={props.data}
/>
</aside>
<article id="article" className="pure-article">
<PureArticle pageData={pageData} utils={props.utils}/>
</article>
</div>
</Layout>;
}
|
src/containers/App.js | ashmaroli/jekyll-admin | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { HotKeys } from 'react-hotkeys';
import DocumentTitle from 'react-document-title';
import { fetchConfig } from '../ducks/config';
import { fetchMeta } from '../ducks/dashboard';
import keyboardShortcuts from '../constants/keyboardShortcuts';
// Components
import Sidebar from './Sidebar';
import Header from './Header';
import Notifications from './Notifications';
class App extends Component {
componentDidMount() {
const { fetchConfig, fetchMeta } = this.props;
fetchConfig();
fetchMeta();
}
componentWillReceiveProps(nextProps) {
if (this.props.updated !== nextProps.updated) {
const { fetchConfig } = this.props;
fetchConfig();
}
}
render() {
const { isFetching } = this.props;
if (isFetching) {
return null;
}
const config = this.props.config.content;
const { admin, site } = this.props.meta;
return (
<DocumentTitle title="Jekyll Manager">
<HotKeys keyMap={keyboardShortcuts} className="wrapper">
{
config &&
<div>
{site && <Sidebar config={config} site={site} />}
<div className="container">
{admin && <Header config={config} admin={admin} />}
<div className="content">
{this.props.children}
</div>
</div>
<Notifications />
</div>
}
</HotKeys>
</DocumentTitle>
);
}
}
App.propTypes = {
children: PropTypes.element,
fetchConfig: PropTypes.func.isRequired,
fetchMeta: PropTypes.func.isRequired,
config: PropTypes.object.isRequired,
meta: PropTypes.object.isRequired,
isFetching: PropTypes.bool.isRequired,
updated: PropTypes.bool
};
const mapStateToProps = (state) => ({
config: state.config.config,
meta: state.dashboard.meta,
updated: state.config.updated,
isFetching: state.config.isFetching,
});
const mapDispatchToProps = (dispatch) => bindActionCreators({
fetchConfig,
fetchMeta
}, dispatch);
export default connect(mapStateToProps, mapDispatchToProps)(App);
|
src/svg-icons/social/share.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialShare = (props) => (
<SvgIcon {...props}>
<path d="M18 16.08c-.76 0-1.44.3-1.96.77L8.91 12.7c.05-.23.09-.46.09-.7s-.04-.47-.09-.7l7.05-4.11c.54.5 1.25.81 2.04.81 1.66 0 3-1.34 3-3s-1.34-3-3-3-3 1.34-3 3c0 .24.04.47.09.7L8.04 9.81C7.5 9.31 6.79 9 6 9c-1.66 0-3 1.34-3 3s1.34 3 3 3c.79 0 1.5-.31 2.04-.81l7.12 4.16c-.05.21-.08.43-.08.65 0 1.61 1.31 2.92 2.92 2.92 1.61 0 2.92-1.31 2.92-2.92s-1.31-2.92-2.92-2.92z"/>
</SvgIcon>
);
SocialShare = pure(SocialShare);
SocialShare.displayName = 'SocialShare';
SocialShare.muiName = 'SvgIcon';
export default SocialShare;
|
views/decoration_toggle.js | williara/black-screen | import React from 'react';
export default React.createClass({
getInitialState() {
return {enabled: this.props.invocation.state.decorate};
},
handleClick(event) {
stopBubblingUp(event);
var newState = !this.state.enabled;
this.setState({enabled: newState});
this.props.invocation.setState({decorate: newState});
},
render() {
var classes = ['decoration-toggle'];
if (!this.state.enabled) {
classes.push('disabled');
}
return (
<a href="#" className={classes.join(' ')} onClick={this.handleClick}>
<i className="fa fa-magic"></i>
</a>
);
}
});
|
docs/src/pages/component-demos/app-bar/ButtonAppBar.js | dsslimshaddy/material-ui | // @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import AppBar from 'material-ui/AppBar';
import Toolbar from 'material-ui/Toolbar';
import Typography from 'material-ui/Typography';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import MenuIcon from 'material-ui-icons/Menu';
const styles = {
root: {
marginTop: 30,
width: '100%',
},
flex: {
flex: 1,
},
};
function ButtonAppBar(props) {
const classes = props.classes;
return (
<div className={classes.root}>
<AppBar position="static">
<Toolbar>
<IconButton color="contrast" aria-label="Menu">
<MenuIcon />
</IconButton>
<Typography type="title" color="inherit" className={classes.flex}>
Title
</Typography>
<Button color="contrast">Login</Button>
</Toolbar>
</AppBar>
</div>
);
}
ButtonAppBar.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(ButtonAppBar);
|
app/javascript/mastodon/features/ui/components/upload_area.js | tootsuite/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { FormattedMessage } from 'react-intl';
export default class UploadArea extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onClose: PropTypes.func,
};
handleKeyUp = (e) => {
const keyCode = e.keyCode;
if (this.props.active) {
switch(keyCode) {
case 27:
e.preventDefault();
e.stopPropagation();
this.props.onClose();
break;
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
}
render () {
const { active } = this.props;
return (
<Motion defaultStyle={{ backgroundOpacity: 0, backgroundScale: 0.95 }} style={{ backgroundOpacity: spring(active ? 1 : 0, { stiffness: 150, damping: 15 }), backgroundScale: spring(active ? 1 : 0.95, { stiffness: 200, damping: 3 }) }}>
{({ backgroundOpacity, backgroundScale }) => (
<div className='upload-area' style={{ visibility: active ? 'visible' : 'hidden', opacity: backgroundOpacity }}>
<div className='upload-area__drop'>
<div className='upload-area__background' style={{ transform: `scale(${backgroundScale})` }} />
<div className='upload-area__content'><FormattedMessage id='upload_area.title' defaultMessage='Drag & drop to upload' /></div>
</div>
</div>
)}
</Motion>
);
}
}
|
src/components/GraphControls.js | chrisfisher/graph-editor | // @flow
import React from 'react';
import { connect } from 'react-redux';
import {
addNode,
deleteNodes,
bringNodesToFront,
sendNodesToBack,
addManyNodes,
selectAllNodes,
} from '../actions';
const DEFAULT_NODE_WIDTH = 100;
const DEFAULT_NODE_HEIGHT = 100;
const GraphControls = props => (
<div>
<span className="button" onClick={() => { props.addNode(DEFAULT_NODE_WIDTH, DEFAULT_NODE_HEIGHT); }}>Add</span>
<span className="button" onClick={() => { props.addManyNodes(DEFAULT_NODE_WIDTH, DEFAULT_NODE_HEIGHT); }}>Add many</span>
<span className="button" onClick={() => { props.selectAllNodes(); }}>Select all</span>
<span className="button" onClick={() => { props.deleteNodes(); }}>Delete</span>
<span className="button" onClick={() => { props.bringNodesToFront(); }}>Bring to front</span>
<span className="button" onClick={() => { props.sendNodesToBack(); }}>Send to back</span>
</div>
);
export default connect(
null,
{
addNode,
deleteNodes,
bringNodesToFront,
sendNodesToBack,
addManyNodes,
selectAllNodes,
}
)(GraphControls);
|
src/svg-icons/action/search.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let 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 = pure(ActionSearch);
ActionSearch.displayName = 'ActionSearch';
ActionSearch.muiName = 'SvgIcon';
export default ActionSearch;
|
src/index.js | cindyqian/BoardGames | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import ReducerManager from './components/ReducerManager'
import {logger, currentAction, asyncDispatchMiddleware, callbackMiddleware} from './components/CommonMiddleware'
import cs from './services/CommunicationService'
import TopContainer from './components/TopContainer'
import MainRouteContainer from './components/MainRouteContainer'
import StackViewContainer from './components/StackViewContainer'
import { Router, Route, IndexRoute, useRouterHistory, browserHistory } from 'react-router'
import { createHashHistory } from 'history'
const history = useRouterHistory(createHashHistory)({ queryKey: false });
let store = createStore(ReducerManager, applyMiddleware(logger, currentAction, asyncDispatchMiddleware, callbackMiddleware));
cs.init(store);
render(
<Provider store={store}>
<Router history={browserHistory }>
<Route path='/' component={TopContainer}>
<IndexRoute component={MainRouteContainer} />
<Route path='main' component={MainRouteContainer} />
</Route>
<Route path='/cindyqian/BoardGames/' component={TopContainer}>
<IndexRoute component={MainRouteContainer} />
<Route path='main' component={MainRouteContainer} />
</Route>
</Router>
</Provider>,
document.getElementById('root')
)
|
src/containers/Ecommerce/checkout/billing-form.js | EncontrAR/backoffice | import React from 'react';
import Input from '../../../components/uielements/input';
import Select from '../../../components/uielements/select';
import Checkbox from '../../../components/uielements/checkbox';
import InputBox from './input-box';
import IntlMessages from '../../../components/utility/intlMessages';
const Option = Select.Option;
class BillingForm extends React.Component {
handleOnChange = checkedValues => {
console.log('checked = ', checkedValues);
};
render() {
return (
<div className="isoBillingForm">
<div className="isoInputFieldset">
<InputBox
label={<IntlMessages id="checkout.billingform.firstname" />}
important
/>
<InputBox
label={<IntlMessages id="checkout.billingform.lastname" />}
important
/>
</div>
<div className="isoInputFieldset">
<InputBox
label={<IntlMessages id="checkout.billingform.company" />}
/>
</div>
<div className="isoInputFieldset">
<InputBox
label={<IntlMessages id="checkout.billingform.email" />}
important
/>
<InputBox label={<IntlMessages id="checkout.billingform.mobile" />} />
</div>
<div className="isoInputFieldset">
<div className="isoInputBox">
<label>
{<IntlMessages id="checkout.billingform.country" />}
</label>
<Select size="large" defaultValue="unitedstate">
<Option value="argentina">Argentina</Option>
<Option value="australia">Australia</Option>
<Option value="brazil">Brazil</Option>
<Option value="france">France</Option>
<Option value="germany">Germany</Option>
<Option value="southafrica">South Africa</Option>
<Option value="spain">Spain</Option>
<Option value="unitedstate">United State</Option>
<Option value="unitedkingdom">United Kingdom</Option>
</Select>
</div>
<InputBox label={<IntlMessages id="checkout.billingform.city" />} />
</div>
<div className="isoInputFieldset vertical">
<InputBox
label={<IntlMessages id="checkout.billingform.address" />}
placeholder="Address"
/>
<Input
size="large"
placeholder="Apartment, suite, unit etc. (optional)"
style={{ marginTop: '35px' }}
/>
</div>
<Checkbox onChange={this.handleOnChange}>
<IntlMessages id="checkout.billingform.checkbox" />
</Checkbox>
</div>
);
}
}
export default BillingForm;
|
client/src/entwine/TinyMCE_sslink-file.js | silverstripe/silverstripe-asset-admin | /* global tinymce, editorIdentifier, ss */
import i18n from 'i18n';
import TinyMCEActionRegistrar from 'lib/TinyMCEActionRegistrar';
import React from 'react';
import ReactDOM from 'react-dom';
import jQuery from 'jquery';
import ShortcodeSerialiser from 'lib/ShortcodeSerialiser';
import InsertMediaModal from 'containers/InsertMediaModal/InsertMediaModal';
import Injector, { loadComponent } from 'lib/Injector';
import * as modalActions from 'state/modal/ModalActions';
const commandName = 'sslinkfile';
// Link to external url
TinyMCEActionRegistrar.addAction(
'sslink',
{
text: i18n._t('AssetAdmin.LINKLABEL_FILE', 'Link to a file'),
// eslint-disable-next-line no-console
onclick: (activeEditor) => activeEditor.execCommand(commandName),
priority: 80
},
editorIdentifier,
).addCommandWithUrlTest(commandName, /^\[file_link/);
const plugin = {
init(editor) {
editor.addCommand(commandName, () => {
const field = jQuery(`#${editor.id}`).entwine('ss');
field.openLinkFileDialog();
});
},
};
const modalId = 'insert-link__dialog-wrapper--file';
const InjectableInsertMediaModal = loadComponent(InsertMediaModal);
jQuery.entwine('ss', ($) => {
$('textarea.htmleditor').entwine({
openLinkFileDialog() {
let dialog = $(`#${modalId}`);
if (!dialog.length) {
dialog = $(`<div id="${modalId}" />`);
$('body').append(dialog);
}
dialog.addClass('insert-link__dialog-wrapper');
dialog.setElement(this);
dialog.open();
},
});
/**
* Assumes that $('.insert-link__dialog-wrapper').entwine({}); is defined for shared functions
*/
$(`.js-injector-boot #${modalId}`).entwine({
renderModal(isOpen) {
// We're updating the redux store from outside react. This is a bit unusual, but it's
// the best way to initialise our modal setting.
const { dispatch } = Injector.reducer.store;
dispatch(modalActions.initFormStack('insert-link', 'admin'));
const handleHide = () => {
dispatch(modalActions.reset());
this.close();
};
const handleInsert = (...args) => this.handleInsert(...args);
const attrs = this.getOriginalAttributes();
const selection = tinymce.activeEditor.selection;
const selectionContent = selection.getContent() || '';
const tagName = selection.getNode().tagName;
const requireLinkText = tagName !== 'A' && selectionContent.trim() === '';
// create/update the react component
ReactDOM.render(
<InjectableInsertMediaModal
isOpen={isOpen}
type="insert-link"
onInsert={handleInsert}
onClosed={handleHide}
title={false}
bodyClassName="modal__dialog"
className="insert-link__dialog-wrapper--internal"
fileAttributes={attrs}
requireLinkText={requireLinkText}
/>,
this[0]
);
},
/**
* @param {Object} data - Posted data
* @return {Object}
*/
buildAttributes(data) {
const shortcode = ShortcodeSerialiser.serialise({
name: 'file_link',
properties: { id: data.ID },
}, true);
// Add anchor
const anchor = data.Anchor && data.Anchor.length ? `#${data.Anchor}` : '';
const href = `${shortcode}${anchor}`;
return {
href,
target: data.TargetBlank ? '_blank' : '',
title: data.Description,
};
},
getOriginalAttributes() {
const editor = this.getElement().getEditor();
const node = $(editor.getSelectedNode());
// Get href
const hrefParts = (node.attr('href') || '').split('#');
if (!hrefParts[0]) {
return {};
}
// check if file is safe
const shortcode = ShortcodeSerialiser.match('file_link', false, hrefParts[0]);
if (!shortcode) {
return {};
}
return {
ID: shortcode.properties.id ? parseInt(shortcode.properties.id, 10) : 0,
Anchor: hrefParts[1] || '',
Description: node.attr('title'),
TargetBlank: !!node.attr('target'),
};
},
});
});
// Adds the plugin class to the list of available TinyMCE plugins
tinymce.PluginManager.add(commandName, (editor) => plugin.init(editor));
export default plugin;
|
packages/sandbox/pages/index.js | styled-components/styled-components | import React from 'react';
import styled, { createGlobalStyle } from 'styled-components';
import ButtonExample from '../src/Button.example';
const GlobalStyle = createGlobalStyle`
body {
font-size: 16px;
line-height: 1.2;
font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", Helvetica, Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol";
font-style: normal;
padding: 0;
margin: 0;
color: rgb(46, 68, 78);
-webkit-font-smoothing: subpixel-antialiased;
}
* {
box-sizing: border-box;
}
`;
const Body = styled.main`
width: 100vw;
min-width: 100vw;
min-height: 100vh;
background-image: linear-gradient(20deg, #e6356f, #69e7f7);
padding: 30px 20px;
`;
const Heading = styled.div`
text-align: center;
`;
const Title = styled.h1`
@media (max-width: 40.625em) {
font-size: 26px;
}
`;
const Subtitle = styled.p``;
const Content = styled.div`
background: white;
display: flex;
align-items: center;
justify-content: center;
width: 100%;
max-width: 860px;
margin: 0 auto;
margin-top: 60px;
`;
const Code = styled.span`
white-space: pre;
vertical-align: middle;
font-family: monospace;
display: inline-block;
background-color: #1e1f27;
color: #c5c8c6;
padding: 0.1em 0.3em 0.15em;
font-size: 0.8em;
border-radius: 0.2em;
`;
const App = () => (
<Body>
<GlobalStyle />
<Heading>
<Title>
Interactive sandbox for <Code>styled-components</Code>
</Title>
<Subtitle>
Make changes to the files in <Code>./src</Code> and see them take effect in realtime!
</Subtitle>
</Heading>
<Content>
<ButtonExample />
</Content>
</Body>
);
export default App;
|
src/svg-icons/image/iso.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageIso = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM5.5 7.5h2v-2H9v2h2V9H9v2H7.5V9h-2V7.5zM19 19H5L19 5v14zm-2-2v-1.5h-5V17h5z"/>
</SvgIcon>
);
ImageIso = pure(ImageIso);
ImageIso.displayName = 'ImageIso';
ImageIso.muiName = 'SvgIcon';
export default ImageIso;
|
src/Accordion.js | pivotal-cf/react-bootstrap | import React from 'react';
import PanelGroup from './PanelGroup';
const Accordion = React.createClass({
render() {
return (
<PanelGroup {...this.props} accordion>
{this.props.children}
</PanelGroup>
);
}
});
export default Accordion;
|
src/ChipsCatalog.js | material-components/material-components-web-catalog | import React, { Component } from 'react';
import ComponentCatalogPanel from './ComponentCatalogPanel.js';
import {MDCChipSet} from '@material/chips/index';
import './styles/ChipsCatalog.scss';
const ChipsCatalog = () => {
return (
<ComponentCatalogPanel
hero={<ChipsHero />}
title='Chips'
description='Chips are compact elements that allow users to enter information, select a choice, filter content, or trigger an action.'
designLink='https://material.io/go/design-chips'
docsLink='https://material.io/components/web/catalog/chips/'
sourceLink='https://github.com/material-components/material-components-web/tree/master/packages/mdc-chips'
demos={<ChipsDemos />}
/>
);
}
export class ChipsHero extends Component {
constructor(props) {
super(props);
this.chipSet = null;
}
componentWillUnmount() {
this.chipSet.destroy();
}
renderChip(text) {
return (
<div className='mdc-chip' role='row'>
<div class='mdc-chip__ripple'></div>
<div className='mdc-chip__text'>{text}</div>
<span role='gridcell'>
<span role='button' tabIndex='0' class='mdc-chip__text'>Chip Two</span>
</span>
</div>
);
}
render() {
const initChipSet = chipSetEl => {
if (chipSetEl) {
this.chipSet = new MDCChipSet(chipSetEl);
}
}
return (
<div className='mdc-chip-set' role='grid' ref={initChipSet}>
{this.renderChip('Chip One')}
{this.renderChip('Chip Two')}
{this.renderChip('Chip Three')}
{this.renderChip('Chip Four')}
</div>
);
}
}
class ChipsDemos extends Component {
constructor(props) {
super(props);
this.chipSets = [];
}
componentWillUnmount() {
this.chipSets.forEach(chipSet => chipSet.destroy());
}
renderIcon(name, classes) {
return (
<i className={`material-icons mdc-chip__icon mdc-chip__icon--leading ${classes}`}>
{name}
</i>
);
}
renderFilterCheckmark() {
return(
<div className='mdc-chip__checkmark' >
<svg className='mdc-chip__checkmark-svg' viewBox='-2 -3 30 30'>
<path className='mdc-chip__checkmark-path' fill='none' stroke='black' d='M1.73,12.91 8.1,19.28 22.79,4.59'/>
</svg>
</div>
);
}
// For choice and action chips
renderChip(text, classes, leadingIcon) {
return (
<div className={`mdc-chip ${classes}`} role='row'>
{leadingIcon ? leadingIcon : ''}
<span role='button' tabIndex='0' class='mdc-chip__text'>{text}</span>
</div>
);
}
// For filter chips
renderFilterChip(text, classes, leadingIcon) {
return (
<div className={`mdc-chip ${classes}`} role='row'>
{leadingIcon}
{this.renderFilterCheckmark()}
<span role='button' tabIndex='0' class='mdc-chip__text'>{text}</span>
</div>
);
}
render() {
const initChipSet = chipSetEl => chipSetEl && this.chipSets.push(new MDCChipSet(chipSetEl));
return (
<div>
<h3 className='mdc-typography--subtitle1'>Choice Chips</h3>
<div className='mdc-chip-set mdc-chip-set--choice' ref={initChipSet}>
{this.renderChip('Extra Small')}
{this.renderChip('Small')}
{this.renderChip('Medium', 'mdc-chip--selected')}
{this.renderChip('Large')}
{this.renderChip('Extra Large')}
</div>
<h3 className='mdc-typography--subtitle1'>Filter Chips</h3>
<h3 className='mdc-typography--body2'>No leading icon</h3>
<div className='mdc-chip-set mdc-chip-set--filter' ref={initChipSet}>
{this.renderFilterChip('Tops', 'mdc-chip--selected')}
{this.renderFilterChip('Bottoms', 'mdc-chip--selected')}
{this.renderFilterChip('Shoes')}
{this.renderFilterChip('Accessories')}
</div>
<h3 className='mdc-typography--body2'>With leading icon</h3>
<div className='mdc-chip-set mdc-chip-set--filter' ref={initChipSet}>
{this.renderFilterChip('Alice',
'mdc-chip--selected',
this.renderIcon('face', 'mdc-chip__icon--leading mdc-chip__icon--leading-hidden'))}
{this.renderFilterChip('Bob',
'' /* classes */,
this.renderIcon('face', 'mdc-chip__icon--leading'))}
{this.renderFilterChip('Charlie',
'' /* classes */,
this.renderIcon('face', 'mdc-chip__icon--leading'))}
{this.renderFilterChip('Danielle',
'' /* classes */,
this.renderIcon('face', 'mdc-chip__icon--leading'))}
</div>
<div className='catalog-variant'>
<h3 className='mdc-typography--subtitle1'>Action Chips</h3>
<div className='mdc-chip-set' ref={initChipSet}>
{this.renderChip('Add to calendar',
'' /* classes */,
this.renderIcon('event', 'mdc-chip__icon--leading'))}
{this.renderChip('Bookmark',
'' /* classes */,
this.renderIcon('bookmark', 'mdc-chip__icon--leading'))}
{this.renderChip('Set alarm',
'' /* classes */,
this.renderIcon('alarm', 'mdc-chip__icon--leading'))}
{this.renderChip('Get directions',
'' /* classes */,
this.renderIcon('directions', 'mdc-chip__icon--leading'))}
</div>
</div>
<div className='catalog-variant'>
<h3 className='mdc-typography--subtitle1'>Shaped Chips</h3>
<div className='mdc-chip-set mdc-chip-set--filter' ref={initChipSet}>
{this.renderChip('Bookcase', 'demo-chip-shaped')}
{this.renderChip('TV Stand', 'demo-chip-shaped')}
{this.renderChip('Sofas', 'demo-chip-shaped')}
{this.renderChip('Office chairs', 'demo-chip-shaped')}
</div>
</div>
</div>
);
}
}
export default ChipsCatalog;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.