path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
docs/src/app/pages/components/Checkbox/Page.js
|
GetAmbassador/react-ions
|
import React from 'react'
import PropsList from 'private/modules/PropsList'
import docs from '!!docgen!react-ions/lib/components/Checkbox/Checkbox'
import CodeExample from 'private/modules/CodeExample'
import ExampleCheckboxDefault from './ExampleCheckboxDefault'
import exampleCheckboxDefaultCode from '!raw!./ExampleCheckboxDefault'
import ExampleCheckboxChecked from './ExampleCheckboxChecked'
import exampleCheckboxCheckedCode from '!raw!./ExampleCheckboxChecked'
import ExampleCheckboxDisabled from './ExampleCheckboxDisabled'
import exampleCheckboxDisabledCode from '!raw!./ExampleCheckboxDisabled'
import ExampleCheckboxError from './ExampleCheckboxError'
import exampleCheckboxErrorCode from '!raw!./ExampleCheckboxError'
import ExampleCheckboxLocked from './ExampleCheckboxLocked'
import exampleCheckboxLockedCode from '!raw!./ExampleCheckboxLocked'
import ExampleCheckboxCallback from './ExampleCheckboxCallback'
import exampleCheckboxCallbackCode from '!raw!./ExampleCheckboxCallback'
import ExampleCheckboxToggle from './ExampleCheckboxToggle'
import exampleCheckboxToggleCode from '!raw!./ExampleCheckboxToggle'
import ExampleCheckboxCustomIcon from './ExampleCheckboxCustomIcon'
import exampleCheckboxCustomIconCode from '!raw!./ExampleCheckboxCustomIcon'
import ExampleCheckboxCustomLabel from './ExampleCheckboxCustomLabel'
import exampleCheckboxCustomLabelCode from '!raw!./ExampleCheckboxCustomLabel'
import ExampleCheckboxDescription from './ExampleCheckboxDescription'
import exampleCheckboxDescriptionCode from '!raw!./ExampleCheckboxDescription'
import ExampleCheckboxNative from './ExampleCheckboxNative'
import exampleCheckboxNativeCode from '!raw!./ExampleCheckboxNative'
import styles from 'private/css/content'
const description = {
checkboxDefault: 'This is the `checkbox component` as it appears by default.',
checkboxChecked: 'This is the checked `checkbox component`.',
checkboxDisabled: 'This is the disabled `checkbox component`.',
checkboxError: 'This is the `checkbox component` with an error.',
checkboxLocked: 'This is the `checkbox component` when locked. It can only be changed by receiving props.',
checkboxCallback: 'This is the `checkbox component` with a callback function. __Note__: the `style import` and `code` tag is for display purposes only.',
checkboxToggle: 'This is the `checkbox component` that you can toggle from the outside by changing its checked property.',
checkboxCustomIcon: 'This is the `checkbox component` with a custom icon.',
checkboxCustomLabel: 'This is the `checkbox component` with a node as the label.',
checkboxDescription: 'This is the `checkbox component` with a description.',
checkboxNative: 'This is the native `checkbox component`.'
}
const CheckboxPage = () => (
<div>
<div className={styles.content}>
<div className={styles.block}>
<CodeExample
title='Default Checkbox'
description={description.checkboxDefault}
markup={exampleCheckboxDefaultCode}>
<ExampleCheckboxDefault />
</CodeExample>
<CodeExample
title='Checked Checkbox'
description={description.checkboxChecked}
markup={exampleCheckboxCheckedCode}>
<ExampleCheckboxChecked />
</CodeExample>
<CodeExample
title='Disabled Checkbox'
description={description.checkboxDisabled}
markup={exampleCheckboxDisabledCode}>
<ExampleCheckboxDisabled />
</CodeExample>
<CodeExample
title='Locked Checkbox'
description={description.checkboxLocked}
markup={exampleCheckboxLockedCode}>
<ExampleCheckboxLocked />
</CodeExample>
<CodeExample
title='Error Checkbox'
description={description.checkboxError}
markup={exampleCheckboxErrorCode}>
<ExampleCheckboxError />
</CodeExample>
<CodeExample
title='Checkbox with callback function'
description={description.checkboxCallback}
markup={exampleCheckboxCallbackCode}>
<ExampleCheckboxCallback />
</CodeExample>
<CodeExample
title='Checkbox that can be toggled from the outside'
description={description.checkboxToggle}
markup={exampleCheckboxToggleCode}>
<ExampleCheckboxToggle />
</CodeExample>
<CodeExample
title='Checkbox with a custom icon'
description={description.checkboxCustomIcon}
markup={exampleCheckboxCustomIconCode}>
<ExampleCheckboxCustomIcon />
</CodeExample>
<CodeExample
title='Checkbox with a custom label'
description={description.checkboxCustomLabel}
markup={exampleCheckboxCustomLabelCode}>
<ExampleCheckboxCustomLabel />
</CodeExample>
<CodeExample
title='Checkbox with a description'
description={description.checkboxDescription}
markup={exampleCheckboxDescriptionCode}>
<ExampleCheckboxDescription />
</CodeExample>
<CodeExample
title='Native Checkbox'
description={description.nativeCheckbox}
markup={exampleCheckboxNativeCode}>
<ExampleCheckboxNative />
</CodeExample>
<div className={styles.block}>
<h3>Props</h3>
<PropsList list={docs[0].props} />
</div>
</div>
</div>
</div>
)
export default CheckboxPage
|
components/DashboardTeam.js
|
turntwogg/final-round
|
import React from 'react';
import { useTheme } from '@turntwo/react-ui';
import Link from './Link';
import Typography from './Typography';
import FollowButton from './FollowButton';
import Image from './Image';
const DashboardTeam = ({ team, ...rest }) => {
const {
title,
fieldSlug: slug,
fieldTeamGame: { name: gameName },
fieldTeamOrganization: { fieldOrganizationLogo },
} = team;
const theme = useTheme();
const logoUrl = fieldOrganizationLogo?.uri.url;
return (
<article className="dashboard-team" {...rest}>
<Link href="/games/[slug]/teams/[single]" as={`/games${slug}`}>
<a className="dashboard-team-link">
{logoUrl && (
<div className="dashboard-team-logo">
<Image
src={logoUrl}
className="dashboard-team-logo-img"
alt={title}
/>
</div>
)}
<Typography
is="h3"
className="dashboard-team-title"
style={{ fontSize: 14, marginBottom: theme.baseSpacingUnit / 3 }}
>
{title}
</Typography>
<Typography
is="h4"
style={{
fontWeight: theme.fontWeight.default,
fontSize: 12,
color: '#6b6885',
marginBottom: 0,
}}
>
{gameName}
</Typography>
</a>
</Link>
<FollowButton
className={'dashboard-team-follow-button'}
entityType="teams"
entity={team}
size="tiny"
style={{ position: 'absolute', top: 0, right: 0 }}
/>
<style jsx>{`
.dashboard-team {
position: relative;
display: flex;
flex-flow: column;
}
.dashboard-team-link {
display: flex;
flex-flow: column;
justify-content: center;
align-items: center;
}
.dashboard-team-logo {
margin-bottom: ${theme.baseSpacingUnit}px;
height: 75px;
}
:global(.dashboard-team-logo-img) {
width: auto;
max-height: 100%;
}
`}</style>
</article>
);
};
export default DashboardTeam;
|
src/components/TableQuerySwitch/index.js
|
cantonjs/re-admin
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { observer } from 'mobx-react';
import panelsStore from 'stores/panelsStore';
import withStore from 'hocs/withStore';
import localize from 'hocs/localize';
import { Checkbox } from 'antd';
@withStore()
@localize('TableQuerySwitch')
@observer
export default class TableQuerySwitch extends Component {
static propTypes = {
children: PropTypes.node,
store: PropTypes.object.isRequired,
localeStore: PropTypes.object.isRequired,
};
_handleToggle = (ev) => {
panelsStore.updateQuery(ev.target.checked);
};
render() {
const { store: { queryFieldsCount }, children, localeStore } = this.props;
if (!queryFieldsCount) return null;
return (
<Checkbox checked={panelsStore.isShowQuery} onChange={this._handleToggle}>
{localeStore.localizeProp(children, 'label')}
</Checkbox>
);
}
}
|
client/components/DashboardSection.js
|
mmazzarolo/numvalidate
|
/* @flow */
import React from 'react';
import Spinner from './Spinner';
import Button from './Button';
import style from './DashboardSection.css';
type Props = {
title: string,
subtitle: string,
rightElement?: any,
rightButtonText?: string,
rightButtonType?: string,
onRightButtonClick?: () => mixed,
loading?: boolean,
children?: any,
};
const DashboardSection = (props: Props) => {
const {
title,
subtitle,
rightElement,
rightButtonText,
onRightButtonClick,
loading,
children,
} = props;
let rightButton;
if (rightElement) {
rightButton = rightElement;
} else if (rightButtonText && onRightButtonClick) {
rightButton = <Button onClick={onRightButtonClick}>{rightButtonText}</Button>;
}
return (
<section className={'DashboardSection'}>
<style jsx>{style}</style>
<header className={'DashboardSection-header'}>
<div className={'DashboardSection-header-left'}>
<h1>{title}</h1>
<p>{subtitle}</p>
</div>
<div className={'DashboardSection-header-right'}>
{!loading && rightButton}
{loading && <Spinner visible={true} />}
</div>
</header>
{children}
</section>
);
};
export default DashboardSection;
|
packages/react/src/components/organisms/GenTeaser/TeaserSearch/index.js
|
massgov/mayflower
|
/**
* TeaserSearch module.
* @module @massds/mayflower-react/TeaserSearch
* @requires module:@massds/mayflower-assets/scss/01-atoms/button-with-icon
* @requires module:@massds/mayflower-assets/scss/01-atoms/button-search
* @requires module:@massds/mayflower-assets/scss/01-atoms/input-typeahead
* @requires module:@massds/mayflower-assets/scss/01-atoms/svg-icons
* @requires module:@massds/mayflower-assets/scss/01-atoms/svg-loc-icons
*/
import React from 'react';
import PropTypes from 'prop-types';
import HeaderSearch from 'MayflowerReactMolecules/HeaderSearch';
class TeaserSearch extends React.Component {
constructor(props) {
super(props);
this.inputRef = React.createRef();
}
onClick = (e) => {
e.preventDefault();
const { target, queryInput } = this.props;
const query = this.inputRef.current.value;
if (query.length > 0) {
const searchURL = queryInput ? target.replace(`{${queryInput}}`, query) : target;
this.redirect(searchURL);
}
}
redirect = (searchURL) => {
if (window.location !== window.parent.location) {
window.parent.location.assign(searchURL);
} else {
window.location.assign(searchURL);
}
}
render() {
const {
placeholder, id, queryInput, ...rest
} = this.props;
return(
<HeaderSearch
buttonSearch={{
'aria-label': '',
onClick: (e) => this.onClick(e),
text: 'Search',
usage: ''
}}
defaultText=""
id={id}
label="Search terms"
onSubmit={(e) => this.onSubmit(e)}
inputRef={this.inputRef}
placeholder={placeholder}
{...rest}
/>
);
}
}
TeaserSearch.propTypes = {
/** The target url of the search bar */
target: PropTypes.string.isRequired,
/** The id of the search bar */
id: PropTypes.string.isRequired,
/** The query input variable to replace in the target url with the user entered term */
queryInput: PropTypes.string.isRequired,
/** Placeholder text of the search bar. */
placeholder: PropTypes.string.isRequired
};
export default TeaserSearch;
|
src/Parser/MarksmanshipHunter/Modules/Features/AlwaysBeCasting.js
|
mwwscott0/WoWAnalyzer
|
import React from 'react';
import CoreAlwaysBeCasting from 'Parser/Core/Modules/AlwaysBeCasting';
import SPELLS from 'common/SPELLS';
import Icon from 'common/Icon';
import { formatPercentage } from 'common/format';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
import SpellLink from 'common/SpellLink';
class AlwaysBeCasting extends CoreAlwaysBeCasting {
static ABILITIES_ON_GCD = [
// Marksmanship:
SPELLS.AIMED_SHOT.id,
SPELLS.WINDBURST.id,
SPELLS.ARCANE_SHOT.id,
SPELLS.MULTISHOT.id,
SPELLS.MARKED_SHOT.id,
SPELLS.TAR_TRAP.id,
SPELLS.FREEZING_TRAP.id,
SPELLS.BLACK_ARROW_TALENT.id,
SPELLS.EXPLOSIVE_SHOT_TALENT.id,
SPELLS.SIDEWINDERS_TALENT.id,
SPELLS.PIERCING_SHOT_TALENT.id,
SPELLS.TRICK_SHOT_TALENT.id,
SPELLS.A_MURDER_OF_CROWS_TALENT_SHARED.id,
SPELLS.BARRAGE_TALENT.id,
];
suggestions(when) {
const deadTimePercentage = this.totalTimeWasted / this.owner.fightDuration;
when(deadTimePercentage).isGreaterThan(0.2)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Your dead GCD time can be improved. Try to Always Be Casting (ABC), try to reduce the delay between casting spells. Even if you have to move, try casting something instant like <SpellLink id={SPELLS.ARCANE_SHOT.id} /> for single target or <SpellLink id={SPELLS.MULTISHOT.id} /> for multiple</span>)
.icon('spell_mage_altertime')
.actual(`${formatPercentage(actual)}% dead GCD time`)
.recommended(`<${formatPercentage(recommended)}% is recommended`)
.regular(recommended + 0.15).major(recommended + 0.2);
});
}
statistic() {
const deadTimePercentage = this.totalTimeWasted / this.owner.fightDuration;
return (
<StatisticBox
icon={<Icon icon="spell_mage_altertime" alt="Dead time" />}
value={`${formatPercentage(deadTimePercentage)} %`}
label="Dead time"
tooltip="Dead time is available casting time not used for casting any spell. This can be caused by latency, cast interrupting, not casting anything (e.g. due to movement/being stunned), etc."
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(1);
}
export default AlwaysBeCasting;
|
test/ButtonSpec.js
|
JimiHFord/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Button from '../src/Button';
describe('Button', function () {
it('Should output a button', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).nodeName, 'BUTTON');
});
it('Should have type=button by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).getAttribute('type'), 'button');
});
it('Should show the type if passed one', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button type='submit'>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).getAttribute('type'), 'submit');
});
it('Should output an anchor if called with a href', function () {
let href = '/url';
let instance = ReactTestUtils.renderIntoDocument(
<Button href={href}>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).nodeName, 'A');
assert.equal(React.findDOMNode(instance).getAttribute('href'), href);
});
it('Should output an anchor if called with a target', function () {
let target = '_blank';
let instance = ReactTestUtils.renderIntoDocument(
<Button target={target}>
Title
</Button>
);
assert.equal(React.findDOMNode(instance).nodeName, 'A');
assert.equal(React.findDOMNode(instance).getAttribute('target'), target);
});
it('Should call onClick callback', function (done) {
let doneOp = function () {
done();
};
let instance = ReactTestUtils.renderIntoDocument(
<Button onClick={doneOp}>
Title
</Button>
);
ReactTestUtils.Simulate.click(React.findDOMNode(instance));
});
it('Should be disabled', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button disabled>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).disabled);
});
it('Should be disabled link', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button disabled href='#'>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bdisabled\b/));
});
it('Should have block class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button block>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-block\b/));
});
it('Should apply bsStyle class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button bsStyle='danger'>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/));
});
it('Should honour additional classes passed in, adding not overriding', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button className="bob" bsStyle="danger">
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bbob\b/));
assert.ok(React.findDOMNode(instance).className.match(/\bbtn-danger\b/));
});
it('Should default to bsStyle="default"', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button bsStyle='default'>
Title
</Button>
);
assert.equal(instance.props.bsStyle, 'default');
});
it('Should be active', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button active>
Title
</Button>
);
assert.ok(React.findDOMNode(instance).className.match(/\bactive\b/));
});
it('Should render an anchor in a list item when in a nav', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button navItem active>
Title
</Button>
);
let li = React.findDOMNode(instance);
let anchor = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'a');
assert.equal(li.nodeName, 'LI');
assert.ok(li.className.match(/\bactive\b/));
assert.ok(anchor.props.href, '#');
});
it('Should render an anchor when in a navDropdown', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Button navDropdown>
Title
</Button>
);
let anchor = React.findDOMNode(instance);
assert.equal(anchor.nodeName, 'A');
assert.ok(anchor.getAttribute('href'), '#');
});
});
|
src/Comment.js
|
diginatu/nagome-webui
|
import React, { Component } from 'react';
import {ngm} from './NagomeConn.js';
import CommentList from './CommentList.js';
import DropArea from './DropArea.js';
export default class Comment extends Component {
constructor() {
super();
this.state = {
data: [
//{"no":70,"date":"20:08:58","raw":"おつ","comment":"おつ","is_premium":true,"is_broadcaster":false,"is_staff":false,"is_anonymity":false,"score":0,"user_id":"11246304","user_name":"デジネイ","user_thumbnail_url":"http://usericon.nimg.jp/usericon/1124/11246304.jpg"},
//{"no":71,"date":"20:09:17","raw":"anony","comment":"anony","is_premium":true,"is_broadcaster":false,"is_staff":false,"is_anonymity":true,"score":0,"user_id":"TnPRtKVgHdYW4Uklky8yjLn982Y","user_name":""},
//{"no":72,"date":"20:09:17","raw":"/disconnect","comment":"/disconnect","is_premium":true,"is_broadcaster":true,"is_staff":false,"is_anonymity":true,"score":0,"user_id":"TnPRtKVgHdYW4Uklky8yjLn982Y","user_name":"Broadcaster"}
],
};
ngm.addNgmEvHandler("nagome", this.ngmEvHandler.bind(this));
ngm.addNgmEvHandler("nagome_ui", this.ngmEvUIHandler.bind(this));
ngm.addNgmEvHandler("nagome_comment", this.ngmEvCommentHandler.bind(this));
}
ngmEvHandler(arrM) {
let st = this.state;
for (const m of arrM) {
switch (m.command) {
case "User.Update":
const ct = m.content;
let updateCount = 0;
for (let i = st.data.length-1; i >= 0 && updateCount < 10; i--) {
if (st.data[i].user_id === ct.id) {
st.data[i].user_name = ct.name;
st.data[i].user_thumbnail_url = ct.thumbnail_url;
updateCount++;
}
}
break;
default:
}
}
this.setState(st);
}
ngmEvUIHandler(arrM) {
let st = this.state;
for (const m of arrM) {
switch (m.command) {
case "ClearComments":
st = { data: [] };
break;
case "Notification":
break;
default:
console.log(m);
}
}
this.setState(st);
}
ngmEvCommentHandler(arrM) {
let st = this.state;
for (const m of arrM) {
if (m.command === "Got") {
m.content.date = m.content.date.split(RegExp('[T.]'))[1];
st.data.push(m.content);
} else {
console.log(m);
}
}
this.setState(st);
}
handleDrop(e) {
e.preventDefault(); // stop moving page
const text = e.dataTransfer.getData('Text');
ngm.broadConnect(text);
return false;
}
render() {
return (
<div className="comment fill_parent"
onDrop={this.handleDrop.bind(this)} >
<CommentList data={this.state.data} />
{ !this.props.isBroadOpen && this.state.data.length === 0 ? <DropArea /> : null }
</div>
);
}
}
|
src/components/Main.js
|
pierlo-upitup/polyrhythmical
|
import React from 'react';
import { Button, Panel}
from 'muicss/react';
import WebMidi from 'webmidi';
import Clock from './Clock';
import StepSequencer from './StepSequencer';
const TO_BIND = [
'handleOnClockTick',
'handleAddSequencer',
'handleDestroySequencer',
'handleOnClockReset',
'onWebMidiDisconnected',
'onWebMidiConnected'
];
export default class Main extends React.Component {
constructor() {
super();
TO_BIND.forEach(method => {
this[method] = this[method].bind(this);
});
this.initialRefCounter = 1;
this.sequencerRefs = [];
this.state = {
outputs: null,
sequencers: [{
ref: `--seq-${this.initialRefCounter}`,
component: StepSequencer
}]
}
}
componentDidMount() {
this.onWebMidiConnected();
}
componentWillMount() {
WebMidi.enable((err) => {
if (err) {
alert("Your browser does not support Web MIDI.");
return;
}
WebMidi.addListener("connected", this.onWebMidiConnected);
WebMidi.addListener("disconnected", this.onWebMidiDisconnected);
this.onWebMidiConnected();
});
}
componentWillUnmount() {
WebMidi.removeListener("connected", this.onWebMidiConnected);
WebMidi.removeListener("disconnected", this.onWebMidiDisconnected);
}
onWebMidiDisconnected() {
this.assignDefaultMidiDevice();
}
onWebMidiConnected() {
this.assignDefaultMidiDevice();
}
handleAddSequencer(e) {
e.preventDefault();
// TODO immutability
let newSequencers = this.state.sequencers;
newSequencers.push({
ref: `--seq-${++this.initialRefCounter}`,
component: StepSequencer
});
this.setState({sequencers: newSequencers});
}
handleDestroySequencer(id) {
let newSequencers = this.state.sequencers;
let index = newSequencers.findIndex(definition => definition.ref === id);
if (index > -1) {
newSequencers.splice(index, 1);
this.setState({sequencers: newSequencers});
}
}
handleOnClockTick(t0, t1, e = {args: null}) {
this.state.sequencers.forEach(definition => {
this.refs[definition.ref].onClockTick(...arguments);
});
}
handleOnClockReset() {
this.state.sequencers.forEach(definition => {
this.refs[definition.ref].onClockReset(...arguments);
});
}
assignDefaultMidiDevice() {
const {outputs} = WebMidi;
this.setState({outputs});
}
getSequencers() {
return this.state.sequencers.map(definition => {
let Sequencer = definition.component;
let ref = definition.ref;
return (
<Sequencer ref={ref}
key={ref}
id={ref}
onDestroy={this.handleDestroySequencer}
outputs={this.state.outputs}
onNoteOn={this.handleNoteOn}
onNoteOff={this.handleNoteOff} />
);
});
}
// TODO
// [ ] set gate duration in 1/N beats
// [ ] https://github.com/dbkaplun/euclidean-rhythm
render() {
return (
<div>
<Clock onClockTick={this.handleOnClockTick}
onClockReset={this.handleOnClockReset} />
{this.getSequencers()}
<Panel>
<Button color="primary"
onClick={this.handleAddSequencer}>
Add Step Sequencer
</Button>
</Panel>
</div>
);
}
}
|
src/components/video_list_item.js
|
akh000/YoutubeApp
|
import React from 'react';
const VideoListItem = ({ video, onVideoSelect }) => {
const imgUrl = video.snippet.thumbnails.default.url;
const title = video.snippet.title;
return(
<li
className='list-group-item' onClick={()=>onVideoSelect(video)}
>
<div className='video-list media'>
<div className='media-left'>
<img className='media-object' src={imgUrl}/>
</div>
<div className='media-body'>
<div className='media-heading'>
{title}
</div>
</div>
</div>
</li>
);
};
export default VideoListItem;
|
src/App.js
|
jamesbibby/reactnd_project_mybooks
|
import React from 'react'
import * as BooksAPI from './BooksAPI'
import SearchBooks from './SearchBooks'
import BookshelfGrid from './BookshelfGrid'
import { Route } from 'react-router-dom'
import Notifications, { notify } from 'react-notify-toast'
import './App.css'
class BooksApp extends React.Component {
// this way we can always go back to an initial state when reducing the getAll() result
initialState = {
searchResults: [],
searchResultsMessage: 'Search for books to add to your shelves!',
bookMap: {},
currentlyReading: [],
read: [],
wantToRead: [],
}
// set the state to initial state on load
state = this.initialState
// when the component mounts for the first time, retrieve the book list and categorize them
componentDidMount() {
BooksAPI.getAll()
.then(books => {
// Organize the books into a map (id:object) to allow constant time lookups
// store the shelf contents as ids, the detailed object can be retreived from the map if needed
const myState = books.reduce((state, book) => {
state.bookMap[book.id] = book
switch (book.shelf) {
case 'wantToRead':
state.wantToRead.push(book.id)
break
case 'currentlyReading':
state.currentlyReading.push(book.id)
break
case 'read':
state.read.push(book.id)
break
default:
break
}
return state
}, this.initialState)
this.setState(myState)
})
.catch(error => {
// show a small toast message when the api call fails
console.log('an error ocurred', error)
notify.show(`Failed to communicate with Books API`, 'error', 2000)
})
}
// Check if this id is in any of our shelves
getCurrentShelf = id => {
return this.state.read.includes(id)
? 'read'
: this.state.currentlyReading.includes(id)
? 'currentlyReading'
: this.state.wantToRead.includes(id) ? 'wantToRead' : 'none'
}
onSearch = term => {
// Retrieve the search results from the BooksAPI,
// filter them for unique entries and set the state
BooksAPI.search(term)
.then(books => {
if (!books || books.error || books.length === 0) {
if (books && books.error) {
notify.show('Invalid search term', 'error', 2000)
}
this.setState({
searchResults: [],
searchResultsMessage: `No results found for ${term}`,
})
return
}
// there are duplicates in the results so we need to filter
const uniqueIds = new Set()
const uniqueBooks = books.filter(book => {
if (uniqueIds.has(book.id)) {
return false
}
uniqueIds.add(book.id)
return true
})
this.setState({
searchResults: uniqueBooks,
searchResultsMessage: `${books.length} results found for ${term}`,
})
})
.catch(error => {
// show a small toast message when the api call fails
console.log('an error ocurred', error)
notify.show(`Failed to communicate with Books API`, 'error', 2000)
})
}
// clear the search results, used when the user exist the search screen
clearSearchResults = () => {
this.setState({
searchResults: this.initialState.searchResults,
searchResultsMessage: this.initialState.searchResultsMessage,
})
}
// When the shelf changes we can directly update the id list of books on each shelf
// We also need to update the current shelf of the book in the book map
// (this ensures the select box shows the correct default)
onShelfChange = (book, shelf) => {
BooksAPI.update(book, shelf)
.then(results => {
this.setState(state => {
const bookMap = { ...state.bookMap }
if (bookMap[book.id]) {
bookMap[book.id].shelf = shelf
} else {
BooksAPI.get(book.id).then(book => {
this.setState(state => {
bookMap[book.id] = book
return { bookMap }
})
})
}
// show a small toast message when the book as changed shelves
notify.show(`Succesfully moved book`, 'success', 2000)
return { ...results, bookMap }
})
})
.catch(error => {
// show a small toast message when the book as changed shelves
console.log('an error ocurred', error)
notify.show(`Failed to move book`, 'error', 2000)
})
}
render() {
return (
<div className="app">
<Notifications />
<Route
path="/search"
render={({ history }) =>
<SearchBooks
history={history}
searchResults={this.state.searchResults}
searchResultsMessage={this.state.searchResultsMessage}
clearSearchResults={this.clearSearchResults}
onSearch={this.onSearch}
onShelfChange={this.onShelfChange}
getCurrentShelf={this.getCurrentShelf}
/>}
/>
<Route
exact
path="/"
render={({ history }) =>
<div className="list-books">
<div className="list-books-title">
<h1>MyReads</h1>
</div>
<BookshelfGrid
bookMap={this.state.bookMap}
onShelfChange={this.onShelfChange}
currentlyReading={this.state.currentlyReading}
read={this.state.read}
wantToRead={this.state.wantToRead}
/>
<div className="open-search">
<a onClick={() => history.push('/search')}>Add a book</a>
</div>
</div>}
/>
</div>
)
}
}
export default BooksApp
|
src/components/MenuBar.js
|
cannc4/Siren
|
import React from 'react';
import { inject, observer } from 'mobx-react';
// import _ from 'lodash'
// CSS Imports
import '../styles/App.css';
import '../styles/Layout.css';
import '../styles/MenuBar.css';
import '../styles/Help.css';
// import Popup from "reactjs-popup";
@inject('menubarStore', 'pulseStore', 'pathStore')
@observer
export default class MenuBar extends React.Component {
render() {
// console.log("RENDER MENUBAR.JS");
let serverStatusClass = 'ServerStatus';
if (this.props.menubarStore.getActive <= 0)
serverStatusClass += ' inactive';
else if (this.props.menubarStore.getActive === 1)
serverStatusClass += ' ready';
else if (this.props.menubarStore.getActive === 2)
serverStatusClass += ' running';
const startServer = () => {
this.props.menubarStore.bootServer(this.props.pathStore.paths);
}
const stopServer = () => {
this.props.menubarStore.stopServer()
}
return (<div className='MenuBar boxshadow'>
<div className={'Logo'} id={'logo_disp'} title={"Refresh"}>
{<img
onClick={() => {if(window.confirm('Do you want to refresh page? Unsaved changes will be destroyed.')) {
window.location.reload(false)}}}
alt=""
src={require('../assets/logo.svg')}
height={30} width={30} />}
</div>
<div className={'TimerControls'}>
{/* RMS SHAPE LEFT */}
{/* <canvas className={'RMSVis'} id={'RMSVis_Left'}
width={menubarStore.rmsArray.length * 0.5 * 20} height={30}>
</canvas> */}
{<button className={'Button'} title={'Stop Pulse'}
onClick={() => (this.props.pulseStore.stopPulseStop())}>◼</button>}
{!this.props.pulseStore.isActive &&
<button className={'Button'} title={'Start Pulse'}
onClick={() => (this.props.pulseStore.startPulse())}>▶</button>}
{this.props.pulseStore.isActive &&
<button className={'Button'} title={'Pause Pulse'}
onClick={() => (this.props.pulseStore.stopPulse())}>||</button>}
<div style={{borderLeft: "1px solid var(--global-color)", height: "90%", marginLeft: "5px", marginRight: "10px"}}></div>
{<button className={'Button ' + (this.props.menubarStore.isRecording ? 'Record' : '')}
title={(this.props.menubarStore.isRecording ? 'Recording...' : 'Start recording')}
onClick={() => {this.props.menubarStore.toggleRecording()}}>
⬤
</button>}
{/* RMS SHAPE RIGHT */}
{/* <canvas className={'RMSVis'} id={'RMSVis_Right'}
width={menubarStore.rmsArray.length * 0.5 * 20} height={30}>
</canvas> */}
</div>
{/* <div className={'OtherControls'}>
{!this.props.menubarStore.isPlaying && <button className={'Button '}
onClick={() => this.props.menubarStore.togglePlay()}>
>
</button>}
{this.props.menubarStore.isPlaying && <button className={'Button '}
onClick={() => this.props.menubarStore.togglePlay()}>
||
</button>}
</div> */}
<div className= 'OtherControls'>
<div className={serverStatusClass} title={"Server Status"} ></div>
{this.props.menubarStore.getActive === 0 &&
<button className={'Button draggableCancel ' }
onClick={startServer} title={"Initalize Server"}> Start </button>}
{this.props.menubarStore.getActive === 1 &&
<button className={'Button draggableCancel disabledView' }
title={"Booting Server"}> Loading </button>}
{this.props.menubarStore.getActive === 2 &&
<button className={'Button draggableCancel ' }
onClick={stopServer} title={"Terminate Server"}> Stop </button>}
{/* <Popup trigger={<button className={'Button draggableCancel'} title={"Help"} > Help</button>} position={'bottom right'}>
<div className={'helpContainer'}>
TODO
</div>
</Popup> */}
</div>
</div>)
}
}
|
src/parser/warlock/destruction/modules/features/Havoc.js
|
sMteX/WoWAnalyzer
|
import React from 'react';
import Analyzer, { SELECTED_PLAYER } from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
import Events from 'parser/core/Events';
import SPELLS from 'common/SPELLS';
import { formatThousands, formatNumber, formatPercentage } from 'common/format';
import Statistic from 'interface/statistics/Statistic';
import BoringSpellValueText from 'interface/statistics/components/BoringSpellValueText';
import STATISTIC_ORDER from 'interface/others/STATISTIC_ORDER';
class Havoc extends Analyzer {
static dependencies = {
enemies: Enemies,
};
damage = 0;
constructor(...args) {
super(...args);
this.addEventListener(Events.damage.by(SELECTED_PLAYER), this.onDamage);
}
onDamage(event) {
const enemy = this.enemies.getEntity(event);
if (!enemy || !enemy.hasBuff(SPELLS.HAVOC.id, event.timestamp)) {
return;
}
this.damage += event.amount + (event.absorbed || 0);
}
get dps() {
return this.damage / this.owner.fightDuration * 1000;
}
// TODO: this could perhaps be reworked somehow to be more accurate but not sure how yet. Take it as a Havoc v1.0
statistic() {
if (this.damage === 0) {
return null;
}
return (
<Statistic
position={STATISTIC_ORDER.CORE(5)}
size="small"
tooltip={(
<>
You cleaved {formatThousands(this.damage)} damage to targets afflicted by your Havoc.<br /><br />
Note: This number is probably higher than it should be, as it also counts the damage you did directly to the Havoc target (not just the cleaved damage).
</>
)}
>
<BoringSpellValueText spell={SPELLS.HAVOC}>
{formatNumber(this.dps)} DPS <small>{formatPercentage(this.owner.getPercentageOfTotalDamageDone(this.damage))} % of total</small>
</BoringSpellValueText>
</Statistic>
);
}
}
export default Havoc;
|
client/DevTools.js
|
cavnak/throneteki
|
import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
const DevTools = createDevTools(
// Monitors are individually adjustable with props.
// Consult their repositories to learn about those props.
// Here, we put LogMonitor inside a DockMonitor.
// Note: DockMonitor is visible by default.
<DockMonitor toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'
defaultIsVisible={ false }>
<LogMonitor theme='tomorrow' />
</DockMonitor>
);
export default DevTools;
|
src/Routes.js
|
material-components/material-components-web-catalog
|
import React from 'react';
import {Route} from 'react-router-dom';
import ButtonCatalog from './ButtonCatalog';
import CardCatalog from './CardCatalog';
import CheckboxCatalog from './CheckboxCatalog';
import ChipsCatalog from './ChipsCatalog';
import DataTableCatalog from './DataTableCatalog';
import DialogCatalog from './DialogCatalog';
import DrawerCatalog from './DrawerCatalog';
import ElevationCatalog from './ElevationCatalog';
import FabCatalog from './FabCatalog';
import IconButtonCatalog from './IconButtonCatalog';
import ImageListCatalog from './ImageListCatalog';
import LayoutGridCatalog from './LayoutGridCatalog';
import LinearProgressIndicatorCatalog from './LinearProgressIndicatorCatalog';
import ListCatalog from './ListCatalog';
import MenuCatalog from './MenuCatalog';
import RadioButtonCatalog from './RadioButtonCatalog';
import RippleCatalog from './RippleCatalog';
import SelectCatalog from './SelectCatalog';
import SliderCatalog from './SliderCatalog';
import SnackbarCatalog from './SnackbarCatalog';
import SwitchCatalog from './SwitchCatalog';
import TabsCatalog from './TabsCatalog';
import TextFieldCatalog from './TextFieldCatalog';
import TopAppBarCatalog from './TopAppBarCatalog';
import TypographyCatalog from './TypographyCatalog';
const routesList = [{
urlPath: 'button',
Component: ButtonCatalog,
}, {
urlPath: 'card',
Component: CardCatalog,
}, {
urlPath: 'checkbox',
Component: CheckboxCatalog,
}, {
urlPath: 'chips',
Component: ChipsCatalog,
}, {
urlPath: 'data-table',
Component: DataTableCatalog,
}, {
urlPath: 'dialog',
Component: DialogCatalog,
}, {
urlPath: 'drawer',
Component: DrawerCatalog,
}, {
urlPath: 'elevation',
Component: ElevationCatalog,
}, {
urlPath: 'fab',
Component: FabCatalog,
}, {
urlPath: 'icon-button',
Component: IconButtonCatalog,
}, {
urlPath: 'image-list',
Component: ImageListCatalog,
}, {
urlPath: 'layout-grid',
Component: LayoutGridCatalog,
}, {
urlPath: 'linear-progress-indicator',
Component: LinearProgressIndicatorCatalog,
}, {
urlPath: 'list',
Component: ListCatalog,
}, {
urlPath: 'menu',
Component: MenuCatalog,
}, {
urlPath: 'radio',
Component: RadioButtonCatalog,
}, {
urlPath: 'ripple',
Component: RippleCatalog,
}, {
urlPath: 'select',
Component: SelectCatalog,
}, {
urlPath: 'slider',
Component: SliderCatalog,
}, {
urlPath: 'snackbar',
Component: SnackbarCatalog,
}, {
urlPath: 'switch',
Component: SwitchCatalog,
}, {
urlPath: 'tabs',
Component: TabsCatalog,
}, {
urlPath: 'text-field',
Component: TextFieldCatalog,
}, {
urlPath: 'top-app-bar',
Component: TopAppBarCatalog,
}, {
urlPath: 'typography',
Component: TypographyCatalog,
}];
const Routes = () => {
return (
routesList.map((route) => {
const {Component, urlPath} = route;
return (
<Route
key={urlPath}
path={`/component/${urlPath}`}
render={(props) => <Component {...props}/>} />
);
})
);
}
export default Routes;
|
docs/src/app/components/pages/components/TextField/ExampleCustomize.js
|
andrejunges/material-ui
|
import React from 'react';
import TextField from 'material-ui/TextField';
import {orange500, blue500} from 'material-ui/styles/colors';
const styles = {
errorStyle: {
color: orange500,
},
underlineStyle: {
borderColor: orange500,
},
floatingLabelStyle: {
color: orange500,
},
floatingLabelFocusStyle: {
color: blue500,
},
};
const TextFieldExampleCustomize = () => (
<div>
<TextField
hintText="Styled Hint Text"
hintStyle={styles.errorStyle}
/><br />
<TextField
hintText="Custom error color"
errorText="This field is required."
errorStyle={styles.errorStyle}
/><br />
<TextField
hintText="Custom Underline Color"
underlineStyle={styles.underlineStyle}
/><br />
<TextField
hintText="Custom Underline Focus Color"
underlineFocusStyle={styles.underlineStyle}
/><br />
<TextField
floatingLabelText="Styled Floating Label Text"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
/>
</div>
);
export default TextFieldExampleCustomize;
|
stories/EditProfileCategory.stories.js
|
nekuno/client
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { action } from '@storybook/addon-actions';
import { linkTo } from '@storybook/addon-links'
import EditProfileCategory from '../src/js/components/ui/EditProfileCategory/EditProfileCategory.js';
storiesOf('EditProfileCategory', module)
.add('with text', () => (
<EditProfileCategory onClickHandler={action('clicked')}>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam et elit ante.
</EditProfileCategory>
))
.add('with HTML', () => (
<EditProfileCategory onClickHandler={action('clicked')}>
<div>Lorem ipsum</div>
<br/>
<div>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam et elit ante.</div>
</EditProfileCategory>
));
|
tests/routes/Home/components/HomeView.spec.js
|
alexblacksnow/alexblacksnow.github.io
|
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!/)
})
})
|
node_modules/_rc-calendar@9.0.4@rc-calendar/es/calendar/CalendarHeader.js
|
ligangwolai/blog
|
import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
import MonthPanel from '../month/MonthPanel';
import YearPanel from '../year/YearPanel';
import toFragment from 'rc-util/es/Children/mapSelf';
function goMonth(direction) {
var next = this.props.value.clone();
next.add(direction, 'months');
this.props.onValueChange(next);
}
function goYear(direction) {
var next = this.props.value.clone();
next.add(direction, 'years');
this.props.onValueChange(next);
}
function showIf(condition, el) {
return condition ? el : null;
}
var CalendarHeader = createReactClass({
displayName: 'CalendarHeader',
propTypes: {
prefixCls: PropTypes.string,
value: PropTypes.object,
onValueChange: PropTypes.func,
showTimePicker: PropTypes.bool,
showMonthPanel: PropTypes.bool,
showYearPanel: PropTypes.bool,
onPanelChange: PropTypes.func,
locale: PropTypes.object,
enablePrev: PropTypes.any,
enableNext: PropTypes.any,
disabledMonth: PropTypes.func
},
getDefaultProps: function getDefaultProps() {
return {
enableNext: 1,
enablePrev: 1,
onPanelChange: function onPanelChange() {},
onValueChange: function onValueChange() {}
};
},
getInitialState: function getInitialState() {
this.nextMonth = goMonth.bind(this, 1);
this.previousMonth = goMonth.bind(this, -1);
this.nextYear = goYear.bind(this, 1);
this.previousYear = goYear.bind(this, -1);
var _props = this.props,
showMonthPanel = _props.showMonthPanel,
showYearPanel = _props.showYearPanel;
return { showMonthPanel: showMonthPanel, showYearPanel: showYearPanel };
},
componentWillReceiveProps: function componentWillReceiveProps() {
var props = this.props;
if ('showMonthpanel' in props) {
this.setState({ showMonthPanel: props.showMonthPanel });
}
if ('showYearpanel' in props) {
this.setState({ showYearPanel: props.showYearPanel });
}
},
onSelect: function onSelect(value) {
this.triggerPanelChange({
showMonthPanel: 0,
showYearPanel: 0
});
this.props.onValueChange(value);
},
triggerPanelChange: function triggerPanelChange(panelStatus) {
if (!('showMonthPanel' in this.props)) {
this.setState({ showMonthPanel: panelStatus.showMonthPanel });
}
if (!('showYearPanel' in this.props)) {
this.setState({ showYearPanel: panelStatus.showYearPanel });
}
this.props.onPanelChange(panelStatus);
},
monthYearElement: function monthYearElement(showTimePicker) {
var props = this.props;
var prefixCls = props.prefixCls;
var locale = props.locale;
var value = props.value;
var localeData = value.localeData();
var monthBeforeYear = locale.monthBeforeYear;
var selectClassName = prefixCls + '-' + (monthBeforeYear ? 'my-select' : 'ym-select');
var year = React.createElement(
'a',
{
className: prefixCls + '-year-select',
role: 'button',
onClick: showTimePicker ? null : this.showYearPanel,
title: locale.yearSelect
},
value.format(locale.yearFormat)
);
var month = React.createElement(
'a',
{
className: prefixCls + '-month-select',
role: 'button',
onClick: showTimePicker ? null : this.showMonthPanel,
title: locale.monthSelect
},
localeData.monthsShort(value)
);
var day = void 0;
if (showTimePicker) {
day = React.createElement(
'a',
{
className: prefixCls + '-day-select',
role: 'button'
},
value.format(locale.dayFormat)
);
}
var my = [];
if (monthBeforeYear) {
my = [month, day, year];
} else {
my = [year, month, day];
}
return React.createElement(
'span',
{ className: selectClassName },
toFragment(my)
);
},
showMonthPanel: function showMonthPanel() {
this.triggerPanelChange({
showMonthPanel: 1,
showYearPanel: 0
});
},
showYearPanel: function showYearPanel() {
this.triggerPanelChange({
showMonthPanel: 0,
showYearPanel: 1
});
},
render: function render() {
var props = this.props,
state = this.state;
var prefixCls = props.prefixCls,
locale = props.locale,
value = props.value,
showTimePicker = props.showTimePicker,
enableNext = props.enableNext,
enablePrev = props.enablePrev,
disabledMonth = props.disabledMonth;
var panel = null;
if (state.showMonthPanel) {
panel = React.createElement(MonthPanel, {
locale: locale,
defaultValue: value,
rootPrefixCls: prefixCls,
onSelect: this.onSelect,
disabledDate: disabledMonth
});
} else if (state.showYearPanel) {
panel = React.createElement(YearPanel, {
locale: locale,
defaultValue: value,
rootPrefixCls: prefixCls,
onSelect: this.onSelect
});
}
return React.createElement(
'div',
{ className: prefixCls + '-header' },
React.createElement(
'div',
{ style: { position: 'relative' } },
showIf(enablePrev && !showTimePicker, React.createElement('a', {
className: prefixCls + '-prev-year-btn',
role: 'button',
onClick: this.previousYear,
title: locale.previousYear
})),
showIf(enablePrev && !showTimePicker, React.createElement('a', {
className: prefixCls + '-prev-month-btn',
role: 'button',
onClick: this.previousMonth,
title: locale.previousMonth
})),
this.monthYearElement(showTimePicker),
showIf(enableNext && !showTimePicker, React.createElement('a', {
className: prefixCls + '-next-month-btn',
onClick: this.nextMonth,
title: locale.nextMonth
})),
showIf(enableNext && !showTimePicker, React.createElement('a', {
className: prefixCls + '-next-year-btn',
onClick: this.nextYear,
title: locale.nextYear
}))
),
panel
);
}
});
export default CalendarHeader;
|
packages/cf-component-checkbox/example/basic/component.js
|
manatarms/cf-ui
|
import React from 'react';
import { Checkbox, CheckboxGroup } from 'cf-component-checkbox';
class CheckboxComponent extends React.Component {
constructor(props) {
super(props);
this.state = {
checkbox1: true,
checkbox2: false,
checkboxValues: ['option1']
};
this.onCheckboxGroupChange = this.onCheckboxGroupChange.bind(this);
}
onCheckboxGroupChange(values) {
this.setState({
checkboxValues: values
});
}
render() {
return (
<div>
<p>You can create them individually with <code>Checkbox</code></p>
<Checkbox
label="Checkbox 1"
name="checkbox-1"
value="checkbox1"
checked={this.state.checkbox1}
onChange={checked => this.setState({ checkbox1: checked })}
/>
<Checkbox
label="Checkbox 2"
name="checkbox-2"
value="checkbox2"
checked={this.state.checkbox2}
onChange={checked => this.setState({ checkbox2: checked })}
/>
<p>Or as a group with <code>CheckboxGroup</code></p>
<CheckboxGroup
values={this.state.checkboxValues}
onChange={this.onCheckboxGroupChange}
options={[
{ label: 'Option 1', name: 'group-option-1', value: 'option1' },
{ label: 'Option 2', name: 'group-option-2', value: 'option2' }
]}
/>
<p>
You can also disable a label by passing <code>false</code> explicitly
</p>
<Checkbox
label={false}
name="checkbox-1-no-label"
value="checkbox1"
checked={this.state.checkbox1}
onChange={checked => this.setState({ checkbox1: checked })}
/>
</div>
);
}
}
export default CheckboxComponent;
|
src/main.js
|
nordsoftware/react-starter
|
/*eslint no-undef: 0*/
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import { Provider } from 'react-redux';
import { syncHistoryWithStore } from 'react-router-redux';
import { buildStore } from './helpers/store';
import getRoutes from './routes';
import './main.scss';
const store = buildStore();
const history = syncHistoryWithStore(browserHistory, store);
render(
<Provider store={store}>
<Router onUpdate={() => window.scrollTo(0, 0)} history={history}>
{getRoutes()}
</Router>
</Provider>,
document.getElementById('root')
);
|
examples/pinterest/app.js
|
fanhc019/react-router
|
import React from 'react';
import { Router, Route, IndexRoute, Link } from 'react-router';
var PICTURES = [
{ id: 0, src: 'http://placekitten.com/601/601' },
{ id: 1, src: 'http://placekitten.com/610/610' },
{ id: 2, src: 'http://placekitten.com/620/620' }
];
var Modal = React.createClass({
styles: {
position: 'fixed',
top: '20%',
right: '20%',
bottom: '20%',
left: '20%',
padding: 20,
boxShadow: '0px 0px 150px 130px rgba(0, 0, 0, 0.5)',
overflow: 'auto',
background: '#fff'
},
render () {
return (
<div style={this.styles}>
<p><Link to={this.props.returnTo}>Back</Link></p>
{this.props.children}
</div>
)
}
})
var App = React.createClass({
componentWillReceiveProps (nextProps) {
// if we changed routes...
if ((
nextProps.location.key !== this.props.location.key &&
nextProps.location.state &&
nextProps.location.state.modal
)) {
// save the old children (just like animation)
this.previousChildren = this.props.children
}
},
render() {
var { location } = this.props
var isModal = (
location.state &&
location.state.modal &&
this.previousChildren
)
return (
<div>
<h1>Pinterest Style Routes</h1>
<div>
{isModal ?
this.previousChildren :
this.props.children
}
{isModal && (
<Modal isOpen={true} returnTo={location.state.returnTo}>
{this.props.children}
</Modal>
)}
</div>
</div>
);
}
});
var Index = React.createClass({
render () {
return (
<div>
<p>
The url `/pictures/:id` can be rendered anywhere in the app as a modal.
Simply put `modal: true` in the `state` prop of links.
</p>
<p>
Click on an item and see its rendered as a modal, then copy/paste the
url into a different browser window (with a different session, like
Chrome -> Firefox), and see that the image does not render inside the
overlay. One URL, two session dependent screens :D
</p>
<div>
{PICTURES.map(picture => (
<Link key={picture.id} to={`/pictures/${picture.id}`} state={{ modal: true, returnTo: this.props.location.pathname }}>
<img style={{ margin: 10 }} src={picture.src} height="100" />
</Link>
))}
</div>
<p><Link to="/some/123/deep/456/route">Go to some deep route</Link></p>
</div>
)
}
})
var Deep = React.createClass({
render () {
return (
<div>
<p>You can link from anywhere really deep too</p>
<p>Params stick around: {this.props.params.one} {this.props.params.two}</p>
<p>
<Link to={`/pictures/0`} state={{ modal: true, returnTo: this.props.location.pathname}}>
Link to picture with Modal
</Link><br/>
<Link to={`/pictures/0`}>
Without modal
</Link>
</p>
</div>
)
}
})
var Picture = React.createClass({
render() {
return (
<div>
<img src={PICTURES[this.props.params.id].src} style={{ height: '80%' }} />
</div>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<IndexRoute component={Index}/>
<Route path="/pictures/:id" component={Picture}/>
<Route path="/some/:one/deep/:two/route" component={Deep}/>
</Route>
</Router>
), document.getElementById('example'))
|
server/sonar-web/src/main/js/app/components/nav/global/GlobalNavUser.js
|
Builders-SonarSource/sonarqube-bis
|
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser 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 React from 'react';
import { Link, withRouter } from 'react-router';
import Avatar from '../../../../components/ui/Avatar';
import { translate } from '../../../../helpers/l10n';
class GlobalNavUser extends React.Component {
handleLogin = e => {
e.preventDefault();
const returnTo = window.location.pathname + window.location.search;
window.location = `${window.baseUrl}/sessions/new?return_to=${encodeURIComponent(returnTo)}${window.location.hash}`;
};
handleLogout = e => {
e.preventDefault();
this.props.router.push('/sessions/logout');
};
renderAuthenticated () {
const { currentUser } = this.props;
return (
<li className="dropdown js-user-authenticated">
<a className="dropdown-toggle" data-toggle="dropdown" href="#">
<Avatar email={currentUser.email} size={20}/>
{currentUser.name} <i className="icon-dropdown"/>
</a>
<ul className="dropdown-menu dropdown-menu-right">
<li>
<Link to="/account">{translate('my_account.page')}</Link>
</li>
<li>
<a onClick={this.handleLogout} href="#">{translate('layout.logout')}</a>
</li>
</ul>
</li>
);
}
renderAnonymous () {
return (
<li>
<a onClick={this.handleLogin} href="#">{translate('layout.login')}</a>
</li>
);
}
render () {
return this.props.currentUser.isLoggedIn ? this.renderAuthenticated() : this.renderAnonymous();
}
}
export default withRouter(GlobalNavUser);
|
node_modules/@material-ui/core/es/Table/TableContext.js
|
pcclarke/civ-techs
|
import React from 'react';
/**
* @ignore - internal component.
*/
const TableContext = React.createContext();
export default TableContext;
|
lib/Datepicker/stories/BasicUsage.js
|
folio-org/stripes-components
|
/**
* Datepicker: Basic Usage
*/
import React from 'react';
import DatepickerDemo from './DatepickerDemo';
const BasicUsage = () => (
<div>
<DatepickerDemo />
</div>
);
export default BasicUsage;
|
docs/app/components/preview/index.js
|
react-toolbox/react-toolbox
|
/* eslint-disable no-eval*/
import React from 'react';
import PropTypes from 'prop-types';
import ReactDOM from 'react-dom';
import { transform } from 'babel-standalone';
import * as ReactToolbox from 'react-toolbox';
import style from './style.css';
const ERROR_TIMEOUT = 500;
const Preview = React.createClass({
propTypes: {
className: PropTypes.string,
code: PropTypes.string.isRequired,
scope: PropTypes.object
},
getDefaultProps () {
return {
className: '',
scope: { React, ...ReactToolbox }
};
},
getInitialState () {
return {
error: null
};
},
componentDidMount () {
this.executeCode();
},
componentDidUpdate (prevProps) {
clearTimeout(this.timeoutID);
if (this.props.code !== prevProps.code) {
this.executeCode();
}
},
setTimeout () {
clearTimeout(this.timeoutID);
this.timeoutID = setTimeout(...arguments);
},
compileCode () {
const code = `
(function (${Object.keys(this.props.scope).join(', ')}, mountNode) {
${this.props.code}
});`;
return transform(code, {
presets: ['es2015', 'stage-0', 'react']
}).code;
},
buildScope (mountNode) {
return Object.keys(this.props.scope).map(key => this.props.scope[key]).concat(mountNode);
},
executeCode () {
const mountNode = this.refs.mount;
const scope = this.buildScope(mountNode);
try {
ReactDOM.unmountComponentAtNode(mountNode);
} catch (e) {
console.error(e);
}
try {
ReactDOM.render(eval(this.compileCode())(...scope), mountNode);
if (this.state.error) {
this.setState({ error: null });
}
} catch (err) {
this.setTimeout(() => {
this.setState({ error: err.toString() });
}, ERROR_TIMEOUT);
}
},
render () {
let className = style.preview;
if (this.props.className) className += ` ${this.props.className}`;
return (
<div className={className}>
{this.state.error !== null ? <span className={style.error}>{this.state.error}</span> : null}
<div ref="mount" className={style.content} />
</div>
);
}
});
export default Preview;
|
src/routes/ui/dropOption/index.js
|
liufulin90/react-admin
|
import React from 'react'
import { DropOption } from '../../../components'
import { Table, Row, Col, Card, message } from 'antd'
const DropOptionPage = () => <div className="content-inner">
<Row gutter={32}>
<Col lg={8} md={12}>
<Card title="默认">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="样式">
<DropOption menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]} buttonStyle={{ border: 'solid 1px #eee', width: 60 }} />
</Card>
</Col>
<Col lg={8} md={12}>
<Card title="事件">
<DropOption
menuOptions={[{ key: '1', name: '编辑' }, { key: '2', name: '删除' }]}
buttonStyle={{ border: 'solid 1px #eee', width: 60 }}
onMenuClick={({ key }) => {
switch (key) {
case '1':
message.success('点击了编辑')
break
case '2':
message.success('点击了删除')
break
default:
break
}
}}
/>
</Card>
</Col>
</Row>
<h2 style={{ margin: '16px 0' }}>Props</h2>
<Row>
<Col lg={18} md={24}>
<Table
rowKey={(record, key) => key}
pagination={false}
bordered
scroll={{ x: 800 }}
columns={[
{
title: '参数',
dataIndex: 'props',
},
{
title: '说明',
dataIndex: 'desciption',
},
{
title: '类型',
dataIndex: 'type',
},
{
title: '默认值',
dataIndex: 'default',
},
]}
dataSource={[
{
props: 'menuOptions',
desciption: '下拉操作的选项,格式为[{name:string,key:string}]',
type: 'Array',
default: '必选',
},
{
props: 'onMenuClick',
desciption: '点击 menuitem 调用此函数,参数为 {item, key, keyPath}',
type: 'Function',
default: '-',
},
{
props: 'buttonStyle',
desciption: '按钮的样式',
type: 'Object',
default: '-',
},
{
props: 'dropdownProps',
desciption: '下拉菜单的参数,可参考antd的【Dropdown】组件',
type: 'Object',
default: '-',
},
]}
/>
</Col>
</Row>
</div>
export default DropOptionPage
|
test/components/Counter.spec.js
|
Lucassios/simple-video-library-react
|
import { spy } from 'sinon';
import React from 'react';
import { shallow } from 'enzyme';
import { BrowserRouter as Router } from 'react-router-dom';
import renderer from 'react-test-renderer';
import Counter from '../../app/components/Counter';
function setup() {
const actions = {
increment: spy(),
incrementIfOdd: spy(),
incrementAsync: spy(),
decrement: spy()
};
const component = shallow(<Counter counter={1} {...actions} />);
return {
component,
actions,
buttons: component.find('button'),
p: component.find('.counter')
};
}
describe('Counter component', () => {
it('should should display count', () => {
const { p } = setup();
expect(p.text()).toMatch(/^1$/);
});
it('should first button should call increment', () => {
const { buttons, actions } = setup();
buttons.at(0).simulate('click');
expect(actions.increment.called).toBe(true);
});
it('should match exact snapshot', () => {
const { actions } = setup();
const tree = renderer
.create(
<div>
<Router>
<Counter counter={1} {...actions} />
</Router>
</div>
)
.toJSON();
expect(tree).toMatchSnapshot();
});
it('should second button should call decrement', () => {
const { buttons, actions } = setup();
buttons.at(1).simulate('click');
expect(actions.decrement.called).toBe(true);
});
it('should third button should call incrementIfOdd', () => {
const { buttons, actions } = setup();
buttons.at(2).simulate('click');
expect(actions.incrementIfOdd.called).toBe(true);
});
it('should fourth button should call incrementAsync', () => {
const { buttons, actions } = setup();
buttons.at(3).simulate('click');
expect(actions.incrementAsync.called).toBe(true);
});
});
|
src/CreateGoalPanel1/index.js
|
DuckyTeam/ducky-components
|
import React from 'react';
import PropTypes from 'prop-types';
import SectionHeaderGeneral from '../SectionHeaderGeneral';
import GoalMenuItem from '../GoalMenuItem';
import Spacer from '../Spacer';
import styles from './styles.css';
import SectionFooterNew from '../SectionFooterNew';
function CreateGoalPanel1(props) {
return (
<div className={styles.outerWrapper}>
<SectionHeaderGeneral
children={props.children}
rightIcon={"icon-close"}
title={props.title}
/>
<Spacer
size={"standard"}
/>
<GoalMenuItem
inactive={props.inactive}
onClick={props.onClick}
type={"co2"}
/>
<Spacer
className={styles.hr2}
hr={"true"}
size={"hr2"}
/>
<GoalMenuItem
inactive={props.inactive}
onClick={props.onClick}
type={'points'}
/>
<Spacer
className={styles.hr2}
hr={"true"}
size={"hr2"}
/>
<GoalMenuItem
inactive={props.inactive}
onClick={props.onClick}
type={'activity'}
/>
<Spacer
className={styles.hr2}
hr={"true"}
size={"hr2"}
/>
<GoalMenuItem
inactive={props.inactive}
onClick={props.onClick}
type={'habit'}
/>
<Spacer
hr={"true"}
size={'double'}
/>
<SectionFooterNew
className={styles.footer}
text={props.text}
type={'SEF005'}
/>
</div>
);
}
CreateGoalPanel1.propTypes = {
children: PropTypes.string,
className: PropTypes.string,
inactive: PropTypes.bool,
onClick: PropTypes.func,
rightIcon: PropTypes.string,
text: PropTypes.string,
title: PropTypes.string,
type: PropTypes.string
};
export default CreateGoalPanel1;
|
docs/src/app/components/pages/components/Menu/ExampleSimple.js
|
lawrence-yu/material-ui
|
import React from 'react';
import Paper from 'material-ui/Paper';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
const style = {
display: 'inline-block',
margin: '16px 32px 16px 0',
};
const MenuExampleSimple = () => (
<div>
<Paper style={style}>
<Menu>
<MenuItem primaryText="Maps" />
<MenuItem primaryText="Books" />
<MenuItem primaryText="Flights" />
<MenuItem primaryText="Apps" />
</Menu>
</Paper>
<Paper style={style}>
<Menu>
<MenuItem primaryText="Refresh" />
<MenuItem primaryText="Help & feedback" />
<MenuItem primaryText="Settings" />
<MenuItem primaryText="Sign out" />
</Menu>
</Paper>
</div>
);
export default MenuExampleSimple;
|
generators/electron/modules/test/components/Counter.spec.js
|
sahat/megaboilerplate
|
/* eslint no-unused-expressions: 0 */
import { expect } from 'chai';
import { spy } from 'sinon';
import React from 'react';
import {
renderIntoDocument,
scryRenderedDOMComponentsWithTag,
findRenderedDOMComponentWithClass,
Simulate
} from 'react-addons-test-utils';
import Counter from '../../app/components/Counter';
function setup() {
const actions = {
increment: spy(),
incrementIfOdd: spy(),
incrementAsync: spy(),
decrement: spy()
};
const component = renderIntoDocument(<Counter counter={1} {...actions} />);
return {
component,
actions,
buttons: scryRenderedDOMComponentsWithTag(component, 'button').map(button => button),
p: findRenderedDOMComponentWithClass(component, 'counter')
};
}
describe('Counter component', () => {
it('should display count', () => {
const { p } = setup();
expect(p.textContent).to.match(/^1$/);
});
it('first button should call increment', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[0]);
expect(actions.increment.called).to.be.true;
});
it('second button should call decrement', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[1]);
expect(actions.decrement.called).to.be.true;
});
it('third button should call incrementIfOdd', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[2]);
expect(actions.incrementIfOdd.called).to.be.true;
});
it('fourth button should call incrementAsync', () => {
const { buttons, actions } = setup();
Simulate.click(buttons[3]);
expect(actions.incrementAsync.called).to.be.true;
});
});
|
client/node_modules/uu5g03/dist-node/forms/auto-complete.js
|
UnicornCollege/ucl.itkpd.configurator
|
import React from 'react';
import {BaseMixin, ElementaryMixin, ContentMixin} from './../common/common.js';
import {Link, Backdrop} from './../bricks/bricks.js';
import $ from 'jquery';
import './auto-complete.less';
export default React.createClass({
mixins: [
BaseMixin,
ElementaryMixin,
ContentMixin
],
statics: {
tagName: 'UU5.Forms.AutoComplete',
classNames: {
main: 'uu5-forms-auto-complete',
open: 'uu5-forms-auto-complete-opened',
menu: 'uu5-forms-auto-complete-menu list-group',
item: 'uu5-forms-auto-complete-item list-group-item',
selected: 'uu5-forms-auto-complete-selected'
}
},
propTypes: {
items: React.PropTypes.arrayOf(
React.PropTypes.shape({
value: React.PropTypes.string.isRequired,
params: React.PropTypes.object,
content: React.PropTypes.any
})
),
onClick: React.PropTypes.func
},
// Setting defaults
getDefaultProps: function () {
return {
items: null,
onClick: null
};
},
getInitialState: function () {
return {
items: null,
selectedIndex: null
};
},
// Interface
find: function (foundValue, setStateCallback) {
var values = { first: [], last: [] };
this.props.items.forEach(function (item) {
if (foundValue !== '') {
if (new RegExp('^' + foundValue, 'i').exec(item.value)) {
values.first.push(item);
} else if (new RegExp(foundValue, 'gi').exec(item.value)) {
values.last.push(item);
}
}
});
var allValues = values.first.concat(values.last);
this.setState({ items: allValues.length ? allValues : null, selectedIndex: null }, setStateCallback);
return this;
},
close: function (setStateCallback) {
this.setState({ items: null, selectedIndex: null }, setStateCallback);
return this;
},
isOpened: function () {
return !!this.state.items;
},
selectUp: function (setStateCallback) {
var autoComplete = this;
this.setState(function (state) {
var index = null;
if (autoComplete.state.items) {
if (state.selectedIndex == null || state.selectedIndex === 0) {
index = autoComplete.state.items.length - 1;
} else {
index = state.selectedIndex - 1;
}
}
var offset = index > autoComplete.state.items.length - 3 ?
$('#' + autoComplete.getId() + '-item-' + (autoComplete.state.items.length - 1))[0].offsetTop :
index - 1 > 0 ? $('#' + autoComplete.getId() + '-item-' + (index - 1))[0].offsetTop : 0;
$('#' + this.getId() + '-menu').animate({ scrollTop: offset }, 0);
return { selectedIndex: index };
}, setStateCallback);
return this;
},
selectDown: function (setStateCallback) {
var autoComplete = this;
this.setState(function (state) {
var index = null;
var newState;
if (autoComplete.state.items) {
if (state.selectedIndex == null || state.selectedIndex === autoComplete.state.items.length - 1) {
index = 0;
} else {
index = state.selectedIndex + 1;
}
var offset = index > 1 ? $('#' + autoComplete.getId() + '-item-' + (index - 1))[0].offsetTop : 0;
$('#' + autoComplete.getId() + '-menu').animate({ scrollTop: offset }, 0);
newState = { selectedIndex: index };
} else {
newState = {
items: autoComplete.props.items.sort(function (a, b) {
if (a < b) return -1;
if (a > b) return 1;
return 0;
}), selectedIndex: 0
};
}
return newState;
}, setStateCallback);
return this;
},
confirmSelected: function (setStateCallback) {
this.state.items && this._confirm(this.state.items[this.state.selectedIndex], this.state.selectedIndex, setStateCallback);
return this;
},
// Overriding Functions
// Component Specific Helpers
_getBackdropProps: function () {
var backdropId = this.getId() + "-backdrop";
return {
hidden: !this.isOpened(),
id: backdropId,
onClick: function (backdrop, event) {
event.target.id === backdropId && this.close();
}.bind(this)
};
},
_onClick: function (value, i) {
this._confirm(value, i);
return this;
},
_confirm: function (item, i, setStateCallback) {
if (typeof this.props.onClick === 'function') {
this.props.onClick({ value: item.value, item: item, index: i, component: this });
}
this.close(setStateCallback);
return this;
},
_getChildren: function () {
var autoComplete = this;
return this.state.items && this.state.items.map(function (item, i) {
var className = autoComplete.getClassName().item;
autoComplete.state.selectedIndex === i && (className += ' ' + autoComplete.getClassName().selected);
return (
<Link
className={className}
key={i}
content={item.content || item.value}
onClick={autoComplete._onClick.bind(autoComplete, item, i)}
mainAttrs={{ id: autoComplete.getId() + '-item-' + i }}
/>
);
});
},
_getMainAttrs: function () {
var mainAttrs = this.buildMainAttrs();
this.state.items && (mainAttrs.className += ' ' + this.getClassName().open);
return mainAttrs;
},
// Render
render: function () {
return (
<div {...this._getMainAttrs()}>
<Backdrop {...this._getBackdropProps()} />
<div className={this.getClassName().menu} id={this.getId() + '-menu'}>
{this._getChildren()}
</div>
</div>
);
}
});
|
app/javascript/mastodon/features/ui/components/column.js
|
imas/mastodon
|
import React from 'react';
import ColumnHeader from './column_header';
import PropTypes from 'prop-types';
import { debounce } from 'lodash';
import { scrollTop } from '../../../scroll';
import { isMobile } from '../../../is_mobile';
export default class Column extends React.PureComponent {
static propTypes = {
heading: PropTypes.string,
icon: PropTypes.string,
children: PropTypes.node,
active: PropTypes.bool,
hideHeadingOnMobile: PropTypes.bool,
};
handleHeaderClick = () => {
const scrollable = this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
scrollTop () {
const scrollable = this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
handleScroll = debounce(() => {
if (typeof this._interruptScrollAnimation !== 'undefined') {
this._interruptScrollAnimation();
}
}, 200)
setRef = (c) => {
this.node = c;
}
render () {
const { heading, icon, children, active, hideHeadingOnMobile } = this.props;
const showHeading = heading && (!hideHeadingOnMobile || (hideHeadingOnMobile && !isMobile(window.innerWidth)));
const columnHeaderId = showHeading && heading.replace(/ /g, '-');
const header = showHeading && (
<ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} columnHeaderId={columnHeaderId} />
);
return (
<div
ref={this.setRef}
role='region'
aria-labelledby={columnHeaderId}
className='column'
onScroll={this.handleScroll}
>
{header}
{children}
</div>
);
}
}
|
src/components/hero_stats/HeroRowPro.js
|
byronsha/open_dota
|
import React from 'react'
import {TableRow, TableRowColumn} from 'material-ui/Table'
import {
blueA200,
greenA700,
redA700
} from 'material-ui/styles/colors';
import CountBar from '../CountBar'
import PercentageBar from '../PercentageBar'
const BASE_URL = 'https://api.opendota.com'
const styles = {
column8: {
width: '8%'
},
column17: {
paddingLeft: '0px',
width: '17%'
},
column25: {
width: '25%',
verticalAlign: 'bottom'
},
image: {
maxWidth: '85px'
}
}
const HeroRowPro = ({ hero, max }) => {
const { id, localized_name, img, pro_win, pro_pick, pro_ban } = hero
if (!pro_win || !pro_pick || !pro_ban) { return null }
return (
<TableRow>
<TableRowColumn style={styles.column8}>
<img src={BASE_URL + img} style={styles.image} />
</TableRowColumn>
<TableRowColumn style={styles.column17}>
{localized_name}
</TableRowColumn>
<TableRowColumn style={styles.column25}>
<PercentageBar
width={pro_win / pro_pick * 100}
height={8}
text={`${(pro_win / pro_pick * 100).toFixed(2)}%`}
color={blueA200}
/>
</TableRowColumn>
<TableRowColumn style={styles.column25}>
<CountBar
width={pro_pick / max * 100}
height={8}
text={pro_pick.toLocaleString()}
color={greenA700}
/>
</TableRowColumn>
<TableRowColumn style={styles.column25}>
<CountBar
width={pro_ban / max * 100}
height={8}
text={pro_ban.toLocaleString()}
color={redA700}
/>
</TableRowColumn>
</TableRow>
)
}
export default HeroRowPro
|
src/routes/Home/components/HomeView.js
|
loaclhostjason/react-redux-admin
|
import React from 'react'
import DuckImage from '../assets/Duck.jpg'
import './HomeView.scss'
export const HomeView = () => (
<div>
<h4>Welcome!</h4>
<img
alt='This is a duck, because Redux!'
className='duck'
src={DuckImage} />
</div>
)
export default HomeView
|
src/components/upload/picture-controls.js
|
xutou12/draft-richer
|
import React from 'react';
import itis from 'whatitis';
import Upload from 'rc-upload';
import PropTypes from 'prop-types';
import { AtomicBlockUtils, EditorState } from 'draft-js';
import Icon from '../icons';
import Button from '../button';
import { prefixCls } from '../../config';
class PictureControls extends React.Component {
static propsTypes = {
url: PropTypes.oneOfType([
PropTypes.string,
PropTypes.func
]).isRequired,
data: PropTypes.oneOfType([
PropTypes.object,
PropTypes.func
]),
getPost: PropTypes.func,
beforeResponse: PropTypes.func,
onToggle: PropTypes.func.isRequired,
editorState: PropTypes.instanceOf( EditorState ).isRequired
};
state = {
file: null,
entityKey: '',
uploaderProps: {
multiple: false,
supportServerRender: true,
action: itis.Function( this.props.url ) ? this.props.url() : this.props.url,
data: itis.Function( this.props.data ) ? this.props.data() : this.props.data,
onStart: ( file ) => this.handleStart( file ),
onSuccess: ( response ) => this.handleSuccess( response ),
onProgress: ( step ) => {
this.handleProgess( Math.round( step.percent ));
},
onError: ( error ) => this.handleError( error )
}
};
componentDidMount() {
if ( this.props.getPost ) {
this.props.getPost(( files ) => {
files.forEach(( file ) => {
this.uploader.refs.inner.post( file );
});
});
}
}
componentWillUnmount() {
const { file } = this.state;
if ( file ) {
this.uploader.abort( file );
}
}
handleStart = ( file ) => {
const { editorState, onToggle } = this.props;
const editorStateWithFocus = this.getFocus( editorState );
const contentState = editorStateWithFocus.getCurrentContent();
const contentStateWithEntity = contentState.createEntity( 'PICTURE', 'MUTABLE', {
name: file.name, abort: () => { this.uploader.abort( file ); }
});
const entityKey = contentStateWithEntity.getLastCreatedEntityKey();
const newEditorState = EditorState.set( editorStateWithFocus, { currentContent: contentStateWithEntity });
onToggle( AtomicBlockUtils.insertAtomicBlock( newEditorState, entityKey, ' ' ));
this.state.entityKey = entityKey;
this.state.file = file;
};
handleProgess = ( percent ) => {
const { entityKey } = this.state;
const { editorState, onToggle } = this.props;
const contentState = editorState.getCurrentContent().mergeEntityData( entityKey, { percent });
const newEditorState = EditorState.set( editorState, { currentContent: contentState });
onToggle( newEditorState );
};
handleSuccess = ( response ) => {
const { entityKey } = this.state;
const { editorState, beforeResponse, onToggle } = this.props;
const success = ({ hashname }) => {
const contentState = editorState.getCurrentContent().mergeEntityData( entityKey, {
hashname, abort() {}
});
const newEditorState = EditorState.set( editorState, { currentContent: contentState });
onToggle( newEditorState );
};
if ( beforeResponse ) {
beforeResponse( response, success, this.handleError );
} else {
success( response );
}
this.state.file = null;
};
handleError = ( e ) => {
const { entityKey } = this.state;
const { editorState, onToggle } = this.props;
const contentState = editorState.getCurrentContent().mergeEntityData( entityKey, {
error: itis.String( e ) ? e : 'network error', abort() {}
});
const newEditorState = EditorState.set( editorState, { currentContent: contentState });
onToggle( newEditorState );
this.state.file = null;
};
getFocus = ( editorState ) => {
const selection = editorState.getSelection();
if ( !selection.getHasFocus()) {
return EditorState.moveFocusToEnd( editorState );
}
return editorState;
};
render() {
const { uploaderProps } = this.state;
return (
<Upload
component="div"
className={`${prefixCls}-toolbar`}
ref={( c ) => { if ( c ) this.uploader = c; }}
{...uploaderProps}>
<Button
id="picture"
title="插入图片"
label={<Icon type="picture" />} />
</Upload>
);
}
}
export default PictureControls;
|
assets/javascripts/kitten/components/layout/dashboard-layout/test.js
|
KissKissBankBank/kitten
|
import React from 'react'
import renderer from 'react-test-renderer'
import 'jest-styled-components'
import '../../../config/__mocks__/matchMediaMock.js'
import { DashboardLayout } from './index'
describe('<DashboardLayout />', () => {
let component
describe('with default props', () => {
beforeEach(() => {
component = renderer
.create(
<DashboardLayout
backLinkProps={{
href: '#',
children: 'Custom backLink text',
}}
buttonProps={{
openLabel: 'Custom open label',
closeLabel: 'Custom close label',
}}
quickAccessLinkText="Custom quick access link text"
overlayZIndex={133}
>
<DashboardLayout.Header>Header content</DashboardLayout.Header>
<DashboardLayout.SideContent>
Side content
</DashboardLayout.SideContent>
<DashboardLayout.SideFooter>Side footer</DashboardLayout.SideFooter>
<p>Main content</p>
</DashboardLayout>,
)
.toJSON()
})
it('matches with snapshot', () => {
expect(component).toMatchSnapshot()
})
})
describe('with Header, Toaster and Alert', () => {
beforeEach(() => {
component = renderer
.create(
<DashboardLayout
backLinkProps={{
href: '#',
children: 'Custom backLink text',
}}
buttonProps={{
openLabel: 'Custom open label',
closeLabel: 'Custom close label',
}}
quickAccessLinkText="Custom quick access link text"
>
<DashboardLayout.SiteHeader>
Header content
</DashboardLayout.SiteHeader>
<DashboardLayout.Header>Header content</DashboardLayout.Header>
<DashboardLayout.SideContent>
Side content
</DashboardLayout.SideContent>
<DashboardLayout.SideFooter>Side footer</DashboardLayout.SideFooter>
<DashboardLayout.Alerts>Alert!</DashboardLayout.Alerts>
<p>Main content</p>
<DashboardLayout.Toaster>Toaster</DashboardLayout.Toaster>
</DashboardLayout>,
)
.toJSON()
})
it('matches with snapshot', () => {
expect(component).toMatchSnapshot()
})
})
describe('<DefaultLayout.Flow />', () => {
beforeEach(() => {
component = renderer
.create(
<DashboardLayout.Flow>
<DashboardLayout.Flow.Content>
Main flow content
</DashboardLayout.Flow.Content>
<DashboardLayout.Flow.Aside
mobileAsideProps={{
openLabel: 'Open help',
closeLabel: 'Close help',
}}
>
<DashboardLayout.Flow.AsideCard>
Side content in a card
</DashboardLayout.Flow.AsideCard>
</DashboardLayout.Flow.Aside>
<DashboardLayout.Flow.Nav>
<button>Back</button>
<button>Save</button>
</DashboardLayout.Flow.Nav>
</DashboardLayout.Flow>,
)
.toJSON()
})
it('matches with snapshot', () => {
expect(component).toMatchSnapshot()
})
})
describe('<DefaultLayout.Flow loading />', () => {
beforeEach(() => {
component = renderer
.create(
<DashboardLayout.Flow>
<DashboardLayout.Flow.Content>
Main flow content
</DashboardLayout.Flow.Content>
<DashboardLayout.Flow.Aside
mobileAsideProps={{
openLabel: 'Open help',
closeLabel: 'Close help',
}}
>
<DashboardLayout.Flow.AsideCard>
Side content in a card
</DashboardLayout.Flow.AsideCard>
</DashboardLayout.Flow.Aside>
<DashboardLayout.Flow.Nav>
<button>Back</button>
<button>Save</button>
</DashboardLayout.Flow.Nav>
</DashboardLayout.Flow>,
)
.toJSON()
})
it('matches with snapshot', () => {
expect(component).toMatchSnapshot()
})
})
})
|
jenkins-design-language/src/js/components/material-ui/svg-icons/action/trending-flat.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionTrendingFlat = (props) => (
<SvgIcon {...props}>
<path d="M22 12l-4-4v3H3v2h15v3z"/>
</SvgIcon>
);
ActionTrendingFlat.displayName = 'ActionTrendingFlat';
ActionTrendingFlat.muiName = 'SvgIcon';
export default ActionTrendingFlat;
|
public/javascripts/container/mainContainer/app.js
|
MarvenChi/React_Redux_Express
|
import React from 'react';
import './app.css';
import {connect} from 'react-redux'
class App extends React.Component{
constructor(props){
super(props);
this.state={
}
}
componentWillMount(){
console.log('yoyouyoyoyou',this.props.store);
}
render(){
return(
<div>
<h1 >你好吗sssyoyou</h1>
<div>这是首页啊</div>
</div>
)
}
}
const mapState = (state) => {
return {
state
}
};
export default connect(mapState)(App);
|
client/test/components/CreateDocumentModal.js
|
andela-ksolomon/DocumentManagementSys
|
import React from 'react';
|
components/common/Thumbnail.js
|
slidewiki/slidewiki-platform
|
import React from 'react';
/* Read https://slidewiki.atlassian.net/wiki/display/SWIK/How+To+Use+Slide+Thumbnail to know the details */
class Thumbnail extends React.Component {
render() {
const altText = this.props.alt === undefined ? '' : this.props.alt;
return (
<span>
<img src={this.props.url}
alt={altText} />
</span>
);
}
}
export default Thumbnail;
|
client/components/menu/dropdown.js
|
ZeHiro/kresus
|
import React from 'react';
import { NavLink } from 'react-router-dom';
import URL from '../../urls';
import { translate as $t } from '../../helpers';
import DisplayIf from '../ui/display-if';
class DropdownContent extends React.PureComponent {
componentDidMount() {
document.addEventListener('keydown', this.props.onKeydown);
}
componentWillUnmount() {
document.removeEventListener('keydown', this.props.onKeydown);
}
render() {
return (
<div id={this.props.id} onClick={this.props.onClick}>
{this.props.children}
</div>
);
}
}
export default class DropdownMenu extends React.PureComponent {
state = {
show: false
};
handleHide = () => {
this.setState({ show: false });
};
handleToggle = () => {
this.setState({ show: !this.state.show });
};
handleKeydown = event => {
if (event.key === 'Escape') {
this.handleHide();
}
};
render() {
return (
<div className="settings-dropdown">
<button className="fa fa-cogs" onClick={this.handleToggle} />
<DisplayIf condition={this.state.show}>
<DropdownContent
id="overlay"
onKeydown={this.handleKeydown}
onClick={this.handleHide}>
<nav className="settings-dropdown-menu">
<ul>
<li>
<NavLink to={URL.settings.url('categories')}>
<span className="fa fa-list-ul" />
{$t('client.menu.categories')}
</NavLink>
</li>
<li>
<NavLink to={URL.settings.url('accounts')}>
<span className="fa fa-bank" />
{$t('client.settings.tab_accounts')}
</NavLink>
</li>
<li>
<NavLink to={URL.settings.url('emails')}>
<span className="fa fa-envelope" />
{$t('client.settings.tab_alerts')}
</NavLink>
</li>
<li>
<NavLink to={URL.settings.url('backup')}>
<span className="fa fa-save" />
{$t('client.settings.tab_backup')}
</NavLink>
</li>
<li>
<NavLink to={URL.settings.url('admin')}>
<span className="fa fa-sliders" />
{$t('client.settings.tab_admin')}
</NavLink>
</li>
<li>
<NavLink to={URL.settings.url('customization')}>
<span className="fa fa-paint-brush" />
{$t('client.settings.tab_customization')}
</NavLink>
</li>
</ul>
<ul>
<li>
<NavLink to={URL.about.url()}>
<span className="fa fa-question" />
{$t('client.menu.about')}
</NavLink>
</li>
</ul>
</nav>
</DropdownContent>
</DisplayIf>
</div>
);
}
}
|
src/js/components/Object.js
|
kylebyerly-hp/grommet
|
// (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import CSSClassnames from '../utils/CSSClassnames';
const CLASS_ROOT = CSSClassnames.OBJECT;
const LIST_ITEM = CSSClassnames.LIST_ITEM;
export default class GrommetObject extends Component {
_renderArray (array) {
return array.map(function (item, index) {
var itemContent = item;
if ('object' === typeof(item)) {
itemContent = this._renderObject(item);
}
return (
<li key={'i_' + index} className={LIST_ITEM}>{itemContent}</li>
);
}, this);
}
_renderObject (obj) {
var attrs = [];
for (var name in obj) {
if (obj.hasOwnProperty(name)) {
var value = obj[name];
var classes = [CLASS_ROOT + "__attribute"];
if (null === value) {
value = 'null';
classes.push(CLASS_ROOT + "__attribute--unset");
} else if (Array.isArray(value)) {
var items = this._renderArray(value);
value = (
<ol>{items}</ol>
);
classes.push(CLASS_ROOT + "__attribute--array");
} else if ('object' === typeof value) {
value = this._renderObject(value);
classes.push(CLASS_ROOT + "__attribute--container");
} else {
value = value.toString();
}
attrs.push(
<li key={'n_' + name} className={classes.join(' ')}>
<span className={CLASS_ROOT + "__attribute-name"}>{name}</span>
<span className={CLASS_ROOT + "__attribute-value"}>{value}</span>
</li>
);
}
}
return (
<ul>{attrs}</ul>
);
}
render () {
return (
<div className={CLASS_ROOT}>
<div className={CLASS_ROOT + "__container"}>
{this._renderObject(this.props.data)}
</div>
</div>
);
}
}
GrommetObject.propTypes = {
data: PropTypes.object
};
|
node_modules/react-bootstrap/es/SplitToggle.js
|
ivanhristov92/bookingCalendar
|
import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import DropdownToggle from './DropdownToggle';
var SplitToggle = function (_React$Component) {
_inherits(SplitToggle, _React$Component);
function SplitToggle() {
_classCallCheck(this, SplitToggle);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
SplitToggle.prototype.render = function render() {
return React.createElement(DropdownToggle, _extends({}, this.props, {
useAnchor: false,
noCaret: false
}));
};
return SplitToggle;
}(React.Component);
SplitToggle.defaultProps = DropdownToggle.defaultProps;
export default SplitToggle;
|
src/containers/DevToolsWindow.js
|
hoop33/warnerxmas
|
import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
export default createDevTools(
<LogMonitor />
);
|
src/components/basic/Span.js
|
casesandberg/react-mark
|
'use strict';
import React from 'react';
export class SPAN extends React.Component {
render() {
return <span>{ this.props.children }</span>;
}
}
export default SPAN;
|
app/javascript/mastodon/components/relative_timestamp.js
|
tri-star/mastodon
|
import React from 'react';
import { injectIntl, defineMessages } from 'react-intl';
import PropTypes from 'prop-types';
const messages = defineMessages({
today: { id: 'relative_time.today', defaultMessage: 'today' },
just_now: { id: 'relative_time.just_now', defaultMessage: 'now' },
seconds: { id: 'relative_time.seconds', defaultMessage: '{number}s' },
minutes: { id: 'relative_time.minutes', defaultMessage: '{number}m' },
hours: { id: 'relative_time.hours', defaultMessage: '{number}h' },
days: { id: 'relative_time.days', defaultMessage: '{number}d' },
moments_remaining: { id: 'time_remaining.moments', defaultMessage: 'Moments remaining' },
seconds_remaining: { id: 'time_remaining.seconds', defaultMessage: '{number, plural, one {# second} other {# seconds}} left' },
minutes_remaining: { id: 'time_remaining.minutes', defaultMessage: '{number, plural, one {# minute} other {# minutes}} left' },
hours_remaining: { id: 'time_remaining.hours', defaultMessage: '{number, plural, one {# hour} other {# hours}} left' },
days_remaining: { id: 'time_remaining.days', defaultMessage: '{number, plural, one {# day} other {# days}} left' },
});
const dateFormatOptions = {
hour12: false,
year: 'numeric',
month: 'short',
day: '2-digit',
hour: '2-digit',
minute: '2-digit',
};
const shortDateFormatOptions = {
month: 'short',
day: 'numeric',
};
const SECOND = 1000;
const MINUTE = 1000 * 60;
const HOUR = 1000 * 60 * 60;
const DAY = 1000 * 60 * 60 * 24;
const MAX_DELAY = 2147483647;
const selectUnits = delta => {
const absDelta = Math.abs(delta);
if (absDelta < MINUTE) {
return 'second';
} else if (absDelta < HOUR) {
return 'minute';
} else if (absDelta < DAY) {
return 'hour';
}
return 'day';
};
const getUnitDelay = units => {
switch (units) {
case 'second':
return SECOND;
case 'minute':
return MINUTE;
case 'hour':
return HOUR;
case 'day':
return DAY;
default:
return MAX_DELAY;
}
};
export const timeAgoString = (intl, date, now, year, timeGiven = true) => {
const delta = now - date.getTime();
let relativeTime;
if (delta < DAY && !timeGiven) {
relativeTime = intl.formatMessage(messages.today);
} else if (delta < 10 * SECOND) {
relativeTime = intl.formatMessage(messages.just_now);
} else if (delta < 7 * DAY) {
if (delta < MINUTE) {
relativeTime = intl.formatMessage(messages.seconds, { number: Math.floor(delta / SECOND) });
} else if (delta < HOUR) {
relativeTime = intl.formatMessage(messages.minutes, { number: Math.floor(delta / MINUTE) });
} else if (delta < DAY) {
relativeTime = intl.formatMessage(messages.hours, { number: Math.floor(delta / HOUR) });
} else {
relativeTime = intl.formatMessage(messages.days, { number: Math.floor(delta / DAY) });
}
} else if (date.getFullYear() === year) {
relativeTime = intl.formatDate(date, shortDateFormatOptions);
} else {
relativeTime = intl.formatDate(date, { ...shortDateFormatOptions, year: 'numeric' });
}
return relativeTime;
};
const timeRemainingString = (intl, date, now, timeGiven = true) => {
const delta = date.getTime() - now;
let relativeTime;
if (delta < DAY && !timeGiven) {
relativeTime = intl.formatMessage(messages.today);
} else if (delta < 10 * SECOND) {
relativeTime = intl.formatMessage(messages.moments_remaining);
} else if (delta < MINUTE) {
relativeTime = intl.formatMessage(messages.seconds_remaining, { number: Math.floor(delta / SECOND) });
} else if (delta < HOUR) {
relativeTime = intl.formatMessage(messages.minutes_remaining, { number: Math.floor(delta / MINUTE) });
} else if (delta < DAY) {
relativeTime = intl.formatMessage(messages.hours_remaining, { number: Math.floor(delta / HOUR) });
} else {
relativeTime = intl.formatMessage(messages.days_remaining, { number: Math.floor(delta / DAY) });
}
return relativeTime;
};
export default @injectIntl
class RelativeTimestamp extends React.Component {
static propTypes = {
intl: PropTypes.object.isRequired,
timestamp: PropTypes.string.isRequired,
year: PropTypes.number.isRequired,
futureDate: PropTypes.bool,
};
state = {
now: this.props.intl.now(),
};
static defaultProps = {
year: (new Date()).getFullYear(),
};
shouldComponentUpdate (nextProps, nextState) {
// As of right now the locale doesn't change without a new page load,
// but we might as well check in case that ever changes.
return this.props.timestamp !== nextProps.timestamp ||
this.props.intl.locale !== nextProps.intl.locale ||
this.state.now !== nextState.now;
}
componentWillReceiveProps (nextProps) {
if (this.props.timestamp !== nextProps.timestamp) {
this.setState({ now: this.props.intl.now() });
}
}
componentDidMount () {
this._scheduleNextUpdate(this.props, this.state);
}
componentWillUpdate (nextProps, nextState) {
this._scheduleNextUpdate(nextProps, nextState);
}
componentWillUnmount () {
clearTimeout(this._timer);
}
_scheduleNextUpdate (props, state) {
clearTimeout(this._timer);
const { timestamp } = props;
const delta = (new Date(timestamp)).getTime() - state.now;
const unitDelay = getUnitDelay(selectUnits(delta));
const unitRemainder = Math.abs(delta % unitDelay);
const updateInterval = 1000 * 10;
const delay = delta < 0 ? Math.max(updateInterval, unitDelay - unitRemainder) : Math.max(updateInterval, unitRemainder);
this._timer = setTimeout(() => {
this.setState({ now: this.props.intl.now() });
}, delay);
}
render () {
const { timestamp, intl, year, futureDate } = this.props;
const timeGiven = timestamp.includes('T');
const date = new Date(timestamp);
const relativeTime = futureDate ? timeRemainingString(intl, date, this.state.now, timeGiven) : timeAgoString(intl, date, this.state.now, year, timeGiven);
return (
<time dateTime={timestamp} title={intl.formatDate(date, dateFormatOptions)}>
{relativeTime}
</time>
);
}
}
|
test4/src/containers/UserDetailApp/index.js
|
fengnovo/webpack-react
|
import React from 'react'
class UserDetailApp extends React.Component {
constructor (props) {
super (props)
let {userId} = this.props.routeParams;
console.log(userId);
}
render (){
return (
<div>UserDetailApp</div>
)
}
}
export default UserDetailApp
|
src/components/forms/StartEnd.js
|
muiradams/plantogo
|
import _ from 'lodash';
import React, { Component } from 'react';
import moment from 'moment';
import Toggle from 'material-ui/Toggle';
import { TextField, DatePicker, TimePicker } from 'redux-form-material-ui';
import { Field } from 'redux-form';
import { Row, Column } from 'react-cellblock';
// Validation function for redux-form
const required = value => value == null || value === '' ? 'Required' : undefined;
const style = {
error: {
float: "left",
},
fullLength: {
width: "100%",
},
toggle: {
marginTop: "20px",
},
grayBackground: {
background: "#EEEEEE",
},
}
export default class StartEnd extends Component {
constructor(props) {
super(props);
const pastDate = moment('0001-01-01');
const futureDate = moment('3000-01-01');
const minDate = pastDate.clone().toDate();
const maxDate = futureDate.clone().toDate();
this.state = {
minDate: minDate,
maxDate: maxDate,
isLocationToggled: false,
};
}
setMinAndMaxDate() {
const { startDate, endDate } = this.props;
if (_.isEmpty(endDate)) {
this.setState({
maxDate: endDate,
});
}
if (_.isEmpty(startDate)) {
this.setState({
minDate: startDate,
});
}
}
formatDate(date) {
return moment(date).format('MMMM D, YYYY');
}
handleLocationToggle() {
this.setState({ isLocationToggled: !this.state.isLocationToggled });
}
renderToggle(startLabel, endLabel) {
return (
<Row>
<Column>
<Toggle
label={`Add ${startLabel.toLowerCase()} and ${endLabel.toLowerCase()} locations`}
labelPosition="right"
style={style.toggle}
labelStyle={{color: "#999999"}}
onToggle={this.handleLocationToggle.bind(this)}
/>
</Column>
</Row>
);
}
renderLocation(isStart, startLabel, endLabel, isLocationRequired) {
let nameLabel = 'start';
let hintLabel = startLabel;
if (!isStart) {
nameLabel = 'end';
hintLabel = endLabel;
}
return (
<div>
<Row>
<Column>
<Field component={TextField}
name={`${nameLabel}Location`}
hintText={`${hintLabel} Location`}
floatingLabelText={isLocationRequired ? `${hintLabel} Location*` : `${hintLabel} Location` }
validate={isLocationRequired ? [required] : null}
errorStyle={style.error}
className="text-field"
style={style.fullLength}
inputStyle={style.grayBackground}
/>
</Column>
</Row>
</div>
);
}
render() {
let {
startLabel,
endLabel,
location,
isLocationRequired,
isToggleDisabled
} = this.props;
if (!startLabel) startLabel = 'Start';
if (!endLabel) endLabel = 'End';
if (!isLocationRequired) isLocationRequired = false;
if (!isToggleDisabled) isToggleDisabled = false;
return (
<div>
{location || isLocationRequired || this.state.isLocationToggled ? this.renderLocation(true, startLabel, endLabel, isLocationRequired) : null}
<Row>
<Column width="5/8">
<Field component={DatePicker}
name="startDate"
hintText={`${startLabel} Date*`}
floatingLabelText={`${startLabel} Date*`}
maxDate={this.state.maxDate}
format={null}
formatDate={this.formatDate}
validate={[required]}
className="text-field"
textFieldStyle={style.fullLength}
onClick={() => this.setMinAndMaxDate()}
/>
</Column>
<Column width="3/8">
<Field component={TimePicker}
name="startTime"
hintText="Time*"
floatingLabelText="Time*"
format={null}
validate={[required]}
textFieldStyle={style.fullLength}
className="text-field"
/>
</Column>
</Row>
{location || isLocationRequired || this.state.isLocationToggled ? this.renderLocation(false, startLabel, endLabel, isLocationRequired) : null}
<Row>
<Column width="5/8">
<Field component={DatePicker}
name="endDate"
hintText={`${endLabel} Date`}
floatingLabelText={`${endLabel} Date`}
minDate={this.state.minDate}
defaultDate={this.state.minDate}
format={null}
formatDate={this.formatDate}
className="text-field"
textFieldStyle={style.fullLength}
onClick={() => this.setMinAndMaxDate()}
/>
</Column>
<Column width="3/8">
<Field component={TimePicker}
name="endTime"
hintText="Time"
floatingLabelText="Time"
format={null}
errorStyle={style.error}
textFieldStyle={style.fullLength}
className="text-field"
/>
</Column>
</Row>
{ !isToggleDisabled && !location && !isLocationRequired ? this.renderToggle(startLabel, endLabel) : null }
</div>
)
}
}
|
app/components/common/button/Button.js
|
rvpanoz/luna
|
import React from 'react';
import { withStyles } from '@material-ui/core/styles';
import Button from '@material-ui/core/Button';
import PropTypes, { string, bool } from 'prop-types';
import cn from 'classnames';
import styles from './styles';
const AppButton = ({
classes,
color,
round,
border,
children,
fullWidth,
disabled,
...restProps
}) => {
const btnClasses = cn({
[classes[color]]: color,
[classes.round]: round,
[classes.border]: border,
[classes.fullWidth]: fullWidth,
[classes.disabled]: disabled,
});
return (
<Button {...restProps} className={cn(classes.button, btnClasses)}>
{children}
</Button>
);
};
AppButton.defaultProps = {
color: 'transparent',
};
AppButton.propTypes = {
classes: PropTypes.objectOf(string).isRequired,
children: PropTypes.oneOfType([PropTypes.string, PropTypes.node]),
color: PropTypes.oneOf([
'info',
'warning',
'error',
'transparent',
'primary',
'secondary',
'simple',
]),
round: bool,
border: bool,
fullWidth: bool,
disabled: bool,
};
export default withStyles(styles)(AppButton);
|
test/LabelSpec.js
|
pandoraui/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Label from '../src/Label';
describe('Label', function () {
it('Should output a label with message', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Label>
<strong>Message</strong>
</Label>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
it('Should have bsClass by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Label>
Message
</Label>
);
assert.ok(React.findDOMNode(instance).className.match(/\blabel\b/));
});
it('Should have bsStyle by default', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Label>
Message
</Label>
);
assert.ok(React.findDOMNode(instance).className.match(/\blabel-default\b/));
});
});
|
entry_types/scrolled/package/spec/frontend/useEventContextData-spec.js
|
codevise/pageflow
|
import React from 'react';
import {useEventContextData, EventContextDataProvider} from 'frontend/useEventContextData';
import {renderHookInEntry} from 'support';
describe('useEventContextData', () => {
it('returns an object with current section and chapter index', () => {
const {result} = renderHookInEntry((props) => useEventContextData(), {
seed: {
entry: {
locale: 'en'
},
sections: [
{
id: 1,
permaId: 101,
chapterId: 1,
position: 1,
configuration: {
transition: 'scroll'
}
},
],
chapters: [
{
id: 1,
permaId: 10,
position: 1,
configuration: {
title: 'Chapter 1',
summary: 'An introductory chapter'
}
},
]
},
wrapper: ({children}) =>
<EventContextDataProvider sectionIndex={0}>{children}</EventContextDataProvider>
});
expect(result.current).toMatchObject({
page: {
configuration: {
title: 'Chapter 1, Section 0'
},
index: 0
}
});
});
});
|
src/Parser/Warlock/Affliction/Modules/Items/Legendaries/StretensSleeplessShackles.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import Analyzer from 'Parser/Core/Analyzer';
import Enemies from 'Parser/Core/Modules/Enemies';
import Combatants from 'Parser/Core/Modules/Combatants';
import calculateEffectiveDamage from 'Parser/Core/calculateEffectiveDamage';
import ITEMS from 'common/ITEMS';
import ItemDamageDone from 'Main/ItemDamageDone';
import { UNSTABLE_AFFLICTION_DEBUFF_IDS } from '../../../Constants';
const DAMAGE_BONUS_PER_TARGET = 0.04;
class StretensSleeplessShackles extends Analyzer {
static dependencies = {
enemies: Enemies,
combatants: Combatants,
};
bonusDmg = 0;
on_initialized() {
this.active = this.combatants.selected.hasWrists(ITEMS.STRETENS_SLEEPLESS_SHACKLES.id);
}
on_byPlayer_damage(event) {
const enemies = this.enemies.getEntities();
const numberOfEnemiesWithUA = Object.keys(enemies)
.map(x => enemies[x])
.filter(enemy => UNSTABLE_AFFLICTION_DEBUFF_IDS.some(uaId => enemy.hasBuff(uaId, event.timestamp))).length;
this.bonusDmg += calculateEffectiveDamage(event, numberOfEnemiesWithUA * DAMAGE_BONUS_PER_TARGET);
}
item() {
return {
item: ITEMS.STRETENS_SLEEPLESS_SHACKLES,
result: <ItemDamageDone amount={this.bonusDmg} />,
};
}
}
export default StretensSleeplessShackles;
|
src/CarouselItem.js
|
albertojacini/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const CarouselItem = React.createClass({
propTypes: {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
caption: React.PropTypes.node,
index: React.PropTypes.number
},
getInitialState() {
return {
direction: null
};
},
getDefaultProps() {
return {
active: false,
animateIn: false,
animateOut: false
};
},
handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.handleAnimateOutEnd
);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ?
'right' : 'left'
});
},
render() {
let classes = {
item: true,
active: (this.props.active && !this.props.animateIn) || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classes[this.state.direction] = true;
}
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
{this.props.caption ? this.renderCaption() : null}
</div>
);
},
renderCaption() {
return (
<div className="carousel-caption">
{this.props.caption}
</div>
);
}
});
export default CarouselItem;
|
src/components/video-list-item.js
|
romashka50/ReactReduxModern
|
import React from 'react';
const VideoItem = ({ video, onSelectVideo }) => {
const {
snippet: {
thumbnails: {
default: { url }
},
title,
}
} = video;
return (
<li
className="list-group-item"
onClick={() => {onSelectVideo(video)}}
>
<div className="video-list media" >
<div className="media-left" >
<img alt="" className="media-object" src={url} />
</div>
<div className="media-body" >
<div className="media-heading" >
{title}
</div>
</div>
</div>
</li>
);
};
export default VideoItem;
|
packages/react/src/components/FieldsetArray.js
|
wq/wq.app
|
import React from 'react';
import { useComponents } from '../hooks';
import PropTypes from 'prop-types';
export default function FieldsetArray({ label, children, addRow }) {
const { View, Button } = useComponents();
return (
<View>
{children}
{addRow && (
<Button onClick={() => addRow()}>{`Add ${label}`}</Button>
)}
</View>
);
}
FieldsetArray.propTypes = {
label: PropTypes.string,
children: PropTypes.node,
addRow: PropTypes.func
};
|
frontend/components/Behavioral.js
|
ParroApp/parro
|
import React from 'react';
import Navbar from './Navbar';
import TypeWriter from 'react-typewriter';
import Timer from './Timer';
import { captureUserMedia, takePhoto, uploadImage, uploadAudio, mergeAndAnalyze } from './AppUtils';
import RecordRTC from 'recordrtc';
const StereoAudioRecorder = RecordRTC.StereoAudioRecorder;
const hasGetUserMedia = !!(navigator.getUserMedia || navigator.webkitGetUserMedia ||
navigator.mozGetUserMedia || navigator.msGetUserMedia);
class Behavioral extends React.Component {
constructor(props) {
super(props);
this.state = {
recordVideo: '',
doneTyping: false,
isRecording: false,
isBotAsking: true,
minTime: 0,
secTime: 0,
typewriter: '',
time: null
}
// this.startRecording = this.startRecording.bind(this);
this.nextQuestion = this.nextQuestion.bind(this);
this.index = 0;
}
componentDidMount() {
this.setState({userId: '1234'});
if(!hasGetUserMedia) {
alert("Your browser cannot stream from your webcam. Please switch to Chrome or Firefox.");
return;
}
window.addEventListener("load", function() {
var synth = window.speechSynthesis;
var voices = synth.getVoices();
// console.log('loaded', voices);
});
setTimeout(function() {
var synth = window.speechSynthesis;
var voices = synth.getVoices();
for (var i = 0; i < voices.length; i++) {
if (voices[i].name === 'Google US English') {
voices = voices[i];
break;
}
}
var msg = new SpeechSynthesisUtterance();
msg.text = "Hello Caroline! My name is Parro and I will be interviewing you today on behalf of Google. Please turn on your sound so we can have a chat";
msg.voice = voices;
msg.pitch = 1;
msg.rate = 0.9;
synth.speak(msg);
this.setState({
typewriter: "Hello Caroline! My name is Parro and I will be interviewing you today on behalf of Google. Please turn on your sound 🔊 so we can have a chat."
});
}.bind(this), 500);
captureUserMedia((stream) => {
this.setState({ stream: stream, src: window.URL.createObjectURL(stream) });
});
}
startRecordVideo() {
// start recording video
console.log('start video recording');
var recordVideo = RecordRTC(this.state.stream, {
type: 'video',
mimeType: 'video/webm',
bitsPerSecond: 128000
});
recordVideo.startRecording();
var videoElement = document.querySelector('video');
var intervalId = setInterval(() => {
var photo = takePhoto(videoElement);
uploadImage(photo, this.state.userId);
}, 10000)//333)
// stores state
this.setState({
recordVideo: recordVideo,
intervalId: intervalId
});
}
startRecord() {
this.setState({isRecording: true})
setTimeout(() => {
this.setState({ time: 2 });
}, 3000)
// start recording audio
console.log('start audio recording');
var recordAudio = RecordRTC(this.state.stream, {
recorderType: StereoAudioRecorder,
// mimeType: 'audio/wav'
type: 'audio'
});
recordAudio.startRecording();
// stores state
this.setState({
recordAudio: recordAudio,
});
}
stopRecord(temp) {
this.state.recordAudio.stopRecording(() => {
console.log('Stop recording audio');
uploadAudio(this.state.recordAudio.blob, this.state.userId, this.index - 1);
// console.log(this.state.recordAudio.blob);
// console.log(this.state.recordAudio);
temp();
});
this.setState({isRecording: false});
}
talk(val) {
setTimeout(function() {
var synth = window.speechSynthesis;
var voices = synth.getVoices();
for (var i = 0; i < voices.length; i++) {
if (voices[i].name === 'Google US English') {
voices = voices[i];
break;
}
}
var msg = new SpeechSynthesisUtterance();
msg.text = val;
msg.voice = voices;
msg.pitch = 1;
msg.rate = 0.9;
synth.speak(msg);
this.setState({
typewriter: val
});
}.bind(this), 500);
}
startRecording() {
this.nextQuestion();
}
timerEnd() {
console.log('TIMER END');
this.nextQuestion(); // force next question
}
callMerge() {
mergeAndAnalyze(this.state.userId);
}
nextQuestion() {
// setTimeout(() => {
// console.log('YOYOYO');
this.setState({ time: null });
// }, 3000)
console.log('next question');
console.log('start recording here', this.state);
if (!this.state.recordVideo) {
this.startRecordVideo();
}
if (this.state.isRecording) {
console.log('stop audio recording old and upload...');
this.stopRecord(() => {
this.startRecord();
});
// this.state.stream.getVideoTracks().forEach(function(track) {
// track.stop();
// });
// stop recording and restart...
} else {
this.startRecord();
}
this.setState({ doneTyping: false });
this.index++;
if (this.index === 1) {
this.talk('Tell me about yourself');
} else if (this.index === 2) {
this.talk('Tell me about a project');
} else if (this.index === 3) {
this.talk('What is bubble sort?');
} else {
// END OF BEHAVIORAL SECTION
this.state.recordVideo.stopRecording(() => {
console.log('Stop recording video');
let params = {
type: 'video/webm',
data: this.state.recordVideo.blob,
id: Math.floor(Math.random() * 90000) + 10000
}
clearInterval(this.state.intervalId);
this.setState({ uploading: true, intervalId: null, time: '' });
});
this.state.stream.getVideoTracks().forEach(function(track) {
track.stop();
});
// now that behavioral is over, can merge audio
this.callMerge();
this.props.history.push('/technical');
}
}
componentWillMount() {
setTimeout(() => {
this.setState({doneTyping: true})
}, 10000)
}
render() {
return(
<div>
<Navbar {...this.props}/>
<video autoPlay muted src={this.state.src} style={{display: 'none'}}/>
<div style={{height: '60px', width: '100%'}}></div>
<div className="robot"><svg className="robotSVG" version="1.1" xmlns="http://www.w3.org/2000/svg">
<g id="hover">
<ellipse id="shadow_2_" opacity="0.4" fill="#2C3332" cx="300" cy="703.375" rx="88.971" ry="30.625"></ellipse>
</g>
<g id="arms">
<g id="left">
<path id="arm_1_" fill="#BABEB7" d="M183.975,430.936c-50.27-21.595-96.437,29.654-96.132,54.383
c0.06,4.868,7.836,11.424,11.509,7.079c12.145-14.369,36.979-35.733,55.676-16.486
C156.498,477.423,189.086,433.132,183.975,430.936z"></path>
<g id="hand_1_">
<path id="shadow" fill="#BABEB7" d="M63.712,520.545l5.657-7.071c0,0-11.453-8.997-9.402-12.554
c4.469-7.751,15.935-9.515,25.612-3.936c9.676,5.579,13.898,16.385,9.43,24.136c-1.736,3.013-7.363,0.091-7.363,0.091
l-5.657,7.071l0.058,6.027c8.473,0.83,16.454-1.564,21.692-6.847c1.235-1.245,6.329-7.287,7.229-8.85
c1.826-3.166-7.579-26.607-18.73-33.036c-8.361-4.82-31.172-5.074-31.172-5.074s-5.691,5.814-8.805,11.216
c-5.77,10.006-2.253,23.271,7.678,32.486L63.712,520.545z"></path>
<path id="top" fill="#DCE0DA" d="M69.37,513.474c-5.443-5.817-7.202-13.631-3.746-19.625c4.469-7.751,15.935-9.514,25.612-3.935
c9.676,5.578,13.899,16.385,9.43,24.135c-2.575,4.468-7.478,6.932-13.02,7.162l0.058,6.027
c10.471,1.026,20.192-2.873,24.911-11.06c6.976-12.099,0.385-28.965-14.719-37.673c-15.104-8.708-33.002-5.957-39.977,6.142
c-5.769,10.007-2.253,23.271,7.679,32.486L69.37,513.474z"></path>
</g>
</g>
<g id="right">
<path id="arm" fill="#DCE0DA" d="M416.025,430.936c50.27-21.595,96.437,29.654,96.131,54.383
c-0.059,4.868-7.836,11.424-11.509,7.079c-12.145-14.369-36.979-35.733-55.676-16.486
C443.502,477.423,410.914,433.132,416.025,430.936z"></path>
<g id="hand">
<path id="shadow_1_" fill="#BABEB7" d="M536.287,520.545l-5.656-7.071c0,0,11.453-8.997,9.402-12.554
c-4.469-7.751-15.936-9.515-25.612-3.936s-13.898,16.385-9.43,24.136c1.736,3.013,7.362,0.091,7.362,0.091l5.657,7.071
l-0.058,6.027c-8.474,0.83-16.455-1.564-21.692-6.847c-1.235-1.245-6.329-7.287-7.229-8.85
c-1.826-3.166,7.578-26.607,18.73-33.036c8.361-4.82,31.172-5.074,31.172-5.074s5.691,5.814,8.805,11.216
c5.77,10.006,2.253,23.271-7.678,32.486L536.287,520.545z"></path>
<path id="top_1_" fill="#DCE0DA" d="M530.631,513.474c5.443-5.817,7.201-13.631,3.745-19.625
c-4.469-7.751-15.935-9.514-25.612-3.935c-9.676,5.578-13.898,16.385-9.43,24.135c2.575,4.468,7.479,6.932,13.02,7.162
l-0.058,6.027c-10.472,1.026-20.192-2.873-24.911-11.06c-6.975-12.099-0.385-28.965,14.72-37.673s33.003-5.957,39.978,6.142
c5.769,10.007,2.252,23.271-7.68,32.486L530.631,513.474z"></path>
</g>
</g>
</g>
<g id="body">
<g id="chassie">
<g id="base">
<path fill="#DCE0DA" d="M137.424,525.622c0-47.887,60.669-219.342,162.576-219.342c101.907,0,162.576,171.854,162.576,219.342
c0,47.489-137.88,56.438-162.576,56.438C275.303,582.06,137.424,573.511,137.424,525.622z"></path>
</g>
<g id="highlight">
<defs>
<path id="SVGID_1_" d="M137.424,525.622c0-47.887,60.669-219.342,162.576-219.342c101.907,0,162.576,171.854,162.576,219.342
c0,47.489-137.88,56.438-162.576,56.438C275.303,582.06,137.424,573.511,137.424,525.622z"></path>
</defs>
<clipPath id="SVGID_2_">
<use xlinkHref="#SVGID_1_" overflow="visible"></use>
</clipPath>
<path clipPath="url(#SVGID_2_)" fill="#BABEB7" d="M455.667,419c0,0-38.299,61.503-156.983,61.503
c-67.685,0-86.351,14.831-96.684,39.164S203.368,588,298.684,588s1.816,21.923,1.816,21.923s-198.833-42.589-198.833-43.589
s54.333-215,54.333-215L455.667,419z"></path>
</g>
</g>
<g id="progress-indicator">
<g id="divet">
<path id="highlight-bottom" fill="#EAECE8" d="M425.182,524.775l-4.682-21.211c0,0-48.18,19.563-120.34,19.563
s-120.82-19.079-120.82-19.079l-4.542,20.636c0,0,37.523,20.052,125.363,20.052S425.182,524.775,425.182,524.775z"></path>
<path id="divet-bottom" fill="#4C4C4C" d="M420.682,521.823l-4.514-16.654c0,0-46.447,17.959-116.014,17.959
c-69.566,0-116.477-17.551-116.477-17.551l-4.379,16.159c0,0,36.174,18.597,120.856,18.597
C384.837,540.333,420.682,521.823,420.682,521.823z"></path>
<polygon id="shadow-right_1_" fill="#BABEB7" points="416.168,505.169 420.5,503.564 425.182,524.775 420.682,521.823 "></polygon>
<polygon id="shadow-left" fill="#8F918D" points="183.677,505.577 179.34,504.049 174.797,524.685 179.297,521.736 "></polygon>
<path id="shadow-bottom" fill="#BABEB7" d="M204.738,530.305l-5.786,2.959c0,0-8.125-2.072-14.702-4.556
s-9.453-4.023-9.453-4.023l4.5-2.948c0,0,4.039,2.192,11.313,4.463S204.738,530.305,204.738,530.305z"></path>
</g>
<g id="completed">
<path id="blue" fill="#84D3E8" d="M300.154,523.128c-69.566,0-116.477-17.551-116.477-17.551l-4.379,16.159
c0,0,36.174,18.597,120.856,18.597c28.812,0,51.965-2.144,69.983-4.971l-1.808-18.073
C349.822,520.518,326.67,523.128,300.154,523.128z"></path>
<path id="blue-shadow" fill="#6DADBC" d="M208.568,512.712c-15.682-3.741-24.93-7.135-24.93-7.135l-4.437,16.159
c0,0,8.037,4.175,25.537,8.568C205.625,524.125,206,520.875,208.568,512.712z"></path>
</g>
</g>
</g>
<g id="head">
<g id="face">
<path id="screen-shadow" fill="#9AB2B0" d="M418.268,235.276C377.932,233.144,327.52,232,300.003,232
c-27.517,0-77.766,1.144-118.102,3.276c-34.071,1.801-41.222,17.035-41.222,69.742s3.15,88.311,24.65,107.819
c35.831,32.511,101.258,47.829,134.673,47.829c33.832,0,99.06-15.318,134.891-47.829c21.5-19.508,24.758-55.112,24.758-107.819
S452.338,237.078,418.268,235.276z"></path>
<path id="screen" fill="#A4BCB9" d="M164.381,353.965c0,55.225,107.043,76.693,135.619,76.693
c28.576,0,135.618-21.469,135.618-76.693c0-100.027-60.717-123.293-135.618-123.293
C225.101,230.671,164.381,253.938,164.381,353.965z"></path>
<path id="case_x5F_shadow" fill="#EAECE8" d="M300,239c27.54,0,78.739,1.16,119.383,3.309c15.837,0.837,18.06,4.715,19.388,7.032
c5.026,8.771,5.671,29.167,5.671,45.955c0,49.954-0.156,81.738-16.287,96.374c-31.639,28.708-96.014,44.997-128.154,44.997
c-32.048,0-95.295-16.289-126.934-44.997c-16.039-14.552-17.176-46.356-17.176-96.374c0-16.825,0.638-37.258,5.614-46
c1.395-2.45,3.503-6.153,19.279-6.987C221.426,240.16,272.541,239,300,239 M300,210.5c-80.5,0-160.11,7.167-160.11,60.795
S141.095,385.151,162.971,405C199.429,438.08,266,453.666,300,453.666c34.424,0,100.792-15.586,137.25-48.666
c21.876-19.849,23.191-80.076,23.191-133.705S380.5,210.5,300,210.5z"></path>
<path id="case" fill="#DCE0DA" d="M300,248c27.54,0,78.739,1.16,119.383,3.309c15.837,0.837,18.06,4.715,19.388,7.032
c5.026,8.771,5.671,29.167,5.671,45.955c0,49.954-3.156,81.738-19.287,96.374c-31.639,28.708-93.014,43.997-125.154,43.997
c-32.048,0-93.295-15.289-124.934-43.997c-16.039-14.552-19.176-46.356-19.176-96.374c0-16.825,0.638-37.258,5.614-46
c1.395-2.45,3.503-6.153,19.279-6.987C221.426,249.16,272.541,248,300,248 M300,230c-27.999,0-79.126,1.164-120.167,3.333
c-34.667,1.833-41.943,17.333-41.943,70.962s3.205,89.856,25.081,109.705C199.429,447.08,266,462.666,300,462.666
c34.424,0,100.792-15.586,137.25-48.666c21.876-19.849,25.191-56.076,25.191-109.705s-7.441-69.129-42.108-70.962
C379.292,231.164,327.998,230,300,230L300,230z"></path>
</g>
<g id="eyes">
<ellipse id="left_1_" fill="#2C3332" cx="231" cy="316.667" rx="6.333" ry="17"></ellipse>
<ellipse id="right_1_" fill="#2C3332" cx="369" cy="316.667" rx="6.334" ry="17"></ellipse>
</g>
<g id="indicators">
<path id="mount" fill="#DCE0DA" d="M354.333,220.333c0-29.916-24.252-54.167-54.167-54.167c-29.916,0-54.167,24.251-54.167,54.167
c0,4.667,24.251,4.667,54.167,4.667C330.081,225,354.333,225,354.333,220.333z"></path>
<g id="leds">
<circle id="yellow" fill="#F0C419" cx="300.418" cy="207" r="8.084"></circle>
<circle id="red" fill="#E64C3C" cx="324.67" cy="206" r="8.084"></circle>
<circle id="green" fill="#4EBA64" cx="275.33" cy="206" r="8.083"></circle>
</g>
</g>
</g>
</svg></div>
<div className="container" style={{textAlign: 'center', display: 'flex', justifyContent: 'center', alignItems: 'center'}}>
<div className="columns">
<div className="column is-vertical">
{this.state.typewriter && <TypeWriter fixed={true} style={{fontSize: '30px', textAlign: 'center'}} typing={1}>
{this.state.typewriter}
</TypeWriter>}
{this.state.time && <Timer time={this.state.time} timerEnd={this.timerEnd.bind(this)} />}
{
this.state.isBotDone && (<span>{this.state.minTime + ':' + this.state.secTime}</span>)
}
</div>
</div>
</div>
{
this.state.doneTyping &&
(<button onClick={this.nextQuestion} style={{position: 'absolute', top: '80%', left: '45.5%'}} className="button is-primary is-large">
Let's Begin
</button>)
}
{
this.state.isRecording &&
(<button onClick={this.nextQuestion} style={{position: 'absolute', top: '80%', left: '46.5%'}} className="button is-success is-large">
<span className="icon">
<i className="fa fa-arrow-right"></i>
</span>
<span>Next</span>
</button>)
}
</div>
)
}
}
export default Behavioral;
|
index.android.js
|
Abrax20/snap-react
|
// @flow
import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import App from './src/App.js';
export default class reactSnap extends Component {
render() {
return (
<App />
);
}
}
AppRegistry.registerComponent('reactSnap', () => reactSnap);
|
client/index.js
|
vronic/weather-spa
|
import { Router, Route, browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import { render } from 'react-dom'
import React from 'react'
import App from './containers/App'
import configure from './store'
const store = configure()
render(
<Provider store={store}>
<Router history={browserHistory}>
<Route path="/" component={App}>
</Route>
</Router>
</Provider>,
document.getElementById('root')
)
|
app/javascript/mastodon/features/compose/components/emoji_picker_dropdown.js
|
cybrespace/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import { EmojiPicker as EmojiPickerAsync } from '../../ui/util/async-components';
import Overlay from 'react-overlays/lib/Overlay';
import classNames from 'classnames';
import ImmutablePropTypes from 'react-immutable-proptypes';
import detectPassiveEvents from 'detect-passive-events';
import { buildCustomEmojis } from '../../emoji/emoji';
const messages = defineMessages({
emoji: { id: 'emoji_button.label', defaultMessage: 'Insert emoji' },
emoji_search: { id: 'emoji_button.search', defaultMessage: 'Search...' },
emoji_not_found: { id: 'emoji_button.not_found', defaultMessage: 'No emojos!! (╯°□°)╯︵ ┻━┻' },
custom: { id: 'emoji_button.custom', defaultMessage: 'Custom' },
recent: { id: 'emoji_button.recent', defaultMessage: 'Frequently used' },
search_results: { id: 'emoji_button.search_results', defaultMessage: 'Search results' },
people: { id: 'emoji_button.people', defaultMessage: 'People' },
nature: { id: 'emoji_button.nature', defaultMessage: 'Nature' },
food: { id: 'emoji_button.food', defaultMessage: 'Food & Drink' },
activity: { id: 'emoji_button.activity', defaultMessage: 'Activity' },
travel: { id: 'emoji_button.travel', defaultMessage: 'Travel & Places' },
objects: { id: 'emoji_button.objects', defaultMessage: 'Objects' },
symbols: { id: 'emoji_button.symbols', defaultMessage: 'Symbols' },
flags: { id: 'emoji_button.flags', defaultMessage: 'Flags' },
});
const assetHost = process.env.CDN_HOST || '';
let EmojiPicker, Emoji; // load asynchronously
const backgroundImageFn = () => `${assetHost}/emoji/sheet_10.png`;
const listenerOptions = detectPassiveEvents.hasSupport ? { passive: true } : false;
const categoriesSort = [
'recent',
'custom',
'people',
'nature',
'foods',
'activity',
'places',
'objects',
'symbols',
'flags',
];
class ModifierPickerMenu extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
onSelect: PropTypes.func.isRequired,
onClose: PropTypes.func.isRequired,
};
handleClick = e => {
this.props.onSelect(e.currentTarget.getAttribute('data-index') * 1);
}
componentWillReceiveProps (nextProps) {
if (nextProps.active) {
this.attachListeners();
} else {
this.removeListeners();
}
}
componentWillUnmount () {
this.removeListeners();
}
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
attachListeners () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
removeListeners () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
render () {
const { active } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers__menu' style={{ display: active ? 'block' : 'none' }} ref={this.setRef}>
<button onClick={this.handleClick} data-index={1}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={1} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={2}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={2} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={3}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={3} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={4}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={4} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={5}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={5} backgroundImageFn={backgroundImageFn} /></button>
<button onClick={this.handleClick} data-index={6}><Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={6} backgroundImageFn={backgroundImageFn} /></button>
</div>
);
}
}
class ModifierPicker extends React.PureComponent {
static propTypes = {
active: PropTypes.bool,
modifier: PropTypes.number,
onChange: PropTypes.func,
onClose: PropTypes.func,
onOpen: PropTypes.func,
};
handleClick = () => {
if (this.props.active) {
this.props.onClose();
} else {
this.props.onOpen();
}
}
handleSelect = modifier => {
this.props.onChange(modifier);
this.props.onClose();
}
render () {
const { active, modifier } = this.props;
return (
<div className='emoji-picker-dropdown__modifiers'>
<Emoji emoji='fist' set='twitter' size={22} sheetSize={32} skin={modifier} onClick={this.handleClick} backgroundImageFn={backgroundImageFn} />
<ModifierPickerMenu active={active} onSelect={this.handleSelect} onClose={this.props.onClose} />
</div>
);
}
}
@injectIntl
class EmojiPickerMenu extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
loading: PropTypes.bool,
onClose: PropTypes.func.isRequired,
onPick: PropTypes.func.isRequired,
style: PropTypes.object,
placement: PropTypes.string,
arrowOffsetLeft: PropTypes.string,
arrowOffsetTop: PropTypes.string,
intl: PropTypes.object.isRequired,
skinTone: PropTypes.number.isRequired,
onSkinTone: PropTypes.func.isRequired,
};
static defaultProps = {
style: {},
loading: true,
frequentlyUsedEmojis: [],
};
state = {
modifierOpen: false,
placement: null,
};
handleDocumentClick = e => {
if (this.node && !this.node.contains(e.target)) {
this.props.onClose();
}
}
componentDidMount () {
document.addEventListener('click', this.handleDocumentClick, false);
document.addEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
componentWillUnmount () {
document.removeEventListener('click', this.handleDocumentClick, false);
document.removeEventListener('touchend', this.handleDocumentClick, listenerOptions);
}
setRef = c => {
this.node = c;
}
getI18n = () => {
const { intl } = this.props;
return {
search: intl.formatMessage(messages.emoji_search),
notfound: intl.formatMessage(messages.emoji_not_found),
categories: {
search: intl.formatMessage(messages.search_results),
recent: intl.formatMessage(messages.recent),
people: intl.formatMessage(messages.people),
nature: intl.formatMessage(messages.nature),
foods: intl.formatMessage(messages.food),
activity: intl.formatMessage(messages.activity),
places: intl.formatMessage(messages.travel),
objects: intl.formatMessage(messages.objects),
symbols: intl.formatMessage(messages.symbols),
flags: intl.formatMessage(messages.flags),
custom: intl.formatMessage(messages.custom),
},
};
}
handleClick = emoji => {
if (!emoji.native) {
emoji.native = emoji.colons;
}
this.props.onClose();
this.props.onPick(emoji);
}
handleModifierOpen = () => {
this.setState({ modifierOpen: true });
}
handleModifierClose = () => {
this.setState({ modifierOpen: false });
}
handleModifierChange = modifier => {
this.props.onSkinTone(modifier);
}
render () {
const { loading, style, intl, custom_emojis, skinTone, frequentlyUsedEmojis } = this.props;
if (loading) {
return <div style={{ width: 299 }} />;
}
const title = intl.formatMessage(messages.emoji);
const { modifierOpen } = this.state;
return (
<div className={classNames('emoji-picker-dropdown__menu', { selecting: modifierOpen })} style={style} ref={this.setRef}>
<EmojiPicker
perLine={8}
emojiSize={22}
sheetSize={32}
custom={buildCustomEmojis(custom_emojis)}
color=''
emoji=''
set='twitter'
title={title}
i18n={this.getI18n()}
onClick={this.handleClick}
include={categoriesSort}
recent={frequentlyUsedEmojis}
skin={skinTone}
showPreview={false}
backgroundImageFn={backgroundImageFn}
autoFocus
emojiTooltip
/>
<ModifierPicker
active={modifierOpen}
modifier={skinTone}
onOpen={this.handleModifierOpen}
onClose={this.handleModifierClose}
onChange={this.handleModifierChange}
/>
</div>
);
}
}
export default @injectIntl
class EmojiPickerDropdown extends React.PureComponent {
static propTypes = {
custom_emojis: ImmutablePropTypes.list,
frequentlyUsedEmojis: PropTypes.arrayOf(PropTypes.string),
intl: PropTypes.object.isRequired,
onPickEmoji: PropTypes.func.isRequired,
onSkinTone: PropTypes.func.isRequired,
skinTone: PropTypes.number.isRequired,
};
state = {
active: false,
loading: false,
};
setRef = (c) => {
this.dropdown = c;
}
onShowDropdown = ({ target }) => {
this.setState({ active: true });
if (!EmojiPicker) {
this.setState({ loading: true });
EmojiPickerAsync().then(EmojiMart => {
EmojiPicker = EmojiMart.Picker;
Emoji = EmojiMart.Emoji;
this.setState({ loading: false });
}).catch(() => {
this.setState({ loading: false });
});
}
const { top } = target.getBoundingClientRect();
this.setState({ placement: top * 2 < innerHeight ? 'bottom' : 'top' });
}
onHideDropdown = () => {
this.setState({ active: false });
}
onToggle = (e) => {
if (!this.state.loading && (!e.key || e.key === 'Enter')) {
if (this.state.active) {
this.onHideDropdown();
} else {
this.onShowDropdown(e);
}
}
}
handleKeyDown = e => {
if (e.key === 'Escape') {
this.onHideDropdown();
}
}
setTargetRef = c => {
this.target = c;
}
findTarget = () => {
return this.target;
}
render () {
const { intl, onPickEmoji, onSkinTone, skinTone, frequentlyUsedEmojis } = this.props;
const title = intl.formatMessage(messages.emoji);
const { active, loading, placement } = this.state;
return (
<div className='emoji-picker-dropdown' onKeyDown={this.handleKeyDown}>
<div ref={this.setTargetRef} className='emoji-button' title={title} aria-label={title} aria-expanded={active} role='button' onClick={this.onToggle} onKeyDown={this.onToggle} tabIndex={0}>
<img
className={classNames('emojione', { 'pulse-loading': active && loading })}
alt='🤔'
src={`${assetHost}/emoji/1f914.svg`}
/>
</div>
<Overlay show={active} placement={placement} target={this.findTarget}>
<EmojiPickerMenu
custom_emojis={this.props.custom_emojis}
loading={loading}
onClose={this.onHideDropdown}
onPick={onPickEmoji}
onSkinTone={onSkinTone}
skinTone={skinTone}
frequentlyUsedEmojis={frequentlyUsedEmojis}
/>
</Overlay>
</div>
);
}
}
|
node_modules/react-bootstrap/es/TabContainer.js
|
mohammed52/door-quote-automator
|
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
import uncontrollable from 'uncontrollable';
var TAB = 'tab';
var PANE = 'pane';
var idPropType = PropTypes.oneOfType([PropTypes.string, PropTypes.number]);
var propTypes = {
/**
* HTML id attribute, required if no `generateChildId` prop
* is specified.
*/
id: function id(props) {
var error = null;
if (!props.generateChildId) {
for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
args[_key - 1] = arguments[_key];
}
error = idPropType.apply(undefined, [props].concat(args));
if (!error && !props.id) {
error = new Error('In order to properly initialize Tabs in a way that is accessible ' + 'to assistive technologies (such as screen readers) an `id` or a ' + '`generateChildId` prop to TabContainer is required');
}
}
return error;
},
/**
* A function that takes an `eventKey` and `type` and returns a unique id for
* child tab `<NavItem>`s and `<TabPane>`s. The function _must_ be a pure
* function, meaning it should always return the _same_ id for the same set
* of inputs. The default value requires that an `id` to be set for the
* `<TabContainer>`.
*
* The `type` argument will either be `"tab"` or `"pane"`.
*
* @defaultValue (eventKey, type) => `${this.props.id}-${type}-${key}`
*/
generateChildId: PropTypes.func,
/**
* A callback fired when a tab is selected.
*
* @controllable activeKey
*/
onSelect: PropTypes.func,
/**
* The `eventKey` of the currently active tab.
*
* @controllable onSelect
*/
activeKey: PropTypes.any
};
var childContextTypes = {
$bs_tabContainer: PropTypes.shape({
activeKey: PropTypes.any,
onSelect: PropTypes.func.isRequired,
getTabId: PropTypes.func.isRequired,
getPaneId: PropTypes.func.isRequired
})
};
var TabContainer = function (_React$Component) {
_inherits(TabContainer, _React$Component);
function TabContainer() {
_classCallCheck(this, TabContainer);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
TabContainer.prototype.getChildContext = function getChildContext() {
var _props = this.props,
activeKey = _props.activeKey,
onSelect = _props.onSelect,
generateChildId = _props.generateChildId,
id = _props.id;
var getId = generateChildId || function (key, type) {
return id ? id + '-' + type + '-' + key : null;
};
return {
$bs_tabContainer: {
activeKey: activeKey,
onSelect: onSelect,
getTabId: function getTabId(key) {
return getId(key, TAB);
},
getPaneId: function getPaneId(key) {
return getId(key, PANE);
}
}
};
};
TabContainer.prototype.render = function render() {
var _props2 = this.props,
children = _props2.children,
props = _objectWithoutProperties(_props2, ['children']);
delete props.generateChildId;
delete props.onSelect;
delete props.activeKey;
return React.cloneElement(React.Children.only(children), props);
};
return TabContainer;
}(React.Component);
TabContainer.propTypes = propTypes;
TabContainer.childContextTypes = childContextTypes;
export default uncontrollable(TabContainer, { activeKey: 'onSelect' });
|
jenkins-design-language/src/js/components/material-ui/svg-icons/navigation/chevron-left.js
|
alvarolobato/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const NavigationChevronLeft = (props) => (
<SvgIcon {...props}>
<path d="M15.41 7.41L14 6l-6 6 6 6 1.41-1.41L10.83 12z"/>
</SvgIcon>
);
NavigationChevronLeft.displayName = 'NavigationChevronLeft';
NavigationChevronLeft.muiName = 'SvgIcon';
export default NavigationChevronLeft;
|
_experiment/react-fetch-github-repo/v2-fetch-in-react-didmount/src/App.js
|
David-JC/react-testing
|
import React from 'react';
import ReactDOM from 'react-dom';
class FetchDemo extends React.Component {
constructor(props) {
super(props); // la parola 'super' è usata per chiamare funzioni dal parente di un oggetto
// inizializzo lo state
this.state = {
repos: [] // setto l'array dei repo come vuoto
};
}
// metodo che si esegue quando il componente viene montato la prima volta
componentDidMount() {
const url = 'https://api.github.com/users/iGenius-Srl/repos';
// fetch dei dati
fetch(url)
// se riesce
.then(
response => response.json()
)
.then(
json => {
//console.log(json);
const repos = json; // creo un nuovo array con i dati di risultato
// aggiorno lo stato del componente con il nuovo array di repo, questo comando triggera il re-render
this.setState({ repos });
console.log(repos);
}
)
}
render() {
return (
<div>
<h1>Test Fetch data</h1>
<ul>
{this.state.repos.map(repo =>
<li key={repo.id}>{repo.name}</li>
)}
</ul>
</div>
);
}
}
ReactDOM.render(
<FetchDemo/>,
document.getElementById('app')
);
|
src/svg-icons/av/music-video.js
|
manchesergit/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvMusicVideo = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3V5h18v14zM8 15c0-1.66 1.34-3 3-3 .35 0 .69.07 1 .18V6h5v2h-3v7.03c-.02 1.64-1.35 2.97-3 2.97-1.66 0-3-1.34-3-3z"/>
</SvgIcon>
);
AvMusicVideo = pure(AvMusicVideo);
AvMusicVideo.displayName = 'AvMusicVideo';
AvMusicVideo.muiName = 'SvgIcon';
export default AvMusicVideo;
|
src/containers/tests/Species.spec.js
|
adrianha/swapii
|
import React from 'react';
import { shallow } from 'enzyme';
import { expect } from 'chai';
import { Species } from '../Species';
describe('<Species />', () => {
it('should have a class .species', () => {
const props = {
specieses: {
isFetching: false,
detail: {
name: 'Luke Skywalker'
}
}
};
expect(shallow(<Species {...props} />).is('.species')).to.equal(true);
});
});
|
app/javascript/flavours/glitch/features/following/index.js
|
vahnj/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from 'flavours/glitch/components/loading_indicator';
import {
fetchAccount,
fetchFollowing,
expandFollowing,
} from 'flavours/glitch/actions/accounts';
import { ScrollContainer } from 'react-router-scroll-4';
import AccountContainer from 'flavours/glitch/containers/account_container';
import Column from 'flavours/glitch/features/ui/components/column';
import HeaderContainer from 'flavours/glitch/features/account_timeline/containers/header_container';
import LoadMore from 'flavours/glitch/components/load_more';
import ColumnBackButton from 'flavours/glitch/components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'following', props.params.accountId, 'items']),
hasMore: !!state.getIn(['user_lists', 'following', props.params.accountId, 'next']),
});
@connect(mapStateToProps)
export default class Following extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
hasMore: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchAccount(this.props.params.accountId));
this.props.dispatch(fetchFollowing(this.props.params.accountId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.accountId !== this.props.params.accountId && nextProps.params.accountId) {
this.props.dispatch(fetchAccount(nextProps.params.accountId));
this.props.dispatch(fetchFollowing(nextProps.params.accountId));
}
}
handleScroll = (e) => {
const { scrollTop, scrollHeight, clientHeight } = e.target;
if (scrollTop === scrollHeight - clientHeight && this.props.hasMore) {
this.props.dispatch(expandFollowing(this.props.params.accountId));
}
}
handleLoadMore = (e) => {
e.preventDefault();
this.props.dispatch(expandFollowing(this.props.params.accountId));
}
render () {
const { accountIds, hasMore } = this.props;
let loadMore = null;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
if (hasMore) {
loadMore = <LoadMore onClick={this.handleLoadMore} />;
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='following'>
<div className='scrollable' onScroll={this.handleScroll}>
<div className='following'>
<HeaderContainer accountId={this.props.params.accountId} hideTabs />
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
{loadMore}
</div>
</div>
</ScrollContainer>
</Column>
);
}
}
|
src/ReturnButton.js
|
PSilling/StudentHubUIDevelopment
|
import React, { Component } from 'react';
import Button from 'react-toolbox/lib/button/Button.js';
/**
* Renders the return to university list Button.
* @param returnCallback() defines the return function to call onClick
*/
class ReturnButton extends Component {
render() {
return(
<span>
<Button onClick={() => this.props.returnCallback()} icon="arrow_back" label="Back" />
</span>
);
}
}
export default ReturnButton;
|
src/icons/SettingsBackupRestoreIcon.js
|
kiloe/ui
|
import React from 'react';
import Icon from '../Icon';
export default class SettingsBackupRestoreIcon extends Icon {
getSVG(){return <svg xmlns="http://www.w3.org/2000/svg" width="48" height="48" viewBox="0 0 48 48"><path d="M28 24c0-2.21-1.79-4-4-4s-4 1.79-4 4 1.79 4 4 4 4-1.79 4-4zM24 6C14.06 6 6 14.06 6 24H0l8 8 8-8h-6c0-7.73 6.27-14 14-14s14 6.27 14 14-6.27 14-14 14c-3.03 0-5.82-.97-8.12-2.61l-2.83 2.87C16.09 40.6 19.88 42 24 42c9.94 0 18-8.06 18-18S33.94 6 24 6z"/></svg>;}
};
|
src/tabs/Tab.js
|
kosiakMD/react-native-elements
|
/*eslint-disable no-console */
import React from 'react';
import TabNavigator from 'react-native-tab-navigator';
const Tab = props => {
console.warn(
`Warning: Tab has been deprecated and will be removed in a future version of React Native Elements. For a complete navigation solution that includes Tabs as well as many other features, be sure to check out react-navigation (https://reactnavigation.org) and it's TabNavigator.`
);
return <TabNavigator.Item {...props} />;
};
export default Tab;
|
src/components/pc_index.js
|
nanhaishiyounan/css3
|
import React from 'react';
import PCHeader from './pc_header';
import PCContainer from './pc_container';
import PCNewsBlock from './pc_news_block';
import PCNewsDetails from './pc_news_details';
import PCCSSHTML from './pc_csshtml';
import { Router, Route, Link, hashHistory} from 'react-router';
export default class PCIndex extends React.Component {
constructor(){
super();
this.state={
};
}
render() {
return (
<div>
<Router history={hashHistory}>
<Route path="/" component={PCHeader}>
<Route path="newsdemo" component={PCContainer} />
<Route path="csshtml" component={PCCSSHTML} />
</Route>
<Route path="/details/:uniquekey" component={PCNewsDetails} />
</Router>
</div>
);
}
}
|
pages/less.js
|
elliotec/LnL
|
import React from 'react'
import './example.less'
import Helmet from 'react-helmet'
import { config } from 'config'
export default class Less extends React.Component {
render () {
return (
<div>
<Helmet
title={`${config.siteTitle} | Hi lessy friends`}
/>
<h1
className="the-less-class"
>
Hi lessy friends
</h1>
<div className="less-nav-example">
<h2>Nav example</h2>
<ul>
<li>
<a href="#">Store</a>
</li>
<li>
<a href="#">Help</a>
</li>
<li>
<a href="#">Logout</a>
</li>
</ul>
</div>
</div>
)
}
}
|
src/svg-icons/av/videocam-off.js
|
rhaedes/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvVideocamOff = (props) => (
<SvgIcon {...props}>
<path d="M21 6.5l-4 4V7c0-.55-.45-1-1-1H9.82L21 17.18V6.5zM3.27 2L2 3.27 4.73 6H4c-.55 0-1 .45-1 1v10c0 .55.45 1 1 1h12c.21 0 .39-.08.54-.18L19.73 21 21 19.73 3.27 2z"/>
</SvgIcon>
);
AvVideocamOff = pure(AvVideocamOff);
AvVideocamOff.displayName = 'AvVideocamOff';
export default AvVideocamOff;
|
src/views/UserManage/index.js
|
halo-design/halo-optimus
|
import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
import { Row, Col } from 'antd'
import BranchTree from 'COMPONENT/BranchTree'
import InputSearch from 'COMPONENT/InputSearch'
import UserQuery from './UserQuery'
import UserTable from './UserTable'
import { initBranchList } from 'REDUCER/public/branchTree'
import { userPageByBrh } from 'REDUCER/pages/userManage'
@connect(
state => {
const {
pages: {
userManage: { selectedKeys }
},
public: {
branchTree: {
allBranchList,
treeBranchList
}
}
} = state
return {
treeBranchList,
allBranchList,
selectedKeys
}
},
dispatch => bindActionCreators({ initBranchList, userPageByBrh }, dispatch)
)
export default class UserManageView extends React.Component {
constructor (props) {
super(props)
this.branchSelected = this.branchSelected.bind(this)
this.onSearch = this.onSearch.bind(this)
}
componentWillMount () {
// 初始化银行机构列表
this.props.initBranchList()
}
branchSelected (info) {
const { userPageByBrh } = this.props
userPageByBrh({
currentPage: '1',
brhId: info.brhId,
brhName: info.title
})
}
onSearch (brhName) {
const { userPageByBrh, allBranchList } = this.props
// 取到 brhId
let id = ''
allBranchList.map(item => {
if (item.brhName === brhName) {
id = item.brhId
}
})
userPageByBrh({
currentPage: '1',
brhId: id,
brhName: brhName
})
}
render () {
const { treeBranchList, selectedKeys } = this.props
return (
<div className='pageUserManage'>
<Row>
<Col span={5}>
<div className='app-left-side'>
<InputSearch
placeholder='请输入搜索机构名称'
initialValue=''
onSearch={this.onSearch}
/>
<BranchTree
selectedKeys={selectedKeys}
selected={this.branchSelected}
branchList={treeBranchList}
/>
</div>
</Col>
<Col span={19}>
<UserQuery />
<UserTable />
</Col>
</Row>
</div>
)
}
}
|
src/routes/about/index.js
|
ChrisWC/MaterL
|
import React from 'react';
import About from './About';
import fetch from '../../core/fetch';
export default {
path: '/about',
async action() {
return <About />;
},
};
|
src/containers/Switcher/index.js
|
LeoVitale/express-beer
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import universal from 'react-universal-component';
const UniversalComponent = universal(({ page }) => import(`../${page}`), {
minDelay: 500,
loading: () => (
<div>
<div />
</div>
),
error: () => <div>PAGE NOT FOUND - 404</div>
});
const Switcher = ({ page }) => (
<div>
<UniversalComponent page={page} />
</div>
);
Switcher.propTypes = {
page: PropTypes.string
};
const mapState = ({ page }) => ({ page });
export default connect(mapState)(Switcher);
|
src/routes/error/ErrorPage.js
|
takahashik/todo-app
|
/**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './ErrorPage.css';
class ErrorPage extends React.Component {
static propTypes = {
error: PropTypes.shape({
name: PropTypes.string.isRequired,
message: PropTypes.string.isRequired,
stack: PropTypes.string.isRequired,
}).isRequired,
};
render() {
if (__DEV__) {
const { error } = this.props;
return (
<div>
<h1>{error.name}</h1>
<p>{error.message}</p>
<pre>{error.stack}</pre>
</div>
);
}
return (
<div>
<h1>Error</h1>
<p>Sorry, a critical error occurred on this page.</p>
</div>
);
}
}
export { ErrorPage as ErrorPageWithoutStyle };
export default withStyles(s)(ErrorPage);
|
src/components/Dashboard/sendButton.js
|
ChronoBank/ChronoWAVES
|
import log from 'loglevel';
import React from 'react';
import FlatButton from 'material-ui/FlatButton';
import Popover from 'material-ui/Popover';
import Menu from 'material-ui/Menu';
import MenuItem from 'material-ui/MenuItem';
import {SendIcon} from '../Icons';
import {Link} from 'react-router';
const styles = {
display: 'inline-block'
};
export default class SendButton extends React.Component {
constructor(props) {
super(props);
this.state = {
open: false,
};
}
handleTouchTap = (event) => {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget,
});
};
handleRequestClose = () => {
this.setState({
open: false,
});
};
render() {
const addresses = this.props.addresses;
return (
<div style={ styles }>
<FlatButton
onTouchTap={ this.handleTouchTap }
label="SEND"
icon={<SendIcon />}/>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{horizontal: 'left', vertical: 'bottom'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
onRequestClose={this.handleRequestClose}
>
<Menu>
{addresses.entrySeq().map(([key, value]) => (
<MenuItem key={ key }
onTouchTap={ this.handleRequestClose }
containerElement={ <Link to={`/wallet/account/${value.address}/send`}/>}
primaryText={ (<span>{ value.address }</span>) }
secondaryText={ value.balance.toString() }/>
))}
</Menu>
</Popover>
</div>
);
}
}
|
node_modules/semantic-ui-react/dist/es/elements/Reveal/Reveal.js
|
SuperUncleCat/ServerMonitoring
|
import _extends from 'babel-runtime/helpers/extends';
import cx from 'classnames';
import PropTypes from 'prop-types';
import React from 'react';
import { customPropTypes, getElementType, getUnhandledProps, META, useKeyOnly } from '../../lib';
import RevealContent from './RevealContent';
/**
* A reveal displays additional content in place of previous content when activated.
*/
function Reveal(props) {
var active = props.active,
animated = props.animated,
children = props.children,
className = props.className,
disabled = props.disabled,
instant = props.instant;
var classes = cx('ui', animated, useKeyOnly(active, 'active'), useKeyOnly(disabled, 'disabled'), useKeyOnly(instant, 'instant'), 'reveal', className);
var rest = getUnhandledProps(Reveal, props);
var ElementType = getElementType(Reveal, props);
return React.createElement(
ElementType,
_extends({}, rest, { className: classes }),
children
);
}
Reveal.handledProps = ['active', 'animated', 'as', 'children', 'className', 'disabled', 'instant'];
Reveal._meta = {
name: 'Reveal',
type: META.TYPES.ELEMENT
};
Reveal.propTypes = process.env.NODE_ENV !== "production" ? {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** An active reveal displays its hidden content. */
active: PropTypes.bool,
/** An animation name that will be applied to Reveal. */
animated: PropTypes.oneOf(['fade', 'small fade', 'move', 'move right', 'move up', 'move down', 'rotate', 'rotate left']),
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
/** A disabled reveal will not animate when hovered. */
disabled: PropTypes.bool,
/** An element can show its content without delay. */
instant: PropTypes.bool
} : {};
Reveal.Content = RevealContent;
export default Reveal;
|
packages/benchmarks/src/implementations/emotion/Dot.js
|
necolas/react-native-web
|
import React from 'react';
import { css } from '@emotion/css';
const Dot = ({ size, x, y, children, color }) => (
<div
className={css([
styles.root,
{
borderBottomColor: color,
borderRightWidth: `${size / 2}px`,
borderBottomWidth: `${size / 2}px`,
borderLeftWidth: `${size / 2}px`,
marginLeft: `${x}px`,
marginTop: `${y}px`
}
])}
>
{children}
</div>
);
const styles = {
root: {
position: 'absolute',
cursor: 'pointer',
width: 0,
height: 0,
borderColor: 'transparent',
borderStyle: 'solid',
borderTopWidth: 0,
transform: 'translate(50%, 50%)'
}
};
export default Dot;
|
app/javascript/mastodon/features/direct_timeline/index.js
|
5thfloor/ichiji-social
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { mountConversations, unmountConversations, expandConversations } from '../../actions/conversations';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { connectDirectStream } from '../../actions/streaming';
import ConversationsListContainer from './containers/conversations_list_container';
const messages = defineMessages({
title: { id: 'column.direct', defaultMessage: 'Direct messages' },
});
export default @connect()
@injectIntl
class DirectTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
columnId: PropTypes.string,
intl: PropTypes.object.isRequired,
hasUnread: PropTypes.bool,
multiColumn: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn('DIRECT', {}));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch } = this.props;
dispatch(mountConversations());
dispatch(expandConversations());
this.disconnect = dispatch(connectDirectStream());
}
componentWillUnmount () {
this.props.dispatch(unmountConversations());
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
this.props.dispatch(expandConversations({ maxId }));
}
render () {
const { intl, hasUnread, columnId, multiColumn, shouldUpdateScroll } = this.props;
const pinned = !!columnId;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='envelope'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
/>
<ConversationsListContainer
trackScroll={!pinned}
scrollKey={`direct_timeline-${columnId}`}
timelineId='direct'
onLoadMore={this.handleLoadMore}
emptyMessage={<FormattedMessage id='empty_column.direct' defaultMessage="You don't have any direct messages yet. When you send or receive one, it will show up here." />}
shouldUpdateScroll={shouldUpdateScroll}
/>
</Column>
);
}
}
|
lib/ui/src/containers/nav.js
|
storybooks/react-storybook
|
import { DOCS_MODE } from 'global';
import React from 'react';
import memoize from 'memoizerific';
import { Badge } from '@storybook/components';
import { Consumer } from '@storybook/api';
import { shortcutToHumanString } from '../libs/shortcut';
import ListItemIcon from '../components/sidebar/ListItemIcon';
import Sidebar from '../components/sidebar/Sidebar';
const focusableUIElements = {
storySearchField: 'storybook-explorer-searchfield',
storyListMenu: 'storybook-explorer-menu',
storyPanelRoot: 'storybook-panel-root',
};
const shortcutToHumanStringIfEnabled = (shortcuts, enableShortcuts) =>
enableShortcuts ? shortcutToHumanString(shortcuts) : null;
const createMenu = memoize(1)(
(api, shortcutKeys, isFullscreen, showPanel, showNav, enableShortcuts) => [
{
id: 'S',
title: 'Show sidebar',
onClick: () => api.toggleNav(),
right: shortcutToHumanStringIfEnabled(shortcutKeys.toggleNav, enableShortcuts),
left: showNav ? <ListItemIcon icon="check" /> : <ListItemIcon />,
},
{
id: 'A',
title: 'Show addons',
onClick: () => api.togglePanel(),
right: shortcutToHumanStringIfEnabled(shortcutKeys.togglePanel, enableShortcuts),
left: showPanel ? <ListItemIcon icon="check" /> : <ListItemIcon />,
},
{
id: 'D',
title: 'Change addons orientation',
onClick: () => api.togglePanelPosition(),
right: shortcutToHumanStringIfEnabled(shortcutKeys.panelPosition, enableShortcuts),
left: <ListItemIcon />,
},
{
id: 'F',
title: 'Go full screen',
onClick: api.toggleFullscreen,
right: shortcutToHumanStringIfEnabled(shortcutKeys.fullScreen, enableShortcuts),
left: isFullscreen ? 'check' : <ListItemIcon />,
},
{
id: '/',
title: 'Search',
onClick: () => api.focusOnUIElement(focusableUIElements.storySearchField),
right: shortcutToHumanStringIfEnabled(shortcutKeys.search, enableShortcuts),
left: <ListItemIcon />,
},
{
id: 'up',
title: 'Previous component',
onClick: () => api.jumpToComponent(-1),
right: shortcutToHumanStringIfEnabled(shortcutKeys.prevComponent, enableShortcuts),
left: <ListItemIcon />,
},
{
id: 'down',
title: 'Next component',
onClick: () => api.jumpToComponent(1),
right: shortcutToHumanStringIfEnabled(shortcutKeys.nextComponent, enableShortcuts),
left: <ListItemIcon />,
},
{
id: 'prev',
title: 'Previous story',
onClick: () => api.jumpToStory(-1),
right: shortcutToHumanStringIfEnabled(shortcutKeys.prevStory, enableShortcuts),
left: <ListItemIcon />,
},
{
id: 'next',
title: 'Next story',
onClick: () => api.jumpToStory(1),
right: shortcutToHumanStringIfEnabled(shortcutKeys.nextStory, enableShortcuts),
left: <ListItemIcon />,
},
{
id: 'about',
title: 'About your Storybook',
onClick: () => api.navigate('/settings/about'),
right: api.versionUpdateAvailable() && <Badge status="positive">Update</Badge>,
left: <ListItemIcon />,
},
{
id: 'shortcuts',
title: 'Keyboard shortcuts',
onClick: () => api.navigate('/settings/shortcuts'),
right: shortcutToHumanStringIfEnabled(shortcutKeys.shortcutsPage, enableShortcuts),
left: <ListItemIcon />,
},
{
id: 'collapse',
title: 'Collapse all',
onClick: () => api.collapseAll(),
right: shortcutToHumanString(shortcutKeys.collapseAll),
left: <ListItemIcon />,
},
]
);
export const collapseAllStories = stories => {
// keep track of component IDs that have been rewritten to the ID of their first leaf child
const componentIdToLeafId = {};
// 1) remove all leaves
const leavesRemoved = Object.values(stories).filter(
item => !(item.isLeaf && stories[item.parent].isComponent)
);
// 2) make all components leaves and rewrite their ID's to the first leaf child
const componentsFlattened = leavesRemoved.map(item => {
const { id, isComponent, children, ...rest } = item;
// this is a folder, so just leave it alone
if (!isComponent) {
return item;
}
const nonLeafChildren = [];
const leafChildren = [];
children.forEach(child => (stories[child].isLeaf ? leafChildren : nonLeafChildren).push(child));
if (leafChildren.length === 0) {
return item; // pass through, we'll handle you later
}
const leafId = leafChildren[0];
const component = { ...rest, id: leafId, isLeaf: true, isComponent: true };
componentIdToLeafId[id] = leafId;
// this is a component, so it should not have any non-leaf children
if (nonLeafChildren.length !== 0) {
throw new Error(
`Unexpected '${item.id}': ${JSON.stringify({ isComponent, nonLeafChildren })}`
);
}
return component;
});
// 3) rewrite all the children as needed
const childrenRewritten = componentsFlattened.map(item => {
if (item.isLeaf) {
return item;
}
const { children, ...rest } = item;
const rewritten = children.map(child => componentIdToLeafId[child] || child);
return { children: rewritten, ...rest };
});
const result = {};
childrenRewritten.forEach(item => {
result[item.id] = item;
});
return result;
};
export const collapseDocsOnlyStories = storiesHash => {
// keep track of component IDs that have been rewritten to the ID of their first leaf child
const componentIdToLeafId = {};
const docsOnlyStoriesRemoved = Object.values(storiesHash).filter(item => {
if (item.isLeaf && item.parameters && item.parameters.docsOnly) {
componentIdToLeafId[item.parent] = item.id;
return false; // filter it out
}
return true;
});
const docsOnlyComponentsCollapsed = docsOnlyStoriesRemoved.map(item => {
// collapse docs-only components
const { isComponent, children, id } = item;
if (isComponent && children.length === 1) {
const leafId = componentIdToLeafId[id];
if (leafId) {
const collapsed = {
...item,
id: leafId,
isLeaf: true,
children: undefined,
};
return collapsed;
}
}
// update groups
if (children) {
const rewritten = children.map(child => componentIdToLeafId[child] || child);
return { ...item, children: rewritten };
}
// pass through stories unmodified
return item;
});
const result = {};
docsOnlyComponentsCollapsed.forEach(item => {
result[item.id] = item;
});
return result;
};
export const mapper = ({ state, api }) => {
const {
ui: { name, url, enableShortcuts },
viewMode,
storyId,
layout: { isFullscreen, showPanel, showNav },
storiesHash,
storiesConfigured,
} = state;
const stories = DOCS_MODE
? collapseAllStories(storiesHash)
: collapseDocsOnlyStories(storiesHash);
const shortcutKeys = api.getShortcutKeys();
return {
loading: !storiesConfigured,
title: name,
url,
stories,
storyId,
viewMode,
menu: createMenu(api, shortcutKeys, isFullscreen, showPanel, showNav, enableShortcuts),
menuHighlighted: api.versionUpdateAvailable(),
};
};
export default props => (
<Consumer filter={mapper}>{fromState => <Sidebar {...props} {...fromState} />}</Consumer>
);
|
node_modules/react-scripts/template/src/index.js
|
jlbooker/shop-hours-demo
|
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/components/AdminPage.js
|
vladpolonskiy/news-feed-react-redux
|
import React from 'react';
export default class AdminPage extends React.Component {
render() {
return (
<div>
<div className="app-header">
<h1>Admin Page</h1>
</div>
<h3>Attention</h3>
<p>It's just test page to show role capabilities.</p>
</div>
);
}
}
|
dist/lib/carbon-fields/assets/js/containers/components/container/tabs.js
|
ArtFever911/statrer-kit
|
/**
* The external dependencies.
*/
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
/**
* The internal dependencies.
*/
import ContainerBase from 'containers/components/container/base';
/**
* Render the tabs of the container.
*
* @param {Object} props
* @param {Object} prop.container
* @param {Array} prop.tabs
* @return {React.Element}
*/
const ContainerTabs = ({ container, tabs }) => {
return <div className="carbon-tabs-body">
{
tabs.map(({ id, active, fields }) => (
<div key={id} className={cx('carbon-fields-collection', 'carbon-tab', { active })}>
<ContainerBase
container={container}
fields={fields} />
</div>
))
}
</div>;
};
/**
* Validate the props.
*
* @type {Object}
*/
ContainerTabs.propTypes = {
container: PropTypes.object,
tabs: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.string,
active: PropTypes.bool,
fields: PropTypes.array,
})),
};
export default ContainerTabs;
|
js/webui/src/app.js
|
hyperblast/beefweb
|
import React from 'react'
import { PanelHeader } from './elements'
import ControlBar from './control_bar'
import PlaylistSwitcher from './playlist_switcher'
import PlaylistMenu from './playlist_menu'
import PlaylistContent from './playlist_content'
import FileBrowser from './file_browser'
import FileBrowserHeader from './file_browser_header'
import StatusBar from './status_bar'
import ModelBinding from './model_binding';
import { View } from './navigation_model';
import SettingsHeader from './settings_header';
import SettingsContent from './settings_content';
import ServiceContext from './service_context';
import PlaybackInfoBar from './playback_info_bar';
class App extends React.PureComponent
{
constructor(props, context)
{
super(props, context);
this.state = this.getStateFromModel();
this.renderView = {
[View.playlist]: this.renderPlaylistView,
[View.fileBrowser]: this.renderFileBrowserView,
[View.settings]: this.renderSettingsView,
[View.notFound]: this.renderNotFoundView,
};
}
getStateFromModel()
{
const { navigationModel, settingsModel } = this.context;
const { view } = navigationModel;
const { showPlaybackInfo } = settingsModel;
return { view, showPlaybackInfo };
}
renderPlaylistView()
{
const {
playerModel,
playlistModel,
settingsModel,
scrollManager,
} = this.context;
return {
header: (
<div className='panel-header'>
<PlaylistSwitcher
playerModel={playerModel}
playlistModel={playlistModel}
settingsModel={settingsModel} />
<PlaylistMenu
playlistModel={playlistModel}
settingsModel={settingsModel} />
</div>
),
main: (
<PlaylistContent
playerModel={playerModel}
playlistModel={playlistModel}
scrollManager={scrollManager} />
)
};
}
renderFileBrowserView()
{
const {
playlistModel,
fileBrowserModel,
notificationModel,
scrollManager,
} = this.context;
return {
header: (
<FileBrowserHeader
fileBrowserModel={fileBrowserModel}
playlistModel={playlistModel}
notificationModel={notificationModel} />
),
main: (
<FileBrowser
fileBrowserModel={fileBrowserModel}
playlistModel={playlistModel}
notificationModel={notificationModel}
scrollManager={scrollManager} />
)
};
}
renderSettingsView()
{
return {
header: <SettingsHeader />,
main: <SettingsContent />
};
}
renderNotFoundView()
{
return {
header: <PanelHeader title='Invalid url' />,
main: <div className='panel main-panel'>Invalid url</div>
};
}
render()
{
const {
playerModel,
playlistModel,
settingsModel,
navigationModel
} = this.context;
const view = this.renderView[this.state.view].call(this);
const playbackInfoBar = this.state.showPlaybackInfo
? <PlaybackInfoBar />
: null;
return (
<div className='app'>
{ playbackInfoBar }
<ControlBar
playerModel={playerModel}
settingsModel={settingsModel}
navigationModel={navigationModel} />
{ view.header }
{ view.main }
<StatusBar />
</div>
);
}
}
App.contextType = ServiceContext;
export default ModelBinding(App, {
navigationModel: 'viewChange',
settingsModel: 'change'
});
|
test/specs/lib/AutoControlledComponent-test.js
|
shengnian/shengnian-ui-react
|
/* eslint-disable no-console */
import faker from 'faker'
import _ from 'lodash'
import React from 'react'
import { AutoControlledComponent } from 'src/lib'
import { consoleUtil } from 'test/utils'
let TestClass
/* eslint-disable */
const createTestClass = (options = {}) => class Test extends AutoControlledComponent {
static autoControlledProps = options.autoControlledProps
static defaultProps = options.defaultProps
getInitialAutoControlledState() {
return options.state
}
render = () => <div />
}
/* eslint-enable */
const toDefaultName = prop => `default${prop.slice(0, 1).toUpperCase() + prop.slice(1)}`
const makeProps = () => ({
computer: 'hardware',
flux: 'capacitor',
ion: 'belt',
})
const makeDefaultProps = props => _.transform(props, (res, val, key) => {
res[toDefaultName(key)] = val
})
describe('extending AutoControlledComponent', () => {
beforeEach(() => {
TestClass = createTestClass({ autoControlledProps: [], state: {} })
})
it('does not throw with a `null` state', () => {
TestClass = createTestClass({ autoControlledProps: [], state: null })
shallow(<TestClass />)
})
describe('trySetState', () => {
it('is an instance method', () => {
shallow(<TestClass />)
.instance()
.trySetState.should.be.a('function')
})
it('sets state for autoControlledProps', () => {
consoleUtil.disableOnce()
const autoControlledProps = _.keys(makeProps())
const randomProp = _.sample(autoControlledProps)
const randomValue = faker.hacker.verb()
TestClass = createTestClass({ autoControlledProps })
const wrapper = shallow(<TestClass />)
wrapper
.instance()
.trySetState({ [randomProp]: randomValue })
wrapper
.should.have.state(randomProp, randomValue)
})
it('does not set state for non autoControlledProps', () => {
consoleUtil.disableOnce()
TestClass = createTestClass({ autoControlledProps: [], state: {} })
const wrapper = shallow(<TestClass />)
wrapper
.instance()
.trySetState({ [faker.hacker.noun()]: faker.hacker.verb() })
wrapper
.state()
.should.be.empty()
})
it('does not set state for props defined by the parent', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const randomProp = _.sample(autoControlledProps)
const randomValue = faker.hacker.phrase()
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...props} />)
wrapper
.instance()
.trySetState({ [randomProp]: randomValue })
// not updated
wrapper
.should.not.have.state(randomProp, randomValue)
// is original value
wrapper
.should.have.state(randomProp, props[randomProp])
})
it('sets state for props passed as undefined by the parent', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const randomProp = _.sample(autoControlledProps)
const randomValue = faker.hacker.phrase()
props[randomProp] = undefined
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...props} />)
wrapper
.instance()
.trySetState({ [randomProp]: randomValue })
wrapper
.should.have.state(randomProp, randomValue)
})
it('does not set state for props passed as null by the parent', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const randomProp = _.sample(autoControlledProps)
const randomValue = faker.hacker.phrase()
props[randomProp] = null
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...props} />)
wrapper
.instance()
.trySetState({ [randomProp]: randomValue })
// not updated
wrapper
.should.not.have.state(randomProp, randomValue)
// is original value
wrapper
.should.have.state(randomProp, props[randomProp])
})
})
describe('initial state', () => {
it('is derived from autoControlledProps in props', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
TestClass = createTestClass({ autoControlledProps, state: {} })
shallow(<TestClass {...props} />)
.state()
.should.deep.equal(props)
})
it('does not include non autoControlledProps', () => {
const props = makeProps()
const wrapper = shallow(<TestClass {...props} />)
_.each(props, (val, key) => wrapper.should.not.have.state(key, val))
})
it('includes non autoControlled state', () => {
const props = makeProps()
TestClass = createTestClass({ autoControlledProps: [], state: { foo: 'bar' } })
shallow(<TestClass {...props} />)
.should.have.state('foo', 'bar')
})
it('uses the initial state if default and regular props are undefined', () => {
consoleUtil.disableOnce()
const defaultProps = { defaultFoo: undefined }
const autoControlledProps = ['foo']
TestClass = createTestClass({ autoControlledProps, defaultProps, state: { foo: 'bar' } })
shallow(<TestClass foo={undefined} />)
.should.have.state('foo', 'bar')
})
it('uses the default prop if the regular prop is undefined', () => {
consoleUtil.disableOnce()
const defaultProps = { defaultFoo: 'default' }
const autoControlledProps = ['foo']
TestClass = createTestClass({ autoControlledProps, defaultProps, state: {} })
shallow(<TestClass foo={undefined} />)
.should.have.state('foo', 'default')
})
it('uses the regular prop when a default is also defined', () => {
consoleUtil.disableOnce()
const defaultProps = { defaultFoo: 'default' }
const autoControlledProps = ['foo']
TestClass = createTestClass({ autoControlledProps, defaultProps, state: {} })
shallow(<TestClass foo='initial' />)
.should.have.state('foo', 'initial')
})
it('defaults "checked" to false if not present', () => {
consoleUtil.disableOnce()
TestClass.autoControlledProps.push('checked')
shallow(<TestClass />)
.should.have.state('checked', false)
})
it('defaults "value" to an empty string if not present', () => {
consoleUtil.disableOnce()
TestClass.autoControlledProps.push('value')
shallow(<TestClass />)
.should.have.state('value', '')
})
it('defaults "value" to an empty array if "multiple"', () => {
consoleUtil.disableOnce()
TestClass.autoControlledProps.push('value')
shallow(<TestClass multiple />)
.state().should.deep.equal({ value: [] })
})
})
describe('default props', () => {
it('are applied to state for props in autoControlledProps', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const defaultProps = makeDefaultProps(props)
TestClass = createTestClass({ autoControlledProps, state: {} })
shallow(<TestClass {...defaultProps} />)
.state()
.should.deep.equal(props)
})
it('are not applied to state for normal props', () => {
const props = makeProps()
const defaultProps = makeDefaultProps(props)
const wrapper = shallow(<TestClass {...defaultProps} />)
_.each(props, (val, key) => wrapper.should.not.have.state(key, val))
})
it('allows trySetState to work on non-default autoControlledProps', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const defaultProps = makeDefaultProps(props)
const randomProp = _.sample(autoControlledProps)
const randomValue = faker.hacker.phrase()
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...defaultProps} />)
wrapper
.instance()
.trySetState({ [randomProp]: randomValue })
wrapper
.should.have.state(randomProp, randomValue)
})
})
describe('changing props', () => {
it('sets state for props in autoControlledProps', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const randomProp = _.sample(autoControlledProps)
const randomValue = faker.hacker.phrase()
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...props} />)
wrapper
.setProps({ [randomProp]: randomValue })
wrapper
.should.have.state(randomProp, randomValue)
})
it('does not set state for props not in autoControlledProps', () => {
consoleUtil.disableOnce()
const props = makeProps()
const randomProp = _.sample(_.keys(props))
const randomValue = faker.hacker.phrase()
TestClass = createTestClass({ autoControlledProps: [], state: {} })
const wrapper = shallow(<TestClass {...props} />)
wrapper
.setProps({ [randomProp]: randomValue })
wrapper
.should.not.have.state(randomProp, randomValue)
})
it('does not set state for default props when changed', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const defaultProps = makeDefaultProps(props)
const randomDefaultProp = _.sample(defaultProps)
const randomValue = faker.hacker.phrase()
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...defaultProps} />)
wrapper
.setProps({ [randomDefaultProp]: randomValue })
wrapper
.should.not.have.state(randomDefaultProp, randomValue)
})
it('does not return state to default props when setting props undefined', () => {
consoleUtil.disableOnce()
const autoControlledProps = ['foo']
const defaultProps = { defaultFoo: 'default' }
TestClass = createTestClass({ autoControlledProps, defaultProps, state: {} })
const wrapper = shallow(<TestClass foo='initial' />)
// default value
wrapper
.should.have.state('foo', 'initial')
wrapper
.setProps({ foo: undefined })
wrapper
.should.not.have.state('foo', 'foo')
})
it('sets state to undefined for props passed as undefined by the parent', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const randomProp = _.sample(autoControlledProps)
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...props} />)
// state exists initially
wrapper
.should.have.state(randomProp)
wrapper
.setProps({ [randomProp]: undefined })
// use "should not have" to assert undefined state
wrapper
.should.not.have.state(randomProp)
})
it('does not set state for props passed as null by the parent', () => {
consoleUtil.disableOnce()
const props = makeProps()
const autoControlledProps = _.keys(props)
const randomProp = _.sample(autoControlledProps)
TestClass = createTestClass({ autoControlledProps, state: {} })
const wrapper = shallow(<TestClass {...props} />)
wrapper
.setProps({ [randomProp]: null })
wrapper
.should.have.state(randomProp, null)
})
})
})
|
src/esm/components/form/field/examples.js
|
KissKissBankBank/kitten
|
import React from 'react';
import { Field } from '.';
var FieldBase = function FieldBase(_ref) {
var tooltip = _ref.tooltip,
tooltipId = _ref.tooltipId,
tooltipProps = _ref.tooltipProps,
label = _ref.label,
id = _ref.id,
error = _ref.error,
errorMessage = _ref.errorMessage,
children = _ref.children;
return /*#__PURE__*/React.createElement(Field, null, /*#__PURE__*/React.createElement(Field.Label, {
labelProps: {
htmlFor: id
},
tooltip: tooltip,
tooltipProps: tooltipProps,
tooltipId: tooltipId
}, label), children, error && /*#__PURE__*/React.createElement(Field.ErrorMessage, null, errorMessage));
};
export var FieldInputExample = function FieldInputExample(_ref2) {
var id = _ref2.id,
label = _ref2.label,
tooltip = _ref2.tooltip,
tooltipId = _ref2.tooltipId,
tooltipProps = _ref2.tooltipProps,
placeholder = _ref2.placeholder,
error = _ref2.error,
errorMessage = _ref2.errorMessage,
limit = _ref2.limit,
unit = _ref2.unit,
size = _ref2.size,
noMargin = _ref2.noMargin;
return /*#__PURE__*/React.createElement(FieldBase, {
id: id,
label: label,
tooltip: tooltip,
tooltipProps: tooltipProps,
tooltipId: tooltipId,
error: error,
errorMessage: errorMessage
}, /*#__PURE__*/React.createElement(Field.Input, {
id: id,
size: size,
limit: limit,
unit: unit,
name: "field",
placeholder: placeholder,
error: error,
noMargin: noMargin
}));
};
export var FieldPasswordExample = function FieldPasswordExample(_ref3) {
var id = _ref3.id,
label = _ref3.label,
tooltip = _ref3.tooltip,
tooltipId = _ref3.tooltipId,
tooltipProps = _ref3.tooltipProps,
placeholder = _ref3.placeholder,
error = _ref3.error,
errorMessage = _ref3.errorMessage,
size = _ref3.size;
return /*#__PURE__*/React.createElement(FieldBase, {
id: id,
label: label,
tooltip: tooltip,
tooltipProps: tooltipProps,
tooltipId: tooltipId,
error: error,
errorMessage: errorMessage
}, /*#__PURE__*/React.createElement(Field.Password, {
id: id,
size: size,
name: "field",
iconLabel: "Show password",
hiddenIconLabel: "Hide password",
placeholder: placeholder,
error: error
}));
};
export var FieldRadioButtonSetExample = function FieldRadioButtonSetExample(_ref4) {
var id = _ref4.id,
label = _ref4.label,
tooltip = _ref4.tooltip,
tooltipId = _ref4.tooltipId,
tooltipProps = _ref4.tooltipProps,
items = _ref4.items,
error = _ref4.error,
errorMessage = _ref4.errorMessage,
variant = _ref4.variant;
return /*#__PURE__*/React.createElement(FieldBase, {
id: id,
label: label,
tooltip: tooltip,
tooltipProps: tooltipProps,
tooltipId: tooltipId,
error: error,
errorMessage: errorMessage
}, /*#__PURE__*/React.createElement(Field.RadioButtonSet, {
name: "radio",
items: items,
error: error,
variant: variant
}));
};
export var FieldRadioSetExample = function FieldRadioSetExample(_ref5) {
var id = _ref5.id,
label = _ref5.label,
tooltip = _ref5.tooltip,
tooltipId = _ref5.tooltipId,
tooltipProps = _ref5.tooltipProps,
items = _ref5.items,
error = _ref5.error,
errorMessage = _ref5.errorMessage,
variant = _ref5.variant;
return /*#__PURE__*/React.createElement(FieldBase, {
id: id,
label: label,
tooltip: tooltip,
tooltipProps: tooltipProps,
tooltipId: tooltipId,
error: error,
errorMessage: errorMessage
}, /*#__PURE__*/React.createElement(Field.RadioSet, {
name: "radio",
items: items,
error: error,
variant: variant
}));
};
export var FieldAutocompleteExample = function FieldAutocompleteExample(_ref6) {
var id = _ref6.id,
label = _ref6.label,
tooltip = _ref6.tooltip,
tooltipId = _ref6.tooltipId,
tooltipProps = _ref6.tooltipProps,
placeholder = _ref6.placeholder,
error = _ref6.error,
errorMessage = _ref6.errorMessage,
items = _ref6.items,
size = _ref6.size;
return /*#__PURE__*/React.createElement(FieldBase, {
id: id,
label: label,
tooltip: tooltip,
tooltipProps: tooltipProps,
tooltipId: tooltipId,
error: error,
errorMessage: errorMessage
}, /*#__PURE__*/React.createElement(Field.Autocomplete, {
id: id,
size: size,
name: "field",
placeholder: placeholder,
error: error,
items: items
}));
};
|
pootle/static/js/auth/index.js
|
claudep/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 $ from 'jquery';
import assign from 'object-assign';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { q } from 'utils/dom';
import Auth from './containers/Auth';
const mountNodeSelector = '.js-auth';
const commonProps = {
canContact: PTL.settings.CONTACT_ENABLED,
canRegister: PTL.settings.SIGNUP_ENABLED,
socialAuthProviders: PTL.settings.SOCIAL_AUTH_PROVIDERS,
};
export default {
init(props) {
$(document).on('click', '.js-login', (e) => {
e.preventDefault();
this.open(props);
});
},
open(props) {
const newProps = assign({}, commonProps, props);
ReactDOM.render(
<Provider store={PTL.store}>
<Auth onClose={this.close} {...newProps} />
</Provider>,
q(mountNodeSelector)
);
},
close() {
ReactDOM.unmountComponentAtNode(q(mountNodeSelector));
},
};
|
src/js/components/icons/base/Dashboard.js
|
linde12/grommet
|
// (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-dashboard`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'dashboard');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M12,22 C17.5228475,22 22,17.5228475 22,12 C22,6.4771525 17.5228475,2 12,2 C6.4771525,2 2,6.4771525 2,12 C2,17.5228475 6.4771525,22 12,22 Z M15,16 C15,14.3431458 13.6568542,13 12,13 C10.3431458,13 9,14.3431458 9,16 M5,5 L7,7 M12,7 L12,13 M12,3 L12,5 M19,12 L21,12 M3,12 L5,12 M17,7 L19,5 M3,17 L21,17"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Dashboard';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
src/routes/app/routes/ui/routes/testimonials/components/Testimonials.js
|
ahthamrin/kbri-admin2
|
import React from 'react';
import classnames from 'classnames';
import QueueAnim from 'rc-queue-anim';
const testimonials = [
{
content: 'Lorem ipsum dolor sit amet, consectetur adipisicing elit. Eaque ratione consequuntur ut placeat.',
avatar: 'assets/images-demo/avatars/1.jpg',
name: 'Jason Bourne',
title: 'Senior PM'
}, {
content: 'Cum suscipit voluptatem modi repellat consequuntur aliquid nostrum, dolore pariatur consequatur nobis',
avatar: 'assets/images-demo/avatars/2.jpg',
name: 'Bella Swan',
title: 'VP Product'
}, {
content: 'Temporibus nesciunt quod magnam dicta ea, quae minima tempore eiciendis nisi ab, perferendis',
avatar: 'assets/images-demo/avatars/3.jpg',
name: 'Min Chan',
title: 'Engineer Lead'
}
];
class Section1 extends React.Component {
state = {
testimonials,
};
render() {
return (
<article className="article">
<h2 className="article-title">Basic Testimonials</h2>
<div className="row">
{
this.state.testimonials.map((testimonial, index) => (
<div className="col-xl-4" key={index}>
<div className="testimonial">
<span className="testimonial__quote"><i className="material-icons">format_quote</i></span>
<blockquote>
{testimonial.content}
</blockquote>
<img alt="avatar" className="avatar" src={testimonial.avatar} />
<h5>{testimonial.name}</h5>
<span className="title">{testimonial.title}</span>
</div>
</div>
))
}
</div>
</article>
);
}
}
class Section2 extends React.Component {
state = {
testimonials,
};
render() {
return (
<article className="article">
<h2 className="article-title">Basic Testimonials</h2>
<div className="row">
{
this.state.testimonials.map((testimonial, index) => (
<div className="col-xl-4" key={index}>
<div className="testimonial testimonial-alt">
<span className="testimonial__quote"><i className="material-icons">format_quote</i></span>
<blockquote>
{testimonial.content}
</blockquote>
<img alt="avatar" className="avatar" src={testimonial.avatar} />
<h5>{testimonial.name}</h5>
<span className="title">{testimonial.title}</span>
</div>
</div>
))
}
</div>
</article>
);
}
}
class Section3 extends React.Component {
state = {
testimonials,
};
render() {
return (
<article className="article">
<h2 className="article-title">Basic Testimonials</h2>
<div className="row">
{
this.state.testimonials.map((testimonial, index) => (
<div className="col-xl-4" key={index}>
<div className="box box-default">
<div className="box-body padding-lg-v">
<div className="testimonial testimonial-alt">
<img alt="avatar" className="avatar" src={testimonial.avatar} />
<blockquote>
{testimonial.content}
</blockquote>
<p className="citation">{testimonial.name}, {testimonial.title}</p>
</div>
</div>
</div>
</div>
))
}
</div>
</article>
);
}
}
const Page = () => (
<section className="container-fluid with-maxwidth chapter" >
<QueueAnim type="bottom" className="ui-animate">
<div key="1"><Section1 /></div>
<div key="2"><Section2 /></div>
<div key="3"><Section3 /></div>
</QueueAnim>
</section>
);
module.exports = Page;
|
lms/static/js/student_account/components/spec/PasswordResetConfirmation_spec.js
|
gsehub/edx-platform
|
/* globals setFixtures */
import ReactDOM from 'react-dom';
import React from 'react';
import sinon from 'sinon'; // eslint-disable-line import/no-extraneous-dependencies
import { PasswordResetConfirmation } from '../PasswordResetConfirmation';
describe('PasswordResetConfirmation', () => {
beforeEach(() => {
setFixtures('<div id="wrapper"></div>');
sinon.stub(window, 'fetch');
});
afterEach(() => {
window.fetch.restore();
});
function init(submitError) {
ReactDOM.render(
React.createElement(PasswordResetConfirmation, {
csrfToken: 'csrfToken',
errorMessage: submitError,
}, null),
document.getElementById('wrapper'),
);
}
function triggerValidation() {
$('#new_password1').focus();
$('#new_password1').val('a');
$('#new_password2').focus();
expect(window.fetch.calledWithMatch(
'/api/user/v1/validation/registration',
{ body: JSON.stringify({ password: 'a' }) },
));
}
function prepareValidation(validationError, done) {
window.fetch.reset();
window.fetch.callsFake(() => {
done();
return Promise.resolve({
json: () => ({ validation_decisions: { password: validationError } }),
});
});
}
it('shows submit error', () => {
init('Submit error.');
expect($('.alert-dialog')).toExist();
expect($('.alert-dialog')).not.toBeHidden();
expect($('.alert-dialog')).toHaveText('Submit error.');
});
describe('validation', () => {
beforeEach((done) => {
init('');
prepareValidation('Validation error.', done);
triggerValidation();
});
it('shows validation error', () => {
expect($('#error-new_password1')).toContainText('Validation error.');
});
});
});
|
client/src/pages/software-resources-for-nonprofits.js
|
HKuz/FreeCodeCamp
|
import React from 'react';
import { Grid } from '@freecodecamp/react-bootstrap';
import Helmet from 'react-helmet';
import Layout from '../components/layouts/Default';
import FullWidthRow from '../components/helpers/FullWidthRow';
import { Spacer } from '../components/helpers';
function SoftwareResourcesForNonProfits() {
return (
<Layout>
<Helmet>
<title>Software Resources for Nonprofits | freeCodeCamp.org</title>
</Helmet>
<Spacer />
<Spacer />
<Grid>
<FullWidthRow>
<h2 className='text-center'>Software Resources for Nonprofits</h2>
<hr />
<p>
Please note that freeCodeCamp is not partnered with, nor do we
receive a referral fee from, any of the following providers. We
simply want to help guide you toward a solution for your
organization.
</p>
<h3>Skills-based Volunteer Organizations:</h3>
<ul>
<li>
<a
href='http://givecamp.org/'
rel='noopener noreferrer'
target='_blank'
>
Give Camp
</a>
</li>
<li>
<a
href='http://www.volunteermatch.com'
rel='noopener noreferrer'
target='_blank'
>
Volunteer Match.com
</a>
</li>
<li>
<a
href='http://www.catchafire.org'
rel='noopener noreferrer'
target='_blank'
>
Catchafire
</a>
</li>
<li>
<a
href='http://anyonecanhaveawebsite.com'
rel='noopener noreferrer'
target='_blank'
>
Anyone Can Have A Website
</a>
</li>
</ul>
<h3>Building a website:</h3>
<ul>
<li>
<a
href='https://www.youtube.com/watch?v=4AXDKWuY9QM'
rel='noopener noreferrer'
target='_blank'
>
How to build and deploy a website without writing any code for
free
</a>
</li>
<li>
<a
href='http://www.wix.com/'
rel='noopener noreferrer'
target='_blank'
>
Wix
</a>
</li>
<li>
<a
href='https://www.squarespace.com/'
rel='noopener noreferrer'
target='_blank'
>
Square Space
</a>
</li>
<li>
<a
href='https://wordpress.com/'
rel='noopener noreferrer'
target='_blank'
>
WordPress
</a>
</li>
<li>
<a
href='https://xprs.imcreator.com'
rel='noopener noreferrer'
target='_blank'
>
Imcreator.com
</a>
</li>
</ul>
<h3>Donor and Volunteer Management Systems:</h3>
<ul>
<li>
<a
href='http://causesignal.com'
rel='noopener noreferrer'
target='_blank'
>
Cause Signal
</a>
</li>
<li>
<a
href='https://www.thedatabank.com/'
rel='noopener noreferrer'
target='_blank'
>
The Data Bank
</a>
</li>
<li>
<a
href='http://www.donorsnap.com/'
rel='noopener noreferrer'
target='_blank'
>
Donor Snap
</a>
</li>
<li>
<a
href='http://www.donorperfect.com/'
rel='noopener noreferrer'
target='_blank'
>
Donor Perfect
</a>
</li>
<li>
<a
href={
'https://www.blackbaud.com/fundraising-crm/etapestry-donor' +
'-management'
}
rel='noopener noreferrer'
target='_blank'
>
E Tapestry
</a>
</li>
<li>
<a
href='http://www.z2systems.com'
rel='noopener noreferrer'
target='_blank'
>
Z2 Systems
</a>
</li>
<li>
<a
href='http://www.regpacks.com/volunteer-management'
rel='noopener noreferrer'
target='_blank'
>
Reg Packs
</a>
</li>
<li>
<a
href='http://sumac.com'
rel='noopener noreferrer'
target='_blank'
>
Sumac
</a>
</li>
<li>
<a
href='http://www.volgistics.com'
rel='noopener noreferrer'
target='_blank'
>
Volgistics
</a>
</li>
</ul>
<h3>Inventory Management Systems:</h3>
<ul>
<li>
<a
href='https://www.ordoro.com'
rel='noopener noreferrer'
target='_blank'
>
Ordoro
</a>
</li>
<li>
<a
href='http://www.unleashedsoftware.com'
rel='noopener noreferrer'
target='_blank'
>
Unleashed Software
</a>
</li>
<li>
<a
href='https://www.ezofficeinventory.com/industries/non-profits'
rel='noopener noreferrer'
target='_blank'
>
EZ Office Inventory
</a>
</li>
</ul>
<h3>E-Learning platforms:</h3>
<ul>
<li>
<a
href='http://www.dokeos.com'
rel='noopener noreferrer'
target='_blank'
>
Dokeos
</a>
</li>
<li>
<a
href='http://www.efrontlearning.net/'
rel='noopener noreferrer'
target='_blank'
>
E Front Learning
</a>
</li>
<li>
<a
href='https://moodle.org/'
rel='noopener noreferrer'
target='_blank'
>
Moodle
</a>
</li>
<li>
<a
href='https://sakaiproject.org/'
rel='noopener noreferrer'
target='_blank'
>
Sakai Project
</a>
</li>
</ul>
<h3>Community Management:</h3>
<ul>
<li>
<a
href='https://civicrm.org/'
rel='noopener noreferrer'
target='_blank'
>
CiviCRM
</a>
</li>
<li>
<a
href='http://tcmgr.com/'
rel='noopener noreferrer'
target='_blank'
>
Total Community Manager
</a>
</li>
</ul>
<h3>Electronic Forms:</h3>
<ul>
<li>
<a
href='http://www.google.com/forms'
rel='noopener noreferrer'
target='_blank'
>
Google Forms
</a>
</li>
<li>
<a
href='http://www.typeform.com'
rel='noopener noreferrer'
target='_blank'
>
Typeform
</a>
</li>
</ul>
</FullWidthRow>
</Grid>
</Layout>
);
}
SoftwareResourcesForNonProfits.displayName = 'SoftwareResourcesForNonProfits';
export default SoftwareResourcesForNonProfits;
|
js-old/src/modals/CreateWallet/createWallet.spec.js
|
destenson/ethcore--parity
|
// Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity 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 Parity. If not, see <http://www.gnu.org/licenses/>.
import { shallow } from 'enzyme';
import React from 'react';
import sinon from 'sinon';
import { CreateWallet } from './createWallet';
import { ACCOUNTS } from './createWallet.test.js';
let api;
let component;
let onClose;
function createApi () {
api = {
parity: {
getNewDappsDefaultAddress: sinon.stub().resolves('')
}
};
return api;
}
function render () {
onClose = sinon.stub();
component = shallow(
<CreateWallet
accounts={ ACCOUNTS }
onClose={ onClose }
/>,
{
context: { api: createApi() }
}
);
return component;
}
describe('modals/CreateWallet', () => {
it('renders defaults', () => {
expect(render()).to.be.ok;
});
});
|
app/containers/CarsPage/index.js
|
ddobby94/szakdoge_admin
|
import React from 'react';
import Helmet from 'react-helmet';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { createStructuredSelector } from 'reselect';
import HeaderLink from 'components/Header/HeaderLink';
import { makeSelectLoading, makeSelectError, allCars } from '../App/selectors';
import H2 from 'components/H2';
import DataTable from 'components/DataTable'
import CenteredSection from './CenteredSection';
// import { loadCars } from '../App/actions';
import s from '../Styles'
class CarsPage extends React.PureComponent {
componentDidMount() {
// this.props.loadCars();
}
renderAddCarsButton() {
return(
<CenteredSection >
<Link to='new?new=car' >
<div style={s.submitButton}>ÚJ AUTÓ HOZZÁADÁSA</div>
</Link>
</CenteredSection>
);
}
render() {
const { loading, error, cars, location } = this.props;
console.log('cars,',cars)
if (!loading) {
return (
<div>
<Helmet
title="Home Page"
meta={[
{ name: 'description', content: 'A React.js Boilerplate application homepage' },
]}
/>
<div>
<div style={s.dataTableTitleContainer}>
<h3>AZ AUTÓK ADATAI: </h3>
<p>Az egyes sorokra kattintva lehet megnézni az autók részeletes adatait. </p>
</div>
{cars && <DataTable data={cars} mainHeaderName={'AUTÓK'} location={location} />}
{!cars && <H2>NINCS AUTÓ A RENDSZERBEN!</H2>}
{this.renderAddCarsButton()}
</div>
</div>
);
} else if(!loading && error) {
return (
<div>
<Helmet
title="CARS Page"
meta={[
{ name: 'description', content: 'Útnyílvántartó admin felület' },
]}
/>
<div>
<CenteredSection>
<H2>
{error}
</H2>
</CenteredSection>
</div>
</div>
);
}
return (
<div>
<Helmet
title="Home Page"
meta={[
{ name: 'description', content: 'Útnyílvántartó admin felület' },
]}
/>
<div>
<CenteredSection>
<H2>
LOADING...
</H2>
</CenteredSection>
</div>
</div>
);
}
}
CarsPage.propTypes = {
loading: React.PropTypes.bool,
cars: React.PropTypes.array,
// loadCars: React.PropTypes.func,
};
const mapStateToProps = (state) => createStructuredSelector({
loading: makeSelectLoading(),
error: makeSelectError(),
cars: allCars(),
});
export function mapDispatchToProps(dispatch) {
return {
// loadCars: () => dispatch(loadCars()),
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CarsPage);
|
src/components/Grid/Grid.js
|
RetroGameNight/rgn-ui
|
/*
* Retro Game Night
* Copyright (c) 2015 Sasha Fahrenkopf, Cameron White
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import './Grid.less'
import React from 'react'
import Radium from 'radium'
@Radium
export default class Grid extends React.Component {
styles = {
width: '100%',
display: 'inline-block',
}
render() {
const items = React.Children.map(
this.props.children,
(each) => <GridItem>{each}</GridItem>
)
return (
<div style={[
this.styles,
]}>
{items}
</div>
)
}
}
@Radium
class GridItem extends React.Component {
styles = {
position: 'relative',
float: 'left',
overflow: 'hidden',
}
render() {
return (
<div style={[
this.styles,
]}>
{this.props.children}
</div>
)
}
}
|
frontend/src/components/eois/filters/eoiUnFilter.js
|
unicef/un-partner-portal
|
import R from 'ramda';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { reduxForm } from 'redux-form';
import { connect } from 'react-redux';
import { browserHistory as history, withRouter } from 'react-router';
import { withStyles } from 'material-ui/styles';
import Grid from 'material-ui/Grid';
import Button from 'material-ui/Button';
import CheckboxForm from '../../forms/checkboxForm';
import SelectForm from '../../forms/selectForm';
import TextFieldForm from '../../forms/textFieldForm';
import Agencies from '../../forms/fields/projectFields/agencies';
import CountryField from '../../forms/fields/projectFields/locationField/countryField';
import AdminOneLocation from '../../forms/fields/projectFields/adminOneLocations';
import { selectMappedSpecializations, selectNormalizedCountries, selectNormalizedDirectSelectionSource } from '../../../store';
import resetChanges from './eoiHelper';
const messages = {
choose: 'Choose',
labels: {
search: 'Search',
country: 'Country',
location: 'Location',
sector: 'Sector & Area of Specialization',
agency: 'Agency',
show: 'Show only those chosen for "direct selection/retention"',
},
clear: 'clear',
submit: 'submit',
};
const styleSheet = theme => ({
filterContainer: {
padding: `${theme.spacing.unit * 2}px ${theme.spacing.unit * 3}px`,
background: theme.palette.primary[300],
},
button: {
display: 'flex',
justifyContent: 'flex-end',
},
});
export const STATUS_VAL = [
{
value: true,
label: 'Active',
},
{
value: false,
label: 'Finalized',
},
];
const FORM_NAME = 'unsolicitedFilter';
class EoiFilter extends Component {
constructor(props) {
super(props);
this.state = {
actionOnSubmit: {},
};
this.onSearch = this.onSearch.bind(this);
}
componentWillMount() {
const { pathName, query, agencyId } = this.props;
const agency = this.props.query.agency ? this.props.query.agency : agencyId;
history.push({
pathname: pathName,
query: R.merge(query,
{ agency },
),
});
}
componentWillReceiveProps(nextProps) {
if (R.isEmpty(nextProps.query)) {
const { pathname } = nextProps.location;
const agencyQ = R.is(Number, this.props.query.agency) ? this.props.query.agency : this.props.agencyId;
history.push({
pathname,
query: R.merge(this.props.query,
{ agency: agencyQ },
),
});
}
}
onSearch(values) {
const { pathName, query } = this.props;
const { project_title, agency, active, country_code,
specializations, selected_source, ds_converted } = values;
const agencyQ = R.is(Number, agency) ? agency : this.props.agencyId;
history.push({
pathname: pathName,
query: R.merge(query, {
page: 1,
project_title,
agency: agencyQ,
active,
country_code,
specializations: Array.isArray(specializations) ? specializations.join(',') : specializations,
selected_source,
ds_converted,
}),
});
}
resetForm() {
const query = resetChanges(this.props.pathName, this.props.query);
const { pathName, agencyId } = this.props;
history.push({
pathname: pathName,
query: R.merge(query,
{ agency: agencyId },
),
});
}
render() {
const { classes, countryCode, specs, handleSubmit, reset } = this.props;
return (
<form onSubmit={handleSubmit(this.onSearch)}>
<Grid item xs={12} className={classes.filterContainer} >
<Grid container direction="row" >
<Grid item sm={4} xs={12} >
<TextFieldForm
label={messages.labels.search}
placeholder={messages.labels.search}
fieldName="project_title"
optional
/>
</Grid>
<Grid item sm={4} xs={12}>
<CountryField
initialValue={countryCode}
fieldName="country_code"
label={messages.labels.country}
optional
/>
</Grid>
<Grid item sm={4} xs={12}>
<AdminOneLocation
fieldName="locations"
formName={FORM_NAME}
observeFieldName="country_code"
label={messages.labels.location}
optional
/>
</Grid>
</Grid>
<Grid container direction="row" >
<Grid item sm={4} xs={12} >
<SelectForm
label={messages.labels.sector}
placeholder={messages.labels.choose}
fieldName="specializations"
multiple
values={specs}
sections
optional
/>
</Grid>
<Grid item sm={3} xs={12}>
<Agencies
fieldName="agency"
label={messages.labels.agency}
placeholder={messages.choose}
optional
/>
</Grid>
<Grid item sm={5} xs={12}>
<CheckboxForm
label={messages.labels.show}
fieldName="ds_converted"
optional
/>
</Grid>
</Grid>
<Grid item className={classes.button}>
<Button
color="accent"
onTouchTap={() => { reset(); this.resetForm(); }}
>
{messages.clear}
</Button>
<Button
type="submit"
color="accent"
onTouchTap={handleSubmit(this.onSearch)}
>
{messages.labels.search}
</Button>
</Grid>
</Grid>
</form >
);
}
}
EoiFilter.propTypes = {
/**
* reset function
*/
reset: PropTypes.func.isRequired,
classes: PropTypes.object.isRequired,
specs: PropTypes.array.isRequired,
pathName: PropTypes.string,
agencyId: PropTypes.number,
query: PropTypes.object,
};
const formEoiFilter = reduxForm({
form: FORM_NAME,
destroyOnUnmount: true,
forceUnregisterOnUnmount: true,
enableReinitialize: true,
})(EoiFilter);
const mapStateToProps = (state, ownProps) => {
const { query: { project_title } = {} } = ownProps.location;
const { query: { country_code } = {} } = ownProps.location;
const { query: { agency } = {} } = ownProps.location;
const { query: { specializations } = {} } = ownProps.location;
const { query: { selected_source } = {} } = ownProps.location;
const { query: { ds_converted } = {} } = ownProps.location;
const agencyQ = Number(agency);
const specializationsQ = specializations &&
R.map(Number, specializations.split(','));
return {
countries: selectNormalizedCountries(state),
specs: selectMappedSpecializations(state),
directSources: selectNormalizedDirectSelectionSource(state),
pathName: ownProps.location.pathname,
agencyId: state.session.agencyId,
query: ownProps.location.query,
countryCode: country_code,
initialValues: {
project_title,
country_code,
agency: agencyQ,
specializations: specializationsQ,
selected_source,
ds_converted,
},
};
};
const connected = connect(mapStateToProps, null)(formEoiFilter);
const withRouterEoiFilter = withRouter(connected);
export default (withStyles(styleSheet, { name: 'formEoiFilter' })(withRouterEoiFilter));
|
src/components/services.js
|
barrierandco/barrierandco
|
import React from 'react'
import styled from 'styled-components'
import frontend from '../assets/images/service-frontend.svg'
import management from '../assets/images/service-management.svg'
import uxui from '../assets/images/service-uxui.svg'
const ServicesCard = styled.div`
background: white;
border-radius: ${props => props.theme.borderRadius};
box-shadow: ${props => props.theme.boxShadow};
flex-grow: ${props => props.left || props.right ? '0' : '1'};
margin-bottom: 24px;
order: ${props => props.left || props.right ? '1' : '0'};
overflow: hidden;
position: relative;
@media ${props => props.theme.breakpoint} {
margin: ${props => props.left ? '80px -16px 0 0' : props.right ? '136px 0 0 -16px' : '0 -8px'};
order: 0;
width: 100%;
z-index: ${props => props.left || props.right ? '0' : '10'};
}
img {
display: block;
height: auto;
width: 100%;
}
li {
margin-bottom: 4px;
&:last-of-type {
margin-bottom: 0;
}
}
p {
margin: 0;
@media ${props => props.theme.breakpoint} {
font-size: 0.785rem;
}
}
ul {
margin: 8px 0 0;
@media ${props => props.theme.breakpoint} {
font-size: 0.785rem;
}
}
.inner {
padding: 24px;
@media ${props => props.theme.breakpoint} {
padding: ${props => props.left ? '32px 56px 40px 40px' : props.right ? '32px 40px 40px 56px' : '32px 40px 40px'};
}
}
`
const ServicesContainer = styled.div`
align-items: flex-start;
display: flex;
flex-flow: column nowrap;
margin: 40px 0;
@media ${props => props.theme.breakpoint} {
flex-direction: row;
}
`
const Services = props =>
<ServicesContainer>
<ServicesCard left>
<img src={frontend} alt="an absract illustrated image representing front-end development" />
<div className="inner">
<h3>Web Development</h3>
<p>Bringing your dream to reality requires practical implementation. Having extensive experience with both front‑end and back‑end systems, I'm ready to help your business succeed by providing the following services:</p>
<ul>
<li><strong>HTML, CSS & Javascript</strong></li>
<li><strong>Sinatra & Ruby on Rails</strong></li>
<li><strong>React & Redux</strong></li>
<li><strong>Google's Firebase</strong></li>
</ul>
</div>
</ServicesCard>
<ServicesCard>
<img src={uxui} alt="an absract illustrated image representing user experience and user interface design" />
<div className="inner">
<h3>UX/UI Design</h3>
<p>Creating a solution for your roadblock requires someone like me who can look towards where you want to go while at the same time keeping an eye on where you are currently. This is done specifically through the following design services:</p>
<ul>
<li><strong>Information architecture & wireframes</strong></li>
<li><strong>Interactive prototyping</strong></li>
<li><strong>High fidelity mockups</strong></li>
</ul>
</div>
</ServicesCard>
<ServicesCard right>
<img src={management} alt="an absract illustrated image representing product management" />
<div className="inner">
<h3>Product Management</h3>
<p>Some projects need a leader who is aware of every detail of a project and can take a team from concept to reality. While I am effective at doing everything myself, I'm also capable of reaching out to my network to <strong>form and lead a team through the entire product development process</strong>. Doing so helps you with the larger projects that need more power than a single person contracted even fulltime can provide.</p>
</div>
</ServicesCard>
</ServicesContainer>
export default Services
|
test/WellSpec.js
|
cgvarela/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Well from '../src/Well';
describe('Well', () => {
it('Should output a well with content', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Well>
<strong>Content</strong>
</Well>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
it('Should have a well class', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Well>
Content
</Well>
);
assert.ok(React.findDOMNode(instance).className.match(/\bwell\b/));
});
it('Should accept bsSize arguments', () => {
let instance = ReactTestUtils.renderIntoDocument(
<Well bsSize='small'>
Content
</Well>
);
assert.ok(React.findDOMNode(instance).className.match(/\bwell-sm\b/));
});
});
|
src/svg-icons/action/zoom-in.js
|
ichiohta/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionZoomIn = (props) => (
<SvgIcon {...props}>
<path d="M15.5 14h-.79l-.28-.27C15.41 12.59 16 11.11 16 9.5 16 5.91 13.09 3 9.5 3S3 5.91 3 9.5 5.91 16 9.5 16c1.61 0 3.09-.59 4.23-1.57l.27.28v.79l5 4.99L20.49 19l-4.99-5zm-6 0C7.01 14 5 11.99 5 9.5S7.01 5 9.5 5 14 7.01 14 9.5 11.99 14 9.5 14zm2.5-4h-2v2H9v-2H7V9h2V7h1v2h2v1z"/>
</SvgIcon>
);
ActionZoomIn = pure(ActionZoomIn);
ActionZoomIn.displayName = 'ActionZoomIn';
ActionZoomIn.muiName = 'SvgIcon';
export default ActionZoomIn;
|
Front-End/components/explorercell.component.js
|
brandonrninefive/prIDE
|
import React from 'react';
import ReactDOM from 'react-dom';
import {Cell} from 'fixed-data-table';
class ExplorerCell extends React.Component {
constructor(props){
super(props);
this.state = {
};
this.handleClick = this.handleClick.bind(this);
}
handleClick(){
if(this.props.contents.charAt(this.props.contents.length - 1) == "/")
this.props.appendToPath(this.props.contents);
else
this.props.openFile(this.props.path + this.props.contents);
}
render(){
var iconClass = "";
if(this.props.type == "dir")
{
iconClass = "glyphicon glyphicon-folder-close"
}
else if(this.props.type == "file")
{
iconClass = "glyphicon glyphicon-file";
}
iconClass += " explorerCellIcon"
return(
<Cell>
<a href="#" onClick={this.handleClick}>
<span className={iconClass}></span>
{this.props.contents}
</a>
</Cell>
);
}
}
export default ExplorerCell
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.