path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
blueocean-material-icons/src/js/components/svg-icons/hardware/developer-board.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const HardwareDeveloperBoard = (props) => (
<SvgIcon {...props}>
<path d="M22 9V7h-2V5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2v-2h2v-2h-2v-2h2v-2h-2V9h2zm-4 10H4V5h14v14zM6 13h5v4H6zm6-6h4v3h-4zM6 7h5v5H6zm6 4h4v6h-4z"/>
</SvgIcon>
);
HardwareDeveloperBoard.displayName = 'HardwareDeveloperBoard';
HardwareDeveloperBoard.muiName = 'SvgIcon';
export default HardwareDeveloperBoard;
|
docs/src/App.js
|
GWShark0/hello-package
|
import React, { Component } from 'react';
import Hello from '../../src/Hello';
import '../../src/Hello.css';
class App extends Component {
render() {
return (
<div className="app">
<Hello />
</div>
);
}
}
export default App;
|
app/components/UnitCard/index.js
|
medevelopment/UMA
|
import React from 'react';
import {Link, browserHistory} from 'react-router';
import {CardTitle} from 'material-ui/Card';
import styled from 'styled-components';
const PropCard = styled.div`
position: relative;
margin-bottom: 25px;
background-position: 50% 50%;
background-size: cover;
width: 100% !important;
overflow: hidden;
background: #fff;
img {
width: 30px;
margin: 0px auto;
height: 30px;
}
&:hover {
box-shadow: 0px 0px 11px #d6d6d6;
}
.prop_title {
margin-top: -27px;
background: rgba(56, 56, 56, 0.35);
display: block;
color: #fff;
z-index: 99;
position: absolute;
padding: 2px 10px;
height: 25px;
overflow: hidden;
}
`;
export default class UnitCard extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
go(propUrl) {
browserHistory.push(propUrl);
}
render() {
const propUrl = '/unit/' + this.props.property.PropertyId;
return (
<div className="col-md-4">
<PropCard>
<div onClick={() => this.go(propUrl)}
overlay={<CardTitle title="Overlay title" subtitle="Overlay subtitle" />}
>
<Link to={propUrl} >
{(this.props.property.FileName) ? <img src={this.props.property.FileName} alt="" style={{width: '100%', height: '140px', objectFit: 'cover'}} /> :
<img src="http://res.cloudinary.com/me-development/image/upload/v1499499169/1499499169default.jpg.jpg" alt="" style={{width: '100%', height: '140px', objectFit: 'cover'}} />}
<div className="prop_title"> {this.props.property.PropertyName} </div>
</Link>
</div>
</PropCard>
</div>
);
}
}
|
PhotoSpace/imports/ui/layouts/MainLayout.js
|
gergi30/elte-ik-szakdolgozat
|
// Llamado por /imports/startup/client/routes.js
import React from 'react';
import {createContainer} from 'meteor/react-meteor-data';
import lightBaseTheme from 'material-ui/styles/baseThemes/lightBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import injectTapEventPlugin from 'react-tap-event-plugin';
import Drawer from 'material-ui/Drawer';
import MenuItem from 'material-ui/MenuItem';
import ImageDehaze from 'material-ui/svg-icons/image/dehaze';
import ContentClear from 'material-ui/svg-icons/content/clear';
import AppBar from 'material-ui/AppBar';
injectTapEventPlugin();
class MainLayout extends React.Component {
constructor(props) {
super(props);
this.state = {open: false};
this.handleToggle = this.handleToggle.bind(this);
this.handleClose = this.handleClose.bind(this);
}
handleToggle() { this.setState({open: !this.state.open}); }
handleClose() { this.setState({open: false}); }
render() {
return (
<MuiThemeProvider muiTheme={getMuiTheme(lightBaseTheme)}>
<div>
<AppBar
title="PhotoSpace"
iconClassNameRight="muidocs-icon-navigation-expand-more"
onLeftIconButtonTouchTap={this.handleToggle}
/>
<Drawer
docked={false}
width={300}
open={this.state.open}
onRequestChange={(open) => this.setState({open})}
>
{/* <ContentClear onClick={this.handleClose}/> */}
<img src="https://s13.postimg.org/hkhubr0rb/menu_img.png"></img>
<MenuItem a href="/" onClick={this.handleClose}>Home</MenuItem>
<MenuItem onClick={this.handleClose}>Menu Item 2</MenuItem>
</Drawer>
{this.props.main}
</div>
</MuiThemeProvider>
);
}
}
export default createContainer(props => {
return {
// user: Meteor.user(),
};
}, MainLayout);
|
webapp/src/NewPlayerButton.js
|
mathieu-pousse/go-dart
|
import React, { Component } from 'react';
import { browserHistory } from 'react-router';
import {Input} from 'react-materialize'
class NewPlayerButton extends Component {
constructor(props) {
super(props)
this.state = {
boards: []
}
this.handleBoardChange = this.handleBoardChange.bind(this)
this.handlePlayerNameChange = this.handlePlayerNameChange.bind(this)
}
componentDidMount() {
this.listBoards()
}
addPlayer() {
fetch('/api/games/' + this.props.gameId + "/players", {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
name: this.name,
board: this.board
})
})
.then((response) => response.json())
.then((json) => console.log(json))
.catch((error) => console.log(error))
}
listBoards() {
fetch('/api/boards')
.then(response => response.json())
.then((json) => {
this.setState({ boards: json });
if (json.length != 0) { this.board = json[0] }
})
.catch((error) => console.log(error))
}
handlePlayerNameChange(event) {
this.name = event.target.value
}
handleBoardChange(event) {
this.board = event.target.value
}
render() {
return (
<div className="col s12">
<div className="input-field col s12 l5">
<input id="playerName" type="text" className="validate" onChange={this.handlePlayerNameChange}/>
<label htmlFor="playerName">Player name</label>
</div>
<div className=" col s8 l4">
<Input type='select' label="Board" onChange={this.handleBoardChange}>
{ this.state.boards.map((board) => <option value={board}>{ board }</option>) }
</Input>
</div>
<div className="input-field col s4 l3">
<a className="waves-effect waves-light btn light-blue" onClick={() => this.addPlayer() }>Add</a>
</div>
</div>
)
}
}
export default NewPlayerButton;
|
test/test_helper.js
|
nfcortega89/nikkotoonaughty
|
import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/shared/components/form/formInput/formInput.js
|
sethbergman/operationcode_frontend
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Label from 'shared/components/label/label';
import styles from './formInput.css';
class FormInput extends Component {
constructor() {
super();
this.state = {
text: '',
isValid: true
};
}
handleChange = (event) => {
const valid = this.validate(event.target.value);
this.setState({ text: event.target.value, isValid: valid }, () => {
if (this.props.onChange) {
this.props.onChange(this.state.text, this.state.isValid);
}
});
};
validate = (text) => {
if (this.props.validateFunc) {
return this.props.validateFunc(text);
} else if (text.length > 0 && this.props.validationRegex) {
return this.props.validationRegex.test(text);
} else if (text.length > 0) {
return true;
}
return false;
};
revalidate() {
const valid = this.validate(this.state.text);
this.setState({ isValid: valid });
}
render() {
return (
<div className={styles.formInput}>
{this.props.label && <Label htmlFor={this.props.id}>{this.props.label}</Label>}
<input
className={!this.state.isValid ? styles.error : undefined}
id={this.props.id}
type={this.props.inputType}
value={this.state.text}
placeholder={this.props.placeholder}
onChange={this.handleChange}
/>
{!this.state.isValid && <span>{this.props.validationErrorMessage}</span>}
</div>
);
}
}
FormInput.propTypes = {
label: PropTypes.string,
placeholder: PropTypes.string,
id: PropTypes.string.isRequired,
validationRegex: PropTypes.instanceOf(RegExp),
validationErrorMessage: PropTypes.string,
validateFunc: PropTypes.func,
onChange: PropTypes.func,
inputType: PropTypes.string
};
FormInput.defaultProps = {
label: null,
placeholder: null,
validationRegex: null,
validationErrorMessage: null,
validateFunc: null,
onChange: null,
inputType: 'text'
};
export default FormInput;
|
src/js/components/nodes/registerNodes/RegisterNodesForm.js
|
knowncitizen/tripleo-ui
|
/**
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import { defineMessages, FormattedMessage, injectIntl } from 'react-intl';
import React from 'react';
import PropTypes from 'prop-types';
import { reduxForm, FieldArray } from 'redux-form';
import { Form } from 'react-bootstrap';
import BlankSlate from '../../ui/BlankSlate';
import InlineNotification from '../../ui/InlineNotification';
import RegisterNodeFields from './RegisterNodeFields';
import TabPane from '../../ui/TabPane';
const messages = defineMessages({
addANodeManually: {
id: 'RegisterNodesDialog.addANodeManually',
defaultMessage: 'Add a node manually or upload nodes from a file.'
},
noNodesToRegister: {
id: 'RegisterNodesDialog.noNodesToRegister',
defaultMessage: '"No Nodes To Register"'
}
});
export const RegisterNodesTabPanes = ({ fields, meta, selectedNodeIndex }) => (
<div className="tab-content">
{fields.map((node, index, fields) => (
<TabPane
key={index}
isActive={selectedNodeIndex === index}
// renderOnlyActive
>
<RegisterNodeFields node={node} />
</TabPane>
))}
</div>
);
RegisterNodesTabPanes.propTypes = {
fields: PropTypes.object.isRequired,
meta: PropTypes.object.isRequired,
selectedNodeIndex: PropTypes.number.isRequired
};
const RegisterNodesForm = ({
error,
handleSubmit,
intl: { formatMessage },
selectedNodeIndex
}) => (
<Form onSubmit={handleSubmit} horizontal>
{error && <InlineNotification>{error}</InlineNotification>}
{selectedNodeIndex !== -1 ? (
<FieldArray
name="nodes"
component={RegisterNodesTabPanes}
selectedNodeIndex={selectedNodeIndex}
/>
) : (
<BlankSlate
iconClass="fa fa-cubes"
title={formatMessage(messages.noNodesToRegister)}
>
<p>
<FormattedMessage {...messages.addANodeManually} />
</p>
</BlankSlate>
)}
</Form>
);
RegisterNodesForm.propTypes = {
error: PropTypes.string,
handleSubmit: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
selectedNodeIndex: PropTypes.number.isRequired
};
const form = reduxForm({
form: 'registerNodesForm',
initialValues: { nodes: [] },
destroyOnUnmount: false
});
export default injectIntl(form(RegisterNodesForm));
|
src/GridList/GridList.spec.js
|
rscnt/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import GridList from './GridList';
import getMuiTheme from '../styles/getMuiTheme';
describe('<GridList />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const tilesData = [
{
img: 'images/grid-list/00-52-29-429_640.jpg',
title: 'Breakfast',
author: 'jill111',
},
{
img: 'images/grid-list/burger-827309_640.jpg',
title: 'Tasty burger',
author: 'pashminu',
},
];
it('renders children and change cellHeight', () => {
const cellHeight = 250;
const wrapper = shallowWithContext(
<GridList cellHeight={cellHeight}>
{tilesData.map((tile) => (
<span
key={tile.img}
className="grid-tile"
title={tile.title}
subtitle={<span>by <b>{tile.author}</b></span>}
>
<img src={tile.img} />
</span>
))}
</GridList>
);
assert.equal(wrapper.find('.grid-tile').length, 2, 'should contain the children');
assert.equal(wrapper.children().at(0).prop('style').height, cellHeight + 4, 'should have height to 254');
});
it('renders children by default', () => {
const wrapper = shallowWithContext(
<GridList>
{tilesData.map((tile) => (
<span
key={tile.img}
className="grid-tile"
title={tile.title}
subtitle={<span>by <b>{tile.author}</b></span>}
>
<img src={tile.img} />
</span>
))}
</GridList>
);
assert.equal(wrapper.find('.grid-tile').length, 2, 'should contain the children');
});
it('renders children and change cols', () => {
const wrapper = shallowWithContext(
<GridList cols={4}>
{tilesData.map((tile) => (
<span
key={tile.img}
className="grid-tile"
title={tile.title}
subtitle={<span>by <b>{tile.author}</b></span>}
>
<img src={tile.img} />
</span>
))}
</GridList>
);
assert.equal(wrapper.find('.grid-tile').length, 2, 'should contain the children');
assert.equal(wrapper.children().at(0).prop('style').width, '25%', 'should have 25% of width');
});
it('renders children and change padding', () => {
const padding = 10;
const wrapper = shallowWithContext(
<GridList padding={padding}>
{tilesData.map((tile) => (
<span
key={tile.img}
className="grid-tile"
title={tile.title}
subtitle={<span>by <b>{tile.author}</b></span>}
>
<img src={tile.img} />
</span>
))}
</GridList>
);
assert.equal(wrapper.find('.grid-tile').length, 2, 'should contain the children');
assert.equal(wrapper.children().at(0).prop('style').padding, padding / 2, 'should have 5 of padding');
});
it('renders children and overwrite style', () => {
const style = {
backgroundColor: 'red',
};
const wrapper = shallowWithContext(
<GridList style={style}>
{tilesData.map((tile) => (
<span
key={tile.img}
className="grid-tile"
title={tile.title}
subtitle={<span>by <b>{tile.author}</b></span>}
>
<img src={tile.img} />
</span>
))}
</GridList>
);
assert.equal(wrapper.find('.grid-tile').length, 2, 'should contain the children');
assert.equal(wrapper.prop('style').backgroundColor, style.backgroundColor, 'should have a red backgroundColor');
});
});
|
src/GridList/GridTile.spec.js
|
ichiohta/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import GridTile from './GridTile';
import getMuiTheme from '../styles/getMuiTheme';
describe('<GridTile />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const tileData = {
img: 'images/grid-list/00-52-29-429_640.jpg',
title: 'Breakfast',
author: 'jill111',
};
describe('prop: children', () => {
it('should renders children by default', () => {
const testChildren = <img src={tileData.img} />;
const wrapper = shallowWithContext(
<GridTile>{testChildren}</GridTile>
);
assert.strictEqual(wrapper.containsMatchingElement(testChildren), true,
'should contain the children');
});
});
describe('prop: className', () => {
it('should renders className', () => {
const wrapper = shallowWithContext(
<GridTile className="foo" />
);
assert.strictEqual(wrapper.hasClass('foo'), true,
'should contain the className');
});
});
describe('prop: title', () => {
it('should renders title', () => {
const wrapper = shallowWithContext(
<GridTile title={tileData.title} />
);
assert.strictEqual(wrapper.children('div').text(), tileData.title,
'should contain the title');
});
});
describe('prop: titleStyle', () => {
it('should overwrite styles', () => {
const titleStyle = {
fontSize: 20,
};
const wrapper = shallowWithContext(
<GridTile title="foo" titleStyle={titleStyle} />
);
assert.strictEqual(wrapper.find('div > div > div > div').props().style.fontSize,
titleStyle.fontSize, 'should overwrite title fontSize');
});
});
});
|
src/svg-icons/notification/vibration.js
|
verdan/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationVibration = (props) => (
<SvgIcon {...props}>
<path d="M0 15h2V9H0v6zm3 2h2V7H3v10zm19-8v6h2V9h-2zm-3 8h2V7h-2v10zM16.5 3h-9C6.67 3 6 3.67 6 4.5v15c0 .83.67 1.5 1.5 1.5h9c.83 0 1.5-.67 1.5-1.5v-15c0-.83-.67-1.5-1.5-1.5zM16 19H8V5h8v14z"/>
</SvgIcon>
);
NotificationVibration = pure(NotificationVibration);
NotificationVibration.displayName = 'NotificationVibration';
NotificationVibration.muiName = 'SvgIcon';
export default NotificationVibration;
|
src/components/feed/posts/link.js
|
alexcurtis/react-fbpage
|
'use strict';
import React from 'react';
class LinkPost extends React.Component {
constructor(props){
super(props);
}
render(){
return (
<div>
<a href={this.props.link}>
<img
src={this.props.full_picture}
style={this.props.style.image}
/>
</a>
</div>
);
}
}
LinkPost.propTypes = {
style: React.PropTypes.object,
link: React.PropTypes.string,
full_picture: React.PropTypes.string
};
LinkPost.type = 'link';
export default LinkPost;
|
packages/material-ui-icons/src/PhonePaused.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M17 3h-2v7h2V3zm3 12.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.59l2.2-2.21c.28-.26.36-.65.25-1C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM19 3v7h2V3h-2z" /></g>
, 'PhonePaused');
|
packages/jsbattle-webpage/src/containers/test/LeagueReplayScreen.spec.js
|
jamro/jsbattle
|
import 'babel-polyfill';
import React from 'react';
import {shallow} from 'enzyme';
import {LeagueReplayScreen} from '../LeagueReplayScreen.js';
import Loading from '../../components/Loading.js';
import DuelResultScreen from "../../components/DuelResultScreen.js";
import JsBattleBattlefield from "jsbattle-react";
const match = {
params: {
id: '123456abcdXYZ'
}
}
const aiDefList = [
{
name: 'brick',
team: 'alpha/brick',
code: "importScripts('lib/tank.js'); tank.init(function(settings, info) { }); tank.loop(function(state, control) { });",
initData: null,
useSandbox: true,
executionLimit: 100
},
{
name: 'moore',
team: 'beta/moore',
code: "importScripts('lib/tank.js'); tank.init(function(settings, info) { }); tank.loop(function(state, control) { });",
initData: null,
useSandbox: true,
executionLimit: 100
}
];
let logOrig;
let warnOrig;
beforeAll(() => {
logOrig = console.log;
warnOrig = console.warn;
console.log = () => {};
console.warn = () => {};
});
afterAll(() => {
console.log = logOrig;
console.warn = warnOrig;
});
test('show loading', () => {
const wrapper = shallow(<LeagueReplayScreen
match={match}
isLoading={true}
isAuthorized={true}
/>);
expect(wrapper.find(Loading)).toHaveLength(1);
});
test('show player in breadcrumb', () => {
const wrapper = shallow(<LeagueReplayScreen
match={match}
isLoading={false}
isAuthorized={true}
result={[
{name: 'alpha7638'},
{name: 'bravo9743'},
]}
/>);
expect(wrapper.find('.breadcrumb').text()).toMatch(/league/i)
expect(wrapper.find('.breadcrumb').text()).toMatch(/alpha7638/i)
expect(wrapper.find('.breadcrumb').text()).toMatch(/bravo9743/i)
});
test('play the battle (authorized)', () => {
const wrapper = shallow(<LeagueReplayScreen
match={match}
isLoading={false}
isAuthorized={true}
rngSeed={787223}
timeLimit={12340}
simQuality={0.65}
simSpeed={0.42}
result={[
{name: 'alpha7638'},
{name: 'bravo9743'},
]}
aiDefList={aiDefList}
/>);
expect(wrapper.find(JsBattleBattlefield)).toHaveLength(1);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('rngSeed', 787223);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('timeLimit', 12340);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('speed', 0.42);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('quality', 0.65);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('aiDefList');
expect(wrapper.find(JsBattleBattlefield).prop('aiDefList')).toHaveLength(2);
expect(wrapper.find(JsBattleBattlefield).prop('aiDefList')[0]).toHaveProperty('name', 'brick');
expect(wrapper.find(JsBattleBattlefield).prop('aiDefList')[1]).toHaveProperty('name', 'moore');
});
test('play the battle (unauthorized)', () => {
const wrapper = shallow(<LeagueReplayScreen
match={match}
isLoading={false}
isAuthorized={false}
rngSeed={787223}
timeLimit={12340}
simQuality={0.65}
simSpeed={0.42}
result={[
{name: 'alpha7638'},
{name: 'bravo9743'},
]}
aiDefList={aiDefList}
/>);
expect(wrapper.find(JsBattleBattlefield)).toHaveLength(1);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('rngSeed', 787223);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('timeLimit', 12340);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('speed', 0.42);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('quality', 0.65);
expect(wrapper.find(JsBattleBattlefield).props()).toHaveProperty('aiDefList');
expect(wrapper.find(JsBattleBattlefield).prop('aiDefList')).toHaveLength(2);
expect(wrapper.find(JsBattleBattlefield).prop('aiDefList')[0]).toHaveProperty('name', 'brick');
expect(wrapper.find(JsBattleBattlefield).prop('aiDefList')[1]).toHaveProperty('name', 'moore');
});
test('restart the battle', async () => {
const wrapper = shallow(<LeagueReplayScreen
match={match}
isLoading={false}
isAuthorized={true}
rngSeed={787223}
timeLimit={12340}
simQuality={0.65}
simSpeed={0.42}
result={[
{name: 'alpha7638'},
{name: 'bravo9743'},
]}
aiDefList={aiDefList}
/>);
expect(wrapper.find(JsBattleBattlefield)).toHaveLength(1);
wrapper.find(JsBattleBattlefield).props().onFinish({
teamWinner: {
name: 'alpha342',
score: 873,
members: [
{skin: 'desert'}
]
},
teamList: [
{
name: 'alpha342',
score: 873,
members: [
{skin: 'desert'}
]
},
{
name: 'bravo883',
score: 12,
members: [
{skin: 'ocean'}
]
}
]
});
expect(wrapper.find(JsBattleBattlefield)).toHaveLength(0);
expect(wrapper.find(DuelResultScreen).props()).toHaveProperty('winnerName', 'alpha342');
expect(wrapper.find(DuelResultScreen).props()).toHaveProperty('loserName', 'bravo883');
expect(wrapper.find(DuelResultScreen).props()).toHaveProperty('winnerSkin', 'desert');
expect(wrapper.find(DuelResultScreen).props()).toHaveProperty('loserSkin', 'ocean');
expect(wrapper.find(DuelResultScreen).props()).toHaveProperty('winnerScore', 873);
expect(wrapper.find(DuelResultScreen).props()).toHaveProperty('loserScore', 12);
});
test('display battle errors', async () => {
const showError = jest.fn()
const wrapper = shallow(<LeagueReplayScreen
match={match}
isLoading={false}
isAuthorized={true}
rngSeed={787223}
timeLimit={12340}
simQuality={0.65}
simSpeed={0.42}
result={[
{name: 'alpha7638'},
{name: 'bravo9743'},
]}
aiDefList={aiDefList}
showError={showError}
/>);
expect(wrapper.find(JsBattleBattlefield)).toHaveLength(1);
wrapper.find(JsBattleBattlefield).props().onError('Ooooops3245234')
expect(showError.mock.calls).toHaveLength(1);
expect(showError.mock.calls[0][0]).toBe('Ooooops3245234');
});
|
src/app/views/myFriendsRecipes.js
|
webcoding/reactui-starter
|
import _ from 'lodash';
import React from 'react';
import Reflux from 'reflux';
import meFriendsRecipesStore from 'stores/myFriendsRecipes';
import meActions from 'actions/me';
import RecipeListItem from 'components/recipeListItem';
import Spinner from 'components/spinner';
export default React.createClass( {
mixins: [
Reflux.connect( meFriendsRecipesStore, 'recipes' )
],
componentDidMount() {
meActions.getMyFriendsRecipes();
},
render() {
document.title = 'Soapee - My Friend\'s Recipes';
return (
<div id="my-friends-recipes">
<legend>My Friend's Recipes</legend>
{ this.renderLoading() }
{ this.renderRecipes() }
</div>
);
},
renderLoading() {
if ( !(this.state.recipes) ) {
return <Spinner />;
}
},
renderRecipes() {
let lengthRecipes = _.get(this.state.recipes, 'length', 0);
if ( lengthRecipes > 0 ) {
return _.map( this.state.recipes, this.renderRecipe );
} else if ( lengthRecipes === 0 ) {
return (
<div className="jumbotron">
No recipes found.
</div>
);
}
},
renderRecipe( recipe ) {
return (
<div key={ `recipe-${ recipe.id }` }>
<RecipeListItem
showUser={ true }
recipe={recipe}
/>
</div>
);
}
} );
|
src/components/Main.js
|
ryanism37/Gallery-By-React
|
require('normalize.css/normalize.css');
require('styles/App.scss');
import React from 'react';
import ReactDOM from 'react-dom';
//获取相册图片的相关数据
var imageData = require('../data/imageData.json');
//利用自执行函数,将图片名信息转换为图片url路径信息
imageData = (function getImageUrl(imageDataArr){
for(var i = 0;i < imageDataArr.length;i ++){
imageDataArr[i].imageUrl = require('../images/' + imageDataArr[i].filename);
}
return imageDataArr;
})(imageData);
/*
* 根据给定区间产生区间内的一个随机值
*/
function getRangeRandom(start,end){
return Math.floor(Math.random() * (end - start) + start);
}
/*
* 根据给定范围区间产生一个随机角度(范围:正负30deg)
*/
function getRotateRandom(){
return ((Math.random() < 0.5?'':'-') + Math.floor(Math.random() * 30));
}
//创建每一个图片板块的组件
class ImageBox extends React.Component{
constructor(props) {
super(props);
//在原本React.creatClass创建组件的方式中,handleClick在onClick触发时会自动将this绑定到组件实例上,
//而在ES6的class的写法中,Facebook取消了自动绑定,所以需要手动绑定this的上下文,避免出错
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
if(this.props.arrange.isCenter){
//当前点击图片是居中图片
this.props.inverse();
}else{
//当前点击图片不是居中图片
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render() {
var styleObj = {};
var pos = this.props.arrange.pos;
if(pos){
styleObj = pos;
}
//为不同浏览器厂商添加css属性前缀,给当前图片添加旋转样式
if(this.props.arrange.rotate){ //旋转非0时设置rotate内联样式,避免居中图片无法顺利完成翻转动画,类样式被内联样式覆盖
var pre = ['Moz','ms','Webkit',''];
pre.forEach(function(value){
styleObj[value + 'Transform'] = 'rotate(' + this.props.arrange.rotate + 'deg)';
}.bind(this));
}
//判断当前图片是否居中,是的话提高其z-index值
if(this.props.arrange.isCenter){
styleObj.zIndex = 11;
}
//判断当前居中图片是否翻转,从而控制样式变化
var figureClassName = 'img-box';
figureClassName += this.props.arrange.isInverse ? ' is-inverse' : '';
return (
<figure className={figureClassName} style={styleObj} onClick={this.handleClick}>
<img src={this.props.data.imageUrl} alt={this.props.data.title}/>
<figcaption>
<h2 className="img-title">{this.props.data.title}</h2>
<div className="img-back" onClick={this.handleClick}>
<p>{this.props.data.desc}</p>
</div>
</figcaption>
</figure>
);
}
}
//创建每一个控制导航的组件
class Controller extends React.Component{
constructor(props){
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(e){
if(this.props.arrange.isCenter){
//当前导航点是对应中心图片,那么翻转
this.props.inverse();
}else{
//当前导航点并非对应中心图片,那么执行居中
this.props.center();
}
e.stopPropagation();
e.preventDefault();
}
render(){
var spanClassName = 'nav';
if(this.props.arrange.isCenter){
spanClassName += ' is-center';
if(this.props.arrange.isInverse){
spanClassName += ' is-inverse';
}
}
return (
<span className={spanClassName} onClick={this.handleClick}></span>
);
}
}
//原始最顶层祖先组件
class GalleryByReactApp extends React.Component {
constructor(props){
super(props);
//声明常量
this.Constant = {
centerPos:{
left:0,
top:0
},
hPosRange:{ //图片块在水平方向的取值范围(舞台左右侧)
leftSecX:[0,0],
rightSecX:[0,0],
y:[0,0]
}, //图片块在垂直方向的取值范围(舞台中上方)
vPosRange:{
x:[0,0],
y:[0,0]
}
};
//初始化状态
this.state = {
imgArr:[
// {
// pos:{
// left:0,
// top:0
// },
// rotate:0, //旋转角度
// isInverse:false, //是否翻转,默认为否(默认正面)
// isCenter:false, //是否居中
// }
]
};
}
/*
* 翻转当前居中图片
* 返回的是一个闭包函数,用于将该闭包传递给子组件的属性,让子组件内部得以调用
*/
inverse(index){
return function(){
var imgArr = this.state.imgArr;
imgArr[index].isInverse = !imgArr[index].isInverse;
this.setState({
imgArr:imgArr
});
}.bind(this);
}
/*
* 居中当前所点击的索引对应图片
* 返回的是一个闭包函数,用于将该闭包传递给子组件的属性,让子组件内部得以调用
*/
center(index){
return function(){
this.reRange(index);
}.bind(this);
}
/*
* 重新布局所有图片
* @param 参数centerImgIndex为待居中的图片索引
*/
reRange(centerImgSpliceIndex){
var imgArr = this.state.imgArr,
constant = this.Constant,
centerPos = constant.centerPos,
hPosRange = constant.hPosRange,
vPosRange = constant.vPosRange,
leftSecX = hPosRange.leftSecX,
rightSecX = hPosRange.rightSecX,
sideSecY = hPosRange.y,
topSecX = vPosRange.x,
topSecY = vPosRange.y;
//布局正中的那张图片
var centerImgArr = imgArr.splice(centerImgSpliceIndex,1);
centerImgArr[0] = {
pos:centerPos,
rotate:0,
isCenter:true
};
//取出要布局在中上侧的图片的状态信息
var topSecImgArr = [],
topSecImgNum = Math.floor(Math.random() * 2), //上侧只分布0或1张图片
topSecImgSpliceIndex = Math.floor(Math.random() * topSecImgArr.length);
topSecImgArr = imgArr.splice(topSecImgSpliceIndex,topSecImgNum);
//布局中上侧的图片
topSecImgArr.forEach(function(value,index){
topSecImgArr[0] = {
pos:{
top:getRangeRandom(vPosRange.y[0],vPosRange.y[1]),
left:getRangeRandom(vPosRange.x[0],vPosRange.x[1])
},
rotate:getRotateRandom(),
isCenter:false
};
});
//布局左右两侧的图片
for(var i = 0,j = imgArr.length,k = j / 2;i < j;i ++){
var leftOrRightSecX = null;
if(i < k){
leftOrRightSecX = leftSecX;
}else{
leftOrRightSecX = rightSecX;
}
imgArr[i] = {
pos:{
top:getRangeRandom(sideSecY[0],sideSecY[1]),
left:getRangeRandom(leftOrRightSecX[0],leftOrRightSecX[1])
},
rotate:getRotateRandom(),
isCenter:false
};
}
//本次布局后,重新将中上侧和中心图片的数组添加回原始全部图片数组,方便下一次的随机布局
if(topSecImgArr && topSecImgArr[0]){
imgArr.splice(topSecImgSpliceIndex,0,topSecImgArr[0]);
}
imgArr.splice(centerImgSpliceIndex,0,centerImgArr[0]);
//更新状态值
this.setState({
imgArr:imgArr
});
}
//组件加载以后,为每张图片计算其位置的范围
componentDidMount(){
//首先获取舞台的大小
var stageDom = ReactDOM.findDOMNode(this.refs.stage),
stageW = stageDom.scrollWidth,
stageH = stageDom.scrollHeight,
halfStageW = Math.ceil(stageW/2),
halfStageH = Math.ceil(stageH/2);
//获取每一个imageBox的大小
var imageBoxDom = ReactDOM.findDOMNode(this.refs.imageBox0),
imageW = imageBoxDom.scrollWidth,
imageH = imageBoxDom.scrollWidth,
halfImageW = Math.ceil(imageW/2),
halfImageH = Math.ceil(imageH/2);
//计算中心图片块的位置
this.Constant.centerPos = {
left:halfStageW - halfImageW,
top:halfStageH - halfImageH
}
//计算水平方向图片块的位置(左右侧)
this.Constant.hPosRange.leftSecX[0] = -halfImageW;
this.Constant.hPosRange.leftSecX[1] = halfStageW - halfImageW*3;
this.Constant.hPosRange.rightSecX[0] = halfStageW + halfImageW;
this.Constant.hPosRange.rightSecX[1] = stageW - halfImageW;
this.Constant.hPosRange.y[0] = -halfImageH;
this.Constant.hPosRange.y[1] = stageH - halfImageH;
//计算水平方向图片块的位置(中上侧)
this.Constant.vPosRange.x[0] = halfStageW - imageW;
this.Constant.vPosRange.x[1] = halfStageW;
this.Constant.vPosRange.y[0] = - halfImageH;
this.Constant.vPosRange.y[1] = halfStageH - halfImageH*3;
//默认居中第一张图片
this.reRange(0);
}
render(){
var controllerNavs = [],
imgBoxs = [];
imageData.forEach(function(value,index){
if(!this.state.imgArr[index]){
this.state.imgArr[index] = {
pos:{
left:0,
top:0
},
rotate:0,
isInverse:false,
isCenter:false
};
}
imgBoxs.push(<ImageBox data={value} key={index} ref={'imageBox' + index} arrange={this.state.imgArr[index]} inverse={this.inverse(index)} center={this.center(index)}/>);
controllerNavs.push(<Controller key={index} arrange={this.state.imgArr[index]} inverse={this.inverse(index)} center={this.center(index)} />);
}.bind(this));
return (
<section className="stage" ref="stage">
<section className="img-sec">
{imgBoxs}
</section>
<nav className="controller-nav">
{controllerNavs}
</nav>
</section>
);
}
}
GalleryByReactApp.defaultProps = {};
export default GalleryByReactApp;
|
examples/js/column-filter/select-filter-with-sort.js
|
prajapati-parth/react-bootstrap-table
|
/* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
const qualityType = {
0: 'good',
1: 'bad',
2: 'unknown'
};
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,
quality: i % (Object.keys(qualityType).length)
});
}
}
addProducts(15);
function enumFormatter(cell, row, enumObject) {
return enumObject[cell];
}
export default class SelectFilterWithSort extends React.Component {
render() {
const filter = {
type: 'TextFilter'
};
return (
<BootstrapTable data={ products }>
<TableHeaderColumn dataSort dataField='id' filter={ filter } isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataSort dataField='quality' filterFormatted dataFormat={ enumFormatter }
formatExtraData={ qualityType } filter={ { type: 'SelectFilter', options: qualityType, defaultValue: 1 } }>Product Quality</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/esm/components/graphics/icons/stats-icon/index.js
|
KissKissBankBank/kitten
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title"];
import React from 'react';
import PropTypes from 'prop-types';
export var StatsIcon = function StatsIcon(_ref) {
var color = _ref.color,
title = _ref.title,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement("svg", _extends({
width: "18",
height: "18",
viewBox: "0 0 18 18",
xmlns: "http://www.w3.org/2000/svg"
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", {
d: "M18 16v2H0v-2h18zM3 8v6H0V8h3zm5-8v14H5V0h3zm5 5v9h-3V5h3zm5 5v4h-3v-4h3z",
fill: color
}));
};
StatsIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string
};
StatsIcon.defaultProps = {
color: '#222',
title: ''
};
|
src/components/conversation-admin/participant-header.js
|
colinmegill/polis-admin-console
|
/*
* Copyright 2012-present, Polis Technology Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights for non-commercial use can be found in the PATENTS file
* in the same directory.
*/
import React from 'react';
import Radium from 'radium';
// import _ from 'lodash';
import Flex from '../framework/flex';
// import { connect } from 'react-redux';
// import { FOO } from '../actions';
import Awesome from "react-fontawesome";
import VerifiedTwitterIcon from "../framework/verified-twitter-icon";
// const style = {
// };
// @connect(state => {
// return state.FOO;
// })
@Radium
class ParticipantHeader extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
static propTypes = {
/* react */
// dispatch: React.PropTypes.func,
params: React.PropTypes.object,
routes: React.PropTypes.array,
/* component api */
style: React.PropTypes.object,
fb_name: React.PropTypes.string,
// foo: React.PropTypes.string
}
static defaultProps = {
// foo: "bar"
}
getStyles() {
return {
image: {
borderRadius: 3,
},
name: {
marginLeft: 10,
marginBottom: 3,
fontWeight: 700,
},
};
}
getRealName() {
let name = "";
if (this.props.name) {
name = this.props.name;
}
if (this.props.fb_name) {
name = this.props.fb_name;
}
return name;
}
getImage() {
let image = "";
if (this.props.fb_user_id) {
image = (
<img src={this.props.fb_picture} style={this.getStyles().image}/>
)
} else if (this.props.profile_image_url_https) {
image = (
<img src={this.props.profile_image_url_https} style={this.getStyles().image}/>
)
} else if (this.props.twitter_profile_image_url_https) {
image = (
<img src={this.props.twitter_profile_image_url_https} style={this.getStyles().image}/>
)
}
return image;
}
facebookIcon() {
return (
<a target="_blank" href={this.props.fb_link}>
<Awesome
style={{
fontSize: 24,
color: "#3b5998",
}}
name={"facebook-square"} />
</a>
)
}
twitterIcon() {
return (
<a target="_blank" href={`https://twitter.com/${this.props.screen_name}`}>
<Awesome
style={{
fontSize: 24,
color: "#4099FF",
marginLeft: 10,
}}
name={"twitter-square"} />
</a>
)
}
followers() {
return (
<a
target="_blank" href={`https://twitter.com/${this.props.screen_name}`}
style={{
textDecoration: "none",
fontWeight: 300,
color: "black",
marginLeft: 10
}}>
<Awesome
style={{
fontSize: 16,
color: "#4099FF",
}}
name={"twitter"} />
<span style={{marginLeft: 5}}>
{this.props.followers_count}
</span>
</a>
)
}
render() {
const styles = this.getStyles();
return (
<Flex
styleOverrides={{width: "100%"}}
justifyContent="space-between"
alignItems="flex-start">
<Flex alignItems="flex-start">
{this.getImage()}
<Flex direction="column" alignItems="flex-start">
<span style={styles.name}>
{this.getRealName()}
</span>
<span>
{this.props.followers_count ? this.followers() : ""}
</span>
</Flex>
{this.props.is_verified ? <VerifiedTwitterIcon/> : ""}
</Flex>
<div>
{/*this.props.twitter_user_id ? this.props.followerCount : ""*/}
{this.props.fb_user_id ? this.facebookIcon() : ""}
{this.props.twitter_user_id ? this.twitterIcon() : ""}
</div>
</Flex>
);
}
}
export default ParticipantHeader;
/*
propTypes: {
// You can declare that a prop is a specific JS primitive. By default, these
// are all optional.
optionalArray: React.PropTypes.array,
optionalBool: React.PropTypes.bool,
optionalFunc: React.PropTypes.func,
optionalNumber: React.PropTypes.number,
optionalObject: React.PropTypes.object,
optionalString: React.PropTypes.string,
// Anything that can be rendered: numbers, strings, elements or an array
// (or fragment) containing these types.
optionalNode: React.PropTypes.node,
// A React element.
optionalElement: React.PropTypes.element,
// You can also declare that a prop is an instance of a class. This uses
// JS's instanceof operator.
optionalMessage: React.PropTypes.instanceOf(Message),
// You can ensure that your prop is limited to specific values by treating
// it as an enum.
optionalEnum: React.PropTypes.oneOf(['News', 'Photos']),
// An object that could be one of many types
optionalUnion: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
React.PropTypes.instanceOf(Message)
]),
// An array of a certain type
optionalArrayOf: React.PropTypes.arrayOf(React.PropTypes.number),
// An object with property values of a certain type
optionalObjectOf: React.PropTypes.objectOf(React.PropTypes.number),
// An object taking on a particular shape
optionalObjectWithShape: React.PropTypes.shape({
color: React.PropTypes.string,
fontSize: React.PropTypes.number
}),
// You can chain any of the above with `isRequired` to make sure a warning
// is shown if the prop isn't provided.
requiredFunc: React.PropTypes.func.isRequired,
// A value of any data type
requiredAny: React.PropTypes.any.isRequired,
*/
|
client/components/FlassCommon/Video/VideoControllerWrapper/VideoControllerWrapperComponent.js
|
Nexters/flass
|
import React from 'react';
import PropTypes from 'prop-types';
import './VideoControllerWrapperStyle.scss';
const { arrayOf, element } = PropTypes;
const propTypes = {
children: arrayOf(element).isRequired
};
const VideoControllerWrapperComponent = props => (
<div className="video-controller-wrapper">
{ props.children }
</div>
);
VideoControllerWrapperComponent.propTypes = propTypes;
export { VideoControllerWrapperComponent };
|
src/Pagination.js
|
adampickeral/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import PaginationButton from './PaginationButton';
import CustomPropTypes from './utils/CustomPropTypes';
import SafeAnchor from './SafeAnchor';
const Pagination = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
activePage: React.PropTypes.number,
items: React.PropTypes.number,
maxButtons: React.PropTypes.number,
ellipsis: React.PropTypes.bool,
first: React.PropTypes.bool,
last: React.PropTypes.bool,
prev: React.PropTypes.bool,
next: React.PropTypes.bool,
onSelect: React.PropTypes.func,
/**
* You can use a custom element for the buttons
*/
buttonComponentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
activePage: 1,
items: 1,
maxButtons: 0,
first: false,
last: false,
prev: false,
next: false,
ellipsis: true,
buttonComponentClass: SafeAnchor,
bsClass: 'pagination'
};
},
renderPageButtons() {
let pageButtons = [];
let startPage, endPage, hasHiddenPagesAfter;
let {
maxButtons,
activePage,
items,
onSelect,
ellipsis,
buttonComponentClass
} = this.props;
if(maxButtons){
let hiddenPagesBefore = activePage - parseInt(maxButtons / 2, 10);
startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1;
hasHiddenPagesAfter = startPage + maxButtons <= items;
if(!hasHiddenPagesAfter){
endPage = items;
startPage = items - maxButtons + 1;
if(startPage < 1){
startPage = 1;
}
} else {
endPage = startPage + maxButtons - 1;
}
} else {
startPage = 1;
endPage = items;
}
for(let pagenumber = startPage; pagenumber <= endPage; pagenumber++){
pageButtons.push(
<PaginationButton
key={pagenumber}
eventKey={pagenumber}
active={pagenumber === activePage}
onSelect={onSelect}
buttonComponentClass={buttonComponentClass}>
{pagenumber}
</PaginationButton>
);
}
if(maxButtons && hasHiddenPagesAfter && ellipsis){
pageButtons.push(
<PaginationButton
key='ellipsis'
disabled
buttonComponentClass={buttonComponentClass}>
<span aria-label='More'>...</span>
</PaginationButton>
);
}
return pageButtons;
},
renderPrev() {
if(!this.props.prev){
return null;
}
return (
<PaginationButton
key='prev'
eventKey={this.props.activePage - 1}
disabled={this.props.activePage === 1}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='Previous'>‹</span>
</PaginationButton>
);
},
renderNext() {
if(!this.props.next){
return null;
}
return (
<PaginationButton
key='next'
eventKey={this.props.activePage + 1}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='Next'>›</span>
</PaginationButton>
);
},
renderFirst() {
if(!this.props.first){
return null;
}
return (
<PaginationButton
key='first'
eventKey={1}
disabled={this.props.activePage === 1 }
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='First'>«</span>
</PaginationButton>
);
},
renderLast() {
if(!this.props.last){
return null;
}
return (
<PaginationButton
key='last'
eventKey={this.props.items}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label='Last'>»</span>
</PaginationButton>
);
},
render() {
return (
<ul
{...this.props}
className={classNames(this.props.className, this.getBsClassSet())}>
{this.renderFirst()}
{this.renderPrev()}
{this.renderPageButtons()}
{this.renderNext()}
{this.renderLast()}
</ul>
);
}
});
export default Pagination;
|
archimate-frontend/src/main/javascript/components/view/nodes/model_m/outcome.js
|
zhuj/mentha-web-archimate
|
import React from 'react'
import { BaseMotivationWidget } from './_base'
export const TYPE='outcome';
export class OutcomeWidget extends BaseMotivationWidget {
getClassName(node) { return 'a-node model_m outcome'; }
}
|
src/components/Modal.js
|
Minishlink/DailyScrum
|
// @flow
import React, { Component } from 'react';
import { StyleSheet, View, Modal as RCTModal, TouchableWithoutFeedback } from 'react-native';
export default class Modal extends Component<Props> {
// FUTURE remove shouldComponentUpdate if children can change
shouldComponentUpdate(nextProps: Props) {
return nextProps.visible !== this.props.visible;
}
render() {
const { onRequestClose, visible, children, backgroundStyle, ...rest } = this.props;
return (
<RCTModal animationType="fade" transparent visible={visible} onRequestClose={onRequestClose} {...rest}>
<TouchableWithoutFeedback onPress={onRequestClose}>
<View style={[styles.background, backgroundStyle]} />
</TouchableWithoutFeedback>
{children}
</RCTModal>
);
}
}
type Props = {
onRequestClose: Function,
visible: boolean,
children?: any,
style: any,
backgroundStyle: any,
};
const styles = StyleSheet.create({
background: {
flex: 1,
backgroundColor: 'black',
opacity: 0.8,
},
});
|
web/src/components/Footer.js
|
MauriceMahan/FocusOverlay
|
import React from 'react';
import { Link } from 'gatsby';
const Footer = props => (
<footer id="footer">
<section>
<h2>Aliquam sed mauris</h2>
<p>
Sed lorem ipsum dolor sit amet et nullam consequat feugiat consequat
magna adipiscing tempus etiam dolore veroeros. eget dapibus mauris. Cras
aliquet, nisl ut viverra sollicitudin, ligula erat egestas velit, vitae
tincidunt odio.
</p>
<ul className="actions">
<li>
<Link to="/generic" className="button">
Learn More
</Link>
</li>
</ul>
</section>
<section>
<h2>Etiam feugiat</h2>
<dl className="alt">
<dt>Address</dt>
<dd>1234 Somewhere Road • Nashville, TN 00000 • USA</dd>
<dt>Phone</dt>
<dd>(000) 000-0000 x 0000</dd>
<dt>Email</dt>
<dd>
<a href="#">information@untitled.tld</a>
</dd>
</dl>
<ul className="icons">
<li>
<a href="#" className="icon fa-twitter alt">
<span className="label">Twitter</span>
</a>
</li>
<li>
<a href="#" className="icon fa-facebook alt">
<span className="label">Facebook</span>
</a>
</li>
<li>
<a href="#" className="icon fa-instagram alt">
<span className="label">Instagram</span>
</a>
</li>
<li>
<a href="#" className="icon fa-github alt">
<span className="label">GitHub</span>
</a>
</li>
<li>
<a href="#" className="icon fa-dribbble alt">
<span className="label">Dribbble</span>
</a>
</li>
</ul>
</section>
<p className="copyright">
© Untitled. Design: <a href="https://html5up.net">HTML5 UP</a>.
</p>
</footer>
);
export default Footer;
|
src/pages/Home.js
|
mtomcal/reactjs-hooligans-tv
|
import React, { Component } from 'react';
import { Jumbotron, Button } from 'react-bootstrap';
import Player from '../player';
import { Containers } from '../data';
import { Card } from '../cards';
import {api_url} from '../config.js';
var Home = React.createClass({
propTypes: {
queryData: React.PropTypes.object.isRequired
},
render() {
var style = {};
const videos = this.props.queryData.data.map(function (res, index) {
return (<div className="col-lg-4">
<Player
key={index}
source={res.snippet.resourceId.videoId}
title={res.snippet.title}
autoplay={true}
imageURL={res.snippet.thumbnails.high.url}
/>
</div>);
});
const offense = videos.filter((item, index) => {
return index < 6;
});
const defense = videos.filter((item, index) => {
return index >= 6 && index < 12;
});
return (
<div>
<div className="container-fluid" style={style}>
<div className="row">
<div className="col-lg-12">
<Card title="Home" />
</div>
</div>
<div className="row">
<div className="col-lg-6">
<Card title="Offense">
{offense}
</Card>
</div>
<div className="col-lg-6">
<Card title="Defense">
{defense}
</Card>
</div>
</div>
<div className="row">
<div className="col-lg-6">
<Card title="Offense">
{offense}
</Card>
</div>
<div className="col-lg-6">
<Card title="Defense">
{defense}
</Card>
</div>
</div>
</div>
</div>
);
}
});
export default Containers.query.createContainer(Home, {
method: 'get',
route: api_url + '/videos',
})
|
src/routes/login/index.js
|
cineindustria/site
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Login from './Login';
const title = 'Log In';
export default {
path: '/login',
action() {
return {
title,
component: <Layout><Login title={title} /></Layout>,
};
},
};
|
docs/src/app/components/pages/components/Avatar/ExampleSimple.js
|
igorbt/material-ui
|
import React from 'react';
import Avatar from 'material-ui/Avatar';
import FileFolder from 'material-ui/svg-icons/file/folder';
import FontIcon from 'material-ui/FontIcon';
import List from 'material-ui/List/List';
import ListItem from 'material-ui/List/ListItem';
import {
blue300,
indigo900,
orange200,
deepOrange300,
pink400,
purple500,
} from 'material-ui/styles/colors';
const style = {margin: 5};
/**
* Examples of `Avatar` using an image, [Font Icon](/#/components/font-icon), [SVG Icon](/#/components/svg-icon)
* and "Letter" (string), with and without custom colors at the default size (`40dp`) and an alternate size (`30dp`).
*/
const AvatarExampleSimple = () => (
<List>
<ListItem
disabled={true}
leftAvatar={
<Avatar src="images/uxceo-128.jpg" />
}
>
Image Avatar
</ListItem>
<ListItem
disabled={true}
leftAvatar={
<Avatar
src="images/uxceo-128.jpg"
size={30}
style={style}
/>
}
>
Image Avatar with custom size
</ListItem>
<ListItem
disabled={true}
leftAvatar={
<Avatar icon={<FontIcon className="muidocs-icon-communication-voicemail" />} />
}
>
FontIcon Avatar
</ListItem>
<ListItem
disabled={true}
leftAvatar={
<Avatar
icon={<FontIcon className="muidocs-icon-communication-voicemail" />}
color={blue300}
backgroundColor={indigo900}
size={30}
style={style}
/>
}
>
FontIcon Avatar with custom colors and size
</ListItem>
<ListItem
disabled={true}
leftAvatar={
<Avatar icon={<FileFolder />} />
}
>
SvgIcon Avatar
</ListItem>
<ListItem
disabled={true}
leftAvatar={
<Avatar
icon={<FileFolder />}
color={orange200}
backgroundColor={pink400}
size={30}
style={style}
/>
}
>
SvgIcon Avatar with custom colors and size
</ListItem>
<ListItem
disabled={true}
leftAvatar={<Avatar>A</Avatar>}
>
Letter Avatar
</ListItem>
<ListItem
disabled={true}
leftAvatar={
<Avatar
color={deepOrange300}
backgroundColor={purple500}
size={30}
style={style}
>
A
</Avatar>
}
>
Letter Avatar with custom colors and size
</ListItem>
</List>
);
export default AvatarExampleSimple;
|
examples/js/column/column-title-table.js
|
echaouchna/react-bootstrap-tab
|
/* 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);
export default class ColumnAlignTable extends React.Component {
render() {
return (
<BootstrapTable data={ products }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' headerTitle={ false } columnTitle={ true }>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price' columnTitle={ true }>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/routes/index.js
|
hirako2000/react-hackathon-board
|
import React from 'react';
import { Route } from 'react-router';
// NOTE: here we're making use of the `resolve.root` configuration
// option in webpack, which allows us to specify import paths as if
// they were from the root of the ~/src directory. This makes it
// very easy to navigate to files regardless of how deeply nested
// your current file is.
import CoreLayout from 'layouts/CoreLayout/CoreLayout';
import LoginView from 'views/LoginView/LoginView';
import SignupView from 'views/LoginView/SignupView';
import ProfileView from 'views/ProfileView/ProfileView';
import HackathonsView from 'views/HackathonsView/HackathonsView';
import HackathonView from 'views/HackathonsView/HackathonView';
import EditHackathonView from 'views/HackathonsView/EditHackathonView';
import HacksView from 'views/HacksView/HacksView';
import MyHacksView from 'views/HacksView/MyHacksView';
import UserHacksView from 'views/HacksView/UserHacksView';
import NominatedView from 'views/HacksView/NominatedView';
import HackView from 'views/HacksView/HackView';
import EditHackView from 'views/HacksView/EditHackView';
import UsersView from 'views/UsersView/UsersView';
import UserView from 'views/UsersView/UserView';
import RulesView from 'views/HackathonsView/RulesView';
import PrizesView from 'views/HackathonsView/PrizesView';
import BeautifierView from 'views/BeautifierView/BeautifierView';
export default (store) => (
<Route component={CoreLayout}>
<Route name='login' path='/login' component={LoginView} />
<Route name='signup' path='/signup' component={SignupView} />
<Route name='profile' path='/profile' component={ProfileView} />
<Route name='home' path='/' component={HacksView} />
<Route name='hackathons' path='/hackathons' component={HackathonsView} />
<Route name='editHackathon' path='/hackathons/edit/:id' component={EditHackathonView} />
<Route name='hackathon' path='/hackathons/:id' component={HackathonView} />
<Route name='createHackathon' path='/hackathons/create/new/' component={EditHackathonView} />
<Route name='hacks' path='/hacks' component={HacksView} />
<Route name='myHacks' path='/hacks/my' component={MyHacksView} />
<Route name='userHacks' path='/hacks/user/:id' component={UserHacksView} />
<Route name='judging' path='/judging' component={NominatedView} />
<Route name='hack' path="/hacks">
<Route path=":id" component={HackView}/>
</Route>
<Route name='editHack' path='/hacks/edit/:id' component={EditHackView} />
<Route name='createHack' path='/hacks/create/new/' component={EditHackView} />
<Route name='people' path='/people' component={UsersView} />
<Route name='otherUser' path='/people/:id' component={UserView} />
<Route name='rules' path='/rules' component={RulesView} />
<Route name='prizes' path='/prizes' component={PrizesView} />
<Route name='beautifier' path='/beautifier' component={BeautifierView} />
</Route>
);
|
test/render/Sidebar.spec.js
|
caljrimmer/financial-redux-app
|
import React from 'react';
import addons from 'react/addons';
import expect from 'expect';
import Sidebar from '../../src/common/components/layout/Sidebar';
const TestUtils = React.addons.TestUtils;
describe('Sidebar Rending', function(){
const user = {
name : 'John Smith',
dept : 'Web Team',
lastLogin : new Date(),
email : 'john@smith.com',
id : 'abcde1234'
};
const version = '0.0.1';
before('render and locate element', function() {
const renderedComponent = TestUtils.renderIntoDocument(
<Sidebar user={user} version={version} />
);
const username = TestUtils.findRenderedDOMComponentWithClass(
renderedComponent,
'user-name'
);
const versionNumber = TestUtils.findRenderedDOMComponentWithClass(
renderedComponent,
'version'
);
this.linkArray = TestUtils.scryRenderedDOMComponentsWithClass(
renderedComponent,
'sidebar-nav-item'
);
this.firstLink = this.linkArray[0].getDOMNode();
this.username = username.getDOMNode();
this.versionNumber = versionNumber.getDOMNode();
});
it('user name should be "' + user.name+ '"', function() {
expect(this.username.textContent).toBe(user.name);
});
it('version should not be ' + version , function() {
expect(this.versionNumber.textContent).toBe('Currently version ' + version);
});
it('There should be 5 Navigation Links', function() {
expect(this.linkArray.length - 1).toBe(5);
});
it('First link should be "Home [static]"', function() {
expect(this.firstLink.textContent).toBe('Home [static]');
});
});
|
docs/src/pages/style/TypographyTheme.js
|
AndriusBil/material-ui
|
// @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
const styles = theme => ({
root: theme.typography.button,
});
function TypograpghyTheme(props) {
return <div className={props.classes.root}>{'This div looks like a button.'}</div>;
}
TypograpghyTheme.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(TypograpghyTheme);
|
src/react/jsx/样式.js
|
huangming1994/react-tutorial
|
import React from 'react'
import ReactDOM from 'react-dom'
const h1Style = { color: red }
ReactDOM.render(
<h1 style={h1Style}>Hello World</h1>,
document.getElementById('root')
)
|
src/lib/components/Example.js
|
thepixelninja/react-component-test
|
import React from 'react';
import './Example.scss';
const Example = () => (
<div className="Example">
<h1 className="Example-text">Create React Libraries</h1>
</div>
);
export default Example;
|
tests/layouts/PageLayout.spec.js
|
crssn/funfunapp
|
import React from 'react'
import PageLayout from 'layouts/PageLayout/PageLayout'
import { shallow } from 'enzyme'
describe('(Layout) PageLayout', () => {
it('renders as a <div>', () => {
shallow(<PageLayout />).should.have.tagName('div')
})
it('renders a project title', () => {
shallow(<PageLayout />).find('h1').should.have.text('React Redux Starter Kit')
})
it('renders its children inside of the viewport', () => {
const Child = () => <h2>child</h2>
shallow(
<PageLayout>
<Child />
</PageLayout>
)
.find('.page-layout__viewport')
.should.contain(<Child />)
})
})
|
packages/react-scripts/fixtures/kitchensink/src/features/webpack/CssInclusion.js
|
IamJoseph/create-react-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import './assets/style.css';
export default () => <p id="feature-css-inclusion">We love useless text.</p>;
|
src/core/requireAuth.js
|
yanivefraim/mobile-device-manager
|
import React from 'react';
import auth from './auth';
var requireAuth = (Component) => {
return class Authenticated extends React.Component {
static willTransitionTo(transition) {debugger;
if (!auth.loggedIn()) {
transition.redirect('/login', {}, {'nextPath' : transition.path});
}
}
render () {
return <Component {...this.props}/>
}
}
};
export default requireAuth;
|
docs/app/Examples/modules/Popup/Usage/PopupExampleControlled.js
|
vageeshb/Semantic-UI-React
|
import React from 'react'
import { Button, Grid, Header, Popup } from 'semantic-ui-react'
const timeoutLength = 2500
class PopupExampleControlled extends React.Component {
state = { isOpen: false }
handleOpen = () => {
this.setState({ isOpen: true })
this.timeout = setTimeout(() => {
this.setState({ isOpen: false })
}, timeoutLength)
}
handleClose = () => {
this.setState({ isOpen: false })
clearTimeout(this.timeout)
}
render() {
return (
<Grid>
<Grid.Column width={8}>
<Popup
trigger={<Button content='Open controlled popup' />}
content={`This message will self-destruct in ${timeoutLength / 1000} seconds!`}
on='click'
open={this.state.isOpen}
onClose={this.handleClose}
onOpen={this.handleOpen}
positioning='top right'
/>
</Grid.Column>
<Grid.Column width={8}>
<Header>State</Header>
<pre>{JSON.stringify(this.state, null, 2)}</pre>
</Grid.Column>
</Grid>
)
}
}
export default PopupExampleControlled
|
src/js/ui/components/welcome/footerBar.js
|
hiddentao/heartnotes
|
import React from 'react';
import Icon from '../icon';
import ExternalLink from '../externalLink';
import Loading from '../loading';
import { connectRedux, routing } from '../../helpers/decorators';
import Footer from '../footer';
class Component extends React.Component {
constructor() {
super();
}
render() {
let { app } = this.props.data;
let newVersionMsg = null;
if (app.newVersionAvailable) {
newVersionMsg = (
<ExternalLink href={app.downloadLink}>new version available!</ExternalLink>
);
} else if (app.checkingForUpdate.inProgress) {
newVersionMsg = (
<Loading />
);
}
return (
<Footer className="welcome-footer-bar">
<div className="meta">
<span className="version">
<span className="new-version">{newVersionMsg}</span>
v{this.props.data.app.version}
</span>
<span className="home">
<ExternalLink href="https://heartnotes.me"><Icon name="home" /></ExternalLink>
</span>
</div>
</Footer>
);
}
}
module.exports = connectRedux()(routing()(Component));
|
modules/__tests__/Redirect-test.js
|
nvartolomei/react-router
|
import expect from 'expect'
import React from 'react'
import { render, unmountComponentAtNode } from 'react-dom'
import createHistory from '../createMemoryHistory'
import Redirect from '../Redirect'
import Router from '../Router'
import Route from '../Route'
describe('A <Redirect>', function () {
let node
beforeEach(function () {
node = document.createElement('div')
})
afterEach(function () {
unmountComponentAtNode(node)
})
it('works', function (done) {
render((
<Router history={createHistory('/notes/5')}>
<Route path="/messages/:id" />
<Redirect from="/notes/:id" to="/messages/:id" />
</Router>
), node, function () {
expect(this.state.location.pathname).toEqual('/messages/5')
done()
})
})
it('works with relative paths', function (done) {
render((
<Router history={createHistory('/nested/route1')}>
<Route path="nested">
<Route path="route2" />
<Redirect from="route1" to="route2" />
</Route>
</Router>
), node, function () {
expect(this.state.location.pathname).toEqual('/nested/route2')
done()
})
})
it('works with relative paths with param', function (done) {
render((
<Router history={createHistory('/nested/1/route1')}>
<Route path="nested/:id">
<Route path="route2" />
<Redirect from="route1" to="route2" />
</Route>
</Router>
), node, function () {
expect(this.state.location.pathname).toEqual('/nested/1/route2')
done()
})
})
})
|
src/components/mobile/AdOne/AdOne.js
|
pppp22591558/ChinaPromotion
|
import React, { Component } from 'react';
import reactDOM from 'react-dom';
import styles from './AdOne.css';
import withStyles from '../../../decorators/withStyles';
import Modal from '../Modal';
import { get as getContent } from '../../../constants/ABTest';
@withStyles(styles)
class AdOne extends Component{
constructor(){
super();
this.handleClick = this.handleClick.bind(this);
this.addScale = this.addScale.bind(this);
this.removeScale = this.removeScale.bind(this);
this.showModal = this.showModal.bind(this);
this.hideModal = this.hideModal.bind(this);
}
static propTypes = {
next: React.PropTypes.func.isRequired
}
state = {
isModalActive: false,
modalType: '',
os: null
}
componentWillUpdate(nextProps, nextState) {
if (nextProps.active) {
TweenMax.fromTo(this.header, 0.4, {top: -40, color: '#69D6D8'}, {top: 0, color: 'white'});
this.tl.to(this.icon1, 0.2, {WebkitTransform: 'translateY(0%)'})
.to(this.icon2, 0.2, {WebkitTransform: 'translateY(0%)'});
} else {
TweenMax.fromTo(this.header, 0.4, {top: -40, color: '#69D6D8'}, {top: 0, color: 'white', reversed: true});
this.tl.to(this.icon1, 0, {WebkitTransform: 'translateY(300%)'})
.to(this.icon2, 0, {WebkitTransform: 'translateY(300%)'});
}
}
componentDidMount() {
const land = reactDOM.findDOMNode(this.refs.land);
const mark = reactDOM.findDOMNode(this.refs.mark);
this.header = reactDOM.findDOMNode(this.refs.header);
this.icon1 = reactDOM.findDOMNode(this.refs.icon1);
this.icon2 = reactDOM.findDOMNode(this.refs.icon2);
TweenMax.to(mark, 0.5, {top: '34%' ,yoyo: true, repeat: -1});
this.tl = new TimelineMax();
}
handleClick(){
this.props.next();
}
addScale(e){
TweenMax.to(e.target, 0, {WebkitTransform: 'scale(1.2)'});
}
removeScale(e){
TweenMax.to(e.target, 0, {WebkitTransform: 'scale(1)'});
}
showModal(type){
let downloadType = type;
// this.setState({isModalActive: true, modalType: downloadType});
//send the download data to GA
ga('send', {
hitType: 'event',
eventCategory: 'Download',
eventAction: 'click the icon',
eventLabel: downloadType
});
}
hideModal(){
this.setState({isModalActive: false});
}
getAndroidDownloadLink() {
const { version } = this.props
return version == 'us'? 'https://play.google.com/store/apps/details?id=com.boniotw.global.pagamo' : '/download'
}
render(){
let styles = {
header: {
position: 'relative',
color: '#69D6D8',
top: -40
},
land: {
width: '100%'
},
mark: {
width: '15%',
zIndex: 1,
position: 'absolute',
display: 'block',
top: '40%',
left: '45%'
}
};
const { version } = this.props
const content = getContent(version).scene1
const { header_1, header_2, subtitle, long_press, other_browsers, switch_version } = content
let img_type;
if (version === 'us'){
img_type = '_us';
} else if (version === 'tw'){
img_type = '_tw'
} else {
img_type = '';
}
const { isModalActive } = this.state
const { os, ua, isWx } = this.props
return(
<div className="AdOne">
<div className="AdOne-header" ref="header" style={styles.header}>
<img className="palm palm-left" alt={header_1} src={require('./palm-left.png')}></img>
<img className="palm palm-right" src={require('./palm-right.png')} alt={header_2}></img>
<h2 className={`${version}`}>{header_1}<br/>{header_2}<br/></h2>
<h3 dangerouslySetInnerHTML={{ __html: subtitle }} />
</div>
<div className="view">
<img ref="land" onClick={this.handleClick} style={styles.land} src={require('./land-08.png')} alt={subtitle}></img>
<img ref="mark" onClick={this.handleClick} style={styles.mark} src={require('./mark-08.png')}></img>
<div className={`download ${version}`}>
<a href={`/ios-download?version=${version}`}
className={`ios ${(os != 'AndroidOS') && 'active'}`}
data-download="ios">
<img ref="icon1"
src={isWx?
require('./ios_qr_code.png') :
require('./apple' + img_type + '.png')}
data-download="ios"/>
{ isWx &&
<span className="long-press">{long_press}</span>
}
</a>
<a href={this.getAndroidDownloadLink()}
className={`android ${(os != 'iOS' || version == 'us') && 'active'}`}
data-download="android">
<img ref="icon2"
src={require('./android' + img_type + '.png')}
data-download="android"/>
{ isWx &&
<span className="other-browsers">{other_browsers}</span>
}
</a>
<a className="switch-version" href={`/switch?to=${version === 'us'? '/tw' : '/us'}`}>
{switch_version}
</a>
</div>
</div>
<Modal active = {isModalActive} hide = {this.hideModal} version = {this.props.version}/>
</div>
)
}
}
// <img ref="icon3" onTouchStart={this.addScale} onTouchEnd={this.removeScale} onClick={this.showModal} src={require('./official' + img_type +'.png')} data-download="official"></img>
export default AdOne;
|
modules/Header.js
|
marquesarthur/learning_react
|
import React from 'react';
import { Router, Route, browserHistory, IndexRoute } from 'react-router';
import { Link } from 'react-router'
import { Nav, NavItem, NavDropdown, Glyphicon, DropdownButton, MenuItem, ProgressBar, Grid, Row, Col } from 'react-bootstrap';
import Navbar, {Brand} from 'react-bootstrap/lib/Navbar';
var LogoImg = require('../imgs/ubc-logo-final.png');
const logoStyle = {
margin: "17 auto",
marginLeft: "20px",
float: "left"
}
const navStyle = {
backgroundColor: "#002145",
color: "#ffffff"
}
const menuStyle = {
paddingTop: "15px",
paddingRight: "25px"
}
const gearIcon = <Glyphicon glyph="th-list" />;
const html = (
<Nav className="navbar navbar-fixed-top" style={navStyle}>
<Link to="/"><img style={logoStyle} src={LogoImg}/></Link>
<div>
<h1 className="text-center">
CPSC 410 - Software Engineering
<div className="pull-right" style={menuStyle}>
<DropdownButton bsStyle="default" bsSize="medium" title={gearIcon} id="menu" pullRight>
<MenuItem eventKey="1"><Link to="/">App Store</Link></MenuItem>
<MenuItem eventKey="2"><Link to="/students">Students</Link></MenuItem>
<MenuItem eventKey="3"><Link to="/teams">Teams</Link></MenuItem>
</DropdownButton>
</div>
</h1>
</div>
</Nav>
);
export default React.createClass({
render() {
return html;
}
});
|
examples/huge-apps/routes/Grades/components/Grades.js
|
chrisirhc/react-router
|
import React from 'react';
class Grades extends React.Component {
render () {
return (
<div>
<h2>Grades</h2>
</div>
);
}
}
export default Grades;
|
src/components/Feedback/Feedback.js
|
egut/react-docker-demo
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Feedback.css';
class Feedback extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<a
className={s.link}
href="https://gitter.im/egut/react-docker-demo"
>Ask a question</a>
<span className={s.spacer}>|</span>
<a
className={s.link}
href="https://github.com/egut/react-docker-demo/issues/new"
>Report an issue</a>
</div>
</div>
);
}
}
export default withStyles(s)(Feedback);
|
src/StyleButton.js
|
isuttell/react-texteditor
|
/**
* @file Text Editor StyleButton
* @author Isaac Suttell <isaac@isaacsuttell.com>
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
// CSS Module
import css from './StyleButton.css';
export default class StyleButton extends Component {
/**
* Make Render
* @return {React}
*/
render() {
return (
<div
className={classNames(this.props.className, 'text-editor---btn', css.btn, this.props.iconClass, {
[css.icon] : typeof this.props.iconClass === 'string',
'text-editor--btn-active': this.props.active,
[css.active]: this.props.active
})}
onMouseDown={this.props.onMouseDown}
title={this.props.title}
>
{typeof this.props.iconClass !== 'string' ?
this.props.label
: null}
</div>
);
}
}
/**
* Type checking
* @type {Object}
*/
StyleButton.propTypes = {
iconClass: PropTypes.string,
style: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
active: PropTypes.bool.isRequired,
className: PropTypes.string,
title: PropTypes.string
};
|
src/js/views/form.js
|
unidevel/touchstonejs-starter
|
import Container from 'react-container';
import dialogs from 'cordova-dialogs';
import React from 'react';
import Tappable from 'react-tappable';
import { UI } from 'touchstonejs';
const scrollable = Container.initScrollable();
// html5 input types for testing
// omitted: button, checkbox, radio, image, hidden, reset, submit
const HTML5_INPUT_TYPES = ['color', 'date', 'datetime', 'datetime-local', 'email', 'file', 'month', 'number', 'password', 'range', 'search', 'tel', 'text', 'time', 'url', 'week'];
const FLAVOURS = [
{ label: 'Vanilla', value: 'vanilla' },
{ label: 'Chocolate', value: 'chocolate' },
{ label: 'Caramel', value: 'caramel' },
{ label: 'Strawberry', value: 'strawberry' }
];
module.exports = React.createClass({
statics: {
navigationBar: 'main',
getNavigation () {
return {
title: 'Forms'
}
}
},
getInitialState () {
return {
flavourLabelSelect: 'chocolate',
flavourRadioList: 'chocolate',
switchValue: true
}
},
handleRadioListChange (key, newValue) {
console.log('handleFlavourChange:', key, newValue);
let newState = {};
newState[key] = newValue;
this.setState(newState);
},
handleLabelSelectChange (key, event) {
console.log('handleFlavourChange:', key, event.target.value);
let newState = {};
newState[key] = event.target.value;
this.setState(newState);
},
handleSwitch (key, event) {
let newState = {};
newState[key] = !this.state[key];
this.setState(newState);
},
alert (message) {
dialogs.alert(message, function() {}, null)
},
// used for testing
renderInputTypes () {
return HTML5_INPUT_TYPES.map(type => {
return <UI.LabelInput key={type} type={type} label={type} placeholder={type} />;
});
},
showDatePicker () {
this.setState({datePicker: true});
},
handleDatePickerChange (d) {
this.setState({datePicker: false, date: d});
},
formatDate (date) {
if (date) {
return date.getFullYear() + '-' + (date.getMonth() + 1) + '-' + date.getDate();
}
},
render () {
return (
<Container fill>
<Container scrollable={scrollable}>
{/*<UI.Group>
<UI.GroupHeader>Input Type Experiment</UI.GroupHeader>
<UI.GroupBody>
{this.renderInputTypes()}
</UI.GroupBody>
</UI.Group>*/}
<UI.Group>
<UI.GroupHeader>Checkbox</UI.GroupHeader>
<UI.GroupBody>
<UI.Item>
<UI.ItemInner>
<UI.FieldLabel>Switch</UI.FieldLabel>
<UI.Switch onTap={this.handleSwitch.bind(this, 'switchValue')} on={this.state.switchValue} />
</UI.ItemInner>
</UI.Item>
<UI.Item>
<UI.ItemInner>
<UI.FieldLabel>Disabled</UI.FieldLabel>
<UI.Switch disabled />
</UI.ItemInner>
</UI.Item>
</UI.GroupBody>
</UI.Group>
<UI.Group>
<UI.GroupHeader>Radio</UI.GroupHeader>
<UI.GroupBody>
<UI.RadioList value={this.state.flavourRadioList} onChange={this.handleRadioListChange.bind(this, 'flavourRadioList')} options={FLAVOURS} />
</UI.GroupBody>
</UI.Group>
<UI.Group>
<UI.GroupHeader>Inputs</UI.GroupHeader>
<UI.GroupBody>
<UI.Input placeholder="Default" />
<UI.Input defaultValue="With Value" placeholder="Placeholder" />
<UI.Textarea defaultValue="Longtext is good for bios etc." placeholder="Longtext" />
</UI.GroupBody>
</UI.Group>
<UI.Group>
<UI.GroupHeader>Labelled Inputs</UI.GroupHeader>
<UI.GroupBody>
<UI.LabelInput type="email" label="Email" placeholder="your.name@example.com" />
<Tappable component="label" onTap={this.showDatePicker}>
<UI.LabelValue label="Date" value={this.formatDate(this.state.date)} placeholder="Select a date" />
</Tappable>
<UI.LabelInput type="url" label="URL" placeholder="http://www.yourwebsite.com" />
<UI.LabelInput noedit label="No Edit" defaultValue="Un-editable, scrollable, selectable content" />
<UI.LabelSelect label="Flavour" value={this.state.flavourLabelSelect} onChange={this.handleLabelSelectChange.bind(this, 'flavourLabelSelect')} options={FLAVOURS} />
</UI.GroupBody>
</UI.Group>
<UI.Button type="primary" onTap={this.alert.bind(this, 'You clicked the Primary Button')}>
Primary Button
</UI.Button>
<UI.Button onTap={this.alert.bind(this, 'You clicked the Default Button')}>
Default Button
</UI.Button>
<UI.Button type="danger" onTap={this.alert.bind(this, 'You clicked the Danger Button')}>
Danger Button
</UI.Button>
<UI.Button type="danger" onTap={this.alert.bind(this, 'You clicked the Danger Button')} disabled>
Disabled Button
</UI.Button>
</Container>
<UI.DatePickerPopup visible={this.state.datePicker} date={this.state.date} onChange={this.handleDatePickerChange}/>
</Container>
);
}
});
|
src/tools/web/client/src/utils.js
|
e1528532/libelektra
|
import React from 'react'
export const toElektraBool = (val) =>
val ? '1' : '0'
export const fromElektraBool = (val) =>
(val === '1') ? true : false
export const RANGE_REGEX = /([-+]?[0-9]*\.?[0-9]+)-([-+]?[0-9]*\.?[0-9]+)/
export const HOST_REGEX = /(https?:\/\/[^/]+)(\/.*)?/
export const ARRAY_KEY_REGEX = /#(_*)([0-9]+)/
export const prettyPrintArrayIndex = (str) => {
const match = str.match(ARRAY_KEY_REGEX)
if (!match) return str
const [ , prefix, index ] = match
return (
<span>
<span style={{ opacity: 0.4 }}>#</span>
<span style={{ opacity: 0.3 }}>{prefix}</span>
<span style={{ fontWeight: 'bold' }}>{index}</span>
</span>
)
}
export const isNumberType = (type) => {
switch (type) {
case 'short':
case 'unsigned_short':
case 'long':
case 'unsigned_long':
case 'long_long':
case 'unsigned_long_long':
case 'float':
case 'double':
return true
default:
return false
}
}
export const VISIBILITY_LEVELS = {
critical: 7,
important: 6,
user: 5,
advanced: 4,
developer: 3,
internal: 2,
}
export const visibility = (name) => VISIBILITY_LEVELS[name]
|
src/components/Sample2/Sample2.js
|
tinkertrain/qsenseistyleguide
|
import React, { Component } from 'react';
import CodeBlock from '../CodeBlock';
import './Sample2.scss';
export class Sample2 extends Component {
state = {
classSize: 'qs_Base--16'
};
render() {
return (
<div className={this.state.classSize}>
<div className="fontSizeSwitcher qs_Bg--lightgray">
<label htmlFor="fontSizeOptions">Base:</label>
<div className="qs_Input qs_Select">
<select
name="fontSizeOptions"
id="fontSizeOptions"
onChange={this.switchFontSize.bind(this)}>
<option value="16">16px</option>
<option value="18">18px</option>
<option value="20">20px</option>
</select>
</div>
</div>
<section className="qs_PageSection qs_Center qs_Bg--darkgray">
<div className="qs_PageSection__container">
<h1 className="qs_PageTitle">Get Fuse</h1>
</div>
</section>
<section className="qs_PageSection qs_Bg--white">
<div className="qs_PageSection__container qs_Center">
<p className="qs_Entry">Fuse Free is the free edition of our data platform that you can use for non-commercial purposes.
You can use it at no cost for as long as you want.</p>
<p className="qs_Entry">Your Access Token is:</p>
<div className="qs_Input">
<input className="qs_Center" type="text" name="example1" id="example1" value="08896316e74945129367c4d123456789"/>
</div>
</div>
</section>
<section className="qs_PageSection qs_Bg--lightgray">
<div className="qs_PageSection__container">
<h2 className="qs_Center">Get Started</h2>
<p className="qs_Entry qs_Center">To get and run Fuse, you need to have Docker installed on your system *. Follow the instructions on the Docker website.</p>
<ol>
<li>
<p>Login to our Docker registry</p>
<div className="qs_CodeBlock">
<CodeBlock language="bash">
{
`$ docker login -u 'token' -p 08896316e74945129367c4d123456789 -e 'me@company.com' docker.qsensei.com`
}
</CodeBlock>
</div>
</li>
<li>
<p>What’s next?</p>
<p>To get you started easily we provide a step by step Tutorial to guide you through the process of creating your first Fuse powered data app. In addition, take a look at our Documentation to get a more in depth view into the basics of deploying and setting up Fuse.</p>
<p className="qs_Mediumgray qs_Center"><em>* Other System requirements can be found <a href="#">here</a> in our Documentation.</em></p>
</li>
</ol>
</div>
</section>
<section className="qs_PageSection qs_Bg--white">
<div className="qs_PageSection__container qs_Center">
<h2>Discover Fuse Professional</h2>
<p className="qs_Entry">Want to build data apps with replication over several servers? Want to understand the impact your data apps have on your organization? Want to use advanced Data Services to improve data ingest and data preparation? Fuse Professional is our solution for advanced data needs.</p>
<div className="button-row">
<button className="qs_Button qs_Button--dark qs_Button--outline">browse all features</button>
<button className="qs_Button qs_Button--dark qs_Button--outline">view pricing plans</button>
</div>
</div>
</section>
<section className="qs_PageSection qs_Bg--darkgray">
<div className="qs_PageSection__container qs_Center">
Footer…
</div>
</section>
</div>
);
}
switchFontSize(event) {
this.setState({
classSize: `qs_Base--${event.target.value}`
});
}
}
|
templates/rubix/rails/rails-example/src/common/sidebar.js
|
jeffthemaximum/Teachers-Dont-Pay-Jeff
|
import React from 'react';
import {
Sidebar, SidebarNav, SidebarNavItem,
SidebarControls, SidebarControlBtn,
LoremIpsum, Grid, Row, Col, FormControl,
Label, Progress, Icon,
SidebarDivider
} from '@sketchpixy/rubix';
import { Link } from 'react-router';
class ApplicationSidebar extends React.Component {
handleChange(e) {
this._nav.search(e.target.value);
}
render() {
return (
<div>
<Grid>
<Row>
<Col xs={12}>
<FormControl type='text' placeholder='Search...' onChange={::this.handleChange} className='sidebar-search' style={{border: 'none', background: 'none', margin: '10px 0 0 0', borderBottom: '1px solid #666', color: 'white'}} />
<div className='sidebar-nav-container'>
<SidebarNav style={{marginBottom: 0}} ref={(c) => this._nav = c}>
{ /** Pages Section */ }
<div className='sidebar-header'>PAGES</div>
<SidebarNavItem glyph='icon-outlined-todolist' name='All Todos' href='/' />
<SidebarNavItem glyph='icon-outlined-pencil' name='Edit Todo' href='/todos/:id' />
</SidebarNav>
</div>
</Col>
</Row>
</Grid>
</div>
);
}
}
class DummySidebar extends React.Component {
render() {
return (
<Grid>
<Row>
<Col xs={12}>
<div className='sidebar-header'>DUMMY SIDEBAR</div>
<LoremIpsum query='1p' />
</Col>
</Row>
</Grid>
);
}
}
export default class SidebarContainer extends React.Component {
render() {
return (
<div id='sidebar'>
<div id='avatar'>
<Grid>
<Row className='fg-white'>
<Col xs={4} collapseRight>
<img src='/imgs/app/avatars/avatar0.png' width='40' height='40' />
</Col>
<Col xs={8} collapseLeft id='avatar-col'>
<div style={{top: 23, fontSize: 16, lineHeight: 1, position: 'relative'}}>Anna Sanchez</div>
<div>
<Progress id='demo-progress' value={30} color='#ffffff'/>
<Icon id='demo-icon' bundle='fontello' glyph='lock-5' />
</div>
</Col>
</Row>
</Grid>
</div>
<SidebarControls>
<SidebarControlBtn bundle='fontello' glyph='docs' sidebar={0} />
<SidebarControlBtn bundle='fontello' glyph='chat-1' sidebar={1} />
<SidebarControlBtn bundle='fontello' glyph='chart-pie-2' sidebar={2} />
<SidebarControlBtn bundle='fontello' glyph='th-list-2' sidebar={3} />
<SidebarControlBtn bundle='fontello' glyph='bell-5' sidebar={4} />
</SidebarControls>
<div id='sidebar-container'>
<Sidebar sidebar={0}>
<ApplicationSidebar />
</Sidebar>
<Sidebar sidebar={1}>
<DummySidebar />
</Sidebar>
<Sidebar sidebar={2}>
<DummySidebar />
</Sidebar>
<Sidebar sidebar={3}>
<DummySidebar />
</Sidebar>
<Sidebar sidebar={4}>
<DummySidebar />
</Sidebar>
</div>
</div>
);
}
}
|
examples/auth-with-shared-root/app.js
|
zenlambda/react-router
|
import React from 'react'
import { render } from 'react-dom'
import { browserHistory, Router } from 'react-router'
import routes from './config/routes'
render(<Router history={browserHistory} routes={routes}/>, document.getElementById('example'))
|
src/pages/resume/education/index.fr.js
|
angeloocana/angeloocana
|
import React from 'react';
import EducationsPage from '../../../components/Resume/EducationsPage';
import graphql from 'graphql';
export default (props) =>
<EducationsPage
{...props}
/>;
export const pageQuery = graphql`
query ResumeEducationsFr {
site {
siteMetadata {
resume {
menu {
label
link
}
educations {
name
subject {
fr
}
needWhiteBg
link
fullName
years
img
}
}
}
}
}
`;
|
src/ShallowTraversal.js
|
dustinsanders/enzyme
|
import React from 'react';
import isEmpty from 'lodash/isEmpty';
import isSubset from 'is-subset';
import {
coercePropValue,
propsOfNode,
splitSelector,
isCompoundSelector,
selectorType,
AND,
SELECTOR,
nodeHasType,
} from './Utils';
export function childrenOfNode(node) {
if (!node) return [];
const maybeArray = propsOfNode(node).children;
const result = [];
React.Children.forEach(maybeArray, child => {
if (child !== null && child !== false && typeof child !== 'undefined') {
result.push(child);
}
});
return result;
}
export function hasClassName(node, className) {
let classes = propsOfNode(node).className || '';
classes = classes.replace(/\s/g, ' ');
return ` ${classes} `.indexOf(` ${className} `) > -1;
}
export function treeForEach(tree, fn) {
if (tree !== null && tree !== false && typeof tree !== 'undefined') {
fn(tree);
}
childrenOfNode(tree).forEach(node => treeForEach(node, fn));
}
export function treeFilter(tree, fn) {
const results = [];
treeForEach(tree, node => {
if (fn(node)) {
results.push(node);
}
});
return results;
}
function pathFilter(path, fn) {
return path.filter(tree => treeFilter(tree, fn).length !== 0);
}
export function pathToNode(node, root) {
const queue = [root];
const path = [];
const hasNode = (testNode) => node === testNode;
while (queue.length) {
const current = queue.pop();
const children = childrenOfNode(current);
if (current === node) return pathFilter(path, hasNode);
path.push(current);
if (children.length === 0) {
// leaf node. if it isn't the node we are looking for, we pop.
path.pop();
}
queue.push.apply(queue, children);
}
return null;
}
export function parentsOfNode(node, root) {
return pathToNode(node, root).reverse();
}
export function nodeHasId(node, id) {
return propsOfNode(node).id === id;
}
export function nodeHasProperty(node, propKey, stringifiedPropValue) {
const nodeProps = propsOfNode(node);
const propValue = coercePropValue(propKey, stringifiedPropValue);
const descriptor = Object.getOwnPropertyDescriptor(nodeProps, propKey);
if (descriptor && descriptor.get) {
return false;
}
const nodePropValue = nodeProps[propKey];
if (nodePropValue === undefined) {
return false;
}
if (propValue) {
return nodePropValue === propValue;
}
return nodeProps.hasOwnProperty(propKey);
}
export function nodeMatchesObjectProps(node, props) {
return isSubset(propsOfNode(node), props);
}
export function buildPredicate(selector) {
switch (typeof selector) {
case 'function':
// selector is a component constructor
return node => node && node.type === selector;
case 'string':
if (isCompoundSelector.test(selector)) {
return AND(splitSelector(selector).map(buildPredicate));
}
switch (selectorType(selector)) {
case SELECTOR.CLASS_TYPE:
return node => hasClassName(node, selector.substr(1));
case SELECTOR.ID_TYPE:
return node => nodeHasId(node, selector.substr(1));
case SELECTOR.PROP_TYPE: {
const propKey = selector.split(/\[([a-zA-Z\-]*?)(=|\])/)[1];
const propValue = selector.split(/=(.*?)\]/)[1];
return node => nodeHasProperty(node, propKey, propValue);
}
default:
// selector is a string. match to DOM tag or constructor displayName
return node => nodeHasType(node, selector);
}
case 'object':
if (!Array.isArray(selector) && selector !== null && !isEmpty(selector)) {
return node => nodeMatchesObjectProps(node, selector);
}
throw new TypeError(
'Enzyme::Selector does not support an array, null, or empty object as a selector'
);
default:
throw new TypeError('Enzyme::Selector expects a string, object, or Component Constructor');
}
}
export function getTextFromNode(node) {
if (node === null || node === undefined) {
return '';
}
if (typeof node === 'string' || typeof node === 'number') {
return String(node);
}
if (node.type && typeof node.type === 'function') {
return `<${node.type.displayName || node.type.name} />`;
}
return childrenOfNode(node).map(getTextFromNode).join('').replace(/\s+/, ' ');
}
|
src/components/ImgFigure.js
|
movingStars/gallery-by-react-from-xiongjiao
|
require('normalize.css/normalize.css');
import React from 'react';
class ImgFigure extends React.Component {
render(){
let { data } = this.props;
return(
<figure className="img-figure">
<img className="img-img" src={data.imageURL} alt={data.title}/>
<figcaption>
<h2 className="img-title">{data.title}</h2>
</figcaption>
</figure>
);
}
};
ImgFigure.defaultProps = {
};
export default ImgFigure;
|
src/Snackbar/Snackbar.spec.js
|
mmrtnz/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import Snackbar from './Snackbar';
import SnackbarBody from './SnackbarBody';
import getMuiTheme from '../styles/getMuiTheme';
describe('<Snackbar />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
describe('prop: open', () => {
it('should be hidden when open is false', () => {
const wrapper = shallowWithContext(
<Snackbar open={false} message="Message" />
);
assert.strictEqual(
wrapper.find('div').at(0).node.props.style.visibility,
'hidden',
'The element should be hidden.'
);
});
it('should be hidden when open is true', () => {
const wrapper = shallowWithContext(
<Snackbar open={true} message="Message" />
);
assert.strictEqual(
wrapper.find('div').at(0).node.props.style.visibility,
'visible',
'The element should be hidden.'
);
});
});
it('should show the next message after an update', (done) => {
const wrapper = shallowWithContext(
<Snackbar open={true} message="First message" />
);
wrapper.setProps({
message: 'Second message',
});
assert.strictEqual(wrapper.state('message'), 'First message');
setTimeout(() => {
assert.strictEqual(wrapper.state('message'), 'Second message',
'Should take into account the next message');
done();
}, 500);
});
it('should show the latest message of consecutive updates', (done) => {
const wrapper = shallowWithContext(
<Snackbar open={false} message="First message" />
);
wrapper.setProps({
open: true,
message: 'Second message',
});
assert.strictEqual(wrapper.state('message'), 'Second message');
wrapper.setProps({
open: true,
message: 'Third message',
});
assert.strictEqual(wrapper.state('message'), 'Second message');
setTimeout(() => {
assert.strictEqual(wrapper.state('message'), 'Third message',
'Should take into account the latest message');
done();
}, 500);
});
describe('prop: contentStyle', () => {
it('should apply the style on the right element', () => {
const contentStyle = {};
const wrapper = shallowWithContext(
<Snackbar open={false} message="" contentStyle={contentStyle} />
);
assert.strictEqual(
wrapper.find(SnackbarBody).props().contentStyle,
contentStyle
);
});
});
});
|
src/svg-icons/av/forward-10.js
|
pancho111203/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvForward10 = (props) => (
<SvgIcon {...props}>
<path d="M4 13c0 4.4 3.6 8 8 8s8-3.6 8-8h-2c0 3.3-2.7 6-6 6s-6-2.7-6-6 2.7-6 6-6v4l5-5-5-5v4c-4.4 0-8 3.6-8 8zm6.8 3H10v-3.3L9 13v-.7l1.8-.6h.1V16zm4.3-1.8c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1.3.2.5.3.2.3.3.6.1.5.1.8v.7zm-.8-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/>
</SvgIcon>
);
AvForward10 = pure(AvForward10);
AvForward10.displayName = 'AvForward10';
AvForward10.muiName = 'SvgIcon';
export default AvForward10;
|
docs/app/Examples/elements/Button/Usage/index.js
|
shengnian/shengnian-ui-react
|
import React from 'react'
import { Message } from 'shengnian-ui-react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ButtonUsageExamples = () => (
<ExampleSection title='Usage'>
<ComponentExample
title='Focus'
description='A button can be focused.'
examplePath='elements/Button/Usage/ButtonExampleFocus'
/>
<ComponentExample
title='Attached events'
description='A button can be handle all events.'
examplePath='elements/Button/Usage/ButtonExampleAttachedEvents'
>
<Message warning>
<p>
When <code>Button</code> is <code>attached</code> or rendered as non-<code>button</code> element, it losses
ability to handle keyboard events when it focused.
</p>
<p>
However, <code>button</code> behaviour can be replicated with <code>onKeyPress</code> handler. You can find
out more details on {' '}
<a
href='https://developer.mozilla.org/en-US/docs/Web/Accessibility/ARIA/ARIA_Techniques/Using_the_button_role'
rel='noopener noreferrer'
target='_blank'
>
MDN
</a>.
</p>
</Message>
</ComponentExample>
</ExampleSection>
)
export default ButtonUsageExamples
|
src/Paper/Paper.js
|
AndriusBil/material-ui
|
// @flow
import React from 'react';
import type { ComponentType } from 'react';
import classNames from 'classnames';
import warning from 'warning';
import withStyles from '../styles/withStyles';
export const styles = (theme: Object) => {
const shadows = {};
theme.shadows.forEach((shadow, index) => {
shadows[`shadow${index}`] = {
boxShadow: shadow,
};
});
return {
root: {
backgroundColor: theme.palette.background.paper,
},
rounded: {
borderRadius: 2,
},
...shadows,
};
};
type DefaultProps = {
classes: Object,
component: string,
elevation: number,
square: boolean,
};
export type Props = {
/**
* Useful to extend the style applied to components.
*/
classes?: Object,
/**
* @ignore
*/
className?: string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component?: string | ComponentType<*>,
/**
* Shadow depth, corresponds to `dp` in the spec.
* It's accepting values between 0 and 24 inclusive.
*/
elevation?: number,
/**
* If `true`, rounded corners are disabled.
*/
square?: boolean,
};
type AllProps = DefaultProps & Props;
function Paper(props: AllProps) {
const {
classes,
className: classNameProp,
component: ComponentProp,
square,
elevation,
...other
} = props;
warning(
elevation >= 0 && elevation < 25,
`Material-UI: this elevation \`${elevation}\` is not implemented.`,
);
const className = classNames(
classes.root,
classes[`shadow${elevation >= 0 ? elevation : 0}`],
{
[classes.rounded]: !square,
},
classNameProp,
);
return <ComponentProp className={className} {...other} />;
}
Paper.defaultProps = {
component: 'div',
elevation: 2,
square: false,
};
export default withStyles(styles, { name: 'MuiPaper' })(Paper);
|
actor-apps/app-web/src/app/components/sidebar/HeaderSection.react.js
|
gale320/actor-platform
|
import _ from 'lodash';
import React from 'react';
import mixpanel from 'utils/Mixpanel';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import classNames from 'classnames';
import MyProfileActions from 'actions/MyProfileActions';
import LoginActionCreators from 'actions/LoginActionCreators';
import HelpActionCreators from 'actions/HelpActionCreators';
import AddContactActionCreators from 'actions/AddContactActionCreators';
import AvatarItem from 'components/common/AvatarItem.react';
import MyProfileModal from 'components/modals/MyProfile.react';
import ActorClient from 'utils/ActorClient';
import AddContactModal from 'components/modals/AddContact.react';
import PreferencesModal from '../modals/Preferences.react';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
var getStateFromStores = () => {
return {
dialogInfo: null
};
};
@ReactMixin.decorate(IntlMixin)
class HeaderSection extends React.Component {
constructor(props) {
super(props);
this.state = _.assign({
isOpened: false
}, getStateFromStores());
}
componentDidMount() {
ActorClient.bindUser(ActorClient.getUid(), this.setUser);
}
componentWillUnmount() {
ActorClient.unbindUser(ActorClient.getUid(), this.setUser);
}
setUser = (user) => {
this.setState({user: user});
};
setLogout = () => {
LoginActionCreators.setLoggedOut();
};
openMyProfile = () => {
MyProfileActions.modalOpen();
mixpanel.track('My profile open');
};
openHelpDialog = () => {
HelpActionCreators.open();
mixpanel.track('Click on HELP');
};
openAddContactModal = () => {
AddContactActionCreators.openModal();
};
onSettingsOpen = () => {
PreferencesActionCreators.show();
};
toggleHeaderMenu = () => {
const isOpened = this.state.isOpened;
if (!isOpened) {
this.setState({isOpened: true});
mixpanel.track('Open sidebar menu');
document.addEventListener('click', this.closeHeaderMenu, false);
} else {
this.closeHeaderMenu();
}
};
closeHeaderMenu = () => {
this.setState({isOpened: false});
document.removeEventListener('click', this.closeHeaderMenu, false);
};
render() {
const user = this.state.user;
if (user) {
let headerClass = classNames('sidebar__header', 'sidebar__header--clickable', {
'sidebar__header--opened': this.state.isOpened
});
let menuClass = classNames('dropdown', {
'dropdown--opened': this.state.isOpened
});
return (
<header className={headerClass}>
<div className="sidebar__header__user row" onClick={this.toggleHeaderMenu}>
<AvatarItem image={user.avatar}
placeholder={user.placeholder}
size="tiny"
title={user.name} />
<span className="sidebar__header__user__name col-xs">{user.name}</span>
<div className={menuClass}>
<span className="dropdown__button">
<i className="material-icons">arrow_drop_down</i>
</span>
<ul className="dropdown__menu dropdown__menu--right">
<li className="dropdown__menu__item hide">
<i className="material-icons">photo_camera</i>
<FormattedMessage message={this.getIntlMessage('setProfilePhoto')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openMyProfile}>
<i className="material-icons">edit</i>
<FormattedMessage message={this.getIntlMessage('editProfile')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openAddContactModal}>
<i className="material-icons">person_add</i>
Add contact
</li>
<li className="dropdown__menu__separator"></li>
<li className="dropdown__menu__item hide">
<svg className="icon icon--dropdown"
dangerouslySetInnerHTML={{__html: '<use xlink:href="assets/sprite/icons.svg#integration"/>'}}/>
<FormattedMessage message={this.getIntlMessage('configureIntegrations')}/>
</li>
<li className="dropdown__menu__item" onClick={this.openHelpDialog}>
<i className="material-icons">help</i>
<FormattedMessage message={this.getIntlMessage('helpAndFeedback')}/>
</li>
<li className="dropdown__menu__item hide" onClick={this.onSettingsOpen}>
<i className="material-icons">settings</i>
<FormattedMessage message={this.getIntlMessage('preferences')}/>
</li>
<li className="dropdown__menu__item dropdown__menu__item--light" onClick={this.setLogout}>
<FormattedMessage message={this.getIntlMessage('signOut')}/>
</li>
</ul>
</div>
</div>
<MyProfileModal/>
<AddContactModal/>
<PreferencesModal/>
</header>
);
} else {
return null;
}
}
}
export default HeaderSection;
|
ui/src/components/role/AddMemberToRoles.js
|
yahoo/athenz
|
/*
* Copyright 2020 Verizon Media
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import AddModal from '../modal/AddModal';
import FlatPicker from '../flatpicker/FlatPicker';
import { colors } from '../denali/styles';
import Input from '../denali/Input';
import InputLabel from '../denali/InputLabel';
import styled from '@emotion/styled';
import Checkbox from '../denali/CheckBox';
import DateUtils from '../utils/DateUtils';
import NameUtils from '../utils/NameUtils';
import RequestUtils from '../utils/RequestUtils';
const SectionsDiv = styled.div`
width: 800px;
text-align: left;
background-color: ${colors.white};
`;
const SectionDiv = styled.div`
align-items: flex-start;
display: flex;
flex-flow: row nowrap;
padding: 10px 30px;
`;
const ContentDiv = styled.div`
flex: 1 1;
display: flex;
flex-flow: row wrap;
`;
const StyledInputLabel = styled(InputLabel)`
flex: 0 0 150px;
font-weight: 600;
line-height: 36px;
`;
const StyledInput = styled(Input)`
max-width: 500px;
margin-right: 10px;
width: 300px;
`;
const FlatPickrInputDiv = styled.div`
margin-right: 10px;
max-width: 500px;
width: 260px;
& > div input {
position: relative;
font: 300 14px HelveticaNeue-Reg, Helvetica, Arial, sans-serif;
background-color: rgba(53, 112, 244, 0.05);
box-shadow: none;
color: rgb(48, 48, 48);
height: 16px;
min-width: 50px;
text-align: left;
border-width: 2px;
border-style: solid;
border-color: transparent;
border-image: initial;
border-radius: 2px;
flex: 1 0 auto;
margin: 0;
margin-right: 10px;
outline: none;
padding: 0.6em 12px;
transition: background-color 0.2s ease-in-out 0s,
color 0.2s ease-in-out 0s, border 0.2s ease-in-out 0s;
width: 80%;
}
`;
const StyledRoleContainer = styled.div`
width: 100%;
`;
const StyledRoles = styled.div`
border-top: 1px solid #d8dade;
height: 60%;
`;
const StyledRole = styled.div`
background-color: rgba(53, 112, 244, 0.06);
padding: 10px;
width: calc(100% - 10px);
`;
const StyledJustification = styled(Input)`
width: 300px;
margin-top: 5px;
`;
export default class AddMemberToRoles extends React.Component {
constructor(props) {
super(props);
this.api = this.props.api;
this.onSubmit = this.onSubmit.bind(this);
this.state = {
showModal: !!this.props.showAddMemberToRoles,
checkedRoles: [],
};
this.dateUtils = new DateUtils();
}
onSubmit() {
if (!this.state.memberName || this.state.memberName === '') {
this.setState({
errorMessage: 'Member name is required.',
});
return;
}
if (!this.state.checkedRoles || this.state.checkedRoles.length === 0) {
this.setState({
errorMessage: 'Should select at least one role to add members.',
});
return;
}
if (
this.props.justificationRequired &&
(this.state.justification === undefined ||
this.state.justification.trim() === '')
) {
this.setState({
errorMessage: 'Justification is required to add a member.',
});
return;
}
let member = {
memberName: this.state.memberName,
expiration:
this.state.memberExpiry && this.state.memberExpiry.length > 0
? this.dateUtils.uxDatetimeToRDLTimestamp(
this.state.memberExpiry
)
: '',
reviewReminder:
this.state.memberReviewReminder &&
this.state.memberReviewReminder.length > 0
? this.dateUtils.uxDatetimeToRDLTimestamp(
this.state.memberReviewReminder
)
: '',
};
// send api call and then reload existing members component
this.api
.addMemberToRoles(
this.props.domain,
this.state.checkedRoles,
this.state.memberName,
member,
this.state.justification
? this.state.justification
: 'added using Athenz UI',
this.props._csrf
)
.then(() => {
this.setState({
showModal: false,
justification: '',
});
const successRoles = this.state.checkedRoles.join(', ');
this.props.onSubmit(
`Successfully added ${this.state.memberName} to roles: ${successRoles}`
);
})
.catch((err) => {
this.setState({
errorMessage: RequestUtils.xhrErrorCheckHelper(err),
});
});
}
inputChanged(key, evt) {
this.setState({ [key]: evt.target.value });
}
onCheckboxChanged(role, event) {
let checkedRoles = this.state.checkedRoles;
if (checkedRoles.includes(role) && !event.target.checked) {
checkedRoles = checkedRoles.filter((checkedRole) => {
return checkedRole !== role;
});
} else {
checkedRoles.push(role);
}
this.setState({ checkedRoles });
}
render() {
let roleCheckboxes = [];
this.props.roles.forEach((role) => {
const roleName = NameUtils.getShortName(':role.', role.name);
let onCheckboxChanged = this.onCheckboxChanged.bind(this, roleName);
roleCheckboxes.push(
<StyledRole key={roleName}>
<Checkbox
checked={this.state.checkedRoles.includes(roleName)}
label={roleName}
name={roleName}
onChange={onCheckboxChanged}
key={roleName}
/>
</StyledRole>
);
});
let sections = (
<SectionsDiv
autoComplete={'off'}
data-testid='add-member-to-roles-form'
>
<SectionDiv>
<StyledInputLabel htmlFor='member-name'>
Member
</StyledInputLabel>
<ContentDiv>
<StyledInput
id='member-name'
name='member-name'
value={this.state.memberName}
onChange={this.inputChanged.bind(
this,
'memberName'
)}
placeholder='user.<shortid> or <domain>.<service>'
/>
<FlatPickrInputDiv>
<FlatPicker
onChange={(memberExpiry) => {
this.setState({ memberExpiry });
}}
id='addMemberToRoles'
clear={this.state.memberExpiry}
/>
</FlatPickrInputDiv>
<FlatPickrInputDiv>
<FlatPicker
onChange={(memberReviewReminder) => {
this.setState({ memberReviewReminder });
}}
placeholder='Reminder (Optional)'
id='addMemberToRoles-reminder'
clear={this.state.memberReviewReminder}
/>
</FlatPickrInputDiv>
{this.props.justificationRequired && (
<StyledJustification
id='justification'
name='justification'
value={this.state.justification}
onChange={this.inputChanged.bind(
this,
'justification'
)}
autoComplete={'off'}
placeholder='Enter justification here'
/>
)}
</ContentDiv>
</SectionDiv>
<SectionDiv>
<StyledInputLabel htmlFor=''>Roles</StyledInputLabel>
<ContentDiv>
<StyledRoleContainer>
<StyledRoles>{roleCheckboxes}</StyledRoles>
</StyledRoleContainer>
</ContentDiv>
</SectionDiv>
</SectionsDiv>
);
return (
<div data-testid='add-member-to-roles-form'>
<AddModal
isOpen={this.state.showModal}
cancel={this.props.onCancel}
submit={this.onSubmit}
title={'Add Member to Roles:'}
errorMessage={this.state.errorMessage}
sections={sections}
/>
</div>
);
}
}
|
fixtures/output/webpack-message-formatting/src/AppNoDefault.js
|
IamJoseph/create-react-app
|
import React, { Component } from 'react';
import myImport from './ExportNoDefault';
class App extends Component {
render() {
return <div className="App">{myImport}</div>;
}
}
export default App;
|
superset/assets/spec/javascripts/explore/components/ExploreViewContainer_spec.js
|
dmigo/incubator-superset
|
// this test must be commented out because ChartContainer is now importing files
// from visualizations/*.js which are also importing css files which breaks in the testing env.
// import React from 'react';
// import { expect } from 'chai';
// import { describe, it } from 'mocha';
// import { shallow } from 'enzyme';
// import ExploreViewContainer
// from '../../../../src/explore/components/ExploreViewContainer';
// import QueryAndSaveBtns
// from '../../../../src/explore/components/QueryAndSaveBtns';
// import ControlPanelsContainer
// from '../../../../src/explore/components/ControlPanelsContainer';
// import ChartContainer
// from '../../../../src/explore/components/ChartContainer';
// describe('ExploreViewContainer', () => {
// it('renders', () => {
// expect(
// React.isValidElement(<ExploreViewContainer />)
// ).to.equal(true);
// });
// it('renders QueryAndSaveButtons', () => {
// const wrapper = shallow(<ExploreViewContainer />);
// expect(wrapper.find(QueryAndSaveBtns)).to.have.length(1);
// });
// it('renders ControlPanelsContainer', () => {
// const wrapper = shallow(<ExploreViewContainer />);
// expect(wrapper.find(ControlPanelsContainer)).to.have.length(1);
// });
// it('renders ChartContainer', () => {
// const wrapper = shallow(<ExploreViewContainer />);
// expect(wrapper.find(ChartContainer)).to.have.length(1);
// });
// });
|
example/src/index.js
|
romainberger/react-portal-tooltip
|
import React from 'react'
import ReactDOM from 'react-dom'
import App from './app'
ReactDOM.render(<App />, document.querySelector('#root'))
|
node_modules/semantic-ui-react/dist/es/collections/Form/FormInput.js
|
SuperUncleCat/ServerMonitoring
|
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META } from '../../lib';
import Input from '../../elements/Input';
import FormField from './FormField';
/**
* Sugar for <Form.Field control={Input} />.
* @see Form
* @see Input
*/
function FormInput(props) {
var control = props.control;
var rest = getUnhandledProps(FormInput, props);
var ElementType = getElementType(FormInput, props);
return React.createElement(ElementType, _extends({}, rest, { control: control }));
}
FormInput.handledProps = ['as', 'control'];
FormInput._meta = {
name: 'FormInput',
parent: 'Form',
type: META.TYPES.COLLECTION
};
FormInput.propTypes = process.env.NODE_ENV !== "production" ? {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A FormField control prop. */
control: FormField.propTypes.control
} : {};
FormInput.defaultProps = {
as: FormField,
control: Input
};
export default FormInput;
|
src/index.js
|
fmakdemir/react-boilerplate
|
import React from 'react';
import ReactDom from 'react-dom';
import App from 'containers/app';
import Pages from 'pages';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
// theming
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import theme from 'lib/theme';
// redux thingies
import { Provider } from 'react-redux';
import { createStore, combineReducers} from 'redux';
import { syncHistoryWithStore, routerReducer } from 'react-router-redux';
import reducers from 'reducers';
// tap event plugin
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
const combinedReducers = combineReducers({
...reducers,
routing: routerReducer,
});
let store = createStore(combinedReducers, // combine reducers
{ // initial data for reducers
sidebar: false,
notif: {open: false, message: ''},
},
// enable redux monitor
window.__REDUX_DEVTOOLS_EXTENSION__ && window.__REDUX_DEVTOOLS_EXTENSION__());
const history = syncHistoryWithStore(browserHistory, store);
ReactDom.render((
<MuiThemeProvider muiTheme={theme}>
<Provider store={store}>
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={Pages.Home}/>
<Route path="about" component={Pages.About}/>
</Route>
</Router>
</Provider>
</MuiThemeProvider>
), document.getElementById('root'));
|
packages/component/src/Attachment/ImageAttachment.js
|
billba/botchat
|
import PropTypes from 'prop-types';
import React from 'react';
import ImageContent from './ImageContent';
import readDataURIToBlob from '../Utils/readDataURIToBlob';
const ImageAttachment = ({ attachment }) => {
let imageURL = attachment.thumbnailUrl || attachment.contentUrl;
// To support Content Security Policy, data URI cannot be used.
// We need to parse the data URI into a blob: URL.
const blob = readDataURIToBlob(imageURL);
if (blob) {
imageURL = URL.createObjectURL(blob);
}
return <ImageContent alt={attachment.name} src={imageURL} />;
};
ImageAttachment.propTypes = {
// Either attachment.contentUrl or attachment.thumbnailUrl must be specified.
attachment: PropTypes.oneOfType([
PropTypes.shape({
contentUrl: PropTypes.string.isRequired,
name: PropTypes.string,
thumbnailUrl: PropTypes.string
}),
PropTypes.shape({
contentUrl: PropTypes.string,
name: PropTypes.string,
thumbnailUrl: PropTypes.string.isRequired
})
]).isRequired
};
export default ImageAttachment;
|
src/ui/pages/App.js
|
notifapi/notifapi-web
|
import React from 'react';
import { Component } from 'react';
import AppContainer from '../containers/AppContainer';
import HeaderContainer from '../containers/HeaderContainer';
import FooterContainer from '../containers/FooterContainer';
export default class App extends Component {
render() {
return (
<div>
<HeaderContainer />
<AppContainer>
{this.props.children}
</AppContainer>
<FooterContainer />
</div>
);
}
}
|
src/encoded/static/components/item-pages/FileSetCalibrationView.js
|
4dn-dcic/fourfront
|
'use strict';
import React from 'react';
import _ from 'underscore';
import { FilesInSetTable } from './components/FilesInSetTable';
import DefaultItemView from './DefaultItemView';
/**
* Page view for a FileSetCalibration Item.
* Renders out a {@link module:item-pages/components.FilesInSetTable} Component.
*
* @module {Component} item-pages/file-set-calibration-view
*/
export default class FileSetCalibrationView extends DefaultItemView {
getTabViewContents(){
var initTabs = [];
if (Array.isArray(this.props.context.files_in_set)){
initTabs.push(FilesInSetTable.getTabObject(this.props.context));
}
return initTabs.concat(_.filter(this.getCommonTabs(), function(tabObj){
if (tabObj.key === 'details') return false;
return true;
}));
}
}
|
src/components/Chat/Input/EmojiSuggestion.js
|
welovekpop/uwave-web-welovekpop.club
|
import React from 'react';
import PropTypes from 'prop-types';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import ListItemText from '@material-ui/core/ListItemText';
import Suggestion from './Suggestion';
const shortcode = emoji => `:${emoji.shortcode}:`;
const EmojiSuggestion = ({
value: emoji,
...props
}) => (
<Suggestion {...props}>
<ListItemAvatar>
<span
className="EmojiSuggestion-image"
style={{ backgroundImage: `url(/assets/emoji/${emoji.image})` }}
/>
</ListItemAvatar>
<ListItemText primary={shortcode(emoji)} />
</Suggestion>
);
EmojiSuggestion.propTypes = {
value: PropTypes.shape({
shortcode: PropTypes.string,
image: PropTypes.string,
}).isRequired,
};
export default EmojiSuggestion;
|
examples/with-react-intl/components/Layout.js
|
sedubois/next.js
|
import React from 'react'
import {defineMessages, injectIntl} from 'react-intl'
import Head from 'next/head'
import Nav from './Nav'
const messages = defineMessages({
title: {
id: 'title',
defaultMessage: 'React Intl Next.js Example'
}
})
export default injectIntl(({intl, title, children}) => (
<div>
<Head>
<meta name='viewport' content='width=device-width, initial-scale=1' />
<title>{title || intl.formatMessage(messages.title)}</title>
</Head>
<header>
<Nav />
</header>
{children}
</div>
))
|
source/common/components/App/App.js
|
shery15/react
|
import React from 'react';
import {
BrowserRouter as Router,
Route,
Switch,
Link
} from 'react-router-dom';
import CSSModules from 'react-css-modules';
import styles from '../../css/bulma.css';
import Greeter from '../Greeter';
import Todo from '../Todo';
import MarkdownEditor from '../MarkdownEditor';
import Info from '../Info';
import AuthExample from '../Login';
import Prompt from '../Prompt';
import Animation from '../Animation';
const OldSchoolMenuLink = ({ label, to, activeOnlyWhenExact }) => (
<Route path={to} exact={activeOnlyWhenExact} children={({ match }) => (
<div className={match ? 'active' : ''}>
{match ? '> ' : ''}<Link to={to}>{label}</Link>
</div>
)}/>
);
const App = () => (
<Router>
<div className="tabs">
<ul>
<li><OldSchoolMenuLink to="/" activeOnlyWhenExact={true} label="Home" /></li>
<li><OldSchoolMenuLink to="/topics" label="Topics" /></li>
<li><OldSchoolMenuLink to="/info" label="Info" /></li>
<li><OldSchoolMenuLink to="/todo" label="Todo" /></li>
<li><OldSchoolMenuLink to="/markdowneditor" label="MarkdownEditor" /></li>
<li><OldSchoolMenuLink to="/auth" label="AuthExample" /></li>
<li><OldSchoolMenuLink to="/prompt" label="Prompt" /></li>
<li><OldSchoolMenuLink to="/animation" label="Animation" /></li>
<li><OldSchoolMenuLink to="/404" label="404" /></li>
</ul>
<hr />
<Switch>
<Route exact path="/" name="Router v4.0" component={Greeter} />
<Route path="/topics" component={Topics} />
<Route path="/todo" component={Todo} />
<Route path="/info" component={Info} />
<Route path="/markdowneditor" component={MarkdownEditor} />
<Route path="/auth" component={AuthExample} />
<Route path="/animation" component={Animation} />
<Route path="/prompt" component={Prompt} />
<Route component={NoMatch}/>
</Switch>
</div>
</Router>
);
const NoMatch = ({ location }) => (
<div>
<h3>No match for <code>{location.pathname}</code></h3>
</div>
)
const Topics = ({ match }) => (
<div>
<h2>Topics</h2>
<ul>
<li>
<Link to={`${match.url}/rendering`}>
Rendering with React
</Link>
</li>
<li>
<Link to={`${match.url}/component`}>
Components
</Link>
</li>
<li>
<Link to={`${match.url}/props-v-state`}>
Props v. State
</Link>
</li>
</ul>
<Route path={`${match.url}/:topicId`} component={Topic} />
<Route exact path={match.url} render={() => (
<h3>Please select a topic.</h3>
)} />
</div>
);
const Topic = ({ match }) => (
<div>
<h3>{match.params.topicId}</h3>
</div>
);
export default CSSModules(App, styles, { allowMultiple: true });
|
src/svg-icons/action/delete.js
|
ArcanisCz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionDelete = (props) => (
<SvgIcon {...props}>
<path d="M6 19c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V7H6v12zM19 4h-3.5l-1-1h-5l-1 1H5v2h14V4z"/>
</SvgIcon>
);
ActionDelete = pure(ActionDelete);
ActionDelete.displayName = 'ActionDelete';
ActionDelete.muiName = 'SvgIcon';
export default ActionDelete;
|
src/Paper/Paper.js
|
dsslimshaddy/material-ui
|
// @flow
import React from 'react';
import classNames from 'classnames';
import warning from 'warning';
import withStyles from '../styles/withStyles';
export const styles = (theme: Object) => {
const shadows = {};
theme.shadows.forEach((shadow, index) => {
shadows[`shadow${index}`] = {
boxShadow: shadow,
};
});
return {
root: {
backgroundColor: theme.palette.background.paper,
},
rounded: {
borderRadius: 2,
},
...shadows,
};
};
type DefaultProps = {
classes: Object,
component: string,
elevation: number,
square: boolean,
};
export type Props = {
/**
* Useful to extend the style applied to components.
*/
classes?: Object,
/**
* @ignore
*/
className?: string,
/**
* The component used for the root node.
* Either a string to use a DOM element or a component.
*/
component?: string | Function,
/**
* Shadow depth, corresponds to `dp` in the spec.
* It's accepting values between 0 and 24 inclusive.
*/
elevation?: number,
/**
* If `true`, rounded corners are disabled.
*/
square?: boolean,
};
type AllProps = DefaultProps & Props;
function Paper(props: AllProps) {
const {
classes,
className: classNameProp,
component: ComponentProp,
square,
elevation,
...other
} = props;
warning(
elevation >= 0 && elevation < 25,
`Material-UI: this elevation \`${elevation}\` is not implemented.`,
);
const className = classNames(
classes.root,
classes[`shadow${elevation >= 0 ? elevation : 0}`],
{
[classes.rounded]: !square,
},
classNameProp,
);
return <ComponentProp className={className} {...other} />;
}
Paper.defaultProps = {
component: 'div',
elevation: 2,
square: false,
};
export default withStyles(styles, { name: 'MuiPaper' })(Paper);
|
__tests__/Layout-test.js
|
marcosaftertype/React-Redux-App-Boilerplate
|
'use strict'
import React from 'react'
import { shallow } from 'enzyme'
import Layout from '../js/components/layout'
describe('Component: Layout', () => {
const layout = shallow(<Layout />)
it('renders properly, is <div>', () => {
expect(layout.is('div')).toEqual(true)
})
it('has H1 with default title: Layout Component', () => {
expect(layout.find('h1').text()).toEqual('Layout Component')
})
})
|
src/encoded/static/components/viz/components/Legend.js
|
4dn-dcic/fourfront
|
'use strict';
import React from 'react';
import _ from 'underscore';
import memoize from 'memoize-one';
import * as vizUtil from '@hms-dbmi-bgm/shared-portal-components/es/components/viz/utilities';
import { barplot_color_cycler } from './../ColorCycler';
import { console, isServerSide, object, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { Schemas } from './../../util';
import { CursorViewBounds } from './../ChartDetailCursor';
import ReactTooltip from 'react-tooltip';
/**
* @typedef {Object} FieldObject
* @prop {string} field - Dot-separated field identifier string.
* @prop {string} name - Human-readable title or name of field.
* @prop {{ term: string, field: string, color: string, experiment_sets: number, experiments: number, files: number }[]} terms - List of terms in field.
*/
/**
* React component which represents a Term item.
*
* @class Term
* @prop {string} field - Name of field to which this term belongs, in object-dot-notation.
* @prop {string} term - Name of term.
* @prop {string|Object} color - Color to show next to term, should be string or RGBColor object.
* @type Component
*/
class Term extends React.Component {
constructor(props){
super(props);
this.generateNode = this.generateNode.bind(this);
this.onMouseEnter = this.onMouseEnter.bind(this);
this.onMouseLeave = this.onMouseLeave.bind(this);
this.onClick = this.onClick.bind(this);
}
componentWillUnmount(){
const { hoverTerm, selectedTerm, term } = this.props;
if (hoverTerm === term || selectedTerm === term){
this.onMouseLeave();
}
}
generateNode(){
return _.pick(this.props, 'field', 'term', 'color', 'position', 'experiment_sets', 'experiments', 'files');
}
onMouseEnter(e){
const { field, term, color, onNodeMouseEnter } = this.props;
vizUtil.highlightTerm(field, term, color);
if (typeof onNodeMouseEnter === 'function'){
onNodeMouseEnter(this.generateNode(), e);
}
}
onMouseLeave(e){
if (typeof this.props.onNodeMouseLeave === 'function'){
this.props.onNodeMouseLeave(this.generateNode(), e);
}
}
onClick(e){
if (typeof this.props.onNodeClick === 'function'){
this.props.onNodeClick(this.generateNode(), e);
}
}
render(){
const { color: propColor, term, name, field, aggregateType } = this.props;
const color = propColor || "transparent";
return (
<div className="term text-truncate">
<span
onMouseEnter={this.onMouseEnter}
onMouseLeave={this.onMouseLeave}
onClick={this.onClick}
>
<div
className="color-patch no-highlight-color"
data-term={term}
style={{ backgroundColor : color }}
/>
{ name || Schemas.Term.toName(field, term) }
{ aggregateType && this.props[aggregateType] ? <span className="text-300"> ({ this.props[aggregateType] })</span> : null }
</span>
</div>
);
}
}
/**
* May have multiple terms.
*
* @prop {string} field - Field name, in object-dot-notation.
* @prop {boolean} includeFieldTitle - Whether field title should be included at the top of list of terms.
* @prop {Object[]} terms - Terms which belong to this field, in the form of objects.
*/
const Field = React.memo(function Field(props){
const { field, title, name, includeFieldTitle, terms } = props;
return (
<div className="field" data-field={field} onMouseLeave={vizUtil.unhighlightTerms.bind(this, field)}>
{ includeFieldTitle ?
<h5 className="text-500 legend-field-title">{ title || name || field }</h5>
: null }
{ _.map(terms, (term, i) =>
<Legend.Term {...term} field={field} key={term.term} position={i}
{..._.pick(props, 'onNodeMouseEnter', 'onNodeMouseLeave', 'onNodeClick',
'selectedTerm', 'hoverTerm', 'aggregateType')} />
)}
</div>
);
});
Field.defaultProps = { 'includeFieldTitle' : true };
class LegendViewContainer extends React.Component {
static defaultProps = {
'expandable' : false,
'expandableAfter' : 5
};
constructor(props){
super(props);
this.showToggleIcon = this.showToggleIcon.bind(this);
this.toggleIcon = this.toggleIcon.bind(this);
this.render = this.render.bind(this);
}
componentDidUpdate(){
if (this.showToggleIcon()){
ReactTooltip.rebuild();
}
}
showToggleIcon(){ return this.props.expandable && this.props.field.terms && this.props.field.terms.length > this.props.expandableAfter; }
toggleIcon(){
if (!this.showToggleIcon()) return null;
var iconClass = this.props.expanded ? 'compress' : 'expand';
return (
<div className="expand-toggle text-center" onClick={this.props.onToggleExpand} data-tip={this.props.expanded ? "Collapse" : "Expand" } data-place="left">
<i className={"icon icon-fw fas icon-" + iconClass}/>
</div>
);
}
/**
* @returns {JSX.Element} Div element containing props.title and list of {@link Legend.Field} components.
*/
render(){
if (!this.props.field || !this.props.field.field) return null;
var className = 'legend ' + this.props.className;
if (this.props && this.props.expanded) className += ' expanded';
return (
<div className={className} id={this.props.id} style={{ 'width' : this.props.width || null }}>
{ this.props.title }
{ this.toggleIcon() }
<Legend.Field
{...Legend.parseFieldName(this.props.field)}
aggregateType={this.props.aggregateType}
includeFieldTitle={this.props.includeFieldTitles}
onNodeMouseEnter={this.props.onNodeMouseEnter}
onNodeMouseLeave={this.props.onNodeMouseLeave}
onNodeClick={this.props.onNodeClick}
selectedTerm={this.props.selectedTerm}
hoverTerm={this.props.hoverTerm}
/>
</div>
);
}
}
/**
* Legend components to use alongside Charts. Best to include within a UIControlsWrapper, and place next to chart, utilizing the same data.
*
* @class Legend
* @type {Component}
* @prop {FieldObject} field - Object containing at least 'field', in object dot notation, and 'terms'.
* @prop {boolean} includeFieldTitle - Whether to show field title at top of terms.
* @prop {string} className - Optional className to add to Legend's outermost div container.
* @prop {number} width - How wide should the legend container element (<div>) be.
* @prop {string|Element|Component} title - Optional title to display at top of legend.
*/
export class Legend extends React.PureComponent {
static Term = Term;
static Field = Field;
static barPlotFieldDataToLegendFieldsData(field, sortBy = null, colorCycler = barplot_color_cycler){
if (Array.isArray(field) && field.length > 0 && field[0] && typeof field[0] === 'object'){
return field.map(function(f){ return Legend.barPlotFieldDataToLegendFieldsData(f, sortBy); });
}
if (!field) return null;
var terms = _.pairs(field.terms).map(function(p){ // p[0] = term, p[1] = term counts
return {
'field' : field.field,
'name' : Schemas.Term.toName(field.field, p[0]),
'term' : p[0],
'color' : barplot_color_cycler.colorForNode({
'term' : p[0],
'field' : field.field
}),
'experiment_sets' : p[1].experiment_sets,
'experiments' : p[1].experiments,
'files' : p[1].files
};
});
var adjustedField = _.extend({}, field, { 'terms' : terms });
_.extend(adjustedField, { 'terms' : Legend.sortLegendFieldTermsByColorPalette(adjustedField, colorCycler) });
if (sortBy){
adjustedField.terms = _.sortBy(adjustedField.terms, sortBy);
}
return adjustedField;
}
static sortLegendFieldTermsByColorPalette(field, colorCycler){
if (!colorCycler) {
logger.error("No ColorCycler instance supplied.");
return field.terms;
}
if (field.terms && field.terms[0] && field.terms[0].color === null){
console.warn("No colors assigned to legend terms, skipping sorting. BarPlot.UIControlsWrapper or w/e should catch lack of color and force update within 1s.");
return field.terms;
}
return colorCycler.sortObjectsByColorPalette(field.terms);
}
/**
* @param {FieldObject} field - Field object containing at least a title, name, or field.
* @param {{Object}} schemas - Schemas object passed down from app.state.
* @returns {FieldObject} Modified field object.
*/
static parseFieldName(field, schemas = null){
if (!field.title && !field.name) {
return _.extend({} , field, {
'name' : Schemas.Field.toName(field.field, schemas)
});
}
return field;
}
static defaultProps = {
'hasPopover' : false,
'position' : 'absolute',
'id' : null,
'className' : 'chart-color-legend',
'width' : null,
'height' : null,
'expandable': false,
'expandableAfter' : 5,
'defaultExpanded' : false,
'aggregateType' : 'experiment_sets',
'title' : null //<h4 className="text-500">Legend</h4>
};
render(){
return <LegendExpandContainer {...this.props} />;
}
}
class LegendExpandContainer extends React.PureComponent {
static clickCoordsCallback(node, containerPosition, boundsHeight, isOnRightSide){
var margin = 260;
return {
'x' : !isOnRightSide ? containerPosition.left - margin : containerPosition.left + 30,
'y' : containerPosition.top - 10 + (16 * (node.position || 0)),
};
}
static defaultProps = {
'expandableAfter' : 5,
'expandable' : false,
'defaultExpanded' : false,
'hasPopover' : false
};
constructor(props){
super(props);
this.handleExpandToggle = _.throttle(this.handleExpandToggle.bind(this), 500);
if (this.props.expandable){
this.state = {
'expanded' : props.defaultExpanded
};
}
}
handleExpandToggle(evt){
this.setState(function({ expanded }){
return { 'expanded' : !expanded };
});
}
legendComponent(){
var propsToPass = _.clone(this.props);
propsToPass.onToggleExpand = this.handleExpandToggle;
propsToPass.expanded = (this.state && this.state.expanded) || false;
if (!this.props.hasPopover) return <LegendViewContainer {...propsToPass} />;
return (
<CursorViewBounds
eventCategory="BarPlotLegend" href={this.props.href}
actions={this.props.cursorDetailActions}
highlightTerm
width={this.props.width}
clickCoordsFxn={LegendExpandContainer.clickCoordsCallback}>
<LegendViewContainer {...propsToPass} />
</CursorViewBounds>
);
}
render(){
if (!this.props.expandable || !this.state){
return this.legendComponent();
} else {
var className = "legend-expand-container";
if (this.state.expanded) className += ' expanded';
return <div className={className} children={this.legendComponent()} />;
}
}
}
|
1_simple_server_render/app.js
|
chkui/react-server-demo
|
'use strict';
import React from 'react'
const s_contain = {
width: '40rem',
display: 'inline-block'
},s_h3 = {
display: 'inline-block'
}
const App = props =>
<div style={s_contain}>
<h3 style={s_h3}>这是一个简单的服务器端渲染展示页面。</h3>
<P />
<P2 />
</div>
class P extends React.Component{
constructor(...props){
super(...props)
}
render(){
return(
<p>这是用ES6的class实现的组件,当在服务器上运行时对其进行修改页面会同步进行更新。</p>
)
}
}
const P2 = props =>
<p>这是用function实现的组件,当在服务器上运行时修改内容并不会刷新,需要手工F5。</p>
export default App
|
tests/react_children/text.js
|
popham/flow
|
// @flow
import React from 'react';
class Text extends React.Component<{children: string}, void> {}
class TextOptional extends React.Component<{children?: string}, void> {}
class TextLiteral extends React.Component<{children: 'foo' | 'bar'}, void> {}
<Text />; // Error: `children` is required.
<TextOptional />; // OK: `children` is optional.
<TextLiteral />; // Error: `children` is required.
<Text>Hello, world!</Text>; // OK: `children` is a single string.
<Text></Text>; // Error: `children` does not exist.
<Text> </Text>; // OK: `children` is some space.
<Text>{}</Text>; // Error: `children` is required.
<Text>{/* Hello, world! */}</Text>; // Error: `children` is required.
<Text>{undefined}</Text>; // Error: `undefined` is not allowed.
<Text>{null}</Text>; // Error: `null` is not allowed.
<Text>{true}</Text>; // Error: `boolean`s are not allowed.
<Text>{false}</Text>; // Error: `boolean`s are not allowed.
<Text>{0}</Text>; // Error: `number`s are not allowed.
<Text>{42}</Text>; // Error: `number`s are not allowed.
<Text><intrinsic/></Text>; // Error: elements are not allowed.
// OK: Text across multiple lines is fine.
<Text>
Hello, world!
Multiline.
</Text>;
<Text>{'Hello, world!'}</Text>; // OK: Single string in an expression container.
<Text>{'Hello, '}{'world!'}</Text>; // Error: We did not allow an array.
<Text>Hello, {'world!'}</Text>; // Error: We did not allow an array.
<Text>{'Hello, world!'} </Text>; // Error: Spaces cause there to be an array.
<Text> {'Hello, world!'}</Text>; // Error: Spaces cause there to be an array.
// OK: Newlines are trimmed.
<Text>
{'Hello, world!'}
</Text>;
<TextLiteral>foo</TextLiteral>; // OK: Text literal is fine.
<TextLiteral>bar</TextLiteral>; // OK: Text literal is fine.
<TextLiteral>{'foo'}</TextLiteral>; // OK: Text literal is fine.
<TextLiteral>buz</TextLiteral>; // Error: `buz` is not allowed.
<TextLiteral>{'buz'}</TextLiteral>; // Error: `buz` is not allowed.
<TextLiteral>foo </TextLiteral>; // Error: Spaces are not trimmed.
<TextLiteral> foo</TextLiteral>; // Error: Spaces are not trimmed.
<TextLiteral>{'foo'} </TextLiteral>; // Error: Spaces are not trimmed.
<TextLiteral> {'foo'}</TextLiteral>; // Error: Spaces are not trimmed.
// OK: Newlines are trimmed.
<TextLiteral>
foo
</TextLiteral>;
|
blueocean-material-icons/src/js/components/svg-icons/hardware/keyboard-arrow-up.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const HardwareKeyboardArrowUp = (props) => (
<SvgIcon {...props}>
<path d="M7.41 15.41L12 10.83l4.59 4.58L18 14l-6-6-6 6z"/>
</SvgIcon>
);
HardwareKeyboardArrowUp.displayName = 'HardwareKeyboardArrowUp';
HardwareKeyboardArrowUp.muiName = 'SvgIcon';
export default HardwareKeyboardArrowUp;
|
app/javascript/mastodon/components/dropdown_menu.js
|
MitarashiDango/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import IconButton from './icon_button';
import Overlay from 'react-overlays/lib/Overlay';
import Motion from '../features/ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { supportsPassiveEvents } from 'detect-passive-events';
import classNames from 'classnames';
import { CircularProgress } from 'mastodon/components/loading_indicator';
const listenerOptions = supportsPassiveEvents ? { passive: true } : false;
let id = 0;
class DropdownMenu extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
items: PropTypes.oneOfType([PropTypes.array, ImmutablePropTypes.list]).isRequired,
loading: PropTypes.bool,
scrollable: PropTypes.bool,
onClose: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
openedViaKeyboard: PropTypes.bool,
renderItem: PropTypes.func,
renderHeader: PropTypes.func,
onItemClick: PropTypes.func.isRequired,
};
static defaultProps = {
style: {},
placement: 'bottom',
};
state = {
mounted: false,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('keydown', this.handleKeyDown, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
if (this.focusedItem && this.props.openedViaKeyboard) {
this.focusedItem.focus({ preventScroll: true });
}
this.setState({ mounted: true });
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('keydown', this.handleKeyDown, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
setFocusRef = c => {
this.focusedItem = c;
}
handleKeyDown = e => {
const items = Array.from(this.node.querySelectorAll('a, button'));
const index = items.indexOf(document.activeElement);
let element = null;
switch(e.key) {
case 'ArrowDown':
element = items[index+1] || items[0];
break;
case 'ArrowUp':
element = items[index-1] || items[items.length-1];
break;
case 'Tab':
if (e.shiftKey) {
element = items[index-1] || items[items.length-1];
} else {
element = items[index+1] || items[0];
}
break;
case 'Home':
element = items[0];
break;
case 'End':
element = items[items.length-1];
break;
case 'Escape':
this.props.onClose();
break;
}
if (element) {
element.focus();
e.preventDefault();
e.stopPropagation();
}
}
handleItemKeyPress = e => {
if (e.key === 'Enter' || e.key === ' ') {
this.handleClick(e);
}
}
handleClick = e => {
const { onItemClick } = this.props;
onItemClick(e);
}
renderItem = (option, i) => {
if (option === null) {
return <li key={`sep-${i}`} className='dropdown-menu__separator' />;
}
const { text, href = '#', target = '_blank', method } = option;
return (
<li className='dropdown-menu__item' key={`${text}-${i}`}>
<a href={href} target={target} data-method={method} rel='noopener noreferrer' role='button' tabIndex='0' ref={i === 0 ? this.setFocusRef : null} onClick={this.handleClick} onKeyPress={this.handleItemKeyPress} data-index={i}>
{text}
</a>
</li>
);
}
render () {
const { items, style, placement, arrowOffsetLeft, arrowOffsetTop, scrollable, renderHeader, loading } = this.props;
const { mounted } = this.state;
let renderItem = this.props.renderItem || this.renderItem;
return (
<Motion defaultStyle={{ opacity: 0, scaleX: 0.85, scaleY: 0.75 }} style={{ opacity: spring(1, { damping: 35, stiffness: 400 }), scaleX: spring(1, { damping: 35, stiffness: 400 }), scaleY: spring(1, { damping: 35, stiffness: 400 }) }}>
{({ opacity, scaleX, scaleY }) => (
// It should not be transformed when mounting because the resulting
// size will be used to determine the coordinate of the menu by
// react-overlays
<div className={`dropdown-menu ${placement}`} style={{ ...style, opacity: opacity, transform: mounted ? `scale(${scaleX}, ${scaleY})` : null }} ref={this.setRef}>
<div className={`dropdown-menu__arrow ${placement}`} style={{ left: arrowOffsetLeft, top: arrowOffsetTop }} />
<div className={classNames('dropdown-menu__container', { 'dropdown-menu__container--loading': loading })}>
{loading && (
<CircularProgress size={30} strokeWidth={3.5} />
)}
{!loading && renderHeader && (
<div className='dropdown-menu__container__header'>
{renderHeader(items)}
</div>
)}
{!loading && (
<ul className={classNames('dropdown-menu__container__list', { 'dropdown-menu__container__list--scrollable': scrollable })}>
{items.map((option, i) => renderItem(option, i, { onClick: this.handleClick, onKeyPress: this.handleItemKeyPress }))}
</ul>
)}
</div>
</div>
)}
</Motion>
);
}
}
export default class Dropdown extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
children: PropTypes.node,
icon: PropTypes.string,
items: PropTypes.oneOfType([PropTypes.array, ImmutablePropTypes.list]).isRequired,
loading: PropTypes.bool,
size: PropTypes.number,
title: PropTypes.string,
disabled: PropTypes.bool,
scrollable: PropTypes.bool,
status: ImmutablePropTypes.map,
isUserTouching: PropTypes.func,
onOpen: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
dropdownPlacement: PropTypes.string,
openDropdownId: PropTypes.number,
openedViaKeyboard: PropTypes.bool,
renderItem: PropTypes.func,
renderHeader: PropTypes.func,
onItemClick: PropTypes.func,
};
static defaultProps = {
title: 'Menu',
};
state = {
id: id++,
};
handleClick = ({ target, type }) => {
if (this.state.id === this.props.openDropdownId) {
this.handleClose();
} else {
const { top } = target.getBoundingClientRect();
const placement = top * 2 < innerHeight ? 'bottom' : 'top';
this.props.onOpen(this.state.id, this.handleItemClick, placement, type !== 'click');
}
}
handleClose = () => {
if (this.activeElement) {
this.activeElement.focus({ preventScroll: true });
this.activeElement = null;
}
this.props.onClose(this.state.id);
}
handleMouseDown = () => {
if (!this.state.open) {
this.activeElement = document.activeElement;
}
}
handleButtonKeyDown = (e) => {
switch(e.key) {
case ' ':
case 'Enter':
this.handleMouseDown();
break;
}
}
handleKeyPress = (e) => {
switch(e.key) {
case ' ':
case 'Enter':
this.handleClick(e);
e.stopPropagation();
e.preventDefault();
break;
}
}
handleItemClick = e => {
const { onItemClick } = this.props;
const i = Number(e.currentTarget.getAttribute('data-index'));
const item = this.props.items[i];
this.handleClose();
if (typeof onItemClick === 'function') {
e.preventDefault();
onItemClick(item, i);
} else if (item && typeof item.action === 'function') {
e.preventDefault();
item.action();
} else if (item && item.to) {
e.preventDefault();
this.context.router.history.push(item.to);
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
componentWillUnmount = () => {
if (this.state.id === this.props.openDropdownId) {
this.handleClose();
}
}
close = () => {
this.handleClose();
}
render () {
const {
icon,
items,
size,
title,
disabled,
loading,
scrollable,
dropdownPlacement,
openDropdownId,
openedViaKeyboard,
children,
renderItem,
renderHeader,
} = this.props;
const open = this.state.id === openDropdownId;
const button = children ? React.cloneElement(React.Children.only(children), {
ref: this.setTargetRef,
onClick: this.handleClick,
onMouseDown: this.handleMouseDown,
onKeyDown: this.handleButtonKeyDown,
onKeyPress: this.handleKeyPress,
}) : (
<IconButton
icon={icon}
title={title}
active={open}
disabled={disabled}
size={size}
ref={this.setTargetRef}
onClick={this.handleClick}
onMouseDown={this.handleMouseDown}
onKeyDown={this.handleButtonKeyDown}
onKeyPress={this.handleKeyPress}
/>
);
return (
<React.Fragment>
{button}
<Overlay show={open} placement={dropdownPlacement} target={this.findTarget}>
<DropdownMenu
items={items}
loading={loading}
scrollable={scrollable}
onClose={this.handleClose}
openedViaKeyboard={openedViaKeyboard}
renderItem={renderItem}
renderHeader={renderHeader}
onItemClick={this.handleItemClick}
/>
</Overlay>
</React.Fragment>
);
}
}
|
src/components/Dashboard.js
|
jainvabhi/PWD
|
import React from 'react';
import PropTypes from 'prop-types';
import Webcam from '../actions/webcam';
import TimeTable from './TimeTable';
const Dashboard = ({user, logout}) => {
Webcam.reset();
const userImage = {
backgroundImage: `url(${user.webcam.image})`,
};
return (
<div className="medical-portal dashboard">
<div className="medical-portal-header">
<div className="medical-logo">
<svg version="1.1" id="Layer_1" x="0px" y="0px" viewBox="0 0 309.665 309.665" xmlSpace="preserve" className="svgLogo">
<g xmlns="http://www.w3.org/2000/svg">
<path className="svgWhite" d="M309.665,94.734c0,15.903-10.797,29.301-25.496,33.562v136.653 c0,22.342-18.374,40.521-40.976,40.521c-21.984,0-39.968-17.269-40.879-38.83h-0.065v-1.594c0-0.033-0.033-0.065-0.033-0.098 h0.033v-81.173c0-13.106-10.797-23.773-24.033-23.773c-13.171,0-23.87,10.537-24.001,23.513v81.335 c0,22.374-18.407,40.554-40.976,40.554c-21.919,0-39.838-17.106-40.879-38.537h-0.098v-1.919c0-0.033,0-0.065,0-0.098 l-0.033-96.035C31.708,164.589,0,130.604,0,89.4V36.196c0-4.618,3.805-8.39,8.488-8.39h20.423v-15.22 c0-4.618,3.805-8.39,8.488-8.39h21.952c4.683,0,8.455,3.772,8.455,8.39v45.139c0,4.651-3.772,8.39-8.455,8.39H37.399 c-4.683,0-8.488-3.74-8.488-8.39V44.586H16.943V89.4c0,34.798,28.619,63.091,63.774,63.091s63.774-28.293,63.774-63.091V44.586 h-13.106v13.138c0,4.651-3.805,8.39-8.488,8.39h-21.952c-4.683,0-8.455-3.74-8.455-8.39V12.586c0-4.618,3.772-8.39,8.455-8.39 h21.952c4.683,0,8.488,3.772,8.488,8.39v15.22h21.561c4.683,0,8.488,3.772,8.488,8.39V89.4 c0,41.204-31.708,75.189-72.229,79.416v96.132c0.033,13.073,10.797,23.675,24.033,23.675s24.001-10.667,24.001-23.773v-81.075 c0-0.098,0-0.163,0-0.26v-2.732h0.163c1.528-20.944,19.22-37.562,40.814-37.562c22.602,0,40.977,18.212,40.977,40.554v81.27 c0.065,13.073,10.797,23.675,24.001,23.675c13.269,0,24.033-10.667,24.033-23.773v-135.97 c-16.098-3.252-28.228-17.366-28.228-34.245c0-19.285,15.838-34.96,35.318-34.96C293.795,59.774,309.665,75.449,309.665,94.734z M292.722,94.734c0-10.016-8.26-18.179-18.407-18.179s-18.374,8.163-18.374,18.179c0,10.049,8.228,18.179,18.374,18.179 C284.461,112.913,292.722,104.783,292.722,94.734z M114.442,49.334V20.976h-5.008v28.358H114.442z M50.863,49.334V20.976h-5.008 v28.358H50.863z"/>
<path className="svgBlue" d="M274.315,76.555c10.147,0,18.407,8.163,18.407,18.179c0,10.049-8.26,18.179-18.407,18.179 s-18.374-8.13-18.374-18.179C255.941,84.717,264.168,76.555,274.315,76.555z M283.974,94.734c0-5.268-4.325-9.529-9.659-9.529 c-5.333,0-9.626,4.26-9.626,9.529s4.293,9.561,9.626,9.561S283.974,100.002,283.974,94.734z"/>
<path className="svgWhite" d="M274.315,85.205c5.333,0,9.659,4.26,9.659,9.529s-4.325,9.561-9.659,9.561 c-5.333,0-9.626-4.293-9.626-9.561C264.689,89.465,268.981,85.205,274.315,85.205z"/>
<rect x="109.433" y="20.976" className="svgBlue" width="5.008" height="28.358"/>
<rect x="45.855" y="20.976" className="svgBlue" width="5.008" height="28.358"/>
</g>
</svg>
<h1>Welcome Dr. {user.webcam.name}</h1>
</div>
<button onClick={logout} className="logout">
Logout
<svg version="1.1" id="Capa_1" xmlns="http://www.w3.org/2000/svg" xmlnsXlink="http://www.w3.org/1999/xlink" x="0px" y="0px" viewBox="0 0 471.2 471.2" xmlSpace="preserve">
<g>
<path d="M227.619,444.2h-122.9c-33.4,0-60.5-27.2-60.5-60.5V87.5c0-33.4,27.2-60.5,60.5-60.5h124.9c7.5,0,13.5-6,13.5-13.5 s-6-13.5-13.5-13.5h-124.9c-48.3,0-87.5,39.3-87.5,87.5v296.2c0,48.3,39.3,87.5,87.5,87.5h122.9c7.5,0,13.5-6,13.5-13.5 S235.019,444.2,227.619,444.2z"/>
<path d="M450.019,226.1l-85.8-85.8c-5.3-5.3-13.8-5.3-19.1,0c-5.3,5.3-5.3,13.8,0,19.1l62.8,62.8h-273.9c-7.5,0-13.5,6-13.5,13.5 s6,13.5,13.5,13.5h273.9l-62.8,62.8c-5.3,5.3-5.3,13.8,0,19.1c2.6,2.6,6.1,4,9.5,4s6.9-1.3,9.5-4l85.8-85.8 C455.319,239.9,455.319,231.3,450.019,226.1z"/>
</g>
</svg>
</button>
</div>
<div className="content">
<div className="row">
<div className="col-sm-12 col-md-4">
<div className="card card-dashboard">
<div className="card-header userHeader" style={userImage}></div>
<div className="card-content">
<div className="card-content-member">
<h4 className="m-t-0">{user.webcam.name}</h4>
<p className="m-0"><i className="fa fa-map-marker"></i>{user.webcam.detail}</p>
</div>
<div className="card-content-summary">
<p>Specialties are Creative UI, HTML5, CSS3, Semantic Web, Responsive Layouts, Web Standards Compliance, Performance Optimization, Cross Device Troubleshooting.</p>
</div>
</div>
<div className="card-footer">
<div className="card-footer-stats">
<div>
<p>PROJECTS:</p><i className="fa fa-users"></i><span>241</span>
</div>
<div>
<p>MESSAGES:</p><i className="fa fa-coffee"></i><span>350</span>
</div>
<div>
<p>Last online</p><span className="stats-small">3 days ago</span>
</div>
</div>
<div className="card-footer-message">
<h4><i className="fa fa-comments"></i> Message me</h4>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-4">
<div className="card normal">
<div className="card-header">
<h2>Recently Viewed Patients</h2>
</div>
<div className="card-content patient-list">
<ul>
<li>David Caresoniwski</li>
<li>Deborah Smeerkat</li>
<li>Geregory Steinberg</li>
<li>Shantell Blakeson-Smith</li>
<li>Kanye Eastern</li>
</ul>
</div>
<div className="card-footer">
<div className="card-footer-message">
<h4><i className="fa fa-comments"></i> Look Up Patients </h4>
</div>
</div>
</div>
</div>
<div className="col-sm-12 col-md-4">
<div className="card normal">
<div className="card-header">
<h2>Recently Viewed Claims</h2>
</div>
<div className="card-content patient-list">
<ul>
<li><div>ID# 113478512-03 - Caresoniwski</div> <span className="badge badge-success">Processing</span></li>
<li><div>ID# 178890231-01 - Smeerkat</div> <span className="badge badge-paid">Paid</span></li>
<li><div>ID# 100021537-00 - Steinberg</div> <span className="badge badge-danger">Denied</span></li>
<li><div>ID# 100006942-03 - Blakeson-Smith</div> <span className="badge badge-default">Adjusted</span></li>
<li><div>ID# 178890231-00 - Eastern</div> <span className="badge badge-success">Processing</span></li>
</ul>
</div>
<div className="card-footer">
<div className="card-footer-message">
<h4><i className="fa fa-comments"></i> Manage Claims </h4>
</div>
</div>
</div>
</div>
</div>
</div>
<TimeTable />
</div>
);
};
Dashboard.propTypes = {
user: PropTypes.object,
logout: PropTypes.func,
};
export default Dashboard;
|
popup-study/components/StyledText.js
|
Morhaus/popupstudy
|
import React from 'react';
import { Text } from 'react-native';
export class MonoText extends React.Component {
render() {
return (
<Text
{...this.props}
style={[this.props.style, {fontFamily: 'space-mono'}]}
/>
);
}
}
|
internals/scaffold/testTemplate.js
|
jgunnison/react-boilerplate
|
module.exports = function (name) { return (`import React from 'react';
import { shallow } from 'enzyme';
import ${name} from './';
describe('Component: ${name}', () => {
it('It renders without errors', () => {
expect(
shallow(
<${name} text="Hello; World" />
).length,
).toEqual(1);
});
});
`)};
|
src/js/components/ui/FullWidthButton.js
|
nekuno/client
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import shouldPureComponentUpdate from 'react-pure-render/function';
export default class FullWidthButton extends Component {
shouldComponentUpdate = shouldPureComponentUpdate;
static propTypes = {
disabled: PropTypes.bool,
onClick : PropTypes.func,
};
render() {
const {disabled, onClick} = this.props;
return (
<button disabled={disabled} className="button button-fill button-big button-round" onClick={onClick}>
{this.props.children}
</button>
);
}
}
FullWidthButton.defaultProps = {
disabled: false,
onClick : () => {
},
};
|
src/components/Form/InlineInput/__tests__/StyledInlineInput.js
|
thegrinder/basic-styled-uikit
|
import React from 'react';
import { ThemeProvider } from 'styled-components';
import { render, cleanup } from '@testing-library/react';
import theme from '../../../../theme/theme';
import StyledInlineInput from '../StyledInlineInput';
const renderComponent = () =>
render(
<ThemeProvider theme={theme}>
<StyledInlineInput invalid={false} submitting={true} />
</ThemeProvider>
);
describe('<InlineInput />', () => {
afterEach(cleanup);
it('should render correctly', () => {
const {
container: { firstChild },
} = renderComponent();
expect(firstChild).toBeDefined();
});
it('should render <input> tag', () => {
const {
container: { firstChild },
} = renderComponent();
expect(firstChild.tagName).toEqual('INPUT');
});
});
|
app/jsx/gradezilla/default_gradebook/components/ComingSoonContent.js
|
venturehive/canvas-lms
|
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas 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, version 3 of the License.
*
* Canvas 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 React from 'react';
import SVGWrapper from 'jsx/shared/SVGWrapper';
import Typography from 'instructure-ui/lib/components/Typography';
import I18n from 'i18n!gradebook';
export default function ContentComingSoon () {
return (
<div className="ComingSoonContent__Container">
<div className="ComingSoonContent__Body">
<SVGWrapper url="/images/gift_closed.svg" />
<Typography size="xx-large" weight="light">{I18n.t('New goodies coming soon!')}</Typography>
<br />
<Typography weight="bold">{I18n.t('Check back in a little while.')}</Typography>
</div>
</div>
);
}
|
front/src/utils/ebetsCategories.js
|
ethbets/ebets
|
/* Copyright (C) 2017 ethbets
* All rights reserved.
*
* This software may be modified and distributed under the terms
* of the BSD license. See the LICENSE file for details.
*/
import React from 'react';
const ebetsCategories = [
{
name: 'Fighting',
subcategory: [
{
name: 'Boxing',
path: 'fighting/boxing'
},
{
name: 'MMA',
subcategory: [
{
name: 'UFC',
path: 'fighting/ufc'
},
{
name: 'Bellator',
path: 'fighting/bellator'
},
{
name: 'Invicta FC',
path: 'fighting/invictafc'
}
]
}
]
},
{
name: 'E-Sports',
subcategory: [
{
name: 'CS-GO',
path: 'esports/csgo'
},
{
name: 'League of Legends',
path: 'esports/lol'
},
// {
// name: 'League of Legends',
// subcategory: [
// {
// category: 'foo',
// subcategory: [
// {
// name: 'Bar',
// path: 'esports/lol/foo/bar'
// }
// ]
// },
// {
// name: 'EU League',
// path: 'esports/lol/eu_league'
// },
// {
// name: 'US League',
// path: 'esports/lol/us_league'
// },
// ]
// }
]
},
{
name: 'Football',
subcategory: [
{
name: 'UEFA Champions League',
path: 'football/uefachampionsleague'
},
{
name: 'UEFA Europa League',
path: 'football/uefaeuropaleague'
},
{
name: 'La Liga',
path: 'football/laliga'
},
{
name: 'Bundesliga',
path: 'football/bundesliga'
},
{
name: 'Brasileirão',
path: 'football/brasileirao'
},
{
name: 'Premier League',
path: 'football/premierleague'
},
{
name: 'Serie A',
path: 'football/seriea'
},
{
name: 'Ligue 1',
path: 'football/ligue1'
}
]
}
]
const getParsedCategories = () => {
const getCategoriesRecursive = (category) => {
if (!category.subcategory)
return [category];
return category.subcategory.map(cat => (
getCategoriesRecursive(cat)
)).reduce((a, b) => {
return a.concat(b);
}, []);
}
return ebetsCategories.map(categoryList => {
const cat = getCategoriesRecursive(categoryList);
return cat.map(category => {
return <div key={category.path}>
{category.name}
</div>
});
}).reduce((a, b) => {
return a.concat(b);
}, []);
}
export { getParsedCategories, ebetsCategories };
|
local_modules/react-component-redux/decorators/pure.js
|
pashaigood/react-component-redux
|
/**
* @author PBelugin
*/
import React from 'react';
import container from './container';
import {functionName} from '../helpers/functions';
/**
*
* @param {React.Component} Component
* @param {{actions: Object, state: Object, name: String, reducers: String, view: Function}} params
* @returns {Container}
*/
export default function (Component, params) {
if (! arguments[1]) {
params = Component;
Component = params.view;
delete params.view;
}
const state = params.state || params.reducers.state;
const actions = params.actions || params.reducers;
@container
class Container extends React.PureComponent {
state = state;
actions = actions;
constructor(props) {
super(props);
this.name = params.name || (functionName(Component));
if (! this.name) {
throw new Error('Component should have a name.');
}
}
render() {
return <Component {...Object.assign({}, this.props, this.state, this.actions)}/>;
}
}
return Container;
};
|
packages/material-ui-icons/src/PhotoSizeSelectLarge.js
|
dsslimshaddy/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PhotoSizeSelectLarge = props =>
<SvgIcon {...props}>
<path d="M21 15h2v2h-2v-2zm0-4h2v2h-2v-2zm2 8h-2v2c1 0 2-1 2-2zM13 3h2v2h-2V3zm8 4h2v2h-2V7zm0-4v2h2c0-1-1-2-2-2zM1 7h2v2H1V7zm16-4h2v2h-2V3zm0 16h2v2h-2v-2zM3 3C2 3 1 4 1 5h2V3zm6 0h2v2H9V3zM5 3h2v2H5V3zm-4 8v8c0 1.1.9 2 2 2h12V11H1zm2 8l2.5-3.21 1.79 2.15 2.5-3.22L13 19H3z" />
</SvgIcon>;
PhotoSizeSelectLarge = pure(PhotoSizeSelectLarge);
PhotoSizeSelectLarge.muiName = 'SvgIcon';
export default PhotoSizeSelectLarge;
|
docs/src/components/Homepage/Heading/index.js
|
rhalff/storybook
|
import React from 'react';
import './style.css';
import storybookLogo from '../../../design/homepage/storybook-logo.svg';
const Heading = () => (
<div id="heading" className="row">
<div className="col-xs-12">
<img className="sb-title" src={storybookLogo} alt="Storybook Logo" />
<h3 className="sb-tagline">
The UI Development Environment
<br />
You'll ♥️ to use
</h3>
</div>
</div>
);
export default Heading;
|
src/components/concent/steps/Step5.js
|
golemfactory/golem-electron
|
import React from 'react';
import Lottie from 'react-lottie';
import animData from './../../../assets/anims/Concent05';
const defaultOptions = {
loop: false,
autoplay: true,
animationData: animData,
rendererSettings: {
preserveAspectRatio: 'xMidYMid slice'
}
};
export default class Step5 extends React.Component {
constructor(props) {
super(props);
this.state = {
isStopped: false,
isPaused: false
};
}
render() {
return (
<div className="concent-onboarding__container-step">
<div className="concent-onboarding__section-image">
<Lottie options={defaultOptions}
isStopped={this.state.isStopped}
isPaused={this.state.isPaused}/>
</div>
<div className="concent-onboarding__desc">
<h2>FAQ</h2>
<span className="concent-info">
If you have any more questions regarding Concent Service and it's usage, please head over to our <a href="https://docs.golem.network/#/Products/Clay-Beta/Usage?id=concent-service">docs</a>, where we try to answer most of the questions you might have.
<br/>
<br/>
You can also talk with us via <a href="https://chat.golem.network">chat</a>.
</span>
</div>
</div>
);
}
}
|
example/MyMousetrap.js
|
georgeOsdDev/react-mousetrap-mixin
|
'use strict';
import React from 'react';
import {MousetrapMixin} from '../index.js';
let MyMousetrap = React.createClass({
mixins: [MousetrapMixin],
getInitialState(){
return {
color: 'red',
greenChecked: false
}
},
getMousetrap(){
return {
'y e l l o w':() => {
this.setState({
color: 'yellow'
});
},
'b l u e':() => {
this.setState({
color: 'blue'
});
}
};
},
onChange(event){
this.setState({
greenChecked: event.target.checked
}, () => {
event.target.blur();
if (this.state.greenChecked){
this.addMousetrap('g r e e n', () => {
this.setState({
color: 'green'
});
});
} else {
this.removeMousetrap('g r e e n');
}
});
},
render() {
let style = {
backgroundColor: this.state.color
}
return (
<div>
<div style={style}>
Type 'yellow' or 'blue'
</div>
<input type='checkbox' onChange={this.onChange} checked={this.state.greenChecked} />
Enable 'green'
</div>
);
}
});
export default MyMousetrap;
|
index.js
|
l-urence/react-native-autocomplete-input
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
FlatList,
Platform,
StyleSheet,
Text,
TextInput,
View,
ViewPropTypes as RNViewPropTypes
} from 'react-native';
// Keep this line for downwards compatibility with RN.
// eslint-disable-next-line react/forbid-foreign-prop-types
const ViewPropTypes = RNViewPropTypes || View.propTypes;
class Autocomplete extends Component {
static propTypes = {
...TextInput.propTypes,
/**
* These styles will be applied to the container which
* surrounds the autocomplete component.
*/
containerStyle: ViewPropTypes.style,
/**
* Assign an array of data objects which should be
* rendered in respect to the entered text.
*/
data: PropTypes.array,
/**
* Set to `true` to hide the suggestion list.
*/
hideResults: PropTypes.bool,
/*
* These styles will be applied to the container which surrounds
* the textInput component.
*/
inputContainerStyle: ViewPropTypes.style,
/*
* Set `keyboardShouldPersistTaps` to true if RN version is <= 0.39.
*/
keyboardShouldPersistTaps: PropTypes.oneOfType([
PropTypes.string,
PropTypes.bool
]),
/*
* These styles will be applied to the container which surrounds
* the result list.
*/
listContainerStyle: ViewPropTypes.style,
/**
* These style will be applied to the result list.
*/
listStyle: ViewPropTypes.style,
/**
* `onShowResults` will be called when list is going to
* show/hide results.
*/
onShowResults: PropTypes.func,
/**
* method for intercepting swipe on ListView. Used for ScrollView support on Android
*/
onStartShouldSetResponderCapture: PropTypes.func,
/**
* `renderItem` will be called to render the data objects
* which will be displayed in the result view below the
* text input.
*/
renderItem: PropTypes.func,
keyExtractor: PropTypes.func,
/**
* `renderSeparator` will be called to render the list separators
* which will be displayed between the list elements in the result view
* below the text input.
*/
renderSeparator: PropTypes.func,
/**
* renders custom TextInput. All props passed to this function.
*/
renderTextInput: PropTypes.func,
flatListProps: PropTypes.object
};
static defaultProps = {
data: [],
keyboardShouldPersistTaps: 'always',
onStartShouldSetResponderCapture: () => false,
renderItem: ({ item }) => <Text>{item}</Text>,
renderSeparator: null,
renderTextInput: props => <TextInput {...props} />,
flatListProps: {}
};
constructor(props) {
super(props);
this.resultList = null;
this.textInput = null;
this.onRefListView = this.onRefListView.bind(this);
this.onRefTextInput = this.onRefTextInput.bind(this);
this.onEndEditing = this.onEndEditing.bind(this);
}
onEndEditing(e) {
this.props.onEndEditing && this.props.onEndEditing(e);
}
onRefListView(resultList) {
this.resultList = resultList;
}
onRefTextInput(textInput) {
this.textInput = textInput;
}
/**
* Proxy `blur()` to autocomplete's text input.
*/
blur() {
const { textInput } = this;
textInput && textInput.blur();
}
/**
* Proxy `focus()` to autocomplete's text input.
*/
focus() {
const { textInput } = this;
textInput && textInput.focus();
}
/**
* Proxy `isFocused()` to autocomplete's text input.
*/
isFocused() {
const { textInput } = this;
return textInput && textInput.isFocused();
}
renderResultList() {
const {
data,
listStyle,
renderItem,
keyExtractor,
renderSeparator,
keyboardShouldPersistTaps,
flatListProps,
onEndReached,
onEndReachedThreshold
} = this.props;
return (
<FlatList
ref={this.onRefListView}
data={data}
keyboardShouldPersistTaps={keyboardShouldPersistTaps}
renderItem={renderItem}
keyExtractor={keyExtractor}
renderSeparator={renderSeparator}
onEndReached={onEndReached}
onEndReachedThreshold={onEndReachedThreshold}
style={[styles.list, listStyle]}
{...flatListProps}
/>
);
}
renderTextInput() {
const { renderTextInput, style } = this.props;
const props = {
style: [styles.input, style],
ref: this.onRefTextInput,
onEndEditing: this.onEndEditing,
...this.props
};
return renderTextInput(props);
}
render() {
const {
data,
containerStyle,
hideResults,
inputContainerStyle,
listContainerStyle,
onShowResults,
onStartShouldSetResponderCapture
} = this.props;
const showResults = data.length > 0;
// Notify listener if the suggestion will be shown.
onShowResults && onShowResults(showResults);
return (
<View style={[styles.container, containerStyle]}>
<View style={[styles.inputContainer, inputContainerStyle]}>
{this.renderTextInput()}
</View>
{!hideResults && (
<View
style={listContainerStyle}
onStartShouldSetResponderCapture={onStartShouldSetResponderCapture}
>
{showResults && this.renderResultList()}
</View>
)}
</View>
);
}
}
const border = {
borderColor: '#b9b9b9',
borderRadius: 1,
borderWidth: 1
};
const androidStyles = {
container: {
flex: 1
},
inputContainer: {
...border,
marginBottom: 0
},
list: {
...border,
backgroundColor: 'white',
borderTopWidth: 0,
margin: 10,
marginTop: 0
}
};
const iosStyles = {
container: {
zIndex: 1
},
inputContainer: {
...border
},
input: {
backgroundColor: 'white',
height: 40,
paddingLeft: 3
},
list: {
...border,
backgroundColor: 'white',
borderTopWidth: 0,
left: 0,
position: 'absolute',
right: 0
}
};
const styles = StyleSheet.create({
input: {
backgroundColor: 'white',
height: 40,
paddingLeft: 3
},
...Platform.select({
android: { ...androidStyles },
ios: { ...iosStyles }
})
});
export default Autocomplete;
|
011/src/components/app.js
|
StephenGrider/RallyCodingWeekly
|
import React, { Component } from 'react';
import { Link } from 'react-router';
export default class App extends Component {
render() {
return (
<div>
<h4>App</h4>
<Link to="/users">Users</Link>
<hr />
{this.props.children}
</div>
);
}
}
|
src/components/login/login.js
|
ndxm/nd-react-scaffold
|
/**
* Created by hjx on 11/3/2015.
*/
import styles from './login.css';
import React from 'react';
import Router from 'react-router';
const { Navigation } = Router;
export default React.createClass({
mixins: [ Navigation ],
getInitialState: function () {
return {
username: '',
password: '',
showPassword: false,
userClick: false,
loginErr: '',
isFocusPassword: false
};
},
componentDidMount() {
if (this.props.isLoggedIn) {
this.props.redirect();
}
},
componentWillReceiveProps(nextProps) {
if (nextProps.isLoggedIn) {
nextProps.redirect();
}
},
handleUsernameChange: function (e) {
this.setState({
username: e.currentTarget.value.trim()
});
},
handlePasswordChange: function (e) {
this.setState({
password: e.currentTarget.value.trim()
});
},
handleToggle: function (e) {
this.setState({
showPassword: e.currentTarget.checked
});
},
handleFormSubmit: function (e) {
e.preventDefault();
this.setState({
userClick: true,
loginErr: ''
});
if (this.state.username === '' || this.state.password === '') {
return;
}
this.props.onLogin({
name: (/@/.test(this.state.username)?this.state.username:this.state.username + '@ndtest'),
password: this.state.password
});
},
blurPassword: function () {
this.setState({
isFocusPassword: false
});
},
focusPassword: function () {
if (this.state.showPassword) {
return;
}
this.setState({
isFocusPassword: true
});
},
render: function () {
let errForUsername, errForPassword;
if (this.state.userClick === true) {
errForUsername = this.state.username === '' ? '请输入用户名' : '';
errForPassword = this.state.password === '' ? '请输入密码' : '';
}
return (
<div>
<div className={styles.loginBody}>
<div className={styles.loginRoad}></div>
</div>
<div className={styles.loginPanel}>
<div
className={styles.loginHi + ' ' + (this.state.isFocusPassword?styles.focusPassword:'')}></div>
<h1 className={styles.siteTitle}>微博</h1>
<form noValidate onSubmit={this.handleFormSubmit} className={`${styles['c-form']}`}>
<div>
<div className={`${styles['c-form__input']}`}>
<span className={styles['c-form__label']+' '+styles['c-form-name']}></span>
<input
className={errForUsername ? `${styles['c-form__inputBox']} ${styles['c-form__inputBox--err']}` : `${styles['c-form__inputBox']}`}
placeholder="工号/学号"
type='text' value={this.state.username}
onChange={this.handleUsernameChange}/>
<span className={`${styles['c-form__err']}`}>{errForUsername}</span>
</div>
<div className={`${styles['c-form__input']}`}>
<span className={styles['c-form__label'] +' '+styles['c-form-pwd']}></span>
<input
className={errForPassword ? `${styles['c-form__inputBox']} ${styles['c-form__inputBox--err']}` : `${styles['c-form__inputBox']}`}
type={this.state.showPassword ? 'text' : 'password'} value={this.state.password}
placeholder="密码"
onFocus={this.focusPassword}
onBlur={this.blurPassword}
onChange={this.handlePasswordChange}/>
<span className={`${styles['c-form__err']}`}>{errForPassword}</span>
</div>
<div className={`${styles['c-form__input']}`}>
<label><input type='checkbox' checked={this.state.showPassword}
onChange={this.handleToggle}/>显示密码</label>
</div>
</div>
<div className={styles.loginFormBtm}>
<span className={styles['c-form__err']}>{this.props.loginErr}</span>
<input type='submit' value='登录' className={`${styles['c-form__btn']}`}/>
</div>
</form>
</div>
</div>
);
}
});
|
blueprints/layout/files/__test__/layouts/__name__Layout.spec.js
|
simonvpe/borrkoll-react
|
import React from 'react'
describe('(Layout) <%= pascalEntityName %>', () => {
it('should exist', () => {
})
})
|
packages/demos/demo/src/components/Project/card.js
|
garth/cerebral
|
import React from 'react'
import { connect } from '@cerebral/react'
import { signal } from 'cerebral/tags'
import projectWithDetails from '../../compute/projectWithDetails'
import { displayElapsed } from '../../helpers/dateTime'
export default connect(
{
item: projectWithDetails,
penClick: signal`projects.penClicked`,
trashClick: signal`projects.trashClicked`,
},
function ProjectCard({ item, itemKey, penClick, trashClick }) {
return (
<div className="card">
<div className="card-content">
<div className="media">
<div className="media-left">
<span className="icon is-medium">
<i className="fa fa-folder" />
</span>
</div>
<div className="media-content">
<p className="title is-5">
{item.name}
</p>
<p className="subtitle is-6">{item.client && item.client.name}</p>
</div>
<div className="media-right">
{displayElapsed(item.elapsed)}
</div>
</div>
<div className="content">
{item.notes}
</div>
<nav className="level" onClick={e => e.stopPropagation()}>
<div className="level-left" />
<div className="level-right">
{item.$isDefaultItem !== true &&
<a
className="level-item"
onClick={() => penClick({ key: item.key })}
>
<span className="icon is-small">
<i className="fa fa-pencil" />
</span>
</a>}
{item.$isDefaultItem !== true &&
<a
className="level-item"
onClick={() => trashClick({ key: item.key })}
>
<span className="icon is-small">
<i className="fa fa-trash" />
</span>
</a>}
</div>
</nav>
</div>
</div>
)
}
)
|
docs/src/app/components/pages/components/TimePicker/Page.js
|
ngbrown/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import timePickerReadmeText from './README';
import TimePickerExampleSimple from './ExampleSimple';
import timePickerExampleSimpleCode from '!raw!./ExampleSimple';
import TimePickerExampleComplex from './ExampleComplex';
import timePickerExampleComplexCode from '!raw!./ExampleComplex';
import TimePickerExampleInternational from './ExampleInternational';
import timePickerExampleInternationalCode from '!raw!./ExampleInternational';
import timePickerCode from '!raw!material-ui/TimePicker/TimePicker';
const descriptions = {
simple: 'Time Picker supports 12 hour and 24 hour formats. In 12 hour format the AM and PM indicators toggle the ' +
'selected time period. You can also disable the Dialog passing true to the disabled property.',
controlled: '`TimePicker` can be used as a controlled component.',
localised: 'The buttons can be localised using the `cancelLabel` and `okLabel` properties.',
};
const TimePickersPage = () => (
<div>
<Title render={(previousTitle) => `Time Picker - ${previousTitle}`} />
<MarkdownElement text={timePickerReadmeText} />
<CodeExample
title="Simple examples"
description={descriptions.simple}
code={timePickerExampleSimpleCode}
>
<TimePickerExampleSimple />
</CodeExample>
<CodeExample
title="Controlled examples"
description={descriptions.controlled}
code={timePickerExampleComplexCode}
>
<TimePickerExampleComplex />
</CodeExample>
<CodeExample
title="Localised example"
description={descriptions.localised}
code={timePickerExampleInternationalCode}
>
<TimePickerExampleInternational />
</CodeExample>
<PropTypeDescription code={timePickerCode} />
</div>
);
export default TimePickersPage;
|
RelayExample/src/Book.js
|
davidpaulmcintyre/graphql-stockticker
|
import React from 'react';
import Relay from 'react-relay';
import './Book.css';
function Book({ book }) {
console.log(book.image)
return (
<div className="book">
<img src={book.image} />
<div>{book.title}</div>
</div>
);
}
export default Relay.createContainer(Book, {
fragments: {
book: () => Relay.QL`
fragment on Book {
title
image
}
`,
},
});
|
src/ui/auth/RegisterScreen.js
|
exponentjs/xde
|
/**
* @flow
*/
import React from 'react';
import RegisterForm from './components/RegisterForm';
import { actions } from 'xde/state';
import { connectToData } from 'xde/state/utils';
import type { AppActions, AppState } from 'xde/state/types';
import type { UserOrLegacyUser } from 'xdl/build/User';
import type { RegisterFormData } from './components/RegisterForm';
type Props = {
user: ?UserOrLegacyUser,
isRegistering: boolean,
actions: AppActions,
};
class RegisterScreen extends React.Component {
props: Props;
static data = ({ auth }: AppState) => ({
user: auth.user,
isRegistering: auth.pendingAction === 'REGISTER',
});
render() {
return (
<RegisterForm
user={this.props.user}
isRegistering={this.props.isRegistering}
onRegister={this._handleRegister}
onLogout={this._handleLogout}
/>
);
}
_handleLogout = () => {
this.props.actions.auth.logout();
};
_handleRegister = (formData: RegisterFormData) => {
if (this.props.isRegistering) {
return;
}
this.props.actions.auth.register({
...formData,
});
};
}
export default connectToData(actions)(RegisterScreen);
|
src/components/HomeScreen.js
|
teamstrobe/mancreact-client
|
import React, { Component } from 'react';
import apiFetch from '../apiFetch';
import { eventsURI } from '../config/urls';
import UpcomingEventHero from './UpcomingEventHero';
import PreviousMeetupsList from './PreviousMeetupsList';
import Spinner from './Spinner';
class HomeScreen extends Component {
state = {
events: null,
loading: false,
};
componentWillMount() {
this.fetchData();
}
async fetchData() {
this.setState({
loading: true,
});
const events = await this.getEvents();
this.setState({
events,
loading: false,
});
}
async getEvents() {
return await apiFetch(eventsURI());
}
render() {
const { events, loading } = this.state;
let upcomingEvent;
let previousEvents;
if (events != null) {
upcomingEvent = events.filter(event => event.status === 'upcoming')[0];
previousEvents = events.filter(event => event.status === 'past');
}
return (
<div>
{loading
? <Spinner />
: <div>
{upcomingEvent && <UpcomingEventHero event={upcomingEvent} />}
{previousEvents &&
<PreviousMeetupsList events={previousEvents} />}
</div>}
</div>
);
}
}
export default HomeScreen;
|
src/containers/CreateCategory.js
|
nickeblewis/walkapp
|
/**
* Component for category creation
*/
import React from 'react'
import { withRouter } from 'react-router'
import { graphql } from 'react-apollo'
import gql from 'graphql-tag'
class CreateCategory extends React.Component {
static propTypes = {
router: React.PropTypes.object,
addName: React.PropTypes.func,
}
state = {
name: '',
}
render () {
return (
<div className='w-100 pa4 flex justify-center'>
<div style={{ maxWidth: 400 }} className=''>
<input
className='w-100 pa3 mv2'
value={this.state.name}
placeholder='Name'
onChange={(e) => this.setState({name: e.target.value})}
/>
{this.state.name &&
<button className='pa3 bg-black-10 bn dim ttu pointer' onClick={this.handleCategory}>Category</button>
}
</div>
</div>
)
}
handleCategory = () => {
const {name} = this.state
this.props.addCategory({ name })
.then(() => {
this.props.router.push('/categories')
})
}
}
const addMutation = gql`
mutation addCategory($name: String!) {
createCategory(name: $name) {
id
name
}
}
`
const CategoryWithMutation = graphql(addMutation, {
props: ({ ownProps, mutate }) => ({
addCategory: ({ name }) =>
mutate({
variables: { name },
updateQueries: {
allCategories: (state, { mutationResult }) => {
const newCategory = mutationResult.data.createCategory
return {
allCategories: [...state.allCategories, newCategory]
}
},
},
})
})
})(withRouter(CreateCategory))
export default CategoryWithMutation
|
assets/TopNav.js
|
rmccue/new-list-tables
|
import React from 'react';
const PageLink = props => {
const { children, isActive } = props;
if ( ! isActive ) {
return <span className='tablenav-pages-navspan'>{ children }</span>;
}
// Remove the isActive prop.
const otherProps = Object.assign( {}, props );
delete otherProps.isActive;
return <a { ...otherProps } />;
};
PageLink.propTypes = {
isActive: React.PropTypes.bool.isRequired,
};
export default class TopNav extends React.Component {
constructor(props) {
super(props);
this.state = {
page: null,
};
}
componentWillReceiveProps( nextProps ) {
// If receiving page update, wipe input.
if ( nextProps.page !== this.props.page ) {
this.setState({ page: null });
}
}
render() {
const { page, total, totalPages, onJump } = this.props;
return <form
className="tablenav top"
onSubmit={ e => { e.preventDefault(); onJump( this.state.page ) } }
>
<h2 className="screen-reader-text">Comments list navigation</h2>
{ totalPages > 1 ?
<div className="tablenav-pages">
<span className="displaying-num">{ total } items</span>
<span className="pagination-links">
<PageLink
className="first-page"
isActive={ page !== 1 }
onClick={ () => onJump( 1 ) }
>
<span className="screen-reader-text">First page</span>
<span aria-hidden="true">«</span>
</PageLink>
{ ' ' }
<PageLink
className="prev-page"
isActive={ page !== 1 }
onClick={ () => onJump( page - 1 ) }
>
<span className="screen-reader-text">Previous page</span>
<span aria-hidden="true">‹</span>
</PageLink>
{ ' ' }
<span className="paging-input">
<label className="screen-reader-text">Current Page</label>
<input
aria-describedby="table-paging"
className="current-page"
id="current-page-selector"
name="paged"
size="2"
type="text"
value={ this.state.page === null ? page : this.state.page }
onChange={ e => this.setState({ page: e.target.value }) }
/>
<span className="tablenav-paging-text">
{ ' of ' }
<span className="total-pages">{ totalPages }</span>
</span>
</span>
{ ' ' }
<PageLink
className="next-page"
isActive={ page !== totalPages }
onClick={ () => onJump( page + 1 ) }
>
<span className="screen-reader-text">Next page</span>
<span aria-hidden="true">›</span>
</PageLink>
{ ' ' }
<PageLink
className="last-page"
isActive={ page !== totalPages }
onClick={ () => onJump( totalPages ) }
>
<span className="screen-reader-text">Last page</span>
<span aria-hidden="true">»</span>
</PageLink>
</span>
</div>
: null }
<br className="clear" />
</form>;
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.