path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
webpack/withProtectedView.js | theforeman/foreman_templates | import React from 'react';
// TODO: extract to core
const withProtectedView = (
ProtectedComponent,
ProtectionComponent,
protectionFn,
extraProtectionProps = {}
) => props =>
protectionFn(props) ? (
<ProtectedComponent {...props} />
) : (
<ProtectionComponent {...props} {...extraProtectionProps} />
);
export default withProtectedView;
|
app/jsx/assignments_2/student/components/Context.js | djbender/canvas-lms | /*
* Copyright (C) 2019 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
export const StudentViewContextDefaults = {
// Controls for moving back and forth between displayed submissions
nextButtonAction: () => {},
nextButtonEnabled: false,
prevButtonAction: () => {},
prevButtonEnabled: false,
startNewAttemptAction: () => {},
// Used to display the most current grade in the header, regardless of the
// current attempt being displayed in the student view
latestSubmission: {}
}
const StudentViewContext = React.createContext(StudentViewContextDefaults)
export default StudentViewContext
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/ClassProperties.js | liamhu/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
users = [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
];
componentDidMount() {
this.props.onReady();
}
render() {
return (
<div id="feature-class-properties">
{this.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
front/components/navbar/navbar.js | bigkangtheory/wanderly | import React, { Component } from 'react';
import { Link } from 'react-router';
import '../../styles/navbar.css';
class Navbar extends Component {
constructor(props) {
super(props);
}
handleClick = () => {
this.props.action()
}
render() {
const { pathname } = this.props.routing
if(pathname === '/') {
return (
<div className='loggedout-navbar navbar'>
<div className="parent-logo">
<div className='logo-nav '></div>
</div>
<div className='buttons'>
<button className='login-link button-log one' onClick={this.props.loginPop}>Login</button>
</div>
</div>
)
} else {
return (
<div className='login-navbar navbar'>
<div className="parent-logo">
<div className='logo-nav '></div>
</div>
<div className="dropdown buttons">
<div id='name-nav'>
<button className="dropbtn button-log">{this.props.profile.first_name}</button>
<div className='arrow-down'></div>
</div>
<div className="dropdown-content button-log">
<button className='logout' onClick={this.handleClick}>Log out</button>
</div>
</div>
</div>
)
}
}
}
export default Navbar
|
src/components/artboard/ArtBoardTabs.js | justinyueh/express-react | import { Router, Route, IndexRoute, Redirect, Link, browserHistory } from 'react-router'
import React from 'react'
import SysTpl from './artboardtabs/SysTpl'
export default class ArtBoardTabs extends React.Component {
constructor() {
super();
this.addTpl = this.addTpl.bind(this);
this.state = {
activeId: 0,
tabs: [
{name: '系统模版', id: 0, icon: 'fa-paper-plane', children: <SysTpl addTpl={this.addTpl} />},
{name: '草稿箱', id: 1, icon: 'fa-archive'}
]
}
this.handleTabClick = this.handleTabClick.bind(this);
}
addTpl(tpl) {
this.props.addTpl(tpl);
}
handleTabClick(tab) {
return () => {
if (tab.id != this.state.activeId) {
this.setState({
activeId: tab.id
});
}
}
}
render() {
let createItem = (tab) => {
let className = 'item';
if (tab.id == this.state.activeId) {
this.children = tab.children;
className = 'item active';
}
return (
<li key={tab.id} className={className} onClick={this.handleTabClick(tab)} >
<i className={'fa ' + tab.icon}></i><span className="title">{tab.name}</span>
</li>
)
}
return (
<aside className="sidebar">
<ul className="tabs">{this.state.tabs.map(createItem)}</ul>
<div className="tab-body">
{this.children}
</div>
</aside>
)
}
}
|
frontend/src/Components/Table/VirtualTableHeader.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React from 'react';
import styles from './VirtualTableHeader.css';
function VirtualTableHeader({ children }) {
return (
<div className={styles.header}>
{children}
</div>
);
}
VirtualTableHeader.propTypes = {
children: PropTypes.node
};
export default VirtualTableHeader;
|
src/app/tabela.js | hugotacito/tabelaebtt | import React from 'react';
import {Navbar, Grid, Row, Col} from 'react-bootstrap';
import {Formulario} from './form';
import {Resultado} from './resultado';
export class Tabela extends React.Component {
constructor(props) {
super(props);
this.state = {
formData: {}
};
this.handleUserInput = this.handleUserInput.bind(this);
}
handleUserInput(data) {
this.setState({formData: data.formData});
}
render() {
return (
<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand>
<a href="#">Simulador EBTT</a>
</Navbar.Brand>
</Navbar.Header>
</Navbar>
<Grid>
<Row className="show-grid">
<Col xs={12} md={6}>
<Formulario formData={this.state.formData} onUserInput={this.handleUserInput}/>
</Col>
<Col xs={12} md={6}>
<Resultado formData={this.state.formData} onUserInput={this.handleUserInput}/>
</Col>
</Row>
</Grid>
</div>
);
}
}
|
src/App.js | drothschild/react-led-board | import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import Flag from './Flag'
import ColorPicker from './ColorPicker'
class App extends Component {
constructor(props) {
super(props);
const defaultColor= "blue"
this.state = {
color: defaultColor
}
};
updateColor(color) {
this.setState ({
color: color
});
};
render() {
const onChangeColor= this.updateColor.bind(this);
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<div className="Primary-flag">
<Flag color={this.state.color} editable={true} />
</div>
<ColorPicker color={this.state.color} onChange={onChangeColor}/>
</div>
);
}
}
export default App;
|
code/workspaces/web-app/src/containers/modal/ModalRoot.js | NERC-CEH/datalab | import React from 'react';
import { connect } from 'react-redux';
import CreateNotebookDialog from '../notebooks/CreateNotebookDialogContainer';
import CreateSiteDialog from '../sites/CreateSiteDialogContainer';
import CreateDataStoreDialog from '../../components/modal/CreateDataStoreDialog';
import Confirmation from '../../components/modal/Confirmation';
import RobustConfirmation from '../../components/modal/RobustConfirmation';
import EditDataStore from '../dataStorage/EditDataStoreContainer';
import CreateProjectDialog from '../../components/modal/CreateProjectDialog';
import ShareStackDialog from '../../components/modal/ShareStackDialog';
import EditNotebookDialog from '../../components/modal/EditNotebookDialog';
import EditSiteDialog from '../../components/modal/EditSiteDialog';
import Logs from '../../components/modal/SiteLogs';
import ConfirmationDialog from '../../components/modal/ConfirmationDialog';
import CreateClusterDialog from '../../components/modal/CreateClusterDialog';
import EditAssetDialog from '../../components/modal/EditAssetDialog';
import {
MODAL_TYPE_CREATE_NOTEBOOK,
MODAL_TYPE_CREATE_SITE,
MODAL_TYPE_CONFIRMATION,
MODAL_TYPE_LOGS,
MODAL_TYPE_CREATE_DATA_STORE,
MODAL_TYPE_ROBUST_CONFIRMATION,
MODAL_TYPE_EDIT_DATA_STORE,
MODAL_TYPE_CREATE_PROJECT,
MODAL_TYPE_SHARE_STACK,
MODAL_TYPE_EDIT_NOTEBOOK,
MODAL_TYPE_EDIT_SITE,
MODAL_TYPE_RESTART_STACK,
MODAL_TYPE_SCALE_STACK,
MODAL_TYPE_CREATE_CLUSTER,
MODAL_TYPE_EDIT_ASSET,
MODAL_TYPE_CONFIRM_CREATION,
} from '../../constants/modaltypes';
const MODAL_COMPONENTS = {
[MODAL_TYPE_CREATE_NOTEBOOK]: CreateNotebookDialog,
[MODAL_TYPE_CREATE_SITE]: CreateSiteDialog,
[MODAL_TYPE_CONFIRMATION]: Confirmation,
[MODAL_TYPE_CREATE_DATA_STORE]: CreateDataStoreDialog,
[MODAL_TYPE_ROBUST_CONFIRMATION]: RobustConfirmation,
[MODAL_TYPE_EDIT_DATA_STORE]: EditDataStore,
[MODAL_TYPE_CREATE_PROJECT]: CreateProjectDialog,
[MODAL_TYPE_LOGS]: Logs,
[MODAL_TYPE_SHARE_STACK]: ShareStackDialog,
[MODAL_TYPE_EDIT_NOTEBOOK]: EditNotebookDialog,
[MODAL_TYPE_EDIT_SITE]: EditSiteDialog,
[MODAL_TYPE_RESTART_STACK]: ConfirmationDialog,
[MODAL_TYPE_SCALE_STACK]: ConfirmationDialog,
[MODAL_TYPE_CREATE_CLUSTER]: CreateClusterDialog,
[MODAL_TYPE_EDIT_ASSET]: EditAssetDialog,
[MODAL_TYPE_CONFIRM_CREATION]: ConfirmationDialog,
};
const ModalRoot = ({ modalType, props }) => {
if (!modalType) {
return null;
}
const ModalComponent = MODAL_COMPONENTS[modalType];
return <ModalComponent {...props} />;
};
export default connect(state => state.modal)(ModalRoot);
|
src/components/GameCell.js | Airse/react-minesweeper | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { FaFlag, FaBomb } from 'react-icons/lib/fa';
class GameCell extends Component {
constructor(props) {
super(props);
this.onCellClick = this.onCellClick.bind(this);
this.onCellFlag = this.onCellFlag.bind(this);
}
onCellFlag(e) {
e.preventDefault();
this.props.onFlagCell(this.props.cell);
}
onCellClick(e) {
e.preventDefault();
this.props.onOpenCell(this.props.cell);
}
render() {
if (this.props.cell.isOpen) {
let cellContent = this.props.cell.value;
if (cellContent === 0) {
cellContent = '';
} else if (cellContent === -1) {
cellContent = <FaBomb />;
}
return (
<td className="game-cell game-cell-open">
<div className={`game-number-${this.props.cell.value}`}>
{cellContent}
</div>
</td>
);
}
return (
<td className="game-cell">
<div>
<button onClick={this.onCellClick} onContextMenu={this.onCellFlag}>
{this.props.cell.isFlagged ? <FaFlag /> : ''}
</button>
</div>
</td>
);
}
}
GameCell.propTypes = {
cell: PropTypes.object.isRequired,
onOpenCell: PropTypes.func.isRequired,
onFlagCell: PropTypes.func.isRequired,
};
export default GameCell;
|
src/Tooltip.js | albertojacini/react-bootstrap | import classNames from 'classnames';
import React from 'react';
import CustomPropTypes from './utils/CustomPropTypes';
export default class Tooltip extends React.Component {
render() {
const {
placement,
positionLeft,
positionTop,
arrowOffsetLeft,
arrowOffsetTop,
className,
style,
children,
...props
} = this.props;
return (
<div
role="tooltip"
{...props}
className={classNames(className, 'tooltip', placement)}
style={{left: positionLeft, top: positionTop, ...style}}
>
<div
className="tooltip-arrow"
style={{left: arrowOffsetLeft, top: arrowOffsetTop}}
/>
<div className="tooltip-inner">
{children}
</div>
</div>
);
}
}
Tooltip.propTypes = {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: CustomPropTypes.isRequiredForA11y(
React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
),
/**
* The direction the tooltip is positioned towards
*/
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The `left` position value for the tooltip
*/
positionLeft: React.PropTypes.number,
/**
* The `top` position value for the tooltip
*/
positionTop: React.PropTypes.number,
/**
* The `left` position value for the tooltip arrow
*/
arrowOffsetLeft: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
]),
/**
* The `top` position value for the tooltip arrow
*/
arrowOffsetTop: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
])
};
Tooltip.defaultProps = {
placement: 'right'
};
|
actor-apps/app-web/src/app/components/DialogSection.react.js | ruikong/actor-platform | import _ from 'lodash';
import React from 'react';
import { PeerTypes } from 'constants/ActorAppConstants';
import MessagesSection from 'components/dialog/MessagesSection.react';
import TypingSection from 'components/dialog/TypingSection.react';
import ComposeSection from 'components/dialog/ComposeSection.react';
import DialogStore from 'stores/DialogStore';
import MessageStore from 'stores/MessageStore';
import GroupStore from 'stores/GroupStore';
import DialogActionCreators from 'actions/DialogActionCreators';
// On which scrollTop value start loading older messages
const LoadMessagesScrollTop = 100;
const initialRenderMessagesCount = 20;
const renderMessagesStep = 20;
let renderMessagesCount = initialRenderMessagesCount;
let lastPeer = null;
let lastScrolledFromBottom = 0;
const getStateFromStores = () => {
const messages = MessageStore.getAll();
let messagesToRender;
if (messages.length > renderMessagesCount) {
messagesToRender = messages.slice(messages.length - renderMessagesCount);
} else {
messagesToRender = messages;
}
return {
peer: DialogStore.getSelectedDialogPeer(),
messages: messages,
messagesToRender: messagesToRender
};
};
class DialogSection extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
DialogStore.addSelectListener(this.onSelectedDialogChange);
MessageStore.addChangeListener(this.onMessagesChange);
}
componentWillUnmount() {
DialogStore.removeSelectListener(this.onSelectedDialogChange);
MessageStore.removeChangeListener(this.onMessagesChange);
}
componentDidUpdate() {
this.fixScroll();
this.loadMessagesByScroll();
}
render() {
const peer = this.state.peer;
if (peer) {
let isMember = true;
let memberArea;
if (peer.type === PeerTypes.GROUP) {
const group = GroupStore.getGroup(peer.id);
isMember = DialogStore.isGroupMember(group);
}
if (isMember) {
memberArea = (
<div>
<TypingSection/>
<ComposeSection peer={this.state.peer}/>
</div>
);
} else {
memberArea = (
<section className="compose compose--disabled row center-xs middle-xs">
<h3>You are not member</h3>
</section>
);
}
return (
<section className="dialog" onScroll={this.loadMessagesByScroll}>
<MessagesSection messages={this.state.messagesToRender}
peer={this.state.peer}
ref="MessagesSection"/>
{memberArea}
</section>
);
} else {
return (
<section className="dialog dialog--empty row middle-xs center-xs">
Select dialog or start a new one.
</section>
);
}
}
fixScroll = () => {
if (lastPeer !== null ) {
let node = React.findDOMNode(this.refs.MessagesSection);
node.scrollTop = node.scrollHeight - lastScrolledFromBottom;
}
}
onSelectedDialogChange = () => {
renderMessagesCount = initialRenderMessagesCount;
if (lastPeer != null) {
DialogActionCreators.onConversationClosed(lastPeer);
}
lastPeer = DialogStore.getSelectedDialogPeer();
DialogActionCreators.onConversationOpen(lastPeer);
}
onMessagesChange = _.debounce(() => {
this.setState(getStateFromStores());
}, 10, {maxWait: 50, leading: true});
loadMessagesByScroll = _.debounce(() => {
if (lastPeer !== null ) {
let node = React.findDOMNode(this.refs.MessagesSection);
let scrollTop = node.scrollTop;
lastScrolledFromBottom = node.scrollHeight - scrollTop;
if (node.scrollTop < LoadMessagesScrollTop) {
DialogActionCreators.onChatEnd(this.state.peer);
if (this.state.messages.length > this.state.messagesToRender.length) {
renderMessagesCount += renderMessagesStep;
if (renderMessagesCount > this.state.messages.length) {
renderMessagesCount = this.state.messages.length;
}
this.setState(getStateFromStores());
}
}
}
}, 5, {maxWait: 30});
}
export default DialogSection;
|
src/components/Github/TabsScreen.js | jseminck/react-native-github-feed | import React from 'react';
import { View, TabBarIOS } from 'react-native';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import * as githubActions from './githubActions';
import {onLogout} from './../Login/loginActions';
import routes from './../../scripts/routes';
import Loading from './Loading';
import Feed from './Feed';
import User from './User';
class TabsScreen extends React.Component {
static propTypes = {
state: React.PropTypes.object.isRequired,
user: React.PropTypes.object,
loggedIn: React.PropTypes.bool,
navigator: React.PropTypes.object.isRequired,
onLogout: React.PropTypes.func.isRequired,
onGithubLoad: React.PropTypes.func.isRequired,
onLoadMore: React.PropTypes.func.isRequired,
onChangeTab: React.PropTypes.func.isRequired
};
componentDidMount() {
if (this.props.loggedIn) {
this.props.onGithubLoad(this.props.user);
}
}
componentWillReceiveProps(nextProps) {
if (this.props.loggedIn !== nextProps.loggedIn && !nextProps.loggedIn) {
let route = routes.getLoginRoute();
this.props.navigator.replace(route);
}
}
render() {
if (this.props.state.loading) {
return <Loading />;
}
return (
<TabBarIOS>
<TabBarIOS.Item
title='Github Feed'
selected={this.props.state.selectedTab === 'feed'}
onPress={this.changeTab.bind(this, 'feed')}
icon={require('./feed.png')}
>
<View style={styles.view}>
<Feed
navigator={this.props.navigator}
feed={this.props.state.feed}
onLoadMore={this.props.onLoadMore}
/>
</View>
</TabBarIOS.Item>
<TabBarIOS.Item
title='User Info'
selected={this.props.state.selectedTab === 'user'}
onPress={this.changeTab.bind(this, 'user')}
icon={require('./user.png')}
>
<View style={styles.view}>
<User
user={this.props.user}
repos={this.props.state.repos}
/>
</View>
</TabBarIOS.Item>
<TabBarIOS.Item
title='Log out'
selected={false}
icon={require('./signout.png')}
onPress={::this.logout}
>
</TabBarIOS.Item>
</TabBarIOS>
);
}
logout() {
this.props.onLogout();
}
changeTab(tab) {
this.props.onChangeTab(tab);
}
}
const styles = {
view: {
flex: 1
}
};
function mapStateToProps(state) {
return {
state: state.github,
user: state.login.user,
loggedIn: state.login.loggedIn
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators(Object.assign(githubActions, {onLogout}), dispatch);
}
export default connect(mapStateToProps, mapDispatchToProps)(TabsScreen);
|
src/components/MainHeader/ControlSidebarToggle.js | falmar/react-adm-lte | import React from 'react'
import PropTypes from 'prop-types'
import Link from './../../utils/Link'
const ControlSidebarToggle = ({href, onToggle}) => {
return (
<li>
<Link href={href} onClick={onToggle}>
<i className='fa fa-gears' />
</Link>
</li>
)
}
ControlSidebarToggle.propTypes = {
href: PropTypes.string,
onToggle: PropTypes.func
}
export default ControlSidebarToggle
|
src/Dropdown/Dropdown.js | yurizhang/ishow | import React from 'react';
import ReactDOM from 'react-dom';
import ClickOutside from 'react-click-outside';
import PropTypes from 'prop-types';
import {default as Component} from '../Common/plugs/index.js'; //提供style, classname方法
import Button from '../Button/Button';
import ButtonGroup from '../Button/ButtonGroup';
import '../Common/css/Dropdown.css'
Button.Group = ButtonGroup;
class Dropdown extends Component {
constructor(props) {
super(props);
this.state = {
visible: false
}
}
getChildContext() {
return {
component: this
};
}
componentDidMount() {
this.initEvent();
}
componentWillUpdate(props, state) {
if (state.visible !== this.state.visible) {
this.refs.dropdown.onVisibleChange(state.visible);
if (this.props.onVisibleChange) {
this.props.onVisibleChange(state.visible);
}
}
}
handleClickOutside() {
if (this.state.visible) {
this.setState({ visible: false });
}
}
show() {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => this.setState({ visible: true }), 250);
}
hide() {
clearTimeout(this.timeout);
this.timeout = setTimeout(() => this.setState({ visible: false }), 150);
}
handleClick() {
this.setState({ visible: !this.state.visible });
}
initEvent() {
const { trigger, splitButton } = this.props;
const triggerElm = ReactDOM.findDOMNode(splitButton ? this.refs.trigger : this.refs.default);
if (trigger === 'hover') {
triggerElm.addEventListener('mouseenter', this.show.bind(this));
triggerElm.addEventListener('mouseleave', this.hide.bind(this));
let dropdownElm = ReactDOM.findDOMNode(this.refs.dropdown);
dropdownElm.addEventListener('mouseenter', this.show.bind(this));
dropdownElm.addEventListener('mouseleave', this.hide.bind(this));
} else if (trigger === 'click') {
triggerElm.addEventListener('click', this.handleClick.bind(this));
}
}
handleMenuItemClick(command, instance) {
if (this.props.hideOnClick) {
this.setState({
visible: false
});
}
if (this.props.onCommand) {
setTimeout(() => {
this.props.onCommand(command, instance);
});
}
}
render(){
const { splitButton, type, size, menu } = this.props;
return (
<div style={this.style()} className={this.className('ishow-dropdown')}>
{
splitButton ? (
<Button.Group>
<Button type={type} size={size} onClick={this.props.onClick.bind(this)}>
{this.props.children}
</Button>
<Button ref="trigger" type={type} size={size} className="ishow-dropdown__caret-button">
<i className="ishow-dropdown__icon ishow-icon-caret-bottom"></i>
</Button>
</Button.Group>
) : React.cloneElement(this.props.children, { ref: 'default' })
}
{
React.cloneElement(menu, {
ref: 'dropdown'
})
}
</div>
)
}
}
Dropdown.childContextTypes = {
component: PropTypes.any
};
Dropdown.propTypes = {
menu: PropTypes.node.isRequired,
type: PropTypes.string,
size: PropTypes.string,
trigger: PropTypes.oneOf(['hover', 'click']),
menuAlign: PropTypes.oneOf(['start', 'end']),
splitButton: PropTypes.bool,
hideOnClick: PropTypes.bool,
onClick: PropTypes.func,
onCommand: PropTypes.func,
onVisibleChange: PropTypes.func
}
Dropdown.defaultProps = {
hideOnClick: true,
trigger: 'hover',
menuAlign: 'end'
}
export default ClickOutside(Dropdown);
|
setup/src/universal/features/user/auth/components/ProfileCompleted/index.js | ch-apptitude/goomi | /**
*
* ProfileCompleted
*
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import { Row, Col } from 'react-flexbox-grid';
import moment from 'moment';
import styled from 'styled-components';
import HOCAuth from 'features/user/hoc/HOCAuth';
import { UserPropTypes } from 'features/user/constants';
import Box from 'features/common_ui/components/Box';
import Text from 'features/common_ui/components/Text';
import { GreenButton } from 'features/common_ui/components/Button';
import messages from './messages';
const StyledProfileCompleted = styled.div`
height: 100%;
width: 100%;
.title {
margin-bottom: 30px;
}
.continue {
margin-top: 30px;
}
`;
const ProfileCompleted = ({ user }) => (
<StyledProfileCompleted>
{user && (
<div>
<Row>
<Col xs={12}>
<Text className="title" tag="h1" size={Theme.Metrics.title} message={messages.title} />
</Col>
</Row>
<Row>
<Col xs={12}>
<Text tag="p" message={messages.body} />
</Col>
</Row>
<Row>
<Col>
<GreenButton className="continue" linkTo={'/profile'} message={messages.continue} />
</Col>
</Row>
</div>
)}
</StyledProfileCompleted>
);
ProfileCompleted.defaultProps = {
user: undefined,
};
ProfileCompleted.propTypes = {
user: UserPropTypes,
};
export default HOCAuth(ProfileCompleted);
|
src/widgets/modals/QrScannerModal.js | sussol/mobile | /**
* mSupply Mobile
* Sustainable Solutions (NZ) Ltd. 2021
*/
import React from 'react';
import { StyleSheet } from 'react-native';
import PropTypes from 'prop-types';
import { RNCamera } from 'react-native-camera';
import BarcodeMask from 'react-native-barcode-mask';
import { ModalContainer } from './ModalContainer';
import { SUSSOL_ORANGE } from '../../globalStyles/colors';
import { modalStrings } from '../../localization/index';
import { FlexRow } from '../FlexRow';
export const QrScannerModal = ({ isOpen, onClose, onBarCodeRead }) => (
<ModalContainer
isVisible={isOpen}
onBarcodeRead={onBarCodeRead}
onClose={onClose}
title={modalStrings.qr_scanner_header}
>
<FlexRow flex={1} justifyContent="center">
<RNCamera
androidCameraPermissionOptions={{
title: 'Camera access is required to scan QR codes',
message: 'Your device will prompt you for access on the next screen.',
buttonPositive: 'Ok',
buttonNegative: 'Cancel',
}}
barCodeTypes={[RNCamera.Constants.BarCodeType.qr]}
captureAudio={false}
flashMode={RNCamera.Constants.FlashMode.on}
onBarCodeRead={onBarCodeRead}
style={localStyles.preview}
>
<BarcodeMask edgeColor={SUSSOL_ORANGE} showAnimatedLine={false} outerMaskOpacity={0.0} />
</RNCamera>
</FlexRow>
</ModalContainer>
);
const localStyles = StyleSheet.create({
preview: {
alignItems: 'center',
flexGrow: 0.5,
},
});
QrScannerModal.defaultProps = {};
QrScannerModal.propTypes = {
isOpen: PropTypes.bool.isRequired,
onBarCodeRead: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
};
|
examples/code-highlighting/index.js | ashutoshrishi/slate | import { Editor } from 'slate-react'
import { Value } from 'slate'
import Prism from 'prismjs'
import React from 'react'
import initialValue from './value.json'
/**
* Define our code components.
*
* @param {Object} props
* @return {Element}
*/
function CodeBlock(props) {
const { editor, node } = props
const language = node.data.get('language')
function onChange(event) {
editor.change(c =>
c.setNodeByKey(node.key, { data: { language: event.target.value } })
)
}
return (
<div style={{ position: 'relative' }}>
<pre>
<code {...props.attributes}>{props.children}</code>
</pre>
<div
contentEditable={false}
style={{ position: 'absolute', top: '5px', right: '5px' }}
>
<select value={language} onChange={onChange}>
<option value="css">CSS</option>
<option value="js">JavaScript</option>
<option value="html">HTML</option>
</select>
</div>
</div>
)
}
function CodeBlockLine(props) {
return <div {...props.attributes}>{props.children}</div>
}
/**
* The code highlighting example.
*
* @type {Component}
*/
class CodeHighlighting extends React.Component {
/**
* Deserialize the raw initial value.
*
* @type {Object}
*/
state = {
value: Value.fromJSON(initialValue),
}
/**
* On change, save the new value.
*
* @param {Change} change
*/
onChange = ({ value }) => {
this.setState({ value })
}
/**
* On key down inside code blocks, insert soft new lines.
*
* @param {Event} event
* @param {Change} change
* @return {Change}
*/
onKeyDown = (event, change) => {
const { value } = change
const { startBlock } = value
if (event.key != 'Enter') return
if (startBlock.type != 'code') return
if (value.isExpanded) change.delete()
change.insertText('\n')
return true
}
/**
* Render.
*
* @return {Component}
*/
render = () => {
return (
<div className="editor">
<Editor
placeholder="Write some code..."
value={this.state.value}
onChange={this.onChange}
onKeyDown={this.onKeyDown}
renderNode={this.renderNode}
renderMark={this.renderMark}
decorateNode={this.decorateNode}
/>
</div>
)
}
/**
* Render a Slate node.
*
* @param {Object} props
* @return {Element}
*/
renderNode = props => {
switch (props.node.type) {
case 'code':
return <CodeBlock {...props} />
case 'code_line':
return <CodeBlockLine {...props} />
}
}
/**
* Render a Slate mark.
*
* @param {Object} props
* @return {Element}
*/
renderMark = props => {
const { children, mark } = props
switch (mark.type) {
case 'comment':
return <span style={{ opacity: '0.33' }}>{children}</span>
case 'keyword':
return <span style={{ fontWeight: 'bold' }}>{children}</span>
case 'tag':
return <span style={{ fontWeight: 'bold' }}>{children}</span>
case 'punctuation':
return <span style={{ opacity: '0.75' }}>{children}</span>
}
}
tokenToContent = token => {
if (typeof token == 'string') {
return token
} else if (typeof token.content == 'string') {
return token.content
} else {
return token.content.map(this.tokenToContent).join('')
}
}
/**
* Decorate code blocks with Prism.js highlighting.
*
* @param {Node} node
* @return {Array}
*/
decorateNode = node => {
if (node.type != 'code') return
const language = node.data.get('language')
const texts = node.getTexts().toArray()
const string = texts.map(t => t.text).join('\n')
const grammar = Prism.languages[language]
const tokens = Prism.tokenize(string, grammar)
const decorations = []
let startText = texts.shift()
let endText = startText
let startOffset = 0
let endOffset = 0
let start = 0
for (const token of tokens) {
startText = endText
startOffset = endOffset
const content = this.tokenToContent(token)
const newlines = content.split('\n').length - 1
const length = content.length - newlines
const end = start + length
let available = startText.text.length - startOffset
let remaining = length
endOffset = startOffset + remaining
while (available < remaining && texts.length > 0) {
endText = texts.shift()
remaining = length - available
available = endText.text.length
endOffset = remaining
}
if (typeof token != 'string') {
const range = {
anchorKey: startText.key,
anchorOffset: startOffset,
focusKey: endText.key,
focusOffset: endOffset,
marks: [{ type: token.type }],
}
decorations.push(range)
}
start = end
}
return decorations
}
}
/**
* Export.
*/
export default CodeHighlighting
|
fluent-react/examples/redux-async/src/index.js | zbraniecki/fluent.js | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import store from './store';
import AppLocalizationProvider from './l10n';
import App from './App';
ReactDOM.render(
<Provider store={store}>
<AppLocalizationProvider>
<App />
</AppLocalizationProvider>
</Provider>,
document.getElementById('root')
);
|
examples/src/main.js | mohebifar/react-persian-datepicker | import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
ReactDOM.render(<App />, document.getElementById('content'));
|
src/containers/RemoteTodo/RemoteTodoApp.js | yatsu/react-apollo-koa-example | // @flow
import React from 'react'
import { Container, Divider } from 'semantic-ui-react'
import AddTodo from './AddTodo'
import TodoList from './TodoList'
const RemoteTodoApp = () => (
<Container text className="main main-content">
<h1>Todo Example (GraphQL)</h1>
<AddTodo />
<Divider />
<TodoList />
</Container>
)
export default RemoteTodoApp
|
app/components/add_button.js | therealaldo/MacroManagement | 'use strict';
import React from 'react';
import { View, StyleSheet, Alert } from 'react-native';
import { Actions } from 'react-native-router-flux';
import Button from 'react-native-button';
import Icon from 'react-native-vector-icons/Ionicons';
export default class AddButton extends React.Component {
render() {
return (
<Button onPress={ Actions.weeklyPlan }>
<Icon name='md-add-circle' size={ 50 } color='#efbe14' />
</Button>
)
}
};
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
|
client/react/frontpage/components/PrivacyPolicyPage.js | uclaradio/uclaradio | // PrivacyPolicyPage.js
import React from 'react';
import './PrivacyPolicyPage.scss';
/**
Privacy Policy Page
* */
const PrivacyPolicyPage = () => (
<div className="policyPage">
<h1>Welcome to our Privacy Policy</h1>
<h3>Your privacy is critically important to us.</h3>
UCLA Radio is located at:
<br />
<address>
UCLA Radio
<br />
308 Westwood Plaza Los Angeles <br />
90095 - CA , United States
<br />
</address>
<p>
It is UCLA Radio's policy to respect your privacy regarding any
information we may collect while operating our website. This Privacy
Policy applies to <a href="http://uclaradio.com">uclaradio.com</a>{' '}
(hereinafter, "us", "we", or "uclaradio.com"). We respect your privacy and
are committed to protecting personally identifiable information you may
provide us through the Website. We have adopted this privacy policy
("Privacy Policy") to explain what information may be collected on our
Website, how we use this information, and under what circumstances we may
disclose the information to third parties. This Privacy Policy applies
only to information we collect through the Website and does not apply to
our collection of information from other sources.
</p>
<p>
This Privacy Policy, together with the Terms and conditions posted on our
Website, set forth the general rules and policies governing your use of
our Website. Depending on your activities when visiting our Website, you
may be required to agree to additional terms and conditions.
</p>
<h2>Website Visitors</h2>
<p>
Like most website operators, UCLA Radio collects
non-personally-identifying information of the sort that web browsers and
servers typically make available, such as the browser type, language
preference, referring site, and the date and time of each visitor request.
UCLA Radio's purpose in collecting non-personally identifying information
is to better understand how UCLA Radio's visitors use its website. From
time to time, UCLA Radio may release non-personally-identifying
information in the aggregate, e.g., by publishing a report on trends in
the usage of its website.
</p>
<p>
UCLA Radio also collects potentially personally-identifying information
like Internet Protocol (IP) addresses for logged in users and for users
leaving comments on http://uclaradio.com blog posts. UCLA Radio only
discloses logged in user and commenter IP addresses under the same
circumstances that it uses and discloses personally-identifying
information as described below.
</p>
<h2>Gathering of Personally-Identifying Information</h2>
<p>
Certain visitors to UCLA Radio's websites choose to interact with UCLA
Radio in ways that require UCLA Radio to gather personally-identifying
information. The amount and type of information that UCLA Radio gathers
depends on the nature of the interaction. For example, we ask visitors who
sign up for a blog at http://uclaradio.com to provide a username and email
address.
</p>
<h2>Security</h2>
<p>
The security of your Personal Information is important to us, but remember
that no method of transmission over the Internet, or method of electronic
storage is 100% secure. While we strive to use commercially acceptable
means to protect your Personal Information, we cannot guarantee its
absolute security.
</p>
<h2>Links To External Sites</h2>
<p>
Our Service may contain links to external sites that are not operated by
us. If you click on a third party link, you will be directed to that third
party's site. We strongly advise you to review the Privacy Policy and
terms and conditions of every site you visit.
</p>
<p>
We have no control over, and assume no responsibility for the content,
privacy policies or practices of any third party sites, products or
services.
</p>
<h2>Protection of Certain Personally-Identifying Information</h2>
<p>
UCLA Radio discloses potentially personally-identifying and
personally-identifying information only to those of its employees,
contractors and affiliated organizations that (i) need to know that
information in order to process it on UCLA Radio's behalf or to provide
services available at UCLA Radio's website, and (ii) that have agreed not
to disclose it to others. Some of those employees, contractors and
affiliated organizations may be located outside of your home country; by
using UCLA Radio's website, you consent to the transfer of such
information to them. UCLA Radio will not rent or sell potentially
personally-identifying and personally-identifying information to anyone.
Other than to its employees, contractors and affiliated organizations, as
described above, UCLA Radio discloses potentially personally-identifying
and personally-identifying information only in response to a subpoena,
court order or other governmental request, or when UCLA Radio believes in
good faith that disclosure is reasonably necessary to protect the property
or rights of UCLA Radio, third parties or the public at large.
</p>
<p>
If you are a registered user of http://uclaradio.com and have supplied
your email address, UCLA Radio may occasionally send you an email to tell
you about new features, solicit your feedback, or just keep you up to date
with what's going on with UCLA Radio and our products. We primarily use
our blog to communicate this type of information, so we expect to keep
this type of email to a minimum. If you send us a request (for example via
a support email or via one of our feedback mechanisms), we reserve the
right to publish it in order to help us clarify or respond to your request
or to help us support other users. UCLA Radio takes all measures
reasonably necessary to protect against the unauthorized access, use,
alteration or destruction of potentially personally-identifying and
personally-identifying information.
</p>
<h2>Aggregated Statistics</h2>
<p>
UCLA Radio may collect statistics about the behavior of visitors to its
website. UCLA Radio may display this information publicly or provide it to
others. However, UCLA Radio does not disclose your personally-identifying
information.
</p>
<h2>Cookies</h2>
<p>
To enrich and perfect your online experience, UCLA Radio uses "Cookies",
similar technologies and services provided by others to display
personalized content, appropriate advertising and store your preferences
on your computer.
</p>
<p>
A cookie is a string of information that a website stores on a visitor's
computer, and that the visitor's browser provides to the website each time
the visitor returns. UCLA Radio uses cookies to help UCLA Radio identify
and track visitors, their usage of http://uclaradio.com, and their website
access preferences. UCLA Radio visitors who do not wish to have cookies
placed on their computers should set their browsers to refuse cookies
before using UCLA Radio's websites, with the drawback that certain
features of UCLA Radio's websites may not function properly without the
aid of cookies.
</p>
<p>
By continuing to navigate our website without changing your cookie
settings, you hereby acknowledge and agree to UCLA Radio's use of cookies.
</p>
<h2>Privacy Policy Changes</h2>
<p>
Although most changes are likely to be minor, UCLA Radio may change its
Privacy Policy from time to time, and in UCLA Radio's sole discretion.
UCLA Radio encourages visitors to frequently check this page for any
changes to its Privacy Policy. Your continued use of this site after any
change in this Privacy Policy will constitute your acceptance of such
change.
</p>
</div>
);
export default PrivacyPolicyPage;
|
docs/src/Anchor.js | bvasko/react-bootstrap | import React from 'react';
const Anchor = React.createClass({
propTypes: {
id: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
},
render() {
return (
<a id={this.props.id} href={'#' + this.props.id} className="anchor">
<span className="anchor-icon">#</span>
{this.props.children}
</a>
);
}
});
export default Anchor;
|
app/imports/ui/client/components/ScrumBoard/index.js | valcol/ScrumNinja | import React, { Component } from 'react';
import { Session } from 'meteor/session';
import { createContainer } from 'meteor/react-meteor-data';
import { Collections } from '../../../../api/common/collections.js';
import {Meteor} from 'meteor/meteor';
import moment from 'moment';
import Board from './Board.js';
import FeedbackMessage from '../misc/FeedbackMessage';
import Box from '../misc/Box';
import BoxHeader from '../misc/BoxHeader';
import BoxBody from '../misc/BoxBody';
import BoxFooter from '../misc/BoxFooter';
import Loading from '../misc/Loading';
class ScrumBoard extends Component {
constructor(props) {
super(props);
}
isPaOrPm(){
return (this.props.currentProject.roles[Meteor.userId()] === 'pa' || this.props.currentProject.roles[Meteor.userId()] === 'pm');
}
currentSprintTasks(){
let currentSprintTasks = [];
for (sprint of this.props.sprints){
if (moment(sprint.end).isBefore(moment())){
for (usId of sprint.userstory){
for (task of this.props.tasks){
if ((task.state < 4) && (task.userstory.indexOf(usId) > -1) &&
(currentSprintTasks.indexOf(task) === -1)){
task.isLate = true;
currentSprintTasks.push(task);
}
}
}
}
else if (moment(sprint.start).isBefore(moment())) {
for (usId of sprint.userstory){
for (task of this.props.tasks){
if ((task.userstory.indexOf(usId) > -1) &&
(currentSprintTasks.indexOf(task) === -1)){
task.isLate = false;
currentSprintTasks.push(task);
}
}
}
}
}
return currentSprintTasks;
}
getColor(id){
for (userstory of this.props.userstories)
if (id === userstory.id)
return userstory.color;
}
renderUs(userstories){
return userstories.sort().map((userstory) => (<span className='badge' style={{backgroundColor: this.getColor(userstory)}} >#{userstory}</span>));
}
render() {
return (
<div>
{!this.props.loaded ? <div></div> :
<Board currentProject={this.props.currentProject}
currentSprintTasks = {this.currentSprintTasks()}
userstories = {this.props.userstories}
tasks = {this.props.tasks}
isPaOrPm={this.isPaOrPm}/>
}
<div className="modal fade" id="myModal" tabIndex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div className="modal-dialog" role="document">
<div className="modal-content">
<div className="modal-header">
<button type="button" className="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
<h4 className="modal-title">You must add traceability for the following US :</h4>
</div>
<div className="modal-body">
{(this.props.usFinished) ? this.renderUs(this.props.usFinished) : ''}
</div>
<div className="modal-footer">
<button type="button" className="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default createContainer((props) => {
const subscribeSprints = Meteor.subscribe('sprints', props.currentProject.name);
const subscribeUS = Meteor.subscribe('userstories', props.currentProject.name);
const subscribeTasks = Meteor.subscribe('tasks', props.currentProject.name);
const subscribeUsers = Meteor.subscribe('users', props.currentProject.name);
const sprints = Collections.Sprints.find({}).fetch();
const userstories = Collections.UserStories.find({}).fetch();
const tasks = Collections.Tasks.find({}).fetch();
const loaded = !!subscribeUS && !!subscribeUsers && !!subscribeSprints && !!subscribeTasks && !!sprints && !!tasks && !!userstories;
return {
error: Session.get('error'),
success: Session.get('success'),
warning: Session.get('warning'),
usFinished: Session.get('usTrace'),
loaded,
userstories: loaded ? userstories : [],
sprints: loaded ? sprints : [],
tasks: loaded ? tasks : []
};
}, ScrumBoard);
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | ejc233/tour-of-heroes | 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/components/widgets/controls/skew.js | abbr/ShowPreper | import React from 'react'
import EditableHtmlElement from './editableHtmlElement'
import {langs} from 'i18n/lang'
import _ from 'lodash'
let SkewControl = class extends React.Component {
onBlur = (p, v) => {
if (isNaN(v)) {
return
}
let newPropObj = _.cloneDeep(this.props.component.skew || {})
newPropObj[p] = parseInt(v) % 360 * Math.PI / 180
this.props.onSelectedWidgetUpdated(
{
container: this.props.container,
index: this.props.idx
},
{ skew: newPropObj },
langs[this.props.language].skewComponents
)
}
onDoubleClick = () => {
let newPropObj = _.cloneDeep(this.props.component.skew || {})
newPropObj[this.props.axis] = 0
this.props.onSelectedWidgetUpdated(
{
container: this.props.container,
index: this.props.idx
},
{ skew: newPropObj },
langs[this.props.language].skewComponents
)
}
onMouseDown = ev => {
this.props.onRotateMouseDown(ev, this.props.idx, this.props.axis, 'skew')
}
render() {
let skew = 0
try {
skew = this.props.component.skew[this.props.axis] || 0
} catch (ex) {}
return (
<span className={'skew-' + this.props.axis}>
<span
onMouseDown={this.onMouseDown}
onTouchStart={this.onMouseDown}
className={'sp-skew-' + this.props.axis + '-icon'}
onDoubleClick={this.onDoubleClick}
title={langs[this.props.language].skew + '-' + this.props.axis}
>
♢
</span>
<EditableHtmlElement
eleNm="span"
idx={this.props.idx}
onBlur={ev => this.onBlur(this.props.axis, ev.target.innerHTML)}
dangerouslySetInnerHTML={{
__html: Math.round(skew * 180 / Math.PI) % 360
}}
/>
<span contentEditable={false}>°</span>
</span>
)
}
}
module.exports = SkewControl
|
packages/material-ui-icons/src/Textsms.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let Textsms = props =>
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM9 11H7V9h2v2zm4 0h-2V9h2v2zm4 0h-2V9h2v2z" />
</SvgIcon>;
Textsms = pure(Textsms);
Textsms.muiName = 'SvgIcon';
export default Textsms;
|
packages/mineral-ui-icons/src/IconTabletMac.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconTabletMac(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M18.5 0h-14A2.5 2.5 0 0 0 2 2.5v19A2.5 2.5 0 0 0 4.5 24h14a2.5 2.5 0 0 0 2.5-2.5v-19A2.5 2.5 0 0 0 18.5 0zm-7 23c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm7.5-4H4V3h15v16z"/>
</g>
</Icon>
);
}
IconTabletMac.displayName = 'IconTabletMac';
IconTabletMac.category = 'hardware';
|
src/components/App.react.js | mizki9577/arevelk | import React from 'react'
import { Grid, Row, Navbar, Panel, Button } from 'react-bootstrap'
import Drawer from './Drawer.react'
import ControlPanel from './ControlPanel.react'
const App = () => (
<div>
<Navbar>
<Navbar.Header>
<Navbar.Brand>Arevelk</Navbar.Brand>
</Navbar.Header>
</Navbar>
<Grid>
<Row style={{textAlign: 'center'}}>
<Drawer />
</Row>
<Row>
<ControlPanel />
</Row>
</Grid>
</div>
)
export default App
// vim: set ts=2 sw=2 et:
|
src/components/Footer.js | GrooshBene/shellscripts | import './style/Footer.scss';
import React, { Component } from 'react';
export default class Footer extends Component {
render() {
return (
<footer>
<div className='container'>
This is a footer.<br />
A test footer. :P
</div>
</footer>
);
}
}
|
src/routes/Home/components/HomeView.js | BigBlueDot/SMT4AEncyclopedia | import React from 'react';
import DuckImage from '../assets/Duck.jpg';
import './HomeView.scss';
export const HomeView = () => (
<div>
<h4>Welcome!</h4>
<img
alt='This is a duck, because Redux!'
className='duck'
src={DuckImage} />
</div>
);
export default HomeView;
|
src/svg-icons/action/view-array.js | skarnecki/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewArray = (props) => (
<SvgIcon {...props}>
<path d="M4 18h3V5H4v13zM18 5v13h3V5h-3zM8 18h9V5H8v13z"/>
</SvgIcon>
);
ActionViewArray = pure(ActionViewArray);
ActionViewArray.displayName = 'ActionViewArray';
export default ActionViewArray;
|
www/spa/src/Survey/components/Complete/Survey.js | gram7gram/Survey | "use strict";
import '../../../../node_modules/react-intl-tel-input/dist/main.css';
import '../../../../node_modules/react-intl-tel-input/dist/libphonenumber.js';
import React from 'react';
import {Row,Col,FormGroup,FormControl,Button,ButtonGroup,Portlet,HelpBlock,Alert} from 'react-bootstrap';
import Spinner from 'react-spinner'
import PhoneInput from 'react-intl-tel-input';
import trans from '../../translator'
import * as Utils from '../../utils';
import Question from './Question';
import nextQuestion from '../../actions/Client/NextQuestion/Action'
import lastQuestion from '../../actions/Client/LastQuestion/Action'
import answerQuestion from '../../actions/Client/AnswerQuestion/Action'
import completeSurvey from '../../actions/Client/CompleteSurvey/Action'
import individualChanged from '../../actions/IndividualChanged/Action'
import userChanged from '../../actions/UserChanged/Action'
import contactsChanged from '../../actions/ContactsChanged/Action'
import cityChanged from '../../actions/CityChanged/Action'
import validate from '../../actions/Validate/Action'
export default class Survey extends React.Component {
constructor() {
super();
this.getSurvey = this.getSurvey.bind(this)
this.getActiveSurvey = this.getActiveSurvey.bind(this)
this.submitSurvey = this.submitSurvey.bind(this)
this.isLastQuestion = this.isLastQuestion.bind(this)
this.setAge = this.setAge.bind(this)
this.setCity = this.setCity.bind(this)
this.setFirstName = this.setFirstName.bind(this)
this.setLastName = this.setLastName.bind(this)
this.setMobilePhone = this.setMobilePhone.bind(this)
this.setEmail = this.setEmail.bind(this)
}
componentWillReceiveProps(nextProps) {
if (nextProps.ActiveSurvey.canValidate) {
this.props.dispatch(validate(nextProps.ActiveSurvey.model, {
survey: nextProps.ActiveSurvey.survey
}));
}
}
getSurvey() {
return this.props.ActiveSurvey.survey;
}
getActiveSurvey() {
return this.props.ActiveSurvey.model;
}
isLastQuestion() {
const orders = this.props.ActiveSurvey.questionOrder;
const question = this.getCurrentQuestion()
return question && question.cid === orders[orders.length - 1]
}
isFirstQuestion() {
return this.props.ActiveSurvey.currentQuestionIndex === 0
}
submitSurvey() {
this.props.dispatch(completeSurvey(this.getActiveSurvey()));
}
getCurrentQuestion() {
const orders = this.props.ActiveSurvey.questionOrder;
const cid = orders[this.props.ActiveSurvey.currentQuestionIndex]
return this.props.ActiveSurvey.questions[cid];
}
setFirstName(e) {
this.props.dispatch(individualChanged({
firstName: e.target.value
}))
}
setLastName(e) {
this.props.dispatch(individualChanged({
lastName: e.target.value
}))
}
setAge(e) {
this.props.dispatch(individualChanged({
age: parseInt(e.target.value)
}))
}
setMobilePhone(isValid, shortNumber, event, fullNumber) {
if (!isValid) return;
fullNumber = fullNumber.replace(/[^0-9]/g, '');
this.props.dispatch(contactsChanged({
number: fullNumber
}))
}
setEmail(e) {
this.props.dispatch(userChanged({
email: e.target.value
}))
}
setCity(e) {
this.props.dispatch(cityChanged({
name: e.target.value
}))
}
renderContent() {
const survey = this.getSurvey();
return Utils.objectValues(survey.questions)
.sort((a, b) => {
if (a.order < b.order) return -1
if (a.order > b.order) return 1
return 0
})
.map(question =>
<Question
key={question.id}
{...this.props.ActiveSurvey}
dispatch={this.props.dispatch}
question={question}
survey={survey}/>
)
}
renderGlobalErrors() {
const globalErrors = this.props.ActiveSurvey.globalErrors
if (globalErrors.length === 0) return null;
return <Alert bsStyle="danger">
{globalErrors.map((e, i) => <p key={i}>{e}</p>)}
</Alert>
}
render() {
if (this.props.ActiveSurvey.isLoading) {
return <Spinner/>
}
const survey = this.getSurvey();
const user = this.props.ActiveSurvey.model.user;
const phone = user.individual.contacts.mobilePhone;
const email = user.email;
const address = user.individual.address;
const areRulesAccepted = this.props.ActiveSurvey.areRulesAccepted;
const validator = this.props.ActiveSurvey.validator;
const isValid = validator.total === 0;
return (
<div>
<Row>
<div className="col-md-12 text-center">
<h2>{survey.name}</h2>
<p>{survey.description}</p>
</div>
<Col md={12}>
{this.renderGlobalErrors()}
{this.props.ActiveSurvey.isSaving ? <Spinner/> : null}
</Col>
</Row>
<Row>
<Col md={12}>
<Row>
<Col xs={12} sm={12} md={12} lg={12}>
<h4>Прошу внести меня в перечень участников Программы и предоставить ознакомительный
образец:</h4>
</Col>
</Row>
<Row>
<Col md={12}>
<div className="panel panel-info">
<div className="panel-heading">
<div className="panel-title bold">Персональная информация</div>
</div>
<div className="panel-body">
<div className="container-fluid">
<Row>
<Col xs={12} sm={6} md={6} lg={6}>
<FormGroup
validationState={validator.errors.firstName ? 'error' : null}>
<label htmlFor="">Имя</label>
<FormControl
type="text"
placeholder="Введите имя"
value={user.individual.firstName || ''}
onChange={this.setFirstName}/>
{validator.errors.firstName
?
<HelpBlock>{validator.errors.firstName.message}</HelpBlock>
: null}
</FormGroup>
</Col>
<Col xs={12} sm={6} md={6} lg={6}>
<FormGroup
validationState={validator.errors.lastName ? 'error' : null}>
<label htmlFor="">Фамилия</label>
<FormControl
type="text"
placeholder="Введите фамилию"
value={user.individual.lastName || ''}
onChange={this.setLastName}/>
{validator.errors.lastName
? <HelpBlock>{validator.errors.lastName.message}</HelpBlock>
: null}
</FormGroup>
</Col>
</Row>
<Row>
<Col xs={12} sm={6} md={6} lg={6}>
<FormGroup validationState={validator.errors.age ? 'error' : null}>
<label htmlFor="">Возраст, полных лет</label>
<FormControl
type="text"
placeholder="Введите количество"
value={user.individual.age || ''}
onChange={this.setAge}/>
{validator.errors.age
? <HelpBlock>{validator.errors.age.message}</HelpBlock>
: null}
</FormGroup>
</Col>
<Col xs={12} sm={6} md={6} lg={6}>
<FormGroup validationState={validator.errors.city ? 'error' : null}>
<label htmlFor="">Город проживания:</label>
<FormControl
type="text"
placeholder="Введите название"
value={address && address.city ? address.city : ''}
onChange={this.setCity}/>
{validator.errors.city
? <HelpBlock>{validator.errors.city.message}</HelpBlock>
: null}
</FormGroup>
</Col>
</Row>
<Row>
<Col xs={12} sm={12} md={6} lg={6}>
<FormGroup
validationState={validator.errors.mobilePhone ? 'error' : null}>
<label htmlFor="">Контактный мобильный телефон</label>
<PhoneInput
defaultCountry="ua"
preferredCountries={['ua']}
utilsScript={'libphonenumber.js'}
onPhoneNumberChange={this.setMobilePhone}
css={['intl-tel-input', 'form-control']}
value={phone || ''}
/>
{validator.errors.mobilePhone
?
<HelpBlock>{validator.errors.mobilePhone.message}</HelpBlock>
: null}
</FormGroup>
</Col>
<Col xs={12} sm={12} md={6} lg={6}>
<FormGroup
validationState={validator.errors.email ? 'error' : null}>
<label htmlFor="">Контактный e-mail</label>
<FormControl
type="text"
placeholder="Введите название"
value={email || ''}
onChange={this.setEmail}/>
{validator.errors.email
? <HelpBlock>{validator.errors.email.message}</HelpBlock>
: null}
</FormGroup>
</Col>
</Row>
</div>
</div>
</div>
</Col>
</Row>
</Col>
<Col md={12}>
{this.renderContent()}
</Col>
<div className="col-md-12 text-center">
<FormGroup>
{
this.props.ActiveSurvey.isSaving
? <Spinner/>
: <a href="javascript:"
className="btn btn-block btn-lg btn-primary btn-participate"
disabled={!(areRulesAccepted && isValid)}
onClick={this.submitSurvey}>{trans.ru.submitCompletedSurvey}</a>
}
</FormGroup>
</div>
</Row>
</div>
);
}
}
|
examples/ExampleDnD.js | t-hiroyoshi/react-dnd-item | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { DragDropContext }from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import { DnDItem, DropPositions } from '../src/index';
@DragDropContext(HTML5Backend)
class ExampleDnD extends Component {
constructor(props) {
super(props);
this.state = {
somethings: [
{id: '1', name: 'somethigs1'},
{id: '2', name: 'somethigs2'},
{id: '3', name: 'somethigs3'},
{id: '4', name: 'somethigs4'},
{id: '5', name: 'somethigs5'},
{id: '6', name: 'somethigs6'}
],
message: ""
};
}
dropAction(position, sourceId, targetId) {
const {
TOP_LEFT,
TOP_CENTER,
TOP_RIGHT,
MIDDLE_LEFT,
MIDDLE_CENTER,
MIDDLE_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT
} = DropPositions;
switch (position) {
case TOP_LEFT:
return this.setState({ message: `TOP_LEFT ${sourceId} dropped on ${targetId}` });
case TOP_CENTER:
return this.setState({ message: `TOP_CENTER ${sourceId} dropped on ${targetId}` });
case TOP_RIGHT:
return this.setState({ message: `TOP_RIGHT ${sourceId} dropped on ${targetId}` });
case MIDDLE_LEFT:
return this.setState({ message: `MIDDLE_LEFT ${sourceId} dropped on ${targetId}` });
case MIDDLE_CENTER:
return this.setState({ message: `MIDDLE_CENTER ${sourceId} dropped on ${targetId}` });
case MIDDLE_RIGHT:
return this.setState({ message: `MIDDLE_RIGHT ${sourceId} dropped on ${targetId}` });
case BOTTOM_LEFT:
return this.setState({ message: `BOTTOM_LEFT ${sourceId} dropped on ${targetId}` });
case BOTTOM_CENTER:
return this.setState({ message: `BOTTOM_CENTER ${sourceId} dropped on ${targetId}` });
case BOTTOM_RIGHT:
return this.setState({ message: `BOTTOM_RIGHT ${sourceId} dropped on ${targetId}` });
default:
return false;
}
}
hoverAction(position, sourceId, targetId) {
const {
TOP_LEFT,
TOP_CENTER,
TOP_RIGHT,
MIDDLE_LEFT,
MIDDLE_CENTER,
MIDDLE_RIGHT,
BOTTOM_LEFT,
BOTTOM_CENTER,
BOTTOM_RIGHT
} = DropPositions;
switch (position) {
case TOP_LEFT:
return this.setState({ message: `TOP_LEFT ${sourceId} hover on ${targetId}` });
case TOP_CENTER:
return this.setState({ message: `TOP_CENTER ${sourceId} hover on ${targetId}` });
case TOP_RIGHT:
return this.setState({ message: `TOP_RIGHT ${sourceId} hover on ${targetId}` });
case MIDDLE_LEFT:
return this.setState({ message: `MIDDLE_LEFT ${sourceId} hover on ${targetId}` });
case MIDDLE_CENTER:
return this.setState({ message: `MIDDLE_CENTER ${sourceId} hover on ${targetId}` });
case MIDDLE_RIGHT:
return this.setState({ message: `MIDDLE_RIGHT ${sourceId} hover on ${targetId}` });
case BOTTOM_LEFT:
return this.setState({ message: `BOTTOM_LEFT ${sourceId} hover on ${targetId}` });
case BOTTOM_CENTER:
return this.setState({ message: `BOTTOM_CENTER ${sourceId} hover on ${targetId}` });
case BOTTOM_RIGHT:
return this.setState({ message: `BOTTOM_RIGHT ${sourceId} hover on ${targetId}` });
default:
return false;
}
}
render() {
const {
somethings,
message
} = this.state;
const dropAction = ::this.dropAction;
const hoverAction = ::this.hoverAction;
const style = {
background: "skyblue",
width: "400px",
height: "100px",
margin: "5px 5px"
};
return (
<div>
<h1>{ message }</h1>
{somethings.map(something =>
<DnDItem dropAction={dropAction} hoverAction={hoverAction} id={something.id} key={something.id}>
<div style={style}>{something.name}</div>
</DnDItem>
)}
</div>
);
}
}
ReactDOM.render(<ExampleDnD />, document.getElementById('example'));
|
ui/src/main/js/components/UpdateStateMachine.js | thinker0/aurora | import React from 'react';
import StateMachine from 'components/StateMachine';
import { addClass } from 'utils/Common';
import { UPDATE_STATUS } from 'utils/Thrift';
import { getClassForUpdateStatus } from 'utils/Update';
export default function UpdateStateMachine({ update }) {
const events = update.updateEvents;
const states = events.map((e, i) => ({
className: addClass(
getClassForUpdateStatus(e.status),
(i === events.length - 1) ? ' active' : ''),
state: UPDATE_STATUS[e.status],
message: e.message,
timestamp: e.timestampMs
}));
const className = getClassForUpdateStatus(events[events.length - 1].status);
return <StateMachine className={addClass('update-state-machine', className)} states={states} />;
}
|
src/ui/components/Settings/Settings.react.js | Eeltech/SpaceMusik | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Nav, NavItem } from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';
/*
|--------------------------------------------------------------------------
| Global View
|--------------------------------------------------------------------------
*/
export default class Settings extends Component {
static propTypes = {
config: PropTypes.object,
library: PropTypes.object,
children: PropTypes.object,
}
constructor(props) {
super(props);
}
render() {
const config = this.props.config;
return (
<div className='view view-settings'>
<div className='settings-switcher'>
<Nav bsStyle="pills" activeKey={1} onSelect={undefined}>
<LinkContainer to='/settings/library'>
<NavItem eventKey={1}>Library</NavItem>
</LinkContainer>
<LinkContainer to='/settings/audio'>
<NavItem eventKey={2}>Audio</NavItem>
</LinkContainer>
<LinkContainer to='/settings/interface'>
<NavItem eventKey={3}>Interface</NavItem>
</LinkContainer>
<LinkContainer to='/settings/advanced'>
<NavItem eventKey={4}>Advanced</NavItem>
</LinkContainer>
<LinkContainer to='/settings/about'>
<NavItem eventKey={5}>About</NavItem>
</LinkContainer>
</Nav>
<div className="tab-content">
{ React.cloneElement(
this.props.children, {
config,
library: this.props.library,
})
}
</div>
</div>
</div>
);
}
}
|
src/svg-icons/notification/do-not-disturb-off.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationDoNotDisturbOff = (props) => (
<SvgIcon {...props}>
<path d="M17 11v2h-1.46l4.68 4.68C21.34 16.07 22 14.11 22 12c0-5.52-4.48-10-10-10-2.11 0-4.07.66-5.68 1.78L13.54 11H17zM2.27 2.27L1 3.54l2.78 2.78C2.66 7.93 2 9.89 2 12c0 5.52 4.48 10 10 10 2.11 0 4.07-.66 5.68-1.78L20.46 23l1.27-1.27L11 11 2.27 2.27zM7 13v-2h1.46l2 2H7z"/>
</SvgIcon>
);
NotificationDoNotDisturbOff = pure(NotificationDoNotDisturbOff);
NotificationDoNotDisturbOff.displayName = 'NotificationDoNotDisturbOff';
NotificationDoNotDisturbOff.muiName = 'SvgIcon';
export default NotificationDoNotDisturbOff;
|
app/components/ToggleOption/index.js | kdprojects/nichesportapp | /**
*
* ToggleOption
*
*/
import React from 'react';
import { injectIntl, intlShape } from 'react-intl';
const ToggleOption = ({ value, message, intl }) => (
<option value={value}>
{message ? intl.formatMessage(message) : value}
</option>
);
ToggleOption.propTypes = {
value: React.PropTypes.string.isRequired,
message: React.PropTypes.object,
intl: intlShape.isRequired,
};
export default injectIntl(ToggleOption);
|
packages/react/src/components/organisms/EmergencyAlerts/index.js | massgov/mayflower | /**
* EmergencyAlerts module.
* @module @massds/mayflower-react/EmergencyAlerts
* @requires module:@massds/mayflower-assets/scss/03-organisms/emergency-alerts
* @requires module:@massds/mayflower-assets/scss/02-molecules/emergency-alert
* @requires module:@massds/mayflower-assets/scss/02-molecules/emergency-header
*/
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import is from 'is';
import Collapse from 'MayflowerReactAnimations/Collapse';
import ButtonAlert from 'MayflowerReactButtons/ButtonAlert';
import EmergencyAlert from 'MayflowerReactMolecules/EmergencyAlert';
import EmergencyHeader from 'MayflowerReactMolecules/EmergencyHeader';
const EmergencyAlerts = ({
id, emergencyHeader, buttonAlert, alerts, theme, buttonClose, onButtonAlertClick, onButtonCloseClick
}) => {
const [state, setState] = React.useState({
open: false,
close: false
});
const handleClick = (e) => {
const { currentTarget } = e;
setState({
open: !state.open
});
if (is.fn(onButtonAlertClick)) {
onButtonAlertClick({ open: state.open, currentTarget });
}
};
const handleClose = (e) => {
const { currentTarget } = e;
setState({
close: !state.close
});
if (is.fn(onButtonCloseClick)) {
onButtonCloseClick({ close: state.close, currentTarget });
}
};
const sectionClasses = classNames({
'ma__emergency-alerts': true,
[`ma__emergency-alerts--${theme}`]: theme
});
const alertsWrapperClasses = classNames({
'ma__emergency-alerts__content': true,
'js-accordion-content': true,
[`ma__emergency-alerts__content--${theme}`]: theme
});
const headerClasses = classNames({
'ma__emergency-alerts__header': true,
[`ma__emergency-alerts__header--${theme}`]: theme
});
const interfaceClasses = classNames({
'ma__emergency-alerts__interface': true,
'js-accordion-link': true,
[`ma__emergency-alerts__interface--${theme}`]: theme,
open: state.open,
closed: !state.open
});
const hideButtonClasses = classNames({
'ma__emergency-alerts__hide': true,
'js-emergency-alerts-link': true,
[`ma__emergency-alerts__hide--${theme}`]: theme
});
return(
<Collapse in={!state.close} dimension="height">
<section className={sectionClasses} data-id={id}>
<div className={headerClasses}>
<div className="ma__emergency-alerts__container">
{emergencyHeader && <EmergencyHeader {...emergencyHeader} theme={theme} />}
{ alerts ? (
<div className="ma__emergency-alerts__header-interface js-accordion-link">
{buttonAlert && <ButtonAlert {...buttonAlert} onClick={handleClick} isOpen={state.open} />}
</div>
) : (buttonClose && (
<button
type="button"
className={hideButtonClasses}
title="hide alert"
aria-label="hide alert"
onClick={handleClose}
>
+
</button>
)
)}
</div>
</div>
{ alerts && (
<>
<Collapse in={state.open} dimension="height">
<div className={alertsWrapperClasses}>
<div className="ma__emergency-alerts__container">
{
/* eslint-disable-next-line react/no-array-index-key */
alerts.map((alert, i) => <EmergencyAlert {...alert} theme={theme} key={`alert-nested--${i}`} />)
}
</div>
</div>
</Collapse>
<div className={interfaceClasses}>
{buttonAlert && <ButtonAlert {...buttonAlert} onClick={handleClick} isOpen={state.open} />}
</div>
</>
)}
</section>
</Collapse>
);
};
EmergencyAlerts.propTypes = {
/** The data-id of the organism */
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
/** A string that controls different color themes for the component. */
theme: PropTypes.oneOf(['c-warning', 'c-primary-alt', 'c-primary', 'c-gray', 'c-error']),
/** An on button alert click callback function */
onButtonAlertClick: PropTypes.func,
/** An on button close click callback function */
onButtonCloseClick: PropTypes.func,
/** The emergency header props */
emergencyHeader: PropTypes.shape(EmergencyHeader.propTypes),
/** The props for the button alert */
buttonAlert: PropTypes.shape(ButtonAlert.propTypes),
/** An array of alert messages: <br />
* `message:` A message describing the event.<br />
* `timeStamp:` A string representing the time of the event.<br />
* `link:` An optional function whose return value is a link to take the user to page with more information.
*/
alerts: PropTypes.arrayOf(PropTypes.shape({
message: PropTypes.string.isRequired,
timeStamp: PropTypes.string,
link: PropTypes.func
})),
/** Whether or not to render a close button if not alerts are provided */
buttonClose: PropTypes.bool
};
EmergencyAlerts.defaultProps = {
theme: 'c-warning',
buttonClose: true
};
export default EmergencyAlerts;
|
app/jsx/external_apps/components/ExternalToolPlacementButton.js | venturehive/canvas-lms | /*
* Copyright (C) 2015 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import _ from 'underscore'
import I18n from 'i18n!external_tools'
import React from 'react'
import PropTypes from 'prop-types'
import ReactModal from 'react-modal'
import store from 'jsx/external_apps/lib/ExternalAppsStore'
import 'compiled/jquery.rails_flash_notifications'
const modalOverrides = {
overlay : {
backgroundColor: 'rgba(0,0,0,0.5)'
},
content : {
position: 'static',
top: '0',
left: '0',
right: 'auto',
bottom: 'auto',
borderRadius: '0',
border: 'none',
padding: '0'
}
};
export default React.createClass({
displayName: 'ExternalToolPlacementButton',
componentDidUpdate: function() {
const _this = this;
window.requestAnimationFrame(function() {
if (_this.refs.closex) {
_this.refs.closex.focus();
}
});
},
propTypes: {
tool: PropTypes.object.isRequired,
type: PropTypes.string, // specify "button" if this is not a menu item
onClose: PropTypes.func
},
getInitialState() {
return {
tool: this.props.tool,
modalIsOpen: false
}
},
openModal(e) {
e.preventDefault();
if (this.props.tool.app_type === 'ContextExternalTool') {
store.fetchWithDetails(this.props.tool).then(function(data) {
var tool = _.extend(data, this.props.tool);
this.setState({
tool: tool,
modalIsOpen: true
});
}.bind(this));
} else {
this.setState({
tool: this.props.tool,
modalIsOpen: true
});
}
},
closeModal() {
this.setState({ modalIsOpen: false }, () => {
if (this.props.onClose) this.props.onClose()
})
},
placements() {
var allPlacements = {
"account_navigation":I18n.t("Account Navigation"),
"assignment_selection":I18n.t("Assignment Selection"),
"similarity_detection":I18n.t("Similarity Detection"),
"assignment_menu":I18n.t("Assignment Menu"),
"collaboration":I18n.t("Collaboration"),
"course_assignments_menu":I18n.t("Course Assignments Menu"),
"course_home_sub_navigation":I18n.t("Course Home Sub Navigation"),
"course_navigation":I18n.t("Course Navigation"),
"course_settings_sub_navigation":I18n.t("Course Settings Sub Navigation"),
"discussion_topic_menu":I18n.t("Discussion Topic Menu"),
"editor_button":I18n.t("Editor Button"),
"file_menu":I18n.t("File Menu"),
"global_navigation":I18n.t("Global Navigation"),
"homework_submission":I18n.t("Homework Submission"),
"link_selection":I18n.t("Link Selection"),
"migration_selection":I18n.t("Migration Selection"),
"module_menu":I18n.t("Module Menu"),
"post_grades":I18n.t("Sync Grades"),
"quiz_menu":I18n.t("Quiz Menu"),
"tool_configuration":I18n.t("Tool Configuration"),
"user_navigation":I18n.t("User Navigation"),
"wiki_page_menu":I18n.t("Wiki Page Menu"),
};
var tool = this.state.tool;
var hasPlacements = false;
var appliedPlacements = _.map(allPlacements, function(value, key){
if (tool[key] || (tool["resource_selection"] && key == "assignment_selection") ||
(tool["resource_selection"] && key == "link_selection")) {
hasPlacements = true;
return <div>{ value }</div>;
}
});
return hasPlacements ? appliedPlacements : null;
},
getModal() {
return(
<ReactModal
ref='reactModal'
isOpen={this.state.modalIsOpen}
onRequestClose={this.closeModal}
style={modalOverrides}
className='ReactModal__Content--canvas ReactModal__Content--mini-modal'
overlayClassName='ReactModal__Overlay--canvas'
>
<div id={this.state.tool.name + "Heading"}
className="ReactModal__Layout"
>
<div className="ReactModal__Header">
<div className="ReactModal__Header-Title">
<h4 tabIndex="-1">{I18n.t('App Placements')}</h4>
</div>
<div className="ReactModal__Header-Actions">
<button className="Button Button--icon-action" type="button" ref='closex' onClick={this.closeModal} >
<i className="icon-x"></i>
<span className="screenreader-only">Close</span>
</button>
</div>
</div>
<div tabIndex="-1" className="ReactModal__Body" >
<div id={ this.state.tool.name.replace(/\s/g,'') + 'Placements' } >
{ this.placements() || I18n.t("No Placements Enabled")}
</div>
</div>
<div className="ReactModal__Footer">
<div className="ReactModal__Footer-Actions">
<button
ref="btnClose" type="button" className="btn btn-default"
id={ 'close' + this.state.tool.name }
onClick={this.closeModal}>
{I18n.t('Close')}
</button>
</div>
</div>
</div>
</ReactModal>
);
},
getButton() {
var editAriaLabel = I18n.t('View %{toolName} Placements', { toolName: this.state.tool.name });
if (this.props.type === "button") {
return(
<a href="#" ref="placementButton" role="button" aria-label={editAriaLabel} className="btn long" onClick={this.openModal} >
<i className="icon-info" data-tooltip="left" title={I18n.t('Tool Placements')}></i>
{ this.getModal() }
</a>
);
} else {
return(
<li role="presentation" className="ExternalToolPlacementButton">
<a href="#" tabIndex="-1" ref="placementButton" role="menuitem" aria-label={editAriaLabel} className="icon-info" onClick={this.openModal}>
{I18n.t('Placements')}
</a>
{ this.getModal() }
</li>
);
}
},
render() {
if (this.state.tool.app_type === 'ContextExternalTool') {
return (
this.getButton()
);
}
return false;
}
});
|
src/WindowControls.js | manojsinghnegiwd/react-window-titlebar | import React from 'react';
class WindowControls extends React.Component {
constructor(props){
super(props);
}
closeWindow = (remote) => {
remote.getCurrentWindow().close();
}
minimize = (remote) => {
remote.getCurrentWindow().minimize();
}
maximize = (remote) => {
let window = remote.getCurrentWindow();
if(window.isMaximized())
window.unmaximize();
else
window.maximize();
}
render () {
const {remote} = this.props;
return (
<ul className="windowControls">
<li onClick={ () => this.closeWindow(remote) } className="windowControlsButtons closeButton"></li>
<li onClick={ () => this.minimize(remote) } className="windowControlsButtons minButton"></li>
<li onClick={ () => this.maximize(remote) } className="windowControlsButtons maxButton"></li>
</ul>
)
}
}
export default WindowControls; |
vgdb-frontend/src/components/nav/Nav.js | mattruston/idb | import React, { Component } from 'react';
import './Nav.css';
import NavItem from './NavItem';
import SearchBar from './SearchBar';
/* Nav component for a standard style navbar */
class Nav extends Component {
render() {
return (
<nav className="nav">
<div className="container nav-container">
<div className="nav-start nav-section">
<NavItem text="gamingdb" link="/" bold={true}/>
</div>
<SearchBar/>
<div className="nav-end nav-section">
<div className="nav-menu">
<NavItem text="Games" link="/games"/>
<NavItem text="Developers" link="/developers"/>
<NavItem text="Platforms" link="/platforms"/>
<NavItem text="Characters" link="/characters"/>
<NavItem text="About" link="/about"/>
</div>
</div>
</div>
</nav>
);
}
}
export default Nav;
|
src/Components/App/Greetings.js | sailingmontezuma/strategiesandtrades | import React from 'react';
class Greetings extends React.Component {
render() {
return (
<div className="jumbotron">
<h1>Hi!</h1>
</div>
);
}
}
export default Greetings;
|
src/components/MessageForm/component.js | Hylozoic/hylo-redux | import React from 'react'
import { throttle, isEmpty } from 'lodash'
import CommentImageButton from '../CommentImageButton'
import { SENT_MESSAGE, trackEvent } from '../../util/analytics'
import { onEnterNoShift } from '../../util/textInput'
import { getSocket, socketUrl } from '../../client/websockets'
import { STARTED_TYPING_INTERVAL } from '../CommentForm/component'
import cx from 'classnames'
var { func, object, string, bool } = React.PropTypes
export default class MessageForm extends React.Component {
static propTypes = {
postId: string.isRequired,
placeholder: string,
onFocus: func,
onBlur: func,
pending: bool,
createComment: func.isRequired
}
static contextTypes = {
isMobile: bool,
currentUser: object
}
constructor (props) {
super(props)
this.state = {}
}
submit = event => {
if (event) event.preventDefault()
if (!this.state.text) return false
const { postId, createComment } = this.props
const { currentUser } = this.context
const userId = currentUser.id
const { text } = this.state
createComment({postId, text, userId})
.then(({ error }) => {
if (error) {
this.setState({text})
} else {
trackEvent(SENT_MESSAGE)
}
})
this.startTyping.cancel()
this.sendIsTyping(false)
this.setState({text: ''})
return false
}
componentDidMount () {
this.socket = getSocket()
}
focus () {
this.refs.editor.focus()
}
isFocused () {
return this.refs.editor === document.activeElement
}
sendIsTyping (isTyping) {
const { postId } = this.props
if (this.socket) {
this.socket.post(socketUrl(`/noo/post/${postId}/typing`), {isTyping})
}
}
// broadcast "I'm typing!" every 5 seconds starting when the user is typing.
// We send repeated notifications to make sure that a user gets notified even
// if they load a comment thread after someone else has already started
// typing.
startTyping = throttle(() => {
this.sendIsTyping(true)
}, STARTED_TYPING_INTERVAL)
render () {
const { onFocus, onBlur, postId, pending } = this.props
const placeholder = this.props.placeholder || 'Type a message...'
const { isMobile } = this.context
const { text } = this.state
const handleKeyDown = e => {
this.startTyping()
onEnterNoShift(e => {
e.preventDefault()
this.submit()
}, e)
}
return <form onSubmit={this.submit} className='message-form'>
<CommentImageButton postId={postId} />
<textarea ref='editor' name='message' value={text}
placeholder={placeholder}
onFocus={onFocus}
onChange={e => this.setState({text: e.target.value})}
onBlur={onBlur}
onKeyUp={this.stopTyping}
onKeyDown={handleKeyDown} />
{isMobile && <button onClick={isMobile ? this.submit : null}
className={cx({enabled: !isEmpty(text) && !pending})}>Send</button>}
</form>
}
}
|
react/CloseIcon/CloseIcon.iconSketch.js | seekinternational/seek-asia-style-guide | import React from 'react';
import CloseIcon from './CloseIcon';
export const symbols = {
'CloseIcon': <CloseIcon />
};
|
votrfront/js/LoginPage.js | fmfi-svt/votr |
import React from 'react';
import _ from 'lodash';
import { AboutModal } from './About';
import { Modal, ModalBase } from './layout';
import { AnalyticsMixin, FakeLink } from './router';
var TYPE_NAMES = {
'cosignproxy': 'Cosign (automatické)',
'cosignpassword': 'Cosign (meno a heslo)',
'cosigncookie': 'Cosign (manuálne cookie)',
'plainpassword': 'Meno a heslo',
'demo': 'Demo'
};
export class LoginForm extends React.Component {
state = {
server: Votr.settings.server || 0,
type: Votr.settings.type
}
handleServerChange = (event) => {
var server = event.target.value;
var newTypes = Votr.settings.servers[server].login_types;
var type = _.includes(newTypes, this.state.type) ? this.state.type : null;
this.setState({ server, type });
}
handleTypeChange = (event) => {
this.setState({ type: event.target.value });
}
render() {
var serverConfig = Votr.settings.servers[this.state.server];
var currentType = this.state.type || serverConfig.login_types[0];
return <form className="login" action="login" method="POST">
{Votr.settings.invalid_session &&
<p>Vaše prihlásenie vypršalo. Prihláste sa znova.</p>}
{Votr.settings.error &&
<React.Fragment>
<p>Prihlásenie sa nepodarilo.</p>
<p>
{"Technické detaily: "}
<code className="login-error">
{_.last(Votr.settings.error.trim("\n").split("\n"))}
</code>
{" "}
<FakeLink onClick={this.props.onOpenError}>Viac detailov...</FakeLink>
</p>
<p>
Ak problém pretrváva, napíšte nám na <a className="text-nowrap"
href="mailto:[email protected]">[email protected]
</a>.
</p>
<hr />
</React.Fragment>}
<input type="hidden" name="destination" value={location.search} />
{Votr.settings.servers.length > 1 ?
<p>
<label>
{"Server: "}
<select name="server" value={this.state.server} onChange={this.handleServerChange}>
{Votr.settings.servers.map((server, index) =>
<option key={index} value={index}>{server.title}</option>
)}
</select>
</label>
</p> :
<input type="hidden" name="server" value="0" />
}
{serverConfig.login_types.length > 1 ?
<p>
<label>
{"Typ prihlásenia: "}
<select name="type" value={currentType} onChange={this.handleTypeChange}>
{serverConfig.login_types.map((type) =>
<option key={type} value={type}>{TYPE_NAMES[type]}</option>
)}
</select>
</label>
</p> :
<input type="hidden" name="type" value={currentType} />
}
{(currentType == 'cosignpassword' || currentType == 'plainpassword') &&
<React.Fragment>
<p>
<label>
{"Meno: "}
<input name="username" />
</label>
</p>
<p>
<label>
{"Heslo: "}
<input name="password" type="password" />
</label>
</p>
</React.Fragment>}
{currentType == 'cosigncookie' &&
<React.Fragment>
{/* TODO: Detailed instructions for cosigncookie. */}
{serverConfig.ais_cookie &&
<p>
<label>
{"Hodnota cookie " + serverConfig.ais_cookie + ": "}
<input name="ais_cookie" />
</label>
</p>}
{serverConfig.rest_cookie &&
<p>
<label>
{"Hodnota cookie " + serverConfig.rest_cookie + ": "}
<input name="rest_cookie" />
</label>
</p>}
</React.Fragment>}
<button type="submit" className="btn btn-lg btn-primary center-block">Prihlásiť</button>
</form>;
}
}
export function LoginErrorModal() {
return (
<Modal title="Chyba pri prihlásení">
<pre>{Votr.settings.error}</pre>
</Modal>
);
}
export class LoginPage extends React.Component {
state = {}
openAbout = () => {
this.setState({ modal: 'about' });
}
openError = () => {
this.setState({ modal: 'error' });
}
closeModal = () => {
this.setState({ modal: null });
}
render() {
var content = <div className="login-page">
<div className="navbar navbar-inverse navbar-static-top">
<div className="container-fluid">
<div className="navbar-header">
<a href={Votr.settings.url_root} className="navbar-brand">Votr</a>
</div>
</div>
</div>
<div className="login-content">
<p>
<strong>Votr</strong> ponúka študentom jednoduchší a pohodlnejší
spôsob, ako robiť najčastejšie činnosti zo systému AIS. Zapíšte sa na
skúšky, prezrite si vaše hodnotenia a skontrolujte si počet kreditov
bez zbytočného klikania.
</p>
<hr />
<LoginForm onOpenError={this.openError} />
</div>
<div className="text-center">
<ul className="list-inline">
<li><FakeLink className="btn btn-link" onClick={this.openAbout}>O aplikácii</FakeLink></li>
<li><a className="btn btn-link" href="https://uniba.sk/" target="_blank">Univerzita Komenského</a></li>
<li><a className="btn btn-link" href="https://moja.uniba.sk/" target="_blank">IT služby na UK</a></li>
</ul>
</div>
</div>;
var modals = { 'about': AboutModal, 'error': LoginErrorModal };
var modalComponent = modals[this.state.modal];
return <React.Fragment>
{content}
<ModalBase component={modalComponent} onClose={this.closeModal} />
</React.Fragment>;
}
}
|
src/components/content.js | RaulEscobarRivas/React-Redux-High-Order-Components | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { getPositionSelected } from '../reducers';
import PlayerSelection from './player-selection';
import Share from './share';
class Content extends Component {
renderTitle() {
return (
<div className="title">
{this.props.positionSelected}
<div className="subtitle">
{`ELIGE A TU ${this.props.positionSelected}`}
</div>
</div>
);
}
render() {
const { positionSelected } = this.props;
return (
<div className="content">
{positionSelected && positionSelected !== '11 IDEAL' && this.renderTitle()}
{positionSelected==='ARQUERO' &&
<PlayerSelection freeSpots={1} />
}
{positionSelected==='DEFENSA' &&
<PlayerSelection freeSpots={3} />
}
{positionSelected==='MEDIOCAMPO' &&
<PlayerSelection freeSpots={4} />
}
{positionSelected==='DELANTEROS' &&
<PlayerSelection freeSpots={3} />
}
{positionSelected==='11 IDEAL' &&
<Share />
}
</div>
);
}
}
const mapStateToProps = state => {
return {
positionSelected: getPositionSelected(state)
}
}
export default connect(mapStateToProps)(Content);
|
src/svg-icons/content/flag.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentFlag = (props) => (
<SvgIcon {...props}>
<path d="M14.4 6L14 4H5v17h2v-7h5.6l.4 2h7V6z"/>
</SvgIcon>
);
ContentFlag = pure(ContentFlag);
ContentFlag.displayName = 'ContentFlag';
ContentFlag.muiName = 'SvgIcon';
export default ContentFlag;
|
packages/wix-style-react/src/Pagination/Pagination.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import { Pagination as CorePagination } from 'wix-ui-core/dist/src/components/pagination';
import { withFocusable } from 'wix-ui-core/dist/src/hocs/Focusable/FocusableHOC';
import ChevronLeft from 'wix-ui-icons-common/ChevronLeft';
import ChevronRight from 'wix-ui-icons-common/ChevronRight';
import { st, classes } from './Pagination.st.css';
const coreComponentDefaults = {
showFirstPage: true,
showLastPage: true,
responsive: false,
showFirstLastNavButtons: false,
showInputModeTotalPages: false,
paginationMode: 'pages',
nextLabel: <ChevronRight className={classes.arrow} />,
previousLabel: <ChevronLeft className={classes.arrow} />,
};
/** Component for pagination */
class Pagination extends React.PureComponent {
static displayName = 'Pagination';
static propTypes = {
/** Applied as data-hook HTML attribute that can be used in the tests */
dataHook: PropTypes.string,
/** A css class to be applied to the component's root element */
className: PropTypes.string,
/** Total available pages to show */
totalPages: PropTypes.number,
/** Currently selected page */
currentPage: PropTypes.number,
/** Returns selected page or arrow ({event,page}) */
onChange: PropTypes.func,
};
static defaultProps = {
currentPage: 1,
};
_getMaxPagesToShow = () => {
const { currentPage, totalPages } = this.props;
const absoluteNumDistance = Math.min(
Math.abs(1 - currentPage),
Math.abs(currentPage - totalPages),
);
if (absoluteNumDistance >= 4) {
return 9;
} else if (absoluteNumDistance === 3) {
return 8;
}
return 7;
};
render() {
const {
dataHook,
currentPage,
totalPages,
onChange,
nextLabel,
previousLabel,
className,
} = this.props;
return (
<div
className={st(classes.root, className)}
data-hook={dataHook}
onFocus={this.props.focusableOnFocus}
onBlur={this.props.focusableOnBlur}
>
<CorePagination
className={classes.pagination}
{...coreComponentDefaults}
previousLabel={previousLabel || coreComponentDefaults.previousLabel}
nextLabel={nextLabel || coreComponentDefaults.nextLabel}
onChange={onChange}
totalPages={totalPages}
currentPage={currentPage}
maxPagesToShow={this._getMaxPagesToShow()}
showNextLabel={currentPage !== totalPages}
showPreviousLabel={currentPage !== 1}
/>
</div>
);
}
}
export default withFocusable(Pagination);
|
src/app/domains/NotFound/NotFound.js | blueshift-cc/snooker-scoreboard | import React from 'react';
const NotFound = () => (
<div>
<h3>404 page not found</h3>
<p>We are sorry but the page you are looking for does not exist.</p>
</div>
);
export default NotFound;
|
Realization/frontend/czechidm-core/src/content/role/RoleCompositionTable.js | bcvsolutions/CzechIdMng | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
//
import * as Basic from '../../components/basic';
import * as Advanced from '../../components/advanced';
import * as Utils from '../../utils';
import { RoleCompositionManager, RoleManager, DataManager } from '../../redux';
import IncompatibleRoleWarning from './IncompatibleRoleWarning';
//
const uiKeyIncompatibleRoles = 'role-incompatible-roles-';
let manager = new RoleCompositionManager();
let roleManager = new RoleManager();
/**
* Table of role compositions - define business roles
*
* @author Radek Tomiška
*/
export class RoleCompositionTable extends Advanced.AbstractTableContent {
getContentKey() {
return 'content.role.compositions';
}
getUiKey() {
return this.props.uiKey;
}
componentDidMount() {
super.componentDidMount();
//
this._loadIncompatibleRoles();
}
getManager() {
// Init manager - evaluates if we want to use standard (original) manager or
// universal request manager (depends on existing of 'requestId' param)
manager = this.getRequestManager(this.props.match.params, manager);
roleManager = this.getRequestManager(this.props.match.params, roleManager);
return manager;
}
_loadIncompatibleRoles() {
const { forceSearchParameters } = this.props;
let entityId = null;
//
if (forceSearchParameters) {
if (forceSearchParameters.getFilters().has('superiorId')) {
entityId = forceSearchParameters.getFilters().get('superiorId');
}
if (forceSearchParameters.getFilters().has('subId')) {
entityId = forceSearchParameters.getFilters().get('subId');
}
}
if (entityId) {
this.context.store.dispatch(roleManager.fetchIncompatibleRoles(entityId, `${ uiKeyIncompatibleRoles }${ entityId }`));
}
}
showDetail(entity) {
if (!Utils.Entity.isNew(entity)) {
this.context.store.dispatch(this.getManager().fetchPermissions(entity.id, `${this.getUiKey()}-detail`));
}
//
super.showDetail(entity, () => {
this.refs.superior.focus();
});
}
save(entity, event) {
const formEntity = this.refs.form.getData();
//
super.save(formEntity, event);
}
afterSave(entity, error) {
if (!error) {
this.addMessage({ level: 'info', message: this.i18n('save.success', { count: 1, record: this.getManager().getNiceLabel(entity) }) });
this._loadIncompatibleRoles();
// reload parent in redux
const superior = entity._embedded.superior;
const sub = entity._embedded.sub;
//
this.context.store.dispatch(roleManager.clearEntities()); // sync
this.context.store.dispatch(roleManager.receiveEntity(superior.id, superior)); // sync
this.context.store.dispatch(roleManager.receiveEntity(sub.id, sub)); // sync
}
//
super.afterSave(entity, error);
}
afterDelete() {
super.afterDelete();
this._loadIncompatibleRoles();
}
_getIncompatibleRoles(role) {
const { _incompatibleRoles } = this.props;
//
if (!_incompatibleRoles) {
return [];
}
//
return _incompatibleRoles.filter(ir => ir.directRole.id === role.id);
}
render() {
const { uiKey, forceSearchParameters, _showLoading, _permissions, className } = this.props;
const { detail } = this.state;
let superiorId = null;
if (forceSearchParameters.getFilters().has('superiorId')) {
superiorId = forceSearchParameters.getFilters().get('superiorId');
}
let subId = null;
if (forceSearchParameters.getFilters().has('subId')) {
subId = forceSearchParameters.getFilters().get('subId');
}
//
return (
<div>
<Basic.Confirm ref="confirm-delete" level="danger"/>
<Advanced.Table
ref="table"
uiKey={ uiKey }
manager={ manager }
forceSearchParameters={ forceSearchParameters }
showRowSelection={ manager.canDelete() }
className={ className }
_searchParameters={ this.getSearchParameters() }
actions={
[
{ value: 'delete', niceLabel: this.i18n('action.delete.action'), action: this.onDelete.bind(this), disabled: false }
]
}
buttons={
[
<Basic.Button
level="success"
key="add_button"
className="btn-xs"
onClick={ this.showDetail.bind(this, { sub: subId, superior: superiorId }) }
rendered={ manager.canSave() }>
<Basic.Icon type="fa" icon="plus"/>
{' '}
{ this.i18n('button.add') }
</Basic.Button>
]
}>
<Advanced.Column
header=""
className="detail-button"
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
const content = [];
//
content.push(
<Advanced.DetailButton
title={this.i18n('button.detail')}
onClick={this.showDetail.bind(this, data[rowIndex])}/>
);
content.push(
<IncompatibleRoleWarning
incompatibleRoles={
superiorId !== null
?
this._getIncompatibleRoles(entity._embedded.sub)
:
this._getIncompatibleRoles(entity._embedded.superior)
}/>
);
return content;
}
}
sort={false}/>
<Advanced.Column
property="superior"
sortProperty="superior.name"
face="text"
header={ this.i18n('entity.RoleComposition.superior.label') }
sort
cell={
/* eslint-disable react/no-multi-comp */
({ rowIndex, data }) => {
const entity = data[rowIndex];
//
return (
<Advanced.EntityInfo
entityType="role"
entityIdentifier={ entity.superior }
entity={ entity._embedded.superior }
face="popover"
showIcon/>
);
}
}
rendered={ subId !== null }/>
<Advanced.Column
property="sub"
sortProperty="sub.name"
face="text"
header={ this.i18n('entity.RoleComposition.sub.label') }
sort
cell={
({ rowIndex, data }) => {
const entity = data[rowIndex];
//
return (
<Advanced.EntityInfo
entityType="role"
entityIdentifier={ entity.sub }
entity={ entity._embedded.sub }
face="popover"
showIcon/>
);
}
}
rendered={ superiorId !== null }/>
</Advanced.Table>
<Basic.Modal
bsSize="large"
show={detail.show}
onHide={this.closeDetail.bind(this)}
backdrop="static"
keyboard={!_showLoading}>
<form onSubmit={this.save.bind(this, {})}>
<Basic.Modal.Header
closeButton={ !_showLoading }
text={ this.i18n('create.header')}
rendered={ Utils.Entity.isNew(detail.entity) }/>
<Basic.Modal.Header
closeButton={ !_showLoading }
text={ this.i18n('edit.header', { name: manager.getNiceLabel(detail.entity) }) }
rendered={ !Utils.Entity.isNew(detail.entity) }/>
<Basic.Modal.Body>
<Basic.AbstractForm
ref="form"
showLoading={ _showLoading }
readOnly={ !manager.canSave(detail.entity, _permissions) }>
<Advanced.RoleSelect
ref="superior"
manager={ roleManager }
label={ this.i18n('entity.RoleComposition.superior.label') }
helpBlock={ this.i18n('entity.RoleComposition.superior.help') }
readOnly={ !Utils.Entity.isNew(detail.entity) || superiorId !== null }
required/>
<Advanced.RoleSelect
ref="sub"
manager={ roleManager }
label={ this.i18n('entity.RoleComposition.sub.label') }
helpBlock={ this.i18n('entity.RoleComposition.sub.help') }
readOnly={ !Utils.Entity.isNew(detail.entity) || subId !== null }
required/>
</Basic.AbstractForm>
</Basic.Modal.Body>
<Basic.Modal.Footer>
<Basic.Button
level="link"
onClick={ this.closeDetail.bind(this) }
showLoading={ _showLoading }>
{ this.i18n('button.close') }
</Basic.Button>
<Basic.Button
type="submit"
level="success"
rendered={ manager.canSave(detail.entity, _permissions) && Utils.Entity.isNew(detail.entity) }
showLoading={ _showLoading}
showLoadingIcon
showLoadingText={ this.i18n('button.saving') }>
{this.i18n('button.save')}
</Basic.Button>
</Basic.Modal.Footer>
</form>
</Basic.Modal>
</div>
);
}
}
RoleCompositionTable.propTypes = {
uiKey: PropTypes.string.isRequired,
/**
* "Hard filters"
*/
forceSearchParameters: PropTypes.object,
//
_showLoading: PropTypes.bool
};
RoleCompositionTable.defaultProps = {
forceSearchParameters: null,
_showLoading: false
};
function select(state, component) {
const forceSearchParameters = component.forceSearchParameters;
let entityId = null;
//
if (forceSearchParameters) {
if (forceSearchParameters.getFilters().has('superiorId')) {
entityId = forceSearchParameters.getFilters().get('superiorId');
}
if (forceSearchParameters.getFilters().has('subId')) {
entityId = forceSearchParameters.getFilters().get('subId');
}
}
//
return {
_showLoading: Utils.Ui.isShowLoading(state, `${component.uiKey}-detail`),
_permissions: Utils.Permission.getPermissions(state, `${component.uiKey}-detail`),
_searchParameters: Utils.Ui.getSearchParameters(state, component.uiKey),
_incompatibleRoles: DataManager.getData(state, `${ uiKeyIncompatibleRoles }${ entityId }`)
};
}
export default connect(select)(RoleCompositionTable);
|
spec/components/tabs.js | soyjavi/react-toolbox | import React from 'react';
import { Tabs, Tab } from '../../components/tabs';
class TabsTest extends React.Component {
state = {
index: 1,
fixedIndex: 1,
inverseIndex: 1
};
handleTabChange = (index) => {
this.setState({index});
};
handleFixedTabChange = (index) => {
this.setState({fixedIndex: index});
};
handleInverseTabChange = (index) => {
this.setState({inverseIndex: index});
};
handleActive = () => {
console.log('Special one activated');
};
render () {
return (
<section>
<h5>Tabs</h5>
<p>This tabs can be disabled or hidden</p>
<Tabs disableAnimatedBottomBorder index={this.state.index} onChange={this.handleTabChange}>
<Tab label='Primary'><small>Primary content</small></Tab>
<Tab label='Secondary' onActive={this.handleActive}><small>Secondary content</small></Tab>
<Tab label='Third' disabled><small>Disabled content</small></Tab>
<Tab label='Fourth' hidden><small>Fourth content hidden</small></Tab>
<Tab label='Fifth'><small>Fifth content</small></Tab>
</Tabs>
<h5>Fixed Tabs</h5>
<p>These tabs fill the given space.</p>
<Tabs index={this.state.fixedIndex} onChange={this.handleFixedTabChange} fixed>
<Tab label='First'><small>First Content</small></Tab>
<Tab label='Second'><small>Second Content</small></Tab>
<Tab label='Third'><small>Third Content</small></Tab>
</Tabs>
<h5>Inverse Tabs</h5>
<p>These tabs have an inverted theme.</p>
<Tabs index={this.state.inverseIndex} onChange={this.handleInverseTabChange} inverse>
<Tab label='First'><small>First Content</small></Tab>
<Tab label='Second'><small>Second Content</small></Tab>
<Tab label='Third'><small>Third Content</small></Tab>
<Tab label='Disabled' disabled><small>Disabled Content</small></Tab>
</Tabs>
<h5>Inverse Tabs with labels and icons</h5>
<Tabs index={this.state.inverseIndex} onChange={this.handleInverseTabChange} inverse>
<Tab label='Home' icon='home'><small>First Content</small></Tab>
<Tab label='Favorite' icon='favorite'><small>Second Content</small></Tab>
<Tab label='Call' icon='call'><small>Third Content</small></Tab>
</Tabs>
<h5>Inverse Tabs with icons</h5>
<Tabs index={this.state.inverseIndex} onChange={this.handleInverseTabChange} inverse>
<Tab icon='home'><small>First Content</small></Tab>
<Tab icon='favorite'><small>Second Content</small></Tab>
<Tab icon='call'><small>Third Content</small></Tab>
</Tabs>
</section>
);
}
}
export default TabsTest;
|
src/index.js | ansonpellissier/gordon-shuffle-react | import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import promise from 'redux-promise';
import createSagaMiddleware from 'redux-saga';
import { Router, hashHistory } from 'react-router';
import reducers from './reducers';
import routes from './routes';
import { runDraw } from './sagas';
import './styles/main.css';
const store = createStore(
reducers,
applyMiddleware(
promise,
createSagaMiddleware(runDraw)
)
);
render(
<Provider store={store}>
<Router history={hashHistory} routes={routes} />
</Provider>,
document.getElementById('root')
);
|
src/svg-icons/action/remove-shopping-cart.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionRemoveShoppingCart = (props) => (
<SvgIcon {...props}>
<path d="M22.73 22.73L2.77 2.77 2 2l-.73-.73L0 2.54l4.39 4.39 2.21 4.66-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h7.46l1.38 1.38c-.5.36-.83.95-.83 1.62 0 1.1.89 2 1.99 2 .67 0 1.26-.33 1.62-.84L21.46 24l1.27-1.27zM7.42 15c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h2.36l2 2H7.42zm8.13-2c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H6.54l9.01 9zM7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
ActionRemoveShoppingCart = pure(ActionRemoveShoppingCart);
ActionRemoveShoppingCart.displayName = 'ActionRemoveShoppingCart';
ActionRemoveShoppingCart.muiName = 'SvgIcon';
export default ActionRemoveShoppingCart;
|
src/component/InputPhone.js | chengfh11/react | import React, { Component } from 'react';
export default class InputPhone extends React.Component {
constructor() {
super();
this.state = {
phone: ''
}
}
handleChange = (e) => {
const formValue = parseInt(e.target.value);
if(!Number.isNaN(formValue) && formValue.toString().length <= 10) {
this.setState({ phone: e.target.value });
}
}
handleClick = (e) => {
e.preventDefault();
window.alert('Your phone number is ' + this.state.phone);
}
render() {
return(
<div>
<p>Input anthing i will alert you</p>
<input
type="text"
value={this.state.phone}
onChange={this.handleChange} />
<button
type="submit"
disabled={!this.state.phone}
onClick={this.handleClick}>
Submit
</button>
</div>
);
}
} |
packages/reactor-kitchensink/src/examples/D3/HeatMap/ConfigurablePivotHeatmap/ConfigurablePivotHeatmap.js | markbrocato/extjs-reactor | import React, { Component } from 'react';
import { Button, Toolbar, Spacer } from '@extjs/ext-react';
import { PivotD3Container } from '@extjs/ext-react-pivot-d3';
import salesData from './salesData';
Ext.require('Ext.pivot.d3.HeatMap');
const regions = {
"Belgium": 'Europe',
"Netherlands": 'Europe',
"United Kingdom": 'Europe',
"Canada": 'North America',
"United States": 'North America',
"Australia": 'Australia'
};
export default class ConfigurablePivotHeatmap extends Component {
store = Ext.create('Ext.data.Store', {
fields: [
{name: 'id', type: 'string'},
{name: 'company', type: 'string'},
{name: 'country', type: 'string'},
{name: 'person', type: 'string'},
{name: 'date', type: 'date', dateFormat: 'c'},
{name: 'value', type: 'float'},
{name: 'quantity', type: 'float'},
{
name: 'year',
calculate: function(data){
return parseInt(Ext.Date.format(data.date, "Y"), 10);
}
},{
name: 'month',
calculate: function(data){
return parseInt(Ext.Date.format(data.date, "m"), 10) - 1;
}
},{
name: 'continent',
calculate: function(data){
return regions[data.country];
}
}
],
data: salesData
})
showConfigurator = () => {
this.refs.mainCtn.showConfigurator();
}
onBeforeAddConfigField = (panel, config) => {
const dest = config.toContainer,
store = dest.getStore()
if(dest.getFieldType() !== 'all' && store.getCount() >= 1) {
// this will force single fields on both axis and aggregate
store.removeAll();
}
}
onShowFieldSettings = (panel, config) => {
const align = config.container.down('[name=align]');
// hide the alignment field in settings since it's useless
if(align) {
align.hide();
}
}
onTooltip = (component, tooltip, datum) => {
const d = datum.data,
x = component.getXAxis().getField(),
y = component.getYAxis().getField(),
z = component.getColorAxis().getField();
tooltip.setHtml(
'<div>X: ' + d[x] + '</div>' +
'<div>Y: ' + d[y] + '</div>' +
'<div>Z: ' + d[z] + '</div>' +
'<div>Records: ' + d.records + '</div>'
);
}
state = {
theme: 'default'
}
changeTheme = (select, choice) => {
this.setState({ theme: choice.get('value') });
}
render() {
const { theme } = this.state;
return (
<PivotD3Container
ref="mainCtn"
shadow
layout="fit"
onBeforeMoveConfigField={this.onBeforeAddConfigField}
onShowConfigFieldSettings={this.onShowFieldSettings}
matrix={{
store: this.store,
aggregate: [{
dataIndex: 'value',
header: 'Value',
aggregator: 'avg'
}],
leftAxis: [{
dataIndex: 'person',
header: 'Person'
}],
topAxis: [{
dataIndex: 'year',
header: 'Year'
}]
}}
drawing={{
xtype: 'pivotheatmap',
legend: {
items: {
count: 10
}
},
tooltip: {
renderer: this.onTooltip
},
platformConfig: {
phone: {
tiles: {
cls: 'phone-tiles'
}
},
tablet: {
tiles: {
cls: 'tablet-tiles'
}
}
}
}}
configurator={{
// It is possible to configure a list of fields that can be used to configure the pivot matrix
// If no fields list is supplied then all fields from the Store model are fetched automatically
fields: [{
dataIndex: 'quantity',
header: 'Qty',
// You can even provide a default aggregator function to be used when this field is dropped
// on the agg dimensions
aggregator: 'sum',
formatter: 'number("0")',
settings: {
// Define here in which areas this field could be used
allowed: ['aggregate'],
// Set a custom style for this field to inform the user that it can be dragged only to "Values"
style: {
fontWeight: 'bold'
},
// Define here custom formatters that ca be used on this dimension
formatters: {
'0': 'number("0")',
'0%': 'number("0%")'
}
}
}, {
dataIndex: 'value',
header: 'Value',
settings: {
// Define here in which areas this field could be used
allowed: 'aggregate',
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: ['sum', 'avg', 'count'],
// Set a custom style for this field to inform the user that it can be dragged only to "Values"
style: {
fontWeight: 'bold'
},
// Define here custom formatters that ca be used on this dimension
formatters: {
'0': 'number("0")',
'0.00': 'number("0.00")',
'0,000.00': 'number("0,000.00")',
'0%': 'number("0%")',
'0.00%': 'number("0.00%")'
}
}
}, {
dataIndex: 'company',
header: 'Company',
settings: {
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: ['count']
}
}, {
dataIndex: 'country',
header: 'Country',
settings: {
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: ['count']
}
}, {
dataIndex: 'person',
header: 'Person',
settings: {
// Define here what aggregator functions can be used when this field is
// used as an aggregate dimension
aggregators: 'count'
}
}, {
dataIndex: 'year',
header: 'Year',
settings: {
// Define here in which areas this field could be used
allowed: ['leftAxis', 'topAxis']
}
}, {
dataIndex: 'month',
header: 'Month',
labelRenderer: 'monthLabelRenderer',
settings: {
// Define here in which areas this field could be used
allowed: ['leftAxis', 'topAxis']
}
}]
}}
>
<Toolbar docked="top">
<Spacer/>
<Button handler={this.showConfigurator} text="Show configurator"/>
</Toolbar>
</PivotD3Container>
)
}
} |
src/client/admin/tags/tagForm.js | r3dDoX/geekplanet | import Button from '@material-ui/core/Button';
import MenuItem from '@material-ui/core/MenuItem/index';
import Paper from '@material-ui/core/Paper/index';
import MaterialTextField from '@material-ui/core/TextField';
import Downshift from 'downshift';
import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { Field, reduxForm } from 'redux-form';
import actions from 'redux-form/es/actions';
import styled from 'styled-components';
import TextField from '../../formHelpers/textField';
import { TagPropType } from '../../propTypes';
import { createLoadTags } from '../adminActions';
import TagService from './tagService';
const { initialize } = actions;
const FormContainer = styled.form`
padding: 24px;
`;
const ClearButton = styled(Button)`
margin-right: 10px !important;
`;
const formName = 'tags';
class TagForm extends React.Component {
constructor(props) {
super(props);
this.downshiftInstance = React.createRef();
}
render() {
const {
handleSubmit,
onSubmit,
selectTag,
clearForm,
savedTags: tags,
} = this.props;
return (
<FormContainer
name={formName}
onSubmit={(...props) => {
handleSubmit(onSubmit)(...props);
this.downshiftInstance.current.clearSelection();
}}
>
<Downshift
onSelect={selectTag}
itemToString={tag => (tag ? tag.name : '')}
ref={this.downshiftInstance}
>
{({ getInputProps, getItemProps, isOpen, inputValue, highlightedIndex }) => (
<div>
<MaterialTextField
InputProps={{
...getInputProps({
placeholder: 'Create New',
id: 'select-tag',
}),
}}
/>
{isOpen ? (
<Paper square>
{tags
.filter(({ name }) => name.toLowerCase().includes(inputValue.toLowerCase()))
.map((tag, index) => (
<MenuItem
{...getItemProps({ item: tag })}
key={tag.name}
selected={highlightedIndex === index}
component="div"
>
{tag.name}
</MenuItem>
))
}
</Paper>
) : null}
</div>
)}
</Downshift>
<br />
<Field
component={TextField}
name="_id"
label=""
type="text"
style={{ display: 'none' }}
/>
<Field
component={TextField}
name="name"
label="Name"
type="text"
/>
<br />
{this.downshiftInstance.current && this.downshiftInstance.current.state.inputValue && (
<ClearButton
onClick={() => {
this.downshiftInstance.current.clearSelection();
clearForm();
}}
variant="contained"
type="button"
>
Clear
</ClearButton>
)}
<Button variant="contained" color="primary" type="submit">
Save
</Button>
</FormContainer>
);
}
}
TagForm.propTypes = {
handleSubmit: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
selectTag: PropTypes.func.isRequired,
clearForm: PropTypes.func.isRequired,
savedTags: PropTypes.arrayOf(TagPropType).isRequired,
};
export default connect(
state => state.forms,
(dispatch) => {
function clearForm() {
dispatch(initialize(formName));
}
function loadTags() {
dispatch(createLoadTags());
}
return {
clearForm,
selectTag(tag) {
dispatch(initialize(formName, tag));
},
onSubmit(tag) {
TagService
.saveTag(tag)
.then(loadTags)
.then(clearForm);
},
};
},
)(reduxForm({
form: formName,
destroyOnUnmount: false,
})(TagForm));
|
packages/component/src/Middleware/ActivityStatus/RelativeTime.js | billba/botchat | import { hooks } from 'botframework-webchat-api';
import PropTypes from 'prop-types';
import React from 'react';
import ScreenReaderText from '../../ScreenReaderText';
import useForceRenderAtInterval from '../../hooks/internal/useForceRenderAtInterval';
const { useDateFormatter, useLocalizer, useRelativeTimeFormatter } = hooks;
const TIMER_INTERVAL = 60000;
const RelativeTime = ({ value }) => {
const formatDate = useDateFormatter();
const formatRelativeTime = useRelativeTimeFormatter();
const localize = useLocalizer();
useForceRenderAtInterval(value, TIMER_INTERVAL);
return (
<React.Fragment>
<ScreenReaderText text={localize('ACTIVITY_STATUS_SEND_STATUS_ALT_SENT_AT', formatDate(value))} />
<span aria-hidden={true}>{formatRelativeTime(value)}</span>
</React.Fragment>
);
};
RelativeTime.propTypes = {
value: PropTypes.string.isRequired
};
export default RelativeTime;
|
client/routes.js | msucorey/street-canvas | /* eslint-disable global-require */
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import cookie from 'react-cookie';
import App from './modules/App/App';
import PhotoDetailPageContainer from './modules/Photo/pages/PhotoDetailPage/PhotoDetailPageContainer';
import PhotoAddPageContainer from './modules/Photo/pages/PhotoAddPage/PhotoAddPageContainer';
import PhotoGalleryPage from './modules/Photo/pages/PhotoGalleryPage/PhotoGalleryPage';
import LoginPage from './modules/User/pages/LoginPage/LoginPage';
import PhotoListPage from './modules/Photo/pages/PhotoListPage/PhotoListPage';
import RegisterPage from './modules/User/pages/RegisterPage/RegisterPage';
// require.ensure polyfill for node
if (typeof require.ensure !== 'function') {
require.ensure = function requireModule(deps, callback) {
callback(require);
};
}
const requireLoggedIn = (nextState, replace, cb) => {
const authCookie = cookie.load('mernAuth');
if (!authCookie || !authCookie.t) {
replace('/login');
}
cb();
};
const requireNotLoggedIn = (nextState, replace, cb) => {
const authCookie = cookie.load('mernAuth');
if (authCookie && authCookie.t) {
replace('/');
}
cb();
};
// react-router setup with code-splitting
// More info: http://blog.mxstbr.com/2016/01/react-apps-with-pages/
export default (
<Route path="/" component={App}>
<IndexRoute component={PhotoListPage} />
<Route
path="/photos/:cuid" component={PhotoDetailPageContainer}
/>
<Route
path="/add"
onEnter={requireLoggedIn}
component={PhotoAddPageContainer}
/>
<Route
path="/gallery"
component={PhotoGalleryPage}
/>
<Route
path="/login" component={LoginPage}
/>
<Route
path="/register" component={RegisterPage}
/>
</Route>
);
|
js/webui/src/position_control.js | hyperblast/beefweb | import React from 'react'
import PropTypes from 'prop-types'
import clamp from 'lodash/clamp'
import PlayerModel from './player_model'
import { formatTime } from './utils'
import ModelBinding from './model_binding';
class PositionControl extends React.PureComponent
{
constructor(props)
{
super(props);
this.state = this.getStateFromModel();
this.handleClick = this.handleClick.bind(this);
}
getStateFromModel()
{
const { position, duration } = this.props.playerModel.activeItem;
return { duration, position };
}
handleClick(e)
{
if (e.button !== 0)
return;
const rect = e.target.getBoundingClientRect();
const positionPercent = (e.clientX - rect.left) / rect.width;
const newPosition = this.state.duration * positionPercent;
if (newPosition >= 0)
this.props.playerModel.setPosition(newPosition);
}
render()
{
var position = this.state.position;
var duration = this.state.duration;
var positionPercent = '0%';
var timeInfo = '';
if (position >= 0 && duration > 0)
{
positionPercent = '' + clamp(100 * position / duration, 0, 100) + '%';
timeInfo = formatTime(position) + ' / ' + formatTime(duration);
}
return (
<div className='position-control'>
<div className='progress-bar' onClick={this.handleClick}>
<div className='progress-bar-gauge' style={{width: positionPercent}}></div>
<div className='progress-bar-text'>{timeInfo}</div>
</div>
</div>
);
}
}
PositionControl.propTypes = {
playerModel: PropTypes.instanceOf(PlayerModel).isRequired
};
export default ModelBinding(PositionControl, { playerModel: 'change' });
|
fields/types/numberarray/NumberArrayFilter.js | suryagh/keystone | import React from 'react';
import ReactDOM from 'react-dom';
import { FormField, FormInput, FormRow, FormSelect } from 'elemental';
const MODE_OPTIONS = [
{ label: 'Exactly', value: 'equals' },
{ label: 'Greater Than', value: 'gt' },
{ label: 'Less Than', value: 'lt' },
{ label: 'Between', value: 'between' },
];
const PRESENCE_OPTIONS = [
{ label: 'At least one element', value: 'some' },
{ label: 'No element', value: 'none' },
];
function getDefaultValue () {
return {
mode: MODE_OPTIONS[0].value,
presence: PRESENCE_OPTIONS[0].value,
value: '',
};
}
var NumberArrayFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
mode: React.PropTypes.oneOf(MODE_OPTIONS.map(i => i.value)),
presence: React.PropTypes.oneOf(PRESENCE_OPTIONS.map(i => i.value)),
value: React.PropTypes.oneOf(
React.PropTypes.string,
React.PropTypes.shape({
min: React.PropTypes.number,
max: React.PropTypes.number,
})
),
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
// Returns a function that handles a specific type of onChange events for
// either 'minValue', 'maxValue' or simply 'value'
handleValueChangeBuilder (type) {
var self = this;
return function (e) {
switch (type) {
case 'minValue':
self.updateFilter({
value: {
min: e.target.value,
max: self.props.filter.value.max,
},
});
break;
case 'maxValue':
self.updateFilter({
value: {
min: self.props.filter.value.min,
max: e.target.value,
},
});
break;
case 'value':
self.updateFilter({
value: e.target.value,
});
break;
}
};
},
// Update the props with this.props.onChange
updateFilter (changedProp) {
this.props.onChange({ ...this.props.filter, ...changedProp });
},
// Update the filter mode
selectMode (mode) {
this.updateFilter({ mode });
ReactDOM.findDOMNode(this.refs.focusTarget).focus();
},
// Update the presence selection
selectPresence (presence) {
this.updateFilter({ presence });
ReactDOM.findDOMNode(this.refs.focusTarget).focus();
},
// Render the controls, showing two inputs when the mode is "between"
renderControls (presence, mode) {
let controls;
const placeholder = presence.label + ' is ' + mode.label.toLowerCase() + '...';
if (mode.value === 'between') {
// Render "min" and "max" input
controls = (
<FormRow>
<FormField width="one-half" style={{ marginBottom: 0 }}>
<FormInput
type="number"
ref="focusTarget"
placeholder="Min."
onChange={this.handleValueChangeBuilder('minValue')}
value={this.props.filter.value.min}
/>
</FormField>
<FormField width="one-half" style={{ marginBottom: 0 }}>
<FormInput
type="number"
placeholder="Max."
onChange={this.handleValueChangeBuilder('maxValue')}
value={this.props.filter.value.max}
/>
</FormField>
</FormRow>
);
} else {
// Render one number input
controls = (
<FormField>
<FormInput
type="number"
ref="focusTarget"
placeholder={placeholder}
onChange={this.handleValueChangeBuilder('value')}
value={this.props.filter.value}
/>
</FormField>
);
}
return controls;
},
render () {
const { filter } = this.props;
// Get mode and presence based on their values with .filter
const mode = MODE_OPTIONS.filter(i => i.value === filter.mode)[0];
const presence = PRESENCE_OPTIONS.filter(i => i.value === filter.presence)[0];
return (
<div>
<FormSelect options={PRESENCE_OPTIONS} onChange={this.selectPresence} value={presence.value} />
<FormSelect options={MODE_OPTIONS} onChange={this.selectMode} value={mode.value} />
{this.renderControls(presence, mode)}
</div>
);
},
});
module.exports = NumberArrayFilter;
|
modules/IndexLink.js | pheadra/react-router | import React from 'react'
import Link from './Link'
const IndexLink = React.createClass({
render() {
return <Link {...this.props} onlyActiveOnIndex={true} />
}
})
export default IndexLink
|
src/lib/plot/axis/y-axis.js | jameskraus/react-vis | // Copyright (c) 2016 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import Axis from './axis';
import {ORIENTATION} from '../../utils/axis-utils';
const {LEFT, RIGHT} = ORIENTATION;
const propTypes = {
...Axis.propTypes,
orientation: React.PropTypes.oneOf([
LEFT, RIGHT
])
};
const defaultProps = {
orientation: LEFT,
attr: 'y'
};
function YAxis(props) {
return (
<Axis {...props} />
);
}
YAxis.displayName = 'YAxis';
YAxis.propTypes = propTypes;
YAxis.defaultProps = defaultProps;
YAxis.requiresSVG = true;
export default YAxis;
|
src/admin/client/routes/products/categories/index.js | cezerin/cezerin | import React from 'react';
import CategoryEdit from 'modules/productCategories/edit';
import Categories from 'modules/productCategories/list';
export default () => (
<div className="row row--no-gutter col-full-height">
<div className="col-xs-12 col-sm-4 col-md-3 col--no-gutter scroll col-full-height">
<Categories showAll={false} showTrash={false} showAdd={true} />
</div>
<div className="col-xs-12 col-sm-8 col-md-9 col--no-gutter scroll col-full-height">
<CategoryEdit />
</div>
</div>
);
|
html.js | waigo/waigo.github.io | import React from 'react';
import DocumentTitle from 'react-document-title';
import { prefixLink } from 'gatsby-helpers';
const BUILD_TIME = new Date().getTime();
module.exports = React.createClass({
displayName: 'HTML',
propTypes: {
body: React.PropTypes.string,
},
render () {
const title = DocumentTitle.rewind();
let css;
if (process.env.NODE_ENV === 'production') {
css = <style dangerouslySetInnerHTML={{ __html: require('!raw!./public/styles.css') }} />
}
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<meta httpEquiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta
name="viewport"
content="width=device-width, initial-scale=1, maximum-scale=1, user-scalable=no"
/>
<link rel="shortcut icon" href="/img/logo.ico" />
<link rel="shortcut icon" href="/img/logo.png" />
<meta name="msapplication-TileColor" content="#fff" />
<meta name="msapplication-TileImage" content="/img/logo.png" />
<title>{title}</title>
{css}
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />
<script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
<script dangerouslySetInnerHTML={{ __html: `
(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
(i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','https://www.google-analytics.com/analytics.js','ga');
ga('create', 'UA-11640584-17', 'auto');
ga('send', 'pageview');
`}}></script>
</body>
</html>
);
},
})
|
index.js | tgecho/react-prosemirror | import React from 'react'
import {ProseMirror} from 'prosemirror'
export default React.createClass({
displayName: 'ProseMirror',
propTypes: {
options: React.PropTypes.object,
defaultValue: React.PropTypes.any,
value: React.PropTypes.any,
onChange: React.PropTypes.func,
valueLink: React.PropTypes.shape({
value: React.PropTypes.any,
requestChange: React.PropTypes.func,
}),
},
render() {
return React.createElement('div', {ref: 'pm'})
},
componentWillUpdate(props) {
if ('value' in props || 'valueLink' in props) {
const value = props.value ||
('valueLink' in props && props.valueLink.value) ||
''
if (value !== this._lastValue) {
this.pm.setContent(value, props.options.docFormat)
this._lastValue = value
}
}
},
componentWillMount() {
this._lastValue = this.props.value
if (this._lastValue === undefined && 'valueLink' in this.props) {
this._lastValue = this.props.valueLink.value
}
if (this._lastValue === undefined) {
this._lastValue = this.props.defaultValue
}
const options = Object.assign({doc: this._lastValue}, this.props.options)
if (options.doc === undefined || options.doc === null) {
// We could fall back to an empty string, but that wouldn't work for the json
// docFormat. Setting docFormat to null allows ProseMirror to use its own
// default empty document.
options.doc = null
options.docFormat = null
}
this.pm = new ProseMirror(options)
},
componentDidMount() {
this.refs.pm.appendChild(this.pm.wrapper)
this.pm.on('change', () => {
const callback = this.props.onChange ||
'valueLink' in this.props && this.props.valueLink.requestChange
if (callback) {
this._lastValue = this.pm.getContent(this.props.options.docFormat)
callback(this._lastValue)
}
})
},
componentDidUpdate({options: previous}) {
const current = this.props.options
Object.keys(current).forEach(k => {
if (current[k] !== previous[k]) {
try {
this.pm.setOption(k, current[k])
} catch(e) {
console.error(e)
console.warn(`Are you creating "${k}" in your render function? If so it will fail the strict equality check.`)
}
}
})
},
getContent(type = this.props.options.docFormat) {
return this.pm.getContent(type)
},
})
|
src/index.js | cleancodedojo/numerology-ui-react | /* eslint-disable import/default */
import React from 'react';
import {render} from 'react-dom';
import { Provider } from 'react-redux';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import configureStore from './store/configureStore';
import './styles/styles.scss'; // Yep, that's right. You can import SASS/CSS files too! Webpack will run the associated loader and plug this into the page.
import { syncHistoryWithStore } from 'react-router-redux';
browserHistory.listen( location => {
window.ga('send', 'pageview', location.pathname);
});
const store = configureStore();
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>, document.getElementById('app')
);
|
docs/src/app/components/pages/components/CircularProgress/Page.js | nathanmarks/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import circleProgressReadmeText from './README';
import circleProgressCode from '!raw!material-ui/CircularProgress/CircularProgress';
import CircleProgressExampleSimple from './ExampleSimple';
import circleProgressExampleSimpleCode from '!raw!./ExampleSimple';
import CircleProgressExampleDeterminate from './ExampleDeterminate';
import circleProgressExampleDeterminateCode from '!raw!./ExampleDeterminate';
const descriptions = {
indeterminate: 'By default, the indicator animates continuously.',
determinate: 'In determinate mode, the indicator adjusts to show the percentage complete, ' +
'as a ratio of `value`: `max-min`.',
};
const CircleProgressPage = () => (
<div>
<Title render={(previousTitle) => `Circular Progress - ${previousTitle}`} />
<MarkdownElement text={circleProgressReadmeText} />
<CodeExample
title="Indeterminate progress"
description={descriptions.indeterminate}
code={circleProgressExampleSimpleCode}
>
<CircleProgressExampleSimple />
</CodeExample>
<CodeExample
title="Determinate progress"
description={descriptions.determinate}
code={circleProgressExampleDeterminateCode}
>
<CircleProgressExampleDeterminate />
</CodeExample>
<PropTypeDescription code={circleProgressCode} />
</div>
);
export default CircleProgressPage;
|
examples/js/style/td-class-string-table.js | prajapati-parth/react-bootstrap-table | /* eslint max-len: 0 */
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
const products = [];
function addProducts(quantity) {
const startId = products.length;
for (let i = 0; i < quantity; i++) {
const id = startId + i;
products.push({
id: id,
name: 'Item name ' + id,
price: 2100 + i
});
}
}
addProducts(5);
export default class TrClassStringTable extends React.Component {
render() {
return (
<BootstrapTable data={ products }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name' className='td-header-string-example'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price' columnClassName='td-column-string-example'>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
ngiiedu-client/src/components/users/join/MainContainer.js | jinifor/branchtest | import React from 'react';
import { withRouter } from "react-router-dom";
import RaisedButton from 'material-ui/RaisedButton';
import TextField from 'material-ui/TextField';
import Paper from 'material-ui/Paper';
import FontIcon from 'material-ui/FontIcon';
import {orange500, cyan500} from 'material-ui/styles/colors';
class MainContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
idErrorText: '',
pwdErrorText: '',
emailErrorText: '',
authkeyErrorText: '',
idErrorStyle: {},
pwdErrorStyle: {},
emailErrorStyle: {},
authkeyErrorStyle: {},
idCheck: false,
pwdCheck: false,
emailCheck: false,
authkeyCheck: false
};
}
submit() {
if (!this.state.idCheck) {
alert("아이디를 확인해주세요.");
return;
} else if (!this.state.pwdCheck) {
alert("비밀번호를 확인해주세요.");
return;
} else if (!this.state.emailCheck) {
alert("이메일을 확인해주세요.")
return;
} else if ($('#userName').val() == '') {
alert('이름을 입력해주세요.');
return;
}
const $form = $('#join');
if (this.state.authkeyCheck) {
const userDivision = $('<input type="hidden" name="userDivision" value="1" />');
userDivision.appendTo($form);
}
this.props.history.push("/");
$form.submit();
}
checkID(value) {
if (value == '') {
this.setState({
idErrorText: "필수 입력 사항입니다.",
idErrorStyle: {color: orange500},
isComplete: false
});
return;
}
$.ajax({
url: 'http://localhost:8080/ngiiedu/api/v1/users/' + value + '.json',
dataType: 'json',
cache: false,
success: function(data) {
const users = JSON.parse(JSON.stringify(data)).response.data;
if (users) {
this.setState({
idErrorText: "이미 사용중인 아이디입니다.",
idErrorStyle: {color: orange500},
idCheck: false
});
} else {
this.setState({
idErrorText: "사용 가능한 아이디입니다.",
idErrorStyle: {color: cyan500},
idCheck: true
});
}
}.bind(this),
error: function(xhr, status, err) {
console.error(status, err.toString());
}.bind(this)
});
}
checkEmail(userEmail) {
if (userEmail == '') {
this.setState({
emailErrorText: "필수 입력 사항입니다.",
emailErrorStyle: {color: orange500},
emailCheck: false
});
return;
}
if (!this.isEmail(userEmail)) {
this.setState({
emailErrorText: "올바른 이메일 형식이 아닙니다.",
emailErrorStyle: {color: orange500},
emailCheck: false
});
return;
}
$.ajax({
url: 'http://localhost:8080/ngiiedu/api/v1/users/' + userEmail + '.json',
dataType: 'json',
cache: false,
success: function(data) {
const users = JSON.parse(JSON.stringify(data)).response.data;
if (users) {
this.setState({
emailErrorText: "이미 사용중인 이메일입니다.",
emailErrorStyle: {color: orange500},
emailCheck: false
});
} else {
this.setState({
emailErrorText: "사용 가능한 이메일입니다.",
emailErrorStyle: {color: cyan500},
emailCheck: true
});
}
}.bind(this),
error: function(xhr, status, err) {
console.error(status, err.toString());
}.bind(this)
});
}
isEmail(email) {
var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
return re.test(email);
}
checkPwd(id) {
const password = $('#password').val();
const rePassword = $('#rePassword').val();
if (password == rePassword) {
this.setState({
pwdErrorText: "비밀번호가 일치합니다.",
pwdErrorStyle: {color: cyan500},
pwdCheck: true
});
} else {
if (this.state.pwdErrorText == '' && id == "password") return;
this.setState({
pwdErrorText: "비밀번호가 일치하지 않습니다.",
pwdErrorStyle: {color: orange500},
pwdCheck: false
});
}
}
checkAuthkey(schoolAuthkey) {
if (schoolAuthkey == '') {
this.setState({
authkeyErrorText: "",
authkeyErrorStyle: {color: cyan500},
authkeyCheck: false
});
return;
}
$.ajax({
url: 'http://localhost:8080/ngiiedu/api/v1/schools/authkey/' + schoolAuthkey +'/get.json',
dataType: 'json',
cache: false,
success: function(data) {
const school = JSON.parse(JSON.stringify(data)).response.data;
if (school) {
this.setState({
authkeyErrorText: "학교명: " + school.schoolName + ", 소재지: " + school.schoolAddrRoad,
authkeyErrorStyle: {color: cyan500},
authkeyCheck: true
});
} else {
this.setState({
authkeyErrorText: "해당하는 학교코드가 없습니다.",
authkeyErrorStyle: {color: orange500},
authkeyCheck: false
});
}
}.bind(this),
error: function(xhr, status, err) {
console.error(status, err.toString());
}.bind(this)
});
}
render() {
return (
<div
style={{
padding: '20px',
margin: 'auto'
}}
>
<h3 style={{textAlign: 'center'}}>회원가입</h3>
<p style={{textAlign: 'center', fontSize: '11px'}}>로그인정보 및 가입정보를 입력하세요.</p>
<p style={{textAlign: 'right', fontSize: '10px'}}>*표시는 필수입력 사항입니다.</p>
<form action="http://localhost:8080/ngiiedu/api/v1/users.json" method="post" id="join">
<div style={{maxWidth: '60%', textAlign: 'center', margin: 'auto'}}>
<TextField
name="userid"
floatingLabelText="*아이디"
fullWidth={true}
errorText={this.state.idErrorText}
errorStyle={this.state.idErrorStyle}
floatingLabelFocusStyle={this.state.idErrorStyle}
onChange={(e) => this.checkID(e.target.value)}
/>
<TextField
id="password"
name="password"
floatingLabelText="*비밀번호"
fullWidth={true}
type="password"
onChange={() => this.checkPwd("password")}
/>
<TextField
id="rePassword"
name="rePassword"
floatingLabelText="*비밀번호 재확인"
fullWidth={true}
type="password"
errorText={this.state.pwdErrorText}
errorStyle={this.state.pwdErrorStyle}
floatingLabelFocusStyle={this.state.pwdErrorStyle}
onChange={() => this.checkPwd("rePassword")}
/>
<TextField
id="userName"
name="userName"
floatingLabelText="*이름"
fullWidth={true}
/>
<TextField
name="userEmail"
floatingLabelText="*이메일"
fullWidth={true}
errorText={this.state.emailErrorText}
errorStyle={this.state.emailErrorStyle}
floatingLabelFocusStyle={this.state.emailErrorStyle}
onChange={(e) => this.checkEmail(e.target.value)}
/>
<TextField
name="schoolName"
floatingLabelText="학교명"
fullWidth={true}
/>
<TextField
name="schoolAuthkey"
floatingLabelText="학교 비밀코드(교사전용)"
fullWidth={true}
errorText={this.state.authkeyErrorText}
errorStyle={this.state.authkeyErrorStyle}
floatingLabelFocusStyle={this.state.authkeyErrorStyle}
onChange={(e) => this.checkAuthkey(e.target.value)}
/>
</div>
<div style={{textAlign: 'center', maxWidth: '30%', margin: 'auto'}}>
<br />
<RaisedButton
label="가입하기"
fullWidth={true}
primary={true}
icon={<FontIcon className="fa fa-check" />}
onClick={this.submit.bind(this)}
/>
</div>
</form>
</div>
);
}
}
export default withRouter(MainContainer);
|
src/components/Button/index.js | oneteam-dev/draft-js-oneteam-rte-plugin | import React, { Component } from 'react';
import unionClassNames from 'union-class-names';
import isFunction from 'lodash/isFunction';
export default class Button extends Component {
onMouseDown = (e) => {
const { onMouseDown } = this.props;
if (isFunction(onMouseDown)) {
e.preventDefault();
onMouseDown();
}
}
onClick = (e) => {
const { onClick } = this.props;
if (isFunction(onClick)) {
e.preventDefault();
onClick();
}
}
render() {
const { theme, children } = this.props;
const activeClassName = unionClassNames('active', theme.active);
const containerClassName = unionClassNames('toolbar-button', theme.button, activeClassName);
const innerClassName = unionClassNames('toolbar-button__inner', theme.inner);
const bodyClassName = unionClassNames('toolbar-button__body', theme.inner);
return (
<span
className={containerClassName}
onMouseDown={this.onMouseDown}
onClick={this.onClick}
>
<span className={innerClassName}>
<span className={bodyClassName}>
{children || 'Button'}
</span>
</span>
</span>
);
}
}
|
src/website/app/demos/Flex/FlexItem/bestPractices.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Flex, { FlexItem } from '../../../../../library/Flex';
import Button from '../../../../../library/Button';
import Link from '../../../../../library/Link';
import type { BestPractices } from '../../../pages/ComponentDoc/types';
const bestPractices: BestPractices = [
{
type: 'do',
description: `Use FlexItem within [Flex](/components/flex) to align components
relative to one another.`,
example: (
<Flex justifyContent="end">
<FlexItem>
<Link href="https://example.com">Products</Link>
</FlexItem>
<FlexItem>
<Link href="https://example.com">About</Link>
</FlexItem>
<FlexItem>
<Link href="https://example.com">Contact</Link>
</FlexItem>
</Flex>
)
},
{
type: 'dont',
description: `Don't use FlexItem within [Flex](/components/flex) to align
components to a columnar layout. Use [GridItem](/components/grid-item) within
[Grid](/components/grid), instead.`,
example: (
<Flex>
<FlexItem grow={1}>
<Button size="small" fullWidth>
Cut
</Button>
</FlexItem>
<FlexItem grow={1}>
<Button size="small" fullWidth>
Copy
</Button>
</FlexItem>
<FlexItem grow={1}>
<Button size="small" fullWidth>
Paste
</Button>
</FlexItem>
</Flex>
)
},
{
type: 'dont',
description: `Don't display content directly inside FlexItem. Wrap
FlexItem around components instead.`,
example: (
<Flex>
<FlexItem>1: Shipping Info</FlexItem>
<FlexItem>2: Billing Info</FlexItem>
<FlexItem>3: Confirm Order</FlexItem>
</Flex>
)
}
];
export default bestPractices;
|
client/modules/ManageNews/components/NewsList/NewsList.js | tranphong001/BIGVN | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Table, Button, Tooltip, OverlayTrigger } from 'react-bootstrap';
import { getCategories, getCities, getDistricts, getWards, getId } from '../../../App/AppReducer';
import { fetchDistricts, fetchWards, addDistricts, addWards, setNotify } from '../../../App/AppActions';
import { fetchUserNews } from '../../ManageNewsActions';
import { getUserNews } from '../../ManageNewsReducer';
import dateFormat from 'dateformat';
import styles from '../../../../main.css';
class NewsList extends Component {
constructor(props) {
super(props);
this.state = {
};
}
componentWillMount() {
if (this.props.id === '') {
this.context.router.push('/');
} else {
this.props.dispatch(fetchUserNews(this.props.id));
}
}
render() {
return (
<div>
<Table responsive striped bordered condensed hover className={styles.table}>
<thead>
<tr>
<th style={{ width: '40%' }}>Tiêu đề</th>
<th style={{ width: '13%' }}>Ngày tạo</th>
<th style={{ width: '12%', textAlign: 'center' }}>Đã duyệt</th>
<th style={{ width: '15%' }}>VIP</th>
<th style={{ width: '20%', textAlign: 'center' }}>Thao tác</th>
</tr>
</thead>
<tbody>
{
this.props.userNews.map((news, index) => {
const titleTooltip = (
<Tooltip id="tooltip" label="titleTooltip">{news.title}</Tooltip>
);
return (
<tr key={index}>
<td style={{ }} className={styles.titleOverFlow}>
<OverlayTrigger placement="top" overlay={titleTooltip}>
<p style={{ overflow: 'hidden', textOverflow: 'ellipsis' }}>{news.title}</p>
</OverlayTrigger>
</td>
<td>{dateFormat(news.dateCreated, 'dd/mm/yyyy HH:mm')}</td>
<td style={{ textAlign: 'center' }}>{(news.approved ? 'Đã duyệt' : 'Đang chờ')}</td>
<td>
{news.vipAll ? 'Toàn trang' : ''}
{news.vipCategory ? (news.vipAll ? ', danh mục' : 'Danh mục') : ''}
{(!news.vipAll && !news.vipCategory && news.approved) ? 'Tin thường' : ''}
{(!news.vipAll && !news.vipCategory && !news.approved) ? '---' : ''}
</td>
<td style={{ textAlign: 'center' }}>
<Button bsStyle="primary" style={{ float: 'left' }} bsSize="xs" onClick={() => this.props.onInfo(news)}>Xem trước</Button>
<Button bsStyle="primary" style={{ float: 'right' }} bsSize="xs" onClick={() => this.props.onEdit(news)}>Chỉnh sửa</Button>
</td>
</tr>
)
})
}
</tbody>
</Table>
</div>
);
}
}
// Retrieve data from store as props
function mapStateToProps(state) {
return {
id: getId(state),
userNews: getUserNews(state),
};
}
NewsList.propTypes = {
dispatch: PropTypes.func.isRequired,
onEdit: PropTypes.func.isRequired,
onInfo: PropTypes.func.isRequired,
id: PropTypes.string.isRequired,
userNews: PropTypes.array.isRequired,
};
NewsList.contextTypes = {
router: PropTypes.object,
};
export default connect(mapStateToProps)(NewsList);
|
node_modules/react-bootstrap/es/Tabs.js | CallumRocks/ReduxSimpleStarter | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
import requiredForA11y from 'prop-types-extra/lib/isRequiredForA11y';
import uncontrollable from 'uncontrollable';
import Nav from './Nav';
import NavItem from './NavItem';
import UncontrolledTabContainer from './TabContainer';
import TabContent from './TabContent';
import { bsClass as setBsClass } from './utils/bootstrapUtils';
import ValidComponentChildren from './utils/ValidComponentChildren';
var TabContainer = UncontrolledTabContainer.ControlledComponent;
var propTypes = {
/**
* Mark the Tab with a matching `eventKey` as active.
*
* @controllable onSelect
*/
activeKey: PropTypes.any,
/**
* Navigation style
*/
bsStyle: PropTypes.oneOf(['tabs', 'pills']),
animation: PropTypes.bool,
id: requiredForA11y(PropTypes.oneOfType([PropTypes.string, PropTypes.number])),
/**
* Callback fired when a Tab is selected.
*
* ```js
* function (
* Any eventKey,
* SyntheticEvent event?
* )
* ```
*
* @controllable activeKey
*/
onSelect: PropTypes.func,
/**
* Wait until the first "enter" transition to mount tabs (add them to the DOM)
*/
mountOnEnter: PropTypes.bool,
/**
* Unmount tabs (remove it from the DOM) when it is no longer visible
*/
unmountOnExit: PropTypes.bool
};
var defaultProps = {
bsStyle: 'tabs',
animation: true,
mountOnEnter: false,
unmountOnExit: false
};
function getDefaultActiveKey(children) {
var defaultActiveKey = void 0;
ValidComponentChildren.forEach(children, function (child) {
if (defaultActiveKey == null) {
defaultActiveKey = child.props.eventKey;
}
});
return defaultActiveKey;
}
var Tabs = function (_React$Component) {
_inherits(Tabs, _React$Component);
function Tabs() {
_classCallCheck(this, Tabs);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tabs.prototype.renderTab = function renderTab(child) {
var _child$props = child.props,
title = _child$props.title,
eventKey = _child$props.eventKey,
disabled = _child$props.disabled,
tabClassName = _child$props.tabClassName;
if (title == null) {
return null;
}
return React.createElement(
NavItem,
{
eventKey: eventKey,
disabled: disabled,
className: tabClassName
},
title
);
};
Tabs.prototype.render = function render() {
var _props = this.props,
id = _props.id,
onSelect = _props.onSelect,
animation = _props.animation,
mountOnEnter = _props.mountOnEnter,
unmountOnExit = _props.unmountOnExit,
bsClass = _props.bsClass,
className = _props.className,
style = _props.style,
children = _props.children,
_props$activeKey = _props.activeKey,
activeKey = _props$activeKey === undefined ? getDefaultActiveKey(children) : _props$activeKey,
props = _objectWithoutProperties(_props, ['id', 'onSelect', 'animation', 'mountOnEnter', 'unmountOnExit', 'bsClass', 'className', 'style', 'children', 'activeKey']);
return React.createElement(
TabContainer,
{
id: id,
activeKey: activeKey,
onSelect: onSelect,
className: className,
style: style
},
React.createElement(
'div',
null,
React.createElement(
Nav,
_extends({}, props, {
role: 'tablist'
}),
ValidComponentChildren.map(children, this.renderTab)
),
React.createElement(
TabContent,
{
bsClass: bsClass,
animation: animation,
mountOnEnter: mountOnEnter,
unmountOnExit: unmountOnExit
},
children
)
)
);
};
return Tabs;
}(React.Component);
Tabs.propTypes = propTypes;
Tabs.defaultProps = defaultProps;
setBsClass('tab', Tabs);
export default uncontrollable(Tabs, { activeKey: 'onSelect' }); |
src/main/resources/ui/components/JobSummaryView.js | mesos/chronos | import React from 'react'
import {observer} from 'mobx-react'
import $ from 'jquery'
import 'bootstrap'
import {JsonStore} from '../stores/JsonStore'
import JsonEditor from './JsonEditor'
$(document).ready(function(){
$('[data-toggle="tooltip"]').tooltip()
})
@observer
class JobSummaryView extends React.Component {
jsonStore = new JsonStore()
disabledWrap(job, value) {
if (job.disabled) {
return (
<s>{value}</s>
)
} else {
return (
value
)
}
}
getNameTd(job) {
if (job.disabled) {
return (
<td data-container="body" data-toggle="tooltip" data-placement="top" title="Job is disabled"><s>{job.name}</s></td>
)
} else {
return (
<td>{job.name}</td>
)
}
}
renderJob(job) {
return (
<tr key={job.name}>
{this.getNameTd(job)}
<td className={job.nextExpected === 'OVERDUE' ? 'danger' : null} data-container="body" data-toggle="tooltip" data-placement="top" title={job.schedule}>{job.nextExpected}</td>
<td className={this.getStatusClass(job)}>{job.status}</td>
<td className={this.getStateClass(job)}>{job.state}</td>
<td className="text-right">
<div className="btn-group" role="group" aria-label="Left Align">
<button
type="button"
onClick={(event) => this.runJob(event, job)}
className="btn btn-success btn-secondary"
aria-label="Run"
data-loading-text='<i class="fa fa-spinner fa-pulse fa-fw"></i>'
autoComplete="off"
title="Run">
<i className="fa fa-play" aria-hidden="true"></i>
</button>
<button
type="button"
className="btn btn-info"
aria-label="Edit"
onClick={() => this.editJob(job)}
title="Edit">
<i className="fa fa-pencil-square-o" aria-hidden="true"></i>
</button>
<button
type="button"
className="btn btn-warning"
aria-label="Stop"
data-loading-text='<i class="fa fa-spinner fa-pulse fa-fw"></i>'
onClick={(event) => this.stopJob(event, job)}
title="Stop">
<i className="fa fa-stop" aria-hidden="true"></i>
</button>
<button
type="button"
className="btn btn-danger"
aria-label="Delete"
data-loading-text='<i class="fa fa-spinner fa-pulse fa-fw"></i>'
onClick={(event) => this.deleteJob(this, job)}
title="Delete">
<i className="fa fa-times" aria-hidden="true"></i>
</button>
</div>
</td>
</tr>
)
}
render() {
const jobs = this.props.jobs
return (
<div>
<div className="table-responsive">
<table className="table table-striped table-hover table-condensed">
<thead>
<tr>
<th>JOB</th>
<th>NEXT RUN</th>
<th>STATUS</th>
<th>STATE</th>
<th className="text-right">ACTIONS</th>
</tr>
</thead>
<tbody>
{jobs.map(job => this.renderJob(job))}
</tbody>
</table>
</div>
<JsonEditor jsonStore={this.jsonStore} />
</div>
)
}
getStatusClass(job) {
if (job.status === 'success') {
return 'success'
}
if (job.status === 'failure') {
return 'warning'
}
return ''
}
getStateClass(job) {
if (job.state.match(/\d+ running/)) {
return 'success'
}
if (job.state === 'queued') {
return 'info'
}
return ''
}
doRequest(target, method, url, success, fail) {
var btn = $(target).button('loading')
$.ajax({
type: method,
url: url,
}).done(function(resp) {
setTimeout(function() {
btn.button('reset')
if (success) {
success()
}
}, 500)
}).fail(function(resp) {
setTimeout(function() {
btn.button('reset')
if (fail) {
fail(resp)
}
}, 500)
})
}
runJob(event, job) {
this.doRequest(
event.currentTarget,
'PUT',
'v1/scheduler/job/' + encodeURIComponent(job.name)
)
}
stopJob(event, job) {
this.doRequest(
event.currentTarget,
'DELETE',
'v1/scheduler/task/kill/' + encodeURIComponent(job.name)
)
}
deleteJob(event, job) {
let _job = job
this.doRequest(
event.currentTarget,
'DELETE',
'v1/scheduler/job/' + encodeURIComponent(job.name),
function(resp) {
_job.destroy()
}
)
}
editJob(job) {
this.jsonStore.loadJob(job.name)
$('#json-modal').modal('show')
}
}
JobSummaryView.propTypes = {
jobs: React.PropTypes.object.isRequired
}
export default JobSummaryView
|
src/client/components/NavbarBrand.js | xouabita/friends-radio | import React from 'react'
import {Link} from 'react-router-dom'
const NavbarBrand = ({className, ...props}) =>
<Link className={`${className} navbar-brand`} {...props} />
export default NavbarBrand
|
src/containers/dne.js | bulletcms/bullet-tracer | import React from 'react';
import {Section} from 'views';
class Dne extends React.Component{
render(){
return <div>
<Section>
<h1>404</h1>
<h4>content not found</h4>
</Section>
</div>;
}
}
export {Dne};
|
src/components/Privacy/Privacy.react.js | DeveloperAlfa/chat.susi.ai | import '../Terms/Terms.css';
import $ from 'jquery';
import Footer from '../Footer/Footer.react';
import PropTypes from 'prop-types';
import StaticAppBar from '../StaticAppBar/StaticAppBar.react';
import React, { Component } from 'react';
class Privacy extends Component {
constructor(props) {
super(props);
this.state = {
open: false,
showOptions: false,
anchorEl: null,
login: false,
signup: false,
video: false,
openDrawer: false,
};
}
componentDidMount() {
// Adding title tag to page
document.title = 'Privacy Policy - SUSI.AI, Open Source Artificial Intelligence for Personal Assistants, Robots, Help Desks and Chatbots';
// Scrolling to top of page when component loads
$('html, body').animate({ scrollTop: 0 }, 'fast');
}
showOptions = (event) => {
event.preventDefault();
this.setState({
showOptions: true,
anchorEl: event.currentTarget
})
}
_onReady(event) {
// access to player in all event handlers via event.target
event.target.pauseVideo();
}
render() {
document.body.style.setProperty('background-image', 'none');
return (
<div>
<StaticAppBar {...this.props}
location={this.props.location} />
<div className='head_section'>
<div className='container'>
<div className="heading">
<h1>Privacy</h1>
<p>Privacy Policy for SUSI</p>
</div>
</div>
</div>
<div className='section'>
<div className="section-container" >
<div className="terms-list">
<br /><br />
<h2>Welcome to SUSI!</h2>
<p>Thanks for using our products and services (“Services”).
The Services are provided by SUSI Inc. (“SUSI”),
located at 93 Mau Than, Can Tho City, Viet Nam.
By using our Services, you are agreeing to these terms.
Please read them carefully.
</p>
<h2>Using our Services</h2>
<p>You must follow any policies made available to you within the Services.
<br /><br />
Don’t misuse our Services. For example, don’t interfere with our
Services or try to access them using a method other than the
interface and the instructions that we provide. You may use
our Services only as permitted by law, including applicable
export and re-export control laws and regulations. We may
suspend or stop providing our Services to you if you do not
comply with our terms or policies or if we are investigating
suspected misconduct.
<br /><br />
Using our Services does not give you ownership of any intellectual
property rights in our Services or the content you access.
You may not use content from our Services unless you obtain
permission from its owner or are otherwise permitted by law.
These terms do not grant
you the right to use any branding or logos used in our Services.
Don’t remove, obscure, or alter any legal notices displayed in or
along with our Services.
<br /><br />
Our Services display some content that is not SUSI’s.
This content is the sole responsibility of the entity that
makes it available. We may review content to determine whether
it is illegal or violates our policies, and we may remove or
refuse to display content that we reasonably believe violates
our policies or the law. But that does not necessarily mean
that we review content, so please don’t assume that we do.
<br /><br />
In connection with your use of the Services, we may send
you service announcements, administrative messages,
and other information. You may opt out of some of those communications.
<br /><br />
Some of our Services are available on mobile devices.
Do not use such Services in a way that distracts you
and prevents you from obeying traffic or safety laws.
<br /><br />
</p>
<h2>Your SUSI Account</h2>
<p>
You may need a SUSI Account in order to use some of our Services.
You may create your own SUSI Account, or your SUSI Account may be
assigned to you by an administrator, such as your employer or
educational institution. If you are using a SUSI Account assigned
to you by an administrator, different or additional terms
may apply and your administrator may be able to access or
disable your account.
<br /><br />
To protect your SUSI Account, keep your password confidential.
You are responsible for the activity that happens on or through your
SUSI Account. Try not to reuse your SUSI Account password on
third-party applications. If you learn of any unauthorized
use of your password or SUSI Account, change your password
and take measures to secure your account.
<br /><br />
</p>
<h2>Privacy and Copyright Protection</h2>
<p>SUSI’s privacy policies ensures that your personal data is
safe and protected. By using our Services, you agree that
SUSI can use such data in accordance with our privacy policies.
<br /><br />
We respond to notices of alleged copyright infringement and
terminate accounts of repeat infringers. If you think somebody
is violating your copyrights and want to notify us,
you can find information about submitting notices and SUSI’s
policy about responding to notices on our website.
<br /><br />
</p>
<h2>Your Content in our Services</h2>
<p>Some of our Services allow you to upload, submit, store, send
or receive content. You retain ownership of any intellectual
property rights that you hold in that content. In short,
what belongs to you stays yours.
<br /><br />
When you upload, submit, store, send or receive content to
or through our Services, you give SUSI (and those we work with)
a worldwide license to use, host, store, reproduce, modify,
create derivative works (such as those resulting from
translations, adaptations or other changes we make so
that your content works better with our Services),
communicate, publish, publicly perform, publicly display
and distribute such content. The rights you grant in this
license are for the limited purpose of operating, promoting,
and improving our Services, and to develop new ones.
This license continues even if you stop using our Services
(for example, for a business listing you have added to
SUSI Maps). Some Services may offer you ways to access
and remove content that has been provided to that Service.
Also, in some of our Services, there are terms or settings
that narrow the scope of our use of the content submitted
in those Services. Make sure you have the necessary rights
to grant this license for any content that you submit to
our Services.
<br /><br />
If you have a SUSI Account, we may display your Profile name,
Profile photo, and actions you take on SUSI or on third-party
applications connected to your SUSI Account in our Services,
including displaying in ads and other commercial contexts.
We will respect the choices you make to limit sharing or
visibility settings in your SUSI Account.
<br /><br />
</p>
<h2>About Software in our Services</h2>
<p>When a Service requires or includes downloadable software,
this software may update automatically on your device once
a new version or feature is available. Some Services may
let you adjust your automatic update settings.
<br /><br />
SUSI gives you a personal, worldwide, royalty-free,
non-assignable and non-exclusive license to use the
software provided to you by SUSI as part of the Services.
This license is for the sole purpose of enabling you to
use and enjoy the benefit of the Services as provided by
SUSI, in the manner permitted by these terms.
<br /><br />
Most of our services are offered through Free
Software and/or Open Source Software. You may
copy, modify, distribute, sell, or lease these
applications and share the source code of that
software as stated in the License agreement provided
with the Software.
<br /><br />
</p>
<h2>Modifying and Terminating our Services</h2>
<p>We are constantly changing and improving our Services.
We may add or remove functionalities or features,
and we may suspend or stop a Service altogether.
<br /><br />
You can stop using our Services at any time.
SUSI may also stop providing Services to you,
or add or create new limits to our Services at any time.
<br /><br />
We believe that you own your data and preserving
your access to such data is important. If we
discontinue a Service, where reasonably possible,
we will give you reasonable advance notice and a
chance to get information out of that Service.
<br /><br />
</p>
<h2>Our Warranties and Disclaimers</h2>
<p>We provide our Services using a reasonable level
of skill and care and we hope that you will enjoy using them.
But there are certain things that we don’t promise about our Services.
<br /><br />
Other than as expressly set out in these terms or
additional terms, neither SUSI nor its suppliers or
distributors make any specific promises about the Services.
For example, we don’t make any commitments about the content
within the Services, the specific functions of the Services,
or their reliability, availability, or ability to meet your
needs. We provide the Services “as is”.
<br /><br />
Some jurisdictions provide for certain warranties,
like the implied warranty of merchantability,
fitness for a particular purpose and non-infringement.
To the extent permitted by law, we exclude all warranties.
<br /><br />
</p>
<h2>Liability for our Services</h2>
<p>When permitted by law, SUSI, and SUSI’s
suppliers and distributors, will not be responsible
for lost profits, revenues, or data, financial losses
or indirect, special, consequential, exemplary, or punitive damages.
<br /><br />
To the extent permitted by law, the total liability of SUSI,
and its suppliers and distributors, for any claims under these terms,
including for any implied warranties, is limited to the amount
you paid us to use the Services (or, if we choose,
to supplying you the Services again).
<br /><br />
In all cases, SUSI, and its suppliers and distributors,
will not be liable for any loss or damage that is not
reasonably foreseeable.
<br /><br />
We recognize that in some countries, you might have legal
rights as a consumer. If you are using the Services for
a personal purpose, then nothing in these terms or any additional
terms limits any consumer legal rights which may not be waived by
contract.
<br /><br />
</p>
<h2>Business uses of our Services</h2>
<p>If you are using our Services on behalf of a business,
that business accepts these terms. It will hold harmless
and indemnify SUSI and its affiliates, officers, agents,
and employees from any claim, suit or action arising from
or related to the use of the Services or violation of these terms,
including any liability or expense arising from claims, losses
, damages, suits, judgments, litigation costs and attorneys’ fees.
<br /><br /></p>
<h2>About these Terms</h2>
<p>We may modify these terms or any additional terms that
apply to a Service to,
for example, reflect changes to the law or changes to our Services.
You should look at the terms regularly.
We’ll post notice of modifications to these terms on this page.
We’ll post notice of modified additional terms in the applicable Service.
Changes will not apply retroactively and will become effective
no sooner than fourteen days after they are posted.
However,changes addressing new functions for a Service or changes made
for legal reasons will be effective immediately.
If you do not agree to the modified terms for a Service,
you should discontinue your use of that Service.
<br /><br />
If there is a conflict between these terms and the additional terms,
the additional terms will control for that conflict.
<br />
These terms control the relationship between SUSI and you.
They do not create any third party beneficiary rights.
<br /><br />
If you do not comply with these terms,
and we don’t take action right away,
this doesn’t mean that we are giving up any rights that
we may have (such as taking action in the future).
<br /><br />
If it turns out that a particular term is not enforceable,
this will not affect any other terms.<br /><br />
You agree that the laws of Can Tho, Viet Nam will
apply to any disputes arising out of or relating to
these terms or the Services. All claims arising out
of or relating to these terms or the services will be
litigated exclusively in the courts of Can Tho City,
Viet Nam, and you and SUSI consent to personal jurisdiction
in those courts.
<br /><br />
For information about how to contact SUSI, please visit our contact page.
<br /><br />
</p>
</div>
</div>
</div>
<Footer />
</div>
);
};
}
Privacy.propTypes = {
history: PropTypes.object,
location: PropTypes.object
}
export default Privacy;
|
src/PieChart.js | onefold/react-native-chart | /* @flow */
import React, { Component } from 'react';
import { ART, View, TouchableWithoutFeedback } from 'react-native';
const { Group, Surface } = ART;
import * as C from './constants';
import Wedge from './Wedge';
const getColor = (colors : Array<string>, index : number) => colors[index] || colors[colors.length % index];
export default class PieChart extends Component<void, any, any> {
constructor(props : any) {
super(props);
this.state = { rotation: 0 };
(this:any).boundingAreas = {};
}
shouldComponentUpdate(props : any) {
return (
props.data !== this.props.data
|| props.height !== this.props.height
|| props.width !== this.props.width
);
}
// TODO: Handle press on chart by emitting event
_handlePress = (_e : Object) => {
// const { locationX, locationY } = e.nativeEvent;
};
render() {
if (!this.props.width || !this.props.height) return <View />;
const COLORS = this.props.sliceColors || [
C.BLUE,
C.GREY,
C.RED,
C.YELLOW,
C.GREEN,
C.DARK_PURPLE,
C.LIGHT_PURPLE,
];
// TODO: Read stroke width from props?
const STROKE_WIDTH = 1;
const radius = (this.props.height / 2) - STROKE_WIDTH;
const centerX = this.props.width / 2;
const centerY = this.props.height / 2;
// Gather sum of all data to determine angles
let sum = 0;
const data = this.props.data || [];
data.forEach(n => { sum += (n[1] > 0) ? n[1] : 0.001; });
const sectors = data.map(n => Math.floor(360 * (n[1]/sum)));
let startAngle = 0;
const arcs = [];
const colors = [];
sectors.forEach((sectionPiece, i) => {
let endAngle = startAngle + sectionPiece;
if (endAngle > 360) {
endAngle = 360;
}
if (endAngle - startAngle === 0) {
startAngle += sectionPiece;
return;
}
if ((i === sectors.length - 1) && endAngle < 360) {
endAngle = 360;
}
arcs.push({ startAngle, endAngle, outerRadius: radius });
colors.push(getColor(COLORS, i));
startAngle += sectionPiece;
});
return (
<TouchableWithoutFeedback onPress={this._handlePress}>
<View>
<Surface width={this.props.width} height={this.props.height}>
<Group originX={centerX} width={this.props.width} height={this.props.height} originY={centerY} rotation={this.state.rotation}>
{arcs.map((arc, i) => {
return (
<Wedge
stroke={colors[i]}
strokeWidth={STROKE_WIDTH}
fill={colors[i]}
key={i}
originX={centerX}
originY={centerY}
{...arc}
/>
);
})}
</Group>
</Surface>
</View>
</TouchableWithoutFeedback>
);
}
}
|
src/routes.js | GuyLivni/react-redux-login-draggable | import React from 'react';
import {Route, IndexRoute} from 'react-router';
import App from './containers/App';
import LoginPage from './containers/LoginPage';
import HomePage from './containers/HomePage';
import NotFoundPage from './components/NotFoundPage';
import {checkAuth} from './routesAuth';
export default (
<Route component={App}>
<IndexRoute component={LoginPage}/>
<Route onEnter={checkAuth}>
<Route path="/" component={LoginPage}/>
<Route path="/homepage" component={HomePage}/>
</Route>
<Route path="*" component={NotFoundPage} />
</Route>
);
|
src/components/NotFoundPage.js | freelance-tech-writer/barstool-messages-frontend | import React from 'react';
import { Link } from 'react-router';
const NotFoundPage = () => {
return (
<div>
<h4>
404 Page Not Found
</h4>
<Link to="/messages"> Go back to messages </Link>
</div>
);
};
export default NotFoundPage;
|
js/components/sideBar/sidebar.js | GoldenOwlAsia/cooking-app | import React, { Component } from 'react';
import { Content, Container, Header, Text, Button, Icon, Title } from 'native-base';
import myTheme from '../../themes/base-theme';
import styles from './style';
class SideBar extends Component {
static propTypes = {
// setIndex: React.PropTypes.func,
navigateTo: React.PropTypes.func,
}
navigateTo(route) {
this.props.navigateTo(route, 'home');
}
render() {
return (
<Container theme={myTheme}>
<Header>
<Button transparent onPress={() => this.navigateTo('homeView')}>
<Icon name="ios-home" style={styles.icon} />
<Text>Trang chủ</Text>
</Button>
<Text></Text>
</Header>
<Content style={styles.sidebar}>
<Button transparent onPress={() => this.navigateTo('historyView')}>
<Icon name="ios-time" style={styles.icon} />
<Text>Lịch sử</Text>
</Button>
<Button transparent onPress={() => this.navigateTo('profileView')}>
<Icon name="ios-person" style={styles.icon} />
<Text>Về bạn</Text>
</Button>
</Content>
</Container>
);
}
}
export default SideBar;
|
examples/huge-apps/routes/Profile/components/Profile.js | stanleycyang/react-router | import React from 'react';
class Profile extends React.Component {
render () {
return (
<div>
<h2>Profile</h2>
</div>
);
}
}
export default Profile;
|
docs/src/scenes/Api/components/Section/index.js | directlyio/redink | import React from 'react';
import styles from './styles.scss';
const Method = ({ name, reference }) => {
console.log('reference.tags:', reference.tags);
const tags = reference.tags;
if (!tags) return null;
if (!tags[0]) return null;
if (tags[0].title !== 'method') return null;
tags.shift();
return (
<div className={styles.method}>
<h2>{name}#{reference.tags[0].name}</h2>
</div>
);
};
const Section = ({ name, references }) => (
<div className={styles.wrapper}>
<h1 className={styles.heading}>{name}</h1>
{references.map(reference =>
<Method name={name} reference={reference} />
)}
</div>
);
export default Section;
|
src/components/pages/Home.js | cristianszwarc/react_crud_localStorage | import React from 'react';
import { Component } from 'react';
export default class Home extends Component {
render() {
return (
<div >
<h1>
Home
</h1>
<div className="alert alert-info" role="alert">
This is a linked page.
</div>
</div>
);
}
}
|
app/javascript/mastodon/features/ui/util/reduced_motion.js | Kirishima21/mastodon | // Like react-motion's Motion, but reduces all animations to cross-fades
// for the benefit of users with motion sickness.
import React from 'react';
import Motion from 'react-motion/lib/Motion';
import PropTypes from 'prop-types';
const stylesToKeep = ['opacity', 'backgroundOpacity'];
const extractValue = (value) => {
// This is either an object with a "val" property or it's a number
return (typeof value === 'object' && value && 'val' in value) ? value.val : value;
};
class ReducedMotion extends React.Component {
static propTypes = {
defaultStyle: PropTypes.object,
style: PropTypes.object,
children: PropTypes.func,
}
render() {
const { style, defaultStyle, children } = this.props;
Object.keys(style).forEach(key => {
if (stylesToKeep.includes(key)) {
return;
}
// If it's setting an x or height or scale or some other value, we need
// to preserve the end-state value without actually animating it
style[key] = defaultStyle[key] = extractValue(style[key]);
});
return (
<Motion style={style} defaultStyle={defaultStyle}>
{children}
</Motion>
);
}
}
export default ReducedMotion;
|
website/core/WebPlayer.js | tszajna0/react-native | /**
* 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.
*
* @providesModule WebPlayer
*/
'use strict';
var Prism = require('Prism');
var React = require('React');
var WEB_PLAYER_VERSION = '1.2.6';
/**
* Use the WebPlayer by including a ```ReactNativeWebPlayer``` block in markdown.
*
* Optionally, include url parameters directly after the block's language. For
* the complete list of url parameters, see: https://github.com/dabbott/react-native-web-player
*
* E.g.
* ```ReactNativeWebPlayer?platform=android
* import React from 'react';
* import { AppRegistry, Text } from 'react-native';
*
* const App = () => <Text>Hello World!</Text>;
*
* AppRegistry.registerComponent('MyApp', () => App);
* ```
*/
var WebPlayer = React.createClass({
parseParams: function(paramString) {
var params = {};
if (paramString) {
var pairs = paramString.split('&');
for (var i = 0; i < pairs.length; i++) {
var pair = pairs[i].split('=');
params[pair[0]] = pair[1];
}
}
return params;
},
render: function() {
var hash = `#code=${encodeURIComponent(this.props.children)}`;
if (this.props.params) {
hash += `&${this.props.params}`;
}
return (
<div className={'web-player'}>
<Prism>{this.props.children}</Prism>
<iframe
style={{marginTop: 4}}
width="880"
height={this.parseParams(this.props.params).platform === 'android' ? '425' : '420'}
data-src={`//cdn.rawgit.com/dabbott/react-native-web-player/gh-v${WEB_PLAYER_VERSION}/index.html${hash}`}
frameBorder="0"
/>
</div>
);
},
});
module.exports = WebPlayer;
|
app/routes.js | ClearwaterClinical/cwc-react-redux-starter | import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from './containers/App'
import NotFoundPage from './containers/NotFoundPage'
import LoginPage from './containers/LoginPage'
import DashboardPage from './containers/DashboardPage'
import { urlPrefix } from './constants'
export default (
<Route path={urlPrefix} component={ App }>
<IndexRoute component={ LoginPage } />
<Route path="login" component={ LoginPage }/>
<Route path="dashboard" component={ DashboardPage }/>
<Route path="*" component={ NotFoundPage }/>
</Route>
)
|
pkg/interface/groups/src/js/components/skeleton.js | ngzax/urbit | import React, { Component } from 'react';
import classnames from 'classnames';
import { HeaderBar } from '/components/lib/header-bar';
import { GroupSidebar } from '/components/lib/group-sidebar';
export class Skeleton extends Component {
render() {
const { props } = this;
let rightPanelClasses =
props.activeDrawer === "groups" ? "dn flex-m flex-l flex-xl" : "flex";
return (
<div className="h-100 w-100 ph4-m ph4-l ph4-xl pb4-m pb4-l pb4-xl">
<HeaderBar invites={props.invites} associations={props.associations} />
<div className="cf w-100 h-100 h-100-m-40-ns flex ba-m ba-l ba-xl b--gray4 b--gray1-d br1">
<GroupSidebar
contacts={props.contacts}
groups={props.groups}
invites={props.invites}
activeDrawer={props.activeDrawer}
selected={props.selected}
selectedGroups={props.selectedGroups}
history={props.history}
api={api}
associations={props.associations}
/>
<div
className={"h-100 w-100 relative " + rightPanelClasses}
style={{ flexGrow: 1 }}>
{props.children}
</div>
</div>
</div>
);
}
}
|
vocab.js | thaiinhk/VocabReactNative | import React from 'react';
import {
Platform,
} from 'react-native';
// 3rd party libraries
import { Actions, Router, Scene } from 'react-native-router-flux';
import { AdMobInterstitial } from 'react-native-admob';
import DeviceInfo from 'react-native-device-info';
// Views
import MainView from './app/views/main';
import LessonView from './app/views/lesson';
import CardView from './app/views/card';
import AssignmentView from './app/views/assignment';
import InfoView from './app/views/info';
import { config } from './app/config';
AdMobInterstitial.setAdUnitID(config.admob[Platform.OS].interstital);
if (DeviceInfo.getDeviceName() === 'iPhone Simulator' || DeviceInfo.getDeviceName() === 'apple’s MacBook Pro' || DeviceInfo.getManufacturer() === 'Genymotion') {
AdMobInterstitial.setTestDeviceID('EMULATOR');
}
// @todo remove when RN upstream is fixed
console.ignoredYellowBox = [
'Warning: Failed propType: SceneView',
'Possible Unhandled Promise Rejection',
'ActivityIndicatorIOS is deprecated. Use ActivityIndicator instead.',
'Each ViewPager child must be a <View>.',
];
const scenes = Actions.create(
<Scene key="root" hideNavBar={true}>
<Scene key="main" title="Vocab" component={MainView} initial={true} />
<Scene key="lesson" title="Lesson" component={LessonView} />
<Scene key="card" title="Card" component={CardView} direction="vertical" />
<Scene key="assignment" title="Assignment" component={AssignmentView} direction="vertical" />
<Scene key="info" title="Info" component={InfoView} direction="vertical" />
</Scene>
);
const Periods = function Photos() {
return <Router scenes={scenes} />;
};
export default Periods;
|
src/index.js | TobiasBales/PlayuavOSDConfigurator | import extensiblePolyfill from 'extensible-polyfill';
extensiblePolyfill('immutable');
import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'react-redux';
import { Router, hashHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
import configureStore from './store/configureStore';
import 'material-design-icons-iconfont/dist/material-design-icons.css';
import './app.global.css';
import 'react-toolbox/lib/commons.scss';
import 'roboto-fontface/css/roboto-fontface';
import injectTapEventPlugin from 'react-tap-event-plugin';
const store = configureStore();
const history = syncHistoryWithStore(hashHistory, store);
injectTapEventPlugin();
render(
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>,
document.getElementById('root')
);
if (process.env.NODE_ENV !== 'production') {
// Use require because imports can't be conditional.
// In production, you should ensure process.env.NODE_ENV
// is envified so that Uglify can eliminate this
// module and its dependencies as dead code.
// require('./createDevToolsWindow')(store);
}
|
src/components/web/Card.js | Manuelandro/Universal-Commerce | import React from 'react'
import styled from 'styled-components'
const { View } = {
View: styled.div`
border: 1px solid #ddd;
border-radius: 2px;
border-bottom-width: 0;
box-shadow: 0, 2px 9px #000;
margin-left: 5px;
margin-right: 5px;
margin-top: 10px;
`
}
const Card = ({ children }) =>
<View>
{children}
</View>
export { Card }
|
app/app.js | tinysoft-ph/baiji-ui | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
src/routes.js | arpachuilo/fizz | import React from 'react'
import { Route, Router, IndexRedirect, browserHistory } from 'react-router'
import { ReduxRouter } from 'redux-router'
import App from './containers/App'
import Home from './pages/Home'
import Browse from './pages/Browse'
const routes = (
<ReduxRouter>
<Router history={browserHistory}>
<Route path='/' component={App}>
<IndexRedirect to='/browse' />
<Route path='/home' component={Home} />
<Route path='/browse' component={Browse} />
</Route>
</Router>
</ReduxRouter>
)
export default routes
|
packages/bonde-admin/src/components/navigation/browsable-list/browsable-list.js | ourcities/rebu-client | import PropTypes from 'prop-types'
import React from 'react'
import classnames from 'classnames'
if (require('exenv').canUseDOM) {
require('./browsable-list.scss')
}
const BrowsableList = ({ children, className, style }) => (
<div className={classnames('browsable-list rounded', className)} style={style}>
{children}
</div>
)
BrowsableList.propTypes = {
children: PropTypes.oneOfType([PropTypes.object, PropTypes.array]),
className: PropTypes.oneOfType([PropTypes.string, PropTypes.array]),
style: PropTypes.object
}
export default BrowsableList
|
app/containers/ContributeMenu/index.js | BeautifulTrouble/beautifulrising-client | /**
*
* ContributeMenu
*
*/
import React from 'react';
import { injectIntl } from 'react-intl';
import TranslatableStaticText from 'containers/TranslatableStaticText';
import LanguageThemeProvider from 'components/LanguageThemeProvider';
import MenuLink from 'components/MenuLink';
import MenuBlock from 'components/MenuBlock';
import MenuList from 'components/MenuList';
import MenuListItem from 'components/MenuListItem';
import MenuTitle from 'components/MenuTitle';
import staticText from './staticText';
function ContributeMenu(props) {
const { locale } = props.intl;
return (
<MenuBlock isArabic={locale==='ar'}>
<LanguageThemeProvider>
<MenuTitle>
<TranslatableStaticText {...staticText.header} />
</MenuTitle>
<MenuList>
<MenuListItem>
<MenuLink to="/contribute/how-it-works" onClick={props.onClick}>
<TranslatableStaticText {...staticText.howItWorks} />
</MenuLink>
<a href="http://donate.beautifultrouble.org" target="_blank" style={{textTransform: "uppercase", fontWeight: "bold", fontSize: "12px"}} key="donate">
<TranslatableStaticText {...staticText.donate} />
</a>
</MenuListItem>
</MenuList>
</LanguageThemeProvider>
</MenuBlock>
);
}
ContributeMenu.propTypes = {
};
export default injectIntl(ContributeMenu);
|
packages/@lyra/google-maps-input/src/GoogleMapsLoadProxy.js | VegaPublish/vega-studio | import PropTypes from 'prop-types'
import React from 'react'
import loadGoogleMapsApi from './loadGoogleMapsApi'
class GoogleMapsLoadProxy extends React.Component {
static propTypes = {
component: PropTypes.func.isRequired
}
constructor(props) {
super(props)
this.state = {
loading: true,
error: null
}
}
componentDidMount() {
loadGoogleMapsApi(this.props)
.then(api => this.setState({loading: false, api}))
.catch(err => this.setState({error: err}))
}
render() {
const {error, loading, api} = this.state
if (error) {
return <div>Load error: {error.stack}</div>
}
if (loading) {
return <div>Loading Google Maps API</div>
}
const GeopointSelect = this.props.component
return <GeopointSelect {...this.props} api={api} />
}
}
export default GoogleMapsLoadProxy
|
imports/client/ui/includes/MainMenu/Sidebar/Category/index.js | mordka/fl-events | import React from 'react'
import { Nav } from 'reactstrap'
import LinkItem from '../../LinkItem'
import './styles.scss'
const Category = ({ item, onClick }) => {
const {
title,
content
} = item
return (
<li className='category'>
<div className='divider' />
<Nav vertical>
<div className='title'>{title}</div>
{content.map((link, index) => (
<LinkItem key={index} item={link} onClick={onClick} />
))}
</Nav>
</li>
)
}
export default Category
|
src/Subscription.js | Samuron/VideoHustle | import React, { Component } from 'react';
import firebase from 'firebase';
import VideoContent from './VideoContent';
import YouTube from 'react-youtube';
import FlatButton from 'material-ui/FlatButton';
const Broadcast = React.createClass({
getInitialState() {
return {
video: {},
videoKey: this.props.params.videoKey
}
},
componentDidMount() {
firebase.database()
.ref(`/broadcasts/${this.state.videoKey}`)
.on( 'value', snapshot => {
const video = snapshot.val();
this.setState({ video });
this._setVideoState(video);
});
},
_setVideoState({ time, state }) {
if (this.player) {
// sync time
this.player.seekTo(time);
// playing or buffering
if (state === 1) {
this.player.playVideo();
} else {
this.player.pauseVideo();
}
}
},
onReady({ target }) {
this.player = target;
},
render() {
const opts = {
width: '500',
height: '300',
frameBorder: '0',
playerVars: {
autoPlay: 0,
controls: 0
}
};
return (
<div style={{ width: 500, margin: 'auto' }}>
{
this.state.videoKey ? <VideoContent
videoKey={this.state.videoKey}
collection="broadcasts"
onReady={e => this.onReady(e)}
expanded={true}
opts={opts} /> : null
}
</div>
);
}
});
export default Broadcast;
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.