path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
examples/js/selection/unselectable-table.js
|
rolandsusans/react-bootstrap-table
|
/* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
const selectRowProp = {
mode: 'checkbox',
clickToSelect: true,
unselectable: [ 1, 3 ] // give rowkeys for unselectable row
};
export default class UnSelectableTable extends React.Component {
render() {
return (
<BootstrapTable data={ products } selectRow={ selectRowProp }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/svg-icons/device/signal-wifi-1-bar-lock.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi1BarLock = (props) => (
<SvgIcon {...props}>
<path d="M23 16v-1.5c0-1.4-1.1-2.5-2.5-2.5S18 13.1 18 14.5V16c-.5 0-1 .5-1 1v4c0 .5.5 1 1 1h5c.5 0 1-.5 1-1v-4c0-.5-.5-1-1-1zm-1 0h-3v-1.5c0-.8.7-1.5 1.5-1.5s1.5.7 1.5 1.5V16z"/><path d="M15.5 14.5c0-2.8 2.2-5 5-5 .4 0 .7 0 1 .1L23.6 7c-.4-.3-4.9-4-11.6-4C5.3 3 .8 6.7.4 7L12 21.5l3.5-4.3v-2.7z" opacity=".3"/><path d="M6.7 14.9l5.3 6.6 3.5-4.3v-2.6c0-.2 0-.5.1-.7-.9-.5-2.2-.9-3.6-.9-3 0-5.1 1.7-5.3 1.9z"/>
</SvgIcon>
);
DeviceSignalWifi1BarLock = pure(DeviceSignalWifi1BarLock);
DeviceSignalWifi1BarLock.displayName = 'DeviceSignalWifi1BarLock';
export default DeviceSignalWifi1BarLock;
|
test/BadgeSpec.js
|
15lyfromsaturn/react-materialize
|
import 'es5-shim';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import Badge from '../src/Badge';
describe('Badge', () => {
it('should output a badge with the className of `badge`', () => {
let badge = TestUtils.renderIntoDocument(<Badge>4</Badge>);
assert.equal(ReactDOM.findDOMNode(badge).className, 'badge');
});
it('should output a badge with just the number 4 in it', () => {
let badge = TestUtils.renderIntoDocument(<Badge>4</Badge>);
assert.equal(ReactDOM.findDOMNode(badge).innerHTML, '4');
});
it('should output a badge with the className of `badge new` and', () => {
let badge = TestUtils.renderIntoDocument(<Badge newIcon={true}>4</Badge>);
assert.include(ReactDOM.findDOMNode(badge).className, 'badge');
assert.include(ReactDOM.findDOMNode(badge).className, 'new');
});
});
|
src/components/Greeting.js
|
kesean/Dashboard-Frontend
|
import React from 'react'
import Paper from 'material-ui/Paper'
import {CardTitle} from 'material-ui/Card'
export default function Greeting(props) {
//Set greeting depending on hour of day
return(
<Paper zDepth={5} className="greeting">
<CardTitle>{getGreeting()}</CardTitle>
<CardTitle>{props.userFirst} {props.userLast}!</CardTitle>
</Paper>
)
}
function getGreeting(){
let time = new Date().getHours()
if (time >= 2 && time <= 11) {
return "Good Morning"
}else if (time >= 12 && time <= 17) {
return "Good Afternoon"
}else {
return "Good Evening"
}
}
|
src/components/form/__tests__/DatePickerFormField.spec.js
|
bcongdon/EachDay
|
import React from 'react'
import { mount } from 'enzyme'
import toJson from 'enzyme-to-json'
import DatePickerFormField from '../DatePickerFormField'
const onChange = jest.fn()
describe('DatePickerFormField component', () => {
beforeEach(() => {
jest.resetAllMocks()
Date.now = jest.fn(() => 1495984743025)
Date.prototype.getTimezoneOffset = () => 0 // eslint-disable-line no-extend-native
})
it('should render correctly', () => {
var field = mount(
<DatePickerFormField
input={{onChange, value: '2017-01-01'}}
meta={{touched: false, error: ''}}
/>
)
expect(toJson(field)).toMatchSnapshot()
})
it('should set default date if none provided', () => {
mount(
<DatePickerFormField
input={{onChange, value: ''}}
meta={{touched: false, error: ''}}
/>
)
expect(onChange).toBeCalled()
expect(onChange.mock.calls[0][0]).toEqual('2017-05-28')
})
it('should not display error if not touched', () => {
var field = mount(
<DatePickerFormField
input={{onChange, value: '2017-01-01'}}
meta={{touched: false, error: 'Warning!'}}
/>
)
expect(field.find('span').length).toBe(0)
expect(toJson(field)).toMatchSnapshot()
})
it('should display error if touched', () => {
var field = mount(
<DatePickerFormField
input={{onChange, value: '2017-01-01'}}
meta={{touched: true, error: 'Warning!'}}
/>
)
expect(field.find('span').length).toBe(1)
expect(field.find('span').first().text()).toEqual('Warning!')
expect(toJson(field)).toMatchSnapshot()
})
})
|
src/mui/list/DatagridCell.spec.js
|
azureReact/AzureReact
|
import assert from 'assert';
import React from 'react';
import { shallow } from 'enzyme';
import DatagridCell from './DatagridCell';
describe('<DatagridCell />', () => {
it('should render as a mui <TableRowColumn /> component', () => {
const wrapper = shallow(
<DatagridCell field={{ type: 'foo', props: {} }} />
);
const col = wrapper.find('TableRowColumn');
assert.equal(col.length, 1);
});
it('should use regular col style by default', () => {
const wrapper = shallow(
<DatagridCell
field={{ type: 'foo', props: {} }}
defaultStyle={{ color: 'blue' }}
/>
);
const col = wrapper.find('TableRowColumn');
assert.deepEqual(col.at(0).prop('style'), { color: 'blue' });
});
it('should use field style to override default style', () => {
const wrapper = shallow(
<DatagridCell
field={{ type: 'foo', props: { style: { color: 'red' } } }}
/>
);
const col = wrapper.find('TableRowColumn');
assert.deepEqual(col.at(0).prop('style'), { color: 'red' });
});
});
|
data-browser-ui/public/app/components/tableComponents/td/numberTdComponent.js
|
CloudBoost/cloudboost
|
import React from 'react';
import ReactDOM from 'react-dom';
class NumberTdComponent extends React.Component {
constructor(){
super()
this.state = {}
}
componentDidMount(){
this.state = {
inputHidden:true
}
this.setState(this.state)
}
toggleInput(which,e){
if(which){
let string = this.props.elementData.toString()
this.props.updateElement(parseFloat(string.replace(/[^\d.-]/g, '')))
this.props.updateObject()
}
this.state['inputHidden'] = which
this.setState(this.state)
}
saveKeyAction(e){
if(e.which == 13){
this.toggleInput(true)
}
}
componentDidUpdate(){
if(!this.state['inputHidden']){
ReactDOM.findDOMNode(this.refs.Input).focus()
}
}
changeHandler(e){
this.props.updateElement(e.target.value)
}
render() {
let requiredClass = this.props.isRequired ? " requiredred":""
return (
<td className={ this.state.inputHidden ? ('mdl-data-table__cell--non-numeric pointer'+requiredClass) : 'mdl-data-table__cell--non-numeric pointer padleftright0' } onDoubleClick={this.toggleInput.bind(this,false)}>
<span className={!this.state.inputHidden ? 'hide':''}>{this.props.elementData ? this.props.elementData.toString().slice(0,20):''}</span>
<input ref="Input" value={this.props.elementData || "" } onChange={this.changeHandler.bind(this)} className={this.state.inputHidden ? 'hide':'form-control texttypetdinput'} onBlur={this.toggleInput.bind(this,true)} type="text" onKeyDown={ this.saveKeyAction.bind(this) }/>
</td>
);
}
}
export default NumberTdComponent;
|
app/javascript/mastodon/components/__tests__/display_name-test.js
|
blackle/mastodon
|
import React from 'react';
import renderer from 'react-test-renderer';
import { fromJS } from 'immutable';
import DisplayName from '../display_name';
describe('<DisplayName />', () => {
it('renders display name + account name', () => {
const account = fromJS({
username: 'bar',
acct: 'bar@baz',
display_name_html: '<p>Foo</p>',
});
const component = renderer.create(<DisplayName account={account} />);
const tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
examples/simple/components/App.js
|
gaearon/library-boilerplate
|
import React, { Component } from 'react';
import { add } from 'library-boilerplate';
export default class App extends Component {
render() {
return (
<p>
2 + 2 = {add(2, 2)}
</p>
);
}
}
|
webapp-src/src/Admin/Navbar.js
|
babelouest/glewlwyd
|
import React, { Component } from 'react';
import i18next from 'i18next';
import messageDispatcher from '../lib/MessageDispatcher';
import apiManager from '../lib/APIManager';
class Navbar extends Component {
constructor(props) {
super(props);
this.state = {
config: props.config,
curNav: "users",
navDropdown: false,
profileList: props.profileList,
loggedIn: props.loggedIn
}
messageDispatcher.subscribe('Navbar', (message) => {
});
this.navigate = this.navigate.bind(this);
this.toggleLogin = this.toggleLogin.bind(this);
this.changeLang = this.changeLang.bind(this);
this.changeProfile = this.changeProfile.bind(this);
this.gotoManageUsers = this.gotoManageUsers.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({loggedIn: nextProps.loggedIn, profileList: nextProps.profileList});
}
navigate(e, page, navDropdown) {
e.preventDefault();
messageDispatcher.sendMessage('App', {type: "nav", message: page});
this.setState({curNav: page, navDropdown: navDropdown});
}
reloadApp(e) {
messageDispatcher.sendMessage('App', {type: "reloadApp"});
}
toggleLogin() {
if (this.state.loggedIn) {
apiManager.glewlwydRequest("/auth/?username=" + encodeURIComponent(this.state.profileList[0].username), "DELETE")
.then(() => {
messageDispatcher.sendMessage('Notification', {type: "info", message: i18next.t("login.success-delete-session")});
messageDispatcher.sendMessage('App', {type: 'loggedIn', loggedIn: false});
})
.fail((err) => {
if (err.status !== 401) {
messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("login.error-delete-session")});
}
messageDispatcher.sendMessage('App', {type: 'loggedIn', loggedIn: false});
});
} else {
var schemeDefault = false;
this.state.config.sessionSchemes.forEach((scheme) => {
if (scheme.scheme_default) {
scheme.scheme_default.forEach((page) => {
if (page === "admin") {
schemeDefault = scheme.scheme_name;
}
});
}
});
document.location.href = this.state.config.LoginUrl + "?callback_url=" + encodeURIComponent([location.protocol, '//', location.host, location.pathname].join('')) + "&scope=" + encodeURIComponent(this.state.config.admin_scope) + (schemeDefault?("&scheme="+encodeURIComponent(schemeDefault)):"");
}
}
changeLang(e, lang) {
i18next.changeLanguage(lang)
.then(() => {
this.setState({lang: lang});
messageDispatcher.sendMessage('App', {type: "lang"});
});
}
changeProfile(e, profile) {
e.preventDefault();
if (profile) {
apiManager.glewlwydRequest("/auth/", "POST", {username: profile.username})
.then(() => {
messageDispatcher.sendMessage('App', {type: "profile"});
})
.fail(() => {
messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("login.error-login")});
});
} else {
var schemeDefault = false;
this.state.config.sessionSchemes.forEach((scheme) => {
if (scheme.scheme_default) {
scheme.scheme_default.forEach((page) => {
if (page === "admin") {
schemeDefault = scheme.scheme_name;
}
});
}
});
document.location.href = this.state.config.LoginUrl + "?callback_url=" + encodeURIComponent([location.protocol, '//', location.host, location.pathname].join('')) + "&scope=" + encodeURIComponent(this.state.config.admin_scope) + (schemeDefault?("&scheme="+encodeURIComponent(schemeDefault)):"") + "&prompt=login";
}
}
gotoManageUsers(e) {
e.preventDefault();
document.location.href = this.state.config.LoginUrl + "?callback_url=" + encodeURIComponent([location.protocol, '//', location.host, location.pathname].join('')) + "&scope=" + encodeURIComponent(this.state.config.admin_scope) + "&prompt=select_account";
}
userHasScope(user, scope_list) {
var hasScope = false;
if (scope_list) {
scope_list.split(" ").forEach(scope => {
if (user.scope.indexOf(scope) > -1) {
hasScope = true;
}
});
}
return hasScope;
}
render() {
var langList = [], profileList = [], profileDropdown, loginButton;
var profilePicture;
this.state.config.lang.forEach((lang, i) => {
if (lang === i18next.language) {
langList.push(<a className="dropdown-item active" href="#" key={i}>{lang}</a>);
} else {
langList.push(<a className="dropdown-item" href="#" onClick={(e) => this.changeLang(e, lang)} key={i}>{lang}</a>);
}
});
if (this.state.profileList.length) {
this.state.profileList.forEach((profile, index) => {
if (this.userHasScope(profile, this.state.config.admin_scope)) {
profileList.push(<a className={"dropdown-item"+(!index?" active":"")} href="#" onClick={(e) => this.changeProfile(e, profile)} key={index}>{profile.name||profile.username}</a>);
} else {
profileList.push(<a className={"dropdown-item glwd-nav-user-unavailable"+(!index?" active":"")} key={index} href="#" disabled={true}>{profile.name||profile.username}</a>);
}
});
profileList.push(<div className="dropdown-divider" key={profileList.length}></div>);
profileList.push(<a className="dropdown-item" href="#" onClick={(e) => this.changeProfile(e, null)} key={profileList.length}>{i18next.t("profile.menu-session-new")}</a>);
profileList.push(<a className="dropdown-item" href="#" onClick={(e) => this.gotoManageUsers(e)} key={profileList.length}>{i18next.t("login.manage-users")}</a>);
if (this.state.profileList && this.state.profileList[0]) {
if (this.state.config.profilePicture && this.state.profileList[0][this.state.config.profilePicture.property]) {
var picData = this.state.profileList[0][this.state.config.profilePicture.property];
if (Array.isArray(picData)) {
picData = picData[0];
}
profilePicture =
<div className="glwd-nav-picture-div">
<img className="img-medium glwd-nav-picture-image" src={"data:image/*;base64,"+picData}/>
{this.state.profileList[0].username}
</div>
} else {
profilePicture =
<div className="glwd-nav-picture-div">
<img className="img-medium glwd-nav-picture-spacer" src="data:image/gif;base64,R0lGODlhAQABAIAAAP///wAAACH5BAEAAAAALAAAAAABAAEAAAICRAEAOw==" /> {/*1-pixel transparent image as spacer (Possible Bootstrap bug)*/}
<i className="fas fa-user">
</i>
{this.state.profileList[0].username}
</div>
}
}
profileDropdown =
<div className="btn-group" role="group">
<button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownProfile" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<div className="glwd-nav-picture-container">
{profilePicture}
</div>
</button>
<div className="dropdown-menu" aria-labelledby="dropdownProfile">
{profileList}
</div>
</div>
}
if (this.state.loggedIn) {
loginButton = <button type="button" className="btn btn-secondary" onClick={this.toggleLogin} title={i18next.t("title-logout")}>
<i className="fas btn-icon fa-sign-out-alt"></i>
</button>
} else {
loginButton = <button type="button" className="btn btn-secondary" onClick={this.toggleLogin} title={i18next.t("title-login")}>
<i className="fas btn-icon fa-sign-in-alt"></i>
</button>
}
return (
<nav className="navbar navbar-expand-lg navbar-light bg-light">
<a className="navbar-brand" href="#">
<img className="mr-3" src="img/logo-admin.png" alt="logo"/>
{i18next.t("admin.menu-title")}
</a>
<button className="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
<span className="navbar-toggler-icon"></span>
</button>
<div className="collapse navbar-collapse" id="navbarSupportedContent">
<ul className="navbar-nav mr-auto">
<li className={"nav-item" + (this.state.curNav==="users"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users", false)}>
{i18next.t("admin.menu-users")}
</a>
</li>
<li className={"nav-item" + (this.state.curNav==="clients"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "clients", false)}>
{i18next.t("admin.menu-clients")}
</a>
</li>
<li className={"nav-item" + (this.state.curNav==="scopes"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "scopes", false)}>
{i18next.t("admin.menu-scopes")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="users-mod"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users-mod", false)}>
{i18next.t("admin.menu-users-mod")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="clients-mod"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "clients-mod", false)}>
{i18next.t("admin.menu-clients-mod")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="auth-schemes"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "auth-schemes", false)}>
{i18next.t("admin.menu-auth-schemes")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="plugins"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "plugins", false)}>
{i18next.t("admin.menu-plugins")}
</a>
</li>
<li className={"d-md-none nav-item" + (this.state.curNav==="api-key"?" active":"")}>
<a className="nav-link" href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "api-key", false)}>
{i18next.t("admin.menu-api-key")}
</a>
</li>
<li className="nav-item dropdown d-none d-md-block">
<a className={"nav-link dropdown-toggle" + (this.state.navDropdown?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
{i18next.t("admin.menu-parameters")}
</a>
<div className={"dropdown-menu"} aria-labelledby="navbarDropdown">
<a className={"dropdown-item" + (this.state.curNav==="users-mod"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users-mod", true)}>{i18next.t("admin.menu-users-mod")}</a>
<a className={"dropdown-item" + (this.state.curNav==="clients-mod"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "clients-mod", true)}>{i18next.t("admin.menu-clients-mod")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="users-middleware-mod"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "users-middleware-mod", true)}>{i18next.t("admin.menu-users-middleware-mod")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="auth-schemes"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "auth-schemes", true)}>{i18next.t("admin.menu-auth-schemes")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="plugins"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "plugins", true)}>{i18next.t("admin.menu-plugins")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="api-key"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "api-key", true)}>{i18next.t("admin.menu-api-key")}</a>
<div className="dropdown-divider"></div>
<a className={"dropdown-item" + (this.state.curNav==="misc-config"?" active":"")} href="#" data-toggle="collapse" data-target=".navbar-collapse.show" onClick={(e) => this.navigate(e, "misc-config", true)}>{i18next.t("admin.menu-misc-config")}</a>
</div>
</li>
</ul>
<form className="form-inline my-2 my-lg-0">
<div className="btn-group" role="group">
<div className="btn-group" role="group">
<button disabled={!this.state.loggedIn} type="button" className="btn btn-secondary" onClick={(e) => this.reloadApp(e)} title={i18next.t("login.btn-reload")}>
<i className="fas fa-refresh"></i>
</button>
<button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownLang" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i className="fas fa-language"></i>
</button>
<div className="dropdown-menu" aria-labelledby="dropdownLang">
{langList}
</div>
</div>
{profileDropdown}
{loginButton}
</div>
</form>
</div>
</nav>
);
}
}
export default Navbar;
|
src/containers/AppContainer/index.js
|
pnicolli/demo-calculator
|
import React, { Component } from 'react';
import App from '../../views/App';
class AppContainer extends Component {
initialState = () => ({
negativeSign: false,
intValue: '0',
decimalValue: '',
showComma: false,
firstOperand: 0,
currentOperation: null,
resetNumberOnNextDigit: false,
});
constructor(props) {
super(props);
this.state = this.initialState();
}
// AC button
resetState = () => this.setState(this.initialState);
// C button
resetCurrentValue = () => this.setState((prevState, props) => ({
...this.initialState(),
firstOperand: prevState.firstOperand,
currentOperation: prevState.currentOperation,
}));
invertSign = () => this.setState((prevState, props) => ({
negativeSign: !prevState.negativeSign,
}));
// concat a digit, or replace the whole string if it is just '0'
// TODO: unit test this
addIntDigit = (digit, numString) => (
numString === '0' ? digit : numString.concat(digit)
);
// add the digit to the correct state number,
// using showComma to decide which one is the correct one
// TODO: unit test this
numberClick = digit => this.setState((prevState, props) => {
if (prevState.resetNumberOnNextDigit) {
return {
...this.initialState(),
intValue: digit,
firstOperand: this.numFromState(prevState),
currentOperation: prevState.currentOperation,
};
}
if (prevState.showComma) {
return { decimalValue: prevState.decimalValue.concat(digit) };
}
else {
return { intValue: this.addIntDigit(digit, prevState.intValue) };
}
});
// create an actual number from the given state
// TODO: unit test this
numFromState = state => {
let number = parseInt(state.intValue, 10);
if (state.showComma && state.decimalValue !== '') {
// compute 0.2345 from string '2345'
const numOfDigits = state.decimalValue.length;
const decimalNumber = parseInt(state.decimalValue, 10);
const decimalPart = decimalNumber / Math.pow(10, numOfDigits);
number += decimalPart;
}
if (state.negativeSign) {
number *= (-1);
}
return number;
};
// set the next operation to be performed
// TODO compute current operation, if given, before assigning the new one
// in order to allow chaining operations
setOperation = op => this.setState((prevState, props) => ({
currentOperation: op,
firstOperand: this.numFromState(prevState),
resetNumberOnNextDigit: true,
}));
// start typing decimal part of the number (a.k.a. show comma)
startDecimal = () => this.setState(() => ({
showComma: true,
}));
// called when '=' is pressed TODO
// computes operation based on the current state
computeNow = () => this.setState((prevState, props) => this.computeOperation(prevState));
// compute the operation described by the given state
// TODO: unit test this
computeOperation = state => {
//no-op if no operation is set
if (!state.currentOperation) {
return state;
}
const firstOperand = state.firstOperand;
const secondOperand = this.numFromState(state);
let result;
switch (state.currentOperation) {
case '+':
result = firstOperand + secondOperand;
break;
case '-':
result = firstOperand - secondOperand;
break;
case '/':
// TODO handle division by 0
result = firstOperand / secondOperand;
break;
case 'x':
result = firstOperand * secondOperand;
break;
default:
result = 0;
break;
}
const negativeSign = result < 0;
if (negativeSign) {
result *= (-1);
}
const numStrings = result.toString().split('.');
const hasDecimal = numStrings.length > 1;
return {
...this.initialState(),
intValue: numStrings[0],
decimalValue: hasDecimal ? numStrings[1] : '',
showComma: hasDecimal,
negativeSign: negativeSign,
resetNumberOnNextDigit: true,
};
};
// compute text to display from given state
// TODO: unit test this
textToDisplay = state => {
let text = state.negativeSign ? '-' : '';
text += state.intValue;
if (state.showComma) {
text += ',' + state.decimalValue;
}
return text;
}
controls = [
{ text: 'AC', className: 'dark smaller', onClick: this.resetState },
{ text: '7', onClick: () => this.numberClick('7') },
{ text: '4', onClick: () => this.numberClick('4') },
{ text: '1', onClick: () => this.numberClick('1') },
{ text: '0', onClick: () => this.numberClick('0') },
{ text: 'C', className: 'dark smaller', onClick: this.resetCurrentValue },
{ text: '8', onClick: () => this.numberClick('8') },
{ text: '5', onClick: () => this.numberClick('5') },
{ text: '2', onClick: () => this.numberClick('2') },
{ text: '.', className: 'dark', onClick: this.startDecimal },
{ text: '+/−', className: 'dark smaller', onClick: this.invertSign },
{ text: '9', onClick: () => this.numberClick('9') },
{ text: '6', onClick: () => this.numberClick('6') },
{ text: '3', onClick: () => this.numberClick('3') },
{ text: '=', className: 'dark', onClick: this.computeNow },
{ text: '÷', className: 'dark', onClick: () => this.setOperation('/') },
{ text: '×', className: 'dark', onClick: () => this.setOperation('x') },
{ text: '−', className: 'dark', onClick: () => this.setOperation('-') },
{ text: '+', className: 'dark double', onClick: () => this.setOperation('+') },
];
render() {
return (
<App
currentValue={this.textToDisplay(this.state)}
controls={[...this.controls]}
/>
);
}
}
export default AppContainer;
|
src/components/modals/alert_modal.js
|
dcporter44/tunefest-frontend
|
import React, { Component } from 'react';
import { RaisedButton } from 'material-ui';
export default class AlertModal extends Component {
render () {
return (
<div className="modal modal-sm">
<div className="modal-content">
<div className="modal-body">
{this.props.text}
</div>
<div className="modal-footer">
<RaisedButton autoFocus label="OK" primary={true} onClick={this.props.closeModal} />
</div>
</div>
</div>
)
}
}
|
pages/apply-now.js
|
aimanaiman/supernomadfriendsquad
|
import React from 'react'
import Helmet from 'react-helmet'
import { config } from 'config'
import { prefixLink } from 'gatsby-helpers'
import { Link } from 'react-router'
import skype from '../icon/skype.png'
import pencil from '../icon/pencil.png'
import gift from '../icon/gift.png'
import businessman from '../icon/businessman.png'
import tie from '../icon/tie.png'
export default class ApplyNow extends React.Component {
render () {
return (
<div>
<Helmet
title={`${config.siteTitle} | Application`}
/>
<div className="hero" id="apply-now-hero">
<div className="overlay">
<h1 style={{color:'#f3f3f3'}}>Here We Go . . .</h1>
</div>
</div>
<section id="proccess" >
<div className="gallery">
<h1>The Proccess</h1>
</div>
<div className="row center-xs">
<div className="col-xs-6 col-lg-3">
<img src={pencil} alt=""/>
<p>Fill in the application form below.</p>
</div>
<div className="col-xs-6 col-lg-3">
<img src={skype} alt=""/>
<p>We set up a skype call interview.</p>
</div>
<div className="col-xs-6 col-lg-3">
<img src={tie} alt=""/>
<p>We assess all applicants and select 50 Super Nomad Friend Squad Members. "12 Angry Men" style.</p>
</div>
<div className="col-xs-6 col-lg-3">
<img src={gift} alt=""/>
<p>Once approved we will send you an awesome care package to all our successful applicants.</p>
</div>
</div>
</section>
<section id="application-form" style={{backgroundColor:'#ecf0f1'}}>
<div className="gallery">
<h1>Application Form</h1>
</div>
<div className="row around-xs" id="form">
<div className="col-xs-10 col-lg-5" style={{padding:'0'}} >
<form name="application" data-netlify={true} data-netlify-honeypot={true}>
<label htmlFor="name">Name:</label>
<input type="text" name="name" placeholder="Sandy H. Warmbuns" required />
<label htmlFor="email">Email:</label>
<input type="email" name="email" placeholder="sandy@warm.buns" required />
<label htmlFor="skype">Skype ID:</label>
<input type="text" name="skype" placeholder="the.warmest.bun" required />
<label htmlFor="gender" className="gender">Gender:</label>
<select name="gender" id="gender">
<option value="male">Male</option>
<option value="female">Female</option>
<option value="other">Other</option>
</select>
<label htmlFor="occupation">What do you do for a living?</label>
<input type="text" name="occupation" placeholder="Bun Warmer" />
<label htmlFor="citizenship">Country of Citizenship:</label>
<input type="text" name="citizenship" placeholder="Narnia" />
<label htmlFor="remote-work">
Are you currently working remotely?
</label>
<label htmlFor="yes" className="yes-no">
<input type="radio" name="remote-work" value="yes" id="yes"/>Yes
</label>
<label htmlFor="no" className="yes-no" style={{marginTop:'0'}}>
<input type="radio" name="remote-work" value="no" id="no"/>No
</label>
<label htmlFor="income" className="income">Income Level?</label>
<select name="income" id="income">
<option value="25k">0 - $25,000</option>
<option value="25k-75k">$25,000 - $75,000</option>
<option value="75k-150k">$75,000 - $150,000</option>
<option value="150k">$150,000 and above</option>
</select>
<label htmlFor="about-you">
Tell us a little about yourself. About your daily routines.
</label>
<textarea type="textarea" name="about-you" placeholder="" />
<label htmlFor="why">
Why do you want to join our program?
</label>
<textarea type="why" name="why" placeholder="" />
<div className="row around-xs">
<button className="col-xs-12">
<Link to="/success">Submit</Link>
</button>
</div>
</form>
</div>
</div>
</section>
</div>
)
}
}
|
src/index.js
|
simoneas02/contracts-list
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
packages/icons/src/md/action/List.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdList(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M6 26h4v-4H6v4zm0 8h4v-4H6v4zm0-16h4v-4H6v4zm8 8h28v-4H14v4zm0 8h28v-4H14v4zm0-20v4h28v-4H14z" />
</IconBase>
);
}
export default MdList;
|
app/shared/wrapper.component.js
|
TPW-team/tpw_ui
|
import React from 'react';
export const Wrapper = ({component: Component, ...rest}) => (
<Component {...rest}></Component>
);
|
src/components/decoline_item.js
|
lizarraldeignacio/personal-website
|
import React, { Component } from 'react';
/**
DecolineItem atomic element of DecoLine list
Params:
title: The title of the element
description: The description of the element
remove: A function to handle the removal of this item from the list
auth: A flag that indicates if the user is authenticated or not
**/
class DecolineItem extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="o-grid__col-md-4 o-grid__col-sm-6">
<div className="o-media o-media--block">
<div className="o-content">
<hr className="c-deco-line t-primary-color-line" />
<div className="o-content__body">
<h3>{this.props.title}</h3>
<p>{this.props.description}</p>
</div>
</div>
{this.props.auth &&
<div className="o-media__figure inline-elem-rigth">
<div className="materialize-iso inline-elem btn-add">
<a className="btn-floating btn-tiny waves-effect waves-light red"
href="javascript:void(0);"
onClick={() => {this.props.remove(this.props.title)}}>
<i className="material-icons">clear</i>
</a>
</div>
</div>}
</div>
</div>
);
}
}
export default DecolineItem;
|
app/components/map/footer/index.js
|
Vizzuality/forest-watcher
|
// @flow
import type { Alert, SelectedAlert } from 'types/alerts.types';
import type { MapItemFeatureProperties } from 'types/common.types';
import type { SelectedReport } from 'types/reports.types';
import type { LocationPoint } from 'types/routes.types';
import React, { Component } from 'react';
import { Animated, View } from 'react-native';
import CircleButton from 'components/common/circle-button';
import InfoBanner from 'components/map/info-banner';
import LocationErrorBanner from 'components/map/locationErrorBanner';
import { withSafeArea } from 'react-native-safe-area';
const FooterSafeAreaView = withSafeArea(View, 'margin', 'bottom');
const FooterBackgroundSafeAreaView = withSafeArea(View, 'padding', 'bottom');
const startTrackingIcon = require('assets/startTracking.png');
const stopTrackingIcon = require('assets/stopTracking.png');
const myLocationIcon = require('assets/my_location.png');
const createReportIcon = require('assets/createReport.png');
const addLocationIcon = require('assets/add_location.png');
const cancelIcon = require('assets/cancel.png');
import styles from './styles';
type Props = {|
animatedPosition: Animated.Value,
customReporting: boolean,
isRouteTracking: boolean,
locationError: ?number,
onCustomReportingPress: () => void,
onReportSelectionPress: () => void,
onSelectAllConnectedAlertsPress: ($ReadOnlyArray<Alert>) => void,
onSelectionCancelPress: () => void,
onStartTrackingPress: () => void,
onStopTrackingPress: () => void,
onZoomToUserLocationPress: () => void,
connectedAlerts: $ReadOnlyArray<SelectedAlert>,
highlightedAlerts: $ReadOnlyArray<Alert>,
selectedAlerts: $ReadOnlyArray<SelectedAlert>,
selectedReports: $ReadOnlyArray<SelectedReport>,
tappedOnFeatures: $ReadOnlyArray<MapItemFeatureProperties>,
userLocation: ?LocationPoint
|};
export default class MapFooter extends Component<Props> {
renderButtonPanel() {
const {
animatedPosition,
connectedAlerts,
customReporting,
isRouteTracking,
userLocation,
locationError,
selectedAlerts,
highlightedAlerts,
selectedReports,
tappedOnFeatures,
onReportSelectionPress,
onCustomReportingPress,
onZoomToUserLocationPress,
onSelectionCancelPress,
onStartTrackingPress,
onStopTrackingPress,
onSelectAllConnectedAlertsPress
} = this.props;
const hasAlertsSelected = selectedAlerts && selectedAlerts.length > 0;
const hasReportSelected = selectedReports?.length;
const canReport = hasAlertsSelected || hasReportSelected || customReporting;
// To fix the missing signal text overflow rendering in reverse row
// last to render will be on top of the others
return (
<React.Fragment>
<LocationErrorBanner
style={styles.locationErrorBanner}
locationError={locationError}
mostRecentLocationTime={userLocation?.timestamp}
/>
<Animated.View style={{ transform: [{ translateY: animatedPosition }] }}>
<InfoBanner
style={styles.infoBanner}
tappedOnFeatures={tappedOnFeatures}
connectedAlerts={connectedAlerts}
highlightedAlerts={highlightedAlerts}
onSelectAllConnectedAlertsPress={onSelectAllConnectedAlertsPress}
/>
</Animated.View>
<View style={styles.buttonPanel}>
{canReport ? (
<CircleButton shouldFillContainer onPress={onReportSelectionPress} light icon={createReportIcon} />
) : (
<CircleButton shouldFillContainer onPress={onCustomReportingPress} icon={addLocationIcon} />
)}
{userLocation ? (
<CircleButton shouldFillContainer onPress={onZoomToUserLocationPress} light icon={myLocationIcon} />
) : null}
{canReport ? (
<CircleButton shouldFillContainer onPress={onSelectionCancelPress} light icon={cancelIcon} />
) : null}
{isRouteTracking || canReport ? (
<CircleButton
shouldFillContainer
onPress={isRouteTracking ? onStopTrackingPress : onStartTrackingPress}
light
icon={isRouteTracking ? stopTrackingIcon : startTrackingIcon}
/>
) : null}
</View>
</React.Fragment>
);
}
render() {
return [
<FooterBackgroundSafeAreaView key="bg" pointerEvents="none" style={styles.footerBGContainer}>
<View style={styles.buttonPanelTray} />
</FooterBackgroundSafeAreaView>,
<FooterSafeAreaView key="footer" pointerEvents="box-none" style={styles.footer}>
{this.renderButtonPanel()}
</FooterSafeAreaView>
];
}
}
|
src/js/contexts/ResponsiveContext/ResponsiveContext.js
|
HewlettPackard/grommet
|
import React from 'react';
import { ResponsiveContextPropTypes } from './propTypes';
export const ResponsiveContext = React.createContext(undefined);
ResponsiveContext.propTypes = ResponsiveContextPropTypes;
|
app/javascript/mastodon/features/compose/components/character_counter.js
|
masto-donte-com-br/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { length } from 'stringz';
export default class CharacterCounter extends React.PureComponent {
static propTypes = {
text: PropTypes.string.isRequired,
max: PropTypes.number.isRequired,
};
checkRemainingText (diff) {
if (diff < 0) {
return <span className='character-counter character-counter--over'>{diff}</span>;
}
return <span className='character-counter'>{diff}</span>;
}
render () {
const diff = this.props.max - length(this.props.text);
return this.checkRemainingText(diff);
}
}
|
src/containers/NotFound/container/NotFound.js
|
WCCrazyCoder/react-redux-web-application
|
import React from 'react';
export default class NotFound extends React.Component {
render() {
return (
<div>
<h1>...喔噢... 404 not found.</h1>
</div>
)
}
}
|
src/TextField/TextField.js
|
dsslimshaddy/material-ui
|
// @flow
import React from 'react';
import type { Element } from 'react';
import Input, { InputLabel } from '../Input';
import FormControl from '../Form/FormControl';
import FormHelperText from '../Form/FormHelperText';
export type Props = {
/**
* This property helps users to fill forms faster, especially on mobile devices.
* The name can be confusion, it's more like an autofill.
* You can learn about it with that article
* https://developers.google.com/web/updates/2015/06/checkout-faster-with-autofill
*/
autoComplete?: string,
/**
* If `true`, the input will be focused during the first mount.
*/
autoFocus?: boolean,
/**
* @ignore
*/
className?: string,
/**
* The default value of the `Input` element.
*/
defaultValue?: string,
/**
* If `true`, the input will be disabled.
*/
disabled?: boolean,
/**
* If `true`, the label will be displayed in an error state.
*/
error?: boolean,
/**
* Properties applied to the `FormHelperText` element.
*/
FormHelperTextProps?: Object,
/**
* If `true`, the input will take up the full width of its container.
*/
fullWidth?: boolean,
/**
* The helper text content.
*/
helperText?: string | Element<*>,
/**
* The CSS class name of the helper text element.
*/
helperTextClassName?: string,
/**
* The id of the `input` element.
*/
id?: string,
/**
* The CSS class name of the `input` element.
*/
inputClassName?: string,
/**
* The CSS class name of the `Input` element.
*/
InputClassName?: string,
/**
* Properties applied to the `InputLabel` element.
*/
InputLabelProps?: Object,
/**
* Properties applied to the `input` element.
*/
inputProps?: Object,
/**
* Properties applied to the `Input` element.
*/
InputProps?: Object,
/**
* Use that property to pass a ref callback to the native input component.
*/
inputRef?: Function,
/**
* The label content.
*/
label?: string | Element<*>,
/**
* The CSS class name of the label element.
*/
labelClassName?: string,
/**
* If `true`, a textarea element will be rendered instead of an input.
*/
multiline?: boolean,
/**
* Name attribute of the `Input` element.
*/
name?: string,
placeholder?: string,
/**
* If `true`, the label is displayed as required.
*/
required?: boolean,
/**
* Use that property to pass a ref callback to the root component.
*/
rootRef?: Function,
/**
* Number of rows to display when multiline option is set to true.
*/
rows?: string | number,
/**
* Maximum number of rows to display when multiline option is set to true.
*/
rowsMax?: string | number,
/**
* Type attribute of the `Input` element. It should be a valid HTML5 input type.
*/
type?: string,
/**
* The value of the `Input` element, required for a controlled component.
*/
value?: string | number,
/**
* If `dense` | `normal`, will adjust vertical spacing of this and contained components.
*/
margin?: 'none' | 'dense' | 'normal',
};
function TextField(props: Props) {
const {
autoComplete,
autoFocus,
className,
defaultValue,
disabled,
error,
id,
inputClassName,
InputClassName,
inputProps: inputPropsProp,
InputProps,
inputRef,
label,
labelClassName,
InputLabelProps,
helperText,
helperTextClassName,
FormHelperTextProps,
fullWidth,
required,
type,
multiline,
name,
placeholder,
rootRef,
rows,
rowsMax,
value,
...other
} = props;
let inputProps = inputPropsProp;
if (inputClassName) {
inputProps = {
className: inputClassName,
...inputProps,
};
}
return (
<FormControl
fullWidth={fullWidth}
ref={rootRef}
className={className}
error={error}
required={required}
{...other}
>
{label &&
<InputLabel htmlFor={id} className={labelClassName} {...InputLabelProps}>
{label}
</InputLabel>}
<Input
autoComplete={autoComplete}
autoFocus={autoFocus}
className={InputClassName}
defaultValue={defaultValue}
disabled={disabled}
multiline={multiline}
name={name}
rows={rows}
rowsMax={rowsMax}
type={type}
value={value}
id={id}
inputProps={inputProps}
inputRef={inputRef}
placeholder={placeholder}
{...InputProps}
/>
{helperText &&
<FormHelperText className={helperTextClassName} {...FormHelperTextProps}>
{helperText}
</FormHelperText>}
</FormControl>
);
}
TextField.defaultProps = {
required: false,
};
export default TextField;
|
app/javascript/mastodon/features/notifications/components/clear_column_button.js
|
clworld/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Icon from 'mastodon/components/icon';
export default class ClearColumnButton extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func.isRequired,
};
render () {
return (
<button className='text-btn column-header__setting-btn' tabIndex='0' onClick={this.props.onClick}><Icon id='eraser' /> <FormattedMessage id='notifications.clear' defaultMessage='Clear notifications' /></button>
);
}
}
|
src/svg-icons/action/hourglass-full.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionHourglassFull = (props) => (
<SvgIcon {...props}>
<path d="M6 2v6h.01L6 8.01 10 12l-4 4 .01.01H6V22h12v-5.99h-.01L18 16l-4-4 4-3.99-.01-.01H18V2H6z"/>
</SvgIcon>
);
ActionHourglassFull = pure(ActionHourglassFull);
ActionHourglassFull.displayName = 'ActionHourglassFull';
ActionHourglassFull.muiName = 'SvgIcon';
export default ActionHourglassFull;
|
src/generator/Component/__tests__/Component.web.js
|
Fineighbor/ui-kit
|
/* eslint-env jest */
import 'jest-styled-components'
import React from 'react'
import { shallow } from 'enzyme'
import Component from '../index.js'
describe('Component.web', () => {
it('renders a snapshot', () => {
const wrapper = shallow(
<Component>Apple</Component>
)
expect(wrapper).toMatchSnapshot()
})
})
|
test/SplitButtonSpec.js
|
xiaoking/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import SplitButton from '../src/SplitButton';
import MenuItem from '../src/MenuItem';
import Button from '../src/Button';
describe('SplitButton', function() {
const simple = (
<SplitButton title='Title' id='test-id'>
<MenuItem>Item 1</MenuItem>
<MenuItem>Item 2</MenuItem>
<MenuItem>Item 3</MenuItem>
<MenuItem>Item 4</MenuItem>
</SplitButton>
);
it('should open the menu when dropdown button is clicked', function () {
const instance = ReactTestUtils.renderIntoDocument(simple);
const toggleNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-toggle'));
const splitButtonNode = React.findDOMNode(instance);
splitButtonNode.className.should.not.match(/open/);
ReactTestUtils.Simulate.click(toggleNode);
splitButtonNode.className.should.match(/open/);
});
it('should not open the menu when other button is clicked', function() {
const instance = ReactTestUtils.renderIntoDocument(simple);
const buttonNode = React.findDOMNode(ReactTestUtils.scryRenderedComponentsWithType(instance, Button)[0]);
const splitButtonNode = React.findDOMNode(instance);
splitButtonNode.className.should.not.match(/open/);
ReactTestUtils.Simulate.click(buttonNode);
splitButtonNode.className.should.not.match(/open/);
});
it('should invoke onClick when SplitButton.Button is clicked (prop)', function(done) {
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton title='Title' id='test-id' onClick={ () => done() }>
<MenuItem>Item 1</MenuItem>
</SplitButton>
);
const buttonNode = React.findDOMNode(ReactTestUtils.scryRenderedComponentsWithType(instance, Button)[0]);
ReactTestUtils.Simulate.click(buttonNode);
});
it('should not invoke onClick when SplitButton.Toggle is clicked (prop)', function(done) {
let onClickSpy = sinon.spy();
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton
title='Title'
id='test-id'
onClick={onClickSpy}
>
<MenuItem>Item 1</MenuItem>
</SplitButton>
);
const toggleNode = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-toggle'));
ReactTestUtils.Simulate.click(toggleNode);
setTimeout(()=> {
onClickSpy.should.not.have.been.called;
done();
}, 10);
});
it('Should pass disabled to both buttons', function () {
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton title='Title' id='test-id' disabled>
<MenuItem>Item 1</MenuItem>
</SplitButton>
);
const toggleNode = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-toggle'));
const buttonNode = React.findDOMNode(
ReactTestUtils.scryRenderedComponentsWithType(instance, Button)[0]);
expect(toggleNode.disabled).to.be.true;
expect(buttonNode.disabled).to.be.true;
});
it('Should set target attribute on anchor', function () {
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" id='test-id' href="/some/unique-thing/" target="_blank">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
</SplitButton>
);
let anchors = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a');
let linkElement = React.findDOMNode(anchors[0]);
assert.equal(linkElement.target, '_blank');
});
});
|
docs/app/Examples/elements/Loader/Variations/LoaderExampleInline.js
|
koenvg/Semantic-UI-React
|
import React from 'react'
import { Loader } from 'semantic-ui-react'
const LoaderExampleInline = () => (
<Loader active inline />
)
export default LoaderExampleInline
|
test/fixtures/bugfix-175/actual.js
|
oliviertassinari/babel-plugin-transform-react-remove-prop-types
|
import React from 'react';
import PropTypes from 'prop-types';
const sharedPropType = PropTypes.number;
export default class Foo extends React.Component {
static propTypes = {
bar: sharedPropType,
}
}
|
src/routes/x-axis-assembly/XAxisAssembly.js
|
bigearth/www.clone.earth
|
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './XAxisAssembly.css';
import { Grid, Row, Col, Image } from 'react-bootstrap';
import DocsTOC from '../../components/DocsTOC';
class XAxisAssembly extends React.Component {
render() {
return (
<Grid fluid>
<Row className={s.root}>
<Col xs={12} sm={12} md={2} lg={2} >
<DocsTOC selected="/x-axis-assembly" />
</Col>
<Col xs={12} sm={12} md={10} lg={10}>
<Row>
<Col xs={12} md={6}>
<h2>X Axis Assembly</h2>
<h3 id='step1'>Step 1 Gather materials</h3>
<h4>Tools</h4>
<ul>
<li>Needle nose pliers x1</li>
<li>2 mm Hex key</li>
<li>1.5 mm Hex key</li>
</ul>
<h4>3D printed parts</h4>
<ul>
<li>Carriage x1</li>
<li>Motor x1</li>
<li>Idler x1</li>
</ul>
<h4>Hardware</h4>
<ul>
<li>
Rods
<ul>
<li>M8 Chrome rod 35 cm x2</li>
</ul>
</li>
<li>
Nuts & Bolts
<ul>
<li>M3x10 screw x2</li>
<li>M3x18 screw x4</li>
<li>M3x16 screw x2</li>
<li>M3 square nut x2</li>
<li>M3 locknut x1</li>
<li>GT2 pulley x1</li>
<li>Idler Bearing x1</li>
<li>Linear bearings x7</li>
</ul>
</li>
<li>
Electronics
<ul>
<li>Nema 17 stepper motor x1</li>
<li>X axis endstop x1</li>
</ul>
</li>
<li>
Miscellaneous
<ul>
<li>Zip tie 10 cm x6</li>
<li>GT2 belt 68 cm x1</li>
</ul>
</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-1.jpg'>
<Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-1.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step2'>Step 2 Assemble the Y-axis rods</h3>
<h4>Hardware</h4>
<ul>
<li>Linear Bearings x3</li>
<li>Chrome rods 35 cm x2</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Carefully slide linear bearings on rods.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-2-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step3'>Step 3 Prepare the printed parts</h3>
<h4>Hardware</h4>
<ul>
<li>Linear Bearing x4</li>
<li>X-end-motor</li>
<li>X-end-idler</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert linear bearing into the printed parts.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-3-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step4'>Step 4 Prepare the tension screws</h3>
<h4>Hardware</h4>
<ul>
<li>M3 squre nut x2</li>
<li>M3x10 screw x2</li>
<li>X-end-idler</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert M3 square nuts and put in place M3x10 screws.</li>
<li>Avoid overtightening of the screws.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-4-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step5'>Step 5 Assemble the X-axis base</h3>
<h4>Hardware</h4>
<ul>
<li>Assembled y-axis rods</li>
<li>Prepared printed parts</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert the rods with bearings fully into the printed parts.</li>
<li>Ensure the correct orientation of the parts and rods (rod with 2 bearings must be on the side with the nut trap).</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-5-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step6'>Step 6 Preparing the X-end idler</h3>
<h4>Hardware</h4>
<ul>
<li>M3x18 screw x1</li>
<li>bearing w/ housing x1</li>
<li>M3 locknut x1</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert the bearing into the X-end idler.</li>
<li>Secure it in position using M3x18 screw.</li>
<li>Tighten it with M3 nylock nut, but the idler (wheel) must rotate freely.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-6-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step7'>Step 7 Prepare the X carriage</h3>
<h4>Hardware</h4>
<ul>
<li>X Carriage</li>
<li>Zip tie x6</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Insert zipties into the X-carriage.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-7-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step8'>Step 8 Placing the X carriage</h3>
<h4>Hardware</h4>
<ul>
<li>Assembled X axis base</li>
<li>Prepared X Carriage</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Place the X-carriage on the X-axis base.</li>
<li>Ensure the correct orientation of X-carriage.</li>
<li>Use pliers to tighten the zipties.</li>
<li>Use pliers to cut off any excess ziptie.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-b.jpg' />
</a>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-d.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-8-d.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step9'>Step 9 Assemble the X Motor</h3>
<h4>Hardware</h4>
<ul>
<li>M3x18 screw x3</li>
<li>Stepper motor</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Tighten the motor to the X-end-motor part.</li>
<li>Ensure the correct position of cables (Cables should face down).</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-9-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step10'>Step 10 Assemble the X motor pulley</h3>
<h4>Hardware</h4>
<ul>
<li>GT2 Pulley</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Place GT2 pulley on the X motor shaft.</li>
<li>Tighten up the pulley.</li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-10-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='step11'>Step 11 Assemble the X endstop</h3>
<h4>Hardware</h4>
<ul>
<li>X Endstop</li>
<li>M3x16 screw x2</li>
</ul>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-a.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-a.jpg' />
</a>
</Col>
</Row>
<Row className={s.root}>
<Col xs={12} md={6}>
<ol>
<li>Place the endstop on the printed part and insert </li>
</ol>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-b.jpg'>
<Image className={s.rotate} src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/step-11-b.jpg' />
</a>
</Col>
</Row>
<hr />
<Row className={s.root}>
<Col xs={12} md={6}>
<h3 id='allDone'>All Done!</h3>
<p>Congratulations! Now on to the next step.</p>
</Col>
<Col xs={12} md={6}>
<a href='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/done.jpg'>
<Image src='https://s3-us-west-1.amazonaws.com/www-clone-earth-assets/x-axis/done.jpg' />
</a>
</Col>
</Row>
</Col>
</Row>
</Grid>
);
}
}
export default withStyles(s)(XAxisAssembly);
|
src/svg-icons/communication/rss-feed.js
|
kittyjumbalaya/material-components-web
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationRssFeed = (props) => (
<SvgIcon {...props}>
<circle cx="6.18" cy="17.82" r="2.18"/><path d="M4 4.44v2.83c7.03 0 12.73 5.7 12.73 12.73h2.83c0-8.59-6.97-15.56-15.56-15.56zm0 5.66v2.83c3.9 0 7.07 3.17 7.07 7.07h2.83c0-5.47-4.43-9.9-9.9-9.9z"/>
</SvgIcon>
);
CommunicationRssFeed = pure(CommunicationRssFeed);
CommunicationRssFeed.displayName = 'CommunicationRssFeed';
CommunicationRssFeed.muiName = 'SvgIcon';
export default CommunicationRssFeed;
|
tests/routes/Counter/components/Counter.spec.js
|
pptang/ggm
|
import React from 'react'
import { bindActionCreators } from 'redux'
import { Counter } from 'routes/Counter/components/Counter'
import { shallow } from 'enzyme'
describe('(Component) Counter', () => {
let _props, _spies, _wrapper
beforeEach(() => {
_spies = {}
_props = {
counter : 5,
...bindActionCreators({
doubleAsync : (_spies.doubleAsync = sinon.spy()),
increment : (_spies.increment = sinon.spy())
}, _spies.dispatch = sinon.spy())
}
_wrapper = shallow(<Counter {..._props} />)
})
it('Should render as a <div>.', () => {
expect(_wrapper.is('div')).to.equal(true)
})
it('Should render with an <h2> that includes Sample Counter text.', () => {
expect(_wrapper.find('h2').text()).to.match(/Counter:/)
})
it('Should render props.counter at the end of the sample counter <h2>.', () => {
expect(_wrapper.find('h2').text()).to.match(/5$/)
_wrapper.setProps({ counter: 8 })
expect(_wrapper.find('h2').text()).to.match(/8$/)
})
it('Should render exactly two buttons.', () => {
expect(_wrapper.find('button')).to.have.length(2)
})
describe('An increment button...', () => {
let _button
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Increment')
})
it('has bootstrap classes', () => {
expect(_button.hasClass('btn btn-default')).to.be.true
})
it('Should dispatch a `increment` action when clicked', () => {
_spies.dispatch.should.have.not.been.called
_button.simulate('click')
_spies.dispatch.should.have.been.called
_spies.increment.should.have.been.called
})
})
describe('A Double (Async) button...', () => {
let _button
beforeEach(() => {
_button = _wrapper.find('button').filterWhere(a => a.text() === 'Double (Async)')
})
it('has bootstrap classes', () => {
expect(_button.hasClass('btn btn-default')).to.be.true
})
it('Should dispatch a `doubleAsync` action when clicked', () => {
_spies.dispatch.should.have.not.been.called
_button.simulate('click')
_spies.dispatch.should.have.been.called
_spies.doubleAsync.should.have.been.called
})
})
})
|
client/portfolio2017/src/Components/Routs/ProjectsRoute/ProjectsRoute.js
|
corrortiz/portafolio2017
|
import React from 'react';
//Internal Components
import ListOfProjects from '../../ListOfProjects/ListOfProjects';
import FooterApp from '../../FooterApp/FooterApp';
//locale Assest
import { Projects } from '../../../Assets/diccionary';
/**
* layout of the projects rout
*/
const ProjectsRoute = () => {
return (
<div>
<FooterApp title={Projects} />
<ListOfProjects />
</div>
);
};
export default ProjectsRoute;
|
docs/app/Examples/elements/Header/Types/HeaderExampleContent.js
|
vageeshb/Semantic-UI-React
|
import React from 'react'
import { Header } from 'semantic-ui-react'
const HeaderExampleContent = () => (
<div>
<Header size='huge'>Huge Header</Header>
<Header size='large'>Large Header</Header>
<Header size='medium'>Medium Header</Header>
<Header size='small'>Small Header</Header>
<Header size='tiny'>Tiny Header</Header>
</div>
)
export default HeaderExampleContent
|
src/components/storyComment/StoryComment.js
|
ummahusla/Hacker-Reader
|
import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import Navigation from '../navigation/Navigation';
import ScoreLabel from '../shared-components/scoreLabel/ScoreLabel';
import AuthorLabel from '../shared-components/authorLabel/AuthorLabel';
import DateLabel from '../shared-components/dateLabel/DateLabel';
import './StoryComment.css';
import * as api from '../../helpers/api';
class StoryComment extends Component {
constructor(props) {
super(props);
this.state = {
storyItems: []
};
}
loadStoryItems() {
api.getStoryItem(this.props.params.id)
.then((response) => {
if(response.data) {
this.setState({ storyItems: response.data });
}
});
}
componentDidMount() {
this.loadStoryItems();
}
render() {
const storyItem = this.state.storyItems;
return (
<div>
<Navigation />
<div className="container">
<div className="row">
<div className="col-12">
<div>
<Button href={storyItem.url} className="story-header" bsStyle="link"><h3>{storyItem.title}</h3></Button>
</div>
</div>
</div>
<div className="row">
<div className="col-12">
<div>
<ScoreLabel score={storyItem.score}/>
<AuthorLabel author={storyItem.by}/>
<DateLabel date={storyItem.time}/>
</div>
</div>
</div>
</div>
</div>
);
}
}
StoryComment.propTypes = {
id: React.PropTypes.string
};
export default StoryComment;
|
src/components/topic/MediaTableContainer.js
|
mitmedialab/MediaCloud-Web-Tools
|
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import MediaTable from './MediaTable';
import { isUrlSharingFocalSet } from '../../lib/topicVersionUtil';
/**
* Simple wrapper around MediaTable to pull in some stuff from state (so the components that use
* MediaTable don't need to pass it in). This just passses along all the other props so maintenance
* cost is low.
*/
const MediaTableContainer = (props) => (
<MediaTable {...props} />
);
MediaTableContainer.propTypes = {
// from state
showTweetCounts: PropTypes.bool.isRequired,
topicId: PropTypes.number.isRequired,
usingUrlSharingSubtopic: PropTypes.bool.isRequired,
};
const mapStateToProps = state => ({
topicId: state.topics.selected.id,
// show tweet counts if the user has a crimson hexagon id on the topic (to deptecate?)
showTweetCounts: Boolean(state.topics.selected.info.ch_monitor_id),
// only show the author count, and hide inlinks/outlinks, if the user is in a "url sharing" focus
usingUrlSharingSubtopic: (state.topics.selected.filters.focusId !== null) && isUrlSharingFocalSet(state.topics.selected.timespans.selected.focal_set),
});
export default (
connect(mapStateToProps)(
MediaTableContainer
)
);
|
src/svg-icons/action/flip-to-back.js
|
hwo411/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFlipToBack = (props) => (
<SvgIcon {...props}>
<path d="M9 7H7v2h2V7zm0 4H7v2h2v-2zm0-8c-1.11 0-2 .9-2 2h2V3zm4 12h-2v2h2v-2zm6-12v2h2c0-1.1-.9-2-2-2zm-6 0h-2v2h2V3zM9 17v-2H7c0 1.1.89 2 2 2zm10-4h2v-2h-2v2zm0-4h2V7h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2zM5 7H3v12c0 1.1.89 2 2 2h12v-2H5V7zm10-2h2V3h-2v2zm0 12h2v-2h-2v2z"/>
</SvgIcon>
);
ActionFlipToBack = pure(ActionFlipToBack);
ActionFlipToBack.displayName = 'ActionFlipToBack';
ActionFlipToBack.muiName = 'SvgIcon';
export default ActionFlipToBack;
|
js/controls/AttributionControl.js
|
mekto/brouter-online
|
import React from 'react';
import Control from './Control';
class AttributionComponent extends React.Component {
state = { layerAttributions: [] }
componentDidMount() {
this.props.map.on('layerchange', ::this.updateLayerAttributions);
}
updateLayerAttributions(e) {
this.setState({
layerAttributions: e.layers.map(layer => layer.attribution),
});
}
render() {
return (
<div>
<span>© <a href="http://leafletjs.com" title="A JS library for interactive maps" target="_blank">Leaflet</a> | </span>
{this.state.layerAttributions.map((attribution, i) =>
<span key={i}>tiles <span dangerouslySetInnerHTML={{__html: attribution}}></span> | </span>
)}
<span>routing © <a href="http://brouter.de/brouter/" title="BRouter: Let's get serious about bike routing" target="_blank">BRouter</a> | </span>
<span>search © <a href="https://www.google.com/maps" target="_blank">Google</a> | </span>
<span>code on <a href="https://github.com/mekto/brouter-online" target="_blank">GitHub</a></span>
</div>
);
}
}
export default Control.extend({
options: {
position: 'bottomright',
className: 'leaflet-control-attribution',
},
getComponentClass() { return AttributionComponent; }
});
|
src/layouts/index.js
|
xenotime-india/CV
|
import React from 'react'
import { siteMetadata } from '../../gatsby-config'
import './../styles/init.scss'
import 'font-awesome/css/font-awesome.css'
class Template extends React.Component {
componentDidMount() {}
componentDidUpdate() {}
render() {
const { location, children } = this.props
return <div>{children()}</div>
}
}
export default Template
|
test/utils/CustomPropTypesSpec.js
|
jontewks/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import CustomPropTypes from '../../src/utils/CustomPropTypes';
import {shouldWarn} from '../helpers';
function isChainableAndUndefinedOK(validatorUnderTest) {
it('Should validate OK with undefined or null values', function() {
assert.isUndefined(validatorUnderTest({}, 'p', 'Component'));
assert.isUndefined(validatorUnderTest({p: null}, 'p', 'Component'));
});
it('Should be able to chain', function() {
let err = validatorUnderTest.isRequired({}, 'p', 'Component');
assert.instanceOf(err, Error);
assert.include(err.message, 'Required prop');
assert.include(err.message, 'was not specified in');
});
}
describe('CustomPropTypes', function() {
describe('mountable', function () {
function validate(prop) {
return CustomPropTypes.mountable({p: prop}, 'p', 'Component');
}
isChainableAndUndefinedOK(CustomPropTypes.mountable);
it('Should return error with non mountable values', function() {
let err = validate({});
assert.instanceOf(err, Error);
assert.include(err.message, 'expected a DOM element or an object that has a `render` method');
});
it('Should return undefined with mountable values', function() {
assert.isUndefined(validate(document.createElement('div')));
assert.isUndefined(validate(document.body));
assert.isUndefined(validate(ReactTestUtils.renderIntoDocument(<div />)));
});
});
describe('elementType', function () {
function validate(prop) {
return CustomPropTypes.elementType({p: prop}, 'p', 'TestComponent');
}
isChainableAndUndefinedOK(CustomPropTypes.elementType);
it('Should validate OK with elementType values', function() {
assert.isUndefined(validate('span'));
assert.isUndefined(validate(function() {}));
});
it('Should return error with not a string or function values', function() {
let err = validate({});
assert.instanceOf(err, Error);
assert.include(err.message, 'Expected an Element `type` such as a tag name or return value of React.createClass(...)');
});
it('Should return error with react element', function() {
let err = validate(React.createElement('span'));
assert.instanceOf(err, Error);
assert.include(err.message, 'Expected an Element `type`, not an actual Element');
});
});
describe('keyOf', function () {
let obj = {'foo': 1};
function validate(prop) {
return CustomPropTypes.keyOf(obj)({p: prop}, 'p', 'Component');
}
isChainableAndUndefinedOK(CustomPropTypes.keyOf(obj));
it('Should return error with non-key values', function() {
let err = validate('bar');
assert.instanceOf(err, Error);
assert.include(err.message, 'expected one of ["foo"]');
});
it('Should validate OK with key values', function() {
assert.isUndefined(validate('foo'));
obj.bar = 2;
assert.isUndefined(validate('bar'));
});
});
describe('singlePropFrom', function () {
function validate(testProps) {
const propList = ['children', 'value'];
return CustomPropTypes.singlePropFrom(propList)(testProps, 'value', 'Component');
}
it('Should validate OK if only one listed prop in used', function () {
const testProps = {value: 5};
assert.isUndefined(validate(testProps));
});
it('Should return error if multiple of the listed properties have values', function () {
let err = validate({value: 5, children: 5});
assert.instanceOf(err, Error);
assert.include(err.message, 'only one of the following may be provided: value and children');
});
});
describe('all', function() {
let validators;
const props = {
key: 'value'
};
const propName = 'key';
const componentName = 'TestComponent';
beforeEach(function() {
validators = [
sinon.stub(),
sinon.stub(),
sinon.stub()
];
});
it('with no arguments provided', function() {
expect(() => {
CustomPropTypes.all();
}).to.throw(Error, /No validations provided/);
});
it('with no validations provided', function() {
expect(() => {
CustomPropTypes.all([]);
}).to.throw(Error, /No validations provided/);
});
it('with invalid arguments provided', function() {
expect(() => {
CustomPropTypes.all(1);
}).to.throw(Error, /Invalid argument must be an array/);
});
it('validates each validation', function() {
const all = CustomPropTypes.all(validators);
let result = all(props, propName, componentName);
expect(result).to.equal(undefined);
validators.forEach(x => {
x.should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
});
});
it('returns first validation failure', function() {
let err = new Error('Failure');
validators[1].returns(err);
const all = CustomPropTypes.all(validators);
let result = all(props, propName, componentName);
expect(result).to.equal(err);
validators[0].should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
validators[1].should.have.been.calledOnce
.and.calledWith(props, propName, componentName);
validators[2].should.not.have.been.called;
});
});
describe('isRequiredForA11y', function () {
function validate(prop) {
return CustomPropTypes.isRequiredForA11y(React.PropTypes.string)({p: prop}, 'p', 'Component');
}
it('Should validate OK when property is provided', function() {
let err = validate('aria-tag');
assert.notInstanceOf(err, Error);
});
it('Should return custom error message when property is not provided', function() {
let err = validate(null);
assert.instanceOf(err, Error);
assert.include(err.message, 'accessible for users using assistive technologies such as screen readers');
});
});
describe('deprecated', function () {
function validate(prop) {
return CustomPropTypes.deprecated(React.PropTypes.string, 'Read more at link')({pName: prop}, 'pName', 'ComponentName');
}
it('Should warn about deprecation and validate OK', function() {
let err = validate('value');
shouldWarn('"pName" property of "ComponentName" has been deprecated.\nRead more at link');
assert.notInstanceOf(err, Error);
});
it('Should warn about deprecation and throw validation error when property value is not OK', function() {
let err = validate({});
shouldWarn('"pName" property of "ComponentName" has been deprecated.\nRead more at link');
assert.instanceOf(err, Error);
assert.include(err.message, 'Invalid undefined `pName` of type `object` supplied to `ComponentName`');
});
});
});
|
fields/types/password/PasswordField.js
|
linhanyang/keystone
|
import React from 'react';
import Field from '../Field';
import {
Button,
FormInput,
InlineGroup as Group,
InlineGroupSection as Section,
} from '../../../admin/client/App/elemental';
module.exports = Field.create({
displayName: 'PasswordField',
statics: {
type: 'Password',
},
getInitialState () {
return {
passwordIsSet: this.props.value ? true : false,
showChangeUI: this.props.mode === 'create' ? true : false,
password: '',
confirm: '',
};
},
valueChanged (which, event) {
var newState = {};
newState[which] = event.target.value;
this.setState(newState);
},
showChangeUI () {
this.setState({
showChangeUI: true,
}, () => this.focus());
},
onCancel () {
this.setState({
showChangeUI: false,
}, () => this.focus());
},
renderValue () {
return <FormInput noedit>{this.props.value ? 'Password Set' : ''}</FormInput>;
},
renderField () {
return this.state.showChangeUI ? this.renderFields() : this.renderChangeButton();
},
renderFields () {
return (
<Group block>
<Section grow>
<FormInput
autoComplete="off"
name={this.getInputName(this.props.path)}
onChange={this.valueChanged.bind(this, 'password')}
placeholder="New password"
ref="focusTarget"
type="password"
value={this.state.password}
/>
</Section>
<Section grow>
<FormInput
autoComplete="off"
name={this.getInputName(this.props.paths.confirm)}
onChange={this.valueChanged.bind(this, 'confirm')}
placeholder="Confirm new password" value={this.state.confirm}
type="password"
/>
</Section>
{this.state.passwordIsSet ? (
<Section>
<Button onClick={this.onCancel}>Cancel</Button>
</Section>
) : null}
</Group>
);
},
renderChangeButton () {
var label = this.state.passwordIsSet
? 'Change Password'
: 'Set Password';
return (
<Button ref="focusTarget" onClick={this.showChangeUI}>{label}</Button>
);
},
});
|
examples/jenarMine/components/WindowOverlay.js
|
tatsuhino/reactPractice
|
import styles from '../css/main.css'
import React from 'react'
import {hashHistory} from 'react-router';
const WindowOverlay = () =>{
return (
<div className={styles.windowOverlay} onClick={linkTo}></div>
)
}
const linkTo = () =>{
hashHistory.push('/');
}
export default WindowOverlay
|
src/redux/utils/createDevToolsWindow.js
|
wwwiiilll/drinkstat
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Provider } from 'react-redux'
import DevTools from '../../containers/DevToolsWindow'
export default function createDevToolsWindow (store) {
const win = window.open(
null,
'redux-devtools', // give it a name so it reuses the same window
`width=400,height=${window.outerHeight},menubar=no,location=no,resizable=yes,scrollbars=no,status=no`
)
// reload in case it's reusing the same window with the old content
win.location.reload()
// wait a little bit for it to reload, then render
setTimeout(() => {
// Wait for the reload to prevent:
// "Uncaught Error: Invariant Violation: _registerComponent(...): Target container is not a DOM element."
win.document.write('<div id="react-devtools-root"></div>')
win.document.body.style.margin = '0'
ReactDOM.render(
<Provider store={store}>
<DevTools />
</Provider>
, win.document.getElementById('react-devtools-root')
)
}, 10)
}
|
docs/app/Examples/collections/Message/Types/MessageMessagePropsExample.js
|
jcarbo/stardust
|
import React from 'react'
import { Message } from 'stardust'
const MessageMessagePropsExample = () => (
<Message
header='Changes in Service'
content='We updated our privacy policy here to better service our customers. We recommend reviewing the changes.'
/>
)
export default MessageMessagePropsExample
|
scripts/apps/translations/directives/TranslationReactDropdown.js
|
thnkloud9/superdesk-client-core
|
/* eslint-disable react/no-multi-comp */
import React from 'react';
/**
* @ngdoc directive
* @module superdesk.apps.translations
* @name TranslationReactDropdown
*
* @requires React
* @requires item
* @requires className
* @requires TranslationService
* @requires noLanguagesLabel
*
* @param {Object} [langugages] collection of languages
*
* @description Creates dropdown react element with list of available languages
*/
TranslationReactDropdown.$inject = ['item', 'className', 'TranslationService', 'noLanguagesLabel'];
export function TranslationReactDropdown(item, className, TranslationService, noLanguagesLabel) {
var languages = TranslationService.get() || {_items: []};
/*
* Creates specific language button in list
* @return {React} Language button
*/
class TranslateBtn extends React.Component {
constructor(props) {
super(props);
this.markTranslate = this.markTranslate.bind(this);
}
markTranslate(event) {
event.stopPropagation();
TranslationService.set(this.props.item, this.props.language);
}
render() {
var item = this.props.item;
var language = this.props.language;
var isCurrentLang = item.language === language.language;
if (!language.destination) {
return false;
}
return React.createElement(
'button', {
disabled: isCurrentLang,
onClick: this.markTranslate
},
language.label
);
}
}
TranslateBtn.propTypes = {
item: React.PropTypes.object,
language: React.PropTypes.object
};
/*
* Creates list element for specific language
* @return {React} Single list element
*/
var createTranslateItem = function(language) {
return React.createElement(
'li',
{key: 'language-' + language._id},
React.createElement(TranslateBtn, {item: item, language: language})
);
};
/*
* If there are no languages, print none-langugage message
* @return {React} List element
*/
var noLanguage = function() {
return React.createElement(
'li',
{},
React.createElement(
'button',
{disabled: true},
noLanguagesLabel)
);
};
/*
* Creates list with languages
* @return {React} List element
*/
return React.createElement(
'ul',
{className: className},
languages._items.length ? languages._items.map(createTranslateItem) : React.createElement(noLanguage)
);
}
|
packages/app/app/containers/MainContentContainer/index.js
|
nukeop/nuclear
|
import React from 'react';
import { Route, Switch, withRouter } from 'react-router-dom';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as SearchActions from '../../actions/search';
import MainLayout from '../../components/MainLayout';
import AlbumViewContainer from '../AlbumViewContainer';
import ArtistViewContainer from '../ArtistViewContainer';
import DashboardContainer from '../DashboardContainer';
import DownloadsContainer from '../DownloadsContainer';
import EqualizerViewContainer from '../EqualizerViewContainer';
import FavoritesContainer from '../FavoritesContainer';
import LibraryViewContainer from '../LibraryViewContainer';
import LyricsContainer from '../LyricsContainer';
import PlaylistViewContainer from '../PlaylistViewContainer';
import PlaylistsContainer from '../PlaylistsContainer';
import PluginsContainer from '../PluginsContainer';
import SearchResultsContainer from '../SearchResultsContainer';
import SettingsContainer from '../SettingsContainer';
import TagViewContainer from '../TagViewContainer';
import VisualizerNode from '../VisualizerContainer/VisualizerNode';
class MainContentContainer extends React.Component {
componentDidMount () {
if (this.props.history &&
this.props.location &&
this.props.location.pathname === '/') {
this.props.history.push('/dashboard');
}
}
render () {
return (
<Route render={({ location }) => {
return (
<MainLayout>
<Switch key={location.key} location={location}>
<Route path='/album/:albumId' component={AlbumViewContainer} />
<Route path='/artist/:artistId' component={ArtistViewContainer} />
<Route path='/dashboard' component={DashboardContainer} />
<Route path='/downloads' component={DownloadsContainer} />
<Route path='/favorites/albums' component={FavoritesContainer} />
<Route path='/favorites/tracks' component={FavoritesContainer} />
<Route path='/favorites/artists' component={FavoritesContainer} />
<Route path='/playlists' component={PlaylistsContainer} />
<Route path='/playlist/:playlistId' component={PlaylistViewContainer} />
<Route path='/plugins' component={PluginsContainer} />
<Route path='/settings' component={SettingsContainer} />
<Route path='/tag/:tagName' component={TagViewContainer} />
<Route path='/search' component={SearchResultsContainer} />
<Route path='/lyrics' component={LyricsContainer} />
<Route path='/equalizer' component={EqualizerViewContainer} />
<Route path='/visualizer' component={VisualizerNode} />
<Route path='/library' component={LibraryViewContainer} />
</Switch>
</MainLayout>
);
}
} />
);
}
}
function mapStateToProps () {
return {};
}
function mapDispatchToProps (dispatch) {
return {
searchActions: bindActionCreators(SearchActions, dispatch)
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(MainContentContainer));
|
src/interface/layout/Footer/index.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import Tooltip, { TooltipElement } from 'common/Tooltip';
import DiscordLogo from 'interface/icons/DiscordTiny';
import GithubLogo from 'interface/icons/GitHubMarkSmall';
import PatreonIcon from 'interface/icons/PatreonTiny';
import { hasPremium } from 'interface/selectors/user';
import Logo from 'interface/images/logo.svg';
import Ad from 'interface/common/Ad';
import './style.scss';
class Footer extends React.PureComponent {
static propTypes = {
premium: PropTypes.bool,
};
render() {
const { premium } = this.props;
return (
<footer>
<div className="container text-center">
<div>
<a href="/">
<img src={Logo} alt="Logo" className="wowanalyzer-logo" />
</a>
<h1>
Be a part of us
</h1>
<div className="social-links">
{/* For some reason the tooltip disappears and reappears when mousing over the svg icons (maybe when the cursor leaves filled areas)*/}
<Tooltip content="Discord">
<a href="https://wowanalyzer.com/discord">
<DiscordLogo />
</a>
</Tooltip>
<Tooltip content="GitHub">
<a href="https://github.com/WoWAnalyzer/WoWAnalyzer">
<GithubLogo />
</a>
</Tooltip>
<Tooltip content="Patreon">
<a href="https://www.patreon.com/join/wowanalyzer">
<PatreonIcon />
</a>
</Tooltip>
</div>
<br />
<div className="attribution">
Log data from <a href="https://www.warcraftlogs.com">Warcaft Logs</a>.{' '}
<TooltipElement
content={(
<>
Icon creators:<br />
<ul>
<li>Fingerprint by IconsGhost</li>
<li>Scroll by jngll</li>
<li>Delete by johartcamp</li>
<li>Skull by Royyan Razka</li>
<li>Heart by Emir Palavan</li>
<li>armor by Jetro Cabau Quirós</li>
<li>Checklist by David</li>
<li>Idea by Anne</li>
<li>About Document by Deepz</li>
<li>Stats by Barracuda</li>
<li>Dropdown by zalhan</li>
<li>timeline by Alexander Blagochevsky</li>
<li>abilities by sachin modgekar</li>
<li>Vision by supalerk laipawat</li>
<li>Lightning by Mooms</li>
<li>Grid Many Rows by Justin White</li>
<li>Info by Gregor Cresnar</li>
<li>Plus by Galaxicon</li>
<li>duration by Bohdan Burmich</li>
<li>link by arjuazka</li>
</ul>
</>
)}
>Icons by the <a href="https://thenounproject.com">Noun Project</a>.</TooltipElement><br />
World of Warcraft and related artwork is copyright of Blizzard Entertainment, Inc.<br />
This is a fan site and we are not affiliated.
</div>
</div>
{premium === false && (
<div>
<Ad
data-ad-slot="3815063023" // Footer
/>
</div>
)}
</div>
</footer>
);
}
}
const mapStateToProps = state => ({
premium: hasPremium(state),
});
export default connect(mapStateToProps)(Footer);
|
examples/js/others/table-in-tabs.js
|
powerhome/react-bootstrap-table
|
/* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
import { Tabs, Tab } from 'react-bootstrap';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class TableInTabs extends React.Component {
constructor(props) {
super(props);
this.state = {
key: 2
};
}
handleTabChange = (key) => {
this.setState({
key
}, () => {
/*
* If you enable animation in react-bootstrap tab
* please remember to call forceUpdate in async call.
* If disable animation, call forceUpdate directly.
*/
if (key === 1) {
setTimeout(() => {
this.refs.table1.forceUpdate();
}, 500);
} else if (key === 2) {
setTimeout(() => {
this.refs.table2.forceUpdate();
}, 500);
}
});
}
render() {
return (
<Tabs activeKey={ this.state.key } onSelect={ this.handleTabChange } animation>
<Tab eventKey={ 1 } title='Tab 1'>
<BootstrapTable ref='table1' data={ products }>
<TableHeaderColumn dataField='id' isKey dataSort>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' width='300' dataSort>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
</Tab>
<Tab eventKey={ 2 } title='Tab 2'>
<BootstrapTable ref='table2' data={ products }>
<TableHeaderColumn dataField='id' isKey dataSort>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' width='300' dataSort>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
<TableHeaderColumn dataField='price' width='90'>Product Price</TableHeaderColumn>
</BootstrapTable>
</Tab>
<Tab eventKey={ 3 } title='Tab 3'>Tab 3 content</Tab>
</Tabs>
);
}
}
|
code/workspaces/web-app/src/components/modal/ConfirmationDialog.spec.js
|
NERC-CEH/datalab
|
import React from 'react';
import { shallow } from 'enzyme';
import ConfirmationDialog from './ConfirmationDialog';
describe('ConfirmationDialog', () => {
const shallowRender = props => shallow(
<ConfirmationDialog {...props} />,
);
it('renders to match snapshot', () => {
const render = shallowRender({
onSubmit: jest.fn().mockName('onSubmit'),
title: 'Dialog title',
body: 'Dialog body',
onCancel: jest.fn().mockName('onCancel'),
});
expect(render).toMatchSnapshot();
});
});
|
src/Repeat/index.js
|
pinebit/react-cr
|
import React from 'react';
import PropTypes from 'prop-types';
import Wrapper from '../Wrapper';
const Repeat = ({ count, children, ...wrapperProps }) => {
if (!children || count <= 0 || Array.isArray(children)) {
return null;
}
if (count === 1) {
return (
<Wrapper {...wrapperProps}>
{children}
</Wrapper>
);
}
const fakeArray = Array.from(new Array(count)).map((x, index) => index + 1);
return (
<Wrapper {...wrapperProps}>
{fakeArray.map(key => React.cloneElement(children, { key }))}
</Wrapper>
);
};
Repeat.propTypes = {
count: PropTypes.number.isRequired,
children: PropTypes.node
};
export default Repeat;
|
src/common/containers/LocationPanel/LocationPanel.js
|
aarmour/my-denver
|
import React, { Component } from 'react';
import BasePanel from '../BasePanel';
export default class LocationPanel extends Component {
render() {
return (
<BasePanel>
</BasePanel>
);
}
}
|
src/components/Search/SearchStories.js
|
DeloitteDigitalUK/react-redux-starter-app
|
import React from 'react';
import { storiesOf } from '@kadira/storybook';
import Search from './index';
storiesOf('Search', module)
.addDecorator(story => (
<div className="col-xs-8 col-xs-offset-2">
{story()}
</div>
))
.add('Default State', () => (
<Search
heading="Search GitHub"
buttonText="Search"
/>
))
.add('With A Valid Search Term', () => (
<Search
heading="Search GitHub"
inputValue="React"
buttonText="Search"
/>
))
.add('With an invalid Character', () => (
<Search
heading="Search GitHub"
inputValue="~"
buttonText="Search"
errorMessage="You have entered a forbidden character!"
/>
))
.add('Submitted without entering anything', () => (
<Search
heading="Search GitHub"
buttonText="Search"
errorMessage="You need to enter search criteria before submitting"
/>
))
.add('Clicking off Search box', () => (
<Search
heading="Search GitHub"
buttonText="Search"
errorMessage="Please enter search criteria"
/>
));
|
web/src/js/__tests__/components/ContentView/ShowFullContentButtonSpec.js
|
zlorb/mitmproxy
|
import React from 'react'
import renderer from 'react-test-renderer'
import { Provider } from 'react-redux'
import ConnectedComponent, { ShowFullContentButton } from '../../../components/ContentView/ShowFullContentButton'
import { TStore } from '../../ducks/tutils'
describe('ShowFullContentButton Component', () => {
let setShowFullContentFn = jest.fn(),
showFullContentButton = renderer.create(
<ShowFullContentButton
setShowFullContent={setShowFullContentFn}
showFullContent={false}
visibleLines={10}
contentLines={20}
/>
),
tree = showFullContentButton.toJSON()
it('should render correctly', () => {
expect(tree).toMatchSnapshot()
})
it('should handle click', () => {
tree.children[0].props.onClick()
expect(setShowFullContentFn).toBeCalled()
})
it('should connect to state', () => {
let store = TStore(),
provider = renderer.create(
<Provider store={store}>
<ConnectedComponent/>
</Provider>
),
tree = provider.toJSON()
expect(tree).toMatchSnapshot()
})
})
|
src/pages/navbar.js
|
michaelnyu/michaelnyu.github.io
|
import React from 'react';
import House from '~/assets/house.svg';
import NavbarComponent from '~/src/components/navbar';
import Link from '~/src/components/link';
import { Heading, FONT_COLORS } from '~/src/shared/typography';
export const leftNavbar = (
<Link to="/">
<House css={{ width: 60, height: 'auto' }} />
</Link>
);
export const rightNavbar = (
<div css={{ display: 'flex', alignItems: 'center' }}>
<Link to="/about">
<Heading css={{ display: 'inline' }} color={FONT_COLORS.GRAY}>
about
</Heading>
</Link>
</div>
);
const Navbar = () => {
return <NavbarComponent left={leftNavbar} right={rightNavbar} />;
};
export default Navbar;
|
src/ToggleButtonWithLabel/index.js
|
DuckyTeam/ducky-components
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import Typography from '../Typography';
import SwitchToggleButton from '../SwitchToggleButton';
import styles from './styles.css';
function ToggleButtonWithLabel(props) {
return (
<div className={classNames(styles.wrapper)}>
<Typography
className={classNames(styles.text, {
[styles.textDarkTheme]: props.theme === 'dark'
})}
type="bodyTextNormal"
>
{props.label}
</Typography>
<SwitchToggleButton
onChange={props.onChange}
checked={props.checked}
defaultChecked={props.defaultChecked}
theme={props.theme}
/>
</div>
);
}
ToggleButtonWithLabel.propTypes = {
checked: PropTypes.bool,
label: PropTypes.string,
theme: PropTypes.string
};
export default ToggleButtonWithLabel;
|
packages/material-ui-icons/src/Details.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Details = props =>
<SvgIcon {...props}>
<path d="M3 4l9 16 9-16H3zm3.38 2h11.25L12 16 6.38 6z" />
</SvgIcon>;
Details = pure(Details);
Details.muiName = 'SvgIcon';
export default Details;
|
src/organisms/cards/PolicyCard/Compare.js
|
policygenius/athenaeum
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import Text from 'atoms/Text';
import Hide from 'wrappers/Hide';
import Spacer from 'atoms/Spacer';
import CheckBoxField from 'molecules/formfields/CheckBoxField';
import styles from './policy_card.module.scss';
const Compare = ({ compareSelected, onCompare, name }) => (
<Hide hideOn='mobile' className={styles['compare']}>
<div
id={`${name}-checkbox-wrapper`}
className={styles['checkbox-wrapper']}
onClick={onCompare}
>
<Text
color='neutral-2'
size={11}
font='a'
bold
spaced
className={classnames(compareSelected && styles['checked'])}
>
COMPARE
</Text>
<Spacer spacer={1} />
<CheckBoxField
input={{
value: compareSelected,
name
}}
/>
</div>
</Hide>
);
Compare.propTypes = {
compareSelected: PropTypes.bool,
onCompare: PropTypes.func,
name: PropTypes.string,
};
export default Compare;
|
client/node_modules/react-router/es/withRouter.js
|
bourdakos1/Visual-Recognition-Tool
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import PropTypes from 'prop-types';
import hoistStatics from 'hoist-non-react-statics';
import Route from './Route';
/**
* A public higher-order component to access the imperative API
*/
var withRouter = function withRouter(Component) {
var C = function C(props) {
var wrappedComponentRef = props.wrappedComponentRef,
remainingProps = _objectWithoutProperties(props, ['wrappedComponentRef']);
return React.createElement(Route, { render: function render(routeComponentProps) {
return React.createElement(Component, _extends({}, remainingProps, routeComponentProps, { ref: wrappedComponentRef }));
} });
};
C.displayName = 'withRouter(' + (Component.displayName || Component.name) + ')';
C.WrappedComponent = Component;
C.propTypes = {
wrappedComponentRef: PropTypes.func
};
return hoistStatics(C, Component);
};
export default withRouter;
|
js/src/dialogs/NewFolder.js
|
syslo/file_publisher
|
import React from 'react'
import {Button, Form, FormControl, FormGroup, InputGroup} from 'react-bootstrap'
import {Modal} from 'react-bootstrap'
const validator = new RegExp('^[_a-zA-Z0-9]+$')
export default class NewFolder extends React.Component {
create() {
const n = this.props.state.nodes[this.props.state.active.path]
this.props.actions.newFolder(
`${n.path}/${this.props.value}`
).then(()=>
this.props.actions.fetchNode(n)
)
this.props.onChange('')
this.props.onClose()
}
onSubmit(e) {
e.preventDefault()
e.stopPropagation()
if (validator.test(this.props.value)){
this.create()
}
return false
}
render() {
let value = this.props.value || ''
let active = this.props.state.active || {}
let valid = validator.test(value)
return (
<Modal
show={this.props.show && active.asFolder}
onHide={this.props.onClose}
>
<Modal.Header closeButton>
<Modal.Title>New Folder</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form onSubmit={this.onSubmit.bind(this)}>
<FormGroup validationState={value && !valid ? 'error' : null}>
<InputGroup>
<InputGroup.Addon>{active.path}/</InputGroup.Addon>
<FormControl
autoFocus
type="text"
value={value}
onChange={(e)=>this.props.onChange(e.target.value)}
/>
</InputGroup>
</FormGroup>
<FormGroup>
<Button bsStyle="primary" disabled={!valid} onClick={this.create.bind(this)}>
Create
</Button>
</FormGroup>
</Form>
</Modal.Body>
</Modal>
)
}
}
|
components/form/FileImage.js
|
resource-watch/resource-watch
|
import 'isomorphic-fetch';
import React from 'react';
import PropTypes from 'prop-types';
// Components
import Dropzone from 'react-dropzone';
import Icon from 'components/ui/icon';
import FormElement from './FormElement';
class FileImage extends FormElement {
constructor(props) {
super(props);
const defaultValue = props.properties.default;
const previewURL = `${defaultValue || ''}`;
const { getUrlImage } = props;
this.state = {
value: (defaultValue && !getUrlImage)
? this.getBase64FromURL(previewURL)
: '',
accepted: (defaultValue)
? [{ name: defaultValue, preview: previewURL }]
: [],
rejected: [],
dropzoneActive: false,
loading: false,
};
// BINDINGS
this.triggerBrowseOrCancel = this.triggerBrowseOrCancel.bind(this);
this.onDragEnter = this.onDragEnter.bind(this);
this.onDragLeave = this.onDragLeave.bind(this);
this.onDrop = this.onDrop.bind(this);
}
/**
* DROPZONE EVENTS
* - onDragEnter
* - onDragLeave
* - onDrop
*/
onDragEnter() {
this.setState({
dropzoneActive: true,
});
}
onDragLeave() {
this.setState({
dropzoneActive: false,
});
}
onDrop(accepted, rejected) {
this.setState({
accepted,
rejected,
dropzoneActive: false,
}, () => {
if (accepted.length) {
switch (this.props.mode) {
case 'image':
this.getBase64(accepted[0]);
break;
case 'url':
this.props.getUrlImage(accepted[0])
.then((value) => {
this.setState({
value,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
});
break;
default:
this.getBase64(accepted[0]);
}
}
});
}
/**
* - getBase64
* - getFileFromUrl
*/
getBase64(file) {
const reader = new FileReader();
reader.readAsDataURL(file);
reader.onload = () => {
this.setState({
value: reader.result,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
};
reader.onerror = (error) => {
this.setState({
value: '',
error,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
};
}
getBase64FromURL(url) {
if (typeof window !== 'undefined') {
const xhr = new XMLHttpRequest();
xhr.open('get', url);
xhr.responseType = 'blob';
xhr.onload = () => {
this.getBase64(xhr.response);
};
xhr.send();
}
}
/**
* UI EVENTS
* - triggerBrowseOrCancel
* - triggerChange
*/
triggerBrowseOrCancel() {
const { accepted } = this.state;
if (accepted.length) {
this.setState({
accepted: [],
value: '',
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
} else {
this.dropzone.open();
}
}
triggerChange(e) {
this.setState({
value: e.currentTarget.value,
}, () => {
// Publish the new value to the form
if (this.props.onChange) this.props.onChange(this.state.value);
// Trigger validation
this.triggerValidate();
});
}
/**
* HELPERS
* - getFileImageName
* - uploadFileImage
*/
getFileImageName() {
const { accepted } = this.state;
if (accepted.length) {
const current = accepted[0];
return current.name;
}
return 'Select file to upload';
}
render() {
const { properties } = this.props;
const { accepted } = this.state;
return (
<div className="c-file-image">
<Dropzone
accept=".jpg,.jpeg,.png"
ref={(node) => { this.dropzone = node; }}
className="file-dropzone"
disableClick
multiple={false}
onDrop={this.onDrop}
onDragEnter={this.onDragEnter}
onDragLeave={this.onDragLeave}
>
{!accepted.length
&& (
<div className="file-placeholder" onClick={this.triggerBrowseOrCancel}>
{properties.placeholder}
</div>
)}
{!!accepted.length && accepted[0].preview
&& (
<div className="file-preview">
<img className="file-image" src={accepted[0].preview} alt={accepted[0].name} />
<button onClick={this.triggerBrowseOrCancel} className="file-button c-button">
<Icon name="icon-cross" className="-small" />
</button>
</div>
)}
</Dropzone>
</div>
);
}
}
FileImage.propTypes = {
properties: PropTypes.object.isRequired,
validations: PropTypes.array,
onChange: PropTypes.func,
};
export default FileImage;
|
examples/js/custom/search/fully-custom-search-field.js
|
echaouchna/react-bootstrap-tab
|
/* eslint max-len: 0 */
/* eslint no-unused-vars: 0 */
/* eslint no-alert: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
class MySearchField extends React.Component {
// It's necessary to implement getValue
getValue() {
return ReactDOM.findDOMNode(this).value;
}
// It's necessary to implement setValue
setValue(value) {
ReactDOM.findDOMNode(this).value = value;
}
render() {
return (
<input
className={ `form-control` }
type='text'
defaultValue={ this.props.defaultValue }
placeholder={ this.props.placeholder }
onKeyUp={ this.props.search }/>
);
}
}
export default class FullyCustomSearchFieldTable extends React.Component {
render() {
const options = {
clearSearch: true,
searchField: (props) => (<MySearchField { ...props }/>)
};
return (
<BootstrapTable data={ products } options={ options } search>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
stories/Transform.js
|
unruffledBeaver/react-animation-components
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import * as knobs from '@storybook/addon-knobs';
import { createCommonKnobs } from '../src/utilities';
import { Transform } from '../src/index';
storiesOf('Animations/Transform', module)
.addDecorator(knobs.withKnobs)
.add('default', () => {
const commonKnobs = createCommonKnobs(knobs);
const enterTransform = knobs.text('enterTransform', 'translateY(50vh)');
const exitTransform = knobs.text('exitTransform', 'none');
return (
<Transform
in={commonKnobs.inProp}
delay={commonKnobs.delay}
duration={commonKnobs.duration}
timingFn={commonKnobs.timingFn}
enterTransform={enterTransform}
exitTransform={exitTransform}
>
<h1>Example</h1>
</Transform>
);
});
|
src/js/index.js
|
Landerson352/rpga
|
import React from 'react';
import ReactDOM from 'react-dom';
import '../css/app.less';
import App from './components/App';
ReactDOM.render(<App/>,document.getElementById('app'));
|
src/svg-icons/notification/wifi.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationWifi = (props) => (
<SvgIcon {...props}>
<path d="M1 9l2 2c4.97-4.97 13.03-4.97 18 0l2-2C16.93 2.93 7.08 2.93 1 9zm8 8l3 3 3-3c-1.65-1.66-4.34-1.66-6 0zm-4-4l2 2c2.76-2.76 7.24-2.76 10 0l2-2C15.14 9.14 8.87 9.14 5 13z"/>
</SvgIcon>
);
NotificationWifi = pure(NotificationWifi);
NotificationWifi.displayName = 'NotificationWifi';
NotificationWifi.muiName = 'SvgIcon';
export default NotificationWifi;
|
app/client/src/routes/manageCampaignVolunteers/index.js
|
uprisecampaigns/uprise-app
|
import React from 'react';
import ManageCampaignVolunteers from 'scenes/ManageCampaignVolunteers';
import Layout from 'components/Layout';
import organizeCampaignPaths from 'routes/organizeCampaignPaths';
export default organizeCampaignPaths({
path: '/organize/:slug/volunteers',
component: campaign => (
<Layout>
<ManageCampaignVolunteers campaignId={campaign.id} />
</Layout>
),
});
|
src/svg-icons/image/broken-image.js
|
kittyjumbalaya/material-components-web
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrokenImage = (props) => (
<SvgIcon {...props}>
<path d="M21 5v6.59l-3-3.01-4 4.01-4-4-4 4-3-3.01V5c0-1.1.9-2 2-2h14c1.1 0 2 .9 2 2zm-3 6.42l3 3.01V19c0 1.1-.9 2-2 2H5c-1.1 0-2-.9-2-2v-6.58l3 2.99 4-4 4 4 4-3.99z"/>
</SvgIcon>
);
ImageBrokenImage = pure(ImageBrokenImage);
ImageBrokenImage.displayName = 'ImageBrokenImage';
ImageBrokenImage.muiName = 'SvgIcon';
export default ImageBrokenImage;
|
packages/carbon-react/src/components/Layer/index.js
|
carbon-design-system/carbon-components
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import { usePrefix } from '../../internal/usePrefix';
export function Layer({
as: BaseComponent = 'div',
className: customClassName,
children,
...rest
}) {
const prefix = usePrefix();
const className = cx(`${prefix}--layer`, customClassName);
return (
<BaseComponent {...rest} className={className}>
{children}
</BaseComponent>
);
}
Layer.propTypes = {
/**
* Specify a custom component or element to be rendered as the top-level
* element in the component
*/
as: PropTypes.oneOfType([
PropTypes.func,
PropTypes.string,
PropTypes.elementType,
]),
/**
* Provide child elements to be rendered inside of `Theme`
*/
children: PropTypes.node,
/**
* Provide a custom class name to be used on the outermost element rendered by
* the component
*/
className: PropTypes.string,
};
|
src/containers/EditPetition.js
|
iris-dni/iris-frontend
|
import React from 'react';
import Helmet from 'react-helmet';
import { withRouter } from 'react-router';
import { connect } from 'react-redux';
import { fetchPetition } from 'actions/PetitionActions';
import { updateSuggestionInputValue } from 'actions/AutocompleteActions';
import settings from 'settings';
import citySuggestionFormatter from 'helpers/citySuggestionFormatter';
import EditPetition from 'components/EditPetition';
import getPetitionForm from 'selectors/petitionForm';
const EditPetitionContainer = React.createClass({
componentWillMount () {
const { petition, params, fetchPetition, updateSuggestionInputValue } = this.props;
if (!petition.id) {
fetchPetition(params.id)
.then(({ petition }) => {
updateSuggestionInputValue(
citySuggestionFormatter(petition.city.data)
);
});
} else {
updateSuggestionInputValue(
citySuggestionFormatter(this.props.petition.city)
);
}
},
render () {
return (
<div>
<Helmet title={settings.editPetitionPage.title} />
<EditPetition petition={this.props.petition} />
</div>
);
}
});
export const mapStateToProps = ({ petition }) => ({
petition: getPetitionForm(petition)
});
export const mapDispatchToProps = (dispatch) => ({
fetchPetition: (id) => dispatch(fetchPetition(id)),
updateSuggestionInputValue: (city) => dispatch(updateSuggestionInputValue(city))
});
export default withRouter(connect(
mapStateToProps,
mapDispatchToProps
)(EditPetitionContainer));
|
src/components/App.js
|
migueliriano/react-anime-project
|
import React from 'react';
import { Provider } from 'react-redux';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import { Switch, Route } from 'react-router-dom';
import Home from 'containers/Home';
import SingleAnimePage from 'containers/SingleAnimePage';
import configureStore from 'configureStore';
import 'index.css';
const store = configureStore();
const App = () => (
<Provider store={store}>
<MuiThemeProvider>
<Switch>Home
<Route exact path="/" component={Home} />
<Route path="/anime/:id" component={SingleAnimePage} />
</Switch>
</MuiThemeProvider>
</Provider>
);
export default App;
|
examples/example4.js
|
gabrielbull/react-tether2
|
import React, { Component } from 'react';
import Target from './example4/target';
import Source from './example4/source';
class Example4 extends Component {
getTarget = () => this.refs.target;
render() {
return (
<div style={{ background: 'red', position: 'relative', padding: '20px' }}>
<div style={{ height: '600px', background: 'purple' }}>
</div>
<Target ref="target"/>
<Source target={this.getTarget}/>
</div>
);
}
}
export default Example4;
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/CssInclusion.js
|
Bogala/create-react-app-awesome-ts
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import './assets/style.css';
export default () => <p id="feature-css-inclusion">We love useless text.</p>;
|
src/components/ADAGUC/CanvasComponent.spec.js
|
maartenlterpstra/GeoWeb-FrontEnd
|
import React from 'react';
// eslint-disable-next-line no-unused-vars
import { default as CanvasComponent } from './CanvasComponent';
import { shallow } from 'enzyme';
describe('(Component) CanvasComponent', () => {
it('Renders a canvas', () => {
const _component = shallow(<CanvasComponent />);
expect(_component.type()).to.eql('div'); // Todo check child canvas
});
});
|
examples/with-algolia-react-instantsearch/components/app.js
|
arunoda/next.js
|
import React from 'react'
import PropTypes from 'prop-types'
import {
RefinementList,
SearchBox,
Hits,
Configure,
Highlight,
Pagination
} from 'react-instantsearch/dom'
import { InstantSearch } from './instantsearch'
const HitComponent = ({ hit }) =>
<div className='hit'>
<div>
<div className='hit-picture'>
<img src={`${hit.image}`} />
</div>
</div>
<div className='hit-content'>
<div>
<Highlight attributeName='name' hit={hit} />
<span>
{' '}- ${hit.price}
</span>
<span>
{' '}- {hit.rating} stars
</span>
</div>
<div className='hit-type'>
<Highlight attributeName='type' hit={hit} />
</div>
<div className='hit-description'>
<Highlight attributeName='description' hit={hit} />
</div>
</div>
</div>
HitComponent.propTypes = {
hit: PropTypes.object
}
export default class extends React.Component {
static propTypes = {
searchState: PropTypes.object,
resultsState: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
onSearchStateChange: PropTypes.func
};
render () {
return (
<InstantSearch
appId='appId' // change this
apiKey='apiKey' // change this
indexName='indexName' // change this
resultsState={this.props.resultsState}
onSearchStateChange={this.props.onSearchStateChange}
searchState={this.props.searchState}
>
<Configure hitsPerPage={10} />
<header>
<h1>React InstantSearch + Next.Js</h1>
<SearchBox />
</header>
<content>
<menu>
<RefinementList attributeName='category' />
</menu>
<results>
<Hits hitComponent={HitComponent} />
</results>
</content>
<footer>
<Pagination />
<div>
See{' '}
<a href='https://github.com/algolia/react-instantsearch/tree/master/packages/react-instantsearch/examples/next-app'>
source code
</a>{' '}
on github
</div>
</footer>
</InstantSearch>
)
}
}
|
src/redux/components/App.js
|
davidraleigh/universal-redux-starter-todo
|
import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'
const App = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
)
export default App
|
admin/client/App/screens/Item/components/EditFormHeader.js
|
benkroeger/keystone
|
import React from 'react';
import { findDOMNode } from 'react-dom';
import { connect } from 'react-redux';
import Toolbar from './Toolbar';
import ToolbarSection from './Toolbar/ToolbarSection';
import EditFormHeaderSearch from './EditFormHeaderSearch';
import { Link } from 'react-router';
import Drilldown from './Drilldown';
import { GlyphButton, ResponsiveText } from '../../../elemental';
export const EditFormHeader = React.createClass({
displayName: 'EditFormHeader',
propTypes: {
data: React.PropTypes.object,
list: React.PropTypes.object,
toggleCreate: React.PropTypes.func,
},
getInitialState () {
return {
searchString: '',
};
},
toggleCreate (visible) {
this.props.toggleCreate(visible);
},
searchStringChanged (event) {
this.setState({
searchString: event.target.value,
});
},
handleEscapeKey (event) {
const escapeKeyCode = 27;
if (event.which === escapeKeyCode) {
findDOMNode(this.refs.searchField).blur();
}
},
renderDrilldown () {
return (
<ToolbarSection left>
{this.renderDrilldownItems()}
{this.renderSearch()}
</ToolbarSection>
);
},
renderDrilldownItems () {
const { data, list } = this.props;
const items = data.drilldown ? data.drilldown.items : [];
let backPath = `${Keystone.adminPath}/${list.path}`;
const backStyles = { paddingLeft: 0, paddingRight: 0 };
// Link to the list page the user came from
if (this.props.listActivePage && this.props.listActivePage > 1) {
backPath = `${backPath}?page=${this.props.listActivePage}`;
}
// return a single back button when no drilldown exists
if (!items.length) {
return (
<GlyphButton
component={Link}
data-e2e-editform-header-back
glyph="chevron-left"
position="left"
style={backStyles}
to={backPath}
variant="link"
>
{list.plural}
</GlyphButton>
);
}
// prepare the drilldown elements
const drilldown = [];
items.forEach((item, idx) => {
// FIXME @jedwatson
// we used to support relationships of type MANY where items were
// represented as siblings inside a single list item; this got a
// bit messy...
item.items.forEach(link => {
drilldown.push({
href: link.href,
label: link.label,
title: item.list.singular,
});
});
});
// add the current list to the drilldown
drilldown.push({
href: backPath,
label: list.plural,
});
return (
<Drilldown items={drilldown} />
);
},
renderSearch () {
var list = this.props.list;
return (
<form action={`${Keystone.adminPath}/${list.path}`} className="EditForm__header__search">
<EditFormHeaderSearch
value={this.state.searchString}
onChange={this.searchStringChanged}
onKeyUp={this.handleEscapeKey}
/>
{/* <GlyphField glyphColor="#999" glyph="search">
<FormInput
ref="searchField"
type="search"
name="search"
value={this.state.searchString}
onChange={this.searchStringChanged}
onKeyUp={this.handleEscapeKey}
placeholder="Search"
style={{ paddingLeft: '2.3em' }}
/>
</GlyphField> */}
</form>
);
},
renderInfo () {
return (
<ToolbarSection right>
{this.renderCreateButton()}
</ToolbarSection>
);
},
renderCreateButton () {
const { nocreate, autocreate, singular } = this.props.list;
if (nocreate) return null;
let props = {};
if (autocreate) {
props.href = '?new' + Keystone.csrf.query;
} else {
props.onClick = () => { this.toggleCreate(true); };
}
return (
<GlyphButton data-e2e-item-create-button="true" color="success" glyph="plus" position="left" {...props}>
<ResponsiveText hiddenXS={`New ${singular}`} visibleXS="Create" />
</GlyphButton>
);
},
render () {
return (
<Toolbar>
{this.renderDrilldown()}
{this.renderInfo()}
</Toolbar>
);
},
});
export default connect((state) => ({
listActivePage: state.lists.page.index,
}))(EditFormHeader);
|
app/javascript/spec/catalog-form/catalog-form.spec.js
|
ManageIQ/manageiq-ui-classic
|
import React from 'react';
import toJson from 'enzyme-to-json';
import fetchMock from 'fetch-mock';
import { shallow } from 'enzyme';
import CatalogForm from '../../components/catalog-form/catalog-form';
import '../helpers/miqSparkle';
import '../helpers/miqAjaxButton';
import '../helpers/addFlash';
import { mount } from '../helpers/mountForm';
describe('Catalog form component', () => {
let submitSpyMiqSparkleOn;
let submitSpyMiqSparkleOff;
let spyMiqAjaxButton;
const resources = [
{ href: 'http://localhost:3000/api/service_templates/44', name: 'template 44' },
{ href: 'http://localhost:3000/api/service_templates/10', name: 'template 10' },
];
const assignedResources = {
name: 'DROGO',
description: 'This is a DROGO!',
service_templates: {
resources: [
{ href: 'http://localhost:3000/api/service_templates/2', name: 'template 2' },
{ href: 'http://localhost:3000/api/service_templates/6', name: 'template 6' },
],
},
};
const originalRightValues = [
{ value: 'http://localhost:3000/api/service_templates/2', label: 'template 2' },
{ value: 'http://localhost:3000/api/service_templates/6', label: 'template 6' },
];
const rightValues = [
'http://localhost:3000/api/service_templates/2',
'http://localhost:3000/api/service_templates/6',
];
const urlFreeTemplates = '/api/service_templates?expand=resources&filter[]=service_template_catalog_id=null';
const urlTemplates = '/api/service_catalogs/1001?expand=service_templates';
beforeEach(() => {
submitSpyMiqSparkleOn = jest.spyOn(window, 'miqSparkleOn');
submitSpyMiqSparkleOff = jest.spyOn(window, 'miqSparkleOff');
spyMiqAjaxButton = jest.spyOn(window, 'miqAjaxButton');
});
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
submitSpyMiqSparkleOn.mockRestore();
submitSpyMiqSparkleOff.mockRestore();
spyMiqAjaxButton.mockRestore();
});
it('should render add variant form', (done) => {
fetchMock.getOnce(urlFreeTemplates, { resources });
const wrapper = shallow(<CatalogForm />);
setImmediate(() => {
wrapper.update();
expect(toJson(wrapper.dive())).toMatchSnapshot();
done();
});
});
it('should render edit variant form', (done) => {
fetchMock.getOnce(urlFreeTemplates, { resources })
.getOnce(urlTemplates, assignedResources);
const wrapper = shallow(<CatalogForm catalogId="1001" />);
setImmediate(() => {
wrapper.update();
expect(toJson(wrapper.dive())).toMatchSnapshot();
done();
});
});
it('should call cancel callback', (done) => {
fetchMock.getOnce(urlFreeTemplates, { resources })
.getOnce(urlTemplates, assignedResources);
const wrapper = mount(<CatalogForm catalogId="1001" />);
const url = '/catalog/st_catalog_edit/1001?button=cancel';
setImmediate(() => {
wrapper.update();
const button = wrapper.find('Button[label="Cancel"] button').first();
button.simulate('click');
expect(spyMiqAjaxButton).toHaveBeenCalledWith(url);
done();
});
});
it('should request data after mount and stop loading when creating new catalog', (done) => {
fetchMock.getOnce(urlFreeTemplates, { resources });
const wrapper = mount(<CatalogForm />);
expect(submitSpyMiqSparkleOn).toHaveBeenCalled();
expect(fetchMock.called(urlFreeTemplates)).toBe(true);
setImmediate(() => {
wrapper.update();
expect(wrapper.children().state().isLoaded).toBe(true);
expect(submitSpyMiqSparkleOff).toHaveBeenCalled();
done();
});
});
it('should request data after mount and set to state when editing catalog', (done) => {
fetchMock
.getOnce(urlFreeTemplates, { resources })
.getOnce(urlTemplates, assignedResources);
const wrapper = mount(<CatalogForm catalogId="1001" />);
expect(submitSpyMiqSparkleOn).toHaveBeenCalled();
expect(fetchMock.called(urlFreeTemplates)).toBe(true);
expect(fetchMock.called(urlTemplates)).toBe(true);
setImmediate(() => {
wrapper.update();
expect(wrapper.children().state().initialValues).toEqual({
name: 'DROGO',
description: 'This is a DROGO!',
service_templates: rightValues,
});
expect(wrapper.children().state().originalRightValues).toEqual(originalRightValues);
expect(submitSpyMiqSparkleOff).toHaveBeenCalled();
done();
});
});
it('should not submit values when form is not valid', (done) => {
fetchMock.getOnce(urlFreeTemplates, { resources });
const wrapper = mount(<CatalogForm />);
setImmediate(() => {
wrapper.update();
const spy = jest.spyOn(wrapper.children().instance(), 'submitValues');
wrapper.find('form').simulate('submit');
expect(spy).toHaveBeenCalledTimes(0);
done();
});
});
it('submit post data to API when adding new form', (done) => {
const urlCreate = '/api/service_catalogs';
fetchMock.getOnce(urlFreeTemplates, { resources });
fetchMock.postOnce(urlCreate, {});
const wrapper = mount(<CatalogForm />);
const values = {
name: 'Some name',
description: '11',
service_templates: [
{ value: 'http://localhost:3000/api/service_templates/44', label: 'template 44' },
],
};
wrapper.children().instance().submitValues(values).then(() => {
expect(fetchMock.called(urlCreate)).toBe(true);
expect(spyMiqAjaxButton).toHaveBeenCalledWith('/catalog/st_catalog_edit?button=add', { name: 'Some name' });
done();
});
});
it('submit post data to API when adding new form and get error back', (done) => {
const urlCreate = '/api/service_catalogs';
const returnObject = {
status: 400,
body: {
error: { message: 'something' },
},
};
fetchMock.getOnce(urlFreeTemplates, { resources });
fetchMock.postOnce(urlCreate, returnObject);
const wrapper = mount(<CatalogForm />);
const spyHandleError = jest.spyOn(wrapper.children().instance(), 'handleError');
expect(spyHandleError).not.toHaveBeenCalled();
const values = {
name: 'Some name',
description: '11',
service_templates: [
{ value: 'http://localhost:3000/api/service_templates/44', label: 'template 44' },
],
};
return wrapper.children().instance().submitValues(values).then(() => {
expect(spyHandleError).toHaveBeenCalledWith(expect.objectContaining({ data: returnObject.body, status: returnObject.status }));
done();
});
});
it('submit post data to API when editing form and get error back', (done) => {
const returnObject = {
status: 500,
body: {
error: { message: 'something' },
},
};
const apiBase = '/api/service_catalogs/1001';
fetchMock.getOnce(urlFreeTemplates, { resources });
fetchMock.getOnce('/api/service_catalogs/1001?expand=service_templates', {});
fetchMock.postOnce(apiBase, returnObject);
const wrapper = mount(<CatalogForm catalogId="1001" />);
const spyHandleError = jest.spyOn(wrapper.children().instance(), 'handleError');
wrapper.children().instance().setState({ originalRightValues: [] });
expect(spyHandleError).not.toHaveBeenCalled();
const values = {
name: 'Some name',
description: '11',
service_templates: [],
};
return wrapper.children().instance().submitValues(values).then(() => {
expect(spyHandleError).toHaveBeenCalledWith(expect.objectContaining({ data: returnObject.body, status: returnObject.status }));
done();
});
});
it('submit post data to API when editing form and switching items in lists', (done) => {
const apiBase = '/api/service_catalogs/1001';
fetchMock.get(urlFreeTemplates, { resources });
fetchMock.postOnce(apiBase, { id: '1001' });
fetchMock.post(`${apiBase}/service_templates`, {});
fetchMock.get(urlTemplates, assignedResources);
const wrapper = mount(<CatalogForm catalogId="1001" />);
const values = {
name: 'Some name',
description: '11',
service_templates: [
{ value: 'http://localhost:3000/api/service_templates/44', label: 'template 44' },
],
};
wrapper.children().instance().setState({ originalRightValues });
wrapper.children().instance().submitValues(values).then(() => {
expect(fetchMock.called(apiBase)).toBe(true);
expect(fetchMock.called(`${apiBase}/service_templates`)).toBe(true);
expect(spyMiqAjaxButton).toHaveBeenCalledWith('/catalog/st_catalog_edit/1001?button=save', { name: 'Some name' });
done();
});
});
it('submit post data to API when editing form without switching items in lists', (done) => {
const apiBase = '/api/service_catalogs/1001';
fetchMock.get(urlFreeTemplates, { resources });
fetchMock.postOnce(apiBase, { id: '1001' });
fetchMock.post(`${apiBase}/service_templates`, {});
fetchMock.get(urlTemplates, assignedResources);
const wrapper = mount(<CatalogForm catalogId="1001" />);
const values = {
name: 'Some name',
description: '11',
service_templates: rightValues,
};
wrapper.children().instance().setState({ originalRightValues });
wrapper.children().instance().submitValues(values).then(() => {
expect(fetchMock.called(apiBase)).toBe(true);
expect(fetchMock.called(`${apiBase}/service_templates`)).toBe(false);
expect(spyMiqAjaxButton).toHaveBeenCalledWith('/catalog/st_catalog_edit/1001?button=save', { name: 'Some name' });
done();
});
});
describe('#handleError', () => {
it('should not parse duplicate name error', () => {
const error = {
data: { error: { message: 'This is some nice error' } },
};
const wrapper = mount(<CatalogForm catalogId="1001" />);
expect(wrapper.children().instance().handleError(error)).toEqual(error.data.error.message);
});
it('should parse duplicate name error', () => {
const error = {
data: { error: { message: 'Service catalog: Name has already been taken' } },
};
const wrapper = mount(<CatalogForm catalogId="1001" />);
expect(wrapper.children().instance().handleError(error)).toEqual(__('Name has already been taken'));
});
});
});
|
src/Table/TableRow.spec.js
|
und3fined/material-ui
|
// @flow weak
/* eslint-env mocha */
import React from 'react';
import { assert } from 'chai';
import { createShallowWithContext } from 'test/utils';
import TableRow, { styleSheet } from './TableRow';
describe('<TableRow />', () => {
let shallow;
let classes;
before(() => {
shallow = createShallowWithContext();
classes = shallow.context.styleManager.render(styleSheet);
});
it('should render a tr', () => {
const wrapper = shallow(<TableRow />);
assert.strictEqual(wrapper.is('tr'), true, 'should be a tr');
});
it('should spread custom props on the root node', () => {
const wrapper = shallow(<TableRow data-my-prop="woof" />);
assert.strictEqual(wrapper.prop('data-my-prop'), 'woof', 'custom prop should be woof');
});
it('should render with the user and root classes', () => {
const wrapper = shallow(<TableRow className="woof" />);
assert.strictEqual(wrapper.hasClass('woof'), true, 'should have the "woof" class');
assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
});
it('should render children', () => {
const children = <td className="test" />;
const wrapper = shallow(<TableRow>{children}</TableRow>);
assert.strictEqual(wrapper.childAt(0).equals(children), true);
});
it('should render with the head class when in the context of a table head', () => {
const wrapper = shallow(
<TableRow />,
);
wrapper.setContext({ ...wrapper.options.context, table: { head: true } });
assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
assert.strictEqual(wrapper.hasClass(classes.head), true, 'should have the head class');
});
it('should render with the footer class when in the context of a table footer', () => {
const wrapper = shallow(
<TableRow />,
);
wrapper.setContext({ ...wrapper.options.context, table: { footer: true } });
assert.strictEqual(wrapper.hasClass(classes.root), true, 'should have the root class');
assert.strictEqual(wrapper.hasClass(classes.footer), true, 'should have the footer class');
});
});
|
app/views/Resume.js
|
sysrex/sysrex
|
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import Helmet from 'react-helmet';
import axios from 'axios';
import Main from '../layouts/Main';
import Education from '../components/Resume/Education';
import Experience from '../components/Resume/Experience';
import Skills from '../components/Resume/Skills';
import Courses from '../components/Resume/Courses';
import References from '../components/Resume/References';
const sections = [
'Education',
'Experience',
'Skills',
'Courses',
'References',
];
class Resume extends Component {
constructor(props) {
super(props);
this.state = {
data: {},
};
}
componentWillMount() {
axios.get('/api/resume').then(({ data }) => {
if (!data.success) {
return Promise.reject(data.error);
}
return this.setState({ data });
}).catch((error) => {
console.error('resume-api-fetch-error', error);
this.props.history.push('/login'); // eslint-disable-line react/prop-types
});
}
render() {
return (
<Main>
<Helmet title="Resume" />
<article className="post" id="resume">
<header>
<div className="title">
<h2><Link to="/resume">Resume</Link></h2>
<div className="link-container">
{sections.map(sec => (
<h4 key={sec}>
<a href={`#${sec.toLowerCase()}`}>{sec}</a>
</h4>))}
</div>
</div>
</header>
<Education data={this.state.data.degrees} />
<Experience data={this.state.data.positions} />
<Skills skills={this.state.data.skills} categories={this.state.data.categories} />
<Courses data={this.state.data.courses} />
<References />
</article>
</Main>
);
}
}
export default withRouter(Resume);
|
src/svg-icons/action/zoom-in.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionZoomIn = (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 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/>
</SvgIcon>
);
ActionZoomIn = pure(ActionZoomIn);
ActionZoomIn.displayName = 'ActionZoomIn';
ActionZoomIn.muiName = 'SvgIcon';
export default ActionZoomIn;
|
react-components/src/library/components/site-notices/notices.js
|
concord-consortium/rigse
|
import React from 'react'
import Notice from './notice'
import css from './style.scss'
export default class Notices extends React.Component {
constructor (props) {
super(props)
this.renderNoNotices = this.renderNoNotices.bind(this)
}
renderNoNotices () {
return (
<div className={css.adminSiteNoticesNone}>
You have no notices.<br />
To create a notice click the "Create New Notice" button.
</div>
)
}
render () {
const { notices, receivedData } = this.props
if (!receivedData) {
return (
<div>
Loading notices...
</div>
)
}
if (notices.length === 0) {
return (
this.renderNoNotices()
)
}
return (
<table id={css.notice_list} className={css.adminSiteNoticesList}>
<tbody>
<tr>
<th>Notice</th>
<th>Updated</th>
<th>Options</th>
</tr>
{ notices.map(notice => <Notice key={notice.id} notice={notice} getPortalData={this.props.getPortalData} />) }
</tbody>
</table>
)
}
}
|
client/tests/components/layouts/AdminSidebar.spec.js
|
andela-iukwuoma/docman
|
import React from 'react';
import expect from 'expect';
import { shallow } from 'enzyme';
import enzymify from 'expect-enzyme';
import AdminSidebar from '../../../components/layouts/AdminSidebar';
expect.extend(enzymify());
function setup(roleId = 1) {
const props = {
access: { user: { roleId } }
};
return shallow(<AdminSidebar {...props} />);
}
describe('AdminSidebar', () => {
it('renders a div', () => {
const wrapper = setup();
expect(wrapper.find('div').length).toBe(1);
});
it('Material icons have a class of document-icons', () => {
const wrapper = setup();
expect(wrapper.find('i').first()).toHaveClass('document-icons');
});
it('renders 2 Links for superadmin', () => {
const wrapper = setup();
expect(wrapper.find('Link').length).toBe(2);
});
it('renders 1 Link for admin', () => {
const wrapper = setup(2);
expect(wrapper.find('Link').length).toBe(1);
});
});
|
static/src/containers/Group.js
|
cas-x/cas-server
|
/**
* @Author: BingWu Yang <detailyang>
* @Date: 2016-03-14T10:30:11+08:00
* @Email: detailyang@gmail.com
* @Last modified by: detailyang
* @Last modified time: 2016-04-21T17:23:02+08:00
* @License: The MIT License (MIT)
*/
import React, { Component } from 'react';
import Antd, { Table, Button, Row, Col, Input, Icon, Popconfirm } from 'antd';
import { connect } from 'react-redux';
import GroupEditModal from './GroupEditModal';
import GroupMemberModal from './GroupMemberModal';
import { fetchGroupList, setGroupPage, setGroupKeyword, deleteGroup } from '../actions';
const InputGroup = Input.Group;
class Group extends Component {
constructor(props) {
super(props);
this.state = {
editModalVisible: false,
editModalId: 0,
memberModalVisible: false,
memberModalTitle: '',
memberModalId: 0,
};
}
componentWillMount() {
this.fetchGroupList();
}
handleCreateClick() {
this.setState({ editModalVisible: true, editModalId: 0 });
}
handleEditClick(record) {
this.setState({ editModalVisible: true, editModalId: record.id });
}
handleDeleteClick(record) {
this.props.deleteGroup(record.id)
.then(() => {
Antd.message.success('删除成功');
this.fetchGroupList();
})
.catch(() => {
Antd.message.error('删除失败');
});
}
handleKeywordKeyDown(e) {
if (e.key === 'Enter') {
this.handleSearchClick();
}
}
handleSearchClick() {
this.fetchGroupList();
}
openMemberModal(record) {
this.setState({
memberModalTitle: record.name,
memberModalId: record.id,
memberModalVisible: true,
});
}
fetchGroupList() {
return this.props.fetchGroupList()
.catch(error => Antd.message.error(error.message));
}
renderTable() {
const columns = [
{
title: '组名',
dataIndex: 'name',
key: 'name',
}, {
title: '描述',
dataIndex: 'desc',
key: 'desc',
}, {
title: '创建时间',
dataIndex: 'created_at',
key: 'created_at',
}, {
title: '操作',
dataIndex: 'x',
key: 'x',
className: 'text-rigth',
render: (value, record) => {
return (
<div>
<Button
type="ghost"
size="small"
onClick={() => this.openMemberModal(record)}
>
成员
</Button>
<Button
type="ghost"
size="small"
onClick={() => this.handleEditClick(record)}
>
编辑
</Button>
<Popconfirm
placement="left"
title="确认删除?"
onConfirm={() => this.handleDeleteClick(record)}
>
<Button type="ghost" size="small">删除</Button>
</Popconfirm>
</div>
);
},
},
];
const {
group: { list, loading, page, per_page, total },
setGroupPage,
} = this.props;
list.forEach(item => {
item.key = item.id;
});
const pagination = {
total,
current: page,
pageSize: per_page,
showTotal: (_total) => `共 ${_total} 条`,
onChange: (_page) => {
setGroupPage(_page);
this.fetchGroupList();
},
};
return (
<Table
dataSource={list}
loading={loading}
columns={columns}
pagination={pagination}
/>);
}
renderFilter() {
const { setGroupKeyword } = this.props;
return (
<Row style={{ marginBottom: '10px' }}>
<Col span="2">
<Button type="primary" onClick={::this.handleCreateClick}>
<Icon type="plus" />新建
</Button>
</Col>
<Col span="4" offset="18">
<InputGroup className="ant-search-input" size="default">
<Input
defaultValue={this.state.keyword}
onChange={e => { setGroupKeyword(e.target.value); }}
onKeyDown={::this.handleKeywordKeyDown}
/>
<div className="ant-input-group-wrap">
<Button className="ant-search-btn" onClick={this.handleSearchClick}>
<Icon type="search" />
</Button>
</div>
</InputGroup>
</Col>
</Row>
);
}
renderEditModal() {
if (!this.state.editModalVisible) {
return '';
}
const handleOk = () => {
this.setState({ editModalVisible: false });
this.fetchGroupList();
};
const handleCancel = () => {
this.setState({ editModalVisible: false });
};
return (
<GroupEditModal
id={this.state.editModalId}
visible={this.state.editModalVisible}
onOk={handleOk}
onCancel={handleCancel}
/>);
}
renderMemberModal() {
if (!this.state.memberModalVisible) {
return '';
}
const handleClose = () => {
this.setState({ memberModalVisible: false });
};
return (
<GroupMemberModal
visible={this.state.memberModalVisible}
title={this.state.memberModalTitle}
id={this.state.memberModalId}
onOk={handleClose}
onCancel={handleClose}
/>);
}
render() {
return (
<div>
{this.renderEditModal()}
{this.renderMemberModal()}
{this.renderFilter()}
{this.renderTable()}
</div>
);
}
}
export default connect(
({ group }) => ({ group }),
{ fetchGroupList, setGroupPage, setGroupKeyword, deleteGroup }
)(Group);
|
src/components/Promises/promises_categories_tabs.js
|
Betree/democracy-watcher
|
import React from 'react'
import TabsView from '../Utils/tabs_view'
import PromisesList from './promises_list'
const PromisesCategoriesTabs = ({categories, promises}) => {
// Categorize promises in an object
const promisesTabs = []
for(let category of categories) {
const promisesList = <PromisesList promises={promises[category]}/>
promisesTabs.push(TabsView.create_tab(category, category, promisesList))
}
return <TabsView className="tabs-view" tabs={promisesTabs}/>
}
export default PromisesCategoriesTabs
|
src/index.js
|
chasm/react-redux-base
|
import React from 'react'
import ReactDOM from 'react-dom'
import App from './components/App.jsx'
const app = document.createElement('div')
document.body.appendChild(app)
ReactDOM.render(<App/>, app)
|
newclient/scripts/components/user/sidebar-step/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 classNames from 'classnames';
import {CurrentStepIcon} from '../../dynamic-icons/current-step-icon';
import {CompletedStepIcon} from '../../dynamic-icons/completed-step-icon';
import {DisclosureActions} from '../../../actions/disclosure-actions';
export class SidebarStep extends React.Component {
constructor() {
super();
this.navigate = this.navigate.bind(this);
}
navigate() {
DisclosureActions.jumpToStep(this.props.step);
}
render() {
switch (this.props.state.toLowerCase()) {
case 'complete':
return (
<div className={classNames(styles.clickable, this.props.className)} onClick={this.navigate}>
<li className={styles.container}>
<CompletedStepIcon
className={`${styles.override} ${styles.icon}`}
color={window.colorBlindModeOn ? 'black' : '#0095A0'}
/>
<span className={styles.stepName}>{this.props.label}</span>
</li>
</div>
);
case 'active':
return (
<div className={classNames(this.props.className)}>
<li className={`${styles.container} ${styles.selected}`}>
<CurrentStepIcon
className={`${styles.override} ${styles.icon}`}
color={window.colorBlindModeOn ? 'black' : '#0095A0'}
/>
<span className={styles.stepName}>{this.props.label}</span>
</li>
</div>
);
case 'incomplete':
if (this.props.visited) {
return (
<li className={classNames(styles.container, styles.clickable, this.props.className)} onClick={this.navigate}>
<i className={`fa fa-circle ${styles.futureIcon}`} />
<span className={styles.stepName}>{this.props.label}</span>
</li>
);
}
return (
<li className={classNames(styles.container, styles.incomplete, this.props.className)}>
<i className={`fa fa-circle ${styles.futureIcon} ${styles.incomplete}`} />
<span className={styles.stepName}>{this.props.label}</span>
</li>
);
}
}
}
SidebarStep.defaultProps = {
state: ''
};
|
frontend/src/AddMovie/AddNewMovie/AddNewMovieConnector.js
|
Radarr/Radarr
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { clearAddMovie, lookupMovie } from 'Store/Actions/addMovieActions';
import { clearQueueDetails, fetchQueueDetails } from 'Store/Actions/queueActions';
import { fetchRootFolders } from 'Store/Actions/rootFolderActions';
import { fetchImportExclusions } from 'Store/Actions/Settings/importExclusions';
import createUISettingsSelector from 'Store/Selectors/createUISettingsSelector';
import parseUrl from 'Utilities/String/parseUrl';
import AddNewMovie from './AddNewMovie';
function createMapStateToProps() {
return createSelector(
(state) => state.addMovie,
(state) => state.movies.items.length,
(state) => state.router.location,
createUISettingsSelector(),
(addMovie, existingMoviesCount, location, uiSettings) => {
const { params } = parseUrl(location.search);
return {
...addMovie,
term: params.term,
hasExistingMovies: existingMoviesCount > 0,
colorImpairedMode: uiSettings.enableColorImpairedMode
};
}
);
}
const mapDispatchToProps = {
lookupMovie,
clearAddMovie,
fetchRootFolders,
fetchImportExclusions,
fetchQueueDetails,
clearQueueDetails
};
class AddNewMovieConnector extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this._movieLookupTimeout = null;
}
componentDidMount() {
this.props.fetchRootFolders();
this.props.fetchImportExclusions();
this.props.fetchQueueDetails();
}
componentWillUnmount() {
if (this._movieLookupTimeout) {
clearTimeout(this._movieLookupTimeout);
}
this.props.clearAddMovie();
this.props.clearQueueDetails();
}
//
// Listeners
onMovieLookupChange = (term) => {
if (this._movieLookupTimeout) {
clearTimeout(this._movieLookupTimeout);
}
if (term.trim() === '') {
this.props.clearAddMovie();
} else {
this._movieLookupTimeout = setTimeout(() => {
this.props.lookupMovie({ term });
}, 300);
}
};
onClearMovieLookup = () => {
this.props.clearAddMovie();
};
//
// Render
render() {
const {
term,
...otherProps
} = this.props;
return (
<AddNewMovie
term={term}
{...otherProps}
onMovieLookupChange={this.onMovieLookupChange}
onClearMovieLookup={this.onClearMovieLookup}
/>
);
}
}
AddNewMovieConnector.propTypes = {
term: PropTypes.string,
lookupMovie: PropTypes.func.isRequired,
clearAddMovie: PropTypes.func.isRequired,
fetchRootFolders: PropTypes.func.isRequired,
fetchImportExclusions: PropTypes.func.isRequired,
fetchQueueDetails: PropTypes.func.isRequired,
clearQueueDetails: PropTypes.func.isRequired
};
export default connect(createMapStateToProps, mapDispatchToProps)(AddNewMovieConnector);
|
test/TooltipSpec.js
|
laran/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Tooltip from '../src/Tooltip';
describe('Tooltip', () => {
it('Should output a tooltip with content', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Tooltip positionTop={10} positionLeft={20}>
<strong>Tooltip Content</strong>
</Tooltip>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
const tooltip = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tooltip');
assert.deepEqual(tooltip.props.style, {top: 10, left: 20});
});
describe('When a style property is provided', () => {
it('Should render a tooltip with merged styles', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Tooltip style={{opacity: 0.9}} positionTop={10} positionLeft={20}>
<strong>Tooltip Content</strong>
</Tooltip>
);
const tooltip = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'tooltip');
assert.deepEqual(tooltip.props.style, {opacity: 0.9, top: 10, left: 20});
});
});
});
|
js/src/components/Editor/__test__/editorTest.js
|
andresin87/react-draft-wysiwyg
|
/* @flow */
import React from 'react';
import { expect, assert } from 'chai';
import { shallow, mount } from 'enzyme';
import Editor from '..';
describe('Editor menu test suite', () => {
it('should have a div when rendered', () => {
expect(shallow(<Editor />).node.type).to.equal('div');
});
it('should have an editorState object in state', () => {
const editor = shallow(<Editor />);
assert.isDefined(editor.state().editorState);
assert.isDefined(editor.state().editorFocused);
});
});
|
stories/Dropdown/ExampleWithCustomValue.js
|
skyiea/wix-style-react
|
import React from 'react';
import Dropdown from 'wix-style-react/Dropdown';
import Checkbox from 'wix-style-react/Checkbox';
const style = {
display: 'inline-block',
padding: '0 5px 0',
width: '200px',
lineHeight: '22px',
marginBottom: '350px'
};
class CustomValuesInDropdown extends React.Component {
constructor(props) {
super(props);
this.state = {checkboxChecked: false};
}
render() {
const valueParser = option => (typeof option.value === 'string') ?
option.value :
option.value.props.children[0].props.children;
const onSelect = option => console.log('Selected ', valueParser(option));
const onChange = () => this.setState({checkboxChecked: !this.state.checkboxChecked});
const customValue = (
<div>
<span>Custom Value</span>
<span style={{marginLeft: '5px'}} onClick={e => e.stopPropagation()}>
<Checkbox onChange={onChange} checked={this.state.checkboxChecked}/>
</span>
</div>
);
const options = [
{id: 1, value: 'Option 1'},
{id: 2, value: 'Option 2'},
{id: 3, value: 'Option 3'},
{id: 4, value: 'Option 4', disabled: true},
{id: 5, value: 'Option 5'},
{id: 6, value: customValue},
{id: 7, value: customValue}
];
return (
<Dropdown
options={options}
selectedId={6}
placeholder={'Choose an option'}
valueParser={valueParser}
onSelect={onSelect}
/>
);
}
}
export default () =>
<div className="ltr" style={style}>
<CustomValuesInDropdown/>
</div>;
|
src/components/App/index.js
|
mvaldas9/wallscreen
|
import './styles.css';
import React from 'react';
import Background from '../Background';
import Clock from '../Clock';
import Board from '../Board';
import Settings from '../Settings';
class App extends React.Component {
render() {
return (
<div className="app">
<Background />
<Clock />
<Board />
<Settings />
</div>
);
}
}
export default App;
|
src/components/Main.js
|
bjhan/mytesthome
|
require('normalize.css/normalize.css');
require('styles/App.css');
import React from 'react';
//获取图片的信息
var imageDatas = require('../data/imageDatas.json');
//利用自执行函数,返回图片的URL信息
imageDatas = (function getImageURL(imageDatasArr) {
for(var i = 0;i < imageDatasArr.length; i++){
var singleImageData = imageDatasArr[i];
singleImageData.imgURL = require('../images/' + singleImageData.filename);
imageDatasArr[i] = singleImageData;
}
return imageDatasArr;
})(imageDatas);
class ImgFigures extends React.Component {
render() {
return (
<figure className = "img-figure">
<img src={this.props.data.imgURL} alt={this.props.data.title}/>
<figcaption>
<h2 className = "img-title">{this.props.data.title}</h2>
</figcaption>
</figure>
);
}
}
class AppComponent extends React.Component {
Constant:{
centerPos:{
left: 0;
right: 0;
},
hPosRange: {
leftSecX: [0,0],
rightSecX: [0,0],
y: [0,0]
},
vPosRange: {
x: [0,0],
topY: [0,0]
}
};
//获取区间内随机值
function getRangeRandom(low, high) {
return Math.ceil(Math.random() * (high - low) + low);
}
rearange = function (centerIndex) {
var imgsArrangeArr = this.state.imgsArrangeArr,
Constant = this.Constant,
centerPos = Constant.centerPos,
hPosRange = Constant.hPosRange,
vPosRange = Constant.vPosRange,
hPosRangeLeftSecX = hPosRange.leftSecX,
hPosRangeRightSecX = hPosRange.rightSecx,
hPosRangeY = hPosRange.y,
vPosRangeTopY = vPosRange.topY,
vPosRangeX = vPosRange.x,
imgsArrangeTopArr = [],
topImgNum = Math.ceil(Math.random() * 2),
topImgSpliceIndex = 0,
imgsArrangeCenterArr = imgsArrangeArr.splice(centerIndex,1);
//居中
imgsArrangeCenterArr[0].pos = centerPos;
//取出布局上册图片的状态信息
topImgSpliceIndex = Math.ceil(Math.random * (imgsArrangeArr.length - topImgNum));
imgsArrangeTopArr = imgsArrangeArr.splice(topImgSpliceIndex,topImgNum);
//布局上册图片
imgsArrangeTopArr.forEach(function (value,index) {
imgsArrangeTopArr[index].pos = {
top: ,
left:
}
});
}
getInitialState() {
return {
imgsArrangeArr: [
/* {
pos: {
left: 0,
right: 0
}
}
*/
]
};
}
//组件加载以后为每一张图片计算范围
componentDidMount() {
//拿到舞台大小
var stageDom = this.refs.stage,
stageWidth = stageDom.scrollWidth,
stageHeight = stageDom.scrollHeight,
halfStageW = Math.ceil(stageWidth / 2),
halfStageH = Math.ceil(stageHeight / 2);
//拿到imageFigure大小
var imgFigureDom = this.refs.imageFigure0,
imageW = imgFigureDom.scrollWidth,
imageH = imgFigureDom.scrollHeight,
halfImgW = Math.ceil(imageW / 2),
halfImgH = Math.ceil(imageH / 2);
//计算中心图片的位置点
this.Constant.centerPos = {
left: halfStageW - halfImgW,
top: halfStageH - halfImgH
}
//计算左侧右侧区域图片排布图片取值范围
this.Constant.hPosRange.leftSecX[0] = -halfImgW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImgW * 3;
this.Constant.hPosRange.rightSecX[0] = halfStageW - halfImgW;
this.Constant.hPosRange.rightSecX[1] = stageWidth -halfImgW;
this.Constant.hPosRange.y[0] = -halfImgH;
this.Constant.hPosRange.y[1] = stageHeight - halfImgH;
//计算上侧区域图片排布位置的取值范围
this.Constant.vPosRange.topY[0] = -halfImgH;
this.Constant.vPosRange.topY[1] = halfStageH - halfImgH * 3;
this.Constant.vPosRange.x[0] = halfImgW -imageW;
this.Constant.vPosRange.x[1] = halfImgW
this.rearange(0);
}
render() {
var controllerUnits = [],
imgFigure = [];
imageDatas.forEach(function (value,index) {
if(!this.state.imgsArrangeArr[index]){
this.state.imgsArrangeArr[index] = {
pos: {
left: 0,
top: 0
}
}
}
imgFigure.push(<ImgFigures data = {value} key = {value.filename} ref ={'imageFigure'+index}/>);
}.bind(this));
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgFigure}
</section>
<nav className="controller-nav">
{controllerUnits}
</nav>
</section>
);
}
}
AppComponent.defaultProps = {
};
export default AppComponent;
|
packages/reactor-tests/src/App.js
|
dbuhrman/extjs-reactor
|
import React, { Component } from 'react';
import { Router, Route, IndexRoute, Link, hashHistory } from 'react-router'
import * as tests from './tests';
import Layout from './Layout';
import TestIndex from './TestIndex';
export default class App extends Component {
render() {
return (
<Router history={hashHistory}>
<Route path="/" component={Layout}>
<IndexRoute component={TestIndex}/>
{ Object.keys(tests).map(name => (
<Route key={name} path={name} component={tests[name]}/>
))}
</Route>
</Router>
)
}
}
|
src/Tooltip.js
|
adampickeral/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
const Tooltip = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: CustomPropTypes.isRequiredForA11y(
React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
),
/**
* Sets the direction the Tooltip is positioned towards.
*/
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "left" position value for the Tooltip.
*/
positionLeft: React.PropTypes.number,
/**
* The "top" position value for the Tooltip.
*/
positionTop: React.PropTypes.number,
/**
* The "left" position value for the Tooltip arrow.
*/
arrowOffsetLeft: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
]),
/**
* The "top" position value for the Tooltip arrow.
*/
arrowOffsetTop: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
]),
/**
* Title text
*/
title: React.PropTypes.node
},
getDefaultProps() {
return {
placement: 'right'
};
},
render() {
const classes = {
'tooltip': true,
[this.props.placement]: true
};
const style = {
'left': this.props.positionLeft,
'top': this.props.positionTop,
...this.props.style
};
const arrowStyle = {
'left': this.props.arrowOffsetLeft,
'top': this.props.arrowOffsetTop
};
return (
<div role='tooltip' {...this.props} className={classNames(this.props.className, classes)} style={style}>
<div className="tooltip-arrow" style={arrowStyle} />
<div className="tooltip-inner">
{this.props.children}
</div>
</div>
);
}
});
export default Tooltip;
|
packages/watif-display/src/components/display.js
|
jwillesen/watif
|
import React from 'react'
import {func, string} from 'prop-types'
import {FontAwesomeIcon} from '@fortawesome/react-fontawesome'
import {faBook, faEye, faSearch, faHandHoldingBox} from '@fortawesome/pro-regular-svg-icons'
import {Tabs, TabPanel} from './tabs'
import InteractiveDescription from './interactive-description'
import Watext from './watext'
import {storyShape} from '../property-shapes'
import './display.css'
export default class Display extends React.Component {
static propTypes = {
storyState: storyShape.isRequired,
executeVerb: func, // ({ id: verb-id, subject: item-id, target: (item-id | null) })
title: string,
}
constructor(...args) {
super(...args)
this.state = {
activeTab: 'look',
}
}
handleTabRequest = tabPanelId => {
this.setState({activeTab: tabPanelId})
}
handleItemClick = itemId => {
if (this.props.executeVerb) {
this.props.executeVerb({
id: 'examine',
subject: itemId,
target: null,
})
}
this.setState({activeTab: 'examine'})
}
handleCurrentItemVerbClick = verb => {
if (!this.props.executeVerb) return
this.props.executeVerb({
id: verb.id,
subject: this.props.storyState.universe.currentItemId,
})
// this.setState({activeTab: 'events'})
}
handleCurrentRoomVerbClick = verb => {
if (!this.props.executeVerb) return
this.props.executeVerb({
id: verb.id,
subject: this.props.storyState.universe.currentRoomId,
})
// this.setState({activeTab: 'events'})
}
icon(fa) {
return <FontAwesomeIcon icon={fa} size="lg" />
}
render() {
return (
<div styleName="root">
<div styleName="log-header">
<div styleName="log-header-icon">
{this.icon(faBook)} {this.props.title}
</div>
</div>
<div styleName="log">
<Watext watext={this.props.storyState.universe.log} />
</div>
<div styleName="tabs">
<Tabs
label="Story Content"
activeTab={this.state.activeTab}
onTabRequest={this.handleTabRequest}
>
<TabPanel id="look" label={this.icon(faEye)} a11yLabel="look around">
<InteractiveDescription
title="Look Around"
emptyText="No Current Room"
watext={this.props.storyState.currentRoomDescription}
verbs={this.props.storyState.currentRoomVerbs}
onItemClick={this.handleItemClick}
onVerbClick={this.handleCurrentRoomVerbClick}
/>
</TabPanel>
<TabPanel id="examine" label={this.icon(faSearch)} a11yLabel="examine">
<InteractiveDescription
title="Examine"
emptyText="No Current Item"
watext={this.props.storyState.currentItemDescription}
verbs={this.props.storyState.currentItemVerbs}
onItemClick={this.handleItemClick}
onVerbClick={this.handleCurrentItemVerbClick}
/>
</TabPanel>
<TabPanel id="inventory" label={this.icon(faHandHoldingBox)} a11yLabel="inventory">
<span>Inventory</span>
</TabPanel>
</Tabs>
</div>
</div>
)
}
}
|
src/svg-icons/editor/vertical-align-center.js
|
pomerantsev/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorVerticalAlignCenter = (props) => (
<SvgIcon {...props}>
<path d="M8 19h3v4h2v-4h3l-4-4-4 4zm8-14h-3V1h-2v4H8l4 4 4-4zM4 11v2h16v-2H4z"/>
</SvgIcon>
);
EditorVerticalAlignCenter = pure(EditorVerticalAlignCenter);
EditorVerticalAlignCenter.displayName = 'EditorVerticalAlignCenter';
EditorVerticalAlignCenter.muiName = 'SvgIcon';
export default EditorVerticalAlignCenter;
|
node_modules/react-bootstrap/es/Badge.js
|
ProjectSunday/rooibus
|
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 { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
// TODO: `pullRight` doesn't belong here. There's no special handling here.
var propTypes = {
pullRight: React.PropTypes.bool
};
var defaultProps = {
pullRight: false
};
var Badge = function (_React$Component) {
_inherits(Badge, _React$Component);
function Badge() {
_classCallCheck(this, Badge);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Badge.prototype.hasContent = function hasContent(children) {
var result = false;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (child || child === 0) {
result = true;
}
});
return result;
};
Badge.prototype.render = function render() {
var _props = this.props,
pullRight = _props.pullRight,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['pullRight', 'className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), {
'pull-right': pullRight,
// Hack for collapsing on IE8.
hidden: !this.hasContent(children)
});
return React.createElement(
'span',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
children
);
};
return Badge;
}(React.Component);
Badge.propTypes = propTypes;
Badge.defaultProps = defaultProps;
export default bsClass('badge', Badge);
|
frontend/assets/js/layout/GenreSlide.js
|
fga-verival/2017-1Grupo2
|
import React from 'react';
import Slider from 'react-slick'
require("slick-carousel/slick/slick.css");
require("slick-carousel/slick/slick-theme.css");
import GameCard from "../components/cards/GameCard";
import { gameListApi } from '../resource/GameApi';
import { Link } from 'react-router-dom'
import { Grid } from 'semantic-ui-react'
const slideHeight = {
"height": "280px",
"position":"relative",
"minHeight":"180px",
};
export default class GenreSlide extends React.Component {
constructor (props) {
super(props);
this.state = {"games": []};
}
componentWillMount () {
gameListApi((games) => { this.setState({games}) });
}
render() {
const gameCards = this.mountCards();
const settings = {
dots: true,
centerMode: true,
infinite: true,
speed: 500,
slidesToShow: 3,
slidesToScroll: 1,
responsive: [
{
breakpoint: 980,
settings: {
arrows: false,
centerMode: true,
centerPadding: '40px',
slidesToShow: 2
}
},
{
breakpoint: 480,
settings: {
arrows: false,
centerMode: true,
centerPadding: '40px',
slidesToShow: 1
}
}
]
};
if(gameCards.length){
return (
<div style={slideHeight}>
<Grid.Column>
<Slider {...settings}>
{gameCards}
</Slider>
</Grid.Column>
</div>
);
}else{
return <img/>
}
}
mountCards(){
const gameCards = [], cardsAmount = 6;
for(var i=0; i < cardsAmount && i < this.state.games.length - 1; i++){
const image =
(<div>
<Link to={"games/" + this.state.games[i].pk}>
<GameCard data={this.state.games[i]} />
</Link>
</div>)
gameCards.push(image);
}
return gameCards;
}
}
|
app/containers/App.js
|
lumibloc/tabloc
|
// @flow
import React, { Component } from 'react';
import type { Children } from 'react';
export default class App extends Component {
props: {
children: Children
};
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
|
docs/src/Anchor.js
|
roderickwang/react-bootstrap
|
import React from 'react';
const Anchor = React.createClass({
propTypes: {
id: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
},
render() {
return (
<a id={this.props.id} href={'#' + this.props.id} className="anchor">
<span className="anchor-icon">#</span>
{this.props.children}
</a>
);
}
});
export default Anchor;
|
imports/ui/pages/reset-password.js
|
irvinlim/free4all
|
import React from 'react';
import { Grid, Row, Col, Alert, FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap';
import { handleResetPassword } from '../../modules/reset-password';
export class ResetPassword extends React.Component {
componentDidMount() {
handleResetPassword({
component: this,
token: this.props.params.token,
});
}
handleSubmit(event) {
event.preventDefault();
}
render() {
return <Grid>
<Row>
<Col xs={ 12 } sm={ 6 } md={ 4 }>
<h4 className="page-header">Reset Password</h4>
<Alert bsStyle="info">
To reset your password, enter a new one below. You will be logged in
with your new password.
</Alert>
<form ref="resetPassword" className="reset-password" onSubmit={ this.handleSubmit }>
<FormGroup>
<ControlLabel>New Password</ControlLabel>
<FormControl
type="password"
ref="newPassword"
name="newPassword"
placeholder="New Password"
/>
</FormGroup>
<FormGroup>
<ControlLabel>Repeat New Password</ControlLabel>
<FormControl
type="password"
ref="repeatNewPassword"
name="repeatNewPassword"
placeholder="Repeat New Password"
/>
</FormGroup>
<Button type="submit" bsStyle="success">Reset Password & Login</Button>
</form>
</Col>
</Row>
</Grid>;
}
}
ResetPassword.propTypes = {
params: React.PropTypes.object,
};
|
src/index.js
|
GiacomoSorbi/8-form-elements
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.