path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
actor-apps/app-web/src/app/components/ToolbarSection.react.js
|
chieryw/actor-platform
|
import React from 'react';
import DialogStore from 'stores/DialogStore';
import ActivityActionCreators from 'actions/ActivityActionCreators';
//import AvatarItem from 'components/common/AvatarItem.react';
var getStateFromStores = () => {
return {dialogInfo: null};
};
class ToolbarSection extends React.Component {
componentWillMount() {
DialogStore.addSelectedChangeListener(this.onChange);
}
componentWillUnmount() {
DialogStore.removeSelectedChangeListener(this.onChange);
}
constructor() {
super();
this.onClick = this.onClick.bind(this);
this.onChange = this.onChange.bind(this);
this.state = getStateFromStores();
}
onClick() {
ActivityActionCreators.show();
}
onChange() {
this.setState({dialogInfo: DialogStore.getSelectedDialogInfo()});
}
render() {
let info = this.state.dialogInfo;
let dialogElement;
if (info != null) {
dialogElement = (
<div className="toolbar__peer row">
{/*
<a onClick={this.onClick}>
<AvatarItem image={info.avatar}
placeholder={info.placeholder}
size="small"
title={info.name}/>
</a>
*/}
<div className="toolbar__peer__body col-xs">
<span className="toolbar__peer__title" onClick={this.onClick}>{info.name}</span>
<span className="toolbar__peer__presence">{info.presence}</span>
</div>
</div>
);
} else {
dialogElement = null;
}
return (
<header className="toolbar">
{dialogElement}
</header>
);
}
}
export default ToolbarSection;
|
tests/routes/Home/components/HomeView.spec.js
|
jhardin293/colorize
|
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!/)
})
})
|
src/layouts/CoreLayout/CoreLayout.js
|
howlowck/train-faces
|
import React from 'react'
import Header from '../../components/Header'
import { Layout } from 'antd'
import './CoreLayout.scss'
import '../../styles/core.scss'
const { Content, Footer } = Layout
export const CoreLayout = ({ children }) => (
<Layout className='layout'>
<Header />
<Content style={{ padding: '0 50px' }}>
<div style={{ background: '#fff', padding: 0, minHeight: 280 }}>{children}</div>
</Content>
<Footer style={{ textAlign: 'center' }}>
Created by Hao Luo
</Footer>
</Layout>
)
CoreLayout.propTypes = {
children: React.PropTypes.element.isRequired
}
export default CoreLayout
|
app/javascript/mastodon/containers/account_container.js
|
nonoz/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { makeGetAccount } from '../selectors';
import Account from '../components/account';
import {
followAccount,
unfollowAccount,
blockAccount,
unblockAccount,
muteAccount,
unmuteAccount,
} from '../actions/accounts';
import { openModal } from '../actions/modal';
const messages = defineMessages({
unfollowConfirm: { id: 'confirmations.unfollow.confirm', defaultMessage: 'Unfollow' },
});
const makeMapStateToProps = () => {
const getAccount = makeGetAccount();
const mapStateToProps = (state, props) => ({
account: getAccount(state, props.id),
me: state.getIn(['meta', 'me']),
unfollowModal: state.getIn(['meta', 'unfollow_modal']),
});
return mapStateToProps;
};
const mapDispatchToProps = (dispatch, { intl }) => ({
onFollow (account) {
if (account.getIn(['relationship', 'following'])) {
if (this.unfollowModal) {
dispatch(openModal('CONFIRM', {
message: <FormattedMessage id='confirmations.unfollow.message' defaultMessage='Are you sure you want to unfollow {name}?' values={{ name: <strong>@{account.get('acct')}</strong> }} />,
confirm: intl.formatMessage(messages.unfollowConfirm),
onConfirm: () => dispatch(unfollowAccount(account.get('id'))),
}));
} else {
dispatch(unfollowAccount(account.get('id')));
}
} else {
dispatch(followAccount(account.get('id')));
}
},
onBlock (account) {
if (account.getIn(['relationship', 'blocking'])) {
dispatch(unblockAccount(account.get('id')));
} else {
dispatch(blockAccount(account.get('id')));
}
},
onMute (account) {
if (account.getIn(['relationship', 'muting'])) {
dispatch(unmuteAccount(account.get('id')));
} else {
dispatch(muteAccount(account.get('id')));
}
},
});
export default injectIntl(connect(makeMapStateToProps, mapDispatchToProps)(Account));
|
src/components/Weui/grid/grid.js
|
ynu/res-track-wxe
|
/**
* Created by n7best
*/
import React from 'react';
import classNames from 'classnames';
import GridIcon from './grid_icon';
import GridLabel from './grid_label';
export default class Grid extends React.Component {
static propTypes = {
label: React.PropTypes.string,
icon: React.PropTypes.any
};
static defaultProps = {
label: '',
icon: false
};
render() {
const {children, icon, label, className, ...others} = this.props;
const cls = classNames({
weui_grid: true
}, className);
return (
<a className={cls} {...others}>
{icon ? <GridIcon>{icon}</GridIcon> : false}
{children}
{label ? <GridLabel>{label}</GridLabel> : false}
</a>
);
}
};
|
desktop/apps/auction2/test/components.js
|
dblock/force
|
require('babel-core/register')
require('coffee-script/register')
import * as actions from '../actions'
import auctions from '../reducers'
import ArtistFilter from '../components/artist_filter'
import AuctionGridArtwork from '../components/auction_grid_artwork'
import AuctionListArtwork from '../components/auction_list_artwork'
import FilterSort from '../components/filter_sort'
import MediumFilter from '../components/medium_filter'
import { shallow } from 'enzyme'
import React from 'react'
import { renderToString } from 'react-dom/server'
import { Provider } from 'react-redux'
import { createStore } from 'redux'
describe('React components', () => {
let initialStore
beforeEach(() => {
initialStore = createStore(auctions)
})
describe('AuctionArtwork', () => {
let saleArtwork
beforeEach(() => {
saleArtwork = {
lot_number: 2,
current_bid: {
display: '$100'
},
counts: {
bidder_positions: 2
},
artwork: {
_id: '123',
title: 'My Artwork',
date: '2002',
artists: {
name: 'Andy Warhol'
},
images: [{
image_url: 'my_image.jpg'
}]
}
}
})
it('renders an auction grid artwork component', () => {
const renderedArtwork = renderToString(AuctionGridArtwork({ saleArtwork }))
renderedArtwork.should.containEql('<em>My Artwork</em>, 2002')
})
it('renders an auction list artwork component', () => {
const renderedArtwork = renderToString(AuctionListArtwork({ saleArtwork }))
renderedArtwork.should.containEql('<em>My Artwork</em>, 2002')
})
})
describe('ArtistFilter', () => {
let aggregatedArtists
beforeEach(() => {
aggregatedArtists = [
{ id: 'artist-1', name: 'Artist 1', count: 23 },
{ id: 'artist-2', name: 'Artist 2', count: 44 },
{ id: 'artist-3', name: 'Artist 3', count: 57 }
]
})
describe('no artists selected', () => {
it('contains all of the aggregated artists and checks the artists-all box', () => {
initialStore.dispatch(actions.updateAggregatedArtists(aggregatedArtists))
const wrapper = shallow(
<Provider><ArtistFilter store={initialStore} /></Provider>
)
const rendered = wrapper.render()
rendered.find('.artsy-checkbox').length.should.eql(4)
const renderedText = rendered.text()
renderedText.should.containEql('All')
renderedText.should.containEql('Artist 1(23)')
renderedText.should.containEql('Artist 2(44)')
renderedText.should.containEql('Artist 3(57)')
rendered.find('input[value="artists-all"]:checked').length.should.eql(1)
})
})
describe('some artists selected', () => {
it('checks the correct artist boxes', () => {
initialStore.dispatch(actions.updateAggregatedArtists(aggregatedArtists))
initialStore.dispatch(actions.updateArtistId('artist-1'))
const wrapper = shallow(
<Provider><ArtistFilter store={initialStore} /></Provider>
)
const rendered = wrapper.render()
rendered.find('.artsy-checkbox').length.should.eql(4)
const renderedText = rendered.text()
renderedText.should.containEql('All')
renderedText.should.containEql('Artist 1(23)')
renderedText.should.containEql('Artist 2(44)')
renderedText.should.containEql('Artist 3(57)')
rendered.find('input[value="artists-all"]:checked').length.should.eql(0)
rendered.find('input[value="artist-1"]:checked').length.should.eql(1)
})
})
})
describe('MediumFilter', () => {
let aggregatedMediums
beforeEach(() => {
aggregatedMediums = [
{ id: 'painting', name: 'Painting', count: 23 },
{ id: 'work-on-paper', name: 'Works on Paper', count: 44 },
{ id: 'design', name: 'Design', count: 57 }
]
})
describe('no mediums selected', () => {
it('checks the mediums-all box', () => {
initialStore.dispatch(actions.updateInitialMediumMap(aggregatedMediums))
initialStore.dispatch(actions.updateAggregatedMediums(aggregatedMediums))
const wrapper = shallow(
<Provider><MediumFilter store={initialStore} /></Provider>
)
const rendered = wrapper.render()
rendered.find('.artsy-checkbox').length.should.eql(4)
const renderedText = rendered.text()
renderedText.should.containEql('All')
renderedText.should.containEql('Painting(23)')
renderedText.should.containEql('Works on Paper(44)')
renderedText.should.containEql('Design(57)')
rendered.find('input[value="mediums-all"]:checked').length.should.eql(1)
})
})
describe('some mediums selected', () => {
it('checks the correct medium boxes', () => {
initialStore.dispatch(actions.updateInitialMediumMap(aggregatedMediums))
initialStore.dispatch(actions.updateAggregatedMediums(aggregatedMediums))
initialStore.dispatch(actions.updateMediumId('painting'))
const wrapper = shallow(
<Provider><MediumFilter store={initialStore} /></Provider>
)
const rendered = wrapper.render()
rendered.find('.artsy-checkbox').length.should.eql(4)
const renderedText = rendered.text()
renderedText.should.containEql('All')
renderedText.should.containEql('Painting(23)')
renderedText.should.containEql('Works on Paper(44)')
renderedText.should.containEql('Design(57)')
rendered.find('input[value="mediums-all"]:checked').length.should.eql(0)
rendered.find('input[value="painting"]:checked').length.should.eql(1)
})
})
})
describe('FilterSort', () => {
it('selects the correct option', () => {
const wrapper = shallow(
<Provider><FilterSort store={initialStore} /></Provider>
)
wrapper.render().find('.bordered-pulldown-text').text().should.eql('Lot Number (asc.)')
})
})
})
|
app/components/Home.js
|
munir7/react
|
import React from 'react';
class Home extends React.Component {
render() {
return (
<h2 className="text-center">
Search by Github Username Above
</h2>
)
}
};
export default Home;
|
src/SplitButton.js
|
kwnccc/react-bootstrap
|
/* eslint react/prop-types: [2, {ignore: "bsSize"}] */
/* BootstrapMixin contains `bsSize` type validation */
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import DropdownStateMixin from './DropdownStateMixin';
import Button from './Button';
import ButtonGroup from './ButtonGroup';
import DropdownMenu from './DropdownMenu';
const SplitButton = React.createClass({
mixins: [BootstrapMixin, DropdownStateMixin],
propTypes: {
pullRight: React.PropTypes.bool,
title: React.PropTypes.node,
href: React.PropTypes.string,
id: React.PropTypes.string,
target: React.PropTypes.string,
dropdownTitle: React.PropTypes.node,
dropup: React.PropTypes.bool,
onClick: React.PropTypes.func,
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool,
className: React.PropTypes.string,
children: React.PropTypes.node
},
getDefaultProps() {
return {
dropdownTitle: 'Toggle dropdown',
disabled: false,
dropup: false,
pullRight: false
};
},
render() {
let groupClasses = {
'open': this.state.open,
'dropup': this.props.dropup
};
let button = (
<Button
{...this.props}
ref="button"
onClick={this.handleButtonClick}
title={null}
id={null}>
{this.props.title}
</Button>
);
let dropdownButton = (
<Button
{...this.props}
ref="dropdownButton"
className={classNames(this.props.className, 'dropdown-toggle')}
onClick={this.handleDropdownClick}
title={null}
href={null}
target={null}
id={null}>
<span className="sr-only">{this.props.dropdownTitle}</span>
<span className="caret" />
<span style={{letterSpacing: '-.3em'}}> </span>
</Button>
);
return (
<ButtonGroup
bsSize={this.props.bsSize}
className={classNames(groupClasses)}
id={this.props.id}>
{button}
{dropdownButton}
<DropdownMenu
ref="menu"
onSelect={this.handleOptionSelect}
aria-labelledby={this.props.id}
pullRight={this.props.pullRight}>
{this.props.children}
</DropdownMenu>
</ButtonGroup>
);
},
handleButtonClick(e) {
if (this.state.open) {
this.setDropdownState(false);
}
if (this.props.onClick) {
this.props.onClick(e, this.props.href, this.props.target);
}
},
handleDropdownClick(e) {
e.preventDefault();
this.setDropdownState(!this.state.open);
},
handleOptionSelect(key) {
if (this.props.onSelect) {
this.props.onSelect(key);
}
this.setDropdownState(false);
}
});
export default SplitButton;
|
src/components/Keyword.js
|
Bynno/politicheck-app
|
import React from 'react';
export default React.createClass({
getInitialState() {
return {
collapsed: true
};
},
toggleCollapse() {
console.log('Toggle collapse', this.state.collapsed);
this.setState({
collapsed: !this.state.collapsed
});
},
renderVotes() {
return this.props.data.votes.map((vote, i) => {
const {official_title, short_title, popular_title, urls} = vote.bill;
const color = vote.vote_type === 'Yea' ? 'green' : (vote.vote_type === 'Nay' ? 'red' : '');
const title = popular_title ? popular_title : (short_title ? short_title : official_title);
return (
<a key={i} className={`ui ${color} fluid card`} target="_blank" href={urls.opencongress}>
<div className="content">
{title}
</div>
<div className="extra content">
<div className="meta">
Vote: {vote.vote_type}
</div>
</div>
</a>
);
});
},
render() {
const {data} = this.props;
if (!this.state.collapsed) {
return (
<div className="item">
<a onClick={this.toggleCollapse}>
<span className="ui right pointing label">{data.score}</span>
{data.key}
</a>
<div className="ui info message">
{data.votes.length} Votes
</div>
{this.renderVotes()}
</div>
);
} else {
return (
<div className="item">
<a onClick={this.toggleCollapse}>
<span className="ui right pointing label">{data.score}</span>
{data.key}
</a>
</div>
);
}
}
});
|
assets/jqwidgets/demos/react/app/numberinput/righttoleftlayout/app.js
|
juannelisalde/holter
|
import React from 'react';
import ReactDOM from 'react-dom';
import JqxNumberInput from '../../../jqwidgets-react/react_jqxnumberinput.js';
class App extends React.Component {
render() {
return (
<div id='jqxWidget' style={{ fontSize: 13, fontFamily: 'Verdana', float: 'left' }}>
<div style={{ marginTop: 10 }}>Number</div>
<JqxNumberInput ref='numericInput' style={{ marginTop: 3 }}
rtl={true} inputMode={'simple'}
width={250} height={25} spinButtons={true}
/>
<div style={{ marginTop: 10 }}>Percentage</div>
<JqxNumberInput ref='percentageInput' style={{ marginTop: 3 }}
rtl={true}
width={250} height={25}
digits={3} symbolPosition={'right'}
symbol={'%'} spinButtons={true}
/>
<div style={{ marginTop: 10 }}>Currency</div>
<JqxNumberInput ref='currencyInput' style={{ marginTop: 3 }}
rtl={true}
width={250} height={25}
symbol={'$'} spinButtons={true}
/>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/PokemonPreview.js
|
rafaelkyrdan/relay-app
|
import React from 'react'
import Relay from 'react-relay'
import { Link } from 'react-router'
import classes from './PokemonPreview.css'
class PokemonPreview extends React.Component {
static propTypes = {
pokemon: React.PropTypes.object,
router: React.PropTypes.object,
}
render () {
return (
<Link className={classes.link} to={`/view/${this.props.pokemon.id}`}>
<div className={classes.previewPage}>
<img className={classes.previewImg} src={this.props.pokemon.url} alt='Pokemon Image' />
<div className={classes.previewName}>
{this.props.pokemon.name}
</div>
</div>
</Link>
)
}
}
export default Relay.createContainer(
PokemonPreview,
{
fragments: {
pokemon: () => Relay.QL`
fragment on Pokemon {
id
name
url
}
`,
},
}
)
|
src/components/Form/Checklist.js
|
ilxanlar/cathode
|
import React from 'react';
import styled from 'styled-components';
import Grid from '../Layout/Grid';
import { checklist as propTypes } from '../../helpers/propTypes';
const ChecklistRaw = ({ children, gridColumnProps, gridRowProps }) => (
<Grid.Row {...gridRowProps}>
{
React.Children.map(children, child => (
<Grid.Column {...gridColumnProps}>
{child}
</Grid.Column>
))
}
</Grid.Row>
);
const Checklist = styled(ChecklistRaw)``;
Checklist.propTypes = propTypes;
Checklist.defaultProps = {
gridColumnProps: {
xxs: 24,
md: 12,
lg: 8,
xl: 6
},
gridRowProps: {}
};
export default Checklist;
|
packages/@vega/communicator-system/src/components/views/CommentBodyInput.js
|
VegaPublish/vega-studio
|
//@flow
import React from 'react'
import schema from 'part:@lyra/base/schema'
import EditDocumentField from '@vega/components/EditDocumentField'
const commentType = schema.get('comment')
type Props = {
comment: {
_id: string,
body: Array<*>
},
onChange: Function,
patchChannel: Object
}
export default function CommentBodyInput(props: Props) {
const {comment, onChange, patchChannel} = props
return (
<EditDocumentField
key={comment._id}
fieldName="body"
type={commentType}
value={comment}
onChange={onChange}
patchChannel={patchChannel}
hideLabel
/>
)
}
|
src/App/App.js
|
romellogood/react-stylus-reactrouter-boilerplate
|
import React from 'react';
import styles from './App.styl';
export default class App extends React.Component {
render() {
return (
<div className={styles.App}>
<h1>App Home</h1>
<ul>
<li><a href="/">Home</a></li>
<li><a href="/about">About</a></li>
<li><a href="/test">Not Found</a></li>
</ul>
{this.props.children}
</div>
)
}
}
|
mysite/ctms/frontend/src/AddManually.js
|
cjlee112/socraticqs2
|
import React from 'react';
import Cookie from 'js-cookie';
import {NavLink} from 'react-router-dom';
export class AddManually extends React.Component {
render() {
return (
<div>
<main className="card__content">
<form action={window.location} method="POST">
<input type="hidden" name="csrfmiddlewaretoken" value={Cookie.get("csrftoken")} />
<label htmlFor="id_title" className="card__title">Add a Thread Manually</label>
<p className="content--medium">
Use this option to add a new thread on your own. If you prefer, you can also
<NavLink to="/upload"> upload a document </NavLink> and let our experienced instructors do it for you.
</p>
<label htmlFor="new-todo">
Thread title.
</label>
<p className="content--large">
Choose a name that's short – a few words – and distinct – that helps students easily recognize this question within the list shown in the sidebar. For example, if your courselet presented questions about probability, and this question was the only one that featured trains (as an example), you could name it something like "Two Trains". Don't try to make the name a summary of what the question's asking -- that will be too long.
</p>
<input
id="new-todo"
type="text"
name="title"
required
/>
<input type="submit" value="Add Thread" />
</form>
</main>
</div>
);
}
}
|
src/javascripts/base.react.js
|
him0/nem-invoice
|
import React from 'react';
import { render } from 'react-dom'
import { BrowserRouter, Route, Switch } from 'react-router-dom'
import { Textfield } from 'react-mdl';
import InvoicesIndex from './views/invoices/index';
import InvoicesNew from './views/invoices/new';
import InvoicesShow from './views/invoices/show';
export default () => {
render(
<Textfield
value=""
onChange={() => {}}
label="Search"
expandable
expandableIcon="search"
style={{ color: "black" }}
/>,
document.getElementById('search')
);
render(
<BrowserRouter>
<Switch>
<Route path='/invoices/new' component={InvoicesNew} />
<Route path='/invoices/:id' component={InvoicesShow} />
<Route path='/invoices' component={InvoicesIndex} />
</Switch>
</BrowserRouter>,
document.getElementById('root')
);
};
|
src/components/Settings/Speech/Speech.container.js
|
shayc/cboard
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import debounce from 'lodash/debounce';
import { injectIntl } from 'react-intl';
import {
speak,
cancelSpeech,
changeVoice,
changePitch,
changeRate
} from '../../../providers/SpeechProvider/SpeechProvider.actions';
import Speech from './Speech.component';
import messages from './Speech.messages';
import API from '../../../api';
export class SpeechContainer extends Component {
static propTypes = {
/**
* Active language
*/
lang: PropTypes.string,
speech: PropTypes.object,
voices: PropTypes.array,
cancelSpeech: PropTypes.func,
changeVoice: PropTypes.func,
changePitch: PropTypes.func,
changeRate: PropTypes.func,
history: PropTypes.object.isRequired
};
state = {
selectedVoiceIndex: 0,
voiceOpen: false,
anchorEl: null
};
speakSample = debounce(() => {
const { cancelSpeech, intl, speak } = this.props;
const text = intl.formatMessage(messages.sampleSentence);
cancelSpeech();
speak(text);
}, 500);
handleClickListItem = event => {
this.setState({ voiceOpen: true, anchorEl: event.currentTarget });
};
handleMenuItemClick = async ({ voiceURI, lang }, index) => {
const { changeVoice } = this.props;
changeVoice(voiceURI, lang);
this.speakSample();
await this.updateSettings('voiceURI', voiceURI);
this.setState({ voiceOpen: false, selectedVoiceIndex: index });
};
updateSettings(property, value) {
if (this.updateSettingsTimeout) {
clearTimeout(this.updateSettingsTimeout);
}
this.updateSettingsTimeout = setTimeout(async () => {
const {
speech: {
options: { voiceURI, pitch, rate }
}
} = this.props;
const speech = {
voiceURI,
pitch,
rate,
[property]: value
};
try {
await API.updateSettings({ speech });
} catch (e) {}
}, 500);
}
handleChangePitch = async (event, value) => {
const { changePitch } = this.props;
await this.updateSettings('pitch', value);
changePitch(value);
this.speakSample();
};
handleChangeRate = async (event, value) => {
const { changeRate } = this.props;
await this.updateSettings('rate', value);
changeRate(value);
this.speakSample();
};
handleVoiceClose = () => {
this.setState({ voiceOpen: false });
};
render() {
const {
history,
intl,
lang,
speech: {
voices,
options: { voiceURI, pitch, rate }
}
} = this.props;
const langVoices = voices.filter(
voice => voice.lang.slice(0, 2) === lang.slice(0, 2)
);
const voiceArray = voices.filter(v => voiceURI === v.voiceURI);
const voice = voiceArray[0];
return (
<Speech
{...this.state}
handleChangePitch={this.handleChangePitch}
handleChangeRate={this.handleChangeRate}
handleClickListItem={this.handleClickListItem}
handleMenuItemClick={this.handleMenuItemClick}
handleVoiceClose={this.handleVoiceClose}
intl={intl}
langVoices={langVoices}
onClose={history.goBack}
pitch={pitch}
rate={rate}
voice={voice}
/>
);
}
}
const mapStateToProps = state => ({
lang: state.language.lang,
voices: state.speech.voices,
speech: state.speech
});
const mapDispatchToProps = {
cancelSpeech,
changeVoice,
changePitch,
changeRate,
speak
};
const EnhancedSpeechContainer = injectIntl(SpeechContainer);
export default connect(
mapStateToProps,
mapDispatchToProps
)(EnhancedSpeechContainer);
|
docs/app/Examples/views/Feed/Variations/FeedExampleSizeSmall.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import { Feed, Header } from 'semantic-ui-react'
const FeedExampleSizeSmall = () => (
<Feed size='small'>
<Header as='h4'>Followers Activity</Header>
<Feed.Event>
<Feed.Content>
<Feed.Summary>
<a>Elliot Fu</a> added <a>Jenny Hess</a> as a friend
</Feed.Summary>
</Feed.Content>
</Feed.Event>
<Feed.Event>
<Feed.Content>
<Feed.Summary>
<a>Stevie Feliciano</a> added <a>Elliot Fu</a> as a friend
</Feed.Summary>
</Feed.Content>
</Feed.Event>
<Feed.Event>
<Feed.Content>
<Feed.Summary>
<a>Helen Troy</a> added <a>Christian Rocha</a> as a friend
</Feed.Summary>
</Feed.Content>
</Feed.Event>
<Feed.Event>
<Feed.Content>
<Feed.Summary>
<a>Christian Rocha</a> signed up for the site.
</Feed.Summary>
</Feed.Content>
</Feed.Event>
</Feed>
)
export default FeedExampleSizeSmall
|
src/DropdownButton.js
|
Sipree/react-bootstrap
|
import React from 'react';
import Dropdown from './Dropdown';
import omit from 'lodash-compat/object/omit';
import pick from 'lodash-compat/object/pick';
import Button from './Button';
class DropdownButton extends React.Component {
render() {
let { bsStyle, bsSize, disabled, className, menuStyle, open } = this.props;
let { title, children, ...props } = this.props;
let dropdownProps = pick(props, Object.keys(Dropdown.ControlledComponent.propTypes));
let toggleProps = omit(props, Object.keys(Dropdown.ControlledComponent.propTypes));
return (
<Dropdown {...dropdownProps}
bsSize={bsSize}
bsStyle={bsStyle}
>
<Dropdown.Toggle
{...toggleProps}
disabled={disabled}
>
{title}
</Dropdown.Toggle>
<Dropdown.Menu open={this.props.open} menuStyle={this.props.hasOwnProperty('menuStyle') ? this.props.menuStyle : {}}>
{children}
</Dropdown.Menu>
</Dropdown>
);
}
}
DropdownButton.propTypes = {
disabled: React.PropTypes.bool,
bsStyle: Button.propTypes.bsStyle,
bsSize: Button.propTypes.bsSize,
/**
* When used with the `title` prop, the noCaret option will not render a caret icon, in the toggle element.
*/
noCaret: React.PropTypes.bool,
title: React.PropTypes.node.isRequired,
...Dropdown.propTypes,
};
DropdownButton.defaultProps = {
disabled: false,
pullRight: false,
dropup: false,
navItem: false,
noCaret: false
};
export default DropdownButton;
|
examples/websdk-samples/LayerReactNativeSample/src/ui/announcements/MessageList.js
|
layerhq/layer-js-sampleapps
|
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
ListView,
TouchableOpacity
} from 'react-native';
import MessageListItem from './MessageListItem';
import Icon from 'react-native-vector-icons/FontAwesome';
export default class MessageList extends Component {
constructor(props) {
super(props);
const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.state = {
dataSource: ds.cloneWithRows(this.props.messages)
};
}
componentWillReceiveProps(nextProps) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(nextProps.messages),
})
}
render() {
const { onMarkMessageRead } = this.props;
return (
<View style={styles.container}>
<View style={styles.header}>
<Text style={styles.title}>Announcements</Text>
<TouchableOpacity
style={styles.closeButton}
onPress={this.props.onClose}
activeOpacity={.5}
>
<Icon style={styles.closeIcon} name='close' />
</TouchableOpacity>
</View>
<ListView
enableEmptySections={true}
dataSource={this.state.dataSource}
renderRow={(message) => {
return (
<MessageListItem
key={message.id}
message={message}
onMarkMessageRead={onMarkMessageRead}/>
);
}}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
margin: 20,
borderColor: '#777',
borderWidth: 2
},
header: {
flexDirection: 'row',
padding: 15,
alignItems: 'center',
backgroundColor: '#ebebeb'
},
title: {
flex: 1,
fontFamily: 'System',
fontSize: 14,
color: '#404F59',
textAlign: 'center',
marginLeft: 20
},
closeButton: {
width: 20,
alignItems: 'flex-end'
},
closeIcon: {
fontSize: 20
}
});
|
imports/ui/components/fields/Fields.js
|
hwillson/file-metadata-manager
|
import React from 'react';
import { _ } from 'meteor/underscore';
import { css, StyleSheet } from 'aphrodite';
import Loading from '../loading/Loading';
import Field from './Field';
import UtilityStyles from '../../styles/utility';
let styles;
const Fields = ({ fieldsReady, fields }) => {
let content;
if (!fieldsReady) {
content = <Loading />;
} else if (fieldsReady && _.isEmpty(fields)) {
content = (
<p className={css(UtilityStyles.marginTopBottom20)}>No fields found.</p>
);
} else {
content = (
<ul className={css(styles.ul)}>
{fields.map(field => <Field key={field._id} field={field} />)}
</ul>
);
}
return (
<div className="fields">
{content}
</div>
);
};
Fields.propTypes = {
fieldsReady: React.PropTypes.bool.isRequired,
fields: React.PropTypes.array.isRequired,
};
styles = StyleSheet.create({
ul: {
listStyle: 'none',
border: '1px solid #ddd',
padding: 0,
margin: '20px 0',
},
});
export default Fields;
|
app/javascript/mastodon/features/community_timeline/index.js
|
dwango/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandCommunityTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import ColumnSettingsContainer from './containers/column_settings_container';
import { connectCommunityStream } from '../../actions/streaming';
const messages = defineMessages({
title: { id: 'column.community', defaultMessage: 'Local timeline' },
});
const mapStateToProps = (state, { onlyMedia, columnId }) => {
const uuid = columnId;
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === uuid);
return {
hasUnread: state.getIn(['timelines', `community${onlyMedia ? ':media' : ''}`, 'unread']) > 0,
onlyMedia: (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'community', 'other', 'onlyMedia']),
};
};
export default @connect(mapStateToProps)
@injectIntl
class CommunityTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static defaultProps = {
onlyMedia: false,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
columnId: PropTypes.string,
intl: PropTypes.object.isRequired,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
onlyMedia: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch, onlyMedia } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('COMMUNITY', { other: { onlyMedia } }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, onlyMedia } = this.props;
dispatch(expandCommunityTimeline({ onlyMedia }));
this.disconnect = dispatch(connectCommunityStream({ onlyMedia }));
}
componentDidUpdate (prevProps) {
if (prevProps.onlyMedia !== this.props.onlyMedia) {
const { dispatch, onlyMedia } = this.props;
this.disconnect();
dispatch(expandCommunityTimeline({ onlyMedia }));
this.disconnect = dispatch(connectCommunityStream({ onlyMedia }));
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { dispatch, onlyMedia } = this.props;
dispatch(expandCommunityTimeline({ maxId, onlyMedia }));
}
render () {
const { intl, shouldUpdateScroll, hasUnread, columnId, multiColumn, onlyMedia } = this.props;
const pinned = !!columnId;
return (
<Column ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='users'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer columnId={columnId} />
</ColumnHeader>
<StatusListContainer
trackScroll={!pinned}
scrollKey={`community_timeline-${columnId}`}
timelineId={`community${onlyMedia ? ':media' : ''}`}
onLoadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.community' defaultMessage='The local timeline is empty. Write something publicly to get the ball rolling!' />}
shouldUpdateScroll={shouldUpdateScroll}
/>
</Column>
);
}
}
|
src/components/Countdown.js
|
greg5green/isrobhomeyet
|
import React from 'react';
import CountdownNumber from './CountdownNumber';
import {isHereNow, timeRemaining} from '../services/status';
class Countdown extends React.Component {
constructor(props) {
super(props);
this.state = { timeRemaining: timeRemaining() };
}
componentDidMount() {
this.updateInterval = setInterval(() => this.updateTimeRemaining(), 1000);
}
componentWillUnmount() {
clearInterval(this.updateInterval);
}
updateTimeRemaining() {
this.setState({ timeRemaining: timeRemaining() });
}
render() {
return (
<div>
<h3>Countdown to Rob</h3>
<CountdownNumber number={this.state.timeRemaining.weeks} />
<CountdownNumber number={this.state.timeRemaining.days} />
<CountdownNumber number={this.state.timeRemaining.hours} />
<CountdownNumber number={this.state.timeRemaining.minutes} />
<CountdownNumber number={this.state.timeRemaining.seconds} />
</div>
);
}
}
export default Countdown;
|
GankDemo/index.ios.js
|
MisterZhouZhou/ReactNativeLearing
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {AppRegistry,} from 'react-native';
import StartView from './jscore/StartView'
export default class GankDemo extends Component {
render() {
return (
<StartView />
);
}
}
AppRegistry.registerComponent('GankDemo', () => GankDemo);
|
src/components/modules/learn/life-cycle/humans/list.js
|
xavier-besson/react-playground
|
import React from 'react';
import LearnLifeCycleHumansItem from './item';
import Immutable from 'immutable';
/**
* @class LearnLifeCycleHumansList
* @extends React.Component
*/
class LearnLifeCycleHumansList extends React.Component {
/**
* Range of validators that can be used to make sure the data you receive is valid
* @type {Object}
*/
static propTypes = {
humans: React.PropTypes.instanceOf(Immutable.List),
addLog: React.PropTypes.func.isRequired,
killHuman: React.PropTypes.func.isRequired,
updateHumanProperties: React.PropTypes.func.isRequired,
}
/**
* Default values for props property
* @type {Object}
*/
static defaultProps = {
humans: Immutable.List(),
}
/**
* Sub rendering method called by the render method.
* Return a single React element.
* This element can be either a representation of a native DOM component,
* such as <div />, or another composite component that you've defined yourself.
* You can also return null or false to indicate that you don't want anything rendered.
* When returning null or false, ReactDOM.findDOMNode(this) will return null.
* @method renderHuman
* @param {Object} human Human properties
* @param {Number} index Index of the human
* @return {Mixed} A representation of a native DOM component
*/
renderHuman(human, index) {
return (
<LearnLifeCycleHumansItem
id={index}
name={human.get('name')}
superpowers={human.get('superpowers')}
key={index}
addLog={this.props.addLog}
killMe={() => {
this.props.killHuman(index);
}}
updateProperties={(key, value) => {
this.props.updateHumanProperties(index, properties);
}}
friendsNumber={this.props.humans.size - 1}
/>
);
}
/**
* React method.
* Return a single React element.
* This element can be either a representation of a native DOM component,
* such as <div />, or another composite component that you've defined yourself.
* You can also return null or false to indicate that you don't want anything rendered.
* When returning null or false, ReactDOM.findDOMNode(this) will return null.
* @method render
* @return {Mixed} A representation of a native DOM component
*/
render() {
return (
<div>
{this.props.humans.map(::this.renderHuman)}
</div>
);
}
}
export default LearnLifeCycleHumansList;
|
app/javascript/mastodon/features/standalone/community_timeline/index.js
|
unarist/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../../ui/containers/status_list_container';
import { expandCommunityTimeline } from '../../../actions/timelines';
import Column from '../../../components/column';
import ColumnHeader from '../../../components/column_header';
import { defineMessages, injectIntl } from 'react-intl';
import { connectCommunityStream } from '../../../actions/streaming';
const messages = defineMessages({
title: { id: 'standalone.public_title', defaultMessage: 'A look inside...' },
});
@connect()
@injectIntl
export default class CommunityTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
componentDidMount () {
const { dispatch } = this.props;
dispatch(expandCommunityTimeline());
this.disconnect = dispatch(connectCommunityStream());
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandCommunityTimeline({ maxId }));
}
render () {
const { intl } = this.props;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='users'
title={intl.formatMessage(messages.title)}
onClick={this.handleHeaderClick}
/>
<StatusListContainer
timelineId='community'
onLoadMore={this.handleLoadMore}
scrollKey='standalone_public_timeline'
trackScroll={false}
/>
</Column>
);
}
}
|
src/index.js
|
octoblu/store-octoblu
|
import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import { browserHistory } from 'react-router'
import { syncHistoryWithStore, routerReducer } from 'react-router-redux'
import { applyMiddleware, createStore, compose } from 'redux'
import thunkMiddleware from 'redux-thunk'
import createLogger from 'redux-logger'
import reducers from './reducers/'
import AppRoutes from './config/routes'
const createStoreWithMiddleware = applyMiddleware(thunkMiddleware, createLogger())
const store = createStore(reducers, createStoreWithMiddleware)
// Create an enhanced history that syncs navigation events with the store
const history = syncHistoryWithStore(browserHistory, store)
render(
<Provider store={store}>
<AppRoutes history={history} />
</Provider>,
document.getElementById('app')
)
|
app/javascript/spec/miq-alert-set-form/miq-alert-set-form.spec.js
|
ManageIQ/manageiq-ui-classic
|
import React from 'react';
import fetchMock from 'fetch-mock';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import MiqAlertSetForm from '../../components/miq-alert-set-form/index';
import '../helpers/miqFlashLater';
import '../helpers/sprintf';
import '../helpers/miqSparkle';
import '../helpers/addFlash';
describe('Alert Profile Form Component', () => {
let initialProps;
beforeEach(() => {
initialProps = {
mode: [['Host', 'Host']],
emsId: 'Host',
alertState: [
{ label: 'Host Datastore < 5% of Free Space', value: '1' },
{ label: 'Host Event Log Error - Failed to validate VM IP address', value: '2' },
{ label: 'Host Event Log Error - Memory Exceed Soft Limit ', value: '3' },
{ label: 'Host VMs >10', value: '10' }],
};
});
afterEach(() => {
fetchMock.reset();
fetchMock.restore();
});
it('should render correctly', (done) => {
const wrapper = shallow(<MiqAlertSetForm {...initialProps} />);
setImmediate(() => {
wrapper.update();
expect(toJson(wrapper)).toMatchSnapshot();
done();
});
});
});
|
src/parser/warrior/protection/CHANGELOG.js
|
FaideWW/WoWAnalyzer
|
// import React from 'react';
export default [
];
|
ui/src/components/AlbumList.js
|
damianmoore/photo-manager
|
import React from 'react'
import styled from '@emotion/styled'
import Thumbnails from './Thumbnails'
import useInfiniteScroll from './InfiniteScroll'
const Container = styled('div')`
height: 100%;
overflow-y: auto;
`
const AlbumList = ({
photoSections,
refetchPhotos,
refetchPhotoList,
refetchAlbumList,
mapPhotosRefetch,
mode,
}) => {
const [scrollerRef, handleScroll] = useInfiniteScroll(refetchPhotos)
const params = new URLSearchParams(window.location.search)
const albumName = params.get('album_name')
if (albumName) photoSections[0].title = albumName
return (
<Container ref={scrollerRef} onScroll={handleScroll}>
<Thumbnails
photoSections={photoSections}
refetchPhotoList={refetchPhotoList}
refetchAlbumList={refetchAlbumList}
mapPhotosRefetch={mapPhotosRefetch}
mode={mode}
rateable
/>
{/* TODO: Add the DateHistogram feature back here */}
</Container>
)
}
export default AlbumList
|
example/examples/PolygonCreator.js
|
jiaminglu/react-native-maps
|
import React from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
TouchableOpacity,
} from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 31.23295;
const LONGITUDE = 121.3822;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
let id = 0;
class PolygonCreator extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
polygons: [],
editing: null,
creatingHole: false,
};
}
finish() {
const { polygons, editing } = this.state;
this.setState({
polygons: [...polygons, editing],
editing: null,
creatingHole: false,
});
}
createHole() {
const { editing, creatingHole } = this.state;
if (!creatingHole) {
this.setState({
creatingHole: true,
editing: {
...editing,
holes: [
...editing.holes,
[],
],
},
});
} else {
const holes = [...editing.holes];
if (holes[holes.length - 1].length === 0) {
holes.pop();
this.setState({
editing: {
...editing,
holes,
},
});
}
this.setState({ creatingHole: false });
}
}
onPress(e) {
const { editing, creatingHole } = this.state;
if (!editing) {
this.setState({
editing: {
id: id++,
coordinates: [e.nativeEvent.coordinate],
holes: [],
},
});
} else if (!creatingHole) {
this.setState({
editing: {
...editing,
coordinates: [
...editing.coordinates,
e.nativeEvent.coordinate,
],
},
});
} else {
const holes = [...editing.holes];
holes[holes.length - 1] = [
...holes[holes.length - 1],
e.nativeEvent.coordinate,
];
this.setState({
editing: {
...editing,
id: id++, // keep incrementing id to trigger display refresh
coordinates: [
...editing.coordinates,
],
holes,
},
});
}
}
render() {
const mapOptions = {
scrollEnabled: true,
};
if (this.state.editing) {
mapOptions.scrollEnabled = false;
mapOptions.onPanDrag = e => this.onPress(e);
}
return (
<View style={styles.container}>
<MapView
provider={this.props.provider}
style={styles.map}
mapType={MapView.MAP_TYPES.HYBRID}
initialRegion={this.state.region}
onPress={e => this.onPress(e)}
{...mapOptions}
>
{this.state.polygons.map(polygon => (
<MapView.Polygon
key={polygon.id}
coordinates={polygon.coordinates}
holes={polygon.holes}
strokeColor="#F00"
fillColor="rgba(255,0,0,0.5)"
strokeWidth={1}
/>
))}
{this.state.editing && (
<MapView.Polygon
key={this.state.editing.id}
coordinates={this.state.editing.coordinates}
holes={this.state.editing.holes}
strokeColor="#000"
fillColor="rgba(255,0,0,0.5)"
strokeWidth={1}
/>
)}
</MapView>
<View style={styles.buttonContainer}>
{this.state.editing && (
<TouchableOpacity
onPress={() => this.createHole()}
style={[styles.bubble, styles.button]}
>
<Text>{this.state.creatingHole ? 'Finish Hole' : 'Create Hole'}</Text>
</TouchableOpacity>
)}
{this.state.editing && (
<TouchableOpacity
onPress={() => this.finish()}
style={[styles.bubble, styles.button]}
>
<Text>Finish</Text>
</TouchableOpacity>
)}
</View>
</View>
);
}
}
PolygonCreator.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
bubble: {
backgroundColor: 'rgba(255,255,255,0.7)',
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 20,
},
latlng: {
width: 200,
alignItems: 'stretch',
},
button: {
width: 80,
paddingHorizontal: 12,
alignItems: 'center',
marginHorizontal: 10,
},
buttonContainer: {
flexDirection: 'row',
marginVertical: 20,
backgroundColor: 'transparent',
},
});
module.exports = PolygonCreator;
|
src/components/WorkerListItem.js
|
Ricky-Nz/knocknock-web
|
import React from 'react';
import Relay from 'react-relay';
import { ListItem } from 'material-ui/List';
import Avatar from 'material-ui/Avatar';
import { UpdateWorkerMutation, DeleteWorkerMutation } from '../mutations';
const WorkerListItem = ({worker, onClick}) => (
<ListItem leftAvatar={<Avatar src={worker.avatarUrl}/>}
primaryText={`${worker.firstName||''} ${worker.lastName}||''`}
secondaryTextLines={2}
secondaryText={
<div>
<div>{`Email: ${worker.email||''}`}</div>
<div>{`Tel: ${worker.contact||''}`}</div>
</div>
} onTouchTap={() => onClick(worker)}/>
);
export default Relay.createContainer(WorkerListItem, {
fragments: {
worker: () => Relay.QL`
fragment on Worker {
email
contact
firstName
lastName
avatarUrl
${UpdateWorkerMutation.getFragment('worker')}
${DeleteWorkerMutation.getFragment('worker')}
}
`
}
});
|
node_modules/recharts/demo/component/Rectangle.js
|
SerendpityZOEY/Fixr-RelevantCodeSearch
|
import React, { Component } from 'react';
import { Surface, Rectangle } from 'recharts';
class RectangleDemo extends Component {
state = {
x: 50,
y: 50,
width: 80,
height: 100,
};
changeSize() {
this.setState({
x: Math.random() * 50,
y: Math.random() * 50,
width: Math.random() * 400,
height: Math.random() * 400,
});
}
render() {
const { width, height, x, y } = this.state;
return (
<div>
<a
href="javascript:void(0);"
className="btn"
onClick={::this.changeSize}
>
change size
</a>
<Surface width={500} height={500}>
<Rectangle
x={x}
y={y}
width={width}
height={height}
radius={[5, 10, 8, 15]}
stroke="#ff7300"
isAnimationActive
fill="none"
/>
</Surface>
</div>
);
}
}
export default RectangleDemo;
|
src/components/Posts.js
|
angeloocana/angeloocana
|
import React from 'react';
import PropTypes from 'prop-types';
import Link from './Link';
import PostList from './PostList';
import BtnLink from './BtnLink';
import H2 from './H2';
import { FormattedMessage } from 'react-intl';
const Posts = (props) => {
const btnMorePosts = props.showBtnMorePosts
? (
<FormattedMessage id="posts.seeMore">
{(txt) => (
<BtnLink to={`/${props.langKey}/blog/`}>
{txt}
</BtnLink>
)}
</FormattedMessage>
)
: null;
return (
<section className="post-list">
<header>
<Link to={`/${props.langKey}/blog/`}>
<FormattedMessage id={props.title || 'posts'}>
{(txt) => (
<H2>{txt}</H2>
)}
</FormattedMessage>
</Link>
</header>
<PostList {...props} />
{btnMorePosts}
</section>
);
};
Posts.propTypes = {
posts: PropTypes.array.isRequired,
langKey: PropTypes.string.isRequired,
showBtnMorePosts: PropTypes.bool,
title: PropTypes.string
};
export default Posts;
|
app/toolbars/TopBar.js
|
stanfordv/curriculum1
|
import React from 'react';
import AddNode from './AddNode';
import AddLink from './AddLink';
export default class extends React.Component {
render() {
return (
<div className="toolBar toolBar--top">
<div className="row">
<div className="col-xs-4">
<AddNode addNode={this.props.addNode} nodes={this.props.nodes} />
</div>
<div className="col-xs-8">
<AddLink addLink={this.props.addLink} nodes={this.props.nodes} />
</div>
</div>
</div>
);
}
};
|
app/containers/PomodoroPage.js
|
liveyourheart/woke-electron
|
import React, { Component } from 'react';
import Home from '../components/Home';
import NavBar from '../components/common/navbar';
import Timer from '../components/timer/timer'
export default class PomodoroPage extends Component {
render() {
return (
<div>
<Timer progress={90}/>
</div>
);
}
}
|
aiohttp_admin/static/react-admin/js/utils/fields.js
|
jettify/aiohttp_admin
|
import React from 'react';
import { ShowField } from '../components/Fields/ShowField';
export function getFields(fields) {
return Object.keys(fields).map(function(key, index) {
return (
<ShowField
key={index}
source={fields[key].name}
/>
);
});
}
|
actor-apps/app-web/src/app/components/common/Banner.react.js
|
VikingDen/actor-platform
|
import React from 'react';
import BannerActionCreators from 'actions/BannerActionCreators';
class Banner extends React.Component {
constructor(props) {
super(props);
if (window.localStorage.getItem('banner_jump') === null) {
BannerActionCreators.show();
}
}
onClose = () => {
BannerActionCreators.hide();
};
onJump = (os) => {
BannerActionCreators.jump(os);
this.onClose();
};
render() {
return (
<section className="banner">
<p>
Welcome to <b>Actor Network</b>! Check out our <a href="//actor.im/ios" onClick={this.onJump.bind(this, 'IOS')} target="_blank">iPhone</a> and <a href="//actor.im/android" onClick={this.onJump.bind(this, 'ANDROID')} target="_blank">Android</a> apps!
</p>
<a className="banner__hide" onClick={this.onClose}>
<i className="material-icons">close</i>
</a>
</section>
);
}
}
export default Banner;
|
src/js/react/container/Root.js
|
koluch/db-scheme
|
// @flow
import React from 'react'
import {connect} from 'react-redux'
import type {Dispatch} from 'redux'
import cn from 'bem-cn'
import type {TTableShape} from '~/types/TTableShape'
import type {TLinkShape} from '~/types/TLinkShape'
import type {TSchemeState, TTableState, TSelected, TDndTarget, TTco} from '~/types/TSchemeState'
import type {TState} from '~/types/TState'
import type {TAction, TStyleChange} from '~/types/TAction'
import type {TAttr} from '~/types/TAttr'
import type {TBounds} from '~/types/TBounds'
import type {TSize} from '~/types/TSize'
import type {TPoint} from '~/types/TPoint'
import type {TTable} from '~/types/TTable'
import type {TPath} from '~/types/TPath'
import type {TSchemeMetrics} from '~/types/TSchemeMetrics'
import type {THistoryStateRecord} from '~/types/THistoryState'
import type {TSchemeStyle} from '~/types/styles/TSchemeStyle'
import * as tableMetricsHelper from '~/metrics/table'
import * as metricsSelectors from '~/react/selectors/metrics'
import {isAttrProperForeignKeyTarget} from '~/react/helpers/tco'
import Scheme from '~/react/presentational/svg/Scheme'
import Controls from '~/react/presentational/Controls'
import AttrPropsModal from '~/react/presentational/modals/AttrPropsModal'
import TablePropsModal from '~/react/presentational/modals/TablePropsModal'
import JsonExportModal from '~/react/presentational/modals/JsonExportModal'
import JsonImportModal from '~/react/presentational/modals/JsonImportModal'
import ToolPanel from '~/react/presentational/tools/ToolPanel'
import ToolPanelGroup from '~/react/presentational/tools/ToolPanelGroup'
import Scroll from '~/react/presentational/Scroll'
import History from '~/react/presentational/History'
import Button from '~/react/presentational/Button'
import NumberInput from '~/react/presentational/inputs/NumberInput'
import TextInput from '~/react/presentational/inputs/TextInput'
import ColorInput from '~/react/presentational/inputs/ColorInput'
import SelectInput from '~/react/presentational/inputs/SelectInput'
import FieldSet, {Field} from '~/react/presentational/tools/FieldSet'
const calcConnections = (p1: TPoint, p2: TPoint, direct: boolean): Array<TPath> => {
if (direct) {
return [
[p1, {x: p1.x, y: p2.y}, p2],
[p1, {x: p2.x, y: p1.y}, p2],
]
}
else {
return [[
p1,
{x: p1.x + (p2.x - p1.x) / 2, y: p1.y},
{x: p1.x + (p2.x - p1.x) / 2, y: p2.y},
p2,
]]
}
}
const isPointInBounds = (p: TPoint, b: TBounds): boolean => {
return p.x > b.x
&& p.x < b.x + b.width
&& p.y > b.y
&& p.y < b.y + b.height
}
const isPathCrossBound = (path: TPath, b: TBounds): boolean => {
for (let i = 0; i < path.length - 1; ++i) {
const p1 = path[i]
const p2 = path[i + 1]
if (isPointInBounds(p1, b)) {
return true
}
if (isPointInBounds(p2, b)) {
return true
}
if (p1.y >= b.y && p1.y <= b.y + b.height
&& p2.y >= b.y && p2.y <= b.y + b.height) {
if (p1.x < b.x && p2.x > b.x + b.width) {
return true
}
}
if (p1.x >= b.x && p1.x <= b.x + b.width
&& p2.x >= b.x && p2.x <= b.x + b.width) {
if (p1.y < b.y && p2.y > b.y + b.height) {
return true
}
}
}
return false
}
const calcPathLength = (path: TPath): number => {
let len = 0
for (let i = 0; i < path.length - 1; ++i) {
const p1 = path[i]
const p2 = path[i + 1]
if (p1.x === p2.x) {
len += p1.y > p2.y ? p1.y - p2.y : p2.y - p1.y
}
else {
len += p1.x > p2.x ? p1.x - p2.x : p2.x - p1.x
}
}
return len
}
const calculatePath = (b1: TBounds, b2: TBounds): Array<TPoint> => {
if (b1.x === b2.x && b1.y === b2.y && b1.width === b2.width && b1.height === b2.height) {
return []
}
// Link connection should be placed in some distance from attribute bounds
const MARGIN = 15
// Build attribute bounds, considering margins
const b1m = {x: b1.x - MARGIN, y: b1.y, width: b1.width + (MARGIN * 2), height: b1.height}
const b2m = {x: b2.x - MARGIN, y: b2.y, width: b2.width + (MARGIN * 2), height: b2.height}
// Build left/right connection points, considering or not margins
const b1left = {x: b1.x, y: b1.y + b1.height / 2}
const b1right = {x: b1.x + b1.width, y: b1.y + b1.height / 2}
const b2left = {x: b2.x, y: b2.y + b2.height / 2}
const b2right = {x: b2.x + b2.width, y: b2.y + b2.height / 2}
const b1leftm = {x: b1m.x, y: b1m.y + b1m.height / 2}
const b1rightm = {x: b1m.x + b1m.width, y: b1m.y + b1m.height / 2}
const b2leftm = {x: b2m.x, y: b2m.y + b2m.height / 2}
const b2rightm = {x: b2m.x + b2m.width, y: b2m.y + b2m.height / 2}
// Calculate pathes, adding to each finishing points
const pathes: Array<TPath> = [
...(calcConnections(b1leftm, b2rightm, false).map((path: TPath) => [b1left, ...path, b2right])),
...(calcConnections(b1rightm, b2leftm, false).map((path: TPath) => [b1right, ...path, b2left])),
...(calcConnections(b1leftm, b2leftm, true).map((path: TPath) => [b1left, ...path, b2left])),
...(calcConnections(b1rightm, b2rightm, true).map((path: TPath) => [b1right, ...path, b2right])),
]
// Take only pathes which are not cross extended bounds
let filteredPathes = pathes
.filter((path) => (
// check if path is crossing some bound (cutting first and last point, becouse they do cross bounds)
!isPathCrossBound(path.slice(1, path.length - 1), b1m)
&& !isPathCrossBound(path.slice(1, path.length - 1), b2m)
))
// Sometimes, there are not appropriate pathes (bounds can overlap, for example)
if (filteredPathes.length === 0) {
filteredPathes = pathes
}
const bestPath: TPath = filteredPathes
// Calculate length for each path
.map((path) => ({path, length: calcPathLength(path)}))
// Take shorted path
.reduce((minPath, nextPath) => nextPath.length < minPath.length ? nextPath : minPath).path
return bestPath
}
const mapStateToProps = (state: TState): * => {
const {scheme: schemeState, history} = state
const {tables, dnd, tco, mousePosition, size, style} = schemeState
const metrics = metricsSelectors.scheme(schemeState)
let newLink = null
if (tco !== false) {
if (tco.type === 'ADD_LINK') {
const {table, attr} = tco
const tableShapeFrom = tables.filter((x) => x.table.name === table)[0]
if (!tableShapeFrom) {
throw new Error(`Table "${table}" doesn't exists, unable to draw link`)
}
const attrFrom = tableShapeFrom.table.attrs.filter((x) => x.name === attr)[0]
if (!attrFrom) {
throw new Error(`Attribute "${table}.${attr}" doesn't exists, unable to draw link`)
}
const tableShapeFromMetrics = metrics.tables.filter(({name}) => name === tableShapeFrom.table.name)[0].metrics //todo: check
const attrFromBounds = tableMetricsHelper.getAttrBounds(tableShapeFromMetrics, tableShapeFrom.position, attrFrom.name)
if (!attrFromBounds) {
throw new Error(`Unable to get attribue bounds for
attribute "${table}.${attr}": attribute doesnt exists`)
}
const attrToBounds = {...mousePosition, width: 0, height: 0}
newLink = calculatePath(attrFromBounds, attrToBounds)
}
}
const linkShapes = schemeState.tables.map(({table}) => (
table.foreignKeys.map(({from, to}) => ({
from: {
...from,
table: table.name,
},
to,
})).map((link) => {
const {from, to} = link
const tableShapeFrom = tables.filter((x) => x.table.name === from.table)[0]
if (!tableShapeFrom) {
throw new Error(`Table "${from.table}" doesn't exists, unable to draw link`)
}
const tableShapeTo = tables.filter((x) => x.table.name === to.table)[0]
if (!tableShapeTo) {
throw new Error(`Table "${to.table}" doesn't exists, unable to draw link`)
}
const attrFrom = tableShapeFrom.table.attrs.filter((x) => x.name === from.attr)[0]
if (!attrFrom) {
throw new Error(`Attribute "${from.table}.${from.attr}" doesn't exists, unable to draw link`)
}
const attrTo = tableShapeTo.table.attrs.filter((x) => x.name === to.attr)[0]
if (!attrTo) {
throw new Error(`Attribute "${to.table}.${to.attr}" doesn't exists, unable to draw link`)
}
const tableShapeFromMetrics = metrics.tables.filter(({name}) => name === tableShapeFrom.table.name)[0].metrics //todo: check
const tableShapeToMetrics = metrics.tables.filter(({name}) => name === tableShapeTo.table.name)[0].metrics //todo: check
const tableShapeFromPosition = {x: tableShapeFrom.position.x, y: tableShapeFrom.position.y}
const tableShapeToPosition = {x: tableShapeTo.position.x, y: tableShapeTo.position.y}
const attrFromBounds = tableMetricsHelper.getAttrBounds(tableShapeFromMetrics, tableShapeFromPosition, attrFrom.name)
if (!attrFromBounds) {
throw new Error(`Unable to get attribue bounds for
attribute "${from.table}.${from.attr}": attribute doesnt exists`)
}
const attrToBounds = tableMetricsHelper.getAttrBounds(tableShapeToMetrics, tableShapeToPosition, attrTo.name)
if (!attrToBounds) {
throw new Error(`Unable to get attribue bounds for
attribute "${to.table}.${to.attr}": attribute doesnt exists`)
}
const path = calculatePath(attrFromBounds, attrToBounds)
return {
link,
path,
}
})
)).reduce((acc, links) => acc.concat(links), [])
return {
fullSchemeState: schemeState,
metrics,
selected: schemeState.selected,
tables: schemeState.tables.map((tableState: TTableState): TTableShape => tableState),
newLink,
links: linkShapes,
historyRecords: history.records,
historyActiveRecord: history.active,
dnd,
tco,
size,
style,
}
}
const mapDispatchToProps = (dispatch: Dispatch<TAction>): * => {
return {
dispatch,
onTableClick: (tableShape: TTableShape) => {
dispatch({
type: 'SELECT',
target: 'TABLE',
table: tableShape.table.name,
})
},
onTableMouseDown: (tableShape: TTableShape, point: TPoint) => {
dispatch({
type: 'START_DND',
attrs: {
type: 'TABLE',
table: tableShape.table.name,
},
startPoint: point,
})
},
onMouseUp: (point: TPoint) => {
dispatch({
type: 'STOP_DND',
point,
})
},
onAttrMouseDown: (tableShape: TTableShape, attr: TAttr, point: TPoint) => {
dispatch({
type: 'START_DND',
attrs: {
type: 'ATTR',
attr: attr.name,
table: tableShape.table.name,
},
startPoint: point,
})
},
onLinkAddClick: (tableShape: TTableShape, attr: TAttr) => {
dispatch({
type: 'START_TCO',
attrs: {
type: 'ADD_LINK',
attr: attr.name,
table: tableShape.table.name,
},
})
},
onLinkDeleteClick: (tableShape: TTableShape, attr: TAttr) => {
dispatch({
type: 'DELETE_LINK',
attr: attr.name,
table: tableShape.table.name,
})
},
onAttrDeleteClick: (tableShape: TTableShape, attr: TAttr) => {
dispatch({
type: 'DELETE_ATTR',
attr: attr.name,
table: tableShape.table.name,
})
},
onTableDeleteClick: (tableShape: TTableShape) => {
dispatch({
type: 'DELETE_TABLE',
table: tableShape.table.name,
})
},
onImportSchemeState: (schemeState: TSchemeState) => {
dispatch({
type: 'IMPORT_SCHEME_STATE',
schemeState,
})
},
onChangeSchemeSize: (size: TSize) => {
dispatch({
type: 'CHANGE_SCHEME_SIZE',
size,
})
},
changeStyle: (change: TStyleChange) => {
dispatch({
type: 'CHANGE_STYLE',
change,
})
},
}
}
const mergeProps = (stateProps, dispatchProps): * => {
const {tco, dnd, tables, metrics} = stateProps
const {dispatch} = dispatchProps
return {
...stateProps,
...dispatchProps,
onSchemeClick: () => {
if (tco !== false) {
dispatch({
type: 'STOP_TCO',
})
}
else {
dispatch({
type: 'CANCEL_SELECT',
})
}
},
onMouseMove: (point: TPoint) => {
dispatch({
type: 'MOUSE_MOVE',
point,
})
if (dnd !== false) {
if (dnd.type === 'TABLE') {
const {lastPoint, table} = dnd
const tableState = tables.filter((tableState) => tableState.table.name === table)[0]
if (tableState) {
const dif = {
x: point.x - lastPoint.x,
y: point.y - lastPoint.y,
}
dispatch({
type: 'MOVE_TABLE',
table,
position: {
x: tableState.position.x + dif.x,
y: tableState.position.y + dif.y,
},
})
}
}
else if (dnd.type === 'ATTR') {
const {attr, table} = dnd
const tableShape = tables.filter((tableShape) => tableShape.table.name === table)[0] //todo: check
const tableMetrics = metrics.tables.filter(({name}) => name === table)[0].metrics //todo: check
const hoveredAttr = tableShape.table.attrs.filter(({name}) => {
const attrBounds = tableMetricsHelper.getAttrBounds(tableMetrics, tableShape.position, name)
if (attrBounds) {
return point.y > attrBounds.y
&& point.y < attrBounds.y + attrBounds.height
&& point.x > attrBounds.x
&& point.x < attrBounds.x + attrBounds.width
}
return false
})[0]
if (hoveredAttr && hoveredAttr.name !== attr) {
dispatch({
type: 'SWITCH_ATTRS',
table,
attr1: attr,
attr2: hoveredAttr.name,
})
}
}
dispatch({
type: 'UPDATE_DND',
lastPoint: point,
})
}
},
onAttrClick: (tableShape: TTableShape, attr: TAttr) => {
if (tco !== false) {
if (tco.type === 'ADD_LINK') {
const tableFrom = tables.filter((tableShape) => tableShape.table.name === tco.table)[0].table //todo: check
const attrFrom = tableFrom.attrs.filter(({name}) => name === tco.attr)[0]
if (isAttrProperForeignKeyTarget(tableFrom, attrFrom, tableShape.table, attr)) {
dispatch({type: 'STOP_TCO'})
dispatch({
type: 'ADD_LINK',
from: {
table: tco.table,
attr: tco.attr,
},
to: {
table: tableShape.table.name,
attr: attr.name,
},
})
}
}
}
else {
dispatch({
type: 'SELECT',
target: 'ATTR',
table: tableShape.table.name,
attr: attr.name,
})
}
},
onAttrCreate: (table: string, attr: TAttr) => {
dispatch({
type: 'ADD_ATTR',
table,
attr,
})
},
onTableCreate: (table: TTable) => {
dispatch({
type: 'ADD_TABLE',
table,
})
},
onTableEdit: (oldTable: TTable, newTable: TTable) => {
dispatch({
type: 'UPDATE_TABLE',
oldTable,
newTable,
})
},
onAttrEdit: (table: string, oldAttr: TAttr, newAttr: TAttr) => {
dispatch({
type: 'UPDATE_ATTR',
table,
oldAttr,
newAttr,
})
},
onHistoryRecordActivate: (record: THistoryStateRecord) => {
dispatch({
type: 'ACTIVATE_HISTORY_RECORD',
record: record.id,
})
},
}
}
type TProps = {
fullSchemeState: TSchemeState,
tables: Array<TTableShape>,
links: Array<TLinkShape>,
newLink: ?TPath,
metrics: TSchemeMetrics,
selected: TSelected,
dnd: TDndTarget,
tco: TTco,
historyRecords: Array<THistoryStateRecord>,
historyActiveRecord: number,
style: TSchemeStyle,
onTableClick: (tableShape: TTableShape) => void,
onTableDeleteClick: (tableShape: TTableShape) => void,
onSchemeClick: () => void,
onTableMouseDown: (tableShape: TTableShape, point: TPoint) => void,
onAttrClick: (tableShape: TTableShape, attr: TAttr) => void,
onLinkAddClick: (tableShape: TTableShape, attr: TAttr) => void,
onLinkDeleteClick: (tableShape: TTableShape, attr: TAttr) => void,
onAttrDeleteClick: (tableShape: TTableShape, attr: TAttr) => void,
onAttrMouseDown: (tableShape: TTableShape, attr: TAttr, point: TPoint) => void,
onAttrCreate: (table: string, attr: TAttr) => void,
onAttrEdit: (table: string, oldAttr: TAttr, newAttr: TAttr) => void,
onTableCreate: (table: TTable) => void,
onTableEdit: (oldTable: TTable, newTable: TTable) => void,
onMouseMove: (point: TPoint) => void,
onMouseUp: (point: TPoint) => void,
onHistoryRecordActivate: (record: THistoryStateRecord) => void,
onImportSchemeState: (schemeState: TSchemeState) => void,
onChangeSchemeSize: (size: TSize) => void,
changeStyle: (action: TStyleChange) => void,
size: TSize,
}
type TRootState = {
attrCreateModal: false | {table: string},
attrEditModal: false | {table: string, attr: TAttr},
tableCreateModal: boolean,
tableEditModal: false | {table: TTable},
jsonExportModal: false | {json: string},
jsonImportModal: boolean,
}
export default connect(mapStateToProps, mapDispatchToProps, mergeProps)(class extends React.Component {
props: TProps
state: TRootState = {
attrCreateModal: false,
tableCreateModal: false,
tableEditModal: false,
jsonExportModal: false,
jsonImportModal: false,
attrEditModal: false,
}
absoluteContainerEl: *
handleAttrCreateClick = (tableShape: TTableShape) => {
this.setState({
attrCreateModal: {
table: tableShape.table.name,
},
})
}
handleAttrCreate = (table: string, attr: TAttr) => {
this.setState({
attrCreateModal: false,
}, () => {
this.props.onAttrCreate(table, attr)
})
}
handleAttrCreateCancel = () => {
this.setState({
attrCreateModal: false,
})
}
handleAttrEditClick = (tableShape: TTableShape, attr: TAttr) => {
this.setState({
attrEditModal: {
table: tableShape.table.name,
attr,
},
})
}
handleAttrEdit = (table: string, newAttr: TAttr) => {
if (this.state.attrEditModal !== false) {
const {table, attr: oldAttr} = this.state.attrEditModal
this.setState({
attrEditModal: false,
}, () => {
this.props.onAttrEdit(table, oldAttr, newAttr)
})
}
}
handleAttrEditCancel = () => {
this.setState({
attrEditModal: false,
})
}
handleTableCreateClick = () => {
this.setState({
tableCreateModal: true,
})
}
handleTableCreate = (table: TTable) => {
this.setState({
tableCreateModal: false,
}, () => {
this.props.onTableCreate(table)
})
}
handleTableEditClick = (tableShape: TTableShape) => {
this.setState({
tableEditModal: {table: tableShape.table},
})
}
handleTableEdit = (newTable: TTable) => {
if (this.state.tableEditModal !== false) {
const {table: oldTable} = this.state.tableEditModal
this.setState({
tableEditModal: false,
}, () => {
this.props.onTableEdit(oldTable, newTable)
})
}
}
handleTableEditCancel = () => {
this.setState({
tableEditModal: false,
})
}
handleTableCreateCancel = () => {
this.setState({
tableCreateModal: false,
})
}
handleExportToPngButton = () => {
const download = (filename: string, dataUrl: string) => {
const elem = window.document.createElement('a')
elem.href = dataUrl
elem.download = filename
document.body.appendChild(elem)
elem.click()
document.body.removeChild(elem)
}
const canvas = document.createElement('canvas')
canvas.setAttribute('width', `${this.props.size.width}`)
canvas.setAttribute('height', `${this.props.size.height}`)
const ctx = canvas.getContext('2d')
if (ctx) {
const img = new Image()
img.onload = () => {
ctx.drawImage(img, 0, 0)
const dataUrl = canvas.toDataURL('image/png')
download('scheme.png', dataUrl)
}
const svgNode = document.querySelector('#for_export svg')
if (svgNode) {
const body = new XMLSerializer().serializeToString(svgNode)
const encoded = window.btoa(body)
img.src = 'data:image/svg+xml;base64,' + encoded
}
}
}
handleExportToJsonButton = () => {
const {fullSchemeState} = this.props
const data = {
version: null,
scheme: fullSchemeState,
}
this.setState({
jsonExportModal: {json: JSON.stringify(data)},
})
}
handleImportFromJsonButton = () => {
this.setState({
jsonImportModal: true,
})
}
handleImportJson = (schemeState: TSchemeState) => {
this.setState({
jsonImportModal: false,
})
this.props.onImportSchemeState(schemeState)
}
renderSettingsStyle() {
const {style} = this.props
const {changeStyle} = this.props
return (
<ToolPanelGroup>
<ToolPanel title="Tables" opened={false}>
<ToolPanelGroup>
<ToolPanel title="Attributes" opened={false}>
<ToolPanelGroup>
<ToolPanel title="Font" opened={false}>
<FieldSet>
<Field title="Color"><ColorInput size="10" value={style.table.attrs.font.color} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_FONT_COLOR', value}) }}/></Field>
<Field title="Size"><NumberInput size="10" value={style.table.attrs.font.size} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_FONT_SIZE', value}) }}/></Field>
<Field title="Style"><SelectInput value={style.table.attrs.font.style} options={{'normal': 'Normal', 'italic': 'Italic'}} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_FONT_STYLE', value}) }}/></Field>
<Field title="Weight"><SelectInput value={style.table.attrs.font.weight} options={{'normal': 'Normal', 'bold': 'Bold'}} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_FONT_WEIGHT', value}) }}/></Field>
<Field title="Family"><SelectInput value={style.table.attrs.font.family} options={{'serif': 'Serif', 'sans-serif': 'Sans-serif', 'monospace': 'Monospace'}} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_FONT_FAMILY', value}) }}/></Field>
</FieldSet>
</ToolPanel>
<ToolPanel title="Paddings" opened={false}>
<FieldSet>
<Field title="Top"><NumberInput size="10" value={style.table.attrs.padding.top} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_PADDING_TOP', value}) }}/></Field>
<Field title="Right"><NumberInput size="10" value={style.table.attrs.padding.right} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_PADDING_RIGHT', value}) }}/></Field>
<Field title="Bottom"><NumberInput size="10" value={style.table.attrs.padding.bottom} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_PADDING_BOTTOM', value}) }}/></Field>
<Field title="Left"><NumberInput size="10" value={style.table.attrs.padding.left} onChange={(value) => { changeStyle({field: 'TABLE_ATTRS_PADDING_LEFT', value}) }}/></Field>
</FieldSet>
</ToolPanel>
</ToolPanelGroup>
</ToolPanel>
<ToolPanel title="Header" opened={false}>
<FieldSet>
<Field title="Background color"><ColorInput value={style.table.header.backgroundColor} size="10" onChange={(value) => { changeStyle({field: 'TABLE_HEADER_BACKGROUND_COLOR', value}) }}/></Field>
</FieldSet>
<ToolPanelGroup>
<ToolPanel title="Font" opened={false}>
<FieldSet>
<Field title="Color"><ColorInput size="10" value={style.table.header.font.color} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_FONT_COLOR', value}) }}/></Field>
<Field title="Size"><NumberInput size="10" value={style.table.header.font.size} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_FONT_SIZE', value}) }}/></Field>
<Field title="Style"><SelectInput value={style.table.header.font.style} options={{'normal': 'Normal', 'italic': 'Italic'}} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_FONT_STYLE', value}) }}/></Field>
<Field title="Weight"><SelectInput value={style.table.header.font.weight} options={{'normal': 'Normal', 'bold': 'Bold'}} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_FONT_WEIGHT', value}) }}/></Field>
<Field title="Family"><SelectInput value={style.table.header.font.family} options={{'serif': 'Serif', 'sans-serif': 'Sans-serif', 'monospace': 'Monospace'}} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_FONT_FAMILY', value}) }}/></Field>
</FieldSet>
</ToolPanel>
<ToolPanel title="Paddings" opened={false}>
<FieldSet>
<Field title="Top"><NumberInput size="10" value={style.table.header.padding.top} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_PADDING_TOP', value}) }}/></Field>
<Field title="Right"><NumberInput size="10" value={style.table.header.padding.right} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_PADDING_RIGHT', value}) }}/></Field>
<Field title="Bottom"><NumberInput size="10" value={style.table.header.padding.bottom} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_PADDING_BOTTOM', value}) }}/></Field>
<Field title="Left"><NumberInput size="10" value={style.table.header.padding.left} onChange={(value) => { changeStyle({field: 'TABLE_HEADER_PADDING_LEFT', value}) }}/></Field>
</FieldSet>
</ToolPanel>
</ToolPanelGroup>
</ToolPanel>
<ToolPanel title="Border" opened={false}>
<FieldSet>
<Field title="Color"><ColorInput value={style.table.border.color} onChange={(value) => { changeStyle({field: 'TABLE_BORDER_COLOR', value}) }}/></Field>
</FieldSet>
</ToolPanel>
</ToolPanelGroup>
</ToolPanel>
<ToolPanel title="Links" opened={false}>
<FieldSet>
<Field title="Stroke style:"><input size="10"/></Field>
</FieldSet>
</ToolPanel>
</ToolPanelGroup>
)
}
renderSettingsPanel() {
return (
<ToolPanel title={'Settings'} opened={false}>
<Scroll>
<div style={{padding: '10px'}}>
<FieldSet fields={[
[
'Size',
<div>
<NumberInput
size="5"
value={this.props.size.width}
onChange={(value) => { this.props.onChangeSchemeSize({...this.props.size, width: value}) }}
/>
{' x '}
<NumberInput
size="5"
value={this.props.size.height}
onChange={(value) => { this.props.onChangeSchemeSize({...this.props.size, height: value}) }}
/>
</div>,
],
]}/>
<FieldSet>
<Field title="Size">
<NumberInput
size="5"
value={this.props.size.width}
onChange={(value) => { this.props.onChangeSchemeSize({...this.props.size, width: value}) }}
/>
{' x '}
<NumberInput
size="5"
value={this.props.size.height}
onChange={(value) => { this.props.onChangeSchemeSize({...this.props.size, height: value}) }}
/>
</Field>
</FieldSet>
{this.renderSettingsStyle()}
</div>
</Scroll>
</ToolPanel>
)
}
render(): * {
const bem = cn('root')
const {width, height} = this.props.size
return (
<div className={bem()}>
<div style={{display: 'none'}} id="for_export">
<Scheme
style={this.props.style}
size={{width, height}}
tables={this.props.tables}
links={this.props.links}
selected={false}
metrics={this.props.metrics}
onClick={() => {}}
onMouseMove={() => {}}
onAttrClick={() => {}}
onAttrMouseDown={() => {}}
onTableClick={() => {}}
onTableMouseDown={() => {}}
onMouseUp={() => {}}
newLink={null}
/>
</div>
<div className={bem('scheme-container')}>
<div className={bem('scheme-container-absolute')} ref={(el) => { this.absoluteContainerEl = el }}>
<Controls
isDnd={this.props.dnd !== false}
tco={this.props.tco}
size={{width, height}}
selected={this.props.selected}
metrics={this.props.metrics}
tables={this.props.tables}
onMouseMove={this.props.onMouseMove}
onAttrClick={this.props.onAttrClick}
onLinkAddClick={this.props.onLinkAddClick}
onLinkDeleteClick={this.props.onLinkDeleteClick}
onAttrDeleteClick={this.props.onAttrDeleteClick}
onAttrEditClick={this.handleAttrEditClick}
onTableDeleteClick={this.props.onTableDeleteClick}
onTableEditClick={this.handleTableEditClick}
onTableCreateClick={this.handleTableCreateClick}
onMouseUp={this.props.onMouseUp}
onAttrCreateClick={this.handleAttrCreateClick}
/>
<Scheme
style={this.props.style}
size={{width, height}}
tables={this.props.tables}
links={this.props.links}
selected={this.props.selected}
metrics={this.props.metrics}
onClick={this.props.onSchemeClick}
onMouseMove={this.props.onMouseMove}
onAttrClick={this.props.onAttrClick}
onAttrMouseDown={this.props.onAttrMouseDown}
onTableClick={this.props.onTableClick}
onTableMouseDown={this.props.onTableMouseDown}
onMouseUp={this.props.onMouseUp}
newLink={this.props.newLink}
/>
</div>
</div>
<div className={bem('tools')}>
<ToolPanelGroup mode="SINGLE">
<ToolPanel title="Export / Import" opened={false}>
<p><b>{'Export'}</b></p>
<div style={{display: 'flex'}}>
<Button onClick={this.handleExportToPngButton}>{'PNG'}</Button>
<Button onClick={this.handleExportToJsonButton}>{'JSON'}</Button>
</div>
<br/>
<p><b>{'Import'}</b></p>
<div style={{display: 'flex'}}>
<Button onClick={this.handleImportFromJsonButton}>{'JSON'}</Button>
</div>
</ToolPanel>
{this.renderSettingsPanel()}
<ToolPanel title="History">
<Scroll>
<History
records={this.props.historyRecords}
active={this.props.historyActiveRecord}
onRecordClick={this.props.onHistoryRecordActivate}
/>
</Scroll>
</ToolPanel>
</ToolPanelGroup>
</div>
{this.state.attrCreateModal !== false && <AttrPropsModal
table={this.state.attrCreateModal.table}
onSave={this.handleAttrCreate}
onCancel={this.handleAttrCreateCancel}
/>}
{this.state.attrEditModal !== false && <AttrPropsModal
edit
table={this.state.attrEditModal.table}
name={this.state.attrEditModal.attr.name}
onSave={this.handleAttrEdit}
onCancel={this.handleAttrEditCancel}
/>}
{this.state.tableCreateModal !== false && <TablePropsModal
onSave={this.handleTableCreate}
onCancel={this.handleTableCreateCancel}
/>}
{this.state.tableEditModal !== false && <TablePropsModal
edit
name={this.state.tableEditModal.table.name}
onSave={this.handleTableEdit}
onCancel={this.handleTableEditCancel}
/>}
{this.state.jsonExportModal !== false && <JsonExportModal
json={this.state.jsonExportModal.json}
onCancel={() => this.setState({jsonExportModal: false})}
/>}
{this.state.jsonImportModal !== false && <JsonImportModal
onSave={this.handleImportJson}
onCancel={() => this.setState({jsonImportModal: false})}
/>}
{this.state.jsonExportModal !== false && <JsonExportModal
json={this.state.jsonExportModal.json}
onCancel={() => this.setState({jsonExportModal: false})}
/>}
{this.state.jsonImportModal !== false && <JsonImportModal
onSave={this.handleImportJson}
onCancel={() => this.setState({jsonImportModal: false})}
/>}
</div>
)
}
})
|
js/components/Sidebar.js
|
magalhini/firstaidgit
|
/*jshint esnext:true */
import React from 'react';
import SVGIcon from './../utils/SVG';
let Sidebar = React.createClass({
render() {
return (
<div className="sidebar-wrapper">
<a className="nb" href="https://github.com/magalhini/firstaidgit">
<SVGIcon class="icon-github" icon="githubFull"/>
</a>
<h2 className="sidebar--title">Sources</h2>
<p>Answers for these questions were collected from personal experience,
Stackoverflow, and the official Git documentation.
</p>
<h2 className="sidebar--title">Contributing</h2>
<p>Searching for an issue that is not listed here or found an answer that can be improved?
Great! You can submit a pull request on the project's <a href="https://github.com/magalhini/firstaidgit">Github</a> page.</p>
<p>Questions? <a href="http://twitter.com/magalhini">Tweet me.</a></p>
</div>
);
}
});
export default Sidebar;
|
docs/app/Examples/modules/Progress/States/ProgressExampleSuccess.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Progress } from 'semantic-ui-react'
const ProgressExampleSuccess = () => (
<Progress percent={100} success>
The progress was successful
</Progress>
)
export default ProgressExampleSuccess
|
node_modules/react-bootstrap/ie8/server.js
|
gitoneman/react-home
|
import React from 'react';
import express from 'express';
import path from 'path';
import webpack from 'webpack';
import webpackMiddleware from 'webpack-dev-middleware';
import webpackConfigBuilder from '../webpack/webpack.config';
const development = process.env.NODE_ENV !== 'production';
let app = express();
if (development) {
let webpackConfig = webpackConfigBuilder({
development: development,
ie8: true
});
let publicPath = webpackConfig.output.publicPath;
webpackConfig.output.path = '/';
webpackConfig.output.publicPath = undefined;
console.log('webpackConfig');
console.log(webpackConfig);
app = app
.use(webpackMiddleware(webpack(webpackConfig), {
noInfo: false,
publicPath: publicPath,
stats: {
colors: true
}
}))
.use(express.static(path.join(__dirname)));
} else {
app = app
.use(express.static(path.join(__dirname, '../ie8-built')));
}
app
.listen(4000, function () {
console.log('Server started at http://localhost:4000');
});
|
docs/app/Examples/collections/Menu/Types/MenuExampleAttached.js
|
clemensw/stardust
|
import React from 'react'
import { Dropdown, Icon, Menu, Segment } from 'semantic-ui-react'
// TODO: Update <Search> usage after its will be implemented
const MenuExampleAttached = () => {
return (
<div>
<Menu attached='top'>
<Dropdown as={Menu.Item} icon='wrench' simple>
<Dropdown.Menu>
<Dropdown.Item>
<Icon name='dropdown' />
<span className='text'>New</span>
<Dropdown.Menu>
<Dropdown.Item>Document</Dropdown.Item>
<Dropdown.Item>Image</Dropdown.Item>
</Dropdown.Menu>
</Dropdown.Item>
<Dropdown.Item>Open</Dropdown.Item>
<Dropdown.Item>Save...</Dropdown.Item>
<Dropdown.Item>Edit Permissions</Dropdown.Item>
<Dropdown.Divider />
<Dropdown.Header>Export</Dropdown.Header>
<Dropdown.Item>Share</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Menu.Menu position='right'>
<div className='ui right aligned category search item'>
<div className='ui transparent icon input'>
<input className='prompt' type='text' placeholder='Search animals...' />
<i className='search link icon' />
</div>
<div className='results'></div>
</div>
</Menu.Menu>
</Menu>
<Segment attached='bottom'>
<img src='http://semantic-ui.com/images/wireframe/paragraph.png' />
</Segment>
</div>
)
}
export default MenuExampleAttached
|
actor-apps/app-web/src/app/components/common/Banner.react.js
|
hzy87email/actor-platform
|
import React from 'react';
import BannerActionCreators from 'actions/BannerActionCreators';
class Banner extends React.Component {
constructor(props) {
super(props);
if (window.localStorage.getItem('banner_jump') === null) {
BannerActionCreators.show();
}
}
onClose = () => {
BannerActionCreators.hide();
};
onJump = (os) => {
BannerActionCreators.jump(os);
this.onClose();
};
render() {
return (
<section className="banner">
<p>
Welcome to <b>Actor Network</b>! Check out our <a href="//actor.im/ios" onClick={this.onJump.bind(this, 'IOS')} target="_blank">iPhone</a> and <a href="//actor.im/android" onClick={this.onJump.bind(this, 'ANDROID')} target="_blank">Android</a> apps!
</p>
<a className="banner__hide" onClick={this.onClose}>
<i className="material-icons">close</i>
</a>
</section>
);
}
}
export default Banner;
|
node_modules/material-ui/src/utils/children.js
|
aykutyaman/meteor1.3-react-flowrouter-demo
|
import React from 'react';
import createFragment from 'react-addons-create-fragment';
export default {
create(fragments) {
let newFragments = {};
let validChildrenCount = 0;
let firstKey;
//Only create non-empty key fragments
for (let key in fragments) {
const currentChild = fragments[key];
if (currentChild) {
if (validChildrenCount === 0) firstKey = key;
newFragments[key] = currentChild;
validChildrenCount++;
}
}
if (validChildrenCount === 0) return undefined;
if (validChildrenCount === 1) return newFragments[firstKey];
return createFragment(newFragments);
},
extend(children, extendedProps, extendedChildren) {
return React.isValidElement(children) ?
React.Children.map(children, (child) => {
const newProps = typeof (extendedProps) === 'function' ?
extendedProps(child) : extendedProps;
const newChildren = typeof (extendedChildren) === 'function' ?
extendedChildren(child) : extendedChildren ?
extendedChildren : child.props.children;
return React.cloneElement(child, newProps, newChildren);
}) : children;
},
};
|
react-ui/src/components/contact/CalendarComponent/TimePeriod.js
|
MaGuangChen/resume-maguangchen
|
import React from 'react';
import { connect } from 'react-redux';
import * as actions from '../../../actions/actions';
const TimePeriod = (props) => {
const { month, date, dispatch } = props;
const today = `${month}月
${date.date()}日`;
const changeHour = (e) => {
const hour = e.target.value;
dispatch(actions.selectedHour(hour));
}
const changeMinutes = (e) => {
const minute = e.target.value;
dispatch(actions.selectedMinutes(minute));
}
const submitSelectTime = () => {
dispatch(actions.handleCalendar(false));
dispatch(actions.handleSubmitSelectedTime(true));
if(props.page === 'user'){
props.handleReservationDate();
}
}
const hourArray = ['10', '11', '12', '13', '14', '15', '16', '17', '18'];
const minutes = ['00', '30'];
const hourOption = hourArray.map(hour => <option className="time-period_select_option" key={hour} value={hour}>{ hour }</option>);
const minutesOption = minutes.map(min => <option className="time-period_select_option" key={min}>{ min }</option>);
return (
<div className="time-period">
{ today }
<div>您可以選擇10:00~18:30分之間的時間</div>
<div>
<select onChange={changeHour} className="time-period_select">{ hourOption }</select>
<span className="time-deviend">:</span>
<select onChange={changeMinutes} className="time-period_select">{ minutesOption }</select>
</div>
<div onClick={submitSelectTime} className="calendar_submit">確認所選日期與時段</div>
</div>
);
}
export default connect()(TimePeriod);
|
src/client/me/index.react.js
|
jirastom/react-learnig
|
import Component from '../components/component.react';
import DocumentTitle from 'react-document-title';
import Logout from '../auth/logout.react';
import React from 'react';
import requireAuth from '../auth/requireauth.react';
import {format} from '../intl/store';
@requireAuth
export default class Index extends Component {
static propTypes = {
actions: React.PropTypes.object.isRequired,
msg: React.PropTypes.object.isRequired,
users: React.PropTypes.object.isRequired
}
render() {
const {actions, msg, users: {viewer: {email}}} = this.props;
return (
<DocumentTitle title={msg.me.title}>
<div className="me-page">
<p>{format(msg.me.welcome, {email})}</p>
<Logout {...{actions, msg}} />
</div>
</DocumentTitle>
);
}
}
|
Examples/ForTest/src/components/SQLiteDemo.js
|
ksti/react-native-utils
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
TouchableOpacity,
ListView
} from 'react-native';
var SQLite = require('react-native-sqlite-storage');
SQLite.DEBUG(true);
SQLite.enablePromise(true);
SQLite.enablePromise(false);
var database_name = "Test.db";
var database_version = "1.0";
var database_displayname = "SQLite Test Database";
var database_size = 200000;
var db;
export default class SQLiteDemo extends Component {
runDemo=()=>{
this.state.progress = ["Starting SQLite Demo"];
this.setState(this.state);
this.loadAndQueryDB();
}
loadAndQueryDB=()=>{
this.state.progress.push("Opening database ...");
this.setState(this.state);
db = SQLite.openDatabase(database_name, database_version, database_displayname, database_size, this.openCB, this.errorCB);
this.populateDatabase(db);
}
constructor(props){
super(props);
this.state={
progress: [],
dataSource: new ListView.DataSource({rowHasChanged: (row1, row2) => row1 !== row2,})
}
}
componentWillUnmount=()=>{
this.closeDatabase();
}
errorCB=(err)=> {
console.log("error: ",err);
this.state.progress.push("Error: "+ (err.message || err));
this.setState(this.state);
return false;
}
successCB=()=> {
console.log("SQL executed ...");
}
openCB=()=> {
this.state.progress.push("Database OPEN");
this.setState(this.state);
}
closeCB=()=> {
this.state.progress.push("Database CLOSED");
this.setState(this.state);
}
deleteCB=()=> {
console.log("Database DELETED");
this.state.progress.push("Database DELETED");
this.setState(this.state);
}
populateDatabase=(db)=>{
var that = this;
that.state.progress.push("Database integrity check");
that.setState(that.state);
db.executeSql('SELECT 1 FROM Version LIMIT 1', [],
function () {
that.state.progress.push("Database is ready ... executing query ...");
that.setState(that.state);
db.transaction(that.queryEmployees,that.errorCB,function() {
that.state.progress.push("Processing completed");
that.setState(that.state);
});
},
function (error) {
console.log("received version error:", error);
that.state.progress.push("Database not yet ready ... populating data");
that.setState(that.state);
db.transaction(that.populateDB, that.errorCB, function () {
that.setState(that.state);
db.transaction(that.queryEmployees,that.errorCB, function () {
that.state.progress.push("Processing completed");
that.setState(that.state);
that.closeDatabase();
});
});
});
}
populateDB=(tx)=> {
this.state.progress.push("Executing DROP stmts");
this.setState(this.state);
tx.executeSql('DROP TABLE IF EXISTS Employees;');
tx.executeSql('DROP TABLE IF EXISTS Offices;');
tx.executeSql('DROP TABLE IF EXISTS Departments;');
this.state.progress.push("Executing CREATE stmts");
this.setState(this.state);
tx.executeSql('CREATE TABLE IF NOT EXISTS Version( '
+ 'version_id INTEGER PRIMARY KEY NOT NULL); ', [], this.successCB, this.errorCB);
tx.executeSql('CREATE TABLE IF NOT EXISTS Departments( '
+ 'department_id INTEGER PRIMARY KEY NOT NULL, '
+ 'name VARCHAR(30) ); ', [], this.successCB, this.errorCB);
tx.executeSql('CREATE TABLE IF NOT EXISTS Offices( '
+ 'office_id INTEGER PRIMARY KEY NOT NULL, '
+ 'name VARCHAR(20), '
+ 'longtitude FLOAT, '
+ 'latitude FLOAT ) ; ', [], this.successCB, this.errorCB);
tx.executeSql('CREATE TABLE IF NOT EXISTS Employees( '
+ 'employe_id INTEGER PRIMARY KEY NOT NULL, '
+ 'name VARCHAR(55), '
+ 'office INTEGER, '
+ 'department INTEGER, '
+ 'FOREIGN KEY ( office ) REFERENCES Offices ( office_id ) '
+ 'FOREIGN KEY ( department ) REFERENCES Departments ( department_id ));', []);
this.state.progress.push("插入数据开始");
this.setState(this.state);
//插入:tx.executeSql('INSERT INTO Departments (name) VALUES ("军情六处");', []);
let initDepartmentArr = [
{
name:'军情六处',
},{
name:'克格勃',
},{
name:'CIA',
},{
name:'啥东西',
}
];
initDepartmentArr.map((object,index)=>{
this.sqlInsert('Departments',object);
});
// tx.executeSql('INSERT INTO Offices (name, longtitude, latitude) VALUES ("中国", 59.8, 34.);', []);
let initOfficeArr = [
{
name:'陕西',
longtitude:59.8,
latitude:34,
},{
name:'河南',
longtitude:59.8,
latitude:34,
},{
name:'四川',
longtitude:59.8,
latitude:34,
},{
name:'山西',
longtitude:59.8,
latitude:34,
},{
name:'北京',
longtitude:59.8,
latitude:34,
},
]
initOfficeArr.map((object,index)=>{
this.sqlInsert('Offices',object);
});
// tx.executeSql('INSERT INTO Employees (name, office, department) VALUES ("王庆", 2, 4);', []);
let initEmployeeArr = [
{
name:'王高',
office:1,
department:1,
},{
name:'王瑞华',
office:1,
department:2,
},{
name:'赵立峰',
office:1,
department:3,
},{
name:'阙凯',
office:1,
department:4,
},{
name:'郭军帅',
office:1,
department:1,
},
]
initEmployeeArr.map((object,index)=>{
this.sqlInsert('Employees',object);
});
console.log("all config SQL done");
this.state.progress.push("插入数据结束");
}
sqlCreateTable=(table)=>{
tx.executeSql('CREATE TABLE IF NOT EXISTS Employees( '
+ 'employe_id INTEGER PRIMARY KEY NOT NULL, '
+ 'name VARCHAR(55), '
+ 'office INTEGER, '
+ 'department INTEGER, '
+ 'FOREIGN KEY ( office ) REFERENCES Offices ( office_id ) '
+ 'FOREIGN KEY ( department ) REFERENCES Departments ( department_id ));', []);
}
sqlInsert=(table,object)=>{
var keyString='';
var valueString = '';
for (var key in object) {
keyString = keyString+key+',';
if ( typeof(object[key]) == 'string' ) {
valueString = valueString+'"'+object[key]+'",';
}else {
valueString = valueString+object[key]+',';
}
}
keyString = keyString.slice(0,-1);
valueString = valueString.slice(0,-1);
var sqlString = 'INSERT INTO '+table+' ('+keyString+') VALUES ('+valueString+');'
console.log('插入数据:'+sqlString);
return db.executeSql(sqlString,[]);
}
queryEmployees=(tx)=> {
this.state.progress.push("查询员工数据queryEmployees");
tx.executeSql('SELECT a.name, b.name as deptName FROM Employees a, Departments b WHERE a.department = b.department_id ', [],
this.queryEmployeesSuccess,this.errorCB);
//tx.executeSql('SELECT a.name, from TEST', [],() => {},this.errorCB);
tx.executeSql('SELECT a.name,b.name as deptName FROM Employees a,Departments b WHERE a.name="王花花" and a.department=b.department_id ',[],this.queryEmployeesSuccess,this.errorCB);
}
queryEmployeesSuccess=(tx,results)=> {
this.state.progress.push("Query completed");
this.setState(this.state);
var len = results.rows.length;
for (let i = 0; i < len; i++) {
let row = results.rows.item(i);
this.state.progress.push(`Empl Name: ${row.name}, Dept Name: ${row.deptName}`);
}
this.setState(this.state);
}
deleteDatabase=()=>{
this.state.progress = ["Deleting database"];
this.setState(this.state);
SQLite.deleteDatabase(database_name, this.deleteCB, this.errorCB);
}
closeDatabase=()=>{
var that = this;
if (db) {
console.log("Closing database ...");
that.state.progress.push("Closing database");
that.setState(that.state);
db.close(that.closeCB,that.errorCB);
} else {
that.state.progress.push("Database was not OPENED");
that.setState(that.state);
}
}
renderProgressEntry=(entry)=>{
return (
<View style={listStyles.li}>
<View>
<Text style={listStyles.title}>{entry}</Text>
</View>
</View>
)
}
render=()=>{
var ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
return (
<View style={styles.mainContainer}>
<View style={styles.toolbar}>
<Text style={styles.toolbarButton} onPress={this.runDemo}>
Run Demo
</Text>
<Text style={styles.toolbarButton} onPress={this.closeDatabase}>
Close DB
</Text>
<Text style={styles.toolbarButton} onPress={this.deleteDatabase}>
Delete DB
</Text>
</View>
<ListView
dataSource={ds.cloneWithRows(this.state.progress)}
renderRow={this.renderProgressEntry}
style={listStyles.liContainer}/>
</View>
);
}
};
var listStyles = StyleSheet.create({
li: {
borderBottomColor: '#c8c7cc',
borderBottomWidth: 0.5,
paddingTop: 15,
paddingRight: 15,
paddingBottom: 15,
},
liContainer: {
backgroundColor: '#fff',
flex: 1,
paddingLeft: 15,
},
liIndent: {
flex: 1,
},
liText: {
color: '#333',
fontSize: 17,
fontWeight: '400',
marginBottom: -3.5,
marginTop: -3.5,
},
});
var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
toolbar: {
backgroundColor: '#51c04d',
paddingTop: 30,
paddingBottom: 10,
flexDirection: 'row'
},
toolbarButton: {
color: 'blue',
textAlign: 'center',
flex: 1
},
mainContainer: {
flex: 1
}
});
|
src/SquaresBanner/index.js
|
dave-worley/zenlab
|
import React from 'react';
import Canvas from '../PaperCanvas';
import { Shape, Point, Color, Size } from 'paper';
import './styles.css';
let animation = (scope) => {
const { view } = scope;
let bounds = view.size;
let randn = () => Math.random();
let color = () => new Color(randn(), 0, 0);
let randint = (max, min) => Math.floor(Math.random() * (max - min) + min);
let squares = [];
const makesquares = (i) => {
let c = new Shape.Rectangle(new Point(i * bounds.height, 0), new Size(bounds.height, bounds.height));
c.fillColor = color();
c.blendMode = 'multiply';
return c;
};
for (let i = 0; i < view.bounds.width/bounds.height; i++) {
squares.push(makesquares(i))
}
view.onFrame = () => {
squares.forEach((square) => {
square.fillColor = color();
});
bounds = view.size;
};
};
export default ({
width,
height
}) => {
return (
<div className="squares">
<Canvas
width={ width }
height={ height }
script={
animation
}/>
</div>
);
};
|
js/views/newChallenge/ItemSelectView.js
|
SamyZ/BoomApp
|
import React from 'react';
import {
View,
Text,
TouchableOpacity,
} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';
import itemSelectStyles from '../../styles/newChallenge/itemSelectStyles';
const propTypes = {
label: React.PropTypes.string,
style: React.PropTypes.object,
onItemSelect: React.PropTypes.func,
};
const ItemSelectView = (props) => {
console.log(props)
return (
<View style={[itemSelectStyles.mainContainer, { marginTop: props.style.marginTop, opacity: props.style.opacity }]} >
<TouchableOpacity style={itemSelectStyles.touchableContainer} onPress={() => props.onItemSelect(props.label)} >
<View style={itemSelectStyles.labelContainer}>
<Text style={[itemSelectStyles.labelFont, { fontSize: props.style.labelFontSize }]}>{props.label}</Text>
</View>
<View style={itemSelectStyles.iconContainer} >
<Icon
name="ios-arrow-dropdown-outline"
color={props.style.iconColor}
style={[itemSelectStyles.iconFont, { fontSize: props.style.iconFontSize }]}
/>
</View>
</TouchableOpacity>
</View>
)
}
ItemSelectView.propTypes = propTypes;
export default ItemSelectView;
|
src/Input.js
|
egauci/react-bootstrap
|
import React from 'react';
import InputBase from './InputBase';
import * as FormControls from './FormControls';
import deprecationWarning from './utils/deprecationWarning';
class Input extends InputBase {
render() {
if (this.props.type === 'static') {
deprecationWarning('Input type=static', 'FormControls.Static');
return <FormControls.Static {...this.props} />;
}
return super.render();
}
}
Input.propTypes = {
type: React.PropTypes.string
};
export default Input;
|
src/components/Quiz/Question.spec.js
|
SirWinn3r/gauche-ou-droite-client
|
import chai, { expect } from 'chai'
import chaiEnzyme from 'chai-enzyme'
import React from 'react'
import { shallow } from 'enzyme'
import sinon from 'sinon'
import Question from './Question'
chai.use(chaiEnzyme())
describe('<Question />', () => {
const apiUrl = 'api-url'
const congressman = {
name: 'congressman-name',
parti: 'congressman-party',
path: 'congressman-photo-path'
}
const currentQuestionIndex = 34
const questionCount = 50
it('Should render appropriately', () => {
const wrapper = shallow(
<Question
apiUrl={apiUrl}
congressman={congressman}
currentQuestionIndex={currentQuestionIndex}
questionCount={questionCount}
selectAnswerFn={() => null}
/>
)
const infosToDisplay = ['photo']
// <QuizProgress />
const quizProgress = wrapper.find('QuizProgress')
expect(quizProgress)
.to.have.length(1, '<Question /> does not display <QuizProgress />')
expect(quizProgress.prop('currentQuestionIndex'))
.to.equal(currentQuestionIndex, '<Question /> does not pass correct current question index to <QuizProgress />')
expect(quizProgress.prop('questionCount'))
.to.equal(questionCount, '<Question /> does not pass correct question count to <QuizProgress />')
// <CongressmanCard />
const congressmanCard = wrapper.find('CongressmanCard')
expect(congressmanCard)
.to.have.length(1, '<Question /> does not display <CongressmanCard />')
expect(congressmanCard.prop('congressman'))
.to.deep.equal(congressman, '<Question /> does not pass congressman correctly to <CongressmanCard />')
expect(congressmanCard.prop('infosToDisplay'))
.to.deep.equal(infosToDisplay, '<Question /> does not just display congressman photo')
// <button />
const button = wrapper.find('button')
expect(button)
.to.have.length(2, '<Question /> does not display both buttons')
})
it('Should select correct answer on button click', () => {
const selectAnswerFn = sinon.spy()
const wrapper = shallow(
<Question
apiUrl={apiUrl}
congressman={congressman}
currentQuestionIndex={currentQuestionIndex}
questionCount={questionCount}
selectAnswerFn={selectAnswerFn}
/>
)
// Left button
wrapper.find('.button-left').simulate('click')
expect(selectAnswerFn.calledOnce)
.to.equal(true, '.button-left clicked more than once')
expect(selectAnswerFn.calledWith('gauche'))
.to.equal(true, '.button-left does not select correct answer')
// Right button
wrapper.find('.button-right').simulate('click')
expect(selectAnswerFn.calledTwice)
.to.equal(true, '.button-right clicked more than once')
expect(selectAnswerFn.calledWith('droite'))
.to.equal(true, '.button-right does not select correct answer')
})
})
|
src/client/components/input/drag-and-drop.js
|
bookbrainz/bookbrainz-site
|
/*
* Copyright (C) 2016 Max Prettyjohns
*
* 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 CustomInput from '../../input';
import PropTypes from 'prop-types';
import React from 'react';
class DragAndDrop extends React.Component {
constructor() {
super();
this.handleClick = this.handleClick.bind(this);
this.handleDragOver = this.handleDragOver.bind(this);
this.handleDrop = this.handleDrop.bind(this);
this.state = {
achievement: {
name: 'drag badge to set',
src: '/images/blankbadge.svg'
}
};
}
handleClick(ev) {
ev.preventDefault();
this.setState({
achievement: {
name: 'drag badge to set',
src: '/images/blankbadge.svg'
}
});
}
handleDragOver(ev) {
ev.preventDefault();
}
addChild(data) {
this.setState({achievement: data});
}
handleDrop(ev) {
ev.preventDefault();
let data;
try {
data = JSON.parse(ev.dataTransfer.getData('text'));
}
catch (err) {
return;
}
this.addChild(data);
}
getValue() {
return this.target.getValue();
}
render() {
return (
<div
className="well col-sm-4"
onClick={this.handleClick}
onDragOver={this.handleDragOver}
onDrop={this.handleDrop}
>
<CustomInput
name={this.props.name}
type="hidden"
value={this.state.achievement.id}
/>
<img
className="center-block"
height="100px"
src={this.state.achievement.src}
/>
<div className="center-block h3">
{this.state.achievement.name}
</div>
</div>
);
}
}
DragAndDrop.displayName = 'DragAndDrop';
DragAndDrop.propTypes = {
name: PropTypes.string.isRequired
};
export default DragAndDrop;
|
frontend/src/javascripts/utils/EventUtil.js
|
funaota/notee
|
import React from 'react';
import assign from 'object-assign';
var EventEmitter = require('events').EventEmitter;
var EventUtil = assign({}, EventEmitter.prototype, {
emitChange: function(change_event) {
this.emit(change_event);
},
addChangeListener: function(change_event, callback) {
this.on(change_event, callback);
},
removeChangeListener: function(change_event, callback) {
this.removeListener(change_event, callback);
}
});
module.exports = EventUtil;
|
tests/helpers/intl-enzyme-test-helper.js
|
korabh/quran.com-frontend
|
/**
* Based on: https://gist.github.com/mirague/c05f4da0d781a9b339b501f1d5d33c37/
*
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import { mount, shallow } from 'enzyme';
// Create the IntlProvider to retrieve context for wrapping around.
// NOTE: Phantomjs requires usage of `var`
var intlProvider = new IntlProvider({ locale: 'en' }, {}); // eslint-disable-line
var intl = intlProvider.getChildContext(); // eslint-disable-line
/**
* When using React-Intl `injectIntl` on components, props.intl is required.
*/
function nodeWithIntlProp(node) {
return React.cloneElement(node, intl);
}
/**
* Export these methods.
*/
export function shallowWithIntl(node) {
return shallow(nodeWithIntlProp(node), { context: intl });
}
export function mountWithIntl(node) {
return mount(nodeWithIntlProp(node), {
context: intl,
childContextTypes: { intl: intlShape }
});
}
|
src/Parser/DeathKnight/Unholy/Modules/Items/ColdHeartEfficiency.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import ITEMS from 'common/ITEMS';
import { formatPercentage } from 'common/format';
import Wrapper from 'common/Wrapper';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
const coldHeartMaxStack = 20;
const unholyStrengthDuration = 15000;
const concordanceDuration = 10000;
const khazgorothDuration = 15000;
const coldHeartOptimalMinStack = 14;
const remainingDurationAllowed = 4000;
const maxDurationAtMaxStacksAllowed = 4000;
class ColdHeartEfficiency extends Analyzer {
static dependencies = {
combatants: Combatants,
};
on_initialized() {
this.active = this.combatants.selected.hasChest(ITEMS.COLD_HEART.id);
}
totalColdHeartCasts = 0;
correctColdHeartCasts = 0;
buffColdHeart = coldHeartMaxStack; //Stacks start at 20 at start of fight
unholyStrengthStart = 0;
concordanceStart = 0;
khazgorothStart = 0;
timeAtMaxStacksStart = this.owner.fight.start_time;
castsTooEarly = 0;
castsTooLate = 0;
on_byPlayer_applybuff(event) {
const spellID = event.ability.guid;
if (spellID === SPELLS.UNHOLY_STRENGTH_BUFF.id) {
this.unholyStrengthStart = event.timestamp;
}
if (spellID === SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_STRENGTH.id) {
this.concordanceStart = event.timestamp;
}
if (spellID === SPELLS.KHAZGOROTHS_SHAPING.id) {
this.khazgorothStart = event.timestamp;
}
}
on_byPlayer_refreshbuff(event) {
const spellID = event.ability.guid;
if (spellID === SPELLS.UNHOLY_STRENGTH_BUFF.id) {
this.unholyStrengthStart = event.timestamp;
}
if (spellID === SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_STRENGTH.id) {
this.concordanceStart = event.timestamp;
}
if (spellID === SPELLS.KHAZGOROTHS_SHAPING.id) {
this.khazgorothStart = event.timestamp;
}
}
on_byPlayer_removebuff(event) {
const spellID = event.ability.guid;
if (spellID === SPELLS.UNHOLY_STRENGTH_BUFF.id) {
this.unholyStrengthStart = 0;
}
if (spellID === SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_STRENGTH.id) {
this.concordanceStart = 0;
}
if (spellID === SPELLS.KHAZGOROTHS_SHAPING.id) {
this.khazgorothStart = 0;
}
}
on_byPlayer_applybuffstack(event) {
const spellID = event.ability.guid;
if (spellID === SPELLS.COLD_HEART_BUFF.id) {
this.buffColdHeart = event.stack;
if (this.buffColdHeart === coldHeartMaxStack) {
this.timeAtMaxStacksStart = event.timestamp;
}
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
if (spellId === SPELLS.CHAINS_OF_ICE.id) {
this.totalColdHeartCasts++;
const timeAtMaxStacks = event.timestamp - this.timeAtMaxStacksStart;
const unholyStrengthRemaining = unholyStrengthDuration - (event.timestamp - this.unholyStrengthStart);
const concordanceRemaining = concordanceDuration - (event.timestamp - this.concordanceStart);
const khazgorothRemaining = khazgorothDuration - (event.timestamp - this.khazgorothStart);
//This checks wether or not any of the three buffs are about to fall off within the next 4 seconds.
if (this.buffColdHeart < coldHeartMaxStack && this.buffColdHeart >= coldHeartOptimalMinStack) {
if ((unholyStrengthRemaining > 0 && unholyStrengthRemaining < remainingDurationAllowed) || (concordanceRemaining > 0 && concordanceRemaining < remainingDurationAllowed) || (khazgorothRemaining > 0 && khazgorothRemaining < remainingDurationAllowed)){
this.correctColdHeartCasts++;
}
else if (this.buffColdHeart < coldHeartMaxStack) {
this.castsTooEarly++;
}
}
else if (this.buffColdHeart < coldHeartMaxStack) {
this.castsTooEarly++;
}
else if (this.buffColdHeart === coldHeartMaxStack && ((timeAtMaxStacks <= maxDurationAtMaxStacksAllowed) || ((event.timestamp - this.owner.fight.start_time) < 7000))) {
this.correctColdHeartCasts++;
}
else if(this.buffColdHeart === coldHeartMaxStack){
this.castsTooLate++;
}
//This is only here for double casting Cold Heart. If Cold Heart is casted again before it reaches 2 stacks, the event won't update.
this.buffColdHeart = 0;
}
}
suggestions(when) {
const castEfficiency = this.correctColdHeartCasts / this.totalColdHeartCasts;
when(castEfficiency).isLessThan(0.8)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<Wrapper> You are casting <SpellLink id={SPELLS.CHAINS_OF_ICE.id} /> at non optimal times. {this.castsTooLate} cast(s) were made too late and {this.castsTooEarly} cast(s) were made too early. You either want to cast <SpellLink id={SPELLS.CHAINS_OF_ICE.id} /> when at 20 stacks of <SpellLink id={SPELLS.COLD_HEART_BUFF.id} /> ASAP, or when you are above 13 stacks and any of your buffs <SpellLink id={SPELLS.UNHOLY_STRENGTH_BUFF.id}/> or <SpellLink id={SPELLS.CONCORDANCE_OF_THE_LEGIONFALL_STRENGTH.id} /> or <SpellLink id={SPELLS.KHAZGOROTHS_SHAPING.id} /> are about to run out. You also don't want to hold <SpellLink id={SPELLS.CHAINS_OF_ICE.id} /> at 20 stacks for too long.</Wrapper>)
.icon(SPELLS.CHAINS_OF_ICE.icon)
.actual(`${formatPercentage(actual)}% of Chains of Ice were cast correctly.`)
.recommended(`>${formatPercentage(recommended)}% is recommended`)
.regular(recommended - 0.20).major(recommended - 0.40);
});
}
statistic() {
const castEfficiency = this.correctColdHeartCasts / this.totalColdHeartCasts;
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.CHAINS_OF_ICE.id} />}
value={`${formatPercentage(castEfficiency)} %`}
label="Cold Heart Efficiency"
tooltip={`${this.correctColdHeartCasts} out of ${this.totalColdHeartCasts} casts of Cold Heart were made optimally.`}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(5);
}
export default ColdHeartEfficiency;
|
src/profesor/components/ProgramiLista.js
|
zeljkoX/e-learning
|
import React from 'react';
import {State, History} from 'react-router';
import { Menu, Mixins, Styles } from 'material-ui';
import Content from '../../components/layout/Content';
import ContentHeader from '../../components/layout/ContentHeader';
import Tabela from '../../components/Tabela';
class ProgramiLista extends React.Component {
render() {
var menu = [{name:'Dodaj Program', link:'profesor/program/add'}];
return (
<Content>
<ContentHeader title='Lista Programa' menu={menu}/>
<Tabela/>
</Content>
);
}
}
export default ProgramiLista;
|
examples/samples/phone.js
|
andreaValenzi/react-native-swiper
|
import React from 'react'
import { StyleSheet, Text, View, Image } from 'react-native'
import Swiper from '../swiper.dist'
const styles = StyleSheet.create({
wrapper: {
// backgroundColor: '#f00'
},
slide: {
flex: 1,
backgroundColor: 'transparent'
},
image: {
flex: 1
}
})
export default class PhoneSample extends React.Component {
render() {
return (
<View>
<Image source={{uri: 'http://i.imgur.com/rVekwfn.jpg'}}>
<Swiper style={styles.wrapper}
dot={<View style={{backgroundColor:'rgba(255,255,255,.3)', width: 13, height: 13,borderRadius: 7, marginLeft: 7, marginRight: 7,}} />}
activeDot={<View style={{backgroundColor: '#fff', width: 13, height: 13, borderRadius: 7, marginLeft: 7, marginRight: 7}} />}
paginationStyle={{
bottom: 70,
}}
loop={false}>
<View style={styles.slide}>
<Image style={styles.image} source={{uri: 'http://i.imgur.com/u3kXqo7.png'}} />
</View>
<View style={styles.slide}>
<Image style={styles.image} source={{uri: 'http://i.imgur.com/3Z4nQyb.png'}} />
</View>
<View style={styles.slide}>
<Image style={styles.image} source={{uri: 'http://i.imgur.com/5Wa3Iyb.png'}} />
</View>
</Swiper>
</Image>
</View>
)
}
}
|
admin/client/App/screens/List/components/Filtering/ListFiltersAddForm.js
|
jstockwin/keystone
|
import React from 'react';
import { findDOMNode } from 'react-dom';
import Popout from '../../../../shared/Popout';
import { Filters } from 'FieldTypes';
var ListFiltersAddForm = React.createClass({
propTypes: {
field: React.PropTypes.object.isRequired,
maxHeight: React.PropTypes.number,
onApply: React.PropTypes.func,
onCancel: React.PropTypes.func,
onHeightChange: React.PropTypes.func,
},
getInitialState () {
const filterComponent = Filters[this.props.field.type];
let filterValue = this.props.activeFilters.filter(i => i.field.path === this.props.field.path)[0];
if (filterValue) {
filterValue = filterValue.value;
} else {
filterValue = filterComponent && filterComponent.getDefaultValue ? filterComponent.getDefaultValue() : {};
}
return {
filterComponent: filterComponent,
filterValue: filterValue,
};
},
updateHeight (bodyHeight) {
bodyHeight += 40; // TODO: remove magic number, currently accounts for padding
const footerHeight = findDOMNode(this.refs.footer).offsetHeight;
const maxBodyHeight = this.props.maxHeight - footerHeight;
const newHeight = bodyHeight + footerHeight;
// console.log(bodyHeight, maxBodyHeight, '|', newHeight, this.props.maxHeight);
this.setState({
bodyHeight: Math.min(bodyHeight, maxBodyHeight),
}, () => {
this.props.onHeightChange(Math.min(newHeight, this.props.maxHeight));
});
},
updateValue (filterValue) {
this.setState({
filterValue: filterValue,
});
},
handleFormSubmit (e) {
e.preventDefault();
this.props.onApply(this.state.filterValue);
},
renderInvalidFilter () {
return (
<div>Error: type {this.props.field.type} has no filter UI.</div>
);
},
render () {
var FilterComponent = this.state.filterComponent;
return (
<form onSubmit={this.handleFormSubmit}>
<Popout.Body ref="body" scrollable style={{ height: this.state.bodyHeight }}>
{FilterComponent ? <FilterComponent field={this.props.field} filter={this.state.filterValue} onChange={this.updateValue} onHeightChange={this.updateHeight} /> : this.renderInvalidFilter()}
</Popout.Body>
<Popout.Footer
ref="footer"
primaryButtonIsSubmit
primaryButtonLabel="Apply"
secondaryButtonAction={this.props.onCancel}
secondaryButtonLabel="Cancel" />
</form>
);
},
});
module.exports = ListFiltersAddForm;
|
packages/web/examples/ssr/pages/_document.js
|
appbaseio/reactivesearch
|
import React from 'react';
import Document, { Head, Main, NextScript } from 'next/document';
import { renderToString } from 'react-dom/server';
export default class MyDocument extends Document {
static getInitialProps({ renderPage }) {
// for emotion-js
const page = renderPage();
const styles = renderToString(page.html);
return { ...page, ...styles };
}
constructor(props) {
// for emotion-js
super(props);
const { __NEXT_DATA__, ids } = props;
if (ids) {
__NEXT_DATA__.ids = ids;
}
}
render() {
return (
<html lang="en">
<Head>
<link rel="stylesheet" href="/_next/static/style.css" />
<meta charSet="utf-8" />
<meta name="viewport" content="initial-scale=1.0, width=device-width" />
{/* for emotion-js */}
<style dangerouslySetInnerHTML={{ __html: this.props.css }} />
</Head>
<body>
<Main />
<NextScript />
</body>
</html>
);
}
}
|
app/javascript/mastodon/features/compose/containers/warning_container.js
|
ambition-vietnam/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import Warning from '../components/warning';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import { me } from '../../../initial_state';
const APPROX_HASHTAG_RE = /(?:^|[^\/\)\w])#(\w*[a-zA-Z·]\w*)/i;
const mapStateToProps = state => ({
needsLockWarning: state.getIn(['compose', 'privacy']) === 'private' && !state.getIn(['accounts', me, 'locked']),
hashtagWarning: state.getIn(['compose', 'privacy']) !== 'public' && APPROX_HASHTAG_RE.test(state.getIn(['compose', 'text'])),
});
const WarningWrapper = ({ needsLockWarning, hashtagWarning }) => {
if (needsLockWarning) {
return <Warning message={<FormattedMessage id='compose_form.lock_disclaimer' defaultMessage='Your account is not {locked}. Anyone can follow you to view your follower-only posts.' values={{ locked: <a href='/settings/profile'><FormattedMessage id='compose_form.lock_disclaimer.lock' defaultMessage='locked' /></a> }} />} />;
}
if (hashtagWarning) {
return <Warning message={<FormattedMessage id='compose_form.hashtag_warning' defaultMessage="This toot won't be listed under any hashtag as it is unlisted. Only public toots can be searched by hashtag." />} />;
}
return null;
};
WarningWrapper.propTypes = {
needsLockWarning: PropTypes.bool,
hashtagWarning: PropTypes.bool,
};
export default connect(mapStateToProps)(WarningWrapper);
|
src/components/file-list/file-list-item.js
|
Storj/metadisk-gui
|
import React from 'react';
import FileIcon from 'components/file-list/file-icon';
const FileListItem = (props) => {
function handleClick(event) {
event.preventDefault();
props.fileSelectAction(props.hash, props.mimetype, props.filename);
}
return (
<tr>
<td>
<FileIcon mimetype={props.mimetype}/>
<a href="#noop" onClick={handleClick}>{props.filename}</a>
</td>
<td>
<span>{props.size}B</span>
</td>
<td>
<span>{props.mimetype}</span>
</td>
</tr>
);
};
export default FileListItem;
|
test/SplitButtonSpec.js
|
sheep902/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import SplitButton from '../src/SplitButton';
import MenuItem from '../src/MenuItem';
import Button from '../src/Button';
describe('SplitButton', () => {
const simple = (
<SplitButton title='Title' id='test-id'>
<MenuItem>Item 1</MenuItem>
<MenuItem>Item 2</MenuItem>
<MenuItem>Item 3</MenuItem>
<MenuItem>Item 4</MenuItem>
</SplitButton>
);
it('should open the menu when dropdown button is clicked', () => {
const instance = ReactTestUtils.renderIntoDocument(simple);
const toggleNode = React.findDOMNode(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-toggle'));
const splitButtonNode = React.findDOMNode(instance);
splitButtonNode.className.should.not.match(/open/);
ReactTestUtils.Simulate.click(toggleNode);
splitButtonNode.className.should.match(/open/);
});
it('should not open the menu when other button is clicked', () => {
const instance = ReactTestUtils.renderIntoDocument(simple);
const buttonNode = React.findDOMNode(ReactTestUtils.scryRenderedComponentsWithType(instance, Button)[0]);
const splitButtonNode = React.findDOMNode(instance);
splitButtonNode.className.should.not.match(/open/);
ReactTestUtils.Simulate.click(buttonNode);
splitButtonNode.className.should.not.match(/open/);
});
it('should invoke onClick when SplitButton.Button is clicked (prop)', (done) => {
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton title='Title' id='test-id' onClick={ () => done() }>
<MenuItem>Item 1</MenuItem>
</SplitButton>
);
const buttonNode = React.findDOMNode(ReactTestUtils.scryRenderedComponentsWithType(instance, Button)[0]);
ReactTestUtils.Simulate.click(buttonNode);
});
it('should not invoke onClick when SplitButton.Toggle is clicked (prop)', (done) => {
let onClickSpy = sinon.spy();
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton
title='Title'
id='test-id'
onClick={onClickSpy}
>
<MenuItem>Item 1</MenuItem>
</SplitButton>
);
const toggleNode = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-toggle'));
ReactTestUtils.Simulate.click(toggleNode);
setTimeout(()=> {
onClickSpy.should.not.have.been.called;
done();
}, 10);
});
it('Should pass disabled to both buttons', () => {
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton title='Title' id='test-id' disabled>
<MenuItem>Item 1</MenuItem>
</SplitButton>
);
const toggleNode = React.findDOMNode(
ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'dropdown-toggle'));
const buttonNode = React.findDOMNode(
ReactTestUtils.scryRenderedComponentsWithType(instance, Button)[0]);
expect(toggleNode.disabled).to.be.true;
expect(buttonNode.disabled).to.be.true;
});
it('Should set target attribute on anchor', () => {
const instance = ReactTestUtils.renderIntoDocument(
<SplitButton title="Title" id='test-id' href="/some/unique-thing/" target="_blank">
<MenuItem eventKey="1">MenuItem 1 content</MenuItem>
</SplitButton>
);
let anchors = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a');
let linkElement = React.findDOMNode(anchors[0]);
assert.equal(linkElement.target, '_blank');
});
});
|
client/modules/RootWiki/components/WikiDataFormForm/WikiDataFormForm.js
|
XuHaoJun/tiamat
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Container, Col, Row } from 'react-grid-system';
import exampleData from '../../../Wiki/components/WikiDataForm/HearthStoneSchema.json';
import WikiDataForm from '../../../Wiki/components/WikiDataForm';
import EnhancedSwipeableViews from '../../../../components/EnhancedSwipableViews';
import validate from './validate';
import AceEditorOri from '../../../../components/AceEditor';
const AceEditor = props => {
const defaultProps = {
mode: 'json',
theme: 'github',
tabSize: 2,
highlightActiveLine: true,
showLineNumbers: true,
enableLiveAutocompletion: true,
showGutter: true,
};
const finalProps = Object.assign(defaultProps, props);
return <AceEditorOri {...finalProps} />;
};
class WikiDataFormForm extends React.PureComponent {
static propTypes = {
enablePreview: PropTypes.bool,
previewShowKind: PropTypes.oneOf(['grid', 'tabs']),
defaultWikiDataForm: PropTypes.object,
onRequestSubmit: PropTypes.func,
};
static defaultProps = {
enablePreview: true,
previewShowKind: 'grid',
defaultWikiDataForm: undefined,
onRequestSubmit: undefined,
};
constructor(props) {
super(props);
this.state = {
name: '',
jsonSchemaValue: JSON.stringify(exampleData.schema, null, 2),
uiSchemaValue: JSON.stringify(exampleData.uiSchema, null, 2),
};
const { defaultWikiDataForm } = props;
if (defaultWikiDataForm) {
const { name, jsonSchema, uiSchema } = defaultWikiDataForm;
this.state.name = name;
this.state.jsonSchemaValue = JSON.stringify(jsonSchema, null, 2);
this.state.uiSchemaValue = JSON.stringify(uiSchema, null, 2);
}
}
getForm = () => {
try {
const { name, jsonSchemaValue, uiSchemaValue } = this.state;
const jsonSchema = JSON.parse(jsonSchemaValue);
const uiSchema = JSON.parse(uiSchemaValue);
const wikiDataForm = {
name,
jsonSchema,
uiSchema,
};
return wikiDataForm;
} catch (error) {
if (error instanceof SyntaxError) {
return null;
} else {
throw error;
}
}
};
validate = validate;
submit = () => {
const form = this.getForm();
const valid = this.validate(form);
if (valid) {
if (this.props.onRequestSubmit) {
this.props.onRequestSubmit(form, this.validate);
}
}
};
handleSchemaChange = jsonSchemaValue => {
this.setState({ jsonSchemaValue });
};
handleUISchemaChange = uiSchemaValue => {
this.setState({ uiSchemaValue });
};
renderPreview = () => {
let wikiDataForm = this.getForm();
if (wikiDataForm) {
this.previousWikiDataForm = wikiDataForm;
} else {
if (this.previousWikiDataForm) {
wikiDataForm = this.previousWikiDataForm;
}
}
return <WikiDataForm wikiDataForm={wikiDataForm} />;
};
renderForm = () => {
const { jsonSchemaValue, uiSchemaValue } = this.state;
return (
<div>
<h1>Schema</h1>
<AceEditor
mode="json"
name="WikiDataFormForm-schema"
onChange={this.handleSchemaChange}
value={jsonSchemaValue}
/>
<h1>UI Schema</h1>
<AceEditor
mode="json"
name="WikiDataFormForm-uiSchema"
onChange={this.handleUISchemaChange}
value={uiSchemaValue}
/>
</div>
);
};
render() {
const { enablePreview, previewShowKind } = this.props;
if (enablePreview) {
if (previewShowKind === 'grid') {
return (
<div>
<Container fluid={true}>
<Row>
<Col sm={12} md={6}>
{this.renderForm()}
</Col>
<Col sm={12} md={6}>
{this.renderPreview()}
</Col>
</Row>
</Container>
</div>
);
} else if (previewShowKind === 'tabs') {
return (
<div>
{this.renderForm()}
{this.renderPreview()}
</div>
);
// TODO
// implement tabs
// return (
// <div>
// <Tabs>
// <Tab label="表單" />
// <Tab label="預覽" />
// </Tabs>
// <EnhancedSwipeableViews>
// {this.renderForm()}
// {this.renderPreview()}
// </EnhancedSwipeableViews>
// </div>
// );
} else {
return <div>Not support previewShowKind: {previewShowKind}</div>;
}
} else {
return this.renderForm();
}
}
}
export const WikiDataFormFormWithoutConnect = WikiDataFormForm;
export default connect(
(state, props) => {
let { previewShowKind } = props;
if (!previewShowKind) {
const { browser } = state;
if (browser.lessThan.medium) {
previewShowKind = 'tabs';
} else {
previewShowKind = 'grid';
}
}
return { previewShowKind };
},
null,
null,
{ withRef: true }
)(WikiDataFormForm);
|
src/website/app/demos/Dropdown/Dropdown/examples/rtl.js
|
mineral-ui/mineral-ui
|
/* @flow */
import styled from '@emotion/styled';
import React from 'react';
import Button from '../../../../../../library/Button';
import Dropdown from '../../../../../../library/Dropdown';
import { pxToEm } from '../../../../../../library/styles';
import { ThemeProvider } from '../../../../../../library/themes';
import data from '../../../Menu/common/menuData';
import type { StyledComponent } from '@emotion/styled-base/src/utils';
const Root: StyledComponent<{ [key: string]: any }> = styled('div')({
paddingBottom: pxToEm(130)
});
const DemoLayout = (props: Object) => <Root {...props} />;
export default {
id: 'rtl',
title: 'Bidirectionality',
description: `Dropdowns support right-to-left (RTL) languages. The placement of
the menu as well as the menu itself will be reversed when the \`direction\`
theme variable is set to \`rtl\`.`,
scope: { Button, data, DemoLayout, Dropdown, ThemeProvider },
source: `
<DemoLayout dir="rtl">
<ThemeProvider theme={{ direction: 'rtl' }}>
<Dropdown data={data} isOpen>
<Button>Menu</Button>
</Dropdown>
</ThemeProvider>
</DemoLayout>`
};
|
src/components/NewToDo.js
|
RedGeekPanda/reactive-todos
|
import React from 'react';
import {ENTER} from '../constants/KeyboardKeys';
import './NewToDo.css';
export default class NewToDo extends React.Component {
render() {
return (
<div className="NewToDo">
<input className="NewToDo" type="text"
placeholder="What needs to be done?"
onKeyDown={this.handleKeyDown}/>
</div>
);
}
handleKeyDown = ({keyCode, target}) => {
if (keyCode === ENTER && target.value) {
this.props.addTodo(target.value);
target.value = '';
}
};
}
|
src/components/NoMatch.js
|
yyssc/sanhu
|
import React from 'react';
export default class NoMatch extends React.Component {
render() {
return (
<div>404, 你要请求的内容未找到...</div>
);
}
};
|
modules/Plan.js
|
SomethingSexy/react-planner
|
import PropTypes from 'prop-types';
import React from 'react';
const style = {
height: '100%',
width: '100%',
backgroundColor: 'white',
textAlign: 'center',
color: 'inherit',
cursor: 'pointer'
};
const Plan = ({ plan, highlightedPlan, onSelectPlan, onOpenPlan, render }) => {
let localStyle = style;
if (plan.id === highlightedPlan) {
localStyle = Object.assign({}, localStyle, { backgroundColor: 'hsl(204, 86%, 53%)', color: 'white' });
}
return (React.createElement("div", { style: localStyle, onClick: onSelectPlan.bind(onSelectPlan, plan.id), onDoubleClick: onOpenPlan.bind(onOpenPlan, plan.id) }, render ? render(plan, { expanded: plan.toTime - plan.time > 1 }) : null));
};
Plan.propTypes = {
onRemovePlan: PropTypes.func,
onSelectPlan: PropTypes.func,
plan: PropTypes.shape({ label: PropTypes.string }),
render: PropTypes.func
};
export default Plan;
//# sourceMappingURL=Plan.js.map
|
src/scripts/utils/requireAuth.js
|
poldracklab/crn_app
|
// dependencies ----------------------------------------------------
import React from 'react';
import userStore from '../user/user.store.js';
// require auth ----------------------------------------------------
var requireAuth = (Component, role) => {
return class Authenticated extends React.Component {
static willTransitionTo(transition) {
role = role ? role : 'user';
if (!userStore.data.token) { // if not logged in
transition.redirect('signIn', {});
} else if (role === 'admin' && (!userStore.data.scitran || !userStore.data.scitran.root)) {
transition.redirect('signIn', {});
}
}
render () {
return <Component />;
}
};
};
export default requireAuth;
|
src/renderer/ui/components/modals/UpdateModal.js
|
petuhovskiy/Google-Play-Music-Desktop-Player-UNOFFICIAL-
|
import React, { Component } from 'react';
import Dialog from './ThemedDialog';
import FlatButton from 'material-ui/FlatButton';
export default class UpdateModal extends Component {
constructor(...args) {
super(...args);
this.state = {
open: false,
};
}
componentDidMount() {
Emitter.on('update:available', this.show);
}
componentWillUnmount() {
Emitter.off('update:available', this.show);
}
handleClose = () => {
this.setState({
open: false,
});
}
show = () => {
this.setState({
open: true,
});
}
updateNow = () => {
Emitter.fire('update:trigger');
}
updateLater = () => {
Emitter.fire('update:wait');
this.handleClose();
}
render() {
const actions = [
<FlatButton
label={TranslationProvider.query('button-text-not-now')}
labelStyle={{ fontSize: 12 }}
style={{ height: 26, lineHeight: '26px', opacity: 0.7 }}
onTouchTap={this.updateLater}
/>,
<FlatButton
label={TranslationProvider.query('button-text-lets-do-this')}
primary
keyboardFocused
onTouchTap={this.updateNow}
/>,
];
return (
<Dialog
title={TranslationProvider.query('modal-confirmUpdate-title')}
actions={actions}
open={this.state.open}
onRequestClose={this.handleClose}
>
<div dangerouslySetInnerHTML={{ __html: TranslationProvider.query('modal-confirmUpdate-content') }}></div>
</Dialog>
);
}
}
|
packages/crisimus-react/src/index.js
|
Prefinem/crisimus
|
import 'babel-polyfill';
import App from './components/App';
import { Provider } from 'react-redux';
import React from 'react';
import { render } from 'react-dom';
import { store } from './store';
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('app')
);
|
App/Containers/ListviewGridExample.js
|
oreofish/v2exClient
|
// @flow
import React from 'react'
import { View, Text, ListView } from 'react-native'
import { connect } from 'react-redux'
// For empty lists
import AlertMessage from '../Components/AlertMessage'
// Styles
import styles from './Styles/ListviewGridExampleStyle'
class ListviewGridExample extends React.Component {
state: {
dataSource: Object
}
constructor (props) {
super(props)
/* ***********************************************************
* STEP 1
* This is an array of objects with the properties you desire
* Usually this should come from Redux mapStateToProps
*************************************************************/
const dataObjects = [
{title: 'First Title', description: 'First Description'},
{title: 'Second Title', description: 'Second Description'},
{title: 'Third Title', description: 'Third Description'},
{title: 'Fourth Title', description: 'Fourth Description'},
{title: 'Fifth Title', description: 'Fifth Description'},
{title: 'Sixth Title', description: 'Sixth Description'},
{title: 'Seventh Title', description: 'Seventh Description'},
{title: 'Eighth Title', description: 'Eighth Description'},
{title: 'Ninth Title', description: 'Ninth Description'},
{title: 'Tenth Title', description: 'Tenth Description'},
{title: 'Eleventh Title', description: 'Eleventh Description'},
{title: '12th Title', description: '12th Description'},
{title: '13th Title', description: '13th Description'},
{title: '14th Title', description: '14th Description'},
{title: '15th Title', description: '15th Description'},
{title: '16th Title', description: '16th Description'},
{title: '17th Title', description: '17th Description'},
{title: '18th Title', description: '18th Description'},
{title: '19th Title', description: '19th Description'},
{title: '20th Title', description: '20th Description'},
{title: 'BLACKJACK!', description: 'BLACKJACK! Description'}
]
/* ***********************************************************
* STEP 2
* Teach datasource how to detect if rows are different
* Make this function fast! Perhaps something like:
* (r1, r2) => r1.id !== r2.id}
*************************************************************/
const rowHasChanged = (r1, r2) => r1 !== r2
// DataSource configured
const ds = new ListView.DataSource({rowHasChanged})
// Datasource is always in state
this.state = {
dataSource: ds.cloneWithRows(dataObjects)
}
}
/* ***********************************************************
* STEP 3
* `_renderRow` function -How each cell/row should be rendered
* It's our best practice to place a single component here:
*
* e.g.
return <MyCustomCell title={rowData.title} description={rowData.description} />
*************************************************************/
_renderRow (rowData) {
return (
<View style={styles.row}>
<Text style={styles.boldLabel}>{rowData.title}</Text>
<Text style={styles.label}>{rowData.description}</Text>
</View>
)
}
/* ***********************************************************
* STEP 4
* If your datasource is driven by Redux, you'll need to
* reset it when new data arrives.
* DO NOT! place `cloneWithRows` inside of render, since render
* is called very often, and should remain fast! Just replace
* state's datasource on newProps.
*
* e.g.
componentWillReceiveProps (newProps) {
if (newProps.someData) {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newProps.someData)
})
}
}
*************************************************************/
// Used for friendly AlertMessage
// returns true if the dataSource is empty
_noRowData () {
return this.state.dataSource.getRowCount() === 0
}
render () {
return (
<View style={styles.container}>
<AlertMessage title='Nothing to See Here, Move Along' show={this._noRowData()} />
<ListView
contentContainerStyle={styles.listContent}
dataSource={this.state.dataSource}
renderRow={this._renderRow}
pageSize={15}
/>
</View>
)
}
}
const mapStateToProps = (state) => {
return {
// ...redux state to props here
}
}
export default connect(mapStateToProps)(ListviewGridExample)
|
src/containers/Home/Home.js
|
xaevir/brasiliausa
|
import React, { Component } from 'react';
export default class Home extends Component {
render() {
const styles = require('./Home.scss');
return (
<div className={styles.home + ' container'}>
<div className="header">
<img src={require('./home-page-banner.png')} />
</div>
<div className="row clearfix">
<div className="col-md-4">
<h2>Espresso Machines</h2>
<img src={require('./home-page-espresso.jpg')} className="img-responsive" />
<p>
We stock a vast line of traditional and automatic Brasilia espresso machines,
with models ranging from simple and dependable to elegant, art decorative,
and technologically advanced. Regardless of your needs, we have a Brasilia espresso
machine
that will both meet and exceed your expectations. Whether you are a national
account, a distributor, an independent coffee bar, restaurant, or simply a home
user, our commitment to your espresso program remains unsurpassed.
</p>
</div>
<div className="col-md-4">
<h2>Zumex<br />Juicers</h2>
<img src={require('./juicer.png')} className="img-responsive" />
<p>
Interested in adding some healthy items to your menu offering? How about freshly squeezed juices!? Ask us about our new line of Zumex citrus and multi-fruit juicers! We now stock equipment, parts, and offer service on all Zumex products. Based in Valencia, Spain, Zumex is the leading manufacturer of citrus juicers and innovators of the world’s first juicers with ASP antibacterial technology.
</p>
</div>
<div className="col-md-4">
<h2>World Class Support</h2>
<img src={require('./home-page-service.jpg')} className="img-responsive" />
<p>
The technical department at Brasilia USA® takes pride in providing the highest level of service and support to its customers. All of our factory trained technicians have completed rigorous training courses in both the US and Italy, and attend annual seminars at our factory outside Milan to keep up with the latest trends and technology in espresso equipment service, specifically Brasilia® espresso machines.
</p>
</div>
</div>
</div>
);
}
}
|
app/javascript/mastodon/features/compose/components/action_bar.js
|
masto-donte-com-br/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import DropdownMenuContainer from '../../../containers/dropdown_menu_container';
import { defineMessages, injectIntl } from 'react-intl';
const messages = defineMessages({
edit_profile: { id: 'account.edit_profile', defaultMessage: 'Edit profile' },
pins: { id: 'navigation_bar.pins', defaultMessage: 'Pinned posts' },
preferences: { id: 'navigation_bar.preferences', defaultMessage: 'Preferences' },
follow_requests: { id: 'navigation_bar.follow_requests', defaultMessage: 'Follow requests' },
favourites: { id: 'navigation_bar.favourites', defaultMessage: 'Favourites' },
lists: { id: 'navigation_bar.lists', defaultMessage: 'Lists' },
blocks: { id: 'navigation_bar.blocks', defaultMessage: 'Blocked users' },
domain_blocks: { id: 'navigation_bar.domain_blocks', defaultMessage: 'Hidden domains' },
mutes: { id: 'navigation_bar.mutes', defaultMessage: 'Muted users' },
filters: { id: 'navigation_bar.filters', defaultMessage: 'Muted words' },
logout: { id: 'navigation_bar.logout', defaultMessage: 'Logout' },
bookmarks: { id: 'navigation_bar.bookmarks', defaultMessage: 'Bookmarks' },
});
export default @injectIntl
class ActionBar extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
onLogout: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleLogout = () => {
this.props.onLogout();
}
render () {
const { intl } = this.props;
let menu = [];
menu.push({ text: intl.formatMessage(messages.edit_profile), href: '/settings/profile' });
menu.push({ text: intl.formatMessage(messages.preferences), href: '/settings/preferences' });
menu.push({ text: intl.formatMessage(messages.pins), to: '/pinned' });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.follow_requests), to: '/follow_requests' });
menu.push({ text: intl.formatMessage(messages.favourites), to: '/favourites' });
menu.push({ text: intl.formatMessage(messages.bookmarks), to: '/bookmarks' });
menu.push({ text: intl.formatMessage(messages.lists), to: '/lists' });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.mutes), to: '/mutes' });
menu.push({ text: intl.formatMessage(messages.blocks), to: '/blocks' });
menu.push({ text: intl.formatMessage(messages.domain_blocks), to: '/domain_blocks' });
menu.push({ text: intl.formatMessage(messages.filters), href: '/filters' });
menu.push(null);
menu.push({ text: intl.formatMessage(messages.logout), action: this.handleLogout });
return (
<div className='compose__action-bar'>
<div className='compose__action-bar-dropdown'>
<DropdownMenuContainer items={menu} icon='chevron-down' size={16} direction='right' />
</div>
</div>
);
}
}
|
modules/admin/client/components/Admin.component.js
|
Trustroots/trustroots
|
import React from 'react';
import AdminHeader from './AdminHeader.component.js';
import bmoDancing from '../images/bmo-dancing.gif';
export default function Admin() {
return (
<>
<AdminHeader />
<div className="container container-spacer">
<p>
<img src={bmoDancing} alt="" width="200" />
</p>
<p>Welcome, friend! 👋</p>
<ul>
<li>
<a href="https://team.trustroots.org/">Team Guide</a>
</li>
<li>
<a href="https://trustroots.zendesk.com/inbox/">Support queue</a>
</li>
<li>
<a href="https://ideas.trustroots.org/wp-admin/">Blog admin</a>
</li>
<li>
<a href="https://ideas.trustroots.org/wp-admin/admin.php?page=mailpoet-newsletters">
Newsletter admin
</a>
</li>
<li>
<a href="https://grafana.trustroots.org/">Statistics</a>
</li>
</ul>
<p>
<strong>
<em>Remember to logout on public computers!</em>
</strong>
</p>
</div>
</>
);
}
Admin.propTypes = {};
|
lib/PasswordStrength/tests/password-strength-test.js
|
folio-org/stripes-components
|
import React from 'react';
import { describe, beforeEach, it } from 'mocha';
import { expect } from 'chai';
import { Field } from 'redux-form';
import { Row, Col } from '../../LayoutGrid/index';
import TestForm from '../../../tests/TestForm';
import PasswordStrength from '../PasswordStrength';
import PasswordStrengthInteractor from './interactor';
import { mountWithContext } from '../../../tests/helpers';
import translation from '../../../translations/stripes-components/en';
describe('password strength', () => {
beforeEach(async () => {
await mountWithContext(
<Row>
<Col xs={12}>
<div data-test-password-strength>
<TestForm>
<Field
component={PasswordStrength}
type="password"
id="current-password"
name="currentPassword"
label="test"
autoFocus
/>
</TestForm>
</div>
</Col>
</Row>
);
});
it('component should be presented', () => {
expect(PasswordStrengthInteractor.isPresent).to.be.true;
});
it('textInput should be presented', () => {
expect(PasswordStrengthInteractor.textInput.isPresent).to.be.true;
});
it('password strength meter should not be presented', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.false;
});
describe('very week password', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('1');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('password strength meter should be presented through password insertion', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.true;
});
it('password strength meter should have proper text', () => {
expect(PasswordStrengthInteractor.passwordStrength.text.text).to.equal(translation['passwordStrength.veryWeak']);
});
it('password strength meter should have label', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.isPresent).to.be.true;
});
it('password strength meter should have proper label text', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.text).to.be.equal(translation['passwordStrength.label']);
});
it('password strength meter should have proper indicator', () => {
expect(PasswordStrengthInteractor.passwordStrength.veryWeakIndicator.isPresent).to.be.true;
});
});
describe('week password', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('test1test');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('password strength meter should be presented through password insertion', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.true;
});
it('password strength meter should have proper text', () => {
expect(PasswordStrengthInteractor.passwordStrength.text.text).to.equal(translation['passwordStrength.weak']);
});
it('password strength meter should have label', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.isPresent).to.be.true;
});
it('password strength meter should have proper label text', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.text).to.be.equal(translation['passwordStrength.label']);
});
it('password strength meter should have proper indicator', () => {
expect(PasswordStrengthInteractor.passwordStrength.weakIndicator.isPresent).to.be.true;
});
});
describe('reasonable password', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('test1test1');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('password strength meter should be presented through password insertion', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.true;
});
it('password strength meter should have proper text', () => {
expect(
PasswordStrengthInteractor.passwordStrength.text.text
).to.equal(translation['passwordStrength.reasonable']);
});
it('password strength meter should have label', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.isPresent).to.be.true;
});
it('password strength meter should have proper label text', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.text).to.be.equal(translation['passwordStrength.label']);
});
it('password strength meter should have proper indicator', () => {
expect(PasswordStrengthInteractor.passwordStrength.reasonableIndicator.isPresent).to.be.true;
});
});
describe('strong password', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('test1test1test');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('password strength meter should be presented through password insertion', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.true;
});
it('password strength meter should have proper text', () => {
expect(PasswordStrengthInteractor.passwordStrength.text.text).to.equal(translation['passwordStrength.strong']);
});
it('password strength meter should have label', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.isPresent).to.be.true;
});
it('password strength meter should have proper label text', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.text).to.be.equal(translation['passwordStrength.label']);
});
it('password strength meter should have proper indicator', () => {
expect(PasswordStrengthInteractor.passwordStrength.strongIndicator.isPresent).to.be.true;
});
});
describe('very strong password', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('test1test1test@test1test1test');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('password strength meter should be presented through password insertion', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.true;
});
it('password strength meter should have proper text', () => {
expect(
PasswordStrengthInteractor.passwordStrength.text.text
).to.equal(translation['passwordStrength.veryStrong']);
});
it('password strength meter should have label', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.isPresent).to.be.true;
});
it('password strength meter should have proper label text', () => {
expect(PasswordStrengthInteractor.passwordStrength.label.text).to.be.equal(translation['passwordStrength.label']);
});
it('password strength meter should have proper indicator', () => {
expect(PasswordStrengthInteractor.passwordStrength.veryStrongIndicator.isPresent).to.be.true;
});
});
describe('password deletion', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('test1test1test@test1test1test');
await PasswordStrengthInteractor.textInput.fillInput('');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('password strength meter should not be presented', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.false;
});
});
});
describe('password strength hidden', () => {
beforeEach(async () => {
await mountWithContext(
<Row>
<Col xs={12}>
<div data-test-password-strength>
<TestForm>
<Field
component={PasswordStrength}
type="password"
id="current-password"
name="currentPassword"
label="test"
autoFocus
inputColProps={{ xs: 6 }}
passwordStrengthHidden
/>
</TestForm>
</div>
</Col>
</Row>
);
});
it('component should be presented', () => {
expect(PasswordStrengthInteractor.isPresent).to.be.true;
});
it('textInput should be presented', () => {
expect(PasswordStrengthInteractor.textInput.isPresent).to.be.true;
});
it('password strength meter should not be presented', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.false;
});
describe('password insertion', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('test');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('textInput should be presented', () => {
expect(PasswordStrengthInteractor.textInput.isPresent).to.be.true;
});
it('password strength meter should not be presented through password insertion', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.false;
});
});
describe('password deletion', () => {
beforeEach(async () => {
await PasswordStrengthInteractor.textInput.focusInput();
await PasswordStrengthInteractor.textInput.fillInput('test1test1test@test1test1test');
await PasswordStrengthInteractor.textInput.fillInput('');
await PasswordStrengthInteractor.textInput.blurInput();
});
it('textInput should be presented', () => {
expect(PasswordStrengthInteractor.textInput.isPresent).to.be.true;
});
it('password strength meter should not be presented', () => {
expect(PasswordStrengthInteractor.passwordStrength.isPresent).to.be.false;
});
});
});
|
node_modules/eslint-config-airbnb/test/test-react-order.js
|
xtreemze/TAXi
|
import test from 'tape';
import { CLIEngine } from 'eslint';
import eslintrc from '../';
import reactRules from '../rules/react';
import reactA11yRules from '../rules/react-a11y';
const cli = new CLIEngine({
useEslintrc: false,
baseConfig: eslintrc,
// This rule fails when executing on text.
rules: { indent: 0 },
});
function lint(text) {
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
const linter = cli.executeOnText(text);
return linter.results[0];
}
function wrapComponent(body) {
return `
import React from 'react';
export default class MyComponent extends React.Component {
/* eslint no-empty-function: 0 */
${body}
}
`;
}
test('validate react prop order', (t) => {
t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => {
t.plan(2);
t.deepEqual(reactRules.plugins, ['react']);
t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']);
});
t.test('passes a good component', (t) => {
t.plan(3);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
someMethod() {}
renderDogs() {}
render() { return <div />; }
`));
t.notOk(result.warningCount, 'no warnings');
t.notOk(result.errorCount, 'no errors');
t.deepEquals(result.messages, [], 'no messages in results');
});
t.test('order: when random method is first', t => {
t.plan(2);
const result = lint(wrapComponent(`
someMethod() {}
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
t.test('order: when random method after lifecycle methods', t => {
t.plan(2);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
someMethod() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
});
|
src/components/common/mediaPicker/MediaPickerResultsContainer.js
|
mitmedialab/MediaCloud-Web-Tools
|
import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import { connect } from 'react-redux';
import { toggleMedia, selectMedia, selectMediaPickerQueryArgs, resetMediaPickerQueryArgs, resetMediaPickerSources, resetMediaPickerCollections, resetMetadataShortlist } from '../../../actions/systemActions';
import { PICK_SOURCE_AND_COLLECTION, PICK_FEATURED } from '../../../lib/explorerUtil';
import * as fetchConstants from '../../../lib/fetchConstants';
import AllMediaSearchResultsContainer from './results/AllMediaSearchResultsContainer';
import FeaturedFavoriteGeoSearchResultsContainer from './results/FeaturedFavoriteGeoSearchResultsContainer';
import { VALID_COLLECTION_IDS } from '../../../lib/tagUtil';
class MediaPickerResultsContainer extends React.Component {
UNSAFE_componentWillMount() {
this.correlateSelection(this.props);
}
UNSAFE_componentWillReceiveProps(nextProps) {
// const { handleMediaConcurrency } = this.props;
if (nextProps.selectedMediaQueryType !== this.props.selectedMediaQueryType) {
this.updateMediaQuery({ type: nextProps.selectedMediaQueryType, tags: {}, keyword: '' });
}
if (nextProps.selectedMedia !== this.props.selectedMedia
// if the results have changed from a keyword entry, we need to update the UI
|| (nextProps.sourceResults && nextProps.sourceResults.lastFetchSuccess !== this.props.sourceResults.lastFetchSuccess)) {
this.correlateSelection(nextProps);
}
}
componentWillUnmount() {
const { resetComponents } = this.props;
resetComponents();
}
updateMediaQuery(values) {
const { updateMediaQuerySelection } = this.props;
updateMediaQuerySelection(values);
}
correlateSelection(whichProps) {
let whichList = {};
if (!whichProps.selectedMediaQueryType) return 0;
switch (whichProps.selectedMediaQueryType) {
/* case PICK_COUNTRY:
whichList = whichProps.collectionResults;
break; */
case PICK_SOURCE_AND_COLLECTION:
whichList = whichProps.collectionResults;
break;
default:
break;
}
// if selected media has changed, update current results
if (whichProps.selectedMedia && whichProps.selectedMedia.length > 0
// we can't be sure we have received results yet
&& whichList.list && whichList.list.length > 0) {
// sync up selectedMedia and push to result sets.
whichList.list.map((m) => {
const mediaIndex = whichProps.selectedMedia.findIndex(q => q.id === m.id);
if (mediaIndex < 0) {
this.props.toggleConcurrency(m, false);
} else if (mediaIndex >= 0) {
this.props.toggleConcurrency(m, true);
}
return m;
});
}
// if selected metadata has changed, update here
// selected metadata search settings has to be handled
if (whichProps.selectedMedia && whichProps.selectedMedia.length > 0) {
// sync up incoming selectedMedia and push to result sets.
// for each *metadata search item*, push it into query args
// whichProps.selectedMedia.filter(m => m.customColl).map(s => this.updateMediaQuery({ ...s, type: this.props.selectedMediaQueryType }));
}
return 0;
}
render() {
const { selectedMediaQueryType, toggleConcurrency, updateMediaQuerySelection, handleToggleSelected } = this.props;
let content = null;
const whichMedia = {};
whichMedia.fetchStatus = null;
switch (selectedMediaQueryType) {
/* case PICK_COUNTRY:
content = (
<CountryCollectionSearchResultsContainer
whichTagSet={TAG_SET_ABYZ_GEO_COLLECTIONS}
onToggleSelected={handleToggleSelected}
/>
);
break; */
case PICK_SOURCE_AND_COLLECTION:
content = (
<AllMediaSearchResultsContainer
whichTagSet={VALID_COLLECTION_IDS}
onToggleSelected={handleToggleSelected}
handleMediaConcurrency={toggleConcurrency}
updateMediaQuerySelection={updateMediaQuerySelection}
/>
);
break;
case PICK_FEATURED:
content = (
<FeaturedFavoriteGeoSearchResultsContainer
whichTagSet={VALID_COLLECTION_IDS}
handleMediaConcurrency={toggleConcurrency}
onToggleSelected={handleToggleSelected}
/>
);
break;
default:
break;
}
return (
<div className="select-media-container">
{content}
</div>
);
}
}
MediaPickerResultsContainer.propTypes = {
intl: PropTypes.object.isRequired,
toggleConcurrency: PropTypes.func.isRequired,
handleToggleSelected: PropTypes.func.isRequired,
updateMediaQuerySelection: PropTypes.func.isRequired,
selectedMediaQueryType: PropTypes.number,
resetComponents: PropTypes.func.isRequired,
featured: PropTypes.object,
favoritedCollections: PropTypes.object,
favoritedSources: PropTypes.object,
collectionResults: PropTypes.object,
sourceResults: PropTypes.object,
selectedMedia: PropTypes.array,
};
const mapStateToProps = state => ({
fetchStatus: (state.system.mediaPicker.sourceQueryResults.fetchStatus === fetchConstants.FETCH_SUCCEEDED || state.system.mediaPicker.collectionQueryResults.fetchStatus === fetchConstants.FETCH_SUCCEEDED || state.system.mediaPicker.favoritedCollections.fetchStatus === fetchConstants.FETCH_SUCCEEDED) ? fetchConstants.FETCH_SUCCEEDED : fetchConstants.FETCH_INVALID,
selectedMedia: state.system.mediaPicker.selectMedia.list,
selectedMediaQueryType: state.system.mediaPicker.selectMediaQuery ? state.system.mediaPicker.selectMediaQuery.args.type : null,
collectionResults: state.system.mediaPicker.collectionQueryResults,
featured: state.system.mediaPicker.featured ? state.system.mediaPicker.featured : null,
sourceResults: state.system.mediaPicker.sourceQueryResults,
favoritedCollections: state.system.mediaPicker.favoritedCollections ? state.system.mediaPicker.favoritedCollections : null,
favoritedSources: state.system.mediaPicker.favoritedSources ? state.system.mediaPicker.favoritedSources : null,
});
const mapDispatchToProps = dispatch => ({
updateMediaQuerySelection: (values) => {
if (values) {
dispatch(selectMediaPickerQueryArgs(values));
}
},
toggleConcurrency: (selectedMedia, onOrOff) => {
if (selectedMedia) {
dispatch(toggleMedia({ selectedMedia, setSelected: onOrOff })); // for search results selectedMedia >> results
}
},
handleToggleSelected: (selectedMedia) => {
if (selectedMedia) {
dispatch(selectMedia(selectedMedia)); // disable button too
}
},
resetComponents: () => {
dispatch(resetMediaPickerQueryArgs());
dispatch(resetMediaPickerSources());
dispatch(resetMediaPickerCollections());
dispatch(resetMetadataShortlist());
},
});
export default
injectIntl(
connect(mapStateToProps, mapDispatchToProps)(
MediaPickerResultsContainer
)
);
|
src/js/components/input/autocomplete/input_autocomplete_values.js
|
working-minds/realizejs
|
import React, { Component } from 'react';
import PropTypes from '../../../prop_types';
import $ from 'jquery';
import {} from '../../../components';
export default class InputAutocompleteValues extends Component {
static propTypes = {
id: PropTypes.string,
name: PropTypes.string,
multiple: PropTypes.bool,
selectedOptions: PropTypes.array,
};
static defaultProps = {
multiple: false,
selectedOptions: [],
};
selectedOptionsValues() {
return $.map(
this.props.selectedOptions,
(selectedOption) => selectedOption.value
);
}
valueInputName() {
let inputName = this.props.name;
if (this.props.multiple) {
inputName += '[]';
}
return inputName;
}
renderValueInputs() {
const valueInputs = [];
const selectedOptions = this.props.selectedOptions;
for (let i = 0; i < selectedOptions.length; i++) {
const option = selectedOptions[i];
valueInputs.push(<option value={option.value} key={option.name} />);
}
return valueInputs;
}
render() {
return (
<select
multiple
id={this.props.id}
name={this.valueInputName()}
value={this.selectedOptionsValues()}
readOnly
style={{ display: 'none' }}
>
{this.renderValueInputs()}
</select>
);
}
}
|
Libraries/Modal/Modal.js
|
browniefed/react-native
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Modal
* @flow
*/
'use strict';
const I18nManager = require('I18nManager');
const Platform = require('Platform');
const PropTypes = require('react/lib/ReactPropTypes');
const React = require('React');
const StyleSheet = require('StyleSheet');
const UIManager = require('UIManager');
const View = require('View');
const deprecatedPropType = require('deprecatedPropType');
const requireNativeComponent = require('requireNativeComponent');
const RCTModalHostView = requireNativeComponent('RCTModalHostView', null);
/**
* The Modal component is a simple way to present content above an enclosing view.
*
* _Note: If you need more control over how to present modals over the rest of your app,
* then consider using a top-level Navigator. Go [here](/react-native/docs/navigator-comparison.html) to compare navigation options._
*
* ```javascript
* import React, { Component } from 'react';
* import { Modal, Text, TouchableHighlight, View } from 'react-native';
*
* class ModalExample extends Component {
*
* constructor(props) {
* super(props);
* this.state = {modalVisible: false};
* }
*
* setModalVisible(visible) {
* this.setState({modalVisible: visible});
* }
*
* render() {
* return (
* <View style={{marginTop: 22}}>
* <Modal
* animationType={"slide"}
* transparent={false}
* visible={this.state.modalVisible}
* onRequestClose={() => {alert("Modal has been closed.")}}
* >
* <View style={{marginTop: 22}}>
* <View>
* <Text>Hello World!</Text>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(!this.state.modalVisible)
* }}>
* <Text>Hide Modal</Text>
* </TouchableHighlight>
*
* </View>
* </View>
* </Modal>
*
* <TouchableHighlight onPress={() => {
* this.setModalVisible(true)
* }}>
* <Text>Show Modal</Text>
* </TouchableHighlight>
*
* </View>
* );
* }
* }
* ```
*/
class Modal extends React.Component {
static propTypes = {
/**
* The `animationType` prop controls how the modal animates.
*
* - `slide` slides in from the bottom
* - `fade` fades into view
* - `none` appears without an animation
*/
animationType: PropTypes.oneOf(['none', 'slide', 'fade']),
/**
* The `transparent` prop determines whether your modal will fill the entire view. Setting this to `true` will render the modal over a transparent background.
*/
transparent: PropTypes.bool,
/**
* The `visible` prop determines whether your modal is visible.
*/
visible: PropTypes.bool,
/**
* The `onRequestClose` prop allows passing a function that will be called once the modal has been dismissed.
*
* _On the Android platform, this is a required function._
*/
onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func,
/**
* The `onShow` prop allows passing a function that will be called once the modal has been shown.
*/
onShow: PropTypes.func,
animated: deprecatedPropType(
PropTypes.bool,
'Use the `animationType` prop instead.'
),
/**
* The `supportedOrientations` prop allows the modal to be rotated to any of the specified orientations.
* On iOS, the modal is still restricted by what's specified in your app's Info.plist's UISupportedInterfaceOrientations field.
* @platform ios
*/
supportedOrientations: PropTypes.arrayOf(PropTypes.oneOf(['portrait', 'portrait-upside-down', 'landscape', 'landscape-left', 'landscape-right'])),
/**
* The `onOrientationChange` callback is called when the orientation changes while the modal is being displayed.
* The orientation provided is only 'portrait' or 'landscape'. This callback is also called on initial render, regardless of the current orientation.
* @platform ios
*/
onOrientationChange: PropTypes.func,
};
static defaultProps = {
visible: true,
};
render(): ?ReactElement<any> {
if (this.props.visible === false) {
return null;
}
const containerStyles = {
backgroundColor: this.props.transparent ? 'transparent' : 'white',
top: Platform.OS === 'android' && Platform.Version >= 19 ? UIManager.RCTModalHostView.Constants.StatusBarHeight : 0,
};
let animationType = this.props.animationType;
if (!animationType) {
// manually setting default prop here to keep support for the deprecated 'animated' prop
animationType = 'none';
if (this.props.animated) {
animationType = 'slide';
}
}
return (
<RCTModalHostView
animationType={animationType}
transparent={this.props.transparent}
onRequestClose={this.props.onRequestClose}
onShow={this.props.onShow}
style={styles.modal}
onStartShouldSetResponder={this._shouldSetResponder}
supportedOrientations={this.props.supportedOrientations}
onOrientationChange={this.props.onOrientationChange}
>
<View style={[styles.container, containerStyles]}>
{this.props.children}
</View>
</RCTModalHostView>
);
}
// We don't want any responder events bubbling out of the modal.
_shouldSetResponder(): boolean {
return true;
}
}
const side = I18nManager.isRTL ? 'right' : 'left';
const styles = StyleSheet.create({
modal: {
position: 'absolute',
},
container: {
position: 'absolute',
[side] : 0,
top: 0,
}
});
module.exports = Modal;
|
src/list/__tests__/ListItem.js
|
kosiakMD/react-native-elements
|
import React from 'react';
import { Text } from 'react-native';
import { shallow } from 'enzyme';
import toJson from 'enzyme-to-json';
import ListItem from '../ListItem';
describe('ListItem component', () => {
it('should render without issues', () => {
const component = shallow(<ListItem />);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render with avatar', () => {
const component = shallow(
<ListItem
avatar="avatar_uri"
containerStyle={{ backgroundColor: 'peru' }}
wrapperStyle={{ backgroundColor: 'peru' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render with left icon', () => {
const component = shallow(
<ListItem
leftIcon={{
name: 'wifi',
type: 'font-awesome',
color: 'red',
size: 20,
}}
wrapperStyle={{ backgroundColor: 'peru' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render with left icon component', () => {
const component = shallow(
<ListItem
leftIcon={<Text>I'm left icon</Text>}
wrapperStyle={{ backgroundColor: 'peru' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render with right icon component', () => {
const component = shallow(
<ListItem
rightIcon={<Text>I'm right icon</Text>}
wrapperStyle={{ backgroundColor: 'peru' }}
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render with title and subtitle', () => {
const component = shallow(
<ListItem
title="title test"
subtitle="title test"
rightTitle="title"
wrapperStyle={{ backgroundColor: 'peru' }}
titleStyle={{ backgroundColor: 'peru' }}
subtitleStyle={{ backgroundColor: 'peru' }}
fontFamily="arial"
/>
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
it('should render with textInput', () => {
const component = shallow(
<ListItem textInput hideChevron switchButton fontFamily="arial" />
);
expect(component.length).toBe(1);
expect(toJson(component)).toMatchSnapshot();
});
});
|
__tests__/index.android.js
|
connectordb/connectordb-android
|
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 />
);
});
|
src/index.js
|
HurricaneJames/react-action-tabs
|
import React from 'react';
import App from './App';
React.render(<App />, document.getElementById('root'));
|
app/router/persons-route.js
|
KleeGroup/focus-demo-app
|
import React from 'react';
import PersonDetailView from '../views/person/detail';
const route = [
{
path: 'persons/:id',
component: (props) => (<PersonDetailView id={parseInt(props.params.id)} {...props}/>)
}
];
export default route;
|
src/svg-icons/device/signal-wifi-1-bar.js
|
ngbrown/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi1Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/><path d="M6.67 14.86L12 21.49v.01l.01-.01 5.33-6.63C17.06 14.65 15.03 13 12 13s-5.06 1.65-5.33 1.86z"/>
</SvgIcon>
);
DeviceSignalWifi1Bar = pure(DeviceSignalWifi1Bar);
DeviceSignalWifi1Bar.displayName = 'DeviceSignalWifi1Bar';
DeviceSignalWifi1Bar.muiName = 'SvgIcon';
export default DeviceSignalWifi1Bar;
|
app/src/components/signUp/SignUp.spec.js
|
joedunu/react-redux-example
|
import React from 'react'
import {shallow} from 'enzyme'
import {shallowToJson} from 'enzyme-to-json'
import configureMockStore from 'redux-mock-store'
import SignUP from './SignUP'
describe('User Registration Form', () => {
const mockStore = configureMockStore([])
let store
let combinedReducersState = {
form: {}
}
beforeEach(() => {
store = mockStore(combinedReducersState)
})
test('should pass snapshot test', () => {
const component = shallow(<SignUP
store={store}
goTo={jest.fn()}
/>)
const tree = shallowToJson(component)
expect(tree).toMatchSnapshot()
})
})
|
examples/async/index.js
|
przeor/redux
|
import 'babel-core/polyfill';
import React from 'react';
import Root from './containers/Root';
React.render(
<Root />,
document.getElementById('root')
);
|
src/Components/App.js
|
NickGlenn/React-Project
|
import React, { Component } from 'react';
export default class App extends Component {
render () {
return (
<div className='app'>
<h1 className='app__greeting'>
Example Application
</h1>
{this.props.children}
</div>
);
}
}
|
app/components/ItemMercado.js
|
cosio55/app-informacion-bitso
|
import React, { Component } from 'react';
import styles from './ItemMercado.css';
class ItemMercado extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={styles.itemMercado}>
<div className={styles.nombre}>
<p>{this.props.nombre}</p>
<p className={styles.book_fancy}>{this.props.book_fancy}</p>
</div>
<div className={styles.precioMasReciente}>
<p className={styles.precio}>${this.props.ultimo}</p>
</div>
<div className={styles.cambioPrecioContenedor}>
<div className={styles.cambioPrecio}>
{this.props.porcentaje}
</div>
</div>
</div>
);
}
}
export default ItemMercado;
|
client/pages/examples/threejs/graphing/elements/oscilloscope.js
|
fdesjardins/webgl
|
import React from 'react'
import * as THREE from 'three'
import threeOrbitControls from 'three-orbit-controls'
import { createAxes, createLineGraph, createLabel } from '../utils'
const WHITE = 0xffffff
const BLACK = 0x000000
const init = ({ state }) => {
const canvas = document.getElementById('oscilloscope')
let scene = new THREE.Scene()
const range = [-2 * Math.PI, 2 * Math.PI]
const gridSize = Math.PI / 4
// left, right, top, bottom
const margin = [1, 1, 1, 1]
const camera = new THREE.OrthographicCamera(
range[0] - margin[0],
range[1] + margin[1],
range[1] + margin[2],
range[0] - margin[3],
0.1,
1000
)
camera.position.z = 500
camera.position.x = 0
camera.position.y = 0
camera.updateProjectionMatrix()
let renderer = new THREE.WebGLRenderer({ canvas, antialias: true })
renderer.setSize(canvas.clientWidth, canvas.clientWidth)
scene.background = new THREE.Color(BLACK)
const light = new THREE.PointLight(WHITE, 2, 100)
light.position.set(0, 0, 20)
scene.add(light)
const grid = new THREE.GridHelper(
range[1] - range[0],
(range[1] - range[0]) / gridSize,
0xbbbbbb,
0x444444
)
grid.rotation.x = Math.PI / 2
scene.add(grid)
const axes = createAxes({ size: (range[1] - range[0]) / 2, fontSize: 0 })
scene.add(axes)
//
// for (let y = range[0]; y <= range[1]; y += gridSize * 2) {
// const label = createLabel({ text: y.toFixed(0), size: 0.3, color: WHITE })
// const bbox = new THREE.Box3().setFromObject(label)
// label.position.y = y - bbox.getSize().y / 2
// label.position.x = range[0] - bbox.getSize().x * 2.5
// scene.add(label)
// }
// for (let x = range[0]; x <= range[1]; x += Math.PI) {
// const label = createLabel({
// text: `${(x / Math.PI).toFixed(0)} PI`,
// size: 0.3,
// color: WHITE
// })
// const bbox = new THREE.Box3().setFromObject(label)
// label.position.x = x - bbox.getSize().x / 2
// label.position.y = -1 * range[1] - bbox.getSize().y * 2.5
// scene.add(label)
// }
const resizeRendererToDisplaySize = (renderer) => {
const canvas = renderer.domElement
const width = canvas.clientWidth
const height = canvas.clientHeight
const needResize = canvas.width !== width || canvas.height !== height
if (needResize) {
renderer.setSize(width, height, false)
}
return needResize
}
let lastMousePos = { x: 0.5, y: 0.5 }
const mousePos = (event) => {
const bounds = event.target.getBoundingClientRect()
// const center = {
// x: (bounds.right - bounds.left) / 2,
// y: (bounds.bottom - bounds.top) / 2
// }
const xy = {
x: event.clientX - bounds.left,
y: event.clientY - bounds.top,
}
const x = xy.x / event.target.clientWidth
const y = xy.y / event.target.clientHeight
// const x = event.target.clientX / event.target.clientWidth
// const x = (event.clientX / window.innerWidth) * 2 - 1
// const y = event.clientY / event.target.clientHeight
return [x, y]
}
canvas.onmousemove = (event) => {
const [x, y] = mousePos(event)
lastMousePos = {
x,
y,
}
}
const note = {
label: 'A',
frequency: 1200,
}
const zoom = 200
// const speedOfSound = 343
const c = 299792458
const wavelength = c / note.frequency
const amplitude = 0.5 * Math.PI
const { object: lineGraph, animate: animateLineGraph } = createLineGraph(
(t) => (x) => {
// console.log(t * 0.001)
return 2 * amplitude * Math.sin((x * c) / wavelength / zoom)
},
'f(x) = 2 * sin(x)',
0xeeee00,
'solid',
range
)
scene.add(lineGraph)
const label = createLabel({
text: `Freq: ${parseFloat(note.frequency).toFixed(4)}Hz`,
size: 0.3,
color: WHITE,
})
label.position.set(range[0] + gridSize, range[1] - gridSize, 0)
scene.add(label)
const cycleLabel = createLabel({
text: `Cycl: ${parseFloat(note.frequency).toFixed(4)}Hz`,
size: 0.3,
color: WHITE,
})
cycleLabel.position.set(range[0] + gridSize, range[1] - gridSize * 2, 0)
scene.add(cycleLabel)
const vmaxLabel = createLabel({
text: `Vmax: ${parseFloat(amplitude).toFixed(4)}V`,
size: 0.3,
color: WHITE,
})
vmaxLabel.position.set(range[1] * 0.25 + gridSize, range[1] - gridSize, 0)
scene.add(vmaxLabel)
const vminLabel = createLabel({
text: `Vmin: ${parseFloat(-1 * amplitude).toFixed(4)}V`,
size: 0.3,
color: WHITE,
})
vminLabel.position.set(range[1] * 0.25 + gridSize, range[1] - gridSize * 2, 0)
scene.add(vminLabel)
console.log(wavelength)
const objectState = state.select('object')
let thenSecs = 0
const animate = (now) => {
if (!renderer) {
return
}
if (resizeRendererToDisplaySize(renderer)) {
const c = renderer.domElement
// camera.aspect = c.clientWidth / c.clientHeight
// camera.left = c.clientWidth / -2
// camera.right = c.clientWidth / 2
// camera.top = c.clientHeight / 2
// camera.bottom = c.clientHeight / -2
camera.updateProjectionMatrix()
}
requestAnimationFrame(animate)
const nowSecs = now * 0.001
const deltaSecs = nowSecs - thenSecs
thenSecs = nowSecs
if (deltaSecs) {
const rotationSpeed = objectState.get('rotationSpeed')
}
animateLineGraph(now)
renderer.render(scene, camera)
}
animate()
return () => {
renderer.dispose()
scene = null
renderer = null
}
}
const Oscilloscope = ({ state, labels }) => {
React.useEffect(() => {
if (document.getElementById('oscilloscope')) {
return init({ state })
}
})
return <canvas id="oscilloscope" />
}
export { init }
export default Oscilloscope
|
docs/lib/Home/index.js
|
video-react/video-react
|
import React from 'react';
import { PrismCode } from 'react-prism';
import { Button, Container, Row, Col, Jumbotron } from 'reactstrap';
import { Link } from 'react-router';
import BasicExample from '../examples/import-basic';
const importBasic = require('!!raw-loader!../examples/import-basic');
export default () => {
return (
<div>
<Jumbotron tag="section" className="jumbotron-header text-center mb-3">
<Container>
<Row>
<Col>
<p className="lead">
<img src="/assets/logo.png" alt="" width="150px" />
</p>
<h1 className="jumbotron-heading display-4">Video-React</h1>
<p className="lead">
The web video player built from the ground up for an HTML5 world
using React library.
</p>
<p>
<Button
outline
color="danger"
href="https://github.com/video-react/video-react"
>
View on Github
</Button>
<Button color="danger" tag={Link} to="/components/">
View Components
</Button>
</p>
</Col>
</Row>
</Container>
</Jumbotron>
<Container fluid>
<Row>
<Col sm={{ size: 8, offset: 2 }}>
<h2>Installation</h2>
<hr />
<h3>NPM</h3>
<p>Install video-react and peer dependencies via NPM</p>
<pre>
<PrismCode className="language-bash">
npm install --save video-react react react-dom redux
</PrismCode>
</pre>
<h3>Basic example</h3>
<p>The basic player</p>
<div className="docs-example">
<BasicExample />
</div>
<p>import css in your app or add video-react styles in your page</p>
<pre>
<PrismCode className="language-jsx">
import "node_modules/video-react/dist/video-react.css"; //
import css
</PrismCode>
</pre>
<pre>
<PrismCode className="language-jsx">
@import "~video-react/styles/scss/video-react"; // or import
scss
</PrismCode>
</pre>
<pre>
<PrismCode className="language-html">
<link rel="stylesheet" href="/css/video-react.css" />
</PrismCode>
</pre>
<pre>
<PrismCode className="language-jsx">{importBasic}</PrismCode>
</pre>
<h2 className="m-t-3">Development</h2>
<hr />
<p>Install dependencies:</p>
<pre>
<PrismCode className="language-bash">npm install</PrismCode>
</pre>
<p>
Run examples at{' '}
<a href="http://localhost:9000/" target="_blank">
http://localhost:9000/
</a>{' '}
with webpack dev server:
</p>
<pre>
<PrismCode className="language-bash">npm start</PrismCode>
</pre>
<p>Run tests & coverage report:</p>
<pre>
<PrismCode className="language-bash">npm test</PrismCode>
</pre>
</Col>
</Row>
</Container>
</div>
);
};
|
tests/components/Header/Header.spec.js
|
townmi/bis
|
import React from 'react'
import { Header } from 'components/Header/Header'
import classes from 'components/Header/Header.scss'
import { IndexLink, Link } from 'react-router'
import { shallow } from 'enzyme'
describe('(Component) Header', () => {
let _wrapper
beforeEach(() => {
_wrapper = shallow(<Header />)
})
it('Renders a welcome message', () => {
const welcome = _wrapper.find('h1')
expect(welcome).to.exist
expect(welcome.text()).to.match(/React Starter Kit/)
})
describe('Navigation links...', () => {
it('Should render a Link to Home route', () => {
expect(_wrapper.contains(
<IndexLink activeClassName='route--active' to='/'>
Home
</IndexLink>
)).to.be.true
})
it('Should render a Link to Stock route', () => {
expect(_wrapper.contains(
<Link activeClassName='route--active' to='/counter'>
Counter
</Link>
)).to.be.true
})
})
})
|
resources/js/Admin/components/Form/CheckboxOptionsField.js
|
DoSomething/northstar
|
/** @jsx jsx */
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { jsx, css } from '@emotion/react';
import CheckboxInput from '../../../components/FormInput/CheckboxInput';
import CheckIcon from '../../../components/artifacts/CheckIcon/CheckIcon';
const CheckboxOptionsField = ({
className,
clearErrors,
description,
error,
label,
name,
options,
optionalField,
setData,
stateData,
}) => {
return (
<div className={classnames('mb-10 relative', className)}>
{label && (
<p className="mb-2">
<strong className="font-bold">{label}</strong>
{optionalField && (
<span className="font-bold ml-2 text-gray-600">(optional)</span>
)}
</p>
)}
{description && (
<small className="block mb-3 max-chars text-gray-600">
{description}
</small>
)}
{options.length ? (
<ul className="flex flex-wrap">
{options.map((option, index) => {
// Remvoe "name" prefix from value when used for state data.
const value = option.value.replace(`${name}-`, '');
return (
<li
className="flex items-center my-2 w-1/2"
css={css`
column-gap: 5px;
.check-input {
opacity: 0;
transition: opacity 0.25s ease-in-out;
}
input:checked + .check-input {
opacity: 1;
}
`}
key={index}
>
<CheckboxInput
checked={stateData[name][value] === value ? true : false}
className={classnames(
'appearance-none text-blurple-400 bg-gray-200 checked:bg-blurple-500 border border-gray-300 cursor-pointer rounded-sm',
{ 'border-red-300': error },
)}
clearErrors={clearErrors}
icon={
<span className="check-input absolute items-center flex inset-0 justify-center p-1 pointer-events-none w-full h-full">
<CheckIcon color="#fff" size="16px" />
</span>
}
id={option.value}
label={option.label}
name={name}
setData={setData}
size="18px"
stateData={stateData[name]}
value={option.value}
/>
</li>
);
})}
</ul>
) : null}
{error && <small className="absolute mt-2 text-red-500">{error}</small>}
</div>
);
};
CheckboxOptionsField.propTypes = {
className: PropTypes.string,
clearErrors: PropTypes.func,
description: PropTypes.string,
error: PropTypes.string,
label: PropTypes.string,
name: PropTypes.string,
options: PropTypes.arrayOf(
PropTypes.shape({
label: PropTypes.string,
value: PropTypes.string,
}),
),
optionalField: PropTypes.bool,
setData: PropTypes.func,
stateData: PropTypes.object,
};
CheckboxOptionsField.defaultProps = {
className: null,
clearErrors: () => {},
description: null,
error: null,
setData: () => {},
stateData: {},
};
export default CheckboxOptionsField;
|
src/Components/TopBar.js
|
thipokKub/ReQoot-FrontEnd
|
import React from 'react';
import styled from 'styled-components';
// import PropTypes from 'prop-types';
const TopBarStyled = styled.div`
width: 100vw;
height: ${(props) => props.height}px;
position: sticky;
background-color: #FFF;
display: flex;
align-items: center;
button {
display: none;
margin-left: 10px !important;
}
@media all and (max-width: 400px) {
button {
display: initial;
}
}
`;
const TopBar = (props) => {
return (
<TopBarStyled {...props}>
<button className="square-round outline" onClick={props.onSwitchActive}>
<i className="fa fa-bars" />
</button>
</TopBarStyled>
);
}
export default TopBar;
|
examples/redirect-using-index/app.js
|
cgrossde/react-router
|
import React from 'react';
import { Router, Route, IndexRoute, Link } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
{this.props.children}
</div>
);
}
});
var Index = React.createClass({
render () {
return (
<div>
<h1>You should not see this.</h1>
{this.props.children}
</div>
)
}
});
var Child = React.createClass({
render () {
return (
<div>
<h2>Redirected to "/child"</h2>
<Link to="/">Try going to "/"</Link>
</div>
)
}
});
function redirectToChild(location, replaceWith) {
replaceWith(null, '/child');
}
React.render((
<Router>
<Route path="/" component={App}>
<IndexRoute component={Index} onEnter={redirectToChild}/>
<Route path="/child" component={Child}/>
</Route>
</Router>
), document.getElementById('example'));
|
pootle/static/js/admin/components/SearchBox.js
|
r-o-b-b-i-e/pootle
|
/*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import _ from 'underscore';
const SearchBox = React.createClass({
propTypes: {
onSearch: React.PropTypes.func.isRequired,
placeholder: React.PropTypes.string,
searchQuery: React.PropTypes.string,
},
/* Lifecycle */
getInitialState() {
return {
// XXX: review, prop should be explicitly named `initialSearchQuery`
searchQuery: this.props.searchQuery,
};
},
componentWillMount() {
this.handleSearchDebounced = _.debounce(() => {
this.props.onSearch.apply(this, [this.state.searchQuery]);
}, 300);
},
componentDidMount() {
this.refs.input.focus();
},
componentWillReceiveProps(nextProps) {
if (nextProps.searchQuery !== this.state.searchQuery) {
this.setState({ searchQuery: nextProps.searchQuery });
}
},
/* Handlers */
handleKeyUp(e) {
const key = e.nativeEvent.keyCode;
if (key === 27) {
this.refs.input.blur();
}
},
handleChange() {
this.setState({ searchQuery: this.refs.input.value });
this.handleSearchDebounced();
},
/* Layout */
render() {
return (
<input
type="text"
ref="input"
value={this.state.searchQuery}
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
{...this.props}
/>
);
},
});
export default SearchBox;
|
features/fixtures/rn-monorepo/xyz/App.js
|
bugsnag/bugsnag-android-gradle-plugin
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
*
* @format
* @flow strict-local
*/
import React from 'react';
import {
SafeAreaView,
StyleSheet,
ScrollView,
View,
Text,
StatusBar,
} from 'react-native';
import {
Header,
LearnMoreLinks,
Colors,
DebugInstructions,
ReloadInstructions,
} from 'react-native/Libraries/NewAppScreen';
const App: () => React$Node = () => {
return (
<>
<StatusBar barStyle="dark-content" />
<SafeAreaView>
<ScrollView
contentInsetAdjustmentBehavior="automatic"
style={styles.scrollView}>
<Header />
{global.HermesInternal == null ? null : (
<View style={styles.engine}>
<Text style={styles.footer}>Engine: Hermes</Text>
</View>
)}
<View style={styles.body}>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Step One</Text>
<Text style={styles.sectionDescription}>
Edit <Text style={styles.highlight}>App.js</Text> to change this
screen and then come back to see your edits.
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>See Your Changes</Text>
<Text style={styles.sectionDescription}>
<ReloadInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Debug</Text>
<Text style={styles.sectionDescription}>
<DebugInstructions />
</Text>
</View>
<View style={styles.sectionContainer}>
<Text style={styles.sectionTitle}>Learn More</Text>
<Text style={styles.sectionDescription}>
Read the docs to discover what to do next:
</Text>
</View>
<LearnMoreLinks />
</View>
</ScrollView>
</SafeAreaView>
</>
);
};
const styles = StyleSheet.create({
scrollView: {
backgroundColor: Colors.lighter,
},
engine: {
position: 'absolute',
right: 0,
},
body: {
backgroundColor: Colors.white,
},
sectionContainer: {
marginTop: 32,
paddingHorizontal: 24,
},
sectionTitle: {
fontSize: 24,
fontWeight: '600',
color: Colors.black,
},
sectionDescription: {
marginTop: 8,
fontSize: 18,
fontWeight: '400',
color: Colors.dark,
},
highlight: {
fontWeight: '700',
},
footer: {
color: Colors.dark,
fontSize: 12,
fontWeight: '600',
padding: 4,
paddingRight: 12,
textAlign: 'right',
},
});
export default App;
|
js/jqwidgets/jqwidgets-react/react_jqxlistmenu.js
|
luissancheza/sice
|
/*
jQWidgets v5.3.2 (2017-Sep)
Copyright (c) 2011-2017 jQWidgets.
License: http://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxListMenu extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['alwaysShowNavigationArrows','animationType','animationDuration','autoSeparators','backLabel','disabled','enableScrolling','filterCallback','height','headerAnimationDuration','placeHolder','readOnly','rtl','roundedCorners','showNavigationArrows','showFilter','showHeader','showBackButton','theme','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxListMenu(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxListMenu('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxListMenu(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
alwaysShowNavigationArrows(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('alwaysShowNavigationArrows', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('alwaysShowNavigationArrows');
}
};
animationType(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('animationType', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('animationType');
}
};
animationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('animationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('animationDuration');
}
};
autoSeparators(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('autoSeparators', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('autoSeparators');
}
};
backLabel(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('backLabel', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('backLabel');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('disabled');
}
};
enableScrolling(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('enableScrolling', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('enableScrolling');
}
};
filterCallback(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('filterCallback', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('filterCallback');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('height', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('height');
}
};
headerAnimationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('headerAnimationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('headerAnimationDuration');
}
};
placeHolder(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('placeHolder', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('placeHolder');
}
};
readOnly(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('readOnly', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('readOnly');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('rtl');
}
};
roundedCorners(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('roundedCorners', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('roundedCorners');
}
};
showNavigationArrows(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('showNavigationArrows', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('showNavigationArrows');
}
};
showFilter(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('showFilter', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('showFilter');
}
};
showHeader(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('showHeader', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('showHeader');
}
};
showBackButton(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('showBackButton', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('showBackButton');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('theme');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxListMenu('width', arg)
} else {
return JQXLite(this.componentSelector).jqxListMenu('width');
}
};
back() {
JQXLite(this.componentSelector).jqxListMenu('back');
};
changePage(Item) {
JQXLite(this.componentSelector).jqxListMenu('changePage', Item);
};
destroy() {
JQXLite(this.componentSelector).jqxListMenu('destroy');
};
render() {
let id = 'jqxListMenu' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
kitsune/sumo/static/sumo/js/tests/crashidtests.js
|
NewPresident1/kitsune
|
import {default as mochaJsdom, rerequire} from 'mocha-jsdom';
import {expect} from 'chai';
import React from 'react';
import mochaK from './fixtures/mochaK.js';
import mochaJquery from './fixtures/mochaJquery.js';
import mochaGettext from './fixtures/mochaGettext.js';
import mochaMarky from './fixtures/mochaMarky.js';
describe('k', () => {
mochaJsdom({useEach: true});
mochaJquery();
mochaK();
mochaGettext();
mochaMarky();
/* globals window, document, $, k */
describe('linkCrashIds', () => {
beforeEach(() => {
rerequire('../questions.js');
});
afterEach(() => {
React.unmountComponentAtNode(document.body);
});
it('should link one crash ID', () => {
let sandbox = (
<section>
<h1>Firefox keeps crashing</h1>
<p>Firefox keeps crashing</p>
<p>
This is my crash ID:<br/>
bp-6ec83338-f37e-4ee1-aef4-0e66c2120808
</p>
<div className="stem"></div>
</section>
);
React.render(sandbox, document.body);
k.linkCrashIds($('body'));
expect($('.crash-report').length).to.equal(1);
});
it('should link multiple crash IDs', function() {
let sandbox = (
<section>
<h1>Firefox keeps crashing</h1>
<p>Firefox keeps crashing</p>
<p>
Here's a list of my crash IDs (copied directly from about:crashes):<br/>
bp-6ec83338-f37e-4ee1-aef4-0e66c212080808.08.1217:52
bp-d8951614-c928-44ed-902c-6ccb6212080808.08.1217:52
bp-5eb7d4ec-5f9e-4cbf-9335-a574c212071717.07.1211:29
bp-15a73687-dabf-4014-9c03-b97b3212071717.07.1211:27
bp-f894adf7-9ff8-4f21-8564-da425212071111.07.1218:22
</p>
<div className="stem"></div>
</section>
);
React.render(sandbox, document.body);
k.linkCrashIds($('body'));
expect($('.crash-report').length).to.equal(5);
});
it("shouldn't link invalid crash IDs", function() {
let sandbox = (
<section>
<p>The following will look like an invalid crash ID that hasn't been processed yet:</p>
<p>765879E6-CFE7-43A7-BE93-B2F322E67649</p>
</section>
);
React.render(sandbox, document.body);
k.linkCrashIds($('body'));
expect($('.crash-report').length).to.equal(0);
});
it("shouldn't link crash IDs without 'bp-'", function() {
let sandbox = (
<section>
<p>Now, crash IDs without 'bp-' at the beginning shouldn't get linked either</p>
<p>6ec83338-f37e-4ee1-aef4-0e66c2120808</p>
</section>
);
React.render(sandbox, document.body);
k.linkCrashIds($('body'));
expect($('.crash-report').length).to.equal(0);
});
});
});
|
src/mui/input/BooleanInput.js
|
azureReact/AzureReact
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Toggle from 'material-ui/Toggle';
import FieldTitle from '../../util/FieldTitle';
const styles = {
block: {
margin: '1rem 0',
maxWidth: 250,
},
label: {
color: 'rgba(0, 0, 0, 0.298039)',
},
toggle: {
marginBottom: 16,
},
};
class BooleanInput extends Component {
handleToggle = (event, value) => {
this.props.input.onChange(value);
};
render() {
const {
input,
isRequired,
label,
source,
elStyle,
resource,
options,
} = this.props;
return (
<div style={elStyle || styles.block}>
<Toggle
defaultToggled={!!input.value}
onToggle={this.handleToggle}
labelStyle={styles.label}
style={styles.toggle}
label={
<FieldTitle
label={label}
source={source}
resource={resource}
isRequired={isRequired}
/>
}
{...options}
/>
</div>
);
}
}
BooleanInput.propTypes = {
addField: PropTypes.bool.isRequired,
elStyle: PropTypes.object,
input: PropTypes.object,
isRequired: PropTypes.bool,
label: PropTypes.string,
resource: PropTypes.string,
source: PropTypes.string,
options: PropTypes.object,
};
BooleanInput.defaultProps = {
addField: true,
options: {},
};
export default BooleanInput;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.