path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
client/views/admin/oauthApps/OAuthAppsRoute.js
|
VoiSmart/Rocket.Chat
|
import React from 'react';
import NotAuthorizedPage from '../../../components/NotAuthorizedPage';
import { usePermission } from '../../../contexts/AuthorizationContext';
import OAuthAppsPage from './OAuthAppsPage';
export default function MailerRoute() {
const canAccessOAuthApps = usePermission('manage-oauth-apps');
if (!canAccessOAuthApps) {
return <NotAuthorizedPage />;
}
return <OAuthAppsPage />;
}
|
web/src/layout/Breadcrumb.js
|
caicloud/cyclone
|
import React from 'react';
import { Link } from 'react-router-dom';
import { Breadcrumb } from 'antd';
import PropTypes from 'prop-types';
const mainModules = [
'overview',
'projects',
'stageTemplate',
'resource',
'integration',
'workflows',
];
const operations = ['update', 'add'];
/**
* define the route rules
* list page => /projects
* project detail => /projects/:projectId
* update project => /projects/:projectId/update
* add project => /projects/add
*/
const BreadcrumbComponent = ({ location }) => {
const pathSnippets = location.pathname.split('/').filter(i => i);
const extraBreadcrumbItems = pathSnippets.map((path, index) => {
const url = `/${pathSnippets.slice(0, index + 1).join('/')}`;
let text = path;
if (_.includes(mainModules, path)) {
text = <Link to={url}>{intl.get(`sideNav.${path}`)}</Link>;
} else if (_.includes(operations, path)) {
text = intl.get(`operation.${path}`);
} else if (_.includes(mainModules, pathSnippets[index - 1])) {
text = <Link to={url}>{path}</Link>;
}
return <Breadcrumb.Item key={url}>{text}</Breadcrumb.Item>;
});
return (
<Breadcrumb style={{ marginBottom: '12px' }}>
{extraBreadcrumbItems}
</Breadcrumb>
);
};
BreadcrumbComponent.propTypes = {
location: PropTypes.object,
};
export default BreadcrumbComponent;
|
roguelike-dungeon-crawler-game/src/App.js
|
mstoyanovca/front-end
|
import React, { Component } from 'react';
import Dungeon from './Dungeon';
import Header from './Header';
import LossModal from './LossModal';
import WinModal from './WinModal';
const weapons = ["stick", "brass knuckles", "serrated dagger", "katana", "reaper's scythe", "large trout"];
//tune the game here; you need 240 health points to beet the boss:
const attackValues = [7, 26, 64, 88, 200, 300]; // per dungeon/weapon
// board size in cells:
const boardWidth = 80;
const boardHeight = 80;
// 20 gives good board density:
const numberOfChambers = 20;
// nextLevelPoints = 60, add 60 for each level;
export default class App extends Component {
constructor(props) {
super(props);
this.state = {health: 100, weapon: weapons[0], attack: attackValues[0], level: 0, nextLevelPoints: 60, dungeon: 0, cells: [], cursor: {},
showLossModal: false, showWinModal: false, dark: false};
this.updateCells = this.updateCells.bind(this);
this.move = this.move.bind(this);
this.updateHealth = this.updateHealth.bind(this);
this.updateWeapon = this.updateWeapon.bind(this);
this.updateAttack = this.updateAttack.bind(this);
this.updateLevel = this.updateLevel.bind(this);
this.updateNextLevelPoints = this.updateNextLevelPoints.bind(this);
this.updateDungeon = this.updateDungeon.bind(this);
this.updateShowLossModal = this.updateShowLossModal.bind(this);
this.updateShowWinModal = this.updateShowWinModal.bind(this);
this.startNewDungeon = this.startNewDungeon.bind(this);
this.startNewGame = this.startNewGame.bind(this);
this.updateDark = this.updateDark.bind(this);
}
componentDidMount() {
let cells = this.createEmptyBoard();
cells = this.createDungeon(cells);
let cellsWithCursor = this.createContent(cells, this.state.dungeon);
this.setState({cells: cellsWithCursor.cells, cursor: cellsWithCursor.cursor});
}
createEmptyBoard() {
let cells = [];
for (let i = 0; i < boardHeight; i++) {
cells[i] = [];
for (let j = 0; j < boardWidth; j++) {
cells[i][j] = {id: j + i * boardWidth, row: i, column: j, className: "cell"};
}
}
return cells;
}
createDungeon(cells) {
let chambers = [];
let doors = [];
for (let i = 0; i < numberOfChambers; i++) {
if(i === 0) {
let chamber = this.createChamber(true);
chambers.push(chamber);
cells = this.drawChamber(chamber, {x: chamber.x, y: chamber.y}, cells);
} else {
let chamber = this.createChamber(false);
for(let j = 0; j < i; j++) {
let chamberWithDoor = this.attachToTheRight(chambers[j], chamber, cells);
if(chamberWithDoor.chamber.x >= 0) {
chambers.push(chamberWithDoor.chamber);
doors.push(chamberWithDoor.door);
cells = this.drawChamber(chamberWithDoor.chamber, chamberWithDoor.door, cells);
break;
}
chamberWithDoor = this.attachToTheBottom(chambers[j], chamber, cells);
if(chamberWithDoor.chamber.y >= 0) {
chambers.push(chamberWithDoor.chamber);
doors.push(chamberWithDoor.door);
cells = this.drawChamber(chamberWithDoor.chamber, chamberWithDoor.door, cells);
break;
}
}
}
}
return cells;
}
createChamber(isFirst) {
// random size from 6 to 18 by 6 to 18 cells:
let width = Math.floor(Math.random() * 13) + 6;
let height = Math.floor(Math.random() * 13) + 6;
// chambers 2 and up to be positioned later:
let x = -1;
let y = -1;
if(isFirst) {
// position the first chamber randomly in the top left corner:
x = Math.floor(Math.random() * 21);
y = Math.floor(Math.random() * 11);
}
return {x: x, y: y, width: width, height: height};
}
attachToTheRight(previousChamber, chamber, cells) {
// try to attach to the right of an existing chamber:
chamber.x = previousChamber.x + previousChamber.width + 1;
let possibleYs = [];
for (let i = previousChamber.y - chamber.height + 1; i < previousChamber.y + previousChamber.height; i++) {
if (this.checkAvailability(chamber.x, i, chamber.width, chamber.height, cells)) {
possibleYs.push(i);
}
}
if (possibleYs.length > 0) {
let index = Math.floor(Math.random() * possibleYs.length);
chamber.y = possibleYs[index];
} else {
chamber.x = -1;
return {chamber, undefined};
}
// create a door between the chambers:
let overlappingYs = [];
for (let i = chamber.y; i < chamber.y + chamber.height; i++) {
if (i >= previousChamber.y && i < previousChamber.y + previousChamber.height) {
overlappingYs.push(i);
}
}
let index = Math.floor(Math.random() * overlappingYs.length);
let door = { x: chamber.x - 1, y: overlappingYs[index] };
return {chamber, door};
}
attachToTheBottom(previousChamber, chamber, cells) {
// try to attach to the bottom of an existing chamber:
chamber.y = previousChamber.y + previousChamber.height + 1;
let possibleXs = [];
for (let i = previousChamber.x - chamber.width + 1; i < previousChamber.x + previousChamber.width; i++) {
if (this.checkAvailability(i, chamber.y, chamber.width, chamber.height, cells)) {
possibleXs.push(i);
}
}
if (possibleXs.length > 0) {
let index = Math.floor(Math.random() * possibleXs.length);
chamber.x = possibleXs[index];
} else {
chamber.y = -1;
return {chamber, undefined};
}
// create a door between the chambers:
let overlappingXs = [];
for (let i = chamber.x; i < chamber.x + chamber.width; i++) {
if (i >= previousChamber.x && i < previousChamber.x + previousChamber.width) {
overlappingXs.push(i);
}
}
let index = Math.floor(Math.random() * overlappingXs.length);
let door = { x: overlappingXs[index], y: chamber.y - 1 };
return {chamber, door};
}
checkAvailability(x, y, width, height, cells) {
// make sure the new chamber is within the board:
if (x < 0 || x + width > boardWidth || y < 0 || y + height > boardHeight) return false;
// check if the cells that are going to be taken are free:
for (let i = y; i < y + height; i++) {
for (let j = x; j < x + width; j++) {
if (cells[i][j].className.includes("empty")) return false;
}
}
return true;
}
drawChamber(chamber, door, cells) {
for (let i = chamber.y; i < chamber.y + chamber.height; i++) {
for (let j = chamber.x; j < chamber.x + chamber.width; j++) {
if(cells[i][j].className === "cell") cells[i][j].className += " empty";
}
}
if(cells[door.y][door.x].className === "cell") cells[door.y][door.x].className += " empty"
return cells;
}
createContent(cells, dungeon) {
let emptyCells = [];
for (let i = 0; i < boardHeight; i++) {
for (let j = 0; j < boardWidth; j++) {
if (cells[i][j].className.includes("empty")) emptyCells.push(cells[i][j]);
}
}
// create the cursor:
let index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "cursor");
let cursor = {x: emptyCells[index].column, y: emptyCells[index].row};
emptyCells.splice(index, 1);
// create the weapon:
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "weapon");
emptyCells.splice(index, 1);
// create the stairs to the next dungeon:
if (dungeon < 4) {
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "stairs");
emptyCells.splice(index, 1);
}
// create the health items:
for (let i = 0; i < 5; i++) {
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "health");
emptyCells.splice(index, 1);
}
// create the enemies:
for (let i = 0; i < 5; i++) {
index = Math.floor(Math.random() * emptyCells.length);
cells[emptyCells[index].row][emptyCells[index].column].className = cells[emptyCells[index].row][emptyCells[index].column].className.replace("empty", "enemy");
emptyCells.splice(index, 1);
}
// create the boss:
if (dungeon === 4) {
let bosses = [{}];
for (let i = 0; i < boardHeight - 1; i++) {
for (let j = 0; j < boardWidth - 1; j++) {
if (cells[i][j].className.includes("empty") &&
cells[i][j + 1].className.includes("empty") &&
cells[i + 1][j].className.includes("empty") &&
cells[i + 1][j + 1].className.includes("empty")) {
bosses.push([cells[i][j], cells[i][j + 1], cells[i + 1][j], cells[i + 1][j + 1]]);
}
}
}
// pick a square randomly:
index = Math.floor(Math.random() * bosses.length);
for (let i = 0; i < bosses[index].length; i++) {
cells[bosses[index][i].row][bosses[index][i].column].className = "cell boss";
}
}
return {cells: cells, cursor: cursor};
}
updateCells(cells) {
this.setState({cells: cells});
}
move(cells, cursor) {
this.setState({cells: cells, cursor: cursor});
}
updateHealth(health) {
this.setState({health: health});
}
updateWeapon(weapon, attack) {
this.setState({weapon: weapon, attack: attack});
}
updateAttack(attack) {
this.setState({attack: attack});
}
updateLevel(level) {
this.setState({level: level});
}
updateNextLevelPoints(nextLevelPoints) {
this.setState({nextLevelPoints: nextLevelPoints});
}
updateDungeon(dungeon) {
this.setState({dungeon: dungeon});
}
updateDark(dark) {
this.setState({dark: dark});
}
updateShowLossModal(show) {
this.setState({showLossModal: show});
}
updateShowWinModal(show) {
this.setState({showWinModal: show});
}
startNewDungeon() {
let cells = this.createEmptyBoard();
cells = this.createDungeon(cells);
let cellsWithCursor = this.createContent(cells, this.state.dungeon);
this.setState({cells: cellsWithCursor.cells, cursor: cellsWithCursor.cursor, showLossModal: false, showWinModal: false});
}
startNewGame() {
let cells = this.createEmptyBoard();
cells = this.createDungeon(cells);
let cellsWithCursor = this.createContent(cells, 0);
this.setState({health: 100, weapon: weapons[0], attack: attackValues[0], level: 0, nextLevelPoints: 60, dungeon: 0, cells: cellsWithCursor.cells, cursor: cellsWithCursor.cursor,
showLossModal: false, showWinModal: false, dark: false});
}
render() {
return (
<div>
<Header health={this.state.health} weapon={this.state.weapon} attack={this.state.attack} level={this.state.level} nextLevelPoints={this.state.nextLevelPoints}
dungeon={this.state.dungeon} cells={this.state.cells} cursor={this.state.cursor} dark={this.state.dark} updateCells={this.updateCells} updateDark={this.updateDark} />
<Dungeon boardWidth={boardWidth} boardHeight={boardHeight} health={this.state.health} weapons={weapons} weapon={this.state.weapon} attackValues={attackValues}
attack={this.state.attack} level={this.state.level} nextLevelPoints={this.state.nextLevelPoints} dungeon={this.state.dungeon} cells={this.state.cells}
cursor={this.state.cursor} dark={this.state.dark} move={this.move} updateHealth={this.updateHealth} updateWeapon={this.updateWeapon} updateAttack={this.updateAttack}
updateLevel={this.updateLevel} updateNextLevelPoints={this.updateNextLevelPoints} updateDungeon={this.updateDungeon} updateShowLossModal={this.updateShowLossModal}
updateShowWinModal={this.updateShowWinModal} startNewDungeon={this.startNewDungeon} />
<LossModal show={this.state.showLossModal} startNewGame={this.startNewGame} />
<WinModal show={this.state.showWinModal} startNewGame={this.startNewGame} />
</div>
);
}
}
|
packages/react-scripts/fixtures/kitchensink/src/features/env/ShellEnvVariables.js
|
RobzDoom/frame_trap
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react';
export default () => (
<span id="feature-shell-env-variables">
{process.env.REACT_APP_SHELL_ENV_MESSAGE}.
</span>
);
|
src/ContractRows.js
|
simoneas02/contracts-list
|
import React, { Component } from 'react';
import update from 'immutability-helper';
import edit from './icons/edit.svg'
import save from './icons/save.svg'
import close from './icons/close.svg'
class ContractRows extends Component {
constructor(props) {
super(props);
this.state = {
contract: [],
isEditable: false,
isVisible: false
};
};
showContract(contractNumber) {
const contract = this.props.list.filter((contract) => {
return (contractNumber === contract.codigo);
});
this.setState({ contract: contract[0] });
this.setState({ isVisible: true });
};
updateInput(columnName) {
const contract = this.state.contract;
const value = this.refs[columnName];
const contractUpdated = update(contract, { $merge: {[columnName]: value.value }} );
this.setState({ contract: contractUpdated })
};
editList() {
this.setState({ isEditable: true });
};
closeList() {
this.setState({ isVisible: false });
this.setState({ isEditable: false });
};
render() {
const contractsList = this.props.list.map((contract)=> {
const columns = this.props.columns;
const columnsList = columns.map((column) => {
if(column.isActive && column.name !== "key") {
return (
<td className="column-cell" key = { contract[column.name] }>{ contract[column.name] }</td>
);
}
return null;
});
return (
<tr className="contract-row" key = { contract.codigo } onClick={ this.showContract.bind(this, contract.codigo) }>{ columnsList }</tr>
)
});
const itemsList = this.props.columns.map((item) => {
if(!this.state.isEditable){
return (
<tr>
<td>{ item.name }</td>
<td>{ this.state.contract[item.name] }</td>
</tr>
)
} else {
return (
<tr>
<td>
{ item.name }:
</td>
<td>
<input type="text"
ref={ item.name }
value={ this.state.contract[item.name] }
onChange={ this.updateInput.bind(this, item.name) } />
</td>
</tr>
);
};
});
const contractDialog = () => {
if(this.state.isVisible) {
return (
<div className="contract-dialog">
<div className="controlDialog">
<button className="buttom-icon" onClick={ this.editList.bind(this) }>
<img src={ edit }/>
</button>
<button className="buttom-icon" onClick={ this.closeList.bind(this) }>
<img src={ close }/>
</button>
<button className="buttom-icon" onClick={ this.props.updatelist.bind(this, this.state.contract) }>
<img src={ save }/>
</button>
</div>
<table>
{ itemsList }
</table>
</div>
);
};
};
return(
<tbody>
{ contractsList }
{ contractDialog() }
</tbody>
);
}
}
export default ContractRows;
|
components/utils/PositionCard.js
|
Mudano/m-dash-ui
|
import React from 'react'
import className from 'classnames'
export default class PositionCard extends React.Component {
static defaultProps = {
}
constructor(props){
super(props)
this.state = {
isOpen : this.props.isOpen,
isReady : !this.props.isOpen,
}
}
componentWillReceiveProps(nextProps){
if(nextProps.isOpen !== this.state.isOpen){
if(nextProps.isOpen){
this.showCard()
}else{
this.hideCard()
}
}
}
showCard(){
this.setState({isOpen:true})
setTimeout(()=>{
this.setState({isReady:true})
},100)
}
hideCard(){
this.setState({isReady:true})
setTimeout(()=>{
this.setState({isOpen:false})
},500)
}
render() {
const cn = className("m-card m-position-card",{
"m-position-card":this.state.isReady
})
return (
<span>
{this.props.children}
{this.state.isOpen &&
<div className="m-card m-position-card">{this.props.comp}</div>
}
</span>
);
}
}
|
src/Label.js
|
roderickwang/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Label = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render() {
let classes = this.getBsClassSet();
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Label;
|
packages/demos/demo/src/components/Project/Input.js
|
yusufsafak/cerebral
|
import React from 'react'
import { connect } from 'cerebral/react'
import { props, signal, state } from 'cerebral/tags'
import translations from '../../common/compute/translations'
export default connect(
{
// autoFocus
enterPressed: signal`projects.enterPressed`,
escPressed: signal`projects.escPressed`,
// field
// placeholderKey
value: state`projects.$draft.${props`field`}`,
valueChanged: signal`projects.formValueChanged`,
t: translations,
},
function Input({
autoFocus,
enterPressed,
escPressed,
field,
placeholderKey,
value,
valueChanged,
t,
}) {
const onKeyDown = e => {
switch (e.key) {
case 'Enter':
enterPressed()
break
case 'Escape':
escPressed()
break
default:
break // noop
}
}
const onChange = e => {
valueChanged({ key: field, value: e.target.value })
}
return (
<input
className="input"
type="text"
autoFocus={autoFocus}
placeholder={t[placeholderKey]}
onKeyDown={onKeyDown}
onChange={onChange}
value={value || ''}
name={field}
/>
)
}
)
|
src/www/js/index.js
|
training4developers/bootcamp_04112016
|
import React from 'react';
import Relay from 'react-relay';
import ReactDOM from 'react-dom';
import WidgetToolContainer from './containers/widget-tool-container';
import ViewerRoute from './routes/viewer-route';
ReactDOM.render(
<Relay.RootContainer Component={WidgetToolContainer} route={new ViewerRoute()} />,
document.querySelector('main')
);
|
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/Modal.js
|
Akkuma/npm-cache-benchmark
|
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import classNames from 'classnames';
import events from 'dom-helpers/events';
import ownerDocument from 'dom-helpers/ownerDocument';
import canUseDOM from 'dom-helpers/util/inDOM';
import getScrollbarSize from 'dom-helpers/util/scrollbarSize';
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import BaseModal from 'react-overlays/lib/Modal';
import isOverflowing from 'react-overlays/lib/utils/isOverflowing';
import elementType from 'react-prop-types/lib/elementType';
import Fade from './Fade';
import Body from './ModalBody';
import ModalDialog from './ModalDialog';
import Footer from './ModalFooter';
import Header from './ModalHeader';
import Title from './ModalTitle';
import { bsClass, bsSizes, prefix } from './utils/bootstrapUtils';
import createChainedFunction from './utils/createChainedFunction';
import splitComponentProps from './utils/splitComponentProps';
import { Size } from './utils/StyleConfig';
var propTypes = _extends({}, BaseModal.propTypes, ModalDialog.propTypes, {
/**
* Include a backdrop component. Specify 'static' for a backdrop that doesn't
* trigger an "onHide" when clicked.
*/
backdrop: PropTypes.oneOf(['static', true, false]),
/**
* Close the modal when escape key is pressed
*/
keyboard: PropTypes.bool,
/**
* Open and close the Modal with a slide and fade animation.
*/
animation: PropTypes.bool,
/**
* A Component type that provides the modal content Markup. This is a useful
* prop when you want to use your own styles and markup to create a custom
* modal component.
*/
dialogComponentClass: elementType,
/**
* When `true` The modal will automatically shift focus to itself when it
* opens, and replace it to the last focused element when it closes.
* Generally this should never be set to false as it makes the Modal less
* accessible to assistive technologies, like screen-readers.
*/
autoFocus: PropTypes.bool,
/**
* When `true` The modal will prevent focus from leaving the Modal while
* open. Consider leaving the default value here, as it is necessary to make
* the Modal work well with assistive technologies, such as screen readers.
*/
enforceFocus: PropTypes.bool,
/**
* When `true` The modal will restore focus to previously focused element once
* modal is hidden
*/
restoreFocus: PropTypes.bool,
/**
* When `true` The modal will show itself.
*/
show: PropTypes.bool,
/**
* A callback fired when the header closeButton or non-static backdrop is
* clicked. Required if either are specified.
*/
onHide: PropTypes.func,
/**
* Callback fired before the Modal transitions in
*/
onEnter: PropTypes.func,
/**
* Callback fired as the Modal begins to transition in
*/
onEntering: PropTypes.func,
/**
* Callback fired after the Modal finishes transitioning in
*/
onEntered: PropTypes.func,
/**
* Callback fired right before the Modal transitions out
*/
onExit: PropTypes.func,
/**
* Callback fired as the Modal begins to transition out
*/
onExiting: PropTypes.func,
/**
* Callback fired after the Modal finishes transitioning out
*/
onExited: PropTypes.func,
/**
* @private
*/
container: BaseModal.propTypes.container
});
var defaultProps = _extends({}, BaseModal.defaultProps, {
animation: true,
dialogComponentClass: ModalDialog
});
var childContextTypes = {
$bs_modal: PropTypes.shape({
onHide: PropTypes.func
})
};
var Modal = function (_React$Component) {
_inherits(Modal, _React$Component);
function Modal(props, context) {
_classCallCheck(this, Modal);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleEntering = _this.handleEntering.bind(_this);
_this.handleExited = _this.handleExited.bind(_this);
_this.handleWindowResize = _this.handleWindowResize.bind(_this);
_this.handleDialogClick = _this.handleDialogClick.bind(_this);
_this.state = {
style: {}
};
return _this;
}
Modal.prototype.getChildContext = function getChildContext() {
return {
$bs_modal: {
onHide: this.props.onHide
}
};
};
Modal.prototype.componentWillUnmount = function componentWillUnmount() {
// Clean up the listener if we need to.
this.handleExited();
};
Modal.prototype.handleEntering = function handleEntering() {
// FIXME: This should work even when animation is disabled.
events.on(window, 'resize', this.handleWindowResize);
this.updateStyle();
};
Modal.prototype.handleExited = function handleExited() {
// FIXME: This should work even when animation is disabled.
events.off(window, 'resize', this.handleWindowResize);
};
Modal.prototype.handleWindowResize = function handleWindowResize() {
this.updateStyle();
};
Modal.prototype.handleDialogClick = function handleDialogClick(e) {
if (e.target !== e.currentTarget) {
return;
}
this.props.onHide();
};
Modal.prototype.updateStyle = function updateStyle() {
if (!canUseDOM) {
return;
}
var dialogNode = this._modal.getDialogElement();
var dialogHeight = dialogNode.scrollHeight;
var document = ownerDocument(dialogNode);
var bodyIsOverflowing = isOverflowing(ReactDOM.findDOMNode(this.props.container || document.body));
var modalIsOverflowing = dialogHeight > document.documentElement.clientHeight;
this.setState({
style: {
paddingRight: bodyIsOverflowing && !modalIsOverflowing ? getScrollbarSize() : undefined,
paddingLeft: !bodyIsOverflowing && modalIsOverflowing ? getScrollbarSize() : undefined
}
});
};
Modal.prototype.render = function render() {
var _this2 = this;
var _props = this.props,
backdrop = _props.backdrop,
animation = _props.animation,
show = _props.show,
Dialog = _props.dialogComponentClass,
className = _props.className,
style = _props.style,
children = _props.children,
onEntering = _props.onEntering,
onExited = _props.onExited,
props = _objectWithoutProperties(_props, ['backdrop', 'animation', 'show', 'dialogComponentClass', 'className', 'style', 'children', 'onEntering', 'onExited']);
var _splitComponentProps = splitComponentProps(props, BaseModal),
baseModalProps = _splitComponentProps[0],
dialogProps = _splitComponentProps[1];
var inClassName = show && !animation && 'in';
return React.createElement(
BaseModal,
_extends({}, baseModalProps, {
ref: function ref(c) {
_this2._modal = c;
},
show: show,
onEntering: createChainedFunction(onEntering, this.handleEntering),
onExited: createChainedFunction(onExited, this.handleExited),
backdrop: backdrop,
backdropClassName: classNames(prefix(props, 'backdrop'), inClassName),
containerClassName: prefix(props, 'open'),
transition: animation ? Fade : undefined,
dialogTransitionTimeout: Modal.TRANSITION_DURATION,
backdropTransitionTimeout: Modal.BACKDROP_TRANSITION_DURATION
}),
React.createElement(
Dialog,
_extends({}, dialogProps, {
style: _extends({}, this.state.style, style),
className: classNames(className, inClassName),
onClick: backdrop === true ? this.handleDialogClick : null
}),
children
)
);
};
return Modal;
}(React.Component);
Modal.propTypes = propTypes;
Modal.defaultProps = defaultProps;
Modal.childContextTypes = childContextTypes;
Modal.Body = Body;
Modal.Header = Header;
Modal.Title = Title;
Modal.Footer = Footer;
Modal.Dialog = ModalDialog;
Modal.TRANSITION_DURATION = 300;
Modal.BACKDROP_TRANSITION_DURATION = 150;
export default bsClass('modal', bsSizes([Size.LARGE, Size.SMALL], Modal));
|
1l_React_ET_Lynda/Ex_Files_React_EssT/Ch07/07_01/finish/src/index.js
|
yevheniyc/C
|
import React from 'react'
import { render } from 'react-dom'
// import routes from './routes'
import Member from './components/ui/Member'
window.React = React
render(
<Member admin={true}
name="Edna Welch"
email="edna.welch88@example.com"
thumbnail="https://randomuser.me/api/portraits/women/90.jpg"
makeAdmin={(email) => console.log(email)}/>,
document.getElementById('react-container'))
|
src/routes/tool/index.js
|
chunkiat82/rarebeauty-ui
|
/**
* 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 Tool from './Tool';
import Layout from '../../components/Layout';
function listFreeSlots(fetch) {
return async () => {
const slotsResponse = await fetch('/graphql', {
body: JSON.stringify({
query: `{slots{
start,
end,
durationInMinutes,
amp,
}
}`,
}),
});
const { data } = await slotsResponse.json();
return (data && data.slots) || [];
};
}
function show(store) {
return () => {
store.dispatch({ type: 'SHOW_LOADER' });
};
}
function hide(store) {
return () => {
store.dispatch({ type: 'HIDE_LOADER' });
};
}
async function action({ fetch, store }) {
show(store)();
const freeSlots = await listFreeSlots(fetch)();
hide(store)();
return {
chunks: ['tool'],
title: 'Rare Beauty Professional',
component: (
<Layout>
<Tool rows={freeSlots} />
</Layout>
),
};
}
export default action;
|
src/containers/NewRoutineForm.js
|
snsavage/timer-react
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux'
import RoutineForm from './RoutineForm';
import { createRoutine } from '../actions/routineFormActions';
import { clearCurrentRoutine } from '../actions/routineActions';
export class NewRoutineForm extends Component {
componentWillMount() {
const { saved, clearCurrentRoutine } = this.props;
if(saved) { clearCurrentRoutine() };
}
render () {
return (
<RoutineForm
onSubmit={createRoutine}
formTitle={"New Routine"}
submitValue={"Create Routine"} />
);
}
}
function mapStateToProps(state) {
return {
saved: state.currentRoutine.saved,
}
}
function mapDispatchToProps(dispatch) {
return {
clearCurrentRoutine: bindActionCreators(clearCurrentRoutine, dispatch),
}
}
export default connect(mapStateToProps, mapDispatchToProps)(NewRoutineForm);
|
client/components/Common/ListItem.js
|
Mignon-han/issue-processing
|
import React from 'react';
import './css/style.css';
import { hexToRgb } from '../../utils/utils';
const ListItem = ({ selected, label, value, color, onClick, visible }) => (
<div className="common-list-item">
<div className='item-container bgStyle' data-value={value}
onClick={() => onClick()} style={selected ? { backgroundColor: color ? hexToRgb(color, 0.5) : hexToRgb("#A8A8A8", 0.4) ,display:visible?'':'none'} : {display:visible?'':'none'}}>
<div className="item-color" style={{background:color}}></div>
<div className="item-label textOver">{label}</div>
</div>
</div>
);
export default ListItem;
|
components/TimePickerSelect.js
|
hellobrian/carbon-components-react
|
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import Icon from './Icon';
export default class TimePickerSelect extends Component {
static propTypes = {
children: PropTypes.node,
className: PropTypes.string,
id: PropTypes.string.isRequired,
inline: PropTypes.bool,
disabled: PropTypes.bool,
defaultValue: PropTypes.any,
iconDescription: PropTypes.string,
hideLabel: PropTypes.bool,
labelText: PropTypes.string,
};
static defaultProps = {
disabled: false,
inline: true,
iconDescription: 'open list of options',
hideLabel: true,
labelText: 'Provide label text',
};
render() {
const {
id,
disabled,
children,
iconDescription,
className,
hideLabel,
labelText,
inline, // eslint-disable-line
...other
} = this.props;
const selectClasses = classNames({
'bx--select': true,
'bx--time-picker__select': true,
'bx--select--inline': true,
[className]: className,
});
const labelClasses = classNames('bx--label', {
'bx--visually-hidden': hideLabel,
});
const label = labelText ? (
<label htmlFor={id} className={labelClasses}>
{labelText}
</label>
) : null;
return (
<div className={selectClasses}>
{label}
<select
{...other}
id={id}
className="bx--select-input"
disabled={disabled}>
{children}
</select>
<Icon
name="caret--down"
className="bx--select__arrow"
description={iconDescription}
/>
</div>
);
}
}
|
docs-ui/components/checkboxFancy.stories.js
|
beeftornado/sentry
|
import React from 'react';
import {withInfo} from '@storybook/addon-info';
import {number, boolean} from '@storybook/addon-knobs';
import styled from '@emotion/styled';
import CheckboxFancy from 'app/components/checkboxFancy/checkboxFancy';
export default {
title: 'Core/Style/Icons',
};
export const _CheckboxFancy = withInfo('A fancy looking checkbox')(() => {
return (
<Container>
<CheckboxFancy
size={`${number('Size', 100)}px`}
isChecked={boolean('Checked', true)}
/>
</Container>
);
});
_CheckboxFancy.story = {
name: 'CheckboxFancy',
};
const Container = styled('div')`
display: flex;
flex-direction: column;
padding: 20px;
`;
|
src/js/components/Employees/New.js
|
appdev-academy/appdev.academy-react
|
import React from 'react'
import { browserHistory } from 'react-router'
import { inject, observer } from 'mobx-react'
import Form from './Form'
@inject('employeesStore')
@observer
export default class New extends React.Component {
constructor(props) {
super(props)
this.state = {
errors: []
}
}
handleSubmit(employeeParams) {
this.props.employeesStore.create(employeeParams).then((response) => {
if (response.status == 201) {
browserHistory.push('/employees')
}
}).catch((error) => {
if (error.response && error.response.data && error.response.data.errors) {
this.setState({
errors: error.response.data.errors
})
}
})
}
render() {
return (
<Form
errors={ this.state.errors }
handleSubmit={ this.handleSubmit.bind(this) }
ref='employeeForm'
/>
)
}
}
|
app/test/components/ContentFilter.spec.js
|
seanislegend/RushDiscography-ReactDemo
|
import React from 'react';
import {expect} from 'chai';
import {shallow} from 'enzyme';
import {spy} from 'sinon';
import ContentFilter from '../../src/js/components/ContentFilter';
describe('Component: <ContentFilter />', () => {
it('should render a filter element', () => {
const handleClick = spy();
const values = ['Foo', 'Bar', 'Baz'];
const wrapper = shallow(
<ContentFilter
handleClick={handleClick}
values={values}
/>
);
const actual = wrapper.find('.c-content-filter').length;
const expected = 1;
expect(actual).to.equal(expected);
});
it('should render a toggle button for each value', () => {
const handleClick = spy();
const values = ['Foo', 'Bar', 'Baz'];
const wrapper = shallow(
<ContentFilter
handleClick={handleClick}
values={values}
/>
);
const actual = wrapper.find('.c-content-filter__toggle').length;
const expected = values.length;
expect(actual).to.equal(expected);
});
it('should handle clicks on a toggle button', () => {
const handleClick = spy();
const values = ['Foo', 'Bar', 'Baz'];
const wrapper = shallow(
<ContentFilter
handleClick={handleClick}
values={values}
/>
);
wrapper.find('.c-content-filter__toggle')
.first()
.prop('onClick')();
const actual = handleClick.called;
const expected = true;
expect(actual).to.equal(expected);
});
it('should pass the value to the handler when a toggle button is clicked', () => {
const handleClick = spy();
const values = ['Foo', 'Bar', 'Baz'];
const wrapper = shallow(
<ContentFilter
handleClick={handleClick}
values={values}
/>
);
wrapper.find('.c-content-filter__toggle')
.first()
.prop('onClick')();
const actual = handleClick.calledWith('Foo');
const expected = true;
expect(actual).to.equal(expected);
});
it('should add an \'active\' class to a toggle button if its value is the active value', () => {
const handleClick = spy();
const values = ['Foo', 'Bar', 'Baz'];
const wrapper = shallow(
<ContentFilter
activeValue={values[0]}
handleClick={handleClick}
values={values}
/>
);
const actual = wrapper.find('.c-content-filter__toggle')
.first()
.hasClass('c-content-filter__toggle--active');
const expected = true;
expect(actual).to.equal(expected);
});
});
|
src/components/Header/index.js
|
frintjs/frint.js.org
|
import React from 'react';
import Link from "gatsby-link";
import SearchForm from '../SearchForm';
const Header = () => (
<div className="container">
<div className="nav-left">
<Link activeClassName="is-active" className="nav-item brand" to="/">
<img alt="Frint" className="dark" src="/img/frint-logo-7a7a7a.png" />
<img alt="Frint" className="light" src="/img/frint-logo-fff.png" />
</Link>
<Link activeClassName="is-active" className="nav-item is-tab" to="/docs">
Documentation
</Link>
<a className="nav-item is-tab" href="https://medium.com/frintjs">
Blog
</a>
<Link activeClassName="is-active" className="nav-item is-tab" to="/repl">
REPL
</Link>
<Link activeClassName="is-active" className="nav-item is-tab" to="/about">
About
</Link>
</div>
<div className="nav-right">
<div className="field nav-item">
<SearchForm />
</div>
</div>
</div>
);
export default Header;
|
src/components/common/FeedbackBlock/index.js
|
goodjoblife/GoodJobShare
|
import React from 'react';
import PropTypes from 'prop-types';
import cn from 'classnames';
import ReactGA from 'react-ga';
import { Heading } from 'common/base';
import Button from 'common/button/Button';
import ButtonGroupImage from 'common/button/ButtonGroupImage';
import Checked from 'common/icons/Checked';
import Close from 'common/icons/Close';
import styles from './FeedbackBlock.module.css';
class FeedbackBlock extends React.Component {
static propTypes = {
category: PropTypes.string.isRequired,
question: PropTypes.string,
placeholders: PropTypes.shape({
yes: PropTypes.string,
no: PropTypes.string,
}),
className: PropTypes.string,
};
static defaultProps = {
question: '請問您是否覺得以上的資訊實用? 感到滿意?',
placeholders: {
yes: '說說為什麼你覺得很實用?',
no: '說說為什麼你覺得不實用? 或是有任何其他的回饋?',
},
className: '',
};
constructor(props) {
super(props);
this.state = {
polarity: null,
feedback: '',
done: false,
};
}
onSubmit = () => {
ReactGA.event({
category: this.props.category,
action: this.state.polarity,
label: this.state.feedback,
});
this.setState({ done: true });
};
render() {
const { polarity, feedback, done } = this.state;
const { question, placeholders, className } = this.props;
if (done) {
return (
<div className={cn(styles.doneBlock, className)}>
<Checked className={styles.icon} style={{ marginRight: 20 }} />
<Heading size="sm" Tag="h4">
感謝您的回饋!
</Heading>
</div>
);
}
return (
<div className={cn(styles.feedbackBlock, className)}>
<Heading size="sm" Tag="h4">
{question}
</Heading>
<ButtonGroupImage
className={styles.btnGroup}
value={this.state.polarity}
onChange={v => {
this.setState({ polarity: v });
}}
options={[
{
value: 'yes',
label: '是',
icon: <Checked className={styles.icon} />,
},
{
value: 'no',
label: '否',
icon: <Close className={styles.icon} />,
},
]}
theme="yellow"
/>
{polarity === null ? null : (
<textarea
className={styles.feedback}
placeholder={
polarity === 'yes' ? placeholders.yes : placeholders.no
}
onChange={e => {
e.preventDefault();
this.setState({ feedback: e.target.value });
}}
value={feedback}
/>
)}
{polarity === null ? null : (
<Button
btnStyle="submit"
onClick={this.onSubmit}
className={styles.submitBtn}
>
送出
</Button>
)}
</div>
);
}
}
export default FeedbackBlock;
|
pootle/static/js/admin/components/ItemTableRow.js
|
JohnnyKing94/pootle
|
/*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import cx from 'classnames';
import React from 'react';
const ItemTableRow = React.createClass({
propTypes: {
fields: React.PropTypes.array.isRequired,
item: React.PropTypes.object.isRequired,
index: React.PropTypes.number.isRequired,
selectedItem: React.PropTypes.object,
onSelectItem: React.PropTypes.func.isRequired,
},
render() {
const { item } = this.props;
const { selectedItem } = this.props;
const { index } = this.props;
const values = item.toJSON();
values.index = index + 1;
function createColumn(field, i) {
return <td key={i}>{values[field]}</td>;
}
const classNames = cx({
'is-selected': selectedItem && item.id === selectedItem.id,
// FIXME: this is too coupled to certain item types
'is-disabled': item.get('disabled'),
'row-divider': index !== 0 && index % 10 === 0,
});
return (
<tr
className={classNames}
key={item.id}
onClick={() => this.props.onSelectItem(item.id)}
>
{this.props.fields.map(createColumn)}
</tr>
);
},
});
export default ItemTableRow;
|
docs/website/src/templates/package.js
|
adaltas/node-nikita
|
// React
import React from 'react'
// Gatsby
import { graphql, Link } from 'gatsby'
// MDX
import { MDXProvider } from "@mdx-js/react"
import { MDXRenderer } from "gatsby-plugin-mdx"
// Local
import Layout from '../components/Layout'
const Template = ({
data
}) => {
const { page } = data
return (
<Layout page={{
keywords: page.keywords,
description: page.description,
...page.parent.frontmatter,
slug: page.slug,
version: page.version.alias,
edit_url: page.edit_url}}>
<>
<MDXProvider>
<MDXRenderer>{page.parent.body}</MDXRenderer>
</MDXProvider>
{page.actions && (
<>
<h2>Actions</h2>
<ul>
{page.actions
.sort((p1, p2) => p1.slug > p2.slug)
.map( item => (
<li key={item.slug}>
<Link to={item.slug}>{item.name}</Link>
</li>
)
)}
</ul>
</>
)}
</>
</Layout>
)
}
export default Template
export const pageQuery = graphql`
query($path: String!) {
page: nikitaPackage(slug: { eq: $path }) {
slug
edit_url
description
keywords
version {
alias
}
parent {
... on Mdx {
frontmatter {
title
titleHtml
}
body
}
}
actions {
name
slug
}
}
}
`
|
app/javascript/mastodon/components/admin/Retention.js
|
abcang/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import api from 'mastodon/api';
import { FormattedMessage, FormattedNumber, FormattedDate } from 'react-intl';
import classNames from 'classnames';
import { roundTo10 } from 'mastodon/utils/numbers';
const dateForCohort = cohort => {
switch(cohort.frequency) {
case 'day':
return <FormattedDate value={cohort.period} month='long' day='2-digit' />;
default:
return <FormattedDate value={cohort.period} month='long' year='numeric' />;
}
};
export default class Retention extends React.PureComponent {
static propTypes = {
start_at: PropTypes.string,
end_at: PropTypes.string,
frequency: PropTypes.string,
};
state = {
loading: true,
data: null,
};
componentDidMount () {
const { start_at, end_at, frequency } = this.props;
api().post('/api/v1/admin/retention', { start_at, end_at, frequency }).then(res => {
this.setState({
loading: false,
data: res.data,
});
}).catch(err => {
console.error(err);
});
}
render () {
const { loading, data } = this.state;
const { frequency } = this.props;
let content;
if (loading) {
content = <FormattedMessage id='loading_indicator.label' defaultMessage='Loading...' />;
} else {
content = (
<table className='retention__table'>
<thead>
<tr>
<th>
<div className='retention__table__date retention__table__label'>
<FormattedMessage id='admin.dashboard.retention.cohort' defaultMessage='Sign-up month' />
</div>
</th>
<th>
<div className='retention__table__number retention__table__label'>
<FormattedMessage id='admin.dashboard.retention.cohort_size' defaultMessage='New users' />
</div>
</th>
{data[0].data.slice(1).map((retention, i) => (
<th key={retention.date}>
<div className='retention__table__number retention__table__label'>
{i + 1}
</div>
</th>
))}
</tr>
<tr>
<td>
<div className='retention__table__date retention__table__average'>
<FormattedMessage id='admin.dashboard.retention.average' defaultMessage='Average' />
</div>
</td>
<td>
<div className='retention__table__size'>
<FormattedNumber value={data.reduce((sum, cohort, i) => sum + ((cohort.data[0].value * 1) - sum) / (i + 1), 0)} maximumFractionDigits={0} />
</div>
</td>
{data[0].data.slice(1).map((retention, i) => {
const average = data.reduce((sum, cohort, k) => cohort.data[i + 1] ? sum + (cohort.data[i + 1].rate - sum)/(k + 1) : sum, 0);
return (
<td key={retention.date}>
<div className={classNames('retention__table__box', 'retention__table__average', `retention__table__box--${roundTo10(average * 100)}`)}>
<FormattedNumber value={average} style='percent' />
</div>
</td>
);
})}
</tr>
</thead>
<tbody>
{data.slice(0, -1).map(cohort => (
<tr key={cohort.period}>
<td>
<div className='retention__table__date'>
{dateForCohort(cohort)}
</div>
</td>
<td>
<div className='retention__table__size'>
<FormattedNumber value={cohort.data[0].value} />
</div>
</td>
{cohort.data.slice(1).map(retention => (
<td key={retention.date}>
<div className={classNames('retention__table__box', `retention__table__box--${roundTo10(retention.rate * 100)}`)}>
<FormattedNumber value={retention.rate} style='percent' />
</div>
</td>
))}
</tr>
))}
</tbody>
</table>
);
}
let title = null;
switch(frequency) {
case 'day':
title = <FormattedMessage id='admin.dashboard.daily_retention' defaultMessage='User retention rate by day after sign-up' />;
break;
default:
title = <FormattedMessage id='admin.dashboard.monthly_retention' defaultMessage='User retention rate by month after sign-up' />;
};
return (
<div className='retention'>
<h4>{title}</h4>
{content}
</div>
);
}
}
|
client/src/index.js
|
medelbou/react-redux-express
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
examples/react-application/index.js
|
alexeyraspopov/actor-system
|
import React from 'react';
import ReactDOM from 'react-dom';
import { ActorSystem } from 'actor-system';
import Application from './modules/Application.react';
import Wrapper from './modules/Wrapper.react';
import Storage from './modules/Storage';
import Main from './modules/Main.actor';
const system = ActorSystem.fromDefaults();
const storage = new Storage();
ReactDOM.render((
<Application system={system} storage={storage}>
<Wrapper />
</Application>
), document.querySelector('main'));
system.spawn(Main);
|
tp-3/euge/src/components/pages/alumnos/components/form/AlumnoForm.js
|
jpgonzalezquinteros/sovos-reactivo-2017
|
import React from 'react';
import './alumnoForm.scss';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import TextField from 'material-ui/TextField';
import {orange500, blue500} from 'material-ui/styles/colors';
import RaisedButton from 'material-ui/RaisedButton';
const styles = {
errorStyle: {
color: '#283593',
},
underlineStyle: {
borderColor: '#283593',
},
floatingLabelStyle: {
color: '#283593',
},
floatingLabelFocusStyle: {
color: blue500,
},
buttonStyle: {
margin: 12,
}
};
class AlumnoForm extends React.Component{
constructor(){
super();
this.alumno = {
nombre: "",
dni: "",
direccion: "",
fechanac: "",
estado: ""
};
}
compomentDidUpdate(){
this.alumno = {};
}
handleNombreChange =(evt)=>{
this.alumno.nombre = evt.target.value;
}
handleDniChange =(evt)=>{
this.alumno.dni = evt.target.value;
}
handleDireccionChange =(evt)=>{
this.alumno.direccion = evt.target.value;
}
handleFechanacChange =(evt)=>{
this.alumno.fechanac = evt.target.value;
}
handleEstadoChange =(evt)=>{
this.alumno.estado = evt.target.value;
}
handleSaveClick =(evt)=>{
console.log(this.alumno);
this.props.onNewAlumno(this.alumno);
document.getElementById("alumno-form").reset();
this.alumno={};
}
render(){
return (
<MuiThemeProvider>
<div>
<h2 className="alumnoForm">Nuevo Alumno</h2>
<form className="alumnoForm" id="alumno-form">
<TextField
floatingLabelText="Nombre"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleNombreChange}
/><br/>
<TextField
floatingLabelText="DNI"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleDniChange}
/><br/>
<TextField
floatingLabelText="Fecha de Nacimiento"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleFechanacChange}
/><br/>
<TextField
floatingLabelText="Direccion"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleDireccionChange}
/><br/>
<TextField
floatingLabelText="Estado"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
onChange={this.handleEstadoChange}
/><br/><br/>
<RaisedButton label="Guardar" style={styles.buttonStyle} onClick={this.handleSaveClick} />
</form>
</div>
</MuiThemeProvider>
);
}
};
export default AlumnoForm;
|
src/commons/title.js
|
jessy1092/react-semantify
|
import React from 'react';
import filter from '../filter';
import Div from './div';
const stateArray = ['active'];
const defaultClassName = 'title';
const componentName = 'Title';
const Title = new filter(Div)
.stateFilter(stateArray)
.classGenerator(defaultClassName)
.getComposeComponent(componentName);
export default Title;
|
mobile/mock ups/tech_stack/App.js
|
parammehta/TravLendar
|
import React from 'react';
import { View } from 'react-native';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from './src/reducers';
import { Header } from './src/components/common';
import LibraryList from './src/components/LibraryList';
const App = () => (
<Provider store={createStore(reducers)}>
<View style={{ flex: 1 }}>
<Header headerText="Tech Stack" />
<LibraryList />
</View>
</Provider>
);
export default App;
|
web/test/feedback/components/Pagination.js
|
trendmicro/serverless-survey-forms
|
import DomMock from '../../helpers/dom-mock';
import expect from 'expect';
import React from 'react';
import TestUtils from 'react-dom/test-utils';
import Pagination from '../../../src/components/Pagination';
DomMock('<html><body></body></html>');
describe('[Feedback] Testing Pagination Component', () => {
it('check total pages < 1: Only submit button', () => {
const content = TestUtils.renderIntoDocument(
<Pagination pages={1} currentPage={1} settings={{ type: 'preview' }} />
);
// const PrevBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-prev');
const NextBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-next');
const DoneBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-done');
// Expect only submit button
// expect(PrevBtn).toEqual([]);
expect(NextBtn).toEqual([]);
expect(DoneBtn[0].textContent).toEqual('Submit');
});
/* it('check page one scenario: No prev button', () => {
const content = TestUtils.renderIntoDocument(
<Pagination pages={4} currentPage={1} settings={{ type: 'preview' }} />
);
const PrevBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-prev');
// Expect no prev button
expect(PrevBtn).toEqual([]);
}); */
it('check page one scenario: Has next button', () => {
const content = TestUtils.renderIntoDocument(
<Pagination pages={4} currentPage={1} settings={{ type: 'preview' }} />
);
const NextBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-next');
// Expect to have next button
expect(NextBtn[0].textContent).toEqual('Next');
});
it('check last page scenario: No next button', () => {
const content = TestUtils.renderIntoDocument(
<Pagination pages={4} currentPage={4} settings={{ type: 'preview' }} />
);
const NextBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-next');
// Expect no prev button
expect(NextBtn).toEqual([]);
});
it('check last page scenario: Has prev and submit button', () => {
const content = TestUtils.renderIntoDocument(
<Pagination pages={4} currentPage={4} settings={{ type: 'preview' }} />
);
// const PrevBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-prev');
const DoneBtn = TestUtils.scryRenderedDOMComponentsWithClass(content, 'ut-done');
// Expect to have prev and submit button
// expect(PrevBtn[0].textContent).toEqual('Prev');
expect(DoneBtn[0].textContent).toEqual('Submit');
});
});
|
src/components/CardsList/cardsList.js
|
VitaliiK91/AlramRN
|
import React from 'react';
import PropTypes from 'prop-types';
import {
ScrollView,
} from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { cards as actions } from '../../store/actions';
import Card from '../Card';
const CardList = props => (
<ScrollView>
{
props.cards.map(
card => (
<Card
key={card.id}
onToggle={() => props.toggleCard(card.id)}
text={card.text}
enabled={card.enabled}
/>
),
)
}
</ScrollView>
);
CardList.defaultProps = {
cards: [],
};
CardList.propTypes = {
cards: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number,
text: PropTypes.string,
enabled: PropTypes.bool,
})),
};
export default connect(
null,
dispatch => ({
toggleCard: bindActionCreators(actions.toggleCard, dispatch),
}),
)(CardList);
|
src/components/atoms/Paragraph/index.stories.js
|
SIB-Colombia/dataportal_v2_frontend
|
import React from 'react'
import { storiesOf } from '@kadira/storybook'
import Paragraph from '.'
storiesOf('Paragraph', module)
.add('default', () => (
<Paragraph>
Nisi eu eiusmod cupidatat aute laboris commodo excepteur esse dolore incididunt incididunt aliquip pariatur est minim officia sit. Nulla pariatur duis duis quis commodo cupidatat voluptate enim culpa elit adipisicing do cupidatat sint anim. Cillum elit magna occaecat proident sit cupidatat ad quis sunt id culpa culpa. Ad duis nulla in incididunt amet consequat officia ad voluptate voluptate. Pariatur eiusmod ullamco cupidatat non magna officia aute magna deserunt qui aute dolor eu. Qui amet non ex cillum sunt ad velit consequat ipsum velit.
</Paragraph>
))
.add('reverse', () => (
<Paragraph reverse>
Nisi eu eiusmod cupidatat aute laboris commodo excepteur esse dolore incididunt incididunt aliquip pariatur est minim officia sit. Nulla pariatur duis duis quis commodo cupidatat voluptate enim culpa elit adipisicing do cupidatat sint anim. Cillum elit magna occaecat proident sit cupidatat ad quis sunt id culpa culpa. Ad duis nulla in incididunt amet consequat officia ad voluptate voluptate. Pariatur eiusmod ullamco cupidatat non magna officia aute magna deserunt qui aute dolor eu. Qui amet non ex cillum sunt ad velit consequat ipsum velit.
</Paragraph>
))
|
src/svg-icons/action/flight-land.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFlightLand = (props) => (
<SvgIcon {...props}>
<path d="M2.5 19h19v2h-19zm7.18-5.73l4.35 1.16 5.31 1.42c.8.21 1.62-.26 1.84-1.06.21-.8-.26-1.62-1.06-1.84l-5.31-1.42-2.76-9.02L10.12 2v8.28L5.15 8.95l-.93-2.32-1.45-.39v5.17l1.6.43 5.31 1.43z"/>
</SvgIcon>
);
ActionFlightLand = pure(ActionFlightLand);
ActionFlightLand.displayName = 'ActionFlightLand';
ActionFlightLand.muiName = 'SvgIcon';
export default ActionFlightLand;
|
src/Tab.js
|
thealjey/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const Tab = React.createClass({
propTypes: {
/**
* @private
*/
active: React.PropTypes.bool,
animation: React.PropTypes.bool,
/**
* It is used by 'Tabs' - parent component
* @private
*/
onAnimateOutEnd: React.PropTypes.func,
disabled: React.PropTypes.bool,
title: React.PropTypes.node
},
getDefaultProps() {
return {
animation: true
};
},
getInitialState() {
return {
animateIn: false,
animateOut: false
};
},
componentWillReceiveProps(nextProps) {
if (this.props.animation) {
if (!this.state.animateIn && nextProps.active && !this.props.active) {
this.setState({
animateIn: true
});
} else if (!this.state.animateOut && !nextProps.active && this.props.active) {
this.setState({
animateOut: true
});
}
}
},
componentDidUpdate() {
if (this.state.animateIn) {
setTimeout(this.startAnimateIn, 0);
}
if (this.state.animateOut) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.stopAnimateOut
);
}
},
startAnimateIn() {
if (this.isMounted()) {
this.setState({
animateIn: false
});
}
},
stopAnimateOut() {
if (this.isMounted()) {
this.setState({
animateOut: false
});
if (this.props.onAnimateOutEnd) {
this.props.onAnimateOutEnd();
}
}
},
render() {
let classes = {
'tab-pane': true,
'fade': true,
'active': this.props.active || this.state.animateOut,
'in': this.props.active && !this.state.animateIn
};
return (
<div {...this.props}
title={undefined}
role="tabpanel"
aria-hidden={!this.props.active}
className={classNames(this.props.className, classes)}
>
{this.props.children}
</div>
);
}
});
export default Tab;
|
example/app.js
|
snario/react-mapbox-gl
|
import React from 'react';
import SimpleExample from './simple';
import EventsExample from './events';
import VectorLayersExample from './vector-layers';
const examples = <div>
<h1>React-Leaflet examples</h1>
<h2>Popup with Marker</h2>
<SimpleExample />
<h2>Events</h2>
<p>Click the map to show a marker at your detected location</p>
<EventsExample />
<h2>Vector layers</h2>
<VectorLayersExample />
</div>;
React.render(examples, document.getElementById('app'));
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-forms-auto-complete.js
|
UnicornCollege/ucl.itkpd.configurator
|
import React from 'react';
import {BaseMixin, ElementaryMixin, ContentMixin} from './../common/common.js';
import {Link, Backdrop} from './../bricks/bricks.js';
import $ from 'jquery';
import './auto-complete.less';
export default React.createClass({
mixins: [
BaseMixin,
ElementaryMixin,
ContentMixin
],
statics: {
tagName: 'UU5.Forms.AutoComplete',
classNames: {
main: 'uu5-forms-auto-complete',
open: 'uu5-forms-auto-complete-opened',
menu: 'uu5-forms-auto-complete-menu list-group',
item: 'uu5-forms-auto-complete-item list-group-item',
selected: 'uu5-forms-auto-complete-selected'
}
},
propTypes: {
items: React.PropTypes.arrayOf(
React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
params: React.PropTypes.object,
content: React.PropTypes.any
})
),
onClick: React.PropTypes.func
},
// Setting defaults
getDefaultProps: function () {
return {
items: null,
onClick: null
};
},
getInitialState: function () {
return {
items: null,
selectedIndex: null
};
},
// Interface
find: function (foundValue, setStateCallback) {
var values = { first: [], last: [] };
this.props.items.forEach(function (item) {
if (foundValue !== '') {
if (new RegExp('^' + foundValue, 'i').exec(item.value)) {
values.first.push(item);
} else if (new RegExp(foundValue, 'gi').exec(item.value)) {
values.last.push(item);
}
}
});
var allValues = values.first.concat(values.last);
this.setState({ items: allValues.length ? allValues : null, selectedIndex: null }, setStateCallback);
return this;
},
close: function (setStateCallback) {
this.setState({ items: null, selectedIndex: null }, setStateCallback);
return this;
},
isOpened: function () {
return !!this.state.items;
},
selectUp: function (setStateCallback) {
var autoComplete = this;
this.setState(function (state) {
var index = null;
if (autoComplete.state.items) {
if (state.selectedIndex == null || state.selectedIndex === 0) {
index = autoComplete.state.items.length - 1;
} else {
index = state.selectedIndex - 1;
}
}
var offset = index > autoComplete.state.items.length - 3 ?
$('#' + autoComplete.getId() + '-item-' + (autoComplete.state.items.length - 1))[0].offsetTop :
index - 1 > 0 ? $('#' + autoComplete.getId() + '-item-' + (index - 1))[0].offsetTop : 0;
$('#' + this.getId() + '-menu').animate({ scrollTop: offset }, 0);
return { selectedIndex: index };
}, setStateCallback);
return this;
},
selectDown: function (setStateCallback) {
var autoComplete = this;
this.setState(function (state) {
var index = null;
var newState;
if (autoComplete.state.items) {
if (state.selectedIndex == null || state.selectedIndex === autoComplete.state.items.length - 1) {
index = 0;
} else {
index = state.selectedIndex + 1;
}
var offset = index > 1 ? $('#' + autoComplete.getId() + '-item-' + (index - 1))[0].offsetTop : 0;
$('#' + autoComplete.getId() + '-menu').animate({ scrollTop: offset }, 0);
newState = { selectedIndex: index };
} else {
newState = {
items: autoComplete.props.items.sort(function (a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}), selectedIndex: 0
};
}
return newState;
}, setStateCallback);
return this;
},
confirmSelected: function (setStateCallback) {
this.state.items && this._confirm(this.state.items[this.state.selectedIndex], this.state.selectedIndex, setStateCallback);
return this;
},
// Overriding Functions
// Component Specific Helpers
_getBackdropProps: function () {
var backdropId = this.getId() + "-backdrop";
return {
hidden: !this.isOpened(),
id: backdropId,
onClick: function (backdrop, event) {
event.target.id === backdropId && this.close();
}.bind(this)
};
},
_onClick: function (value, i) {
this._confirm(value, i);
return this;
},
_confirm: function (item, i, setStateCallback) {
if (typeof this.props.onClick === 'function') {
this.props.onClick({ value: item.value, item: item, index: i, component: this });
}
this.close(setStateCallback);
return this;
},
_getChildren: function () {
var autoComplete = this;
return this.state.items && this.state.items.map(function (item, i) {
var className = autoComplete.getClassName().item;
autoComplete.state.selectedIndex === i && (className += ' ' + autoComplete.getClassName().selected);
return (
<Link
className={className}
key={i}
content={item.content || item.value}
onClick={autoComplete._onClick.bind(autoComplete, item, i)}
mainAttrs={{ id: autoComplete.getId() + '-item-' + i }}
/>
);
});
},
_getMainAttrs: function () {
var mainAttrs = this.buildMainAttrs();
this.state.items && (mainAttrs.className += ' ' + this.getClassName().open);
return mainAttrs;
},
// Render
render: function () {
return (
<div {...this._getMainAttrs()}>
<Backdrop {...this._getBackdropProps()} />
<div className={this.getClassName().menu} id={this.getId() + '-menu'}>
{this._getChildren()}
</div>
</div>
);
}
});
|
app/screens/gold/gold.container.js
|
it-surya/hack-jeninvest
|
import React from 'react';
import {
View,
Image,
Keyboard
} from 'react-native';
import {
RkButton,
RkText,
RkTextInput,
RkStyleSheet,
RkTheme,
RkAvoidKeyboard,
RkChoice
} from 'react-native-ui-kitten';
import {GradientButton} from '../../components/';
import {scale, scaleModerate, scaleVertical} from '../../utils/scale';
export class GoldForm extends React.Component {
static navigationOptions = {
title: 'Gold Investment'.toUpperCase()
};
constructor(props) {
super(props);
this._renderPtName = this._renderPtName.bind(this);
}
_renderPtName = () => {
return (
<View style={styles.ptName}>
<Image style={styles.image} source={require('../../assets/images/logo.png')}/>
<RkText style={styles.ptNameTitle}>fds</RkText>
</View>
);
}
render() {
let renderIcon = () => {
if (RkTheme.current.name === 'light')
return <Image style={styles.image} source={require('../../assets/images/logo.png')}/>;
return <Image style={styles.image} source={require('../../assets/images/logoDark.png')}/>
};
return (
<RkAvoidKeyboard
style={styles.screen}
onStartShouldSetResponder={ (e) => true}
onResponderRelease={ (e) => Keyboard.dismiss()}>
{this._renderPtName()}
<View style={styles.content}>
<View>
<RkChoice rkType='posNeg' selected={false}/>
<RkTextInput rkType='topLabel' placeholder='Email'/>
<RkTextInput rkType='bordered' placeholder='Name'/>
<RkTextInput rkType='form' placeholder='Email'/>
<RkTextInput rkType='rounded' placeholder='Password' secureTextEntry={true}/>
<RkTextInput placeholder='Confirm Password' secureTextEntry={true}/>
</View>
<RkButton style={{backgroundColor: '#8fbc5a'}} rkType='stretch' onPress={() => this.props.navigation.navigate('Login1')}>
<RkText style={{color: '#ffffff'}} rkType='header6'> Sign in now </RkText>
</RkButton>
<View style={styles.footer}>
<View style={styles.textRow}>
<RkText rkType='primary3'>Already have an account?</RkText>
</View>
</View>
</View>
</RkAvoidKeyboard>
)
}
}
let styles = RkStyleSheet.create(theme => ({
screen: {
padding: 16,
flex: 1,
justifyContent: 'space-around',
backgroundColor: theme.colors.screen.base
},
ptName: {
flexDirection: 'row',
paddingBottom: 10,
borderBottomWidth: 1,
borderColor: '#d1d1d1'
},
ptNameTitle: {
paddingLeft: 10
},
image: {
width: scale(30),
height:scaleVertical(30),
resizeMode:'contain',
paddingRight: 10
},
content: {
justifyContent: 'space-between'
},
save: {
//marginVertical: 20
},
buttons: {
flexDirection: 'row',
marginBottom: 24,
marginHorizontal: 24,
justifyContent: 'space-around'
},
footer:{
justifyContent:'flex-end'
},
textRow: {
flexDirection: 'row',
justifyContent: 'center'
},
}));
|
src/px-modal/index.js
|
jonniespratley/px-components-react
|
import React from 'react';
import Overlay from '../px-overlay';
import Button from '../px-button';
import classnames from 'classnames';
import stylesheet from './style.scss';
/**
* px-modal component
*/
export default ({
style,
modalHeading = 'Modal',
btnModalNegative,
onBtnModalNegativeClick,
btnModalPositive,
onBtnModalPositiveClick,
visible,
isOpen,
onBackdropClick,
btnModalPositiveDisabled = false,
children
}) => {
const modalClassnames = classnames(
'modal',
'flex',
'flex--middle',
'flex--center',
'full-height',
{'invisible' : !visible}
);
return (
<div className='px-modal'>
<Overlay visible={visible} onOverlayClick={(e) => onBackdropClick(e)}/>
<div className={modalClassnames} role="dialog">
<section className="modal__content" role='region'>
<h3 className="modal__title epsilon weight--normal">{modalHeading}</h3>
<div>
{children}
</div>
<div className="modal__buttons flex flex--right">
<div className='flex'>
{btnModalNegative && <Button id="btnModalNegative"
label={btnModalNegative}
onClick={(e) => onBtnModalNegativeClick(e)}/>}
{btnModalPositive && <Button primary
disabled={btnModalPositiveDisabled}
id="btnModalPositive"
label={btnModalPositive}
onClick={(e) => onBtnModalPositiveClick(e)}/>}
</div>
</div>
</section>
</div>
<style jsx>{stylesheet}</style>
</div>);
}
|
src/svg-icons/av/recent-actors.js
|
nathanmarks/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvRecentActors = (props) => (
<SvgIcon {...props}>
<path d="M21 5v14h2V5h-2zm-4 14h2V5h-2v14zM14 5H2c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h12c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zM8 7.75c1.24 0 2.25 1.01 2.25 2.25S9.24 12.25 8 12.25 5.75 11.24 5.75 10 6.76 7.75 8 7.75zM12.5 17h-9v-.75c0-1.5 3-2.25 4.5-2.25s4.5.75 4.5 2.25V17z"/>
</SvgIcon>
);
AvRecentActors = pure(AvRecentActors);
AvRecentActors.displayName = 'AvRecentActors';
AvRecentActors.muiName = 'SvgIcon';
export default AvRecentActors;
|
app/javascript/mastodon/features/hashtag_timeline/components/column_settings.js
|
cybrespace/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { injectIntl, FormattedMessage } from 'react-intl';
import Toggle from 'react-toggle';
import AsyncSelect from 'react-select/lib/Async';
export default @injectIntl
class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onLoad: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
state = {
open: this.hasTags(),
};
hasTags () {
return ['all', 'any', 'none'].map(mode => this.tags(mode).length > 0).includes(true);
}
tags (mode) {
let tags = this.props.settings.getIn(['tags', mode]) || [];
if (tags.toJSON) {
return tags.toJSON();
} else {
return tags;
}
};
onSelect = (mode) => {
return (value) => {
this.props.onChange(['tags', mode], value);
};
};
onToggle = () => {
if (this.state.open && this.hasTags()) {
this.props.onChange('tags', {});
}
this.setState({ open: !this.state.open });
};
modeSelect (mode) {
return (
<div className='column-settings__section'>
{this.modeLabel(mode)}
<AsyncSelect
isMulti
autoFocus
value={this.tags(mode)}
settings={this.props.settings}
settingPath={['tags', mode]}
onChange={this.onSelect(mode)}
loadOptions={this.props.onLoad}
classNamePrefix='column-settings__hashtag-select'
name='tags'
/>
</div>
);
}
modeLabel (mode) {
switch(mode) {
case 'any': return <FormattedMessage id='hashtag.column_settings.tag_mode.any' defaultMessage='Any of these' />;
case 'all': return <FormattedMessage id='hashtag.column_settings.tag_mode.all' defaultMessage='All of these' />;
case 'none': return <FormattedMessage id='hashtag.column_settings.tag_mode.none' defaultMessage='None of these' />;
}
return '';
};
render () {
return (
<div>
<div className='column-settings__row'>
<div className='setting-toggle'>
<Toggle
id='hashtag.column_settings.tag_toggle'
onChange={this.onToggle}
checked={this.state.open}
/>
<span className='setting-toggle__label'>
<FormattedMessage id='hashtag.column_settings.tag_toggle' defaultMessage='Include additional tags in this column' />
</span>
</div>
</div>
{this.state.open &&
<div className='column-settings__hashtags'>
{this.modeSelect('any')}
{this.modeSelect('all')}
{this.modeSelect('none')}
</div>
}
</div>
);
}
}
|
extension/panel/src/components/app-view.js
|
capacitorjs/capacitor
|
'use strict';
import React from 'react';
import {RouteHandler} from 'react-router';
import Locator from 'capacitor-locator';
import PluginList from 'src/components/plugin-list';
import PluginStore from 'src/stores/plugin';
/**
* Display the current list of plugins and the currently-selected plugin
*/
export default class AppView extends React.Component {
constructor(props) {
super(props);
this._pluginStore = Locator.get(PluginStore);
this.state = {plugins: this._pluginStore.data};
const listener = this._updatePlugins.bind(this);
this._pluginStore.emitter.on('change', listener);
this._dispose = () => {
this._pluginStore.emitter.removeListener('change', listener);
};
}
_updatePlugins() {
this.setState({plugins: this._pluginStore.data});
}
componentWillUnmount() {
this._dispose();
}
render() {
return (
<div className='app-view'>
<PluginList plugins={this.state.plugins}/>
<RouteHandler/>
</div>
);
}
}
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-bricks-camera.js
|
UnicornCollege/ucl.itkpd.configurator
|
import React from 'react';
import {BaseMixin, ElementaryMixin, Tools} from '../common/common.js';
import './camera.less';
// TODO
// quality of picture -> jpg, png, ...
// choice of camera devices if pc has more cameras
export const Camera = React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Bricks.Camera',
classNames: {
main: 'uu5-bricks-camera',
video: 'uu5-bricks-camera-video',
canvas: 'uu5-bricks-camera-canvas'
},
errors: {
videoError: 'Video can not be loaded.'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
componentWillMount: function () {
navigator.getUserMedia = navigator.getUserMedia
|| navigator.webkitGetUserMedia
|| navigator.mozGetUserMedia
|| navigator.msGetUserMedia
|| navigator.oGetUserMedia;
if (navigator.getUserMedia) {
navigator.getUserMedia({ video: true }, this._handleVideo, this._videoError);
}
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
getScreenShot: function () {
var img = null;
if (this.localMediaStream) {
var canvas = this.canvas;
canvas.width = Tools.getWidth(this);
canvas.height = Tools.getHeight(this);
var ctx = canvas.getContext('2d');
ctx.drawImage(this.video, 0, 0, Tools.getWidth(this), Tools.getHeight(this));
img = canvas.toDataURL('image/png');
}
return img;
},
//@@viewOff:interface
//@@viewOn:overridingMethods
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
_handleVideo: function (stream) {
var video = this.video;
video.src = window.URL.createObjectURL(stream);
this.localMediaStream = stream;
return this;
},
_videoError: function (e) {
this.showError('videoError', null, { context: { event: e, src: this.video.src } });
return this;
},
_refVideo: function (video) {
this.video = video;
return this;
},
_refCanvas: function (canvas) {
this.canvas = canvas;
return this;
},
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render: function () {
return (
<div {...this.getMainAttrs()}>
<video autoPlay="true" ref={this._refVideo} className={this.getClassName().video} />
<canvas ref={this._refCanvas} className={this.getClassName().canvas} />
{this.getDisabledCover()}
</div>
);
}
//@@viewOff:render
});
export default Camera;
|
shared/app/Tms/config/components/TmsConfig.js
|
pebie/react-universally-node-config
|
import React from 'react';
import PropTypes from 'prop-types';
import serialize from 'serialize-javascript';
import filterWithRules from '../../../../../shared/utils/objects/filterWithRules';
import { getConfig } from '../../config';
const values = getConfig();
// Filter the config down to the properties that are allowed to be included
// in the HTML response.
const clientConfig = filterWithRules(
// These are the rules used to filter the config.
values.clientConfigFilter,
// The config values to filter.
values,
);
const serializedClientConfig = serialize(clientConfig);
/**
* A react component that generates a script tag that binds the allowed
* values to the window so that config values can be read within the
* browser.
*
* They get bound to window.__CLIENT_CONFIG__
*/
function TmsConfig({ nonce, children }) {
return (
<div>
<script
type="text/javascript"
nonce={nonce}
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{
__html: `window.__TMS_CONFIG__=${serializedClientConfig}`,
}}
/>
{children}
</div>
);
}
TmsConfig.propTypes = {
nonce: PropTypes.string.isRequired,
children: PropTypes.node,
};
TmsConfig.defaultProps = {
children: null,
};
export default TmsConfig;
|
src/common/EmptyView/EmptyViewDouble.js
|
Syncano/syncano-dashboard
|
import React from 'react';
import { FontIcon, RaisedButton } from 'material-ui';
const EmptyViewDouble = ({
title,
description,
iconClassName,
iconColor,
leftIconType,
rightIconType,
handleClickRightButton,
handleClickLeftButton,
labelButtonLeft,
labelButtonRight
}) => {
const styles = {
container: {
display: 'flex',
flexDirection: 'column',
justifyContent: 'space-around',
alignItems: 'center',
height: '100%',
textAlign: 'center',
padding: '70px 50px'
},
mainContainer: {
color: '#000',
width: 680,
height: 500,
border: '2px #dedede dashed',
borderRadius: 5,
margin: '50px auto 0 auto'
},
icon: {
fontSize: 72
},
title: {
marginTop: 40,
fontSize: 26,
fontWeight: 400,
lineHeight: '34px',
hyphens: 'none',
'-webkit-hyphens': 'none', /* Saf 5.1+ */
'-moz-hyphens': 'none', /* Fx 6.0+ */
'-ms-hyphens': 'none' /* IE 10+ */
},
description: {
lineHeight: '26px',
fontSize: 16,
padding: 40,
textAlign: 'center'
},
url: {
display: 'block',
fontSize: 16,
marginBottom: 20
},
box: {
width: 250
},
flexContainer: {
display: 'flex',
flexDirection: 'row',
justifyContent: 'center',
alignItems: 'flex-start'
}
};
return (
<div style={styles.mainContainer}>
<div
data-e2e="push-notifications-empty-view"
style={styles.container}
>
<FontIcon
className={iconClassName}
color={iconColor}
style={styles.icon}
/>
<div style={styles.title}>
{title}
</div>
<div style={styles.description}>
{description}
</div>
<div style={styles.flexContainer}>
<div style={styles.box}>
<RaisedButton
label={labelButtonLeft}
primary={true}
onTouchTap={handleClickLeftButton}
icon={leftIconType}
/>
</div>
<div style={styles.box}>
<RaisedButton
label={labelButtonRight}
primary={true}
onTouchTap={handleClickRightButton}
icon={rightIconType}
/>
</div>
</div>
</div>
</div>
);
};
export default EmptyViewDouble;
|
src/components/exercises/LetterRotated.stories.js
|
cognostics/serlo-abc
|
import React from 'react';
import { storiesOf } from '@storybook/react-native';
import LetterRotated from './LetterRotated';
storiesOf('exercises/LetterRotated', module)
.add('difficulty level 1', () => (
<LetterRotated
letters={['a', 'N', 'E']}
rotated={[4]}
angles={['50deg']}
difficulty={0.1}
/>
))
.add('difficulty level 2', () => (
<LetterRotated
letters={['a', 'N', 'E', 's', 'T']}
rotated={[4]}
angles={['50deg']}
difficulty={0.3}
/>
))
.add('difficulty level 3', () => (
<LetterRotated
letters={['a', 'N', 'E', 's', 'T']}
rotated={[3, 4]}
angles={['50deg', '-30deg']}
difficulty={0.5}
/>
));
|
src/ModalBody.js
|
PeterDaveHello/react-bootstrap
|
import React from 'react';
import classnames from 'classnames';
class ModalBody extends React.Component {
render() {
return (
<div {...this.props} className={classnames(this.props.className, this.props.modalClassName)}>
{this.props.children}
</div>
);
}
}
ModalBody.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string
};
ModalBody.defaultProps = {
modalClassName: 'modal-body'
};
export default ModalBody;
|
src/widgets/codes-lists/components/codes-lists.spec.js
|
Zenika/Pogues
|
import React from 'react';
import { shallow } from 'enzyme';
import CodesLists from './codes-lists';
import CodesListsCodes from './codes-lists-codes';
import { WIDGET_CODES_LISTS } from 'constants/dom-constants';
import { CODES_LIST_INPUT_ENUM } from 'constants/pogues-constants';
const { PANEL_CLASS } = WIDGET_CODES_LISTS;
const { NEW, REF, QUEST } = CODES_LIST_INPUT_ENUM;
describe('<CodesList />', () => {
const customPath = 'this.is.a.fake.path';
test.skip('Should exists hidden fields with the codes list id and label', () => {
const wrapper = shallow(<CodesLists path={customPath} />);
expect(wrapper.find(`Field[name="${customPath}id"]`)).toHaveLength(1);
expect(wrapper.find(`Field[name="${customPath}label"]`)).toHaveLength(1);
});
test.skip('Should render a CodesListsCodes component', () => {
const wrapper = shallow(<CodesLists path={customPath} />);
expect(wrapper.find('FieldArray').props()).toMatchObject({
name: `${customPath}codes`,
component: CodesListsCodes
});
});
test.skip('Should render a CodesListsPanelSelector component', () => {
const wrapper = shallow(<CodesLists path={customPath} />);
expect(wrapper.find('CodesListsPanelSelector')).toHaveLength(1);
});
test.skip(
'Should render a panel to create a new codes list, to search in the codes lists referential and to select a ' +
'codes list from the existing in the questionnaire',
() => {
const wrapper = shallow(<CodesLists path={customPath} />);
expect(
wrapper.find(`.${PANEL_CLASS}.${PANEL_CLASS}-${NEW}`)
).toHaveLength(1);
expect(
wrapper.find(`.${PANEL_CLASS}.${PANEL_CLASS}-${REF}`)
).toHaveLength(1);
expect(
wrapper.find(`.${PANEL_CLASS}.${PANEL_CLASS}-${QUEST}`)
).toHaveLength(1);
}
);
});
|
src/EmptyRadar.js
|
shauns/react-d3-radar
|
// @flow
import React from 'react';
import RadarAxis from './RadarAxis';
import RadarRings from './RadarRings';
import type {RadarVariable} from './types';
import {radiusScales, forEachArray} from './utils';
type Props = {
width: number,
height: number,
padding: number,
variables: Array<RadarVariable>,
domainMax: number,
style?: {},
};
const defaultRadarStyle = {
numRings: 4,
axisColor: '#cdcdcd',
ringColor: '#cdcdcd',
};
export default function EmptyRadar(props: Props) {
const {width, height, padding, variables, domainMax, style} = props;
const {axisColor, ringColor, numRings} = {...defaultRadarStyle, ...style};
const innerHeight = height - padding * 2;
const innerWidth = width - padding * 2;
const radius = Math.min(innerWidth / 2, innerHeight / 2);
const diameter = radius * 2;
const scales = radiusScales(variables, domainMax, radius);
const angleSliceRadians = Math.PI * 2 / variables.length;
const offsetAngles = {};
forEachArray(variables, ({key}, i) => {
offsetAngles[key] = angleSliceRadians * i;
});
const backgroundScale = scales[variables[0].key];
const ticks = backgroundScale.ticks(numRings).slice(1);
const tickFormat = backgroundScale.tickFormat(numRings);
return (
<svg width={width} height={height}>
<g transform={`translate(${padding}, ${padding})`}>
<rect
width={diameter}
height={diameter}
fill={'transparent'}
transform={
`translate(${(innerWidth - diameter) / 2}, ${(innerHeight -
diameter) /
2})`
}
/>
<g transform={`translate(${innerWidth / 2}, ${innerHeight / 2})`}>
<RadarRings
ticks={ticks}
scale={backgroundScale}
color={ringColor}
format={tickFormat}
/>
{variables.map(({key, label}) => {
return (
<RadarAxis
key={key}
scale={scales[key]}
offsetAngle={offsetAngles[key]}
label={label}
domainMax={domainMax}
color={axisColor}
/>
);
})}
</g>
</g>
</svg>
);
}
|
src/views/Blocks/Clock.js
|
abachman/my-new-tab
|
import React from 'react'
import PropTypes from 'prop-types'
import { GridBlockWrapper } from './Base'
import formatDate from '../../lib/formatDate'
import '../../stylesheets/Clock.css'
class Clock extends React.Component {
static propTypes = {
block: PropTypes.object.isRequired
}
state = {
time: new Date()
}
componentDidMount() {
this._tick = setInterval(() => {
this.setState({time: new Date()})
}, 2000)
}
componentWillUnmount() {
if (this._tick)
clearInterval(this._tick)
}
formattedTime() {
const { size, block } = this.props
const { fontFamily } = block
const now = this.state.time,
bigFont = {fontSize: Math.floor(size.width / 6) + 'px'},
smallFont = {fontSize: Math.floor(size.width / 14) + 'px'}
return (
<div className='clock-time' style={{fontFamily: fontFamily}}>
<div className='time' style={bigFont}>{formatDate(now, 'h:mm TT')}</div>
<div className='date' style={smallFont}>{formatDate(now, 'dddd, d MMM yyyy')}</div>
</div>
)
}
render() {
return (
<div className='item-container'>
{this.formattedTime()}
</div>
)
}
}
export default GridBlockWrapper(Clock)
|
src/components/common/svg-icons/editor/format-shapes.js
|
abzfarah/Pearson.NAPLAN.GnomeH
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorFormatShapes = (props) => (
<SvgIcon {...props}>
<path d="M23 7V1h-6v2H7V1H1v6h2v10H1v6h6v-2h10v2h6v-6h-2V7h2zM3 3h2v2H3V3zm2 18H3v-2h2v2zm12-2H7v-2H5V7h2V5h10v2h2v10h-2v2zm4 2h-2v-2h2v2zM19 5V3h2v2h-2zm-5.27 9h-3.49l-.73 2H7.89l3.4-9h1.4l3.41 9h-1.63l-.74-2zm-3.04-1.26h2.61L12 8.91l-1.31 3.83z"/>
</SvgIcon>
);
EditorFormatShapes = pure(EditorFormatShapes);
EditorFormatShapes.displayName = 'EditorFormatShapes';
EditorFormatShapes.muiName = 'SvgIcon';
export default EditorFormatShapes;
|
fields/types/date/DateColumn.js
|
asifiqbal84/keystone
|
import React from 'react';
import moment from 'moment';
import ItemsTableCell from '../../../admin/src/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/src/components/ItemsTableValue';
var DateColumn = React.createClass({
displayName: 'DateColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
let value = this.props.data.fields[this.props.col.path];
if (!value) return null;
let format = (this.props.col.path === 'dateTime') ? 'MMMM Do YYYY, h:mm:ss a' : 'MMMM Do YYYY';
let formattedValue = moment(value).format(format);
return (
<ItemsTableValue title={formattedValue} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
}
});
module.exports = DateColumn;
|
examples/huge-apps/routes/Grades/components/Grades.js
|
nhunzaker/react-router
|
import React from 'react'
class Grades extends React.Component {
render() {
return (
<div>
<h2>Grades</h2>
</div>
)
}
}
export default Grades
|
app/containers/App/index.js
|
nguyenduong127/kong-dashboard
|
/**
*
* App
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*/
import React from 'react';
import Helmet from 'react-helmet';
import styled from 'styled-components';
import Header from 'components/Header';
import Footer from 'components/Footer';
import withProgressBar from 'components/ProgressBar';
const AppWrapper = styled.div`
min-height: 100%;
`;
export function App(props) {
return (
<AppWrapper>
<Helmet
titleTemplate="%s - Kong Dashboard"
defaultTitle="Kong Dashboard"
meta={[
{ name: 'description', content: 'A Kong Dashboard application' },
]}
/>
<Header />
{React.Children.toArray(props.children)}
<Footer />
</AppWrapper>
);
}
App.propTypes = {
children: React.PropTypes.node,
};
export default withProgressBar(App);
|
js/components/blankPage/index.js
|
laurar07/onMy6
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Container, Header, Title, Content, Text, Button, Icon } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import { popRoute } from '../../actions/route';
import styles from './styles';
class BlankPage extends Component {
static propTypes = {
popRoute: React.PropTypes.func,
openDrawer: React.PropTypes.func,
name: React.PropTypes.string,
index: React.PropTypes.number,
list: React.PropTypes.arrayOf(React.PropTypes.string),
}
popRoute() {
this.props.popRoute();
}
render() {
const { props: { name, index, list } } = this;
return (
<Container style={styles.container}>
<Header>
<Button transparent onPress={() => this.popRoute()}>
<Icon name="ios-arrow-back" />
</Button>
<Title>{(name) ? this.props.name : 'Blank Page'}</Title>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="ios-menu" />
</Button>
</Header>
<Content padder>
<Text>
{(!isNaN(index)) ? list[index] : 'Create Something Awesome . . .'}
</Text>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: () => dispatch(popRoute()),
};
}
function mapStateToProps(state) {
return {
name: state.user.name,
index: state.list.selectedIndex,
list: state.list.list,
};
}
export default connect(mapStateToProps, bindAction)(BlankPage);
|
src/entypo/Foursquare.js
|
cox-auto-kc/react-entypo
|
import React from 'react';
import EntypoIcon from '../EntypoIcon';
const iconClass = 'entypo-svgicon entypo--Foursquare';
let EntypoFoursquare = (props) => (
<EntypoIcon propClass={iconClass} {...props}>
<path d="M4.92,1C4.412,1,4,1.412,4,1.92v16.516c0,0.625,0.765,0.926,1.192,0.47l4.471-4.79C9.731,14.042,9.826,14,9.927,14h3.237c0.486,0,0.905-0.343,1.001-0.82l2.111-10.514C16.449,1.804,15.79,1,14.911,1H4.92z M8.838,12.19L6,15.527V3.343C6,3.154,6.154,3,6.343,3h7.14c0.342,0,0.598,0.313,0.53,0.648l-0.413,2.055C13.566,5.876,13.414,6,13.238,6h-3.71C9.236,6,9,6.236,9,6.528v1.22C9,7.887,9.113,8,9.253,8h3.294c0.306,0,0.536,0.28,0.476,0.581l-0.614,3.058C12.366,11.849,12.181,12,11.967,12H9.25C9.091,12,8.941,12.069,8.838,12.19z"/>
</EntypoIcon>
);
export default EntypoFoursquare;
|
src/components/Notification/Notification.js
|
carbon-design-system/carbon-components-react
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import classNames from 'classnames';
import { settings } from 'carbon-components';
import Close16 from '@carbon/icons-react/lib/close/16';
import ErrorFilled20 from '@carbon/icons-react/lib/error--filled/20';
import CheckmarkFilled20 from '@carbon/icons-react/lib/checkmark--filled/20';
import WarningFilled20 from '@carbon/icons-react/lib/warning--filled/20';
const { prefix } = settings;
export class NotificationButton extends Component {
static propTypes = {
/**
* Specify an optional className to be applied to the notification button
*/
className: PropTypes.string,
/**
* Specify a label to be read by screen readers on the notification button
*/
ariaLabel: PropTypes.string,
/**
* Optional prop to specify the type of the Button
*/
type: PropTypes.string,
/**
* Provide a description for "close" icon that can be read by screen readers
*/
iconDescription: PropTypes.string,
/**
* Optional prop to allow overriding the icon rendering.
* Can be a React component class
*/
renderIcon: PropTypes.oneOfType([PropTypes.func, PropTypes.object]),
/**
* Specify an optional icon for the Button through a string,
* if something but regular "close" icon is desirable
*/
name: PropTypes.string,
/**
* Specify the notification type
*/
notificationType: PropTypes.oneOf(['toast', 'inline']),
};
static defaultProps = {
ariaLabel: 'close notification', // TODO: deprecate this prop
notificationType: 'toast',
type: 'button',
iconDescription: 'close icon',
renderIcon: Close16,
};
render() {
const {
ariaLabel,
className,
iconDescription,
type,
renderIcon: IconTag,
name,
notificationType,
...other
} = this.props;
const buttonClasses = classNames(
{
[`${prefix}--toast-notification__close-button`]:
notificationType === 'toast',
[`${prefix}--inline-notification__close-button`]:
notificationType === 'inline',
},
className
);
const iconClasses = classNames({
[`${prefix}--toast-notification__close-icon`]:
notificationType === 'toast',
[`${prefix}--inline-notification__close-icon`]:
notificationType === 'inline',
});
const NotificationButtonIcon = (() => {
if (Object(IconTag) === IconTag) {
return (
<IconTag aria-label={ariaLabel} className={iconClasses} name={name} />
);
}
return null;
})();
return (
<button
{...other}
type={type}
aria-label={iconDescription}
title={iconDescription}
className={buttonClasses}>
{NotificationButtonIcon}
</button>
);
}
}
export class NotificationTextDetails extends Component {
static propTypes = {
/**
* Pass in the children that will be rendered in NotificationTextDetails
*/
children: PropTypes.node,
/**
* Specify the title
*/
title: PropTypes.string,
/**
* Specify the sub-title
*/
subtitle: PropTypes.node,
/**
* Specify the caption
*/
caption: PropTypes.node,
/**
* Specify the notification type
*/
notificationType: PropTypes.oneOf(['toast', 'inline']),
};
static defaultProps = {
title: 'title',
subtitle: 'subtitle',
caption: 'caption',
notificationType: 'toast',
};
render() {
const { title, subtitle, caption, notificationType, ...other } = this.props;
if (notificationType === 'toast') {
return (
<div {...other} className={`${prefix}--toast-notification__details`}>
<h3 className={`${prefix}--toast-notification__title`}>{title}</h3>
<div className={`${prefix}--toast-notification__subtitle`}>
{subtitle}
</div>
<div className={`${prefix}--toast-notification__caption`}>
{caption}
</div>
{this.props.children}
</div>
);
}
if (notificationType === 'inline') {
return (
<div
{...other}
className={`${prefix}--inline-notification__text-wrapper`}>
<p className={`${prefix}--inline-notification__title`}>{title}</p>
<div className={`${prefix}--inline-notification__subtitle`}>
{subtitle}
</div>
{this.props.children}
</div>
);
}
}
}
const useIcon = kindProp =>
({
error: ErrorFilled20,
success: CheckmarkFilled20,
warning: WarningFilled20,
}[kindProp]);
const NotificationIcon = ({ notificationType, kind, iconDescription }) => {
const NotificationIconX = useIcon(kind);
return !NotificationIconX ? null : (
<NotificationIconX
className={`${prefix}--${notificationType}-notification__icon`}>
<title>{iconDescription}</title>
</NotificationIconX>
);
};
export class ToastNotification extends Component {
static propTypes = {
/**
* Pass in the children that will be rendered within the ToastNotification
*/
children: PropTypes.node,
/**
* Specify an optional className to be applied to the notification box
*/
className: PropTypes.string,
/**
* Specify what state the notification represents
*/
kind: PropTypes.oneOf(['error', 'info', 'success', 'warning']).isRequired,
/**
* Specify the title
*/
title: PropTypes.string.isRequired,
/**
* Specify the sub-title
*/
subtitle: PropTypes.node.isRequired,
/**
* By default, this value is "alert". You can also provide an alternate
* role if it makes sense from the accessibility-side
*/
role: PropTypes.string.isRequired,
/**
* Specify the caption
*/
caption: PropTypes.node,
/**
* Provide a function that is called when menu is closed
*/
onCloseButtonClick: PropTypes.func,
/**
* Provide a description for "close" icon that can be read by screen readers
*/
iconDescription: PropTypes.string.isRequired,
/**
* By default, this value is "toast". You can also provide an alternate type
* if it makes sense for the underlying `<NotificationTextDetails>` and `<NotificationButton>`
*/
notificationType: PropTypes.string,
/**
* Specify the close button should be disabled, or not
*/
hideCloseButton: PropTypes.bool,
/**
* Specify an optional duration the notification should be closed in
*/
timeout: PropTypes.number,
};
static defaultProps = {
kind: 'error',
title: 'provide a title',
subtitle: 'provide a subtitle',
caption: 'provide a caption',
role: 'alert',
notificationType: 'toast',
iconDescription: 'closes notification',
onCloseButtonClick: () => {},
hideCloseButton: false,
timeout: 0,
};
state = {
open: true,
};
componentDidMount() {
if (this.props.timeout) {
setTimeout(() => {
this.handleCloseButtonClick();
}, this.props.timeout);
}
}
handleCloseButtonClick = evt => {
this.setState({ open: false });
this.props.onCloseButtonClick(evt);
};
render() {
if (!this.state.open) {
return null;
}
const {
role,
notificationType,
onCloseButtonClick, // eslint-disable-line
iconDescription, // eslint-disable-line
className,
caption,
subtitle,
title,
kind,
hideCloseButton,
...other
} = this.props;
const classes = classNames(
`${prefix}--toast-notification`,
{
[`${prefix}--toast-notification--${this.props.kind}`]: this.props.kind,
},
className
);
return (
<div {...other} role={role} kind={kind} className={classes}>
<NotificationIcon
notificationType={notificationType}
kind={kind}
iconDescription={iconDescription}
/>
<NotificationTextDetails
title={title}
subtitle={subtitle}
caption={caption}
notificationType={notificationType}>
{this.props.children}
</NotificationTextDetails>
{!hideCloseButton && (
<NotificationButton
iconDescription={iconDescription}
notificationType={notificationType}
onClick={this.handleCloseButtonClick}
/>
)}
</div>
);
}
}
export class InlineNotification extends Component {
static propTypes = {
/**
* Pass in the children that will be rendered within the InlineNotification
*/
children: PropTypes.node,
/**
* Specify an optional className to be applied to the notification box
*/
className: PropTypes.string,
/**
* Specify what state the notification represents
*/
kind: PropTypes.oneOf(['error', 'info', 'success', 'warning']).isRequired,
/**
* Specify the title
*/
title: PropTypes.string.isRequired,
/**
* Specify the sub-title
*/
subtitle: PropTypes.node.isRequired,
/**
* By default, this value is "alert". You can also provide an alternate
* role if it makes sense from the accessibility-side
*/
role: PropTypes.string.isRequired,
/**
* Provide a function that is called when menu is closed
*/
onCloseButtonClick: PropTypes.func,
/**
* Provide a description for "close" icon that can be read by screen readers
*/
iconDescription: PropTypes.string.isRequired,
/**
* By default, this value is "inline". You can also provide an alternate type
* if it makes sense for the underlying `<NotificationTextDetails>` and `<NotificationButton>`
*/
notificationType: PropTypes.string,
/**
* Specify the close button should be disabled, or not
*/
hideCloseButton: PropTypes.bool,
};
static defaultProps = {
role: 'alert',
notificationType: 'inline',
iconDescription: 'closes notification',
onCloseButtonClick: () => {},
hideCloseButton: false,
};
state = {
open: true,
};
handleCloseButtonClick = evt => {
this.setState({ open: false });
this.props.onCloseButtonClick(evt);
};
render() {
if (!this.state.open) {
return null;
}
const {
role,
notificationType,
onCloseButtonClick, // eslint-disable-line
iconDescription, // eslint-disable-line
className,
subtitle,
title,
kind,
hideCloseButton,
...other
} = this.props;
const classes = classNames(
`${prefix}--inline-notification`,
{
[`${prefix}--inline-notification--${this.props.kind}`]: this.props.kind,
},
className
);
return (
<div {...other} role={role} kind={kind} className={classes}>
<div className={`${prefix}--inline-notification__details`}>
<NotificationIcon
notificationType={notificationType}
kind={kind}
iconDescription={iconDescription}
/>
<NotificationTextDetails
title={title}
subtitle={subtitle}
notificationType={notificationType}>
{this.props.children}
</NotificationTextDetails>
</div>
{!hideCloseButton && (
<NotificationButton
iconDescription={iconDescription}
notificationType={notificationType}
onClick={this.handleCloseButtonClick}
/>
)}
</div>
);
}
}
|
example/react-todo/index.js
|
justinjung04/treeful
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Treeful from '../../src/treeful';
import './index.scss';
import TodoController from './components/todo-controller';
import Todo from './components/todo';
class App extends Component {
constructor () {
super();
Treeful.dev();
Treeful.add('todos', []);
this.state = {
todos: Treeful.get('todos')
};
}
componentDidMount() {
this.unsubscribe = Treeful.subscribe('todos', this.updateTodos.bind(this));
}
componentWillUnmount() {
this.unsubscribe();
}
updateTodos(todos) {
this.setState({ todos });
}
render() {
return (
<div className='react'>
<TodoController />
<hr/>
<div className='todos'>
{ this.state.todos.map((item, index) => <Todo data={item} key={index}/>) }
</div>
</div>
);
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/app.js
|
jvstrpv/reactredux_2
|
import React, { Component } from 'react';
import SearchBar from '../containers/search_bar';
export default class App extends Component {
render() {
return (
<div>
<SearchBar />
</div>
);
}
}
|
src/components/Status.js
|
greg5green/isrobhomeyet
|
import React from 'react';
import {isHereNow} from '../services/status';
class Status extends React.Component {
constructor(props) {
super(props);
this.state = this.getRobStatusObject();
}
componentDidMount() {
this.updateInterval = setInterval(() => this.updateStatusText(), 1000);
}
componentWillUnmount() {
clearInterval(this.updateInterval);
}
getRobStatusObject() {
return {
robStatus: isHereNow() ? 'Yes' : 'No'
};
}
render() {
return <h1>{this.state.robStatus}</h1>;
}
updateStatusText() {
this.setState(this.getRobStatusObject());
}
}
export default Status;
|
components/__tests__/RadioButton-test.js
|
hellobrian/carbon-components-react
|
import React from 'react';
import RadioButton from '../RadioButton';
import { mount } from 'enzyme';
const render = (props) => mount(
<RadioButton
{...props}
className="extra-class"
name="test-name"
value="test-value"
/>
);
describe('RadioButton', () => {
describe('renders as expected', () => {
const wrapper = render({
checked: true,
});
const input = wrapper.find('input');
const label = wrapper.find('label');
const div = wrapper.find('div');
describe('input', () => {
it('is of type radio', () => {
expect(input.props().type).toEqual('radio');
});
it('has the expected class', () => {
expect(input.hasClass('bx--radio-button')).toEqual(true);
});
it('has a unique id set by default', () => {
expect(input.props().id).toBeDefined();
});
it('should have checked set when checked is passed', () => {
wrapper.setProps({ checked: true });
expect(input.props().checked).toEqual(true);
});
it('should set the name prop as expected', () => {
expect(input.props().name).toEqual('test-name');
});
});
describe('label', () => {
it('should set htmlFor', () => {
expect(label.props().htmlFor)
.toEqual(input.props().id);
});
it('should set the correct class', () => {
expect(label.props().className).toEqual('bx--radio-button__label');
});
it('should render a span with the correct class', () => {
const span = label.find('span');
expect(span.hasClass('bx--radio-button__appearance')).toEqual(true);
});
it('should render label text', () => {
wrapper.setProps({ labelText: 'test label text' });
expect(label.text()).toMatch(/test label text/);
});
});
describe('wrapper', () => {
it('should have the correct class', () => {
expect(div.hasClass('radioButtonWrapper')).toEqual(true);
});
it('should have extra classes applied', () => {
expect(div.hasClass('extra-class')).toEqual(true);
});
});
});
it('should set defaultChecked as expected', () => {
const wrapper = render({
defaultChecked: true,
});
const input = wrapper.find('input');
expect(input.props().defaultChecked).toEqual(true);
wrapper.setProps({ defaultChecked: false });
expect(input.props().defaultChecked).toEqual(false);
});
it('should set id if one is passed in', () => {
const wrapper = render({
id: 'unique-id',
});
const input = wrapper.find('input');
expect(input.props().id).toEqual('unique-id');
});
describe('events', () => {
it('should invoke onChange with expected arguments', () => {
const onChange = jest.fn();
const wrapper = render({ onChange });
const input = wrapper.find('input');
const inputElement = input.get(0);
inputElement.checked = true;
wrapper.find('input').simulate('change');
const call = onChange.mock.calls[0];
expect(call[0]).toEqual('test-value');
expect(call[1]).toEqual('test-name');
expect(call[2].target).toBe(inputElement);
});
});
});
|
src/app/index.js
|
ucokfm/admin-lte-react
|
import { AppContainer } from 'react-hot-loader';
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const rootEl = document.getElementById('root');
ReactDOM.render(
<AppContainer>
<App />
</AppContainer>,
rootEl
);
if (module.hot) {
module.hot.accept('./App', () => {
// If you use Webpack 2 in ES modules mode, you can
// use <App /> here rather than require() a <NextApp />.
// eslint-disable-next-line global-require
const NextApp = require('./App').default;
ReactDOM.render(
<AppContainer>
<NextApp />
</AppContainer>,
rootEl
);
});
}
|
src/client/devTools.js
|
cle1994/personal-website
|
/* ==========================================================================
* ./src/server/devtools.js
*
* DevTools Container
* ========================================================================== */
import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
export default createDevTools(
<LogMonitor />
);
|
src/svg-icons/device/signal-cellular-connected-no-internet-3-bar.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalCellularConnectedNoInternet3Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M22 8V2L2 22h16V8z"/><path d="M17 22V7L2 22h15zm3-12v8h2v-8h-2zm0 12h2v-2h-2v2z"/>
</SvgIcon>
);
DeviceSignalCellularConnectedNoInternet3Bar = pure(DeviceSignalCellularConnectedNoInternet3Bar);
DeviceSignalCellularConnectedNoInternet3Bar.displayName = 'DeviceSignalCellularConnectedNoInternet3Bar';
export default DeviceSignalCellularConnectedNoInternet3Bar;
|
__tests__/components/Sidebar-test.js
|
odedre/grommet-final
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React from 'react';
import renderer from 'react-test-renderer';
import Sidebar from '../../src/js/components/Sidebar';
// needed because this:
// https://github.com/facebook/jest/issues/1353
jest.mock('react-dom');
describe('Sidebar', () => {
it('has correct default options', () => {
const component = renderer.create(
<Sidebar>Testing</Sidebar>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
it('has correct size="large" and fixed=true rendering', () => {
const component = renderer.create(
<Sidebar size="large" fixed={true}>Testing</Sidebar>
);
let tree = component.toJSON();
expect(tree).toMatchSnapshot();
});
});
|
geonode/contrib/monitoring/frontend/src/components/organisms/error-detail/index.js
|
kartoza/geonode
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Tabs, Tab } from 'material-ui/Tabs';
import HoverPaper from '../../atoms/hover-paper';
import styles from './styles';
import actions from './actions';
const mapStateToProps = (state) => ({
errorDetails: state.errorDetails.response,
from: state.interval.from,
to: state.interval.to,
});
@connect(mapStateToProps, actions)
class ErrorDetail extends React.Component {
static propTypes = {
errorDetails: PropTypes.object,
errorId: PropTypes.number,
get: PropTypes.func.isRequired,
}
componentWillMount() {
this.props.get(this.props.errorId);
}
render() {
const errorDetails = this.props.errorDetails;
const result = {
client: {},
};
if (errorDetails) {
const date = new Date(errorDetails.created);
const year = date.getFullYear();
const month = `0${date.getMonth() + 1}`.slice(-2);
const day = `0${date.getDate()}`.slice(-2);
const hours = `0${date.getHours()}`.slice(-2);
const minutes = `0${date.getMinutes()}`.slice(-2);
const seconds = `0${date.getSeconds()}`.slice(-2);
const formatedDate = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
result.date = `Date: ${formatedDate}`;
result.service = `Service: ${errorDetails.service.name}`;
result.errorType = `Type: ${errorDetails.error_type}`;
result.errorData = errorDetails.error_data;
if (errorDetails.request) {
const request = errorDetails.request.request;
const url = `${request.path}`;
result.url = <span>URL: <a href={url}>{url}</a></span>;
const response = errorDetails.request.response;
result.errorCode = `Status code: ${response.status}`;
if (errorDetails.request.client) {
const client = errorDetails.request.client;
result.client.ip = `IP: ${client.ip}`;
result.client.userAgent = `Browser: ${client.user_agent}`;
result.client.userAgentFamily = `Browser Family: ${client.user_agent_family}`;
}
}
}
return (
<HoverPaper style={styles.content}>
<div style={styles.header}>
<h3 style={styles.title}>Error id: {this.props.errorId}</h3>
</div>
<Tabs>
<Tab label="Metadata">
<div style={styles.tab}>
<div>{result.date}</div>
<div>{result.service}</div>
<div>{result.errorType}</div>
<div>{result.errorCode}</div>
<div>{result.url}</div>
</div>
</Tab>
<Tab label="Client">
<div style={styles.tab}>
<div>{result.client.ip}</div>
<div>{result.client.userAgent}</div>
<div>{result.client.userAgentFamily}</div>
</div>
</Tab>
</Tabs>
<h3>Log</h3>
<pre style={styles.log}>{result.errorData}</pre>
</HoverPaper>
);
}
}
export default ErrorDetail;
|
src/apps/home/root.component.js
|
raquel/cuddly-tribble
|
import React from 'react';
import Technology from './technology.component.js';
import Walkthroughs from './walkthroughs.component.js';
import {getBorder, showFrameworkObservable} from '../common/colored-border';
export default class HomeRoot extends React.Component {
constructor() {
super();
this.state = {
frameworkInspector: false,
};
}
componentWillMount() {
this.subscription = showFrameworkObservable.subscribe(newValue => this.setState({frameworkInspector: newValue}));
}
render() {
return (
<div style={this.state.frameworkInspector ? {border: getBorder('react')} : {}}>
{this.state.frameworkInspector &&
<div>(built with React)</div>
}
<div className="container">
<div className="row">
<h4 className="light">
Introduction
</h4>
<p className="caption">
Single-spa is a javascript libary that allows for many small applications to coexist in one single page application.
This website is a demo application that shows off what single-spa can do.
For more information about single-spa, go to the <a href="https://github.com/CanopyTax/single-spa" target="_blank">single-spa Github page</a>.
Additionally, this website's code can be found at the <a href="https://github.com/CanopyTax/single-spa-examples" target="_blank">single-spa-examples Github</a>.
While you're here, check out the following features:
</p>
<Walkthroughs />
</div>
<div className="row">
<h4 className="light">
Framework examples
</h4>
<p className="caption">
Single-spa allows for multiple frameworks to coexist in the same single page application.
</p>
<div className="row">
<Technology
imgSrc="https://facebook.github.io/react/img/logo.svg"
imgBackgroundColor="#222222"
cardTitle="React"
href="/#/react"
explanation={`Yep we've got a React example. We actually just borrowed it from the react-router examples, to show how easy it is to migrate an existing app into single-spa`}
/>
<Technology
imgSrc="https://angularjs.org/img/ng-logo.png"
cardTitle="Angular 1"
href="/#/angular1"
explanation={`Angular 1 has some quirks, but works just fine when you use the single-spa-angular1 npm library to help you set up your app`}
/>
<Technology
imgSrc="/images/angular.svg"
imgBackgroundColor="#1976D2"
cardTitle="Angular 2"
href="/#/angular2"
explanation={`Angular 2 is compatible with single-spa, check out a simple 'Hello World' in the example.`}
/>
<Technology
imgSrc="https://vuejs.org/images/logo.png"
cardTitle="Vue.js"
href="/#/vue"
explanation={`Vue.js is compatible with single-spa. Easily get started with the single-spa-vue plugin.`}
/>
<Technology
imgSrc="/images/svelte.jpg"
cardTitle="Svelte"
href="/#/svelte"
explanation={`Svelte is compatible with single-spa. Easily get started with the single-spa-svelte plugin.`}
/>
<Technology
imgSrc="https://camo.githubusercontent.com/31415a8c001234dbf4875c2c5a44b646fb9338b4/68747470733a2f2f63646e2e7261776769742e636f6d2f646576656c6f7069742f62343431366435633932623734336462616563316536386263346332376364612f7261772f333233356463353038663765623833346562663438343138616561323132613035646631336462312f7072656163742d6c6f676f2d7472616e732e737667"
cardTitle="Preact"
href="/#/preact"
explanation={`Preact is compatible with single-spa. Easily get started with the single-spa-preact plugin.`}
/>
<Technology
imgSrc="http://xitrus.es/blog/imgs/vnll.jpg"
cardTitle="Vanilla"
href="/#/vanilla"
explanation={`
If you want to write single-spa applications in vanilla javascript, that's fine too.
`}
/>
<Technology
imgSrc="/images/inferno-logo.png"
cardTitle="Inferno"
href="/#/inferno"
explanation={`
Inferno is compatible with single-spa. Easily get started with the single-spa-inferno plugin.
`}
/>
</div>
</div>
<div className="row">
<h4 className="light">
Build system examples
</h4>
<p className="caption">
Each application chooses it's own build system, which will fit into the root single-spa application at runtime.
</p>
<div className="row">
<Technology
imgSrc="https://avatars0.githubusercontent.com/webpack?&s=256"
cardTitle="Webpack"
href="/#/react"
explanation={`The React example is built with Webpack, and even uses require.ensure for extra lazy loading.`}
/>
<Technology
imgSrc="https://avatars3.githubusercontent.com/u/3802108?v=3&s=200"
cardTitle="SystemJS"
href="/#/angular1"
explanation={`The navbar app, home app, and Angular 1 app are all built with JSPM / SystemJS.`}
/>
<Technology
imgSrc="http://4.bp.blogspot.com/-rI6g4ZgVqBA/Uv8fPnl9TLI/AAAAAAAAMZU/tbylo5ngisg/s1600/iFrame+Generator.jpg"
cardTitle="Iframe"
href="/#/vanilla"
explanation={`
Putting things in iframes is the wrong thing to do many times, but there are valid use cases for it.
If you put a single-spa application into an iframe, you get a whole new DOM and global namespace for variables.
But the cons include degraded performance and trickier inter-app communication.
`}
/>
</div>
</div>
</div>
</div>
);
}
componentWillUnmount() {
this.subscription.dispose();
}
}
|
app/components/transactions/AmountInput.js
|
jpsierens/budget
|
// @flow
import React from 'react';
type Props = {
value: String,
onInputChange: () => void
}
const AmountInput = ({ onInputChange, value } : Props) => {
let input;
return (
<div>
<label>Amount</label>
<input
type="text"
ref={(e) => { input = e; }}
value={value}
onChange={() =>
onInputChange({ amount: input.value })
}/>
</div>
);
};
export default AmountInput;
|
src/components/ToolbarCallButton/ToolbarCallButton.js
|
dialogs/dialog-web-components
|
/*
* Copyright 2019 dialog LLC <info@dlg.im>
* @flow
*/
import React from 'react';
import classNames from 'classnames';
import Icon from '../Icon/Icon';
import styles from './ToolbarCallButton.css';
export type Props = {
className?: string,
disabled: boolean,
onClick: (event: SyntheticMouseEvent<>) => mixed,
};
function ToolbarCallButton(props: Props) {
const className = classNames(
styles.container,
{
[styles.disabled]: props.disabled,
},
props.className,
);
if (props.disabled) {
return (
<div className={className} id="toolbar_call_button">
<Icon glyph="phone_outline" className={styles.icon} size={28} />
</div>
);
}
return (
<div className={className} id="toolbar_call_button" onClick={props.onClick}>
<Icon glyph="phone_outline" className={styles.icon} size={28} />
</div>
);
}
export default ToolbarCallButton;
|
src/App.js
|
serban-petrescu/serban-petrescu.github.io
|
import React, { Component } from 'react';
import data from './data';
import Hero from './hero/Hero';
import Introduction from './intro/Introduction';
import Footer from './footer/Footer';
import Highlights from './intro/Highlights';
import ExperienceList from './experience/ExperienceList';
import GalleryModal from './common/GalleryModal';
import ProjectList from './experience/ProjectsList';
export default class App extends Component {
constructor(props) {
super(props);
this.state = data;
}
render() {
const state = this.state;
const onClickGallery = ({ name, images }) => modal.open(name, images);
let modal;
return (
<div>
<Hero name={state.name} title={state.role} avatar={state.avatar} linkedin={state.accounts.linkedin} cv={state.cv} />
<Introduction cover={state.cover} summary={state.summary} social={data.accounts} />
<Highlights {...state.highlights} onClickGallery={onClickGallery} />
<div id='work' />
<ExperienceList title='Work History' items={state.experience.work} />
<div id='certifications' />
<ExperienceList title='Certifications' items={state.experience.certifications} />
<div id='academic' />
<ExperienceList title='Education' items={state.experience.academic} />
<div id='projects' />
<ProjectList projects={data.projects} onClickGallery={onClickGallery} />
<GalleryModal ref={ref => modal = ref} />
<div className='section-divider'/>
<Footer {...state.site} />
</div>
);
}
}
|
frontend/test/app/components/MainInstallButton-test.js
|
6a68/testpilot
|
import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow } from 'enzyme';
import MainInstallButton from '../../../src/app/components/MainInstallButton';
describe('app/components/MainInstallButton', () => {
let subject, props;
beforeEach(() => {
props = {
restartRequired: false,
sendToGA: sinon.spy(),
eventCategory: 'test',
hasAddon: false,
isFirefox: true,
isMinFirefox: true,
isMobile: false,
installAddon: sinon.spy()
};
subject = shallow(<MainInstallButton {...props} />);
});
const findByL10nID = id => subject.findWhere(el => id === el.props()['data-l10n-id']);
it('does not show an install button on mobile', () => {
expect(subject.find('.default-btn-msg')).to.have.property('length', 1);
subject.setProps({ isMobile: true });
expect(subject.find('.default-btn-msg')).to.have.property('length', 0);
});
it('shows a requires desktop message on mobile firefox', () => {
subject.setProps({ isMobile: true });
expect(findByL10nID('landingRequiresDesktop').length).to.equal(1);
});
it('shows an install button on desktop firefox', () => {
expect(findByL10nID('landingInstallButton').length).to.equal(1);
});
it('shows an install firefox button on other desktop browsers', () => {
subject.setProps({ isMinFirefox: false, isFirefox: false });
expect(findByL10nID('landingDownloadFirefoxTitle').length).to.equal(1);
});
it('shows an upgrade button for firefox < minVersion', () => {
subject.setProps({ isMinFirefox: false });
expect(findByL10nID('landingUpgradeFirefoxTitle').length).to.equal(1);
});
it('shows installing text while installing', () => {
subject.setState({ isInstalling: true });
expect(findByL10nID('landingInstallingButton').length).to.equal(1);
});
it('shows installed text when hasAddon is true', () => {
subject.setProps({ hasAddon: true });
expect(findByL10nID('landingInstalledButton').length).to.equal(1);
});
it('calls installAddon on button click', () => {
subject.find('.install').simulate('click', {});
expect(props.installAddon.calledOnce).to.equal(true);
});
it('does nothing on button click when hasAddon is true', () => {
subject.setProps({ hasAddon: true });
subject.find('.install').simulate('click', {});
expect(props.installAddon.called).to.equal(false);
});
});
|
client/containers/Home/HomeContainer.js
|
Moises404/rapbot
|
import React from 'react'
import PostApp from '../../components/PostApp/PostApp'
class HomeContainer extends React.Component {
static displayName = 'HomeContainer'
render() {
return (
<div className="Home">
<PostApp {...this.props}/>
</div>
)
}
}
export default HomeContainer
|
src/demos/custom-layers/4-custom-attribute/root.js
|
uber-common/vis-academy
|
import React from 'react';
import {render} from 'react-dom';
import App from './src/app';
const element = document.getElementById('root');
render(<App />, element);
if (module.hot) {
module.hot.accept('./src/app', () => {
const Next = require('./src/app').default;
render(<Next />, element);
});
}
|
webapp/src/lib/form/FormFieldContainer.js
|
cpollet/itinerants
|
import React from 'react';
class FormFieldContainer extends React.Component {
onChange(event) {
if (typeof event.target.selectedOptions !== 'undefined') {
let value = [];
for (let i = 0; i < event.target.selectedOptions.length; i++) {
value.push(event.target.selectedOptions[i].value);
}
this.context.update(this.props.name, value);
} else {
this.context.update(this.props.name, event.target.value);
}
}
componentWillMount() {
this.context.update(this.props.name, this.context.fieldValues[this.props.name]);
}
render() {
return React.cloneElement(this.props.children, {
onChange: this.onChange.bind(this),
value: this.context.fieldValues[this.props.name]
});
}
}
FormFieldContainer.propTypes = {
children: React.PropTypes.element.isRequired,
/**
* The name of the wrapped field.
*/
name: React.PropTypes.string.isRequired
};
FormFieldContainer.contextTypes = {
/**
* Method to use when the wrapped field is updated. This method expects to have as 1st parameter the field's name
* and as 2nd parameter the field's value.
*/
update: React.PropTypes.func.isRequired,
fieldValues: React.PropTypes.object
};
export default FormFieldContainer;
|
src/components/main.component.js
|
MichelLosier/cardspace
|
import React from 'react';
import { Route, Link } from 'react-router-dom';
import RoomLobby from './rooms/room-lobby.component';
import UserService from '../services/user.service';
import UserEntry from './user/user-entry.component';
import Room from './rooms/room.component';
import '../main.css';
const User$ = new UserService();
class Main extends React.Component {
constructor(){
super();
this.state = {
userLoggedIn: true,
user: {
id: undefined,
alias: undefined
}
}
this.setLocalUser = this.setLocalUser.bind(this);
}
componentDidMount(){
this.checkLocalUser();
}
checkLocalUser(){
const id = window.localStorage.getItem('uid');
if (id) {
User$.getUser(id, (user) => {
if (!user.id) {
console.log('user in local storage not found on server.. create new user');
this.setState({userLoggedIn: false});
} else {
console.log('existing user found in local storage.. setting.')
this.setLocalUser(user);
}
});
} else {
this.setState({userLoggedIn: false});
}
}
setLocalUser(user) {
const id = window.localStorage.getItem('uid');
if (id) {
this.setState({
userLoggedIn: true,
user: user
});
}
}
//Views
_UserEntry(props){
return(
<UserEntry
setLocalUser={this.setLocalUser}
/>
);
}
_RoomLobby(props){
return(
<RoomLobby
{...props}
/>
);
}
_Room(props){
return(
<Room
{...props}
/>
)
}
render(){
const state = this.state;
return(
<div>
<div>
<div className="main-header layout-container">
<div>
<h1><a href="/">cardspace</a></h1>
</div>
<div>
<p>UserId: {state.user.id}</p>
<p>Logged In: {state.user.alias}</p>
</div>
</div>
<div className="main-body layout-container">
{!state.userLoggedIn &&
this._UserEntry()
}
<Route
exact path="/"
render={(props) => this._RoomLobby(props)}
/>
<Route
path="/room/:roomId"
render={(props) => this._Room(props)}
/>
</div>
</div>
</div>
);
}
}
export default Main;
|
mxcube3/ui/components/SampleView/MotorInput.js
|
amilan/mxcube3
|
import React from 'react';
import cx from 'classnames';
import { Button } from 'react-bootstrap';
import PopInput from '../PopInput/PopInput';
import './motor.css';
export default class MotorInput extends React.Component {
constructor(props) {
super(props);
this.handleKey = this.handleKey.bind(this);
this.stopMotor = this.stopMotor.bind(this, props.motorName);
this.stepIncrement = this.stepChange.bind(this, props.motorName, 1);
this.stepDecrement = this.stepChange.bind(this, props.motorName, -1);
}
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.props.value) {
this.refs.motorValue.value = nextProps.value.toFixed(this.props.decimalPoints);
this.refs.motorValue.defaultValue = nextProps.value.toFixed(this.props.decimalPoints);
}
}
handleKey(e) {
e.preventDefault();
e.stopPropagation();
if ([13, 38, 40].includes(e.keyCode) && this.props.state === 2) {
this.props.save(e.target.name, e.target.valueAsNumber);
this.refs.motorValue.value = this.props.value.toFixed(this.props.decimalPoints);
} else if (this.props.state === 4) {
this.refs.motorValue.value = this.props.value.toFixed(this.props.decimalPoints);
}
}
stepChange(name, operator) {
const { value, step } = this.props;
const newValue = value + step * operator;
this.refs.motorValue.value = this.props.value.toFixed(this.props.decimalPoints);
this.refs.motorValue.defaultValue = newValue;
this.props.save(name, newValue);
}
stopMotor(name) {
this.props.stop(name);
}
render() {
const { value, motorName, step, suffix, decimalPoints } = this.props;
const valueCropped = value.toFixed(decimalPoints);
let inputCSS = cx('form-control rw-input', {
'input-bg-moving': this.props.state === 4 || this.props.state === 3,
'input-bg-ready': this.props.state === 2,
'input-bg-fault': this.props.state <= 1,
'input-bg-onlimit': this.props.state === 5
});
let data = { state: 'IMMEDIATE', value: step };
return (
<div className="motor-input-container">
<p className="motor-name">{this.props.label}</p>
<form className="inline form-inline form-group" onSubmit={this.handleKey} noValidate>
<div className="rw-widget rw-numberpicker">
<span className="rw-select">
<button
type="button"
className="rw-btn"
disabled={this.props.state !== 2}
onClick={this.stepIncrement}
>
<i aria-hidden="true" className="rw-i rw-i-caret-up"></i>
</button>
<button
type="button"
className="rw-btn"
disabled={this.props.state !== 2}
onClick={this.stepDecrement}
>
<i aria-hidden="true" className="rw-i rw-i-caret-down"></i>
</button>
</span>
<input
ref="motorValue"
className={inputCSS}
onKeyUp={this.handleKey}
type="number"
step={step}
defaultValue={valueCropped}
name={motorName}
disabled={this.props.state !== 2}
/>
</div>
<span>
{this.props.saveStep ?
<PopInput
className="step-size"
ref={motorName} name="Step size" pkey={`${motorName.toLowerCase()}Step`}
data={data} onSave={this.props.saveStep} suffix={suffix}
/>
: null
}
</span>
<span>
{this.props.state === 4 ?
<Button
className="btn-xs motor-abort"
bsStyle="danger"
disabled={this.props.state !== 4}
onClick={this.stopMotor}
>
<i className="glyphicon glyphicon-remove" />
</Button>
: null
}
</span>
</form>
</div>
);
}
}
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
|
choy1379/MoonEDM
|
import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
src/svg-icons/navigation/more-vert.js
|
igorbt/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationMoreVert = (props) => (
<SvgIcon {...props}>
<path d="M12 8c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zm0 2c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm0 6c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
NavigationMoreVert = pure(NavigationMoreVert);
NavigationMoreVert.displayName = 'NavigationMoreVert';
NavigationMoreVert.muiName = 'SvgIcon';
export default NavigationMoreVert;
|
modules/__tests__/Router-test.js
|
arbas/react-router
|
/*eslint-env mocha */
/*eslint react/prop-types: 0*/
import expect from 'expect'
import React from 'react'
import createHistory from 'history/lib/createMemoryHistory'
import Router from '../Router'
import Route from '../Route'
describe('Router', function () {
let node
beforeEach(function () {
node = document.createElement('div')
})
afterEach(function () {
React.unmountComponentAtNode(node)
})
const Parent = React.createClass({
render() {
return <div>parent{this.props.children}</div>
}
})
const Child = React.createClass({
render() {
return <div>child</div>
}
})
it('renders routes', function (done) {
React.render((
<Router history={createHistory('/')}>
<Route path="/" component={Parent} />
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('parent')
done()
})
})
it('renders child routes when the parent does not have a path', function (done) {
React.render((
<Router history={createHistory('/')}>
<Route component={Parent}>
<Route component={Parent}>
<Route path="/" component={Child} />
</Route>
</Route>
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('parentparentchild')
done()
})
})
it('renders nested children correctly', function (done) {
React.render((
<Router history={createHistory('/hello')}>
<Route component={Parent}>
<Route path="hello" component={Child} />
</Route>
</Router>
), node, function () {
expect(node.textContent.trim()).toMatch(/parent/)
expect(node.textContent.trim()).toMatch(/child/)
done()
})
})
it('renders the child\'s component when it has no component', function (done) {
React.render((
<Router history={createHistory('/hello')}>
<Route>
<Route path="hello" component={Child} />
</Route>
</Router>
), node, function () {
expect(node.textContent.trim()).toMatch(/child/)
done()
})
})
it('renders with a custom `createElement` prop', function(done) {
const Wrapper = React.createClass({
render() {
const { Component } = this.props
return <Component fromWrapper="wrapped" />
}
})
const Component = React.createClass({
render() {
return <div>{this.props.fromWrapper}</div>
}
})
React.render((
<Router history={createHistory('/')} createElement={Component => <Wrapper Component={Component} />}>
<Route path="/" component={Component}/>
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('wrapped')
done()
})
})
describe('with named components', function() {
it('renders the named components', function(done) {
const Parent = React.createClass({
render() {
return (
<div>
{this.props.children.sidebar}-{this.props.children.content}
</div>
)
}
})
const Sidebar = React.createClass({
render() {
return <div>sidebar</div>
}
})
const Content = React.createClass({
render() {
return <div>content</div>
}
})
React.render((
<Router history={createHistory('/')}>
<Route component={Parent}>
<Route path="/" components={{sidebar: Sidebar, content: Content}} />
</Route>
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('sidebar-content')
done()
})
})
})
describe('at a route with special characters', function () {
it('does not double escape', function(done) {
// https://github.com/rackt/react-router/issues/1574
let MyComponent = React.createClass({
render () { return <div>{this.props.params.some_token}</div> }
})
React.render((
<Router history={createHistory('/point/aaa%2Bbbb')}>
<Route path="point/:some_token" component={MyComponent} />
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('aaa+bbb')
done()
})
})
it('does not double escape when nested', function(done) {
// https://github.com/rackt/react-router/issues/1574
let MyWrapperComponent = React.createClass({
render () { return this.props.children }
})
let MyComponent = React.createClass({
render () { return <div>{this.props.params.some_token}</div> }
})
React.render((
<Router history={createHistory('/point/aaa%2Bbbb')}>
<Route component={MyWrapperComponent}>
<Route path="point/:some_token" component={MyComponent} />
</Route>
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('aaa+bbb')
done()
})
})
it('is happy to have colons in parameter values', function(done) {
// https://github.com/rackt/react-router/issues/1759
let MyComponent = React.createClass({
render () { return <div>{this.props.params.foo}</div> }
})
React.render((
<Router history={createHistory('/ns/aaa:bbb/bar')}>
<Route path="ns/:foo/bar" component={MyComponent} />
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('aaa:bbb')
done()
})
})
it('handles % in parameters', function(done) {
// https://github.com/rackt/react-router/issues/1766
let MyComponent = React.createClass({
render () { return <div>{this.props.params.name}</div> }
})
React.render((
<Router history={createHistory('/company/CADENCE%20DESIGN%20SYSTEM%20INC%20NOTE%202.625%25%2060')}>
<Route path="/company/:name" component={MyComponent} />
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('CADENCE DESIGN SYSTEM INC NOTE 2.625% 60')
done()
})
})
it('handles forward slashes', function(done) {
// https://github.com/rackt/react-router/issues/1865
class Parent extends React.Component {
render() {
return <div>{this.props.children} </div>
}
}
class Child extends React.Component {
render() {
const {params} = this.props
return <h1>{params.name}</h1>
}
}
React.render((
<Router history={createHistory('/apple%2Fbanana')}>
<Route component={Parent}>
<Route path='/:name' component={Child} />
</Route>
</Router>
), node, function () {
expect(node.textContent.trim()).toEqual('apple/banana')
done()
})
})
})
})
|
addons/themes/txt/layouts/Blog.js
|
rendact/rendact
|
import $ from 'jquery'
import React from 'react';
import gql from 'graphql-tag';
import {graphql} from 'react-apollo';
import moment from 'moment';
import {Link} from 'react-router';
import scrollToElement from 'scroll-to-element';
let Blog = React.createClass({
componentDidMount(){
require('../assets/css/main.css')
},
componentWillMount(){
document.body.className = "homepage";
},
handleScrolly(e){
scrollToElement("#inti", {
duration: 1500,
offset: 0,
ease: 'in-sine'
})
},
render(){
let { theConfig, latestPosts: data, thePagination, loadDone } = this.props;
return (
<div>
<div id="page-wrapper">
<header id="header">
<div className="logo container">
<div>
<h1><Link to={"/"}>{theConfig?theConfig.name:"Rendact"} </Link></h1>
<p>{theConfig?theConfig.tagline:"Hello, you are in Rendact"}</p>
</div>
</div>
</header>
<nav id="nav">
{this.props.theMenu()}
</nav>
<div id="banner-wrapper">
<section id="banner">
<h2><Link to={"/"}>{theConfig?theConfig.name:"Rendact"}</Link></h2>
<p>{theConfig?theConfig.tagline:"Hello, you are in Rendact"}</p>
<a href="#" className="button" onClick={this.handleScrolly}>Alright let's go</a>
</section>
</div>
<div id="main-wrapper">
<div id="main" className="container">
<div className="row 200%">
<div className="12u">
<section id="inti" className="box features">
<h2 className="major"><span>Posts</span></h2>
<div>
<div className="row">
{data && data.map((post, index) => (
<div className="6u 12u(mobile)">
<section className="box feature">
<Link className="image featured" to={"/post/" + post.id}>
<img src={post.imageFeatured ? post.imageFeatured.blobUrl: require('images/logo-128.png') } alt="" />
</Link>
<h3><Link to={"/post/" + post.id}>{post.title && post.title}</Link></h3>
<p dangerouslySetInnerHTML={{__html: post.content ? post.content.slice(0, 160):""}} />
<Link className="button" to={"/post/" + post.id}>Read More</Link>
</section>
</div>
))}
</div>
</div>
</section>
</div>
</div>
</div>
</div>
<footer id="footer" className="container">
{this.props.footerWidgets &&
this.props.footerWidgets.map((fw, idx) => <div className="row 200%"><div className="12u"><section>{fw}</section></div></div>)}
<div className="row 200%">
<div className="12u">
<section>
<h2 className="major"><span>Get in touch</span></h2>
<ul className="contact">
<li><a className="icon fa-facebook" href="#"><span className="label">Facebook</span></a></li>
<li><a className="icon fa-twitter" href="#"><span className="label">Twitter</span></a></li>
<li><a className="icon fa-instagram" href="#"><span className="label">Instagram</span></a></li>
<li><a className="icon fa-dribbble" href="#"><span className="label">Dribbble</span></a></li>
<li><a className="icon fa-google-plus" href="#"><span className="label">Google+</span></a></li>
</ul>
</section>
</div>
</div>
<div id="copyright">
<ul className="menu">
<li>© Rendact. All rights reserved</li><li>Design: <a href="http://html5up.net">HTML5 UP</a></li>
</ul>
</div>
</footer>
</div>
</div>
)
}
});
export default Blog;
|
packages/material-ui-icons/src/PinDrop.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let PinDrop = props =>
<SvgIcon {...props}>
<path d="M18 8c0-3.31-2.69-6-6-6S6 4.69 6 8c0 4.5 6 11 6 11s6-6.5 6-11zm-8 0c0-1.1.9-2 2-2s2 .9 2 2-.89 2-2 2c-1.1 0-2-.9-2-2zM5 20v2h14v-2H5z" />
</SvgIcon>;
PinDrop = pure(PinDrop);
PinDrop.muiName = 'SvgIcon';
export default PinDrop;
|
src-example/components/molecules/Field/index.js
|
SIB-Colombia/biodiversity_catalogue_v2_frontend
|
import React from 'react'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import { Label, Input, Block } from 'components'
const Error = styled(Block)`
margin: 0.5rem 0 0;
`
const Wrapper = styled.div`
margin-bottom: 1rem;
input[type="checkbox"],
input[type="radio"] {
margin-right: 0.5rem;
}
label {
vertical-align: middle;
}
`
const Field = ({ error, name, invalid, label, type, ...props }) => {
const inputProps = { id: name, name, type, invalid, 'aria-describedby': `${name}Error`, ...props }
const renderInputFirst = type === 'checkbox' || type === 'radio'
return (
<Wrapper>
{renderInputFirst && <Input {...inputProps} />}
{label && <Label htmlFor={inputProps.id}>{label}</Label>}
{renderInputFirst || <Input {...inputProps} />}
{invalid && error &&
<Error id={`${name}Error`} role="alert" palette="danger">
{error}
</Error>
}
</Wrapper>
)
}
Field.propTypes = {
name: PropTypes.string.isRequired,
invalid: PropTypes.bool,
error: PropTypes.string,
label: PropTypes.string,
type: PropTypes.string,
}
Field.defaultProps = {
type: 'text',
}
export default Field
|
src/docs/components/headline/HeadlineExamplesDoc.js
|
karatechops/grommet-docs
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Headline from 'grommet/components/Headline';
import InteractiveExample from '../../../components/InteractiveExample';
const PROPS_SCHEMA = {
strong: { value: true },
size: { options: ['small', 'medium', 'large', 'xlarge'] }
};
export default class HeadlineExamplesDoc extends Component {
constructor () {
super();
this.state = { elementProps: {} };
}
render () {
const { elementProps } = this.state;
const element = <Headline {...elementProps}>Sample Headline</Headline>;
return (
<InteractiveExample contextLabel='Headline' contextPath='/docs/headline'
preamble={`import Headline from 'grommet/components/Headline';`}
propsSchema={PROPS_SCHEMA}
element={element}
onChange={elementProps => this.setState({ elementProps })} />
);
}
};
|
src/svg-icons/image/edit.js
|
rhaedes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageEdit = (props) => (
<SvgIcon {...props}>
<path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
</SvgIcon>
);
ImageEdit = pure(ImageEdit);
ImageEdit.displayName = 'ImageEdit';
export default ImageEdit;
|
senic_hub/setup_app/components/SelectComponentDevices.js
|
grunskis/nuimo-hub-backend
|
import React from 'react'
import { Text } from 'react-native'
import { Button } from 'react-native-elements'
import Screen from './Screen'
import Settings from '../Settings'
export default class AddComponent extends Screen {
constructor(props) {
super(props)
this.setNavigationButtons([], [{
'title': "Save",
'id': 'save',
//TODO: Replace the dummy deviceId value
'onPress': () => this.saveComponent('001788176885')
}])
}
saveComponent(deviceId) {
let body = JSON.stringify({device_id: deviceId})
let params = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: body,
}
fetch(Settings.HUB_API_URL + 'nuimos/0/components', params)
.then(() => this.dismissAllModals())
.catch((error) => console.error(error))
}
render() {
return (
<Text>TODO</Text>
)
}
}
|
examples/src/components/Creatable.js
|
dmatteo/react-select
|
import React from 'react';
import Select from 'react-select';
var CreatableDemo = React.createClass({
displayName: 'CreatableDemo',
propTypes: {
hint: React.PropTypes.string,
label: React.PropTypes.string
},
getInitialState () {
return {
multi: true,
multiValue: [],
options: [
{ value: 'R', label: 'Red' },
{ value: 'G', label: 'Green' },
{ value: 'B', label: 'Blue' }
],
value: undefined
};
},
handleOnChange (value) {
const { multi } = this.state;
if (multi) {
this.setState({ multiValue: value });
} else {
this.setState({ value });
}
},
render () {
const { multi, multiValue, options, value } = this.state;
return (
<div className="section">
<h3 className="section-heading">{this.props.label}</h3>
<Select.Creatable
multi={multi}
options={options}
onChange={this.handleOnChange}
value={multi ? multiValue : value}
/>
<div className="hint">{this.props.hint}</div>
<div className="checkbox-list">
<label className="checkbox">
<input
type="radio"
className="checkbox-control"
checked={multi}
onChange={() => this.setState({ multi: true })}
/>
<span className="checkbox-label">Multiselect</span>
</label>
<label className="checkbox">
<input
type="radio"
className="checkbox-control"
checked={!multi}
onChange={() => this.setState({ multi: false })}
/>
<span className="checkbox-label">Single Value</span>
</label>
</div>
</div>
);
}
});
module.exports = CreatableDemo;
|
src/DropdownButton.js
|
pombredanne/react-bootstrap
|
import React from 'react';
import Dropdown from './Dropdown';
import omit from 'lodash-compat/object/omit';
import pick from 'lodash-compat/object/pick';
import Button from './Button';
class DropdownButton extends React.Component {
render() {
let { bsStyle, bsSize, disabled } = this.props;
let { title, children, ...props } = this.props;
let dropdownProps = pick(props, Object.keys(Dropdown.ControlledComponent.propTypes));
let toggleProps = omit(props, Object.keys(Dropdown.ControlledComponent.propTypes));
return (
<Dropdown {...dropdownProps}
bsSize={bsSize}
bsStyle={bsStyle}
>
<Dropdown.Toggle
{...toggleProps}
disabled={disabled}
>
{title}
</Dropdown.Toggle>
<Dropdown.Menu>
{children}
</Dropdown.Menu>
</Dropdown>
);
}
}
DropdownButton.propTypes = {
disabled: React.PropTypes.bool,
bsStyle: Button.propTypes.bsStyle,
bsSize: Button.propTypes.bsSize,
/**
* When used with the `title` prop, the noCaret option will not render a caret icon, in the toggle element.
*/
noCaret: React.PropTypes.bool,
title: React.PropTypes.node.isRequired,
...Dropdown.propTypes,
};
DropdownButton.defaultProps = {
disabled: false,
pullRight: false,
dropup: false,
navItem: false,
noCaret: false
};
export default DropdownButton;
|
client/src/App.js
|
CrashsLanding/petfinder-searcher
|
import React, { Component } from 'react';
import FacetContainer from './Components/FacetContainer/FacetContainer';
import AnimalContainer from './Components/AnimalContainer/AnimalContainer';
import axios from 'axios';
import config from './config';
import './App.css';
import _ from 'lodash';
class App extends Component {
constructor(props) {
super(props);
this.endpoint = config.apiEndpoint;
this.state = {
animals: [],
facets: {},
selectedFacets: {},
andFacets: [],
andAbleFacets: ["options", "breeds"]
};
}
onFacetChange(updatedFacets) {
this.setState({
selectedFacets: updatedFacets
});
}
onAndFacetChange(updatedFacets) {
this.setState({
andFacets: updatedFacets
});
}
componentDidMount() {
this.loadAnimals().then(animals => {
this.setState({
animals: animals
});
this.loadFacets();
});
}
processPet(pet){
let options = pet.options;
let index = options.indexOf("noClaws");
if (index !== -1){
options[index] = "declawed";
}
return pet;
}
loadAnimals() {
return axios.get(this.endpoint)
.then(response => {
let pets = _.map(response.data['pets'], pet => this.processPet(pet));
return _.sortBy(pets, pet => pet.name);
});
}
loadFacets() {
// let petType = this.createFacetEntriesForFacetName('petType');
let breeds = this.createFacetEntriesForFacetName('breeds');
let age = this.createFacetEntriesForFacetName('age');
let size = this.createFacetEntriesForFacetName('size');
let sex = this.createFacetEntriesForFacetName('sex');
let options = this.createFacetEntriesForFacetName('options');
let colors = this.createFacetEntriesForFacetName('colors');
let shelter = this.createFacetEntriesForFacetName('shelter');
this.setState({
facets: { shelter, options, breeds, colors, age, size, sex }
});
}
createFacetEntriesForFacetName(facetName) {
let animals = this.state.animals;
let availableEntriesForFacet = _.flatMap(animals, animal => _.get(animal, facetName));
return availableEntriesForFacet.reduce((map, obj) => {
map[obj] = false;
return map;
}, {});
}
render() {
return (
<div className="App">
<div className="container-fluid app-container">
<div className="row">
<FacetContainer onFacetChange={this.onFacetChange.bind(this)}
onAndFacetChange={this.onAndFacetChange.bind(this)}
andFacets={this.state.andFacets}
andAbleFacets={this.state.andAbleFacets}
facets={this.state.facets}>
</FacetContainer>
<AnimalContainer selectedFacets={this.state.selectedFacets}
andFacets={this.state.andFacets}
animals={this.state.animals}>
</AnimalContainer>
</div>
</div>
</div>
);
}
}
export default App;
|
src/stores/CountryDefsStore.js
|
alexmasselot/medlineGeoWebFrontend
|
import React from 'react';
import {EventEmitter} from 'events';
import assign from 'object-assign';
import httpClient from '../core/HttpClient';
import dispatcher from '../core/Dispatcher';
import Constants from '../constants/Constants';
import BaseStore from './BaseStore'
import _ from 'lodash';
import topojsonWorld from './data/world-110m.json';
let _data = {};
const store = assign({}, BaseStore, {
getTopoJson() {
return topojsonWorld;
},
getInfoByIso2(iso2){
let _this = this;
//builds the dictionary if not ready
if(_this._hInfos === undefined){
_this._hInfos= {};
_.each(topojsonWorld.features, function(ft){
_this._hInfos[ft.properties.iso_a2] = ft.properties;
});
}
return _this._hInfos[iso2];
},
setCountryFocus(iso2){
_data.countryFocus = this.getInfoByIso2(iso2);
store.emitChange();
},
getCountryFocus(){
return _data.countryFocus
},
dispatcherIndex: dispatcher.register(function (payload) {
let _this = this;
let action = payload.action;
switch (action.type) {
case Constants.ACTION_SET_COUNTRY_FOCUS:
store.setCountryFocus(payload.iso2.toUpperCase());
break;
}
})
});
export default store;
|
test/helpers/shallowRenderHelper.js
|
andresin87/enAlquiler
|
/**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
src/components/subjects/BookSubjectItem.js
|
great-design-and-systems/cataloguing-app
|
import FontAwesome from 'react-fontawesome';
import { LABEL_REMOVE } from '../../labels/';
import { Link } from 'react-router';
import PropTypes from 'prop-types';
import React from 'react';
import { toReadableSubject } from '../../utils/';
export const BookSubjectItem = ({ subject, removeSubject, index }) => {
return (<div className="subject-item list-group-item">
<button type="button" onClick={removeSubject} className="btn btn-danger btn-xs"><FontAwesome fixedWidth={true} name="minus" /><span className="hidden-xs">{LABEL_REMOVE}</span></button><Link to={'/books/subjects/' + index}>{toReadableSubject(subject)}</Link></div>);
};
BookSubjectItem.propTypes = {
index: PropTypes.number,
removeSubject: PropTypes.func.isRequired,
subject: PropTypes.string.isRequired
};
|
src/components/SvgIcons/WhatsApp/index.js
|
RaphaelHaettich/werwolfga.me
|
import React from 'react';
import SvgIcon from 'material-ui/SvgIcon';
/* eslint-disable max-len*/
// SVG d Path | eslint disa
const icon = `M380.9 97.1C339 55.1 283.2 32 223.9 32c-122.4 0-222 99.6-222 222 0 39.1 10.2 77.3 29.6 111L0 480l117.7-30.9c32.4 17.7 68.9 27 106.1 27h.1c122.3 0 224.1-99.6 224.1-222 0-59.3-25.2-115-67.1-157zm-157 341.6c-33.2 0-65.7-8.9-94-25.7l-6.7-4-69.8 18.3L72 359.2l-4.4-7c-18.5-29.4-28.2-63.3-28.2-98.2 0-101.7 82.8-184.5 184.6-184.5 49.3 0 95.6 19.2 130.4 54.1 34.8 34.9 56.2 81.2 56.1 130.5 0 101.8-84.9 184.6-186.6 184.6zm101.2-138.2c-5.5-2.8-32.8-16.2-37.9-18-5.1-1.9-8.8-2.8-12.5 2.8-3.7 5.6-14.3 18-17.6 21.8-3.2 3.7-6.5 4.2-12 1.4-32.6-16.3-54-29.1-75.5-66-5.7-9.8 5.7-9.1 16.3-30.3 1.8-3.7.9-6.9-.5-9.7-1.4-2.8-12.5-30.1-17.1-41.2-4.5-10.8-9.1-9.3-12.5-9.5-3.2-.2-6.9-.2-10.6-.2-3.7 0-9.7 1.4-14.8 6.9-5.1 5.6-19.4 19-19.4 46.3 0 27.3 19.9 53.7 22.6 57.4 2.8 3.7 39.1 59.7 94.8 83.8 35.2 15.2 49 16.5 66.6 13.9 10.7-1.6 32.8-13.4 37.4-26.4 4.6-13 4.6-24.1 3.2-26.4-1.3-2.5-5-3.9-10.5-6.6z`;
/* eslint-enable*/
const Icon = props => (
<SvgIcon {...props}>
<path d={icon} />
</SvgIcon>
);
const WhatsAppIcon = props => (
<Icon {...props} viewBox="0 0 448 512" />
);
export default WhatsAppIcon;
|
src/components/exercises/MatchImage.stories.js
|
cognostics/serlo-abc
|
import React from 'react';
import { storiesOf } from '@storybook/react-native';
import MatchImage from './MatchImage';
storiesOf('exercises/MatchImage', module).add('Apfel', () => (
<MatchImage
images={[
require('../../assets/images/affe.jpg'),
require('../../assets/images/esel.jpg'),
require('../../assets/images/apfel.jpg'),
require('../../assets/images/nase.jpg')
]}
text="Apfel"
sound={require('../../assets/sounds/apfel_short.mp3')}
/>
));
|
app/javascript/src/client/pages/not_found.js
|
rringler/billtalk
|
import React, { Component } from 'react';
export default class NotFound extends Component {
render() {
return <h1>404 <small>Not Found :(</small></h1>;
}
}
|
src/GhostButton/__tests__/GhostButton.web.js
|
Fineighbor/ui-kit
|
/* eslint-env jest */
import 'jest-styled-components'
import React from 'react'
import { shallow } from 'enzyme'
import GhostButton from '../index.js'
describe('GhostButton.web', () => {
it('renders a snapshot', () => {
const wrapper = shallow(
<GhostButton>Apple</GhostButton>
)
expect(wrapper).toMatchSnapshot()
})
it('renders a snapshot with `color:white`', () => {
const wrapper = shallow(
<GhostButton color='white'>Apple</GhostButton>
)
expect(wrapper).toMatchSnapshot()
})
it('renders a snapshot with `onPress`', () => {
const wrapper = shallow(
<GhostButton onPress={() => {}}>Apple</GhostButton>
)
expect(wrapper).toMatchSnapshot()
})
})
|
packages/react-server-website/middleware/PageFooter.js
|
emecell/react-server
|
import React from 'react';
import Footer from '../components/Footer';
export default class PageFooter {
getElements(next) {
return next().concat(<Footer />);
}
}
|
frontend/jqwidgets/jqwidgets-react/react_jqxdragdrop.js
|
liamray/nexl-js
|
/*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxDragDrop extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['appendTo','disabled','distance','data','dropAction','dropTarget','dragZIndex','feedback','initFeedback','opacity','onDragEnd','onDrag','onDragStart','onTargetDrop','onDropTargetEnter','onDropTargetLeave','restricter','revert','revertDuration','tolerance'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxDragDrop(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxDragDrop('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxDragDrop(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
appendTo(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('appendTo', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('appendTo');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('disabled');
}
};
distance(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('distance', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('distance');
}
};
data(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('data', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('data');
}
};
dropAction(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('dropAction', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('dropAction');
}
};
dropTarget(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('dropTarget', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('dropTarget');
}
};
dragZIndex(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('dragZIndex', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('dragZIndex');
}
};
feedback(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('feedback', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('feedback');
}
};
initFeedback(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('initFeedback', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('initFeedback');
}
};
opacity(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('opacity', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('opacity');
}
};
onDragEnd(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('onDragEnd', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('onDragEnd');
}
};
onDrag(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('onDrag', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('onDrag');
}
};
onDragStart(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('onDragStart', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('onDragStart');
}
};
onTargetDrop(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('onTargetDrop', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('onTargetDrop');
}
};
onDropTargetEnter(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('onDropTargetEnter', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('onDropTargetEnter');
}
};
onDropTargetLeave(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('onDropTargetLeave', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('onDropTargetLeave');
}
};
restricter(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('restricter', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('restricter');
}
};
revert(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('revert', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('revert');
}
};
revertDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('revertDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('revertDuration');
}
};
tolerance(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxDragDrop('tolerance', arg)
} else {
return JQXLite(this.componentSelector).jqxDragDrop('tolerance');
}
};
render() {
let id = 'jqxDragDrop' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
src/components/buttons/RaisedButton.js
|
tuckerconnelly/carbon-ui
|
import React from 'react'
import PropTypes from 'prop-types'
import Uranium from 'uranium'
import Color from 'color'
import {
TouchableRipple,
Body2,
Breakpoints,
Colors,
Elevation,
connectTheme,
} from '../../index'
/**
* Raised buttons behave like a piece of material resting on another sheet –
* they lift and fill with color on press.
*
* ### Examples
*
* import React from 'react'
* import { View } from 'react-native'
* import { RaisedButton } from 'carbon-ui'
*
* export default () =>
* <View style={{ justifyContent: 'flex-start', flexDirection: 'row' }}>
* <RaisedButton>Click me!</RaisedButton>
* <RaisedButton disabled>Out of commission</RaisedButton>
* </View>
*
*/
const RaisedButton = ({
disabled,
children,
textStyle,
theme,
...other
}) => {
// Themed styles
const styles = tStyles(theme)
// Uppercase and style if the child is a string
// Otherwise it's probably an icon or image, so let it through
const formattedChildren = typeof children === 'string' ?
(<Body2
style={[
styles.text,
disabled && styles.disabledText,
textStyle,
]}>
{children.toUpperCase()}
</Body2>) :
children
return (
<TouchableRipple
hitSlop={{ top: 6, right: 6, bottom: 6, left: 6 }}
css={[styles.base, disabled && styles.disabled]}
rippleColor={Colors.white}
disabled={disabled}
{...other}>
{formattedChildren}
</TouchableRipple>
)
}
RaisedButton.propTypes = {
/**
* Disables the button if set to true.
*/
disabled: PropTypes.bool,
/**
* The inside of the button. If it's text, it'll be UPPERCASEd.
*/
children: PropTypes.node,
/**
* The style of the button text. Only applies if props.children isn't passed.
*/
textStyle: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
// connectTheme
theme: PropTypes.object.isRequired,
}
const tStyles = theme => ({
base: {
height: 36,
minWidth: 88,
paddingHorizontal: 16,
borderRadius: 2,
marginHorizontal: 8,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: theme.colors.primary,
...Elevation.dp2,
[Breakpoints.ml]: {
height: 32,
...Elevation.none,
},
},
text: {
color: Colors.whitePrimary,
lineHeight: 16,
textAlign: 'center',
},
pressed: {
...Elevation.dp4,
},
disabled: {
backgroundColor: theme.colors.button.raised.disabled,
},
disabledText: {
color: theme.colors.button.raised.disabledText,
},
focused: {
backgroundColor: Color(theme.colors.primary).darken(0.12).hexString(),
},
hovered: {
...Elevation.dp2,
},
})
export default
connectTheme(
Uranium(
RaisedButton))
|
src/js/components/mobile_list.js
|
wangi4myself/myFirstReactJs
|
import React from 'react';
import {Row,Col} from 'antd';
import {Router, Route, Link, browserHistory} from 'react-router'
export default class MobileList extends React.Component {
constructor() {
super();
this.state = {
news: ''
};
}
componentWillMount() {
var myFetchOptions = {
method: 'GET'
};
fetch("http://newsapi.gugujiankong.com/Handler.ashx?action=getnews&type=" + this.props.type + "&count=" + this.props.count, myFetchOptions).then(response => response.json()).then(json => this.setState({news: json}));
};
render() {
const {news} = this.state;
const newsList = news.length
? news.map((newsItem, index) => (
<section key={index} className="m_article list-item special_section clearfix">
<Link to={`details/${newsItem.uniquekey}`}>
<div className="m_article_img">
<img src={newsItem.thumbnail_pic_s} alt={newsItem.title} />
</div>
<div className="m_article_info">
<div className="m_article_title">
<span>{newsItem.title}</span>
</div>
<div className="m_article_desc clearfix">
<div className="m_article_desc_l">
<span className="m_article_channel">{newsItem.realtype}</span>
<span className="m_article_time">{newsItem.date}</span>
</div>
</div>
</div>
</Link>
</section>
))
: '没有加载到任何新闻';
return (
<div>
<Row>
<Col span={24}>
{newsList}
</Col>
</Row>
</div>
);
};
}
|
web/components/shared/Button/cosmos.decorator.js
|
skidding/flatris
|
// @flow
import React from 'react';
import { GameContainerMock } from '../../../mocks/GameContainerMock';
export default ({ children }: { children: React$Node }) => (
<GameContainerMock cols={4} rows={2}>
{children}
</GameContainerMock>
);
|
docs/src/examples/modules/Dropdown/Types/DropdownExampleInline.js
|
Semantic-Org/Semantic-UI-React
|
import React from 'react'
import { Dropdown } from 'semantic-ui-react'
const friendOptions = [
{
key: 'Jenny Hess',
text: 'Jenny Hess',
value: 'Jenny Hess',
image: { avatar: true, src: '/images/avatar/small/jenny.jpg' },
},
{
key: 'Elliot Fu',
text: 'Elliot Fu',
value: 'Elliot Fu',
image: { avatar: true, src: '/images/avatar/small/elliot.jpg' },
},
{
key: 'Stevie Feliciano',
text: 'Stevie Feliciano',
value: 'Stevie Feliciano',
image: { avatar: true, src: '/images/avatar/small/stevie.jpg' },
},
{
key: 'Christian',
text: 'Christian',
value: 'Christian',
image: { avatar: true, src: '/images/avatar/small/christian.jpg' },
},
]
const DropdownExampleInline = () => (
<span>
Show me posts by{' '}
<Dropdown
inline
options={friendOptions}
defaultValue={friendOptions[0].value}
/>
</span>
)
export default DropdownExampleInline
|
src/components/Sidebar/index.js
|
RodgerLai/nodejs-nedb-excel
|
import React from 'react';
import {Link} from 'react-router';
import {connect} from 'react-redux'
import {bindActionCreators} from 'redux'
import {Menu, Icon} from 'antd';
import Logo from '../Logo';
import Logger from '../../utils/Logger';
import items from 'menu.js'; // 由于webpack中的设置, 不用写完整路径
import globalConfig from 'config.js';
import './index.less';
import {sidebarCollapseCreator} from '../../redux/Sidebar.js';
const SubMenu = Menu.SubMenu;
const MenuItem = Menu.Item;
const logger = Logger.getLogger('Sidebar');
/**
* 定义sidebar组件
*/
class Sidebar extends React.PureComponent {
// 尝试把sidebar做成PureComponent, 注意可能的bug
// 注意PureComponent的子组件也应该是pure的
state = {
openKeys: [], // 当前有哪些submenu被展开
};
// 哪些状态组件自己维护, 哪些状态放到redux, 是需要权衡的
/**
* 将菜单项配置转换为对应的MenuItem组件
*
* @param obj sidebar菜单配置项
* @param paths 父级目录, array
* @returns {XML}
*/
transFormMenuItem(obj, paths, isLevel1) {
const parentPath = paths.join('/'); // 将各级父目录组合成完整的路径
logger.debug('transform %o to path %s', obj, parentPath);
// 这个表达式还是有点恶心的...
// JSX虽然方便, 但是很容易被滥用, ES6也是
// 注意这里的样式, 用chrome一点点调出来的...
// 我的css都是野路子, 头痛医头脚痛医脚, 哪里显示有问题就去调一下, 各种inline style
// 估计事后去看的话, 我都忘了为什么要加这些样式...
return (
<MenuItem key={obj.key} style={{ margin: '0px' }}>
{obj.icon && <Icon type={obj.icon}/>}
{/*对于level1的菜单项, 如果没有图标, 取第一个字用于折叠时显示*/}
{isLevel1 && !obj.icon && <span className="invisible-nav-text">{obj.name[0]}</span>}
<Link to={`/${parentPath}`} style={{ display: 'inline' }}><span className="nav-text">{obj.name}</span></Link>
</MenuItem>
);
}
// 在每次组件挂载的时候parse一次菜单, 不用每次render都解析
// 其实这个也可以放在constructor里
componentWillMount() {
const paths = []; // 暂存各级路径, 当作stack用
const level1KeySet = new Set(); // 暂存所有顶级菜单的key
const level2KeyMap = new Map(); // 次级菜单与顶级菜单的对应关系
// 菜单项是从配置中读取的, parse过程还是有点复杂的
// map函数很好用
const menu = items.map((level1) => {
// parse一级菜单
paths.push(level1.key);
level1KeySet.add(level1.key);
if (this.state.openKeys.length === 0) {
this.state.openKeys.push(level1.key); // 默认展开第一个菜单, 直接修改state, 没必要setState
}
// 是否有子菜单?
if (level1.child) {
const level2menu = level1.child.map((level2) => {
// parse二级菜单
paths.push(level2.key);
level2KeyMap.set(level2.key, level1.key);
if (level2.child) {
const level3menu = level2.child.map((level3) => {
// parse三级菜单, 不能再有子菜单了, 即使有也会忽略
paths.push(level3.key);
const tmp = this.transFormMenuItem(level3, paths);
paths.pop();
return tmp;
});
paths.pop();
return (
<SubMenu key={level2.key}
title={level2.icon ? <span><Icon type={level2.icon} />{level2.name}</span> : level2.name}>
{level3menu}
</SubMenu>
);
} else {
const tmp = this.transFormMenuItem(level2, paths);
paths.pop();
return tmp;
}
});
paths.pop();
let level1Title;
// 同样, 如果没有图标的话取第一个字
if (level1.icon) {
level1Title = <span><Icon type={level1.icon}/><span className="nav-text">{level1.name}</span></span>;
} else {
level1Title = <span><span className="invisible-nav-text">{level1.name[0]}</span><span
className="nav-text">{level1.name}</span></span>;
}
return (
<SubMenu key={level1.key} title={level1Title}>
{level2menu}
</SubMenu>
)
}
// 没有子菜单, 直接转换为MenuItem
else {
const tmp = this.transFormMenuItem(level1, paths, true);
paths.pop(); // return之前别忘了pop
return tmp;
}
});
this.menu = menu;
this.level1KeySet = level1KeySet;
this.level2KeyMap = level2KeyMap;
}
// 我决定在class里面, 只有在碰到this问题时才使用箭头函数, 否则还是优先使用成员方法的形式定义函数
// 因为用箭头函数ESlint总是提示语句最后少一个分号...
// 事件处理的方法统一命名为handleXXX
/**
* 处理子菜单的展开事件
*
* @param openKeys
*/
handleOpenChange = (openKeys) => {
// 如果当前菜单是折叠状态, 就先展开
if (this.props.collapse) {
this.props.handleClickCollapse();
}
if (!globalConfig.sidebar.autoMenuSwitch) { // 不开启这个功能
this.setState({openKeys});
return;
}
logger.debug('old open keys: %o', openKeys);
const newOpenKeys = [];
// 有没有更优雅的写法
let lastKey = ''; // 找到最近被点击的一个顶级菜单, 跟数组中元素的顺序有关
for (let i = openKeys.length; i >= 0; i--) {
if (this.level1KeySet.has(openKeys[i])) {
lastKey = openKeys[i];
break;
}
}
// 过滤掉不在lastKey下面的所有子菜单
for (const key of openKeys) {
const ancestor = this.level2KeyMap.get(key);
if (ancestor === lastKey) {
newOpenKeys.push(key);
}
}
newOpenKeys.push(lastKey);
logger.debug('new open keys: %o', newOpenKeys);
this.setState({openKeys: newOpenKeys});
};
/**
* 处理"叶子"节点的点击事件
*
* @param key
*/
handleSelect = ({key}) => {
if (this.props.collapse) {
this.props.handleClickCollapse();
}
// 如果是level1级别的菜单触发了这个事件, 说明这个菜单没有子项, 需要把其他所有submenu折叠
if (globalConfig.sidebar.autoMenuSwitch && this.level1KeySet.has(key) && this.state.openKeys.length > 0) {
this.setState({openKeys: []});
}
};
render() {
return (
<aside className={this.props.collapse ? "ant-layout-sidebar-collapse" : "ant-layout-sidebar"}>
<Logo collapse={this.props.collapse}/>
<Menu theme="dark" mode="inline"
onOpenChange={this.handleOpenChange}
onSelect={this.handleSelect}
openKeys={this.props.collapse ? [] : this.state.openKeys}>
{this.menu}
</Menu>
<div className="ant-layout-sidebar-trigger" onClick={this.props.handleClickCollapse}>
<Icon type={this.props.collapse ? "right" : "left"}/>
</div>
</aside>
);
}
}
// 什么时候使用箭头函数?
// 1. 碰到this问题的时候
// 2. 要写function关键字的时候
const mapStateToProps = (state) => {
return {
collapse: state.Sidebar.collapse,
};
};
const mapDispatchToProps = (dispatch) => {
return {
// 所有处理事件的方法都以handleXXX命名
handleClickCollapse: bindActionCreators(sidebarCollapseCreator, dispatch),
};
};
export default connect(mapStateToProps, mapDispatchToProps)(Sidebar);
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.