path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
client/components/layout/nav.js
|
LIYINGZHEN/meteor-react-redux-base
|
import React from 'react';
import {Link} from 'react-router';
export default (props) => (
<nav className="navbar navbar-default navbar-fixed-top">
<div className="container">
<div className="navbar-header">
<button aria-controls="navbar" aria-expanded="false" data-target="#navbar" data-toggle="collapse" className="navbar-toggle collapsed" type="button">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar" />
<span className="icon-bar" />
<span className="icon-bar" />
</button>
<Link to="/" className="navbar-brand">{props.appName}</Link>
</div>
<div id="navbar" className="navbar-collapse navbar-left collapse">
<ul className="nav navbar-nav">
<li><Link to="/posts">新闻</Link></li>
<li><Link to="/events">活动</Link></li>
<li><Link to="/admin">管理员后台</Link></li>
</ul>
</div>
<ul className="nav navbar-nav navbar-right hidden-xs">
<li className="dropdown">
<a className="dropdown-toggle" id="drop1" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">
Language <span className="caret" />
</a>
<ul className="dropdown-menu" aria-labelledby="drop1">
<li><a href="#" onClick={(e) => props.setLang(e, 'enUS')}>English</a></li>
<li><a href="#" onClick={(e) => props.setLang(e, 'zhCN')}>中文</a></li>
</ul>
</li>
</ul>
</div>
</nav>
);
|
examples/ErrorMessage.js
|
jaredpalmer/formik
|
import React from 'react';
import { Formik, Field, Form, ErrorMessage } from 'formik';
import * as Yup from 'yup';
import { Debug } from './Debug';
// While you can use any validation library (or write you own), Formik
// comes with special support for Yup by @jquense. It has a builder API like
// React PropTypes / Hapi.js's Joi. You can define these inline or, you may want
// to keep them separate so you can reuse schemas (e.g. address) across your application.
const SignUpSchema = Yup.object().shape({
email: Yup.string().email('Invalid email address').required('Required'),
firstName: Yup.string()
.min(2, 'Must be longer than 2 characters')
.max(20, 'Nice try, nobody has a first name that long')
.required('Required'),
lastName: Yup.string()
.min(2, 'Must be longer than 2 characters')
.max(20, 'Nice try, nobody has a last name that long')
.required('Required'),
});
// <ErrorMessage /> will ONLY render when a field has an error and has been touched.
const SignUp = () => (
<div>
<h1>Sign up</h1>
<Formik
initialValues={{
email: '',
firstName: '',
lastName: '',
}}
validationSchema={SignUpSchema}
onSubmit={values => {
setTimeout(() => {
alert(JSON.stringify(values, null, 2));
}, 500);
}}
render={({ errors, touched }) => (
<Form>
<label htmlFor="firstName">First Name</label>
<Field name="firstName" placeholder="Jane" type="text" />
<ErrorMessage
name="firstName"
component="div"
className="field-error"
/>
<label htmlFor="lastName">Last Name</label>
<Field name="lastName" placeholder="Doe" type="text" />
<ErrorMessage name="firstName">
{(msg /** this is the same as the above */) => (
<div className="field-error">{msg}</div>
)}
</ErrorMessage>
<label htmlFor="email">Email</label>
<Field name="email" placeholder="jane@acme.com" type="email" />
{/* This will render a string */}
<ErrorMessage name="email" className="field-error" />
<button type="submit">Submit</button>
<Debug />
</Form>
)}
/>
</div>
);
export default SignUp;
|
webclient/userProfile/changePassword.js
|
souravDutta123/Cognitive-Assistant
|
import React from 'react';
class ChangePassword extends React.Component {
constructor()
{
super();
this.state={
drawerMenu: [],
}
}
componentDidMount()
{
}
render() {
const style={
textAlign: 'center',
};
return(
<div><h1 style={style}>ChangePassword :/</h1></div>
);
}
}
export default ChangePassword;
|
src/svg-icons/notification/airline-seat-recline-normal.js
|
andrejunges/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationAirlineSeatReclineNormal = (props) => (
<SvgIcon {...props}>
<path d="M7.59 5.41c-.78-.78-.78-2.05 0-2.83.78-.78 2.05-.78 2.83 0 .78.78.78 2.05 0 2.83-.79.79-2.05.79-2.83 0zM6 16V7H4v9c0 2.76 2.24 5 5 5h6v-2H9c-1.66 0-3-1.34-3-3zm14 4.07L14.93 15H11.5v-3.68c1.4 1.15 3.6 2.16 5.5 2.16v-2.16c-1.66.02-3.61-.87-4.67-2.04l-1.4-1.55c-.19-.21-.43-.38-.69-.5-.29-.14-.62-.23-.96-.23h-.03C8.01 7 7 8.01 7 9.25V15c0 1.66 1.34 3 3 3h5.07l3.5 3.5L20 20.07z"/>
</SvgIcon>
);
NotificationAirlineSeatReclineNormal = pure(NotificationAirlineSeatReclineNormal);
NotificationAirlineSeatReclineNormal.displayName = 'NotificationAirlineSeatReclineNormal';
NotificationAirlineSeatReclineNormal.muiName = 'SvgIcon';
export default NotificationAirlineSeatReclineNormal;
|
packages/wix-style-react/src/GenericModalLayout/GenericModalLayout.js
|
wix/wix-style-react
|
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import styles from './GenericModalLayout.scss';
export default class GenericModalLayout extends React.PureComponent {
render() {
const { dataHook, fullscreen, header, content, footer } = this.props;
const containerClassNames = classNames(styles.container, {
[styles.fullscreenContainer]: fullscreen,
});
return (
<div
data-hook={dataHook}
className={containerClassNames}
data-fullscreen={Boolean(fullscreen)}
>
<div>{header}</div>
<div className={styles.content}>{content}</div>
<div>{footer}</div>
</div>
);
}
}
GenericModalLayout.propTypes = {
/** Applied as data-hook HTML attribute that can be used in the tests */
dataHook: PropTypes.string,
/** Any node to be rendered */
header: PropTypes.node,
/** Any node to be rendered */
content: PropTypes.node,
/** Any node to be rendered */
footer: PropTypes.node,
/** Is modal layout in fullscreen */
fullscreen: PropTypes.bool,
};
GenericModalLayout.defaultProps = {
fullscreen: false,
};
GenericModalLayout.displayName = 'GenericModalLayout';
|
src/components/ForgotPassword/ForgotPasswordForm.js
|
folio-org/stripes-core
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Field, Form } from 'react-final-form';
import { FormattedMessage } from 'react-intl';
import {
TextField,
Button,
Headline,
Row,
Col,
} from '@folio/stripes-components';
import OrganizationLogo from '../OrganizationLogo';
import AuthErrorsContainer from '../AuthErrorsContainer';
import formStyles from './ForgotPasswordForm.css';
class ForgotPasswordForm extends Component {
static propTypes = {
onSubmit: PropTypes.func.isRequired,
errors: PropTypes.arrayOf(PropTypes.object),
};
static defaultProps = {
errors: []
};
render() {
const {
errors,
onSubmit
} = this.props;
return (
<Form
onSubmit={onSubmit}
render={({ handleSubmit, pristine }) => (
<div className={formStyles.wrap}>
<div className={formStyles.centered}>
<OrganizationLogo />
<form
className={formStyles.form}
data-form="forgot"
onSubmit={handleSubmit}
>
<Headline
size="xx-large"
tag="h1"
data-test-h1
>
<FormattedMessage id="stripes-core.label.forgotPassword" />
</Headline>
<Headline
size="large"
tag="p"
weight="regular"
faded
data-test-p
>
<FormattedMessage id="stripes-core.label.forgotPasswordCallToAction" />
</Headline>
<div className={formStyles.formGroup}>
<Field
id="input-email-or-phone"
component={TextField}
name="userInput"
type="text"
marginBottom0
fullWidth
inputClass={formStyles.input}
validationEnabled={false}
hasClearIcon={false}
autoComplete="on"
autoCapitalize="none"
autoFocus
/>
</div>
<Button
buttonStyle="primary"
id="clickable-login"
name="continue-button"
type="submit"
buttonClass={formStyles.submitButton}
disabled={pristine}
fullWidth
marginBottom0
data-test-submit
>
<FormattedMessage id="stripes-core.button.continue" />
</Button>
<Row center="xs">
<Col xs={12}>
<div
className={formStyles.authErrorsWrapper}
data-test-errors
>
<AuthErrorsContainer
errors={errors}
data-test-container
/>
</div>
</Col>
</Row>
</form>
</div>
</div>
)}
/>
);
}
}
export default ForgotPasswordForm;
|
src/index.js
|
jonathanweiss/pixelboard
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, hashHistory } from 'react-router';
import App from './app.jsx';
import Clock from './apps/clock.jsx';
import FreeText from './apps/freetext.jsx';
import RandomPixels from './apps/random.jsx';
import Draw from './apps/draw.jsx';
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App} />
<Route path="/clock" component={Clock} />
<Route path="/random" component={RandomPixels} />
<Route path="/freetext" component={FreeText} />
<Route path="/draw" component={Draw} />
</Router>
, document.querySelector('#root'));
export default App;
|
code/schritte/redux/7-redux-complete-app/src/main.js
|
st-he/react-workshop
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { composeWithDevTools } from 'redux-devtools-extension';
import Layout from './components/Layout';
import { rootReducer } from './reducers';
import {loadGreetings} from './actions';
const store = createStore(
rootReducer,
composeWithDevTools(applyMiddleware(thunk))
);
// init
store.dispatch(loadGreetings);
const mountNode = document.getElementById('mount');
ReactDOM.render(
<Provider store={store}>
<Layout />
</Provider>,
mountNode
);
|
packages/react/src/components/organisms/HeaderSlim/index.js
|
massgov/mayflower
|
/**
* HeaderSlim module.
* @module @massds/mayflower-react/HeaderSlim
* @requires module:@massds/mayflower-assets/scss/03-organisms/header-slim
*/
import React from 'react';
import PropTypes from 'prop-types';
const HeaderSlim = ({
skipNav,
siteLogo,
mainNav,
utilityNav
}) => (
<div className="ma__header_slim">
{skipNav}
<div className="ma__header_slim__utility">
<div className="ma__header_slim__utility-container ma__container">
{utilityNav}
</div>
</div>
<header className="ma__header_slim__header" id="header">
<div className="ma__header_slim__header-container ma__container">
<div className="ma__header_slim__logo">{siteLogo}</div>
{
mainNav && <div className="ma__header_slim__nav">{mainNav}</div>
}
</div>
</header>
</div>
);
HeaderSlim.propTypes = {
/** A render function that renders SiteLogo component. */
siteLogo: PropTypes.node.isRequired,
/** A render function that renders Anchor link to skip to the main content and bypass the header navigations */
skipNav: PropTypes.node,
/** A render function that renders Navigation items in the blue banner, above the header element */
mainNav: PropTypes.node,
/** A render function that renders Navigation items in the header area */
utilityNav: PropTypes.node
};
export default HeaderSlim;
|
app/packs/src/admin/converter/AdminApp.js
|
ComPlat/chemotion_ELN
|
import React, { Component } from 'react';
import { Button } from 'react-bootstrap';
import ConverterApi from '../../components/fetchers/ConverterFetcher';
import ProfileNewModal from './create/ProfileNewModal';
import ProfileList from './list/ProfileList';
import ProfileEdit from './edit/ProfileEdit';
import ProfileCreate from './create/ProfileCreate';
const initTable = (tableData) => {
const header = {};
if (tableData) {
// eslint-disable-next-line guard-for-in
for (const key in tableData.options) {
header[key] = tableData.options[key][0];
}
}
return {
header,
table: {}
};
};
class AdminApp extends Component {
constructor(props) {
super(props);
this.state = {
status: 'list',
clientId: '',
selectedFile: null,
profiles: [],
tableData: null,
columnList: null,
headerOptions: [],
error: false,
isLoading: false,
uploadModal: false,
uploadType: '',
errorMessage: '',
title: '',
description: '',
tables: [],
identifiers: [],
firstRowIsHeader: [],
currentIdentifier: '',
currentIndex: -1,
};
this.showImportView = this.showImportView.bind(this);
this.showEditView = this.showEditView.bind(this);
this.updateTitle = this.updateTitle.bind(this);
this.updateDescription = this.updateDescription.bind(this);
this.addTable = this.addTable.bind(this);
this.updateTable = this.updateTable.bind(this);
this.removeTable = this.removeTable.bind(this);
this.addHeader = this.addHeader.bind(this);
this.updateHeader = this.updateHeader.bind(this);
this.removeHeader = this.removeHeader.bind(this);
this.addOperation = this.addOperation.bind(this);
this.updateOperation = this.updateOperation.bind(this);
this.removeOperation = this.removeOperation.bind(this);
this.addIdentifier = this.addIdentifier.bind(this);
this.updateIdentifier = this.updateIdentifier.bind(this);
this.removeIdentifier = this.removeIdentifier.bind(this);
this.toggleFirstRowIsHeader = this.toggleFirstRowIsHeader.bind(this);
this.updateFirstRowIsHeader = this.updateFirstRowIsHeader.bind(this);
this.createProfile = this.createProfile.bind(this);
this.updateProfile = this.updateProfile.bind(this);
this.deleteProfile = this.deleteProfile.bind(this);
this.downloadProfile = this.downloadProfile.bind(this);
this.updateFile = this.updateFile.bind(this);
this.uploadFile = this.uploadFile.bind(this);
this.importFile = this.importFile.bind(this);
this.dispatchView = this.dispatchView.bind(this);
this.getTitleforStatus = this.getTitleforStatus.bind(this);
this.showUploadModal = this.showUploadModal.bind(this);
this.hideUploadModal = this.hideUploadModal.bind(this);
this.showImportModal = this.showImportModal.bind(this);
this.handleCreate = this.handleCreate.bind(this);
this.handleUpload = this.handleUpload.bind(this);
this.handleImport = this.handleImport.bind(this);
this.backProfileList = this.backProfileList.bind(this);
}
componentDidMount() {
ConverterApi.fetchProfiles()
.then((profiles) => {
if (profiles) this.setState({ profiles: profiles.profiles, clientId: profiles.client });
});
}
getTitleforStatus() {
if (this.state.status === 'list') {
return `Profiles List [ ${this.state.clientId} ]`;
} else if (this.state.status === 'edit') {
return 'Update Profile';
} else if (this.state.status === 'import') {
return 'Import Profile';
}
return 'Create Profile';
}
showImportView() {
this.setState({ status: 'import' });
}
showUploadModal() {
this.setState({ uploadModal: true, uploadType: 'new' });
}
showImportModal() {
this.setState({ uploadModal: true, uploadType: 'import' });
}
hideUploadModal() {
this.setState({ uploadModal: false, uploadType:'' });
}
showEditView(index, identifier) {
const currentProfile = this.state.profiles[index];
this.setState({
status: 'edit',
currentIdentifier: identifier,
currentIndex: index,
id: currentProfile.id,
title: currentProfile.title,
description: currentProfile.description,
identifiers: currentProfile.identifiers,
header: currentProfile.header,
tables: currentProfile.tables,
firstRowIsHeader: currentProfile.firstRowIsHeader
});
}
updateTitle(title) {
this.setState({
title
});
}
updateDescription(description) {
this.setState({
description
});
}
addTable() {
const { tables, tableData } = this.state;
tables.push(initTable(tableData));
this.setState({ tables });
}
updateTable(index, key, value) {
const tables = [...this.state.tables]
if (index !== -1) {
tables[index].table[key] = value
// remove the column if tableIndex and columnIndex is null
if (Object.values(tables[index].table[key]).every(value => (value === null || isNaN(value)))) {
delete tables[index].table[key];
}
this.setState({ tables });
}
}
removeTable(index) {
const tables = [...this.state.tables];
tables.splice(index, 1);
this.setState({ tables });
}
addHeader(index) {
const tables = [...this.state.tables]
if (index !== -1) {
const key = `HEADER${Object.keys(tables[index].header).length}`;
tables[index].header[key] = '';
}
this.setState({ tables });
}
updateHeader(index, key, value, oldKey) {
const tables = [...this.state.tables];
if (index !== -1) {
if (oldKey === undefined) {
tables[index].header[key] = value;
} else {
// create a new header to preserve the order
tables[index].header = Object.keys(tables[index].header).reduce((agg, cur) => {
if (cur == oldKey) {
agg[key] = value;
} else {
agg[cur] = tables[index].header[cur];
}
return agg;
}, {});
}
this.setState({ tables });
}
}
removeHeader(index, key) {
const tables = [...this.state.tables];
delete tables[index].header[key];
this.setState({ tables });
}
addOperation(index, key, type) {
const tables = [...this.state.tables];
if (index !== -1) {
const operation = {
type,
operator: '+'
};
if (type == 'column') {
operation['column'] = {
tableIndex: null,
columnIndex: null
};
}
if (tables[index].table[key] === undefined) {
tables[index].table[key] = [];
}
tables[index].table[key].push(operation);
this.setState({ tables });
}
}
updateOperation(index, key, opIndex, opKey, value) {
const tables = [...this.state.tables];
if (index !== -1) {
tables[index].table[key][opIndex][opKey] = value;
this.setState({ tables });
}
}
removeOperation(index, key, opIndex) {
const tables = [...this.state.tables];
if (index !== -1) {
tables[index].table[key].splice(opIndex, 1);
// remove operations if it is empty
if (tables[index].table[key].length == 0) {
delete tables[index].table[key];
}
this.setState({ tables });
}
}
addIdentifier(type) {
const { identifiers } = this.state
let metadataKey = '';
let value = '';
if (type === 'metadata' && this.state.status == 'create') {
metadataKey = Object.keys(this.state.tableData.metadata)[0];
value = this.state.tableData.metadata[metadataKey];
}
const identifier = {
type,
tableIndex: 0,
lineNumber: '',
metadataKey,
headerKey: '',
value,
isRegex: false
};
identifiers.push(identifier);
this.setState({ identifiers });
}
updateIdentifier(index, data) {
const identifiers = [...this.state.identifiers];
if (index !== -1) {
const identifier = identifiers[index];
Object.assign(identifier, data);
identifiers[index] = identifier;
this.setState({ identifiers });
}
}
removeIdentifier(index) {
const identifiers = [...this.state.identifiers];
if (index !== -1) {
identifiers.splice(index, 1);
this.setState({ identifiers });
}
}
updateFirstRowIsHeader(index, checked) {
const firstRowIsHeader = [...this.state.firstRowIsHeader];
firstRowIsHeader[index] = checked;
this.setState({ firstRowIsHeader });
}
toggleFirstRowIsHeader(index) {
const { tableData } = this.state;
const table = tableData.data[index];
if (table.firstRowIsHeader) {
table.firstRowIsHeader = false;
table.columns = table._columns;
table.rows.splice(0, 0, table._first);
table._columns = null;
table._first = null;
} else {
table.firstRowIsHeader = true;
table._columns = table.columns;
table._first = table.rows.shift();
table.columns = table._first.map((value, idx) => {
const originalName = table._columns[idx].name;
return {
key: idx.toString(),
name: value + ` (${originalName})`
}
})
}
const firstRowIsHeader = tableData.data.map(_table => _table.firstRowIsHeader || false);
this.setState({ tableData, firstRowIsHeader });
}
handleImport(context) {
const { uploadType } = this.state;
if (uploadType === 'import') {
this.handleUpload(context);
}
if (uploadType === 'new') {
this.handleCreate(context);
}
}
handleUpload(context) {
const createProfile = (e) => {
const profile = JSON.parse(e.target.result);
ConverterApi.createProfile(profile)
.then(() => {
ConverterApi.fetchProfiles()
.then((profiles) => {
this.setState({ profiles: profiles.profiles, uploadModal: false, uploadType: '' });
});
})
.catch((errors) => {
this.setState({
error: true,
errorMessage: Object.values(errors).join(', '),
isLoading: false
});
});
};
const reader = new FileReader();
reader.readAsText(context);
reader.onload = createProfile.bind(this);
}
handleCreate(context) {
const { uploadType } = this.state;
console.log(uploadType);
let profile = context;
if (uploadType === 'import') {
console.log(context);
profile = JSON.parse(context);
}
console.log(profile);
ConverterApi.fetchTables(profile)
.then((tableData) => {
if (tableData.error) {
//
} else {
// create a flat list of all columns
const columnList = tableData.data.reduce((accumulator, table, tableIndex) => {
const tableColumns = table.columns.map((tableColumn, columnIndex) => {
return Object.assign({}, tableColumn, {
label: `Table #${tableIndex} Column #${columnIndex}`,
value: {
tableIndex,
columnIndex
}
});
});
return accumulator.concat(tableColumns);
}, []);
this.setState({
selectedFile: null,
isLoading: false,
tableData,
columnList,
headerOptions: tableData.options,
tables: [initTable(tableData)],
identifiers: [],
firstRowIsHeader: tableData.data.map(table => false),
error: false,
status: 'create',
errorMessage: ''
});
}
}).catch((errorMessage) => {
console.log(errorMessage);
});
this.hideUploadModal();
}
backProfileList(event) {
this.setState({
status: 'list',
title: '',
description: '',
identifiers: [],
header: {},
table: {},
currentIdentifier: '',
currentIndex: -1,
});
}
createProfile(event) {
event.preventDefault();
const {
title, description, tables, identifiers, tableData, firstRowIsHeader
} = this.state;
const profile = {
title,
description,
tables,
identifiers,
firstRowIsHeader
};
ConverterApi.createProfile(profile)
.then((data) => {
const newProfiles = [...this.state.profiles];
newProfiles.push(data);
this.setState({
profiles: newProfiles,
status: 'list',
title: '',
description: '',
identifiers: [],
header: {},
table: {},
currentIdentifier: '',
currentIndex: -1,
showAlert: true
});
// $('#modal').show()
})
.catch(() => ({
errors: {
path: 'File not found'
}
}));
}
updateProfile() {
const {
id, title, description, tables, identifiers, tableData, firstRowIsHeader
} = this.state;
const profile = {
id,
title,
description,
tables,
identifiers,
firstRowIsHeader
};
ConverterApi.updateProfile(profile, this.state.currentIdentifier)
.then((data) => {
const newProfiles = [...this.state.profiles];
newProfiles[this.state.currentIndex] = data;
this.setState({
profiles: newProfiles,
status: 'list',
title: '',
description: '',
identifiers: [],
header: {},
table: {},
currentIdentifier: '',
currentIndex: -1,
showAlert: true
});
});
}
// deleteProfile() {
deleteProfile(index, identifier) {
ConverterApi.deleteProfile(identifier)
.then(() => {
const newProfiles = [...this.state.profiles];
if (index !== -1) {
newProfiles.splice(index, 1);
this.setState({
profiles: newProfiles,
});
}
});
}
downloadProfile(index, identifier) {
const a = document.createElement('a');
a.href = `data:application/json;charset=utf-8,${encodeURIComponent(JSON.stringify(this.state.profiles[index], null, 2))}`;
a.download = `${identifier}.json`;
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
}
updateFile(event) {
this.setState({
selectedFile: event.target.files[0],
loaded: 0,
isLoading: false,
error: false,
errorMessage: ''
});
}
uploadFile() {
const { selectedFile } = this.state;
this.setState({
isLoading: true
});
ConverterApi.fetchTables(selectedFile)
.then((tableData) => {
if (tableData) {
// create a flat list of all columns
const columnList = tableData.data.reduce((accumulator, table, tableIndex) => {
const tableColumns = table.columns.map((tableColumn, columnIndex) => Object.assign({}, tableColumn, {
label: `Table #${tableIndex} Column #${columnIndex}`,
value: {
tableIndex,
columnIndex
}
}));
return accumulator.concat(tableColumns);
}, []);
this.setState({
selectedFile: null,
isLoading: false,
tableData,
columnList,
headerOptions: tableData.options,
tables: [initTable(tableData)],
identifiers: [],
firstRowIsHeader: tableData.data.map(() => false),
error: false,
errorMessage: ''
});
}
})
.catch(error => {
if (error.status === 413) {
this.setState({
error: true,
errorMessage: 'The uploaded file is too large.',
isLoading: false
})
} else {
error.text().then(errorMessage => {
this.setState({
error: true,
errorMessage: JSON.parse(errorMessage).error,
isLoading: false
})
})
}
})
}
importFile() {
const { selectedFile } = this.state;
this.setState({
isLoading: true
});
const createProfile = e => {
const profile = JSON.parse(e.target.result)
ConverterApi.createProfile(profile)
.then(data => {
this.setState({
status: 'list',
selectedFile: null,
isLoading: false,
error: false,
errorMessage: ''
})
})
.catch(errors => {
this.setState({
error: true,
errorMessage: Object.values(errors).join(', '),
isLoading: false
})
})
}
const reader = new FileReader();
reader.readAsText(selectedFile);
reader.onload = createProfile.bind(this);
}
dispatchView() {
const {
tableData, status, error, errorMessage, isLoading, selectedFile
} = this.state;
if (status === 'list') {
return (
<ProfileList
profiles={this.state.profiles}
editProfile={this.showEditView}
deleteProfile={this.deleteProfile}
downloadProfile={this.downloadProfile}
/>
);
} else if (status === 'edit') {
return (
<ProfileEdit
id={this.state.id}
title={this.state.title}
description={this.state.description}
tables={this.state.tables}
identifiers={this.state.identifiers}
firstRowIsHeader={this.state.firstRowIsHeader}
updateTitle={this.updateTitle}
updateDescription={this.updateDescription}
addTable={this.addTable}
updateTable={this.updateTable}
removeTable={this.removeTable}
addHeader={this.addHeader}
updateHeader={this.updateHeader}
removeHeader={this.removeHeader}
addOperation={this.addOperation}
updateOperation={this.updateOperation}
removeOperation={this.removeOperation}
addIdentifier={this.addIdentifier}
updateIdentifier={this.updateIdentifier}
removeIdentifier={this.removeIdentifier}
updateFirstRowIsHeader={this.updateFirstRowIsHeader}
updateProfile={this.updateProfile}
backProfileList={this.backProfileList}
/>
);
} else if (status === 'create') {
if (tableData) {
return (
<ProfileCreate
tableData={this.state.tableData}
columnList={this.state.columnList}
toggleFirstRowIsHeader={this.toggleFirstRowIsHeader}
headerOptions={this.state.headerOptions}
title={this.state.title}
description={this.state.description}
identifiers={this.state.identifiers}
tables={this.state.tables}
updateTitle={this.updateTitle}
updateDescription={this.updateDescription}
addTable={this.addTable}
updateTable={this.updateTable}
removeTable={this.removeTable}
updateHeader={this.updateHeader}
addOperation={this.addOperation}
updateOperation={this.updateOperation}
removeOperation={this.removeOperation}
addIdentifier={this.addIdentifier}
updateIdentifier={this.updateIdentifier}
removeIdentifier={this.removeIdentifier}
createProfile={this.createProfile}
backProfileList={this.backProfileList}
/>
);
}
}
return (<span />);
}
render() {
return (
<div>
<header>
<nav aria-label="breadcrumb">
{this.state.status === 'list' &&
<ol className="breadcrumb">
<li className="breadcrumb-item active" aria-current="page">Chemotion file converter admin</li>
</ol>
}
{this.state.status === 'edit' &&
<ol className="breadcrumb">
<li className="breadcrumb-item" aria-current="page">Chemotion file converter admin</li>
<li className="breadcrumb-item active" aria-current="page">Edit Profile: + {this.state.title}</li>
</ol>
}
{this.state.status === 'create' &&
<ol className="breadcrumb">
<li className="breadcrumb-item" aria-current="page">Chemotion file converter admin</li>
<li className="breadcrumb-item active" aria-current="page">Create Profile</li>
</ol>
}
{this.state.status === 'import' &&
<ol className="breadcrumb">
<li className="breadcrumb-item" aria-current="page">Chemotion file converter admin</li>
<li className="breadcrumb-item active" aria-current="page">Import Profile</li>
</ol>
}
</nav>
<div>
{this.state.status === 'list' &&
<div className="float-right">
<Button bsStyle="info" bsSize="small" onClick={this.showImportModal}>
Import profile <i className="fa fa-upload" aria-hidden="true" />
</Button>
<Button bsStyle="primary" bsSize="small" onClick={this.showUploadModal}>
Create new profile <i className="fa fa-plus" aria-hidden="true" />
</Button>
</div>
}
<h2 className="mb-0">{this.getTitleforStatus()}</h2>
</div>
</header>
<main>
{this.dispatchView()}
</main>
<ProfileNewModal
content="Profile"
showModal={this.state.uploadModal}
fnClose={this.hideUploadModal}
fnCreate={this.handleImport}
/>
<div className="modal modal-backdrop" data-backdrop="static" id="modal" tabIndex="-1">
<div className="modal-dialog modal-dialog-centered">
<div className="modal-content">
<div className="modal-body">
<div className="alert alert-success" role="alert">Profile successfully created!</div>
</div>
<div className="modal-footer">
<a href="." className="btn btn-secondary">Back to profiles list</a>
<a href="/" className="btn btn-primary">Upload file and use profile</a>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default AdminApp;
|
src/boilerplate-layout/components/layout/elements/loading.js
|
joropeza/react-fullscreen-app-boilerplate
|
import React from 'react';
const Loading = () => (
<div>
<p className="center" style={{ marginTop: 100, opacity: 0.5 }}>
<i className="fa fa-cog fa-spin fa-5x" />
</p>
</div>
);
export default Loading;
|
src/routes/Counter/components/Counter.js
|
wookiecookie87/lunch_group_creator_with_reactjs
|
import React from 'react'
import PropTypes from 'prop-types'
export const Counter = ({ counter, increment, doubleAsync }) => (
<div style={{ margin: '0 auto' }} >
<h2>Counter: {counter}</h2>
<button className='btn btn-primary' onClick={increment}>
Increment
</button>
{' '}
<button className='btn btn-secondary' onClick={doubleAsync}>
Double (Async)
</button>
</div>
)
Counter.propTypes = {
counter: PropTypes.number.isRequired,
increment: PropTypes.func.isRequired,
doubleAsync: PropTypes.func.isRequired,
}
export default Counter
|
test/routes/home.spec.js
|
rafaelfbs/rmodel
|
/* eslint-env node, mocha */
const expect = (require('chai')).expect
import React from 'react'
import { render } from 'enzyme'
describe('Home route', function () {
it('should show a route content', function () {
return System.import('routes/home').then((Home) => {
Home = Home.default
const wrapper = render(<Home />)
// console.log(wrapper.html())
return expect(wrapper.text()).to.contain('Home route')
})
})
})
|
js/components/common/AddLocationModal.js
|
a-omsk/Vegreact
|
import React from 'react';
import Modal from 'react-modal';
import AddLocationForm from './AddLocationForm';
const modalStyle = {
overlay: {
zIndex: 10,
},
content: {
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
justifyContent: 'center',
height: '80%',
width: '60%',
margin: 'auto',
},
};
const AddLocationModal = (props) => (
<Modal
isOpen={props.opened}
style={modalStyle}
onRequestClose={props.closeHandler}
>
<AddLocationForm {...props} />
</Modal>
);
AddLocationModal.propTypes = {
opened: React.PropTypes.bool.isRequired,
closeHandler: React.PropTypes.func.isRequired,
};
export default AddLocationModal;
|
src/svg-icons/social/sentiment-satisfied.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let 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 = pure(SocialSentimentSatisfied);
SocialSentimentSatisfied.displayName = 'SocialSentimentSatisfied';
SocialSentimentSatisfied.muiName = 'SvgIcon';
export default SocialSentimentSatisfied;
|
src/svg-icons/av/fiber-dvr.js
|
IsenrichO/mui-with-arrows
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvFiberDvr = (props) => (
<SvgIcon {...props}>
<path d="M17.5 10.5h2v1h-2zm-13 0h2v3h-2zM21 3H3c-1.11 0-2 .89-2 2v14c0 1.1.89 2 2 2h18c1.11 0 2-.9 2-2V5c0-1.11-.89-2-2-2zM8 13.5c0 .85-.65 1.5-1.5 1.5H3V9h3.5c.85 0 1.5.65 1.5 1.5v3zm4.62 1.5h-1.5L9.37 9h1.5l1 3.43 1-3.43h1.5l-1.75 6zM21 11.5c0 .6-.4 1.15-.9 1.4L21 15h-1.5l-.85-2H17.5v2H16V9h3.5c.85 0 1.5.65 1.5 1.5v1z"/>
</SvgIcon>
);
AvFiberDvr = pure(AvFiberDvr);
AvFiberDvr.displayName = 'AvFiberDvr';
AvFiberDvr.muiName = 'SvgIcon';
export default AvFiberDvr;
|
app/components/ConArticle.js
|
Toreant/monster_web
|
/**
* Created by apache on 15-11-14.
*/
import React from 'react';
import ConList from './ConList';
class ConArticle extends React.Component {
constructor(props) {
super(props);
}
render() {
let Result;
if(this.props.params.domain !== undefined) {
Result = (
<ConList tab={this.props.params.column || 'article'} domain={this.props.params.domain} />
);
}
return (
<div>
{Result}
</div>
);
}
}
export default ConArticle;
|
src/common/components/ErrorMessage.js
|
algernon/mad-tooter
|
// @flow
/* The Mad Tooter -- A Mastodon client
* Copyright (C) 2017 Gergely Nagy
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { connect } from 'react-redux';
import Snackbar from 'material-ui/Snackbar';
import { withStyles } from 'material-ui/styles';
const styles = theme => ({
snackbar: {
bottom: theme.spacing.unit,
right: 'auto',
left: theme.spacing.unit,
},
});
class ErrorMessage extends React.Component {
handleRequestClose = () => {
this.props.dispatch({type: 'HIDE_ERROR'});
}
render() {
const { show, message, classes, transient } = this.props;
return (
<Snackbar open={show}
message={<span>{message}</span>}
onRequestClose={this.handleRequestClose}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'left',
}}
autoHideDuration={transient ? 5000 : null}
classes={{
anchorBottomLeft: classes.snackbar,
}} />
);
}
}
const stateToProps = (state, props) => ({
message: state.getIn(["error", "message"]),
show: state.getIn(["error", "show"]),
transient: state.getIn(["error", "transient"]),
});
export default connect(stateToProps)(withStyles(styles)(ErrorMessage));
|
packages/react-router-dom/modules/__tests__/Link-test.js
|
goblortikus/react-router
|
import expect from 'expect'
import React from 'react'
import ReactDOM from 'react-dom'
import MemoryRouter from 'react-router/MemoryRouter'
import HashRouter from '../HashRouter'
import Link from '../Link'
describe('A <Link>', () => {
it('accepts a location "to" prop', () => {
const location = {
pathname: '/the/path',
search: 'the=query',
hash: '#the-hash'
}
const node = document.createElement('div')
ReactDOM.render((
<MemoryRouter>
<Link to={location}>link</Link>
</MemoryRouter>
), node)
const href = node.querySelector('a').getAttribute('href')
expect(href).toEqual('/the/path?the=query#the-hash')
})
})
describe('When a <Link> is clicked', () => {
it('calls its onClick handler')
it('changes the location')
describe('and the onClick handler calls event.preventDefault()', () => {
it('does not change the location')
})
})
describe('A <Link> underneath a <HashRouter>', () => {
const node = document.createElement('div')
afterEach(() => {
ReactDOM.unmountComponentAtNode(node)
})
const createLinkNode = (hashType, to) => {
ReactDOM.render((
<HashRouter hashType={hashType}>
<Link to={to}/>
</HashRouter>
), node)
return node.querySelector('a')
}
describe('with the "slash" hashType', () => {
it('has the correct href', () => {
const linkNode = createLinkNode('slash', '/foo')
expect(linkNode.getAttribute('href')).toEqual('#/foo')
})
it('has the correct href with a leading slash if it is missing', () => {
const linkNode = createLinkNode('slash', 'foo')
expect(linkNode.getAttribute('href')).toEqual('#/foo')
})
})
describe('with the "hashbang" hashType', () => {
it('has the correct href', () => {
const linkNode = createLinkNode('hashbang', '/foo')
expect(linkNode.getAttribute('href')).toEqual('#!/foo')
})
it('has the correct href with a leading slash if it is missing', () => {
const linkNode = createLinkNode('hashbang', 'foo')
expect(linkNode.getAttribute('href')).toEqual('#!/foo')
})
})
describe('with the "noslash" hashType', () => {
it('has the correct href', () => {
const linkNode = createLinkNode('noslash', 'foo')
expect(linkNode.getAttribute('href')).toEqual('#foo')
})
it('has the correct href and removes the leading slash', () => {
const linkNode = createLinkNode('noslash', '/foo')
expect(linkNode.getAttribute('href')).toEqual('#foo')
})
})
})
|
plugins/Files/js/components/unlockwarning.js
|
NebulousLabs/New-Sia-UI
|
import PropTypes from 'prop-types'
import React from 'react'
const UnlockWarning = ({ onClick }) => (
<div className='allowance-dialog unlock-warning'>
<h1 className='unlock-warning-head'>
Your wallet must be unlocked and synchronized to buy storage.
</h1>
<div className='allowance-buttons'>
<button onClick={onClick} className='allowance-button-accept'>
OK
</button>
</div>
</div>
)
UnlockWarning.propTypes = {
onClick: PropTypes.func.isRequired
}
export default UnlockWarning
|
src/app/components/forms/inputs/XEditable.js
|
backpackcoder/world-in-flames
|
import React from 'react'
import 'X-editable/dist/bootstrap3-editable/js/bootstrap-editable.js'
import _ from 'lodash'
export default class XEditable extends React.Component {
componentDidMount() {
this.xEditable()
}
componentDidUpdate() {
this.xEditable()
}
xEditable = ()=> {
const element = $(this.refs.input);
const props = this.props;
const options = {...props};
// $log.log(initOptions);
element.editable('destroy');
element.editable(options);
element.on('save', (e, params) =>{
if (_.isFunction(this.props.onChange)) {
this.props.onChange(params.newValue)
}
});
};
onClick = (e) => {
e.preventDefault();
if (_.isFunction(this.props.onClick))
this.props.onClick();
}
render() {
const {children, ...props} = this.props;
const id = props.id || _.uniqueId('x-editable');
return (
<a href="#" onClick={this.onClick} id={id} ref="input">
{children}
</a>
)
}
}
|
src/svg-icons/social/sentiment-very-satisfied.js
|
mtsandeep/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialSentimentVerySatisfied = (props) => (
<SvgIcon {...props}>
<path d="M11.99 2C6.47 2 2 6.47 2 12s4.47 10 9.99 10S22 17.53 22 12 17.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 8zm1-10.06L14.06 11l1.06-1.06L16.18 11l1.06-1.06-2.12-2.12zm-4.12 0L9.94 11 11 9.94 8.88 7.82 6.76 9.94 7.82 11zM12 17.5c2.33 0 4.31-1.46 5.11-3.5H6.89c.8 2.04 2.78 3.5 5.11 3.5z"/>
</SvgIcon>
);
SocialSentimentVerySatisfied = pure(SocialSentimentVerySatisfied);
SocialSentimentVerySatisfied.displayName = 'SocialSentimentVerySatisfied';
SocialSentimentVerySatisfied.muiName = 'SvgIcon';
export default SocialSentimentVerySatisfied;
|
packages/component/src/SendBox/Assets/MicrophoneIcon.js
|
billba/botchat
|
import React from 'react';
const MicrophoneIcon = () => (
<svg height={28} viewBox="0 0 34.75 46" width={28}>
<path
className="a"
d="M29.75,23v6.36a7,7,0,0,1-.56,2.78,7.16,7.16,0,0,1-3.8,3.8,7,7,0,0,1-2.78.56H18.5v2.25H23V41H11.75v-2.25h4.5V36.5h-4.11a7,7,0,0,1-2.78-.56,7.16,7.16,0,0,1-3.8-3.8,7,7,0,0,1-.56-2.78V23h2.25v6.36a4.72,4.72,0,0,0,.39,1.9,4.78,4.78,0,0,0,2.6,2.6,4.72,4.72,0,0,0,1.9.39h10.47a4.72,4.72,0,0,0,1.9-.39,4.78,4.78,0,0,0,2.6-2.6,4.72,4.72,0,0,0,.39-1.9V23Zm-18,5.62a1.13,1.13,0,0,0,1.13,1.13h9a1.13,1.13,0,0,0,1.12-1.13V8.38a1.13,1.13,0,0,0-1.12-1.13h-9a1.13,1.13,0,0,0-1.13,1.13Zm1.13,3.38a3.41,3.41,0,0,1-1.32-.26,3.31,3.31,0,0,1-1.8-1.8,3.41,3.41,0,0,1-.26-1.32V8.38a3.41,3.41,0,0,1,.26-1.32,3.31,3.31,0,0,1,1.8-1.8,3.41,3.41,0,0,1,1.32-.26h9a3.4,3.4,0,0,1,1.31.26,3.31,3.31,0,0,1,1.8,1.8,3.41,3.41,0,0,1,.26,1.32v20.24a3.41,3.41,0,0,1-.26,1.32,3.31,3.31,0,0,1-1.8,1.8,3.4,3.4,0,0,1-1.31.26Z"
/>
</svg>
);
export default MicrophoneIcon;
|
src/views/containers/pages/error_page/error_page.js
|
michaelBenin/react-ssr-spa
|
import React from 'react';
import PropTypes from 'prop-types';
import Footer from './../../../components/footer/footer';
function ErrorPage({ env, componentInfo, err }) {
const isDevelopment = env === 'development';
if (isDevelopment) {
console.error(err); // eslint-disable-line no-console
console.error(err.stack); // eslint-disable-line no-console
}
return (
<div className="error-page">
<h1>Error Occurred.</h1>
{isDevelopment ? (
<div>
<h2>Error Message: {err.message}</h2>
<h2>Error Stack: {JSON.stringify(err.stack, null, 2)}</h2>
<h2>Component Info: {JSON.stringify(componentInfo, null, 2)}</h2>
</div>
) : (
<p>We\'re sorry please try again later.</p>
)}
<Footer />
</div>
);
}
ErrorPage.propTypes = {
err: PropTypes.shape({}),
componentInfo: PropTypes.shape({}),
env: PropTypes.string.isRequired
};
ErrorPage.defaultProps = {
err: {},
componentInfo: {}
};
export default ErrorPage;
|
packages/material-ui-icons/src/FeaturedPlayList.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let FeaturedPlayList = props =>
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-9 8H3V9h9v2zm0-4H3V5h9v2z" />
</SvgIcon>;
FeaturedPlayList = pure(FeaturedPlayList);
FeaturedPlayList.muiName = 'SvgIcon';
export default FeaturedPlayList;
|
react-ui/src/components/UpdateEmail/UpdateEmail.js
|
hokustalkshow/find-popular
|
import React, { Component } from 'react';
import ErrorAlert from '../ErrorAlert/ErrorAlert';
import SpinnerOnly from '../Spinner/SpinnerOnly';
class UpdateEmail extends Component {
constructor(props) {
super(props);
this.state = {
showEmailForm: false,
newEmail: '',
}
}
displayEmailForm = () => {
this.setState({
showEmailForm: true,
});
}
hideEmailForm = () => {
this.setState({
showEmailForm: false,
});
}
emailInput = (e) => {
this.setState({
newEmail: e.target.value,
});
}
updateEmail = (e) => {
e.preventDefault();
this.props.updateEmail(this.props.id, this.state.newEmail)
this.hideEmailForm();
}
viewOrUpdateEmail = () => {
if (this.props.loading) {
return <SpinnerOnly />
}
if (!this.state.showEmailForm) {
return (
<div>
{this.props.email}
<button onClick={this.displayEmailForm} className="btn btn-link">Change Email</button>
</div>
);
}
return (
<form className="form-group" onSubmit={this.updateEmail}>
<input className="form-control" type="email" placeholder="johndoe@example.com" onChange={this.emailInput} />
<br />
<button className="btn btn-primary" type="submit">Submit</button>
<button className="btn btn-default" onClick={this.hideEmailForm}>Cancel</button>
<ErrorAlert errorMessage={this.props.errorMessage} />
</form>
);
}
render() {
return (
<div>
{this.viewOrUpdateEmail()}
</div>
);
}
}
export default UpdateEmail;
|
app/js/components/PITApp.js
|
makeing/PIT.react
|
import React from 'react';
import ProjectList from './Project/ProjectList';
import ProjectStore from '../stores/ProjectStore';
function getProjectState() {
return {
allProjects: ProjectStore.getAll()
};
}
export default class PITApp extends React.Component {
constructor(props) {
super(props);
this.state = getProjectState();
}
componentDidMount() {
ProjectStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
ProjectStore.removeChangeListener(this._onChange);
}
render() {
return (
);
}
_onChange() {
this.setState(getProjectState());
}
}
|
src/js/components/nodes/NodesToolbar/NodesToolbarForm.js
|
knowncitizen/tripleo-ui
|
/**
* Copyright 2017 Red Hat Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may
* not use this file except in compliance with the License. You may obtain
* a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
import { defineMessages, FormattedMessage, injectIntl } from 'react-intl';
import { Field, reduxForm } from 'redux-form';
import { FormGroup, MenuItem } from 'react-bootstrap';
import PropTypes from 'prop-types';
import React from 'react';
import DropdownSelect from '../../ui/reduxForm/DropdownSelect';
import { nodeColumnMessages } from '../messages';
import { SortDirectionInput } from '../../ui/Toolbar/ToolbarInputs';
const messages = defineMessages({
table: {
id: 'ContentView.table',
defaultMessage: 'Table view'
},
list: {
id: 'ContentView.list',
defaultMessage: 'List view'
},
sortDir: {
id: 'NodesToolbarForm.sortDir',
defaultMessage: 'Sort direction'
}
});
const NodesToolbarForm = ({ handleSubmit, intl }) => (
<form onSubmit={handleSubmit}>
<FormGroup>
<Field
name="sortBy"
component={DropdownSelect}
format={value => intl.formatMessage(nodeColumnMessages[value])}
>
<MenuItem eventKey="name">
<FormattedMessage {...nodeColumnMessages.name} />
</MenuItem>
<MenuItem eventKey="properties.cpu_arch">
<FormattedMessage {...nodeColumnMessages['properties.cpu_arch']} />
</MenuItem>
<MenuItem eventKey="properties.cpus">
<FormattedMessage {...nodeColumnMessages['properties.cpus']} />
</MenuItem>
<MenuItem eventKey="properties.local_gb">
<FormattedMessage {...nodeColumnMessages['properties.local_gb']} />
</MenuItem>
<MenuItem eventKey="properties.memory_mb">
<FormattedMessage {...nodeColumnMessages['properties.memory_mb']} />
</MenuItem>
<MenuItem eventKey="power_state">
<FormattedMessage {...nodeColumnMessages.power_state} />
</MenuItem>
<MenuItem eventKey="provision_state">
<FormattedMessage {...nodeColumnMessages.provision_state} />
</MenuItem>
</Field>
<Field
name="sortDir"
title={intl.formatMessage(messages.sortDir)}
component={SortDirectionInput}
/>
</FormGroup>
{/*
TODO(akrivoka): Hiding the view switcher for now, as the table view is buggy. Once the blueprint
https://blueprints.launchpad.net/tripleo/+spec/ui-rework-nodestableview
is implemented, we can show the view switcher again.
*/}
{/*
<FormGroup className="pull-right">
<Field
name="contentView"
component={ContentViewSelectorInput}
options={{
list: {
title: intl.formatMessage(messages.list),
id: 'NodesToolbarForm__listView'
},
table: {
title: intl.formatMessage(messages.table),
id: 'NodesToolbarForm__tableView'
}
}}
/>
</FormGroup>
*/}
</form>
);
NodesToolbarForm.propTypes = {
children: PropTypes.node,
handleSubmit: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired
};
export default injectIntl(
reduxForm({
form: 'nodesToolbar'
})(NodesToolbarForm)
);
|
local-cli/templates/HelloWorld/__tests__/index.android.js
|
DanielMSchmidt/react-native
|
import 'react-native';
import React from 'react';
import Index from '../index.android.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
tests/lib/rules/vars-on-top.js
|
bbondy/eslint
|
/**
* @fileoverview Tests for vars-on-top rule.
* @author Danny Fritz
* @author Gyandeep Singh
* @copyright 2014 Danny Fritz. All rights reserved.
* @copyright 2014 Gyandeep Singh. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var eslint = require("../../../lib/eslint"),
EslintTester = require("eslint-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var eslintTester = new EslintTester(eslint);
eslintTester.addRuleTest("lib/rules/vars-on-top", {
valid: [
[
"var first = 0;",
"function foo() {",
" first = 2;",
"}"
].join("\n"),
[
"function foo() {",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" if (true) {",
" first = true;",
" } else {",
" first = 1;",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" var third;",
" var fourth = 1, fifth, sixth = third;",
" var seventh;",
" if (true) {",
" third = true;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var i;",
" for (i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var outer;",
" function inner() {",
" var inner = 1;",
" var outer = inner;",
" }",
" outer = 1;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" //Hello",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" /*",
" Hello Clarice",
" */",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var first;",
" first = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var third;",
" third = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var bar = function(){",
" var third;",
" third = 5;",
" }",
" first = 5;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" first.onclick(function(){",
" var third;",
" third = 5;",
" });",
" first = 5;",
"}"
].join("\n"),
{
code: [
"function foo() {",
" var i = 0;",
" for (let j = 0; j < 10; j++) {",
" alert(j);",
" }",
" i = i + 1;",
"}"
].join("\n"),
ecmaFeatures: {
blockBindings: true
}
},
"'use strict'; var x; f();",
"'use strict'; 'directive'; var x; var y; f();",
"function f() { 'use strict'; var x; f(); }",
"function f() { 'use strict'; 'directive'; var x; var y; f(); }",
{code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}
],
invalid: [
{
code: [
"var first = 0;",
"function foo() {",
" first = 2;",
" second = 2;",
"}",
"var second = 0;"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" first = 1;",
" first = 2;",
" first = 3;",
" first = 4;",
" var second = 1;",
" second = 2;",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" if (true) {",
" var second = true;",
" }",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" for (var i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" for (i = 0; i < first; i ++) {",
" var second = i;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" switch (first) {",
" case 10:",
" var hello = 1;",
" break;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" var hello = 1;",
" } catch (e) {",
" alert('error');",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" asdf;",
" } catch (e) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" while (first) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" do {",
" var hello = 1;",
" } while (first == 10);",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" for (var item in first) {",
" item++;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"var foo = () => {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
ecmaFeatures: { arrowFunctions: true },
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: "'use strict'; 0; var x; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "'use strict'; var x; 'directive'; var y; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; 0; var x; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
}
]
});
|
src/components/Clock.js
|
LBNL-UCB-STI/beam-viz
|
/*
* A stateless css-clock component
* Props: time (in seconds)
*/
import React from 'react';
import './Clock.scss';
const getHoursAngle = (time_in_seconds) => {
const time_in_hours = time_in_seconds / (60 * 60);
return time_in_hours * (360 / 12);
}
const getMinutesAngle = (time_in_seconds) => {
const time_in_minutes = time_in_seconds / 60;
return time_in_minutes * (360 / 60);
}
const Clock = ({ time }) => (
<div id='clock'>
<div className='hours-container'>
<div className='hours'
style={{
transform: 'rotateZ(' + getHoursAngle(time) + 'deg)',
WebkitTransform: 'rotateZ(' + getHoursAngle(time) + 'deg)',
}}
/>
</div>
<div className='minutes-container'>
<div className='minutes'
style={{
transform: 'rotateZ(' + getMinutesAngle(time) + 'deg)',
}}
/>
</div>
<div className='twstyle'>{parseInt(time)}</div>
</div>
);
export default Clock;
|
client/src/components/plugins/mention-highlighter.js
|
shamb0t/orbit
|
// Based on https://github.com/banyan/react-emoji
import React from 'react';
import assign from 'object-assign';
let MentionHighlighter = () => {
return {
highlight(srcText, highlightText, options = {}) {
if(typeof srcText !== 'string') return srcText;
if(!srcText || !highlightText) return srcText;
if(highlightText === '' || srcText === '') return srcText;
const result = srcText.split(' ').map(word => {
let match = word.startsWith(highlightText)
|| word.startsWith(highlightText + ":")
|| word.startsWith("@" + highlightText)
|| word.startsWith(highlightText + ",");
if (match) {
return React.createElement(
'span',
assign({className: options.highlightClassName}, options),
word + " "
);
} else {
return word + " ";
}
});
let r = [];
let s = '';
result.forEach((e) => {
if(typeof e === 'string') {
s += e;
} else {
r.push(s);
r.push(e);
s = '';
}
});
r.push(s);
return r;
}
};
};
export default MentionHighlighter();
|
fields/types/geopoint/GeoPointColumn.js
|
xyzteam2016/keystone
|
import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var GeoPointColumn = React.createClass({
displayName: 'GeoPointColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
const formattedValue = `${value[1]}, ${value[0]}`;
const formattedTitle = `Lat: ${value[1]} Lng: ${value[0]}`;
return (
<ItemsTableValue title={formattedTitle} field={this.props.col.type}>
{formattedValue}
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = GeoPointColumn;
|
client/admin/import/ImportHistoryPage.stories.js
|
Sing-Li/Rocket.Chat
|
import React from 'react';
import ImportHistoryPage from './ImportHistoryPage';
export default {
title: 'admin/import/ImportHistoryPage',
component: ImportHistoryPage,
};
export const _default = () => <ImportHistoryPage />;
|
src/layouts/Header.js
|
dash-/netjumpio-tabs-web
|
///
// Dependencies
///
import React, { Component } from 'react';
import TabSetsLogo from '../elements/TabSetsLogo';
import ProfilePanelButton from '../profile/ProfilePanelButton';
///
// View
///
class Header extends Component {
render() {
return (
<div className="app-header-container dark-theme">
<div className="app-header">
<TabSetsLogo />
<h3 className="title">TabSets</h3>
<div className="extras">
<ProfilePanelButton />
</div>
</div>
<div className="app-header-spacer"></div>
</div>
);
}
}
Header.propTypes = {};
export default Header;
|
docs/src/app/components/pages/components/Paper/ExampleSimple.js
|
pradel/material-ui
|
import React from 'react';
import Paper from 'material-ui/Paper';
const style = {
height: 100,
width: 100,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
const PaperExampleSimple = () => (
<div>
<Paper style={style} zDepth={1} />
<Paper style={style} zDepth={2} />
<Paper style={style} zDepth={3} />
<Paper style={style} zDepth={4} />
<Paper style={style} zDepth={5} />
</div>
);
export default PaperExampleSimple;
|
examples/lists-and-named-requests/src/components/BooksList.js
|
jmeas/resourceful-redux
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getStatus, getResources } from 'redux-resource';
class BooksList extends Component {
render() {
const { state } = this.props;
const searchStatus = getStatus(
state,
'books.requests.readUserBooks.status',
true
);
const latestStatus = getStatus(
state,
'books.requests.readLatestBooks.status',
true
);
const userBooks = getResources(state.books, 'userBooks');
const latestBooks = getResources(state.books, 'latestBooks');
return (
<div style={{ display: 'flex' }}>
<div style={{ width: '350px', marginRight: '50px' }}>
<h2>Your Books</h2>
{searchStatus.pending && 'Loading your books...'}
{searchStatus.succeeded && (
<div>
{userBooks.map(book => (
<div key={book.id}>
<h3>{book.title}</h3>
<div>
{book.author} - {book.releaseYear}
</div>
</div>
))}
</div>
)}
</div>
<div style={{ width: '350px' }}>
<h2>Recently Released</h2>
{latestStatus.pending && 'Loading recently released books...'}
{latestStatus.succeeded && (
<div>
{latestBooks.map(book => (
<div key={book.id}>
<h3>{book.title}</h3>
<div>
{book.author} - {book.releaseYear}
</div>
</div>
))}
</div>
)}
</div>
</div>
);
}
componentDidMount() {
const { getUserBooks, getLatestBooks } = this.props;
getUserBooks();
getLatestBooks();
}
}
BooksList.propTypes = {
getUserBooks: PropTypes.func.isRequired,
getLatestBooks: PropTypes.func.isRequired,
state: PropTypes.shape({
books: PropTypes.shape({
resources: PropTypes.object.isRequired,
meta: PropTypes.object.isRequired,
requests: PropTypes.object.isRequired,
lists: PropTypes.object.isRequired
})
}).isRequired
};
export default BooksList;
|
docs/src/app/components/pages/components/DropDownMenu/ExampleLongMenu.js
|
tan-jerene/material-ui
|
import React from 'react';
import DropDownMenu from 'material-ui/DropDownMenu';
import MenuItem from 'material-ui/MenuItem';
const items = [];
for (let i = 0; i < 100; i++ ) {
items.push(<MenuItem value={i} key={i} primaryText={`Item ${i}`} />);
}
export default class DropDownMenuLongMenuExample extends React.Component {
constructor(props) {
super(props);
this.state = {value: 10};
}
handleChange = (event, index, value) => this.setState({value});
render() {
return (
<DropDownMenu maxHeight={300} value={this.state.value} onChange={this.handleChange}>
{items}
</DropDownMenu>
);
}
}
|
app/components/Home.js
|
SumoCreations/SumoCreationsWeb
|
import React from 'react';
import { Parse } from 'parse';
export default class Home extends React.Component {
handleSSO() {
Parse.FacebookUtils.logIn(null, {
success: function(user) {
if (!user.existed()) {
alert("User signed up and logged in through Facebook!");
} else {
alert("User logged in through Facebook!");
}
},
error: function(user, error) {
alert("User cancelled the Facebook login or did not fully authorize.");
}
});
}
render() {
return (
<div className="home invisible">
<h2>Welcome Home!</h2>
<a className="button" href="#">Anchor button</a>
<button onClick={this.handleSSO.bind(this)}>Login w/ Facebook</button>
</div>
);
}
};
|
client/test/containers/CounterPage.spec.js
|
zex713/crypto-test
|
import { expect } from 'chai';
import React from 'react';
import { mount } from 'enzyme';
import { Provider } from 'react-redux';
import CounterPage from '../../app/containers/CounterPage';
import configureStore from '../../app/store/configureStore';
function setup(initialState) {
const store = configureStore(initialState);
const app = mount(
<Provider store={store}>
<CounterPage />
</Provider>
);
return {
app,
buttons: app.find('button'),
p: app.find('.counter')
};
}
describe('containers', () => {
describe('App', () => {
it('should display initial count', () => {
const { p } = setup();
expect(p.text()).to.match(/^0$/);
});
it('should display updated count after increment button click', () => {
const { buttons, p } = setup();
buttons.at(0).simulate('click');
expect(p.text()).to.match(/^1$/);
});
it('should display updated count after descrement button click', () => {
const { buttons, p } = setup();
buttons.at(1).simulate('click');
expect(p.text()).to.match(/^-1$/);
});
it('shouldnt change if even and if odd button clicked', () => {
const { buttons, p } = setup();
buttons.at(2).simulate('click');
expect(p.text()).to.match(/^0$/);
});
it('should change if odd and if odd button clicked', () => {
const { buttons, p } = setup({ counter: 1 });
buttons.at(2).simulate('click');
expect(p.text()).to.match(/^2$/);
});
});
});
|
actor-apps/app-web/src/app/components/common/Fold.React.js
|
Rogerlin2013/actor-platform
|
/* eslint-disable */
import React from 'react';
import classnames from 'classnames';
class Fold extends React.Component {
static PropTypes = {
icon: React.PropTypes.string,
iconClassName: React.PropTypes.string,
title: React.PropTypes.string.isRequired
};
state = {
isOpen: false
};
constructor(props) {
super(props);
}
render() {
const { icon, iconClassName, title, iconElement } = this.props;
const titleIconClassName = classnames('material-icons icon', iconClassName);
const className = classnames({
'fold': true,
'fold--open': this.state.isOpen
});
let foldIcon;
if (icon) {
foldIcon = <i className={titleIconClassName}>{icon}</i>;
}
if (iconElement) {
foldIcon = iconElement;
}
return (
<div className={className}>
<div className="fold__title" onClick={this.onClick}>
{foldIcon}
{title}
<i className="fold__indicator material-icons pull-right">arrow_drop_down</i>
</div>
<div className="fold__content">
{this.props.children}
</div>
</div>
);
}
onClick = () => {
this.setState({isOpen: !this.state.isOpen});
};
}
export default Fold;
|
src/components/Button.js
|
OpenCollective/frontend
|
import React from 'react';
import PropTypes from 'prop-types';
import colors from '../constants/colors';
import { Router } from '../server/pages';
import HashLink from 'react-scrollchor';
const star = '/static/images/icons/star.svg';
const icons = {
star,
};
class Button extends React.Component {
static propTypes = {
label: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
disabled: PropTypes.bool,
type: PropTypes.string, // e.g. type="submit"
onClick: PropTypes.func,
href: PropTypes.string,
className: PropTypes.string,
icon: PropTypes.string,
style: PropTypes.object,
};
constructor(props) {
super(props);
this.renderButton = this.renderButton.bind(this);
this.onClick = this.onClick.bind(this);
}
async onClick(e) {
const { type, href, onClick, disabled } = this.props;
if (type === 'submit') return;
e.preventDefault();
if (href && href.substr(0, 1) !== '#') {
await Router.pushRoute(href);
window.scrollTo(0, 0);
document.body.focus();
}
if (!onClick) return;
return !disabled && onClick && onClick();
}
renderButton() {
return (
<button
type={this.props.type}
disabled={this.props.disabled}
style={this.props.style}
className={`Button ${this.props.className}`}
onClick={this.onClick}
>
<style jsx>
{`
.Button {
--webkit-appearance: none;
font-size: 1.4rem;
font-weight: 500;
height: 3.6rem;
border: 2px solid #45474d;
border-radius: 500px;
padding: 0 24px;
color: #45474d;
background-color: transparent;
}
.Button:hover {
border: 2px solid #2e8ae6;
}
.bluewhite {
border: 2px solid #cacbcc;
color: #3399ff;
}
.Button:focus {
outline: 0;
}
.Button:active {
background-color: #297acc;
border-color: #297acc;
}
.Button[disabled] {
opacity: 0.24;
}
.Button[type='submit'] {
height: 4rem;
}
div {
display: flex;
justify-content: center;
align-items: center;
width: 100%;
height: 100%;
border: 2px solid;
line-height: 17px;
border-color: ${colors.lightgray};
}
img {
height: 1.6rem;
margin: 0 0.5rem;
}
.allcaps {
text-transform: 'uppercase';
}
.whiteblue,
.whiteblue :global(a) {
color: ${colors.blue};
background: white;
}
.whiteblue.small {
width: 20rem;
}
.whiteblue:hover {
box-shadow: 0 0 4px 0 rgba(63, 175, 240, 0.4);
}
.blue {
color: white;
border-color: ${colors.white};
background-color: ${colors.blue};
}
.blue:hover {
background-color: ${colors.blueHover};
}
.blue:active {
background-color: ${colors.blueActive};
border-color: ${colors.blueActive};
}
.gray {
color: ${colors.darkgray};
border-color: ${colors.lightgray};
background: ${colors.lightgray};
}
.gray:hover {
color: ${colors.gray};
}
.Button :global(a) {
display: block;
width: 100%;
height: 100%;
text-align: center;
line-height: 5.4rem;
}
.green {
color: white;
border-color: ${colors.green};
background: ${colors.green};
}
.Button :global(span) {
white-space: nowrap;
}
.darkBackground {
color: #e3e4e6;
}
.ticket,
:global(.EventPage .tier .Button) {
width: 100%;
border-radius: 0;
height: 100%;
border-color: #3385ff;
text-transform: uppercase;
font-weight: bold;
font-size: 1.7rem;
}
.ticket,
:global(.EventPage .tier .Button:hover) {
border-color: #2e8ae6;
}
`}
</style>
<style jsx global>
{`
.mobileOnly .Button {
padding: 0 16px;
}
`}
</style>
{this.props.icon && <img src={icons[this.props.icon]} />}
{this.props.label && <span>{this.props.label}</span>}
{this.props.children}
</button>
);
}
render() {
const { href } = this.props;
if (href && href.substr(0, 1) === '#') {
return <HashLink to={href}>{this.renderButton()}</HashLink>;
} else {
return this.renderButton();
}
}
}
export default Button;
|
src/server.js
|
mdonthireddy/js_exp
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import 'babel-core/polyfill';
import path from 'path';
import express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import Router from './routes';
import Html from './components/Html';
const server = global.server = express();
server.set('port', (process.env.PORT || 5000));
server.use(express.static(path.join(__dirname, 'public')));
//
// Register API middleware
// -----------------------------------------------------------------------------
server.use('/api/content', require('./api/content'));
//
// Register server-side rendering middleware
// -----------------------------------------------------------------------------
server.get('*', async (req, res, next) => {
try {
let statusCode = 200;
const data = { title: '', description: '', css: '', body: '' };
const css = [];
const context = {
onInsertCss: value => css.push(value),
onSetTitle: value => data.title = value,
onSetMeta: (key, value) => data[key] = value,
onPageNotFound: () => statusCode = 404,
};
await Router.dispatch({ path: req.path, context }, (state, component) => {
data.body = ReactDOM.renderToString(component);
data.css = css.join('');
});
const html = ReactDOM.renderToStaticMarkup(<Html {...data} />);
res.status(statusCode).send('<!doctype html>\n' + html);
} catch (err) {
next(err);
}
});
//
// Launch the server
// -----------------------------------------------------------------------------
server.listen(server.get('port'), () => {
/* eslint-disable no-console */
console.log('The server is running at http://localhost:' + server.get('port'));
if (process.send) {
process.send('online');
}
});
|
packages/material-ui-icons/src/LabelOutline.js
|
dsslimshaddy/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LabelOutline = props =>
<SvgIcon {...props}>
<path d="M17.63 5.84C17.27 5.33 16.67 5 16 5L5 5.01C3.9 5.01 3 5.9 3 7v10c0 1.1.9 1.99 2 1.99L16 19c.67 0 1.27-.33 1.63-.84L22 12l-4.37-6.16zM16 17H5V7h11l3.55 5L16 17z" />
</SvgIcon>;
LabelOutline = pure(LabelOutline);
LabelOutline.muiName = 'SvgIcon';
export default LabelOutline;
|
packages/react-ui-components/src/_lib/storyUtils.js
|
grebaldi/PackageFactory.Guevara
|
import React from 'react';
import PropTypes from 'prop-types';
/**
* The StoryWrapper is a simple component which can be used to wrap stories
* of the react-storybook lib.
*/
export const StoryWrapper = ({children, ...rest}) => (
<div
style={{background: '#000', padding: '1rem', position: 'relative'}}
{...rest}
>
{children}
</div>
);
StoryWrapper.propTypes = {
children: PropTypes.node.isRequired
};
|
src/utils/filters.js
|
halo-design/halo-optimus
|
import React from 'react'
const listHasItem = (list, key, val) => {
let hasIt = false
list.map(item => {
if (item[key] === val) {
hasIt = true
}
})
return hasIt
}
export const checkBtnList = (menu, btnList, noDivider) => {
const ableBtn = []
const divider = <span className='ant-divider' />
const size = btnList.length
btnList.map((item, i) => {
const btn = checkBtn(menu, item.item, item.button)
if (btn) {
ableBtn.push(btn)
if (!noDivider && i !== size - 1) {
ableBtn.push(divider)
}
}
})
return ableBtn.length === 0 ? <span>无操作权限</span> : ableBtn.map((item, i) => <span key={i}>{item}</span>)
}
export const checkBtn = (menu, item, button) => {
let menuItem = item
if (item.length <= 4) {
menuItem = menu.currentMenu + item
}
return listHasItem(menu.menuItemList, 'menuItemId', menuItem) ? button : null
}
export const groupList = (list, id, parentId, childName, conver) => {
let groupList = []
let keyMap = {}
list.map(item => {
keyMap[item[id]] = conver ? conver(item) : item
})
list.map(item => {
if (!item[parentId] || !keyMap[item[parentId]]) {
groupList.push(keyMap[item[id]])
} else if (keyMap[item[parentId]]) {
if (!keyMap[item[parentId]][childName]) {
keyMap[item[parentId]][childName] = []
}
keyMap[item[parentId]][childName].push(keyMap[item[id]])
}
})
return groupList
}
export const getNodeFromList = (id, list, idName, childName, conver) => {
let node = null
for (var el of list) {
let chName = el[childName]
if (el[idName] === id) {
node = conver ? conver(el) : el
} else if (chName && chName.length > 0) {
node = getNodeFromList(id, chName, idName, childName, conver)
if (node) {
node = (conver ? conver(node) : node)
}
}
}
return node
}
export const isEmptyObject = obj => {
let name
for (name in obj) {
return false
}
return true
}
export const formatDateTime = text => {
return `${text.substring(0, 4)}/${text.substring(4, 6)}/${text.substring(6, 8)} ${text.substring(8, 10)}:${text.substring(10, 12)}`
}
export const str2json = str => {
let paramsArr = str.split(',')
let jsonArr = []
paramsArr.map(item => {
let tmp = {}
let li = item.split('=')
let key = li[0]
let val = li[1]
if (!key) {
key = '未知'
}
if (val) {
tmp.key = key
if (val.indexOf(':') > 0) {
val = val.replace(/:/g, ', ')
}
tmp.value = val
jsonArr.push(tmp)
} else {
jsonArr.push({
key: key,
value: '暂无'
})
}
})
return jsonArr
}
export const releaseFilter = record => {
switch (record) {
case '1':
return '白名单灰度'
case '2':
return '时间窗灰度'
default:
return '正式发布'
}
}
export const enterpriseFilter = record => record === '0' ? '企业包' : '正式包'
export const upgradeTypeFilter = record => record === '1' ? '单次提醒' : '多次提醒'
export const releaseStatusFilter = record => record === '1' ? '发布中' : record === '2' ? '已结束' : '暂停'
export const platformFilter = record => {
switch (record) {
case '0':
return '平台无关'
case '1':
return 'Android'
case '2':
return 'IOS'
default:
return record
}
}
export const operationFilter = record => {
switch (record) {
case '1':
return '包含'
case '2':
return '不包含'
case '3':
return '范围内'
case '4':
return '范围外'
default:
return record
}
}
export const resourceFilter = record => {
switch (record) {
case 'version':
return '版本号'
case 'city':
return '城市'
case 'mobileModel':
return '机型'
case 'netType':
return '网络'
case 'osVersion':
return 'OS版本'
default:
return record
}
}
export const whitelistIdsFilter = data => data.map(item => item.whiteListName)
export const formatGreyConfigInfo = data => {
const rules = JSON.parse(data).subRules
return rules.map(item => ({
ruleElement: item.right,
operation: item.operator,
value: Array.isArray(item.left) ? item.left.join(', ') : isEmptyObject(item.left) ? '暂无' : `${item.left.upper} - ${item.left.lower}`
}))
}
export const whiteListFilter = record => {
switch (record) {
case 'userid':
return '用户白名单'
default:
return record
}
}
export const businessFilter = record => {
switch (record) {
case 'hotpatch':
return '热修复'
case 'upgrade':
return '升级'
default:
return record
}
}
|
src/DayColumn.js
|
intljusticemission/react-big-calendar
|
import PropTypes from 'prop-types'
import React from 'react'
import { findDOMNode } from 'react-dom'
import clsx from 'clsx'
import Selection, { getBoundsForNode, isEvent } from './Selection'
import * as dates from './utils/dates'
import * as TimeSlotUtils from './utils/TimeSlots'
import { isSelected } from './utils/selection'
import { notify } from './utils/helpers'
import * as DayEventLayout from './utils/DayEventLayout'
import TimeSlotGroup from './TimeSlotGroup'
import TimeGridEvent from './TimeGridEvent'
import { DayLayoutAlgorithmPropType } from './utils/propTypes'
class DayColumn extends React.Component {
state = { selecting: false, timeIndicatorPosition: null }
intervalTriggered = false
constructor(...args) {
super(...args)
this.slotMetrics = TimeSlotUtils.getSlotMetrics(this.props)
}
componentDidMount() {
this.props.selectable && this._selectable()
if (this.props.isNow) {
this.setTimeIndicatorPositionUpdateInterval()
}
}
componentWillUnmount() {
this._teardownSelectable()
this.clearTimeIndicatorInterval()
}
UNSAFE_componentWillReceiveProps(nextProps) {
if (nextProps.selectable && !this.props.selectable) this._selectable()
if (!nextProps.selectable && this.props.selectable)
this._teardownSelectable()
this.slotMetrics = this.slotMetrics.update(nextProps)
}
componentDidUpdate(prevProps, prevState) {
const getNowChanged = !dates.eq(
prevProps.getNow(),
this.props.getNow(),
'minutes'
)
if (prevProps.isNow !== this.props.isNow || getNowChanged) {
this.clearTimeIndicatorInterval()
if (this.props.isNow) {
const tail =
!getNowChanged &&
dates.eq(prevProps.date, this.props.date, 'minutes') &&
prevState.timeIndicatorPosition === this.state.timeIndicatorPosition
this.setTimeIndicatorPositionUpdateInterval(tail)
}
} else if (
this.props.isNow &&
(!dates.eq(prevProps.min, this.props.min, 'minutes') ||
!dates.eq(prevProps.max, this.props.max, 'minutes'))
) {
this.positionTimeIndicator()
}
}
/**
* @param tail {Boolean} - whether `positionTimeIndicator` call should be
* deferred or called upon setting interval (`true` - if deferred);
*/
setTimeIndicatorPositionUpdateInterval(tail = false) {
if (!this.intervalTriggered && !tail) {
this.positionTimeIndicator()
}
this._timeIndicatorTimeout = window.setTimeout(() => {
this.intervalTriggered = true
this.positionTimeIndicator()
this.setTimeIndicatorPositionUpdateInterval()
}, 60000)
}
clearTimeIndicatorInterval() {
this.intervalTriggered = false
window.clearTimeout(this._timeIndicatorTimeout)
}
positionTimeIndicator() {
const { min, max, getNow } = this.props
const current = getNow()
if (current >= min && current <= max) {
const top = this.slotMetrics.getCurrentTimePosition(current)
this.setState({ timeIndicatorPosition: top })
} else {
this.clearTimeIndicatorInterval()
}
}
render() {
const {
max,
rtl,
isNow,
resource,
accessors,
localizer,
getters: { dayProp, ...getters },
components: { eventContainerWrapper: EventContainer, ...components },
} = this.props
let { slotMetrics } = this
let { selecting, top, height, startDate, endDate } = this.state
let selectDates = { start: startDate, end: endDate }
const { className, style } = dayProp(max)
return (
<div
style={style}
className={clsx(
className,
'rbc-day-slot',
'rbc-time-column',
isNow && 'rbc-now',
isNow && 'rbc-today', // WHY
selecting && 'rbc-slot-selecting'
)}
>
{slotMetrics.groups.map((grp, idx) => (
<TimeSlotGroup
key={idx}
group={grp}
resource={resource}
getters={getters}
components={components}
/>
))}
<EventContainer
localizer={localizer}
resource={resource}
accessors={accessors}
getters={getters}
components={components}
slotMetrics={slotMetrics}
>
<div className={clsx('rbc-events-container', rtl && 'rtl')}>
{this.renderEvents()}
</div>
</EventContainer>
{selecting && (
<div className="rbc-slot-selection" style={{ top, height }}>
<span>{localizer.format(selectDates, 'selectRangeFormat')}</span>
</div>
)}
{isNow && (
<div
className="rbc-current-time-indicator"
style={{ top: `${this.state.timeIndicatorPosition}%` }}
/>
)}
</div>
)
}
renderEvents = () => {
let {
events,
rtl,
selected,
accessors,
localizer,
getters,
components,
step,
timeslots,
dayLayoutAlgorithm,
} = this.props
const { slotMetrics } = this
const { messages } = localizer
let styledEvents = DayEventLayout.getStyledEvents({
events,
accessors,
slotMetrics,
minimumStartDifference: Math.ceil((step * timeslots) / 2),
dayLayoutAlgorithm,
})
return styledEvents.map(({ event, style }, idx) => {
let end = accessors.end(event)
let start = accessors.start(event)
let format = 'eventTimeRangeFormat'
let label
const startsBeforeDay = slotMetrics.startsBeforeDay(start)
const startsAfterDay = slotMetrics.startsAfterDay(end)
if (startsBeforeDay) format = 'eventTimeRangeEndFormat'
else if (startsAfterDay) format = 'eventTimeRangeStartFormat'
if (startsBeforeDay && startsAfterDay) label = messages.allDay
else label = localizer.format({ start, end }, format)
let continuesEarlier = startsBeforeDay || slotMetrics.startsBefore(start)
let continuesLater = startsAfterDay || slotMetrics.startsAfter(end)
return (
<TimeGridEvent
style={style}
event={event}
label={label}
key={'evt_' + idx}
getters={getters}
rtl={rtl}
components={components}
continuesEarlier={continuesEarlier}
continuesLater={continuesLater}
accessors={accessors}
selected={isSelected(event, selected)}
onClick={e => this._select(event, e)}
onDoubleClick={e => this._doubleClick(event, e)}
/>
)
})
}
_selectable = () => {
let node = findDOMNode(this)
let selector = (this._selector = new Selection(() => findDOMNode(this), {
longPressThreshold: this.props.longPressThreshold,
}))
let maybeSelect = box => {
let onSelecting = this.props.onSelecting
let current = this.state || {}
let state = selectionState(box)
let { startDate: start, endDate: end } = state
if (onSelecting) {
if (
(dates.eq(current.startDate, start, 'minutes') &&
dates.eq(current.endDate, end, 'minutes')) ||
onSelecting({ start, end, resourceId: this.props.resource }) === false
)
return
}
if (
this.state.start !== state.start ||
this.state.end !== state.end ||
this.state.selecting !== state.selecting
) {
this.setState(state)
}
}
let selectionState = point => {
let currentSlot = this.slotMetrics.closestSlotFromPoint(
point,
getBoundsForNode(node)
)
if (!this.state.selecting) {
this._initialSlot = currentSlot
}
let initialSlot = this._initialSlot
if (dates.lte(initialSlot, currentSlot)) {
currentSlot = this.slotMetrics.nextSlot(currentSlot)
} else if (dates.gt(initialSlot, currentSlot)) {
initialSlot = this.slotMetrics.nextSlot(initialSlot)
}
const selectRange = this.slotMetrics.getRange(
dates.min(initialSlot, currentSlot),
dates.max(initialSlot, currentSlot)
)
return {
...selectRange,
selecting: true,
top: `${selectRange.top}%`,
height: `${selectRange.height}%`,
}
}
let selectorClicksHandler = (box, actionType) => {
if (!isEvent(findDOMNode(this), box)) {
const { startDate, endDate } = selectionState(box)
this._selectSlot({
startDate,
endDate,
action: actionType,
box,
})
}
this.setState({ selecting: false })
}
selector.on('selecting', maybeSelect)
selector.on('selectStart', maybeSelect)
selector.on('beforeSelect', box => {
if (this.props.selectable !== 'ignoreEvents') return
return !isEvent(findDOMNode(this), box)
})
selector.on('click', box => selectorClicksHandler(box, 'click'))
selector.on('doubleClick', box => selectorClicksHandler(box, 'doubleClick'))
selector.on('select', bounds => {
if (this.state.selecting) {
this._selectSlot({ ...this.state, action: 'select', bounds })
this.setState({ selecting: false })
}
})
selector.on('reset', () => {
if (this.state.selecting) {
this.setState({ selecting: false })
}
})
}
_teardownSelectable = () => {
if (!this._selector) return
this._selector.teardown()
this._selector = null
}
_selectSlot = ({ startDate, endDate, action, bounds, box }) => {
let current = startDate,
slots = []
while (dates.lte(current, endDate)) {
slots.push(current)
current = new Date(+current + this.props.step * 60 * 1000) // using Date ensures not to create an endless loop the day DST begins
}
notify(this.props.onSelectSlot, {
slots,
start: startDate,
end: endDate,
resourceId: this.props.resource,
action,
bounds,
box,
})
}
_select = (...args) => {
notify(this.props.onSelectEvent, args)
}
_doubleClick = (...args) => {
notify(this.props.onDoubleClickEvent, args)
}
}
DayColumn.propTypes = {
events: PropTypes.array.isRequired,
step: PropTypes.number.isRequired,
date: PropTypes.instanceOf(Date).isRequired,
min: PropTypes.instanceOf(Date).isRequired,
max: PropTypes.instanceOf(Date).isRequired,
getNow: PropTypes.func.isRequired,
isNow: PropTypes.bool,
rtl: PropTypes.bool,
accessors: PropTypes.object.isRequired,
components: PropTypes.object.isRequired,
getters: PropTypes.object.isRequired,
localizer: PropTypes.object.isRequired,
showMultiDayTimes: PropTypes.bool,
culture: PropTypes.string,
timeslots: PropTypes.number,
selected: PropTypes.object,
selectable: PropTypes.oneOf([true, false, 'ignoreEvents']),
eventOffset: PropTypes.number,
longPressThreshold: PropTypes.number,
onSelecting: PropTypes.func,
onSelectSlot: PropTypes.func.isRequired,
onSelectEvent: PropTypes.func.isRequired,
onDoubleClickEvent: PropTypes.func.isRequired,
className: PropTypes.string,
dragThroughEvents: PropTypes.bool,
resource: PropTypes.any,
dayLayoutAlgorithm: DayLayoutAlgorithmPropType,
}
DayColumn.defaultProps = {
dragThroughEvents: true,
timeslots: 2,
}
export default DayColumn
|
js/components/blankPage/index.js
|
phamngoclinh/PetOnline_vs2
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { AppRegistry, View, TextInput, ScrollView, Dimensions, AsyncStorage } from 'react-native';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Text, Button, Icon, List, ListItem, Thumbnail, Spinner } from 'native-base';
import { openDrawer } from '../../actions/drawer';
import styles from './styles';
// For REALTIME Chatimport
var petAppId = '';
window.navigator.userAgent = 'ReactNative';
import feathers from 'feathers/client'
import hooks from 'feathers-hooks';
import socketio from 'feathers-socketio/client'
import authentication from 'feathers-authentication/client';
var io = require('../../packages/socket.io-client/socket.io');
const PLACEHOLDER = '../../../images/avatarThumbnail.png';
const defaultAvatar = require('../../../images/avatarThumbnail.png');
const ScreenHeight = Dimensions.get("window").height;
const ScreenWidth = Dimensions.get("window").width;
const {
popRoute,
} = actions;
const apiLink = 'http://210.211.118.178/PetsAPI/';
const petAlbum = 'http://210.211.118.178/PetsAPI/Images/PetThumbnails/';
const userAlbum = 'http://210.211.118.178/PetsAPI/Images/UserThumbnails/';
var user_Id = '';
var authToken = '';
var avatarThumbnail = '';
var coverThumbnail = '';
var my_email = '';
class UselessTextInput extends Component {
render() {
return (
<TextInput
{...this.props}
editable = {true}
maxLength = {350} />
);
}
}
class BlankPage extends Component {
static propTypes = {
name: React.PropTypes.string,
index: React.PropTypes.number,
list: React.PropTypes.arrayOf(React.PropTypes.string),
openDrawer: React.PropTypes.func,
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
constructor(props) {
super(props);
this.state = {
text: '',
messages: [],
skip: 0,
hasMoreMessages : false,
loading: true,
is_loading_data : false,
user : null,
username: '',
email: '',
phone : ''
};
const options = {transports: ['websocket'], forceNew: true};
const socket = io('http://192.168.56.1:3030', options);
this.featherAPI = feathers()
.configure(socketio(socket, {timeout: 50000}))
.configure(hooks())
// Use AsyncStorage to store our login toke
.configure(authentication({
storage: AsyncStorage
}));
// this.formatMessage = this.formatMessage.bind(this);
// this.loadMessages = this.loadMessages.bind(this);
// this.deleteMessage = this.deleteMessage.bind(this);
}
componentDidMount() {
let _this = this;
AsyncStorage.getItem('AUTH_TOKEN').then((value) => {
authToken = value;
});
_this.getUserInformation();
AsyncStorage.getItem('PETAPP_ID').then((value) => {
petAppId = value;
});
this.featherAPI.io.on('connect', () => {
console.log("Connect to Socket success");
this.featherAPI.service('messages').on('created', message => {
const messages = this.state.messages;
messages.push(_this.formatMessage(message));
_this.setState({messages});
});
AsyncStorage.getItem('USER_EMAIL').then((value) => {
var loginInfo = {
type: 'local',
email: value,
password: '123456',
};
_this.featherAPI.authenticate(loginInfo).then((response) => {
console.log(response);
console.log('auth ok');
AsyncStorage.setItem('PETAPP_ID', response.data._id);
petAppId = response.data._id;
_this.loadMessages();
_this.setState({loading: false});
}).catch((error) => {
console.log(error);
console.log('auth fail');
_this.setState({loading: false});
alert("auth fail");
});
})
});
}
componentWillMount() {
}
getUserInformation() {
let _this = this;
AsyncStorage.getItem('USER_ID').then((value) => {
console.log("UserId in sidebar: ", value);
// alert("UserId in sidebar: ", value);
fetch('http://210.211.118.178/PetsAPI/api/userauthinfos/'+value, {
method: 'GET',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
'Auth-Token': authToken
}
})
.then((response) => response.json())
.then((responseJson) => {
my_email = responseJson.email,
// Store the results in the state variable results and set loading to
_this.setState({
user: responseJson,
username: responseJson.firstName + " " + responseJson.lastName,
email: responseJson.email,
phone: responseJson.phone,
is_loading_data: false
});
avatarThumbnail = responseJson.avatarThumbnail;
coverThumbnail = responseJson.coverThumbnail;
if(avatarThumbnail == null || avatarThumbnail == '') {
avatarThumbnail = '../../../images/avatar.png';
}
if(coverThumbnail == null || coverThumbnail == '') {
coverThumbnail = '../../../images/avatar.png';
}
console.log("Get USER from server: ", responseJson);
})
.catch((error) => {
_this.setState({
loading: false
});
console.error(error);
});
});
}
createMessage() {
let _this = this;
this.featherAPI.service('messages').create({
text: this.state.text
}).then((result) => {
_this.setState({text: ''});
console.log("Tin nhắn được khởi tạo từ App: ", result);
}).catch((error) => {
console.log("Lỗi. Không thể tạo tin nhắn");
});
}
formatMessage(message) {
return {
id: message._id,
name: message.sentBy._id === petAppId ? (this.state.username ? this.state.username : message.sentBy.email) : message.sentBy.email,
text: message.text,
position: message.sentBy._id === petAppId ? 'right' : 'left',
// image: {uri: message.sentBy.avatar ? message.sentBy.avatar : PLACEHOLDER },
image: message.sentBy._id === petAppId ? (avatarThumbnail ? {uri: userAlbum + avatarThumbnail} : defaultAvatar) : defaultAvatar,
date: message.createdAt
};
}
loadMessages() {
let _this = this;
const query = {query: {$sort: {updatedAt: -1}, $limit: 15}};
this.featherAPI.service('messages').find(query).then((response) => {
console.log("Response: ", response);
if(response.total > 0) {
const messages = this.state.messages;
result = response.data;
console.log(response);
result.forEach(function(message) {
messages.push(_this.formatMessage(message));
});
messages.reverse();
_this.setState({messages});
}
}).catch((error) => {
console.log("error: ", error);
});
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
const { props: { name, index, list } } = this;
return (
<Container style={styles.container}>
<Header>
<Button transparent onPress={() => this.popRoute()}>
<Icon name="ios-arrow-back" />
</Button>
<Title>{(name) ? this.props.name : 'PHÒNG TÁN GẪU'}</Title>
<Button transparent onPress={this.props.openDrawer}>
<Icon name="ios-menu" />
</Button>
</Header>
<Content>
<View style={{flex:1, flexDirection: 'column', justifyContent: 'space-between', height: ScreenHeight - 80}}>
<View style={{flex: 10, backgroundColor: '#FFFFFF'}}>
<ScrollView
ref='_scrollView'
onContentSizeChange={(contentWidth, contentHeight) => {
this.refs._scrollView.scrollTo({x: 0, y: contentHeight, animated: true});
}}
style={{backgroundColor: '#ffffff'}} >
<View style={styles.chatWrapper}>
<List style={{paddingLeft: 0}}>
{
this.state.messages ?
this.state.messages.map((message, index) => {
return (
<ListItem key={message.id} style={{paddingLeft: 0,
marginLeft: 0,
borderBottomWidth: 0,
marginBottom: 5,
marginTop: 5,
flexDirection: 'row'}}>
{
message.position === 'right' ? (
<Thumbnail
source={message.image}
style={{
alignSelf:'flex-end',
marginTop: 5,
width: 60,
height: 60,
borderRadius: 100,
position: 'absolute',
right: 0,
top: 10
}} />
) : (<Thumbnail
source={message.image}
style={{
alignSelf:'flex-start',
marginTop: 5,
width: 60,
height: 60,
borderRadius: 100,
position: 'absolute',
left: 0,
top: 10
}} />)
}
{
message.position === 'right' ? (
<Text note style={{alignSelf:'flex-end',marginRight: 65, marginBottom: 5}}>{ message.name }</Text>
) : (
<Text note style={{alignSelf:'flex-start',marginLeft: 60, marginBottom: 5}}>{ message.name }</Text>
)
}
{
message.position === 'right' ? (
<Text note
style={{ backgroundColor: '#0084ff',
color:'#ffffff',
fontSize: 15,
padding: 10,
borderTopRightRadius: 5,
borderBottomRightRadius: 10,
borderTopLeftRadius: 10,
borderBottomLeftRadius: 10,
alignSelf:'flex-end',
marginRight: 65,
maxWidth: ScreenWidth - 200,
lineHeight: 20
}}>
{ message.text }
</Text>
) : (
<Text note
style={{ backgroundColor: '#f3f3f3',
color:'#333333',
fontSize: 15,
padding: 10,
borderTopLeftRadius: 5,
borderBottomLeftRadius: 10,
borderTopRightRadius: 10,
borderBottomRightRadius: 10,
alignSelf:'flex-start',
marginLeft: 60,
maxWidth: ScreenWidth - 200,
lineHeight: 20 }}>
{ message.text }
</Text>
)
}
</ListItem>
)
})
: null
}
</List>
</View>
</ScrollView>
</View>
<View style={{flex: 2, borderTopWidth: 1, borderTopColor: '#cccccc'}}>
<UselessTextInput
placeholder="Soạn tin nhắn..."
multiline = {true}
numberOfLines = {4}
onChangeText={(text) => this.setState({text})}
value={this.state.text}
style={{paddingLeft: 10, paddingRight: 10}}/>
<View style={{flexDirection: 'row', justifyContent: 'space-between', paddingLeft: 10, paddingRight: 10}}>
<Button transparent><Icon name='ios-heart-outline' style={{fontSize: 25, color: '#333333'}}/></Button>
<Button transparent><Icon name='ios-contact-outline' style={{fontSize: 25, color: '#333333'}}/></Button>
<Button transparent><Icon name='ios-microphone-outline' style={{fontSize: 25, color: '#333333'}}/></Button>
<Button transparent><Icon name='ios-photos-outline' style={{fontSize: 25, color: '#333333'}}/></Button>
<Button transparent onPress = {() => this.createMessage()}><Icon name='ios-send-outline' style={{fontSize: 25, color: '#333333'}}/></Button>
</View>
</View>
</View>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
openDrawer: () => dispatch(openDrawer()),
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
name: state.user.name,
index: state.list.selectedIndex,
list: state.list.list,
});
export default connect(mapStateToProps, bindAction)(BlankPage);
|
pnpm-offline/.pnpm-store-offline/1/registry.npmjs.org/react-bootstrap/0.31.0/es/NavbarCollapse.js
|
JamieMason/npm-cache-benchmark
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
import Collapse from './Collapse';
import { prefix } from './utils/bootstrapUtils';
var contextTypes = {
$bs_navbar: PropTypes.shape({
bsClass: PropTypes.string,
expanded: PropTypes.bool
})
};
var NavbarCollapse = function (_React$Component) {
_inherits(NavbarCollapse, _React$Component);
function NavbarCollapse() {
_classCallCheck(this, NavbarCollapse);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavbarCollapse.prototype.render = function render() {
var _props = this.props,
children = _props.children,
props = _objectWithoutProperties(_props, ['children']);
var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' };
var bsClassName = prefix(navbarProps, 'collapse');
return React.createElement(
Collapse,
_extends({ 'in': navbarProps.expanded }, props),
React.createElement(
'div',
{ className: bsClassName },
children
)
);
};
return NavbarCollapse;
}(React.Component);
NavbarCollapse.contextTypes = contextTypes;
export default NavbarCollapse;
|
src/Popover.js
|
mxc/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
const Popover = React.createClass({
mixins: [ BootstrapMixin ],
propTypes: {
/**
* An html id attribute, necessary for accessibility
* @type {string}
* @required
*/
id: CustomPropTypes.isRequiredForA11y(
React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
])
),
/**
* Sets the direction the Popover is positioned towards.
*/
placement: React.PropTypes.oneOf(['top', 'right', 'bottom', 'left']),
/**
* The "left" position value for the Popover.
*/
positionLeft: React.PropTypes.number,
/**
* The "top" position value for the Popover.
*/
positionTop: React.PropTypes.number,
/**
* The "left" position value for the Popover arrow.
*/
arrowOffsetLeft: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
]),
/**
* The "top" position value for the Popover arrow.
*/
arrowOffsetTop: React.PropTypes.oneOfType([
React.PropTypes.number, React.PropTypes.string
]),
/**
* Title text
*/
title: React.PropTypes.node
},
getDefaultProps() {
return {
placement: 'right'
};
},
render() {
const classes = {
'popover': true,
[this.props.placement]: true
};
const style = {
'left': this.props.positionLeft,
'top': this.props.positionTop,
'display': 'block',
// we don't want to expose the `style` property
...this.props.style // eslint-disable-line react/prop-types
};
const arrowStyle = {
'left': this.props.arrowOffsetLeft,
'top': this.props.arrowOffsetTop
};
return (
<div role="tooltip" {...this.props} className={classNames(this.props.className, classes)} style={style} title={null}>
<div className="arrow" style={arrowStyle} />
{this.props.title ? this.renderTitle() : null}
<div className="popover-content">
{this.props.children}
</div>
</div>
);
},
renderTitle() {
return (
<h3 className="popover-title">{this.props.title}</h3>
);
}
});
export default Popover;
|
fields/components/columns/ArrayColumn.js
|
Yaska/keystone
|
import React from 'react';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var ArrayColumn = React.createClass({
displayName: 'ArrayColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
return value.join(', ');
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = ArrayColumn;
|
packages/extra/src/LinearGradient.js
|
finnfiddle/number-picture
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import get from 'lodash.get';
import gradients from '../node_modules/uigradients/gradients.json';
import { types } from '@potion/util';
const GRADIENTS_HASH = gradients.reduce((acc, g) => ({
...acc,
[g.name.toLowerCase()]: g.colors,
}), {});
const GRADIENT_NAMES = Object.keys(GRADIENTS_HASH);
const randomGradientName = () => {
const index = Math.floor(Math.random() * GRADIENT_NAMES.length);
return GRADIENT_NAMES[index];
};
export default class LinearGradient extends Component {
static propTypes = {
components: PropTypes.shape({
linearGradient: PropTypes.node,
stop: PropTypes.node,
}),
name: PropTypes.oneOf(GRADIENT_NAMES),
colors: PropTypes.array,
offsets: PropTypes.arrayOf(PropTypes.string),
}
static defaultProps = {
offsets: [],
};
static contextTypes = {
components: types.components,
}
render() {
const { name, colors, components, offsets, ...rest } = this.props;
const finalColors = colors || GRADIENTS_HASH[name || randomGradientName()];
const numColors = finalColors.length;
const the = {
linearGradient: get(this, 'context.components.linearGradient') ||
get(components, 'linearGradient') ||
'linearGradient',
stop: get(this, 'context.components.stop') ||
get(components, 'stop') ||
'stop',
};
return (
<the.linearGradient {...rest}>
{
finalColors.map((color, i) => (
<the.stop
key={color}
stopColor={color}
// offset={offsets[i]}
offset={offsets[i] || `${(100 / numColors) * i}%`}
/>
))
}
</the.linearGradient>
);
}
}
|
samples/apollo-client/src/index.js
|
johnberzy-bazinga/FSharp.Data.GraphQL
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import QueryRunner from './QueryRunner';
ReactDOM.render(<QueryRunner />, document.getElementById('root'));
|
examples/with-algolia-react-instantsearch/components/head.js
|
flybayer/next.js
|
import NextHead from 'next/head'
import { string } from 'prop-types'
import React from 'react'
const defaultDescription = ''
const defaultOGURL = ''
const defaultOGImage = ''
export const Head = (props) => (
<NextHead>
<meta charSet="UTF-8" />
<title>{props.title || ''}</title>
<meta
name="description"
content={props.description || defaultDescription}
/>
<meta name="viewport" content="width=device-width, initial-scale=1" />
<link rel="icon" sizes="192x192" href="/static/touch-icon.png" />
<link rel="apple-touch-icon" href="/static/touch-icon.png" />
<link rel="mask-icon" href="/static/favicon-mask.svg" color="#49B882" />
<meta property="og:url" content={props.url || defaultOGURL} />
<meta property="og:title" content={props.title || ''} />
<meta
property="og:description"
content={props.description || defaultDescription}
/>
<meta name="twitter:site" content={props.url || defaultOGURL} />
<meta name="twitter:card" content="summary_large_image" />
<meta name="twitter:image" content={props.ogImage || defaultOGImage} />
<meta property="og:image" content={props.ogImage || defaultOGImage} />
<meta property="og:image:width" content="1200" />
<meta property="og:image:height" content="630" />
<link
rel="stylesheet"
href="https://unpkg.com/react-instantsearch-theme-algolia@3.0.0/style.min.css"
/>
<link rel="stylesheet" href="../static/instantsearch.css" />
</NextHead>
)
Head.propTypes = {
title: string,
description: string,
url: string,
ogImage: string,
}
export default Head
|
packages/ringcentral-widgets-docs/src/app/pages/Components/SlideMenu/Demo.js
|
ringcentral/ringcentral-js-widget
|
import React from 'react';
// eslint-disable-next-line
import SlideMenu from 'ringcentral-widgets/components/SlideMenu';
const props = {};
/**
* A example of `SlideMenu`
*/
const SlideMenuDemo = () => <SlideMenu {...props} />;
export default SlideMenuDemo;
|
src/components/Footer/Footer.js
|
kuao775/mandragora
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Footer.css';
import Link from '../Link';
class Footer extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<span className={s.text}>© Mandragora</span>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/">
Home
</Link>
<span className={s.spacer}>·</span>
<Link className={s.link} to="/admin">
Admin
</Link>
<span className={s.spacer}>·</span>
</div>
</div>
);
}
}
export default withStyles(s)(Footer);
|
packages/mineral-ui-icons/src/IconNextWeek.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconNextWeek(props: IconProps) {
const iconProps = {
rtl: true,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M20 7h-4V5c0-.55-.22-1.05-.59-1.41C15.05 3.22 14.55 3 14 3h-4c-1.1 0-2 .9-2 2v2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9c0-1.1-.9-2-2-2zM10 5h4v2h-4V5zm1 13.5l-1-1 3-3-3-3 1-1 4 4-4 4z"/>
</g>
</Icon>
);
}
IconNextWeek.displayName = 'IconNextWeek';
IconNextWeek.category = 'content';
|
examples/todos-flow/src/components/TodoList.js
|
bvasko/redux
|
// @flow
import React from 'react'
import Todo from './Todo'
import type { Todos, Id } from '../types'
export type Props = {
todos: Todos,
onTodoClick: (id: Id) => void
};
const TodoList = ({ todos, onTodoClick }: Props) => (
<ul>
{todos.map(todo =>
<Todo
key={todo.id}
{...todo}
onClick={() => onTodoClick(todo.id)}
/>
)}
</ul>
)
export default TodoList
|
src/components/MessageDialog/MessageDialog.js
|
austinknight/ui-components
|
import React from 'react';
import styled from 'styled-components';
import Modal from '../Modal'
import ButtonBar from '../ButtonBar';
import {
colors,
fontSizes,
typography,
renderThemeIfPresentOrDefault,
} from '../styles';
const Title = styled.div`
width: 100%;
color: ${renderThemeIfPresentOrDefault({ key: 'white90', defaultValue: colors.black87 })};
margin-bottom: 8px;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
display: inline-block;
${typography.title}
`;
const ContentWrapper = styled.div`
padding: 0 8px;
`;
const BodyDisplay = styled.div`
margin-bottom: 20px;
color: ${renderThemeIfPresentOrDefault({ key: 'white', defaultValue: colors.black60 })};
${typography.body1}
margin-top: ${(props) => {
if (props.dialogTitle) {
return '0';
}
return '8px';
}};
p {
${typography.body1}
}
`;
class MessageDialog extends React.Component {
render() {
const {
dialogTitle,
bodyElement,
center,
...props
} = this.props;
const canRenderButtonBar = props.primaryActionText || props.secondaryActionText;
return (
<Modal {...props}>
<ContentWrapper>
{ dialogTitle &&
<Title className='MessageDialog__Title' title={dialogTitle}>{dialogTitle}</Title>
}
<BodyDisplay className='MessageDialog__BodyDisplay' dialogTitle={dialogTitle}>
{bodyElement}
</BodyDisplay>
</ContentWrapper>
{canRenderButtonBar &&
<ButtonBar className='MessageDialog__ButtonBar' {...this.props} />
}
</Modal>
);
}
}
export const StyledMessageDialog = styled(MessageDialog)`
button {
font-size: ${fontSizes.xSmall}
}
`;
MessageDialog.defaultProps = {
actionLoading: false,
bodyElement: <div />,
dialogTitle: '',
isActionDisabled: false,
};
export default MessageDialog;
|
20200300-js-spa-react-node-sql/client/src/components/UIHelpModal.js
|
DamienFremont/blog
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faCheck } from '@fortawesome/free-solid-svg-icons';
import { Button, Modal, ModalFooter } from 'reactstrap';
const UIHelpModal = (props) => {
const settingsName = props.settingsName;
const toggle = props.toggle;
const isOpen = props.isOpen;
const defaultChecked = localStorage.getItem(settingsName === false);
function onChange(e) {
localStorage.setItem(settingsName, e.target.checked);
}
return (
<Modal isOpen={isOpen} toggle={toggle} fade={true} centered={true}>
{props.children}
<ModalFooter className="d-flex justify-content-between">
<div className="custom-control custom-switch">
<input type="checkbox" className="custom-control-input" id="customSwitch1"
defaultChecked={defaultChecked}
onChange={onChange}
/>
<label className="custom-control-label" for="customSwitch1">
<FormattedMessage id="UIHelpModal.hide" />
</label>
</div>
<Button color="primary" onClick={toggle}>
<FontAwesomeIcon icon={faCheck} />{' '}
<FormattedMessage id="UIHelpModal.ok" />
</Button>
</ModalFooter>
</Modal>
);
}
export default UIHelpModal;
|
src/parser/shaman/elemental/modules/talents/MasterOfTheElements.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import { formatNumber, formatPercentage } from 'common/format';
import SpellIcon from 'common/SpellIcon';
import SPELLS from 'common/SPELLS';
import calculateEffectiveDamage from 'parser/core/calculateEffectiveDamage';
import SpellLink from 'common/SpellLink';
import { SELECTED_PLAYER } from 'parser/core/EventFilter';
import Events from 'parser/core/Events';
import SUGGESTION_IMPORTANCE from 'parser/core/ISSUE_IMPORTANCE';
const MASTER_OF_THE_ELEMENTS = {
INCREASE: 0.2,
DURATION: 15000,
WINDOW_DURATION: 500,
AFFECTED_DAMAGE: [
SPELLS.ICEFURY_TALENT,
SPELLS.ICEFURY_OVERLOAD,
SPELLS.FROST_SHOCK,
SPELLS.LIGHTNING_BOLT,
SPELLS.LIGHTNING_BOLT_OVERLOAD,
SPELLS.CHAIN_LIGHTNING,
SPELLS.CHAIN_LIGHTNING_OVERLOAD,
SPELLS.ELEMENTAL_BLAST_TALENT,
SPELLS.ELEMENTAL_BLAST_OVERLOAD,
SPELLS.EARTH_SHOCK,
],
AFFECTED_CASTS: [
SPELLS.EARTHQUAKE,
SPELLS.ICEFURY_TALENT,
SPELLS.FROST_SHOCK,
SPELLS.ELEMENTAL_BLAST_TALENT,
SPELLS.CHAIN_LIGHTNING,
SPELLS.EARTH_SHOCK,
SPELLS.LIGHTNING_BOLT,
],
TALENTS: [
SPELLS.ICEFURY_TALENT.id,
SPELLS.ELEMENTAL_BLAST_TALENT.id,
],
};
class MasterOfTheElements extends Analyzer {
moteBuffedAbilities = {};
moteActivationTimestamp = null;
moteConsumptionTimestamp = null;
damageGained = 0;
bugCheckNecessary = false;
constructor(...args) {
super(...args);
this.active = this.selectedCombatant.hasTalent(SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.id);
for (const key in MASTER_OF_THE_ELEMENTS.AFFECTED_CASTS) {
const spellid = MASTER_OF_THE_ELEMENTS.AFFECTED_CASTS[key].id;
if((this.selectedCombatant.hasTalent(spellid)) || (!MASTER_OF_THE_ELEMENTS.TALENTS.includes(spellid))) {
this.moteBuffedAbilities[spellid] = 0;
}
}
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(MASTER_OF_THE_ELEMENTS.AFFECTED_CASTS), this._onCast);
this.addEventListener(Events.cast.by(SELECTED_PLAYER).spell(SPELLS.LAVA_BURST), this._onLvBCast);
this.addEventListener(Events.damage.by(SELECTED_PLAYER).spell(MASTER_OF_THE_ELEMENTS.AFFECTED_DAMAGE), this._onDamage);
}
_onCast(event){
if(this.moteActivationTimestamp===null){ //the buff is a clusterfuck so we just track it manually
return;
}
this.moteConsumptionTimestamp=event.timestamp;
this.moteActivationTimestamp=null;
event.meta = event.meta || {};
event.meta.isEnhancedCast = true;
this.moteBuffedAbilities[event.ability.guid]++;
}
_onLvBCast(event){
this.moteActivationTimestamp = event.timestamp;
this.bugCheckNecessary = true;
}
_onDamage(event){
if (event.timestamp<this.moteConsumptionTimestamp || event.timestamp>this.moteConsumptionTimestamp+MASTER_OF_THE_ELEMENTS.WINDOW_DURATION){
return;
}
this.damageGained += calculateEffectiveDamage(event, MASTER_OF_THE_ELEMENTS.INCREASE);
}
get damagePercent() {
return this.owner.getPercentageOfTotalDamageDone(this.damageGained);
}
get damagePerSecond() {
return this.damageGained / (this.owner.fightDuration / 1000);
}
get isBugged() {
return this.bugCheckNecessary && (this.selectedCombatant.getBuffUptime(SPELLS.MASTER_OF_THE_ELEMENTS_BUFF.id) || 0) === 0;
}
get suggestionTresholds() {
return {
actual: this.isBugged,
isEqual: true,
style: 'boolean',
};
}
reverseEffectiveDamageDonePerSecond(number, increase){
return number*(1 + increase)/this.owner.fightDuration*1000;
}
suggestions(when){
when(this.suggestionTresholds)
.addSuggestion((suggest) => {
return suggest(<>Master Of the Elements bugged out and you lost out on at least {formatNumber(this.reverseEffectiveDamageDonePerSecond(this.damageGained,MASTER_OF_THE_ELEMENTS.INCREASE))} DPS.
Consider getting this weakaura: <a href="https://wago.io/motecheck">MotE-Checker</a> to be notified when MotE goes belly up again.</>)
.icon(SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.icon)
.staticImportance(SUGGESTION_IMPORTANCE.MAJOR);
});
}
statistic() {
let value = `${formatPercentage(this.damagePercent)} %`;
let label = `Contributed ${formatNumber(this.damagePerSecond)} DPS (${formatNumber(this.damageGained)} total damage, excluding EQ).`;
if (this.isBugged) {
value = `BUGGED`;
label = `Master Of The Elements can bug out and not work sometimes. Check the Suggestions for more information.`;
}
return (
<StatisticBox
position={STATISTIC_ORDER.OPTIONAL()}
icon={<SpellIcon id={SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.id} />}
value={value}
label={label}
>
<table className="table table-condensed">
<thead>
<tr>
<th>Ability</th>
<th>Number of Buffed Casts</th>
</tr>
</thead>
<tbody>
{Object.keys(this.moteBuffedAbilities).map((e) => (
<tr key={e}>
<th>{<SpellLink id={Number(e)} />}</th>
<td>{this.moteBuffedAbilities[e]}</td>
</tr>
))}
</tbody>
</table>
</StatisticBox>
);
}
}
export default MasterOfTheElements;
|
client/modules/Post/__tests__/components/PostListItem.spec.js
|
acguanacaste/liomysSalvini
|
import React from 'react';
import test from 'ava';
import sinon from 'sinon';
import PostListItem from '../../components/PostListItem/PostListItem';
import { mountWithIntl, shallowWithIntl } from '../../../../util/react-intl-test-helper';
const post = { name: 'Prashant', title: 'Hello Mern', slug: 'hello-mern', cuid: 'f34gb2bh24b24b2', content: "All cats meow 'mern!'" };
const props = {
post,
onDelete: () => {},
};
test('renders properly', t => {
const wrapper = shallowWithIntl(
<PostListItem {...props} />
);
t.truthy(wrapper.hasClass('single-post'));
t.is(wrapper.find('Link').first().prop('children'), post.title);
t.regex(wrapper.find('.author-name').first().text(), new RegExp(post.name));
t.is(wrapper.find('.post-desc').first().text(), post.content);
});
test('has correct props', t => {
const wrapper = mountWithIntl(
<PostListItem {...props} />
);
t.deepEqual(wrapper.prop('post'), props.post);
t.is(wrapper.prop('onClick'), props.onClick);
t.is(wrapper.prop('onDelete'), props.onDelete);
});
test('calls onDelete', t => {
const onDelete = sinon.spy();
const wrapper = shallowWithIntl(
<PostListItem post={post} onDelete={onDelete} />
);
wrapper.find('.post-action > a').first().simulate('click');
t.truthy(onDelete.calledOnce);
});
|
frontend/test/app/containers/RetirePage-test.js
|
dannycoates/testpilot
|
import React from 'react';
import { expect } from 'chai';
import sinon from 'sinon';
import { shallow, mount } from 'enzyme';
import RetirePage from '../../../src/app/containers/RetirePage';
describe('app/containers/RetirePage', () => {
let props, subject;
beforeEach(function() {
props = {
hasAddon: true,
sendToGA: sinon.spy(),
};
subject = shallow(<RetirePage {...props} />);
});
const findByL10nID = (id, useSubject) =>
(useSubject || subject).findWhere(el => id === el.props()['data-l10n-id']);
it('should render expected content', () => {
expect(findByL10nID('retirePageProgressMessage')).to.have.property('length', 1);
expect(findByL10nID('retirePageMessage')).to.have.property('length', 0);
});
it('should fake uninstall completion if too much time has passed', (done) => {
// Switch to mounted component to exercise componentDidMount
const mountedProps = { ...props,
fakeUninstallDelay: 10,
setHasAddon: sinon.spy()
};
const mountedSubject = mount(<RetirePage {...mountedProps} />);
expect(mountedSubject.state('fakeUninstalled')).to.be.false;
expect(findByL10nID('retirePageMessage', mountedSubject)).to.have.property('length', 0);
setTimeout(() => {
expect(mountedSubject.state('fakeUninstalled')).to.be.true;
expect(findByL10nID('retirePageMessage', mountedSubject)).to.have.property('length', 1);
expect(mountedProps.setHasAddon.called).to.be.true;
done();
}, 20);
});
describe('with hasAddon=false', () => {
beforeEach(() => {
subject.setProps({ hasAddon: false });
});
it('should render expected content', () => {
expect(findByL10nID('retirePageProgressMessage')).to.have.property('length', 0);
expect(findByL10nID('retirePageMessage')).to.have.property('length', 1);
});
it('should ping GA when survey button is clicked', () => {
findByL10nID('retirePageSurveyButton').simulate('click');
expect(props.sendToGA.lastCall.args).to.deep.equal(['event', {
eventCategory: 'RetirePage Interactions',
eventAction: 'button click',
eventLabel: 'take survey'
}]);
});
});
});
|
node_modules/react-router/es6/RouteUtils.js
|
jvstrpv/reactredux_2
|
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 React from 'react';
function isValidChild(object) {
return object == null || React.isValidElement(object);
}
export function isReactChildren(object) {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}
function createRoute(defaultProps, props) {
return _extends({}, defaultProps, props);
}
export function createRouteFromReactElement(element) {
var type = element.type;
var route = createRoute(type.defaultProps, element.props);
if (route.children) {
var childRoutes = createRoutesFromReactChildren(route.children, route);
if (childRoutes.length) route.childRoutes = childRoutes;
delete route.children;
}
return route;
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router'
*
* const routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* )
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
export function createRoutesFromReactChildren(children, parentRoute) {
var routes = [];
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
var route = element.type.createRouteFromReactElement(element, parentRoute);
if (route) routes.push(route);
} else {
routes.push(createRouteFromReactElement(element));
}
}
});
return routes;
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
export function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes);
} else if (routes && !Array.isArray(routes)) {
routes = [routes];
}
return routes;
}
|
Libraries/Text/Text.js
|
rickbeerendonk/react-native
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Text
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheetPropType = require('StyleSheetPropType');
const TextStylePropTypes = require('TextStylePropTypes');
const Touchable = require('Touchable');
const createReactClass = require('create-react-class');
const createReactNativeComponentClass = require('createReactNativeComponentClass');
const mergeFast = require('mergeFast');
const processColor = require('processColor');
const stylePropType = StyleSheetPropType(TextStylePropTypes);
const viewConfig = {
validAttributes: mergeFast(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
numberOfLines: true,
ellipsizeMode: true,
allowFontScaling: true,
disabled: true,
selectable: true,
selectionColor: true,
adjustsFontSizeToFit: true,
minimumFontScale: true,
textBreakStrategy: true,
}),
uiViewClassName: 'RCTText',
};
/**
* A React component for displaying text.
*
* `Text` supports nesting, styling, and touch handling.
*
* In the following example, the nested title and body text will inherit the
* `fontFamily` from `styles.baseText`, but the title provides its own
* additional styles. The title and body will stack on top of each other on
* account of the literal newlines:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, Text, StyleSheet } from 'react-native';
*
* export default class TextInANest extends Component {
* constructor(props) {
* super(props);
* this.state = {
* titleText: "Bird's Nest",
* bodyText: 'This is not really a bird nest.'
* };
* }
*
* render() {
* return (
* <Text style={styles.baseText}>
* <Text style={styles.titleText} onPress={this.onPressTitle}>
* {this.state.titleText}{'\n'}{'\n'}
* </Text>
* <Text numberOfLines={5}>
* {this.state.bodyText}
* </Text>
* </Text>
* );
* }
* }
*
* const styles = StyleSheet.create({
* baseText: {
* fontFamily: 'Cochin',
* },
* titleText: {
* fontSize: 20,
* fontWeight: 'bold',
* },
* });
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('TextInANest', () => TextInANest);
* ```
*
* ## Nested text
*
* Both iOS and Android allow you to display formatted text by annotating
* ranges of a string with specific formatting like bold or colored text
* (`NSAttributedString` on iOS, `SpannableString` on Android). In practice,
* this is very tedious. For React Native, we decided to use web paradigm for
* this where you can nest text to achieve the same effect.
*
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, Text } from 'react-native';
*
* export default class BoldAndBeautiful extends Component {
* render() {
* return (
* <Text style={{fontWeight: 'bold'}}>
* I am bold
* <Text style={{color: 'red'}}>
* and red
* </Text>
* </Text>
* );
* }
* }
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('AwesomeProject', () => BoldAndBeautiful);
* ```
*
* Behind the scenes, React Native converts this to a flat `NSAttributedString`
* or `SpannableString` that contains the following information:
*
* ```javascript
* "I am bold and red"
* 0-9: bold
* 9-17: bold, red
* ```
*
* ## Nested views (iOS only)
*
* On iOS, you can nest views within your Text component. Here's an example:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, Text, View } from 'react-native';
*
* export default class BlueIsCool extends Component {
* render() {
* return (
* <Text>
* There is a blue square
* <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
* in between my text.
* </Text>
* );
* }
* }
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('AwesomeProject', () => BlueIsCool);
* ```
*
* > In order to use this feature, you must give the view a `width` and a `height`.
*
* ## Containers
*
* The `<Text>` element is special relative to layout: everything inside is no
* longer using the flexbox layout but using text layout. This means that
* elements inside of a `<Text>` are no longer rectangles, but wrap when they
* see the end of the line.
*
* ```javascript
* <Text>
* <Text>First part and </Text>
* <Text>second part</Text>
* </Text>
* // Text container: all the text flows as if it was one
* // |First part |
* // |and second |
* // |part |
*
* <View>
* <Text>First part and </Text>
* <Text>second part</Text>
* </View>
* // View container: each text is its own block
* // |First part |
* // |and |
* // |second part|
* ```
*
* ## Limited Style Inheritance
*
* On the web, the usual way to set a font family and size for the entire
* document is to take advantage of inherited CSS properties like so:
*
* ```css
* html {
* font-family: 'lucida grande', tahoma, verdana, arial, sans-serif;
* font-size: 11px;
* color: #141823;
* }
* ```
*
* All elements in the document will inherit this font unless they or one of
* their parents specifies a new rule.
*
* In React Native, we are more strict about it: **you must wrap all the text
* nodes inside of a `<Text>` component**. You cannot have a text node directly
* under a `<View>`.
*
*
* ```javascript
* // BAD: will raise exception, can't have a text node as child of a <View>
* <View>
* Some text
* </View>
*
* // GOOD
* <View>
* <Text>
* Some text
* </Text>
* </View>
* ```
*
* You also lose the ability to set up a default font for an entire subtree.
* The recommended way to use consistent fonts and sizes across your
* application is to create a component `MyAppText` that includes them and use
* this component across your app. You can also use this component to make more
* specific components like `MyAppHeaderText` for other kinds of text.
*
* ```javascript
* <View>
* <MyAppText>Text styled with the default font for the entire application</MyAppText>
* <MyAppHeaderText>Text styled as a header</MyAppHeaderText>
* </View>
* ```
*
* Assuming that `MyAppText` is a component that simply renders out its
* children into a `Text` component with styling, then `MyAppHeaderText` can be
* defined as follows:
*
* ```javascript
* class MyAppHeaderText extends Component {
* render() {
* return (
* <MyAppText>
* <Text style={{fontSize: 20}}>
* {this.props.children}
* </Text>
* </MyAppText>
* );
* }
* }
* ```
*
* Composing `MyAppText` in this way ensures that we get the styles from a
* top-level component, but leaves us the ability to add / override them in
* specific use cases.
*
* React Native still has the concept of style inheritance, but limited to text
* subtrees. In this case, the second part will be both bold and red.
*
* ```javascript
* <Text style={{fontWeight: 'bold'}}>
* I am bold
* <Text style={{color: 'red'}}>
* and red
* </Text>
* </Text>
* ```
*
* We believe that this more constrained way to style text will yield better
* apps:
*
* - (Developer) React components are designed with strong isolation in mind:
* You should be able to drop a component anywhere in your application,
* trusting that as long as the props are the same, it will look and behave the
* same way. Text properties that could inherit from outside of the props would
* break this isolation.
*
* - (Implementor) The implementation of React Native is also simplified. We do
* not need to have a `fontFamily` field on every single element, and we do not
* need to potentially traverse the tree up to the root every time we display a
* text node. The style inheritance is only encoded inside of the native Text
* component and doesn't leak to other components or the system itself.
*
*/
const Text = createReactClass({
displayName: 'Text',
propTypes: {
/**
* When `numberOfLines` is set, this prop defines how text will be truncated.
* `numberOfLines` must be set in conjunction with this prop.
*
* This can be one of the following values:
*
* - `head` - The line is displayed so that the end fits in the container and the missing text
* at the beginning of the line is indicated by an ellipsis glyph. e.g., "...wxyz"
* - `middle` - The line is displayed so that the beginning and end fit in the container and the
* missing text in the middle is indicated by an ellipsis glyph. "ab...yz"
* - `tail` - The line is displayed so that the beginning fits in the container and the
* missing text at the end of the line is indicated by an ellipsis glyph. e.g., "abcd..."
* - `clip` - Lines are not drawn past the edge of the text container.
*
* The default is `tail`.
*
* > `clip` is working only for iOS
*/
ellipsizeMode: PropTypes.oneOf(['head', 'middle', 'tail', 'clip']),
/**
* Used to truncate the text with an ellipsis after computing the text
* layout, including line wrapping, such that the total number of lines
* does not exceed this number.
*
* This prop is commonly used with `ellipsizeMode`.
*/
numberOfLines: PropTypes.number,
/**
* Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`
* The default value is `highQuality`.
* @platform android
*/
textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']),
/**
* Invoked on mount and layout changes with
*
* `{nativeEvent: {layout: {x, y, width, height}}}`
*/
onLayout: PropTypes.func,
/**
* This function is called on press.
*
* e.g., `onPress={() => console.log('1st')}`
*/
onPress: PropTypes.func,
/**
* This function is called on long press.
*
* e.g., `onLongPress={this.increaseSize}>`
*/
onLongPress: PropTypes.func,
/**
* When the scroll view is disabled, this defines how far your touch may
* move off of the button, before deactivating the button. Once deactivated,
* try moving it back and you'll see that the button is once again
* reactivated! Move it back and forth several times while the scroll view
* is disabled. Ensure you pass in a constant to reduce memory allocations.
*/
pressRetentionOffset: EdgeInsetsPropType,
/**
* Lets the user select text, to use the native copy and paste functionality.
*/
selectable: PropTypes.bool,
/**
* The highlight color of the text.
* @platform android
*/
selectionColor: ColorPropType,
/**
* When `true`, no visual change is made when text is pressed down. By
* default, a gray oval highlights the text on press down.
* @platform ios
*/
suppressHighlighting: PropTypes.bool,
style: stylePropType,
/**
* Used to locate this view in end-to-end tests.
*/
testID: PropTypes.string,
/**
* Used to locate this view from native code.
*/
nativeID: PropTypes.string,
/**
* Specifies whether fonts should scale to respect Text Size accessibility settings. The
* default is `true`.
*/
allowFontScaling: PropTypes.bool,
/**
* When set to `true`, indicates that the view is an accessibility element. The default value
* for a `Text` element is `true`.
*
* See the
* [Accessibility guide](docs/accessibility.html#accessible-ios-android)
* for more information.
*/
accessible: PropTypes.bool,
/**
* Specifies whether font should be scaled down automatically to fit given style constraints.
* @platform ios
*/
adjustsFontSizeToFit: PropTypes.bool,
/**
* Specifies smallest possible scale a font can reach when adjustsFontSizeToFit is enabled. (values 0.01-1.0).
* @platform ios
*/
minimumFontScale: PropTypes.number,
/**
* Specifies the disabled state of the text view for testing purposes
* @platform android
*/
disabled: PropTypes.bool,
},
getDefaultProps(): Object {
return {
accessible: true,
allowFontScaling: true,
ellipsizeMode: 'tail',
};
},
getInitialState: function(): Object {
return mergeFast(Touchable.Mixin.touchableGetInitialState(), {
isHighlighted: false,
});
},
mixins: [NativeMethodsMixin],
viewConfig: viewConfig,
getChildContext(): Object {
return {isInAParentText: true};
},
childContextTypes: {
isInAParentText: PropTypes.bool
},
contextTypes: {
isInAParentText: PropTypes.bool
},
/**
* Only assigned if touch is needed.
*/
_handlers: (null: ?Object),
_hasPressHandler(): boolean {
return !!this.props.onPress || !!this.props.onLongPress;
},
/**
* These are assigned lazily the first time the responder is set to make plain
* text nodes as cheap as possible.
*/
touchableHandleActivePressIn: (null: ?Function),
touchableHandleActivePressOut: (null: ?Function),
touchableHandlePress: (null: ?Function),
touchableHandleLongPress: (null: ?Function),
touchableGetPressRectOffset: (null: ?Function),
render(): React.Element<any> {
let newProps = this.props;
if (this.props.onStartShouldSetResponder || this._hasPressHandler()) {
if (!this._handlers) {
this._handlers = {
onStartShouldSetResponder: (): bool => {
const shouldSetFromProps = this.props.onStartShouldSetResponder &&
// $FlowFixMe(>=0.41.0)
this.props.onStartShouldSetResponder();
const setResponder = shouldSetFromProps || this._hasPressHandler();
if (setResponder && !this.touchableHandleActivePressIn) {
// Attach and bind all the other handlers only the first time a touch
// actually happens.
for (const key in Touchable.Mixin) {
if (typeof Touchable.Mixin[key] === 'function') {
(this: any)[key] = Touchable.Mixin[key].bind(this);
}
}
this.touchableHandleActivePressIn = () => {
if (this.props.suppressHighlighting || !this._hasPressHandler()) {
return;
}
this.setState({
isHighlighted: true,
});
};
this.touchableHandleActivePressOut = () => {
if (this.props.suppressHighlighting || !this._hasPressHandler()) {
return;
}
this.setState({
isHighlighted: false,
});
};
this.touchableHandlePress = (e: SyntheticEvent<>) => {
this.props.onPress && this.props.onPress(e);
};
this.touchableHandleLongPress = (e: SyntheticEvent<>) => {
this.props.onLongPress && this.props.onLongPress(e);
};
this.touchableGetPressRectOffset = function(): RectOffset {
return this.props.pressRetentionOffset || PRESS_RECT_OFFSET;
};
}
return setResponder;
},
onResponderGrant: function(e: SyntheticEvent<>, dispatchID: string) {
this.touchableHandleResponderGrant(e, dispatchID);
this.props.onResponderGrant &&
this.props.onResponderGrant.apply(this, arguments);
}.bind(this),
onResponderMove: function(e: SyntheticEvent<>) {
this.touchableHandleResponderMove(e);
this.props.onResponderMove &&
this.props.onResponderMove.apply(this, arguments);
}.bind(this),
onResponderRelease: function(e: SyntheticEvent<>) {
this.touchableHandleResponderRelease(e);
this.props.onResponderRelease &&
this.props.onResponderRelease.apply(this, arguments);
}.bind(this),
onResponderTerminate: function(e: SyntheticEvent<>) {
this.touchableHandleResponderTerminate(e);
this.props.onResponderTerminate &&
this.props.onResponderTerminate.apply(this, arguments);
}.bind(this),
onResponderTerminationRequest: function(): bool {
// Allow touchable or props.onResponderTerminationRequest to deny
// the request
var allowTermination = this.touchableHandleResponderTerminationRequest();
if (allowTermination && this.props.onResponderTerminationRequest) {
allowTermination = this.props.onResponderTerminationRequest.apply(this, arguments);
}
return allowTermination;
}.bind(this),
};
}
newProps = {
...this.props,
...this._handlers,
isHighlighted: this.state.isHighlighted,
};
}
if (newProps.selectionColor != null) {
newProps = {
...newProps,
selectionColor: processColor(newProps.selectionColor)
};
}
if (Touchable.TOUCH_TARGET_DEBUG && newProps.onPress) {
newProps = {
...newProps,
style: [this.props.style, {color: 'magenta'}],
};
}
if (this.context.isInAParentText) {
return <RCTVirtualText {...newProps} />;
} else {
return <RCTText {...newProps} />;
}
},
});
type RectOffset = {
top: number,
left: number,
right: number,
bottom: number,
}
var PRESS_RECT_OFFSET = {top: 20, left: 20, right: 20, bottom: 30};
var RCTText = createReactNativeComponentClass(
viewConfig.uiViewClassName,
() => viewConfig
);
var RCTVirtualText = RCTText;
if (Platform.OS === 'android') {
RCTVirtualText = createReactNativeComponentClass('RCTVirtualText', () => ({
validAttributes: mergeFast(ReactNativeViewAttributes.UIView, {
isHighlighted: true,
}),
uiViewClassName: 'RCTVirtualText',
}));
}
module.exports = Text;
|
App/Components/LandmarkList.js
|
quickresolve/CycleTheBay
|
"use strict";
import React, { Component } from 'react';
import {
StyleSheet,
Text,
TouchableOpacity,
ScrollView,
Image,
TabBarIOS,
AlertIOS,
ListView,
View,
AppActions,
navigator
} from 'react-native';
import Trail from './Trail'
import Main from './Main'
import Weather from './Weather'
import Local from './Local'
import navAnimations from '../Helper_Functions/navAnimations'
class LandmarkList extends Component {
constructor(props){
super(props);
this.state = {
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
loaded: false,
trail_id: this.props.trail_id,
landmark_id: '',
title: '',
desc: '',
img_url: ''
};
}
componentDidMount() {
console.log(this.state.trail_id)
var url = `http://pacific-meadow-80820.herokuapp.com/api/locations/${this.state.trail_id}/landmarks`
this.fetchData(url);
}
fetchData(url) {
fetch(url, {method: "GET"})
.then((response) => response.json())
.then((responseData) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(responseData),
loaded: true,
});
})
.done();
}
_handleLandmarkSelection(landmark){
var trail_id = this.state.trail_id
console.log(trail_id)
console.log(landmark.id)
fetch('http://pacific-meadow-80820.herokuapp.com/api/locations/'+trail_id+'/landmarks/'+landmark.id)
.then((response) => response.json())
.then(responseData => {
this.props.navigator.push({
title: landmark.title,
name: 'Landmark',
passProps: {
title: responseData.title,
desc: responseData.desc,
img_url: responseData.image_url
},
});
}).done();
}
render() {
if (!this.state.loaded) {
this.renderLoadingView();
}
return(
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>
Landmarks List
</Text>
</View>
<ListView
dataSource={this.state.dataSource}
renderRow={this.renderLandmark.bind(this)}
style={styles.listView}
/>
<View style={styles.footerNav}>
<TouchableOpacity
onPress={this._onHomeButton.bind(this)}
style={styles.button}
underlayColor="gray">
<Text style={styles.buttonText}>Home</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={this._onBackButton.bind(this)}
style={styles.button}
underlayColor="gray">
<Text style={styles.buttonText}>Back to Overview</Text>
</TouchableOpacity>
<TouchableOpacity
style={styles.button}
underlayColor="gray">
<Text style={styles.blankButton}>blank</Text>
</TouchableOpacity>
</View>
</View>
);
}
renderLoadingView() {
return (
<View style={styles.container}>
<Text>
Loading landmarks...
</Text>
</View>
)
}
renderLandmark(landmark) {
return (
<View>
<Image
source={{uri: landmark.image_url}}
style={styles.image}>
<TouchableOpacity
style={styles.row}
onPress={(this._handleLandmarkSelection.bind(this, landmark))}
underlayColor="white">
<Text style={styles.landmark}>
{landmark.title}
</Text>
</TouchableOpacity>
</Image>
</View>
);
}
_onHomeButton(){
this.props.navigator.popToTop()
}
_onBackButton(){
this.props.navigator.pop()
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'stretch'
},
header: {
flex: 1,
justifyContent: 'center',
alignItems: 'center'
},
title: {
fontSize: 20,
marginTop: 25,
},
landmark: {
flex: 1,
fontSize: 20,
color: 'white',
fontWeight: 'bold',
justifyContent: 'center',
},
listView: {
flex: 10,
marginTop: 20
},
row: {
flex: 1,
alignItems: 'stretch',
margin: 20
},
image: {
flex: 1,
alignItems: 'stretch',
marginBottom: 5,
padding: 20,
width: null,
height: 175
},
button: {
alignSelf: 'stretch',
justifyContent: 'center',
marginBottom: 20
},
buttonText:{
color: '#658D9F',
fontSize: 18,
justifyContent: 'center',
alignItems: 'center'
},
blankButton:{
color: '#d9d9d9',
fontSize: 18,
justifyContent: 'center',
alignItems: 'center'
},
footerNav: {
flex: 0,
flexDirection: 'row',
alignSelf: 'stretch',
justifyContent: 'space-between',
paddingTop: 15,
backgroundColor: '#d9d9d9',
paddingLeft: 20,
paddingRight: 20
}
});
module.exports = LandmarkList;
|
packages/ringcentral-widgets/components/MultiCallAnswerButton/index.js
|
u9520107/ringcentral-js-widget
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import AnswerIcon from '../../assets/images/Answer.svg';
import HoldIcon from '../../assets/images/Hold.svg';
import EndIcon from '../../assets/images/End.svg';
import CircleButton from '../CircleButton';
import styles from './styles.scss';
export default function MultiCallAnswerButton(props) {
const Icon = props.isEndOtherCall ? EndIcon : HoldIcon;
const iconClassName = classnames(
styles.button,
props.isEndOtherCall ? styles.endButton : ''
);
const text = props.title.split('\n').map((line, index) => (
<tspan dy={index ? '1.1em' : 0} x="250" key={line}>
{line}
</tspan>
));
return (
<svg
className={props.className}
viewBox="0 0 500 600"
width={props.width}
height={props.height}
x={props.x}
y={props.y}
>
<CircleButton
width="200"
height="200"
x={60}
y={50}
className={iconClassName}
onClick={props.onClick}
icon={Icon}
/>
<CircleButton
width="250"
height="250"
x={200}
y={110}
className={classnames(styles.button, styles.answer)}
showBorder={false}
onClick={props.onClick}
icon={AnswerIcon}
/>
<text
className={styles.buttonTitle}
x="250"
y="500"
textAnchor="middle"
>
{text}
</text>
</svg>
);
}
MultiCallAnswerButton.propTypes = {
title: PropTypes.string.isRequired,
className: PropTypes.string,
onClick: PropTypes.func.isRequired,
isEndOtherCall: PropTypes.bool,
width: PropTypes.string,
height: PropTypes.string,
x: PropTypes.number,
y: PropTypes.number,
};
MultiCallAnswerButton.defaultProps = {
className: null,
isEndOtherCall: true,
width: '100%',
height: '100%',
x: 0,
y: 0,
};
|
src/svg-icons/av/movie.js
|
xmityaz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMovie = (props) => (
<SvgIcon {...props}>
<path d="M18 4l2 4h-3l-2-4h-2l2 4h-3l-2-4H8l2 4H7L5 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4h-4z"/>
</SvgIcon>
);
AvMovie = pure(AvMovie);
AvMovie.displayName = 'AvMovie';
AvMovie.muiName = 'SvgIcon';
export default AvMovie;
|
src/svg-icons/navigation/subdirectory-arrow-right.js
|
pomerantsev/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationSubdirectoryArrowRight = (props) => (
<SvgIcon {...props}>
<path d="M19 15l-6 6-1.42-1.42L15.17 16H4V4h2v10h9.17l-3.59-3.58L13 9l6 6z"/>
</SvgIcon>
);
NavigationSubdirectoryArrowRight = pure(NavigationSubdirectoryArrowRight);
NavigationSubdirectoryArrowRight.displayName = 'NavigationSubdirectoryArrowRight';
NavigationSubdirectoryArrowRight.muiName = 'SvgIcon';
export default NavigationSubdirectoryArrowRight;
|
imports/ui/components/Transition/Slide.js
|
ShinyLeee/meteor-album-app
|
import PropTypes from 'prop-types';
import React from 'react';
import CSSTransition from 'react-transition-group/CSSTransition';
const SlideTransition = ({ children, ...props }) => (
<CSSTransition
{...props}
classNames="slide"
timeout={300}
appear
>
{children}
</CSSTransition>
);
SlideTransition.propTypes = {
children: PropTypes.any.isRequired,
};
export default SlideTransition;
|
packages/ringcentral-widgets/components/CopyToClipboard/index.js
|
ringcentral/ringcentral-js-widget
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { Button } from '../Button';
import styles from './styles.scss';
import i18n from './i18n';
class CopyToClipboard extends Component {
executeCopy() {
this.copyTextArea.focus();
this.copyTextArea.select();
try {
const result = document.execCommand('copy');
if (result) {
this.copyTextArea.blur();
if (typeof this.props.handleSuccess === 'function')
this.props.handleSuccess();
} else if (typeof this.props.handleFailure === 'function') {
this.props.handleFailure();
}
} catch (e) {
console.error(e);
if (typeof this.props.handleFailure === 'function') {
this.props.handleFailure();
}
}
}
render() {
const {
currentLocale,
buttonClassName,
disabled,
copiedText,
buttonText,
button: CustomButton,
} = this.props;
return (
<div className={styles.container}>
<textarea
className={styles.copyTextArea}
ref={(ref) => {
this.copyTextArea = ref;
}}
defaultValue={copiedText}
/>
{CustomButton ? (
<CustomButton
{...this.props}
executeCopy={() => this.executeCopy()}
/>
) : (
<Button
disabled={disabled}
dataSign="copyToClipboard"
className={classnames(styles.primaryButton, buttonClassName)}
onClick={() => this.executeCopy()}
>
{buttonText || i18n.getString('copyToClipboard', currentLocale)}
</Button>
)}
</div>
);
}
}
CopyToClipboard.propTypes = {
currentLocale: PropTypes.string.isRequired,
handleSuccess: PropTypes.func,
handleFailure: PropTypes.func,
buttonClassName: PropTypes.string,
disabled: PropTypes.bool,
copiedText: PropTypes.string,
buttonText: PropTypes.string,
button: PropTypes.oneOfType([PropTypes.node, PropTypes.func]),
};
CopyToClipboard.defaultProps = {
handleSuccess: undefined,
handleFailure: undefined,
buttonClassName: undefined,
disabled: undefined,
copiedText: undefined,
buttonText: undefined,
button: undefined,
};
export default CopyToClipboard;
|
node_modules/react-dnd/examples/_dustbin-interesting/index.js
|
asm-products/notello
|
'use strict';
import React from 'react';
import Container from './Container';
const DustbinSorted = React.createClass({
render() {
return (
<div>
<Container />
<hr />
<p>
Several different dustbins can handle several types of items. Note that the last dustbin is special: it can handle files from your hard drive and URLs.
</p>
</div>
);
}
});
export default DustbinSorted;
|
static/src/components/StatsPanel.js
|
Firazenics/finalreckoningbot
|
// @flow
import React from 'react';
import numeral from 'numeral';
import * as StatsActions from '../actions/StatsActions';
import Constants from '../Constants';
const BOTTOM_PADDING = 8;
const StatsRow = ({icon, label, value}) => {
return (
<div className="stats-row">
<img src={icon} />
<div className="label-value">
<div className="value">{numeral(value).format('0,0')}</div>
<div className="label">{label}</div>
</div>
</div>
);
};
type StatsPanelProps = {
count: number,
uniqueUsers: number,
uniqueGuilds: number,
uniqueChannels: number,
secretCount: number,
show: boolean,
hasBeenShown: boolean,
bottom: number
};
const StatsPanel = ({
count,
uniqueUsers,
uniqueGuilds,
uniqueChannels,
secretCount,
show,
hasBeenShown,
bottom
}: StatsPanelProps) => {
if (!hasBeenShown) {
return <noscript />;
}
return (
<div className={`stats-panel crossfade ${show ? 'one' : 'one-reverse'}`} style={{bottom: bottom + BOTTOM_PADDING}}>
<StatsRow icon={Constants.Image.ICON_PLAYS} label="Plays" value={count} />
<StatsRow icon={Constants.Image.ICON_USERS} label="Unique Users" value={uniqueUsers} />
<StatsRow icon={Constants.Image.ICON_SERVERS} label="Unique Servers" value={uniqueGuilds} />
<StatsRow icon={Constants.Image.ICON_CHANNELS} label="Unique Channels" value={uniqueChannels} />
<StatsRow icon={Constants.Image.ICON_SECERT} label="Secret Plays" value={secretCount} />
</div>
);
};
export default StatsPanel;
|
2021/src/components/Typography/Text.js
|
sjamcsclub/jamhacks.ca
|
import React from 'react';
import styled from 'styled-components';
import { media } from '../../utils/media';
const Text = styled.p`
color: ${(props) =>
props.dark
? props.theme.colors.text.dark.text
: props.theme.colors.text.light.text};
&::selection {
background: ${(props) =>
props.dark
? props.theme.colors.secondary.default
: props.theme.colors.primary.default};
}
font-size: 1.2rem;
font-style: normal;
font-weight: normal;
line-height: 140%;
font-family: ${(props) => props.theme.fonts.secondary};
${media('md')`
font-size: 1.1rem;
`}
${media('sm')`
font-size: 1rem;
`}
`;
export default Text;
|
app/js/components/LoadingIndicator.js
|
niksoc/srmconnect
|
import React from 'react';
const LoadingIndicator = ()=>(<p>loading...</p>);
export default LoadingIndicator;
|
packages/icons/src/dv/Fortran.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function DvFortran(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M7.314 38.048h2.954c1.637 0 3.246-.925 3.246-3.224V13.176c0-2.912-.97-3.224-3.987-3.224H7.5V6h33.186v14.362h-3.87c0-3.431-.392-5.939-1.373-7.81-1.08-2.08-3.292-2.6-7.167-2.6h-7.893v11.451h1.532c4.472 0 5.657-1.12 5.563-7.084h3.49v18.582h-3.49c-.312-5.98-.647-8.115-6.251-8.05h-.936v9.973c0 2.912 1.208 3.224 4.224 3.224h2.166V42H7.314v-3.952z" />
</IconBase>
);
}
export default DvFortran;
|
src/server.js
|
wework/react-redux-universal-hot-example
|
import Express from 'express';
import React from 'react';
import Location from 'react-router/lib/Location';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import api from './api/api';
import ApiClient from './helpers/ApiClient';
import universalRouter from './helpers/universalRouter';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
const pretty = new PrettyError();
const app = new Express();
const proxy = httpProxy.createProxyServer({
target: 'http://localhost:' + config.apiPort
});
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(require('serve-static')(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
let json;
console.log('proxy error', error);
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = { error: 'proxy_error', reason: error.message };
res.end(JSON.stringify(json));
});
app.use((req, res) => {
if (__DEVELOPMENT__) {
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
webpackIsomorphicTools.refresh();
}
const client = new ApiClient(req);
const store = createStore(client);
const location = new Location(req.path, req.query);
const hydrateOnClient = function() {
res.send('<!doctype html>\n' +
React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={<div/>} store={store}/>));
}
if (__DISABLE_SSR__) {
hydrateOnClient();
return;
} else {
universalRouter(location, undefined, store)
.then(({component, transition, isRedirect}) => {
if (isRedirect) {
res.redirect(transition.redirectInfo.pathname);
return;
}
res.send('<!doctype html>\n' +
React.renderToString(<Html assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
})
.catch((error) => {
if (error.redirect) {
res.redirect(error.redirect);
return;
}
console.error('ROUTER ERROR:', pretty.render(error));
hydrateOnClient(); // let client render error page or re-request data
});
}
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) {
console.error(err);
} else {
api().then(() => {
console.info('==> ✅ Server is listening');
console.info('==> 🌎 %s running on port %s, API on port %s', config.app.name, config.port, config.apiPort);
console.info('----------\n==> 💻 Open http://localhost:%s in a browser to view the app.', config.port);
});
}
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
react_version/src/AppHeader/AppHeader.js
|
maju435/drozdz
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import './AppHeader.css';
import { Link } from 'react-router-dom';
class AppHeader extends Component {
render() {
return (
<header className="App-header">
<nav className="main-nav">
<div className="main-nav-left">
<ul>
<li><Link to="/"><span>Główna</span></Link></li>
<li><Link to="/galery"><span>Galeria</span></Link></li>
<li><Link to="/contact"><span>Kontakt</span></Link></li>
</ul>
</div>
<div className="main-nav-right">
<ul>
<li style={{ float: "right" }} ><a href="#0"><span>Zarejestruj</span></a></li>
<li style={{ float: "right" }} ><a href="#0"><span>Zaloguj</span></a></li>
</ul>
</div>
</nav>
</header>
);
}
}
AppHeader.propTypes = {
};
export default AppHeader;
|
src/components/metadata/MetaArray.js
|
ashmaroli/jekyll-admin
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Sortable from 'sortablejs';
import _ from 'underscore';
import MetaArrayItem from './MetaArrayItem';
export class MetaArray extends Component {
sortableGroupDecorator(component) {
const { moveArrayItem, namePrefix } = this.props;
if (component) {
const options = {
draggable: '.array-item-wrap',
group: { name: 'meta-array-items', pull: false, put: false },
handle: '.move',
animation: 0,
onEnd: (e) => {
let srcInd = e.item.getAttribute('data-id');
moveArrayItem(namePrefix, srcInd, e.newIndex);
}
};
Sortable.create(component, options);
}
}
render() {
const { fieldKey, fieldValue, namePrefix, addField,
removeField, updateFieldKey, updateFieldValue, moveArrayItem,
convertField, key_prefix, appMeta} = this.props;
const items = _.map(fieldValue, (item, i) => {
let type = 'simple';
if (_.isObject(item)) type = 'object';
if (_.isArray(item)) type = 'array';
return (
<MetaArrayItem
key={`${key_prefix}-${i}`}
key_prefix={key_prefix}
index={i}
fieldKey={fieldKey}
fieldValue={item}
type={type}
addField={addField}
removeField={removeField}
updateFieldKey={updateFieldKey}
updateFieldValue={updateFieldValue}
moveArrayItem={moveArrayItem}
convertField={convertField}
nameAttr={`${namePrefix}[${i}]`}
namePrefix={namePrefix}
appMeta={appMeta} />
);
});
return (
<div className="meta-value-array" ref={this.sortableGroupDecorator.bind(this)}>
{items}
<a onClick={() => addField(namePrefix)}
className="add-field-array" title="Add new list item">
<i className="fa fa-plus" />
</a>
</div>
);
}
}
MetaArray.propTypes = {
fieldKey: PropTypes.string.isRequired,
fieldValue: PropTypes.any.isRequired,
nameAttr: PropTypes.string.isRequired,
namePrefix: PropTypes.string.isRequired,
addField: PropTypes.func.isRequired,
removeField: PropTypes.func.isRequired,
updateFieldKey: PropTypes.func.isRequired,
updateFieldValue: PropTypes.func.isRequired,
convertField: PropTypes.func.isRequired,
moveArrayItem: PropTypes.func.isRequired,
key_prefix: PropTypes.string.isRequired,
appMeta: PropTypes.object
};
export default MetaArray;
|
components/list/ListItemActions.js
|
KerenChandran/react-toolbox
|
import React from 'react';
import style from './style';
import ListItemAction from './ListItemAction';
const ListItemActions = ({type, children}) => {
const validChildren = React.Children.toArray(children).filter(c => (
React.isValidElement(c)
));
return (
<span className={style[type]}>
{validChildren.map((action, i) => <ListItemAction key={i} action={action} />)}
</span>
);
};
ListItemActions.propTypes = {
children: React.PropTypes.any,
type: React.PropTypes.oneOf(['left', 'right'])
};
export default ListItemActions;
|
src/js/components/PasswordInput.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../utils/CSSClassnames';
import Button from './Button';
import ViewIcon from './icons/base/View';
import Intl from '../utils/Intl';
const CLASS_ROOT = CSSClassnames.PASSWORD_INPUT;
const INPUT = CSSClassnames.INPUT;
export default class PasswordInput extends Component {
constructor() {
super();
this.state = {
showPassword: false
};
}
render () {
const { className, ...rest } = this.props;
const { showPassword } = this.state;
const { intl } = this.context;
let classes = classnames(
CLASS_ROOT,
className
);
return (
<div className={classes}>
<input {...rest} ref={ref => this.inputRef = ref}
type={showPassword ? 'text' : 'password'}
className={`${INPUT} ${CLASS_ROOT}__input`} />
<Button className={`${CLASS_ROOT}__control`}
a11yTitle={Intl.getMessage(intl, 'Show Password')}
icon={
<ViewIcon colorIndex={showPassword ? 'brand' : undefined} />
}
onClick={() => this.setState({
showPassword: !this.state.showPassword })
} />
</div>
);
}
}
PasswordInput.propTypes = {
className: PropTypes.string
};
PasswordInput.contextTypes = {
intl: PropTypes.object
};
|
react-fundamental/src/components/LifeCycle.js
|
zhangfaliang/learnReact
|
import React, { Component } from 'react';
class LifeCycle extends Component {
static defaultProps = {
value: '开始渲染'
}
componentWillReceiveProps(nextProps){
console.log('componentWillReceiveProps');
this.setState({
value: nextProps.value
});
}
/**
* diff 数据对比
* 对比完成,如果数据没有差异,不更新
* return false
* @param {[type]} nextProps [description]
* @param {[type]} nextState [description]
* @return {[type]} [description]
*/
shouldComponentUpdate(nextProps,nextState){
console.log('shouldComponentUpdate');
return true;
}
componentWillUpdate(nextProps,nextState){
console.log('componentWillUpdate');
}
componentWillMount(){
console.log('componentWillMount');
}
render() {
console.log('render');
return <span>{this.props.value}</span>
}
componentDidMount() {
console.log('componentDidMount');
}
componentDidUpdate(prevProps,prevState) {
console.log('componentDidUpdate');
}
componentWillUnmount(prevProps,prevState) {
console.log('componentWillUnmount');
}
}
export default LifeCycle;
|
index.ios.js
|
t4sk/react-native-todo
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class Todo extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('Todo', () => Todo);
|
template/src/Component.js
|
nkbt/cf-react-component-template
|
import React from 'react';
export const {{package.global}} = () =>
<div>{{package.name}}</div>;
|
docs/src/app/components/pages/customization/Styles.js
|
IsenrichO/mui-with-arrows
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../CodeExample';
import MarkdownElement from '../../MarkdownElement';
import stylesText from './styles.md';
import stylesOverridingInlineText from './styles-overriding-inline.md';
import StylesOverridingInlineExample from './StylesOverridingInlineExample';
import stylesOverridingInlineExampleCode from '!raw!./StylesOverridingInlineExample';
import stylesOvveridingCssText from './styles-overriding-css.md';
import StylesOverridingCssExample from './StylesOverridingCssExample';
import stylesOvveridingCssExampleCode from '!raw!./StylesOverridingCssExample';
const stylesOvveridingCssExampleCodeWithCss = `${stylesOvveridingCssExampleCode}
/*
With the following css style:
.styles-overriding-css-example {
width: 50% !important;
margin: 0 auto !important;
border: 2px solid #FF9800 !important;
background-color: #ffd699 !important;
}
*/
`;
const Styles = () => (
<div>
<Title render={(previousTitle) => `Styles - ${previousTitle}`} />
<MarkdownElement text={stylesText} />
<MarkdownElement text={stylesOverridingInlineText} />
<CodeExample
title="Inline Style example"
code={stylesOverridingInlineExampleCode}
component={false}
>
<StylesOverridingInlineExample />
</CodeExample>
<MarkdownElement text={stylesOvveridingCssText} />
<CodeExample
title="CSS Style example"
code={stylesOvveridingCssExampleCodeWithCss}
component={false}
>
<StylesOverridingCssExample />
</CodeExample>
</div>
);
export default Styles;
|
src/layouts/Header/containers/HeaderContainer.js
|
dkanas/timelog
|
import React from 'react'
import { connect } from 'react-redux'
import pick from 'lodash/pick'
import { logout } from 'store/sessionModule'
import Header from '../components/Header'
const Connect = connect(
state => pick(state.session, ['user', 'isAuthenticated']),
{ logout }
)
const HeaderContainer = ({ isAuthenticated, user, logout }) => (
<Header
logout={logout}
isAuthenticated={isAuthenticated}
user={user} />
)
export default Connect(HeaderContainer)
|
example-swift/ReactNativeEventBridgeSwift/ReactNative/index.ios.js
|
maicki/react-native-event-bridge
|
/**
* @flow
*/
import React from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Button,
Alert,
EmitterSubscription,
} from 'react-native';
import EventBridge from 'react-native-event-bridge';
export default class ReactNativeEventBridgeSwift extends React.Component {
_eventSubscription: ?EmitterSubscription;
static contextTypes = {
rootTag: React.PropTypes.number,
};
componentDidMount() {
this._eventSubscription = EventBridge.addEventListener(
this,
// eslint-disable-next-line no-unused-vars
(name, info) => {
Alert.alert('Native Event', 'Received Event from Native');
}
);
}
componentWillUnmount() {
if (this._eventSubscription) {
this._eventSubscription.remove();
}
}
buttonClicked = () => {
// Emit an event from within a React component
EventBridge.emitEvent(this, 'Event');
};
buttonClickedCallback = () => {
// Emit an event with callback from within a React component
EventBridge.emitEventCallback(this, 'EventWithCallback', () => {
Alert.alert('Callback Response', 'Some Callback Response');
});
};
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native Event Bridge!
</Text>
<Button onPress={this.buttonClicked} title="Send RN Event" />
<Button
onPress={this.buttonClickedCallback}
title="Send RN Event With Callback"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
AppRegistry.registerComponent(
'ReactNativeEventBridgeSwift',
() => ReactNativeEventBridgeSwift
);
|
app/components/Header/index.js
|
juanda99/arasaac-frontend
|
/**
*
* Header
*
*/
import React from 'react'
import PropTypes from 'prop-types'
import AppBar from 'material-ui/AppBar'
import styles from './styles'
import Title from './Title'
import UserMenu from './UserMenu'
import GuestMenu from './GuestMenu'
const Header = (props) => {
const handleTouchTapLeftIconButton = () => {
props.touchTapLeftIconButton()
}
const {
isAuthenticated,
showMenuIconButton,
title,
isTranslating,
changeLocale,
signout,
isMobile,
role
} = props
return (
<div style={{ position: 'relative' }}>
<AppBar
onLeftIconButtonTouchTap={handleTouchTapLeftIconButton}
title={<Title docked={props.docked}>{title}</Title>}
zDepth={0}
id='header'
style={styles.appBar}
showMenuIconButton={showMenuIconButton}
iconElementRight={
isAuthenticated ? (
<UserMenu
isTranslating={isTranslating}
changeLocale={changeLocale}
signout={signout}
role={role}
/>
) : (
<GuestMenu isMobile={isMobile} />
)
}
/>
{/* <div style={{ position: 'absolute', margin: 10, left: '50px', color: 'white', top: 0, zIndex: 14000 }}>
<h1 style={{ display: 'inline' }}>ARASAAC</h1>
</div> */}
</div>
)
}
Header.propTypes = {
isAuthenticated: PropTypes.bool.isRequired,
// we use it both for menu icon and for
showMenuIconButton: PropTypes.bool.isRequired,
// será un string
title: PropTypes.oneOfType([
PropTypes.string.isRequired,
PropTypes.object.isRequired
]),
docked: PropTypes.bool.isRequired,
changeLocale: PropTypes.func.isRequired,
signout: PropTypes.func.isRequired,
touchTapLeftIconButton: PropTypes.func.isRequired,
isTranslating: PropTypes.bool.isRequired,
isMobile: PropTypes.bool.isRequired,
role: PropTypes.string
}
export default Header
|
src/server.js
|
GustavPersson/tvattstuga
|
import path from 'path';
import morgan from 'morgan';
import express from 'express';
import compression from 'compression';
import helmet from 'helmet';
import hpp from 'hpp';
import favicon from 'serve-favicon';
import React from 'react';
import { renderToString } from 'react-dom/server';
import { Provider } from 'react-redux';
import { createMemoryHistory, match, RouterContext } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import chalk from 'chalk';
import createRoutes from './routes';
import configureStore from './redux/store';
import { createSelectLocationState } from './util/helpers';
import renderHtmlPage from './util/renderHtmlPage';
import config from './config';
const app = express();
// Using helmet to secure Express with various HTTP headers
app.use(helmet());
// Prevent HTTP parameter pollution.
app.use(hpp());
// Compress all requests
app.use(compression());
// Use morgan for http request debug (only show error)
app.use(morgan('dev', { skip: (req, res) => res.statusCode < 400 }));
app.use(favicon(path.join(process.cwd(), './public/favicon.ico')));
app.use(express.static(path.join(process.cwd(), './public')));
// Run express as webpack dev server
if (__DEV__) {
const webpack = require('webpack');
const webpackConfig = require('../tools/webpack/config.babel');
const compiler = webpack(webpackConfig);
app.use(require('webpack-dev-middleware')(compiler, {
publicPath: webpackConfig.output.publicPath,
noInfo: true,
stats: { colors: true },
}));
app.use(require('webpack-hot-middleware')(compiler));
}
// Register server-side rendering middleware
app.get('*', (req, res) => {
if (__DEV__) webpackIsomorphicTools.refresh();
const store = configureStore();
// If __DISABLE_SSR__ = true, disable server side rendering
if (__DISABLE_SSR__) {
res.send(renderHtmlPage(store));
return;
}
const memoryHistory = createMemoryHistory(req.url);
const routes = createRoutes(store);
const history = syncHistoryWithStore(memoryHistory, store, {
selectLocationState: createSelectLocationState('routing'),
});
// eslint-disable-next-line max-len
match({ history, routes, location: req.url }, (error, redirectLocation, renderProps) => {
if (error) {
res.status(500).send(error.message);
} else if (redirectLocation) {
res.redirect(302, redirectLocation.pathname + redirectLocation.search);
} else if (!renderProps) {
res.sendStatus(404);
} else {
// Dispatch the initial action of each container first
const promises = renderProps.components
.filter(component => component.fetchData)
.map(component => component.fetchData(store.dispatch, renderProps.params));
// Then render the routes
Promise.all(promises)
.then(() => {
const content = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>,
);
res.status(200).send(renderHtmlPage(store, content));
})
.catch((err) => {
console.error(`==> 😭 Rendering routes error: ${err}`);
})
.catch((err) => {
console.error(`==> 😭 Rendering routes error: ${err}`);
});
}
});
});
if (config.port) {
app.listen(config.port, (err) => {
if (err) console.error(`==> 😭 OMG!!! ${err}`);
console.info(chalk.green(`==> 🌎 Listening at http://${config.host}:${config.port}`));
console.info(chalk.green(`==> 🌎 Server info ${config.host}:${config.port} ${process.env.NODE_ENV}`));
});
} else {
console.error(chalk.red('==> 😭 OMG!!! No PORT environment variable has been specified'));
}
|
src/Row.js
|
omerts/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import CustomPropTypes from './utils/CustomPropTypes';
const Row = React.createClass({
propTypes: {
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
return (
<ComponentClass {...this.props} className={classNames(this.props.className, 'row')}>
{this.props.children}
</ComponentClass>
);
}
});
export default Row;
|
src/svg-icons/hardware/laptop-mac.js
|
manchesergit/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareLaptopMac = (props) => (
<SvgIcon {...props}>
<path d="M20 18c1.1 0 1.99-.9 1.99-2L22 5c0-1.1-.9-2-2-2H4c-1.1 0-2 .9-2 2v11c0 1.1.9 2 2 2H0c0 1.1.9 2 2 2h20c1.1 0 2-.9 2-2h-4zM4 5h16v11H4V5zm8 14c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/>
</SvgIcon>
);
HardwareLaptopMac = pure(HardwareLaptopMac);
HardwareLaptopMac.displayName = 'HardwareLaptopMac';
HardwareLaptopMac.muiName = 'SvgIcon';
export default HardwareLaptopMac;
|
src/public/js/logs.js
|
TooAngel/democratic-collaboration
|
import React from 'react';
/**
* Logs class
**/
export class Logs extends React.Component { // eslint-disable-line no-unused-vars
/**
* contructor - The constructor
*
* @param {object} props - The properties
* @return {void}
**/
constructor(props) {
super(props);
this.state = {
dataFromServer: [],
};
this.initWS = this.initWS.bind(this);
}
/**
* componentDidUpdate - When the component updated
*
* @return {void}
**/
componentDidUpdate() {
this.node.scrollTop = this.node.scrollHeight;
}
/**
* initWS - Initializes the websocket connection
*
* @return {void}
**/
initWS() {
let protocol = 'wss';
if (window.location.protocol === 'http:') {
protocol = 'ws';
}
const url = `${protocol}://${window.location.hostname}:${window.location.port}/admin/logs`;
this.ws = new WebSocket(url);
this.ws.onopen = () => {
console.log('connected');
};
this.ws.onmessage = (event) => {
const dataFromServer = this.state.dataFromServer;
dataFromServer.push(event.data);
if (dataFromServer.length > 100) {
dataFromServer.shift();
}
this.setState({dataFromServer: dataFromServer});
};
this.ws.onclose = () => {
console.log('disconnected');
this.initWS();
};
}
/**
* componentDidMount - on build of the component
*
* @return {void}
**/
componentDidMount() {
this.initWS();
}
/**
* render - renders
* @return {object} - The element to be renderd
**/
render() {
const lines = [];
for (let i=0; i<this.state.dataFromServer.length; i++) {
lines.push(<li key={i}>{this.state.dataFromServer[i]}</li>);
}
const ulStyle = {
listStyleType: 'none',
paddingLeft: '0px',
};
return <div className="log" ref={(node) => {
this.node = node;
}}><ul style={ulStyle}>{ lines }</ul></div>;
}
}
|
src/components/file/upload.js
|
abbr/ShowPreper
|
import React from 'react'
import ReactDOM from 'react-dom'
module.exports = class Importer extends React.Component {
click = () => {
let domEle = ReactDOM.findDOMNode(this)
domEle.value = null
domEle.click()
}
onChange = e => {
let file = e.target.files[0]
// TODO validate file mime type
if (file != null) {
let reader = new FileReader()
reader.onload = function(e) {
// TODO parse files
this.props.onNewDeck(file.name, JSON.parse(e.target.result))
}.bind(this)
reader.readAsText(file)
}
}
render() {
return (
<input
type="file"
style={{ display: 'none' }}
accept=".spj"
onChange={this.onChange}
/>
)
}
}
|
react-dixie-memory-considerate-loading/src/components/SwitchWithLabel/index.js
|
GoogleChromeLabs/adaptive-loading
|
/*
* Copyright 2019 Google LLC
*
* 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
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Toggle from 'react-toggle'; // TODO: update -> deprecated lifecyle usage detected
import 'react-toggle/style.css';
import './switch-with-label.css';
const SwitchWithLabel = ({ label, ...rest }) => (
<div className='switch-with-label'>
<Toggle {...rest}/>
<label>
{label}
</label>
</div>
);
export default SwitchWithLabel;
|
src/svg-icons/image/wb-sunny.js
|
hwo411/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageWbSunny = (props) => (
<SvgIcon {...props}>
<path d="M6.76 4.84l-1.8-1.79-1.41 1.41 1.79 1.79 1.42-1.41zM4 10.5H1v2h3v-2zm9-9.95h-2V3.5h2V.55zm7.45 3.91l-1.41-1.41-1.79 1.79 1.41 1.41 1.79-1.79zm-3.21 13.7l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4zM20 10.5v2h3v-2h-3zm-8-5c-3.31 0-6 2.69-6 6s2.69 6 6 6 6-2.69 6-6-2.69-6-6-6zm-1 16.95h2V19.5h-2v2.95zm-7.45-3.91l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8z"/>
</SvgIcon>
);
ImageWbSunny = pure(ImageWbSunny);
ImageWbSunny.displayName = 'ImageWbSunny';
ImageWbSunny.muiName = 'SvgIcon';
export default ImageWbSunny;
|
app/features/notifications/Notify/index.js
|
Kaniwani/KW-Frontend
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createPortal } from 'react-dom';
import { CSSTransition, TransitionGroup } from 'react-transition-group';
import { POSITIONS } from '../constants';
import actions from '../actions';
import Notification from '../Notification';
import { Container, Wrapper } from './styles';
export class Notify extends React.PureComponent {
static propTypes = {
notifications: PropTypes.array.isRequired,
remove: PropTypes.func.isRequired,
transitionDurations: PropTypes.shape({
enter: PropTypes.number,
exit: PropTypes.number,
}),
position: PropTypes.string,
node: PropTypes.any,
};
static defaultProps = {
transitionDurations: {
enter: 160,
exit: 240,
},
position: POSITIONS.TOP_RIGHT,
};
componentWillUnmount() {
if (this.defaultNode) {
document.body.removeChild(this.defaultNode);
}
this.defaultNode = null;
}
handleDismiss = (id) => {
this.props.remove(id);
};
renderNotification() {
const { notifications, transitionDurations, position, ...props } = this.props;
return (
<TransitionGroup component={Container} position={position}>
{notifications.map((notification, index) => (
// eslint-disable-next-line react/no-array-index-key
<CSSTransition classNames="slide" key={index} timeout={transitionDurations}>
<Wrapper>
<Notification
key={notification.id}
{...props}
{...notification}
handleDismiss={this.handleDismiss}
/>
</Wrapper>
</CSSTransition>
))}
</TransitionGroup>
);
}
render() {
if (!this.props.node && !this.defaultNode) {
/* eslint-disable no-undef */
this.defaultNode = document.createElement('div');
document.body.appendChild(this.defaultNode);
}
return createPortal(this.renderNotification(), this.props.node || this.defaultNode);
}
}
const mapStateToProps = (state) => ({
notifications: state.notifications,
});
const mapDispatchToProps = {
remove: actions.remove,
};
export default connect(mapStateToProps, mapDispatchToProps)(Notify);
|
app/components/LoadingIndicator/index.js
|
chaintng/react-boilerplate
|
import React from 'react';
import Circle from './Circle';
import Wrapper from './Wrapper';
const LoadingIndicator = () => (
<Wrapper>
<Circle />
<Circle rotate={30} delay={-1.1} />
<Circle rotate={60} delay={-1} />
<Circle rotate={90} delay={-0.9} />
<Circle rotate={120} delay={-0.8} />
<Circle rotate={150} delay={-0.7} />
<Circle rotate={180} delay={-0.6} />
<Circle rotate={210} delay={-0.5} />
<Circle rotate={240} delay={-0.4} />
<Circle rotate={270} delay={-0.3} />
<Circle rotate={300} delay={-0.2} />
<Circle rotate={330} delay={-0.1} />
</Wrapper>
);
export default LoadingIndicator;
|
src/components/Account/OAuthLogin/OAuthLogin.container.js
|
shayc/cboard
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { FormattedMessage, injectIntl, intlShape } from 'react-intl';
import { login } from '../Login/Login.actions';
import messages from './OAuthLogin.messages';
import { getUser } from '../../App/App.selectors';
import './OAuthLogin.css';
class OAuthLoginContainer extends React.Component {
static propTypes = {
intl: intlShape.isRequired,
user: PropTypes.object,
login: PropTypes.func
};
constructor(props) {
super(props);
const {
match: {
params: { type }
},
location: { search: query },
history
} = this.props;
this.type = type;
this.query = query;
this.hasErrors = query.indexOf('error=') >= 0;
if (this.hasErrors) {
setTimeout(() => {
history.replace('/');
}, 3000);
}
}
componentDidMount() {
if (!this.checkUser()) {
this.props.login({ email: this.type, password: this.query }, this.type);
}
}
componentDidUpdate() {
this.checkUser();
}
checkUser() {
const { history, user } = this.props;
if (user.email) {
history.replace('/');
}
return !!user.email;
}
render() {
return (
<div className="OAuthContainer">
{!this.hasErrors && <FormattedMessage {...messages.loading} />}
{this.hasErrors && <FormattedMessage {...messages.errorMessage} />}
</div>
);
}
}
const mapStateToProps = state => ({
user: getUser(state)
});
const mapDispatchToProps = {
login
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(injectIntl(OAuthLoginContainer));
|
src/layouts/BaseLayout/BaseLayout.spec.js
|
diMosellaAtWork/GeoWeb-FrontEnd
|
import React from 'react';
import BaseLayout from './BaseLayout';
import { shallow, mount } from 'enzyme';
import { Container } from 'reactstrap';
import { Provider } from 'react-redux';
const STORE = {
getState: () => ({ notifications: [] }),
subscribe: () => null,
dispatch: () => null
};
describe('(Layout) BaseLayout', () => {
it('Renders a Reactstrap Container', () => {
const _component = shallow(<BaseLayout route={{}} />);
expect(_component.type()).to.eql(Container);
});
it('Allows for triggering the fullscreen function', () => {
const _wrappingComponent = mount(<Provider store={STORE}><BaseLayout routes={[{ title: 'title', path: 'full_screen' }]} /></Provider>);
const evt = new KeyboardEvent('keydown', {
bubbles: true,
cancelable: true,
key: 'F11',
keyCode: 122
});
expect(_wrappingComponent.find(BaseLayout)).to.have.length(1);
_wrappingComponent.find(BaseLayout).instance().elementToFullScreen(evt);
expect('everything').to.be.ok();
});
});
|
src/components/Buttons/Switch.js
|
instacart/Snacks
|
import React from 'react'
import PropTypes from 'prop-types'
import RadioCheckboxBase from '../../base/RadioCheckboxBase'
import colors from '../../styles/colors'
import ZeroSvg from '../../assets/zero.svg'
import OneSvg from '../../assets/one.svg'
const SWITCH_WIDTH = 36
const STYLES = {
background: {
borderRadius: '11px',
position: 'relative',
transition: 'background-color 200ms ease-in-out',
},
toggle: {
default: {
height: '18px',
width: '18px',
backgroundColor: colors.WHITE,
borderRadius: '50%',
display: 'block',
position: 'absolute',
top: '2px',
left: '2px',
transition: 'left 200ms ease-in-out',
},
selected: {
left: '16px',
},
},
zero: {
position: 'absolute',
right: '5px',
top: '7px',
},
one: {
position: 'absolute',
left: '8px',
top: '7px',
},
}
const renderInputButton = (isSelected, style, displayOnOffLabel) => {
return (
<div style={[style, { backgroundColor: style.fill }, STYLES.background]}>
{displayOnOffLabel && isSelected && <OneSvg style={STYLES.one} />}
{displayOnOffLabel && !isSelected && <ZeroSvg style={STYLES.zero} />}
<div style={[STYLES.toggle.default, isSelected && STYLES.toggle.selected]} />
</div>
)
}
const Switch = props => {
return (
<RadioCheckboxBase
btnType="checkbox"
width={SWITCH_WIDTH}
renderInputButton={(isSelected, style) =>
renderInputButton(isSelected, style, props.displayOnOffLabel)
}
{...props}
/>
)
}
Switch.propTypes = {
aria: PropTypes.shape({
label: PropTypes.string,
}),
children: PropTypes.node,
id: PropTypes.oneOfType([PropTypes.string, PropTypes.number]).isRequired,
isDisabled: PropTypes.bool,
isSelected: PropTypes.bool,
name: PropTypes.string,
onChange: PropTypes.func,
style: PropTypes.shape({
button: PropTypes.object,
label: PropTypes.object,
wrapEl: PropTypes.object,
}),
value: PropTypes.string,
wrapEl: PropTypes.string,
displayOnOffLabel: PropTypes.bool,
}
export default Switch
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.