path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/entry/SelectWallet.js | safex/safex_wallet | import React from 'react';
import {Link} from 'react-router';
import {
decryptWalletData,
DEFAULT_WALLET_PATH,
downloadWallet,
loadWalletFromFile,
flashField,
} from '../../utils/wallet';
import {
walletResetModal,
walletResetModalStep
} from '../../utils/modals';
import packageJson from "../../../package";
const fs = window.require('fs');
const fileDownload = require('react-file-download');
export default class SelectWallet extends React.Component {
constructor(props) {
super(props);
this.state = {
error: null,
isLoading: true,
walletExists: false,
walletResetModal: false,
walletResetModal1: false,
walletResetModalText: '',
walletResetModal2unencrypted: false,
walletResetModalDone: false,
walletResetModalDlUnencrypted: false,
walletResetModalDlEncrypted: false,
walletResetWarning1: false,
walletResetWarning2: false,
walletResetWarning3: false,
walletResetWarning4: false,
walletResetWarning5: false,
walletResetNoWallet: false,
wrong_password: false
};
this.walletResetStart = this.walletResetStart.bind(this);
this.walletResetWarning1Proceed = this.walletResetWarning1Proceed.bind(this);
this.walletResetWarning2Proceed = this.walletResetWarning2Proceed.bind(this);
this.walletResetWarning3Proceed = this.walletResetWarning3Proceed.bind(this);
this.walletResetWarning4Proceed = this.walletResetWarning4Proceed.bind(this);
this.walletResetWarning5Proceed = this.walletResetWarning5Proceed.bind(this);
this.walletResetStep1Skip = this.walletResetStep1Skip.bind(this);
this.walletResetStep1Proceed = this.walletResetStep1Proceed.bind(this);
this.walletResetStep2 = this.walletResetStep2.bind(this);
this.walletResetDlUnencrypted = this.walletResetDlUnencrypted.bind(this);
this.walletResetDlEncrypted = this.walletResetDlEncrypted.bind(this);
this.walletResetNoWallet = this.walletResetNoWallet.bind(this);
this.walletResetClose = this.walletResetClose.bind(this);
this.wrongPassword = this.wrongPassword.bind(this);
}
componentDidMount() {
this.tryLoadWalletFromDisk();
}
tryLoadWalletFromDisk() {
const walletPath = DEFAULT_WALLET_PATH;
loadWalletFromFile(walletPath, (err, encrypted) => {
if (err) {
console.error(err);
alert(err.message);
return;
}
if (!encrypted) {
this.setState({
walletExists: false,
isLoading: false
});
return;
}
localStorage.setItem('encrypted_wallet', encrypted);
localStorage.setItem('wallet_path', walletPath);
this.setState({
walletExists: true,
isLoading: false
});
});
}
openWalletResetModal(step, message) {
walletResetModal(this, step, message)
}
openWalletResetModalStep(step, closedStep, message) {
walletResetModalStep(this, step, closedStep, message)
}
wrongPassword() {
flashField(this, 'wrong_password');
}
//This happens when you click wallet reset on the main screen
walletResetStart() {
this.openWalletResetModal('walletResetModal', 'This feature is only if you want to delete a wallet and start over. This is not for upgrading wallet versions.');
this.openWalletResetModalStep('walletResetWarning1', '', 'This feature is only if you want to delete a wallet and start over. This is not for upgrading wallet versions.');
}
walletResetWarning1Proceed() {
this.openWalletResetModalStep('walletResetWarning2', 'walletResetWarning1', 'This is not necessary for upgrading wallet versions.');
}
walletResetWarning2Proceed() {
this.openWalletResetModalStep('walletResetWarning3', 'walletResetWarning2', 'PROCEED WITH CAUTION THIS PROCESS WILL DELETE YOUR EXISTING WALLET..');
}
walletResetWarning3Proceed() {
this.openWalletResetModalStep('walletResetWarning4', 'walletResetWarning3', 'This procedure will reset the wallet. It will take you through steps to backup the existing wallet. Then the existing wallet will be deleted to make room for a new one. PROCEED WITH CAUTION!!');
}
walletResetWarning4Proceed() {
this.openWalletResetModalStep('walletResetWarning5', 'walletResetWarning4', 'If you pushed this by mistake hit the white "x" to cancel wallet reset.');
}
walletResetWarning5Proceed() {
this.openWalletResetModalStep('walletResetModal1', 'walletResetWarning5', 'You do not need to do this for upgrading wallet versions. If you have your password and want to backup your keys unencrypted press proceed, otherwise press skip.');
}
//This happens when you click skip on the first modal
walletResetStep1Skip() {
this.openWalletResetModalStep('walletResetModalDlUnencrypted', 'walletResetModal1', 'During this stage you will be able to backup your encrypted wallet file. You may need it in the future and that is why this step exists.');
}
//This happens when you click proceed on the first modal
walletResetStep1Proceed() {
this.setState({
walletResetModal1: false,
})
this.openWalletResetModalStep('walletResetModal2unencrypted', 'walletResetModalDlUnencrypted', '');
}
walletResetNoWallet() {
this.openWalletResetModal('walletResetModal', '');
this.openWalletResetModal('walletResetNoWallet', 'There in no wallet.');
}
//This happens when you click proceed under the password entry for the unencrypted wallet
walletResetDlUnencrypted(e) {
e.preventDefault();
localStorage.setItem('password', e.target.password.value);
let wallet;
try {
wallet = decryptWalletData();
}
catch (err) {
console.error(err);
this.wrongPassword();
return;
}
let niceKeys = '';
const keys = wallet['keys'];
keys.forEach((key) => {
niceKeys += "private key: " + key.private_key + '\n';
niceKeys += "public key: " + key.public_key + '\n';
niceKeys += '\n';
});
const date = Date.now();
fileDownload(niceKeys, date + '_unsafex.txt');
this.setState({
walletResetModal1: false,
walletResetModal2unencrypted: false
});
this.openWalletResetModal('walletResetModalDlUnencrypted', 'During this stage you will be able to backup your encrypted wallet file. You may need it in the future and that is why this step exists.');
}
//This is the step2 of the encrypted and step3 of the unencrypted route
walletResetDlEncrypted(e) {
e.preventDefault();
if (e.target.checkbox.checked) {
this.setState({
walletResetModal1: false,
walletResetModalDlUnencrypted: false,
walletResetModal2unencrypted: false
})
this.openWalletResetModal('walletResetModalDlEncrypted', "This is second confirmation. When you check the box and proceed you will be able to backup your encrypted wallet. After this there is no turning back your wallet will be deleted so that you can make a new one. In this step you'll backup your encrypted wallet that was already in the wallet. During this stage you will be able to backup your encrypted wallet file. You may need it in the future that is why this step exists. AFTER THIS THERE IS NO TURNING BACK, YOUR WALLET WILL BE DELETED HIT THE 'X' TO GET OUT OF THIS");
}
}
//This leads to Done page in both routes
walletResetStep2(e) {
e.preventDefault();
if (e.target.checkbox.checked) {
const walletPath = DEFAULT_WALLET_PATH;
downloadWallet(walletPath, (err) => {
if (err) {
alert(err.message);
} else {
fs.unlink(DEFAULT_WALLET_PATH, (err) => {
if (err) {
alert('There was an issue resetting the wallet');
console.error(err);
} else {
this.setState({
walletResetModal1: false,
walletResetModalDlUnencrypted: false,
walletResetModal2unencrypted: false,
walletResetModalDlEncrypted: false,
walletExists: false
});
this.openWalletResetModal('walletResetModalDone', 'Your wallet reset is done. Now you can make a new wallet.');
}
});
}
});
}
}
//This closes every modal
walletResetClose() {
this.setState({
walletResetModal: false,
walletResetWarning1: false,
walletResetWarning2: false,
walletResetWarning3: false,
walletResetWarning4: false,
walletResetWarning5: false,
walletResetModal1: false,
walletResetModal2: false,
walletResetModal2unencrypted: false,
walletResetModalDone: false,
walletResetModalDlEncrypted: false,
walletResetModalDlUnencrypted: false,
walletResetNoWallet: false,
})
}
render() {
const wallet_exists = this.state.walletExists;
let show_options;
if (this.state.isLoading) {
return (
<div className="spinner-wrap">
<div className="lds-dual-ring"></div>
</div>
)
} else {
if (wallet_exists) {
show_options = (
<div className="container">
<div className="col-xs-12 Login-logo">
<h2>Safex</h2>
<h3>Wallet</h3>
<p>{packageJson.version}</p>
<button className="back-button wallet-reset-button" onClick={this.state.walletResetModal ? this.walletResetClose : this.walletResetStart}>Wallet Reset</button>
</div>
<div className="col-xs-8 col-xs-offset-2 App-intro">
<div className="row text-center">
<div className="col-xs-6 login-wrap fadeInDown">
<Link to="/login">
<div className="col-xs-12">
<img src="images/safex-icon-circle.png" alt="Safex Icon Circle"/>
<button className="btn btn-default button-neon-blue">Login</button>
<p>Enter your password</p>
</div>
</Link>
</div>
<div className="col-xs-6 importwallet-wrap fadeInDown">
<Link to="/importwallet">
<div className="col-xs-12">
<img src="images/import-main.png" alt="Safex Icon Circle"/>
<button className="btn btn-default button-neon-green">Import</button>
<p>Import your wallet or recover from backup file</p>
</div>
</Link>
</div>
</div>
</div>
<div className="col-xs-12 text-center Intro-footer">
<img src="images/footer-logo.png" alt="Safex Icon Footer"/>
<p className="text-center">2014-2019 All Rights Reserved Safe Exchange Developers ©</p>
</div>
</div>
);
} else {
show_options = (
<div className="container">
<div className="col-xs-12 Login-logo">
<h2>Safex</h2>
<h3>Wallet</h3>
<p>{packageJson.version}</p>
<button className="back-button wallet-reset-button" onClick={this.state.walletResetModal ? this.walletResetClose : this.walletResetNoWallet}>Wallet
Reset
</button>
</div>
<div className="col-xs-8 col-xs-offset-2 App-intro">
<div className="row text-center">
<div className="col-xs-6 login-wrap fadeInDown">
<Link to="/createwallet">
<div className="col-xs-12">
<img src="images/safex-icon-circle.png" alt="Safex Icon Circle"/>
<button className="btn btn-default button-neon-blue">New Wallet</button>
<p>Create a new Wallet</p>
</div>
</Link>
</div>
<div className="col-xs-6 importwallet-wrap fadeInDown">
<Link to="/importwallet">
<div className="col-xs-12">
<img src="images/import-main.png" alt="Safex Icon Circle"/>
<button className="btn btn-default button-neon-green">Import</button>
<p>Load a safexwallet .dat file</p>
</div>
</Link>
</div>
</div>
</div>
<div className="col-xs-12 text-center Intro-footer">
<img src="images/footer-logo.png" alt="Safex Icon Footer"/>
<p className="text-center">2014-2019 All Rights Reserved Safe Exchange Developers ©</p>
</div>
</div>
);
}
}
return (
<div>
{show_options}
<div className={this.state.walletResetModal
? 'overflow sendModal walletResetModal active'
: 'overflow sendModal walletResetModal'}>
<div className="container">
{
this.state.walletResetWarning1
?
<div>
<h3>Wallet Reset
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<button className="keys-btn button-shine" onClick={this.walletResetWarning1Proceed}>Proceed
</button>
</div>
:
<div></div>
}
{
this.state.walletResetWarning2
?
<div>
<h3>Wallet Reset
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<button className="keys-btn button-shine" onClick={this.walletResetWarning2Proceed}>Proceed
</button>
</div>
:
<div></div>
}
{
this.state.walletResetWarning3
?
<div>
<h3>Wallet Reset
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<button className="keys-btn button-shine" onClick={this.walletResetWarning3Proceed}>Proceed
</button>
</div>
:
<div></div>
}
{
this.state.walletResetWarning4
?
<div>
<h3>Wallet Reset
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<button className="keys-btn button-shine" onClick={this.walletResetWarning4Proceed}>Proceed
</button>
</div>
:
<div></div>
}
{
this.state.walletResetWarning5
?
<div>
<h3>Wallet Reset
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<button className="keys-btn button-shine" onClick={this.walletResetWarning5Proceed}>Proceed
</button>
</div>
:
<div></div>
}
{
this.state.walletResetModal1
?
<div>
<h3>Back Up Unencrypted Keys
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<button className="keys-btn button-shine" onClick={this.walletResetStep1Skip}>Skip</button>
<button className="keys-btn button-shine" onClick={this.walletResetStep1Proceed}>Proceed
</button>
</div>
:
<div></div>
}
{
this.state.walletResetModal2unencrypted
?
<div>
<h3>Wallet Reset Step 2
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<form className="form-group text-center" onSubmit={this.walletResetDlUnencrypted}>
<input className={this.state.wrong_password ? 'form-control password-btn shake' : 'form-control password-btn'} type="password" name="password" placeholder="Enter Password" autoFocus />
<button className="keys-btn button-shine" type="submit">Proceed</button>
</form>
</div>
:
<div></div>
}
{
this.state.walletResetModalDlUnencrypted
?
<div>
<h3>Download Encrypted Wallet
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<form onSubmit={this.walletResetDlEncrypted}>
<label>
<input name="checkbox" type="checkbox"/>I understand that this is my last chance to
backup my wallet file after this it will be deleted
</label>
<button type="submit" className="submit-btn button-shine">Proceed</button>
</form>
</div>
:
<div></div>
}
{
this.state.walletResetModalDlEncrypted
?
<div>
<h3>Downloading Encrypted Wallet
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<form onSubmit={this.walletResetStep2}>
<label><input name="checkbox" type="checkbox"/> I understand that this is my last chance to
backup my wallet file after this it will be deleted</label>
<button type="submit" className="submit-btn button-shine">Proceed</button>
</form>
</div>
:
<div></div>
}
{
this.state.walletResetModalDone
?
<div>
<h3>Wallet Reset Done
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
<button className="keys-btn button-shine" onClick={this.walletResetClose}>Done</button>
</div>
:
<div></div>
}
{
this.state.walletResetNoWallet
?
<div>
<h3>Wallet Reset
<span onClick={this.walletResetClose} className="close">X</span>
</h3>
<p>{this.state.walletResetModalText}</p>
</div>
:
<div></div>
}
</div>
</div>
</div>
);
}
}
SelectWallet.contextTypes = {
router: React.PropTypes.object.isRequired
};
//if wallet is found main image is new wallet found
|
app/javascript/mastodon/containers/timeline_container.js | verniy6462/mastodon | import React from 'react';
import { Provider } from 'react-redux';
import PropTypes from 'prop-types';
import configureStore from '../store/configureStore';
import { hydrateStore } from '../actions/store';
import { IntlProvider, addLocaleData } from 'react-intl';
import { getLocale } from '../locales';
import PublicTimeline from '../features/standalone/public_timeline';
const { localeData, messages } = getLocale();
addLocaleData(localeData);
const store = configureStore();
const initialStateContainer = document.getElementById('initial-state');
if (initialStateContainer !== null) {
const initialState = JSON.parse(initialStateContainer.textContent);
store.dispatch(hydrateStore(initialState));
}
export default class TimelineContainer extends React.PureComponent {
static propTypes = {
locale: PropTypes.string.isRequired,
};
render () {
const { locale } = this.props;
return (
<IntlProvider locale={locale} messages={messages}>
<Provider store={store}>
<PublicTimeline />
</Provider>
</IntlProvider>
);
}
}
|
assets/jqwidgets/demos/react/app/ribbon/verticalribbon/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxRibbon from '../../../jqwidgets-react/react_jqxribbon.js';
import JqxCheckBox from '../../../jqwidgets-react/react_jqxcheckbox.js';
class App extends React.Component {
componentDidMount() {
this.refs.megaMenuMode.on('change', (event) => {
let checked = event.args.checked;
let mode = checked ? 'popup' : 'default';
let width = checked ? 115 : 425;
this.refs.myRibbon.setOptions({ width: width, mode: mode });
if (mode == 'popup') {
this.refs.myRibbon.setPopupLayout(0, 'default', 310, '100%');
this.refs.myRibbon.setPopupLayout(1, 'default', 310, '100%');
this.refs.myRibbon.setPopupLayout(2, 'default', 310, '100%');
this.refs.myRibbon.setPopupLayout(3, 'default', 310, '100%');
}
});
}
render() {
let ribbonHTML = `
<ul id="header" style="width:115px;">
<li>TV and Players</li>
<li>Cell phones</li>
<li>Cameras</li>
<li>Computers</li>
</ul>
<div>
<div>
<div class="container">
<table>
<tr>
<td class="list">
<b><a href="#">TV</a></b>
</td>
</tr>
<tr>
</tr>
<tr>
<td class="list">
<a href="#">LED</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">LCD</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">Plasma</a>
</td>
</tr>
<tr>
<td>
<hr />
</td>
</tr>
<tr>
<td class="list">
<b><a href="#">PLAYERS</a></b>
</td>
</tr>
<tr>
</tr>
<tr>
<td class="list">
<a href="#">DVD</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">Blu-Ray</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">CD</a>
</td>
</tr>
</table>
</div>
<div class="container">
<table>
<tr>
<td class="promo">
PROMO
</td>
</tr>
<tr>
<td class="image">
<img src="../../images/tv.png" />
</td>
</tr>
<tr>
<td class="name">
<a href="#">LG 22MN43D-PZ</a>
</td>
</tr>
<tr>
<td class="price">
Price: $1583
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="container">
<table>
<tr>
<td class="list">
<b><a href="#">PHONES</a></b>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Brand</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Display size</a>
</td>
</tr>
<tr>
<td>
<hr />
</td>
</tr>
<tr>
<td class="list">
<b><a href="#">SMARTPHONES</a></b>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Brand</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By OS</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Display size</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By CPU</a>
</td>
</tr>
</table>
</div>
<div class="container">
<table>
<tr>
<td class="promo">
PROMO
</td>
</tr>
<tr>
<td class="image">
<img src="../../images/Samsung-Galaxy-S4.png" />
</td>
</tr>
<tr>
<td class="name">
<a href="#">Samsung I9505 Galaxy S4</a>
</td>
</tr>
<tr>
<td class="price">
Price: $569
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="container">
<table>
<tr>
<td class="list">
<b><a href="#">DIGITAL<br />
CAMERAS</a></b>
</td>
</tr>
<tr>
<td class="list">
<a href="#">Hybrid</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">Compact</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">Digital SLR</a>
</td>
</tr>
<tr>
<td>
<hr />
</td>
</tr>
<tr>
<td class="list">
<b><a href="#">CAMCORDERS</a></b>
</td>
</tr>
<tr>
<td class="list">
<a href="#">FLASH</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">HDD</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">HD Flash</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">HD HDD</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">HD Extreme</a>
</td>
</tr>
</table>
</div>
<div class="container">
<table>
<tr>
<td class="promo">
PROMO
</td>
</tr>
<tr>
<td class="image">
<img src="../../images/camera.png" />
</td>
</tr>
<tr>
<td class="name">
<a href="#">Nikon COOLPIX L330</a>
</td>
</tr>
<tr>
<td class="price">
Price: $358
</td>
</tr>
</table>
</div>
</div>
<div>
<div class="container">
<table>
<tr>
<td class="list">
<b><a href="#">LAPTOPS</a></b>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Processor Type</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By RAM Capacity</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By HDD Capacity</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Display Size</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Brand</a>
</td>
</tr>
<tr>
<td>
<hr />
</td>
</tr>
<tr>
<td class="list">
<b><a href="#">DESKTOPS</a></b>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Processor Type</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By RAM Capacity</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By HDD Capacity</a>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Brand</a>
</td>
</tr>
<tr>
<td>
<hr />
</td>
</tr>
<tr>
<td class="list">
<b><a href="#">ALL-IN-ONE</a></b>
</td>
</tr>
<tr>
<td class="list">
<a href="#">By Brand</a>
</td>
</tr>
</table>
</div>
<div class="container">
<table>
<tr>
<td class="promo">
PROMO
</td>
</tr>
<tr>
<td class="image">
<img src="../../images/l-25.jpg" style="width: 140px; height: 105px;" />
</td>
</tr>
<tr>
<td class="name">
<a href="#">Toshiba Qosmio X70-A-114</a>
</td>
</tr>
<tr>
<td class="price">
Price: $2199
</td>
</tr>
</table>
</div>
</div>
</div>`;
return (
<div>
<JqxRibbon ref='myRibbon'
template={ribbonHTML}
width={425}
height={335}
position={'left'}
selectionMode={'hover'}
animationType={'fade'}
/>
<JqxCheckBox style={{ marginTop: 50 }}
ref='megaMenuMode'
value='Menu Mode'
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
docs/app/Examples/modules/Dropdown/Content/index.js | clemensw/stardust | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ContributionPrompt from 'docs/app/Components/ComponentDoc/ContributionPrompt'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const DropdownContentExamples = () => (
<ExampleSection title='Content'>
<ComponentExample
title='Header'
description='A dropdown menu can contain a header.'
examplePath='modules/Dropdown/Content/DropdownExampleHeader'
/>
<ComponentExample
title='Divider'
description='A dropdown menu can contain dividers to separate related content.'
examplePath='modules/Dropdown/Content/DropdownExampleDivider'
/>
<ComponentExample
title='Icon'
description='A dropdown menu can contain an icon.'
examplePath='modules/Dropdown/Content/DropdownExampleIcon'
/>
<ComponentExample
title='Description'
description='A dropdown menu can contain a description.'
examplePath='modules/Dropdown/Content/DropdownExampleDescription'
/>
<ComponentExample
title='Label'
description='A dropdown menu can contain a label.'
examplePath='modules/Dropdown/Content/DropdownExampleLabel'
/>
<ComponentExample
title='Message'
description='A dropdown menu can contain a message.'
examplePath='modules/Dropdown/Content/DropdownExampleMessage'
/>
<ComponentExample
title='Floated Content'
description='A dropdown menu can contain floated content.'
examplePath='modules/Dropdown/Content/DropdownExampleFloatedContent'
/>
<ComponentExample
title='Input'
description='A dropdown menu can contain an input.'
examplePath='modules/Dropdown/Content/DropdownExampleInput'
>
<ContributionPrompt>
The example below shows the desired markup but is not functional.
Needs to be defined via shorthand, which is not yet possible.
</ContributionPrompt>
</ComponentExample>
<ComponentExample
title='Image'
description='A dropdown menu can contain an image.'
examplePath='modules/Dropdown/Content/DropdownExampleImage'
/>
</ExampleSection>
)
export default DropdownContentExamples
|
node_modules/react-bootstrap/es/Table.js | nikhil-ahuja/Express-React | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
striped: React.PropTypes.bool,
bordered: React.PropTypes.bool,
condensed: React.PropTypes.bool,
hover: React.PropTypes.bool,
responsive: React.PropTypes.bool
};
var defaultProps = {
bordered: false,
condensed: false,
hover: false,
responsive: false,
striped: false
};
var Table = function (_React$Component) {
_inherits(Table, _React$Component);
function Table() {
_classCallCheck(this, Table);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Table.prototype.render = function render() {
var _extends2;
var _props = this.props,
striped = _props.striped,
bordered = _props.bordered,
condensed = _props.condensed,
hover = _props.hover,
responsive = _props.responsive,
className = _props.className,
props = _objectWithoutProperties(_props, ['striped', 'bordered', 'condensed', 'hover', 'responsive', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'striped')] = striped, _extends2[prefix(bsProps, 'bordered')] = bordered, _extends2[prefix(bsProps, 'condensed')] = condensed, _extends2[prefix(bsProps, 'hover')] = hover, _extends2));
var table = React.createElement('table', _extends({}, elementProps, {
className: classNames(className, classes)
}));
if (responsive) {
return React.createElement(
'div',
{ className: prefix(bsProps, 'responsive') },
table
);
}
return table;
};
return Table;
}(React.Component);
Table.propTypes = propTypes;
Table.defaultProps = defaultProps;
export default bsClass('table', Table); |
src/Pagination.js | jesenko/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import bootstrapUtils, { bsClass } from './utils/bootstrapUtils';
import PaginationButton from './PaginationButton';
import elementType from 'react-prop-types/lib/elementType';
import SafeAnchor from './SafeAnchor';
const Pagination = React.createClass({
propTypes: {
activePage: React.PropTypes.number,
items: React.PropTypes.number,
maxButtons: React.PropTypes.number,
/**
* When `true`, will display the default node value ('...').
* Otherwise, will display provided node (when specified).
*/
ellipsis: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.node
]),
/**
* When `true`, will display the default node value ('«').
* Otherwise, will display provided node (when specified).
*/
first: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.node
]),
/**
* When `true`, will display the default node value ('»').
* Otherwise, will display provided node (when specified).
*/
last: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.node
]),
/**
* When `true`, will display the default node value ('‹').
* Otherwise, will display provided node (when specified).
*/
prev: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.node
]),
/**
* When `true`, will display the default node value ('›').
* Otherwise, will display provided node (when specified).
*/
next: React.PropTypes.oneOfType([
React.PropTypes.bool,
React.PropTypes.node
]),
onSelect: React.PropTypes.func,
/**
* You can use a custom element for the buttons
*/
buttonComponentClass: elementType
},
getDefaultProps() {
return {
activePage: 1,
items: 1,
maxButtons: 0,
first: false,
last: false,
prev: false,
next: false,
ellipsis: true,
buttonComponentClass: SafeAnchor,
bsClass: 'pagination'
};
},
renderPageButtons() {
let pageButtons = [];
let startPage, endPage, hasHiddenPagesAfter;
let {
maxButtons,
activePage,
items,
onSelect,
ellipsis,
buttonComponentClass
} = this.props;
if (maxButtons) {
let hiddenPagesBefore = activePage - parseInt(maxButtons / 2, 10);
startPage = hiddenPagesBefore > 1 ? hiddenPagesBefore : 1;
hasHiddenPagesAfter = startPage + maxButtons <= items;
if (!hasHiddenPagesAfter) {
endPage = items;
startPage = items - maxButtons + 1;
if (startPage < 1) {
startPage = 1;
}
} else {
endPage = startPage + maxButtons - 1;
}
} else {
startPage = 1;
endPage = items;
}
for (let pagenumber = startPage; pagenumber <= endPage; pagenumber++) {
pageButtons.push(
<PaginationButton
key={pagenumber}
eventKey={pagenumber}
active={pagenumber === activePage}
onSelect={onSelect}
buttonComponentClass={buttonComponentClass}>
{pagenumber}
</PaginationButton>
);
}
if (maxButtons && hasHiddenPagesAfter && ellipsis) {
pageButtons.push(
<PaginationButton
key="ellipsis"
disabled
buttonComponentClass={buttonComponentClass}>
<span aria-label="More">
{this.props.ellipsis === true ? '...' : this.props.ellipsis}
</span>
</PaginationButton>
);
}
return pageButtons;
},
renderPrev() {
if (!this.props.prev) {
return null;
}
return (
<PaginationButton
key="prev"
eventKey={this.props.activePage - 1}
disabled={this.props.activePage === 1}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="Previous">
{this.props.prev === true ? '\u2039' : this.props.prev}
</span>
</PaginationButton>
);
},
renderNext() {
if (!this.props.next) {
return null;
}
return (
<PaginationButton
key="next"
eventKey={this.props.activePage + 1}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="Next">
{this.props.next === true ? '\u203a' : this.props.next}
</span>
</PaginationButton>
);
},
renderFirst() {
if (!this.props.first) {
return null;
}
return (
<PaginationButton
key="first"
eventKey={1}
disabled={this.props.activePage === 1 }
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="First">
{this.props.first === true ? '\u00ab' : this.props.first}
</span>
</PaginationButton>
);
},
renderLast() {
if (!this.props.last) {
return null;
}
return (
<PaginationButton
key="last"
eventKey={this.props.items}
disabled={this.props.activePage >= this.props.items}
onSelect={this.props.onSelect}
buttonComponentClass={this.props.buttonComponentClass}>
<span aria-label="Last">
{this.props.last === true ? '\u00bb' : this.props.last}
</span>
</PaginationButton>
);
},
render() {
return (
<ul
{...this.props}
className={classNames(this.props.className, bootstrapUtils.getClassSet(this.props))}>
{this.renderFirst()}
{this.renderPrev()}
{this.renderPageButtons()}
{this.renderNext()}
{this.renderLast()}
</ul>
);
}
});
export default bsClass('pagination', Pagination);
|
src/src/Components/CustomSelect.js | ioBroker/ioBroker.web | import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import { FormControl, FormHelperText, Input, MenuItem, Select, withStyles } from '@material-ui/core';
import I18n from '@iobroker/adapter-react/i18n';
import Icon from '@iobroker/adapter-react/Components/Icon';
import Utils from '@iobroker/adapter-react/Components/Utils';
const styles = theme => ({
input: {
minWidth: 300
},
inputNumber: {
minWidth: 150
},
icon: {
width: 24,
height: 24,
marginRight: 8
}
});
const CustomSelect = ({ table, value, title, attr, options, style, classes, native, onChange, className, noTranslate, themeType }) => {
return <FormControl
className={clsx(classes.input, classes.controlElement, className)}
style={Object.assign({ paddingTop: 5 }, style)}
>
<Select
value={table ? value : native[attr] || '_'}
onChange={e => {
if (table) {
onChange(e.target.value);
} else {
onChange(attr, e.target.value === '_' ? '' : e.target.value)
}
}}
renderValue={_item => {
const item = options.find(it => it.value === _item);
return item ? <>
<Icon src={item.icon} className={classes.icon}/>
{noTranslate ? item.title : I18n.t(item.title)}
</> : _item
}}
input={<Input name={attr} id={attr + '-helper'} />}
>
{options.map(item =>
<MenuItem key={'key-' + item.value} value={item.value || '_'} style={item.color ? {color: item.color, backgroundColor: Utils.getInvertedColor ? Utils.getInvertedColor(item.color, themeType) : undefined} : {}}>
<Icon src={item.icon} className={classes.icon}/>
{noTranslate ? item.title : I18n.t(item.title)}
</MenuItem>)}
</Select>
<FormHelperText>{title ? I18n.t(title) : ''}</FormHelperText>
</FormControl>;
}
CustomSelect.defaultProps = {
value: '',
className: null,
table: false
};
CustomSelect.propTypes = {
title: PropTypes.string,
attr: PropTypes.string,
options: PropTypes.array.isRequired,
style: PropTypes.object,
native: PropTypes.object.isRequired,
onChange: PropTypes.func,
noTranslate: PropTypes.bool,
themeType: PropTypes.string,
};
export default withStyles(styles)(CustomSelect);
|
src/index.js | nimibahar/newReduxBlog | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';
import reducers from './reducers';
import PostsIndex from "./components/posts_index";
import PostsNew from "./components/posts_new";
import PostsShow from "./components/posts_show";
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Switch>
<Route path="/posts/new" component={PostsNew} />
<Route path="/posts/:id" component={PostsShow} />
<Route path='/' component={PostsIndex} />
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container'));
|
pages/index/index.js | CarlRosell/glamorous-website | import React from 'react'
import glamorous from 'glamorous'
import {LiveProvider, LiveEditor, LiveError} from 'react-live'
import {LiveContextTypes} from 'react-live/lib/components/Live/LiveProvider'
import stripIndent from '../../components/utils/strip-indent'
import {withContent} from '../../components/locale'
import Layout from '../../components/layout'
import {Button} from '../../components/styled-links'
import Hero from '../../components/hero'
import homePageExample from '../../examples/home-page-example'
const CodePreviewWrapper = glamorous.div((props, {colors}) => ({
position: 'relative',
padding: '1em',
paddingTop: 0,
background: 'transparent',
'::after': {
content: '""',
top: '15em',
left: 0,
bottom: 0,
right: 0,
position: 'absolute',
background: colors.primaryMed,
zIndex: -1,
},
}))
const CodeBlock = glamorous.div((props, {colors, fonts}) => ({
background: colors.blue,
borderRadius: 5,
fontFamily: fonts.monospace,
color: colors.lightGray,
padding: '15px 0',
maxWidth: 650,
width: '100%',
textAlign: 'center',
margin: '0 auto',
marginTop: 40,
}))
const GettingStarted = glamorous(Button)(
{
display: 'block',
margin: '3.5rem auto',
textAlign: 'center',
textTransform: 'uppercase',
fontWeight: '600',
fontSize: '1.3rem',
width: '90%',
maxWidth: 450,
},
(props, {colors}) => ({
color: colors.white,
}),
)
const StyledLiveProvider = glamorous(LiveProvider)({
margin: '0 auto',
display: 'flex',
flexDirection: 'column',
flexWrap: 'wrap',
justifyContent: 'space-around',
maxWidth: '50rem',
})
const StyledLiveEditor = glamorous(LiveEditor)({})
const StyledLiveError = glamorous(LiveError)((props, {colors, fonts}) => ({
color: colors.code,
fontFamily: fonts.monospace,
backgroundColor: colors.white,
flexBasis: '100%',
width: '100%',
maxWidth: '100%',
padding: '1rem',
}))
const HomepageLivePreview = (
{className, tryIt, ...rest},
{live: {element: LiveButton}},
) => {
return (
<glamorous.Div textAlign="center" marginBottom="30px">
<LiveButton href="https://github.com/paypal/glamorous" primary>
GitHub
</LiveButton>
<LiveButton href="http://kcd.im/glamorous-help">
{tryIt}
</LiveButton>
</glamorous.Div>
)
}
HomepageLivePreview.contextTypes = LiveContextTypes
const StyledLivePreview = glamorous(HomepageLivePreview)({
padding: '1rem',
})
function CodePreview({code, tryIt, scope = {glamorous}}) {
return (
<StyledLiveProvider code={stripIndent(code).trim()} scope={scope}>
<StyledLivePreview tryIt={tryIt} />
<StyledLiveError />
<StyledLiveEditor />
</StyledLiveProvider>
)
}
function Home({url, content, locale}) {
return (
<Layout pathname={url ? url.pathname : ''} locale={locale}>
<Hero>
{content.tagline}
</Hero>
<CodePreviewWrapper>
<CodePreview code={homePageExample} tryIt={content.tryIt} />
<CodeBlock>
npm install --save glamorous react glamor prop-types
</CodeBlock>
</CodePreviewWrapper>
<GettingStarted prefetch={process.env.USE_PREFETCH} href="/basics">
{content.callToAction}
</GettingStarted>
</Layout>
)
}
export default withContent({page: 'index'}, Home)
|
src/pages/Home.js | jo12bar/blag | import React from 'react';
import deline from 'deline';
import styles from '../css/Home';
const ArticleLink = ({ href, children }) => (
<a
className={styles.articleLinks}
target='_blank'
href={href}
rel='noopener noreferrer'
>
{children}
</a>
);
const Home = () => (
<div className={styles.home}>
<h1>Home</h1>
<h2>
NOTE: The top set of links in the sidebar to the left are real links, made
like this:
</h2>
<span className={styles.linkExampleLabel}>HREF STRING:</span>
<pre>
<code>{'<Link to=\'/list/db-graphql\'>DB & GRAPHQL</Link>'}</code>
</pre>
<span className={styles.linkExampleLabel}>PATH SEGMENTS:</span>
<pre>
<code>
{'<Link to={[\'list\', \'react-redux\']}>REACT & REDUX</Link>'}
</code>
</pre>
<span className={styles.linkExampleLabel}>ACTION:</span>
<pre>
<code>
{'<Link to={{ type: \'LIST\', payload: { slug: \'fp\' } }}>FP</Link>'}
</code>
</pre>
<h2>EVENT HANDLERS CAN DISPATCH ACTIONS:</h2>
<pre>
<code>
{`const onClick = () => dispatch({
type: 'LIST',
payload: { category: 'react-redux' },
});`}
</code>
</pre>
<p>
<span className={styles.directionsLabel}>DIRECTIONS: </span>
<span className={styles.directions}>
{deline`
Inspect the sidebar links to see that the top set are real <a> tags,
and the bottom set are actually <button>'s, but yet the address bar
changes for both. The decision of which one to use is up to you. When
using the <Link /> component, if you provide an action as the \`href\`
prop, then you never need to worry if you cahnge the static path
segments (e.g: \`/list\`) in the routes map passed to
\`connectRoutes\`. ALSO: Don't forget to use the browser's Back/ Next
buttons to see that working too!
`}
</span>
</p>
<h2>Links about Redux-First Router (RFR):</h2>
{'> '}
<ArticleLink
href='https://medium.com/faceyspacey/server-render-like-a-pro-w-redux-first-router-in-10-steps-b27dd93859de'
>
Server-Render Like A Pro in 10 Steps w/ Redux-First Router 🚀
</ArticleLink>
<br />
<br />
{'> '}
<ArticleLink
href='https://medium.com/faceyspacey/redux-first-router-lookin-sexy-on-code-sandbox-d9d9bea15053'
>
Things To Pay Attention To In This Demo
</ArticleLink>
<br />
<br />
{'> '}
<ArticleLink
href='https://medium.com/faceyspacey/pre-release-redux-first-router-a-step-beyond-redux-little-router-cd2716576aea'
>
Pre Release: Redux-First Router — A Step Beyond Redux-Little-Router
</ArticleLink>
<br />
<br />
{'> '}
<ArticleLink
href='https://medium.com/faceyspacey/redux-first-router-data-fetching-solving-the-80-use-case-for-async-middleware-14529606c262'
>
Redux-First Router data-fetching: solving the 80% use case for async
middleware
</ArticleLink>
</div>
);
export default Home;
|
src/svg-icons/action/event.js | hai-cea/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionEvent = (props) => (
<SvgIcon {...props}>
<path d="M17 12h-5v5h5v-5zM16 1v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2h-1V1h-2zm3 18H5V8h14v11z"/>
</SvgIcon>
);
ActionEvent = pure(ActionEvent);
ActionEvent.displayName = 'ActionEvent';
ActionEvent.muiName = 'SvgIcon';
export default ActionEvent;
|
src/components/Forms/Signup.js | txwkx/book-room | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { withRouter } from 'react-router';
import axios from 'axios';
import FormInput from './FormInput';
import Success from './Success';
class Signup extends Component {
state = {
success: false
}
handleSignup = (e) => {
e.preventDefault();
const { username, password } = this.state;
this.setState({error: ''});
const userData = {
username: username,
password: password
};
axios.post('/api/signup', userData)
.then(res => {
const status = res.data.success;
if(!status) {
this.setState({error : res.data.message});
} else {
this.setState({success: true});
setTimeout(() => {
this.props.history.push('/mode');
}, 1500);
}
})
.catch(err => {
console.log(err);
});
}
attrChangeUn = (username) => {
this.setState({username});
}
attrChangePwd = (password) => {
this.setState({password});
}
componentDidMount = () => {
this.FormInput.focus();
}
render() {
const { error, success, username, password } = this.state;
return(
<div class='signup'>
<div class='popup'>
<div class='header'>Create Account</div>
<div class='content'>
{ success ?
<Success /> :
<form action="/api/signup" method="post" id='signup-form'>
<FormInput
type='text'
name='username'
ref={comp => {this.FormInput = comp;}}
onChange={ this.attrChangeUn }
/>
<FormInput
type='password'
name='password'
onChange={ this.attrChangePwd }
/>
<p class='error-msg'>{error}</p>
<input
type='submit'
value='Sign up'
class='btn btn-form'
disabled={!(username && password)}
onClick={this.handleSignup}
/>
<p>Have an account? <Link to="/login">Login</Link></p>
</form>
}
</div>
</div>
</div>
);
}
}
export default withRouter(Signup);
|
src/containers/jupyterlab-integration/instructions.js | OpenChemistry/mongochemclient | import React, { Component } from 'react';
import { connect } from 'react-redux';
import GirderClient from '@openchemistry/girder-client';
import { auth } from '@openchemistry/girder-redux';
import { selectors, jupyterlab } from '@openchemistry/redux';
import InstructionsComponent from '../../components/jupyterlab-integration/instructions';
class InstructionsContainer extends Component {
handleClose = () => {
const { dispatch } = this.props;
dispatch(jupyterlab.showJupyterlabIntegration(false));
}
render() {
const { show, apiKey, config } = this.props;
const appUrl = window.location.origin;
const apiUrl = GirderClient().getBaseURL();
return (
<InstructionsComponent apiKey={apiKey} apiUrl={apiUrl} appUrl={appUrl} show={show} handleClose={this.handleClose} config={config}/>
)
}
}
function mapStateToProps(state, _ownProps) {
const apiKey = auth.selectors.getApiKey(state);
const show = selectors.jupyterlab.getShowJupyterlabIntegration(state);
const config = selectors.configuration.getConfiguration(state);
return {show, apiKey, config};
}
export default connect(mapStateToProps)(InstructionsContainer);
|
src/components/controls/Buttons/MaterialButton.js | TTCErembodegem/TTC-React-Front | import React from 'react';
import Button from '@material-ui/core/Button';
import PropTypes from '../../PropTypes.js';
// This transforms the material-ui Button from v0.x to the new API
export class MaterialButton extends React.Component {
static propTypes = {
label: PropTypes.string.isRequired,
primary: PropTypes.bool,
secondary: PropTypes.bool,
color: PropTypes.string,
}
getColor(primary, secondary, color) {
if (primary) {
return 'primary';
}
if (secondary) {
return 'secondary';
}
return color;
}
render() {
const {label, primary, secondary, color, ...props} = this.props;
return (
<Button {...props} color={this.getColor(primary, secondary, color)}>
{label}
</Button>
);
}
}
|
src/client.js | anshul2209/Chatter | import React from 'react';
import ReactDOM from 'react-dom';
import ChatApp from './components/ChatApp';
ReactDOM.render(<ChatApp />, document.getElementById('content'));
|
src/javascript/wizard/orient.js | apertus-open-source-cinema/elmyra | import React from 'react';
import {
AmbientLight,
AxesHelper,
Color,
DoubleSide,
Geometry,
Mesh,
PerspectiveCamera,
PointLight,
Quaternion,
Scene,
Vector3,
WebGLRenderer
} from 'three';
import { OBJLoader } from 'three/examples/jsm/loaders/OBJLoader.js';
import MediaType from './media_type.js';
const RED_HEX = 0xff414e;
const GREEN_HEX = 0x9bff46;
const BLUE_HEX = 0x59e0ff;
export default class Orient extends React.Component {
static navigationTitle = 'Orient';
camera = null;
geometry = null;
light = null;
material = null;
mesh = null;
renderer = null;
scene = null;
widgetFlipHorizontally = null;
widgetFlipVertically = null;
widgetTilt = null;
widgetTurn = null;
constructor(props) {
super(props);
this.state = {
flipHorizontally: false,
flipVertically: false,
};
}
componentDidMount() {
this.scene = new Scene();
this.scene.add(new AxesHelper(1));
this.camera = new PerspectiveCamera(16, 720 / 480, 1, 20);
this.camera.position.set(7.2706032, -3.5676303, 2.6419632);
this.camera.up = new Vector3(0,0,1);
this.camera.lookAt(new Vector3(0, 0, 0));
this.scene.add(this.camera);
this.light = new AmbientLight(0x404040);
this.scene.add(this.light);
this.light = new PointLight(RED_HEX, 1, 10);
this.light.position.set(3, 0 , 0);
this.scene.add(this.light);
this.light = new PointLight(GREEN_HEX, 1, 10);
this.light.position.set(0, 3 , 0);
this.scene.add(this.light);
this.light = new PointLight(BLUE_HEX, 1, 10);
this.light.position.set(0, 0 , 3);
this.scene.add(this.light);
this.renderer = new WebGLRenderer({ antialias: true });
this.renderer.setSize(720, 480);
this.renderer.setClearColor(0xffffff);
document.getElementById('viewer-container').appendChild(this.renderer.domElement);
// Render white background until obj is loaded
this.renderer.render(this.scene, this.camera);
const loader = new OBJLoader();
loader.load(`/__internal/preview/${this.props.importId}`, root => {
for(const child of root.children) {
if(child.name == 'widget-flip-horizontally' ||
child.name == 'widget-flip-vertically' ||
child.name == 'widget-tilt' ||
child.name == 'widget-turn') {
child.material.color = new Color(0x000000);
child.material.emissiveIntensity = 1;
child.material.side = DoubleSide;
child.visible = false;
if(child.name == 'widget-flip-horizontally') {
child.material.emissive = new Color(GREEN_HEX);
this.widgetFlipHorizontally = child;
} else if(child.name == 'widget-flip-vertically') {
child.material.emissive = new Color(BLUE_HEX);
this.widgetFlipVertically = child;
} else if(child.name == 'widget-tilt') {
child.material.emissive = new Color(RED_HEX);
this.widgetTilt = child;
} else if(child.name == 'widget-turn') {
child.material.emissive = new Color(BLUE_HEX);
this.widgetTurn = child;
}
} else {
const geometry = new Geometry().fromBufferGeometry(child.geometry);
const material = child.material;
material.color = new Color(0xffffff);
material.side = DoubleSide;
this.mesh = new Mesh(geometry, child.material);
}
}
this.scene.add(this.widgetFlipHorizontally);
this.scene.add(this.widgetFlipVertically);
this.scene.add(this.widgetTilt);
this.scene.add(this.widgetTurn);
this.scene.add(this.mesh);
this.renderer.render(this.scene, this.camera);
});
}
flipNormals = () => {
this.mesh.geometry.dynamic = true
this.mesh.geometry.__dirtyVertices = true;
this.mesh.geometry.__dirtyNormals = true;
for(let f = 0; f < this.mesh.geometry.faces.length; f++) {
this.mesh.geometry.faces[f].normal.x *= -1;
this.mesh.geometry.faces[f].normal.y *= -1;
this.mesh.geometry.faces[f].normal.z *= -1;
}
this.mesh.geometry.computeVertexNormals();
this.mesh.geometry.computeFaceNormals();
}
flipHorizontally = () => {
this.setState({ flipHorizontally: !this.state.flipHorizontally });
this.mesh.geometry.scale(1, -1, 1);
this.flipNormals();
this.renderer.render(this.scene, this.camera);
}
flipVertically = () => {
this.setState({ flipVertically: !this.state.flipVertically });
this.mesh.geometry.scale(1, 1, -1);
this.flipNormals();
this.renderer.render(this.scene, this.camera);
}
tilt = () => {
const q = new Quaternion();
q.setFromAxisAngle(new Vector3(1, 0, 0), (90 * Math.PI) / 180);
this.mesh.quaternion.multiplyQuaternions(q, this.mesh.quaternion);
this.renderer.render(this.scene, this.camera);
}
turn = () => {
const q = new Quaternion();
q.setFromAxisAngle(new Vector3(0, 0, 1), (90 * Math.PI) / 180);
this.mesh.quaternion.multiplyQuaternions(q, this.mesh.quaternion);
this.renderer.render(this.scene, this.camera);
}
highlight = (widget, state) => {
if(widget == 'flipHorizontally') {
widget = this.widgetFlipHorizontally.visible = state;
} else if(widget == 'flipVertically') {
widget = this.widgetFlipVertically.visible = state;
} else if(widget == 'turn') {
widget = this.widgetTurn.visible = state;
} else if(widget == 'tilt') {
widget = this.widgetTilt.visible = state;
}
this.renderer.render(this.scene, this.camera);
}
saveTransformAndNavigate = () => {
this.props.navigate(
MediaType,
{
orientFlipHorizontally: this.state.flipHorizontally,
orientFlipVertically: this.state.flipVertically,
orientRotateX: this.mesh.rotation._x,
orientRotateY: this.mesh.rotation._y,
orientRotateZ: this.mesh.rotation._z
}
);
}
render() {
return(
<main>
<div className="tool">
<h1>Orient</h1>
<div className="description">
Use the flip, tilt and turn tools to orient your model such that ...<br />
- the front faces towards the camera along the red axis<br />
- the top faces upwards along the blue axis<br />
- the right side faces away from the camera along the green axis<br />
<br /><br />
<div id="viewer-container" />
<br /><br />
<div className="btn-group" role="toolbar" aria-label="Alignment tools">
<button className="btn btn-secondary"
onClick={this.flipHorizontally}
onMouseEnter={this.highlight.bind(null, 'flipHorizontally', true)}
onMouseLeave={this.highlight.bind(null, 'flipHorizontally', false)}>
Flip Horizontally
</button>
<button className="btn btn-secondary"
onClick={this.flipVertically}
onMouseEnter={this.highlight.bind(null, 'flipVertically', true)}
onMouseLeave={this.highlight.bind(null, 'flipVertically', false)}>
Flip Vertically
</button>
<button className="btn btn-secondary"
onClick={this.turn}
onMouseEnter={this.highlight.bind(null, 'turn', true)}
onMouseLeave={this.highlight.bind(null, 'turn', false)}>
Turn 90°
</button>
<button className="btn btn-secondary"
onClick={this.tilt}
onMouseEnter={this.highlight.bind(null, 'tilt', true)}
onMouseLeave={this.highlight.bind(null, 'tilt', false)}>
Tilt 90°
</button>
</div>
</div>
<div>
<br/>
<button id="confirm-button"
className="btn btn-primary"
onClick={this.saveTransformAndNavigate}>
Continue
</button>
</div>
</div>
</main>
);
}
}
|
app/addons/replication/components/newreplication.js | michellephung/couchdb-fauxton | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import base64 from 'base-64';
import React from 'react';
import Helpers from '../../../helpers';
import {json} from '../../../core/ajax';
import FauxtonAPI from '../../../core/api';
import {ReplicationSource} from './source';
import {ReplicationTarget} from './target';
import {ReplicationOptions} from './options';
import {ReplicationSubmit} from './submit';
import {ReplicationAuth} from './auth-options';
import Constants from '../constants';
import {ConflictModal} from './modals';
import {isEmpty} from 'lodash';
export default class NewReplicationController extends React.Component {
constructor (props) {
super(props);
this.submit = this.submit.bind(this);
this.checkAuth = this.checkAuth.bind(this);
this.runReplicationChecks = this.runReplicationChecks.bind(this);
}
checkAuth () {
this.props.hideConflictModal();
const { replicationSource, replicationTarget,
sourceAuthType, targetAuthType, sourceAuth, targetAuth } = this.props;
const isLocalSource = replicationSource === Constants.REPLICATION_SOURCE.LOCAL;
const isLocalTarget = replicationTarget === Constants.REPLICATION_TARGET.EXISTING_LOCAL_DATABASE ||
replicationTarget === Constants.REPLICATION_TARGET.NEW_LOCAL_DATABASE;
// Ask user to select an auth method for local source/target when one is not selected
// and not on admin party
if (!FauxtonAPI.session.isAdminParty()) {
if (isLocalSource && sourceAuthType === Constants.REPLICATION_AUTH_METHOD.NO_AUTH) {
FauxtonAPI.addNotification({
msg: 'Missing credentials for local source database.',
type: 'error',
clear: true
});
return;
}
if (isLocalTarget && targetAuthType === Constants.REPLICATION_AUTH_METHOD.NO_AUTH) {
FauxtonAPI.addNotification({
msg: 'Missing credentials for local target database.',
type: 'error',
clear: true
});
return;
}
}
this.checkLocalAccountCredentials(sourceAuthType, sourceAuth, 'source', isLocalSource).then(() => {
this.checkLocalAccountCredentials(targetAuthType, targetAuth, 'target', isLocalTarget).then(() => {
this.submit();
}, () => {});
}, () => {});
}
checkLocalAccountCredentials(authType, auth, label, isLocal) {
// Skip check if it's a remote tb or not using BASIC auth
if (authType !== Constants.REPLICATION_AUTH_METHOD.BASIC || !isLocal) {
return FauxtonAPI.Promise.resolve(true);
}
if (!auth.username || !auth.password) {
const err = `Missing ${label} credentials.`;
FauxtonAPI.addNotification({
msg: err,
type: 'error',
clear: true
});
return FauxtonAPI.Promise.reject(new Error(err));
}
return this.checkCredentials(auth.username, auth.password).then((resp) => {
if (resp.error) {
throw (resp);
}
return true;
}).catch(err => {
FauxtonAPI.addNotification({
msg: `Your username or password for ${label} database is incorrect.`,
type: 'error',
clear: true
});
throw err;
});
}
checkCredentials(username, password) {
return json(Helpers.getServerUrl('/'), 'GET', {
credentials: 'omit',
headers: {
'Authorization':'Basic ' + base64.encode(username + ':' + password)
}
});
}
checkReplicationDocID () {
const {showConflictModal, replicationDocName, checkReplicationDocID} = this.props;
checkReplicationDocID(replicationDocName).then(existingDoc => {
if (existingDoc) {
showConflictModal();
return;
}
this.checkAuth();
});
}
runReplicationChecks () {
const {replicationDocName} = this.props;
if (!this.checkSourceTargetDatabases()) {
return;
}
if (replicationDocName) {
this.checkReplicationDocID();
return;
}
this.checkAuth();
}
checkSourceTargetDatabases () {
const {
remoteTarget,
remoteSource,
replicationTarget,
localTarget,
localSource,
databases
} = this.props;
if (replicationTarget === Constants.REPLICATION_TARGET.NEW_LOCAL_DATABASE && _.includes(databases, localTarget)) {
FauxtonAPI.addNotification({
msg: 'The <code>' + localTarget + '</code> database already exists locally. Please enter another database name.',
type: 'error',
escape: false,
clear: true
});
return false;
}
if (replicationTarget === Constants.REPLICATION_TARGET.NEW_LOCAL_DATABASE ||
replicationTarget === Constants.REPLICATION_TARGET.NEW_REMOTE_DATABASE) {
let error = '';
if (/\s/.test(localTarget)) {
error = 'The target database may not contain any spaces.';
} else if (/^_/.test(localTarget)) {
error = 'The target database may not start with an underscore.';
}
if (error) {
FauxtonAPI.addNotification({
msg: error,
type: 'error',
escape: false,
clear: true
});
return false;
}
}
//check if remote source/target URL is valid
if (!isEmpty(remoteSource)) {
let errorMessage = '';
try {
const url = new URL(remoteSource);
if (url.pathname.slice(1) === '') {
errorMessage = 'Invalid source database URL. Database name is missing.';
}
} catch (err) {
errorMessage = 'Invalid source database URL.';
}
if (errorMessage) {
FauxtonAPI.addNotification({
msg: errorMessage,
type: 'error',
escape: false,
clear: true
});
return false;
}
}
if (!isEmpty(remoteTarget)) {
let errorMessage = '';
try {
const url = new URL(remoteTarget);
if (url.pathname.slice(1) === '') {
errorMessage = 'Invalid target database URL. Database name is missing.';
}
} catch (err) {
errorMessage = 'Invalid target database URL.';
}
if (errorMessage) {
FauxtonAPI.addNotification({
msg: errorMessage,
type: 'error',
escape: false,
clear: true
});
return false;
}
}
//check that source and target are not the same. They can trigger a false positive if they are ""
if ((remoteTarget === remoteSource && !isEmpty(remoteTarget))
|| (localSource === localTarget && !isEmpty(localSource))) {
FauxtonAPI.addNotification({
msg: 'Cannot replicate a database to itself',
type: 'error',
escape: false,
clear: true
});
return false;
}
return true;
}
submit () {
const {
replicationTarget,
replicationSource,
replicationType,
replicationDocName,
remoteTarget,
remoteSource,
localTarget,
localSource,
sourceAuthType,
sourceAuth,
targetAuthType,
targetAuth
} = this.props;
let _rev;
if (replicationDocName) {
const doc = this.props.docs.find(doc => doc._id === replicationDocName);
if (doc) {
_rev = doc._rev;
}
}
this.props.replicate({
replicationTarget,
replicationSource,
replicationType,
replicationDocName,
localTarget,
localSource,
remoteTarget,
remoteSource,
_rev,
sourceAuthType,
sourceAuth,
targetAuthType,
targetAuth
});
}
confirmButtonEnabled () {
const {
remoteSource,
localSourceKnown,
replicationSource,
replicationTarget,
localTargetKnown,
localTarget,
submittedNoChange,
} = this.props;
if (submittedNoChange) {
return false;
}
if (!replicationSource || !replicationTarget) {
return false;
}
if (replicationSource === Constants.REPLICATION_SOURCE.LOCAL && !localSourceKnown) {
return false;
}
if (replicationTarget === Constants.REPLICATION_TARGET.EXISTING_LOCAL_DATABASE && !localTargetKnown) {
return false;
}
if (replicationTarget === Constants.REPLICATION_TARGET.NEW_LOCAL_DATABASE && !localTarget) {
return false;
}
if (replicationSource === Constants.REPLICATION_SOURCE.REMOTE && remoteSource === "") {
return false;
}
return true;
}
render () {
const {
replicationSource,
replicationTarget,
replicationType,
replicationDocName,
conflictModalVisible,
databases,
localSource,
remoteSource,
remoteTarget,
localTarget,
updateFormField,
clearReplicationForm,
sourceAuthType,
sourceAuth,
targetAuthType,
targetAuth
} = this.props;
return (
<div style={ {paddingBottom: 20} }>
<ReplicationSource
replicationSource={replicationSource}
localSource={localSource}
databases={databases}
remoteSource={remoteSource}
onSourceSelect={updateFormField('replicationSource')}
onRemoteSourceChange={updateFormField('remoteSource')}
onLocalSourceChange={updateFormField('localSource')}
/>
<ReplicationAuth
credentials={sourceAuth}
authType={sourceAuthType}
onChangeAuthType={updateFormField('sourceAuthType')}
onChangeAuth={updateFormField('sourceAuth')}
authId={'replication-source-auth'}
/>
<hr className="replication__seperator" size="1"/>
<ReplicationTarget
replicationTarget={replicationTarget}
onTargetChange={updateFormField('replicationTarget')}
databases={databases}
localTarget={localTarget}
remoteTarget={remoteTarget}
onRemoteTargetChange={updateFormField('remoteTarget')}
onLocalTargetChange={updateFormField('localTarget')}
/>
<ReplicationAuth
credentials={targetAuth}
authType={targetAuthType}
onChangeAuthType={updateFormField('targetAuthType')}
onChangeAuth={updateFormField('targetAuth')}
authId={'replication-target-auth'}
/>
<hr className="replication__seperator" size="1"/>
<ReplicationOptions
replicationType={replicationType}
replicationDocName={replicationDocName}
onDocChange={updateFormField('replicationDocName')}
onTypeChange={updateFormField('replicationType')}
/>
<ReplicationSubmit
disabled={!this.confirmButtonEnabled()}
onClick={this.runReplicationChecks}
onClear={clearReplicationForm}
/>
<ConflictModal
visible={conflictModalVisible}
onClick={this.checkAuth}
onClose={this.props.hideConflictModal}
docId={replicationDocName}
/>
</div>
);
}
}
|
src/index.js | SayonaraJS/Adios | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
actor-apps/app-web/src/app/components/common/Favicon.react.js | jamesbond12/actor-platform | import React from 'react';
import FaviconStore from 'stores/FaviconStore';
export default class Fav extends React.Component {
constructor(props) {
super(props);
FaviconStore.addChangeListener(this.update)
}
componentWillUnmount() {
FaviconStore.removeChangeListener(this.update);
}
update() {
setTimeout(() => {
// Clone created element and create href attribute
let updatedFavicon = document.getElementById('favicon').cloneNode(true);
// Set new href attribute
updatedFavicon.setAttribute('href', FaviconStore.getFaviconPath());
// Remove old and add new favicon
document.getElementById('favicon').remove();
document.head.appendChild(updatedFavicon);
}, 0);
}
render() {
return null;
}
}
|
src/components/dom3d.js | DarklyLabs/LaserWeb4 | // Copyright 2016 Todd Fleming
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
// Includes code from CSS3DRenderer.js:
// Author mrdoob / http://mrdoob.com/
// Based on http://www.emagix.net/academic/mscs-project/item/camera-sync-with-css3-and-webgl-threejs
import { mat4 } from 'gl-matrix';
import React from 'react'
function epsilon(value) {
return Math.abs(value) < Number.EPSILON ? 0 : value;
};
function getCameraCSSMatrix(matrix) {
return 'matrix3d(' +
epsilon(matrix[0]) + ',' +
epsilon(- matrix[1]) + ',' +
epsilon(matrix[2]) + ',' +
epsilon(matrix[3]) + ',' +
epsilon(matrix[4]) + ',' +
epsilon(-matrix[5]) + ',' +
epsilon(matrix[6]) + ',' +
epsilon(matrix[7]) + ',' +
epsilon(matrix[8]) + ',' +
epsilon(-matrix[9]) + ',' +
epsilon(matrix[10]) + ',' +
epsilon(matrix[11]) + ',' +
epsilon(matrix[12]) + ',' +
epsilon(- matrix[13]) + ',' +
epsilon(matrix[14]) + ',' +
epsilon(matrix[15]) +
')';
};
export class Dom3d extends React.Component {
componentWillUpdate(nextProps) {
if (!nextProps.camera)
return;
let camera = nextProps.camera;
if (camera.fovy) {
this.fov = 0.5 * nextProps.height / Math.tan(camera.fovy * 0.5);
this.transform = "translate3d(0,0," + this.fov + "px)" + getCameraCSSMatrix(camera.view) +
" translate3d(" + nextProps.width / 2 + "px," + nextProps.height / 2 + "px, 0)";
} else {
this.transform = "scale(" + nextProps.width / 2 + "," + nextProps.height / 2 + ") " + getCameraCSSMatrix(camera.view) +
" translate3d(" + nextProps.width / 2 + "px," + nextProps.height / 2 + "px, 0)";
this.fov = 'none';
}
}
render() {
return (
<div className={this.props.className} style={{
overflow: 'hidden',
transformStyle: 'preserve-3d',
perspective: this.fov
}}>
<div style={{
position: 'absolute',
width: this.props.width,
height: this.props.height,
transformStyle: 'preserve-3d',
transform: this.transform,
}}>
{this.props.children}
</div>
</div >
);
}
}
export class Text3d extends React.Component {
shouldComponentUpdate(nextProps, nextState) {
return (
nextProps.x !== this.props.x ||
nextProps.y !== this.props.y ||
nextProps.size !== this.props.size ||
nextProps.label !== this.props.label
);
}
render() {
return (
<div style={{
position: 'absolute',
transform: 'translate3d(' + this.props.x + 'px,' + this.props.y + 'px,0) translate3d(-50%,-50%,0) scale(.1,-.1)',
}}>
<div style={Object.assign({}, this.props.style, {
left: 0,
top: 0,
fontSize: this.props.size * 10,
})}>
{this.props.label || this.props.children}
</div>
</div >
);
}
}
|
src/GreenNav.js | jrios6/GreenNav | import React, { Component } from 'react';
import ol from 'openlayers';
import { Toolbar, ToolbarGroup, ToolbarSeparator, ToolbarTitle } from 'material-ui/Toolbar';
import FlatButton from 'material-ui/FlatButton';
import { green50 } from 'material-ui/styles/colors';
import FontIcon from 'material-ui/FontIcon';
import Dialog from 'material-ui/Dialog';
import Snackbar from 'material-ui/Snackbar';
import Toggle from 'material-ui/Toggle';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import fetch from 'unfetch';
import Menu from './components/Menu';
import GreenNavMap from './components/GreenNavMap';
import { testCoordinatesValidity, getRangeAnxietyPolygonWithCoordinate } from './reachability';
const GreenNavServerAddress = 'http://localhost:8080/';
const styles = {
label: {
color: green50
},
unitSelectField: {
marginLeft: '24px'
}
};
export default class GreenNav extends Component {
constructor(props) {
super(props);
this.state = {
openInfoDialog: false,
openContactDialog: false,
openMapDialog: false,
openInvalidRouteSnackbar: false,
openAllowAccessSnackbar: false,
openIndicateStartSnackbar: false,
openRemainingRangeSnackbar: false,
mapType: 0,
unitsType: 0,
temperatureEnabled: false,
trafficEnabled: false,
windEnabled: false,
findingRoute: false,
userLocationCoordinates: undefined, // in EPSG:3857
rangePolygonOriginCoordinates: undefined, // in EPSG:3857
rangePolygonDestinationCoordinates: undefined, // in EPSG:3857
rangePolygonVisible: false,
locationPickerCoordinates: undefined, // in EPSG:3857
locationPickerCoordinatesTransformed: undefined, // in EPSG:4326
rangeFromField: '',
rangeFromFieldSelected: false,
rangeToField: '',
rangeToFieldSelected: false,
};
this.setLocationPickerCoordinates = this.setLocationPickerCoordinates.bind(this);
this.setUserLocationCoordinates = this.setUserLocationCoordinates.bind(this);
this.setRangePolygonAutocompleteOrigin = this.setRangePolygonAutocompleteOrigin.bind(this);
this.setRangePolygonAutocompleteDestination =
this.setRangePolygonAutocompleteDestination.bind(this);
}
setUserLocationCoordinates(coord) {
this.setState({ userLocationCoordinates: coord });
if (this.state.rangePolygonOriginCoordinates === undefined) {
this.setState({ rangePolygonOriginCoordinates: coord });
}
}
setRangePolygonAutocompleteOrigin(coord) {
const nCoord = ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857');
this.setState({
rangePolygonOriginCoordinates: nCoord,
locationPickerCoordinatesTransformed: coord
});
this.map.setAutocompleteLocationMarker(nCoord);
}
setRangePolygonAutocompleteDestination(coord) {
const nCoord = ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857');
this.setState({
rangePolygonDestinationCoordinates: nCoord,
locationPickerCoordinatesTransformed: coord
});
this.map.setAutocompleteLocationMarker(nCoord);
}
setLocationPickerCoordinates(coord) {
this.setState({ locationPickerCoordinates: coord });
const nCoord = ol.proj.transform(coord, 'EPSG:3857', 'EPSG:4326');
this.setState({ locationPickerCoordinatesTransformed: nCoord });
// update textfield with coordinate if selected
if (this.state.rangeFromFieldSelected) {
this.setState({
rangePolygonOriginCoordinates: coord,
rangeFromField: nCoord.map(i => i.toFixed(6)).join(', ') });
}
else if (this.state.rangeToFieldSelected) {
this.setState({
rangePolygonDestinationCoordinates: coord,
rangeToField: nCoord.map(i => i.toFixed(6)).join(', ')
});
}
}
getRoutes = (waypoints) => {
const routes = [];
let counterRoutes = 0;
if (waypoints.length > 0) {
this.showLoader();
}
for (let i = 0; i < waypoints.length - 1; i += 1) {
const startOsmId = waypoints[i];
const destinationOsmId = waypoints[i + 1];
const url = `${GreenNavServerAddress}astar/from/${startOsmId}/to/${destinationOsmId}`;
fetch(url)
.then((response) => {
if (response.status > 400) {
throw new Error('Failed to load route data!');
}
else {
return response.json();
}
})
.then((routeReceived) => {
// The array received from rt-library is actually from dest to orig,
// so we gotta reverse for now.
routes[i] = routeReceived.reverse();
counterRoutes += 1;
// We use counterRoutes instead of "i" because we don't know the order that
// routes will be received.
if (counterRoutes === waypoints.length - 1) {
let finalRoute = [];
for (let j = 0; j < routes.length; j += 1) {
finalRoute = finalRoute.concat(routes[j]);
}
this.hideLoader();
this.map.setRoute(routes[0]);
}
})
.catch(() => this.hideLoader());
}
}
getRangeVisualisation = (range) => {
const coord = this.state.rangePolygonOriginCoordinates;
if (!coord) {
this.handleAllowAccessSnackbarOpen();
}
else {
this.showLoader();
// test if origin coordinate has valid roads
testCoordinatesValidity(coord)
.then((res) => {
if (res) {
// gets vertices of range anxiety polygon
getRangeAnxietyPolygonWithCoordinate(coord, range)
.then((vertices) => {
this.hideLoader();
if (vertices !== false) {
this.map.setRangePolygon(vertices, coord);
this.setState({ rangePolygonVisible: true });
}
else {
this.handleInvalidRouteSnackbarOpen();
}
});
}
else {
this.hideLoader();
this.handleInvalidRouteSnackbarOpen();
}
});
}
}
hideRangeVisualisation = () => {
this.map.hideRangePolygon();
this.setState({ rangePolygonVisible: false });
}
toggleDrawer = () => {
this.drawer.toggle(this.updateMapSize);
}
updateMapSize = () => {
this.map.updateSize();
}
handleIndicateStartSnackbarOpen = () => {
this.setState({ openIndicateStartSnackbar: true });
}
handleIndicateStartSnackbarClose= () => {
this.setState({ openIndicateStartSnackbar: false });
}
handleRemainingRangeSnackbarOpen = () => {
this.setState({ openRemainingRangeSnackbar: true });
}
handleRemainingRangeSnackbarClose= () => {
this.setState({ openRemainingRangeSnackbar: false });
}
handleInvalidRouteSnackbarOpen = () => {
this.setState({ openInvalidRouteSnackbar: true });
}
handleInvalidRouteSnackbarClose = () => {
this.setState({ openInvalidRouteSnackbar: false });
}
handleAllowAccessSnackbarOpen = () => {
this.setState({ openAllowAccessSnackbar: true });
}
handleAllowAccessSnackbarClose = () => {
this.setState({ openAllowAccessSnackbar: false });
}
handleInfoOpen = () => {
this.setState({ openInfoDialog: true });
}
handleInfoClose = () => {
this.setState({ openInfoDialog: false });
}
handleContactOpen = () => {
this.setState({ openContactDialog: true });
}
handleContactClose = () => {
this.setState({ openContactDialog: false });
}
handleMapOpen = () => {
this.setState({ openMapDialog: true });
}
handleMapClose = () => {
this.setState({ openMapDialog: false });
}
mapTypeChange = (event, index, value) => {
this.setState({ mapType: value });
this.map.setMapType(value);
}
unitsTypeChange = (event, index, value) => {
this.drawer.convertUnits(value);
this.setState({ unitsType: value });
}
toggleTraffic = () => {
this.setState({ trafficEnabled: !this.state.trafficEnabled });
this.map.toggleTraffic();
}
toggleWind = () => {
this.setState({ windEnabled: !this.state.windEnabled });
this.map.toggleWind();
}
toggleTemperature = () => {
this.setState({ temperatureEnabled: !this.state.temperatureEnabled });
this.map.toggleTemperature();
}
showLoader = () => {
// show loader for requests that take more than 400ms to complete
this.searchTimeout = setTimeout(() => {
this.setState({ findingRoute: true });
}, 400);
}
hideLoader = () => {
clearTimeout(this.searchTimeout);
this.setState({ findingRoute: false });
}
updateRangeFromSelected = (e) => {
// selects rangeFromField and unselect rangeToField
this.setState({
rangeFromFieldSelected: e,
rangeToFieldSelected: !e
});
}
updateRangeToSelected = (e) => {
// selects rangeToField and unselects rangeFromField
this.setState({
rangeFromFieldSelected: !e,
rangeToFieldSelected: e
});
}
updateRangeFromField = (val) => {
this.setState({ rangeFromField: val });
const coord = this.isEPSG4326Coordinate(val);
if (coord) {
this.setState({
rangePolygonOriginCoordinates: ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857')
});
}
}
updateRangeToField = (val) => {
this.setState({ rangeToField: val });
const coord = this.isEPSG4326Coordinate(val);
if (coord) {
this.setState({
rangePolygonDestinationCoordinates: ol.proj.transform(coord, 'EPSG:4326', 'EPSG:3857')
});
}
}
isEPSG4326Coordinate = (val) => {
const valArray = val.replace(/\s+/g, '').split(',');
if (valArray.length === 2) {
const lng = parseFloat(valArray[0]);
const lat = parseFloat(valArray[1]);
// returns formatted coordinate if true
if (lng <= 180 && lng >= -180 && lat <= 45 && lat >= -45) {
return [lng, lat];
}
}
return false;
}
render() {
const infoActions = [
<FlatButton
label="Ok"
onTouchTap={this.handleInfoClose}
/>,
];
const contactActions = [
<FlatButton
label="Ok"
onTouchTap={this.handleContactClose}
/>,
];
const mapActions = [
<FlatButton
label="Finish"
onTouchTap={this.handleMapClose}
/>,
];
return (
<div style={{ display: 'flex', flexDirection: 'column', height: '100vh' }}>
<Toolbar>
<ToolbarGroup firstChild>
<FontIcon className="material-icons" onClick={this.toggleDrawer}>
menu</FontIcon>
<img alt="GreenNav" src="/images/logo-64.png" />
</ToolbarGroup>
<ToolbarGroup>
<ToolbarTitle text="Map Options" />
<FontIcon className="material-icons" onTouchTap={this.handleMapOpen}>
map</FontIcon>
<ToolbarSeparator />
<FlatButton
label="Info"
labelStyle={styles.label}
onTouchTap={this.handleInfoOpen}
icon={<FontIcon className="material-icons" color={green50}>info</FontIcon>}
/>
<FlatButton
label="Contact"
labelStyle={styles.label}
onTouchTap={this.handleContactOpen}
icon={<FontIcon className="material-icons" color={green50}>email</FontIcon>}
/>
</ToolbarGroup>
</Toolbar>
<div style={{ display: 'flex', flex: '1 0' }}>
<Menu
autoCompleteAddress={GreenNavServerAddress}
locationPickerCoordinates={this.state.locationPickerCoordinatesTransformed}
ref={c => (this.drawer = c)}
open
getRoutes={this.getRoutes}
unitsType={this.state.unitsType}
rangePolygonVisible={this.state.rangePolygonVisible}
getRangeVisualisation={this.getRangeVisualisation}
hideRangeVisualisation={this.hideRangeVisualisation}
updateRangeFromField={this.updateRangeFromField}
updateRangeFromSelected={this.updateRangeFromSelected}
rangeFromField={this.state.rangeFromField}
updateRangeToField={this.updateRangeToField}
updateRangeToSelected={this.updateRangeToSelected}
rangeToField={this.state.rangeToField}
setRangePolygonAutocompleteOrigin={this.setRangePolygonAutocompleteOrigin}
setRangePolygonAutocompleteDestination={this.setRangePolygonAutocompleteDestination}
handleIndicateStartSnackbarOpen={this.handleIndicateStartSnackbarOpen}
handleRemainingRangeSnackbarOpen={this.handleRemainingRangeSnackbarOpen}
/>
<GreenNavMap
ref={c => (this.map = c)}
mapType={this.state.mapType}
locationPickerCoordinates={this.state.locationPickerCoordinates}
locationPickerCoordinatesTransformed={this.state.locationPickerCoordinatesTransformed}
findingRoute={this.state.findingRoute}
userLocationCoordinates={this.state.userLocationCoordinates}
setLocationPickerCoordinates={this.setLocationPickerCoordinates}
setUserLocationCoordinates={this.setUserLocationCoordinates}
/>
</div>
<Snackbar
open={this.state.openIndicateStartSnackbar}
message="Please select a start and destination from the suggestions"
autoHideDuration={4000}
onRequestClose={this.handleIndicateStartSnackbarClose}
/>
<Snackbar
open={this.state.openRemainingRangeSnackbar}
message="Please indicate the remaining range of your vehicle"
autoHideDuration={4000}
onRequestClose={this.handleRemainingRangeSnackbarClose}
/>
<Snackbar
open={this.state.openInvalidRouteSnackbar}
message="No valid routes were found from your starting location"
autoHideDuration={4000}
onRequestClose={this.handleInvalidRouteSnackbarClose}
/>
<Snackbar
open={this.state.openAllowAccessSnackbar}
message="Please allow access to your current location or pick a starting location"
autoHideDuration={4000}
onRequestClose={this.handleAllowAccessSnackbarClose}
/>
<Dialog
title=""
actions={infoActions}
modal={false}
open={this.state.openInfoDialog}
onRequestClose={this.handleInfoClose}
>
<h2>Green Navigation</h2>
<p>The GreenNav organization is a community of young researchers and students at the
University of Lübeck.We decided not long ago to go open source in order to collaborate
with others and to show what we are working on.
</p>
<p>The projects of the GreenNav organization are closely related to the student projects
at the university’s computer science program. However, with this organisation we
invite everyone to participate in the development of experimental routing systems.
<br />
<a href="http://greennav.github.io/what-is-greennav.html">
Get more information about GreenNav
</a>
</p>
</Dialog>
<Dialog
title=""
actions={contactActions}
modal={false}
open={this.state.openContactDialog}
onRequestClose={this.handleContactClose}
>
<h2>Contact</h2>
<p>There are several ways to contact us. For questions about coding, issues, etc. please
use <a href="https://github.com/Greennav">Github</a>
</p>
<p>For more general questions use our <a href="https://plus.google.com/communities/110704433153909631379">G+ page</a> or <a href="https://groups.google.com/forum/#!forum/greennav">Google Groups</a></p>
</Dialog>
<Dialog
title="Map Settings"
actions={mapActions}
modal={false}
open={this.state.openMapDialog}
onRequestClose={this.handleMapClose}
>
<SelectField
floatingLabelText="Map Type"
value={this.state.mapType}
onChange={this.mapTypeChange}
>
<MenuItem value={0} primaryText="OpenStreetMap" />
<MenuItem value={1} primaryText="Google Map" />
</SelectField>
<SelectField
floatingLabelText="Units"
value={this.state.unitsType}
style={styles.unitSelectField}
onChange={this.unitsTypeChange}
>
<MenuItem value={0} primaryText="Kilometers" />
<MenuItem value={1} primaryText="Miles" />
</SelectField>
<h2>Overlays</h2>
<Toggle
label="Traffic"
toggled={this.state.trafficEnabled}
onToggle={this.toggleTraffic}
labelPosition="right"
thumbSwitchedStyle={styles.thumbSwitched}
trackSwitchedStyle={styles.trackSwitched}
/>
<Toggle
label="Temperature"
toggled={this.state.temperatureEnabled}
onToggle={this.toggleTemperature}
labelPosition="right"
thumbSwitchedStyle={styles.thumbSwitched}
trackSwitchedStyle={styles.trackSwitched}
/>
<Toggle
label="Wind"
toggled={this.state.windEnabled}
onToggle={this.toggleWind}
labelPosition="right"
thumbSwitchedStyle={styles.thumbSwitched}
trackSwitchedStyle={styles.trackSwitched}
/>
</Dialog>
</div>
);
}
}
|
src/components/Header.js | jasongforbes/dorian-js | import React from 'react';
const Header = function render(props) {
return (
<div className="header">
<img className="avatar" src={props.avatar} alt={props.avatarAlt} />
<h1>{props.title}</h1>
<p>{props.description}</p>
</div>
);
};
Header.propTypes = {
avatar: React.PropTypes.string.isRequired,
avatarAlt: React.PropTypes.string.isRequired,
title: React.PropTypes.string.isRequired,
description: React.PropTypes.string.isRequired,
};
export default Header;
|
html.js | minseokim/blog | import React from 'react';
import Helmet from 'react-helmet';
import { prefixLink } from 'gatsby-helpers';
const BUILD_TIME = new Date().getTime();
module.exports = React.createClass({
displayName: 'HTML',
propTypes: {
body: React.PropTypes.string,
},
render() {
const { body } = this.props;
const { title } = Helmet.rewind();
const font = <link href="https://fonts.googleapis.com/css?family=Roboto:400,400italic,500,700&subset=latin,cyrillic" rel="stylesheet" type="text/css" />;
let css;
if (process.env.NODE_ENV === 'production') {
// eslint-disable-next-line import/no-webpack-loader-syntax
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" />
<meta name="viewport" content="width=device-width, initial-scale=1.0 maximum-scale=5.0" />
{ title.toComponent() }
{ font }
{ css }
</head>
<body>
<div id="react-mount" dangerouslySetInnerHTML={{ __html: this.props.body }} />
<script src={prefixLink(`/bundle.js?t=${BUILD_TIME}`)} />
</body>
</html>
);
},
});
|
app/js/home/index.js | DawChihLiou/ci-boilerplate | import React from 'react'
import Test from '../common/Test'
const Home = () => (
<div className="text-center">
<h1>This is Home View.</h1>
<Test />
</div>
)
export default Home
|
src/components/StoriesComponent.js | jimmymintzer/reacter-news | import React from 'react';
import { Link } from 'react-router';
import StoryComponent from './StoryComponent';
import LoaderComponent from './LoaderComponent';
const StoriesComponent = ({ loading, stories, page, linkTo, userId }) => {
document.title = 'Reacter News';
const storiesComponents = stories.map((story) => {
return (
<li key={story.id}>
<StoryComponent story={story} />
</li>
);
});
if (loading) {
return (
<LoaderComponent />
);
}
const index = (30 * (page - 1)) + 1;
const nextPage = page + 1;
const queryObj = (userId) ? { p: nextPage, id: userId } : { p: nextPage };
const link = (stories.length === 30) ?
<Link to={linkTo} href="#" query={queryObj}>More</Link>
: null;
return (
<div>
<ol className="stories" start={index}>
{storiesComponents}
</ol>
<div className="more-link">
{link}
</div>
</div>
);
};
export default StoriesComponent;
|
js/App/Components/TabViews/SubViews/Jobs/NowRow.js | telldus/telldus-live-mobile-v3 | /**
* Copyright 2016-present Telldus Technologies AB.
*
* This file is part of the Telldus Live! app.
*
* Telldus Live! app is free : you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* Telldus Live! app 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with Telldus Live! app. If not, see <http://www.gnu.org/licenses/>.
*/
// @flow
'use strict';
import React from 'react';
import { ListRow, View, Text, StyleSheet } from '../../../../../BaseComponents';
type Props = {
text: string,
roundIconContainerStyle?: Array<any> | Object,
rowWithTriangleContainerStyle?: Array<any> | Object,
textStyle?: Array<any> | Object,
lineStyle?: Array<any> | Object,
appLayout: Object,
};
export default class NowRow extends View<Props, null> {
render(): Object {
const {
text,
roundIconContainerStyle,
rowWithTriangleContainerStyle,
textStyle,
lineStyle,
appLayout,
} = this.props;
return (
<ListRow
roundIcon={''}
roundIconContainerStyle={roundIconContainerStyle}
time={null}
rowStyle={{
backgroundColor: 'transparent',
}}
rowContainerStyle={styles.rowContainerStyle}
rowWithTriangleContainerStyle={[rowWithTriangleContainerStyle, {
backgroundColor: 'transparent',
}]}
triangleStyle={styles.triangleStyle}
triangleContainerStyle={styles.triangleContainerStyle}
appLayout={appLayout}>
<View style={styles.cover}>
<Text style={textStyle}>
{text}
</Text>
<View style={lineStyle}/>
</View>
</ListRow>
);
}
}
const styles = StyleSheet.create({
rowContainerStyle: {
flex: 1,
alignItems: 'flex-start',
justifyContent: 'flex-start',
backgroundColor: 'transparent',
elevation: 0,
shadowColor: '#fff',
shadowOpacity: 0,
shadowOffset: {
height: 0,
width: 0,
},
},
triangleStyle: {
height: 0,
width: 0,
},
triangleContainerStyle: {
height: 0,
width: 0,
zIndex: 0,
elevation: 0,
},
cover: {
flex: 1,
flexDirection: 'row',
justifyContent: 'space-between',
alignItems: 'center',
backgroundColor: 'transparent',
},
});
|
fields/types/Field.js | ONode/keystone | import classnames from 'classnames';
import evalDependsOn from '../utils/evalDependsOn.js';
import React from 'react';
import { findDOMNode } from 'react-dom';
import { FormField, FormInput, FormNote } from '../../admin/client/App/elemental';
import blacklist from 'blacklist';
import CollapsedFieldLabel from '../components/CollapsedFieldLabel';
function isObject (arg) {
return Object.prototype.toString.call(arg) === '[object Object]';
}
function validateSpec (spec) {
if (!spec) spec = {};
if (!isObject(spec.supports)) {
spec.supports = {};
}
if (!spec.focusTargetRef) {
spec.focusTargetRef = 'focusTarget';
}
return spec;
}
var Base = module.exports.Base = {
getInitialState () {
return {};
},
getDefaultProps () {
return {
adminPath: Keystone.adminPath,
inputProps: {},
labelProps: {},
valueProps: {},
size: 'full',
};
},
getInputName (path) {
// This correctly creates the path for field inputs, and supports the
// inputNamePrefix prop that is required for nested fields to work
return this.props.inputNamePrefix
? `${this.props.inputNamePrefix}[${path}]`
: path;
},
valueChanged (event) {
this.props.onChange({
path: this.props.path,
value: event.target.value,
});
},
shouldCollapse () {
return this.props.collapse && !this.props.value;
},
shouldRenderField () {
if (this.props.mode === 'create') return true;
return !this.props.noedit;
},
focus () {
if (!this.refs[this.spec.focusTargetRef]) return;
findDOMNode(this.refs[this.spec.focusTargetRef]).focus();
},
renderNote () {
if (!this.props.note) return null;
return <FormNote html={this.props.note} />;
},
renderField () {
const { autoFocus, value, inputProps } = this.props;
return (
<FormInput {...{
...inputProps,
autoFocus,
autoComplete: 'off',
name: this.getInputName(this.props.path),
onChange: this.valueChanged,
ref: 'focusTarget',
value,
}} />
);
},
renderValue () {
return <FormInput noedit>{this.props.value}</FormInput>;
},
renderUI () {
var wrapperClassName = classnames(
'field-type-' + this.props.type,
this.props.className,
{ 'field-monospace': this.props.monospace }
);
return (
<FormField htmlFor={this.props.path} label={this.props.label} className={wrapperClassName} cropLabel>
<div className={'FormField__inner field-size-' + this.props.size}>
{this.shouldRenderField() ? this.renderField() : this.renderValue()}
</div>
{this.renderNote()}
</FormField>
);
},
};
var Mixins = module.exports.Mixins = {
Collapse: {
componentWillMount () {
this.setState({
isCollapsed: this.shouldCollapse(),
});
},
componentDidUpdate (prevProps, prevState) {
if (prevState.isCollapsed && !this.state.isCollapsed) {
this.focus();
}
},
uncollapse () {
this.setState({
isCollapsed: false,
});
},
renderCollapse () {
if (!this.shouldRenderField()) return null;
return (
<FormField>
<CollapsedFieldLabel onClick={this.uncollapse}>+ Add {this.props.label.toLowerCase()}</CollapsedFieldLabel>
</FormField>
);
},
},
};
module.exports.create = function (spec) {
spec = validateSpec(spec);
var field = {
spec: spec,
displayName: spec.displayName,
mixins: [Mixins.Collapse],
statics: {
getDefaultValue: function (field) {
return field.defaultValue || '';
},
},
render () {
if (!evalDependsOn(this.props.dependsOn, this.props.values)) {
return null;
}
if (this.state.isCollapsed) {
return this.renderCollapse();
}
return this.renderUI();
},
};
if (spec.statics) {
Object.assign(field.statics, spec.statics);
}
var excludeBaseMethods = {};
if (spec.mixins) {
spec.mixins.forEach(function (mixin) {
Object.keys(mixin).forEach(function (name) {
if (Base[name]) {
excludeBaseMethods[name] = true;
}
});
});
}
Object.assign(field, blacklist(Base, excludeBaseMethods));
Object.assign(field, blacklist(spec, 'mixins', 'statics'));
if (Array.isArray(spec.mixins)) {
field.mixins = field.mixins.concat(spec.mixins);
}
return React.createClass(field);
};
|
spec/coffeescripts/react_files/components/UsageRightsSelectBoxSpec.js | djbender/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 'jquery'
import React from 'react'
import {shallow, mount} from 'enzyme'
import UsageRightsSelectBox from 'jsx/files/UsageRightsSelectBox'
QUnit.module('UsageRightsSelectBox', {
teardown() {
return $('div.error_box').remove()
}
})
test('shows alert message if nothing is chosen and component is setup for a message', () => {
const wrapper = shallow(<UsageRightsSelectBox showMessage />)
ok(
wrapper
.find('.alert')
.text()
.includes(
"If you do not select usage rights now, this file will be unpublished after it's uploaded."
),
'message is being shown'
)
})
test('fetches license options when component mounts', () => {
const server = sinon.fakeServer.create()
const wrapper = mount(<UsageRightsSelectBox showMessage={false} />)
server.respond('GET', '', [
200,
{'Content-Type': 'application/json'},
JSON.stringify([
{
id: 'cc_some_option',
name: 'CreativeCommonsOption'
}
])
])
equal(wrapper.instance().state.licenseOptions[0].id, 'cc_some_option', 'sets data just fine')
server.restore()
})
test('inserts copyright into textbox when passed in', () => {
const copyright = 'all dogs go to taco bell'
const wrapper = shallow(<UsageRightsSelectBox copyright={copyright} />)
equal(
wrapper
.find('#copyrightHolder')
.find('input')
.prop('defaultValue'),
copyright
)
})
test('shows creative commons options when set up', () => {
const server = sinon.fakeServer.create()
const props = {
copyright: 'loony',
use_justification: 'creative_commons',
cc_value: 'helloooo_nurse'
}
const wrapper = mount(<UsageRightsSelectBox {...props} />)
server.respond('GET', '', [
200,
{'Content-Type': 'application/json'},
JSON.stringify([
{
id: 'cc_some_option',
name: 'CreativeCommonsOption'
}
])
])
equal(wrapper.instance().creativeCommons.value, 'cc_some_option', 'shows creative commons option')
server.restore()
})
|
src/index.js | hongkheng/hdb-resale | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, Redirect, IndexRedirect, browserHistory } from 'react-router';
import App from './components/App';
import Charts from './components/Charts';
import Maps from './components/Maps';
import About from './components/About';
import {ChartSelector, MapSelector} from './components/Selectors';
import './css/style.css';
window.PouchDB = require('pouchdb');
ReactDOM.render((
<Router history={browserHistory}>
<Route path='/' component={App}>
<Route path='charts(/:town)' components={{main: Charts, selector: ChartSelector}} />
<Route path='maps(/:month)' components={{main: Maps, selector: MapSelector}} />
<Route path='about' components={{main: About}} />
<IndexRedirect to='/charts' />
<Redirect from='*' to='/charts' />
</Route>
</Router>
), document.getElementById('root'));
|
src/modules/Components/User/Sidebar.js | rtellez700/MESA_Connect_2.0 | import React, { Component } from 'react';
class Sidebar extends Component {
_onClick(e){
e.preventDefault();
$('#RT_Sidebar').toggleClass('open');
console.log(e.target)
}
render() {
return (
<div id="RT_Sidebar" className="RT_Sidebar">
<div className="selector-toggle">
<a href="#" onClick={this._onClick.bind(this)}></a>
</div>
<ul>
<li className="theme-option">Label 1</li>
<li className="theme-option">Label 2</li>
<li className="theme-option">Label 3</li>
<li className="theme-option">Label 4</li>
</ul>
</div>
);
}
}
module.exports = Sidebar; |
src/containers/PreviewPetition.js | iris-dni/iris-frontend | import React from 'react';
import Helmet from 'react-helmet';
import { connect } from 'react-redux';
import { fetchPetition, publishPetition } from 'actions/PetitionActions';
import settings from 'settings';
import PreviewPetition from 'components/PreviewPetition';
import getPetitionForm from 'selectors/petitionForm';
const PreviewPetitionContainer = (props) => (
<div>
<Helmet title={settings.previewPetitionPage.title} />
<PreviewPetition {...props} />
</div>
);
PreviewPetitionContainer.fetchData = ({ store, params }) => {
return store.dispatch(fetchPetition(params.id));
};
export const mapStateToProps = ({ petition }) => ({
petition: getPetitionForm(petition)
});
export const mapDispatchToProps = (dispatch) => ({
publishPetition: (petition) => dispatch(publishPetition(petition))
});
export default connect(
mapStateToProps,
mapDispatchToProps
)(PreviewPetitionContainer);
|
src/app/routes/forms/components/layouts/OrderForm.js | backpackcoder/world-in-flames | import React from 'react'
import UiValidate from '../../../../components/forms/validation/UiValidate'
import MaskedInput from '../../../../components/forms/inputs/MaskedInput'
import UiDatepicker from '../../../../components/forms/inputs/UiDatepicker'
const validationOptions = {
// Rules for form validation
rules: {
name: {
required: true
},
email: {
required: true,
email: true
},
phone: {
required: true
},
interested: {
required: true
},
budget: {
required: true
}
},
// Messages for form validation
messages: {
name: {
required: 'Please enter your name'
},
email: {
required: 'Please enter your email address',
email: 'Please enter a VALID email address'
},
phone: {
required: 'Please enter your phone number'
},
interested: {
required: 'Please select interested service'
},
budget: {
required: 'Please select your budget'
}
}
};
export default class OrderForm extends React.Component {
state = {
fileInputValue: ''
};
onSubmit(e) {
e.preventDefault();
console.log('submit stuff')
}
onFileInputChange = (e)=>{
this.setState({
fileInputValue: e.target.value
})
}
render() {
return (
<UiValidate options={validationOptions}>
<form id="order-form" className="smart-form" noValidate="novalidate" onSubmit={this.onSubmit}>
<header>
Order services
</header>
<fieldset>
<div className="row">
<section className="col col-6">
<label className="input"> <i className="icon-append fa fa-user"/>
<input type="text" name="name" placeholder="Name"/>
</label>
</section>
<section className="col col-6">
<label className="input"> <i className="icon-append fa fa-briefcase"/>
<input type="text" name="company" placeholder="Company"/>
</label>
</section>
</div>
<div className="row">
<section className="col col-6">
<label className="input"> <i className="icon-append fa fa-envelope-o"/>
<input type="email" name="email" placeholder="E-mail"/>
</label>
</section>
<section className="col col-6">
<label className="input"> <i className="icon-append fa fa-phone"/>
<MaskedInput type="tel" name="phone" placeholder="Phone" mask="(999) 999-9999"/>
</label>
</section>
</div>
</fieldset>
<fieldset>
<div className="row">
<section className="col col-6">
<label className="select">
<select name="interested" defaultValue={"0"}>
<option value="0" disabled={true}>Interested in</option>
<option value="1">design</option>
<option value="1">development</option>
<option value="2">illustration</option>
<option value="2">branding</option>
<option value="3">video</option>
</select> <i/> </label>
</section>
<section className="col col-6">
<label className="select">
<select name="budget" defaultValue={"0"}>
<option value="0" disabled={true}>Budget</option>
<option value="1">less than 5000$</option>
<option value="2">5000$ - 10000$</option>
<option value="3">10000$ - 20000$</option>
<option value="4">more than 20000$</option>
</select> <i/> </label>
</section>
</div>
<div className="row">
<section className="col col-6">
<label className="input"> <i className="icon-append fa fa-calendar"/>
<UiDatepicker type="text" name="startdate" id="startdate" minRestrict="#finishdate"
placeholder="Expected start date"/>
</label>
</section>
<section className="col col-6">
<label className="input"> <i className="icon-append fa fa-calendar"/>
<UiDatepicker type="text" name="finishdate" id="finishdate" maxRestrict="#startdate"
placeholder="Expected finish date"/>
</label>
</section>
</div>
<section>
<div className="input input-file">
<span className="button"><input id="file2" type="file" name="file2"
onChange={this.onFileInputChange}/>Browse</span><input
type="text" value={this.state.fileInputValue} placeholder="Include some files" readOnly={true}/>
</div>
</section>
<section>
<label className="textarea"> <i className="icon-append fa fa-comment"/>
<textarea rows="5" name="comment" placeholder="Tell us about your project"/>
</label>
</section>
</fieldset>
<footer>
<button type="submit" className="btn btn-primary">
Validate Form
</button>
</footer>
</form>
</UiValidate>
)
}
} |
src/components/wallet/AddressGet.js | whphhg/vcash-electron | import React from 'react'
import { translate } from 'react-i18next'
import { inject, observer } from 'mobx-react'
import { action, computed, extendObservable, reaction } from 'mobx'
/** Ant Design */
import AutoComplete from 'antd/lib/auto-complete'
import Button from 'antd/lib/button'
import Input from 'antd/lib/input'
import Popover from 'antd/lib/popover'
@translate(['common'])
@inject('rpc', 'wallet')
@observer
class AddressGet extends React.Component {
constructor(props) {
super(props)
this.t = props.t
this.rpc = props.rpc
this.wallet = props.wallet
this.getNewAddress = this.getNewAddress.bind(this)
/** Errors that will be shown to the user. */
this.errShow = ['accChars', 'keypoolRanOut']
/** Extend the component with observable properties. */
extendObservable(this, {
account: '',
address: '',
rpcError: '',
popoverVisible: false
})
/** Clear new address when the popover gets hidden. */
this.popoverReaction = reaction(
() => this.popoverVisible,
popoverVisible => {
if (popoverVisible === false) {
if (this.address !== '') this.setProps({ address: '' })
}
},
{ name: 'AddressGet: popover hidden, clearing new address.' }
)
}
/** Dispose of reaction on component unmount. */
componentWillUnmount() {
this.popoverReaction()
}
/**
* Get present error or empty string if none.
* @function errorStatus
* @return {string} Error status.
*/
@computed
get errorStatus() {
if (this.account.match(/^[a-z0-9 -]*$/i) === null) return 'accChars'
if (this.account.length > 100) return 'accLength'
if (this.rpcError !== '') return this.rpcError
return ''
}
/**
* Set observable properties.
* @function setProps
* @param {object} props - Key value combinations.
*/
@action
setProps = props => {
Object.keys(props).forEach(key => (this[key] = props[key]))
}
/**
* Toggle popover visibility.
* @function togglePopover
*/
@action
togglePopover = () => {
this.popoverVisible = !this.popoverVisible
}
/**
* Get new receiving address.
* @function getNewAddress
*/
async getNewAddress() {
const res = await this.rpc.getNewAddress(this.account)
if ('result' in res === true) {
this.setProps({ address: res.result })
this.wallet.updateAddresses([this.account])
}
if ('error' in res === true) {
switch (res.error.code) {
case -12:
return this.setProps({ rpcError: 'keypoolRanOut' })
}
}
}
render() {
return (
<Popover
content={
<div style={{ width: '400px' }}>
<AutoComplete
dataSource={this.wallet.accNames}
filterOption
getPopupContainer={triggerNode => triggerNode.parentNode}
onChange={account => this.setProps({ account })}
placeholder={this.t('accName')}
style={{ width: '100%' }}
value={this.account}
/>
{this.address !== '' && (
<Input
className="green"
readOnly
style={{ margin: '5px 0 0 0' }}
value={this.address}
/>
)}
<div className="flex-sb" style={{ margin: '5px 0 0 0' }}>
<p className="red">
{this.errShow.includes(this.errorStatus) === true &&
this.t(this.errorStatus)}
</p>
<Button
disabled={this.errorStatus !== ''}
onClick={this.getNewAddress}
>
{this.t('addrGet')}
</Button>
</div>
</div>
}
onVisibleChange={this.togglePopover}
placement="topLeft"
title={this.t('addrGetDesc')}
trigger="click"
visible={this.popoverVisible}
>
<Button size="small">
<i className="flex-center material-icons md-16">plus_one</i>
</Button>
</Popover>
)
}
}
export default AddressGet
|
app/client/components/creationForm/Leaderboard.js | breakfast-mimes/cyber-mimes | import React from 'react';
import { Link } from 'react-router';
import {BootstrapTable, TableHeaderColumn} from 'react-bootstrap-table';
const Leaderboard = React.createClass({
// {results.map((char,i)=>
// <li key={i}>{"character name: " + char.charactername + " level " + char.level}</li>)}
componentWillMount() {
this.props.getAllCharacters();
},
render() {
let results = this.props.game.allChars;
results.sort(function(obj1,obj2){return obj2.level - obj1.level;})
return (
<div>
<h1 className='leaderBoard'>Leaderboard</h1>
<h2 className='search'>Search</h2>
<div className='bootstrapTable'>
<BootstrapTable className='table' trClassName= 'tableRow' data={results}
search={true}
striped={true}
hover={true}
searchPlaceholder="Character Name"
>
<TableHeaderColumn className='header' dataField="charactername" isKey={true} dataAlign='center' width='100'>Character Name</TableHeaderColumn>
<TableHeaderColumn className='header' dataField="level" dataSort={true} >Level</TableHeaderColumn>
</BootstrapTable>
</div>
</div>
)
}
})
export default Leaderboard;
|
docs/src/app/components/pages/components/SelectField/ExampleMultiple.js | spiermar/material-ui | import React from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
const style = {
overflow: 'hidden',
whiteSpace: 'nowrap',
};
export default class SelectFieldExampleMultiple extends React.Component {
constructor(props) {
super(props);
this.state = {value: []};
}
handleChange = (event, index, value) => {
const stateValueIndex = this.state.value.indexOf(value);
if (stateValueIndex === -1) {
this.state.value.push(value);
} else {
this.state.value.splice(stateValueIndex, 1);
}
}
render() {
return (
<div>
<SelectField
value={this.state.value}
onChange={this.handleChange}
multiple={true}
style={style}
>
<MenuItem value={1} primaryText="Never" />
<MenuItem value={2} primaryText="Every Night" />
<MenuItem value={3} primaryText="Weeknights" />
<MenuItem value={4} primaryText="Weekends" />
<MenuItem value={5} primaryText="Weekly" />
</SelectField>
</div>
);
}
}
|
EventEmitter.Client/src/routes/Calendar/components/CalendarView.js | Stelmashenko-A/EventEmitter | import React from 'react'
import { Button } from 'react-mdl'
import BigCalendar from 'react-big-calendar'
import moment from 'moment'
import events from './events'
import './CalendarView.scss'
import 'react-big-calendar/lib/css/react-big-calendar.css'
BigCalendar.setLocalizer(
BigCalendar.momentLocalizer(moment)
)
export const Calendar = (props) => (
<div className='calendar'>
<div style={{ width:'100%', textAlign: 'right' }}>
<h1>Calendar</h1>
<Button style={{ right:0, marginBottom: 20 }}>Export Calendar</Button>
</div>
<BigCalendar
onNavigate={props.loadEvents}
events={props.events}
defaultDate={new Date()}
/>
</div>
)
Calendar.propTypes = {
events: React.PropTypes.array,
loadEvents: React.PropTypes.func
}
export default Calendar
|
App/db/entities/content/Events/Theatre.js | nathb2b/mamasound.fr | /*
* Copyright (c) 2017. Caipi Labs. All rights reserved.
*
* This File is part of Caipi. You can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
* This project is dual licensed under AGPL and Commercial Licence.
*
* @author : Nathanael Braun
* @contact : caipilabs@gmail.com
*/
/**
* @author Nathanael BRAUN
*
* Date: 24/11/2015
* Time: 19:18
*/
import React from 'react';
import {types, validate} from 'App/db/field';
export default {
...require("../Event"),
label : "Piece de Theatre",
targetCollection : "Event",
disallowCreate : false,//Can't create pure events so we must enable editing when inheriting...
adminRoute : "Événements/Theatre",
// apiRoute : "dates",
wwwRoute : "Theatre"
}; |
src/containers/hoc-messenger.js | MoveOnOrg/mop-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { petitionShortCode } from '../lib'
import Config from '../config'
function getMobileMessengerLink(encodedValue) {
// testing messenger link on mobile only first
return `fb-messenger://share?link=${encodedValue}&app_id=${encodeURIComponent(Config.MESSENGER_APP_ID)}`
}
export function withMessenger(WrappedComponent) {
class Messenger extends React.Component {
constructor(props) {
super(props)
this.getShareLink = this.getShareLink.bind(this)
this.shareMessenger = this.shareMessenger.bind(this)
}
getShareLink() {
const { shortLinkMode, shortLinkArgs } = this.props
const messengerShareLink = petitionShortCode(
shortLinkMode,
...shortLinkArgs
)
const encodedLink = encodeURIComponent(messengerShareLink)
return encodedLink
}
shareMessenger() {
/* If the app is installed:
- User will be brought to the app with the petition
- The second timeout will still be called and the moveon messenger page will open in a window
If the app is not installed:
- The first window.open call will fail and error
- The second timeout will still be called and the moveon messenger page will open in a window
- The second window.open call is for users without the app installed */
const shareLink = getMobileMessengerLink(this.getShareLink())
window.open(shareLink)
setTimeout(() => { window.open('https://m.me/moveon') }, 3000)
const { recordShare, afterShare } = this.props
if (recordShare) recordShare()
if (afterShare) afterShare()
}
render() {
/* eslint-disable no-unused-vars */
// remove props we don't want to pass through
const {
petition,
shortLinkMode,
shortLinkArgs,
recordShare,
// (just to remove from otherProps)
...otherProps
} = this.props
/* eslint-enable */
return <WrappedComponent {...otherProps} onClick={this.shareMessenger} />
}
}
Messenger.propTypes = {
petition: PropTypes.object,
shortLinkArgs: PropTypes.array,
shortLinkMode: PropTypes.string,
recordShare: PropTypes.func,
afterShare: PropTypes.func
}
return Messenger
}
|
src/client/scenes/User/UserInfo/index.js | kettui/webcord-web-app | import React, { Component } from 'react';
import { observer, inject } from 'mobx-react';
import { autobind } from 'core-decorators';
import classNames from 'classnames/bind';
import { Image, Item } from 'semantic-ui-react';
import { ActivityChart, Avatar, Loading } from 'components/';
import * as date from 'utils/date';
import styles from './user-info.scss';
const cx = classNames.bind(styles);
const UserInfo = ({
avatar,
bot,
createdAt,
discriminator,
id,
game,
username,
status,
}) => {
return (
<Item className={styles['container']}>
<Image src={`https://cdn.discordapp.com/avatars/${id}/${avatar}.jpg`} avatar />
<Item.Content>
<Item.Header>
{/*<span style={{color: userRoleColor}}>{ username }</span>*/}
<span>{ username }</span>
<span className={styles['discriminator']}>{ discriminator }</span>
</Item.Header>
</Item.Content>
</Item>
)
}
export default observer(UserInfo);
|
src/components/containers/sidebar-layout-container.js | HuangXingBin/goldenEast | import React from 'react';
import { connect } from 'react-redux';
import store from '../../store';
import styles from '../../app.less';
import { Link } from 'react-router';
import { sidebarCollapse } from '../../actions/app-interaction-actions';
import imgSrc from '../../appConstants/assets/images/logo_white.png';
import { Menu, Icon } from 'antd';
import { routeBase } from '../../appConstants/urlConfig';
const SubMenu = Menu.SubMenu;
const SidebarLayoutContainer = React.createClass({
onCollapseChange() {
store.dispatch(sidebarCollapse());
},
//匹配的导航列表
matchSubMenu(pathName) {
const subMenuArray = {
'sub1' : ['/home', '/user_list','register_active'],
'sub2' : [ '/author_user_list', '/allot_user_list','hongbao_list'],
'sub3_1' : ['/chuan_shang_board_market', '/shen_wen_suo_board_market'],
'sub3_2' : ['/shenwensuo_wp', '/jishang_wp', '/yueguoji_wp'],
'sub3_3' : ['/chuan_shang_post_card', '/ji_shang_post_card'],
'sub4' : ['/board_market_brokerage', '/wp_brokerage','/post_card_brokerage','/post_card_brokerage'],
'sub5' : ['/board_market_post_card_dredge_schedule'],
'sub6' : ['/info_asset_allot_list', '/gain_info_asset_allot_list'],
'sub7' : ['under_user','under_user_tree'],
};
let matchSubMenu = '';
let defaultSelectedKey = '';
for (let i in subMenuArray) {
// console.log('iiiiiii', i);
subMenuArray[i].forEach(function (ownPathName) {
// console.log('ownPathName', ownPathName.slice(0, 6));
if (ownPathName.slice(0, 5) == pathName.slice(0, 5)) {
matchSubMenu = i;
defaultSelectedKey = ownPathName;
// console.log('hey!', i);
}
})
}
console.log('aaaaaaaaa', [matchSubMenu, defaultSelectedKey]);
return [matchSubMenu, defaultSelectedKey];
},
render() {
const collapse = this.props.collapse;
const sidebarWrapperName = collapse ? 'sidebarWrapperCollapse' : 'sidebarWrapper';
const mode = collapse ? 'vertical' : 'inline';
// const pathName = window.location.pathname;
const pathName = window.location.hash.slice(1, 6);
// console.log('bbbbbbb', pathName);
const matchSubMenu = this.matchSubMenu(pathName);
//console.log('matchSubMenu', matchSubMenu);
return (
<div className={styles[sidebarWrapperName]} style={{transition: 'all 0.3s ease'}}>
<div className={styles.logo}>
<Link to={routeBase}>
<img src={imgSrc} alt="logo"/>
</Link>
</div>
<Menu mode={mode}
defaultSelectedKeys={[matchSubMenu[1]]} defaultOpenKeys={[matchSubMenu[0]]}>
<SubMenu key="sub1" title={<span><Icon type="home" /><span className={styles.navText}>居间商</span></span>}>
<Menu.Item key={routeBase + 'home'}>
<Link to={routeBase + 'home'}>
用户数据总览
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'user_list'}>
<Link to={routeBase + 'user_list'}>
用户列表
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'hongbao_list'}>
<Link to={routeBase + 'hongbao_list'}>
红包列表
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'register_active'}>
<Link to={routeBase + 'register_active'}>
旗下代理商数据
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub3" title={<span><Icon type="pay-circle-o" /><span className={styles.navText}>交易列表</span></span>}>
<SubMenu key="sub3_1" title={<span><Icon type="bar-chart" /><span className={styles.navText}>大盘交易列表</span></span>}>
<Menu.Item key={routeBase + 'shen_wen_suo_board_market'}>
<Link to={routeBase + 'shen_wen_suo_board_market'}>
深文所大盘
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'chuan_shang_board_market'}>
<Link to={routeBase + 'chuan_shang_board_market'}>
川商大盘
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub3_2" title={<span><Icon type="line-chart" /><span className={styles.navText}>微盘交易列表</span></span>}>
<Menu.Item key={routeBase + 'shenwensuo_wp'}>
<Link to={routeBase + 'shenwensuo_wp'}>
深文所微盘
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'jishang_wp'}>
<Link to={routeBase + 'jishang_wp'}>
吉商微盘
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'yueguoji_wp'}>
<Link to={routeBase + 'yueguoji_wp'}>
粤国际微盘
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub3_3" title={<span><Icon type="dot-chart" /><span className={styles.navText}>邮币卡交易列表</span></span>}>
<Menu.Item key={routeBase + 'chuan_shang_post_card'}>
<Link to={routeBase + 'chuan_shang_post_card'}>
川商邮币卡
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'ji_shang_post_card'}>
<Link to={routeBase + 'ji_shang_post_card'}>
吉商邮币卡
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub3_4" title={<span><Icon type="bar-chart" /><span className={styles.navText}>保险交易列表</span></span>}>
<Menu.Item key={routeBase + 'taipingyang_insurance'}>
<Link to={routeBase + 'taipingyang_insurance'}>
太平洋保险
</Link>
</Menu.Item>
</SubMenu>
</SubMenu>
<SubMenu key="sub4" title={<span><Icon type="pay-circle" /><span className={styles.navText}>佣金列表</span></span>}>
<Menu.Item key={routeBase + 'board_market_brokerage'}>
<Link to={routeBase + 'board_market_brokerage'}>
大盘佣金列表
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'wp_brokerage'}>
<Link to={routeBase + 'wp_brokerage'}>
微盘佣金列表
</Link>
</Menu.Item>
{/* <Menu.Item key={routeBase + 'post_card_brokerage'}>
<Link to={routeBase + 'post_card_brokerage'}>
邮币卡佣金列表
</Link>
</Menu.Item>*/}
</SubMenu>
<SubMenu key="sub5" title={<span><Icon type="pie-chart" /><span className={styles.navText}>大盘、邮币卡开户进度</span></span>}>
<Menu.Item key={routeBase + 'open_account_progress'}>
<Link to={routeBase + 'open_account_progress'}>
大盘、邮币卡开户进度
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub6" title={<span><Icon type="solution" /><span className={styles.navText}>信息资产分配</span></span>}>
<Menu.Item key={routeBase + 'info_asset_allot_list'}>
<Link to={routeBase + 'info_asset_allot_list'}>
信息资产分配详情
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'gain_info_asset_allot_list'}>
<Link to={routeBase + 'gain_info_asset_allot_list'}>
已获得信息资产详情
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub7" title={<span><Icon type="team" /><span className={styles.navText}>人脉查询</span></span>}>
<Menu.Item key={routeBase + 'under_user_tree'}>
<Link to={routeBase + 'under_user_tree'}>
名下用户信息
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'under_user'}>
<Link to={routeBase + 'under_user'}>
一度人脉列表
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub2" title={<span><Icon type="share-alt" /><span className={styles.navText}>权限分配列表</span></span>}>
<Menu.Item key={routeBase + 'allot_user_list'}>
<Link to={routeBase + 'allot_user_list'}>
分配用户权限
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'author_user_list'}>
<Link to={routeBase + 'author_user_list'}>
已授权用户
</Link>
</Menu.Item>
</SubMenu>
<SubMenu key="sub8" title={<span><Icon type="select" /><span className={styles.navText}>其他</span></span>}>
<Menu.Item key={routeBase + 'shen_wen_suo_voucher_list'}>
<Link to={routeBase + 'shen_wen_suo_voucher_list'}>
深文所入金送体验券列表
</Link>
</Menu.Item>
<Menu.Item key={routeBase + 'download_center_list'}>
<Link to={routeBase + 'download_center_list'}>
下载中心
</Link>
</Menu.Item>
</SubMenu>
</Menu>
<div className={styles.antAsideAction} onClick={this.onCollapseChange}>
{collapse ? <Icon type="right" /> : <Icon type="left" />}
</div>
</div>
)
}
});
function mapStateToProps(store) {
return {
collapse : store.appInteractionState.sidebarCollapse
}
}
export default connect(mapStateToProps)(SidebarLayoutContainer); |
src/components/Inspector/Trackers/index.js | Secretmapper/react-transmission | import React from 'react';
import CSSModules from 'react-css-modules';
import TrackerGroup from './TrackerGroup';
import styles from './styles/index.css';
function Trackers({ info }) {
return (
<div>
{info.trackers.map(({ name, trackers }, index) => (
<div key={index}>
{info.trackers.length > 1 && <p>{name}</p>}
<TrackerGroup trackers={trackers} />
</div>
))}
</div>
);
}
export default CSSModules(styles)(Trackers);
|
docs/src/pages/index.js | evanlucas/node-tap | import React from 'react';
import Navbar from '../components/navbar';
import Hero from '../components/home/hero';
import Features from '../components/home/features';
import WhyTap from '../components/home/whyTap';
import Credits from '../components/home/credits';
import {ThemeProvider} from 'styled-components';
import {graphql} from 'gatsby';
import {theme} from '../theme';
import SEO from '../components/seo';
export default ({data}) => {
return (
<>
<SEO />
<ThemeProvider theme={theme}>
<div>
<Navbar/>
<Hero/>
<Features/>
<WhyTap markdownData={data.markdownRemark.html}/>
<Credits/>
</div>
</ThemeProvider>
</>
);
};
export const query = graphql`
query MyQuery {
markdownRemark(frontmatter: {title: {eq: "why-tap"}}) {
id
html
}
}
`;
|
admin/client/App/shared/AlertMessages.js | creynders/keystone | import React from 'react';
import { Alert } from 'elemental';
import { upcase } from '../../utils/string';
/**
* This renders alerts for API success and error responses.
* Error format: {
* error: 'validation errors' // The unique error type identifier
* detail: { ... } // Optional details specific to that error type
* }
* Success format: {
* success: 'item updated', // The unique success type identifier
* details: { ... } // Optional details specific to that success type
* }
* Eventually success and error responses should be handled individually
* based on their type. For example: validation errors should be displayed next
* to each invalid field and signin errors should promt the user to sign in.
*/
var AlertMessages = React.createClass({
displayName: 'AlertMessages',
propTypes: {
alerts: React.PropTypes.shape({
error: React.PropTypes.Object,
success: React.PropTypes.Object,
}),
},
getDefaultProps () {
return {
alerts: {},
};
},
renderValidationErrors () {
let errors = this.props.alerts.error.detail;
if (errors.name === 'ValidationError') {
errors = errors.errors;
}
let errorCount = Object.keys(errors).length;
let alertContent;
let messages = Object.keys(errors).map((path) => {
if (errorCount > 1) {
return (
<li key={path}>
{upcase(errors[path].error || errors[path].message)}
</li>
);
} else {
return (
<div key={path}>
{upcase(errors[path].error || errors[path].message)}
</div>
);
}
});
if (errorCount > 1) {
alertContent = (
<div>
<h4>There were {errorCount} errors creating the new item:</h4>
<ul>{messages}</ul>
</div>
);
} else {
alertContent = messages;
}
return <Alert type="danger">{alertContent}</Alert>;
},
render () {
let { error, success } = this.props.alerts;
if (error) {
// Render error alerts
switch (error.error) {
case 'validation errors':
return this.renderValidationErrors();
case 'error':
if (error.detail.name === 'ValidationError') {
return this.renderValidationErrors();
} else {
return <Alert type="danger">{upcase(error.error)}</Alert>;
}
default:
return <Alert type="danger">{upcase(error.error)}</Alert>;
}
}
if (success) {
// Render success alerts
return <Alert type="success">{upcase(success.success)}</Alert>;
}
return null; // No alerts, render nothing
},
});
module.exports = AlertMessages;
|
src/components/results/result/Result.js | jahuk/bet-platform-react | import React from 'react';
import {Link} from 'react-router';
const Result = ({id, home, away, result}) => (
<tr>
<td>{home}</td>
<td>{result}</td>
<td>{away}</td>
<td><Link className="badge" to={{pathname: `/match/${id}`}}>GO</Link></td>
</tr>
);
Result.propTypes = {
id: React.PropTypes.number,
home: React.PropTypes.string,
away: React.PropTypes.string,
result: React.PropTypes.string
};
export default Result;
|
src/views/App.js | isaaguilar/pumpkin-basket | import React from 'react'
import { hashHistory } from 'react-router'
import { Link, withRouter } from 'react-router'
import { connect } from 'react-redux'
import AppBar from 'material-ui/AppBar'
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import FlatButton from 'material-ui/FlatButton';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import NavigationClose from 'material-ui/svg-icons/navigation/close';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import { orange800 } from 'material-ui/styles/colors';
import {List, ListItem} from 'material-ui/List';
import Drawer from 'material-ui/Drawer';
import RaisedButton from 'material-ui/RaisedButton';
import ArrowBack from "material-ui/svg-icons/navigation/arrow-back"
import Paper from 'material-ui/Paper'
import NavLink from './NavLink'
import MenuItemLink from './MenuItemLink'
import { meFromToken, logMeOut } from '../actions/loginActions'
const muiTheme = getMuiTheme({
palette: {
primary1Color: orange800,
},
});
class Logged extends React.Component {
constructor(props) {
super(props);
this.state = {
status: 'Logout'
}
}
goSomewhere(linkRoute, evt) {
hashHistory.push(linkRoute)
}
render(){
return (
<IconMenu
iconButtonElement={
<IconButton iconStyle={{color:"white"}}>
<MoreVertIcon />
</IconButton>
}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
>
<MenuItem
primaryText="Home"
onTouchTap={this.goSomewhere.bind(this, "/")}
/>
<MenuItem
primaryText="About"
onTouchTap={this.goSomewhere.bind(this, "/about")}
/>
{this.props.authenticated ? (
<MenuItem
primaryText="Logout"
onTouchTap={this.goSomewhere.bind(this, "/login")}
/>
) : (
<MenuItem
primaryText="Login"
onTouchTap={this.goSomewhere.bind(this, "/login")}
/>
)}
</IconMenu>
)
}
}
@connect((store) => {
return {
authenticated: store.login.authenticated,
}
})
export default class App extends React.Component{
constructor(props) {
super(props);
this.state = {open: false};
}
handleToggle() {
this.setState({open: !this.state.open});
}
render() {
let mainTitle = (
<Link
to="/"
style={{
fontWeight: "lighter",
textDecoration:"none",
color: "white",
fontSize: "22px"
}}
>
The Pumpkin Basket
</Link>
)
let menuTitle = (
<div>
<p
style={{
fontWeight: "lighter",
textDecoration:"none",
color: "white",
fontSize: "22px"
}}
>
Menu
</p>
</div>
)
let appBarMenu = <Logged authenticated={this.props.authenticated}/>
return (
<div>
<MuiThemeProvider muiTheme={muiTheme}>
<div>
<AppBar
title={mainTitle}
// showMenuIconButton={false}
onLeftIconButtonTouchTap={this.handleToggle.bind(this)}
// iconElementRight={appBarMenu}
/>
<Drawer
open={this.state.open}
docked={false}
onRequestChange={(open) => this.setState({open})}
>
<AppBar
title={menuTitle}
iconElementRight={
<IconButton
iconStyle={{color:"white"}}
>
<ArrowBack color="white" />
</IconButton>
}
showMenuIconButton={false}
onTouchTap={this.handleToggle.bind(this)}
/>
<Paper
zDepth={0}
onTouchTap={this.handleToggle.bind(this)}
>
<NavLink
to="/"
primaryText="My Basket"
active={this.props.pathname}
/>
<NavLink
to="/login"
primaryText="Sign in"
active={this.props.pathname}
/>
<NavLink
to="/about"
primaryText="About"
active={this.props.pathname}
/>
</Paper>
</Drawer>
</div>
</MuiThemeProvider>
{this.props.children}
</div>
)
}
}
|
src/components/login-register/Login.js | ariroseonline/bargame | import React from 'react';
var Login = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getInitialState: function(){
return {
error: false
}
},
handleGoogle: function() {
var provider = new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then((result)=> {
// This gives you a Google Access Token. You can use it to access the Google API.
var token = result.credential.accessToken;
var location = this.props.location
if (location.state && location.state.nextPathname) {
this.context.router.replace(location.state.nextPathname)
} else {
this.context.router.replace('/challenges')
}
}).catch((error)=> {
console.log('ERROr', error)
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
// ...
this.setState({error: error.message})
});
},
handleSubmit: function(e){
e.preventDefault();
var email = this.refs.email.value;
var pw = this.refs.pw.value;
firebase.auth().signInWithEmailAndPassword(email, pw).then((result)=> {
var location = this.props.location
if (location.state && location.state.nextPathname) {
this.context.router.replace(location.state.nextPathname)
} else {
this.context.router.replace('/challenges')
}
// User signed in!
console.log('User signed in!');
// var uid = result.user.uid;
}).catch((error)=> {
this.setState({error: error});
});
},
render: function(){
var errors = this.state.error ? <p> {this.state.error} </p> : '';
return (
<div className="col-sm-6 col-sm-offset-3">
<h1> Login </h1>
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label> Email </label>
<input className="form-control" ref="email" placeholder="Email"/>
</div>
<div className="form-group">
<label>Password</label>
<input ref="pw" type="password" className="form-control" placeholder="Password" />
</div>
{errors}
<button type="submit" className="btn btn-primary">Login</button>
</form>
<span>OR</span>
<button onClick={this.handleGoogle}>GOOGLE LOGIN</button>
</div>
);
}
});
export default Login;
|
spec/coffeescripts/react_files/components/RestrictedDialogFormSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2014 - 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 mockFilesENV from '../mockFilesENV'
import React from 'react'
import ReactDOM from 'react-dom'
import {Simulate} from 'react-dom/test-utils'
import $ from 'jquery'
import RestrictedDialogForm from 'jsx/files/RestrictedDialogForm'
import Folder from 'compiled/models/Folder'
QUnit.module('RestrictedDialogForm Multiple Selected Items', {
setup() {
const props = {
models: [
new Folder({
id: 1000,
hidden: false
}),
new Folder({
id: 999,
hidden: true
})
]
}
this.restrictedDialogForm = ReactDOM.render(
<RestrictedDialogForm {...props} />,
$('<div>').appendTo('#fixtures')[0]
)
},
teardown() {
$('#fixtures').empty()
}
})
test('button is disabled but becomes enabled when you select an item', function() {
equal(this.restrictedDialogForm.updateBtn.disabled, true, 'starts off as disabled')
this.restrictedDialogForm.restrictedSelection.publishInput.checked = true
Simulate.change(this.restrictedDialogForm.restrictedSelection.publishInput)
equal(
this.restrictedDialogForm.updateBtn.disabled,
false,
'is enabled after an option is selected'
)
})
QUnit.module('RestrictedDialogForm#handleSubmit', {
setup() {
const props = {
models: [
new Folder({
id: 999,
hidden: true,
lock_at: undefined,
unlock_at: undefined
})
]
}
this.restrictedDialogForm = ReactDOM.render(
<RestrictedDialogForm {...props} />,
$('<div>').appendTo('#fixtures')[0]
)
},
teardown() {
$('#fixtures').empty()
}
})
test('calls save on the model with only hidden if calendarOption is false', function() {
const stubbedSave = sandbox.spy(this.restrictedDialogForm.props.models[0], 'save')
Simulate.submit(this.restrictedDialogForm.dialogForm)
ok(
stubbedSave.calledWithMatch({}, {attrs: {hidden: true}}),
'Called save with single hidden true attribute'
)
})
test(
'calls save on the model with calendar should update hidden, unlock_at, lock_at and locked',
1,
function() {
const refs = this.restrictedDialogForm
this.restrictedDialogForm.restrictedSelection.setState({selectedOption: 'date_range'})
const startDate = new Date(2016, 5, 1)
const endDate = new Date(2016, 5, 4)
$(refs.restrictedSelection.unlock_at).data('unfudged-date', startDate)
$(refs.restrictedSelection.lock_at).data('unfudged-date', endDate)
const stubbedSave = sandbox.spy(this.restrictedDialogForm.props.models[0], 'save')
Simulate.submit(refs.dialogForm)
ok(
stubbedSave.calledWithMatch(
{},
{
attrs: {
hidden: false,
lock_at: endDate,
unlock_at: startDate,
locked: false
}
}
),
'Called save with lock_at, unlock_at and locked attributes'
)
}
)
test('accepts blank unlock_at date', function() {
const refs = this.restrictedDialogForm
this.restrictedDialogForm.restrictedSelection.setState({selectedOption: 'date_range'})
const endDate = new Date(2016, 5, 4)
$(refs.restrictedSelection.unlock_at).data('unfudged-date', null)
$(refs.restrictedSelection.lock_at).data('unfudged-date', endDate)
const stubbedSave = sandbox.spy(this.restrictedDialogForm.props.models[0], 'save')
Simulate.submit(refs.dialogForm)
ok(
stubbedSave.calledWithMatch(
{},
{
attrs: {
hidden: false,
lock_at: endDate,
unlock_at: '',
locked: false
}
}
),
'Accepts blank unlock_at date'
)
})
test('accepts blank lock_at date', function() {
const refs = this.restrictedDialogForm
this.restrictedDialogForm.restrictedSelection.setState({selectedOption: 'date_range'})
const startDate = new Date(2016, 5, 4)
$(refs.restrictedSelection.unlock_at).data('unfudged-date', startDate)
$(refs.restrictedSelection.lock_at).data('unfudged-date', null)
const stubbedSave = sandbox.spy(this.restrictedDialogForm.props.models[0], 'save')
Simulate.submit(refs.dialogForm)
ok(
stubbedSave.calledWithMatch(
{},
{
attrs: {
hidden: false,
lock_at: '',
unlock_at: startDate,
locked: false
}
}
),
'Accepts blank lock_at date'
)
})
test('rejects unlock_at date after lock_at date', function() {
const refs = this.restrictedDialogForm
this.restrictedDialogForm.restrictedSelection.setState({selectedOption: 'date_range'})
const startDate = new Date(2016, 5, 4)
const endDate = new Date(2016, 5, 1)
$(refs.restrictedSelection.unlock_at).data('unfudged-date', startDate)
$(refs.restrictedSelection.lock_at).data('unfudged-date', endDate)
const stubbedSave = sandbox.spy(this.restrictedDialogForm.props.models[0], 'save')
Simulate.submit(refs.dialogForm)
equal(stubbedSave.callCount, 0)
})
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | alejandro-panos/AngularHeroes | 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'));
|
es/components/toolbar/toolbar-load-button.js | dearkaran/react-planner | import React from 'react';
import PropTypes from 'prop-types';
import IconLoad from 'react-icons/lib/fa/folder-open-o';
import ToolbarButton from './toolbar-button';
import { browserUpload } from '../../utils/browser';
export default function ToolbarLoadButton(_ref, _ref2) {
var state = _ref.state;
var translator = _ref2.translator,
projectActions = _ref2.projectActions;
var loadProjectFromFile = function loadProjectFromFile(event) {
event.preventDefault();
browserUpload().then(function (data) {
projectActions.loadProject(JSON.parse(data));
});
};
return React.createElement(
ToolbarButton,
{ active: false, tooltip: translator.t("Load project"), onClick: loadProjectFromFile },
React.createElement(IconLoad, null)
);
}
ToolbarLoadButton.propTypes = {
state: PropTypes.object.isRequired
};
ToolbarLoadButton.contextTypes = {
projectActions: PropTypes.object.isRequired,
translator: PropTypes.object.isRequired
}; |
src/app/component/offer-card/offer-card.js | all3dp/printing-engine-client | import PropTypes from 'prop-types'
import React from 'react'
import propTypes from '../../prop-types'
import buildClassName from '../../lib/class-names'
const OfferCard = ({
classNames,
label,
value,
recommendation,
sublineLeft,
sublineRight,
children,
action
}) => (
<div className={buildClassName('OfferCard', {recommendation}, classNames)}>
{recommendation && <div className="OfferCard__recommendation">{recommendation}</div>}
<div className="OfferCard__boxContent">
<div className="OfferCard__split">
<strong className="OfferCard__label">{label}</strong>
<strong className="OfferCard__value">{value}</strong>
</div>
<div className="OfferCard__split">
<strong className="OfferCard__sublineLeft">{sublineLeft}</strong>
<strong className="OfferCard__sublineRight">{sublineRight}</strong>
</div>
<div className="OfferCard__descriptionList">{children}</div>
<div className="OfferCard__action">{action}</div>
</div>
</div>
)
OfferCard.propTypes = {
...propTypes.component,
recommendation: PropTypes.string,
label: PropTypes.string.isRequired,
value: PropTypes.node.isRequired,
sublineLeft: PropTypes.string.isRequired,
sublineRight: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
action: PropTypes.node.isRequired
}
export default OfferCard
|
src/Main.js | bcgodfrey91/tier-2 | import React, { Component } from 'react';
import { Router, IndexRoute, Route, browserHistory } from 'react-router';
import Nav from './NavBar';
class Main extends Component {
render(){
return(
<div>
<Nav />
<div>
{this.props.children}
</div>
</div>
)
}
}
export default Main
|
js/components/card/basic.js | LetsBuildSomething/vmag_mobile |
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, Card, CardItem, Text, Body, Left, Right } from 'native-base';
import { Actions } from 'react-native-router-flux';
import styles from './styles';
const {
popRoute,
} = actions;
class Basic extends Component {
static propTypes = {
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Basic Card</Title>
</Body>
<Right />
</Header>
<Content padder>
<Card style={styles.mb}>
<CardItem>
<Body>
<Text>
This is just a basic card with some text to boot. Like it? Keep Scrolling...
</Text>
</Body>
</CardItem>
</Card>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(Basic);
|
components/pages/Layout.js | freyconner24/Quizzly | "use strict";
import React from 'react'
import {browserHistory} from 'react-router'
import {Sidebar} from '../partials/Sidebar.js'
import {Header} from '../partials/Header.js'
import {ProfileModal} from '../partials/ProfileModal.js'
import {UrbanAirshipPush} from 'urban-airship-push'
export default class Layout extends React.Component {
constructor(props) {
super(props);
this.state = {
urbanAirshipPush: {},
showProfileModal: false,
course: {
id: -1,
title: "FAKE 101",
quizzes: [],
sections: []
},
term: {
id: -1,
season: {season: "Oalcoa"},
year: {year: "1398"},
},
terms: [],
user: {
courses: [],
email: "",
firstName: "",
lastName: "",
facultyId: "",
school: "",
id: -1
}
}
}
checkSession() {
return $.post('/session')
.then(function(user) {
console.log(user);
return user;
})
.fail(function() {
console.log("redirecting to entrance...");
browserHistory.push('/entrance');
});
}
componentDidMount() {
var me = this;
this.initPush();
this.checkSession()
.then(function(user) {
//TODO: might not be able to be /PROFESSOR/find/:id
return $.post('/' + user.type + '/find/' + user.id);
})
.then(function(user) {
console.log('user', user);
switch(user.type) {
case 'STUDENT':
me.addPusherListener();
var courseIds = [];
user.sections.map(function(section) {
courseIds.push(section.course);
});
$.post('/course/multifind', {ids: courseIds})
.then(function(courses) {
console.log('courseIds', courseIds);
console.log('courses', courses);
if(courses[0] != undefined) {
me.getCourseById(courses[0].id);
me.getTermsFromCourses(courses);
}
user.courses = courses;
me.setState({user: user});
});
break;
case 'PROFESSOR':
if(user.courses[0] != undefined) {
me.getCourseById(user.courses[0].id);
me.getTermsFromCourses(user.courses);
}
me.setState({user: user});
break;
}
});
}
addPusherListener() {
var me = this;
var pusher = new Pusher('638c5913fb91435e1b42', {
encrypted: true
});
var channel = pusher.subscribe('test_channel');
channel.bind('my_event', function(data) {
console.log("pusher data", data);
$.post('/section/find/' + data.sectionId)
.then(function(section) {
section.students.map(function(student) {
if(me.state.user.id == student.id) {
$.post('/studentanswer/find', {question: data.questionId, student: student.id})
.then(function(studentanswer) {
console.log(studentanswer);
if(studentanswer.length == 0) { // the student has not answered this question before
browserHistory.push('/s/question/' + data.questionId + "/" + data.sectionId);
}
});
}
});
});
});
}
getTermsFromCourses(courses) {
var me = this;
var termIds = [];
courses.map(function(course) {
termIds.push(course.term);
});
termIds = Utility.removeDuplicates(termIds);
return $.post('/term/multifind', {termIds: termIds})
.then(function(terms) {
console.log("terms", terms);
me.setState({
term: terms[0],
terms: terms
});
return terms;
});
}
initPush() {
var config = {
key: 'RpquxajkQKeLnupkBrvWtw',
secret: 'O8p2HuxVQBOrYaTersE5CA',
masterSecret: 'Lcay6AUkQXapKaztfYSJGw'
};
// Create a push object
// var urbanAirshipPush = new UrbanAirshipPush(config);
// this.setState({urbanAirshipPush: urbanAirshipPush});
}
getQuestion() {
var urbanAirshipPush = this.state.urbanAirshipPush;
UrbanAirship.getNotification(function(object) {
browserHistory("//" + object.question.id);
});
}
showProfileModal() {
this.setState({showProfileModal: true});
}
changeCourse(courseId) {
this.getCourseById(courseId);
}
getCourseById(courseId) {
var me = this;
return $.post('/course/find/' + courseId)
.then(function(course) {
if(course == undefined) return; // if there are no courses, then there are no sections
me.setState({course: course});
});
}
changeTerm(termId) {
var me = this;
this.getTermByTermId(termId)
.then(function() {
var courseId = -1;
me.state.user.courses.map(function(course) {
if(courseId == -1 && course.term == termId) {
courseId = course.id;
}
});
if(courseId == -1) return;
me.changeCourse(courseId);
});
}
getTermByTermId(termId) {
var me = this;
return $.post('/term/find/' + termId)
.then(function(term) {
if(term == undefined) return; // if there are no courses, then there are no sections
me.setState({term: term});
});
}
addCourseToProfessor(course, term) {
var me = this;
//TODO: add student array to section
for(var i = 0; i < course.sections.length; ++i) { // this removes empty answers from the array
if(course.sections[i].title.length == 0) {
course.sections.splice(i, 1);
--i;
}
}
console.log("user", this.state.user);
return $.post('/course/create/', {title: course.title, professor: this.state.user.id, sections: course.sections, term: term.id})
.then(function(course) {
console.log("created course", course);
var user = me.state.user;
course.quizzes = [];
course.sections = [];
user.courses.push(course);
var isNewTerm = true;
var terms = me.state.terms;
for(var i = 0; i < terms.length; ++i) {
if(terms[i].id == term.id) {
isNewTerm = false;
break;
}
}
if(isNewTerm) {
terms.push(term);
}
me.setState({
user: user,
course: course,
term: term,
terms: terms
});
return course;
});
}
addStudentsToSection(sectionId, studentIds) {
var me = this;
return $.post('/section/updateStudents/' + sectionId, {studentIds: studentIds})
.then(function(section) {
console.log("Updated section", section);
});
}
deleteCourseFromProfessor(course) {
console.log(">>>>>>>> deleting shit", course);
var me = this;
var sectionIds = [];
course.sections.map(function(section){sectionIds.push(section.id);});
var quizIds = [];
course.quizzes.map(function(quiz){quizIds.push(quiz.id);});
var questionIds = [];
var answerIds = [];
return $.post('/question/find', {quiz: quizIds})
.then(function(questions) {
console.log("questions", questions);
console.log("quizIds", quizIds);
questionIds = [];
questions.map(function(question){ questionIds.push(question.id);});
return $.post('/answer/find', {question: questionIds})
})
.then(function(answers) {
answerIds = [];
answers.map(function(answer){answerIds.push(answer.id);});
return $.post('/course/destroy', {id: course.id});
// return $.when(
// ,
// $.post('/section/multidestroy', {ids: sectionIds}),
// $.post('/quiz/multidestroy', {ids: quizIds}),
// $.post('/question/multidestroy', {ids: questionIds}),
// $.post('/answer/multidestroy', {ids: answerIds})
// );
})
.then(function() {
return $.post('/professor/find/' + me.state.user.id);
})
.then(function(user) {
console.log("DELETED------------", user);
var course = {};
if(user.courses.length == 0) {
course = {
id: -1,
title: "FAKE 101",
quizzes: [],
sections: []
};
} else {
course = user.courses[0];
}
me.getTermsFromCourses(user.courses);
me.setState({
course: course,
user: user
});
});
}
updateUser(user) {
var courses = this.state.user.courses;
user.courses = courses;
this.setState({user: user});
}
closeModal() {
this.setState({showProfileModal: false});
}
render() {
var me = this;
var props = {
course: me.state.course,
term: me.state.term,
};
switch(this.state.user.type) {
case 'STUDENT':
props.student = this.state.user
break;
case 'PROFESSOR':
props.addCourseToProfessor = me.addCourseToProfessor.bind(me);
props.deleteCourseFromProfessor = me.deleteCourseFromProfessor.bind(me);
props.addStudentsToSection = me.addStudentsToSection.bind(me);
break;
}
return (
<div id="quizzlyApp">
<Sidebar
user={this.state.user}
/>
<Header
course={this.state.course}
courses={this.state.user.courses}
term={this.state.term}
terms={this.state.terms}
user={this.state.user}
changeCourse={this.changeCourse.bind(this)}
changeTerm={this.changeTerm.bind(this)}
showProfileModal={this.showProfileModal.bind(this)}
/>
{React.Children.map(me.props.children, function (child) {
return React.cloneElement(child, props);
})}
{(() => {
var me = this;
if(this.state.showProfileModal) {
return (
<ProfileModal
user={this.state.user}
updateUser={this.updateUser.bind(this)}
closeModal={this.closeModal.bind(this)}
/>
);
}
})()}
</div>
)
}
}
|
pages/api/popover.js | cherniavskii/material-ui | import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './popover.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
client/components/FriendsPref.js | carlbernardo/gut | import React from 'react';
import { Button } from 'react-bootstrap';
//Components
import FriendsList from './FriendsList';
import SelectedFriends from './SelectedFriends';
class FriendsPref extends React.Component {
constructor(){
super();
this.displayRestaurantResults = this.displayRestaurantResults.bind(this);
this.displayButton = this.displayButton.bind(this);
}
componentWillMount(){
const { username } = this.props;
const { addToDiners } = this.props.dinerActions;
const { loadFriends } = this.props.friendActions;
addToDiners(username);
loadFriends(username);
}
displayRestaurantResults(e){
e.preventDefault();
const { displayResults } = this.props.viewActions;
displayResults();
}
displayButton(){
const { diners } = this.props;
if(diners.length > 1){
return(
<Button id='dine-alone' onClick={this.displayRestaurantResults}>Find us a table</Button>
)
} else {
return(
<Button id='dine-alone' onClick={this.displayRestaurantResults}>Table for one</Button>
)
}
}
render(){
if (this.props.location) {
return (
<div className='add-user-container col-md-12 col-xl-12'>
<div className='row row-eq-height'>
<div className='add-friends col-sm-12 col-md-6 col-xl-6'>
<h1>Select <span className='cursive'>pea-ps</span> to dine with</h1>
{this.displayButton()}
<SelectedFriends {...this.props} />
</div>
<div className='user-friends col-sm-12 col-md-6 col-xl-6'>
<FriendsList {...this.props} />
</div>
</div>
</div>
)
} else {
return (
<div className='spinner'>
<h1>Determining your <span className='cursive'>location</span>...</h1>
<image src='./../static/assets/spinner.gif' />
</div>
)
}
}
}
export default FriendsPref;
|
app/components/pages/About.js | shalomvolchok/isomorphic-react-base-app | /**
* Copyright 2015, Digital Optimization Group, LLC.
* Copyrights licensed under the APACHE 2 License. See the accompanying LICENSE file for terms.
*/
import React from 'react';
class About extends React.Component {
render() {
return (
<div className="container">
<h1>{this.props.aboutMsg}</h1>
</div>
);
}
}
About.propTypes = {
aboutMsg: React.PropTypes.string,
};
About.defaultProps = {
aboutMsg: "Hello and welcome to the about page."
};
export default About;
|
packages/material-ui-icons/src/SpaceBar.js | cherniavskii/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M18 9v4H6V9H4v6h16V9z" /></g>
, 'SpaceBar');
|
modules/RouterContext.js | taion/rrtr | import invariant from 'invariant'
import React from 'react'
import deprecateObjectProperties from './deprecateObjectProperties'
import getRouteParams from './getRouteParams'
import { isReactChildren } from './RouteUtils'
import warning from './routerWarning'
const { array, func, object } = React.PropTypes
/**
* A <RouterContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
const RouterContext = React.createClass({
propTypes: {
history: object,
router: object.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired,
createElement: func.isRequired
},
getDefaultProps() {
return {
createElement: React.createElement
}
},
childContextTypes: {
history: object,
location: object.isRequired,
router: object.isRequired
},
getChildContext() {
let { router, history, location } = this.props
if (!router) {
warning(false, '`<RouterContext>` expects a `router` rather than a `history`')
router = {
...history,
setRouteLeaveHook: history.listenBeforeLeavingRoute
}
delete router.listenBeforeLeavingRoute
}
if (__DEV__) {
location = deprecateObjectProperties(location, '`context.location` is deprecated, please use a route component\'s `props.location` instead. http://tiny.cc/router-accessinglocation')
}
return { history, location, router }
},
createElement(component, props) {
return component == null ? null : this.props.createElement(component, props)
},
render() {
const { history, location, routes, params, components } = this.props
let element = null
if (components) {
element = components.reduceRight((element, components, index) => {
if (components == null)
return element // Don't create new children; use the grandchildren.
const route = routes[index]
const routeParams = getRouteParams(route, params)
const props = {
history,
location,
params,
route,
routeParams,
routes
}
if (isReactChildren(element)) {
props.children = element
} else if (element) {
for (const prop in element)
if (Object.prototype.hasOwnProperty.call(element, prop))
props[prop] = element[prop]
}
if (typeof components === 'object') {
const elements = {}
for (const key in components) {
if (Object.prototype.hasOwnProperty.call(components, key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = this.createElement(components[key], {
key, ...props
})
}
}
return elements
}
return this.createElement(components, props)
}, element)
}
invariant(
element === null || element === false || React.isValidElement(element),
'The root route must render a single element'
)
return element
}
})
export default RouterContext
|
actor-apps/app-web/src/app/components/modals/Preferences.react.js | changjiashuai/actor-platform | import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
import PreferencesStore from 'stores/PreferencesStore';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const ThemeManager = new Styles.ThemeManager();
const getStateFromStores = () => {
return {
isOpen: PreferencesStore.isModalOpen()
};
};
@ReactMixin.decorate(IntlMixin)
class PreferencesModal extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
PreferencesStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
PreferencesStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
PreferencesActionCreators.hide();
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
render() {
let menuItems = [
{ payload: '1', text: 'English' },
{ payload: '2', text: 'Russian' }
];
if (this.state.isOpen === true) {
return (
<Modal className="modal-new modal-new--preferences"
closeTimeoutMS={150}
isOpen={this.state.isOpen}
style={{width: 760}}>
<div className="modal-new__header">
<i className="modal-new__header__icon material-icons">settings</i>
<h3 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/>
</h3>
<div className="pull-right">
<FlatButton hoverColor="rgba(81,145,219,.17)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onClose}
secondary={true}
style={{marginTop: -6}}/>
</div>
</div>
<div className="modal-new__body">
<div className="preferences">
<aside className="preferences__tabs">
<a className="preferences__tabs__tab preferences__tabs__tab--active">General</a>
<a className="preferences__tabs__tab">Notifications</a>
<a className="preferences__tabs__tab">Sidebar colors</a>
<a className="preferences__tabs__tab">Security</a>
<a className="preferences__tabs__tab">Other Options</a>
</aside>
<div className="preferences__body">
<div className="preferences__list">
<div className="preferences__list__item preferences__list__item--general">
<ul>
<li>
<i className="icon material-icons">keyboard</i>
<RadioButtonGroup defaultSelected="default" name="send">
<RadioButton label="Enter – send message, Shift + Enter – new line"
style={{marginBottom: 12}}
value="default"/>
<RadioButton label="Cmd + Enter – send message, Enter – new line"
//style={{marginBottom: 16}}
value="alt"/>
</RadioButtonGroup>
</li>
<li className="language">
<i className="icon material-icons">menu</i>
Language: <DropDownMenu labelStyle={{color: '#5191db'}}
menuItemStyle={{height: '40px', lineHeight: '40px'}}
menuItems={menuItems}
style={{verticalAlign: 'top', height: 52}}
underlineStyle={{display: 'none'}}/>
</li>
</ul>
</div>
<div className="preferences__list__item preferences__list__item--notifications">
<ul>
<li>
<i className="icon material-icons">notifications</i>
<RadioButtonGroup defaultSelected="all" name="notifications">
<RadioButton label="Notifications for activity of any kind"
style={{marginBottom: 12}}
value="all"/>
<RadioButton label="Notifications for Highlight Words and direct messages"
style={{marginBottom: 12}}
value="quiet"/>
<RadioButton label="Never send me notifications"
style={{marginBottom: 12}}
value="disable"/>
</RadioButtonGroup>
<p className="hint">
You can override your desktop notification preference on a case-by-case
basis for channels and groups from the channel or group menu.
</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default PreferencesModal;
|
src/components/pages/roomA/index.js | kcliu/chatroom-frontend | import React, { Component } from 'react';
import loremIpsum from 'lorem-ipsum';
import moment from 'moment';
import MessageBox from '../../common/MessageBox/index.js';
import MessageInput from '../../common/MessageInput/index.js';
import Message from '../..//common/Message/index.js';
import MembersBox from '../../common/MembersBox/index.js';
import Debug from '../../common/Debug/index.js';
import './styles.css';
const msgGengerator = (count, ids=[]) => {
// console.log("msgGengerator:", count, ids);
return [...Array(count).keys()].map(idx => {
const who = Math.floor(Math.random() * ids.length);
// console.log("index:", who);
return {
id: ids[who],
time: moment(moment.now()).format('h:mm A'),
text: loremIpsum({
count: 1,
units: 'sentences'
}),
}
})
}
const makeUser = (count) => {
return [...Array(count).keys()].map(user => {
const id = loremIpsum({
count: 1,
units: 'words'
})
return {
id,
avatar: `https://api.adorable.io/avatars/10/${id}.png`,
}
})
}
class RoomA extends Component {
state = {
members: [
{
id: 'kcliu',
avatar: `https://api.adorable.io/avatars/10/kcliu.png`,
}
],
messages: [],
me: {
id: 'kcliu',
avatar: `https://api.adorable.io/avatars/10/kcliu.png`,
},
}
sendText = (id, text, time) => {
return (text, time) => {
console.log("send text:", text, time);
const newList = [];
const myMessage = {
id,
text,
time,
}
newList.push(myMessage);
this.setState({
messages: this.state.messages.concat(newList),
})
}
}
sendMyText = this.sendText(this.state.me.id)
addUsers = (users) => {
// console.log("addUser:", users);
this.setState({
members: this.state.members.concat(users),
})
}
addMessages = (messages) => {
// console.log("addMessages:", messages);
this.setState({
messages: this.state.messages.concat(messages),
})
}
getAvatar = (id) => {
return this.state.members.filter(member => member.id === id)[0].avatar;
}
componentWillMount() {
}
componentDidMount() {
// const newMessages = msgGengerator(20, this.state.members.map(member => member.id));
// console.log(newMessages);
// this.addMessages(newMessages);
this.scrollToBottom();
}
scrollToBottom = () => {
const objDiv = document.getElementById("scroller");
objDiv.scrollTop = objDiv.scrollHeight;
}
render() {
console.log(this.state);
const { state } = this;
const messages = state.messages || [];
return (
<div className="room-container">
<Debug
memberIds={this.state.members.map(member => member.id)}
addMsgs={this.addMessages}
addUsers={this.addUsers}
/>
<MembersBox
members={state.members}
/>
<MessageBox>
{
messages.map((msg, i) => {
return (
<Message
avatar={this.getAvatar(msg.id)}
text={msg.text}
time={msg.time}
key={i}
/>
)
})
}
</MessageBox>
<MessageInput
sendText={this.sendMyText}
/>
</div>
);
}
}
export default RoomA;
|
src/Field.js | bradwestfall/informative | import React from 'react'
import PropTypes from 'prop-types'
import { InputField, CheckboxField, RadioField, SelectField, TextareaField } from './FieldTypes'
class Field extends React.Component {
constructor() {
super()
this.onChange = this.onChange.bind(this)
this.setupFieldState = this.setupFieldState.bind(this)
this.updateFieldState = this.updateFieldState.bind(this)
}
componentDidMount() {
const { name } = this.props
this.context.registerField(name, this.setupFieldState(this.props))
}
// Prop Change for `value`
componentWillReceiveProps(nextProps) {
if (nextProps.value === this.props.value && nextProps.checked === this.props.checked) return false
this.updateFieldState(this.setupFieldState(nextProps))
}
setupFieldState(props) {
// Peel off values to leave `restProps`
const { children, component, value, trim, format, ...restProps } = props
return {
// Normalize value before sending it to fieldState
value: (typeof value === 'boolean') ? String(value) : (value || ''),
// A formatter function for the value
format,
// Does the field's value get automatically trimmed
trim,
// Give original props to fieldState
props: { ...restProps, value }
}
}
// DOM Change
onChange(e) {
const { target } = e
const isCheckbox = target.type === 'checkbox'
let value = ''
if (isCheckbox) {
value = target.checked ? target.value : ''
} else {
value = target.value
}
this.updateFieldState({ value, dirty: true }, e)
}
updateFieldState(newState, e = {}) {
const { name, onChange } = this.props
this.context.setFieldState(name, newState, (fieldState, formState) => {
if (onChange) onChange(fieldState, formState, e) // call the field's onChange if the user provided one
this.context.onChange(name, e) // call the form's onChange if the user provided one
})
}
render() {
// Some of these variables aren't used. We just need to peel them off so we can get rest
const { render, component: Component, name, trim, format, value: originalValue, children, ...rest } = this.props
const formState = this.context.getFormState() || {}
const fieldState = formState.fields[name]
// Bail if name not provided
if (!name) throw new Error('the `name` prop must be provided to `<Field>`')
// Don't render if fieldState hasn't been setup
if (!fieldState) return null
// Event callbacks for every field
const events = {
onChange: this.onChange,
onFocus: e => this.context.setFieldState(name, { visited: true, active: true }),
onBlur: e => this.context.setFieldState(name, { active: false, touched: true })
}
// If <Field render={fn} /> is providing a field wrap by virtue of function
if (typeof render === 'function') {
return render(events, fieldState, formState)
// If <Field component="input" /> was passed a string "input" component
} else if (typeof Component === 'string' && Component.toLowerCase() === 'input') {
const type = this.props.type
switch(type) {
case 'checkbox': return <CheckboxField {...rest} name={name} originalValue={originalValue} fieldState={fieldState} events={events} />
case 'radio': return <RadioField {...rest} name={name} originalValue={originalValue} fieldState={fieldState} events={events} />
case 'text':
default: return <InputField {...rest} name={name} fieldState={fieldState} events={events} />
}
// If <Field component="[string]" /> was passed a string component
} else if (typeof Component === 'string') {
switch(Component) {
case 'textarea':
if (children) throw new Error('textarea fields use the `value` prop instead of children - https://facebook.github.io/react/docs/forms.html#the-textarea-tag')
return <TextareaField {...rest} name={name} fieldState={fieldState} events={events} />
case 'select': return <SelectField {...rest} name={name} fieldState={fieldState} events={events}>{children}</SelectField>
default: throw new Error('Invalid string value for `component` prop of <Field /> :', Component)
}
// If <Field component={CustomField} /> was passed a component prop with a custom component
} else if (typeof Component === 'function') {
return <Component {...rest} name={name} originalValue={originalValue} fieldState={fieldState} formState={formState} events={events}>{children}</Component>
// Only the above three are allowed
} else {
throw new Error('Field must have a `component` prop or `render` prop')
}
}
}
Field.contextTypes = {
registerField: PropTypes.func,
setFieldState: PropTypes.func,
getFormState: PropTypes.func,
onChange: PropTypes.func
}
Field.defaultProps = {
format: value => value
}
Field.propTypes = {
name: PropTypes.string.isRequired,
onChange: PropTypes.func,
format: PropTypes.func,
trim: PropTypes.bool
}
export default Field
|
src/slides/iterators.js | philpl/talk-observe-the-future | import React from 'react'
import { Slide, Text, CodePane } from 'spectacle'
import { codeBackground } from '../constants/colors'
import iterator from '~/assets/iterator.example'
export default (
<Slide transition={[ 'slide' ]}>
<Text
textColor='tertiary'
textSize='1.8em'
margin='30px'>
Iterators
</Text>
<CodePane
lang='javascript'
textSize='0.7em'
bgColor={codeBackground}
source={iterator}/>
</Slide>
)
|
src/pages/Admin/Assets/Assets.js | muhammadsayuti/releasify-server | import React from 'react'
import moment from 'moment'
import PropTypes from 'prop-types'
import Table from '@material-ui/core/Table'
import TableRow from '@material-ui/core/TableRow'
import TableBody from '@material-ui/core/TableBody'
import TableCell from '@material-ui/core/TableCell'
import TableHead from '@material-ui/core/TableHead'
import { FormattedMessage } from 'react-intl'
import UploadIcon from '@material-ui/icons/CloudUpload'
import { isLoaded, isEmpty } from 'react-redux-firebase'
import Dialog from '@material-ui/core/Dialog'
import DialogTitle from '@material-ui/core/DialogTitle'
import DialogContent from '@material-ui/core/DialogContent'
import DialogActions from '@material-ui/core/DialogActions'
import InputLabel from '@material-ui/core/InputLabel'
import FormControl from '@material-ui/core/FormControl'
import Select from '@material-ui/core/NativeSelect'
import Button from '@material-ui/core/Button'
import TextField from '@material-ui/core/TextField'
import Typography from '@material-ui/core/Typography/Typography'
import AssetUtility from '../../../utils/asset'
import MetaHelper from '../../../utils/MetaHelper'
import { Page } from '../../../Releasify'
import { firebase } from './compose'
@Page({
admin: true,
name: 'assets',
title: 'Assets',
menu: {
key: 'assets',
icon: <UploadIcon />,
divider: 'bottom'
},
compose: [firebase]
})
@MetaHelper({
title: 'Admin - Assets'
})
class Assets extends React.Component {
static contextTypes = {
store: PropTypes.object.isRequired
}
state = {
items: [],
showDialog: false,
loadComplete: false,
productName: undefined,
versionName: undefined,
assetName: undefined,
editMode: false,
assetKey: undefined,
productKey: undefined,
versionKey: undefined,
platform: undefined,
progress: undefined,
platforms: [
{
value: 'windows_64',
label: 'Windows 64 bit'
},
{
value: 'windows_32',
label: 'Windows 32 bit'
},
{
value: 'osx_64',
label: 'OS X 64 bit'
},
{
value: 'linux_64',
label: 'Linux 64 bit'
},
{
value: 'linux_32',
label: 'Linux 32 bit'
}
],
products: [],
versions: []
}
componentDidMount() {
const productRef = this.props.firebase.ref('/products')
productRef.once('value', snapshot => {
let values = snapshot.val()
let products = Object.keys(values).map(key => {
return { label: values[key].name, value: key }
})
this.setState({ products })
})
const versionRef = this.props.firebase.ref('/versions')
versionRef.once('value', snapshot => {
let values = snapshot.val()
let versions = Object.keys(values).map(key => {
return { label: values[key].name, value: key }
})
this.setState({ versions })
})
this.assetRef = this.props.firebase.ref('/assets')
}
onSave = () => {
const file = this.file.files[0]
const product = this.state.productKey
const version = this.state.versionKey
const platform = this.state.platform
const assetName = this.state.assetName
this.uploadFile(file, this.state.productName, this.state.versionName).then(
metadata => {
var fileExt = file.name.split('.')[1]
var start = 0
var stop = file.size - 1
var blob = file.slice(start, stop + 1)
var hashPromise
if (fileExt === '.nupkg') {
// Calculate the hash of the file, as it is necessary for windows
// files
hashPromise = AssetUtility.getHash(blob)
} else if (fileExt === '.exe' || fileExt === '.zip') {
hashPromise = AssetUtility.getHash(blob, 'sha256')
} else {
hashPromise = Promise.resolve('')
}
hashPromise
.then(hash => {
const assetData = {
product,
hash,
platform,
name: assetName,
filetype: metadata.contentType,
version,
size: metadata.size,
downloadURL: metadata.downloadURL,
createdAt: moment().format(),
updatedAt: moment().format()
}
let assetKey = this.props.firebase
.ref()
.child('assets')
.push().key
if (this.state.editMode) {
assetKey = this.state.assetKey
}
let versionAssetKey = this.props.firebase
.ref('/versions')
.child('assets')
.push().key
/**
* make sure the key is a number because if it is not a number
* assets will become an object instead of array
*/
if (isNaN(versionAssetKey)) {
versionAssetKey = 0
}
let updates = {}
updates[`/assets/${assetKey}`] = assetData
updates[`/versions/${version}/assets/${versionAssetKey}`] = assetKey
return this.assetRef.update(updates)
})
.then(() => {
this.setState({
progress: undefined
})
this.toggleDialog()
})
.catch(err => {
console.error(err)
})
}
)
}
uploadFile(file, product, version) {
// let ext = file.name.split('.')
// ext = ext[ext.length - 1]
return new Promise((resolve, reject) => {
const path = `assets/${product}/${version}/${file.name}`
const uploadTask = this.props.firebase
.storage()
.ref(path)
.put(file)
uploadTask.on(
'state_changed',
snapshot => {
const progress =
(snapshot.bytesTransferred / snapshot.totalBytes) * 100
this.setState({ progress: progress })
},
error => {
this.setState({ progress: undefined })
console.error(error)
reject(error)
},
() => {
const downloadURL = uploadTask.snapshot.downloadURL
/**
* get reference to uploaded file and get the
* metadata to save it in database
*/
const ref = this.props.firebase.storage().ref(path)
ref.getMetadata().then(metadata => {
metadata.downloadURL = downloadURL
resolve(metadata)
})
}
)
})
}
onFileChanged = e => {
this.setState({ assetName: e.target.files[0].name })
}
onDelete = asset => {}
toggleDialog = () => {
this.setState({
assetName: '',
assetKey: '',
productKey: '',
versionKey: '',
platform: '',
editMode: false,
showDialog: !this.state.showDialog
})
}
toggleEditDialog = (asset, e) => {
this.setState({ showDialog: !this.state.showDialog, ...asset })
}
renderAssetTable(assets) {
console.log('assets', assets)
if (assets && typeof assets === 'object') {
if (
typeof assets[Object.keys(assets)[0]].product == 'string' ||
typeof assets[Object.keys(assets)[0]].version == 'string' ||
this.state.versions.length < 1 ||
this.state.products.length < 1
) {
return (
<TableRow>
<TableCell colSpan={6} className="empty-row">
<FormattedMessage id="loading" defaultMessage="Loading" />
</TableCell>
</TableRow>
)
}
return Object.keys(assets).map((key, i) => {
const platform = this.state.platforms.filter(p => {
return p.value === assets[key].platform
})
const productKey = this.state.products.filter(product => {
return product.label === assets[key].product.name
})
const versionKey = this.state.versions.filter(v => {
return v.label === assets[key].version.name
})
const assetRefKey = {
assetName: assets[key].name,
assetKey: key,
productKey: productKey[0].value,
versionKey: versionKey[0].value,
platform: platform[0].value
}
return (
<TableRow key={key}>
<TableCell>{i + 1}</TableCell>
<TableCell>{assets[key].product.name}</TableCell>
<TableCell>{assets[key].version.name}</TableCell>
<TableCell>{assets[key].name}</TableCell>
<TableCell>{platform[0].label}</TableCell>
<TableCell>
{assets[key].downloadCount ? assets[key].downloadCount : 0}
</TableCell>
<TableCell className="btn-column">
<Button
color="primary"
variant="raised"
style={{ marginRight: '10px' }}
onClick={this.toggleEditDialog.bind(this, assetRefKey)}>
<Typography color="secondary">
<FormattedMessage id="edit" defaultMessage="Edit" />
</Typography>
</Button>
<Button
color="primary"
variant="raised"
onClick={this.onDelete.bind(this, [key])}>
<Typography color="secondary">
<FormattedMessage id="delete" defaultMessage="Delete" />
</Typography>
</Button>
</TableCell>
</TableRow>
)
})
}
return null
}
render() {
const { assets } = this.props
return (
<div className="animated fadeIn main-content">
<div className="box box-primary">
<div className="box-header with-border">
<h3 className="box-title">
<span>
<FormattedMessage id="assets" defaultMessage="Assets" />
</span>
</h3>
<div className="box-tools pull-right">
<button
className="btn btn-box-tool"
title="Add New Product"
onClick={this.toggleDialog}>
<i className="fa fa-plus" />
</button>
</div>
</div>
<div className="box-body">
<Table className="table">
<TableHead>
<TableRow>
<TableCell>
<FormattedMessage id="number" defaultMessage="No." />
</TableCell>
<TableCell>
<FormattedMessage
id="product-name"
defaultMessage="Product Name"
/>
</TableCell>
<TableCell>
<FormattedMessage
id="version-name"
defaultMessage="Version Name"
/>
</TableCell>
<TableCell>
<FormattedMessage id="filename" defaultMessage="Filename" />
</TableCell>
<TableCell>
<FormattedMessage id="platform" defaultMessage="Platform" />
</TableCell>
<TableCell>
<FormattedMessage
id="downloads"
defaultMessage="Downloads"
/>
</TableCell>
<TableCell className="btn-column" />
</TableRow>
</TableHead>
<TableBody>
{!isLoaded(assets) ? (
<TableRow>
<TableCell colSpan={6} className="empty-row">
<FormattedMessage id="loading" defaultMessage="Loading" />
</TableCell>
</TableRow>
) : isEmpty(assets) ? (
<TableRow>
<TableCell colSpan={5} className="empty-row">
<FormattedMessage
id="no-data-found"
defaultMessage="No Data Found"
/>
</TableCell>
</TableRow>
) : (
this.renderAssetTable(assets)
)}
</TableBody>
</Table>
</div>
</div>
<Dialog open={this.state.showDialog} style={{ visibility: 'visible' }}>
<DialogTitle>
<FormattedMessage
id="add-new-asset"
defaultMessage="Add New Asset"
/>
</DialogTitle>
<DialogContent>
<TextField
fullWidth
id="assetName"
label="Asset Name"
value={this.state.assetName}
disabled
/>
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="product-name">
<FormattedMessage
id="product-name"
defaultMessage="Product Name"
/>
</InputLabel>
<Select
fullWidth
value={this.state.productKey}
inputProps={{ id: 'product-name' }}
// input={<Input name="name" />}
onChange={e => {
this.setState({ productKey: e.target.value })
}}>
<option value="" />
{this.state.products.map((product, index) => {
return (
<option key={index} value={product.value}>
{product.label}
</option>
)
})}
</Select>
</FormControl>
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="version">
<FormattedMessage id="version" defaultMessage="Version" />
</InputLabel>
<Select
fullWidth
value={this.state.versionKey}
inputProps={{ id: 'version' }}
onChange={e => {
this.setState({ versionKey: e.target.value })
}}>
<option value="" />
{this.state.versions.map((version, index) => {
return (
<option key={index} value={version.value}>
{version.label}
</option>
)
})}
</Select>
</FormControl>
<FormControl fullWidth margin="normal">
<InputLabel htmlFor="platform">
<FormattedMessage id="platform" defaultMessage="Platform" />
</InputLabel>
<Select
fullWidth
value={this.state.platform}
inputProps={{ id: 'platform' }}
onChange={e => {
this.setState({ platform: e.target.value })
}}>
<option value="" />
{this.state.platforms.map((platform, index) => {
return (
<option key={index} value={platform.value}>
{platform.label}
</option>
)
})}
</Select>
</FormControl>
<TextField
style={{ marginTop: '15px' }}
fullWidth
type="file"
label="File"
ref={el => (this.file = el)}
InputLabelProps={{ shrink: true }}
InputProps={{ disableUnderline: true }}
/>
{/* <div className="form-group">
<label className="col-md-2 control-label text-left" style={{ paddingLeft: '20px', textAlign: 'left' }}>File </label>
<div className="col-md-10">
<input className="form-control" type="file" ref="file" id="file" onChange={this.onFileChanged} />
</div>
</div> */}
</DialogContent>
<DialogActions>
<Button onClick={this.onSave}>
<FormattedMessage id="save" defaultMessage="Save" />
</Button>
<Button onClick={this.toggleDialog}>
<FormattedMessage id="cancel" defaultMessage="Cancel" />
</Button>
</DialogActions>
</Dialog>
</div>
)
}
}
export default Assets
|
apps/marketplace/components/Alerts/ErrorAlert.js | AusDTO/dto-digitalmarketplace-frontend | import React from 'react'
import PropTypes from 'prop-types'
import { Errors } from 'react-redux-form'
import PageAlertError from './PageAlertError'
const ErrorAlert = props => {
const { messages, model } = props
return (
<Errors
model={model}
show={field => field.touched && !field.focus}
messages={messages}
component="li"
wrapper={PageAlertError}
/>
)
}
ErrorAlert.defaultProps = {
messages: {}
}
ErrorAlert.propTypes = {
model: PropTypes.string.isRequired,
messages: PropTypes.object
}
export default ErrorAlert
|
app/javascript/mastodon/features/ui/components/focal_point_modal.js | pixiv/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { connect } from 'react-redux';
import ImageLoader from './image_loader';
import classNames from 'classnames';
import { changeUploadCompose } from '../../../actions/compose';
import { getPointerPosition } from '../../video';
const mapStateToProps = (state, { id }) => ({
media: state.getIn(['compose', 'media_attachments']).find(item => item.get('id') === id),
});
const mapDispatchToProps = (dispatch, { id }) => ({
onSave: (x, y) => {
dispatch(changeUploadCompose(id, { focus: `${x.toFixed(2)},${y.toFixed(2)}` }));
},
});
@connect(mapStateToProps, mapDispatchToProps)
export default class FocalPointModal extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
};
state = {
x: 0,
y: 0,
focusX: 0,
focusY: 0,
dragging: false,
};
componentWillMount () {
this.updatePositionFromMedia(this.props.media);
}
componentWillReceiveProps (nextProps) {
if (this.props.media.get('id') !== nextProps.media.get('id')) {
this.updatePositionFromMedia(nextProps.media);
}
}
componentWillUnmount () {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
}
handleMouseDown = e => {
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.handleMouseUp);
this.updatePosition(e);
this.setState({ dragging: true });
}
handleMouseMove = e => {
this.updatePosition(e);
}
handleMouseUp = () => {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
this.setState({ dragging: false });
this.props.onSave(this.state.focusX, this.state.focusY);
}
updatePosition = e => {
const { x, y } = getPointerPosition(this.node, e);
const focusX = (x - .5) * 2;
const focusY = (y - .5) * -2;
this.setState({ x, y, focusX, focusY });
}
updatePositionFromMedia = media => {
const focusX = media.getIn(['meta', 'focus', 'x']);
const focusY = media.getIn(['meta', 'focus', 'y']);
if (focusX && focusY) {
const x = (focusX / 2) + .5;
const y = (focusY / -2) + .5;
this.setState({ x, y, focusX, focusY });
} else {
this.setState({ x: 0.5, y: 0.5, focusX: 0, focusY: 0 });
}
}
setRef = c => {
this.node = c;
}
render () {
const { media } = this.props;
const { x, y, dragging } = this.state;
const width = media.getIn(['meta', 'original', 'width']) || null;
const height = media.getIn(['meta', 'original', 'height']) || null;
return (
<div className='modal-root__modal video-modal focal-point-modal'>
<div className={classNames('focal-point', { dragging })} ref={this.setRef}>
<ImageLoader
previewSrc={media.get('preview_url')}
src={media.get('url')}
width={width}
height={height}
/>
<div className='focal-point__reticle' style={{ top: `${y * 100}%`, left: `${x * 100}%` }} />
<div className='focal-point__overlay' onMouseDown={this.handleMouseDown} />
</div>
</div>
);
}
}
|
lib/components/ContractExecution/index.js | gmtcreators/atom-solidity | 'use babel'
// Copyright 2018 Etheratom Authors
// This file is part of Etheratom.
// Etheratom is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Etheratom 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 General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Etheratom. If not, see <http://www.gnu.org/licenses/>.
import React from 'react';
import { connect } from 'react-redux';
import ReactJson from 'react-json-view';
import { Tab, Tabs, TabList, TabPanel } from 'react-tabs';
import InputsForm from '../InputsForm';
import FunctionABI from '../FunctionABI';
import PropTypes from 'prop-types';
class ContractExecution extends React.Component {
constructor(props) {
super(props);
this.helpers = props.helpers;
}
render() {
const { contractName, bytecode, index, contracts } = this.props;
const contractOptions = contracts[contractName].options;
const transactionHash = contracts[contractName].transactionHash;
const ContractABI = contracts[contractName].options.jsonInterface;
return (
<div className="contract-content" key={index}>
<span className="contract-name inline-block highlight-success">{contractName}</span>
<div className="byte-code">
<pre className="large-code">{JSON.stringify(bytecode)}</pre>
</div>
<div className="abi-definition">
<Tabs>
<TabList>
<div className="tab_btns">
<Tab>
<div className="btn">Interface</div>
</Tab>
<Tab>
<div className="btn">Interface Object</div>
</Tab>
</div>
</TabList>
<TabPanel>
<pre className="large-code">{JSON.stringify(ContractABI)}</pre>
</TabPanel>
<TabPanel>
<ReactJson
src={ContractABI}
theme="ocean"
displayDataTypes={false}
name={false}
collapsed={2}
/>
</TabPanel>
</Tabs>
</div>
{
transactionHash &&
<div id={contractName + '_txHash'}>
<span className="inline-block highlight">Transaction hash:</span>
<pre className="large-code">{transactionHash}</pre>
</div>
}
{
!contractOptions.address &&
<div id={contractName + '_stat'}>
<span className="stat-mining stat-mining-align">waiting to be mined</span>
<span className="loading loading-spinner-tiny inline-block stat-mining-align"></span>
</div>
}
{
contractOptions.address &&
<div id={contractName + '_stat'}>
<span className="inline-block highlight">Mined at:</span>
<pre className="large-code">{contractOptions.address}</pre>
</div>
}
{
ContractABI.map((abi, i) => {
return <InputsForm contractName={contractName} abi={abi} key={i} />;
})
}
<FunctionABI contractName={contractName} helpers={this.helpers} />
</div>
);
}
}
ContractExecution.propTypes = {
helpers: PropTypes.any.isRequired,
contractName: PropTypes.string,
bytecode: PropTypes.string,
index: PropTypes.number,
instances: PropTypes.any,
contracts: PropTypes.any,
interfaces: PropTypes.object
};
const mapStateToProps = ({ contract }) => {
const { contracts } = contract;
return { contracts };
};
export default connect(mapStateToProps, {})(ContractExecution);
|
node_modules/react-router/es6/withRouter.js | MichaelWiss/React_E | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import invariant from 'invariant';
import React from 'react';
import hoistStatics from 'hoist-non-react-statics';
import { routerShape } from './PropTypes';
function getDisplayName(WrappedComponent) {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
export default function withRouter(WrappedComponent, options) {
var withRef = options && options.withRef;
var WithRouter = React.createClass({
displayName: 'WithRouter',
contextTypes: { router: routerShape },
propTypes: { router: routerShape },
getWrappedInstance: function getWrappedInstance() {
!withRef ? process.env.NODE_ENV !== 'production' ? invariant(false, 'To access the wrapped instance, you need to specify ' + '`{ withRef: true }` as the second argument of the withRouter() call.') : invariant(false) : void 0;
return this.wrappedInstance;
},
render: function render() {
var _this = this;
var router = this.props.router || this.context.router;
var props = _extends({}, this.props, { router: router });
if (withRef) {
props.ref = function (c) {
_this.wrappedInstance = c;
};
}
return React.createElement(WrappedComponent, props);
}
});
WithRouter.displayName = 'withRouter(' + getDisplayName(WrappedComponent) + ')';
WithRouter.WrappedComponent = WrappedComponent;
return hoistStatics(WithRouter, WrappedComponent);
} |
app/javascript/mastodon/features/ui/components/focal_point_modal.js | vahnj/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { connect } from 'react-redux';
import ImageLoader from './image_loader';
import classNames from 'classnames';
import { changeUploadCompose } from '../../../actions/compose';
import { getPointerPosition } from '../../video';
const mapStateToProps = (state, { id }) => ({
media: state.getIn(['compose', 'media_attachments']).find(item => item.get('id') === id),
});
const mapDispatchToProps = (dispatch, { id }) => ({
onSave: (x, y) => {
dispatch(changeUploadCompose(id, { focus: `${x.toFixed(2)},${y.toFixed(2)}` }));
},
});
@connect(mapStateToProps, mapDispatchToProps)
export default class FocalPointModal extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
};
state = {
x: 0,
y: 0,
focusX: 0,
focusY: 0,
dragging: false,
};
componentWillMount () {
this.updatePositionFromMedia(this.props.media);
}
componentWillReceiveProps (nextProps) {
if (this.props.media.get('id') !== nextProps.media.get('id')) {
this.updatePositionFromMedia(nextProps.media);
}
}
componentWillUnmount () {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
}
handleMouseDown = e => {
document.addEventListener('mousemove', this.handleMouseMove);
document.addEventListener('mouseup', this.handleMouseUp);
this.updatePosition(e);
this.setState({ dragging: true });
}
handleMouseMove = e => {
this.updatePosition(e);
}
handleMouseUp = () => {
document.removeEventListener('mousemove', this.handleMouseMove);
document.removeEventListener('mouseup', this.handleMouseUp);
this.setState({ dragging: false });
this.props.onSave(this.state.focusX, this.state.focusY);
}
updatePosition = e => {
const { x, y } = getPointerPosition(this.node, e);
const focusX = (x - .5) * 2;
const focusY = (y - .5) * -2;
this.setState({ x, y, focusX, focusY });
}
updatePositionFromMedia = media => {
const focusX = media.getIn(['meta', 'focus', 'x']);
const focusY = media.getIn(['meta', 'focus', 'y']);
if (focusX && focusY) {
const x = (focusX / 2) + .5;
const y = (focusY / -2) + .5;
this.setState({ x, y, focusX, focusY });
} else {
this.setState({ x: 0.5, y: 0.5, focusX: 0, focusY: 0 });
}
}
setRef = c => {
this.node = c;
}
render () {
const { media } = this.props;
const { x, y, dragging } = this.state;
const width = media.getIn(['meta', 'original', 'width']) || null;
const height = media.getIn(['meta', 'original', 'height']) || null;
return (
<div className='modal-root__modal video-modal focal-point-modal'>
<div className={classNames('focal-point', { dragging })} ref={this.setRef}>
<ImageLoader
previewSrc={media.get('preview_url')}
src={media.get('url')}
width={width}
height={height}
/>
<div className='focal-point__reticle' style={{ top: `${y * 100}%`, left: `${x * 100}%` }} />
<div className='focal-point__overlay' onMouseDown={this.handleMouseDown} />
</div>
</div>
);
}
}
|
app/containers/RepoListItem/index.js | KyleAWang/react-boilerplate | /**
* RepoListItem
*
* Lists the name and the issue count of a repository
*/
import React from 'react';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import { FormattedNumber } from 'react-intl';
import { makeSelectCurrentUser } from 'containers/App/selectors';
import ListItem from 'components/ListItem';
import IssueIcon from './IssueIcon';
import IssueLink from './IssueLink';
import RepoLink from './RepoLink';
import Wrapper from './Wrapper';
export class RepoListItem extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
const item = this.props.item;
let nameprefix = '';
// If the repository is owned by a different person than we got the data for
// it's a fork and we should show the name of the owner
if (item.owner.login !== this.props.currentUser) {
nameprefix = `${item.owner.login}/`;
}
// Put together the content of the repository
const content = (
<Wrapper>
<RepoLink href={item.html_url} target="_blank">
{nameprefix + item.name}
</RepoLink>
<IssueLink href={`${item.html_url}/issues`} target="_blank">
<IssueIcon />
<FormattedNumber value={item.open_issues_count} />
</IssueLink>
</Wrapper>
);
// Render the content into a list item
return (
<ListItem key={`repo-list-item-${item.full_name}`} item={content} />
);
}
}
RepoListItem.propTypes = {
item: React.PropTypes.object,
currentUser: React.PropTypes.string,
};
export default connect(createStructuredSelector({
currentUser: makeSelectCurrentUser(),
}))(RepoListItem);
|
src/svg-icons/device/screen-lock-landscape.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceScreenLockLandscape = (props) => (
<SvgIcon {...props}>
<path d="M21 5H3c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm-2 12H5V7h14v10zm-9-1h4c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1v-1c0-1.11-.9-2-2-2-1.11 0-2 .9-2 2v1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1zm.8-6c0-.66.54-1.2 1.2-1.2.66 0 1.2.54 1.2 1.2v1h-2.4v-1z"/>
</SvgIcon>
);
DeviceScreenLockLandscape = pure(DeviceScreenLockLandscape);
DeviceScreenLockLandscape.displayName = 'DeviceScreenLockLandscape';
DeviceScreenLockLandscape.muiName = 'SvgIcon';
export default DeviceScreenLockLandscape;
|
springboot/GReact/node_modules/react-bootstrap/es/Col.js | ezsimple/java | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, prefix, splitBsProps } from './utils/bootstrapUtils';
import { DEVICE_SIZES } from './utils/StyleConfig';
var propTypes = {
componentClass: elementType,
/**
* The number of columns you wish to span
*
* for Extra small devices Phones (<768px)
*
* class-prefix `col-xs-`
*/
xs: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Small devices Tablets (≥768px)
*
* class-prefix `col-sm-`
*/
sm: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Medium devices Desktops (≥992px)
*
* class-prefix `col-md-`
*/
md: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Large devices Desktops (≥1200px)
*
* class-prefix `col-lg-`
*/
lg: React.PropTypes.number,
/**
* Hide column
*
* on Extra small devices Phones
*
* adds class `hidden-xs`
*/
xsHidden: React.PropTypes.bool,
/**
* Hide column
*
* on Small devices Tablets
*
* adds class `hidden-sm`
*/
smHidden: React.PropTypes.bool,
/**
* Hide column
*
* on Medium devices Desktops
*
* adds class `hidden-md`
*/
mdHidden: React.PropTypes.bool,
/**
* Hide column
*
* on Large devices Desktops
*
* adds class `hidden-lg`
*/
lgHidden: React.PropTypes.bool,
/**
* Move columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-offset-`
*/
xsOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-offset-`
*/
smOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-offset-`
*/
mdOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-offset-`
*/
lgOffset: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-push-`
*/
xsPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-push-`
*/
smPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-push-`
*/
mdPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-push-`
*/
lgPush: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Extra small devices Phones
*
* class-prefix `col-xs-pull-`
*/
xsPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Small devices Tablets
*
* class-prefix `col-sm-pull-`
*/
smPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Medium devices Desktops
*
* class-prefix `col-md-pull-`
*/
mdPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Large devices Desktops
*
* class-prefix `col-lg-pull-`
*/
lgPull: React.PropTypes.number
};
var defaultProps = {
componentClass: 'div'
};
var Col = function (_React$Component) {
_inherits(Col, _React$Component);
function Col() {
_classCallCheck(this, Col);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Col.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = [];
DEVICE_SIZES.forEach(function (size) {
function popProp(propSuffix, modifier) {
var propName = '' + size + propSuffix;
var propValue = elementProps[propName];
if (propValue != null) {
classes.push(prefix(bsProps, '' + size + modifier + '-' + propValue));
}
delete elementProps[propName];
}
popProp('', '');
popProp('Offset', '-offset');
popProp('Push', '-push');
popProp('Pull', '-pull');
var hiddenPropName = size + 'Hidden';
if (elementProps[hiddenPropName]) {
classes.push('hidden-' + size);
}
delete elementProps[hiddenPropName];
});
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return Col;
}(React.Component);
Col.propTypes = propTypes;
Col.defaultProps = defaultProps;
export default bsClass('col', Col); |
web_client/dev/components/header/Header.js | crazy-valseeker/carzyfish | /**
* Created by valseek on 17-2-6.
*/
import React from 'react';
import {Component} from 'react-dom'
import './Header.less'
class Header extends Component{
render(){
return(
<div className="cf-header">
</div>
);
}
}
module.exports=Header; |
code/schritte/3-remote/src/GreetingMaster.js | st-he/react-workshop | import React from 'react';
const GreetingMaster = (props) => {
const {greetings, onAdd} = props;
const body = greetings.map(greeting => <tr key={greeting.id}><td>{greeting.name}</td><td>{greeting.greeting}</td></tr>);
return (
<div>
<table>
<thead>
<tr><th>Name</th><th>Greeting</th></tr>
</thead>
<tbody>
{body}
</tbody>
</table>
<button
onClick={onAdd}>
Add
</button>
</div>
);
};
export default GreetingMaster; |
src/components/IconButton/IconButton.js | rajeshpillai/zs-react-pattern-lib | import React from 'react';
import PropTypes from 'prop-types';
import './iconbutton.css';
function IconButton({icon, location, onClick, children }) {
return (
<button className="button" onClick= {onClick}>
{location === "left" && <i className={icon} aria-hidden="true"/>}
{children}
{location === "right" && <i className={icon} aria-hidden="true"/>}
</button>
);
}
IconButton.propTypes = {
/** The icon class to display to display */
icon: PropTypes.string,
/** The location of the icon. Valid values are "left", "right" */
location: PropTypes.string,
/** The click handler for the button */
onClick: PropTypes.func
};
IconButton.defaultProps = {
location: 'left'
};
export default IconButton; |
jrt/src/routes/home/index.js | wizzardo/jrtorrent | import React from 'react';
import './style.css';
import {DiskUsage} from "../../components/DiskUsage";
import {TorrentsList} from "../../components/TorrentsList";
import AddButton from "../../components/AddButton";
const Home = () => (
<div className='home'>
<DiskUsage />
<TorrentsList/>
<AddButton/>
</div>
);
export default Home;
|
src/pages/vintage.js | vitorbarbosa19/ziro-online | import React from 'react'
import BrandGallery from '../components/BrandGallery'
export default () => (
<BrandGallery brand='Vintage' />
)
|
src/js/PaginationContainer.js | Pearson-Higher-Ed/pagination | import React from 'react';
import Pagination from './Pagination';
export default class PaginationContainer extends React.Component {
constructor(props) {
super(props);
this.state = {
activePage: props.activePage,
compactText: props.compactText };
}
setActive = (eventKey) => {
this.setState({ activePage: eventKey });
this.setState({ compactText: `Page ${eventKey} of ${this.props.pages}`});
};
render() {
return (
<Pagination
pages={this.props.pages}
activePage={this.state.activePage}
onSelect={this.setActive}
maxButtons={this.props.maxButtons}
prevTitle={this.props.prevTitle}
nextTitle={this.props.nextTitle}
compactText={this.state.compactText}
paginationType={this.props.paginationType}
/>
);
}
}
|
src/svg-icons/hardware/tv.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareTv = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.1-.9-2-2-2zm0 14H3V5h18v12z"/>
</SvgIcon>
);
HardwareTv = pure(HardwareTv);
HardwareTv.displayName = 'HardwareTv';
HardwareTv.muiName = 'SvgIcon';
export default HardwareTv;
|
React/React-ruan/demo13/src/app.js | duolew/project-zhp | import React from 'react';
export default class App extends React.Component{
constructor(props) {
super(props);
this.render = this.render.bind(this);
this.state = {
items: this.props.items,
disabled: true
};
}
componentDidMount() {
this.setState({
disabled: false
})
}
handleClick() {
this.setState({
items: this.state.items.concat('Item ' + this.state.items.length)
})
}
render() {
return (
<div>
<button onClick={this.handleClick.bind(this)} disabled={this.state.disabled}>Add Item</button>
<ul>
{
this.state.items.map(function(item) {
return <li>{item}</li>
})
}
</ul>
</div>
)
}
};
|
src/routes/register/index.js | jhlav/mpn-web-app | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Register from './Register';
const title = 'New User Registration';
function action() {
return {
chunks: ['register'],
title,
component: (
<Layout>
<Register title={title} />
</Layout>
),
};
}
export default action;
|
CompositeUi/src/views/component/CardExtended.js | kreta-io/kreta | /*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <benatespina@gmail.com>
* (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import './../../scss/components/_card-extended.scss';
import React from 'react';
class CardExtended extends React.Component {
static propTypes = {
subtitle: React.PropTypes.string,
thumbnail: React.PropTypes.element,
title: React.PropTypes.string.isRequired,
};
thumbnail() {
const {thumbnail} = this.props;
if (thumbnail) {
return (
<div className="card-extended__thumbnail">
{thumbnail}
</div>
);
}
return '';
}
subtitle() {
const {subtitle} = this.props;
if (subtitle) {
return (
<span className="card-extended__sub-header">
{subtitle}
</span>
);
}
return '';
}
render() {
const {title, children} = this.props;
return (
<div className="card-extended">
{this.thumbnail()}
<div className="card-extended__container">
<span className="card-extended__header">
{title}
</span>
{this.subtitle()}
</div>
<div className="card-extended__actions">
{children}
</div>
</div>
);
}
}
export default CardExtended;
|
packages/vx-text/src/text/TextWrap.js | Flaque/vx | import React from 'react';
import cx from 'classnames';
const svgNS = "http://www.w3.org/2000/svg";
/**
* TODO: this is horrible and doesn't work. figure this out.
*/
export default class TextWrap extends React.Component {
componentDidMount() {
const { text, width, y = 1, x = 1, dy = 0, lineHeight } = this.props;
let lineNumber = 0;
let line = [];
let word;
let tspan = this.tspan;
const words = text.split(/\s+/).reverse();
while (word = words.pop()) {
line.push(word);
let newText = line.join(" ");
tspan.textContent = newText;
if (tspan.getComputedTextLength() > width) {
line.pop();
newText = line.join(" ");
tspan.textContent = newText;
line = [word];
let newLine = document.createElementNS(svgNS, 'tspan');
newLine.setAttributeNS(svgNS, 'x', x);
newLine.setAttributeNS(svgNS, 'y', y);
newLine.setAttributeNS(svgNS, 'dy', `${++lineNumber * lineHeight}em`);
newLine.textContent = ` ${word}`;
this.tspan.parentNode.append(newLine);
tspan = newLine;
}
}
}
render() {
const {
text,
x,
y,
dx,
dy,
lineHeight,
width,
className,
} = this.props;
return (
<text
className={cx('vx-text-wrap', className)}
x={x}
y={y}
dx={dx}
dy={dy}
>
<tspan
ref={(c) => { this.tspan = c;}}
x={x}
y={y}
dy={dy}
/>
</text>
);
}
}
TextWrap.defaultProps = {
lineHeight: 1.1,
width: 140,
x: 0,
y: 0,
dx: 0,
dy: 0,
};
|
src/components/control/controlTemp.js | gordongordon/hom | import React from 'react'
import { List,TabBar, Tabs, Card, Stepper, Picker, SwipeAction, DatePicker, Badge, Flex, InputItem, Button, WhiteSpace, SegmentedControl } from 'antd-mobile';
import { createForm } from 'rc-form';
import { Fb } from 'firebase-store';
import { observer } from 'mobx-react';
import { DISTRICK } from 'DISTRICK';
const TabPane = Tabs.TabPane;
// import moment from 'moment';
// import 'moment/locale/zh-cn';
//import {propertys} from 'userModelView'
// const Item = List.Item;
// const Brief = Item.Brief;
//
// const NameOfBuilding = [
// { value: 'MOSDBC', label: '迎海' },
// { value: 'MOSCTO', label: '第一城' },
// { value: 'MOSSSC', label: '新港城' },
// ];
// 如果不是使用 List.Item 作为 children
const CustomChildren = props => (
<div
onClick={props.onClick}
style={{ backgroundColor: '#fff', padding: '0.2rem 0.2rem' }}
>
<div style={{ display: 'flex', height: '0.9rem', lineHeight: '0.9rem' }}>
<div style={{ padding: '0.1rem', flex: 1, overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap' }}>{props.children}</div>
<div style={{ textAlign: 'right', color: '#888' }}>{props.extra} ></div>
</div>
</div>
);
@observer
class ControlAgentView extends React.Component {
constructor(props) {
super(props);
this.state = {
disabled: false,
selectedSegmentIndex: 0,
id: this.props.property.fbid
};
this.onChangeAddress = this.onChangeAddress.bind(this);
// this.onChangeEarlyTimeToView = this.onChangeEarlyTimeToView.bind(this);
} // End of constructor
//
onChangeAddress = (value) => {
const id = this.state.id;
// var value = this.props.form.getFieldsValue();
const addressRegion = value[0];
const addressLocation = value[1];
const addressBuilding = value[2];
console.log(`location ${addressLocation}, building ${addressBuilding} with ${id} ${value}`)
// console.log( 'address ${}')
if (addressBuilding === 'ALL') {
// console.log( 'MOS0000')
Fb.app.agentsFilterRef.child(id).update({
orderByChild: 'addressLocation',
addressRegion: addressRegion,
addressLocation: addressLocation,
nameOfBuilding: addressBuilding
});
} else {
Fb.app.agentsFilterRef.child(id).update({
orderByChild: 'nameOfBuilding',
addressRegion: addressRegion,
addressLocation: addressLocation,
nameOfBuilding: addressBuilding
});
}
}
// onChange = (e) => {
// console.log(`ControlAgentView.selectedIndex:${e.nativeEvent.selectedSegmentIndex}`);
// }
//
// onValueChange = (value) => {
// console.log(value);
// }
render() {
const { property } = this.props;
const that = this;
const { getFieldProps } = this.props.form;
// For DatePicker
//const minDate = moment().locale('zh-cn').utcOffset(8);
// const maxDate = moment(minDate).add(6, 'M');
const region = property.addressRegion;
const location = property.addressLocation;
const building = property.nameOfBuilding;
const address = [region, location, building];
console.log(`address ${address}`);
console.log('Single Agent Property property', property);
var selectedIndex = this.props.selectedIndex;
const onChange = this.props.onChange;
if (property.nameOfBuildingLabel === undefined) {
console.log('*nameOfBuildingLabel undefined');
}
return (
<div>
<SegmentedControl values={['B搵買盤', 'S放賣盤', 'R搵租盤', 'L放租盤', '已跟進/回覆']} selectedIndex={this.props.selectedIndex} onChange={onChange} />
<SegmentedControl tintColor="#888" values={['回覆', '已跟進']} selectedIndex={this.props.selectedIndex} onChange={onChange} />
<List>
<Picker data={DISTRICK} cols={3} {...getFieldProps('districk', {
initialValue: address,
}) }
className="forss" title="請選擇大廈/屋苑" extra="請選擇大廈/屋苑"
onChange={this.onChangeAddress}
>
<CustomChildren>大廈/屋苑</CustomChildren>
</Picker>
<List.Item extra={
<Stepper
style={{ width: '100%', minWidth: '2rem' }}
{...getFieldProps('buyBudgetMax', {
initialValue: 300
}) }
showNumber
max={100000}
min={100}
step={5}
/>}
>
預算上限/萬
</List.Item>
</List>
<h5>{property.fbid}</h5>
<WhiteSpace size="sm" />
</div>
);
}
}
// <SegmentedControl tintColor={'#ff0000'} values={['最貴', '最平', '最快', '最滿意']} selectedIndex={this.state.selectedSegmentIndex} onChange={this.onChange} />
export const ControlAgentViewWrapper = createForm()(ControlAgentView);
|
lavalab/html/node_modules/react-bootstrap/es/Tab.js | LavaLabUSC/usclavalab.org | import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import PropTypes from 'prop-types';
import TabContainer from './TabContainer';
import TabContent from './TabContent';
import TabPane from './TabPane';
var propTypes = _extends({}, TabPane.propTypes, {
disabled: PropTypes.bool,
title: PropTypes.node,
/**
* tabClassName is used as className for the associated NavItem
*/
tabClassName: PropTypes.string
});
var Tab = function (_React$Component) {
_inherits(Tab, _React$Component);
function Tab() {
_classCallCheck(this, Tab);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Tab.prototype.render = function render() {
var props = _extends({}, this.props);
// These props are for the parent `<Tabs>` rather than the `<TabPane>`.
delete props.title;
delete props.disabled;
delete props.tabClassName;
return React.createElement(TabPane, props);
};
return Tab;
}(React.Component);
Tab.propTypes = propTypes;
Tab.Container = TabContainer;
Tab.Content = TabContent;
Tab.Pane = TabPane;
export default Tab; |
examples/huge-apps/routes/Course/routes/Grades/components/Grades.js | dmitrigrabov/react-router | /*globals COURSES:true */
import React from 'react'
class Grades extends React.Component {
render() {
let { assignments } = COURSES[this.props.params.courseId]
return (
<div>
<h3>Grades</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>{assignment.grade} - {assignment.title}</li>
))}
</ul>
</div>
)
}
}
export default Grades
|
YEAR 3/SEM 1/MOBILE/non-native/PhotoReact/components/EmailTextInput.js | Zephyrrus/ubb |
import React from 'react';
import { TextInput } from 'react-native';
export default class EmailTextInput extends React.Component {
render() {
return <TextInput {...this.props}
keyboardType="email-address"
autoCapitalize="none"
autoCorrect={false}
/>;
}
} |
examples/huge-apps/routes/Course/routes/Announcements/components/Sidebar.js | Jastrzebowski/react-router | import React from 'react';
import { Link } from 'react-router';
export default class AnnouncementsSidebar extends React.Component {
static loadProps (params, cb) {
console.log('AnnouncementsSidebar', 'loadProps');
cb(null, {
announcements: COURSES[params.courseId].announcements
});
}
render () {
var { announcements } = this.props;
//var announcements = COURSES[this.props.params.courseId].announcements;
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{announcements.map(announcement => (
<li key={announcement.id}>
<Link to={`/course/${this.props.params.courseId}/announcements/${announcement.id}`}>
{announcement.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
|
src/ace.js | eccenca/react-ace-wrapper | /* eslint max-statements: [1, 18] */
/* eslint complexity: [1, 10] */
import React from 'react';
import ace from 'brace';
const AceEditor = React.createClass({
propTypes: {
mode: React.PropTypes.string,
theme: React.PropTypes.string,
name: React.PropTypes.string,
height: React.PropTypes.string,
width: React.PropTypes.string,
fontSize: React.PropTypes.number,
showGutter: React.PropTypes.bool,
onChange: React.PropTypes.func,
defaultValue: React.PropTypes.string,
value: React.PropTypes.string,
onLoad: React.PropTypes.func,
maxLines: React.PropTypes.number,
readOnly: React.PropTypes.bool,
highlightActiveLine: React.PropTypes.bool,
showPrintMargin: React.PropTypes.bool,
selectFirstLine: React.PropTypes.bool,
wrapEnabled: React.PropTypes.bool
},
getDefaultProps() {
return {
name: 'brace-editor',
mode: '',
theme: '',
height: '500px',
width: '500px',
defaultValue: '',
value: '',
fontSize: 12,
showGutter: true,
onChange: null,
onLoad: null,
maxLines: null,
readOnly: false,
highlightActiveLine: true,
showPrintMargin: true,
selectFirstLine: false,
wrapEnabled: false
};
},
onChange() {
if (this.props.onChange) {
const value = this.editor.getValue();
this.props.onChange(value);
}
},
componentDidMount() {
this.editor = ace.edit(this.props.name);
this.editor.$blockScrolling = Infinity;
this.editor.getSession().setMode('ace/mode/' + this.props.mode);
this.editor.setTheme('ace/theme/' + this.props.theme);
this.editor.setFontSize(this.props.fontSize);
this.editor.on('change', this.onChange);
this.editor.setValue(this.props.defaultValue || this.props.value, (this.props.selectFirstLine === true ? -1 : null));
this.editor.setOption('maxLines', this.props.maxLines);
this.editor.setOption('readOnly', this.props.readOnly);
this.editor.setOption('highlightActiveLine', this.props.highlightActiveLine);
this.editor.setShowPrintMargin(this.props.setShowPrintMargin);
this.editor.getSession().setUseWrapMode(this.props.wrapEnabled);
this.editor.renderer.setShowGutter(this.props.showGutter);
if (this.props.onLoad) {
this.props.onLoad(this.editor);
}
},
componentWillReceiveProps(nextProps) {
let currentRange = this.editor.selection.getRange();
// only update props if they are changed
if (nextProps.mode !== this.props.mode) {
this.editor.getSession().setMode('ace/mode/' + nextProps.mode);
}
if (nextProps.theme !== this.props.theme) {
this.editor.setTheme('ace/theme/' + nextProps.theme);
}
if (nextProps.fontSize !== this.props.fontSize) {
this.editor.setFontSize(nextProps.fontSize);
}
if (nextProps.maxLines !== this.props.maxLines) {
this.editor.setOption('maxLines', nextProps.maxLines);
}
if (nextProps.readOnly !== this.props.readOnly) {
this.editor.setOption('readOnly', nextProps.readOnly);
}
if (nextProps.highlightActiveLine !== this.props.highlightActiveLine) {
this.editor.setOption('highlightActiveLine', nextProps.highlightActiveLine);
}
if (nextProps.setShowPrintMargin !== this.props.setShowPrintMargin) {
this.editor.setShowPrintMargin(nextProps.setShowPrintMargin);
}
if (nextProps.wrapEnabled !== this.props.wrapEnabled) {
this.editor.getSession().setUseWrapMode(nextProps.wrapEnabled);
}
if (nextProps.value && this.editor.getValue() !== nextProps.value) {
this.editor.setValue(nextProps.value, (this.props.selectFirstLine === true ? -1 : null));
if(currentRange && typeof currentRange === "object") {
this.editor.getSession().getSelection().setSelectionRange(currentRange);
}
}
if (nextProps.showGutter !== this.props.showGutter) {
this.editor.renderer.setShowGutter(nextProps.showGutter);
}
},
render() {
const divStyle = {
width: this.props.width,
height: this.props.height,
};
return React.DOM.div({
id: this.props.name,
onChange: this.onChange,
style: divStyle,
});
}
});
export default AceEditor;
|
Tutorial/js/project/2.MeiTuan/Component/More/XMGCommonCell.js | onezens/react-native-repo | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Image,
TouchableOpacity,
Platform,
Switch
} from 'react-native';
var CommonCell = React.createClass({
getDefaultProps(){
return{
title: '', // 标题
isSwitch: false, // 是否展示开关
rightTitle: ''
}
},
getInitialState(){
return{
isOn:false
}
},
render() {
return (
<TouchableOpacity onPress={()=>{alert('点了')}}>
<View style={styles.container}>
{/*左边*/}
<Text style={{marginLeft:8}}>{this.props.title}</Text>
{/*右边*/}
{this.renderRightView()}
</View>
</TouchableOpacity>
);
},
// cell右边显示的内容
renderRightView(){
// 判断
if (this.props.isSwitch){ // true
return(
<Switch value={this.state.isOn == true} onValueChange={()=>{this.setState({isOn: !this.state.isOn})}} style={{marginRight:8}} />
)
}else{
return(
<View style={{flexDirection:'row', alignItems:'center'}}>
{this.rightTitle()}
<Image source={{uri: 'icon_cell_rightArrow'}} style={{width:8, height:13, marginRight:8}}/>
</View>
)
}
},
rightTitle(){
if(this.props.rightTitle.length > 0){
return(
<Text style={{color:'gray', marginRight:3}}>{this.props.rightTitle}</Text>
)
}
}
});
const styles = StyleSheet.create({
container:{
height:Platform.OS == 'ios' ? 40: 30,
backgroundColor:'white',
borderBottomColor:'#dddddd',
borderBottomWidth:0.5,
flexDirection:'row',
// 主轴的对齐方式
justifyContent:'space-between',
// 垂直居中
alignItems:'center'
}
});
// 输出组件类
module.exports = CommonCell;
|
docs/public/static/examples/v34.0.0/lottie.js | exponent/exponent | import React from 'react';
import { Button, StyleSheet, View } from 'react-native';
import LottieView from 'lottie-react-native';
export default class App extends React.Component {
componentDidMount() {
this.animation.play();
// Or set a specific startFrame and endFrame with:
// this.animation.play(30, 120);
}
resetAnimation = () => {
this.animation.reset();
this.animation.play();
};
render() {
return (
<View style={styles.animationContainer}>
<LottieView
ref={animation => {
this.animation = animation;
}}
style={{
width: 400,
height: 400,
backgroundColor: '#eee',
}}
source={require('./assets/gradientBall.json')}
// OR find more Lottie files @ https://lottiefiles.com/featured
// Just click the one you like, place that file in the 'assets' folder to the left, and replace the above 'require' statement
/>
<View style={styles.buttonContainer}>
<Button title="Restart Animation" onPress={this.resetAnimation} />
</View>
</View>
);
}
}
const styles = StyleSheet.create({
animationContainer: {
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
flex: 1,
},
buttonContainer: {
paddingTop: 20,
},
});
|
src/components/Contact.js | sivael/simpleBlogThingie | import React from 'react'
export default class Footer extends React.Component {
render() {
return(
<div className="jumbotron">
<h1>Contact</h1>
<p className="lead">Contact us because we're awesome</p>
</div>
);
}
}
|
blueocean-material-icons/src/js/components/svg-icons/social/sentiment-satisfied.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const SocialSentimentSatisfied = (props) => (
<SvgIcon {...props}>
<circle cx="15.5" cy="9.5" r="1.5"/><circle cx="8.5" cy="9.5" r="1.5"/><path d="M11.99 2C6.47 2 2 6.48 2 12s4.47 10 9.99 10C17.52 22 22 17.52 22 12S17.52 2 11.99 2zM12 20c-4.42 0-8-3.58-8-8s3.58-8 8-8 8 3.58 8 8-3.58 8-8 8zm0-4c-1.48 0-2.75-.81-3.45-2H6.88c.8 2.05 2.79 3.5 5.12 3.5s4.32-1.45 5.12-3.5h-1.67c-.7 1.19-1.97 2-3.45 2z"/>
</SvgIcon>
);
SocialSentimentSatisfied.displayName = 'SocialSentimentSatisfied';
SocialSentimentSatisfied.muiName = 'SvgIcon';
export default SocialSentimentSatisfied;
|
client/app/components/Play/Playbar/Playing.js | dring1/gopheringdj | import React from 'react';
import YouTube from 'react-youtube';
import { youtubeId } from '../../../util/youtube';
class Playing extends React . Component {
constructor( props ) {
super( props );
this.state = {
key: '',
metadata: {},
};
}
static propTypes = {
metadata: React.PropTypes.object.isRequired,
}
static contextTypes = {
callback: React.PropTypes.func,
onError: React.PropTypes.func,
onEnd: React.PropTypes.func,
onPlay: React.PropTypes.func,
}
render() {
const data = this.props.metadata;
const opts = {
height: '54',
width: '150',
playerVars: { // https://developers.google.com/youtube/player_parameters
autoplay: 1,
// controls: 0,
},
};
if (data === undefined) {
return (
<div></div>
);
}
return (
<YouTube
videoId={youtubeId(data.url)}
opts={opts}
onPlay={this.context.onPlay}
onError={this.context.onError}
onEnd={this.context.onEnd} />
);
}
}
export default Playing;
|
src/components/app.js | MdShuaib/ReactRouterReduxForm | import React, { Component } from 'react';
export default class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
|
docs/src/modules/components/AppFooter.js | lgollut/material-ui | /* eslint-disable material-ui/no-hardcoded-labels */
import React from 'react';
import PropTypes from 'prop-types';
import { useSelector } from 'react-redux';
import Interpolate from '@trendmicro/react-interpolate';
import { withStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Grid from '@material-ui/core/Grid';
import Container from '@material-ui/core/Container';
import Divider from '@material-ui/core/Divider';
import Link from 'docs/src/modules/components/Link';
const styles = (theme) => ({
root: {
marginTop: theme.spacing(6),
},
footer: {
padding: theme.spacing(3, 0),
[theme.breakpoints.up('sm')]: {
padding: theme.spacing(8, 0),
},
},
logo: {
display: 'flex',
alignItems: 'center',
marginBottom: theme.spacing(4),
'& img': {
width: 28,
height: 22,
marginRight: theme.spacing(1.5),
},
},
list: {
marginBottom: theme.spacing(4),
'& h3': {
fontWeight: theme.typography.fontWeightMedium,
},
'& ul': {
margin: 0,
padding: 0,
listStyle: 'none',
},
'& li': {
padding: '6px 0',
color: theme.palette.text.secondary,
},
},
version: {
marginTop: theme.spacing(3),
},
});
function AppFooter(props) {
const { classes } = props;
const userLanguage = useSelector((state) => state.options.userLanguage);
const languagePrefix = userLanguage === 'en' ? '' : `/${userLanguage}`;
const t = useSelector((state) => state.options.t);
return (
<div className={classes.root}>
<Divider />
<Container maxWidth="md">
<footer className={classes.footer}>
<Grid container>
<Grid item xs={12} sm={3}>
<div className={classes.logo}>
<img src="/static/logo_raw.svg" alt="" />
<Link variant="body1" color="inherit" href="/">
Material-UI
</Link>
</div>
</Grid>
<Grid item xs={6} sm={3} className={classes.list}>
<Typography component="h2" gutterBottom>
{t('footerCommunity')}
</Typography>
<ul>
<li>
<Link
color="inherit"
variant="body2"
href="https://github.com/mui-org/material-ui"
>
GitHub
</Link>
</li>
<li>
<Link color="inherit" variant="body2" href="https://twitter.com/MaterialUI">
Twitter
</Link>
</li>
<li>
<Link
color="inherit"
variant="body2"
href="https://stackoverflow.com/questions/tagged/material-ui"
>
StackOverflow
</Link>
</li>
<li>
<Link color="inherit" variant="body2" href="/discover-more/team/">
{t('pages./discover-more/team')}
</Link>
</li>
</ul>
</Grid>
<Grid item xs={6} sm={3} className={classes.list}>
<Typography component="h2" gutterBottom>
{t('footerResources')}
</Typography>
<ul>
<li>
<Link color="inherit" variant="body2" href="/getting-started/support/">
{t('pages./getting-started/support')}
</Link>
</li>
<li>
<Link color="inherit" variant="body2" href="https://medium.com/material-ui/">
{t('blogTitle')}
</Link>
</li>
<li>
<Link color="inherit" variant="body2" href="/components/material-icons/">
{t('pages./components/material-icons')}
</Link>
</li>
</ul>
</Grid>
<Grid item xs={6} sm={3} className={classes.list}>
<Typography component="h2" gutterBottom>
{t('footerCompany')}
</Typography>
<ul>
<li>
<Link color="inherit" variant="body2" href="/company/about/">
About
</Link>
</li>
<li>
<Link color="inherit" variant="body2" href="/company/contact/">
Contact Us
</Link>
</li>
<li>
<Link color="inherit" variant="body2" href="/company/jobs/">
Jobs
</Link>
</li>
</ul>
</Grid>
</Grid>
<Typography className={classes.version} color="textSecondary" variant="body2">
<Interpolate
replacement={{
versionNumber: (
<Link
color="inherit"
href={`https://material-ui.com${languagePrefix}/versions/`}
aria-label={`v${process.env.LIB_VERSION}. View versions page.`}
>
{`v${process.env.LIB_VERSION}`}
</Link>
),
license: (
<Link
color="inherit"
href="https://github.com/mui-org/material-ui/blob/master/LICENSE"
>
{t('license')}
</Link>
),
}}
>
{t('homeFooterRelease')}
</Interpolate>
{' Copyright © '}
{new Date().getFullYear()}
{' Material-UI. '}
</Typography>
</footer>
</Container>
</div>
);
}
AppFooter.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(AppFooter);
|
src/ImageViewer/ImageViewer.driver.js | skyiea/wix-style-react | import React from 'react';
import ReactDOM from 'react-dom';
import ReactTestUtils from 'react-dom/test-utils';
const imageViewerDriverFactory = ({component, wrapper, element}) => {
const image = () => element.querySelector('[data-hook="image-viewer-image"]');
const addImageButton = () => element.querySelector('[data-hook="add-image"]');
const updateImageButton = () => element.querySelector('[data-hook="update-image"]');
const removeImageButton = () => element.querySelector('[data-hook="remove-image"]');
return {
getImageUrl: () => image().getAttribute('src'),
isImageVisible: () => !!image(),
clickAdd: () => ReactTestUtils.Simulate.click(addImageButton()),
clickUpdate: () => ReactTestUtils.Simulate.click(updateImageButton()),
clickRemove: () => ReactTestUtils.Simulate.click(removeImageButton()),
exists: () => !!element,
setProps: props => {
const ClonedWithProps = React.cloneElement(component, Object.assign({}, component.props, props), ...(component.props.children || []));
ReactDOM.render(<div ref={r => element = r}>{ClonedWithProps}</div>, wrapper);
}
};
};
export default imageViewerDriverFactory;
|
src/svg-icons/places/hot-tub.js | andrejunges/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesHotTub = (props) => (
<SvgIcon {...props}>
<circle cx="7" cy="6" r="2"/><path d="M11.15 12c-.31-.22-.59-.46-.82-.72l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C6.01 9 5 10.01 5 11.25V12H2v8c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2v-8H11.15zM7 20H5v-6h2v6zm4 0H9v-6h2v6zm4 0h-2v-6h2v6zm4 0h-2v-6h2v6zm-.35-14.14l-.07-.07c-.57-.62-.82-1.41-.67-2.2L18 3h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71zm-4 0l-.07-.07c-.57-.62-.82-1.41-.67-2.2L14 3h-1.89l-.06.43c-.2 1.36.27 2.71 1.3 3.72l.07.06c.57.62.82 1.41.67 2.2l-.11.59h1.91l.06-.43c.21-1.36-.27-2.71-1.3-3.71z"/>
</SvgIcon>
);
PlacesHotTub = pure(PlacesHotTub);
PlacesHotTub.displayName = 'PlacesHotTub';
PlacesHotTub.muiName = 'SvgIcon';
export default PlacesHotTub;
|
app/main.js | christianalfoni/webpack-bin | import React from 'react';
import ReactDOM from 'react-dom';
import Controller from 'cerebral';
import Model from 'cerebral-model-baobab';
import {Container} from 'cerebral-view-react';
import Devtools from 'cerebral-module-devtools';
import Router from 'cerebral-module-router';
import Http from 'cerebral-module-http';
import BinModule from './modules/Bin';
import NpmModule from './modules/Npm';
import LiveModule from './modules/Live';
import Mobile from './modules/Mobile';
import hideSnackbar from './modules/Bin/actions/hideSnackbar';
const controller = Controller(Model({}));
controller.addSignals({
snackbarTimedOut: [
hideSnackbar
]
});
controller.addModules({
bin: BinModule(),
npm: NpmModule(),
live: LiveModule(),
mobile: Mobile(),
http: Http(),
devtools: process.env.NODE_ENV === 'production' ? function () {} : Devtools(),
router: Router({
'/': 'bin.rootRouted',
'/:id': 'bin.opened'
})
});
let currentApp = null;
const calculateCurrentApp = function () {
if (window.innerWidth < 400 && window.innerWidth < window.innerHeight) {
return 'mobilePortrait';
}
if (window.innerWidth < 1280) {
return 'mobileLandscape';
}
return 'desktop';
};
const renderApp = function () {
const newApp = calculateCurrentApp();
if (currentApp === newApp) {
return;
}
currentApp = newApp;
document.querySelector('#loader').style.display = 'block';
ReactDOM.unmountComponentAtNode(document.getElementById('root'));
require.ensure([], () => {
let Bin;
if (newApp === 'mobilePortrait') {
Bin = require('./mobilePortrait/Bin/index.js').default;
} else if (newApp === 'mobileLandscape') {
Bin = require('./mobileLandscape/Bin/index.js').default;
} else {
Bin = require('./desktop/Bin/index.js').default;
}
ReactDOM.render(
<Container controller={controller} style={{height: '100%'}}>
<Bin/>
</Container>,
document.getElementById('root'));
});
};
window.addEventListener('resize', renderApp);
renderApp();
|
entry_types/scrolled/package/src/frontend/PlayerControls/TextTracksMenu.js | tf/pageflow | import React from 'react';
import PropTypes from 'prop-types';
import {MenuBarButton} from './MenuBarButton';
import {useI18n} from '../i18n';
import TextTracksIcon from './images/textTracks.svg';
export function TextTracksMenu(props) {
const {t} = useI18n();
if (props.items.length < 2) {
return null;
}
return (
<MenuBarButton title={t('pageflow_scrolled.public.player_controls.text_tracks')}
icon={TextTracksIcon}
subMenuItems={props.items}
onSubMenuItemClick={props.onItemClick} />
);
}
TextTracksMenu.propTypes = {
items: MenuBarButton.propTypes.subMenuItems,
onMenuItemClick: PropTypes.func
};
TextTracksMenu.defaultProps = {
items: []
};
|
node_modules/rc-util/es/Children/mapSelf.js | ZSMingNB/react-news | import React from 'react';
function mirror(o) {
return o;
}
export default function mapSelf(children) {
// return ReactFragment
return React.Children.map(children, mirror);
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.