path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/components/EditHost.js
|
OpenCollective/frontend
|
import React from 'react';
import PropTypes from 'prop-types';
import { get } from 'lodash';
import { FormattedMessage } from 'react-intl';
import withIntl from '../lib/withIntl';
import styled from 'styled-components';
import { Flex, Box } from '@rebass/grid';
import { Radio } from '@material-ui/core';
import CreateHostFormWithData from './CreateHostFormWithData';
import HostsWithData from './HostsWithData';
import CollectiveCard from './CollectiveCard';
import Link from './Link';
import InputField from './InputField';
import { formatCurrency, getQueryParams, formatDate } from '../lib/utils';
import { Button } from 'react-bootstrap';
const Option = styled.div`
h2 {
margin: 10px 0px 5px 0px;
font-weight: bold;
}
`;
const Fineprint = styled.div`
font-size: 14px;
`;
class EditHost extends React.Component {
static propTypes = {
goals: PropTypes.arrayOf(PropTypes.object),
collective: PropTypes.object.isRequired,
LoggedInUser: PropTypes.object.isRequired,
editCollectiveMutation: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.changeHost = this.changeHost.bind(this);
this.handleChange = this.handleChange.bind(this);
this.state = {
selectedOption: 'noHost',
collective: props.collective,
currency: props.collective.currency,
};
}
componentDidMount() {
const queryParams = getQueryParams();
const HostCollectiveId = Number(queryParams.CollectiveId);
if (queryParams.message === 'StripeAccountConnected') {
if (HostCollectiveId && HostCollectiveId !== get(this.props, 'collective.host.id')) {
this.changeHost({ id: HostCollectiveId });
}
}
}
handleChange(attr, value) {
this.setState({ [attr]: value });
}
async changeHost(newHost = { id: null }) {
const { collective } = this.props;
if (newHost.id === get(collective, 'host.id')) {
return;
}
await this.props.editCollectiveMutation({
id: collective.id,
HostCollectiveId: newHost.id,
});
if (!newHost.id) {
this.setState({ selectedOption: 'noHost' });
if (window.location.search.length > 0) {
window.location.replace(`/${collective.slug}/edit/host`); // make sure we clean the query params if any
}
}
}
render() {
const { LoggedInUser, collective } = this.props;
const hostMembership = get(collective, 'members', []).find(m => m.role === 'HOST');
if (get(collective, 'host.id')) {
return (
<Flex>
<Box p={1} mr={3}>
<CollectiveCard collective={collective.host} membership={hostMembership} />
</Box>
<Box>
{!collective.isActive && (
<p>
<FormattedMessage
id="editCollective.host.pending"
defaultMessage="You have applied to be hosted by {host} on {date}. Your application is being reviewed. As soon as the host accepts, you will be able to start collecting money for your collective."
values={{
host: get(collective, 'host.name'),
date: formatDate(get(hostMembership, 'createdAt'), {
day: 'numeric',
month: 'long',
year: 'numeric',
}),
}}
/>
</p>
)}
<p>
<FormattedMessage
id="editCollective.host.label"
defaultMessage="Your host is {host}. It is currently hosting {collectives, plural, one {one collective} other {{collectives} collectives}}"
values={{
collectives: get(collective, 'host.stats.collectives.hosted'),
host: get(collective, 'host.name'),
}}
/>
</p>
{collective.stats.balance > 0 && (
<p>
<FormattedMessage
id="editCollective.host.balance"
defaultMessage="Your host currently holds {balance} on behalf of your collective."
values={{
balance: formatCurrency(collective.stats.balance, collective.currency),
}}
/>
<br />
<FormattedMessage
id="editCollective.host.change.balanceNotEmpty"
defaultMessage="If you would like to change host, you first need to empty your balance by filing expenses or transfering funds to another collective."
/>
</p>
)}
{collective.stats.balance === 0 && (
<div>
<p>
<Button bsStyle="primary" type="submit" onClick={() => this.changeHost()} className="removeHostBtn">
<FormattedMessage id="editCollective.host.removeBtn" defaultMessage="Remove Host" />
</Button>
</p>
<Fineprint>
<FormattedMessage
id="editCollective.host.change.removeFirst"
defaultMessage="Once removed, you won't be able to accept donations anymore. But you will be able to select another host for your collective."
/>
</Fineprint>
</div>
)}
</Box>
</Flex>
);
}
return (
<div>
<style jsx>
{`
.suggestedHostsTitle {
display: flex;
align-items: baseline;
}
.suggestedHostsTitle :global(a) {
font-size: 1.3rem;
margin-left: 0.5rem;
}
.subtitle {
color: #666f80;
font-size: 1.5rem;
}
:global(#findHost label) {
width: 100%;
}
`}
</style>
<Option id="noHost">
<Flex>
<Box width="50px" mr={2}>
<Radio
checked={this.state.selectedOption === 'noHost'}
onChange={() => this.handleChange('selectedOption', 'noHost')}
/>
</Box>
<Box mb={4}>
<h2>
<FormattedMessage id="collective.edit.host.noHost.title" defaultMessage="No host" />
</h2>
<FormattedMessage
id="collective.edit.host.noHost.description"
defaultMessage="Without a host, you can't collect money. But you can still use the other features of Open Collective: filing expenses, posting updates, and creating events."
/>
</Box>
</Flex>
</Option>
<Option id="createHost">
<Flex>
<Box width="50px" mr={2}>
<Radio
checked={this.state.selectedOption === 'createHost'}
onChange={() => this.handleChange('selectedOption', 'createHost')}
/>
</Box>
<Box mb={4}>
<h2>
<FormattedMessage id="collective.edit.host.createHost.title" defaultMessage="Use your own host" />
</h2>
<FormattedMessage
id="collective.edit.host.createHost.description"
defaultMessage="You can create your own host as an individual or as an organization. You will be responsible for keeping custody of the funds raised by this collective and for paying out the expenses that have been approved."
/>
<a href="https://github.com/opencollective/opencollective/wiki/Becoming-an-Open-Collective-Host">
<FormattedMessage id="moreInfo" defaultMessage="More info" />
</a>
.
{this.state.selectedOption === 'createHost' && LoggedInUser && (
<CreateHostFormWithData
collective={collective}
LoggedInUser={LoggedInUser}
onSubmit={hostCollective => this.changeHost(hostCollective)}
/>
)}
</Box>
</Flex>
</Option>
<Option id="findHost">
<Flex>
<Box width="50px" mr={2}>
<Radio
checked={this.state.selectedOption === 'findHost'}
onChange={() => this.handleChange('selectedOption', 'findHost')}
/>
</Box>
<Box mb={4}>
<h2>
<FormattedMessage id="collective.edit.host.findHost.title" defaultMessage="Apply to an existing host" />
</h2>
<FormattedMessage
id="collective.edit.host.findHost.description"
defaultMessage="With this option, everything is taking care of for you. No need to create a new bank account, no need to worry about accounting and invoicing. All of that is being taken care of by an existing non profit organization that acts as your fiscal host. Note: most hosts charge a commission to cover the administrative overhead. "
/>
{this.state.selectedOption === 'findHost' && (
<div>
<InputField
name="currency"
label="What will be the primary currency of your collective?"
description=""
type="select"
options={[
{ AUD: 'AUD' },
{ CAD: 'CAD' },
{ EUR: 'EUR' },
{ GBP: 'GBP' },
{ MXN: 'MXN' },
{ NZD: 'NZD' },
{ USD: 'USD' },
]}
defaultValue={collective.currency}
onChange={val => this.handleChange('currency', val)}
/>
<div className="suggestedHostsTitle">
<h3>
<FormattedMessage
id="collective.edit.host.suggestedHosts.title"
defaultMessage="Suggested hosts"
/>
</h3>
<Link route="/hosts">
<FormattedMessage id="collective.edit.host.viewAllHosts" defaultMessage="View all hosts" />
</Link>
</div>
<div className="suggestedHostsDescription subtitle">
<FormattedMessage
id="collective.edit.host.suggestedHosts.description"
defaultMessage="Based on the currency of your collective ({currency}) and the tags ({tags})"
values={{
tags: collective.tags,
currency: this.state.currency,
}}
/>
.
</div>
<HostsWithData
limit={6}
tags={collective.tags}
currency={this.state.currency}
empty={
<FormattedMessage
id="collective.edit.host.suggestedHosts.empty"
defaultMessage="No suggestion. Please look at all available hosts or consider creating a new host."
/>
}
/>
</div>
)}
</Box>
</Flex>
</Option>
</div>
);
}
}
export default withIntl(EditHost);
|
amartonline-ui/src/components/app/app.js
|
gruberchris/AmartOnline
|
import React, { Component } from 'react';
import { Grid } from 'react-bootstrap';
import { Route, Switch } from 'react-router-dom';
import axios from 'axios';
import Header from '../header/header';
import Home from '../home/home';
import Orders from '../orders/orders';
import ShoppingCart from '../shoppingCart/shoppingCart';
import Callback from '../callback/callback';
import UserProfile from '../userProfile/userProfile';
class App extends Component {
constructor(props) {
super(props);
this.axios = axios;
}
render() {
return (
<Grid fluid={true}>
<Header ref="header" {...this.props} />
<Switch>
<Route exact path="/" render={(props) => <Home config={this.props.config} auth={this.props.auth} onSetCartItemCount={(itemCount) => this.refs.header.setCartItemCount(itemCount)} onAddCartItem={() => this.refs.header.incrementCartItemCount()} {...props}/>} />
<Route path="/callback" render={(props) => {
this.props.auth.onAuthCallback(props);
return <Callback {...props} />;
}} />
<Route exact path="/cart" render={(props) => <ShoppingCart config={this.props.config} auth={this.props.auth} onRemoveCartItem={() => this.refs.header.decrementCartItemCount()} {...props}/>} />
<Route exact path="/orders" render={(props) => <Orders config={this.props.config} auth={this.props.auth} {...props}/>} />
<Route exact path="/profile" render={(props) => <UserProfile config={this.props.config} auth={this.props.auth} {...props}/>} />
</Switch>
</Grid>
);
}
}
export default App;
|
RNAPPDemo/ReactComponent/node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/expected.js
|
xuchengcheng/RNAPPDemo
|
import React from 'react';
const First = React.createNotClass({
displayName: 'First'
});
class Second extends React.NotComponent {}
|
app/javascript/mastodon/features/blocks/index.js
|
increments/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import LoadingIndicator from '../../components/loading_indicator';
import { ScrollContainer } from 'react-router-scroll-4';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountContainer from '../../containers/account_container';
import { fetchBlocks, expandBlocks } from '../../actions/blocks';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
heading: { id: 'column.blocks', defaultMessage: 'Blocked users' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'blocks', 'items']),
});
@connect(mapStateToProps)
@injectIntl
export default class Blocks extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchBlocks());
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight) {
this.props.dispatch(expandBlocks());
}
}
render () {
const { intl, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column icon='ban' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollContainer scrollKey='blocks'>
<div className='scrollable' onScroll={this.handleScroll}>
{accountIds.map(id =>
<AccountContainer key={id} id={id} />
)}
</div>
</ScrollContainer>
</Column>
);
}
}
|
src/components/buttons/toggleDocProperties.js
|
DictumMortuum/dictum-dev
|
'use strict';
import React from 'react';
import IconButton from 'material-ui/IconButton';
import Settings from 'material-ui/svg-icons/action/settings';
import { createSelector } from 'reselect';
import { connect } from 'react-redux';
import { Config } from '../../redux/actions';
class tpl extends React.Component {
render() {
return (
<IconButton {...this.props}>
<Settings />
</IconButton>
);
}
}
const mapStateToProps = state => ({
config: state.config
});
const mapDispatchToProps = {
properties: () => Config.properties()
};
export default connect(
mapStateToProps,
mapDispatchToProps,
createSelector(
(state, actions) => actions.properties,
toggle => ({
onTouchTap: toggle
})
)
)(tpl);
|
App/web/src/js/main.js
|
javierarmendariz/react-flux-material-design
|
import React from 'react';
import ReactDOM from 'react-dom';
import Scaffold from './views/scaffold/scaffold';
import injectTapEventPlugin from 'react-tap-event-plugin';
import AppCanvas from 'material-ui/lib/app-canvas';
injectTapEventPlugin();
ReactDOM.render(<AppCanvas><Scaffold /></AppCanvas>, document.getElementById('main'));
|
app/components/PostForm/ImageUploader.js
|
vlastoun/picture-uploader-crud
|
import React from 'react';
import PropTypes from 'prop-types';
import Script from 'react-load-script';
import RaisedButton from 'material-ui/RaisedButton';
const SCRIPT_URL = '//widget.cloudinary.com/global/all.js';
const buttonStyle = {
marginTop: '2em',
};
/* eslint-disable react/prefer-stateless-function */
/* eslint-disable no-console */
class ImageUploader extends React.Component {
constructor() {
super();
this.uploadWidget = this.uploadWidget.bind(this);
}
uploadWidget() {
cloudinary.openUploadWidget({//eslint-disable-line
cloud_name: process.env.CLOUDI_NAME,
upload_preset: process.env.CLOUDI_PRESET,
api_key: process.env.API_KEY,
},
(error, result) => {
this.props.imagesUploaded(result);
});
}
render() {
return (
<div>
<Script url={SCRIPT_URL} />
<RaisedButton style={buttonStyle} onTouchTap={this.uploadWidget} fullWidth>UploadImages</RaisedButton>
</div>
);
}
}
ImageUploader.propTypes = {
imagesUploaded: PropTypes.func.isRequired,
};
export default ImageUploader;
|
src/pages/about.js
|
elliotschultz/gatsby-portfolio-test
|
import React from 'react'
import { Redirect } from 'react-router';
import Link from 'gatsby-link'
import styled, { keyframes } from 'styled-components'
import { GridProvider, Grid, Row, Col } from 'zooper-grid'
import * as theme from '../theme'
const AboutPage = () =>
<SiteWrapper>
<AboutWrap>
<Title>
About
</Title>
<Copy>
Mattis ut sapien, sodales ut massa ac, cursus dapibus lectus. Cras ante mi, sagittis eu faucibus convallis, dapibus lectus sollicitudin at sapien.
</Copy>
</AboutWrap>
</SiteWrapper>
const SiteWrapper = styled.div`
width: 100%;
height: 100%;
position: absolute;
background-color: ${theme.secondaryColour}
`
const AboutWrap = styled.div`
height: 100%;
display: flex;
flex-direction: column;
align-items: center;
justify-content: center;
`
const Title = styled.h1`
${theme.defaultCopy}
color: lightgrey;
margin: 0 0 2rem;
text-transform: uppercase;
`
const Copy = styled.p`
${theme.prominentCopy}
color: lightgrey;
max-width: 90vw;
@media screen and (min-width: ${theme.mdMin}){
max-width: 60vw;
text-align: center;
}
`
export default AboutPage
|
examples/IconSizes.js
|
mattBlackDesign/react-materialize
|
import React from 'react';
import Section from '../src/Section';
import Icon from '../src/Icon';
import Row from '../src/Row';
import Col from '../src/Col';
export default
<Section>
<Row className='center'>
<Col s={3}>
<Icon tiny>insert_chart</Icon>
<p>tiny</p>
</Col>
<Col s={3}>
<Icon small>insert_chart</Icon>
<p>small</p>
</Col>
<Col s={3}>
<Icon medium>insert_chart</Icon>
<p>medium</p>
</Col>
<Col s={3}>
<Icon large>insert_chart</Icon>
<p>large</p>
</Col>
</Row>
</Section>;
|
webnn/src/App.js
|
lcgong/alchemy
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<header className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h1 className="App-title">Welcome to React</h1>
</header>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
client/components/AboutProfile.js
|
LinearAtWorst/cogile
|
import React, { Component } from 'react';
class AboutProfile extends Component {
render() {
return (
<div className="col-md-3">
<h3 className="about-names">{this.props.name}</h3>
<div className="img-container"><img className="about-img" src={this.props.image}></img>
</div>
<p className="about-bio">{this.props.bio}</p>
<div className="row icon-container">
<a href={this.props.git} target="_blank"><i className="fa fa-github-square fa-2x about-icon"></i></a>
<a href={this.props.linked} target="_blank"><i className="fa fa-linkedin-square fa-2x about-icon"></i></a>
<a href={this.props.email} target="_blank"><i className="fa fa-envelope fa-2x about-icon"></i></a>
</div>
</div>
);
}
}
export default AboutProfile;
|
src/DropdownButton.js
|
adampickeral/react-bootstrap
|
import React from 'react';
import BootstrapMixin from './BootstrapMixin';
import Dropdown from './Dropdown';
import NavDropdown from './NavDropdown';
import CustomPropTypes from './utils/CustomPropTypes';
import deprecationWarning from './utils/deprecationWarning';
import omit from 'lodash/object/omit';
class DropdownButton extends React.Component {
constructor(props) {
super(props);
}
render() {
let { title, navItem, ...props } = this.props;
let toggleProps = omit(props, Dropdown.ControlledComponent.propTypes);
if (navItem){
return <NavDropdown {...this.props}/>;
}
return (
<Dropdown {...props}>
<Dropdown.Toggle {...toggleProps}>
{title}
</Dropdown.Toggle>
<Dropdown.Menu>
{this.props.children}
</Dropdown.Menu>
</Dropdown>
);
}
}
DropdownButton.propTypes = {
/**
* When used with the `title` prop, the noCaret option will not render a caret icon, in the toggle element.
*/
noCaret: React.PropTypes.bool,
/**
* Specify whether this Dropdown is part of a Nav component
*
* @type {bool}
* @deprecated Use the `NavDropdown` instead.
*/
navItem: CustomPropTypes.all([
React.PropTypes.bool,
function(props, propName, componentName) {
if (props.navItem) {
deprecationWarning('navItem', 'NavDropdown component', 'https://github.com/react-bootstrap/react-bootstrap/issues/526');
}
}
]),
title: React.PropTypes.node.isRequired,
...Dropdown.propTypes,
...BootstrapMixin.propTypes
};
DropdownButton.defaultProps = {
pullRight: false,
dropup: false,
navItem: false,
noCaret: false
};
export default DropdownButton;
|
webapp/app/components/CreateUser/Form/index.js
|
EIP-SAM/SAM-Solution-Node-js
|
//
// Component form in create user page
//
import React from 'react';
import Username from 'containers/CreateUser/Form/Username';
import Email from 'containers/CreateUser/Form/Email';
import Password from 'containers/CreateUser/Form/Password';
import PasswordConfirmation from 'containers/CreateUser/Form/PasswordConfirmation';
import Groups from 'containers/CreateUser/Form/Groups';
import Buttons from 'containers/CreateUser/Form/Buttons';
/* eslint-disable react/prefer-stateless-function */
export default class CreateUserForm extends React.Component {
render() {
return (
<form>
<Username />
<Email />
<Password />
<PasswordConfirmation />
<Groups />
<Buttons />
</form>
);
}
}
|
addons/knobs/src/components/__tests__/Panel.js
|
jribeiro/storybook
|
import React from 'react';
import { shallow } from 'enzyme'; // eslint-disable-line
import Panel from '../Panel';
describe('Panel', () => {
it('should subscribe to setKnobs event of channel', () => {
const testChannel = { on: jest.fn() };
const testApi = { onStory: jest.fn() };
shallow(<Panel channel={testChannel} api={testApi} />);
expect(testChannel.on).toHaveBeenCalledWith('addon:knobs:setKnobs', jasmine.any(Function));
});
it('should subscribe to onStory event', () => {
const testChannel = { on: jest.fn() };
const testApi = { onStory: jest.fn() };
shallow(<Panel channel={testChannel} api={testApi} />);
expect(testApi.onStory).toHaveBeenCalled();
expect(testChannel.on).toHaveBeenCalledWith('addon:knobs:setKnobs', jasmine.any(Function));
});
describe('setKnobs handler', () => {
it('should read url params and set values for existing knobs', () => {
const handlers = {};
const testChannel = {
on: (e, handler) => {
handlers[e] = handler;
},
emit: jest.fn(),
};
const testQueryParams = {
'knob-foo': 'test string',
bar: 'some other string',
};
const testApi = {
getQueryParam: key => testQueryParams[key],
setQueryParams: jest.fn(),
onStory: jest.fn(),
};
shallow(<Panel channel={testChannel} api={testApi} />);
const setKnobsHandler = handlers['addon:knobs:setKnobs'];
const knobs = {
foo: {
name: 'foo',
value: 'default string',
type: 'text',
},
baz: {
name: 'baz',
value: 'another knob value',
type: 'text',
},
};
setKnobsHandler({ knobs, timestamp: +new Date() });
const knobFromUrl = {
name: 'foo',
value: testQueryParams['knob-foo'],
type: 'text',
};
const e = 'addon:knobs:knobChange';
expect(testChannel.emit).toHaveBeenCalledWith(e, knobFromUrl);
});
it('should set query params when url params are already read', () => {
const handlers = {};
const testChannel = {
on: (e, handler) => {
handlers[e] = handler;
},
emit: jest.fn(),
};
const testQueryParams = {
'knob-foo': 'test string',
bar: 'some other string',
};
const testApi = {
getQueryParam: key => testQueryParams[key],
setQueryParams: jest.fn(),
onStory: jest.fn(),
};
const wrapper = shallow(<Panel channel={testChannel} api={testApi} />);
const setKnobsHandler = handlers['addon:knobs:setKnobs'];
const knobs = {
foo: {
name: 'foo',
value: 'default string',
type: 'text',
},
baz: {
name: 'baz',
value: 'another knob value',
type: 'text',
},
};
// Make it act like that url params are already checked
wrapper.instance().loadedFromUrl = true;
setKnobsHandler({ knobs, timestamp: +new Date() });
const knobFromStory = {
'knob-foo': knobs.foo.value,
'knob-baz': knobs.baz.value,
};
expect(testApi.setQueryParams).toHaveBeenCalledWith(knobFromStory);
});
});
describe('handleChange()', () => {
it('should set queryParams and emit knobChange event', () => {
const testChannel = {
on: jest.fn(),
emit: jest.fn(),
};
const testApi = {
getQueryParam: jest.fn(),
setQueryParams: jest.fn(),
onStory: jest.fn(),
};
const wrapper = shallow(<Panel channel={testChannel} api={testApi} />);
const testChangedKnob = {
name: 'foo',
value: 'changed text',
type: 'text',
};
wrapper.instance().handleChange(testChangedKnob);
expect(testChannel.emit).toHaveBeenCalledWith('addon:knobs:knobChange', testChangedKnob);
const paramsChange = { 'knob-foo': 'changed text' };
expect(testApi.setQueryParams).toHaveBeenCalledWith(paramsChange);
});
});
});
|
internals/templates/app.js
|
andyfrith/weather.goodapplemedia.com
|
/**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
// Needed for redux-saga es6 generator support
import 'babel-polyfill';
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import { useScroll } from 'react-router-scroll';
import 'sanitize.css/sanitize.css';
// Import root app
import App from 'containers/App';
// Import selector for `syncHistoryWithStore`
import { makeSelectLocationState } from 'containers/App/selectors';
// Import Language Provider
import LanguageProvider from 'containers/LanguageProvider';
// Load the favicon, the manifest.json file and the .htaccess file
/* eslint-disable import/no-unresolved, import/extensions */
import '!file-loader?name=[name].[ext]!./favicon.ico';
import '!file-loader?name=[name].[ext]!./manifest.json';
import 'file-loader?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved, import/extensions */
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import CSS reset and Global Styles
import './global-styles';
// Import root routes
import createRoutes from './routes';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: makeSelectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (messages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={messages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
(new Promise((resolve) => {
resolve(import('intl'));
}))
.then(() => Promise.all([
import('intl/locale-data/jsonp/en.js'),
]))
.then(() => render(translationMessages))
.catch((err) => {
throw err;
});
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
if (process.env.NODE_ENV === 'production') {
require('offline-plugin/runtime').install(); // eslint-disable-line global-require
}
|
src/svg-icons/image/brush.js
|
ArcanisCz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrush = (props) => (
<SvgIcon {...props}>
<path d="M7 14c-1.66 0-3 1.34-3 3 0 1.31-1.16 2-2 2 .92 1.22 2.49 2 4 2 2.21 0 4-1.79 4-4 0-1.66-1.34-3-3-3zm13.71-9.37l-1.34-1.34c-.39-.39-1.02-.39-1.41 0L9 12.25 11.75 15l8.96-8.96c.39-.39.39-1.02 0-1.41z"/>
</SvgIcon>
);
ImageBrush = pure(ImageBrush);
ImageBrush.displayName = 'ImageBrush';
ImageBrush.muiName = 'SvgIcon';
export default ImageBrush;
|
containers/App.js
|
hutsi/bookkeeping
|
import React from 'react';
import { MuiThemeProvider, createMuiTheme } from '@material-ui/core/styles';
import { blue } from '@material-ui/core/colors';
import Paper from '@material-ui/core/Paper';
import Header from '../components/Header';
const theme = createMuiTheme({
palette: {
primary: blue,
},
typography: {
useNextVariants: true,
},
});
const App = ({ children }) => (
<MuiThemeProvider theme={theme}>
<Paper>
<Header />
<div style={{ marginTop: 80 }}>
{children}
</div>
</Paper>
</MuiThemeProvider>
);
export default App;
|
src/examples/example-mouseover/example-mouseover.js
|
smollweide/react-speed-dial
|
import React from 'react';
import Avatar from 'material-ui/Avatar';
import { blue500 } from 'material-ui/styles/colors';
import IconEdit from 'material-ui/svg-icons/image/edit';
import { SpeedDial, BubbleList, BubbleListItem } from '../../speed-dial';
import fakerImage from '../faker-image';
const list = {
items: [
{
primaryText: 'Eric Hoffman',
rightAvatar: <Avatar src={fakerImage(1)} />,
onClick() {
// eslint-disable-next-line
console.log('click on "Eric Hoffman"');
},
},
{
primaryText: 'Grace Ng',
rightAvatar: <Avatar src={fakerImage(3)} />,
},
{
primaryText: 'Kerem Suer',
rightAvatar: <Avatar src={fakerImage(6)} />,
},
{
primaryText: 'Raquel Parrado',
rightAvatar: <Avatar src={fakerImage(7)} />,
},
{
primaryText: 'Write',
rightAvatar: <Avatar backgroundColor={blue500} icon={<IconEdit />} />,
},
],
};
const ExampleMouseover = () => {
return (
<SpeedDial enableMouseActions>
<BubbleList>
{list.items.map((item, index) => {
return <BubbleListItem key={index} {...item} />;
})}
</BubbleList>
</SpeedDial>
);
};
ExampleMouseover.displayName = 'ExampleMouseover';
export default ExampleMouseover;
|
tests/routes/Home/components/HomeView.spec.js
|
taikongfeizhu/webpack-develop-startkit
|
import React from 'react'
import { HomeView } from 'routes/Home/components/HomeView'
import { render } from 'enzyme'
describe('(View) Home', () => {
let _component
beforeEach(() => {
_component = render(<HomeView />)
})
it('Renders a welcome message', () => {
const welcome = _component.find('h4')
expect(welcome).to.exist
expect(welcome.text()).to.match(/Welcome!/)
})
it('Renders an awesome duck image', () => {
const duck = _component.find('img')
expect(duck).to.exist
expect(duck.attr('alt')).to.match(/This is a duck, because Redux!/)
})
})
|
app/javascript/mastodon/features/video/index.js
|
pinfort/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { is } from 'immutable';
import { throttle, debounce } from 'lodash';
import classNames from 'classnames';
import { isFullscreen, requestFullscreen, exitFullscreen } from '../ui/util/fullscreen';
import { displayMedia, useBlurhash } from '../../initial_state';
import Icon from 'mastodon/components/icon';
import Blurhash from 'mastodon/components/blurhash';
const messages = defineMessages({
play: { id: 'video.play', defaultMessage: 'Play' },
pause: { id: 'video.pause', defaultMessage: 'Pause' },
mute: { id: 'video.mute', defaultMessage: 'Mute sound' },
unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' },
hide: { id: 'video.hide', defaultMessage: 'Hide video' },
expand: { id: 'video.expand', defaultMessage: 'Expand video' },
close: { id: 'video.close', defaultMessage: 'Close video' },
fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' },
exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' },
});
export const formatTime = secondsNum => {
let hours = Math.floor(secondsNum / 3600);
let minutes = Math.floor((secondsNum - (hours * 3600)) / 60);
let seconds = secondsNum - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = '0' + hours;
if (minutes < 10) minutes = '0' + minutes;
if (seconds < 10) seconds = '0' + seconds;
return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`;
};
export const findElementPosition = el => {
let box;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0,
};
}
const docEl = document.documentElement;
const body = document.body;
const clientLeft = docEl.clientLeft || body.clientLeft || 0;
const scrollLeft = window.pageXOffset || body.scrollLeft;
const left = (box.left + scrollLeft) - clientLeft;
const clientTop = docEl.clientTop || body.clientTop || 0;
const scrollTop = window.pageYOffset || body.scrollTop;
const top = (box.top + scrollTop) - clientTop;
return {
left: Math.round(left),
top: Math.round(top),
};
};
export const getPointerPosition = (el, event) => {
const position = {};
const box = findElementPosition(el);
const boxW = el.offsetWidth;
const boxH = el.offsetHeight;
const boxY = box.top;
const boxX = box.left;
let pageY = event.pageY;
let pageX = event.pageX;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
pageY = event.changedTouches[0].pageY;
}
position.y = Math.max(0, Math.min(1, (pageY - boxY) / boxH));
position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));
return position;
};
export const fileNameFromURL = str => {
const url = new URL(str);
const pathname = url.pathname;
const index = pathname.lastIndexOf('/');
return pathname.substring(index + 1);
};
export default @injectIntl
class Video extends React.PureComponent {
static propTypes = {
preview: PropTypes.string,
frameRate: PropTypes.string,
src: PropTypes.string.isRequired,
alt: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
sensitive: PropTypes.bool,
currentTime: PropTypes.number,
onOpenVideo: PropTypes.func,
onCloseVideo: PropTypes.func,
detailed: PropTypes.bool,
inline: PropTypes.bool,
editable: PropTypes.bool,
alwaysVisible: PropTypes.bool,
cacheWidth: PropTypes.func,
visible: PropTypes.bool,
onToggleVisibility: PropTypes.func,
deployPictureInPicture: PropTypes.func,
intl: PropTypes.object.isRequired,
blurhash: PropTypes.string,
autoPlay: PropTypes.bool,
volume: PropTypes.number,
muted: PropTypes.bool,
componetIndex: PropTypes.number,
};
static defaultProps = {
frameRate: '25',
};
state = {
currentTime: 0,
duration: 0,
volume: 0.5,
paused: true,
dragging: false,
containerWidth: this.props.width,
fullscreen: false,
hovered: false,
muted: false,
revealed: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
};
setPlayerRef = c => {
this.player = c;
if (this.player) {
this._setDimensions();
}
}
_setDimensions () {
const width = this.player.offsetWidth;
if (this.props.cacheWidth) {
this.props.cacheWidth(width);
}
this.setState({
containerWidth: width,
});
}
setVideoRef = c => {
this.video = c;
if (this.video) {
this.setState({ volume: this.video.volume, muted: this.video.muted });
}
}
setSeekRef = c => {
this.seek = c;
}
setVolumeRef = c => {
this.volume = c;
}
handleClickRoot = e => e.stopPropagation();
handlePlay = () => {
this.setState({ paused: false });
this._updateTime();
}
handlePause = () => {
this.setState({ paused: true });
}
_updateTime () {
requestAnimationFrame(() => {
if (!this.video) return;
this.handleTimeUpdate();
if (!this.state.paused) {
this._updateTime();
}
});
}
handleTimeUpdate = () => {
this.setState({
currentTime: this.video.currentTime,
duration:this.video.duration,
});
}
handleVolumeMouseDown = e => {
document.addEventListener('mousemove', this.handleMouseVolSlide, true);
document.addEventListener('mouseup', this.handleVolumeMouseUp, true);
document.addEventListener('touchmove', this.handleMouseVolSlide, true);
document.addEventListener('touchend', this.handleVolumeMouseUp, true);
this.handleMouseVolSlide(e);
e.preventDefault();
e.stopPropagation();
}
handleVolumeMouseUp = () => {
document.removeEventListener('mousemove', this.handleMouseVolSlide, true);
document.removeEventListener('mouseup', this.handleVolumeMouseUp, true);
document.removeEventListener('touchmove', this.handleMouseVolSlide, true);
document.removeEventListener('touchend', this.handleVolumeMouseUp, true);
}
handleMouseVolSlide = throttle(e => {
const { x } = getPointerPosition(this.volume, e);
if(!isNaN(x)) {
this.setState({ volume: x }, () => {
this.video.volume = x;
});
}
}, 15);
handleMouseDown = e => {
document.addEventListener('mousemove', this.handleMouseMove, true);
document.addEventListener('mouseup', this.handleMouseUp, true);
document.addEventListener('touchmove', this.handleMouseMove, true);
document.addEventListener('touchend', this.handleMouseUp, true);
this.setState({ dragging: true });
this.video.pause();
this.handleMouseMove(e);
e.preventDefault();
e.stopPropagation();
}
handleMouseUp = () => {
document.removeEventListener('mousemove', this.handleMouseMove, true);
document.removeEventListener('mouseup', this.handleMouseUp, true);
document.removeEventListener('touchmove', this.handleMouseMove, true);
document.removeEventListener('touchend', this.handleMouseUp, true);
this.setState({ dragging: false });
this.video.play();
}
handleMouseMove = throttle(e => {
const { x } = getPointerPosition(this.seek, e);
const currentTime = this.video.duration * x;
if (!isNaN(currentTime)) {
this.setState({ currentTime }, () => {
this.video.currentTime = currentTime;
});
}
}, 15);
seekBy (time) {
const currentTime = this.video.currentTime + time;
if (!isNaN(currentTime)) {
this.setState({ currentTime }, () => {
this.video.currentTime = currentTime;
});
}
}
handleVideoKeyDown = e => {
// On the video element or the seek bar, we can safely use the space bar
// for playback control because there are no buttons to press
if (e.key === ' ') {
e.preventDefault();
e.stopPropagation();
this.togglePlay();
}
}
handleKeyDown = e => {
const frameTime = 1 / this.getFrameRate();
switch(e.key) {
case 'k':
e.preventDefault();
e.stopPropagation();
this.togglePlay();
break;
case 'm':
e.preventDefault();
e.stopPropagation();
this.toggleMute();
break;
case 'f':
e.preventDefault();
e.stopPropagation();
this.toggleFullscreen();
break;
case 'j':
e.preventDefault();
e.stopPropagation();
this.seekBy(-10);
break;
case 'l':
e.preventDefault();
e.stopPropagation();
this.seekBy(10);
break;
case ',':
e.preventDefault();
e.stopPropagation();
this.seekBy(-frameTime);
break;
case '.':
e.preventDefault();
e.stopPropagation();
this.seekBy(frameTime);
break;
}
// If we are in fullscreen mode, we don't want any hotkeys
// interacting with the UI that's not visible
if (this.state.fullscreen) {
e.preventDefault();
e.stopPropagation();
if (e.key === 'Escape') {
exitFullscreen();
}
}
}
togglePlay = () => {
if (this.state.paused) {
this.setState({ paused: false }, () => this.video.play());
} else {
this.setState({ paused: true }, () => this.video.pause());
}
}
toggleFullscreen = () => {
if (isFullscreen()) {
exitFullscreen();
} else {
requestFullscreen(this.player);
}
}
componentDidMount () {
document.addEventListener('fullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
window.addEventListener('scroll', this.handleScroll);
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentWillUnmount () {
window.removeEventListener('scroll', this.handleScroll);
window.removeEventListener('resize', this.handleResize);
document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true);
document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
if (!this.state.paused && this.video && this.props.deployPictureInPicture) {
this.props.deployPictureInPicture('video', {
src: this.props.src,
currentTime: this.video.currentTime,
muted: this.video.muted,
volume: this.video.volume,
});
}
}
componentWillReceiveProps (nextProps) {
if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
this.setState({ revealed: nextProps.visible });
}
}
componentDidUpdate (prevProps, prevState) {
if (prevState.revealed && !this.state.revealed && this.video) {
this.video.pause();
}
}
handleResize = debounce(() => {
if (this.player) {
this._setDimensions();
}
}, 250, {
trailing: true,
});
handleScroll = throttle(() => {
if (!this.video) {
return;
}
const { top, height } = this.video.getBoundingClientRect();
const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0);
if (!this.state.paused && !inView) {
this.video.pause();
if (this.props.deployPictureInPicture) {
this.props.deployPictureInPicture('video', {
src: this.props.src,
currentTime: this.video.currentTime,
muted: this.video.muted,
volume: this.video.volume,
});
}
this.setState({ paused: true });
}
}, 150, { trailing: true })
handleFullscreenChange = () => {
this.setState({ fullscreen: isFullscreen() });
}
handleMouseEnter = () => {
this.setState({ hovered: true });
}
handleMouseLeave = () => {
this.setState({ hovered: false });
}
toggleMute = () => {
const muted = !this.video.muted;
this.setState({ muted }, () => {
this.video.muted = muted;
});
}
toggleReveal = () => {
if (this.props.onToggleVisibility) {
this.props.onToggleVisibility();
} else {
this.setState({ revealed: !this.state.revealed });
}
}
handleLoadedData = () => {
const { currentTime, volume, muted, autoPlay } = this.props;
if (currentTime) {
this.video.currentTime = currentTime;
}
if (volume !== undefined) {
this.video.volume = volume;
}
if (muted !== undefined) {
this.video.muted = muted;
}
if (autoPlay) {
this.video.play();
}
}
handleProgress = () => {
const lastTimeRange = this.video.buffered.length - 1;
if (lastTimeRange > -1) {
this.setState({ buffer: Math.ceil(this.video.buffered.end(lastTimeRange) / this.video.duration * 100) });
}
}
handleVolumeChange = () => {
this.setState({ volume: this.video.volume, muted: this.video.muted });
}
handleOpenVideo = () => {
this.video.pause();
this.props.onOpenVideo({
startTime: this.video.currentTime,
autoPlay: !this.state.paused,
defaultVolume: this.state.volume,
componetIndex: this.props.componetIndex,
});
}
handleCloseVideo = () => {
this.video.pause();
this.props.onCloseVideo();
}
getFrameRate () {
if (this.props.frameRate && isNaN(this.props.frameRate)) {
// The frame rate is returned as a fraction string so we
// need to convert it to a number
return this.props.frameRate.split('/').reduce((p, c) => p / c);
}
return this.props.frameRate;
}
render () {
const { preview, src, inline, onOpenVideo, onCloseVideo, intl, alt, detailed, sensitive, editable, blurhash } = this.props;
const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
const progress = Math.min((currentTime / duration) * 100, 100);
const playerStyle = {};
let { width, height } = this.props;
if (inline && containerWidth) {
width = containerWidth;
height = containerWidth / (16/9);
playerStyle.height = height;
}
let preload;
if (this.props.currentTime || fullscreen || dragging) {
preload = 'auto';
} else if (detailed) {
preload = 'metadata';
} else {
preload = 'none';
}
let warning;
if (sensitive) {
warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
} else {
warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
}
return (
<div
role='menuitem'
className={classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen, editable })}
style={playerStyle}
ref={this.setPlayerRef}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
onClick={this.handleClickRoot}
onKeyDown={this.handleKeyDown}
tabIndex={0}
>
<Blurhash
hash={blurhash}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': revealed,
})}
dummy={!useBlurhash}
/>
{(revealed || editable) && <video
ref={this.setVideoRef}
src={src}
poster={preview}
preload={preload}
role='button'
tabIndex='0'
aria-label={alt}
title={alt}
width={width}
height={height}
volume={volume}
onClick={this.togglePlay}
onKeyDown={this.handleVideoKeyDown}
onPlay={this.handlePlay}
onPause={this.handlePause}
onLoadedData={this.handleLoadedData}
onProgress={this.handleProgress}
onVolumeChange={this.handleVolumeChange}
/>}
<div className={classNames('spoiler-button', { 'spoiler-button--hidden': revealed || editable })}>
<button type='button' className='spoiler-button__overlay' onClick={this.toggleReveal}>
<span className='spoiler-button__overlay__label'>{warning}</span>
</button>
</div>
<div className={classNames('video-player__controls', { active: paused || hovered })}>
<div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}>
<div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} />
<div className='video-player__seek__progress' style={{ width: `${progress}%` }} />
<span
className={classNames('video-player__seek__handle', { active: dragging })}
tabIndex='0'
style={{ left: `${progress}%` }}
onKeyDown={this.handleVideoKeyDown}
/>
</div>
<div className='video-player__buttons-bar'>
<div className='video-player__buttons left'>
<button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} className='player-button' onClick={this.togglePlay} autoFocus={detailed}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button>
<button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} className='player-button' onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button>
<div className={classNames('video-player__volume', { active: this.state.hovered })} onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}>
<div className='video-player__volume__current' style={{ width: `${volume * 100}%` }} />
<span
className={classNames('video-player__volume__handle')}
tabIndex='0'
style={{ left: `${volume * 100}%` }}
/>
</div>
{(detailed || fullscreen) && (
<span className='video-player__time'>
<span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span>
<span className='video-player__time-sep'>/</span>
<span className='video-player__time-total'>{formatTime(Math.floor(duration))}</span>
</span>
)}
</div>
<div className='video-player__buttons right'>
{(!onCloseVideo && !editable && !fullscreen && !this.props.alwaysVisible) && <button type='button' title={intl.formatMessage(messages.hide)} aria-label={intl.formatMessage(messages.hide)} className='player-button' onClick={this.toggleReveal}><Icon id='eye-slash' fixedWidth /></button>}
{(!fullscreen && onOpenVideo) && <button type='button' title={intl.formatMessage(messages.expand)} aria-label={intl.formatMessage(messages.expand)} className='player-button' onClick={this.handleOpenVideo}><Icon id='expand' fixedWidth /></button>}
{onCloseVideo && <button type='button' title={intl.formatMessage(messages.close)} aria-label={intl.formatMessage(messages.close)} className='player-button' onClick={this.handleCloseVideo}><Icon id='compress' fixedWidth /></button>}
<button type='button' title={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} className='player-button' onClick={this.toggleFullscreen}><Icon id={fullscreen ? 'compress' : 'arrows-alt'} fixedWidth /></button>
</div>
</div>
</div>
</div>
);
}
}
|
webpack/move_to_pf/LoadingState/LoadingState.js
|
tstrachota/katello
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Spinner } from 'patternfly-react';
import './LoadingState.scss';
class LoadingState extends Component {
constructor(props) {
super(props);
this.state = {
render: false,
};
}
componentDidMount() {
setTimeout(() => {
this.setState({ render: true });
}, this.props.timeout);
}
render() {
const { loading, loadingText, children } = this.props;
const spinner = (
<div className="loading-state">
<Spinner loading={loading} size="lg" />
<p>{loadingText}</p>
</div>);
if (loading) {
return this.state.render ? spinner : null;
}
return children;
}
}
LoadingState.propTypes = {
loading: PropTypes.bool,
loadingText: PropTypes.string,
children: PropTypes.node,
timeout: PropTypes.number,
};
LoadingState.defaultProps = {
loading: false,
loadingText: __('Loading'),
children: null,
timeout: 300,
};
export default LoadingState;
|
app/javascript/mastodon/features/account_gallery/index.js
|
kazh98/social.arnip.org
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { fetchAccount } from 'mastodon/actions/accounts';
import { expandAccountMediaTimeline } from '../../actions/timelines';
import LoadingIndicator from 'mastodon/components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButton from 'mastodon/components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { getAccountGallery } from 'mastodon/selectors';
import MediaItem from './components/media_item';
import HeaderContainer from '../account_timeline/containers/header_container';
import { ScrollContainer } from 'react-router-scroll-4';
import LoadMore from 'mastodon/components/load_more';
import MissingIndicator from 'mastodon/components/missing_indicator';
import { openModal } from 'mastodon/actions/modal';
const mapStateToProps = (state, props) => ({
isAccount: !!state.getIn(['accounts', props.params.accountId]),
attachments: getAccountGallery(state, props.params.accountId),
isLoading: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${props.params.accountId}:media`, 'hasMore']),
});
class LoadMoreMedia extends ImmutablePureComponent {
static propTypes = {
shouldUpdateScroll: PropTypes.func,
maxId: PropTypes.string,
onLoadMore: PropTypes.func.isRequired,
};
handleLoadMore = () => {
this.props.onLoadMore(this.props.maxId);
}
render () {
return (
<LoadMore
disabled={this.props.disabled}
onClick={this.handleLoadMore}
/>
);
}
}
export default @connect(mapStateToProps)
class AccountGallery extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
attachments: ImmutablePropTypes.list.isRequired,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
isAccount: PropTypes.bool,
multiColumn: PropTypes.bool,
};
state = {
width: 323,
};
componentDidMount () {
this.props.dispatch(fetchAccount(this.props.params.accountId));
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId));
}
}
handleScrollToBottom = () => {
if (this.props.hasMore) {
this.handleLoadMore(this.props.attachments.size > 0 ? this.props.attachments.last().getIn(['status', 'id']) : undefined);
}
}
handleScroll = e => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
const offset = scrollHeight - scrollTop - clientHeight;
if (150 > offset && !this.props.isLoading) {
this.handleScrollToBottom();
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountMediaTimeline(this.props.params.accountId, { maxId }));
};
handleLoadOlder = e => {
e.preventDefault();
this.handleScrollToBottom();
}
handleOpenMedia = attachment => {
if (attachment.get('type') === 'video') {
this.props.dispatch(openModal('VIDEO', { media: attachment, status: attachment.get('status') }));
} else if (attachment.get('type') === 'audio') {
this.props.dispatch(openModal('AUDIO', { media: attachment, status: attachment.get('status') }));
} else {
const media = attachment.getIn(['status', 'media_attachments']);
const index = media.findIndex(x => x.get('id') === attachment.get('id'));
this.props.dispatch(openModal('MEDIA', { media, index, status: attachment.get('status') }));
}
}
handleRef = c => {
if (c) {
this.setState({ width: c.offsetWidth });
}
}
render () {
const { attachments, shouldUpdateScroll, isLoading, hasMore, isAccount, multiColumn } = this.props;
const { width } = this.state;
if (!isAccount) {
return (
<Column>
<MissingIndicator />
</Column>
);
}
if (!attachments && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
let loadOlder = null;
if (hasMore && !(isLoading && attachments.size === 0)) {
loadOlder = <LoadMore visible={!isLoading} onClick={this.handleLoadOlder} />;
}
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<ScrollContainer scrollKey='account_gallery' shouldUpdateScroll={shouldUpdateScroll}>
<div className='scrollable scrollable--flex' onScroll={this.handleScroll}>
<HeaderContainer accountId={this.props.params.accountId} />
<div role='feed' className='account-gallery__container' ref={this.handleRef}>
{attachments.map((attachment, index) => attachment === null ? (
<LoadMoreMedia key={'more:' + attachments.getIn(index + 1, 'id')} maxId={index > 0 ? attachments.getIn(index - 1, 'id') : null} onLoadMore={this.handleLoadMore} />
) : (
<MediaItem key={attachment.get('id')} attachment={attachment} displayWidth={width} onOpenMedia={this.handleOpenMedia} />
))}
{loadOlder}
</div>
{isLoading && attachments.size === 0 && (
<div className='scrollable__append'>
<LoadingIndicator />
</div>
)}
</div>
</ScrollContainer>
</Column>
);
}
}
|
packages/recon-engine/src/engine/__tests__/__fixtures__/basic-app/src/button.js
|
recon-js/recon
|
/* eslint-disable */
import React from 'react';
export default function Button({theme, children}) {
return <button color={theme}>{children}</button>;
}
|
react/Text/Text.sketch.js
|
seekinternational/seek-asia-style-guide
|
import React from 'react';
import mapKeys from 'lodash/mapKeys';
import Text from './Text';
export const text = {
'Screaming': <Text screaming>Screaming text</Text>,
'Yelling': <Text yelling>Yelling text</Text>,
'Shouting': <Text shouting>Shouting text</Text>,
'Waving': <Text waving>Waving text</Text>,
'Whistling': <Text whistling>Whistling text</Text>,
'Whispering (Title)': <Text whisperingTitle>Whispering (Title) text</Text>,
'Loud': <Text loud>Loud text</Text>,
'Intimate': <Text intimate>Intimate text</Text>,
'Whispering': <Text whispering>Whispering text</Text>
};
// Export text styles as symbols
// (at least until Sketch libraries support shared text styles)
export const symbols = mapKeys(text, (value, key) => `Text/${key}`);
|
docs/app/Examples/elements/Header/Types/HeaderExampleContent.js
|
koenvg/Semantic-UI-React
|
import React from 'react'
import { Header } from 'semantic-ui-react'
const HeaderExampleContent = () => (
<div>
<Header size='huge'>Huge Header</Header>
<Header size='large'>Large Header</Header>
<Header size='medium'>Medium Header</Header>
<Header size='small'>Small Header</Header>
<Header size='tiny'>Tiny Header</Header>
</div>
)
export default HeaderExampleContent
|
src/client/components/pages/entities/title.js
|
bookbrainz/bookbrainz-site
|
/*
* Copyright (C) 2017 Ben Ockmore
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*/
import * as entityHelper from '../../../helpers/entity';
import PropTypes from 'prop-types';
import React from 'react';
const {
getEntitySecondaryAliases, getEntityDisambiguation, getEntityLabel
} = entityHelper;
function EntityTitle({entity}) {
const aliases = getEntitySecondaryAliases(entity);
const disambiguation = getEntityDisambiguation(entity);
const label = getEntityLabel(entity);
return (
<div>
<h1>{label}{disambiguation}</h1>
{aliases}
<hr/>
</div>
);
}
EntityTitle.displayName = 'EntityTitle';
EntityTitle.propTypes = {
entity: PropTypes.object.isRequired
};
export default EntityTitle;
|
modules/Link.js
|
djkirby/react-router
|
import React from 'react'
import invariant from 'invariant'
import { routerShape } from './PropTypes'
import { ContextSubscriber } from './ContextUtils'
const { bool, object, string, func, oneOfType } = React.PropTypes
function isLeftClickEvent(event) {
return event.button === 0
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey)
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (const p in object)
if (Object.prototype.hasOwnProperty.call(object, p))
return false
return true
}
function resolveToLocation(to, router) {
return typeof to === 'function' ? to(router.location) : to
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*/
const Link = React.createClass({
mixins: [ ContextSubscriber('router') ],
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([ string, object, func ]),
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
}
},
handleClick(event) {
if (this.props.onClick)
this.props.onClick(event)
if (event.defaultPrevented)
return
const { router } = this.context
invariant(
router,
'<Link>s rendered outside of a router context cannot navigate.'
)
if (isModifiedEvent(event) || !isLeftClickEvent(event))
return
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target)
return
event.preventDefault()
router.push(resolveToLocation(this.props.to, router))
},
render() {
const { to, activeClassName, activeStyle, onlyActiveOnIndex, ...props } = this.props
// Ignore if rendered outside the context of router to simplify unit testing.
const { router } = this.context
if (router) {
// If user does not specify a `to` prop, return an empty anchor tag.
if (!to) { return <a {...props} /> }
const toLocation = resolveToLocation(to, router)
props.href = router.createHref(toLocation)
if (activeClassName || (activeStyle != null && !isEmptyObject(activeStyle))) {
if (router.isActive(toLocation, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ` ${activeClassName}`
} else {
props.className = activeClassName
}
}
if (activeStyle)
props.style = { ...props.style, ...activeStyle }
}
}
}
return <a {...props} onClick={this.handleClick} />
}
})
export default Link
|
src/components/common/svg-icons/content/gesture.js
|
abzfarah/Pearson.NAPLAN.GnomeH
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentGesture = (props) => (
<SvgIcon {...props}>
<path d="M4.59 6.89c.7-.71 1.4-1.35 1.71-1.22.5.2 0 1.03-.3 1.52-.25.42-2.86 3.89-2.86 6.31 0 1.28.48 2.34 1.34 2.98.75.56 1.74.73 2.64.46 1.07-.31 1.95-1.4 3.06-2.77 1.21-1.49 2.83-3.44 4.08-3.44 1.63 0 1.65 1.01 1.76 1.79-3.78.64-5.38 3.67-5.38 5.37 0 1.7 1.44 3.09 3.21 3.09 1.63 0 4.29-1.33 4.69-6.1H21v-2.5h-2.47c-.15-1.65-1.09-4.2-4.03-4.2-2.25 0-4.18 1.91-4.94 2.84-.58.73-2.06 2.48-2.29 2.72-.25.3-.68.84-1.11.84-.45 0-.72-.83-.36-1.92.35-1.09 1.4-2.86 1.85-3.52.78-1.14 1.3-1.92 1.3-3.28C8.95 3.69 7.31 3 6.44 3 5.12 3 3.97 4 3.72 4.25c-.36.36-.66.66-.88.93l1.75 1.71zm9.29 11.66c-.31 0-.74-.26-.74-.72 0-.6.73-2.2 2.87-2.76-.3 2.69-1.43 3.48-2.13 3.48z"/>
</SvgIcon>
);
ContentGesture = pure(ContentGesture);
ContentGesture.displayName = 'ContentGesture';
ContentGesture.muiName = 'SvgIcon';
export default ContentGesture;
|
src/components/menus/MainMenu.js
|
openvcash/vcash-electron
|
import React from 'react'
import { translate } from 'react-i18next'
import { withRouter } from 'react-router-dom'
import { action, extendObservable, reaction } from 'mobx'
import { inject, observer } from 'mobx-react'
/** Ant Design */
import Menu from 'antd/lib/menu'
@translate(['common'])
@inject('connections')
@observer
class MainMenu extends React.Component {
constructor(props) {
super(props)
this.t = props.t
this.connections = props.connections
/** Extend the component with observable properties. */
extendObservable(this, { selected: '/' })
/**
* Redirect to the viewing connection when RPC becomes active, or to the
* connections screen if the viewing connection becomes unreachable.
*/
this.viewingReaction = reaction(
() => [this.connections.viewingId, this.connections.viewing.status.rpc],
([id, rpc]) => {
this.setSelected({
key: rpc === true ? '/' + id + '/transactions' : '/'
})
},
{
fireImmediately: true,
name: 'MainMenu: viewing connection status changed, adjusting screen.'
}
)
}
/** Dispose of reaction on component unmount. */
componentWillUnmount() {
this.viewingReaction()
}
/**
* Set selected menu item and navigate to it.
* @function setSelected
* @param {object} item - Routing path and menu item key.
*/
@action
setSelected = ({ key }) => {
this.selected = key
if (this.props.history.location.pathname !== key) {
this.props.history.push(key)
}
}
render() {
const disabled = this.connections.viewing.status.rpc !== true
const key = '/' + this.connections.viewingId + '/'
return (
<Menu
inlineCollapsed
mode="inline"
onClick={this.setSelected}
selectedKeys={[this.selected]}
>
<Menu.Item disabled={disabled} key={key + 'transactions'}>
<div className="flex">
<i className="material-icons md-22">account_balance_wallet</i>
<p style={{ margin: '0 0 0 10px' }}>{this.t('txs')}</p>
</div>
</Menu.Item>
<Menu.Item disabled={disabled} key={key + 'send'}>
<div className="flex">
<i className="material-icons md-22">send</i>
<p style={{ margin: '0 0 0 10px' }}>{this.t('send')}</p>
</div>
</Menu.Item>
<Menu.Item disabled={disabled} key={key + 'network/info'}>
<div className="flex">
<i className="material-icons md-22">public</i>
<p style={{ margin: '0 0 0 10px' }}>{this.t('net')}</p>
</div>
</Menu.Item>
<Menu.Item disabled={disabled} key={key + 'maintenance/general'}>
<div className="flex">
<i className="material-icons md-22">settings</i>
<p style={{ margin: '0 0 0 10px' }}>{this.t('maint')}</p>
</div>
</Menu.Item>
<Menu.Item key="/">
<div className="flex">
<i className="material-icons md-22">cast_connected</i>
<p style={{ margin: '0 0 0 10px' }}>{this.t('connManager')}</p>
</div>
</Menu.Item>
</Menu>
)
}
}
export default withRouter(MainMenu)
|
src/containers/DevTools/DevTools.js
|
UncleYee/crm-ui
|
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>
);
|
src/components/library/managed/books/LibraryBooks.js
|
great-design-and-systems/cataloguing-app
|
import { FontAwesome, ResponsiveButton } from '../../../common/';
import {
LABEL_AUTHOR,
LABEL_EDITION,
LABEL_LIBRARY_BOOKS,
LABEL_PUBLISHER,
LABEL_SUB_TITLE,
LABEL_TITLE
} from '../../../../labels/';
import { Book } from '../../../../api/books/';
import PropTypes from 'prop-types';
import React from 'react';
export const LibraryBooks = ({ books, onRemove }) => {
return (
<div className="col-lg-6">
<fieldset>
<legend>{LABEL_LIBRARY_BOOKS}</legend>
<table className="table table-hover table-condensed table-striped">
<thead>
<th />
<th>{LABEL_TITLE}</th>
<th>{LABEL_SUB_TITLE}</th>
<th>{LABEL_EDITION}</th>
<th>{LABEL_AUTHOR}</th>
<th>{LABEL_PUBLISHER}</th>
</thead>
<tbody>
{books.map((book, index) => (
<tr key={book[Book.BOOK_ID]}>
<td>
<ResponsiveButton onClick={() => { onRemove(book, index); }} className="btn btn-danger"
icon={<FontAwesome name="trash" size="lg" fixedWidth={true} />} />
</td>
<td>{book[Book.TITLE]}</td>
<td>{book[Book.SUB_TITLE]}</td>
<td>{book[Book.EDITION]}</td>
<td>{book[Book.AUTHOR]}</td>
<td>{book[Book.PUBLISHER]}</td>
</tr>
))}
</tbody>
</table>
</fieldset>
</div>);
};
LibraryBooks.propTypes = {
books: PropTypes.array.isRequired,
onRemove: PropTypes.func.isRequired
};
|
packages/@lyra/vision/src/LyraVision.js
|
VegaPublish/vega-studio
|
import React from 'react'
import lyraClient from 'part:@lyra/base/client'
import Button from 'part:@lyra/components/buttons/default'
import schema from 'part:@lyra/base/schema?'
import Select from './lyra/Select'
import Vision from './Vision'
import visionGui from './css/visionGui.css'
import jsonInspector from './css/jsonInspector.css'
import jsonDump from './css/jsonDump.css'
const components = {
Button,
Select
}
const styles = {
jsonDump,
visionGui,
jsonInspector
}
const client = lyraClient.clone()
// Used in Lyra project
function LyraVision() {
return (
<Vision
styles={styles}
components={components}
client={client}
schema={schema}
/>
)
}
module.exports = LyraVision
|
docs/src/pages/components/accordion/DetailedAccordion.js
|
lgollut/material-ui
|
import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import clsx from 'clsx';
import Accordion from '@material-ui/core/Accordion';
import AccordionDetails from '@material-ui/core/AccordionDetails';
import AccordionSummary from '@material-ui/core/AccordionSummary';
import AccordionActions from '@material-ui/core/AccordionActions';
import Typography from '@material-ui/core/Typography';
import ExpandMoreIcon from '@material-ui/icons/ExpandMore';
import Chip from '@material-ui/core/Chip';
import Button from '@material-ui/core/Button';
import Divider from '@material-ui/core/Divider';
const useStyles = makeStyles((theme) => ({
root: {
width: '100%',
},
heading: {
fontSize: theme.typography.pxToRem(15),
},
secondaryHeading: {
fontSize: theme.typography.pxToRem(15),
color: theme.palette.text.secondary,
},
icon: {
verticalAlign: 'bottom',
height: 20,
width: 20,
},
details: {
alignItems: 'center',
},
column: {
flexBasis: '33.33%',
},
helper: {
borderLeft: `2px solid ${theme.palette.divider}`,
padding: theme.spacing(1, 2),
},
link: {
color: theme.palette.primary.main,
textDecoration: 'none',
'&:hover': {
textDecoration: 'underline',
},
},
}));
export default function DetailedAccordion() {
const classes = useStyles();
return (
<div className={classes.root}>
<Accordion defaultExpanded>
<AccordionSummary
expandIcon={<ExpandMoreIcon />}
aria-controls="panel1c-content"
id="panel1c-header"
>
<div className={classes.column}>
<Typography className={classes.heading}>Location</Typography>
</div>
<div className={classes.column}>
<Typography className={classes.secondaryHeading}>Select trip destination</Typography>
</div>
</AccordionSummary>
<AccordionDetails className={classes.details}>
<div className={classes.column} />
<div className={classes.column}>
<Chip label="Barbados" onDelete={() => {}} />
</div>
<div className={clsx(classes.column, classes.helper)}>
<Typography variant="caption">
Select your destination of choice
<br />
<a href="#secondary-heading-and-columns" className={classes.link}>
Learn more
</a>
</Typography>
</div>
</AccordionDetails>
<Divider />
<AccordionActions>
<Button size="small">Cancel</Button>
<Button size="small" color="primary">
Save
</Button>
</AccordionActions>
</Accordion>
</div>
);
}
|
app/containers/TransactionsPage.js
|
soosgit/vessel
|
// @flow
import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { Redirect } from 'react-router';
import { connect } from 'react-redux';
import { Dimmer, Header, Loader, Segment } from 'semantic-ui-react';
import MenuBar from './MenuBar';
import Balances from '../components/Transactions/Balances';
import PendingRewards from '../components/Transactions/PendingRewards';
import ContentBar from '../components/ContentBar';
import * as AccountActions from '../actions/account';
import * as ProcessingActions from '../actions/processing';
import * as KeysActions from '../actions/keys';
import * as SteemActions from '../actions/steem';
class TransactionsPage extends Component {
render() {
let account_data = (
<Dimmer inverted active style={{minHeight: '100px', display: 'block'}}>
<Loader size="large" content="Loading"/>
</Dimmer>
)
if (!this.props.keys.isUser) {
return <Redirect to="/" />;
} else {
account_data = (
<Segment basic attached>
<PendingRewards {...this.props} />
<Balances {...this.props} />
</Segment>
);
}
return (
<ContentBar>
<Segment padded attached secondary>
<Header
icon="lightning"
content="Account Balances"
subheader="The total balance of all accounts and the individual balances of each account."
/>
</Segment>
{account_data}
<MenuBar />
</ContentBar>
);
}
}
function mapStateToProps(state) {
return {
account: state.account,
account_data: state.account_data,
keys: state.keys,
processing: state.processing,
steem: state.steem
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators({
...AccountActions,
...KeysActions,
...ProcessingActions,
...SteemActions,
}, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(TransactionsPage);
|
node_modules/babel-plugin-react-transform/test/fixtures/code-ignore/actual.js
|
Technaesthetic/ua-tools
|
import React from 'react';
const First = React.createNotClass({
displayName: 'First'
});
class Second extends React.NotComponent {}
|
src/client/components/Home.js
|
josh--newman/blog
|
import React from 'react';
import { Link } from 'react-router';
import { SideBar } from './Shared';
import MainContent from './MainContent';
const links = [
<Link key='about' to='/'>About this blog</Link>,
<Link key='12ppm' to='/'>12PPM challenge</Link>,
<Link key='admin' to='/signin'>Sign in</Link>
];
const styles = {
display: 'flex',
maxWidth: '1280px'
};
class Home extends React.Component {
render() {
return (
<div style={styles}>
<SideBar links={links} withBio />
<MainContent />
</div>
);
}
}
export default Home;
|
src/scripts/components/control-panel.js
|
brandly/ss15-queso
|
/** @jsx REACT.DOM */
import React from 'react';
import PianoKeyboard from './piano-keyboard';
import MicRecorder from './mic-recorder';
import SynthShape from './synth-shape';
export default React.createClass({
render: function () {
const trackType = this.props.track ? this.props.track.type : null;
const isMIDI = trackType === 'MIDI';
return (
<div className="control-panel">
<PianoKeyboard track={this.props.track} queso={this.props.queso} />
<SynthShape track={this.props.track} queso={this.props.queso} />
</div>
);
}
});
|
docs/src/sections/PopoverSection.js
|
lzcmaro/react-ratchet
|
import React from 'react';
import Samples from '../Samples'
import ReactPlayground from '../ReactPlayground'
export default function PopoverSection() {
return (
<div>
{/* Popovers */}
<ReactPlayground id="popovers" title='Popovers' desc='Popovers are designed to only fire from title bars. Set the value of the title href to the id of a popover, like so:' codeText={Samples.NavPopover} />
</div>
);
};
|
src/entry.js
|
doeg/skeleton
|
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import Root from './components/Root.jsx';
// Client render (optional):
if (typeof document !== 'undefined') {
// Client render code goes here...
}
// Exported static site renderer.
// @param locals.path - The path currently being rendered
// @param locals.assets - An object containing all assets
// @param locals.webpackStats - Advanced: Webpack's stats object
//
module.exports = function render(locals, callback) {
const html = ReactDOMServer.renderToStaticMarkup(
<Root assets={locals.assets} />
);
callback(null, `<!DOCTYPE html>${html}`);
};
|
src/components/UIShell/HeaderNavigation.js
|
joshblack/carbon-components-react
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import { settings } from 'carbon-components';
import cx from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { AriaLabelPropType } from '../../prop-types/AriaPropTypes';
const { prefix } = settings;
export default class HeaderNavigation extends React.Component {
static propTypes = {
/**
* Required props for accessibility label on the underlying menu
*/
...AriaLabelPropType,
/**
* Optionally provide a custom class to apply to the underlying <nav> node
*/
className: PropTypes.string,
/**
* Provide valid children of HeaderNavigation, for example `HeaderMenuItem`
* or `HeaderMenu`
*/
children: PropTypes.node,
};
constructor(props) {
super(props);
this.items = [];
this.state = {
selectedIndex: 0,
};
}
/**
* Handles individual menuitem refs. We assign them to a class instance
* property so that we can properly manage focus of our children.
*/
handleItemRef = index => node => {
this.items[index] = node;
};
render() {
const {
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
children,
className: customClassName,
...rest
} = this.props;
const className = cx(`${prefix}--header__nav`, customClassName);
// Assign both label strategies in this option, only one should be defined
// so when we spread that should be the one that is applied to the node
const accessibilityLabel = {
'aria-label': ariaLabel,
'aria-labelledby': ariaLabelledBy,
};
return (
<nav {...rest} {...accessibilityLabel} className={className}>
<ul
{...accessibilityLabel}
className={`${prefix}--header__menu-bar`}
role="menubar">
{React.Children.map(children, this._renderNavItem)}
</ul>
</nav>
);
}
/**
* Render an individual menuitem, adding a `ref` for each child inside of
* `this.items` to properly manage focus.
*/
_renderNavItem = (child, index) => {
return React.cloneElement(child, {
ref: this.handleItemRef(index),
});
};
}
|
examples/react-client/src/routes/shows/ShowRoute.js
|
mobx-little-router/mobx-little-router
|
import React from 'react'
import { inject, observer } from 'mobx-react'
import styled from 'styled-components'
import { Link } from 'mobx-little-router-react'
import Modal from '../../components/Modal'
const ShowRoute = ({ route: { params, query }, className, ShowsStore }) => {
let prevShow, nextShow
if (ShowsStore.shows && ShowsStore.shows.length > 0) {
const currIdx = ShowsStore.shows.findIndex(show => show.id === Number(params.id))
if (currIdx > 0) {
prevShow = ShowsStore.shows[currIdx - 1]
}
if (currIdx < ShowsStore.shows.length - 1) {
nextShow = ShowsStore.shows[currIdx + 1]
}
}
const model = ShowsStore.getDetails(params.id)
return (
<Modal className={className} closePath={`/shows?q=${query.q}`}>
{model &&
<Content>
{model.image &&
<CoverImage style={{ backgroundImage: `url(${model.image.original})` }} />}
<Abstract>
<Navigation>
{prevShow &&
<PrevNavigationLink to={`/shows/${prevShow.id}?q=${query.q}`}>
Prev
</PrevNavigationLink>}
{nextShow &&
<NextNavigationLink to={`/shows/${nextShow.id}?q=${query.q}`}>
Next
</NextNavigationLink>}
</Navigation>
<Network>{model.network && model.network.name}</Network>
<Title>{model.name}</Title>
<OfficialSite href={model.officialSite} target="_blank">
Official site
</OfficialSite>
<Summary dangerouslySetInnerHTML={{ __html: model.summary }} />
<Tags>
{model.genres &&
model.genres.map((genre, idx) =>
<Link key={idx} to={`/tags/${genre}`}>{genre}</Link>
)}
</Tags>
<Cast>
<h2>Cast</h2>
{model._embedded.cast.map((member, idx) =>
<CastMember key={idx}>
<Character>{member.character.name}</Character>
<Actor to={`/actors/${member.person.id}`}>{member.person.name}</Actor>
</CastMember>
)}
</Cast>
</Abstract>
</Content>}
</Modal>
)
}
const Content = styled.div`
display: flex;
flex-direction: row;
width: 100%;
height: 100%;
`
const CoverImage = styled.div`
display: block;
width: 50%;
background-position: 50% 50%;
background-size: cover;
position: relative;
&::before {
display: block;
content: "";
height: 5px;
width: 100%;
position: absolute;
top: 0;
left: 0;
background-image: linear-gradient(rgba(255, 255, 255, 0.4), transparent);
}
&::after {
display: block;
content: "";
height: 5px;
width: 100%;
position: absolute;
bottom: 0;
left: 0;
background-image: linear-gradient(transparent, rgba(0,0,0,0.4));
}
`
const Abstract = styled.div`
padding: 72px 36px 0;
width: 50%;
overflow-y: auto;
position: relative;
`
const Navigation = styled.div`
display: flex;
flex-direction: row;
justify-content: space-between;
position: absolute;
top: 0;
left: 36px;
right: 54px;
line-height: 36px;
margin: 18px 0;
`
const NavigationLink = styled(Link)`
font-size: 13px;
line-height: 18px;
color: #777;
&:hover {
color: #333;
}
`
const PrevNavigationLink = styled(NavigationLink)`
margin-right: auto;
`
const NextNavigationLink = styled(NavigationLink)`
margin-left: auto;
`
const Title = styled.h1`
color: #333;
margin: 0 0 18px;
`
const Summary = styled.p`
color: #666;
line-height: 18px;
font-size: 13px;
`
const Network = styled.div`
text-transform: uppercase;
color: #aaa;
font-size: 12px;
`
const OfficialSite = styled.a`
font-size: 13px;
line-height: 18px;
color: #777;
&:hover {
color: #333;
}
`
const Tags = styled.div`
margin: 18px 0;
> a {
font-size: 12px;
color: #079;
margin-right: 9px;
display: inline-block;
text-decoration: none;
border-radius: 9px;
background-color: #eee;
padding: 0 9px;
line-height: 18px;
color: #999;
}
`
const Cast = styled.div`
font-size: 13px;
line-height: 18px;
margin: 36px 0;
`
const CastMember = styled.div`
display: flex;
flex-direction: row;
padding: 9px 0;
`
const Character = styled.div`
width: 50%;
`
const Actor = styled(Link)`
width: 50%;
color: #777;
&:hover {
color: #333;
}
`
export default inject('ShowsStore')(observer(ShowRoute))
|
app/javascript/mastodon/components/status.js
|
8796n/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Avatar from './avatar';
import AvatarOverlay from './avatar_overlay';
import RelativeTimestamp from './relative_timestamp';
import DisplayName from './display_name';
import MediaGallery from './media_gallery';
import VideoPlayer from './video_player';
import AttachmentList from './attachment_list';
import StatusContent from './status_content';
import StatusActionBar from './status_action_bar';
import { FormattedMessage } from 'react-intl';
import emojify from '../emoji';
import escapeTextContentForBrowser from 'escape-html';
import ImmutablePureComponent from 'react-immutable-pure-component';
class Status extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object
};
static propTypes = {
status: ImmutablePropTypes.map,
account: ImmutablePropTypes.map,
wrapped: PropTypes.bool,
onReply: PropTypes.func,
onFavourite: PropTypes.func,
onReblog: PropTypes.func,
onDelete: PropTypes.func,
onOpenMedia: PropTypes.func,
onOpenVideo: PropTypes.func,
onBlock: PropTypes.func,
me: PropTypes.number,
boostModal: PropTypes.bool,
autoPlayGif: PropTypes.bool,
muted: PropTypes.bool
};
handleClick = () => {
const { status } = this.props;
this.context.router.push(`/statuses/${status.getIn(['reblog', 'id'], status.get('id'))}`);
}
handleAccountClick = (id, e) => {
if (e.button === 0) {
e.preventDefault();
this.context.router.push(`/accounts/${id}`);
}
}
render () {
let media = '';
let statusAvatar;
const { status, account, ...other } = this.props;
if (status === null) {
return <div />;
}
if (status.get('reblog', null) !== null && typeof status.get('reblog') === 'object') {
let displayName = status.getIn(['account', 'display_name']);
if (displayName.length === 0) {
displayName = status.getIn(['account', 'username']);
}
const displayNameHTML = { __html: emojify(escapeTextContentForBrowser(displayName)) };
return (
<div className='status__wrapper'>
<div className='status__prepend'>
<div className='status__prepend-icon-wrapper'><i className='fa fa-fw fa-retweet status__prepend-icon' /></div>
<FormattedMessage id='status.reblogged_by' defaultMessage='{name} boosted' values={{ name: <a onClick={this.handleAccountClick.bind(this, status.getIn(['account', 'id']))} href={status.getIn(['account', 'url'])} className='status__display-name muted'><strong dangerouslySetInnerHTML={displayNameHTML} /></a> }} />
</div>
<Status {...other} wrapped={true} status={status.get('reblog')} account={status.get('account')} />
</div>
);
}
if (status.get('media_attachments').size > 0 && !this.props.muted) {
if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
media = <VideoPlayer media={status.getIn(['media_attachments', 0])} sensitive={status.get('sensitive')} onOpenVideo={this.props.onOpenVideo} />;
} else {
media = <MediaGallery media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={this.props.onOpenMedia} autoPlayGif={this.props.autoPlayGif} />;
}
}
if (account === undefined || account === null) {
statusAvatar = <Avatar src={status.getIn(['account', 'avatar'])} staticSrc={status.getIn(['account', 'avatar_static'])} size={48}/>;
}else{
statusAvatar = <AvatarOverlay staticSrc={status.getIn(['account', 'avatar_static'])} overlaySrc={account.get('avatar_static')} />;
}
return (
<div className={`status ${this.props.muted ? 'muted' : ''} status-${status.get('visibility')}`}>
<div className='status__info'>
<div className='status__info-time'>
<a href={status.get('url')} className='status__relative-time' target='_blank' rel='noopener'><RelativeTimestamp timestamp={status.get('created_at')} /></a>
</div>
<a onClick={this.handleAccountClick.bind(this, status.getIn(['account', 'id']))} href={status.getIn(['account', 'url'])} className='status__display-name'>
<div className='status__avatar'>
{statusAvatar}
</div>
<DisplayName account={status.get('account')} />
</a>
</div>
<StatusContent status={status} onClick={this.handleClick} />
{media}
<StatusActionBar {...this.props} />
</div>
);
}
}
export default Status;
|
examples/src/App.js
|
Chrisui/react-hotkeys
|
import { HotKeys, GlobalHotKeys, ObserveKeys, getApplicationKeyMap } from 'react-hotkeys';
import React from 'react';
import Node from './Node';
import HOCWrappedNode from './HOCWrappedNode';
const keyMap = {
DELETE: { name: 'Disable square', sequence: 'backspace', action: 'keyup'},
EXPAND: { name: 'Expand square area', sequence: 'alt+up' },
CONTRACT: { name: 'Reduce square area', sequence: 'alt+down' },
MOVE_UP: { name: 'Move square up', sequence: 'up' },
MOVE_DOWN: { name: 'Move square down', sequence: 'down' },
MOVE_LEFT: { name: 'Move square left', sequence: 'left' },
MOVE_RIGHT: { name: 'Move square right', sequence: 'right' }
};
const globalKeyMap = {
KONAMI: { name: 'Konami code', sequence: 'up up down down left right left right b a enter' },
LOG_DOWN: { name: 'Log Cmd Down', sequence: 'command', action: 'keydown'},
LOG_UP: { name: 'Log Cmd Up', sequence: 'command', action: 'keyup'},
SHOW_DIALOG: { name: 'Display keyboard shortcuts', sequence: 'shift+?', action: 'keyup' },
};
const styles = {
DIALOG: {
width: 600,
position: 'fixed',
top: '50%',
left: '50%',
transform: 'translate(-50%, -50%)',
padding: '0 24',
backgroundColor: 'white',
zIndex: 100,
color: 'rgba(0,0,0,0.87)'
},
KEYMAP_TABLE_CELL: {
padding: 8
}
};
class App extends React.Component {
static logCommandKeyDown() {
console.log('command down');
}
static logCommandKeyUp() {
console.log('command up');
}
constructor(props, context) {
super(props, context);
this.onKonami = this.onKonami.bind(this);
this.state = {
konamiTime: false,
showDialog: false,
filter: '',
};
}
onKonami() {
this.setState({konamiTime: true});
}
renderDialog() {
if (this.state.showDialog) {
const keyMap = getApplicationKeyMap();
const { filter } = this.state;
const _filter = filter.toUpperCase();
return (
<HotKeys
keyMap={{CLOSE_DIALOG: 'Escape' }}
handlers={{ CLOSE_DIALOG: () => this.setState({ showDialog: false })} }
>
<div style={styles.DIALOG}>
<h2>
Keyboard shortcuts
</h2>
<ObserveKeys only={'Escape'}>
<input
autoFocus
onChange={({target: {value}}) => this.setState({ filter: value })}
value={filter}
placeholder='Filter'
/>
</ObserveKeys>
<table>
<tbody>
{ Object.keys(keyMap).reduce((memo, actionName) => {
if (filter.length === 0 || actionName.indexOf(_filter) !== -1) {
const { sequences, name } = keyMap[actionName];
memo.push(
<tr key={name || actionName}>
<td style={styles.KEYMAP_TABLE_CELL}>
{ name }
</td>
<td style={styles.KEYMAP_TABLE_CELL}>
{ sequences.map(({sequence}) => <span key={sequence}>{sequence}</span>) }
</td>
</tr>
)
}
return memo;
}, []) }
</tbody>
</table>
</div>
</HotKeys>
);
}
}
render() {
const {konamiTime} = this.state;
const globalHandlers = {
KONAMI: this.onKonami,
LOG_DOWN: this.constructor.logCommandKeyDown,
LOG_UP: this.constructor.logCommandKeyUp,
SHOW_DIALOG: () => this.setState({ showDialog: !this.state.showDialog })
};
const className = konamiTime ? 'viewport konamiTime' : 'viewport';
return (
<React.StrictMode>
<GlobalHotKeys
keyMap={globalKeyMap}
handlers={globalHandlers}
global
/>
{ this.renderDialog() }
<HotKeys keyMap={keyMap}>
<div className="app">
<div className="tips">
<ul>
<li>Select a node and move it with your arrow keys</li>
<li>Expand or contract a node with `alt+up` or `alt+down` respectively</li>
<li>Delete a node with `delete` or `backspace`</li>
<li>How about the konami code? `up up down down left right left right b a enter`</li>
<li>Want to get started? <a href="https://github.com/greena13/react-hotkeys/blob/master/README.md">Read the guide.</a></li>
</ul>
</div>
<div className={className}>
<HOCWrappedNode />
<div>
{Array.apply(null, new Array(10)).map((e, i) => <Node key={i} />)}
</div>
</div>
</div>
</HotKeys>
</React.StrictMode>
);
}
}
export default App;
|
src/helpers/validation/getErrorMessage.js
|
expdevelop/ultrastore
|
import React from 'react'
import Container from 'components/Container/Container'
import List from 'components/List/List'
import Title from 'components/Title/Title'
import isEmpty from '../app/isEmpty'
export default function getErrorMessage(err, isReact) {
if (isEmpty(err))
return null;
if (typeof err === 'string')
return err;
let error = 'Ошибка';
if (!!err.length && isReact) {
return (
<Container type="article">
<Title center>Ошибка</Title>
<List data={err}/>
</Container>
)
}
if (!!err.length) {
const errors = err.join('\n');
return `Ошибки: ${errors}`;
}
if (err.status != null) {
const status = parseInt(err.status, 10);
if (status === 0) {
error += `: нет подключения к сети.`
} else {
error += `: ${err.status}`
}
}
if (err.statusText != null) {
if (!isEmpty(err.statusText))
error += `, ${err.statusText}`
}
return error;
}
|
src/js/components/icons/base/History.js
|
linde12/grommet
|
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-history`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'history');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M1,12 C1,18.075 5.925,23 12,23 C18.075,23 23,18.075 23,12 C23,5.925 18.075,1 12,1 C7.563,1 4,4 2,7.5 M1,1 L1,8 L8,8 M16,17 L12,13 L12,6"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'History';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
react-apollo/src/containers/NotFoundPage/index.js
|
strapi/strapi-examples
|
/**
*
* NotFoundPage
* This is the component that will show when you have a 404
*/
import React from 'react';
function NotFoundPage(props) {
return (
<div>
<p>The page you're looking for doesn't exist.</p>
</div>
);
}
export default NotFoundPage;
|
app/components/PointListItem/index.js
|
GuiaLa/guiala-web-app
|
/**
*
* PointListItem
*
*/
import React from 'react';
import { Link } from 'react-router';
import {Card, CardActions, CardMedia, CardTitle, CardText} from 'material-ui/Card';
import Star from 'Star';
import AddToItinerary from 'AddToItinerary';
import FlatButton from 'material-ui/FlatButton';
import MoreHoriz from 'material-ui/svg-icons/navigation/more-horiz'
import styles from './styles.css';
const lorem = "Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum."
function PointListItem({ name, slug, description = lorem , region, _id, place }) {
return (
<div className={ styles.wrapper }>
<Card>
<CardMedia
overlayContentStyle={{background: 'linear-gradient(to top, rgba(0,0,0,0.7) 0%,rgba(0,0,0,0.3) 70%,rgba(0,0,0,0) 100%)'}}
overlayContainerStyle={{background: 'linear-gradient(to bottom, rgba(0,0,0,0.45) 0%,rgba(0,0,0,0.3) 24%,rgba(0,0,0,0) 100%)'}}
overlay={<CardTitle title={name} subtitle={region || 'região'} />}
>
<img src={require('../../assets/anjos.jpg')} />
</CardMedia>
<CardText>
{ description.split(/\s+/).slice(0,20).join(" ")+"..." }
</CardText>
<CardActions>
<FlatButton label={<Star _id={_id} />} />
<FlatButton label={<AddToItinerary _id={_id} />} />
<FlatButton label={<Link to={`/${place}/${slug}`}><MoreHoriz /></Link>} />
</CardActions>
</Card>
</div>
);
}
export default PointListItem;
|
frontend/src/components/Timer/index.js
|
XiaocongDong/mongodb-backup-manager
|
import React, { Component } from 'react';
import time from 'utility/time';
export default class Timer extends Component {
constructor(props) {
super(props);
this.timer = null;
this.state = {
remain: null
};
this.getRemain = this.getRemain.bind(this);
this.updateRemain = this.updateRemain.bind(this);
}
componentDidMount() {
this.timer = setInterval(this.updateRemain, 1000);
}
getRemain() {
const endTime = this.props.endTime;
const endDate = new Date(endTime);
const now = new Date();
return endDate - now;
}
updateRemain() {
const remain = time.getTimeStringFromMilliseconds(this.getRemain());
this.setState({
remain
})
}
componentWillUnmount() {
clearInterval(this.timer);
}
render() {
const remain = this.state.remain;
return (
<span className="timer">
{ remain || ""}
</span>
)
}
}
|
__tests__/index.android.js
|
nikolay-radkov/EBudgie
|
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 />
);
});
|
core/js/index.js
|
orgdown/orgdown-notebook
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render((
<App />
), document.getElementById('content'));
|
fields/types/location/LocationFilter.js
|
asifiqbal84/keystone
|
import _ from 'underscore';
import classNames from 'classnames';
import React from 'react';
import { FormField, FormInput, FormRow, SegmentedControl } from 'elemental';
const MODE_OPTIONS = [
{ label: 'Exactly', value: 'exactly' },
{ label: 'Contains', value: 'contains' }
];
const TOGGLE_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true }
];
var TextFilter = React.createClass({
getInitialState () {
return {
inverted: TOGGLE_OPTIONS[0].value,
city: '',
state: '',
code: '',
country: ''
};
},
componentDidMount () {
// focus the text focusTarget
React.findDOMNode(this.refs.focusTarget).focus();
},
toggleInverted (value) {
this.setState({
inverted: value
});
},
render () {
let { modeLabel, modeValue } = this.state;
return (
<div>
<FormField>
<SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={this.toggleInverted} />
</FormField>
<FormField>
<FormInput ref="focusTarget" placeholder="Address" />
</FormField>
<FormRow>
<FormField width="two-thirds">
<FormInput placeholder="City" value={this.state.city} />
</FormField>
<FormField width="one-third">
<FormInput placeholder="State" value={this.state.state} />
</FormField>
<FormField width="one-third" style={{ marginBottom: 0 }}>
<FormInput placeholder="Postcode" value={this.state.code} />
</FormField>
<FormField width="two-thirds" style={{ marginBottom: 0 }}>
<FormInput placeholder="Country" value={this.state.country} />
</FormField>
</FormRow>
</div>
);
}
});
module.exports = TextFilter;
|
src/svg-icons/action/flip-to-back.js
|
mit-cml/iot-website-source
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionFlipToBack = (props) => (
<SvgIcon {...props}>
<path d="M9 7H7v2h2V7zm0 4H7v2h2v-2zm0-8c-1.11 0-2 .9-2 2h2V3zm4 12h-2v2h2v-2zm6-12v2h2c0-1.1-.9-2-2-2zm-6 0h-2v2h2V3zM9 17v-2H7c0 1.1.89 2 2 2zm10-4h2v-2h-2v2zm0-4h2V7h-2v2zm0 8c1.1 0 2-.9 2-2h-2v2zM5 7H3v12c0 1.1.89 2 2 2h12v-2H5V7zm10-2h2V3h-2v2zm0 12h2v-2h-2v2z"/>
</SvgIcon>
);
ActionFlipToBack = pure(ActionFlipToBack);
ActionFlipToBack.displayName = 'ActionFlipToBack';
ActionFlipToBack.muiName = 'SvgIcon';
export default ActionFlipToBack;
|
examples/example-react/components/Header.js
|
risetechnologies/fela
|
import React from 'react'
import { createComponentWithProxy } from 'react-fela'
const Header = ({ title, className }) => (
<div className={className}>{title}</div>
)
const rule = () => ({
'@media (min-width: 1024px)': {
color: 'red',
},
color: 'rgb(50, 50, 50)',
fontSize: 100,
padding: 50,
':hover': { animationDuration: '500ms' },
'@supports (-webkit-flex:1)': {
fontFamily: 'Impact',
},
'@media (min-width: 480px)': {
color: 'blue',
},
'@media (max-width: 800px)': {
'@supports (-webkit-flex:1)': {
fontSize: 180,
},
fontSize: '40px',
},
animationDuration: '2s',
animationIterationCount: 'infinite',
animationName: {
'0%': { color: 'green' },
'50%': { color: 'blue' },
'80%': { color: 'purple' },
'100%': { color: 'green' },
},
})
export default createComponentWithProxy(rule, Header)
|
src/svg-icons/places/beach-access.js
|
andrejunges/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let PlacesBeachAccess = (props) => (
<SvgIcon {...props}>
<path d="M13.127 14.56l1.43-1.43 6.44 6.443L19.57 21zm4.293-5.73l2.86-2.86c-3.95-3.95-10.35-3.96-14.3-.02 3.93-1.3 8.31-.25 11.44 2.88zM5.95 5.98c-3.94 3.95-3.93 10.35.02 14.3l2.86-2.86C5.7 14.29 4.65 9.91 5.95 5.98zm.02-.02l-.01.01c-.38 3.01 1.17 6.88 4.3 10.02l5.73-5.73c-3.13-3.13-7.01-4.68-10.02-4.3z"/>
</SvgIcon>
);
PlacesBeachAccess = pure(PlacesBeachAccess);
PlacesBeachAccess.displayName = 'PlacesBeachAccess';
PlacesBeachAccess.muiName = 'SvgIcon';
export default PlacesBeachAccess;
|
code-samples/js/ViroMediaPlayer/Viro360Theatre.js
|
viromedia/viro
|
'use strict';
/**
* Pull in all imports required for the controls within this scene.
*/
import React, { Component } from 'react';
import {StyleSheet} from 'react-native';
import {
AppRegistry,
ViroScene,
ViroVideo,
ViroSceneNavigator,
ViroMaterials,
Viro360Video,
ViroButton,
ViroImage,
ViroNode,
ViroAnimations,
} from 'react-viro';
var createReactClass = require('create-react-class');
/**
* Set all the image and asset references required in this scene.
*/
var buttonSize = 0.25;
var VIDEO_REF = "videoref";
/**
* Several references to video sources (wether it be local or on AWS) stored in an array.
*/
var videos = [
{uri:'https://s3-us-west-2.amazonaws.com/viro/MediaDemo360_1.mp4'},
{uri:'https://s3-us-west-2.amazonaws.com/viro/MediaDemo360_2.mp4'}
];
var Viro360Theatre = createReactClass({
getInitialState() {
return {
videoControlsAnimation:"fadeIn",
videoPaused: false,
loopVideo: true,
videoIndex: 0,
runAnimation: false,
}
},
/**
* Renders a scene that contains a 360 video and Video Controls.
*/
render: function() {
return (
<ViroScene onClick={this._onVideoTapped} reticleEnabled={this.state.videoControlsAnimation=="fadeIn"}>
<Viro360Video ref={VIDEO_REF} source={videos[this.state.videoIndex]} volume={1.0}
loop={this.state.loopVideo} paused={this.state.videoPaused} />
{this._renderVideoControl()}
</ViroScene>
);
},
_onVideoTapped(){
var videoControlsAnimationState = this.state.videoControlsAnimation;
if (videoControlsAnimationState=="fadeIn"){
videoControlsAnimationState="fadeOut";
} else {
videoControlsAnimationState="fadeIn";
}
this.setState({
videoControlsAnimation:videoControlsAnimationState,
runAnimation: true,
});
},
/**
* Render a set of Video UI Controls. This includes (in the order displayed from left to right):
* Restart, Previous Video, Play/Pause, Next Video, Volume.
*/
_renderVideoControl(){
return(
<ViroNode position={[0,-0.8,0]} opacity={1.0}
animation={{name : this.state.videoControlsAnimation, run : this.state.runAnimation, loop : false}} >
<ViroImage
scale={[1.4, 1.2, 1]}
position={[0, -0.27,-2.1]}
source={require("./res/player_controls_container.png")} />
<ViroButton
position={[-buttonSize-0.1,0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/previous.png")}
hoverSource={require("./res/previous_hover.png")}
clickSource={require("./res/previous_hover.png")}
onClick={this._playPreviousVideo} />
{this._renderPlayControl()}
<ViroButton
position={[buttonSize+0.1, 0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/skip.png")}
hoverSource={require("./res/skip_hover.png")}
clickSource={require("./res/skip_hover.png")}
onClick={this._playNextVideo} />
<ViroButton
position={[-0.3, -0.4 ,-2]}
scale={[1, 1, 1]}
width={0.5}
height={0.5}
source={require("./res/icon_2D.png")}
hoverSource={require("./res/icon_2D_hover.png")}
clickSource={require("./res/icon_2D_hover.png")}
onClick={this._launchTheatreScene} />
<ViroButton
position={[0.3, -0.4 ,-2]}
scale={[1, 1, 1]}
width={0.5}
height={0.5}
source={require("./res/icon_360_hover.png")}
hoverSource={require("./res/icon_360_hover.png")}
clickSource={require("./res/icon_360_hover.png")} />
</ViroNode>
);
},
/**
* Renders either the play or pause icon depending on video state.
*/
_renderPlayControl(){
if (this.state.videoPaused){
return (
<ViroButton
position={[0,0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/play.png")}
hoverSource={require("./res/play_hover.png")}
clickSource={require("./res/play_hover.png")}
transformBehaviors={["billboard"]}
onClick={this._togglePauseVideo}/>
);
} else {
return (
<ViroButton
position={[0,0,-2]}
scale={[1, 1, 1]}
width={buttonSize}
height={buttonSize}
source={require("./res/pause.png")}
hoverSource={require("./res/pause_hover.png")}
clickSource={require("./res/pause_hover.png")}
transformBehaviors={["billboard"]}
onClick={this._togglePauseVideo}/>
);
}
},
_launchTheatreScene(){
this.props.sceneNavigator.jump("ViroTheatre", {scene:require('./ViroTheatre')});
},
_togglePauseVideo() {
this.setState({
videoPaused: !this.state.videoPaused,
})
},
/**
* Play the previous video by setting the videoIndex.
*/
_playPreviousVideo(){
var currentVideo = this.state.videoIndex;
if (currentVideo - 1 > -1){
this.setState({
videoIndex: (currentVideo - 1),
videoPaused: false
});
}
},
/**
* Play the next video by setting the videoIndex.
*/
_playNextVideo(){
var currentVideo = this.state.videoIndex;
if (currentVideo + 1 < videos.length){
this.setState({
videoIndex: (currentVideo + 1),
videoPaused: false
});
}
},
});
ViroAnimations.registerAnimations({
fadeOut:{properties:{opacity: 0.0}, duration: 500},
fadeIn:{properties:{opacity: 1.0}, duration: 500},
});
module.exports = Viro360Theatre;
|
website/components/Navbar/utils/makeSection.js
|
Pop-Code/keystone
|
import React from 'react';
import Link from 'gatsby-link';
import Item from '../Item';
export default function makeSection (currentPath, layer, pathname) {
return layer.map((section, idx) => {
const locationArray = pathname.split('/');
const currentSection = locationArray[locationArray.length - 1];
const menuItems = section.items.map((item, i) => {
const newPath = currentPath + section.slug;
// Secondary items
if (item.items) {
const subItems = item.items.map((subItem, sid) => (
<Item
isActive={currentSection === subItem.slug.split('/')[1] || (!subItem.slug && currentSection === item.slug.split('/')[1])}
key={subItem.slug + '__' + sid}
title={subItem.label}
url={newPath + item.slug + subItem.slug}
depth={2}
/>
));
return (
<div>
<Item
url={newPath + item.slug + item.items[0].slug}
title={item.section}
depth={1}
isExpandable
/>
{locationArray[2] === item.slug.split('/')[1] && subItems}
</div>
);
}
// Primary items
return (
<Item
isActive={
locationArray.length === 2
? !item.slug
: currentSection === item.slug.split('/')[1]
}
key={item.slug + '__' + i}
title={item.label}
url={newPath + item.slug}
depth={1}
/>
);
});
// Sections
return (
<div key={'section__' + idx}>
<Link to={section.slug} css={styles.sectionTitle}>
{section.section}
</Link>
{locationArray[1] === section.slug.split('/')[1] && menuItems}
</div>
);
});
}
const styles = {
sectionTitle: {
display: 'block',
color: 'white',
fontSize: '1rem',
textTransform: 'uppercase',
fontWeight: '600',
textDecoration: 'none',
padding: '0.625rem 1.875rem',
},
};
|
docs/app/Examples/elements/Segment/Groups/SegmentExampleSegments.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import { Segment } from 'semantic-ui-react'
const SegmentExampleSegments = () => (
<Segment.Group>
<Segment>Top</Segment>
<Segment>Middle</Segment>
<Segment>Middle</Segment>
<Segment>Middle</Segment>
<Segment>Bottom</Segment>
</Segment.Group>
)
export default SegmentExampleSegments
|
packages/icons/src/public.js
|
yldio/joyent-portal
|
import React from 'react';
import Rotate from './rotate';
import calcFill from './fill';
export default ({
fill = null,
light = false,
disabled = false,
direction = 'down',
colors = {},
style = {},
...rest
}) => (
<Rotate direction={direction}>
{({ style: rotateStyle }) => (
<svg
viewBox="0 0 12 16"
width="12"
height="16"
style={{ ...style, ...rotateStyle }}
{...rest}
>
<path
fill={calcFill({ fill, disabled, light, colors })}
d="M6,13H6a1,1,0,0,1-1-1V10A1,1,0,0,1,6,9H6a1,1,0,0,1,1,1v2A1,1,0,0,1,6,13Zm4-7V4A4,4,0,0,0,2,4H4c0-1.65.35-2,2-2s2,.35,2,2V6H2A2,2,0,0,0,0,8v6a2,2,0,0,0,2,2h8a2,2,0,0,0,2-2V8A2,2,0,0,0,10,6Zm0,7a1,1,0,0,1-1,1H3a1,1,0,0,1-1-1V9A1,1,0,0,1,3,8H9a1,1,0,0,1,1,1Z"
/>
</svg>
)}
</Rotate>
);
|
app/containers/Web3Alerts/NoInjected.js
|
VonIobro/ab-web
|
import React from 'react';
import { Wrapper } from './styles';
const NoInjected = () => (
<Wrapper theme="warning">
<h2>Account doesn´t exists or locked</h2>
<p>
Please, create or unlock MetaMask account
</p>
</Wrapper>
);
export default NoInjected;
|
src/components/cv.js
|
ateixeira/andreteixeira.info
|
import React from 'react';
import Info from "./cv/info"
import WorkExperience from "./cv/workexperience"
import AwardsSkills from "./cv/awardskills"
import data from "../data/seed"
module.exports = React.createClass({
// RENDER
render: function() {
return (
<div className="cv">
<div className="box">
<h1>CURRICULUM VITAE</h1>
<Info />
<WorkExperience experiences={data.EXPERIENCES}/>
<AwardsSkills skills={data.SKILLS}/>
</div>
<br/>
</div>
);
}
});
|
src/components/layout/sidebar/Sidebar.js
|
Gisto/Gisto
|
import React from 'react';
import { isEmpty, map, trim, startCase } from 'lodash/fp';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import styled, { withTheme } from 'styled-components';
import { SIDEBAR_WIDTH } from 'constants/config';
import { filterSnippetsList, isTag } from 'utils/snippets';
import * as snippetActions from 'actions/snippets';
import SnippetsList from 'components/layout/sidebar/SnippetsList';
import Snippet from 'components/layout/sidebar/Snippet';
import Icon from 'components/common/Icon';
const SideBarWrapper = styled.div`
width: ${SIDEBAR_WIDTH}px;
background: ${(props) => props.theme.baseAppColor};
display: flex;
flex-direction: column;
overflow: auto;
`;
const SearchFilters = styled.div`
color: ${(props) => props.theme.baseAppColor};
padding: 10px 20px;
background: ${(props) => props.theme.lightText};
z-index: 1;
border-top: 1px solid ${(props) => props.theme.borderColor};
box-shadow: 0 1px 2px ${(props) => props.theme.boxShadow};
font-size: 12px;
`;
const ClearAll = styled.a`
cursor: pointer;
color: ${(props) => props.theme.colorDanger};
white-space: nowrap;
`;
const Tag = styled.span`
border: 1px solid ${(props) => props.theme.baseAppColor};
color: ${(props) => props.theme.baseAppColor};
padding: 1px 3px;
border-radius: 3px;
margin-right: 3px;
`;
export const Sidebar = ({
snippets,
filterText,
filterTags,
filterLanguage,
clearFilters,
removeTag,
filterStatus,
filterTruncated,
filterUntagged,
theme
}) => {
const searchType = () => {
if (!isEmpty(trim(filterText))) {
return isTag(filterText) ? 'free text tag' : 'free text';
}
if (!isEmpty(filterTags)) {
return (
<span>
{'tags '}{' '}
{map(
(tag) => (
<Tag key={ tag }>
{tag}
<Icon
type="close"
clickable
size={ 12 }
onClick={ () => removeTag(tag) }
color={ theme.baseAppColor }/>
</Tag>
),
filterTags
)}
</span>
);
}
if (!isEmpty(trim(filterLanguage))) {
return `language: ${filterLanguage}`;
}
if (!isEmpty(filterStatus)) {
return startCase(filterStatus);
}
if (filterTruncated === true) {
return 'large files';
}
if (filterUntagged === true) {
return 'untagged';
}
return '';
};
const shouldShowFilteredBy =
!isEmpty(trim(filterText)) ||
!isEmpty(trim(filterTags)) ||
!isEmpty(trim(filterStatus)) ||
!isEmpty(trim(filterLanguage)) ||
filterTruncated ||
filterUntagged;
const snippetList = map(
(snippet) => <Snippet key={ snippet.id } snippet={ snippet }/>,
filterSnippetsList(
snippets,
filterText,
filterTags,
filterLanguage,
filterStatus,
filterTruncated,
filterUntagged
)
);
return (
<SideBarWrapper>
{shouldShowFilteredBy && (
<SearchFilters>
Filtered by <strong>{searchType()}</strong>
<ClearAll onClick={ () => clearFilters() }>
<Icon type="close-circle" size={ 12 } color={ theme.colorDanger }/>
<strong>clear</strong>
</ClearAll>
</SearchFilters>
)}
<SnippetsList>{snippetList}</SnippetsList>
</SideBarWrapper>
);
};
const mapStateToProps = (state) => ({
snippets: state.snippets.snippets,
filterText: state.snippets.filter.text,
filterTags: state.snippets.filter.tags,
filterLanguage: state.snippets.filter.language,
filterStatus: state.snippets.filter.status,
filterTruncated: state.snippets.filter.truncated,
filterUntagged: state.snippets.filter.untagged
});
Sidebar.propTypes = {
snippets: PropTypes.object,
theme: PropTypes.object,
filterText: PropTypes.string,
filterTags: PropTypes.array,
filterLanguage: PropTypes.string,
filterStatus: PropTypes.string,
clearFilters: PropTypes.func,
removeTag: PropTypes.func,
filterTruncated: PropTypes.bool,
filterUntagged: PropTypes.bool
};
export default withTheme(
connect(
mapStateToProps,
{
clearFilters: snippetActions.clearAllFilters,
removeTag: snippetActions.removeTagFromFilter
}
)(Sidebar)
);
|
fields/components/columns/ArrayColumn.js
|
tony2cssc/keystone
|
import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTable/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTable/ItemsTableValue';
var ArrayColumn = React.createClass({
displayName: 'ArrayColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue () {
const value = this.props.data.fields[this.props.col.path];
if (!value || !value.length) return null;
return value.join(', ');
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
},
});
module.exports = ArrayColumn;
|
blueocean-material-icons/src/js/components/svg-icons/image/brightness-2.js
|
jenkinsci/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageBrightness2 = (props) => (
<SvgIcon {...props}>
<path d="M10 2c-1.82 0-3.53.5-5 1.35C7.99 5.08 10 8.3 10 12s-2.01 6.92-5 8.65C6.47 21.5 8.18 22 10 22c5.52 0 10-4.48 10-10S15.52 2 10 2z"/>
</SvgIcon>
);
ImageBrightness2.displayName = 'ImageBrightness2';
ImageBrightness2.muiName = 'SvgIcon';
export default ImageBrightness2;
|
imports/ui/containers/feed/commentItem.js
|
jiyuu-llc/jiyuu
|
import React from 'react';
import { composeWithTracker } from 'react-komposer';
import { Comments } from '/lib/collections';
import {CommentItem} from '../../components/feed/commentItem.jsx';
const composer = ( postId, onData ) => {
if (Meteor.subscribe('comments').ready()) {
var comment = Comments.findOne({postId:postId.postId});
console.log(comment);
onData( null, { comment } );
}
};
export default composeWithTracker( composer, CommentItem)( CommentItem );
|
app/client/containers/DevTools/index.js
|
bhargav175/dictionary-offline
|
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="H"
changePositionKey="W">
<LogMonitor />
</DockMonitor>
);
|
Shuttle.ProcessManagement/site.react/src/Alerts.js
|
Shuttle/Shuttle.Esb.Samples
|
import React from 'react';
import Alert from 'react-bootstrap/Alert'
import state from './state';
export default class Alerts extends React.Component {
render() {
if (!state.alerts.messages) {
return undefined;
}
return state.alerts.messages.map(message => (
<Alert key={message.name} variant={alert.success} className={"alert-dismissible"} dismissable show onClose={() => state.alerts.remove(alert)}>
{alert.message}
</Alert>
));
}
}
|
src/Parser/Paladin/Retribution/Modules/PaladinCore/BoWProcTracker.js
|
enragednuke/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatNumber, formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import SpellUsable from 'Parser/Core/Modules/SpellUsable';
class BoWProcTracker extends Analyzer {
static dependencies = {
combatants: Combatants,
spellUsable: SpellUsable,
};
overwrittenBoWProcs = 0;
totalBoWProcs = 0;
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.BLADE_OF_WRATH_TALENT.id);
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.BLADE_OF_WRATH_PROC.id) {
return;
}
this.totalBoWProcs += 1;
if (this.spellUsable.isOnCooldown(SPELLS.BLADE_OF_JUSTICE.id)) {
this.spellUsable.endCooldown(SPELLS.BLADE_OF_JUSTICE.id);
}
}
on_byPlayer_refreshbuff(event) {
const spellId = event.ability.guid;
if (spellId !== SPELLS.BLADE_OF_WRATH_PROC.id) {
return;
}
this.overwrittenBoWProcs += 1;
this.totalBoWProcs += 1;
}
get suggestionThresholds() {
const missedProcsPercent = this.overwrittenBoWProcs / this.totalBoWProcs;
return {
actual: missedProcsPercent,
isGreaterThan: {
minor: 0,
average: 0.05,
major: 0.1,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds).addSuggestion((suggest, actual, recommended) => {
return suggest(<span>You wasted {formatPercentage(actual)}% <SpellLink id={SPELLS.BLADE_OF_WRATH_PROC.id} /> procs</span>)
.icon(SPELLS.BLADE_OF_WRATH_PROC.icon)
.actual(`${formatNumber(this.overwrittenBoWProcs)} missed proc(s)`)
.recommended(`Wasting none is recommended`);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.BLADE_OF_WRATH_PROC.id} />}
value={`${formatNumber(this.totalBoWProcs)}`}
label="Blade of Wrath procs"
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL(2);
}
export default BoWProcTracker;
|
react/src/index.js
|
tbauer516/rpimirror
|
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
// import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
// registerServiceWorker();
|
src/Option.js
|
hannahsquier/react-select
|
import React from 'react';
import classNames from 'classnames';
const Option = React.createClass({
propTypes: {
children: React.PropTypes.node,
className: React.PropTypes.string, // className (based on mouse position)
instancePrefix: React.PropTypes.string.isRequired, // unique prefix for the ids (used for aria)
isDisabled: React.PropTypes.bool, // the option is disabled
isFocused: React.PropTypes.bool, // the option is focused
isSelected: React.PropTypes.bool, // the option is selected
onFocus: React.PropTypes.func, // method to handle mouseEnter on option element
onSelect: React.PropTypes.func, // method to handle click on option element
onUnfocus: React.PropTypes.func, // method to handle mouseLeave on option element
option: React.PropTypes.object.isRequired, // object that is base for that option
optionIndex: React.PropTypes.number, // index of the option, used to generate unique ids for aria
},
blockEvent (event) {
event.preventDefault();
event.stopPropagation();
if ((event.target.tagName !== 'A') || !('href' in event.target)) {
return;
}
if (event.target.target) {
window.open(event.target.href, event.target.target);
} else {
window.location.href = event.target.href;
}
},
handleMouseDown (event) {
event.preventDefault();
event.stopPropagation();
this.props.onSelect(this.props.option, event);
},
handleMouseEnter (event) {
this.onFocus(event);
},
handleMouseMove (event) {
this.onFocus(event);
},
handleTouchEnd(event){
// Check if the view is being dragged, In this case
// we don't want to fire the click event (because the user only wants to scroll)
if(this.dragging) return;
this.handleMouseDown(event);
},
handleTouchMove (event) {
// Set a flag that the view is being dragged
this.dragging = true;
},
handleTouchStart (event) {
// Set a flag that the view is not being dragged
this.dragging = false;
},
onFocus (event) {
if (!this.props.isFocused) {
this.props.onFocus(this.props.option, event);
}
},
render () {
var { option, instancePrefix, optionIndex } = this.props;
var className = classNames(this.props.className, option.className);
return option.disabled ? (
<div className={className}
onMouseDown={this.blockEvent}
onClick={this.blockEvent}>
{this.props.children}
</div>
) : (
<div className={className}
style={option.style}
role="option"
onMouseDown={this.handleMouseDown}
onMouseEnter={this.handleMouseEnter}
onMouseMove={this.handleMouseMove}
onTouchStart={this.handleTouchStart}
onTouchMove={this.handleTouchMove}
onTouchEnd={this.handleTouchEnd}
id={instancePrefix + '-option-' + optionIndex}
title={option.title}>
{this.props.children}
</div>
);
}
});
module.exports = Option;
|
lib-es/elements/addons.js
|
bokuweb/re-bulma
|
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../build/styles';
import { getCallbacks } from '../helper/helper';
export default class Addons extends Component {
createControlClassName() {
return [styles.control, styles.hasAddons, this.props.className, this.props.hasAddonsCentered ? styles.hasAddonsCentered : '', this.props.hasAddonsRight ? styles.hasAddonsRight : ''].join(' ').trim();
}
cloneWithProps() {
if (React.Children.count(this.props.children) === 1) {
return this.props.children && React.cloneElement(this.props.children, {
color: this.props.color,
hasAddons: true
});
}
return this.props.children.map((child, i) => React.cloneElement(child, {
color: this.props.color,
key: i,
hasAddons: true
}));
}
renderHelp() {
if (!this.props.help) return null;
return React.createElement(
'span',
{ className: [styles.help, styles[this.props.help.color]].join(' ') },
this.props.help.text
);
}
render() {
return React.createElement(
'span',
null,
React.createElement(
'p',
_extends({
className: this.createControlClassName(),
style: this.props.style
}, getCallbacks(this.props)),
this.props.children && this.cloneWithProps()
),
this.renderHelp()
);
}
}
Addons.propTypes = {
className: PropTypes.string,
style: PropTypes.object,
children: PropTypes.any,
color: PropTypes.oneOf(['isPrimary', 'isInfo', 'isSuccess', 'isWarning', 'isDanger', 'isLink', 'isWhite', 'isLight', 'isDark', 'isBlack', 'isLink']),
help: PropTypes.shape({
text: PropTypes.string,
color: PropTypes.oneOf(['isPrimary', 'isInfo', 'isSuccess', 'isWarning', 'isDanger'])
}),
hasAddonsCentered: PropTypes.bool,
hasAddonsRight: PropTypes.bool
};
Addons.defaultProps = {
style: {},
className: ''
};
|
bai/src/pages/About/index.js
|
blackinai/blackinai.github.io
|
import { CssBaseline, ThemeProvider } from '@material-ui/core';
import React from 'react';
import AboutHeader from '../../components/AboutHeader';
import CommunityValues from '../../components/CommunityValues';
import Footer from '../../components/Footer';
import JoinUs from '../../components/JoinUs';
import Navbar from '../../components/Navbar';
import TeamMembers from '../../components/TeamMembers';
import Loader from '../../loader';
import theme from './../../theme';
function About() {
return (
<ThemeProvider theme={theme}>
<Loader />
<CssBaseline />
<Navbar />
<AboutHeader />
<CommunityValues />
<TeamMembers />
<JoinUs />
<Footer />
</ThemeProvider>
);
}
export default About;
|
react-shrine-network-aware-code-splitting/src/components/ProductImage/ProductZoomImage/ProductZoomImage.js
|
GoogleChromeLabs/adaptive-loading
|
/*
* Copyright 2019 Google LLC
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Magnifier from 'react-magnifier';
import ProductImageWrapper from '../../../hoc/ProductImageWrapper/ProductImageWrapper';
const ProductZoomImage = ({ product, close }) => (
<ProductImageWrapper title={product.title} close={close}>
<Magnifier src={product.imageUrl} width={500} />
</ProductImageWrapper>
);
export default ProductZoomImage;
|
docs/src/new-components/basics/tooltip/TooltipNote.stories.js
|
storybooks/react-storybook
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import WithTooltip from './WithTooltip';
import TooltipNote from './TooltipNote';
storiesOf('basics/tooltip/TooltipNote', module)
.addParameters({
component: TooltipNote,
})
.addDecorator(storyFn => (
<div style={{ height: '300px' }}>
<WithTooltip hasChrome={false} placement="top" trigger="click" startOpen tooltip={storyFn()}>
<div>Tooltip</div>
</WithTooltip>
</div>
))
.add('default', () => <TooltipNote note="Lorem ipsum dolor" />);
|
test/integration/css-fixtures/single-global-src/src/pages/_app.js
|
azukaru/next.js
|
import React from 'react'
import App from 'next/app'
import '../../styles/global.css'
class MyApp extends App {
render() {
const { Component, pageProps } = this.props
return <Component {...pageProps} />
}
}
export default MyApp
|
teoria02/componentes/UnaTarea.js
|
mart-dominguez/OFA2017-S01-C02
|
import React from 'react';
import EditarUnaTarea from './EditarUnaTarea';
class UnaTarea extends React.Component {
constructor(props) {
super(props);
this.state = {editar:false};
this.toggleEditar = this.toggleEditar.bind(this);
}
toggleEditar(){
let aux = !this.state.editar;
this.setState({editar: aux});
}
render(){
let tarea = undefined;
if(this.state.editar) {
tarea =<EditarUnaTarea indice={this.props.indice} onTareaChange={this.props.actualizar} tarea={this.props.tarea} guardar={this.toggleEditar}></EditarUnaTarea>
}else{
tarea = <li>
<strong>{this.props.tarea.titulo}</strong>
<span>{this.props.tarea.estado}</span>
<button onClick={this.toggleEditar}>editar</button>
</li>
}
return tarea;
}
}
export default UnaTarea;
|
src/components/Book/Main/Views/Common/tpl.js
|
LifeSourceUA/lifesource.ua
|
/**
* [IL]
* Library Import
*/
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
/**
* [IS]
* Style Import
*/
import Styles from './Styles/main.scss';
import Grid from 'theme/Grid.scss';
import Palette from 'theme/Palette';
/**
* [IBP]
* Pixel Perfect and Breakpoints
*/
import BP from 'lib/breakpoints';
import Label from 'components/Assets/LabelEdge.js';
import Content from 'components/Assets/Content.js';
import Book from 'components/Assets/Book.js';
import Arrow from 'components/Assets/Arrow.js';
import Ua from 'components/Assets/UA.js';
// import Ru from 'components/Assets/RU.js';
function Common(props) {
const { mediaType } = props;
const seriesBooks = BP.isTabletPortrait(mediaType) || BP.isDesktop(mediaType) ? (
<div className={ Styles.seriesBooks }>
<Label className={ Styles.labelStart } color1={ Palette.midGray }/>
серия книг
<Label className={ Styles.labelEnd } color1={ Palette.midGray }/>
</div>
) : null;
const arrowBack = BP.isDesktop(mediaType) || BP.isTabletPortrait(mediaType) ? (
<div className={ Styles.arrowBack }>
<div className={ Styles.circle }>
<Arrow color={ Palette.red }/>
</div>
{ BP.isDesktop(mediaType) ? 'перейти к списку книг' : null }
</div>
) : null;
const language = BP.isDesktop(mediaType) || BP.isTabletPortrait(mediaType) ? (
<div className={ Styles.language }>
<Ua className={ Styles.flag }/>
{ BP.isDesktop(mediaType) ? (<span className={ Styles.text }>Історії про справжніх</span>) : null }
{ BP.isDesktop(mediaType) ? <Arrow className={ Styles.arrow } color={ Palette.darkGray }/> : null }
</div>
) : null;
const secondAuthor = BP.isTabletPortrait(mediaType) || BP.isDesktop(mediaType) ? (
<h2 className={ Styles.author }>Лори Пекхем
<label className={ Styles.dot }/>
</h2>
) : null;
const description = BP.isDesktop(mediaType) ? (
<p className={ Styles.description }>Вы когда-нибудь чувствовали,
что ваши отношения рушатся? Задумывались ли вы, почему не можете найти того единственного и неповторимого?
</p>
) : null;
const hoverBook = BP.isDesktop(mediaType) ? (
<div className={ Styles.hoverBook }><Book className={ Styles.book } color={ Palette.green }/></div>
) : null;
const popupClasses = cx({
[Styles.popup]: true,
[Styles.active]: false
});
const poapWindow = BP.isDesktop(mediaType) ? (
<div className={ popupClasses }>
<ul className={ Styles.list }>
<li className={ Styles.item }>Вступление</li>
<li className={ Styles.item }>Предисловие</li>
<li className={ Styles.item }>
<ul className={ Styles.sublist }>
<li className={ Styles.item }>Как сносить удары судьбы</li>
<li className={ Styles.item }>Как бороться с ленью</li>
<li className={ Styles.item }>Что такое смерение</li>
<li className={ Styles.item }>Когда нужно уступать</li>
<li className={ Styles.item }>Компромисс</li>
</ul>
</li>
<li className={ Styles.item }>Умеем ли мы слушать?</li>
<li className={ Styles.item }>Искусство слушать</li>
<li className={ Styles.item }>Нехорошо быть одному</li>
<li className={ Styles.item }>Умеем ли мы слушать?</li>
<li className={ Styles.item }>Искусство слушать</li>
<li className={ Styles.item }>Нехорошо быть одному</li>
<li className={ Styles.item }>Умеем ли мы слушать?</li>
<li className={ Styles.item }>Искусство слушать</li>
<li className={ Styles.item }>Нехорошо быть одному</li>
</ul>
</div>
) : null;
const content = BP.isTabletPortrait(mediaType) || BP.isDesktop(mediaType) ? (
<a className={ Styles.tableOfContents }>
<Content color={ Palette.darkGray }/>
Оглавление
{ poapWindow }
</a>
) : null;
const wrap = cx({
[Grid.container]: true,
[Styles.wrap]: true
});
return (
<section className={ Styles.mainComponent }>
<section className={ wrap }>
<div className={ Styles.containerContent }>
{ arrowBack }
<div className={ Styles.content }>
<div className={ Styles.image }>
{ hoverBook }
<div className={ Styles.topLayer }/>
<div className={ Styles.middleLayer }/>
<div className={ Styles.bottomLayer }/>
<span className={ Styles.labelNum }>
<Label className={ Styles.label } color1={ Palette.midGray }/>
5
</span>
<span className={ Styles.labelNew }>
<Label className={ Styles.label } color={ Palette.red } color1={ Palette.red }/>
</span>
</div>
<div className={ Styles.info }>
<h1 className={ Styles.title }>Истории о настоящих героях</h1>
<div className={ Styles.authors }>
{ secondAuthor }
<h2 className={ Styles.author }>Алехандро Буйон</h2>
</div>
<div className={ Styles.tags }>
<div className={ Styles.new }>
<Label
className={ Styles.labelStart }
color={ Palette.red }
color1={ Palette.red }
/>
новинка
<Label className={ Styles.labelEnd } color={ Palette.red } color1={ Palette.red }/>
</div>
{ seriesBooks }
<div className={ Styles.class }>здоровье и семья</div>
</div>
<div className={ Styles.buttons }>
{ content }
<a className={ Styles.read }>
<Book className={ Styles.book } color={ Palette.green }/>
Читать фрагмент книги
</a>
</div>
{ description }
</div>
</div>
{ language }
</div>
</section>
</section>
);
}
/**
* [CPT]
* Component prop types
*/
Common.propTypes = {
mediaType: PropTypes.string.isRequired
};
/**
* [IE]
* Export
*/
export default Common;
|
packages/editor/src/components/Icons/List.js
|
strues/boldr
|
import React from 'react';
import Icon from './Icon';
const List = props => (
<Icon viewBox="0 0 512 512" {...props}>
<path d="M500 124H140c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h360c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm12 148v-32c0-6.627-5.373-12-12-12H140c-6.627 0-12 5.373-12 12v32c0 6.627 5.373 12 12 12h360c6.627 0 12-5.373 12-12zm0 160v-32c0-6.627-5.373-12-12-12H140c-6.627 0-12 5.373-12 12v32c0 6.627 5.373 12 12 12h360c6.627 0 12-5.373 12-12zM92 128V64c0-6.627-5.373-12-12-12H16C9.373 52 4 57.373 4 64v64c0 6.627 5.373 12 12 12h64c6.627 0 12-5.373 12-12zm0 160v-64c0-6.627-5.373-12-12-12H16c-6.627 0-12 5.373-12 12v64c0 6.627 5.373 12 12 12h64c6.627 0 12-5.373 12-12zm0 160v-64c0-6.627-5.373-12-12-12H16c-6.627 0-12 5.373-12 12v64c0 6.627 5.373 12 12 12h64c6.627 0 12-5.373 12-12z" />
</Icon>
);
List.defaultProps = { name: 'List' };
export default List;
|
src/svg-icons/action/open-in-new.js
|
pomerantsev/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionOpenInNew = (props) => (
<SvgIcon {...props}>
<path d="M19 19H5V5h7V3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2v-7h-2v7zM14 3v2h3.59l-9.83 9.83 1.41 1.41L19 6.41V10h2V3h-7z"/>
</SvgIcon>
);
ActionOpenInNew = pure(ActionOpenInNew);
ActionOpenInNew.displayName = 'ActionOpenInNew';
ActionOpenInNew.muiName = 'SvgIcon';
export default ActionOpenInNew;
|
src/parser/warrior/arms/CHANGELOG.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import { Aelexe, Zerotorescue, Sharrq, Matardarix, Korebian } from 'CONTRIBUTORS';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
export default [
{
date: new Date('2019-02-03'),
changes: <>Added a suggestion to not use <SpellLink id={SPELLS.SWEEPING_STRIKES.id} /> during <SpellLink id={SPELLS.COLOSSUS_SMASH.id} /> / <SpellLink id={SPELLS.WARBREAKER_TALENT.id} />.</>,
contributors: [Korebian],
},
{
date: new Date('2019-02-02'),
changes: <>Added more information to the <SpellLink id={SPELLS.CRUSHING_ASSAULT_TRAIT.id} /> module. Added <SpellLink id={SPELLS.LORD_OF_WAR.id} /> module.</>,
contributors: [Korebian],
},
{
date: new Date('2018-12-12'),
changes: <>Updated for patch 8.1, <SpellLink id={SPELLS.CHARGE.id} /> is no longer on the GCD and <SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> have been replaced by <SpellLink id={SPELLS.STRIKING_THE_ANVIL.id} />.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-28'),
changes: <>Added <SpellLink id={SPELLS.CRUSHING_ASSAULT_TRAIT.id} /> module.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-15'),
changes: <>Fixed Overpower events where stacks were applied before casts</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-14'),
changes: <>Added a suggestion on using <SpellLink id={SPELLS.SLAM.id} /> while <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> is available.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-12'),
changes: <>Added <SpellLink id={SPELLS.FERVOR_OF_BATTLE_TALENT.id} /> in Talents module.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-10'),
changes: <>Modified <SpellLink id={SPELLS.MORTAL_STRIKE.id} /> analysis to get it more accurate with the execution phase.</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-07'),
changes: <>Added Rage usage tab and suggestions on rage wast, removed the doughnut chart for rage usage</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-06'),
changes: <>Added cooldown tracker tab</>,
contributors: [Matardarix],
},
{
date: new Date('2018-11-05'),
changes: <>New:<ul><li>Checklist</li><li>Talents module</li><li><SpellLink id={SPELLS.EXECUTIONERS_PRECISION_TRAIT.id} /> module</li><li><SpellLink id={SPELLS.SEISMIC_WAVE.id} /> module</li><li><SpellLink id={SPELLS.TEST_OF_MIGHT.id} /> module</li><li>rage usage module</li><li>suggestions regarding <SpellLink id={SPELLS.DEFENSIVE_STANCE_TALENT.id} /></li></ul>Fixed:<ul><li><SpellLink id={SPELLS.ANGER_MANAGEMENT_TALENT.id} /> cooldown reduction calculation</li></ul></>,
contributors: [Matardarix],
},
{
date: new Date('2018-10-12'),
changes: <>Fixed some spell IDs and ability information. Updated Config.</>,
contributors: [Sharrq],
},
{
date: new Date('2018-06-30'),
changes: <>Update all abilities to new BFA values, removed incompatible modules and added an <SpellLink id={SPELLS.ANGER_MANAGEMENT_TALENT.id} /> statistic.</>,
contributors: [Zerotorescue],
},
{
date: new Date('2018-06-16'),
changes: <>Fixed a rare crash when casting <SpellLink id={SPELLS.EXECUTE.id} /> on a non-boss target.</>,
contributors: [Aelexe],
},
];
|
src/app-client.js
|
keshan3262/weather
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import {Provider} from 'react-redux';
import configureStore from './stores/configureStore';
import Layout from './components/Layout';
import LoginPage from './components/LoginPage';
import SignupPage from './components/SignupPage';
import WeatherPage from './components/WeatherPage';
import axios from 'axios';
import NotFoundPage from './components/NotFoundPage';
import reactCookie from 'react-cookie';
var store = configureStore({
weather: {now: {}, forecast: []},
cities: {data: []},
signupLoginLogout: {}
});
window.onload = () => {
ReactDOM.render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path='/' component={Layout}>
<IndexRoute component={LoginPage}/>
<Route path='/signup' component={SignupPage}/>
<Route path='/weather' component={WeatherPage}
onEnter={(nextState, replace, callback) => {
var sessionID = reactCookie.load('sessionID');
console.log(sessionID);
if (sessionID == null) {
replace('/');
callback();
}
else
axios.get('/api/cities').then((res) => {
callback();
}).catch((err) => {
if (err.response == null) {
callback(err);
}
else {
var status = err.response.status;
if ((status >= 400) && (status < 404)) {
replace('/');
callback();
}
else
callback(err);
}
});
}}/>
<Route path="*" component={NotFoundPage}/>
</Route>
</Router>
</Provider>,
document.getElementById('container')
);
}
|
datarequester/src/App.js
|
e-nettet/CustomerConsentWallet
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
import NavBar from './NavBar.js';
import ApplyForConcentForm from './ApplyForConcentForm.js';
class App extends Component {
render() {
return (
<div>
<NavBar />
<div className="container theme-showcase" role="main">
<div className="jumbotron">
<div className="page-header">
<h3>Welcome to Data Requestor</h3>
</div>
<ApplyForConcentForm />
</div>
</div>
</div>
);
}
}
export default App;
|
tests/react_children/tabs.js
|
MichaelDeBoey/flow
|
// @flow
/**
* This test represents a pattern which is commonly used to make tab bars, but
* this pattern is also used in many other places.
*/
import React from 'react';
class Tab extends React.Component<{}, void> {}
class NotTab extends React.Component<{}, void> {}
type TabBarNode =
| void
| null
| boolean
| React$Element<typeof Tab>
| Array<TabBarNode>; // NOTE: This is intentionally `Array<T>` and not
// `Iterable<T>` because `strings` are `Iterable<string>`
// which is then `Iterable<Iterable<string>>` recursively
// making strings valid children when we use
// `Iterable<T>`.
class TabBar extends React.Component<{children: TabBarNode}, void> {}
<TabBar />; // Error: `children` is required.
<TabBar><Tab/></TabBar>; // OK: We can have a single tab.
<TabBar><Tab/><Tab/></TabBar>; // OK: We can have two tabs.
<TabBar> <Tab/><Tab/></TabBar>; // Error: Spaces are strings.
<TabBar><Tab/> <Tab/></TabBar>; // Error: Spaces are strings.
<TabBar><Tab/><Tab/> </TabBar>; // Error: Spaces are strings.
// OK: We can have a single tab on multiple lines.
<TabBar>
<Tab/>
</TabBar>;
// OK: We can have a multiple tabs on multiple lines.
<TabBar>
<Tab/>
<Tab/>
<Tab/>
</TabBar>;
// OK: We can have an array of tabs.
<TabBar>
{[
<Tab/>,
<Tab/>,
<Tab/>,
]}
</TabBar>;
// OK: We can have two arrays of tabs.
<TabBar>
{[
<Tab/>,
<Tab/>,
]}
{[
<Tab/>,
<Tab/>,
]}
</TabBar>;
<TabBar><NotTab/></TabBar>; // Error: We can only have tab components.
<TabBar><NotTab/><NotTab/></TabBar>; // Error: We can only have tab components.
// Error: Nope, can't sneak a non-tab in there.
<TabBar>
<Tab/>
<NotTab/>
<Tab/>
<Tab/>
</TabBar>;
// OK: Booleans are allowed in the type.
<TabBar>
{Math.random() > 0.5 && <Tab/>}
</TabBar>;
// OK: Booleans are allowed in the type.
<TabBar>
{Math.random() > 0.5 && <Tab/>}
{Math.random() > 0.5 && <Tab/>}
</TabBar>;
|
front/client/components/CommunityList/index.js
|
ytorii/tebukuro
|
import React from 'react'
import CommunityListModel from '../../models/CommunityList'
const CommunityList = ({CommunityList}) => {
return (
<table>
<thead>
<tr>
<th>name</th>
</tr>
</thead>
<tbody>
{
CommunityList.communities.map((community) => {
return (
<tr key={community.id}>
<td>{community.name}</td>
</tr>
)
})
}
</tbody>
</table>
)
}
CommunityList.propTypes = {
CommunityList : React.PropTypes.instanceOf(CommunityListModel).isRequired,
}
export default CommunityList
|
packages/react-vis/src/legends/discrete-color-legend.js
|
uber/react-vis
|
// Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import PropTypes from 'prop-types';
import DiscreteColorLegendItem from 'legends/discrete-color-legend-item';
import {DISCRETE_COLOR_RANGE} from 'theme';
import {getCombinedClassName} from 'utils/styling-utils';
function DiscreteColorLegend({
className,
colors,
height,
items,
onItemClick,
onItemMouseEnter,
onItemMouseLeave,
orientation,
style,
width
}) {
return (
<div
className={getCombinedClassName(
'rv-discrete-color-legend',
orientation,
className
)}
style={{width, height, ...style}}
>
{items.map((item, i) => (
<DiscreteColorLegendItem
title={item.title ? item.title : item}
color={item.color ? item.color : colors[i % colors.length]}
strokeDasharray={item.strokeDasharray}
strokeStyle={item.strokeStyle}
strokeWidth={item.strokeWidth}
disabled={Boolean(item.disabled)}
orientation={orientation}
key={i}
onClick={onItemClick ? e => onItemClick(item, i, e) : null}
onMouseEnter={
onItemMouseEnter ? e => onItemMouseEnter(item, i, e) : null
}
onMouseLeave={
onItemMouseEnter ? e => onItemMouseLeave(item, i, e) : null
}
/>
))}
</div>
);
}
DiscreteColorLegend.displayName = 'DiscreteColorLegendItem';
DiscreteColorLegend.propTypes = {
className: PropTypes.string,
items: PropTypes.arrayOf(
PropTypes.oneOfType([
PropTypes.shape({
title: PropTypes.oneOfType([PropTypes.string, PropTypes.element])
.isRequired,
color: PropTypes.string,
disabled: PropTypes.bool
}),
PropTypes.string.isRequired,
PropTypes.element
])
).isRequired,
onItemClick: PropTypes.func,
onItemMouseEnter: PropTypes.func,
onItemMouseLeave: PropTypes.func,
height: PropTypes.number,
width: PropTypes.number,
orientation: PropTypes.oneOf(['vertical', 'horizontal'])
};
DiscreteColorLegend.defaultProps = {
className: '',
colors: DISCRETE_COLOR_RANGE,
orientation: 'vertical'
};
export default DiscreteColorLegend;
|
app/javascript/mastodon/features/domain_blocks/index.js
|
pinfort/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import DomainContainer from '../../containers/domain_container';
import { fetchDomainBlocks, expandDomainBlocks } from '../../actions/domain_blocks';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.domain_blocks', defaultMessage: 'Blocked domains' },
unblockDomain: { id: 'account.unblock_domain', defaultMessage: 'Unblock domain {domain}' },
});
const mapStateToProps = state => ({
domains: state.getIn(['domain_lists', 'blocks', 'items']),
hasMore: !!state.getIn(['domain_lists', 'blocks', 'next']),
});
export default @connect(mapStateToProps)
@injectIntl
class Blocks extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
hasMore: PropTypes.bool,
domains: ImmutablePropTypes.orderedSet,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchDomainBlocks());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandDomainBlocks());
}, 300, { leading: true });
render () {
const { intl, domains, shouldUpdateScroll, hasMore, multiColumn } = this.props;
if (!domains) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.domain_blocks' defaultMessage='There are no blocked domains yet.' />;
return (
<Column bindToDocument={!multiColumn} icon='minus-circle' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='domain_blocks'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
>
{domains.map(domain =>
<DomainContainer key={domain} domain={domain} />,
)}
</ScrollableList>
</Column>
);
}
}
|
src/SegmentedControl/macOs/Tabs/index.js
|
gabrielbull/react-desktop
|
import React, { Component } from 'react';
import Tab from './Tab';
import styles from '../style/10.11';
class Tabs extends Component {
select(item) {
this.refs[item.props.tabId].setState({ selected: true });
}
unselect(item) {
this.refs[item.props.tabId].setState({ selected: false });
}
render() {
const { style } = this.props;
let children;
// todo: use Children.map
if (!this.props.children) {
return null;
} else if (
Object.prototype.toString.call(this.props.children) !== '[object Array]'
) {
children = [this.props.children];
} else {
children = [...this.props.children];
}
let tabs = [];
let hasSelected = false;
for (let i = 0, len = children.length; i < len; ++i) {
let props = children[i].props;
if (props.selected) hasSelected = true;
if (i === 0) props = { ...props, firstChild: true };
if (i === len - 1) props = { ...props, lastChild: true };
if (
children[i + 1] &&
children[i + 1].props &&
children[i + 1].props.selected
) {
props = { ...props, nextSelected: true };
}
tabs = [...tabs, props];
}
if (!hasSelected && tabs[0]) tabs[0].selected = true;
let prevSelectedIndex = null;
let afterSelected = false;
for (let i = 0, len = tabs.length; i < len; ++i) {
if (afterSelected) {
tabs[i] = { ...tabs[i], afterSelected: true };
afterSelected = false;
}
if (tabs[i].selected) {
afterSelected = true;
prevSelectedIndex = i - 1;
}
}
if (prevSelectedIndex >= 0 && tabs[prevSelectedIndex])
tabs[prevSelectedIndex] = {
...tabs[prevSelectedIndex],
prevSelected: true
};
return (
<div style={{ ...styles.tabs, ...style }}>{this.renderTabs(tabs)}</div>
);
}
renderTabs(tabs) {
const children = [];
for (let i = 0, len = tabs.length; i < len; ++i) {
children.push(
<Tab key={i} {...tabs[i]}>
{tabs[i].title}
</Tab>
);
}
return children;
}
}
export default Tabs;
|
packages/icons/src/md/image/CameraRoll.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdCameraRoll(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M28 11h16v30H28c0 2.21-1.79 4-4 4H8c-2.21 0-4-1.79-4-4V11c0-2.21 1.79-4 4-4h2V5c0-1.1.9-2 2-2h8c1.1 0 2 .9 2 2v2h2c2.21 0 4 1.79 4 4zm-4 26v-4h-4v4h4zm0-18v-4h-4v4h4zm8 18v-4h-4v4h4zm0-18v-4h-4v4h4zm8 18v-4h-4v4h4zm0-18v-4h-4v4h4z" />
</IconBase>
);
}
export default MdCameraRoll;
|
node_modules/semantic-ui-react/src/collections/Form/FormSelect.js
|
mowbell/clickdelivery-fed-test
|
import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
import Select from '../../addons/Select'
import FormField from './FormField'
/**
* Sugar for <Form.Field control={Select} />.
* @see Form
* @see Select
*/
function FormSelect(props) {
const { control } = props
const rest = getUnhandledProps(FormSelect, props)
const ElementType = getElementType(FormSelect, props)
return <ElementType {...rest} control={control} />
}
FormSelect._meta = {
name: 'FormSelect',
parent: 'Form',
type: META.TYPES.COLLECTION,
}
FormSelect.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** A FormField control prop. */
control: FormField.propTypes.control,
}
FormSelect.defaultProps = {
as: FormField,
control: Select,
}
export default FormSelect
|
src/bookmarks/BookmarkButton.js
|
Sekhmet/busy
|
import React from 'react';
import { injectIntl } from 'react-intl';
import { SimpleTooltipOrigin } from '../widgets/tooltip/SimpleTooltip';
import Icon from '../widgets/Icon';
const BookmarkButton = ({ post, bookmarks, toggleBookmark, intl }) =>
<SimpleTooltipOrigin message={
intl.formatMessage({
id: bookmarks[post.id]
? '@tooltip_remove_bookmark'
: '@tooltip_add_bookmark',
defaultMessage: bookmarks[post.id] ?
'Remove from bookmarks' :
'Add in bookmarks',
})}
>
<a onClick={() => toggleBookmark(post.id)} className="PostFeedList__cell__bookmark">
<Icon
name={bookmarks[post.id] ? 'bookmark' : 'bookmark_border'}
/>
</a>
</SimpleTooltipOrigin>;
export default injectIntl(BookmarkButton);
|
app/pods/mockup/builder/container.js
|
slightlytyler/mocksy
|
'use strict'
import React from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import {
setCurrentTemplate
} from 'pods/templates/actions';
import {
currentTemplateSelector,
currentTemplateSetIdSelector,
currentTemplateSetSelector
} from 'pods/templates/selectors';
import { setCurrentScreenshot } from 'pods/screenshots/actions';
import { currentScreenshotSelector } from 'pods/screenshots/selectors';
import {
addSize,
removeSize,
updateSize
} from 'pods/sizes/actions';
import { sizesRecordsSelector } from 'pods/sizes/selectors';
import IndexComponent from './component';
function mapStateToProps(state) {
const { present } = state;
return {
templates: currentTemplateSetSelector(present),
currentTemplate: currentTemplateSelector(present),
currentTemplateSetId: currentTemplateSetIdSelector(present),
currentScreenshot: currentScreenshotSelector(present),
sizes: sizesRecordsSelector(present)
};
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({
setCurrentTemplate,
setCurrentScreenshot,
addSize,
removeSize,
updateSize
}, dispatch);
}
function mergeProps(stateProps, dispatchProps, ownProps) {
return Object.assign({}, stateProps, {
actions: {
...dispatchProps
}
})
}
export default connect(
mapStateToProps,
mapDispatchToProps,
mergeProps
)(IndexComponent);
|
libs/composites/interfaces/react-dom-server-interface-composite.js
|
tuantle/hyperflow
|
/**
* Copyright 2018-present Tuan Le.
*
* Licensed under the MIT License.
* You may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://opensource.org/licenses/mit-license.html
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*------------------------------------------------------------------------
*
* @module ReactDOMServerComponentComposite
* @description - A React DOM server component interface factory composite.
*
* @author Tuan Le (tuan.t.lei@gmail.com)
*/
/* @flow */
'use strict'; // eslint-disable-line
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import {
ENV,
// isNonEmptyString,
isFunction,
isObject,
isSchema,
fallback,
log
} from '../../utils/common-util';
import Composite from '../../../src/composite';
export default Composite({
template: {
/**
* @description - Initialized and check that factory is valid for this composite.
*
* @method $initReactDOMServerComponentComposite
* @return void
*/
$initReactDOMServerComponentComposite () {
const intf = this;
if (ENV.DEVELOPMENT) {
if (!isSchema({
name: `string`,
type: `string`,
incoming: `function`,
outgoing: `function`,
getInterfacedComponent: `function`
}).of(intf) || intf.type !== `interface`) {
log(`error`, `ReactDOMServerComponentComposite.$init - Interface is invalid. Cannot apply composite.`);
}
}
},
/**
* @description - Render app top level component to the target environment.
*
* @method renderToTarget
* @param {string} targetId
* @param {object} option
* @return [stream|string]
*/
renderToTarget (targetId, option = {
useStaticMarkup: false,
useNodeStream: false
}) {
const intf = this;
const Component = intf.getInterfacedComponent(option);
if (ENV.DEVELOPMENT) {
if (!intf.isStreamActivated()) {
log(`error`, `ReactDOMServerComponentComposite.renderToTarget - Interface:${intf.name} render to target cannot be call before event stream activation.`);
}
// if (!isNonEmptyString(targetId)) {
// log(`error`, `ReactDOMServerComponentComposite.renderToTarget - Interface:${intf.name} target Id key is invalid.`);
// }
if (!(isFunction(Component) || isObject(Component))) {
log(`error`, `ReactDOMServerComponentComposite.renderToTarget - Interface:${intf.name} React component is invalid.`);
}
}
const {
useStaticMarkup,
useNodeStream
} = fallback({
useStaticMarkup: false,
useNodeStream: false
}).of(option);
let render;
if (useStaticMarkup) {
render = useNodeStream ? ReactDOMServer.renderToStaticNodeStream : ReactDOMServer.renderToStaticMarkup;
} else {
render = useNodeStream ? ReactDOMServer.renderToNodeStream : ReactDOMServer.renderToString;
}
log(`info1`, `Rendering to target Id:${targetId} for interface:${intf.name}.`);
const html = render(
<Component/>
);
intf.outgoing(`on-component-${intf.name}-render-to-target`).emit(() => html);
return html;
}
}
});
|
src/components/Homepage.js
|
NemethNorbert/restaurant-website
|
import React from 'react';
import Slider from 'react-slick';
import LeftArrow from './LeftArrow';
import RightArrow from './RightArrow';
import {NavLink} from 'reactstrap';
import { NavLink as RRNavLink } from 'react-router-dom';
class Homepage extends React.PureComponent {
render() {
const settings = {
infinite: true,
speed: 500,
slidesToShow: 1,
slidesToScroll: 1,
autoplay: true,
autoplaySpeed: 5000,
centerMode: false,
pauseOnHover:true,
focusOnSelect: true,
nextArrow: <RightArrow {...this.props} />,
prevArrow: <LeftArrow {...this.props} />
};
return (
<div className="">
<div className="row menuWrapper clearfix">
<div className="container">
<div className="menuBox text-center">
<div className="menuTitle">
<p className="lead">Térj be hozzánk</p>
<p className="menuText">Elegáns kényelem, figyelmes kiszolgálást és a bisztrók üde, ráérős hangulata fogad a plázai forgatagban is. Ropogós szendvicsek, friss saláták és francia finomságok várják, hogy belefeledkezz az ízek kavalkádjába.</p>
</div>
</div>
<NavLink to={process.env.PUBLIC_URL+'/Pekseg'} tag={RRNavLink} className="menu menu1">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Pékség</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink} className="menu menu2">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Ételek</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
<NavLink to={process.env.PUBLIC_URL+'/Italok'} tag={RRNavLink} className="menu small1">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Italok</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink} className="menu small2">
<div className="menuImage"></div>
<div className="wrapp text-center">
<div className="menuTitle">
<h3 className="lead">Desszertek</h3>
<p className="menuText">francia pékárú</p>
</div>
</div>
</NavLink>
</div>
</div>
<div className="row text-align bg-clear pad line">
<div className="col-lg-4 col-md-4 lineWrapper">
<h3 className="lead text-center">Mi a titkunk?</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Egy csipetnyi Franciaország, egy kiskanálnyi Itália és a harmónikus ízek szenvedélyes szeretete.</div>
</div>
<div className="col-lg-4 col-md-4 text-center padB lineWrapper">
<img src={process.env.PUBLIC_URL + "/pictures/brand/linepic1.png"} className="linepic"/>
</div>
<div className="col-lg-4 col-md-4 lineWrapper">
<h3 className="lead text-center">Mániánk a minőség</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Ha a minőség van terítéken, nem ismerünk pardont. Csakis a legkiválóbb alapanyagokból és eljárásokkal dolgozunk, gondosan válogatott és fejlesztett receptek alapján.</div>
<NavLink to={process.env.PUBLIC_URL+'/About'} tag={RRNavLink} className="btn btn-outline-brown">A titok</NavLink>
</div>
</div>
<div className="row bigline bg-look text-center">
<div className="col-lg-6 col-md-6 lineWrapper text-white pad">
<h3 className="lead text-center">Menj biztosra!</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Találd meg a kedvencedet villámgyorsan! Vegára vágysz vagy oda vagy az olasz szalámiért? Keress akár típusra vagy hozzávalóra is!</div>
</div>
<div className="col-lg-6 col-md-6 lineWrapper">
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink}><img src={process.env.PUBLIC_URL + "/pictures/brand/biglinepic.png"} className="searchImg" /></NavLink>
</div>
</div>
<div className="row text-align bg-clear pad line">
<div className="col-lg-4 col-md-4 col-sm-6 lineWrapper bg-line2">
<h3 className="lead text-center">Franciaországból a tányérodra</h3>
<div className="padB text-center">frissen, ropogósan</div>
</div>
<div className="col-lg-4 col-md-4 col-sm-6 text-center padB lineWrapper">
<img src={process.env.PUBLIC_URL + "/pictures/brand/linepic2.png"} className="linepic"/>
</div>
<div className="col-lg-4 col-md-4 col-sm-12 lineWrapper mobfixer">
<h3 className="lead text-center">Melegen ajánljuk</h3>
<hr className="hr bg-brown"/>
<div className="padB text-center">Francia receptúra alapján készült péktermékeinket minden reggel mi magunk sütjük házi pékségünkben. Mi sem természetesebb, hogy szendvicdseinket is a frissen sült bagettekből és ciabbatákból készítjük. Így lesz ropogós a szendvics, Párizst idéző a croissant és omlós a muffin.</div>
</div>
</div>
<div className="container text-center" style={{width:"90%"}}>
<NavLink to={process.env.PUBLIC_URL+'/Galeria'} tag={RRNavLink}><div className="galeria"><div className="galeriaText">Galéria</div></div></NavLink>
<Slider {...settings} className="galeriaSlider">
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Kurvajó minden”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Igazi olasz sonka”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Egy gasztronomiai csoda”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
<div className="sliderBox text-white">
<blockquote className="blockquote sliderText">
<p className="mb-0">„Minden nap itt reggelizem”</p>
<footer className="blockquote-footer text-silent">Rólunk írta - Egy random arc</footer>
</blockquote>
</div>
</Slider>
</div>
<div className="row bigline bg-contact">
<div className="col-lg-6 col-md-6 lineWrapper text-center">
<NavLink to={process.env.PUBLIC_URL+'/Etelek'} tag={RRNavLink}><img src={process.env.PUBLIC_URL + "/pictures/brand/google.png"} className="google" /></NavLink>
</div>
<div className="col-lg-6 col-md-6 lineWrapper text-white pad">
<h3 className="lead text-center">Elérhetőségeink</h3>
<hr className="hr bg-brown"/>
<table className="table cont text-center">
<tbody>
<tr>
<th scope="row"><i className="fa fa-map-marker" aria-hidden="true"></i></th>
<td>1138 Budapest, Váci út 178.,<br />Duna Plaza II. emelet</td>
</tr>
<tr>
<th scope="row"><i className="fa fa-phone-square" aria-hidden="true"></i></th>
<td>(1) 465 1666</td>
</tr>
<tr>
<th scope="row"><i className="fa fa-envelope" aria-hidden="true"></i></th>
<td>B54@emid.hu</td>
</tr>
</tbody>
</table>
<div className="pad text-center">
<div><h3><i className="fa fa-clock-o" aria-hidden="true"></i> Nyitvatartás</h3></div>
<div>Hétfőtől szombatig: 9.00-21.00<br/>vasárnap: 9.00-19.00</div>
</div>
</div>
</div>
</div>
);
}
}
export default Homepage;
|
spec/javascripts/jsx/gradezilla/default_gradebook/components/AssignmentColumnHeaderSpec.js
|
venturehive/canvas-lms
|
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { mount, ReactWrapper } from 'enzyme';
import AssignmentColumnHeader from 'jsx/gradezilla/default_gradebook/components/AssignmentColumnHeader';
import CurveGradesDialogManager from 'jsx/gradezilla/default_gradebook/CurveGradesDialogManager';
import AssignmentMuterDialogManager from 'jsx/gradezilla/shared/AssignmentMuterDialogManager';
import SetDefaultGradeDialogManager from 'jsx/gradezilla/shared/SetDefaultGradeDialogManager';
import { findFlyoutMenuContent, findMenuItem } from './helpers/columnHeaderHelpers';
function createAssignmentProp ({ assignment } = {}) {
return {
courseId: '42',
htmlUrl: 'http://assignment_htmlUrl',
id: '1',
invalid: false,
muted: false,
name: 'Assignment #1',
omitFromFinalGrade: false,
pointsPossible: 13,
published: true,
submissionTypes: ['online_text_entry'],
...assignment
};
}
function createStudentsProp () {
return [
{
id: '11',
name: 'Clark Kent',
isInactive: false,
submission: {
score: 7,
submittedAt: null
}
},
{
id: '13',
name: 'Barry Allen',
isInactive: false,
submission: {
score: 8,
submittedAt: new Date('Thu Feb 02 2017 16:33:19 GMT-0500 (EST)')
}
},
{
id: '15',
name: 'Bruce Wayne',
isInactive: false,
submission: {
score: undefined,
submittedAt: undefined
}
}
];
}
function defaultProps ({ props, sortBySetting, assignment, curveGradesAction } = {}) {
return {
assignment: createAssignmentProp({ assignment }),
assignmentDetailsAction: {
disabled: false,
onSelect () {},
},
curveGradesAction: {
isDisabled: false,
onSelect () {},
...curveGradesAction
},
downloadSubmissionsAction: {
hidden: false,
onSelect () {}
},
enterGradesAsSetting: {
hidden: false,
onSelect () {},
selected: 'points',
showGradingSchemeOption: true
},
muteAssignmentAction: {
disabled: false,
onSelect () {}
},
reuploadSubmissionsAction: {
hidden: false,
onSelect () {}
},
setDefaultGradeAction: {
disabled: false,
onSelect () {}
},
showUnpostedMenuItem: true,
sortBySetting: {
direction: 'ascending',
disabled: false,
isSortColumn: true,
onSortByGradeAscending: sinon.stub(),
onSortByGradeDescending: sinon.stub(),
onSortByLate: sinon.stub(),
onSortByMissing: sinon.stub(),
onSortByUnposted: sinon.stub(),
settingKey: 'grade',
...sortBySetting
},
students: createStudentsProp(),
submissionsLoaded: true,
addGradebookElement () {},
removeGradebookElement () {},
onMenuClose () {},
...props
};
}
function mountComponent (props, mountOptions = {}) {
return mount(<AssignmentColumnHeader {...props} />, mountOptions);
}
function mountAndOpenOptions (props, mountOptions = {}) {
const wrapper = mountComponent(props, mountOptions);
wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
return wrapper;
}
QUnit.module('AssignmentColumnHeader', {
setup () {
this.props = defaultProps({
props: {
addGradebookElement: this.stub(),
removeGradebookElement: this.stub(),
onMenuClose: this.stub()
}
});
this.wrapper = mountComponent(this.props);
},
teardown () {
this.wrapper.unmount();
}
});
test('renders the assignment name in a link', function () {
const link = this.wrapper.find('.assignment-name Link');
equal(link.length, 1);
equal(link.text().trim(), 'Assignment #1');
equal(link.props().href, 'http://assignment_htmlUrl');
});
test('renders the points possible', function () {
const pointsPossible = this.wrapper.find('.assignment-points-possible');
equal(pointsPossible.length, 1);
equal(pointsPossible.text().trim(), 'Out of 13');
});
test('renders a PopoverMenu', function () {
const optionsMenu = this.wrapper.find('PopoverMenu');
equal(optionsMenu.length, 1);
});
test('does not render a PopoverMenu if assignment is not published', function () {
const props = defaultProps({ assignment: { published: false } });
const wrapper = mountComponent(props);
const optionsMenu = wrapper.find('PopoverMenu');
equal(optionsMenu.length, 0);
});
test('renders a PopoverMenu with a trigger', function () {
const optionsMenuTrigger = this.wrapper.find('PopoverMenu .Gradebook__ColumnHeaderAction');
equal(optionsMenuTrigger.length, 1);
});
test('calls addGradebookElement prop on open', function () {
notOk(this.props.addGradebookElement.called);
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
ok(this.props.addGradebookElement.called);
});
test('calls removeGradebookElement prop on close', function () {
notOk(this.props.removeGradebookElement.called);
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
ok(this.props.removeGradebookElement.called);
});
test('calls onMenuClose prop on close', function () {
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
this.wrapper.find('.Gradebook__ColumnHeaderAction').simulate('click');
strictEqual(this.props.onMenuClose.callCount, 1);
});
test('adds a class to the trigger when the PopoverMenu is opened', function () {
const optionsMenuTrigger = this.wrapper.find('PopoverMenu .Gradebook__ColumnHeaderAction');
optionsMenuTrigger.simulate('click');
ok(optionsMenuTrigger.hasClass('menuShown'));
});
test('renders a title for the More icon based on the assignment name', function () {
const optionsMenuTrigger = this.wrapper.find('PopoverMenu IconMoreSolid');
equal(optionsMenuTrigger.props().title, 'Assignment #1 Options');
});
QUnit.module('AssignmentColumnHeader: "Enter Grades as" Settings', function (hooks) {
let props;
let wrapper;
function getMenuItem (text) {
const content = new ReactWrapper(wrapper.node.enterGradesAsMenuContent, wrapper.node);
return content.findWhere(component => component.name() === 'MenuItem' && component.text() === text);
}
function getMenuItemFlyout (text) {
const content = new ReactWrapper(wrapper.node.optionsMenuContent, wrapper.node);
return content.findWhere(component => component.name() === 'MenuItemFlyout' && component.text().trim() === text);
}
function mountAndOpenMenu () {
wrapper = mountAndOpenOptions(props);
getMenuItemFlyout('Enter Grades as').find('button').simulate('mouseOver');
}
hooks.beforeEach(function () {
props = defaultProps();
});
hooks.afterEach(function () {
wrapper.unmount();
});
test('renders when "hidden" is false', function () {
wrapper = mountAndOpenOptions(props);
strictEqual(getMenuItemFlyout('Enter Grades as').length, 1);
});
test('does not render when "hidden" is true', function () {
props.enterGradesAsSetting.hidden = true;
wrapper = mountAndOpenOptions(props);
strictEqual(getMenuItemFlyout('Enter Grades as').length, 0);
});
test('includes the "Points" option', function () {
mountAndOpenMenu();
strictEqual(getMenuItem('Points').length, 1);
});
test('includes the "Percentage" option', function () {
mountAndOpenMenu();
strictEqual(getMenuItem('Percentage').length, 1);
});
test('includes the "Grading Scheme" option when "showGradingSchemeOption" is true', function () {
props.enterGradesAsSetting.showGradingSchemeOption = true;
mountAndOpenMenu();
strictEqual(getMenuItem('Grading Scheme').length, 1);
});
test('excludes the "Grading Scheme" option when "showGradingSchemeOption" is false', function () {
props.enterGradesAsSetting.showGradingSchemeOption = false;
mountAndOpenMenu();
strictEqual(getMenuItem('Grading Scheme').length, 0);
});
test('optionally renders the "Points" option as selected', function () {
props.enterGradesAsSetting.selected = 'points';
mountAndOpenMenu();
strictEqual(getMenuItem('Points').prop('selected'), true);
});
test('optionally renders the "Percentage" option as selected', function () {
props.enterGradesAsSetting.selected = 'percent';
mountAndOpenMenu();
strictEqual(getMenuItem('Percentage').prop('selected'), true);
});
test('optionally renders the "Grading Scheme" option as selected', function () {
props.enterGradesAsSetting.showGradingSchemeOption = true;
props.enterGradesAsSetting.selected = 'gradingScheme';
mountAndOpenMenu();
strictEqual(getMenuItem('Grading Scheme').prop('selected'), true);
});
test('calls the onSelect callback with "points" when "Points" is selected', function () {
let selected;
props.enterGradesAsSetting.selected = 'percent';
props.enterGradesAsSetting.onSelect = (value) => { selected = value };
mountAndOpenMenu();
getMenuItem('Points').simulate('click');
equal(selected, 'points');
});
test('calls the onSelect callback with "percent" when "Percentage" is selected', function () {
let selected;
props.enterGradesAsSetting.onSelect = (value) => { selected = value };
mountAndOpenMenu();
getMenuItem('Percentage').simulate('click');
equal(selected, 'percent');
});
test('calls the onSelect callback with "gradingScheme" when "Grading Scheme" is selected', function () {
let selected;
props.enterGradesAsSetting.showGradingSchemeOption = true;
props.enterGradesAsSetting.onSelect = (value) => { selected = value };
mountAndOpenMenu();
getMenuItem('Grading Scheme').simulate('click');
equal(selected, 'gradingScheme');
});
});
QUnit.module('AssignmentColumnHeader: Sort by Settings', {
setup () {
this.mountAndOpenOptions = mountAndOpenOptions;
},
teardown () {
this.wrapper.unmount();
}
});
test('sort by does not allow multiple selects', function () {
const flyout = findFlyoutMenuContent.call(this, defaultProps(), 'Sort by');
strictEqual(flyout.find('MenuItemGroup').prop('allowMultiple'), false);
});
test('selects "Grade - Low to High" when sorting by grade ascending', function () {
const props = defaultProps({ sortBySetting: { direction: 'ascending' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Grade - Low to High" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Grade - Low to High" calls onSortByGradeAscending', function () {
const onSortByGradeAscending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeAscending } });
findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High').simulate('click');
strictEqual(onSortByGradeAscending.callCount, 1);
});
test('clicking "Grade - Low to High" focuses menu trigger', function () {
const onSortByGradeAscending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeAscending } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Grade - Low to High" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - Low to High');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Grade - High to Low" when sorting by grade descending', function () {
const props = defaultProps({ sortBySetting: { direction: 'descending' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Grade - High to Low" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Grade - High to Low" calls onSortByGradeDescending', function () {
const onSortByGradeDescending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeDescending } });
findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low').simulate('click');
strictEqual(onSortByGradeDescending.callCount, 1);
});
test('clicking "Grade - High to Low" focuses menu trigger', function () {
const onSortByGradeDescending = this.stub();
const props = defaultProps({ sortBySetting: { onSortByGradeDescending } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Grade - High to Low" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Missing" when sorting by missing', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'missing' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Missing');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Missing" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'missing', isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Missing" calls onSortByMissing', function () {
const onSortByMissing = this.stub();
const props = defaultProps({ sortBySetting: { onSortByMissing } });
findMenuItem.call(this, props, 'Sort by', 'Missing').simulate('click');
strictEqual(onSortByMissing.callCount, 1);
});
test('clicking "Missing" focuses menu trigger', function () {
const onSortByMissing = this.stub();
const props = defaultProps({ sortBySetting: { onSortByMissing } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Missing');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Missing" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Missing');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Late" when sorting by late', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'late' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Late');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Late" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'late', isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Late" calls onSortByLate', function () {
const onSortByLate = this.stub();
const props = defaultProps({ sortBySetting: { onSortByLate } });
findMenuItem.call(this, props, 'Sort by', 'Late').simulate('click');
strictEqual(onSortByLate.callCount, 1);
});
test('clicking "Late" focuses menu trigger', function () {
const onSortByLate = this.stub();
const props = defaultProps({ sortBySetting: { onSortByLate } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Late');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Late" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Late');
strictEqual(menuItem.prop('disabled'), true);
});
test('selects "Unposted" when sorting by unposted', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'unposted' } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
strictEqual(menuItem.prop('selected'), true);
});
test('does not select "Unposted" when isSortColumn is false', function () {
const props = defaultProps({ sortBySetting: { settingKey: 'unposted', isSortColumn: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Grade - High to Low');
strictEqual(menuItem.prop('selected'), false);
});
test('clicking "Unposted" calls onSortByUnposted', function () {
const onSortByUnposted = this.stub();
const props = defaultProps({ sortBySetting: { onSortByUnposted } });
findMenuItem.call(this, props, 'Sort by', 'Unposted').simulate('click');
strictEqual(onSortByUnposted.callCount, 1);
});
test('clicking "Unposted" focuses menu trigger', function () {
const onSortByUnposted = this.stub();
const props = defaultProps({ sortBySetting: { onSortByUnposted } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
const focusStub = this.stub(this.wrapper.instance(), 'focusAtEnd')
menuItem.simulate('click');
equal(focusStub.callCount, 1);
});
test('"Unposted" is optionally disabled', function () {
const props = defaultProps({ sortBySetting: { disabled: true } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
strictEqual(menuItem.prop('disabled'), true);
});
test('"Unposted" menu item is optionally excluded from the menu', function () {
const props = defaultProps({ props: { showUnpostedMenuItem: false } });
const menuItem = findMenuItem.call(this, props, 'Sort by', 'Unposted');
notOk(menuItem);
});
QUnit.module('AssignmentColumnHeader: Curve Grades Dialog', {
teardown () {
this.wrapper.unmount();
}
});
test('menu item is present in the popover menu', function () {
this.wrapper = mountAndOpenOptions(defaultProps());
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
equal(menuItem.textContent, 'Curve Grades');
notOk(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('Curve Grades menu item is disabled when isDisabled is true', function () {
const props = defaultProps({ curveGradesAction: { isDisabled: true } });
this.wrapper = mountAndOpenOptions(props);
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
ok(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('Curve Grades menu item is enabled when isDisabled is false', function () {
this.wrapper = mountAndOpenOptions(defaultProps());
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
notOk(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('clicking the menu item invokes onSelect with correct callback', function () {
const onSelect = this.stub();
const props = defaultProps({ curveGradesAction: { onSelect } });
this.wrapper = mountAndOpenOptions(props);
const menuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
menuItem.click();
equal(onSelect.callCount, 1);
equal(onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
test('the Curve Grades dialog has focus when it is invoked', function () {
const props = defaultProps();
const curveGradesActionOptions = {
isAdmin: true,
contextUrl: 'http://contextUrl',
submissionsLoaded: true
};
const curveGradesProps = CurveGradesDialogManager.createCurveGradesAction(
props.assignment, props.students, curveGradesActionOptions
);
props.curveGradesAction.onSelect = curveGradesProps.onSelect;
this.wrapper = mountAndOpenOptions(props, { attachTo: document.querySelector('#fixtures') });
const specificMenuItem = document.querySelector('[data-menu-item-id="curve-grades"]');
specificMenuItem.click();
const allDialogCloseButtons = document.querySelectorAll('.ui-dialog-titlebar-close.ui-state-focus');
const dialogCloseButton = allDialogCloseButtons[allDialogCloseButtons.length - 1];
equal(document.activeElement, dialogCloseButton);
dialogCloseButton.click();
});
QUnit.module('AssignmentColumnHeader: Message Students Who Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const menuItem = document.querySelector('[data-menu-item-id="message-students-who"]');
equal(menuItem.textContent, 'Message Students Who');
notOk(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('disables the menu item when submissions are not loaded', function () {
this.props.submissionsLoaded = false;
this.wrapper = mountAndOpenOptions(this.props);
const menuItem = document.querySelector('[data-menu-item-id="message-students-who"]');
equal(menuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), 'true');
});
test('clicking the menu item invokes the Message Students Who dialog with correct callback', function () {
this.wrapper = mountAndOpenOptions(this.props);
const messageStudents = this.stub(window, 'messageStudents');
const menuItem = document.querySelector('[data-menu-item-id="message-students-who"]');
menuItem.click();
equal(messageStudents.callCount, 1);
equal(messageStudents.getCall(0).args[0].onClose, this.wrapper.instance().focusAtEnd);
});
QUnit.module('AssignmentColumnHeader: Mute/Unmute Assignment Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the enabled "Mute Assignment" option when assignment is not muted', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
equal(specificMenuItem.textContent, 'Mute Assignment');
notOk(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('shows the enabled "Unmute Assignment" option when assignment is muted', function () {
this.props.assignment.muted = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
equal(specificMenuItem.textContent, 'Unmute Assignment');
notOk(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('disables the option when prop muteAssignmentAction.disabled is truthy', function () {
this.props.muteAssignmentAction.disabled = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
equal(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), 'true');
});
test('clicking the menu item invokes onSelect with correct callback', function () {
this.props.muteAssignmentAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
specificMenuItem.click();
equal(this.props.muteAssignmentAction.onSelect.callCount, 1);
equal(this.props.muteAssignmentAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
test('the Assignment Muting dialog has focus when it is invoked', function () {
const dialogManager = new AssignmentMuterDialogManager(this.props.assignment, 'http://url', true);
this.props.muteAssignmentAction.onSelect = dialogManager.showDialog;
this.wrapper = mountAndOpenOptions(this.props, { attachTo: document.querySelector('#fixtures') });
const specificMenuItem = document.querySelector('[data-menu-item-id="assignment-muter"]');
specificMenuItem.click();
const allDialogCloseButtons = document.querySelectorAll('.ui-dialog-titlebar-close.ui-state-focus');
const dialogCloseButton = allDialogCloseButtons[allDialogCloseButtons.length - 1];
equal(document.activeElement, dialogCloseButton);
dialogCloseButton.click();
});
QUnit.module('AssignmentColumnHeader: non-standard assignment', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('renders 0 points possible when the assignment has no possible points', function () {
this.props.assignment.pointsPossible = undefined;
this.wrapper = mountComponent(this.props);
const pointsPossible = this.wrapper.find('.assignment-points-possible');
equal(pointsPossible.length, 1);
equal(pointsPossible.text().trim(), 'Out of 0');
});
test('renders a muted icon when the assignment is muted', function () {
this.props.assignment.muted = true;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconMutedSolid');
const expectedLinkTitle = 'This assignment is muted';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
test('renders a warning icon when the assignment does not count towards final grade', function () {
this.props.assignment.omitFromFinalGrade = true;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconWarningSolid');
const expectedLinkTitle = 'This assignment does not count toward the final grade';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
test('renders a warning icon when the assignment has zero points possible', function () {
this.props.assignment.pointsPossible = 0;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconWarningSolid');
const expectedLinkTitle = 'This assignment has no points possible and cannot be included in grade calculation';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
test('renders a warning icon when the assignment has null points possible', function () {
this.props.assignment.pointsPossible = null;
this.wrapper = mountComponent(this.props);
const link = this.wrapper.find('.assignment-name Link');
const icon = link.find('IconWarningSolid');
const expectedLinkTitle = 'This assignment has no points possible and cannot be included in grade calculation';
equal(link.length, 1);
deepEqual(link.props().title, expectedLinkTitle);
equal(icon.length, 1);
equal(icon.props().title, expectedLinkTitle);
});
QUnit.module('AssignmentColumnHeader: Set Default Grade Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
equal(specificMenuItem.textContent, 'Set Default Grade');
strictEqual(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), null);
});
test('disables the menu item when the disabled prop is true', function () {
this.props.setDefaultGradeAction.disabled = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
equal(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'), 'true');
});
test('clicking the menu item invokes onSelect with correct callback', function () {
this.props.setDefaultGradeAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
specificMenuItem.click();
equal(this.props.setDefaultGradeAction.onSelect.callCount, 1);
equal(this.props.setDefaultGradeAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
test('the Set Default Grade dialog has focus when it is invoked', function () {
const dialogManager =
new SetDefaultGradeDialogManager(this.props.assignment, this.props.students, 1, '1', true, true);
this.props.setDefaultGradeAction.onSelect = dialogManager.showDialog;
this.wrapper = mountAndOpenOptions(this.props, { attachTo: document.querySelector('#fixtures') });
const specificMenuItem = document.querySelector('[data-menu-item-id="set-default-grade"]');
specificMenuItem.click();
const allDialogCloseButtons = document.querySelectorAll('.ui-dialog-titlebar-close.ui-state-focus');
const dialogCloseButton = allDialogCloseButtons[allDialogCloseButtons.length - 1];
equal(document.activeElement, dialogCloseButton);
dialogCloseButton.click();
});
QUnit.module('AssignmentColumnHeader: Download Submissions Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="download-submissions"]');
equal(specificMenuItem.textContent, 'Download Submissions');
notOk(specificMenuItem.parentElement.parentElement.parentElement.getAttribute('aria-disabled'));
});
test('does not render the menu item when the hidden prop is true', function () {
this.props.downloadSubmissionsAction.hidden = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="download-submissions"]');
equal(specificMenuItem, null);
});
test('clicking the menu item invokes onSelect with correct callback', function () {
this.props.downloadSubmissionsAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="download-submissions"]');
specificMenuItem.click();
equal(this.props.downloadSubmissionsAction.onSelect.callCount, 1);
equal(this.props.downloadSubmissionsAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
QUnit.module('AssignmentColumnHeader: Reupload Submissions Action', {
setup () {
this.props = defaultProps();
},
teardown () {
this.wrapper.unmount();
}
});
test('shows the menu item in an enabled state', function () {
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="reupload-submissions"]');
equal(specificMenuItem.textContent, 'Re-Upload Submissions');
strictEqual(specificMenuItem.parentElement.getAttribute('aria-disabled'), null);
});
test('does not render the menu item when the hidden prop is true', function () {
this.props.reuploadSubmissionsAction.hidden = true;
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="reupload-submissions"]');
equal(specificMenuItem, null);
});
test('clicking the menu item invokes the onSelect property with correct callback', function () {
this.props.reuploadSubmissionsAction.onSelect = this.stub();
this.wrapper = mountAndOpenOptions(this.props);
const specificMenuItem = document.querySelector('[data-menu-item-id="reupload-submissions"]');
specificMenuItem.click();
equal(this.props.reuploadSubmissionsAction.onSelect.callCount, 1);
equal(this.props.reuploadSubmissionsAction.onSelect.getCall(0).args[0], this.wrapper.instance().focusAtEnd);
});
QUnit.module('AssignmentColumnHeader#handleKeyDown', function (hooks) {
hooks.beforeEach(function () {
this.wrapper = mountComponent(defaultProps(), { attachTo: document.querySelector('#fixtures') });
this.preventDefault = sinon.spy();
});
hooks.afterEach(function () {
this.wrapper.unmount();
});
this.handleKeyDown = function (which, shiftKey = false) {
return this.wrapper.node.handleKeyDown({ which, shiftKey, preventDefault: this.preventDefault });
};
QUnit.module('with focus on assignment link', {
setup () {
this.wrapper.node.assignmentLink.focus();
}
});
test('Tab sets focus on options menu trigger', function () {
this.handleKeyDown(9, false); // Tab
equal(document.activeElement, this.wrapper.node.optionsMenuTrigger);
});
test('prevents default behavior for Tab', function () {
this.handleKeyDown(9, false); // Tab
strictEqual(this.preventDefault.callCount, 1);
});
test('returns false for Tab', function () {
// This prevents additional behavior in Grid Support Navigation.
const returnValue = this.handleKeyDown(9, false); // Tab
strictEqual(returnValue, false);
});
test('does not handle Shift+Tab', function () {
// This allows Grid Support Navigation to handle navigation.
const returnValue = this.handleKeyDown(9, true); // Shift+Tab
equal(typeof returnValue, 'undefined');
});
QUnit.module('with focus on options menu trigger', {
setup () {
this.wrapper.node.optionsMenuTrigger.focus();
}
});
test('Shift+Tab sets focus on assignment link', function () {
this.handleKeyDown(9, true); // Shift+Tab
strictEqual(this.wrapper.node.assignmentLink.focused, true);
});
test('prevents default behavior for Shift+Tab', function () {
this.handleKeyDown(9, true); // Shift+Tab
strictEqual(this.preventDefault.callCount, 1);
});
test('returns false for Shift+Tab', function () {
// This prevents additional behavior in Grid Support Navigation.
const returnValue = this.handleKeyDown(9, true); // Shift+Tab
strictEqual(returnValue, false);
});
test('does not handle Tab', function () {
// This allows Grid Support Navigation to handle navigation.
const returnValue = this.handleKeyDown(9, false); // Tab
equal(typeof returnValue, 'undefined');
});
test('Enter opens the options menu', function () {
this.handleKeyDown(13); // Enter
const optionsMenu = this.wrapper.find('PopoverMenu');
strictEqual(optionsMenu.node.show, true);
});
test('returns false for Enter on options menu', function () {
// This prevents additional behavior in Grid Support Navigation.
const returnValue = this.handleKeyDown(13); // Enter
strictEqual(returnValue, false);
});
QUnit.module('without focus');
test('does not handle Tab', function () {
const returnValue = this.handleKeyDown(9, false); // Tab
equal(typeof returnValue, 'undefined');
});
test('does not handle Shift+Tab', function () {
const returnValue = this.handleKeyDown(9, true); // Shift+Tab
equal(typeof returnValue, 'undefined');
});
test('does not handle Enter', function () {
const returnValue = this.handleKeyDown(13); // Enter
equal(typeof returnValue, 'undefined');
});
});
QUnit.module('AssignmentColumnHeader: focus', {
setup () {
this.wrapper = mountComponent(defaultProps(), { attachTo: document.querySelector('#fixtures') });
},
teardown () {
this.wrapper.unmount();
}
});
test('#focusAtStart sets focus on the assignment link', function () {
this.wrapper.node.focusAtStart();
strictEqual(this.wrapper.node.assignmentLink.focused, true);
});
test('#focusAtEnd sets focus on the options menu trigger', function () {
this.wrapper.node.focusAtEnd();
equal(document.activeElement, this.wrapper.node.optionsMenuTrigger);
});
|
assets/javascripts/kitten/components/action/social-button-icon/stories.js
|
KissKissBankBank/kitten
|
import React from 'react'
import {
FacebookButtonIcon,
TwitterButtonIcon,
LinkedinButtonIcon,
InstagramButtonIcon,
YoutubeButtonIcon,
} from './index'
import { DocsPage } from 'storybook/docs-page'
export default {
component: SocialButtonIcon,
title: 'Action/SocialButtonIcon',
parameters: {
docs: {
page: () => (
<DocsPage filepath={__filename} importString="SocialButtonIcon" />
),
},
},
decorators: [
story => (
<div className="story-Container story-Grid story-Grid--thin">
{story()}
</div>
),
],
}
export const SocialButtonIcon = () => (
<>
<FacebookButtonIcon>Facebook</FacebookButtonIcon>
<TwitterButtonIcon>Twitter</TwitterButtonIcon>
<InstagramButtonIcon>Instagram</InstagramButtonIcon>
<LinkedinButtonIcon>Linkedin</LinkedinButtonIcon>
<YoutubeButtonIcon>Youtube</YoutubeButtonIcon>
</>
)
|
node_modules/react-images/src/components/Header.js
|
ed1d1a8d/macweb
|
import PropTypes from 'prop-types';
import React from 'react';
import { css, StyleSheet } from 'aphrodite/no-important';
import defaults from '../theme';
import { deepMerge } from '../utils';
import Icon from './Icon';
function Header ({
customControls,
onClose,
showCloseButton,
closeButtonTitle,
...props,
}, {
theme,
}) {
const classes = StyleSheet.create(deepMerge(defaultStyles, theme));
return (
<div className={css(classes.header)} {...props}>
{customControls ? customControls : <span />}
{!!showCloseButton && (
<button
title={closeButtonTitle}
className={css(classes.close)}
onClick={onClose}
>
<Icon fill={!!theme.close && theme.close.fill || defaults.close.fill} type="close" />
</button>
)}
</div>
);
}
Header.propTypes = {
customControls: PropTypes.array,
onClose: PropTypes.func.isRequired,
showCloseButton: PropTypes.bool,
};
Header.contextTypes = {
theme: PropTypes.object.isRequired,
};
const defaultStyles = {
header: {
display: 'flex',
justifyContent: 'space-between',
height: defaults.header.height,
},
close: {
background: 'none',
border: 'none',
cursor: 'pointer',
outline: 'none',
position: 'relative',
top: 0,
verticalAlign: 'bottom',
// increase hit area
height: 40,
marginRight: -10,
padding: 10,
width: 40,
},
};
module.exports = Header;
|
react-router-tutorial/lessons/11-productionish-server/modules/Repos.js
|
zerotung/practices-and-notes
|
import React from 'react'
import NavLink from './NavLink'
export default React.createClass({
render() {
return (
<div>
<h2>Repos</h2>
<ul>
<li><NavLink to="/repos/reactjs/react-router">React Router</NavLink></li>
<li><NavLink to="/repos/facebook/react">React</NavLink></li>
</ul>
{this.props.children}
</div>
)
}
})
|
src/svg-icons/social/party-mode.js
|
nathanmarks/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPartyMode = (props) => (
<SvgIcon {...props}>
<path d="M20 4h-3.17L15 2H9L7.17 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 3c1.63 0 3.06.79 3.98 2H12c-1.66 0-3 1.34-3 3 0 .35.07.69.18 1H7.1c-.06-.32-.1-.66-.1-1 0-2.76 2.24-5 5-5zm0 10c-1.63 0-3.06-.79-3.98-2H12c1.66 0 3-1.34 3-3 0-.35-.07-.69-.18-1h2.08c.07.32.1.66.1 1 0 2.76-2.24 5-5 5z"/>
</SvgIcon>
);
SocialPartyMode = pure(SocialPartyMode);
SocialPartyMode.displayName = 'SocialPartyMode';
SocialPartyMode.muiName = 'SvgIcon';
export default SocialPartyMode;
|
app/components/Editor/__tests__/Editor-test.js
|
TailorDev/monod
|
import React from 'react';
import { mount, shallow } from 'enzyme';
import { expect } from 'chai';
import Loader from 'react-loader';
import sinon from 'sinon';
// see: https://github.com/mochajs/mocha/issues/1847
const { before, describe, it } = global;
import Editor, { EditorModes } from '../presenter';
import Markdown from '../../Markdown';
import Preview from '../../Preview';
describe('<Editor />', () => {
it('renders Markdown component', () => {
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
expect(wrapper.find(Markdown)).to.have.length(1);
});
it('renders Preview component', () => {
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
expect(wrapper.find(Preview)).to.have.length(1);
});
it('renders a Loader component', () => {
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
expect(wrapper.find(Loader)).to.have.length(1);
});
it('does not display the editor until content is loaded', () => {
const wrapper = mount(
<Editor
loaded={false}
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
expect(wrapper.find('.editor')).to.have.length(0);
});
it('removes loader once content is loaded', () => {
const wrapper = mount(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
expect(wrapper.find('.editor')).to.have.length(1);
});
it('calls onUpdateContent prop on change', () => {
const spy = sinon.spy();
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={spy}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
wrapper.find('Markdown').simulate('change');
expect(spy.called).to.be.true;
});
it('switches from preview to reading mode', () => {
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
const verticalHandlerWrapper = wrapper.find('VerticalHandler').shallow();
// Mock the click event
verticalHandlerWrapper
.find('.left')
.simulate('click', { target: { className: 'left' } });
expect(wrapper.state('mode')).to.be.equal(EditorModes.READING);
});
it('switches from preview to reading mode and then back to preview mode', () => {
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
const verticalHandlerWrapper = wrapper.find('VerticalHandler').shallow();
// Mock the click event
verticalHandlerWrapper
.find('.left')
.simulate('click', { target: { className: 'left' } });
expect(wrapper.state('mode')).to.be.equal(EditorModes.READING);
verticalHandlerWrapper
.find('.right')
.simulate('click', { target: { className: 'right' } });
expect(wrapper.state('mode')).to.be.equal(EditorModes.PREVIEW);
});
it('switches from preview to focus mode', () => {
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
const verticalHandlerWrapper = wrapper.find('VerticalHandler').shallow();
// Mock the click event
verticalHandlerWrapper
.find('.right')
.simulate('click', { target: { className: 'right' } });
expect(wrapper.state('mode')).to.be.equal(EditorModes.FOCUS);
});
it('switches from preview to focus mode and then back to preview mode', () => {
const wrapper = shallow(
<Editor
loaded
content={''}
onUpdateContent={() => {}}
template={''}
forceUpdate={false}
onClickCheckbox={() => {}}
/>
);
const verticalHandlerWrapper = wrapper.find('VerticalHandler').shallow();
// Mock the click event
verticalHandlerWrapper
.find('.right')
.simulate('click', { target: { className: 'right' } });
expect(wrapper.state('mode')).to.be.equal(EditorModes.FOCUS);
verticalHandlerWrapper
.find('.left')
.simulate('click', { target: { className: 'left' } });
expect(wrapper.state('mode')).to.be.equal(EditorModes.PREVIEW);
});
});
|
packages/core/__deprecated__/Arwes/sandbox.js
|
romelperez/arwes
|
import React from 'react';
import Arwes from './index';
export default () => (
<Arwes animate background='/images/background.jpg' pattern='/images/glow.png'>
<h2>SciFi UI Framework</h2>
<p>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim
veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea
commodo consequat. Duis aute irure dolor in reprehenderit in voluptate
velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat
cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id
est laborum.
</p>
</Arwes>
);
|
src/components/seo.js
|
benjaminmodayil/modayilme
|
import React from 'react';
import PropTypes from 'prop-types';
import Helmet from 'react-helmet';
import { StaticQuery, graphql } from 'gatsby';
function SEO({ description, lang, meta, keywords, title }) {
return (
<StaticQuery
query={detailsQuery}
render={(data) => {
const metaDescription = description || data.site.siteMetadata.description;
return (
<Helmet
htmlAttributes={{
lang,
}}
title={title}
titleTemplate={`%s | ${data.site.siteMetadata.title}`}
meta={[
{
name: `description`,
content: metaDescription,
},
{
property: `og:title`,
content: title,
},
{
property: `og:description`,
content: metaDescription,
},
{
property: `og:type`,
content: `website`,
},
{
name: `twitter:card`,
content: `summary`,
},
{
name: `twitter:creator`,
content: data.site.siteMetadata.author,
},
{
name: `twitter:title`,
content: title,
},
{
name: `twitter:description`,
content: metaDescription,
},
]
.concat(
keywords.length > 0
? {
name: `keywords`,
content: keywords.join(`, `),
}
: []
)
.concat(meta)}
/>
);
}}
/>
);
}
SEO.defaultProps = {
lang: `en`,
meta: [],
keywords: [],
};
SEO.propTypes = {
description: PropTypes.string,
lang: PropTypes.string,
meta: PropTypes.array,
keywords: PropTypes.arrayOf(PropTypes.string),
title: PropTypes.string.isRequired,
};
export default SEO;
const detailsQuery = graphql`
query DefaultSEOQuery {
site {
siteMetadata {
title
description
author
}
}
}
`;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.