path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
---|---|---|
app/classifier/drawing-tools/freehand-segment-shape.spec.js | zooniverse/Panoptes-Front-End | import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import sinon from 'sinon';
import FreehandSegmentShapeTool from './freehand-segment-shape';
describe('FreehandSegmentShapeTool', function () {
let mark = FreehandSegmentShapeTool.defaultValues();
const x = 200;
const y = 400;
const coords = [
{
x: 300.01,
y: 400.02
},
{
x: 250.03,
y: 450.04
},
{
x: 200.051,
y: 500.06
}
];
const roundedCoords = [
{
x: 300,
y: 400
},
{
x: 250,
y: 450
},
{
x: 200.1,
y: 500.1
}
];
it('should initialize with correct values', function () {
expect(mark.points.length).to.equal(0);
expect(mark._inProgress).to.be.false;
expect(mark._currentlyDrawing).to.be.false;
});
describe('static methods', function () {
before(function () {
mark = FreehandSegmentShapeTool.initStart({ x, y }, mark);
});
it('create an initial mark', function () {
expect(mark.points[0].x).to.equal(x);
expect(mark.points[0].y).to.equal(y);
expect(mark._inProgress).to.be.true;
expect(mark._currentlyDrawing).to.be.true;
});
coords.forEach(function (coord, i) {
it('should round coordinates on move to angle ' + roundedCoords[i].x, function () {
const newMark = FreehandSegmentShapeTool.initMove(coord, mark);
expect(newMark.points[i + 1].x).to.equal(roundedCoords[i].x);
expect(newMark.points[i + 1].y).to.equal(roundedCoords[i].y);
});
});
it('should finish drawing on initial release', function () {
const newMark = FreehandSegmentShapeTool.initRelease({ x, y }, mark);
expect(newMark._currentlyDrawing).to.be.false;
});
it('should designate as completed when forceComplete', function () {
mark = FreehandSegmentShapeTool.forceComplete(mark);
expect(FreehandSegmentShapeTool.isComplete(mark)).to.be.true;
});
});
describe('rendered component', function () {
let wrapper;
const onChange = sinon.stub().callsFake(() => null);
const getEventOffset = sinon.stub().callsFake((e) => e);
const renderedMark = {
points: roundedCoords,
_inProgress: false
};
const scale = {
horizontal: 1,
vertical: 1
};
const containerRect = {
top: 0,
bottom: 500,
left: 0,
right: 500
};
const mockEventInViewer = {
pageX: 0,
pageY: 0,
type: 'mouseenter'
};
const mockEventOutOfViewer = {
pageX: -10,
pageY: -10,
type: 'mouseleave'
};
before(function () {
wrapper = shallow(
<FreehandSegmentShapeTool
color="blue"
containerRect={containerRect}
getEventOffset={getEventOffset}
getScreenCurrentTransformationMatrix={() => null}
mark={renderedMark}
onChange={onChange}
scale={scale}
/>
);
});
it('should correctly render the delete position', function () {
const deleteButtonPos = wrapper.instance().getDeletePosition(renderedMark.points);
expect(deleteButtonPos.x).to.equal(284);
expect(deleteButtonPos.y).to.equal(400);
});
it('should handle finish click correctly', function () {
wrapper.instance().handleFinishClick();
const newMark = onChange.getCall(0).args[0];
expect(onChange.callCount).to.equal(1);
expect(newMark._inProgress).to.be.false;
});
it('should handle finish move correctly when in viewer', function () {
wrapper.instance().handleFinishMove(mockEventInViewer);
expect(wrapper.state().mouseWithinViewer).to.be.true;
});
it('should handle finish hover correctly when in viewer', function () {
wrapper.instance().handleFinishHover(mockEventInViewer);
expect(wrapper.state().firstPointHover).to.be.true;
});
it('should handle finish move correctly when out of viewer', function () {
wrapper.instance().handleFinishMove(mockEventOutOfViewer);
expect(wrapper.state().mouseWithinViewer).to.be.false;
});
it('should handle finish hover correctly when out of viewer', function () {
wrapper.instance().handleFinishHover(mockEventOutOfViewer);
expect(wrapper.state().firstPointHover).to.be.false;
});
});
});
|
tp-3/euge/src/index.js | jpgonzalezquinteros/sovos-reactivo-2017 | /* eslint-disable import/default */
import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import Root from './components/Root';
require('./favicon.ico'); // Tell webpack to load favicon.ico
render(
<AppContainer>
<Root/>
</AppContainer>,
document.getElementById('app')
);
if (module.hot) {
module.hot.accept('./components/Root', () => {
const NewRoot = require('./components/Root').default;
render(
<AppContainer>
<NewRoot />
</AppContainer>,
document.getElementById('app')
);
});
}
|
pootle/static/js/shared/components/AutosizeTextarea.js | evernote/zing | /*
* Copyright (C) Pootle contributors.
* Copyright (C) Zing contributors.
*
* This file is a part of the Zing project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import autosize from 'autosize';
import React from 'react';
const AutosizeTextarea = React.createClass({
componentDidMount() {
autosize(this.refs.textarea);
},
componentDidUpdate() {
autosize.update(this.refs.textarea);
},
componentWillUnmount() {
autosize.destroy(this.refs.textarea);
},
render() {
return <textarea ref="textarea" {...this.props} />;
},
});
export default AutosizeTextarea;
|
plugins/react/frontend/components/controls/base/ArrayControl/ConstraintsForm/index.js | carteb/carte-blanche | import React from 'react';
import controlTypes from '../../../../CustomMetadataForm/controlTypes';
import getControl from '../../../../../utils/getControl';
import renderConstraintForm from './renderConstraintForm';
import Row from '../../../../form/Grid/Row';
import LeftColumn from '../../../../form/Grid/LeftColumn';
import RightColumn from '../../../../form/Grid/RightColumn';
import ComboBox from '../../../../form/ComboBox';
/**
*
* Takes care of rendering of the selection & constraint form for nested arrays
*
* The props should have the following structure:
*
* constraints: {
* controlType: "arrayOf",
* constraints: {
* controlType: "string"
* }
* }
*
* parsedMetadata: {
* name: "arrayOf",
* value: {
* name: "string"
* }
* }
*
*
* @param constraints
* @param parsedMetadata
* @param onUpdate
* @returns {Object}
* @constructor
*/
const ConstraintsForm = ({ constraints, parsedMetadata, onUpdate, nestedLevel }) => {
const onChange = (event) => {
const controlType = event.value;
// check if the control type has constraints
// if the type doesn't have constraints neglect the existing constraints.
const control = getControl({ name: controlType });
const hasConstraints = control.type.ConstraintsForm;
const newCustomMetadata = hasConstraints && constraints && constraints.constraints
? { ...constraints.constraints }
: {};
newCustomMetadata.controlType = controlType;
onUpdate({ ...newCustomMetadata });
};
const renderControl = ({ controlType, constraint }) => (
<Row>
<LeftColumn nestedLevel={nestedLevel}>{controlType}</LeftColumn>
<RightColumn>
<ComboBox
value={controlType}
onChange={onChange}
options={controlTypes.map((type) => ({ value: type }))}
/>
</RightColumn>
{renderConstraintForm(
controlType,
onUpdate,
constraints,
parsedMetadata
)}
{constraint && renderControl(constraint)}
</Row>
);
return (
<Row>
{renderControl(constraints)}
</Row>
);
};
export default ConstraintsForm;
|
app/components/Facebook.js | vietvd88/developer-crawler | // @flow
import React, { Component } from 'react';
import { Link } from 'react-router';
import styles from './Facebook.css';
import SortTable from './SortTable'
import { Button, FormControl, FormGroup, ControlLabel } from 'react-bootstrap';
export default class Home extends Component {
constructor(props) {
super(props);
var queryString = this.props.location.query
this.props.getFacebookDeveloperAsync(queryString.user)
this.props.getFacebookJobAsync(queryString.user)
this.onChange = this.onChange.bind(this);
this.postComment = this.postComment.bind(this);
this.comment = ''
}
postComment(evt) {
this.props.postComment(this.props.developer.user_name, this.comment)
}
onChange(evt) {
console.log(evt.target.value)
this.comment = evt.target.value
}
render() {
const columns = [
{name: 'Company', key: 'company', width: 200},
{name: 'Position', key: 'position', width: 200},
{name: 'Duration', key: 'duration', width: 200},
];
var comments = this.props.commentList.map(function(comment) { return comment.comment })
var commentText = comments.join('\n\n')
return (
<div>
<div className={styles.container}>
<h2>Job Search Crawler --
<Link to={{ pathname: '/' }}>
HomePage
</Link>
</h2>
<hr/>
<div className={styles.userPanel}>
<img src={this.props.developer.avatar} className={styles.avatar}/>
<span className={styles.userName}>{this.props.developer.name}</span>
</div>
<div className={styles.repoTable}>
<SortTable
dataList={this.props.facebookJobList}
columns={columns}
onSortChange={this.props.sortFacebookJob}
width={800}
height={200}
/>
</div>
<div className={styles.email}>
Email: {this.props.developer.email}
</div>
<div className={styles.phone}>
Website: {this.props.developer.website}
</div>
<FormGroup controlId="formControlsTextarea">
<FormControl
componentClass="textarea"
value={commentText}
readOnly
className={styles.comments}/>
</FormGroup>
<FormGroup>
<FormControl type="text" placeholder="New Comment" onChange={this.onChange}/>
</FormGroup>
{' '}
<Button
bsStyle="primary"
bsSize="small"
className={styles.filterButton}
onClick={this.postComment}
>
Post
</Button>
</div>
</div>
);
}
}
|
packages/server/src/core/renderers.js | warebrained/basis | import React from 'react';
import { renderToStaticMarkup } from 'react-dom/server';
// renderReactView
export default (res, view, title, componentType, props) => {
const element = React.createElement(componentType, props, null);
const markup = renderToStaticMarkup(element);
res.render(view, { title, markup });
}; |
clients/packages/admin-client/src/pages/admin/mobilizations/launch/page.js | nossas/bonde-client | import React from 'react';
import { FormattedMessage, injectIntl } from 'react-intl';
import * as paths from '../../../../paths';
import * as MobActions from '../../../../mobrender/redux/action-creators';
import { Loading } from '../../../../components/await';
import MobSelectors from '../../../../mobrender/redux/selectors';
import {
PageCentralizedLayout,
PageCentralizedLayoutTitle,
} from '../../../../components/layout';
import { Tabs, Tab } from '../../../../components/navigation/tabs';
import { Button, FlatForm } from '../../../../ux/components';
import { StepsContainerStack, StepContent } from '../../../../components/steps';
import { FormDomain, FormShare } from '../../../../mobilizations/components';
if (require('exenv').canUseDOM) {
require('./form-domain.scss');
require('./form-share.scss');
}
const FormShareImplementation = injectIntl(
FormShare(
(state) => ({ initialValues: MobSelectors(state).getMobilization() }),
{ submit: MobActions.asyncUpdateMobilization },
(values, props) => {
const errors = {};
const messageRequired = props.intl.formatMessage({
id: 'page--mobilizations-launch.form-share.validation.required',
defaultMessage: 'Obrigatório',
});
if (!values.facebook_share_image) {
errors.facebook_share_image = messageRequired;
}
if (!values.facebook_share_title) {
errors.facebook_share_title = messageRequired;
}
if (!values.facebook_share_description) {
errors.facebook_share_description = messageRequired;
}
if (!values.twitter_share_text) {
errors.twitter_share_text = messageRequired;
}
return errors;
}
)
);
const MobilizationsLaunchPage = ({
history,
hostedZones,
mobilization,
isSaving,
...formProps
}) => {
const stepDomainValidation = () => !!mobilization.custom_domain;
const stepShareValidation = () =>
!!mobilization.facebook_share_image &&
!!mobilization.facebook_share_title &&
!!mobilization.facebook_share_description &&
!!mobilization.twitter_share_text;
const stepFinishValidation = () =>
mobilization.custom_domain &&
mobilization.facebook_share_image &&
mobilization.facebook_share_title &&
mobilization.facebook_share_description &&
mobilization.twitter_share_text;
const savingButtonMessage = (
<FormattedMessage
id="page--mobilizations-launch.button.saving"
defaultMessage="Salvando..."
/>
);
const launchButtonMessage = (
<FormattedMessage
id="page--mobilizations-launch.button.launch"
defaultMessage="Lançar mobilização"
/>
);
const continueButtonMessage = (
<FormattedMessage
id="page--mobilizations-launch.button.next"
defaultMessage="Continuar"
/>
);
return (
<PageCentralizedLayout>
<PageCentralizedLayoutTitle>
<FormattedMessage
id="page--mobilizations-launch.title"
defaultMessage="Lançando sua mobilização"
/>
</PageCentralizedLayoutTitle>
<StepsContainerStack
ComponentPointerContainer={Tabs}
ComponentPointerChildren={Tab}
pointerChildrenProps={({ index, step }) => ({
isActive: index === step,
index,
})}
progressValidations={[
stepDomainValidation,
stepShareValidation,
stepFinishValidation,
]}
>
<StepContent>
<FormDomain
{...formProps}
formComponent={FlatForm}
titleText={
<FormattedMessage
id="page--mobilizations-launch.steps.form-domain.title"
defaultMessage="Configure o endereço da mobilização"
/>
}
buttonText={
isSaving
? savingButtonMessage
: stepShareValidation()
? launchButtonMessage
: continueButtonMessage
}
requiredField
mobilization={mobilization}
hostedZones={hostedZones}
redirectToCreateDNS={() => {
history.push(
paths.communityDomainCreate(
`?next=${paths.mobilizationLaunch(mobilization.id)}`
)
);
}}
/>
</StepContent>
<StepContent>
<FormShareImplementation
{...formProps}
FormComponent={FlatForm}
formClassNames="mobilization-launch--form-share"
titleText={
<FormattedMessage
id="page--mobilizations-launch.steps.form-share.title"
defaultMessage="Configure as informações de compartilhamento"
/>
}
buttonText={isSaving ? savingButtonMessage : launchButtonMessage}
/>
</StepContent>
<StepContent>
<div className="ux--flat-form">
<h1>
<FormattedMessage
id="page--mobilizations-launch.steps.done.title"
defaultMessage="Seu BONDE está pronto!"
/>
</h1>
<p className="h5">
<FormattedMessage
id="page--mobilizations-launch.steps.done.helper-text"
defaultMessage={
'Em uma nova aba, digite o endereço que cadastrou na mobilização ' +
'para se certificar de que ela já está no ar. Se ainda não estiver, ' +
'cheque se cadastrou os domínios corretamente. Está tudo certo? Então ' +
'é só esperar ele propagar pela internet!'
}
/>
</p>
<Button
href={`http://${mobilization.custom_domain}`}
target="_blank"
>
<FormattedMessage
id="page--mobilizations-launch.steps.done.button.open"
defaultMessage="Visualizar mobilização"
/>
</Button>
</div>
</StepContent>
</StepsContainerStack>
{isSaving && <Loading />}
</PageCentralizedLayout>
);
};
export default MobilizationsLaunchPage;
|
src/parser/deathknight/blood/modules/features/BoneShield.js | ronaldpereira/WoWAnalyzer | import React from 'react';
import Analyzer from 'parser/core/Analyzer';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatDuration, formatPercentage } from 'common/format';
import { STATISTIC_ORDER } from 'interface/others/StatisticBox';
import StatisticBox from 'interface/others/StatisticBox';
import StatTracker from 'parser/shared/modules/StatTracker';
import BoneShieldTimesByStacks from './/BoneShieldTimesByStacks';
class BoneShield extends Analyzer {
static dependencies = {
statTracker: StatTracker,
boneShieldTimesByStacks: BoneShieldTimesByStacks,
};
get boneShieldTimesByStack() {
return this.boneShieldTimesByStacks.boneShieldTimesByStacks;
}
get uptime() {
return this.selectedCombatant.getBuffUptime(SPELLS.BONE_SHIELD.id) / this.owner.fightDuration;
}
get uptimeSuggestionThresholds() {
return {
actual: this.uptime,
isLessThan: {
minor: 0.95,
average: 0.9,
major: .8,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.uptimeSuggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest('Your Bone Shield uptime can be improved. Try to keep it up at all times.')
.icon(SPELLS.BONE_SHIELD.icon)
.actual(`${formatPercentage(actual)}% Bone Shield uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BONE_SHIELD.id} />}
value={`${formatPercentage(this.uptime)} %`}
label="Bone Shield uptime"
>
<table className="table table-condensed">
<thead>
<tr>
<th>Stacks</th>
<th>Time (s)</th>
<th>Time (%)</th>
</tr>
</thead>
<tbody>
{Object.values(this.boneShieldTimesByStack).map((e, i) => (
<tr key={i}>
<th>{i}</th>
<td>{formatDuration(e.reduce((a, b) => a + b, 0) / 1000)}</td>
<td>{formatPercentage(e.reduce((a, b) => a + b, 0) / this.owner.fightDuration)}%</td>
</tr>
))}
</tbody>
</table>
</StatisticBox>
);
}
statisticOrder = STATISTIC_ORDER.CORE(5);
}
export default BoneShield;
|
app/javascript/mastodon/components/animated_number.js | primenumber/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedNumber } from 'react-intl';
import TransitionMotion from 'react-motion/lib/TransitionMotion';
import spring from 'react-motion/lib/spring';
import { reduceMotion } from 'mastodon/initial_state';
const obfuscatedCount = count => {
if (count < 0) {
return 0;
} else if (count <= 1) {
return count;
} else {
return '1+';
}
};
export default class AnimatedNumber extends React.PureComponent {
static propTypes = {
value: PropTypes.number.isRequired,
obfuscate: PropTypes.bool,
};
state = {
direction: 1,
};
componentWillReceiveProps (nextProps) {
if (nextProps.value > this.props.value) {
this.setState({ direction: 1 });
} else if (nextProps.value < this.props.value) {
this.setState({ direction: -1 });
}
}
willEnter = () => {
const { direction } = this.state;
return { y: -1 * direction };
}
willLeave = () => {
const { direction } = this.state;
return { y: spring(1 * direction, { damping: 35, stiffness: 400 }) };
}
render () {
const { value, obfuscate } = this.props;
const { direction } = this.state;
if (reduceMotion) {
return obfuscate ? obfuscatedCount(value) : <FormattedNumber value={value} />;
}
const styles = [{
key: `${value}`,
data: value,
style: { y: spring(0, { damping: 35, stiffness: 400 }) },
}];
return (
<TransitionMotion styles={styles} willEnter={this.willEnter} willLeave={this.willLeave}>
{items => (
<span className='animated-number'>
{items.map(({ key, data, style }) => (
<span key={key} style={{ position: (direction * style.y) > 0 ? 'absolute' : 'static', transform: `translateY(${style.y * 100}%)` }}>{obfuscate ? obfuscatedCount(data) : <FormattedNumber value={data} />}</span>
))}
</span>
)}
</TransitionMotion>
);
}
}
|
src/index.js | jcxk/ethercity | import React from 'react';
import { render } from 'react-dom';
import { browserHistory } from 'react-router';
import { AppContainer } from 'react-hot-loader';
import Root from './container/Root';
import configureStore from './store/configureStore';
import { syncHistoryWithStore } from 'react-router-redux';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
const store = configureStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
<AppContainer>
<Root store={store} history={history} />
</AppContainer>,
document.getElementById('app')
);
if (module.hot) {
module.hot.accept('./container/Root', () => {
const NewRoot = require('./container/Root').default;
render(
<AppContainer>
<NewRoot store={store} history={history} />
</AppContainer>,
document.getElementById('app')
);
});
} |
ui/src/pages/404.js | danielbh/danielhollcraft.com-gatsbyjs | import React from 'react'
export default ({ data }) => {
return (
<section id="one">
<div className="container">
<header className="major" style={{paddingBottom: '45vh'}}>
<h2>404 error!</h2>
</header>
</div>
</section>
)
}
|
src/components/project/ProjectView.js | omgunis/portfolio | import React from 'react';
{/* View for single project, /project/:id, imported into ManageProjectPage */}
const ProjectView = ({ project }) => {
return (
<form>
<h1>{ project.title }</h1>
</form>
);
};
ProjectView.propTypes = {
project: React.PropTypes.object.isRequired
};
export default ProjectView;
|
modules/Route.js | RickyDan/react-router | import React from 'react';
import invariant from 'invariant';
import { createRouteFromReactElement } from './RouteUtils';
import { component, components } from './PropTypes';
import warning from 'warning';
var { string, bool, func } = React.PropTypes;
/**
* A <Route> is used to declare which components are rendered to the page when
* the URL matches a given pattern.
*
* Routes are arranged in a nested tree structure. When a new URL is requested,
* the tree is searched depth-first to find a route whose path matches the URL.
* When one is found, all routes in the tree that lead to it are considered
* "active" and their components are rendered into the DOM, nested in the same
* order as they are in the tree.
*/
export var Route = React.createClass({
statics: {
createRouteFromReactElement(element) {
var route = createRouteFromReactElement(element);
if (route.handler) {
warning(false, '<Route handler> is deprecated, use <Route component> instead');
route.component = route.handler;
delete route.handler;
}
return route;
}
},
propTypes: {
path: string,
ignoreScrollBehavior: bool,
handler: component,
component,
components,
getComponents: func
},
render() {
invariant(
false,
'<Route> elements are for router configuration only and should not be rendered'
);
}
});
export default Route;
|
client/modules/App/__tests__/Components/Footer.spec.js | trantuthien/React-Test | import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import { Footer } from '../../components/Footer/Footer';
test('renders the footer properly', t => {
const wrapper = shallow(
<Footer />
);
t.is(wrapper.find('p').length, 2);
t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.');
});
|
src/common/components/Routes.js | GarciaEdgar/firstReactApplication | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './App';
import LoginPage from '../../pages/login/page';
import HomePage from '../../pages/home/page';
export default (
<Route path="/" component={App}>
<IndexRoute component={LoginPage} />
<Route path="home" component={HomePage} />
</Route>
);
|
app/javascript/src/pages/settings/VerificationView.js | michelson/chaskiq | import React from 'react'
import Prism from 'prismjs'
import { connect } from 'react-redux'
import FilterMenu from '../../components/FilterMenu'
import Button from '../../components/Button'
import Input from '../../components/forms/Input'
function VerificationView({app}){
const [currentLang, setCurrentLang] = React.useState("ruby")
const [show, setShow] = React.useState(false)
function setupScript () {
const hostname = window.location.hostname
const port = window.location.port ? ':' + window.location.port : ''
const secure = window.location.protocol === 'https:'
const httpProtocol = window.location.protocol
const wsProtocol = secure ? 'wss' : 'ws'
const hostnamePort = `${hostname}${port}`
const code = `
<script>
(function(d,t) {
var g=d.createElement(t),s=d.getElementsByTagName(t)[0];
g.src="${httpProtocol}//${hostnamePort}/embed.js"
s.parentNode.insertBefore(g,s);
g.onload=function(){
new window.ChaskiqMessengerEncrypted({
domain: '${httpProtocol}//${hostnamePort}',
ws: '${wsProtocol}://${hostnamePort}/cable',
app_id: "${app ? app.key : ''}",
data: {
email: "[email protected]",
identifier_key: "INSERT_HMAC_VALUE_HERE",
properties: { }
},
lang: "USER_LANG_OR_DEFAULTS_TO_BROWSER_LANG"
})
}
})(document,"script");
</script>
`
return Prism.highlight(code, Prism.languages.javascript, 'javascript')
}
function keyGeneration () {
const code = optionsForFilter().find(
(o)=> o.id === currentLang
).code
return Prism.highlight(code, Prism.languages.ruby, 'ruby')
}
function optionsForFilter(){
return [
{
title: 'Ruby',
description: 'ruby',
id: 'ruby',
state: 'archived',
code: `
OpenSSL::HMAC.hexdigest(
'sha256', # hash function
'${app.encryptionKey}', # secret key (keep safe!)
current_user.email
)`
},
{
title: 'NodeJs',
description: 'nodejs',
id: 'nodejs',
code: `
const crypto = require('crypto');
const hmac = crypto.createHmac('sha256', '${app.encryptionKey}');
hmac.update('Message');
console.log(hmac.digest('hex'));`
},
{
title: 'PHP',
description: 'PHP',
id: 'php',
code: `
hash_hmac(
'sha256', // hash function
$user->email, // user's id
'${app.encryptionKey}' // secret key (keep safe!)
);`
},
{
title: 'Python 3',
description: 'python',
id: 'python',
code: `
import hmac
import hashlib
hmac.new(
b'${app.encryptionKey}', # secret key (keep safe!)
bytes(request.user.id, encoding='utf-8'), # user's id
digestmod=hashlib.sha256 # hash function
).hexdigest()
`
},
{
title: 'Golang',
description: 'golang',
id: 'golang',
code: `
package main
import (
"crypto/hmac"
"crypto/sha256"
"encoding/hex"
"fmt"
)
func ComputeHmac256(message string, secret string) string {
key := []byte(secret)
h := hmac.New(sha256.New, key)
h.Write([]byte(message))
return hex.EncodeToString(h.Sum(nil))
}
func main() {
fmt.Println(ComputeHmac256("Message", "secret")) // ${app.encryptionKey}
}
`
}
]
}
function toggleButton(clickHandler) {
return (
<div>
<Button
variant={'outlined'}
onClick={clickHandler}>
{currentLang}
</Button>
</div>
)
}
function changeLang(item){
setCurrentLang(item.id)
}
return (
<div className="space-y-6 mx-10-- py-6 text-sm">
<h2 className="text-lg font-bold-">{I18n.t("identified_users.title")}</h2>
<div className="flex md:w-1/4 items-center">
<Input
label="Identity verification secret"
disabled={true}
value={app.encryptionKey}
type={show ? 'text' : 'password'}
helperText={
"Don't share this code"
}
/>
<Button
className="ml-2"
variant="success"
style={{
marginTop: '-12px'
}}
onClick={()=>setShow(!show)}>
show
</Button>
</div>
<p className="">
{I18n.t("identified_users.hint1")}
To configure identity verification, you will need to generate an HMAC on your server for each logged in user and submit it to Chaskiq.
</p>
<p className="font-bold">{I18n.t("identified_users.lang")}</p>
<div className="flex justify-between items-center">
<p className="font-bold text-lg">{currentLang}:</p>
<div className="flex justify-end">
<FilterMenu
options={optionsForFilter()}
value={null}
filterHandler={changeLang}
triggerButton={toggleButton}
position={'right'}
/>
</div>
</div>
<CodeBox content={keyGeneration()}/>
<p
dangerouslySetInnerHTML={{__html: I18n.t("identified_users.hint2")
}}/>
<CodeBox content={setupScript()}/>
</div>
)
}
function CodeBox ({content}){
return (
<pre className="p-3 bg-black rounded-md border-black border-2 dark:border-gray-100 text-white text-sm overflow-auto shadow-sm">
<div dangerouslySetInnerHTML={{__html: content }}/>
</pre>
)
}
function mapStateToProps (state) {
const { app } = state
return {
app
}
}
export default connect(mapStateToProps)(VerificationView)
|
frontend/tests/components/user-menu/user-menu.js | 1905410/Misago | import assert from 'assert';
import React from 'react'; // jshint ignore:line
import { UserMenu, UserNav, CompactUserNav } from 'misago/components/user-menu/user-nav'; // jshint ignore:line
import misago from 'misago/index';
import dropdown from 'misago/services/mobile-navbar-dropdown';
import store from 'misago/services/store';
import * as testUtils from 'misago/utils/test-utils';
describe("User Menu", function() {
beforeEach(function() {
testUtils.contextClear(misago);
testUtils.contextAuthenticated(misago);
testUtils.initEmptyStore(store);
testUtils.initDropdown(dropdown);
/* jshint ignore:start */
testUtils.render(<UserMenu user={misago._context.user} />);
/* jshint ignore:end */
});
afterEach(function() {
testUtils.unmountComponents();
});
it('renders', function() {
let element = $('#test-mount .dropdown-menu');
assert.ok(element.length, "component renders");
});
});
describe("User Nav", function() {
beforeEach(function() {
testUtils.contextClear(misago);
testUtils.contextAuthenticated(misago);
testUtils.initEmptyStore(store);
testUtils.initDropdown(dropdown);
/* jshint ignore:start */
testUtils.render(<UserNav user={misago._context.user} />);
/* jshint ignore:end */
});
afterEach(function() {
testUtils.unmountComponents();
});
it('renders', function() {
let element = $('#test-mount .user-dropdown');
assert.ok(element.length, "component renders");
});
});
describe("Compact User Nav", function() {
beforeEach(function() {
testUtils.contextClear(misago);
testUtils.contextAuthenticated(misago);
store.constructor();
store.addReducer('auth', function(state={}, action=null){
if (action) {
return state;
}
}, {
'isAuthenticated': misago.get('isAuthenticated'),
'isAnonymous': !misago.get('isAuthenticated'),
'user': misago.get('user')
});
store.init();
testUtils.initDropdown(dropdown);
/* jshint ignore:start */
testUtils.render(<CompactUserNav user={misago._context.user} />);
/* jshint ignore:end */
});
afterEach(function() {
testUtils.unmountComponents();
});
it('renders', function() {
let element = $('#test-mount img.user-avatar');
assert.ok(element.length, "component renders");
});
it('opens dropdown on click', function() {
testUtils.simulateClick('#test-mount button');
let element = $('#dropdown-mount>.user-dropdown');
assert.ok(element.length, "component opened dropdown");
});
});
|
auth/src/components/LoginForm.js | carlosnavarro25/calculadora | import React, { Component } from 'react';
import { Text } from 'react-native';
import firebase from 'firebase';
import { Button, Card, CardSection, Input, Spinner } from './common';
class LoginForm extends Component {
state = { email: '', password: '', error: '', loading: false };
onButtonPress(){
const { email, password } = this.state;
this.setState({ error: '', loading: true });
firebase.auth().signInWithEmailAndPassword(email, password)
.then(this.onLogInSuccess.bind(this))
.catch(() => {
firebase.auth().createUserWithEmailAndPassword(email, password)
.then(this.onLogInSuccess.bind(this))
.catch(this.onLogInFail.bind(this));
});
}
onLogInFail(){
this.setState({
error:'Authentication Failed',
loading: false
});
}
onLogInSuccess(){
this.setState({
email: '',
password: '',
loading: false,
error: ''
});
}
renderButton(){
if (this.state.loading){
return <Spinner size="small" />;
}
return (
<Button onPress={this.onButtonPress.bind(this)}>
log in
</Button>
);
}
render(){
return(
<Card>
<CardSection >
<Input
placeholder="[email protected]"
label="Email"
value={this.state.email}
onChangeText={email => this.setState({ email })}
/>
</CardSection>
<CardSection>
<Input
secureTextEntry
placeholder="password"
label="Pasword"
value={this.state.password}
onChangeText={password => this.setState({password})}
/>
</CardSection>
<Text style={styles.errorTextStyle}>
{this.state.error}
</Text>
<CardSection>
{this.renderButton()}
</CardSection>
</Card>
);
}
}
const styles ={
errorTextStyle: {
fontSize: 20,
alignSelf: 'center',
color: 'red'
}
}
export default LoginForm;
|
src/Dropdown/__tests__/Dropdown_test.js | react-fabric/react-fabric | import React from 'react'
import { render, mount } from 'enzyme'
import test from 'tape'
import Dropdown from '..'
import events from '../../util/events.js'
const defaultOptions = [
{ label: 'Foo', value: 'foo' },
{ label: 'Bar', value: 'bar' }
]
test('Dropdown', t => {
t.ok(Dropdown, 'export')
t.equal(Dropdown.displayName, 'FabricComponent(Dropdown)')
t.end()
})
test('Dropdown#render - simple', t => {
const container = render(
<Dropdown options={defaultOptions} />
).contents()
t.assert(container.is('div.ms-Dropdown', 'container'))
t.assert(container.is('[data-fabric="Dropdown"]'), 'data-fabric')
t.equal(container.find('.ms-Dropdown-items > .ms-Dropdown-item').length, defaultOptions.length)
t.end()
})
test('Dropdown lifecycle - unmount', t => {
t.plan(1)
const removeEventsFromDocument = events.removeEventsFromDocument
events.removeEventsFromDocument = ({ click }) => {
t.ok(click)
}
const wrapper = mount(
<Dropdown active options={defaultOptions} />
)
wrapper.unmount()
events.removeEventsFromDocument = removeEventsFromDocument
})
test('Dropdown lifecycle - update', t => {
t.plan(2)
const addEventsToDocument = events.addEventsToDocument
const removeEventsFromDocument = events.removeEventsFromDocument
events.addEventsToDocument = ({ click }) => {
t.ok(click, 'add click handler')
}
events.removeEventsFromDocument = ({ click }) => {
t.ok(click)
}
const wrapper = mount(
<Dropdown options={defaultOptions} />
)
wrapper.setProps({ active: true })
wrapper.setProps({ active: false })
events.addEventsToDocument = addEventsToDocument
events.removeEventsFromDocument = removeEventsFromDocument
})
test('Dropdown - blur', t => {
t.plan(1)
const handleBlur = e => t.ok(e, 'blur called')
const wrapper = mount(
<Dropdown onBlur={handleBlur}
options={defaultOptions} />
)
wrapper.setProps({ active: true })
const event = document.createEvent('HTMLEvents')
event.initEvent('click', true, false)
document.body.dispatchEvent(event)
})
test('Dropdown - focus', t => {
t.plan(1)
const handleFocus = e => t.ok(e, 'focus called')
const wrapper = mount(
<Dropdown onFocus={handleFocus}
options={defaultOptions} />
)
wrapper.find('.ms-Dropdown-title').simulate('mouseDown')
})
test('Dropdown - select', t => {
t.plan(2)
const handleBlur = e => t.equal(e.target.value, 'foo', 'blur called')
const handleChange = e => t.ok(e.target.value, 'foo', 'change called')
const wrapper = mount(
<Dropdown onBlur={handleBlur} onChange={handleChange} value={null}
options={defaultOptions} />
)
wrapper.setProps({ active: true })
wrapper.find('.ms-Dropdown-item > div').first().simulate('mouseDown')
t.end()
})
|
src/components/GoogleMapContainer/RichMarker.js | joelvoss/react-gmaps | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import ReactDOMServer from 'react-dom/server';
import createElementFromString from 'utilities/createElementFromString';
import CustomMarker from 'components/CustomMarker';
/**
* This component represents an overlay view.
*/
class RichMarker extends Component {
// PropTypes
static propTypes = {
google: PropTypes.object.isRequired,
map: PropTypes.object.isRequired,
data: PropTypes.object.isRequired,
handleClick: PropTypes.func
};
/**
* On mount, initialize the factory OverlayView instance provided by google
* and set the three default methods "onAdd", "draw" and "onRemove".
*/
componentDidMount() {
const { google, map } = this.props;
this.richMarker = new google.maps.OverlayView();
this.richMarker.onAdd = this.onAdd;
this.richMarker.draw = this.draw;
this.richMarker.onRemove = this.onRemove;
this.richMarker.setMap(map);
}
/**
* When the component unmounts, set the map of the overlayview to null.
* This calls the "onRemove" method of this class.
*/
componentWillUnmount() {
this.richMarker.setMap(null);
}
/**
* Google maps calls this method as soon as the overlayview can be drawn onto
* the overlay map pane.
*
* This method gets called only once!
*/
onAdd = () => {
const { data, handleClick } = this.props;
const html = ReactDOMServer.renderToStaticMarkup(
<CustomMarker delay={Math.floor(Math.random() * 10) + 1} />
);
this.markerItem = createElementFromString(html);
// Add a standard eventlistener for a click event of the static markup
// react component, since a marker is not a seperate react app.
this.markerItem.addEventListener('click', (e) => {
// prevent event bubbling and propagation
e.stopPropagation();
e.preventDefault();
// execute the custom click event handler which was passed down to the overlay component.
handleClick(data.id)
});
const panes = this.richMarker.getPanes();
panes.overlayMouseTarget.appendChild(this.markerItem);
};
/**
* This method gets called each time the current maps viewport or zoom-level changes.
* In here we convert the lat/lng values to pixel values and position the overlay.
*/
draw = () => {
const { google, data } = this.props;
const latlng = new google.maps.LatLng(data.geometry.location.lat, data.geometry.location.lng);
const point = this.richMarker.getProjection().fromLatLngToDivPixel(latlng);
if (point) {
this.markerItem.style.left = point.x + 'px';
this.markerItem.style.top = point.y + 'px';
}
};
/**
* This method gets called as soon as we set the map property of
* the overlayview to null. We remove all event listener and delete the
* dom representation.
*/
onRemove = () => {
if (this.markerItem) {
this.markerItem.parentNode.removeChild(this.markerItem);
this.markerItem = null;
}
};
render() {
return null;
}
}
export default RichMarker;
|
src/app.js | fjoder/indecision-app | import React from 'react';
import ReactDOM from 'react-dom';
import IndecisionApp from './components/IndecisionApp';
import 'normalize.css/normalize.css';
import './styles/styles.scss';
ReactDOM.render(<IndecisionApp />, document.getElementById('app'));
|
src/svg-icons/maps/train.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsTrain = (props) => (
<SvgIcon {...props}>
<path d="M12 2c-4 0-8 .5-8 4v9.5C4 17.43 5.57 19 7.5 19L6 20.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 19c1.93 0 3.5-1.57 3.5-3.5V6c0-3.5-3.58-4-8-4zM7.5 17c-.83 0-1.5-.67-1.5-1.5S6.67 14 7.5 14s1.5.67 1.5 1.5S8.33 17 7.5 17zm3.5-7H6V6h5v4zm2 0V6h5v4h-5zm3.5 7c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5z"/>
</SvgIcon>
);
MapsTrain = pure(MapsTrain);
MapsTrain.displayName = 'MapsTrain';
MapsTrain.muiName = 'SvgIcon';
export default MapsTrain;
|
src/assets/js/react/components/FontManager/AddFont.js | GravityPDF/gravity-forms-pdf-extended | /* Dependencies */
import React from 'react'
import PropTypes from 'prop-types'
import { sprintf } from 'sprintf-js'
/* Components */
import FontVariant from './FontVariant'
import AddUpdateFontFooter from './AddUpdateFontFooter'
/**
* @package Gravity PDF
* @copyright Copyright (c) 2021, Blue Liquid Designs
* @license http://opensource.org/licenses/gpl-2.0.php GNU Public License
* @since 6.0
*/
/**
* Display add font panel UI
*
* @param label
* @param onHandleInputChange
* @param onHandleUpload
* @param onHandleDeleteFontStyle
* @param onHandleSubmit
* @param fontStyles
* @param validateLabel
* @param validateRegular
* @param msg
* @param loading
* @param tabIndexFontName
* @param tabIndexFontFiles
* @param tabIndexFooterButtons
*
* @since 6.0
*/
export const AddFont = (
{
label,
onHandleInputChange,
onHandleUpload,
onHandleDeleteFontStyle,
onHandleSubmit,
fontStyles,
validateLabel,
validateRegular,
msg,
loading,
tabIndexFontName,
tabIndexFontFiles,
tabIndexFooterButtons
}
) => {
const fontNameLabel = sprintf(GFPDF.fontManagerFontNameLabel, "<span class='required'>", '</span>')
return (
<div data-test='component-AddFont' className='add-font'>
<form onSubmit={onHandleSubmit}>
<h2>{GFPDF.fontManagerAddTitle}</h2>
<p>{GFPDF.fontManagerAddDesc}</p>
<label htmlFor='gfpdf-font-name-input' dangerouslySetInnerHTML={{ __html: fontNameLabel }} />
<p id='gfpdf-font-name-desc-add'>{GFPDF.fontManagerFontNameDesc}</p>
<input
type='text'
id='gfpdf-add-font-name-input'
className={!validateLabel ? 'input-label-validation-error' : ''}
aria-describedby='gfpdf-font-name-desc-add'
name='label'
value={label}
maxLength='60'
onChange={e => onHandleInputChange(e, 'addFont')}
tabIndex={tabIndexFontName}
/>
<div aria-live='polite'>
{!validateLabel && (
<span className='required' role='alert'>
<em>{GFPDF.fontManagerFontNameValidationError}</em>
</span>
)}
</div>
<label id='gfpdf-font-files-label-add' aria-labelledby='gfpdf-font-files-description-add'>{GFPDF.fontManagerFontFilesLabel}</label>
<p id='gfpdf-font-files-description-add'>{GFPDF.fontManagerFontFilesDesc}</p>
<FontVariant
state='addFont'
fontStyles={fontStyles}
validateRegular={validateRegular}
onHandleUpload={onHandleUpload}
onHandleDeleteFontStyle={onHandleDeleteFontStyle}
msg={msg}
tabIndex={tabIndexFontFiles}
/>
<AddUpdateFontFooter
state='addFont'
msg={msg}
loading={loading}
tabIndex={tabIndexFooterButtons}
/>
</form>
</div>
)
}
/**
* PropTypes
*
* @since 6.0
*/
AddFont.propTypes = {
label: PropTypes.string.isRequired,
onHandleInputChange: PropTypes.func.isRequired,
onHandleUpload: PropTypes.func.isRequired,
onHandleDeleteFontStyle: PropTypes.func.isRequired,
onHandleSubmit: PropTypes.func.isRequired,
validateLabel: PropTypes.bool.isRequired,
validateRegular: PropTypes.bool.isRequired,
fontStyles: PropTypes.object.isRequired,
msg: PropTypes.object.isRequired,
loading: PropTypes.bool.isRequired,
tabIndexFontName: PropTypes.string.isRequired,
tabIndexFontFiles: PropTypes.string.isRequired,
tabIndexFooterButtons: PropTypes.string.isRequired
}
export default AddFont
|
src/components/Account.spec.js | febobo/react-redux-start | import React from 'react'
import Account from 'components/Account/Account'
describe('(Component) Account', () => {
it('should exist', () => {
})
})
|
src/svg-icons/action/note-add.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionNoteAdd = (props) => (
<SvgIcon {...props}>
<path d="M14 2H6c-1.1 0-1.99.9-1.99 2L4 20c0 1.1.89 2 1.99 2H18c1.1 0 2-.9 2-2V8l-6-6zm2 14h-3v3h-2v-3H8v-2h3v-3h2v3h3v2zm-3-7V3.5L18.5 9H13z"/>
</SvgIcon>
);
ActionNoteAdd = pure(ActionNoteAdd);
ActionNoteAdd.displayName = 'ActionNoteAdd';
ActionNoteAdd.muiName = 'SvgIcon';
export default ActionNoteAdd;
|
index.ios.js | denistakeda/LifeBalance | import React from 'react';
import { AppRegistry } from 'react-native';
import App from './src/mobile/App';
const LifeBalance = () => {
return (
<App />
);
};
AppRegistry.registerComponent('LifeBalance', () => LifeBalance);
export default LifeBalance;
|
lib/ui/core.js | Markcial/electro-corder | import React from 'react';
import range from '../misc/utils';
export class Button extends React.Component {
constructor(props) {
super(props);
this.state = {
label: props.label,
click: props.click
};
}
click (evt) {
this.state.click(evt);
}
render() {
return (
<button onClick={(e) => this.click(e)}>{this.state.label}</button>
);
}
}
Button.propTypes = { label: React.PropTypes.string, click: React.PropTypes.function };
Button.defaultProps = { label: 'Button', click: () => {} };
export class Slider extends React.Component {
constructor(props) {
super(props);
this.state = {
defaultValue:props.defaultValue,
orientation:props.orientation,
min:props.min,
max:props.max,
onSlide:props.onSlide
}
}
componentDidMount () {
React.findDOMNode(this).style['-webkit-appearance'] = `slider-${this.props.orientation}`;
}
onSlide (evt) {
this.props.onSlide(evt);
}
render () {
return (
<input type="range"
onChange={(e) => this.onSlide(e)}
defaultValue={this.props.defaultValue}
min={this.props.min}
max={this.props.max}
orientation={this.props.orientation} />
);
}
}
Slider.PropTypes = {
defaultValue: React.PropTypes.int,
orientation: React.PropTypes.string,
min: React.PropTypes.integer,
max: React.PropTypes.integer,
onSlide: React.PropTypes.func
}
Slider.defaultProps = {
defaultValue: 0,
orientation: "horizontal",
min: 0,
max: 100,
onSlide: (e) => {}
}
export class Timer extends React.Component {
constructor(props) {
super(props);
this.state = {seconds: props.seconds};
}
onTimerTick (seconds) {}
onTimerEnd () {}
componentDidMount () {}
stopTimer() {
clearInterval(this.intervalID);
}
resetTimer() {
this.stopTimer();
this.setState({seconds:this.props.seconds});
this.startTimer();
}
startTimer () {
this.stopTimer();
this.intervalID = setInterval(() => {
if (this.state.seconds > 0) {
this.onTimerTick(this.state.seconds);
this.tick();
} else {
this.stopTimer();
this.onTimerEnd();
}
}, 1000);
}
tick() {
this.setState({ seconds: this.state.seconds - 1 });
}
render() {
return (
<div>
Seconds left: {this.state.seconds}
</div>
);
}
}
Timer.propTypes = { seconds: React.PropTypes.number };
Timer.defaultProps = { seconds: 10 };
export class Preview extends React.Component {
startRecording () {
navigator.webkitGetUserMedia({
audio: false,
video: {
mandatory: {
chromeMediaSource: 'screen',
maxWidth: screen.availWidth,
maxHeight: screen.availHeight,
maxFrameRate: 25
},
optional: []
}
}, (stream) => this.onStartRecording(stream), (error) => this.onStreamError(error));
}
onStartRecording (stream) {
this.video = React.findDOMNode(this.refs.video);
this.video.style.display = 'none';
this.video.muted = true;
this.video.autoplay = true;
this.video.src = URL.createObjectURL(stream);
this.canvas = React.findDOMNode(this.refs.preview);
this.context = this.canvas.getContext("2d");
this.enrichenCanvasContext(this.context);
requestAnimationFrame(() => {this.drawPreview()})
}
drawPreview() {
requestAnimationFrame(() => {this.drawPreview()});
this.context.drawImage(this.video, 0, 0);
}
onStreamError (error) {
console.log(error);
}
componentDidMount () {
this.startRecording();
}
onVideoClick (evt) {
console.log(evt);
}
onWheel (evt) {
var lastX=this.canvas.width/2, lastY=this.canvas.height/2;
var pt = this.context.transformedPoint(lastX,lastY);
console.log(evt.deltaY);
if (evt.deltaY > 0) {
var scale = 0.9;
} else {
var scale = 1.1;
}
this.context.translate(pt.x,pt.y);
this.context.scale(scale, scale);
this.context.translate(-pt.x,-pt.y);
}
enrichenCanvasContext(ctx) {
var svg = document.createElementNS("http://www.w3.org/2000/svg",'svg');
var xform = svg.createSVGMatrix();
ctx.getTransform = function(){ return xform; };
var savedTransforms = [];
var save = ctx.save;
ctx.save = function(){
savedTransforms.push(xform.translate(0,0));
return save.call(ctx);
};
var restore = ctx.restore;
ctx.restore = function(){
xform = savedTransforms.pop();
return restore.call(ctx);
};
var scale = ctx.scale;
ctx.scale = function(sx,sy){
xform = xform.scaleNonUniform(sx,sy);
return scale.call(ctx,sx,sy);
};
var rotate = ctx.rotate;
ctx.rotate = function(radians){
xform = xform.rotate(radians*180/Math.PI);
return rotate.call(ctx,radians);
};
var translate = ctx.translate;
ctx.translate = function(dx,dy){
xform = xform.translate(dx,dy);
return translate.call(ctx,dx,dy);
};
var transform = ctx.transform;
ctx.transform = function(a,b,c,d,e,f){
var m2 = svg.createSVGMatrix();
m2.a=a; m2.b=b; m2.c=c; m2.d=d; m2.e=e; m2.f=f;
xform = xform.multiply(m2);
return transform.call(ctx,a,b,c,d,e,f);
};
var setTransform = ctx.setTransform;
ctx.setTransform = function(a,b,c,d,e,f){
xform.a = a;
xform.b = b;
xform.c = c;
xform.d = d;
xform.e = e;
xform.f = f;
return setTransform.call(ctx,a,b,c,d,e,f);
};
var pt = svg.createSVGPoint();
ctx.transformedPoint = function(x,y){
pt.x=x; pt.y=y;
return pt.matrixTransform(xform.inverse());
}
}
render () {
return (
<div>
<video ref="video" />
<canvas ref="preview" width="420" height="240" onWheel={(evt) => this.onWheel(evt)} onClick={(evt) => this.onVideoClick(evt)} />
</div>
)
}
}
|
App/__tests__/index.android.js | Tyler-Losinski/Rater-Mc-Ratey-Face | 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 />
);
});
|
app/javascript/mastodon/components/status_content.js | alarky/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import escapeTextContentForBrowser from 'escape-html';
import PropTypes from 'prop-types';
import emojify from '../emoji';
import { isRtl } from '../rtl';
import { FormattedMessage } from 'react-intl';
import Permalink from './permalink';
export default class StatusContent extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
expanded: PropTypes.bool,
onExpandedToggle: PropTypes.func,
onHeightUpdate: PropTypes.func,
onClick: PropTypes.func,
};
state = {
hidden: true,
};
componentDidMount () {
const node = this.node;
const links = node.querySelectorAll('a');
for (var i = 0; i < links.length; ++i) {
let link = links[i];
let mention = this.props.status.get('mentions').find(item => link.href === item.get('url'));
if (mention) {
link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
link.setAttribute('title', mention.get('acct'));
} else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
} else {
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener');
link.setAttribute('title', link.href);
}
}
}
componentDidUpdate () {
if (this.props.onHeightUpdate) {
this.props.onHeightUpdate();
}
}
onMentionClick = (mention, e) => {
if (e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/accounts/${mention.get('id')}`);
}
}
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '').toLowerCase();
if (e.button === 0) {
e.preventDefault();
this.context.router.history.push(`/timelines/tag/${hashtag}`);
}
}
handleMouseDown = (e) => {
this.startXY = [e.clientX, e.clientY];
}
handleMouseUp = (e) => {
if (!this.startXY) {
return;
}
const [ startX, startY ] = this.startXY;
const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)];
if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) {
return;
}
if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) {
this.props.onClick();
}
this.startXY = null;
}
handleSpoilerClick = (e) => {
e.preventDefault();
if (this.props.onExpandedToggle) {
// The parent manages the state
this.props.onExpandedToggle();
} else {
this.setState({ hidden: !this.state.hidden });
}
}
setRef = (c) => {
this.node = c;
}
render () {
const { status } = this.props;
const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden;
const content = { __html: emojify(status.get('content')) };
const spoilerContent = { __html: emojify(escapeTextContentForBrowser(status.get('spoiler_text', ''))) };
const directionStyle = { direction: 'ltr' };
if (isRtl(status.get('search_index'))) {
directionStyle.direction = 'rtl';
}
if (status.get('spoiler_text').length > 0) {
let mentionsPlaceholder = '';
const mentionLinks = status.get('mentions').map(item => (
<Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'>
@<span>{item.get('username')}</span>
</Permalink>
)).reduce((aggregate, item) => [...aggregate, item, ' '], []);
const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />;
if (hidden) {
mentionsPlaceholder = <div>{mentionLinks}</div>;
}
return (
<div className='status__content status__content--with-action' ref={this.setRef} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}>
<p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}>
<span dangerouslySetInnerHTML={spoilerContent} />
{' '}
<button tabIndex='0' className='status__content__spoiler-link' onClick={this.handleSpoilerClick}>{toggleText}</button>
</p>
{mentionsPlaceholder}
<div className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} />
</div>
);
} else if (this.props.onClick) {
return (
<div
ref={this.setRef}
className='status__content status__content--with-action'
style={directionStyle}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
dangerouslySetInnerHTML={content}
/>
);
} else {
return (
<div
ref={this.setRef}
className='status__content'
style={directionStyle}
dangerouslySetInnerHTML={content}
/>
);
}
}
}
|
boxroom/archive/backup-js-glow-2018-01-28/boxroom/archive/js-surface-2018-01-27/boxroom/archive/2018-01-11/src/main/js-surface-react-native.js | js-works/js-surface | import adaptReactLikeComponentSystem from './adaption/adaptReactLikeComponentSystem';
import React from 'react';
import ReactNative from 'react-native';
const {
createElement,
defineComponent,
isElement,
mount,
unmount,
Adapter,
Config
} = adaptReactLikeComponentSystem({
name: 'react-native',
api: { React, ReactNative },
createElement: React.createElement,
createFactory: React.createFactory,
isValidElement: React.isValidElement,
mount: reactNativeMount,
Component: React.Component,
browserBased: false
});
export {
createElement,
defineComponent,
isElement,
mount,
unmount,
Adapter,
Config
};
function reactNativeMount(Component) {
ReactNative.AppRegistry.registerComponent('AppMainComponent', () => Component);
}
|
src/routes/gallery/Gallery.js | malinowsky/dataroot_03 | /**
* 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 PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Contact from '../../components/Contact';
import Gallery from '../../components/Gallery';
import s from './Gallery.scss';
class GalleryR extends React.Component {
render() {
return (
<div className={s.root}>
<Gallery/>
<Contact/>
</div>
);
}
}
export default withStyles(s)(GalleryR);
|
test/containers/Counter/CounterPage.spec.js | DenQ/electron-react-lex | import React from 'react';
import { mount } from 'enzyme';
import { Provider } from 'react-redux';
import { createBrowserHistory } from 'history';
import { ConnectedRouter } from 'react-router-redux';
import CounterPage from '../../../app/containers/Counter/CounterPage';
import { configureStore } from '../../../app/store/configureStore';
function setup(initialState) {
const store = configureStore(initialState);
const history = createBrowserHistory();
const app = mount(
<Provider store={store}>
<ConnectedRouter history={history}>
<CounterPage />
</ConnectedRouter>
</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()).toMatch(/^0$/);
});
it('should display updated count after increment button click', () => {
const { buttons, p } = setup();
buttons.at(0).simulate('click');
expect(p.text()).toMatch(/^1$/);
});
it('should display updated count after descrement button click', () => {
const { buttons, p } = setup();
buttons.at(1).simulate('click');
expect(p.text()).toMatch(/^-1$/);
});
it('shouldnt change if even and if odd button clicked', () => {
const { buttons, p } = setup();
buttons.at(2).simulate('click');
expect(p.text()).toMatch(/^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()).toMatch(/^2$/);
});
it('should set counter to 100', () => {
const { buttons, p } = setup({ counter: 1 });
// console.log(buttons.at(4).find('.fa-grav').length);//1
buttons.at(4).simulate('click');
expect(p.text()).toMatch(/^100$/);
});
});
});
|
test/test_helper.js | YacYac/ReduxSimpleStarter | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
clients/packages/admin-client/src/components/forms/form.spec.js | nossas/bonde-client | /* eslint-disable no-unused-expressions */
import PropTypes from 'prop-types'
import React from 'react'
import { expect } from 'chai'
import { shallow } from 'enzyme'
import { Form } from '../../components/forms'
const Button = (props) => (
<button {...props}>Done!</button>
)
Button.propTypes = {
pristine: PropTypes.bool,
submitting: PropTypes.bool
}
describe('client/components/forms/form', () => {
it('should render without crashed', () => {
const form = shallow(<Form />)
expect(form).to.be.ok
})
it('should render children', () => {
const form = shallow(
<Form>
<Button type='button' />
</Form>
)
expect(form.find('Button').length).to.equal(1)
})
it('should call handleSubmit when submit form', () => {
let handleSubmitCalled = false
const form = shallow(<Form handleSubmit={() => { handleSubmitCalled = true }} />)
form.simulate('submit')
expect(handleSubmitCalled).to.equal(true)
})
it('should pass pristine and submitting to children', () => {
const form = shallow(
<Form pristine={false} submitting>
<Button />
</Form>
)
expect(form.find('Button').props()).to.deep.equal({
pristine: false,
submitting: true
})
})
})
|
src/components/cart/cartCheckOut/CartCheckOutListItemComponent.js | bluebill1049/cart | 'use strict';
import React from 'react';
require('styles/cart/cartCheckOut/CartCheckOutListItem.scss');
class CartCheckOutListItemComponent extends React.Component {
constructor(props) {
super(props)
}
render() {
return (
<li className="cartlistitem-component clearfix">
<img src={this.props.assets[this.props.item.fields.itemImage.sys.id]} />
<div className="cartlistitem-component__brief">
<h3>{this.props.item.fields.itemName}</h3>
<p>{this.props.item.fields.itemShortDescription}</p>
<p className="cartlistitem-component__price">${this.props.item.fields.price}</p>
</div>
<div className="cartlistitem-component__price-section">
<button className="small round alert" onClick={this.props.removeItem.bind(this, this.props.item.id, this.props.itemIndex)}>删除</button>
</div>
</li>
);
}
}
CartCheckOutListItemComponent.displayName = 'CartCartCheckOutCartCheckOutListItemComponent';
// Uncomment properties you need
CartCheckOutListItemComponent.propTypes = {
item : React.PropTypes.object.isRequired,
removeItem : React.PropTypes.func.isRequired,
itemIndex : React.PropTypes.number.isRequired
// viewDetail : React.PropTypes.func.isRequired
};
// CartCheckOutListItemComponent.defaultProps = {};
export default CartCheckOutListItemComponent;
|
src/components/SegmentedControl.js | pairyo/elemental | import classnames from 'classnames';
import React from 'react';
module.exports = React.createClass({
displayName: 'SegmentedControl',
propTypes: {
className: React.PropTypes.string,
equalWidthSegments: React.PropTypes.bool,
onChange: React.PropTypes.func.isRequired,
options: React.PropTypes.array.isRequired,
type: React.PropTypes.oneOf(['default', 'muted', 'danger', 'info', 'primary', 'success', 'warning']),
value: React.PropTypes.string
},
getDefaultProps () {
return {
type: 'default'
};
},
onChange (value) {
this.props.onChange(value);
},
render () {
let componentClassName = classnames('SegmentedControl', ('SegmentedControl--' + this.props.type), {
'SegmentedControl--equal-widths': this.props.equalWidthSegments
}, this.props.className);
let options = this.props.options.map((op) => {
let buttonClassName = classnames('SegmentedControl__button', {
'is-selected': op.value === this.props.value
});
return (
<span key={'option-' + op.value} className="SegmentedControl__item">
<button type="button" onClick={this.onChange.bind(this, op.value)} className={buttonClassName}>
{op.label}
</button>
</span>
);
});
return <div className={componentClassName}>{options}</div>;
}
});
|
src/app.react.js | JasonStoltz/test-runner-demo | import {connect} from 'react-redux';
import {List} from 'immutable';
import React from 'react';
import Promise from 'bluebird';
import PureComponent from 'react-pure-render/component';
import TestsService from './model/test';
import mapStateToProps from './lib/mapStateToProps';
import mapDispatchToProps from './lib/mapDispatchToProps';
import * as actions from './store/tests/actions';
import * as TestConstants from './model/test';
import Test from './model/test';
import * as TestsConstants from './store/tests/reducers';
import Tests from './components/runner/tests.react.js';
import Status from './components/runner/status.react';
@connect(mapStateToProps('tests'), mapDispatchToProps(actions))
export default class App extends PureComponent {
static propTypes = {
tests: React.PropTypes.object.isRequired,
actions: React.PropTypes.object.isRequired
};
constructor() {
super();
this.run = this.run.bind(this); //So we don't break pure render
}
render() {
const {tests} = this.props;
return (
<div>
<div>
<h1>Tests</h1>
{tests.get('status') === TestsConstants.FINISHED &&
<div>FINISHED!</div>
}
<Tests tests={tests.get('tests')} />
<div>
<button onClick={this.run} disabled={tests.get('status') === TestsConstants.RUNNING}>Run</button>
</div>
<Status
running={tests.get('running')}
failed={tests.get('failed')}
passed={tests.get('passed')}
/>
</div>
</div>
);
}
componentDidMount() {
const {actions} = this.props;
const tests = Test.all();
actions.setTests(tests);
}
run(e) {
e.preventDefault();
const {actions} = this.props;
const tests = this.props.tests.get('tests');
tests.forEach(test => {
actions.setStatus(test.get('id'), TestConstants.RUNNING);
TestsService.run(test.get('id')).then(result => {
actions.setStatus(test.get('id'), (result) ? TestConstants.PASSED : TestConstants.FAILED);
});
});
}
}
|
test/DropdownSpec.js | bvasko/react-bootstrap | import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Dropdown from '../src/Dropdown';
import DropdownMenu from '../src/DropdownMenu';
import MenuItem from '../src/MenuItem';
import { shouldWarn } from './helpers';
import keycode from 'keycode';
class CustomMenu extends React.Component {
render() {
return (
<div className='custom-menu'>
{this.props.children}
</div>
);
}
}
describe('Dropdown', () => {
let BaseDropdown = Dropdown.ControlledComponent;
const dropdownChildren = [
<Dropdown.Toggle>
Child Title
</Dropdown.Toggle>,
<Dropdown.Menu>
<MenuItem>Item 1</MenuItem>
<MenuItem>Item 2</MenuItem>
<MenuItem>Item 3</MenuItem>
<MenuItem>Item 4</MenuItem>
</Dropdown.Menu>
];
const simpleDropdown = (
<Dropdown id='test-id'>
{dropdownChildren}
</Dropdown>
);
it('renders div with dropdown class', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const node = React.findDOMNode(instance);
node.tagName.should.equal('DIV');
node.className.should.match(/\bdropdown\b/);
node.className.should.not.match(/\bdropup\b/);
});
it('renders div with dropup class', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Dropdown title='Dropup' dropup id='test-id'>
{dropdownChildren}
</Dropdown>
);
const node = React.findDOMNode(instance);
node.tagName.should.equal('DIV');
node.className.should.not.match(/\bdropdown\b/);
node.className.should.match(/\bdropup\b/);
});
it('renders toggle with Dropdown.Toggle', () => {
const instance = ReactTestUtils.renderIntoDocument(
simpleDropdown
);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
buttonNode.innerText.should.match(/Child Title/);
buttonNode.tagName.should.equal('BUTTON');
buttonNode.className.should.match(/\bbtn[ $]/);
buttonNode.className.should.match(/\bbtn-default\b/);
buttonNode.className.should.match(/\bdropdown-toggle\b/);
buttonNode.getAttribute('type').should.equal('button');
buttonNode.getAttribute('aria-expanded').should.equal('false');
buttonNode.getAttribute('id').should.be.ok;
});
it('renders dropdown toggle button caret', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const caretNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'caret'));
caretNode.tagName.should.equal('SPAN');
});
it('does not render toggle button caret', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Dropdown.Toggle noCaret>
Child Text
</Dropdown.Toggle>
);
const caretNode = ReactTestUtils.scryRenderedDOMComponentsWithClass(instance, 'caret');
caretNode.length.should.equal(0);
});
it('renders custom menu', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Dropdown title='Single child' id='test-id'>
<Dropdown.Toggle>Child Text</Dropdown.Toggle>
<CustomMenu bsRole='menu'>
<MenuItem>Item 1</MenuItem>
</CustomMenu>
</Dropdown>
);
ReactTestUtils.scryRenderedComponentsWithType(instance, DropdownMenu).length.should.equal(0);
ReactTestUtils.scryRenderedComponentsWithType(instance, CustomMenu).length.should.equal(1);
});
it('prop validation with multiple menus', () => {
const props = {
title: 'herpa derpa',
children: [(
<Dropdown.Toggle>Child Text</Dropdown.Toggle>
), (
<Dropdown.Menu>
<MenuItem>Item 1</MenuItem>
</Dropdown.Menu>
), (
<Dropdown.Menu>
<MenuItem>Item 1</MenuItem>
</Dropdown.Menu>
)]
};
let err = BaseDropdown.propTypes.children(props, 'children', 'DropdownButton');
err.message.should.match(/Duplicate children.*bsRole: menu/);
});
it('only renders one menu', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Dropdown title='Single child' id='test-id'>
<Dropdown.Toggle>Child Text</Dropdown.Toggle>
<CustomMenu bsRole='menu'>
<MenuItem>Item 1</MenuItem>
</CustomMenu>
<DropdownMenu>
<MenuItem>Item 1</MenuItem>
</DropdownMenu>
</Dropdown>
);
ReactTestUtils.scryRenderedComponentsWithType(instance, DropdownMenu).length.should.equal(0);
ReactTestUtils.scryRenderedComponentsWithType(instance, CustomMenu).length.should.equal(1);
shouldWarn(/Duplicate children.*bsRole: menu/);
});
it('forwards pullRight to menu', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Dropdown pullRight id='test-id'>
{dropdownChildren}
</Dropdown>
);
const menu = ReactTestUtils.findRenderedComponentWithType(instance, DropdownMenu);
menu.props.pullRight.should.be.true;
});
// NOTE: The onClick event handler is invoked for both the Enter and Space
// keys as well since the component is a button. I cannot figure out how to
// get ReactTestUtils to simulate such though.
it('toggles open/closed when clicked', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const node = React.findDOMNode(instance);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
node.className.should.not.match(/\bopen\b/);
buttonNode.getAttribute('aria-expanded').should.equal('false');
ReactTestUtils.Simulate.click(buttonNode);
node.className.should.match(/\bopen\b/);
buttonNode.getAttribute('aria-expanded').should.equal('true');
ReactTestUtils.Simulate.click(buttonNode);
node.className.should.not.match(/\bopen\b/);
buttonNode.getAttribute('aria-expanded').should.equal('false');
});
it('opens if dropdown contains no focusable menu item', () => {
const instance = ReactTestUtils.renderIntoDocument(
<Dropdown title='custom child' id='dropdown'>
<Dropdown.Toggle>Toggle</Dropdown.Toggle>
<Dropdown.Menu>
<li>Some custom nonfocusable content</li>
</Dropdown.Menu>
</Dropdown>
);
const node = React.findDOMNode(instance);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
ReactTestUtils.Simulate.click(buttonNode);
node.className.should.match(/\bopen\b/);
});
it('when focused and closed toggles open when the key "down" is pressed', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const node = React.findDOMNode(instance);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
ReactTestUtils.Simulate.keyDown(buttonNode, { keyCode: keycode('down') });
node.className.should.match(/\bopen\b/);
buttonNode.getAttribute('aria-expanded').should.equal('true');
});
it('button has aria-haspopup attribute (As per W3C WAI-ARIA Spec)', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
buttonNode.getAttribute('aria-haspopup').should.equal('true');
});
it('closes when child MenuItem is selected', () => {
const instance = ReactTestUtils.renderIntoDocument(
simpleDropdown
);
const node = React.findDOMNode(instance);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
const menuItem = React.findDOMNode(
ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]);
ReactTestUtils.Simulate.click(buttonNode);
node.className.should.match(/\bopen\b/);
ReactTestUtils.Simulate.click(menuItem);
node.className.should.not.match(/\bopen\b/);
});
it('does not close when onToggle is controlled', () => {
const handleSelect = () => {};
const instance = ReactTestUtils.renderIntoDocument(
<Dropdown open={true} onToggle={handleSelect} id='test-id'>
{dropdownChildren}
</Dropdown>
);
const node = React.findDOMNode(instance);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
const menuItem = React.findDOMNode(
ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]);
ReactTestUtils.Simulate.click(buttonNode);
node.className.should.match(/\bopen\b/);
ReactTestUtils.Simulate.click(menuItem);
node.className.should.match(/\bopen\b/);
});
it('is open with explicit prop', () => {
class OpenProp extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false
};
}
render () {
return (
<div>
<button className='outer-button'
onClick={() => this.setState({open: !this.state.open})}>
Outer button
</button>
<Dropdown
open={this.state.open}
onToggle={() => {}}
title='Prop open control'
id='test-id'
>
{dropdownChildren}
</Dropdown>
</div>
);
}
}
const instance = ReactTestUtils.renderIntoDocument(<OpenProp />);
const outerToggle = ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'outer-button');
const dropdownNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown'));
dropdownNode.className.should.not.match(/\bopen\b/);
ReactTestUtils.Simulate.click(outerToggle);
dropdownNode.className.should.match(/\bopen\b/);
ReactTestUtils.Simulate.click(outerToggle);
dropdownNode.className.should.not.match(/\bopen\b/);
});
it('has aria-labelledby same id as toggle button', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const node = React.findDOMNode(instance);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
const menuNode = node.children[1];
buttonNode.getAttribute('id').should.equal(menuNode.getAttribute('aria-labelledby'));
});
describe('PropType validation', () => {
describe('children', () => {
it('menu is exclusive', () => {
const props = {
children: [
<Dropdown.Toggle/>,
<Dropdown.Menu/>,
<Dropdown.Menu/>
]
};
BaseDropdown.propTypes.children(props, 'children', 'Dropdown')
.message.should.match(/Duplicate children.*bsRole: menu/);
});
it('menu is required', () => {
const props = {
children: [
<Dropdown.Toggle/>
]
};
BaseDropdown.propTypes.children(props, 'children', 'Dropdown')
.message.should.match(/Missing a required child.*bsRole: menu/);
});
it('toggles are not exclusive', () => {
const props = {
children: [
<Dropdown.Toggle/>,
<Dropdown.Toggle/>,
<Dropdown.Menu/>
]
};
expect(BaseDropdown.propTypes.children(props, 'children', 'Dropdown'))
.to.not.exist;
});
it('toggle is required', () => {
const props = {
children: [
<Dropdown.Menu/>
]
};
BaseDropdown.propTypes.children(props, 'children', 'Dropdown')
.message.should.match(/Missing a required child.*bsRole: toggle/);
});
});
});
describe('focusable state', () => {
let focusableContainer;
beforeEach(() => {
focusableContainer = document.createElement('div');
document.body.appendChild(focusableContainer);
});
afterEach(() => {
React.unmountComponentAtNode(focusableContainer);
document.body.removeChild(focusableContainer);
});
it('when focused and closed sets focus on first menu item when the key "down" is pressed', () => {
const instance = React.render(simpleDropdown, focusableContainer);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
buttonNode.focus();
ReactTestUtils.Simulate.keyDown(buttonNode, { keyCode: keycode('down') });
const firstMenuItemAnchor = React.findDOMNode(
ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]);
document.activeElement.should.equal(firstMenuItemAnchor);
});
it('when focused and open does not toggle closed when the key "down" is pressed', () => {
const instance = ReactTestUtils.renderIntoDocument(simpleDropdown);
const node = React.findDOMNode(instance);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
ReactTestUtils.Simulate.click(buttonNode);
ReactTestUtils.Simulate.keyDown(buttonNode, { keyCode: keycode('down') });
node.className.should.match(/\bopen\b/);
buttonNode.getAttribute('aria-expanded').should.equal('true');
});
// This test is more complicated then it appears to need. This is
// because there was an intermittent failure of the test when not structured this way
// The failure occured when all tests in the suite were run together, but not a subset of the tests.
//
// I am fairly confident that the failure is due to a test specific conflict and not an actual bug.
it('when open and the key "esc" is pressed the menu is closed and focus is returned to the button', () => {
const instance = React.render(
<Dropdown defaultOpen id='test-id'>
{dropdownChildren}
</Dropdown>
, focusableContainer);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'BUTTON'));
const firstMenuItemAnchor = React.findDOMNode(ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'A')[0]);
document.activeElement.should.equal(firstMenuItemAnchor);
ReactTestUtils.Simulate.keyDown(firstMenuItemAnchor, { type: 'keydown', keyCode: keycode('esc') });
document.activeElement.should.equal(buttonNode);
});
it('when open and the key "tab" is pressed the menu is closed and focus is progress to the next focusable element', done => {
const instance = React.render(
<div>
{simpleDropdown}
<input type='text' id='next-focusable' />
</div>, focusableContainer);
const node = ReactTestUtils.findRenderedComponentWithType(instance, Dropdown);
const buttonNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithTag(node, 'BUTTON'));
ReactTestUtils.Simulate.click(buttonNode);
buttonNode.getAttribute('aria-expanded').should.equal('true');
ReactTestUtils.Simulate.keyDown(buttonNode, { key: keycode('tab'), keyCode: keycode('tab') });
setTimeout(() => {
buttonNode.getAttribute('aria-expanded').should.equal('false');
done();
});
// simulating a tab event doesn't actually shift focus.
// at least that seems to be the case according to SO.
// hence no assert on the input having focus.
});
});
});
|
src/components/Scheme/HypertensionC.js | lethecoa/work-order-pc | import React from 'react';
import {Form, InputNumber, Row, Col} from 'antd';
import styles from './Scheme.less';
const FormItem = Form.Item;
const formItemLayout = {
labelCol: {
xs: { span: 24 },
sm: { span: 8 },
},
wrapperCol: {
xs: { span: 24 },
sm: { span: 16 },
},
};
class HypertensionC extends React.Component {
state = {
scheme: {},
};
componentWillMount() {
this.setState( { scheme: this.props.scheme } );
}
componentWillReceiveProps( nextProps ) {
this.setState( { scheme: nextProps.scheme } );
}
render() {
const { getFieldDecorator } = this.props.form;
const disabled = this.props.disabled;
const { scheme } = this.state;
return (
<div className={styles.need}>
<div className={styles.title}>随访项目</div>
<div className={styles.form}>
<Row>
<Col span={12}>
<FormItem {...formItemLayout} label="舒张压(mmHg)">
{getFieldDecorator( 'sbp', {
initialValue: scheme.sbp
} )(
<InputNumber min={1} max={300} style={{ width: 200 }} disabled={disabled} placeholder="请输入1-300之间的一个数值"/>
)}
</FormItem>
</Col>
<Col span={12}>
<FormItem {...formItemLayout} label="收缩压(mmHg)">
{getFieldDecorator( 'dbp', {
initialValue: scheme.dbp
} )(
<InputNumber min={1} max={300} style={{ width: 200 }} disabled={disabled} placeholder="请输入1-300之间的一个数值"/>
)}
</FormItem>
</Col>
</Row>
</div>
</div>
);
}
}
export default Form.create()( HypertensionC );
|
src/components/pages/NotFoundPage.js | mm-taigarevolution/tas_web_app | import React from 'react';
import { Link } from 'react-router-dom';
const NotFoundPage = () => {
return (
<div>
<h4>
404 Page Not Found
</h4>
<Link to="/"> Go back to homepage </Link>
</div>
);
};
export default NotFoundPage;
|
app/views/Homepage/components/RetroTitanic.js | herereadthis/redwall | import React from 'react';
import AppConstants from 'AppConstants';
export default class RetroTitantic extends React.Component {
constructor() {
super();
}
componentWillMount() {
}
componentDidMount() {
}
render() {
var titanticStyle;
titanticStyle = {
paddingTop: '2rem',
paddingBottom: '1rem'
};
return (
<article id="retro_art"
className="starfield parallax_scroll"
data-parallax-speed="250"
ref="starfield"
style={titanticStyle}>
<h2>Here are some awesome thing!</h2>
<section className="bellmaker_container geocities_me">
<h3>1997 was the best year ever!</h3>
<div className="centered_image">
{AppConstants.dataSprite('titanic_468x60')}
</div>
</section>
</article>
);
}
}
|
src/js/component/ClearCompleted.js | dtk0528/TODOs | import React, { Component } from 'react';
class ClearCompleted extends Component {
render() {
let clearButton = null;
if (this.props.itemCount > 0) {
clearButton = (
<button
className="clear-completed"
onClick={ this.props.onButtonClick }
>Clear</button>
);
}
return (
<div>
{ clearButton }
</div>
);
}
}
export default ClearCompleted;
|
src/mobile/routes.js | Perslu/rerebrace | import chalk from 'chalk';
import { injectReducer } from './redux/reducers';
import React from 'react';
import { Route, IndexRoute } from 'react-router/es6';
import App from './App'
import GalleryView from './public/containers/GalleryView';
import ProfileView from './public/containers/ProfileView';
// import Home from './Home'
import UserInfo from './UserInfo'
import NotFound from './NotFound'
const errorLoading = (err) => {
console.error(chalk.red(`==> 😭 Dynamic page loading failed ${err}`));
};
const loadModule = cb => (Component) => {
cb(null, Component.default);
};
export default (
<Route path="/" component={App}>
<IndexRoute component={GalleryView} />
<Route path="/userinfo" component={UserInfo} />
<Route path="/profile/:profileId" component={ProfileView} />
<Route path="/*" component={NotFound} />
</Route>
)
// export default function createRoutes(store) {
// return {
// path: '/',
// component: App,
// indexRoute: Home,
// childRoutes: [
// {
// path: 'UserInfo/:id',
//
// getComponent(location, cb) {
// const importModules = Promise.all([
// System.import('./UserInfo'),
// // System.import('./UserInfo/reducer'),
// ]);
//
// const renderRoute = loadModule(cb);
//
// importModules
// .then(([Component/*, reducer*/]) => {
// // injectReducer(store, 'userInfo', reducer.default);
//
// renderRoute(Component);
// })
// .catch(errorLoading);
// },
// },
// {
// path: '*',
// getComponent(location, cb) {
// System.import('./NotFound')
// .then(loadModule(cb))
// .catch(errorLoading);
// },
// },
// ],
// };
// }
|
app/javascript/mastodon/components/radio_button.js | kirakiratter/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
export default class RadioButton extends React.PureComponent {
static propTypes = {
value: PropTypes.string.isRequired,
checked: PropTypes.bool,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
label: PropTypes.node.isRequired,
};
render () {
const { name, value, checked, onChange, label } = this.props;
return (
<label className='radio-button'>
<input
name={name}
type='radio'
value={value}
checked={checked}
onChange={onChange}
/>
<span className={classNames('radio-button__input', { checked })} />
<span>{label}</span>
</label>
);
}
}
|
client/src/components/Polls.js | NicholasAsimov/voting-app | import React from 'react';
import { connect } from 'react-redux';
import Poll from './Poll';
import { Link } from 'react-router';
import { LinkContainer } from 'react-router-bootstrap';
import { ListGroup, ListGroupItem } from 'react-bootstrap';
class Polls extends React.Component {
render() {
return (
<div>
<h2>Public polls</h2>
<p>Select a poll to see the results and vote, or make a <Link to="/newpoll">new poll</Link>!</p>
<ListGroup>
{this.props.polls.map((poll, index) => (
<LinkContainer to={"/poll/" + poll._id} key={index}>
<ListGroupItem>{poll.title}</ListGroupItem>
</LinkContainer>
))}
</ListGroup>
</div>
)
}
}
function mapStateToProps(state) {
return { polls: state.polls };
}
export default connect(mapStateToProps)(Polls);
|
src/icons/AndroidAdd.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidAdd extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g id="Icon_7_">
<g>
<path d="M416,277.333H277.333V416h-42.666V277.333H96v-42.666h138.667V96h42.666v138.667H416V277.333z"></path>
</g>
</g>
</g>;
} return <IconBase>
<g id="Icon_7_">
<g>
<path d="M416,277.333H277.333V416h-42.666V277.333H96v-42.666h138.667V96h42.666v138.667H416V277.333z"></path>
</g>
</g>
</IconBase>;
}
};AndroidAdd.defaultProps = {bare: false} |
src/components/GroceryList.js | clayhan/reactserver | import React from 'react';
export default class GroceryList extends React.Component {
constructor(props) {
super(props);
this.state = {
clickedItems: []
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(e) {
const clickedItems = this.state.clickedItems.slice();
clickedItems.push(e.target.textContent);
this.setState({ clickedItems: clickedItems });
}
render() {
console.log('FE Render: GroceryList');
return (
<div className='component grocerylist'>
<div>GroceryList Component</div>
<h3>Ingredients:</h3>
<div>
<ol>
{this.props.ingredients.map((ingredient) => {
return <li onClick={this.handleClick}>{ingredient}</li>
})}
</ol>
</div>
<div>
<h6>Things I need to buy:</h6>
<ul>
{this.state.clickedItems.map((item) => {
return <li>{item}</li>
})}
</ul>
</div>
</div>
);
}
}
|
src/helpers/__tests__/makeRouteHooksSafe-test.js | huangc28/palestine-2 | import { expect } from 'chai';
import React from 'react';
import { IndexRoute, Route } from 'react-router';
import makeRouteHooksSafe from '../makeRouteHooksSafe';
describe('makeRouteHooksSafe', () => {
it('should work with JSX routes', () => {
const onEnter = () => {
throw new Error('Shouldn\'t call onEnter');
};
const getRoutes = makeRouteHooksSafe(() => {
return (
<Route path="/" >
<IndexRoute onEnter={onEnter} />
<Route path="1" />
<Route onEnter={onEnter}>
<Route path="2" />
<Route path="3" onEnter={onEnter}/>
</Route>
</Route>
);
});
const routes = getRoutes(null);
expect(routes[0].indexRoute.onEnter).to.not.throw(Error);
expect(routes[0].childRoutes[1].onEnter).to.not.throw(Error);
expect(routes[0].childRoutes[1].childRoutes[1].onEnter).to.not.throw(Error);
});
it('should work with JS routes', () => {
const onEnter = () => {
throw new Error('Shouldn\'t call onEnter');
};
const getRoutes = makeRouteHooksSafe(() => {
return {
path: '/',
indexRoute: {
onEnter: onEnter
},
onEnter: onEnter,
childRoutes: [
{path: '1'},
{
onEnter: onEnter,
childRoutes: [
{path: '2'},
{path: '3'}
],
}
]
};
});
const routes = getRoutes(null);
expect(routes[0].indexRoute.onEnter).to.not.throw(Error);
expect(routes[0].onEnter).to.not.throw(Error);
expect(routes[0].childRoutes[1].onEnter).to.not.throw(Error);
});
it('should call onEnter if store is initialised', (done) => {
const store = {
getState: () => {}
};
const getRoutes = makeRouteHooksSafe(() => {
return {
onEnter: () => {
done();
}
};
});
const routes = getRoutes(store);
routes[0].onEnter();
});
it('should call callback', (done) => {
const getRoutes = makeRouteHooksSafe(() => {
return {
onEnter: (nextState, replaceState, cb) => {} // eslint-disable-line no-unused-vars
};
});
const routes = getRoutes(null);
routes[0].onEnter(null, null, done);
});
it('should not call callback', () => {
const callback = () => {
throw new Error('Should not be called');
};
const getRoutes = makeRouteHooksSafe(() => {
return {
onEnter: (nextState, replaceState) => {} // eslint-disable-line no-unused-vars
};
});
const routes = getRoutes(null);
routes[0].onEnter(null, null, callback);
});
});
|
src/Containers/Top10/Top10.js | rahulp959/airstats.web | import React from 'react'
import {connect} from 'react-redux'
import TableTop from './TableTop/TableTop'
import './Top10.scss'
import { fetchTop10 } from '../../ducks/top10.js'
let top10Dispatcher
const refreshTime = 60 * 30 * 1000 // Once per half-hour
class Top10 extends React.Component {
componentDidMount () {
this.props.dispatch(fetchTop10())
top10Dispatcher = setInterval(() => this.props.dispatch(fetchTop10()), refreshTime)
}
componentWillUnmount () {
clearInterval(top10Dispatcher)
}
render () {
console.dir(this.props.top10)
let html = ''
if (this.props.top10.get('isFetching') === true) {
html = 'Loading...'
} else {
html = (
<div className='top10'>
<div className='topbox'>
<div className='title'>Top Departures</div>
<TableTop data={this.props.top10.getIn(['data', 'departures'])} />
</div>
<div className='topbox'>
<div className='title'>Top Arrivals</div>
<TableTop data={this.props.top10.getIn(['data', 'arrivals'])} />
</div>
</div>
)
}
return (
<div className='topcontainer'>
<p>Top 10 airports by types of operations within the past 7 days.</p>
{html}
<p>Last updated: {this.props.top10.getIn(['data', 'updated'])}Z</p>
</div>
)
}
}
const mapStateToProps = state => {
return {
top10: state.get('top10')
}
}
export default connect(mapStateToProps)(Top10)
|
src/router.js | ITenTeges/portfolioPage | /**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-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';
function decodeParam(val) {
if (!(typeof val === 'string' || val.length === 0)) {
return val;
}
try {
return decodeURIComponent(val);
} catch (err) {
if (err instanceof URIError) {
err.message = `Failed to decode param '${val}'`;
err.status = 400;
}
throw err;
}
}
// Match the provided URL path pattern to an actual URI string. For example:
// matchURI({ path: '/posts/:id' }, '/dummy') => null
// matchURI({ path: '/posts/:id' }, '/posts/123') => { id: 123 }
function matchURI(route, path) {
const match = route.pattern.exec(path);
if (!match) {
return null;
}
const params = Object.create(null);
for (let i = 1; i < match.length; i += 1) {
params[route.keys[i - 1].name] = match[i] !== undefined ? decodeParam(match[i]) : undefined;
}
return params;
}
// Find the route matching the specified location (context), fetch the required data,
// instantiate and return a React component
function resolve(routes, context) {
for (const route of routes) { // eslint-disable-line no-restricted-syntax
const params = matchURI(route, context.error ? '/error' : context.pathname);
if (!params) {
continue; // eslint-disable-line no-continue
}
// Check if the route has any data requirements, for example:
// { path: '/tasks/:id', data: { task: 'GET /api/tasks/$id' }, page: './pages/task' }
if (route.data) {
// Load page component and all required data in parallel
const keys = Object.keys(route.data);
return Promise.all([
route.load(),
...keys.map((key) => {
const query = route.data[key];
const method = query.substring(0, query.indexOf(' ')); // GET
let url = query.substr(query.indexOf(' ') + 1); // /api/tasks/$id
// TODO: Optimize
Object.keys(params).forEach((k) => {
url = url.replace(`${k}`, params[k]);
});
return fetch(url, { method }).then(resp => resp.json());
}),
]).then(([Page, ...data]) => {
const props = keys.reduce((result, key, i) => ({ ...result, [key]: data[i] }), {});
return <Page route={{ ...route, params }} error={context.error} {...props} />;
});
}
return route.load().then(Page => <Page route={{ ...route, params }} error={context.error} />);
}
const error = new Error('Page not found');
error.status = 404;
return Promise.reject(error);
}
export default { resolve };
|
examples/huge-apps/routes/Course/components/Course.js | AnSavvides/react-router | import React from 'react';
import Dashboard from './Dashboard';
import Nav from './Nav';
var styles = {};
styles.sidebar = {
float: 'left',
width: 200,
padding: 20,
borderRight: '1px solid #aaa',
marginRight: 20
};
class Course extends React.Component {
render () {
let { children, params } = this.props;
let course = COURSES[params.courseId];
return (
<div>
<h2>{course.name}</h2>
<Nav course={course} />
{children && children.sidebar && children.main ? (
<div>
<div className="Sidebar" style={styles.sidebar}>
{children.sidebar}
</div>
<div className="Main" style={{padding: 20}}>
{children.main}
</div>
</div>
) : (
<Dashboard />
)}
</div>
);
}
}
export default Course;
|
components/Login/ReviseUser.js | slidewiki/slidewiki-platform | import PropTypes from 'prop-types';
import React from 'react';
import ReactDOM from 'react-dom';
import classNames from 'classnames';
import {navigateAction} from 'fluxible-router';
import {connectToStores} from 'fluxible-addons-react';
import checkEmail from '../../actions/user/registration/checkEmail';
import checkUsername from '../../actions/user/registration/checkUsername';
import UserRegistrationStore from '../../stores/UserRegistrationStore';
import SSOStore from '../../stores/SSOStore';
import common from '../../common';
import finalizeMergedUser from '../../actions/user/finalizeMergedUser';
import instances from '../../configs/instances.js';
import {FormattedMessage, defineMessages} from 'react-intl';
const headerStyle = {
'textAlign': 'center'
};
const modalStyle = {
top: '15%'
};
class ReviseUser extends React.Component {
constructor(props) {
super(props);
this.errorMessages = defineMessages({
error409: {
id: 'SSOSignIn.errormessage.isForbidden',
defaultMessage: 'Migration is not possible with this user. Please start all over again.'
},
error404: {
id: 'SSOSignIn.errormessage.accountNotFound',
defaultMessage: 'This account was not prepared for migration. Please start all over again.'
},
error500: {
id: 'SSOSignIn.errormessage.badImplementation',
defaultMessage: 'An unknown error occurred.'
}
});
}
componentDidMount() {
//Form validation
const validationRules = {
fields: {
username: {
identifier: 'username',
rules: [{
type: 'empty',
prompt: 'Please select your username'
}, {
type: 'uniqueUsername',
prompt: 'The username is already in use'
}, {
type : 'maxLength[64]',
prompt : 'Your username can not be longer than 64 characters'
}, {
type : 'regExp[/^[a-zA-Z0-9-.~_]+$/i]',
prompt : 'The username must contain only alphanumeric characters plus the following: _ . - ~'
}]
},
email: {
identifier: 'email',
rules: [{
type: 'empty',
prompt: 'Please enter your email address'
}, {
type: 'email',
prompt: 'Please enter a valid email address'
}, {
type: 'uniqueEmail',
prompt: 'The email address is already in use'
}]
}
},
onSuccess: this.handleSignUp.bind(this)
};
$.fn.form.settings.rules.uniqueEmail = (() => {
const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed;
return (emailNotAllowed !== undefined) ? !emailNotAllowed : true;
});
$.fn.form.settings.rules.uniqueUsername = (() => {
const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed;
return (usernameNotAllowed !== undefined) ? !usernameNotAllowed : true;
});
$(ReactDOM.findDOMNode(this.refs.ReviseUser_form)).form(validationRules);
}
componentWillReceiveProps(nextProps) {
console.log('ReviseUser componentWillReceiveProps()', this.props.UserRegistrationStore.socialuserdata, nextProps.UserRegistrationStore.socialuserdata, this.props.SSOStore.username, nextProps.SSOStore.username);
if (nextProps.SSOStore.username !== this.props.SSOStore.username) {
this.refs.username.value = nextProps.SSOStore.username;
this.refs.email.value = nextProps.SSOStore.email;
this.checkUsername();
this.checkEmail();
}
}
handleSignUp(e) {
e.preventDefault();
let user = {};
user.email = this.refs.email.value;
user.username = this.refs.username.value;
user.hash = this.props.SSOStore.hash;
let language = common.getIntlLanguage();
user.language = language;
user.url = instances[instances._self].finalize.replace('{hash}', user.hash);
user.errorMessages = {
error409: this.context.intl.formatMessage(this.errorMessages.error409),
error404: this.context.intl.formatMessage(this.errorMessages.error404),
error500: this.context.intl.formatMessage(this.errorMessages.error500)
};
this.context.executeAction(finalizeMergedUser, user);
$(ReactDOM.findDOMNode(this.refs.ReviseUser_Modal)).modal('hide');
return false;
}
checkEmail() {
const email = this.refs.email.value;
if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || email !== '') {
this.context.executeAction(checkEmail, {email: email});
}
}
checkUsername() {
const username = this.refs.username.value;
if (this.props.UserRegistrationStore.failures.usernameNotAllowed !== undefined || username !== '') {
this.context.executeAction(checkUsername, {username: username});
}
}
render() {
const signUpLabelStyle = {width: '150px'};
const emailNotAllowed = this.props.UserRegistrationStore.failures.emailNotAllowed;
let emailClasses = classNames({
'ui': true,
'field': true,
'inline': true,
'error': (emailNotAllowed !== undefined) ? emailNotAllowed : false
});
let emailIconClasses = classNames({
'icon': true,
'inverted circular red remove': (emailNotAllowed !== undefined) ? emailNotAllowed : false,
'inverted circular green checkmark': (emailNotAllowed !== undefined) ? !emailNotAllowed : false
});
let emailToolTipp = emailNotAllowed ? 'This E-Mail has already been used by someone else. Please choose another one.' : undefined;
const usernameNotAllowed = this.props.UserRegistrationStore.failures.usernameNotAllowed;
let usernameClasses = classNames({
'ui': true,
'field': true,
'inline': true,
'error': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false
});
let usernameIconClasses = classNames({
'icon': true,
'inverted circular red remove': (usernameNotAllowed !== undefined) ? usernameNotAllowed : false,
'inverted circular green checkmark': (usernameNotAllowed !== undefined) ? !usernameNotAllowed : false
});
let usernameToolTipp = usernameNotAllowed ? 'This Username has already been used by someone else. Please choose another one.' : undefined;
if (this.props.UserRegistrationStore.suggestedUsernames.length > 0) {
usernameToolTipp += '\n Here are some suggestions: ' + this.props.UserRegistrationStore.suggestedUsernames;
}
return (
<div>
<div className="ui ssoregistration modal" id='signinModal' style={modalStyle} ref="ReviseUser_Modal" >
<div className="header">
<h1 style={headerStyle}>Validate user information</h1>
<h2 style={headerStyle}>Your account could not migrated automatically. In order to finialize the migration, please change the data which is already in use.</h2>
<h3 style={headerStyle}>Hint: if your email or username is already in use, it could be possible that you have already an stand-alone account on this SlideWiki instance. In this case close the window and do a sign in.</h3>
</div>
<div className="content">
<form className="ui ssoregistrationmodalform form" ref="ReviseUser_form" >
<div className={usernameClasses} data-tooltip={usernameToolTipp} data-position="top center" data-inverted="" onBlur={this.checkUsername.bind(this)}>
<label style={signUpLabelStyle}>Username * </label>
<div className="ui icon input"><i className={usernameIconClasses}/><input type="text" name="username" ref="username" placeholder="Username" aria-required="true" /></div>
</div>
<div className={emailClasses} data-tooltip={emailToolTipp} data-position="top center" data-inverted="" onBlur={this.checkEmail.bind(this)}>
<label style={signUpLabelStyle}>Email * </label>
<div className="ui icon input"><i className={emailIconClasses}/><input type="email" name="email" ref="email" placeholder="Email" aria-required="true" /></div>
</div>
<div className="ui error message" role="region" aria-live="polite"/>
<button type="submit" className="ui blue labeled submit icon button" >
<i className="icon add user"/> Migrate User
</button>
</form>
</div>
<div className="actions">
<div className="ui cancel button">Cancel</div>
</div>
</div>
</div>
);
}
}
ReviseUser.contextTypes = {
executeAction: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired
};
ReviseUser = connectToStores(ReviseUser, [UserRegistrationStore, SSOStore], (context, props) => {
return {
UserRegistrationStore: context.getStore(UserRegistrationStore).getState(),
SSOStore: context.getStore(SSOStore).getState()
};
});
export default ReviseUser;
|
Realization/frontend/czechidm-core/src/components/advanced/ProfileInfo/ProfileInfo.js | bcvsolutions/CzechIdMng | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
//
import * as Basic from '../../basic';
import { ProfileManager } from '../../../redux';
import AbstractEntityInfo from '../EntityInfo/AbstractEntityInfo';
import EntityInfo from '../EntityInfo/EntityInfo';
import TwoFactorAuthenticationTypeEnum from '../../../enums/TwoFactorAuthenticationTypeEnum';
//
const manager = new ProfileManager();
/**
* Component for rendering information about identity profile.
*
* @author Radek Tomiška
* @since 12.0.0
*/
export class ProfileInfo extends AbstractEntityInfo {
getManager() {
return manager;
}
showLink() {
return false;
}
/**
* Returns entity icon (null by default - icon will not be rendered)
*
* @param {object} entity
*/
getEntityIcon() {
return 'fa:cog';
}
getNiceLabel(entity) {
const _entity = entity || this.getEntity();
let label = this.i18n('entity.Profile._type');
if (_entity && _entity._embedded && _entity._embedded.identity) {
label = `${ label } - (${ _entity._embedded.identity.username })`;
}
return label;
}
/**
* Returns popovers title
*
* @param {object} entity
*/
getPopoverTitle() {
return this.i18n('entity.Profile._type');
}
getTableChildren() {
// component are used in #getPopoverContent => skip default column resolving
return [
<Basic.Column property="label"/>,
<Basic.Column property="value"/>
];
}
/**
* Returns popover info content
*
* @param {array} table data
*/
getPopoverContent(entity) {
return [
{
label: this.i18n('entity.Identity._type'),
value: (
<EntityInfo
entityType="identity"
entity={ entity._embedded ? entity._embedded.identity : null }
entityIdentifier={ entity.identity }
face="popover" />
)
},
{
label: this.i18n('entity.Profile.preferredLanguage.label'),
value: entity.preferredLanguage
},
{
label: this.i18n('entity.Profile.systemInformation.label'),
value: (entity.systemInformation ? this.i18n('label.yes') : this.i18n('label.no'))
},
{
label: this.i18n('entity.Profile.twoFactorAuthenticationType.label'),
value: (
<Basic.EnumValue
enum={ TwoFactorAuthenticationTypeEnum }
value={ entity.twoFactorAuthenticationType }/>
)
}
];
}
}
ProfileInfo.propTypes = {
...AbstractEntityInfo.propTypes,
/**
* Selected entity - has higher priority
*/
entity: PropTypes.object,
/**
* Selected entity's id - entity will be loaded automatically
*/
entityIdentifier: PropTypes.string,
/**
* Internal entity loaded by given identifier
*/
_entity: PropTypes.object,
_showLoading: PropTypes.bool
};
ProfileInfo.defaultProps = {
...AbstractEntityInfo.defaultProps,
entity: null,
face: 'link',
_showLoading: true
};
function select(state, component) {
return {
_entity: manager.getEntity(state, component.entityIdentifier),
_showLoading: manager.isShowLoading(state, null, component.entityIdentifier)
};
}
export default connect(select)(ProfileInfo);
|
app/components/App/App.js | Tonnu/workflows-ecs-ecr-demo | import React from 'react';
import createStore from 'lib/createStore';
import { Provider } from 'react-redux';
import HelloApp from 'components/HelloApp/HelloApp';
const store = createStore();
class App extends React.Component {
render() {
return (
<Provider {...{ store }}>
<HelloApp/>
</Provider>
);
}
}
export default App;
|
src/containers/DevTools/DevTools.js | svsool/react-redux-universal-hot-example | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-H"
changePositionKey="ctrl-Q">
<LogMonitor />
</DockMonitor>
);
|
app/javascript/mastodon/features/community_timeline/index.js | ebihara99999/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../ui/components/column';
import {
refreshTimeline,
updateTimeline,
deleteFromTimelines,
connectTimeline,
disconnectTimeline,
} from '../../actions/timelines';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import createStream from '../../stream';
const messages = defineMessages({
title: { id: 'column.community', defaultMessage: 'Local timeline' },
});
const mapStateToProps = state => ({
hasUnread: state.getIn(['timelines', 'community', 'unread']) > 0,
streamingAPIBaseURL: state.getIn(['meta', 'streaming_api_base_url']),
accessToken: state.getIn(['meta', 'access_token']),
});
let subscription;
class CommunityTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
streamingAPIBaseURL: PropTypes.string.isRequired,
accessToken: PropTypes.string.isRequired,
hasUnread: PropTypes.bool,
};
componentDidMount () {
const { dispatch, streamingAPIBaseURL, accessToken } = this.props;
dispatch(refreshTimeline('community'));
if (typeof subscription !== 'undefined') {
return;
}
subscription = createStream(streamingAPIBaseURL, accessToken, 'public:local', {
connected () {
dispatch(connectTimeline('community'));
},
reconnected () {
dispatch(connectTimeline('community'));
},
disconnected () {
dispatch(disconnectTimeline('community'));
},
received (data) {
switch(data.event) {
case 'update':
dispatch(updateTimeline('community', JSON.parse(data.payload)));
break;
case 'delete':
dispatch(deleteFromTimelines(data.payload));
break;
}
},
});
}
componentWillUnmount () {
// if (typeof subscription !== 'undefined') {
// subscription.close();
// subscription = null;
// }
}
render () {
const { intl, hasUnread } = this.props;
return (
<Column icon='users' active={hasUnread} heading={intl.formatMessage(messages.title)}>
<ColumnBackButtonSlim />
<StatusListContainer {...this.props} scrollKey='community_timeline' type='community' emptyMessage={<FormattedMessage id='empty_column.community' defaultMessage='The local timeline is empty. Write something publicly to get the ball rolling!' />} />
</Column>
);
}
}
export default connect(mapStateToProps)(injectIntl(CommunityTimeline));
|
features/filmStrip/components/web/DominantSpeakerIndicator.js | jitsi/jitsi-meet-react | import React, { Component } from 'react';
import Icon from 'react-fontawesome';
import { styles } from './styles';
/**
* Thumbnail badge showing that the participant is the dominant speaker in
* the conference.
*/
export class DominantSpeakerIndicator extends Component {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
*/
render() {
return (
<div style = { styles.dominantSpeakerIndicatorBackground }>
<Icon
name = 'bullhorn'
style = { styles.dominantSpeakerIndicator } />
</div>
);
}
}
|
src/svg-icons/av/video-label.js | mtsandeep/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVideoLabel = (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-2zm0 13H3V5h18v11z"/>
</SvgIcon>
);
AvVideoLabel = pure(AvVideoLabel);
AvVideoLabel.displayName = 'AvVideoLabel';
AvVideoLabel.muiName = 'SvgIcon';
export default AvVideoLabel;
|
examples/todomvc/containers/Root.js | dherault/redux | import React, { Component } from 'react';
import TodoApp from './TodoApp';
import { createStore, combineReducers } from 'redux';
import { Provider } from 'react-redux';
import rootReducer from '../reducers';
const store = createStore(rootReducer);
export default class Root extends Component {
render() {
return (
<Provider store={store}>
{() => <TodoApp /> }
</Provider>
);
}
}
|
test/Motion-test.js | keyanzhang/react-motion | import React from 'react';
import {spring} from '../src/react-motion';
import createMockRaf from './createMockRaf';
import TestUtils from 'react-addons-test-utils';
const {createSpy} = global.jasmine;
const injector = require('inject!../src/Motion');
// temporarily putting the animation loop test here
// TODO: put it in the correct file
describe('animation loop', () => {
let Motion;
let mockRaf;
beforeEach(() => {
mockRaf = createMockRaf();
Motion = injector({
raf: mockRaf.raf,
'performance-now': mockRaf.now,
});
});
it('should interpolate correctly when the timer is perfect', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion defaultStyle={{a: 0}} style={{a: spring(10)}}>
{({a}) => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([0]);
mockRaf.step(5);
expect(count).toEqual([
0,
0.4722222222222222,
1.1897376543209877,
2.0123698988340193,
2.8557218143909084,
3.670989925304686,
]);
});
it('should work with negative numbers', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion defaultStyle={{a: -10}} style={{a: spring(-100)}}>
{({a}) => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
mockRaf.step(5);
expect(count).toEqual([
-10,
-14.25,
-20.70763888888889,
-28.11132908950617,
-35.70149632951818,
-43.038909327742175,
]);
});
it('should interpolate correctly when the timer is imperfect', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion defaultStyle={{a: 0}} style={{a: spring(10)}}>
{({a}) => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([0]);
mockRaf.step(10, 0);
// 0 accumulatedTime, bail out of recalc & render
expect(count).toEqual([0]);
mockRaf.step(3, 0.1);
expect(count).toEqual([
0,
// notice the numbers are all very close together
0.002833333333333333,
0.005666666666666666,
0.0085,
]);
// interval too large; bail
mockRaf.step(10, 999);
expect(count).toEqual([
0,
0.002833333333333333,
0.005666666666666666,
0.0085,
]);
// more than one theoretical frame passed, each tick
mockRaf.step(2, 36);
expect(count).toEqual([
0,
0.002833333333333333,
0.005666666666666666,
0.0085,
1.3213588134430725,
3.116607609883317,
]);
});
});
describe('Motion', () => {
let Motion;
let mockRaf;
beforeEach(() => {
mockRaf = createMockRaf();
Motion = injector({
raf: mockRaf.raf,
'performance-now': mockRaf.now,
});
});
it('should allow returning null from children function', () => {
const App = React.createClass({
render() {
// shouldn't throw here
return <Motion style={{a: 0}}>{() => null}</Motion>;
},
});
TestUtils.renderIntoDocument(<App />);
});
it('should not throw on unmount', () => {
spyOn(console, 'error');
let kill = () => {};
const App = React.createClass({
getInitialState() {
return {kill: false};
},
componentWillMount() {
kill = () => this.setState({kill: true});
},
render() {
return this.state.kill
? null
: <Motion defaultStyle={{a: 0}} style={{a: spring(10)}}>{() => null}</Motion>;
},
});
TestUtils.renderIntoDocument(<App />);
mockRaf.step(2);
kill();
mockRaf.step(3);
expect(console.error).not.toHaveBeenCalled();
});
it('should allow a defaultStyle', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion defaultStyle={{a: 0}} style={{a: spring(10)}}>
{({a}) => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([0]);
mockRaf.step(4);
expect(count).toEqual([
0,
0.4722222222222222,
1.1897376543209877,
2.0123698988340193,
2.8557218143909084,
]);
});
it('should accept different spring configs', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion
defaultStyle={{a: 0}}
style={{a: spring(10, {stiffness: 100, damping: 50, precision: 16})}}>
{({a}) => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
mockRaf.step(99);
expect(count).toEqual([
0,
0.2777777777777778,
0.5941358024691358,
0.9081361454046639,
1.213021309632678,
1.5079182450697726,
1.7929588941684615,
2.0684390330691236,
10,
]);
});
it('should interpolate many values', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion
defaultStyle={{a: 0, b: 10}}
style={{a: spring(10), b: spring(410)}}>
{({a, b}) => {
count.push([a, b]);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([[0, 10]]);
mockRaf.step(4);
expect(count).toEqual([
[0, 10],
[0.4722222222222222, 28.888888888888886],
[1.1897376543209877, 57.589506172839506],
[2.0123698988340193, 90.49479595336075],
[2.8557218143909084, 124.22887257563633],
]);
});
it('should work with nested Motions', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion defaultStyle={{owner: 0}} style={{owner: spring(10)}}>
{({owner}) => {
count.push(owner);
return (
<Motion defaultStyle={{child: 10}} style={{child: spring(400)}}>
{({child}) => {
count.push(child);
return null;
}}
</Motion>
);
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([0, 10]);
mockRaf.step();
expect(count).toEqual([
0,
10,
28.416666666666668, // child
0.4722222222222222, // owner
28.416666666666668, // child
]);
mockRaf.step(2);
expect(count).toEqual([
0,
10,
28.416666666666668,
0.4722222222222222,
28.416666666666668,
56.39976851851852, // child
1.1897376543209877, // owner
56.39976851851852, // child
88.48242605452674, // child
2.0123698988340193, // owner
88.48242605452674, // child
]);
});
it('should reach destination value', () => {
let count = [];
const App = React.createClass({
render() {
return (
<Motion defaultStyle={{a: 0}} style={{a: spring(400)}}>
{({a}) => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([0]);
mockRaf.step(111);
expect(count.slice(0, 5)).toEqual([
0,
18.888888888888886,
47.589506172839506,
80.49479595336075,
114.22887257563633,
]);
expect(count.length).toBe(91);
expect(count[count.length - 1]).toEqual(400);
});
it('should support jumping to value', () => {
let count = [];
let setState = () => {};
const App = React.createClass({
getInitialState() {
return {p: false};
},
componentWillMount() {
setState = this.setState.bind(this);
},
render() {
return (
<Motion style={{a: this.state.p ? 400 : spring(0)}}>
{({a}) => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([0]);
setState({p: true});
expect(count).toEqual([
0,
0, // this new 0 comes from owner update, causing Motion to re-render
]);
mockRaf.step(10);
// jumped to end, will only have two renders no matter how much we step
expect(count).toEqual([
0,
0,
400,
]);
setState({p: false});
mockRaf.step(3);
expect(count).toEqual([
0,
0,
400,
400, // redundant 0 comes from owner update again
381.1111111111111,
352.4104938271605,
319.5052040466392,
]);
});
it('should call onRest at the end of an animation', () => {
const onRest = createSpy('onRest');
let result = 0;
const App = React.createClass({
render() {
return (
<Motion
defaultStyle={{a: 0}}
style={{a: spring(5, {stiffness: 380, damping: 18, precision: 1})}}
onRest={onRest}
>
{
({a}) => {
result = a;
return null;
}
}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
mockRaf.step(22);
expect(result).toEqual(5);
expect(onRest.calls.count()).toEqual(1);
});
it('should not call onRest if an animation is still in progress', () => {
const onRest = createSpy('onRest');
let resultA = 0;
let resultB = 0;
const App = React.createClass({
render() {
return (
<Motion
defaultStyle={{a: 0, b: 0}}
style={
{
a: spring(5, {stiffness: 380, damping: 18, precision: 1}),
b: spring(500, {stiffness: 380, damping: 18, precision: 1}),
}
}
onRest={onRest}
>
{
({a, b}) => {
resultA = a;
resultB = b;
return null;
}
}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
mockRaf.step(22);
expect(resultA).toEqual(5);
expect(resultB).not.toEqual(500);
expect(onRest).not.toHaveBeenCalled();
});
it('should not call onRest unless an animation occurred', () => {
const onRest = createSpy('onRest');
let setState;
const App = React.createClass({
getInitialState() {
return {a: spring(0)};
},
componentWillMount() {
setState = this.setState.bind(this);
},
render() {
return (
<Motion
defaultStyle={{a: 0}}
style={{a: this.state.a}}
onRest={onRest}
>
{() => null}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
mockRaf.step();
setState({a: 50});
mockRaf.step();
expect(onRest).not.toHaveBeenCalled();
});
it('should behave well when many owner updates come in-between rAFs', () => {
let count = [];
let setState = () => {};
const App = React.createClass({
getInitialState() {
return {a: spring(0)};
},
componentWillMount() {
setState = this.setState.bind(this);
},
render() {
return (
<Motion style={this.state}>
{a => {
count.push(a);
return null;
}}
</Motion>
);
},
});
TestUtils.renderIntoDocument(<App />);
expect(count).toEqual([{a: 0}]);
setState({a: 400});
setState({a: spring(100)});
mockRaf.step(2);
setState({a: spring(400)});
mockRaf.step(2);
expect(count).toEqual([
{a: 0},
{a: 0}, // this new 0 comes from owner update, causing Motion to re-render
{a: 400},
{a: 385.8333333333333},
{a: 364.3078703703703},
{a: 364.3078703703703},
{a: 353.79556970164606},
{a: 350.02047519790233},
]);
mockRaf.step(999);
expect(count.length).toBe(85);
setState({a: spring(400)});
// make sure we're still updating children even if there's nothing to interp
expect(count.length).toBe(86);
});
});
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/AsyncAwait.js | timlogemann/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
async function load() {
return [
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
];
}
/* eslint-disable */
// Regression test for https://github.com/facebook/create-react-app/issues/3055
const x = async (
/* prettier-ignore */
y: void
) => {
const z = await y;
};
/* eslint-enable */
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = await load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-async-await">
{this.state.users.map(user => (
<div key={user.id}>{user.name}</div>
))}
</div>
);
}
}
|
src/Components/SearchHeader.stories.js | elderfo/elderfo-react-native-components | import React from 'react';
import { Text, View } from 'react-native';
import { storiesOf, action, linkTo, } from '@kadira/react-native-storybook';
import { Container, SearchHeader } from '../';
storiesOf('SearchHeader', module)
.addDecorator(story => (
<Container>
{story()}
</Container>
))
.add('with left button', () => (
<SearchHeader
onLeftButtonClick={action('onLeftButtonClick')}
leftButtonIcon='md-arrow-back'
onSearch={action('onSearch')} />
))
.add('with right button', () => (
<SearchHeader
onRightButtonClick={action('onRightButtonClick')}
rightButtonIcon='md-qr-scanner'
onSearch={action('onSearch')} />
))
.add('with both buttons', () => (
<SearchHeader
onLeftButtonClick={action('onLeftButtonClick')}
leftButtonIcon='md-arrow-back'
onRightButtonClick={action('onRightButtonClick')}
rightButtonIcon='md-qr-scanner'
onSearch={action('onSearch')} />
))
.add('with custom placeholder', () => (
<SearchHeader
placeholder='Custom Placeholder'
onLeftButtonClick={action('onLeftButtonClick')}
leftButtonIcon='md-arrow-back'
onRightButtonClick={action('onRightButtonClick')}
rightButtonIcon='md-qr-scanner'
onSearch={action('onSearch')} />
))
.add('with a backgroundColor/foregroundColor', () => (
<SearchHeader
onLeftButtonClick={action('onLeftButtonClick')}
leftButtonIcon='md-menu'
onRightButtonClick={action('onRightButtonClick')}
rightButtonIcon='md-qr-scanner'
backgroundColor='red'
foregroundColor='silver' />
)) |
examples/src/app.js | yonaichin/react-select | /* eslint react/prop-types: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import Select from 'react-select';
import Contributors from './components/Contributors';
import GithubUsers from './components/GithubUsers';
import CustomComponents from './components/CustomComponents';
import CustomRender from './components/CustomRender';
import Multiselect from './components/Multiselect';
import NumericSelect from './components/NumericSelect';
import Virtualized from './components/Virtualized';
import States from './components/States';
ReactDOM.render(
<div>
<States label="States" searchable />
<Multiselect label="Multiselect" />
<Virtualized label="Virtualized" />
<Contributors label="Contributors (Async)" />
<GithubUsers label="Github users (Async with fetch.js)" />
<NumericSelect label="Numeric Values" />
<CustomRender label="Custom Render Methods"/>
<CustomComponents label="Custom Placeholder, Option and Value Components" />
{/*
<SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's NOT in the list, then hit return" />
*/}
</div>,
document.getElementById('example')
);
|
src/app/components/team/TeamData/TeamDataComponent.js | meedan/check-web | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import Card from '@material-ui/core/Card';
import CardContent from '@material-ui/core/CardContent';
import SettingsHeader from '../SettingsHeader';
import { ContentColumn } from '../../../styles/js/shared';
const TeamDataComponent = ({ dataReportUrl }) => (
<ContentColumn large>
<SettingsHeader
title={
<FormattedMessage
id="teamDataComponent.title"
defaultMessage="Workspace data"
description="Header for the stored data page of the current team"
/>
}
subtitle={
<FormattedMessage
id="teamDataComponent.subtitle"
defaultMessage="Download data and metadata from Check. Get insight and analysis about workspace and tipline usage."
/>
}
helpUrl="https://help.checkmedia.org/en/articles/4511362"
/>
<Card>
<CardContent>
{ dataReportUrl ?
<React.Fragment>
<Typography variant="body1" component="p" paragraph>
<FormattedMessage id="teamDataComponent.notSet1" defaultMessage="Click the button below to open your data report in a new window." />
</Typography>
<Box mt={2} mb={2}>
<Button
variant="contained"
color="primary"
onClick={() => { window.open(dataReportUrl); }}
>
<FormattedMessage id="teamDataComponent.viewDataReport" defaultMessage="View data report" />
</Button>
</Box>
<Typography variant="body1" component="p" paragraph>
<FormattedMessage id="teamDataComponent.notSet2" defaultMessage="To request any customization of your data report, please reach out to support." />
</Typography>
</React.Fragment> :
<React.Fragment>
<Typography variant="body1" component="p" paragraph>
<FormattedMessage
id="teamDataComponent.set1"
defaultMessage="Fill {thisShortForm} to request access to your data report."
values={{
thisShortForm: (
<a href="https://airtable.com/shrWpaztZ2SzD5TrA" target="_blank" rel="noopener noreferrer">
<FormattedMessage id="teamDataComponent.formLinkText" defaultMessage="this short form" />
</a>
),
}}
/>
</Typography>
<Typography variant="body1" component="p" paragraph>
<FormattedMessage id="teamDataComponent.set2" defaultMessage="Your data report will be enabled within one business day." />
</Typography>
</React.Fragment> }
</CardContent>
</Card>
</ContentColumn>
);
TeamDataComponent.defaultProps = {
dataReportUrl: null,
};
TeamDataComponent.propTypes = {
dataReportUrl: PropTypes.string, // or null
};
export default TeamDataComponent;
|
docs/src/NavMain.js | adampickeral/react-bootstrap | import React from 'react';
import { Link } from 'react-router';
import Navbar from '../../src/Navbar';
import Nav from '../../src/Nav';
const NAV_LINKS = {
'introduction': {
link: 'introduction',
title: 'Introduction'
},
'getting-started': {
link: 'getting-started',
title: 'Getting started'
},
'components': {
link: 'components',
title: 'Components'
},
'support': {
link: 'support',
title: 'Support'
}
};
const NavMain = React.createClass({
propTypes: {
activePage: React.PropTypes.string
},
render() {
let brand = <Link to='home' className="navbar-brand">React-Bootstrap</Link>;
let links = Object.keys(NAV_LINKS).map(this.renderNavItem).concat([
<li key='github-link'>
<a href='https://github.com/react-bootstrap/react-bootstrap' target='_blank'>GitHub</a>
</li>
]);
return (
<Navbar componentClass='header' brand={brand} staticTop className="bs-docs-nav" role="banner" toggleNavKey={0}>
<Nav className="bs-navbar-collapse" role="navigation" eventKey={0} id="top">
{links}
</Nav>
</Navbar>
);
},
renderNavItem(linkName) {
let link = NAV_LINKS[linkName];
return (
<li className={this.props.activePage === linkName ? 'active' : null} key={linkName}>
<Link to={link.link}>{link.title}</Link>
</li>
);
}
});
export default NavMain;
|
src/admin/BedChart.js | ocelotconsulting/global-hack-6 | /* eslint no-new: "off" */
import React from 'react'
import { v4 } from 'uuid'
import ChartKey from './ChartKey'
import Row from 'react-bootstrap/lib/Row'
import Col from 'react-bootstrap/lib/Col'
import ChartistGraph from 'react-chartist'
export default class BedChart extends React.Component {
constructor(props) {
super(props)
this.state = {
id: `chart_${v4().replace(/-/g, '')}`
}
}
render() {
const { total, available, pending } = this.props
const data = {
series: [total - available - pending, pending, available]
}
const options = {
startAngle: 270,
showLabel: false
}
return (
<div className='summary-chart'>
<Row>
<Col md={3}>
<ChartKey/>
</Col>
<Col md={3}>
<ChartistGraph data={data} options={options} type='Pie'/>
</Col>
</Row>
</div>
)
}
}
|
src/components/auth/accountpage.js | Hommasoft/wappuapp-adminpanel | import React, { Component } from 'react';
import { Field, reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import * as Auth from '../../actions/auth';
class AccountPage extends Component {
handleFormSubmit({ newpassword, oldpassword }) {
this.props.changepassword({ newpassword, oldpassword });
}
renderError() {
if (this.props.errorMessage) {
console.log(this.props.errorMessage);
return <div className="alert alert-danger">{this.props.errorMessage}</div>;
}
}
renderField({ input, label, type, meta: { error } }) {
return (
<div>
<label>{label}</label>
<div>
<input className="form-control" {...input} placeholder={label} type={type} />
{error && <span className="text-danger">{error}</span>}
</div>
</div>
);
}
render() {
const { handleSubmit } = this.props;
var accountType = localStorage.getItem('admin');
if (accountType === 'true') {
accountType = 'admin';
} else {
accountType = 'moderator';
}
return (
<div>
<div>
<h3>User details</h3>
Email: {localStorage.getItem('email')} <br />
Account type: {accountType} <br />
Activated: {localStorage.getItem('activated')} <br />
</div>
<br />
<div align="center">
Change password
<form onSubmit={handleSubmit(this.handleFormSubmit.bind(this))}>
<fieldset className="form-group">
<Field
name="oldpassword"
label="Old password"
component={this.renderField}
type="password"
/>
</fieldset>
<br />
<fieldset className="form-group">
<Field
name="newpassword"
label="New password"
component={this.renderField}
type="password"
/>
</fieldset>
<fieldset className="form-group">
<Field
name="newpasswordagain"
label="New password again"
component={this.renderField}
type="password"
/>
</fieldset>
{this.renderError()}
<button action="submit" className="btn btn-primary">
Change password
</button>
</form>
</div>
</div>
);
}
}
const validate = values => {
const errors = {};
//if (values.newpassword && values.newpassword.length < 8) {
// errors.newpassword = 'Password has to be atleast 8 characters long'
//}
if (values.newpassword && values.oldpassword === values.newpassword) {
errors.newpassword = 'New password can not be the same as old one';
}
if (values.newpasswordagain && values.newpassword !== values.newpasswordagain) {
errors.newpasswordagain = 'New passwords need to match';
}
return errors;
};
const mapStateToProps = state => {
return { errorMessage: state.auth.error };
};
export default reduxForm({
form: 'auth',
validate
})(connect(mapStateToProps, Auth)(AccountPage));
|
src/plugins/position/components/SpacerRow.js | joellanciaux/Griddle | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from '../../../utils/griddleConnect';
import compose from 'recompose/compose';
import mapProps from 'recompose/mapProps';
import getContext from 'recompose/getContext';
import withHandlers from 'recompose/withHandlers';
const spacerRow = compose(
getContext({
selectors: PropTypes.object,
}),
connect((state, props) => {
const { topSpacerSelector, bottomSpacerSelector } = props.selectors;
const { placement } = props;
return {
spacerHeight: placement === 'top' ? topSpacerSelector(state, props) : bottomSpacerSelector(state, props),
};
}),
mapProps(props => ({
placement: props.placement,
spacerHeight: props.spacerHeight,
}))
)(class extends Component {
static propTypes = {
placement: PropTypes.string,
spacerHeight: PropTypes.number,
}
static defaultProps = {
placement: 'top'
}
// shouldComponentUpdate(nextProps) {
// const { currentPosition: oldPosition, placement: oldPlacement } = this.props;
// const { currentPosition, placement } = nextProps;
//
// return oldPosition !== currentPosition || oldPlacement !== placement;
// }
render() {
const { placement, spacerHeight } = this.props;
let spacerRowStyle = {
height: `${spacerHeight}px`,
};
return (
<tr key={placement + '-' + spacerHeight} style={spacerRowStyle}></tr>
);
}
});
export default spacerRow;
|
node_modules/react-bootstrap/es/ModalBody.js | firdiansyah/crud-req | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'div'
};
var ModalBody = function (_React$Component) {
_inherits(ModalBody, _React$Component);
function ModalBody() {
_classCallCheck(this, ModalBody);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
ModalBody.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return ModalBody;
}(React.Component);
ModalBody.propTypes = propTypes;
ModalBody.defaultProps = defaultProps;
export default bsClass('modal-body', ModalBody); |
imports/ui/components/Routes/Authenticated.js | haraneesh/mydev | import React from 'react';
import PropTypes from 'prop-types';
import { Route, Redirect } from 'react-router-dom';
/*
const Authenticated = ({ layout: Layout, roles, authenticated, component, ...rest }) => (
<Route
{...rest}
render={props => (
authenticated ?
(<Layout
{...props}
isAdmin={roles.indexOf('admin') !== -1}
authenticated
{...rest}
>
{(React.createElement(component, { ...props, authenticated, ...rest }))}
</Layout>)
:
(<Redirect to="/about" />)
)}
/>
);
*/
const Authenticated = ({
layout: Layout, roles, authenticated, component: Component, ...rest
}) => (
<Route
{...rest}
render={(props) => (
authenticated
? (
<Layout
{...props}
isAdmin={roles.indexOf('admin') !== -1}
authenticated
{...rest}
>
<Component {...props} authenticated {...rest} roles={roles} />
</Layout>
)
: (<Redirect to="/about" />)
)}
/>
);
Authenticated.propTypes = {
routeName: PropTypes.string.isRequired,
roles: PropTypes.array.isRequired,
authenticated: PropTypes.bool.isRequired,
component: PropTypes.func.isRequired,
layout: PropTypes.node.isRequired,
};
export default Authenticated;
|
packages/mcs-lite-ui/src/DataChannelAdapter/DataChannelAdapter.example.js | MCS-Lite/mcs-lite | import React from 'react';
import styled from 'styled-components';
import { storiesOf } from '@storybook/react';
import { withInfo } from '@storybook/addon-info';
import { action } from '@storybook/addon-actions';
import DataChannelCard from '../DataChannelCard';
import DATA_CHANNELS from './API';
import DataChannelAdapter from '.';
const CardWrapper = styled.div`
display: flex;
flex-wrap: wrap;
> * {
height: initial;
padding: 8px 16px;
margin: 4px;
flex-basis: 100%;
}
> [data-width~=' half'] {
flex-grow: 1;
flex-basis: 40%;
}
`;
storiesOf('DataChannelAdapter', module).add(
'API',
withInfo({
text: `
~~~js
type Event = {
type: 'SUBMIT'|'CHANGE'|'CLEAR', // event type
id: string, // data channel id
values: { // datapoint values
value: ?string|number,
period: ?number,
},
}
type DCEventHandler = DCEvent => void
~~~
`,
inline: true,
})(() => (
<CardWrapper>
{DATA_CHANNELS.map(dataChannel => (
<DataChannelCard
key={dataChannel.id}
data-width="half"
title={dataChannel.type}
subtitle="Last data point time : 2015-06-12 12:00"
description="You can input description of controller here. You can input description of You can input description of controller here. You can input description of"
header={<a href=".">Link</a>}
>
<DataChannelAdapter
dataChannelProps={dataChannel}
eventHandler={action(
'DataChannelAdapter eventHandler(event: Event)',
)}
/>
</DataChannelCard>
))}
</CardWrapper>
)),
);
|
src/docs/components/header/HeaderExamplesDoc.js | grommet/grommet-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Header from 'grommet/components/Header';
import Title from 'grommet/components/Title';
import Search from 'grommet/components/Search';
import Menu from 'grommet/components/Menu';
import Box from 'grommet/components/Box';
import Anchor from 'grommet/components/Anchor';
import ActionsIcon from 'grommet/components/icons/base/Actions';
import InteractiveExample from '../../../components/InteractiveExample';
const PROPS_SCHEMA = {
fixed: { value: true },
float: { value: true },
size: { options: ['small', 'medium', 'large', 'xlarge'] },
splash: { value: true }
};
const CONTENTS_SCHEMA = {
title: { value: <Title>Sample Title</Title>, initial: true },
search: { value: (
<Search inline={true} fill={true} size='medium' placeHolder='Search'
dropAlign={{ right: 'right' }}/>
), initial: true },
menu: { value: (
<Menu icon={<ActionsIcon />} dropAlign={{right: 'right'}}>
<Anchor href='#' className='active'>First</Anchor>
<Anchor href='#'>Second</Anchor>
<Anchor href='#'>Third</Anchor>
</Menu>
), initial: true }
};
export default class HeaderExamplesDoc extends Component {
constructor () {
super();
this.state = { contents: {}, elementProps: {} };
}
render () {
let { contents, elementProps } = this.state;
const element = (
<Header {...elementProps}>
{contents.title}
<Box flex={true} justify='end' direction='row' responsive={false}>
{contents.search}
{contents.menu}
</Box>
</Header>
);
return (
<InteractiveExample contextLabel='Header' contextPath='/docs/header'
justify='start' align='stretch'
preamble={`import Header from 'grommet/components/Header';`}
propsSchema={PROPS_SCHEMA}
contentsSchema={CONTENTS_SCHEMA}
element={element}
onChange={(elementProps, contents) => {
this.setState({ elementProps, contents });
}} />
);
}
};
|
packages/benchmarks/src/index.js | css-components/styled-components | /* eslint-disable no-param-reassign */
/* global document */
import React from 'react';
import ReactDOM from 'react-dom';
import App from './app/App';
import impl from './impl';
import Tree from './cases/Tree';
import SierpinskiTriangle from './cases/SierpinskiTriangle';
const implementations = impl;
const packageNames = Object.keys(implementations);
const createTestBlock = fn => {
return packageNames.reduce((testSetups, packageName) => {
const { name, components, version } = implementations[packageName];
const { Component, getComponentProps, sampleCount, Provider, benchmarkType } = fn(components);
testSetups[packageName] = {
Component,
getComponentProps,
sampleCount,
Provider,
benchmarkType,
version,
name,
};
return testSetups;
}, {});
};
const tests = {
'Mount deep tree': createTestBlock(components => ({
benchmarkType: 'mount',
Component: Tree,
getComponentProps: () => ({ breadth: 2, components, depth: 7, id: 0, wrap: 1 }),
Provider: components.Provider,
sampleCount: 500,
})),
'Mount wide tree': createTestBlock(components => ({
benchmarkType: 'mount',
Component: Tree,
getComponentProps: () => ({ breadth: 6, components, depth: 3, id: 0, wrap: 2 }),
Provider: components.Provider,
sampleCount: 500,
})),
'Update dynamic styles': createTestBlock(components => ({
benchmarkType: 'update',
Component: SierpinskiTriangle,
getComponentProps: ({ cycle }) => {
return { components, s: 200, renderCount: cycle, x: 0, y: 0 };
},
Provider: components.Provider,
sampleCount: 1000,
})),
};
ReactDOM.render(<App tests={tests} />, document.querySelector('.root'));
|
app/routes/routes/PaySuccess/components/PaySuccess.view.js | bugknightyyp/leyizhu | import React from 'react'
import {observer} from 'mobx-react'
import {Route, Link} from 'react-router-dom'
import {IMAGE_DIR, TOKEN, GET_HOTEL_INFO, RESPONSE_CODE_SUCCESS} from 'macros'
import {setParamsToURL, dateToZh} from 'utils'
import './paySuccess.less'
export default observer(
(props) => (
<div className="pay-success-container">
<div className="hotel-info">
<i className="iconfont icon-success" />
<h1>支付成功</h1>
<div className="hotel-name">{props.store.hotelName}</div>
<div className="hotel-address">{`酒店地址:${props.store.address}`}</div>
<Link to={{pathname: `${props.match.url}/map`, search: `?longitude=${props.store.longitude}&latitude=${props.store.latitude}`}} className="go-hotel">前往酒店</Link>
</div>
<div className="how-to-checking">
<h6>如何入住</h6>
<p> 1.前往酒店,并找到自助入住登记机<br />
2.在自助机登记证件,并进行脸部识别<br />
3.收取入住短信通知(含房间号和密码)<br />
*房门还可通过网络开锁功能开启</p>
</div>
<div className="safety-tips">
<i className="iconfont icon-tixing" />根据公安部法律规定,住宿需登记身份证信息
</div>
</div>
)
)
|
src/components/__specs__/TabBar.spec.js | yogakurniawan/phoney-mobile | /*eslint-disable max-nested-callbacks*/
import React from 'react';
import {shallow} from 'enzyme';
import {hasStyles} from '../../../test/assertions';
import TabBar from '../TabBar';
import TabBarButton from '../TabBarButton';
const tabs = {
index: 0,
routes: [
{key: 'tab-1', title: 'Tab 1'},
{key: 'tab-2', title: 'Tab 2'},
{key: 'tab-3', title: 'Tab 3'}
]
};
describe('<TabBar />', () => {
it('should render a <TabBarButton> for each passed tab', () => {
const wrapper = shallow(
<TabBar tabs={tabs} height={0} currentTabIndex={1} switchTab={() => null} />
);
// check that count, order and labels match
expect(wrapper.find(TabBarButton).length).toBe(tabs.routes.length);
expect(wrapper.find(TabBarButton).map(e => e.props().text))
.toEqual(['Tab 1', 'Tab 2', 'Tab 3']);
});
it('should mark current tab as selected', () => {
const wrapper = shallow(
<TabBar tabs={tabs} height={0} currentTabIndex={1} switchTab={() => null} />
);
expect(wrapper.find(TabBarButton).map(e => e.props().isSelected))
.toEqual([false, true, false]);
});
it('should apply custom height to the root element', () => {
const wrapper = shallow(
<TabBar tabs={tabs} height={123} currentTabIndex={1} switchTab={() => null} />
);
expect(hasStyles(wrapper.first(), {height: 123})).toBe(true);
});
});
|
src/input/__tests__/TextField.js | material-native/material-native | 'use strict';
import React from 'react';
import MaterialTheme from '../../styles/MaterialTheme';
import ThemeProvider from '../../styles/ThemeProvider';
import TextField from '../TextField';
import ReactTestRenderer from 'react-test-renderer';
import ToJSX from 'react-element-to-jsx-string';
const theme = new MaterialTheme({});
/* eslint-disable react/jsx-key, react-native/no-inline-styles */
const snapshotTests = [
<TextField />,
<TextField label='Label' />,
<TextField label='Label' value='123' />,
<TextField label='Label' multiline />,
<TextField label='Label' disabled />,
<TextField label='Label' light />,
<TextField label='Label' dark />,
<TextField label='Label' dense />,
<TextField label='Label' prefix='$' />,
<TextField label='Label' suffix='kg' />,
<TextField label='Label' error='Error' />,
<TextField label='Label' value='123' maxLength={3} />,
<TextField label='Label' softMaxLength={3} />,
<TextField label='Label' value='123456' softMaxLength={3} />,
<TextField label='Label' style={{width: 100}} />,
<TextField label='Label' inputStyle={{width: 100}} />,
<TextField label='Label' tintColor='#123456' />,
<TextField label='Label' errorColor='#123456' error='Error' />,
<TextField label='Label' placeholder='Placeholder' placeholderTextColor='#123456' />
];
/* eslint-enable react/jsx-key, react-native/no-inline-styles */
for ( const root of snapshotTests ) {
test(ToJSX(root, {maxInlineAttributesLineLength: Infinity}), () => {
const host = ReactTestRenderer.create(
<ThemeProvider theme={theme}>
{root}
</ThemeProvider>
);
expect(host.toJSON()).toMatchSnapshot();
});
}
|
frontend/src/Factura/FacturaTable.js | GAumala/Facturacion | import React from 'react';
import {
Table,
TableBody,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn
} from 'material-ui/Table';
import TextField from 'material-ui/TextField';
import IconButton from 'material-ui/IconButton';
import Delete from 'material-ui/svg-icons/action/delete';
import Math from 'facturacion_common/src/Math.js';
const black54p = '#757575';
const noPaddingStyle = { padding: '0px' };
const RenderTableHeader = props => {
let regSanCol = (
<TableHeaderColumn width={80} style={noPaddingStyle}>
Reg. Santario
</TableHeaderColumn>
);
let loteCol = (
<TableHeaderColumn width={60} style={noPaddingStyle}>
Lote
</TableHeaderColumn>
);
let fechaExpCol = (
<TableHeaderColumn width={70} style={noPaddingStyle}>
Fecha Exp.
</TableHeaderColumn>
);
if (props.isExamen) {
//ocultar columnas que no se usan en examenes
regSanCol = null;
loteCol = null;
fechaExpCol = null;
}
return (
<TableHeader displaySelectAll={false} adjustForCheckbox={false}>
<TableRow>
<TableHeaderColumn width={40} style={noPaddingStyle}>
#
</TableHeaderColumn>
{regSanCol}
<TableHeaderColumn width={170} style={noPaddingStyle}>
Nombre
</TableHeaderColumn>
{loteCol}
<TableHeaderColumn width={40} style={noPaddingStyle}>
Cant.
</TableHeaderColumn>
{fechaExpCol}
<TableHeaderColumn width={60} style={noPaddingStyle}>
Precio
</TableHeaderColumn>
<TableHeaderColumn width={50} style={noPaddingStyle}>
Importe
</TableHeaderColumn>
<TableHeaderColumn width={30} style={noPaddingStyle} />
</TableRow>
</TableHeader>
);
};
export default class FacturaTable extends React.Component {
renderRow = (facturable, i) => {
const { isExamen, onFacturableChanged, onFacturableDeleted } = this.props;
let regSanCol = (
<TableRowColumn width={80} style={noPaddingStyle}>
{facturable.codigo}
</TableRowColumn>
);
let loteCol = (
<TableRowColumn width={60} style={noPaddingStyle}>
<TextField
value={facturable.lote}
style={{ width: '50px' }}
name={'lote'}
inputStyle={{ textAlign: 'right', fontSize: '13px' }}
onChange={event => {
onFacturableChanged(i, 'lote', event.target.value);
}}
/>
</TableRowColumn>
);
let fechaExpCol = (
<TableRowColumn width={70} style={noPaddingStyle}>
<TextField
value={facturable.fechaExp}
hintText={'expiración'}
style={{ width: '70px', fontSize: '13px' }}
onChange={(event, date) => {
onFacturableChanged(i, 'fechaExp', date);
}}
/>
</TableRowColumn>
);
if (isExamen) {
//ocultar columnas que no se usan en examenes
regSanCol = null;
loteCol = null;
fechaExpCol = null;
}
return (
<TableRow key={i}>
<TableRowColumn width={40} style={noPaddingStyle}>
{i + 1}
</TableRowColumn>
{regSanCol}
<TableRowColumn width={170} style={noPaddingStyle}>
{facturable.nombre}
</TableRowColumn>
{loteCol}
<TableRowColumn width={40} style={noPaddingStyle}>
<TextField
style={{ width: '28px' }}
value={facturable.countText}
name={'count'}
inputStyle={{ textAlign: 'right', fontSize: '13px' }}
onChange={event => {
onFacturableChanged(i, 'count', event.target.value);
}}
/>
</TableRowColumn>
{fechaExpCol}
<TableRowColumn width={60} style={noPaddingStyle}>
${' '}
<TextField
style={{ width: '50px' }}
name={'precio'}
value={facturable.precioVentaText}
onChange={event => {
onFacturableChanged(i, 'precioVenta', event.target.value);
}}
inputStyle={{ fontSize: '13px' }}
/>
</TableRowColumn>
<TableRowColumn
width={50}
style={{ padding: '0px', textOverflow: 'clip' }}
>
<span style={{ marginRight: '34px' }}>
$ {Math.calcularImporteFacturable(facturable)}
</span>
</TableRowColumn>
<TableRowColumn
width={30}
style={{ padding: '0px', textAlign: 'right' }}
>
<IconButton onTouchTap={() => onFacturableDeleted(i)}>
<Delete color={black54p} />
</IconButton>
</TableRowColumn>
</TableRow>
);
};
render() {
return (
<Table height={'200px'} selectable={false}>
{RenderTableHeader(this.props)}
<TableBody displayRowCheckbox={false}>
{this.props.items.map(this.renderRow)}
</TableBody>
</Table>
);
}
}
FacturaTable.propTypes = {
isExamen: React.PropTypes.bool,
items: React.PropTypes.array.isRequired,
onFacturableChanged: React.PropTypes.func.isRequired,
onFacturableDeleted: React.PropTypes.func.isRequired
};
FacturaTable.defaultProps = {
isExamen: false
};
|
lib/routes.js | codevlabs/filepizza | import React from 'react'
import { Route, DefaultRoute, NotFoundRoute, RouteHandler } from 'react-router'
import App from './components/App'
import DownloadPage from './components/DownloadPage'
import UploadPage from './components/UploadPage'
import ErrorPage from './components/ErrorPage'
export default (
<Route handler={App}>
<DefaultRoute handler={UploadPage} />
<Route name="download" path="/:a-:b-:c-:d" handler={DownloadPage} />
<Route name="error" path="error" handler={ErrorPage} />
<NotFoundRoute handler={ErrorPage} />
</Route>
)
|
2016-04-declarative-charts/assets/highcharts.js | rosko/slides | import React from 'react';
import IframeExample from '../components/IframeExample';
function Highcharts() {
return <IframeExample html={`<html><head>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://code.highcharts.com/highcharts.js"></script>
<script src="https://code.highcharts.com/modules/exporting.js"></script>
</head><body>
<div id="container" style="width: 100vw; height: 100vh; margin: 0 auto"></div>
<script>
${require('raw!./highcharts.example')}
</script>
</body></html>`}/>;
}
Highcharts.displayName = 'Highcharts';
module.exports = Highcharts;
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | Rmutek/rmutek.github.io | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
packages/ui/src/components/Sprinkle.stories.js | dino-dna/donut | import React from 'react'
import { storiesOf } from '@storybook/react'
import Sprinkle from './Sprinkle'
export default storiesOf('Sprinkle', module)
.add('basic', () => {
return (
<svg viewport='0 0 60 60' width='60' height='60'>
<Sprinkle />
</svg>
)
})
.add('rotated', () => {
return (
<svg viewport='0 0 60 60'>
<Sprinkle deg={90} />
</svg>
)
})
.add('rotated & translated', () => {
return (
<svg viewport='0 0 60 60'>
<g style={{ transform: `translate(${25}px, ${25}px)` }}>
<Sprinkle deg={45} />
</g>
</svg>
)
})
|
actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js | JeeLiu/actor-platform | import _ from 'lodash';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import DialogActionCreators from 'actions/DialogActionCreators';
import LoginStore from 'stores/LoginStore';
import AvatarItem from 'components/common/AvatarItem.react';
const GroupProfileMembers = React.createClass({
propTypes: {
groupId: React.PropTypes.number,
members: React.PropTypes.array.isRequired
},
mixins: [PureRenderMixin],
onClick(id) {
DialogActionCreators.selectDialogPeerUser(id);
},
onKickMemberClick(groupId, userId) {
DialogActionCreators.kickMember(groupId, userId);
},
render() {
let groupId = this.props.groupId;
let members = this.props.members;
let myId = LoginStore.getMyId();
let membersList = _.map(members, (member, index) => {
let controls;
let canKick = member.canKick;
if (canKick === true && member.peerInfo.peer.id !== myId) {
controls = (
<div className="controls pull-right">
<a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a>
</div>
);
}
return (
<li className="profile__list__item row" key={index}>
<a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}>
<AvatarItem image={member.peerInfo.avatar}
placeholder={member.peerInfo.placeholder}
size="small"
title={member.peerInfo.title}/>
</a>
<div className="col-xs">
<a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}>
<span className="title">
{member.peerInfo.title}
</span>
</a>
{controls}
</div>
</li>
);
}, this);
return (
<ul className="profile__list profile__list--members">
<li className="profile__list__item profile__list__item--header">{members.length} members</li>
{membersList}
</ul>
);
}
});
export default GroupProfileMembers;
|
src/DataTables/DataTablesTableBody.js | hyojin/material-ui-datatables | import React from 'react';
import PropTypes from 'prop-types';
import {TableBody} from 'material-ui/Table';
import ClickAwayListener from 'material-ui/internal/ClickAwayListener';
class DataTablesTableBody extends TableBody {
static muiName = 'TableBody';
static propTypes = {
/**
* @ignore
* Set to true to indicate that all rows should be selected.
*/
allRowsSelected: PropTypes.bool,
/**
* Children passed to table body.
*/
children: PropTypes.node,
/**
* The css class name of the root element.
*/
className: PropTypes.string,
/**
* Controls whether or not to deselect all selected
* rows after clicking outside the table.
*/
deselectOnClickaway: PropTypes.bool,
/**
* Controls the display of the row checkbox. The default value is true.
*/
displayRowCheckbox: PropTypes.bool,
/**
* @ignore
* If true, multiple table rows can be selected.
* CTRL/CMD+Click and SHIFT+Click are valid actions.
* The default value is false.
*/
multiSelectable: PropTypes.bool,
/**
* @ignore
* Callback function for when a cell is clicked.
*/
onCellClick: PropTypes.func,
/**
* @ignore
* Customized handler
* Callback function for when a cell is double clicked.
*/
onCellDoubleClick: PropTypes.func,
/**
* @ignore
* Called when a table cell is hovered. rowNumber
* is the row number of the hovered row and columnId
* is the column number or the column key of the cell.
*/
onCellHover: PropTypes.func,
/**
* @ignore
* Called when a table cell is no longer hovered.
* rowNumber is the row number of the row and columnId
* is the column number or the column key of the cell.
*/
onCellHoverExit: PropTypes.func,
/**
* @ignore
* Called when a table row is hovered.
* rowNumber is the row number of the hovered row.
*/
onRowHover: PropTypes.func,
/**
* @ignore
* Called when a table row is no longer
* hovered. rowNumber is the row number of the row
* that is no longer hovered.
*/
onRowHoverExit: PropTypes.func,
/**
* @ignore
* Called when a row is selected. selectedRows is an
* array of all row selections. IF all rows have been selected,
* the string "all" will be returned instead to indicate that
* all rows have been selected.
*/
onRowSelection: PropTypes.func,
/**
* Controls whether or not the rows are pre-scanned to determine
* initial state. If your table has a large number of rows and
* you are experiencing a delay in rendering, turn off this property.
*/
preScanRows: PropTypes.bool,
/**
* @ignore
* If true, table rows can be selected. If multiple
* row selection is desired, enable multiSelectable.
* The default value is true.
*/
selectable: PropTypes.bool,
/**
* If true, table rows will be highlighted when
* the cursor is hovering over the row. The default
* value is false.
*/
showRowHover: PropTypes.bool,
/**
* If true, every other table row starting
* with the first row will be striped. The default value is false.
*/
stripedRows: PropTypes.bool,
/**
* Override the inline-styles of the root element.
*/
style: PropTypes.object,
};
createRows() {
const numChildren = React.Children.count(this.props.children);
let rowNumber = 0;
const handlers = {
onCellClick: this.onCellClick,
onCellDoubleClick: this.onCellDoubleClick,
onCellHover: this.onCellHover,
onCellHoverExit: this.onCellHoverExit,
onRowHover: this.onRowHover,
onRowHoverExit: this.onRowHoverExit,
onRowClick: this.onRowClick,
};
return React.Children.map(this.props.children, (child) => {
if (React.isValidElement(child)) {
const props = {
hoverable: this.props.showRowHover,
selected: this.isRowSelected(rowNumber),
striped: this.props.stripedRows && (rowNumber % 2 === 0),
rowNumber: rowNumber++,
};
if (rowNumber === numChildren) {
props.displayBorder = false;
}
const children = [
this.createRowCheckboxColumn(props),
];
React.Children.forEach(child.props.children, (child) => {
children.push(child);
});
return React.cloneElement(child, {...props, ...handlers}, children);
}
});
}
onCellDoubleClick = (event, rowNumber, columnNumber) => {
event.stopPropagation();
if (this.props.onCellDoubleClick) {
this.props.onCellDoubleClick(rowNumber, this.getColumnId(columnNumber), event);
}
};
render() {
const {
style,
allRowsSelected, // eslint-disable-line no-unused-vars
multiSelectable, // eslint-disable-line no-unused-vars
onCellClick, // eslint-disable-line no-unused-vars
onCellDoubleClick, // eslint-disable-line no-unused-vars
onCellHover, // eslint-disable-line no-unused-vars
onCellHoverExit, // eslint-disable-line no-unused-vars
onRowHover, // eslint-disable-line no-unused-vars
onRowHoverExit, // eslint-disable-line no-unused-vars
onRowSelection, // eslint-disable-line no-unused-vars
selectable, // eslint-disable-line no-unused-vars
deselectOnClickaway, // eslint-disable-line no-unused-vars
showRowHover, // eslint-disable-line no-unused-vars
stripedRows, // eslint-disable-line no-unused-vars
displayRowCheckbox, // eslint-disable-line no-unused-vars
preScanRows, // eslint-disable-line no-unused-vars
...other
} = this.props;
const {prepareStyles} = this.context.muiTheme;
return (
<ClickAwayListener onClickAway={this.handleClickAway}>
<tbody style={prepareStyles(Object.assign({}, style))} {...other}>
{this.createRows()}
</tbody>
</ClickAwayListener>
);
}
}
export default DataTablesTableBody;
|
src/svg-icons/action/settings-backup-restore.js | mit-cml/iot-website-source | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsBackupRestore = (props) => (
<SvgIcon {...props}>
<path d="M14 12c0-1.1-.9-2-2-2s-2 .9-2 2 .9 2 2 2 2-.9 2-2zm-2-9c-4.97 0-9 4.03-9 9H0l4 4 4-4H5c0-3.87 3.13-7 7-7s7 3.13 7 7-3.13 7-7 7c-1.51 0-2.91-.49-4.06-1.3l-1.42 1.44C8.04 20.3 9.94 21 12 21c4.97 0 9-4.03 9-9s-4.03-9-9-9z"/>
</SvgIcon>
);
ActionSettingsBackupRestore = pure(ActionSettingsBackupRestore);
ActionSettingsBackupRestore.displayName = 'ActionSettingsBackupRestore';
ActionSettingsBackupRestore.muiName = 'SvgIcon';
export default ActionSettingsBackupRestore;
|
server/middleware/reactApplication/index.js | dariobanfi/react-avocado-starter | import React from 'react';
import Helmet from 'react-helmet';
import { renderToString, renderToStaticMarkup } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { ServerStyleSheet } from 'styled-components';
import config from '../../../config';
import ServerHTML from './ServerHTML';
import Application from '../../../app/components/Application';
export default function reactApplicationMiddleware(request, response) {
// Ensure a nonce has been provided to us.
// See the server/middleware/security.js for more info.
if (typeof response.locals.nonce !== 'string') {
throw new Error('A "nonce" value has not been attached to the response');
}
const nonce = response.locals.nonce;
// It's possible to disable SSR, which can be useful in development mode.
// In this case traditional client side only rendering will occur.
if (config('disableSSR')) {
if (process.env.BUILD_FLAG_IS_DEV === 'true') {
// eslint-disable-next-line no-console
console.log('==> Handling react route without SSR');
}
// SSR is disabled so we will return an "empty" html page and
// rely on the client to initialize and render the react application.
const html = renderToStaticMarkup(<ServerHTML nonce={nonce} />);
response.status(200).send(`<!DOCTYPE html>${html}`);
return;
}
// Create a context for <StaticRouter>, which will allow us to
// query for the results of the render.
const reactRouterContext = {};
// Declare our React application.
const app = (
<StaticRouter location={request.url} context={reactRouterContext}>
<Application />
</StaticRouter>
);
const appString = renderToString(app);
// Generate the html response.
const html = renderToStaticMarkup(
<ServerHTML
reactAppString={appString}
nonce={nonce}
sheet={new ServerStyleSheet()}
helmet={Helmet.rewind()}
/>,
);
// Check if the router context contains a redirect, if so we need to set
// the specific status and redirect header and end the response.
if (reactRouterContext.url) {
response.status(302).setHeader('Location', reactRouterContext.url);
response.end();
return;
}
response
.status(
reactRouterContext.missed ? 404 : 200,
)
.send(`<!DOCTYPE html>${html}`);
}
|
src/components/Feedback/Feedback.js | seriflafont/react-starter-kit | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react';
import styles from './Feedback.css';
import withStyles from '../../decorators/withStyles';
@withStyles(styles)
class Feedback extends Component {
render() {
return (
<div className="Feedback">
<div className="Feedback-container">
<a className="Feedback-link" href="https://gitter.im/kriasoft/react-starter-kit">Ask a question</a>
<span className="Feedback-spacer">|</span>
<a className="Feedback-link" href="https://github.com/kriasoft/react-starter-kit/issues/new">Report an issue</a>
</div>
</div>
);
}
}
export default Feedback;
|
docs/app/Examples/modules/Checkbox/Types/CheckboxExampleToggle.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Checkbox } from 'semantic-ui-react'
const CheckboxExampleToggle = () => (
<Checkbox toggle />
)
export default CheckboxExampleToggle
|
docs/app/Examples/views/Feed/Content/FeedExampleImageLabelShorthand.js | shengnian/shengnian-ui-react | import React from 'react'
import { Feed } from 'shengnian-ui-react'
const FeedExampleImageLabelShorthand = () => (
<Feed>
<Feed.Event
image='/assets/images/avatar/small/elliot.jpg'
content='You added Elliot Fu to the group Coworkers'
/>
<Feed.Event>
<Feed.Label image='/assets/images/avatar/small/elliot.jpg' />
<Feed.Content content='You added Elliot Fu to the group Coworkers' />
</Feed.Event>
</Feed>
)
export default FeedExampleImageLabelShorthand
|
internals/templates/app.js | Rohitbels/KolheshwariIndustries | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
/* eslint-disable import/no-unresolved, import/extensions */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(System.import('intl'));
}))
.then(() => Promise.all([
System.import('intl/locale-data/jsonp/de.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
|
app/navigation.js | david1820/react-native-boilerplate | import React from 'react';
import PropTypes from 'prop-types';
import { StyleSheet, StatusBar, View } from 'react-native';
import { connect } from 'react-redux';
import { addNavigationHelpers } from 'react-navigation';
import AppNavigator from './routes';
const AppWithNavigationState = ({ dispatch, nav }) => (
<View style={styles.container}>
<StatusBar
barStyle="dark-content"
/>
<AppNavigator navigation={addNavigationHelpers({ dispatch, state: nav })} />
</View>
);
AppWithNavigationState.propTypes = {
dispatch: PropTypes.func.isRequired,
nav: PropTypes.object.isRequired,
};
const mapStateToProps = state => ({
nav: state.nav,
});
const styles = StyleSheet.create({
container: {
flex: 1,
},
});
export default connect(mapStateToProps)(AppWithNavigationState);
|
packages/slate-html-serializer/benchmark/html-serializer/serialize.js | 6174/slate | /** @jsx h */
/* eslint-disable react/jsx-key */
import Html from '../..'
import React from 'react'
import h from '../../test/helpers/h'
import parse5 from 'parse5' // eslint-disable-line import/no-extraneous-dependencies
const html = new Html({
parseHtml: parse5.parseFragment,
rules: [
{
serialize(obj, children) {
switch (obj.kind) {
case 'block': {
switch (obj.type) {
case 'paragraph': return React.createElement('p', {}, children)
case 'quote': return React.createElement('blockquote', {}, children)
}
}
case 'mark': {
switch (obj.type) {
case 'bold': return React.createElement('strong', {}, children)
case 'italic': return React.createElement('em', {}, children)
}
}
}
}
}
]
})
export default function (state) {
html.serialize(state)
}
export const input = (
<state>
<document>
{Array.from(Array(10)).map(() => (
<quote>
<paragraph>
This is editable <b>rich</b> text, <i>much</i> better than a textarea!
</paragraph>
</quote>
))}
</document>
</state>
)
|
src/svg-icons/maps/edit-location.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsEditLocation = (props) => (
<SvgIcon {...props}>
<path d="M12 2C8.14 2 5 5.14 5 9c0 5.25 7 13 7 13s7-7.75 7-13c0-3.86-3.14-7-7-7zm-1.56 10H9v-1.44l3.35-3.34 1.43 1.43L10.44 12zm4.45-4.45l-.7.7-1.44-1.44.7-.7c.15-.15.39-.15.54 0l.9.9c.15.15.15.39 0 .54z"/>
</SvgIcon>
);
MapsEditLocation = pure(MapsEditLocation);
MapsEditLocation.displayName = 'MapsEditLocation';
export default MapsEditLocation;
|
docs/app/Examples/elements/List/Variations/ListExampleRelaxed.js | shengnian/shengnian-ui-react | import React from 'react'
import { Image, List } from 'shengnian-ui-react'
const ListExampleRelaxed = () => (
<List relaxed>
<List.Item>
<Image avatar src='/assets/images/avatar/small/daniel.jpg' />
<List.Content>
<List.Header as='a'>Daniel Louise</List.Header>
<List.Description>Last seen watching <a><b>Arrested Development</b></a> just now.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='/assets/images/avatar/small/stevie.jpg' />
<List.Content>
<List.Header as='a'>Stevie Feliciano</List.Header>
<List.Description>Last seen watching <a><b>Bob's Burgers</b></a> 10 hours ago.</List.Description>
</List.Content>
</List.Item>
<List.Item>
<Image avatar src='/assets/images/avatar/small/elliot.jpg' />
<List.Content>
<List.Header as='a'>Elliot Fu</List.Header>
<List.Description>Last seen watching <a><b>The Godfather Part 2</b></a> yesterday.</List.Description>
</List.Content>
</List.Item>
</List>
)
export default ListExampleRelaxed
|
src/useScroll.js | taion/react-router-scroll | import React from 'react';
import ScrollBehavior from 'scroll-behavior';
import ScrollBehaviorContext from './ScrollBehaviorContext';
function defaultCreateScrollBehavior(config) {
return new ScrollBehavior(config);
}
export default function useScroll(shouldUpdateScrollOrConfig) {
let shouldUpdateScroll;
let createScrollBehavior;
if (
!shouldUpdateScrollOrConfig ||
typeof shouldUpdateScrollOrConfig === 'function'
) {
shouldUpdateScroll = shouldUpdateScrollOrConfig;
createScrollBehavior = defaultCreateScrollBehavior;
} else {
({
shouldUpdateScroll,
createScrollBehavior = defaultCreateScrollBehavior,
} = shouldUpdateScrollOrConfig);
}
return {
renderRouterContext: (child, props) => (
<ScrollBehaviorContext
shouldUpdateScroll={shouldUpdateScroll}
createScrollBehavior={createScrollBehavior}
routerProps={props}
>
{child}
</ScrollBehaviorContext>
),
};
}
|
src/subheader-win.js | danielmoll/component-win-articlepage | import ArticleSubheaderContainer from '@economist/component-articletemplate/lib/subheader';
import React from 'react';
import { defaultGenerateClassNameList } from '@economist/component-variantify';
const extendedSubheaderItemClasses = [
'margin-l-1',
'gutter-l',
];
export default function WinSubheader({
generateClassNameList = defaultGenerateClassNameList,
sectionName,
byline,
publishDate,
}) {
return (
<ArticleSubheaderContainer generateClassNameList={generateClassNameList}>
<h2
itemProp="byline"
className={[
...generateClassNameList('article-template__byline'),
...extendedSubheaderItemClasses,
].join(' ')}
>
{byline}
</h2>
<time
itemProp="publishDate"
dateTime={publishDate.raw}
className={[
...generateClassNameList('article-template__pubdate'),
...extendedSubheaderItemClasses,
].join(' ')}
>
{publishDate.formatted}
</time>
<h2
itemProp="section"
className={[
...generateClassNameList('article-template__section-name'),
...extendedSubheaderItemClasses,
].join(' ')}
>
{sectionName}
</h2>
</ArticleSubheaderContainer>
);
}
if (process.env.NODE_ENV !== 'production') {
WinSubheader.propTypes = {
generateClassNameList: React.PropTypes.func,
sectionName: React.PropTypes.string,
byline: React.PropTypes.string,
publishDate: React.PropTypes.shape({
raw: React.PropTypes.string,
formatted: React.PropTypes.string,
}),
};
}
|
src/pages/generic.js | pascalwhoop/pascalwhoop.github.io | import React from 'react'
import Helmet from 'react-helmet'
import Layout from '../components/layout'
import pic11 from '../assets/images/pic11.jpg'
const Generic = (props) => (
<Layout>
<Helmet>
<title>Generic - Forty by HTML5 UP</title>
<meta name="description" content="Generic Page" />
</Helmet>
<div id="main" className="alt">
<section id="one">
<div className="inner">
<header className="major">
<h1>Generic</h1>
</header>
<span className="image main"><img src={pic11} alt="" /></span>
<p>Donec eget ex magna. Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque venenatis dolor imperdiet dolor mattis sagittis. Praesent rutrum sem diam, vitae egestas enim auctor sit amet. Pellentesque leo mauris, consectetur id ipsum sit amet, fergiat. Pellentesque in mi eu massa lacinia malesuada et a elit. Donec urna ex, lacinia in purus ac, pretium pulvinar mauris. Curabitur sapien risus, commodo eget turpis at, elementum convallis elit. Pellentesque enim turpis, hendrerit.</p>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Duis dapibus rutrum facilisis. Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Etiam tristique libero eu nibh porttitor fermentum. Nullam venenatis erat id vehicula viverra. Nunc ultrices eros ut ultricies condimentum. Mauris risus lacus, blandit sit amet venenatis non, bibendum vitae dolor. Nunc lorem mauris, fringilla in aliquam at, euismod in lectus. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. In non lorem sit amet elit placerat maximus. Pellentesque aliquam maximus risus, vel sed vehicula.</p>
<p>Interdum et malesuada fames ac ante ipsum primis in faucibus. Pellentesque venenatis dolor imperdiet dolor mattis sagittis. Praesent rutrum sem diam, vitae egestas enim auctor sit amet. Pellentesque leo mauris, consectetur id ipsum sit amet, fersapien risus, commodo eget turpis at, elementum convallis elit. Pellentesque enim turpis, hendrerit tristique lorem ipsum dolor.</p>
</div>
</section>
</div>
</Layout>
)
export default Generic |
components/Session.js | sunday-school/sundayschool.rocks | import React from 'react'
import MD from './MD'
import Header from './Header'
import SessionTitle from './SessionTitle'
const Session = (session) =>
<div>
<Header><SessionTitle {...session} /></Header>
<h2>Agenda</h2>
{MD(session.agenda)}
</div>
export default Session
|
examples/huge-apps/routes/Course/routes/Announcements/components/Announcements.js | Jastrzebowski/react-router | import React from 'react';
class Announcements extends React.Component {
render () {
return (
<div>
<h3>Announcements</h3>
{this.props.children || <p>Choose an announcement from the sidebar.</p>}
</div>
);
}
}
export default Announcements;
|
packages/site/pages/_document.js | InventingWithMonster/redshift | import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { ServerStyleSheet } from 'styled-components';
import Analytics from '~/templates/global/Analytics';
export default class PageTemplate extends Document {
render() {
const stylesheet = new ServerStyleSheet();
const main = stylesheet.collectStyles(<Main />);
const styleTags = stylesheet.getStyleElement();
return (
<html lang="en">
<Head>
<meta charSet="UTF-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
<meta name="og:locale" property="og:locale" content="en_US" />
<link href="https://fonts.googleapis.com/css?family=Inconsolata:400|PT+Sans:400,700" rel="stylesheet" />
<link rel="icon" type="image/png" sizes="32x32" href="/images/favicon-32x32.png" />
<link rel="icon" type="image/png" sizes="16x16" href="/images/favicon-16x16.png" />
<meta name="twitter:card" content="summary" />
<meta name="twitter:site" content="@popmotionjs" />
<link rel="shortcut icon" href="/images/favicon.ico" />
{styleTags}
<Analytics />
</Head>
<body id="root">
{main}
<NextScript />
</body>
</html>
);
}
}
|
docs/src/pages/components/menus/CustomizedMenus.js | lgollut/material-ui | import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import Menu from '@material-ui/core/Menu';
import MenuItem from '@material-ui/core/MenuItem';
import ListItemIcon from '@material-ui/core/ListItemIcon';
import ListItemText from '@material-ui/core/ListItemText';
import InboxIcon from '@material-ui/icons/MoveToInbox';
import DraftsIcon from '@material-ui/icons/Drafts';
import SendIcon from '@material-ui/icons/Send';
const StyledMenu = withStyles({
paper: {
border: '1px solid #d3d4d5',
},
})((props) => (
<Menu
elevation={0}
getContentAnchorEl={null}
anchorOrigin={{
vertical: 'bottom',
horizontal: 'center',
}}
transformOrigin={{
vertical: 'top',
horizontal: 'center',
}}
{...props}
/>
));
const StyledMenuItem = withStyles((theme) => ({
root: {
'&:focus': {
backgroundColor: theme.palette.primary.main,
'& .MuiListItemIcon-root, & .MuiListItemText-primary': {
color: theme.palette.common.white,
},
},
},
}))(MenuItem);
export default function CustomizedMenus() {
const [anchorEl, setAnchorEl] = React.useState(null);
const handleClick = (event) => {
setAnchorEl(event.currentTarget);
};
const handleClose = () => {
setAnchorEl(null);
};
return (
<div>
<Button
aria-controls="customized-menu"
aria-haspopup="true"
variant="contained"
color="primary"
onClick={handleClick}
>
Open Menu
</Button>
<StyledMenu
id="customized-menu"
anchorEl={anchorEl}
keepMounted
open={Boolean(anchorEl)}
onClose={handleClose}
>
<StyledMenuItem>
<ListItemIcon>
<SendIcon fontSize="small" />
</ListItemIcon>
<ListItemText primary="Sent mail" />
</StyledMenuItem>
<StyledMenuItem>
<ListItemIcon>
<DraftsIcon fontSize="small" />
</ListItemIcon>
<ListItemText primary="Drafts" />
</StyledMenuItem>
<StyledMenuItem>
<ListItemIcon>
<InboxIcon fontSize="small" />
</ListItemIcon>
<ListItemText primary="Inbox" />
</StyledMenuItem>
</StyledMenu>
</div>
);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.