path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/Console.js
|
sgnh/react-console-wrapper
|
import React from 'react';
const { array, string, bool, shape } = React.PropTypes;
const Console = (props) => {
if (props.assert.assertion) {
console.assert(props.assert.assertion, props.assert.message);
}
if (props.clear) {
console.clear();
}
if (props.count) {
console.count(props.count);
}
if (props.error) {
console.error(props.error);
}
if (props.group) {
console.group();
}
if (props.groupColapsed) {
console.groupCollapsed();
}
if (props.groupEnd) {
console.groupEnd();
}
if (props.info) {
console.info(props.info);
}
if (props.log) {
console.log(props.log);
}
if (props.table.data.length) {
console.table(props.table.data, props.table.columns);
}
if (props.time) {
console.time(props.time);
}
if (props.timeEnd) {
console.timeEnd(props.timeEnd);
}
if (props.trace) {
console.trace();
}
if (props.warn) {
console.warn(props.warn);
}
return null;
};
Console.propTypes = {
assert: shape({
assertion: bool,
message: string,
}),
clear: bool,
count: string,
error: string,
group: bool,
groupColapsed: bool,
groupEnd: bool,
info: string,
log: string,
table: shape({
data: array,
columns: array,
}),
time: string,
timeEnd: string,
trace: bool,
warn: string,
};
Console.defaultProps = {
assert: {
assertion: false,
message: '',
},
clear: false,
count: '',
error: '',
group: false,
groupColapsed: false,
groupEnd: false,
info: '',
log: '',
table: {
data: [],
columns: [],
},
time: '',
timeEnd: '',
trace: false,
warn: '',
};
export default Console;
|
test/FadeMixinSpec.js
|
thealjey/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import FadeMixin from '../src/FadeMixin';
let Component;
describe('FadeMixin', function () {
beforeEach(function() {
Component = React.createClass({
mixins: [ FadeMixin ],
render() {
return (
<div {...this.props} className='fade'>
<span className='fade'/>
</div>
);
}
});
});
afterEach(()=> {
if (console.warn.calledWithMatch('FadeMixin is deprecated')) {
console.warn.reset();
}
});
it('Should add the in class to all elements', function (done) {
let instance = ReactTestUtils.renderIntoDocument(<Component />);
let child = ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'span');
setTimeout(function() {
assert.ok(React.findDOMNode(instance).className.match(/\bin\b/));
assert.ok(React.findDOMNode(instance).className.match(/\bfade\b/));
assert.ok(React.findDOMNode(child).className.match(/\bin\b/));
assert.ok(React.findDOMNode(child).className.match(/\bfade\b/));
done();
}, 25);
});
it('Should remove the in class for all elements', function (done) {
let instance = ReactTestUtils.renderIntoDocument(<Component />);
setTimeout(function() {
instance.componentWillUnmount();
let element = instance._fadeOutEl.children[0];
let child = element.children[0];
assert.ok(element.className.match(/\bin\b/));
assert.ok(child.className.match(/\bin\b/));
setTimeout(function() {
assert.ok(!element.className.match(/\bin\b/));
assert.ok(element.className.match(/\bfade\b/));
assert.ok(!child.className.match(/\bin\b/));
assert.ok(child.className.match(/\bfade\b/));
done();
}, 25);
}, 25);
});
});
|
src/Parser/Priest/Holy/Modules/Items/Tier21_4set.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Analyzer from 'Parser/Core/Analyzer';
import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing';
import Combatants from 'Parser/Core/Modules/Combatants';
import ItemHealingDone from 'Main/ItemHealingDone';
const HOLY_PRIEST_TIER21_4SET_BUFF_EXPIRATION_BUFFER = 150; // the buff expiration can occur several MS before the heal event is logged, this is the buffer time that an IoL charge may have dropped during which it will still be considered active.
const HEALING_BONUS = 0.3;
class Tier21_4set extends Analyzer {
static dependencies = {
combatants: Combatants,
};
healing = 0;
procUsed = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id);
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
const hasBuff = this.combatants.selected.hasBuff(SPELLS.HOLY_PRIEST_EVERLASTING_HOPE.id, event.timestamp, HOLY_PRIEST_TIER21_4SET_BUFF_EXPIRATION_BUFFER);
if (spellId === SPELLS.PRAYER_OF_HEALING.id && hasBuff) {
this.healing += calculateEffectiveHealing(event, HEALING_BONUS);
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
const hasBuff = this.combatants.selected.hasBuff(SPELLS.HOLY_PRIEST_EVERLASTING_HOPE.id, event.timestamp, HOLY_PRIEST_TIER21_4SET_BUFF_EXPIRATION_BUFFER);
if (spellId === SPELLS.PRAYER_OF_HEALING.id && hasBuff) {
this.procUsed += 1;
}
}
item() {
return {
id: `spell-${SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id}`,
icon: <SpellIcon id={SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id} />,
result: (
<dfn data-tip={`A total of ${this.procUsed} procs were used.`}>
<ItemHealingDone amount={this.healing} />
</dfn>
),
};
}
}
export default Tier21_4set;
|
circleci-demo-javascript-express-master/client/modules/App/components/Footer/Footer.js
|
RTHMaK/RPGOne
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
// Import Style
import styles from './Footer.css';
// Import Images
import bg from '../../header-bk.png';
export function Footer() {
return (
<div style={{ background: `#FFF url(${bg}) center` }} className={styles.footer}>
<p>© 2016 · Hashnode · LinearBytes Inc.</p>
<p><FormattedMessage id="twitterMessage" /> : <a href="https://twitter.com/@mern_io" target="_Blank">@mern_io</a></p>
</div>
);
}
export default Footer;
|
docs/src/sections/NavSection.js
|
jesenko/react-bootstrap
|
import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function NavSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="navs">Navs</Anchor> <small>Nav, NavItem</small>
</h2>
<p>Navs come in two styles, <code>pills</code> and <code>tabs</code>. Disable a tab by adding <code>disabled</code>.</p>
<ReactPlayground codeText={Samples.NavBasic} />
<h3><Anchor id="navs-dropdown">Dropdown</Anchor></h3>
<p>Add dropdowns using the <code>NavDropdown</code> component.</p>
<ReactPlayground codeText={Samples.NavDropdown} />
<h3><Anchor id="navs-stacked">Stacked</Anchor></h3>
<p>They can also be <code>stacked</code> vertically.</p>
<ReactPlayground codeText={Samples.NavStacked} />
<h3><Anchor id="navs-justified">Justified</Anchor></h3>
<p>They can be <code>justified</code> to take the full width of their parent.</p>
<ReactPlayground codeText={Samples.NavJustified} />
<h3><Anchor id="navs-props">Props</Anchor></h3>
<h4><Anchor id="navs-props-nav">Nav</Anchor></h4>
<PropTable component="Nav"/>
<h4><Anchor id="navs-props-navitem">NavItem</Anchor></h4>
<PropTable component="NavItem"/>
</div>
);
}
|
src/client/components/SortSelector/SortSelector.js
|
busyorg/busy
|
import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Popover from '../Popover';
import PopoverMenu, { PopoverMenuItem } from '../PopoverMenu/PopoverMenu';
import './SortSelector.less';
export default class SortSelector extends React.Component {
static Item = PopoverMenuItem;
static propTypes = {
sort: PropTypes.string,
children: PropTypes.node,
onChange: PropTypes.func,
};
static defaultProps = {
sort: null,
children: null,
onChange: () => {},
};
constructor(props) {
super(props);
this.state = {
visible: false,
};
this.handleVisibleChange = this.handleVisibleChange.bind(this);
this.handleSelect = this.handleSelect.bind(this);
}
handleVisibleChange() {
this.setState(prevState => ({ visible: !prevState.visible }));
}
handleSelect(current) {
this.setState(
{
visible: false,
},
() => {
this.props.onChange(current);
},
);
}
render() {
const { sort } = this.props;
const { visible } = this.state;
const currentSort = React.Children.map(this.props.children, c => c).find(
c => c.key === `.$${sort}`,
);
return (
<div className="SortSelector">
<span className="SortSelector__title">
<FormattedMessage id="sort_by" defaultMessage="Sort by" />
</span>
<Popover
trigger="click"
placement="bottom"
visible={visible}
onVisibleChange={this.handleVisibleChange}
content={
<PopoverMenu bold onSelect={this.handleSelect}>
{this.props.children}
</PopoverMenu>
}
>
<span className="SortSelector__current">
{currentSort && currentSort.props && currentSort.props.children}
<i className="iconfont icon-unfold" />
</span>
</Popover>
</div>
);
}
}
|
App/Components/SignUp.js
|
OUCHUNYU/Ralli
|
import usersApi from '../Utils/usersApi'
import GoogleMap from './GoogleMap'
import Firebase from 'firebase'
import React, { Component } from 'react';
import {
StyleSheet,
PropTypes,
View,
TextInput,
Text,
Dimensions,
TouchableHighlight,
Image,
AppRegistry
} from 'react-native';
let styles = StyleSheet.create({
header: {
marginBottom: 20,
fontSize: 18,
textAlign: 'center',
color: 'black'
},
wrapper: {
flex: 1
},
container: {
justifyContent: 'center',
marginTop: 50,
padding: 20,
width: null,
height: null
},
title: {
fontSize: 30,
alignSelf: 'flex-start',
marginBottom: 30,
marginTop: 25,
color: 'white',
backgroundColor: 'rgba(0,0,0,0)'
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 36,
backgroundColor: '#6600ff',
borderColor: '#6600ff',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
input: {
padding: 4,
height: 40,
borderColor: 'white',
borderWidth: 1,
borderRadius: 5,
margin: 5,
marginBottom: 20,
flex: 1,
color: 'white',
alignSelf: 'stretch',
backgroundColor: 'rgba(0,0,0,0.4)'
},
label: {
fontSize: 14,
backgroundColor: 'rgba(0,0,0,0)',
color: 'white'
},
spacer: {
marginVertical: 100,
backgroundColor: 'rgba(0,0,0,0)'
},
headerbar: {
flex: 1,
alignItems: 'center',
flexDirection: 'row'
}
});
class SignUp extends Component {
constructor(props) {
super(props);
this.db = new Firebase('https://ralli.firebaseio.com/users');
this.state = {
username: '',
email: '',
password: ''
};
}
signupOnPress() {
usersApi.createNewUser(this.state.email, this.state.password, this.state.username).then((res) => {
usersApi.loginUser(this.state.email, this.state.password).then((res) => {
this.db.push({
username: this.state.username,
email: this.state.email.toLowerCase(),
avatarUrl: res.password.profileImageURL,
})
usersApi.getUserByEmail(this.state.email.toLowerCase()).then((res) => {
this.props.navigator.push({
title: 'Rallies Nearby',
component: GoogleMap,
passProps: {userData: res.val()[Object.keys(res.val())[0]], userId: Object.keys(res.val())[0]}
})
})
this.setState({
username: '',
email: '',
password: ''
});
})
})
}
render() {
return (
<Image source={require('./Common/bokeh-lights.png')} style={styles.container}>
<View>
<View style={styles.headerbar}>
<Image style={styles.image} source={require('./Common/small-icon.png')} />
<Text style={styles.title}> Create Rally Account</Text>
</View>
<Text style={styles.label}>Username:</Text>
<TextInput
style={styles.input}
value={this.state.username}
onChangeText={(text) => this.setState({username: text})}/>
<Text style={styles.label}>Email:</Text>
<TextInput
style={styles.input}
value={this.state.email}
onChangeText={(text) => this.setState({email: text})}/>
<Text style={styles.label}>Password:</Text>
<TextInput
secureTextEntry={true}
style={styles.input}
value={this.state.password}
onChangeText={(text) => this.setState({password: text})}/>
<TouchableHighlight style={styles.button} onPress={this.signupOnPress.bind(this)} underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Create Account</Text>
</TouchableHighlight>
<Text style={styles.spacer}> </Text>
</View>
</Image>
)
}
}
export default SignUp
|
client/src/components/LoginStatusMessage.js
|
wapjude/labify
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Button, StyleSheet, Text, View } from 'react-native';
import { NavigationActions } from 'react-navigation';
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
const LoginStatusMessage = ({ isLoggedIn, dispatch }) => {
if (!isLoggedIn) {
return <Text>Please log in</Text>;
}
return (
<View>
<Text style={styles.welcome}>
{'You are "logged in" right now'}
</Text>
<Button
onPress={() =>
dispatch(NavigationActions.navigate({ routeName: 'Profile' }))}
title="Profile"
/>
</View>
);
};
LoginStatusMessage.propTypes = {
isLoggedIn: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
isLoggedIn: state.auth.isLoggedIn,
});
export default connect(mapStateToProps)(LoginStatusMessage);
|
blueocean-material-icons/src/js/components/svg-icons/maps/directions-bike.js
|
kzantow/blueocean-plugin
|
import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsDirectionsBike = (props) => (
<SvgIcon {...props}>
<path d="M15.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM5 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5zm5.8-10l2.4-2.4.8.8c1.3 1.3 3 2.1 5.1 2.1V9c-1.5 0-2.7-.6-3.6-1.5l-1.9-1.9c-.5-.4-1-.6-1.6-.6s-1.1.2-1.4.6L7.8 8.4c-.4.4-.6.9-.6 1.4 0 .6.2 1.1.6 1.4L11 14v5h2v-6.2l-2.2-2.3zM19 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5z"/>
</SvgIcon>
);
MapsDirectionsBike.displayName = 'MapsDirectionsBike';
MapsDirectionsBike.muiName = 'SvgIcon';
export default MapsDirectionsBike;
|
app/src/components/Tooltip/Tooltip.js
|
WoundedPixels/us-population
|
// @flow
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import * as d3 from 'd3';
import './Tooltip.css';
class Tooltip extends Component {
static update(content: Object = <empty />) {
const tooltip = d3.select('div#tooltip');
const mouse = { x: d3.event.pageX, y: d3.event.pageY };
const tooltipDimensions = tooltip.node().getBoundingClientRect();
const left = Math.min(
mouse.x + 5,
window.innerWidth - tooltipDimensions.width - 5,
);
tooltip
.style('left', `${left}px`)
.style('top', `${mouse.y - tooltipDimensions.height - 5}px`)
.style('display', content.type !== 'empty' ? 'block' : 'none');
ReactDOM.render(content, document.getElementById('tooltip'));
}
render() {
return (
<div className="Tooltip" id="tooltip" style={{ display: 'none' }}>
{this.props.children}
</div>
);
}
}
export default Tooltip;
|
examples/sidebar/app.js
|
dyzhu12/react-router
|
import React from 'react';
import { history } from 'react-router/lib/HashHistory';
import { Router, Route, Link } from 'react-router';
import data from './data';
var Category = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<h1>{category.name}</h1>
{this.props.children || (
<p>{category.description}</p>
)}
</div>
);
}
});
var CategorySidebar = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<Link to="/">◀︎ Back</Link>
<h2>{category.name} Items</h2>
<ul>
{category.items.map(item => (
<li><Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link></li>
))}
</ul>
</div>
);
}
});
var Item = React.createClass({
render() {
var { category, item } = this.props.params;
var menuItem = data.lookupItem(category, item);
return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
);
}
});
var Index = React.createClass({
render() {
return (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
);
}
});
var IndexSidebar = React.createClass({
render() {
return (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map(category => (
<li><Link to={`/category/${category.name}`}>{category.name}</Link></li>
))}
</ul>
</div>
);
}
});
var App = React.createClass({
render() {
return (
<div>
<div className="Sidebar">
{this.props.sidebar || <IndexSidebar/>}
</div>
<div className="Content">
{this.props.content || <Index/>}
</div>
</div>
);
}
});
React.render((
<Router history={history}>
<Route path="/" component={App}>
<Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}>
<Route path=":item" component={Item}/>
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
packages/@vega/core/src/schema/previews/FootnotePreview/index.js
|
VegaPublish/vega-studio
|
import React from 'react'
import styles from './FootnotePreview.css'
export default function FootnotePreview() {
return <span className={styles.footnoteInline}>*</span>
}
|
client/scripts/routes.js
|
amitava82/radiole
|
/**
* Created by amitava on 30/01/16.
*/
import React from 'react';
import {Route, IndexRoute, IndexRedirect} from 'react-router';
import get from 'lodash/get';
//import {ROUTE_MESSAGES} from './constants';
//import {setLoginMessage} from './redux/modules/session';
import {
HomeContainer
} from './routes/home';
import {
WatchlistContainer
} from './routes/watchlist';
import {
ReportContainer
} from './routes/report';
import {
LoginContainer
} from './routes/login';
import {
SettingsContainer
} from './routes/settings'
import Error from './routes/misc/Error';
import App from './app';
export default (store) => {
function ensureLoggedIn(nextState, replace, cb){
const {session: {isLoggedIn, user}} = store.getState();
if(!isLoggedIn){
replace({pathname: '/login'});
}else if(!user.email && this.path !== '/settings'){
replace({pathname: '/settings'});
}
cb();
}
return (
<Route path="/" component={App}>
<IndexRedirect to="/home"/>
<Route path="/login" component={LoginContainer} />
<Route path="/home" component={HomeContainer} onEnter={ensureLoggedIn} />
<Route path="/watching" component={WatchlistContainer} onEnter={ensureLoggedIn} />
<Route path="/watching/:id" component={ReportContainer} onEnter={ensureLoggedIn} />
<Route path="/settings" component={SettingsContainer} onEnter={ensureLoggedIn} />
<Route path="/error" component={Error} />
</Route>
);
};
|
scripts/apps/authoring/authoring/directives/SendItem.js
|
jerome-poisson/superdesk-client-core
|
import _ from 'lodash';
import React from 'react';
import {PreviewModal} from '../previewModal';
SendItem.$inject = ['$q', 'api', 'desks', 'notify', 'authoringWorkspace',
'superdeskFlags', '$location', 'macros', '$rootScope', 'deployConfig',
'authoring', 'send', 'editorResolver', 'confirm', 'archiveService',
'preferencesService', 'multi', 'datetimeHelper', 'config', 'privileges', 'storage', 'modal', 'gettext', 'urls'];
export function SendItem($q, api, desks, notify, authoringWorkspace,
superdeskFlags, $location, macros, $rootScope, deployConfig,
authoring, send, editorResolver, confirm, archiveService,
preferencesService, multi, datetimeHelper, config, privileges, storage, modal, gettext, urls) {
return {
scope: {
item: '=',
view: '=',
orig: '=',
_beforeSend: '&beforeSend',
_editable: '=editable',
_publish: '&publish',
_action: '=action',
mode: '@',
},
controller: function() {
this.userActions = {
send_to: 'send_to',
publish: 'publish',
duplicate_to: 'duplicate_to',
externalsource_to: 'externalsource_to',
};
},
controllerAs: 'vm',
templateUrl: 'scripts/apps/authoring/views/send-item.html',
link: function sendItemLink(scope, elem, attrs, ctrl) {
scope.mode = scope.mode || 'authoring';
scope.desks = null;
scope.stages = null;
scope.macros = null;
scope.userDesks = null;
scope.allDesks = null;
scope.task = null;
scope.selectedDesk = null;
scope.selectedStage = null;
scope.selectedMacro = null;
scope.beforeSend = scope._beforeSend || $q.when;
scope.destination_last = {send_to: null, publish: null, duplicate_to: null};
scope.origItem = angular.extend({}, scope.item);
scope.subscribersWithPreviewConfigured = [];
// key for the storing last desk/stage in the user preferences for send action.
var PREFERENCE_KEY = 'destination:active';
// key for the storing last user action (send to/publish) in the storage.
var USER_ACTION_KEY = 'send_to_user_action';
scope.$watch('item', activateItem);
scope.$watch(send.getConfig, activateConfig);
scope.publish = function() {
scope.loading = true;
var result = scope._publish();
return $q
.resolve(result)
.then(null, (e) => $q.reject(false))
.finally(() => {
scope.loading = false;
});
};
function activateConfig(config, oldConfig) {
if (scope.mode !== 'authoring' && config !== oldConfig) {
scope.isActive = !!config;
scope.item = scope.isActive ? {} : null;
scope.multiItems = multi.count ? multi.getItems() : null;
scope.config = config;
activate();
}
}
function activateItem(item) {
if (scope.mode === 'monitoring') {
superdeskFlags.flags.fetching = !!item;
}
scope.isActive = !!item;
activate();
}
function activate() {
if (scope.isActive) {
api.query('subscribers')
.then((res) => {
const allSubscribers = res['_items'];
scope.subscribersWithPreviewConfigured = allSubscribers
.map(
(subscriber) => {
subscriber.destinations = subscriber.destinations.filter(
(destination) => typeof destination.preview_endpoint_url === 'string'
&& destination.preview_endpoint_url.length > 0
);
return subscriber;
}
)
.filter((subscriber) => subscriber.destinations.length > 0);
});
desks
.initialize()
.then(fetchDesks)
.then(initialize)
.then(setDesksAndStages);
}
}
scope.preview = function() {
if (scope.$parent.save_enabled() === true) {
modal.alert({
headerText: gettext('Preview'),
bodyText: gettext(
'In order to preview the item, save the changes first.'
),
});
} else {
modal.createCustomModal()
.then(({openModal, closeModal}) => {
openModal(
<PreviewModal
subscribersWithPreviewConfigured={scope.subscribersWithPreviewConfigured}
documentId={scope.item._id}
urls={urls}
closeModal={closeModal}
gettext={gettext}
/>
);
});
}
};
scope.close = function() {
if (scope.mode === 'monitoring') {
superdeskFlags.flags.fetching = false;
}
if (scope.$parent.views) {
scope.$parent.views.send = false;
} else if (scope.item) {
scope.item = null;
}
$location.search('fetch', null);
if (scope.config) {
scope.config.reject();
}
};
scope.selectDesk = function(desk) {
scope.selectedDesk = _.cloneDeep(desk);
scope.selectedStage = null;
fetchStages();
fetchMacros();
};
scope.selectStage = function(stage) {
scope.selectedStage = stage;
};
scope.selectMacro = function(macro) {
if (scope.selectedMacro === macro) {
scope.selectedMacro = null;
} else {
scope.selectedMacro = macro;
}
};
scope.send = function(open) {
updateLastDestination();
return runSend(open);
};
scope.$on('item:nextStage', (_e, data) => {
if (scope.item && scope.item._id === data.itemId) {
var oldStage = scope.selectedStage;
scope.selectedStage = data.stage;
scope.send().then((sent) => {
if (!sent) {
scope.selectedStage = oldStage;
}
});
}
});
// events on which panel should close
var closePanelEvents = ['item:spike', 'broadcast:preview'];
angular.forEach(closePanelEvents, (event) => {
scope.$on(event, shouldClosePanel);
});
/**
* @description Closes the opened 'duplicate/send To' panel if the same item getting
* spiked or any item is opening for authoring.
* @param {Object} event
* @param {Object} data - contains the item(=itemId) that was spiked or {item: null} when
* any item opened for authoring (utilising, 'broadcast:preview' with {item: null})
*/
function shouldClosePanel(event, data) {
if (
(scope.config != null && data != null && _.includes(scope.config.itemIds, data.item))
|| (data == null || data.item == null)
) {
scope.close();
}
}
/*
* Returns true if Destination field and Send button needs to be displayed, false otherwise.
* @returns {Boolean}
*/
scope.showSendButtonAndDestination = function() {
if (scope.itemActions) {
var preCondition = scope.mode === 'ingest' ||
scope.mode === 'personal' ||
scope.mode === 'monitoring' ||
scope.mode === 'authoring' &&
scope.isSendEnabled() &&
scope.itemActions.send ||
scope.mode === 'spike';
if (scope.currentUserAction === ctrl.userActions.publish) {
return preCondition && scope.showSendAndPublish();
}
return preCondition;
}
};
/*
* Returns true if Send and Send and Continue button needs to be disabled, false otherwise.
* @returns {Boolean}
*/
scope.disableSendButton = function() {
return !scope.selectedDesk ||
scope.mode !== 'ingest' && scope.selectedStage && scope.mode !== 'spike' &&
(_.get(scope, 'item.task.stage') === scope.selectedStage._id ||
_.includes(_.map(scope.multiItems, 'task.stage'), scope.selectedStage._id));
};
/*
* Returns true if user is not a member of selected desk, false otherwise.
* @returns {Boolean}
*/
scope.disableFetchAndOpenButton = function() {
if (scope.selectedDesk) {
var _isNonMember = _.isEmpty(_.find(desks.userDesks, {_id: scope.selectedDesk._id}));
return _isNonMember;
}
};
/**
* Returns true if Publish Schedule needs to be displayed, false otherwise.
*/
scope.showPublishSchedule = function() {
return scope.item && archiveService.getType(scope.item) !== 'ingest' &&
scope.item.type !== 'composite' && !scope.item.embargo_date && !scope.item.embargo_time &&
['published', 'killed', 'corrected', 'recalled'].indexOf(scope.item.state) === -1 &&
canPublishOnDesk();
};
/**
* Returns true if timezone needs to be displayed, false otherwise.
*/
scope.showTimezone = function() {
return (scope.item.publish_schedule || scope.item.embargo) &&
(scope.showPublishSchedule() || scope.showEmbargo());
};
/**
* Returns true if Embargo needs to be displayed, false otherwise.
*/
scope.showEmbargo = function() {
// If user doesn't have embargo privilege then don't display embargo fields
if (!privileges.privileges.embargo) {
return false;
}
if (config.ui && config.ui.publishEmbargo === false) {
return false;
}
var prePublishCondition = scope.item && archiveService.getType(scope.item) !== 'ingest' &&
scope.item.type !== 'composite' && !scope.item.publish_schedule_date &&
!scope.item.publish_schedule_time;
if (prePublishCondition && authoring.isPublished(scope.item)) {
if (['published', 'corrected'].indexOf(scope.item.state) >= 0) {
return scope.origItem.embargo;
}
// for published states other than 'published', 'corrected'
return false;
}
return prePublishCondition;
};
/**
* Returns true if Embargo needs to be displayed, false otherwise.
*/
scope.isEmbargoEditable = function() {
var publishedCondition = authoring.isPublished(scope.item) && scope.item.schedule_settings &&
scope.item.schedule_settings.utc_embargo &&
datetimeHelper.greaterThanUTC(scope.item.schedule_settings.utc_embargo);
return scope.item && scope.item._editable &&
(!authoring.isPublished(scope.item) || publishedCondition);
};
/**
* Send the content to different desk/stage
* @param {Boolean} open - True to open the item.
* @return {Object} promise
*/
function runSend(open) {
scope.loading = true;
scope.item.sendTo = true;
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
if (scope.mode === 'authoring') {
return sendAuthoring(deskId, stageId, scope.selectedMacro);
} else if (scope.mode === 'archive') {
return sendContent(deskId, stageId, scope.selectedMacro, open);
} else if (scope.config) {
scope.config.promise.finally(() => {
scope.loading = false;
});
return scope.config.resolve({
desk: deskId,
stage: stageId,
macro: scope.selectedMacro ? scope.selectedMacro.name : null,
open: open,
});
} else if (scope.mode === 'ingest') {
return sendIngest(deskId, stageId, scope.selectedMacro, open);
}
}
/**
* Enable Disable the Send and Publish button.
* Send And Publish is enabled using `superdesk.config.js`.
*/
scope.showSendAndPublish = () => !config.ui || angular.isUndefined(config.ui.sendAndPublish) ||
config.ui.sendAndPublish;
/**
* Check if the Send and Publish is allowed or not.
* Following conditions are to met for Send and Publish action
* - Item is not Published i.e. not state Published, Corrected, Killed or Scheduled
* - Selected destination (desk/stage) should be different from item current location (desk/stage)
* - Mode should be authoring
* - Publish Action is allowed on that item.
* @return {Boolean}
*/
scope.canSendAndPublish = function() {
if (scope.mode !== 'authoring' || !scope.item) {
return false;
}
// Selected destination desk should be different from item current location desk
var isDestinationChanged = scope.selectedDesk && scope.item.task.desk !== scope.selectedDesk._id;
return scope.showSendAndPublish() && !authoring.isPublished(scope.item) &&
isDestinationChanged && scope.mode === 'authoring' && scope.itemActions.publish;
};
/**
* Returns true if 'send' button should be displayed. Otherwise, returns false.
* @return {boolean}
*/
scope.isSendEnabled = () => scope.item && !authoring.isPublished(scope.item);
/*
* Send the current item to different desk or stage and publish the item from new location.
*/
scope.sendAndPublish = function() {
return runSendAndPublish();
};
/*
* Returns true if 'send' action is allowed, otherwise false
* @returns {Boolean}
*/
scope.canSendItem = function() {
var itemType = [], typesList;
if (scope.multiItems) {
angular.forEach(scope.multiItems, (item) => {
itemType[item._type] = 1;
});
typesList = Object.keys(itemType);
itemType = typesList.length === 1 ? typesList[0] : null;
}
return scope.mode === 'authoring' || itemType === 'archive' || scope.mode === 'spike' ||
(scope.mode === 'monitoring' && _.get(scope, 'config.action') === scope.vm.userActions.send_to);
};
/**
* Check if it is allowed to publish on current desk
* @returns {Boolean}
*/
function canPublishOnDesk() {
return !(isAuthoringDesk() && config.features.noPublishOnAuthoringDesk);
}
/**
* If the action is correct and kill then the publish privilege needs to be checked.
*/
scope.canPublishItem = function() {
if (!scope.itemActions || !canPublishOnDesk()) {
return false;
}
if (scope._action === 'edit') {
return scope.item ? !scope.item.flags.marked_for_not_publication && scope.itemActions.publish :
scope.itemActions.publish;
} else if (scope._action === 'correct') {
return privileges.privileges.publish && scope.itemActions.correct;
} else if (scope._action === 'kill') {
return privileges.privileges.publish && scope.itemActions.kill;
}
return false;
};
/**
* Set the User Action.
*/
scope.setUserAction = function(action) {
if (scope.currentUserAction === action) {
return;
}
scope.currentUserAction = action;
storage.setItem(USER_ACTION_KEY, action);
setDesksAndStages();
};
/**
* Checks if a given item is valid to publish
*
* @param {Object} item story to be validated
* @return {Object} promise
*/
const validatePublish = (item) => api.save('validate', {act: 'publish', type: item.type, validate: item});
/**
* Sends and publishes the current item in scope
* First checks if the item is dirty and pops up save dialog if needed
* Then checks if the story is valid to publish before sending
* Then sends the story to the destination
* Then publishes it
*
* @param {Object} item story to be validated
* @return {Object} promise
*/
const runSendAndPublish = () => {
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
// send releases lock, increment version.
return scope.beforeSend({action: 'Send and Publish'})
.then(() => validatePublish(scope.item)
.then((validationResult) => {
if (_.get(validationResult, 'errors.length')) {
for (var i = 0; i < validationResult.errors.length; i++) {
notify.error('\'' + _.trim(validationResult.errors[i]) + '\'');
}
return $q.reject();
}
return sendAuthoring(deskId, stageId, scope.selectedMacro, true)
.then((item) => {
scope.loading = true;
// open the item for locking and publish
return authoring.open(scope.item._id, false);
})
.then((item) => {
// update the original item to avoid 412 error.
scope.orig._etag = scope.item._etag = item._etag;
scope.orig._locked = scope.item._locked = item._locked;
scope.orig.task = scope.item.task = item.task;
// change the desk location.
$rootScope.$broadcast('desk_stage:change');
// if locked then publish
if (item._locked) {
return scope.publish();
}
return $q.reject();
})
.then((result) => {
if (result) {
authoringWorkspace.close(false);
}
})
.catch((error) => {
notify.error(gettext('Failed to send and publish.'));
});
})
.finally(() => {
scope.loading = false;
})
);
};
/**
* Run the macro and returns to the modified item.
* @param {Object} item
* @param {String} macro
* @return {Object} promise
*/
function runMacro(item, macro) {
if (macro) {
return macros.call(macro, item, true).then((res) => angular.extend(item, res));
}
return $q.when(item);
}
/**
* Send to different location from authoring.
* @param {String} deskId - selected desk Id
* @param {String} stageId - selected stage Id
* @param {String} macro - macro to apply
* @return {Object} promise
*/
function sendAuthoring(deskId, stageId, macro) {
var msg;
scope.loading = true;
return runMacro(scope.item, macro)
.then((item) => api.find('tasks', scope.item._id)
.then((task) => {
scope.task = task;
msg = 'Send';
return scope.beforeSend({action: msg});
})
.then((result) => {
if (result && result._etag) {
scope.task._etag = result._etag;
}
return api.save('move', {}, {task: {desk: deskId, stage: stageId}}, scope.item);
})
.then((value) => {
notify.success(gettext('Item sent.'));
if (scope.currentUserAction === ctrl.userActions.send_to) {
// Remember last destination desk and stage for send_to.
var lastDestination = scope.destination_last[scope.currentUserAction];
if (!lastDestination ||
(lastDestination.desk !== deskId || lastDestination.stage !== stageId)) {
updateLastDestination();
}
}
authoringWorkspace.close(true);
return true;
}, (err) => {
if (err) {
if (angular.isDefined(err.data._message)) {
notify.error(err.data._message);
} else if (angular.isDefined(err.data._issues['validator exception'])) {
notify.error(err.data._issues['validator exception']);
}
}
}))
.finally(() => {
scope.loading = false;
});
}
/**
* Update the preferences to store last destinations
* @param {String} key
*/
function updateLastDestination() {
var updates = {};
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
updates[PREFERENCE_KEY] = {desk: deskId, stage: stageId};
preferencesService.update(updates, PREFERENCE_KEY);
}
/**
* Send content to different desk and stage
* @param {String} deskId
* @param {String} stageId
* @param {String} macro
* @param {Boolean} open - If true open the item.
*/
function sendContent(deskId, stageId, macro, open) {
var finalItem;
scope.loading = true;
return api.save('duplicate', {}, {desk: scope.item.task.desk}, scope.item)
.then((item) => api.find('archive', item._id))
.then((item) => runMacro(item, macro))
.then((item) => {
finalItem = item;
return api.find('tasks', item._id);
})
.then((_task) => {
scope.task = _task;
api.save('tasks', scope.task, {
task: _.extend(scope.task.task, {desk: deskId, stage: stageId}),
});
})
.then(() => {
notify.success(gettext('Item sent.'));
scope.close();
if (open) {
$location.url('/authoring/' + finalItem._id);
} else {
$rootScope.$broadcast('item:fetch');
}
})
.finally(() => {
scope.loading = false;
});
}
/**
* Fetch content from ingest to a different desk and stage
* @param {String} deskId
* @param {String} stageId
* @param {String} macro
* @param {Boolean} open - If true open the item.
*/
function sendIngest(deskId, stageId, macro, open) {
scope.loading = true;
return send.oneAs(scope.item, {
desk: deskId,
stage: stageId,
macro: macro ? macro.name : macro,
}).then((finalItem) => {
notify.success(gettext('Item fetched.'));
if (open) {
authoringWorkspace.edit(finalItem);
} else {
$rootScope.$broadcast('item:fetch');
}
})
.finally(() => {
scope.loading = false;
});
}
/**
* Fetch desk and last selected desk and stage for send_to and publish action
* @return {Object} promise
*/
function fetchDesks() {
return desks.initialize()
.then(() => {
// get all desks
scope.allDesks = desks.desks._items;
// get user desks
return desks.fetchCurrentUserDesks();
})
.then((deskList) => {
scope.userDesks = deskList;
return preferencesService.get(PREFERENCE_KEY);
})
.then((result) => {
if (result) {
scope.destination_last.send_to = {
desk: result.desk,
stage: result.stage,
};
scope.destination_last.duplicate_to = {
desk: result.desk,
stage: result.stage,
};
}
});
}
/**
* Set the last selected desk based on the user action.
* To be called after currentUserAction is set
*/
function setDesksAndStages() {
if (!scope.currentUserAction) {
return;
}
// set the desks for desk filter
if (scope.currentUserAction === ctrl.userActions.publish) {
scope.desks = scope.userDesks;
} else {
scope.desks = scope.allDesks;
}
if (scope.mode === 'ingest') {
scope.selectDesk(desks.getCurrentDesk());
} else {
// set the last selected desk or current desk
var itemDesk = desks.getItemDesk(scope.item);
var lastDestination = scope.destination_last[scope.currentUserAction];
if (itemDesk) {
if (lastDestination && !_.isNil(lastDestination.desk)) {
scope.selectDesk(desks.deskLookup[lastDestination.desk]);
} else {
scope.selectDesk(itemDesk);
}
} else if (lastDestination && !_.isNil(lastDestination.desk)) {
scope.selectDesk(desks.deskLookup[lastDestination.desk]);
} else {
scope.selectDesk(desks.getCurrentDesk());
}
}
}
/**
* Set stages and last selected stage.
*/
function fetchStages() {
if (!scope.selectedDesk) {
return;
}
scope.stages = desks.deskStages[scope.selectedDesk._id];
var stage = null;
if (scope.currentUserAction === ctrl.userActions.send_to ||
scope.currentUserAction === ctrl.userActions.duplicate_to) {
var lastDestination = scope.destination_last[scope.currentUserAction];
if (lastDestination) {
stage = _.find(scope.stages, {_id: lastDestination.stage});
} else if (scope.item.task && scope.item.task.stage) {
stage = _.find(scope.stages, {_id: scope.item.task.stage});
}
}
if (!stage) {
stage = _.find(scope.stages, {_id: scope.selectedDesk.incoming_stage});
}
scope.selectedStage = stage;
}
/**
* Fetch macros for the selected desk.
*/
function fetchMacros() {
if (!scope.selectedDesk) {
return;
}
macros.getByDesk(scope.selectedDesk.name)
.then((_macros) => {
scope.macros = _macros;
});
}
/**
* Initialize Item Actios and User Actions.
*/
function initialize() {
initializeItemActions();
initializeUserAction();
}
/**
* Initialize User Action
*/
function initializeUserAction() {
// default user action
scope.currentUserAction = storage.getItem(USER_ACTION_KEY) || ctrl.userActions.send_to;
if (scope.orig || scope.item) {
if (scope.config && scope.config.action === 'externalsourceTo') {
scope.currentUserAction = ctrl.userActions.externalsource_to;
}
// if the last action is send to but item is published open publish tab.
if (scope.config && scope.config.action === 'duplicateTo') {
scope.currentUserAction = ctrl.userActions.duplicate_to;
}
if (scope.currentUserAction === ctrl.userActions.send_to &&
scope.canPublishItem() && !scope.isSendEnabled()) {
scope.currentUserAction = ctrl.userActions.publish;
} else if (scope.currentUserAction === ctrl.userActions.publish &&
!scope.canPublishItem() && scope.showSendButtonAndDestination()) {
scope.currentUserAction = ctrl.userActions.send_to;
} else if (scope.currentUserAction === ctrl.userActions.publish &&
isAuthoringDesk() && noPublishOnAuthoringDesk()) {
scope.currentUserAction = ctrl.userActions.send_to;
}
}
}
/**
* The itemActions defined in parent scope (Authoring Directive) is made accessible via this method.
* scope.$parent isn't used as send-item directive is used in multiple places and has different
* hierarchy.
*/
function initializeItemActions() {
if (scope.orig || scope.item) {
scope.itemActions = authoring.itemActions(scope.orig || scope.item);
}
}
/**
* Test if desk of current item is authoring type.
*
* @return {Boolean}
*/
function isAuthoringDesk() {
if (!_.get(scope, 'item.task.desk')) {
return false;
}
const desk = desks.getItemDesk(scope.item);
return desk && desk.desk_type === 'authoring';
}
/**
* Test if noPublishOnAuthoringDesk config is active.
*
* @return {Boolean}
*/
function noPublishOnAuthoringDesk() {
return config.features.noPublishOnAuthoringDesk;
}
// update actions on item save
scope.$watch('orig._current_version', initializeItemActions);
},
};
}
|
js/src/modals/FirstRun/Welcome/welcome.js
|
nipunn1313/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 React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import imagesEthcore from '~/../assets/images/parity-logo-white.svg';
import styles from '../firstRun.css';
const LOGO_STYLE = {
float: 'right',
maxWidth: '10em',
height: 'auto',
margin: '0 1.5em'
};
export default class FirstRun extends Component {
render () {
return (
<div className={ styles.welcome }>
<img
src={ imagesEthcore }
alt='Parity Ltd.'
style={ LOGO_STYLE }
/>
<p>
<FormattedMessage
id='firstRun.welcome.greeting'
defaultMessage='Welcome to Parity, the fastest and simplest way to run your node.'
/>
</p>
<p>
<FormattedMessage
id='firstRun.welcome.description'
defaultMessage='As part of a new installation, the next few steps will guide you through the process of setting up your Parity instance and your associated accounts. Our aim is to make it as simple as possible and to get you up and running in record-time, so please bear with us. Once completed you will have -'
/>
</p>
<div>
<ul>
<li>
<FormattedMessage
id='firstRun.welcome.step.privacy'
defaultMessage='Understood our privacy policy & terms of operation'
/>
</li>
<li>
<FormattedMessage
id='firstRun.welcome.step.account'
defaultMessage='Created your first Parity account'
/>
</li>
<li>
<FormattedMessage
id='firstRun.welcome.step.recovery'
defaultMessage='Have the ability to recover your account'
/>
</li>
</ul>
</div>
<p>
<FormattedMessage
id='firstRun.welcome.next'
defaultMessage='Click Next to continue your journey.'
/>
</p>
</div>
);
}
}
|
fixtures/dom/src/components/fixtures/input-change-events/index.js
|
leexiaosi/react
|
import React from 'react';
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import RangeKeyboardFixture from './RangeKeyboardFixture';
import RadioClickFixture from './RadioClickFixture';
import RadioGroupFixture from './RadioGroupFixture';
import InputPlaceholderFixture from './InputPlaceholderFixture';
class InputChangeEvents extends React.Component {
render() {
return (
<FixtureSet
title="Input change events"
description="Tests proper behavior of the onChange event for inputs">
<TestCase
title="Range keyboard changes"
description={`
Range inputs should fire onChange events for keyboard events
`}>
<TestCase.Steps>
<li>Focus range input</li>
<li>change value via the keyboard arrow keys</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onKeyDown</code> call count should be equal to
the <code>onChange</code> call count.
</TestCase.ExpectedResult>
<RangeKeyboardFixture />
</TestCase>
<TestCase
title="Radio input clicks"
description={`
Radio inputs should only fire change events when the checked
state changes.
`}
resolvedIn="16.0.0">
<TestCase.Steps>
<li>Click on the Radio input (or label text)</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onChange</code> call count should remain at 0
</TestCase.ExpectedResult>
<RadioClickFixture />
</TestCase>
<TestCase
title="Uncontrolled radio groups"
description={`
Radio inputs should fire change events when the value moved to
another named input
`}
introducedIn="15.6.0">
<TestCase.Steps>
<li>Click on the "Radio 2"</li>
<li>Click back to "Radio 1"</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onChange</code> call count should equal 2
</TestCase.ExpectedResult>
<RadioGroupFixture />
</TestCase>
<TestCase
title="Inputs with placeholders"
description={`
Text inputs with placeholders should not trigger changes
when the placeholder is altered
`}
resolvedIn="15.0.0"
resolvedBy="#5004"
affectedBrowsers="IE9+">
<TestCase.Steps>
<li>Click on the Text input</li>
<li>Click on the "Change placeholder" button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onChange</code> call count should remain at 0
</TestCase.ExpectedResult>
<InputPlaceholderFixture />
</TestCase>
</FixtureSet>
);
}
}
export default InputChangeEvents;
|
src/routes.js
|
ivanflorentin/ProvideUI
|
import {Route} from 'react-router'
import React from 'react'
export default function (modelDef, models) {
const mainPath = modelDef.modelName
const modelProperName = modelDef.modelName[0].toUpperCase() +
modelDef.modelName.substring(1)
const edit = 'edit' + modelProperName
const list = 'list' + modelProperName
const display = 'display' + modelProperName
return (
<Route key={mainPath} path={mainPath}>
<Route path='edit' component={models[edit]}/>
<Route path='list' component={models[list]}/>
<Route path='display' component={models[display]}/>
</Route>
)
}
|
app/desktop/ToolbarButtonPopover/index.js
|
christianalfoni/webpack-bin
|
import React from 'react';
import {Decorator as Cerebral} from 'cerebral-view-react';
import ToolbarButton from '../ToolbarButton';
import classNames from 'classnames';
import styles from './styles.css';
@Cerebral()
class ToolbarButtonPopover extends React.Component {
onArrowBoxClick(e) {
e.stopPropagation();
}
renderPopup() {
const className = classNames(styles.arrowBox, {
[styles.arrowBoxRight]: this.props.right,
[styles.arrowBoxMiddle]: this.props.middle
});
return (
<div className={styles.popup}>
<div
className={className}
onClick={(e) => this.onArrowBoxClick(e)}>
<div className={styles.contentBox}>
{this.props.children}
</div>
</div>
</div>
);
}
render() {
return (
<div className={classNames(styles.wrapper, {[this.props.className]: this.props.className})}>
<ToolbarButton
active={this.props.show}
icon={this.props.icon}
title={this.props.title}
onClick={this.props.onClick}/>
{this.props.show ? this.renderPopup() : null}
</div>
);
}
}
export default ToolbarButtonPopover;
|
client/components/charts/balance-chart.js
|
ZeHiro/kresus
|
import React from 'react';
import Dygraph from 'dygraphs';
import { debug, round2, getChartsDefaultColors, translate as $t } from '../../helpers';
import ChartComponent from './chart-base';
import DiscoveryMessage from '../ui/discovery-message';
function createChartBalance(chartId, account, operations, theme) {
if (account === null) {
debug('ChartComponent: no account');
return;
}
let ops = operations.slice().sort((a, b) => +a.date - +b.date);
function makeKey(date) {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
let opmap = new Map();
// Fill all dates.
const DAY = 1000 * 60 * 60 * 24;
let firstDate = ops.length ? +ops[0].date : Date.now();
firstDate = ((firstDate / DAY) | 0) * DAY;
let today = ((Date.now() / DAY) | 0) * DAY;
for (; firstDate <= today; firstDate += DAY) {
opmap.set(makeKey(new Date(firstDate)), 0);
}
// Date (day) -> cumulated sum of amounts for this day (scalar).
for (let o of ops) {
let key = makeKey(o.date);
if (opmap.has(key)) {
opmap.set(key, opmap.get(key) + o.amount);
}
}
let balance = account.initialBalance;
let csv = 'Date,Balance\n';
for (let [date, amount] of opmap) {
balance += amount;
csv += `${date},${round2(balance)}\n`;
}
/* eslint-disable no-new */
// Create the chart
let chartsColors = getChartsDefaultColors(theme);
return new Dygraph(document.getElementById(chartId), csv, {
color: chartsColors.LINES,
axisLineColor: chartsColors.AXIS,
axes: {
x: {
axisLabelFormatter: date => {
// Undefined means the default locale
let defaultLocale;
return date.toLocaleDateString(defaultLocale, {
year: '2-digit',
month: 'short'
});
}
}
},
fillGraph: true,
showRangeSelector: true,
rangeSelectorPlotFillGradientColor: chartsColors.LINES,
rangeSelectorPlotStrokeColor: chartsColors.LINES,
// 6 months (180 days) window
dateWindow: [today - DAY * 180, today],
// 4px dashes separated by a 2px blank space
gridLinePattern: [4, 2]
});
/* eslint-enable no-new */
}
export default class BalanceChart extends ChartComponent {
redraw() {
this.container = createChartBalance(
'barchart',
this.props.account,
this.props.operations,
this.props.theme
);
}
render() {
return (
<React.Fragment>
<DiscoveryMessage message={$t('client.charts.balance_desc')} />
<div id="barchart" style={{ width: '100%' }} />
</React.Fragment>
);
}
}
|
node_modules/react-bootstrap/es/MediaList.js
|
superKaigon/TheCave
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var MediaList = function (_React$Component) {
_inherits(MediaList, _React$Component);
function MediaList() {
_classCallCheck(this, MediaList);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaList.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('ul', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaList;
}(React.Component);
export default bsClass('media-list', MediaList);
|
Tutorial/AwesomeProject/__tests__/index.ios.js
|
iyooooo/ReactNativeExpress
|
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
src/components/TableMortgage.js
|
nickgreengithub/mortgagecalc
|
import React from 'react';
import { connect } from 'react-redux';
import payments from '../selectors/payments';
import Table from './Table';
export const TableMortgage = (({payments, className})=> {
let output=payments.slice(1)
.filter(year=>year.balance>0 || year.interestYearly>0)
.reduce((acc, year, index) => {
return {
interestTotal:acc.interestTotal+year.interestYearly,
overpaymentTotal:acc.overpaymentTotal+year.overpayment,
rows:acc.rows.concat([
[year.partial?year.partial + "m":index+1,
Math.round(year.interestYearly||0),
Math.round(year.overpayment),
Math.round(year.balance)]])
}
}, {interestTotal:0, overpaymentTotal:0, rows:[]});
return <Table className={className}
headings={["Years", "Interest", "Edited Column", "Balance"]}
rows={output.rows}
totals={[" ",Math.round(output.interestTotal), Math.round(output.overpaymentTotal)," "]} />;
});
export default connect(state=>({ ...payments(state) }))(TableMortgage)
|
src/parser/shaman/elemental/modules/core/FlameShock.js
|
fyruna/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatNumber, formatPercentage } from 'common/format';
import Analyzer from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
class FlameShock extends Analyzer {
static dependencies = {
enemies: Enemies,
};
badLavaBursts = 0;
get uptime() {
return this.enemies.getBuffUptime(SPELLS.FLAME_SHOCK.id) / this.owner.fightDuration;
}
on_byPlayer_cast(event) {
if(event.ability.guid !== SPELLS.LAVA_BURST.id) {
return;
}
const target = this.enemies.getEntity(event);
if(target && !target.hasBuff(SPELLS.FLAME_SHOCK.id)){
this.badLavaBursts++;
}
}
suggestions(when) {
when(this.uptime).isLessThan(0.99)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Your <SpellLink id={SPELLS.FLAME_SHOCK.id} /> uptime can be improved.</span>)
.icon(SPELLS.FLAME_SHOCK.icon)
.actual(`${formatPercentage(actual)}% uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`)
.regular(recommended - 0.05).major(recommended - 0.15);
});
when(this.badLavaBursts).isGreaterThan(0)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Make sure to apply <SpellLink id={SPELLS.FLAME_SHOCK.id} /> to your target, so your <SpellLink id={SPELLS.LAVA_BURST.id} /> is guaranteed to critically strike.</span>)
.icon(SPELLS.LAVA_BURST.icon)
.actual(`${formatNumber(this.badLavaBursts)} Lava Burst casts without Flame Shock DOT`)
.recommended(`0 is recommended`)
.major(recommended+1);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.FLAME_SHOCK.id} />}
value={`${formatPercentage(this.uptime)} %`}
label="Uptime"
tooltip="Flame Shock Uptime"
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
}
export default FlameShock;
|
node_modules/redbox-react/examples/react-transform-catch-errors/index.js
|
edsrupp/eds-mess
|
import React from 'react'
import App from './components/App'
const root = document.getElementById('root')
React.render(<App />, root)
|
react-redux-tutorial/todo-reflux/src/components/todo.js
|
react-scott/react-learn
|
import React from 'react'
import Reflux from 'reflux'
import ReactMixin from 'react-mixin'
import store from '../stores/store'
import actions from '../actions/actions'
export default class Todo extends React.Component{
//组件渲染完成后,通过action获取所有的数组,刷新绑定到this.state上
componentDidMount() {
actions.getAll();
}
add(){
var item =this.refs.item.value;
this.refs.item.value='';
actions.add(item);
}
remove(i){
actions.remove(i);
}
render() {
//items用于乘放li的集合
let items;
if(this.state.list){
items=this.state.list.map( (item,i)=> {
//设置key是因为react的diff算法,是通过key来计算最小变化的
return <li key={i}>
{item.name}
<button onClick={this.remove.bind(this,i)}>remove</button>
</li>
})
}
return (
<div>
<input type="text" ref="item"/>
<button onClick={this.add.bind(this)}>add</button>
<ul>
{items}
</ul>
</div>
)
}
}
// ES6 mixin写法,通过mixin将store的与组件连接,功能是监听store带来的state变化并刷新到this.state
ReactMixin.onClass(Todo, Reflux.connect(store));
|
src/layouts/SidebarredLayout/SidebarredLayout.spec.js
|
KNMI/GeoWeb-FrontEnd
|
import React from 'react';
import SidebarredLayout from './SidebarredLayout';
import { shallow } from 'enzyme';
import { Col } from 'reactstrap';
describe('(Layout) SidebarredLayout', () => {
it('Renders a Reactstrap Container', () => {
const _component = shallow(<SidebarredLayout route={{}} />);
expect(_component.type()).to.eql(Col);
});
});
|
src/features/rekit-tools/TestCoveragePage.js
|
supnate/rekit-portal
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Alert, Button } from 'antd';
import history from '../../common/history';
export class TestCoveragePage extends Component {
static propTypes = {
home: PropTypes.object.isRequired,
};
handleRunTestsClick() {
history.push('/tools/tests');
}
render() {
return (
<div className="rekit-tools-test-coverage-page">
<h2>Test coverage report
{this.props.home.testCoverage && <Button type="ghost" onClick={this.handleRunTestsClick}>Re-run tests</Button>}
</h2>
{this.props.home.testCoverage
? <iframe src="/coverage/lcov-report/index.html" />
:
<div className="no-coverage">
<Alert message="No test coverage report found." showIcon type="info" />
<p>You need to run all tests for the project to generate test coverage reoport.</p>
<p><Button type="primary" onClick={this.handleRunTestsClick}>Run tests</Button></p>
</div>
}
</div>
);
}
}
/* istanbul ignore next */
function mapStateToProps(state) {
return {
home: state.home,
};
}
export default connect(
mapStateToProps,
)(TestCoveragePage);
|
src/utils/createContextWrapper.js
|
gianpaj/react-bootstrap
|
import React from 'react';
/**
* Creates new trigger class that injects context into overlay.
*/
export default function createContextWrapper(Trigger, propName) {
return function(contextTypes) {
class ContextWrapper extends React.Component {
getChildContext() {
return this.props.context;
}
render() {
// Strip injected props from below.
const {wrapped, context, ...props} = this.props;
return React.cloneElement(wrapped, props);
}
}
ContextWrapper.childContextTypes = contextTypes;
class TriggerWithContext {
render() {
const props = {...this.props};
props[propName] = this.getWrappedOverlay();
return (
<Trigger {...props}>
{this.props.children}
</Trigger>
);
}
getWrappedOverlay() {
return (
<ContextWrapper
context={this.context}
wrapped={this.props[propName]}
/>
);
}
}
TriggerWithContext.contextTypes = contextTypes;
return TriggerWithContext;
};
}
|
NavigationReactNativeWeb/sample/twitter/createStateNavigator.js
|
grahammendick/navigation
|
import React from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationStack} from 'navigation-react-native';
export default () => {
const stateNavigator = new StateNavigator([
{key: 'home', route: '{tab?}', defaults: {tab: 'home'}},
{key: 'notifications', route: 'x/y'},
{key: 'tweet', route: 'tweet/{id}', trackCrumbTrail: true, defaultTypes: {id: 'number'}},
{key: 'timeline', route: 'timeline/{id}', trackCrumbTrail: true, defaultTypes: {id: 'number'}}
], NavigationStack.HistoryManager && new NavigationStack.HistoryManager(url => {
const {state, data} = stateNavigator.parseLink(url);
let fluent = stateNavigator.fluent().navigate('home');
if (state.key === 'home' && data.tab === 'notifications')
stateNavigator.historyManager.addHistory(fluent.url, true);
return fluent.navigate(state.key, data).url;
}));
if (Platform.OS === 'web') stateNavigator.start();
return stateNavigator;
}
|
classic/src/scenes/wbfa/generated/FASCheck.pro.js
|
wavebox/waveboxapp
|
import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheck } from '@fortawesome/pro-solid-svg-icons/faCheck'
export default class FASCheck extends React.Component {
render () {
return (<FontAwesomeIcon {...this.props} icon={faCheck} />)
}
}
|
packages/wix-style-react/src/Page/test/examples/SomeContentComponent2.js
|
wix/wix-style-react
|
import React from 'react';
import PropTypes from 'prop-types';
import times from '../../../utils/operators/times';
export const LongTextContent = props => {
const pages = times(props.numOfPages, (x, i) => (
<div key={i}>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam facilisis
molestie magna vitae pellentesque. Ut elementum accumsan nibh, ut
faucibus velit. Vestibulum at mollis justo. Vestibulum ante ipsum primis
in faucibus orci luctus et ultrices posuere cubilia Curae; In sapien
odio, hendrerit a iaculis ut, venenatis in ligula. Vestibulum suscipit
egestas augue, nec mattis est mollis et. Curabitur id eleifend leo.
Fusce tempor efficitur commodo.
<br />
<br />
Cras porta augue non erat imperdiet ornare. Aliquam aliquam elit nec
erat ultricies, ac blandit purus efficitur. Suspendisse sagittis id nibh
eget pulvinar. Phasellus congue ultricies interdum. Mauris vel dolor at
diam feugiat imperdiet feugiat varius eros. Aenean accumsan interdum
massa vitae semper. Maecenas tincidunt ut lectus a fringilla. In
eleifend ante in tellus consequat vestibulum. Fusce lacinia turpis quis
turpis semper venenatis. Donec faucibus felis nisi, non maximus augue
mattis ac. Ut erat sem, finibus vel gravida sed, hendrerit ac nibh.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam et
egestas lectus. Ut vitae est maximus, viverra sem et, pharetra diam.
<br />
<br />
Vivamus quis nunc maximus elit ullamcorper ullamcorper non sit amet
metus. Mauris consequat tortor ac ante vestibulum lacinia. Vestibulum
molestie risus purus, nec faucibus odio iaculis vitae. Integer erat
magna, interdum et venenatis vel, aliquet id nunc. Vivamus nec pharetra
dui. Nam sed quam ultricies, molestie dui a, tempus felis. Pellentesque
tincidunt tortor eu tempus porttitor. Nam vitae dapibus lacus, a gravida
ligula. Vestibulum eget pulvinar mauris. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse
platea dictumst. Sed ultrices bibendum urna, elementum condimentum est
faucibus et. Aenean a hendrerit ipsum. Sed aliquam ligula sed magna
commodo, sit amet fringilla urna scelerisque. Phasellus at felis sed
neque euismod tincidunt vitae id leo.
<br />
<br />
Donec vel felis id mauris iaculis posuere eget eu purus. Duis id libero
dolor. Vivamus nec ornare nunc. Ut efficitur quis sem quis consectetur.
Suspendisse et justo ac sem rhoncus posuere et eget quam. Phasellus sit
amet viverra nulla, vel tincidunt ante. Duis nec commodo lorem.
<br />
<br />
Proin orci nisl, facilisis ut efficitur sit amet, sollicitudin et metus.
Nunc dictum laoreet convallis. Praesent iaculis consequat elit non
consectetur. In risus ex, efficitur non tempor ac, suscipit ut nisi.
Etiam vel vehicula eros. Sed molestie, metus sed tristique fringilla,
tortor metus facilisis justo, sit amet blandit dolor urna eget diam.
Etiam nec lorem cursus nisl finibus venenatis. Ut consequat dui non
pharetra fringilla. Nulla facilisi.
{i < props.numOfPages - 1 && [<br key="br1" />, <br key="br2" />]}
</div>
</div>
));
return <div>{pages}</div>;
};
LongTextContent.defaultProps = {
numOfPages: 5,
};
export default class SomeContentComponent2 extends React.Component {
static propTypes = {
shortContent: PropTypes.bool,
stretchVertically: PropTypes.bool,
};
getBody() {
return;
}
render() {
return (
<div
style={{
backgroundColor: 'white',
minHeight: this.props.stretchVertically ? 'inherit' : undefined,
}}
>
<LongTextContent numOfPages={this.props.shortContent ? 1 : undefined} />
</div>
);
}
}
|
app/scenes/Schedule/components/Talk/index.js
|
brentvatne/react-conf-app
|
// @flow
import React, { Component } from 'react';
import {
Animated,
Easing,
PixelRatio,
StyleSheet,
Text,
TouchableHighlight,
View,
} from 'react-native';
import Icon from '@expo/vector-icons/Ionicons';
import Avatar from '../../../../components/Avatar';
import theme from '../../../../theme';
import { lighten } from '../../../../utils/color';
type Status = 'past' | 'present' | 'future';
// ==============================
// TALK SEPARATOR
// ==============================
export function TalkSeparator({ status }: { status: Status }) {
let barColor = theme.color.gray20;
if (status === 'past') barColor = lighten(theme.color.blue, 60);
else if (status === 'present') barColor = theme.color.blue;
return (
<View
style={{
height: 1 / PixelRatio.get(),
flexDirection: 'row',
alignItems: 'stretch',
}}
underlayColor="white"
>
<View style={{ backgroundColor: barColor, width: 5 }} />
<View
style={{ backgroundColor: 'white', width: theme.fontSize.default }}
/>
<View style={{ backgroundColor: theme.color.gray20, flexGrow: 1 }} />
</View>
);
}
// ==============================
// TALK STATUSBAR
// ==============================
export function TalkStatusBar({ status, ...props }: { status: Status }) {
let barColor = theme.color.gray20;
if (status === 'past') barColor = lighten(theme.color.blue, 60);
if (status === 'present') barColor = theme.color.blue;
return (
<View
style={{
backgroundColor: barColor,
width: 5,
}}
{...props}
/>
);
}
// ==============================
// ICON HELPERS
// ==============================
function Indicator({ color, icon }) {
return (
<View
style={{
alignItems: 'center',
backgroundColor: color,
borderRadius: 14,
marginRight: 7,
height: 14,
justifyContent: 'center',
width: 14,
}}
>
<Icon
color="white"
name={icon}
size={14}
style={{ backgroundColor: 'transparent', marginBottom: -1 }}
/>
</View>
);
}
function LightningSubtitle({ text, ...props }) {
return (
<View style={styles.subtitle} {...props}>
<Indicator color={theme.color.yellow} icon="ios-flash" />
<Text style={styles.subtitleText}>{text}</Text>
</View>
);
}
function KeynoteSubtitle({ text, ...props }) {
return (
<View style={styles.subtitle} {...props}>
<Indicator color={theme.color.blue} icon="ios-key" />
<Text style={styles.subtitleText}>{text}</Text>
</View>
);
}
// ==============================
// TALK ROW
// ==============================
type Props = {
keynote: boolean,
lightning: boolean,
onPress: () => mixed,
speaker: Object,
startTime: string,
status: Status,
title: string,
};
const animationDefault = val => ({
toValue: val,
duration: 666,
easing: Easing.inOut(Easing.quad),
});
export default class Talk extends Component {
props: Props;
animValue: Animated.Value;
static defaultProps = {
status: 'future',
};
constructor(props: Props) {
super(props);
this.animValue = new Animated.Value(0);
}
componentDidMount() {
this.cycleAnimation();
}
cycleAnimation() {
Animated.sequence([
Animated.timing(this.animValue, animationDefault(1)),
Animated.timing(this.animValue, animationDefault(0)),
]).start(() => this.cycleAnimation());
}
render() {
const {
keynote,
lightning,
onPress,
speaker,
startTime,
status,
title,
...props
} = this.props;
const isPresent = status === 'present';
const touchableProps = {
activeOpacity: 1,
onPress: onPress,
style: styles.touchable,
underlayColor: theme.color.gray05,
};
const animatedStyle = {
transform: [
{
translateX: this.animValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 4],
}),
},
],
};
// subtitle variants
let subtitleText = startTime;
if (speaker) subtitleText += ` - ${speaker.name}`;
let subtitle = (
<Text style={[styles.subtitle, styles.subtitleText]}>
{subtitleText}
</Text>
);
if (lightning) subtitle = <LightningSubtitle text={speaker.name} />;
else if (keynote) subtitle = <KeynoteSubtitle text={startTime} />;
// avatar variants
const avatar = Array.isArray(speaker)
? speaker.map((s, i) => {
const pull = i + 1 !== speaker.length
? { backgroundColor: 'transparent', marginRight: -16 }
: null;
return (
<Avatar key={s.name} source={s.avatar} style={pull} size={50} />
);
})
: <Avatar source={speaker && speaker.avatar} />;
// const avatar = <Avatar source={speaker.avatar} />;
return (
<TouchableHighlight {...touchableProps} {...props}>
<View style={[styles.base, styles['base__' + status]]}>
<TalkStatusBar status={status}>
{isPresent &&
<Animated.View style={animatedStyle}>
<Icon
color={theme.color.blue}
name="md-arrow-dropright"
size={34}
style={styles.statusbarIcon}
/>
</Animated.View>}
</TalkStatusBar>
<View style={[styles.content, styles['content__' + status]]}>
<View style={[styles.text, styles['text__' + status]]}>
{subtitle}
<Text style={[styles.title, styles['title__' + status]]}>
{title}
</Text>
</View>
<View style={styles.right}>
{avatar}
<Icon
color={theme.color.gray40}
name="ios-arrow-forward"
size={20}
style={styles.chevron}
/>
</View>
</View>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
touchable: {
backgroundColor: 'white',
},
base: {
alignItems: 'stretch',
backgroundColor: 'transparent',
flexDirection: 'row',
},
// base__present: {
// backgroundColor: fade(theme.color.blue, 3),
// },
statusbarIcon: {
backgroundColor: 'transparent',
height: 34,
left: 0,
position: 'absolute',
top: 10,
width: 34,
},
// content
content: {
alignItems: 'center',
backgroundColor: 'transparent',
flexDirection: 'row',
flexGrow: 1,
flexShrink: 1,
padding: theme.fontSize.default,
},
content__past: {
opacity: 0.5,
},
text: {
flexGrow: 1,
flexShrink: 1,
paddingRight: theme.fontSize.xsmall,
},
subtitle: {
alignItems: 'center',
flexDirection: 'row',
marginBottom: theme.fontSize.small,
},
subtitleText: {
color: theme.color.gray60,
flexShrink: 1,
fontSize: theme.fontSize.small,
fontWeight: '300',
},
title: {
color: theme.color.text,
fontSize: theme.fontSize.default,
},
// right (avatar and chevron)
right: {
alignItems: 'center',
flexDirection: 'row',
flexShrink: 0,
},
// chevron
chevron: {
marginLeft: theme.fontSize.default,
},
});
|
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/InputGroupAddon.js
|
GoogleCloudPlatform/prometheus-engine
|
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';
import InputGroupText from './InputGroupText';
const propTypes = {
tag: tagPropType,
addonType: PropTypes.oneOf(['prepend', 'append']).isRequired,
children: PropTypes.node,
className: PropTypes.string,
cssModule: PropTypes.object,
};
const defaultProps = {
tag: 'div'
};
const InputGroupAddon = (props) => {
const {
className,
cssModule,
tag: Tag,
addonType,
children,
...attributes
} = props;
const classes = mapToCssModules(classNames(
className,
'input-group-' + addonType
), cssModule);
// Convenience to assist with transition
if (typeof children === 'string') {
return (
<Tag {...attributes} className={classes}>
<InputGroupText children={children} />
</Tag>
);
}
return (
<Tag {...attributes} className={classes} children={children} />
);
};
InputGroupAddon.propTypes = propTypes;
InputGroupAddon.defaultProps = defaultProps;
export default InputGroupAddon;
|
components/events/EventsList.js
|
BDE-ESIEE/mobile
|
import React, { Component } from 'react';
import {
Text,
View,
ListView,
ActivityIndicator,
StatusBar,
RefreshControl,
Button,
TouchableOpacity
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import moment from 'moment';
import Icon from 'react-native-vector-icons/Ionicons';
import styles from '../styles/events.js';
import EventCard from './EventCard';
import { ifIphoneX } from 'react-native-iphone-x-helper'
import { Actions } from "react-native-router-flux";
class EventsList extends Component {
constructor (props) {
super(props);
this.state = {
events: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
sectionHeaderHasChanged: (s1, s2) => s1 !== s2
}),
loading: true,
refreshing: false
};
}
componentDidMount () {
this.getEvents();
}
_onRefresh() {
this.setState({refreshing: true});
this.getEvents();
}
render () {
let loadingElement;
let listElement;
if (this.state.loading) {
loadingElement = (
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'center'}}>
<ActivityIndicator color='#f4373b' size='large' />
</View>
);
} else {
listElement = (
<ListView
dataSource={this.state.events}
renderRow={(event, sectionID, rowID) => <EventCard event={event} row={rowID} />}
renderSectionHeader={this.renderHeader}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
tintColor={'#f4373b'}
/>
}
/>
);
}
return (
<View style={styles.container}>
<StatusBar translucent backgroundColor='rgba(0,0,0,0.2)' barStyle='light-content' />
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#f4373b']}
style={{...ifIphoneX({height: 45}, {height: 25})}}
/>
<StatusBar translucent={true} backgroundColor="rgba(0,0,0,0.2)" barStyle="light-content"/>
<View>
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#f4373b']}
style={styles.topBar}>
<TouchableOpacity onPress={() => Actions.pop()}>
<Icon
name='ios-arrow-dropleft-outline'
style={styles.topBarButton}
/>
</TouchableOpacity>
<Text style={styles.topBarText}>
<Text style={styles.topBarNormalText}>Évènements</Text>
</Text>
<TouchableOpacity activeOpacity={1}>
<Icon
name='ios-arrow-dropright-outline'
style={[styles.topBarButton, {
opacity: 0.3
}]}
/>
</TouchableOpacity>
</LinearGradient>
</View>
{loadingElement}
{listElement}
</View>
);
}
renderHeader (sectionData, sectionID) {
if (sectionID === '0') {
return (
<View>
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#f4373b']}
style={styles.weekHeader}>
<Text style={styles.weekHeaderBigNumber}>{sectionData.length}</Text>
<Text style={styles.weekHeaderTextCurWeek}>Évènement{sectionData.length > 1 ? 's' : ''} cette semaine !</Text>
</LinearGradient>
</View>
);
} else {
let weekText = sectionID === '1' ? 'La semaine prochaine' : (`Dans ${sectionID} semaines`);
return (
<View>
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#ff686b']}
style={styles.weekHeaderSmall}>
<Text style={styles.weekHeaderText}>{weekText}</Text>
</LinearGradient>
</View>
);
}
}
getEvents() {
fetch('https://bde.esiee.fr/events.json', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => {
response.json().then((json) => {
let events = json;
let eventsByWeek = {};
events.map((event) => {
let start = moment(event.start);
// let end = moment(event.end);
if (start.isAfter()) {
let weekDiff = start.week() - moment().week();
if (!eventsByWeek[weekDiff]) {
eventsByWeek[weekDiff] = [];
}
eventsByWeek[weekDiff].push(event);
}
});
this.setState({loading: false, events: this.state.events.cloneWithRowsAndSections(eventsByWeek), refreshing: false});
});
});
}
}
module.exports = EventsList;
|
tests/routes/Home/components/HomeView.spec.js
|
anitu/NextFlick
|
import React from 'react'
import { HomeView } from 'routes/Home/components/HomeView'
import { render } from 'enzyme'
describe('(View) Home', () => {
let _component
beforeEach(() => {
_component = render(<HomeView />)
})
it('Renders a welcome message', () => {
const welcome = _component.find('h4')
expect(welcome).to.exist
expect(welcome.text()).to.match(/Welcome!/)
})
it('Renders an awesome duck image', () => {
const duck = _component.find('img')
expect(duck).to.exist
expect(duck.attr('alt')).to.match(/This is a duck, because Redux!/)
})
})
|
src/components/header/header.js
|
awaseem/Jam
|
import React from 'react';
function Header(props) {
return (
<div
style={{
height: props.height || '100vh',
background: `no-repeat center url(${props.image})`,
paddingTop: props.paddingTop || '250px',
paddingBottom: props.paddingBottom || '0px',
backgroundSize: 'cover',
width: '100%',
marginBottom: '50px',
color: props.textColor || '#FFF',
}}
>
{props.children}
</div>
);
}
Header.propTypes = {
children: React.PropTypes.any.isRequired,
image: React.PropTypes.string.isRequired,
paddingTop: React.PropTypes.string,
paddingBottom: React.PropTypes.string,
textColor: React.PropTypes.string,
height: React.PropTypes.string,
};
export default Header;
|
ui/src/components/ColorPicker/index.js
|
LearningLocker/learninglocker
|
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { CirclePicker } from 'react-color';
import { compose, withProps } from 'recompose';
import { Map, List } from 'immutable';
import { MAX_CUSTOM_COLORS } from 'lib/constants/visualise';
import { activeOrgIdSelector } from 'ui/redux/modules/router';
import { VISUALISATION_COLORS } from 'ui/utils/constants';
import { withModel } from 'ui/utils/hocs';
import CustomColorPicker from './CustomColorPicker';
class ColorPicker extends React.PureComponent {
static propTypes = {
color: PropTypes.string,
model: PropTypes.instanceOf(Map), // organisation
onChange: PropTypes.func,
updateModel: PropTypes.func, // update organisation
}
constructor(props) {
super(props);
this.state = { isOpen: false };
}
onClickEdit = () => {
this.setState(prevState => ({ isOpen: !prevState.isOpen }));
}
/**
* @params {tinycolor.Instance} color
*/
onSelectCustomColor = (color) => {
this.setState({ isOpen: false });
this.props.onChange(color);
// Add new selected color to the head of customColors
const newCustomColors = this.getCustomColors()
.unshift(color.hex)
.toSet()
.toList()
.slice(0, MAX_CUSTOM_COLORS);
if (!this.getCustomColors().equals(newCustomColors)) {
this.props.updateModel({
path: ['customColors'],
value: newCustomColors,
});
}
}
/**
* @returns {immutable.List} - List of hex. e.g. List(['#FFFFFF', '#2AFEC9'])
*/
getCustomColors = () => this.props.model.get('customColors', new List());
render = () => {
const {
color,
onChange,
} = this.props;
const customColors = this.getCustomColors();
// The selected color or a color that the organisation recently selected
const trendColor = VISUALISATION_COLORS.includes(color.toUpperCase()) ? customColors.first() : color;
return (
<div style={{ display: 'flex' }}>
<CirclePicker
color={color}
colors={trendColor ? VISUALISATION_COLORS.concat(trendColor) : VISUALISATION_COLORS}
onChange={onChange}
width={'auto'} />
<div>
<div
style={{
paddingLeft: '14px',
width: '28px',
height: '28px',
display: 'flex',
alignItems: 'center',
}}
onClick={this.onClickEdit} >
<i className="icon ion-edit" />
</div>
{
this.state.isOpen && (
<div style={{ position: 'absolute', zIndex: '2' }}>
<div
style={{
position: 'fixed',
top: '0px',
right: '0px',
bottom: '0px',
left: '0px',
}}
onClick={() => this.setState({ isOpen: false })} />
<div style={{ position: 'relative' }}>
<div style={{ position: 'absolute', bottom: '40px', right: '-32px' }}>
<CustomColorPicker
initialColor={color}
customColors={customColors}
onClickCheckMark={this.onSelectCustomColor} />
</div>
</div>
</div>
)
}
</div>
</div>
);
}
}
export default compose(
connect(state => ({
organisationId: activeOrgIdSelector(state)
}), {}),
withProps(({ organisationId }) => ({
id: organisationId,
schema: 'organisation'
})),
withModel,
)(ColorPicker);
|
frontend/webapp/js/Event.js
|
damorton/dropwizardheroku-webgateway
|
import React from 'react';
import axios from 'axios';
class ActionControl extends React.Component {
constructor(props){
super(props);
this.state = {
id : props.id,
url: props.url
};
this.edit = this.edit.bind(this)
this.remove = this.remove.bind(this)
}
edit(){
}
remove(){
const requestUrlWithParam = this.state.url + '/' + this.state.id;
axios.delete(requestUrlWithParam).then(function(res) {
});
}
render(){
return (
<div className='ActionControl'>
<button className='ActionControl-edit' onClick={this.edit}>EDIT</button>
<button className='ActionControl-remove' onClick={this.remove}>X</button>
</div>
)
}
}
class Event extends React.Component {
constructor(props){
super(props);
this.state = {
data : props.data,
key: props.key,
url: props.url
};
}
render(){
return (
<li key={this.state.data.id}>
<div className='EventList-item'>
<h2 className='EventListItem-name'>{this.state.data.name}</h2>
<div>{this.state.data.description}</div>
<div>{this.state.data.location}</div>
<div>{this.state.data.date}</div>
<ActionControl url={this.state.url} id={this.state.data.id}/>
</div>
</li>
)
}
}
export default Event;
|
app/components/loader/index.js
|
ajaymathur/fun-community
|
import React from 'react';
import { View, ActivityIndicator } from 'react-native';
class Loader extends React.Component {
constructor(props) {
super( props );
}
render() {
return (
<View>
{this.props.showLoader ?
<ActivityIndicator
animating={true}
style={{height: 80}}
size="large"
color="#004aff"
/>
: null
}
</View>
)
}
}
Loader.propTypes = {
showLoader: React.PropTypes.bool.isRequired,
};
export default Loader;
|
src/components/Map/index.js
|
opentraffic/analyst-ui
|
import React from 'react'
import PropTypes from 'prop-types'
import { Map as Leaflet, ScaleControl } from 'react-leaflet'
import 'leaflet-editable'
import 'leaflet.path.drag'
import TangramLayer from './TangramLayer'
import 'leaflet/dist/leaflet.css'
import './Map.css'
const ATTRIBUTION = '<a href="https://mapzen.com/">Mapzen</a>, © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>, <a href="https://whosonfirst.mapzen.com#License">Who’s on First</a>'
export default class Map extends React.Component {
static propTypes = {
className: PropTypes.string,
children: PropTypes.any,
center: PropTypes.array,
zoom: PropTypes.number,
onChange: PropTypes.func,
onClick: PropTypes.func,
refSpeedComparisonEnabled: PropTypes.bool,
refSpeedEnabled: PropTypes.bool,
recenterMap: PropTypes.func
}
static defaultProps = {
center: [0, 0],
zoom: 3,
onChange: function () {},
onClick: function () {}
}
componentDidMount () {
// Expose map globally for debug
window.map = this.map.leafletElement
}
// When map is dragged/zoomed and lat/lng/zoom are changed, update URL to reflect change
// Config is now also updated whenever lat/lng/zoom are changed
onChange = (event) => {
const newCenter = event.target.getCenter()
const newZoom = event.target.getZoom()
this.props.recenterMap([newCenter.lat, newCenter.lng], newZoom)
}
render () {
const { className, children, center, refSpeedComparisonEnabled, refSpeedEnabled, zoom, onClick, scene } = this.props
// The `editable` option is not provided by Leaflet but by Leaflet.Editable.
// It is passed to the options object via props.
return (
<Leaflet
className={className}
center={center}
zoom={zoom}
onClick={onClick}
onMoveEnd={this.onChange}
ref={(ref) => { this.map = ref }}
editable
>
<TangramLayer
refSpeedComparisonEnabled={refSpeedComparisonEnabled}
refSpeedEnabled={refSpeedEnabled}
scene={scene}
attribution={ATTRIBUTION} />
<ScaleControl />
{children}
</Leaflet>
)
}
}
|
annotate-gt/src/App.js
|
jkerfs/annotate-gt
|
import React, { Component } from 'react';
import './App.css';
import Opening from './Opening'
import Canvas from './Canvas'
import Finalize from './Finalize'
class App extends Component {
constructor() {
super()
this.state = {
comp: "Opening",
data: {}
}
}
handleStart(state) {
this.setState({comp: "Canvas"})
this.setState({color: state.color})
this.setState({mode: state.mode})
this.setState({files: state.files})
}
handleFinish(o) {
this.setState({data: o})
this.setState({comp: "Finish"})
}
handleRestart() {
this.setState({comp: "Opening"})
}
render() {
var body;
if (this.state.comp === "Canvas") {
console.log("Starting Canvas")
body = <Canvas mode={this.state.mode} color={this.state.color}
files={this.state.files} finish={(txt) => this.handleFinish(txt)}/>
}
else if (this.state.comp === "Finish") {
body = <Finalize restart={() => this.handleRestart()} data={this.state.data}/>
}
else {
body = <Opening onSubmit={(state) => this.handleStart(state)} />
}
return (
<div className="App">
<div className="App-header">
<h2>annotate-gt</h2>
</div>
<div className="ui-holder">
{ body }
</div>
</div>
);
}
}
export default App;
|
src/parser/shaman/elemental/CHANGELOG.js
|
fyruna/WoWAnalyzer
|
import { niseko, HawkCorrigan } from 'CONTRIBUTORS';
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
export default [
{
date: new Date('2019-05-06'),
changes: <>Added support for the damage part of <SpellLink id={SPELLS.IGNEOUS_POTENTIAL.id} />.</>,
contributors: [niseko],
},
{
date: new Date('2019-03-20'),
changes: <>Fixing <SpellLink id={SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.id} />-Tracker and Damage Calculation.</>,
contributors: [HawkCorrigan],
},
{
date: new Date('2018-11-13'),
changes: <>Added a basic Checklist, with the cross-spec functionalities.</>,
contributors: [HawkCorrigan],
},
{
date: new Date('2018-11-04'),
changes: <>Added support for <SpellLink id={SPELLS.PACK_SPIRIT_TRAIT.id} /> and <SpellLink id={SPELLS.SERENE_SPIRIT_TRAIT.id} /> azerite traits.</>,
contributors: [niseko],
},
{
date: new Date('2018-11-01'),
changes: <>Added support for <SpellLink id={SPELLS.ASTRAL_SHIFT.id} /> damage reduction.</>,
contributors: [niseko],
},
{
date: new Date('2018-10-17'),
changes: <>Flagged the Elemental Shaman Analyzer as supported.</>,
contributors: [HawkCorrigan],
},
{
date: new Date('2018-10-15'),
changes: <>Added Checks for the correct usage of <SpellLink id={SPELLS.STORM_ELEMENTAL_TALENT.id} /> and <SpellLink id={SPELLS.FIRE_ELEMENTAL.id} /> when talented into <SpellLink id={SPELLS.PRIMAL_ELEMENTALIST_TALENT.id} />.</>,
contributors: [HawkCorrigan],
},
];
|
packages/mineral-ui-icons/src/IconLocalHotel.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconLocalHotel(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3zm12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4z"/>
</g>
</Icon>
);
}
IconLocalHotel.displayName = 'IconLocalHotel';
IconLocalHotel.category = 'maps';
|
client/src/app/components/forms/inputs/NoUiSlider.js
|
zraees/sms-project
|
import React from 'react'
import noUiSlider from 'nouislider'
export default class NoUiSlider extends React.Component {
componentDidMount() {
const slider = this.refs.slider;
const element = $(slider);
const props = this.props;
element.addClass('noUiSlider');
const options = {
range: {
min: props.rangeMin ? parseInt(props.rangeMin) : 0,
max: props.rangeMax ? parseInt(props.rangeMax) : 1000
},
start: props.start
};
if (props.step) options.step = parseInt(props.step);
// if (props.connect) options.connect = props.connect == 'true' ? true : props.connect;
noUiSlider.create(slider, options);
slider.noUiSlider.on('change', ()=>{
if(props.update){
$(props.update).text(JSON.stringify(element.val()));
}
});
}
render() {
return (
<div ref="slider"/>
)
}
}
|
app/javascript/mastodon/features/ui/components/column_link.js
|
sylph-sin-tyaku/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Icon from 'mastodon/components/icon';
const ColumnLink = ({ icon, text, to, href, method, badge }) => {
const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null;
if (href) {
return (
<a href={href} className='column-link' data-method={method}>
<Icon id={icon} fixedWidth className='column-link__icon' />
{text}
{badgeElement}
</a>
);
} else {
return (
<Link to={to} className='column-link'>
<Icon id={icon} fixedWidth className='column-link__icon' />
{text}
{badgeElement}
</Link>
);
}
};
ColumnLink.propTypes = {
icon: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
to: PropTypes.string,
href: PropTypes.string,
method: PropTypes.string,
badge: PropTypes.node,
};
export default ColumnLink;
|
src/containers/search-bar/SearchBar.js
|
SalvaCarsi/SearchView
|
'use strict';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SearchBarWrapper from '../../components/styled/SearchBarWrapper';
import { HeaderTextWrapper } from '../../components/styled/TextWrapper';
import Button from '../../components/styled/Button';
import InputWrapper from '../../components/styled/InputWrapper';
import * as actionsCreator from './actions';
export class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {searchText: ''};
}
handleChange = (event) => {
this.setState({searchText: event.target.value});
};
handleSubmit = () => {
this.props.actions.searchQuestion(this.state.searchText);
};
render = () => {
return (
<SearchBarWrapper>
<HeaderTextWrapper>
Buscador de preguntas
</HeaderTextWrapper>
<InputWrapper value={this.state.value} onChange={this.handleChange} />
<Button onClick={this.handleSubmit}>Buscar</Button>
</SearchBarWrapper>
);
}
}
// Container
const mapStateToProps = state => ({searchText: state.searchBarReducer.searchText});
const mapDispatchToProps = dispatch => ({actions: bindActionCreators(actionsCreator, dispatch)});
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar);
|
src/components/todoForm.js
|
jonkemp/universal-react-todo-app
|
import React from 'react';
import TodoList from './todoList';
export default React.createClass({
getInitialState() {
return {items: ['One', 'Two', 'Three'], text: ''};
},
onChange(e) {
this.setState({text: e.target.value});
},
handleSubmit(e) {
e.preventDefault();
const nextItems = this.state.items.concat([this.state.text]);
const nextText = '';
this.setState({items: nextItems, text: nextText});
},
render() {
return <div>
<form onSubmit={this.handleSubmit.bind(this)}>
<input onChange={this.onChange.bind(this)} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
<TodoList items={this.state.items} />
</div>;
}
});
|
consoles/my-joy-images/src/app.js
|
yldio/joyent-portal
|
import React from 'react';
import Helmet from 'react-helmet-async';
import { RootContainer } from 'joyent-ui-toolkit';
import Routes from '@root/routes';
export default () => (
<RootContainer>
<Helmet>
<title>Images</title>
</Helmet>
<Routes />
</RootContainer>
);
|
internals/templates/containers/App/index.js
|
plasticanthony/coffee-dates
|
/**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
examples/kitchensink/app-color/components/Root.js
|
Travix-International/frint
|
import React from 'react';
import { observe } from 'frint-react';
import { Observable } from 'rxjs/Observable';
import { concatMap } from 'rxjs/operator/concatMap';
import { map } from 'rxjs/operator/map';
import { merge } from 'rxjs/operator/merge';
import { scan } from 'rxjs/operator/scan';
import PropTypes from 'prop-types';
import {
changeColor
} from '../actions/color';
import {
GREEN_COLOR,
RED_COLOR,
ORANGE_COLOR,
CHANGE_COLOR_ASYNC
} from '../constants';
class Root extends React.Component {
static propTypes = {
color: PropTypes.string,
counter: PropTypes.number,
incrementCounter: PropTypes.func,
decrementCounter: PropTypes.func,
changeColor: PropTypes.func,
changeColorAsync: PropTypes.func,
regionProps: PropTypes.object,
foo: PropTypes.object,
bar: PropTypes.object,
baz: PropTypes.object
};
render() {
const codeStyle = {
color: this.props.color,
backgroundColor: this.props.color
};
return (
<div>
<h5>App: Color</h5>
<p>Color value in <strong>ColorApp</strong>: <code style={codeStyle}>{this.props.color}</code></p>
<div>
<button
className="button"
onClick={() => this.props.changeColor(GREEN_COLOR)}
style={{ backgroundColor: GREEN_COLOR, color: '#fff' }}
>
Green
</button>
<button
className="button"
onClick={() => this.props.changeColor(RED_COLOR)}
style={{ backgroundColor: RED_COLOR, color: '#fff' }}
>
Red
</button>
<button
className="button"
onClick={() => this.props.changeColorAsync(ORANGE_COLOR)}
style={{ backgroundColor: ORANGE_COLOR, color: '#fff' }}
>
Async
</button>
</div>
<p>Counter value from <strong>CounterApp</strong>: <code>{this.props.counter}</code></p>
<p>
<a
href="#"
onClick={() => this.props.incrementCounter()}
>
Increment
</a> counter from here.
</p>
<div>
<p>
<strong>Region Props:</strong>
</p>
<pre><code>{JSON.stringify(this.props.regionProps, null, 2)}</code></pre>
</div>
<div>
<p>
<strong>Services:</strong>
</p>
<ul>
<li><strong>Foo</strong> (cascaded): is from <code>{this.props.foo.getAppName()}</code></li>
<li><strong>Bar</strong> (cascaded and scoped): is from <code>{this.props.bar.getAppName()}</code></li>
<li><strong>Baz</strong> (not cascaded): is unavaialble - <code>{this.props.baz}</code></li>
</ul>
</div>
</div>
);
}
}
export default observe(function (app) { // eslint-disable-line func-names
// self
const store = app.get('store');
const region = app.get('region');
const state$ = store.getState$()
::map((state) => {
return {
color: state.color.value,
};
});
const regionProps$ = region.getProps$()
::map((regionProps) => {
return {
regionProps,
};
});
const actions$ = Observable.of({
changeColor: (...args) => {
return store.dispatch(changeColor(...args));
},
changeColorAsync: (color) => {
return store.dispatch({
type: CHANGE_COLOR_ASYNC,
color,
});
},
});
const services$ = Observable.of({
foo: app.get('foo'),
bar: app.get('bar'),
baz: app.get('baz'),
});
// other app: CounterApp
const counterApp$ = app.getAppOnceAvailable$('CounterApp');
const counterAppState$ = counterApp$
::concatMap((counterApp) => {
return counterApp
.get('store')
.getState$();
})
::map((counterState) => {
return {
counter: counterState.counter.value
};
});
const counterAppActions$ = counterApp$
::map((counterApp) => {
const counterStore = counterApp.get('store');
return {
incrementCounter: () => {
return counterStore.dispatch({ type: 'INCREMENT_COUNTER' });
}
};
});
// combine them all into props
return state$
::merge(regionProps$)
::merge(actions$)
::merge(services$)
::merge(counterAppState$)
::merge(counterAppActions$)
::scan((props, emitted) => {
return {
...props,
...emitted,
};
}, {
// default props to start with
counter: 0,
});
})(Root);
|
src/types/bounds.js
|
uniphil/react-leaflet
|
import React from 'react';
import Leaflet from 'leaflet';
import latlngList from './latlngList';
export default React.PropTypes.oneOfType([
React.PropTypes.instanceOf(Leaflet.LatLngBounds),
latlngList,
]);
|
src/pages/About.js
|
TomClarkson/hanzi-gold-web
|
import React from 'react';
import ReactDisqusThread from 'react-disqus-thread';
export default class About extends React.Component {
render() {
return (
<div id="about-page">
<h1 className='lead-header'>Why was Hanzi Gold built?</h1>
<p className="lead">Hanzi Gold combines two of my passions; lanaguage learning and programming.</p>
<p className="lead" style={{marginBottom: 20}}>It was also built for two reasons. Firstly, to be a practical example of how to build
a production ready React application for the web and mobile, and secondly, to win tickets to attend the React conference.</p>
<p>I want to launch reactjscasts.com soon, and I believe Hanzi Gold is rich with features to make screencasts from.</p>
<p>For example, this application implements the Lietner spaced repetition system, which could be built with tdd in a screencast.</p>
<p>The screencasts will be great for a React developer wanting to make React Native apps
because it will compare different components and navigation paradigms and also how animations and business logic code can be re-used.</p>
<p>The next step for Hanzi Gold is to add a node server, this server will sync learning history between mobile and web.</p>
<p>Finally, I want to add hanzi sounds for comprehension and hanzi writing tests to the quiz and add a real time multiplayer mode to the quiz.</p>
<p className="preview-video">Now, preview what is to come. The video below showcases the app and shows how to build the quiz mode.</p>
</div>
);
}
}
|
src/components/Preferences.js
|
chrisjohndigital/OpenLang
|
import React from 'react'
export class Preferences extends React.Component {
constructor(props) {
super();
this.state = {
value: false
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.props.onPreferences(!this.state.value);
this.setState({
value: !this.state.value
});
}
render() {
return (
<div>
<form>
<label>
Record as simultaneous interpretation:
<input type="checkbox" name="dub" value="on" onChange={this.handleChange} />
</label>
</form>
</div>
)
}
componentDidMount() {
}
}
|
src/projects.js
|
kngroo/Kngr
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import Gfycat from './gfycat';
require('./styles/projects.scss');
export default class Project extends Component {
constructor(props) {
super(props);
this.state = {
id: props.data.id,
title: props.data.title,
description: props.data.description
}
}
/* componentDidMount() {
this.setState({
id:
})
}*/
render() {
var link = '/projects/' + this.state.id;
return(
<li className="project-item">
<Link className="project-link" to={link}>{this.state.title}</Link>
<p>{this.state.description}</p>
</li>
)
}
}
export default class Projects extends Component {
constructor(props) {
super(props);
this.state = {
projects: []
}
}
componentDidMount() {
var projects = [
{
id: 0,
title: 'Gfycat Top 20',
description: 'Angular app for viewing trending gifs on Gfycat'
},
{
id: 1,
title: '360 Video Player',
description: 'Video player made with WebGl for viewing 360 video on the web'
}
];
this.setState({
projects: projects
});
}
render() {
var projects = [];
for (let i = 0; i < this.state.projects.length; i++) {
var project = this.state.projects[i];
projects.push(
<Project data={project}></Project>
)
}
return (
<section className="projects">
<ul className="projects-list">{projects}</ul>
</section>
)
}
}
|
src/bundles/Collaborate/CollaborateCodeWidget.js
|
AusDTO/dto-digitalmarketplace-frontend
|
import React from 'react'
import { Provider } from 'react-redux'
import RegisterComponent from '../../RegisterComponent'
import createStore from './redux/create'
import Code from './components/Code'
export const CollaborateCodeWidget = (props) => {
const store = createStore(props)
return (
<Provider store={store} >
<Code />
</Provider>
)
}
export default new RegisterComponent({ 'collaborate-code': CollaborateCodeWidget })
|
docs/src/app/components/pages/components/Dialog/Page.js
|
pancho111203/material-ui
|
import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import dialogReadmeText from './README';
import DialogExampleSimple from './ExampleSimple';
import dialogExampleSimpleCode from '!raw!./ExampleSimple';
import DialogExampleModal from './ExampleModal';
import dialogExampleModalCode from '!raw!./ExampleModal';
import DialogExampleCustomWidth from './ExampleCustomWidth';
import dialogExampleCustomWidthCode from '!raw!./ExampleCustomWidth';
import DialogExampleDialogDatePicker from './ExampleDialogDatePicker';
import dialogExampleDialogDatePickerCode from '!raw!./ExampleDialogDatePicker';
import DialogExampleScrollable from './ExampleScrollable';
import DialogExampleScrollableCode from '!raw!./ExampleScrollable';
import DialogExampleAlert from './ExampleAlert';
import DialogExampleAlertCode from '!raw!./ExampleAlert';
import dialogCode from '!raw!material-ui/Dialog/Dialog';
const DialogPage = () => (
<div>
<Title render={(previousTitle) => `Dialog - ${previousTitle}`} />
<MarkdownElement text={dialogReadmeText} />
<CodeExample
title="Simple dialog"
code={dialogExampleSimpleCode}
>
<DialogExampleSimple />
</CodeExample>
<CodeExample
title="Modal dialog"
code={dialogExampleModalCode}
>
<DialogExampleModal />
</CodeExample>
<CodeExample
title="Styled dialog"
code={dialogExampleCustomWidthCode}
>
<DialogExampleCustomWidth />
</CodeExample>
<CodeExample
title="Nested dialogs"
code={dialogExampleDialogDatePickerCode}
>
<DialogExampleDialogDatePicker />
</CodeExample>
<CodeExample
title="Scrollable dialog"
code={DialogExampleScrollableCode}
>
<DialogExampleScrollable />
</CodeExample>
<CodeExample
title="Alert dialog"
code={DialogExampleAlertCode}
>
<DialogExampleAlert />
</CodeExample>
<PropTypeDescription code={dialogCode} />
</div>
);
export default DialogPage;
|
scene/AnimSpinScene.js
|
withwind318/RNAppDemos
|
import React, { Component } from 'react';
import {
StyleSheet,
View,
Image,
Dimensions,
Text,
Animated,
Easing,
} from 'react-native';
export default class AnimSpinScene extends Component {
constructor(props) {
super(props);
this.spinValue = new Animated.Value(0);
}
componentDidMount() {
this.spin();
}
spin() {
this.spinValue.setValue(0)
Animated.timing(
this.spinValue,
{
toValue: 1,
duration: 4000,
easing: Easing.linear
}
).start(() => this.spin())
}
render() {
const spin = this.spinValue.interpolate({
inputRange: [0, 1],
outputRange: ['0deg', '360deg']
})
return (
<View style={styles.container}>
<Animated.Image
style={{
width: 227,
height: 200,
transform: [{rotate: spin}] }}
source={{uri: 'https://s3.amazonaws.com/media-p.slid.es/uploads/alexanderfarennikov/images/1198519/reactjs.png'}}
/>
</View>
)
}
}
var styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
});
|
app/src/components/TotalFundAvailable.js
|
open-austin/budgetparty
|
import React from 'react'
import { FormattedNumber } from 'react-intl'
import PropTypes from 'prop-types';
const TotalFundAvailable = (props) => {
const { generalFund, generalFundsRemaining } = props.funds
const remainingAmount = generalFundsRemaining === null ? generalFund : generalFundsRemaining
return (
<div className="TotalFundsAvailable">
<h4 className="TotalFundsAvailable__header">
Total Funds<br/>
Available
</h4>
<h4 className="TotalFundsAvailable__dollars">
<FormattedNumber
value={remainingAmount}
style="currency" //eslint-disable-line
currency="USD"
minimumFractionDigits={0}
maximumFractionDigits={0}
/>
</h4>
</div>
)
}
export default TotalFundAvailable
TotalFundAvailable.propTypes = {
funds: PropTypes.shape({
generalFund: PropTypes.number,
generalFundsRemaining: PropTypes.number,
}).isRequired,
};
|
src/components/core/StrikethroughDivider/index.js
|
ClaudiuCeia/mioritic
|
// @flow
import React, { Component } from 'react';
import './StrikethroughDivider.css';
type Props = {
title: string,
subtitle: string,
}
class StrikethroughDivider extends Component {
props: Props;
render() {
return (
<div className="strikethrough-divider">
<div className="strikethrough-divider-middle">
<h2>
{this.props.title}
</h2>
<span>
{this.props.subtitle}
</span>
</div>
</div>
);
}
}
export default StrikethroughDivider;
|
assets/js/routes/app-routes.react.js
|
Nosferatu-lib/nosferatu-reactjs-auth
|
import React from 'react';
import Router from 'react-router';
import Master from '../layouts/master.react';
import Home from '../layouts/home.react';
var {Route, DefaultRoute} = Router;
var AppRoutes = (
<Route name="root" path="/" handler={Master}>
<DefaultRoute handler={Home} />
</Route>
);
export default AppRoutes;
|
sandbox/graphqlVersion/client/components/ecTranslatorHeader.js
|
guigrpa/mady
|
// @flow
/* eslint-env browser */
import timm from 'timm';
import React from 'react';
import Relay, { graphql } from 'react-relay';
import throttle from 'lodash/throttle';
import { getScrollbarWidth, flexItem, flexContainer, Icon, Select } from 'giu';
import type { Choice } from 'giu/lib/gral/types';
import type { ViewerT, StatsT } from '../../common/types';
import _t from '../../translate';
import parseSrcFiles from '../mutations/parseSrcFiles';
import { COLORS } from '../gral/constants';
import { styleKeyCol, styleLangCol } from './adTranslatorStyles';
import { mutate } from './helpers';
// ==========================================
// Component declarations
// ==========================================
type Props = {
// lang: string, // just for refresh
langs: Array<string>,
availableLangs: Array<string>,
onAddLang: () => any,
onRemoveLang: (ev: SyntheticEvent) => any,
onChangeLang: (ev: SyntheticEvent, lang: string) => any,
// Relay
relay: Object,
viewer: ViewerT,
stats: StatsT,
};
const fragment = graphql`
fragment ecTranslatorHeader_stats on Stats {
numTotalKeys
numUsedKeys
numTranslations {
lang
value
}
}
`;
// ==========================================
// Component
// ==========================================
class TranslatorHeader extends React.PureComponent {
props: Props;
state: {
fParsing: boolean,
};
forceRender: () => void;
stats: {
numTotalKeys: number,
numUsedKeys: number,
numTranslations: { [key: string]: number },
};
constructor(props: Props) {
super(props);
this.state = {
fParsing: false,
};
this.forceRender = throttle(this.forceRender.bind(this), 200);
}
componentDidMount() {
window.addEventListener('resize', this.forceRender);
}
componentWillUnmount() {
window.removeEventListener('resize', this.forceRender);
}
forceRender() {
this.forceUpdate();
}
// ------------------------------------------
// Render
// ------------------------------------------
render() {
const langOptions = this.props.availableLangs.map(lang => ({
value: lang,
label: lang,
}));
const { stats } = this.props;
return (
<div
className="tableHeaderRow"
style={timm.merge(style.row, style.headerRow)}
>
<div style={timm.merge(style.headerCell, style.keyCol)}>
{_t('columnTitle_Messages').toUpperCase()}{' '}
<span style={style.numItems}>
[
<span title={_t('tooltip_Used messages')}>{stats.numUsedKeys}</span>
{' / '}
<span title={_t('tooltip_Total messages')}>
{stats.numTotalKeys}
</span>
]
</span>{' '}
<Icon
icon="refresh"
title={_t('tooltip_Parse source files to update the message list')}
onClick={this.onParseSrcFiles}
spin={this.state.fParsing}
/>
</div>
{this.props.langs.map((lang, idx) =>
this.renderLangHeader(lang, idx, langOptions)
)}
{this.renderAdd()}
<div style={style.scrollbarSpacer()} />
</div>
);
}
renderLangHeader(lang: string, idx: number, langOptions: Array<Choice>) {
const { stats } = this.props;
const langStats = stats.numTranslations.find(o => o.lang === lang);
return (
<div
key={lang}
className="madyLangHeader"
style={timm.merge(style.headerCell, style.langCol)}
>
<div
title={_t('tooltip_Change language')}
style={style.langSelectorOuter}
>
<Icon icon="caret-down" style={style.langSelectorCaret} />
{lang}
<Select
id={idx}
value={lang}
onChange={this.props.onChangeLang}
required
items={langOptions}
style={style.langSelector}
/>
</div>{' '}
<span style={style.numItems}>
[
<span title={_t('tooltip_Translations')}>
{langStats ? langStats.value : 0}
</span>
{' / '}
<span title={_t('tooltip_Used messages')}>{stats.numUsedKeys}</span>]
</span>{' '}
<Icon
id={idx}
icon="remove"
title={_t('tooltip_Remove column (does NOT delete any translations)')}
onClick={this.props.onRemoveLang}
/>
</div>
);
}
renderAdd() {
const fDisabled =
this.props.langs.length === this.props.availableLangs.length;
return (
<div
id="madyBtnAddLang"
onClick={fDisabled ? undefined : this.props.onAddLang}
title={_t('tooltip_Add column')}
style={style.addLang(fDisabled)}
>
<Icon icon="plus" disabled={fDisabled} />
</div>
);
}
// ------------------------------------------
onParseSrcFiles = () => {
this.setState({ fParsing: true });
mutate({
description: 'Click on Parse source files',
environment: this.props.relay.environment,
mutationOptions: parseSrcFiles(),
onFinish: () => this.setState({ fParsing: false }),
});
};
// ------------------------------------------
calcStats() {
let numUsedKeys = 0;
let numTotalKeys = 0;
const numTranslations = {};
const keyEdges = this.props.viewer.keys.edges;
for (let i = 0; i < keyEdges.length; i++) {
const key = keyEdges[i].node;
if (key.isDeleted) continue;
numTotalKeys += 1;
if (key.unusedSince) continue;
numUsedKeys += 1;
const translationEdges = key.translations.edges;
for (let k = 0; k < translationEdges.length; k++) {
const translation = translationEdges[k].node;
if (translation.isDeleted) continue;
const { lang } = translation;
if (numTranslations[lang] == null) numTranslations[lang] = 0;
numTranslations[lang] += 1;
}
}
this.stats = { numTotalKeys, numUsedKeys, numTranslations };
}
}
// ------------------------------------------
// Styles
// ------------------------------------------
const style = {
row: flexItem('none', flexContainer('row')),
headerRow: {
position: 'relative',
fontWeight: 'bold',
},
headerCell: {
paddingTop: 3,
paddingBottom: 3,
borderBottom: `1px solid ${COLORS.darkest}`,
textAlign: 'center',
fontWeight: 900,
letterSpacing: 3,
},
numItems: { color: 'darkgrey' },
keyCol: styleKeyCol,
langCol: styleLangCol,
langSelectorOuter: {
position: 'relative',
display: 'inline-block',
paddingRight: 5,
},
langSelectorCaret: { marginRight: 5 },
langSelector: {
position: 'absolute',
top: 0,
left: 0,
width: '100%',
opacity: 0,
cursor: 'pointer',
},
addLang: fDisabled => {
const scrollbarWidth = getScrollbarWidth();
return {
position: 'absolute',
top: 0,
right: 5 + scrollbarWidth,
cursor: fDisabled ? undefined : 'pointer',
padding: '3px 6px',
fontWeight: 900,
letterSpacing: 3,
};
},
scrollbarSpacer: () => flexItem(`0 0 ${getScrollbarWidth()}px`),
};
// ==========================================
// Public API
// ==========================================
const Container = Relay.createFragmentContainer(TranslatorHeader, fragment);
export default Container;
export { TranslatorHeader as _TranslatorHeader };
|
web/client/configdev/src/config/LogFile.js
|
project-owner/Peppy
|
/* Copyright 2021 Peppy Player peppy.player@gmail.com
This file is part of Peppy Player.
Peppy Player 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.
Peppy Player 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 Peppy Player. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { FormControl, Button } from '@material-ui/core';
import Factory from "../Factory";
import RefreshIcon from '@material-ui/icons/Refresh';
export default class LogFile extends React.Component {
render() {
const { log, classes, labels, getLog } = this.props;
let logData = log || "";
let data = { "log": logData };
return (
<FormControl>
<main className={classes.content}>
<div style={{ display: "flex", flexDirection: "column" }} autoComplete="off"
autoCorrect="off" autoCapitalize="off" spellCheck="false">
<div style={{ marginLeft: "auto" }}>
<Button variant="contained" className={classes.addButton} onClick={() => { getLog(true) }}>
{labels.refresh}
<RefreshIcon style={{ marginLeft: "1rem" }} />
</Button>
</div>
{Factory.createResizableTextArea("log", data, { width: "50rem" })}
</div>
</main>
</FormControl>
);
}
}
|
modules/TransitionHook.js
|
leeric92/react-router
|
import React from 'react';
import warning from 'warning';
var { object } = React.PropTypes;
var TransitionHook = {
contextTypes: {
router: object.isRequired
},
componentDidMount() {
warning(
typeof this.routerWillLeave === 'function',
'Components that mixin TransitionHook should have a routerWillLeave method, check %s',
this.constructor.displayName || this.constructor.name
);
if (this.routerWillLeave)
this.context.router.addTransitionHook(this.routerWillLeave);
},
componentWillUnmount() {
if (this.routerWillLeave)
this.context.router.removeTransitionHook(this.routerWillLeave);
}
};
export default TransitionHook;
|
examples/example-with-styleguidist/src/components/Button/Button.js
|
risetechnologies/fela
|
import React from 'react'
import PropTypes from 'prop-types'
import { createComponent } from 'react-fela'
// declare fela styles
const __buttonStyle = props => ({
padding: '.5em 1.5em',
color: `${props.color || props.theme.colorGrey}`,
'background-color': props.theme.colorWhite,
border: '1px solid currentColor',
'border-radius': props.theme.borderRadius,
'text-align': 'center',
'vertical-align': 'middle',
cursor: 'pointer',
fontSize: `${props.theme.buttonSizes[props.size] ||
props.theme.buttonSizes['normal']}`,
})
const ButtonComponent = createComponent(__buttonStyle, 'button', [
'color',
'size',
'onClick',
])
/**
* The only true button.
* Note: This component uses react-fela createComponent api to render styles for demo.
*/
export default function Button(props) {
const { children, ...passDownProps } = props
return <ButtonComponent {...passDownProps}>{children}</ButtonComponent>
}
Button.propTypes = {
/** Button label */
children: PropTypes.oneOfType([
PropTypes.string.isRequired,
PropTypes.number.isRequired,
]),
/** The color for the button */
color: PropTypes.string,
/** The size of the button */
size: PropTypes.oneOf(['small', 'normal', 'large']),
/** Gets called when the user clicks on the button */
onClick: PropTypes.func,
}
Button.defaultProps = {
color: '#333',
size: 'normal',
/* eslint-disable no-console */
onClick: event => {
console.log('You have clicked me!', event.target)
},
/* eslint-enable no-console */
}
|
actor-apps/app-web/src/app/components/activity/UserProfileContactInfo.react.js
|
tsdl2013/actor-platform
|
import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
const {addons: { PureRenderMixin }} = addons;
@ReactMixin.decorate(PureRenderMixin)
class UserProfileContactInfo extends React.Component {
static propTypes = {
phones: React.PropTypes.array
};
constructor(props) {
super(props);
}
render() {
let phones = this.props.phones;
let contactPhones = _.map(phones, (phone, i) => {
return (
<li className="profile__list__item row" key={i}>
<i className="material-icons">call</i>
<div className="col-xs">
<span className="contact">+{phone.number}</span>
<span className="title">{phone.title}</span>
</div>
</li>
);
});
return (
<ul className="profile__list profile__list--contacts">
{contactPhones}
</ul>
);
}
}
export default UserProfileContactInfo;
|
src/entry-points/client.js
|
StevenLangbroek/react-redux-starter-kit
|
import React from 'react';
import App from 'containers/app';
import { history } from 'react-router/lib/BrowserHistory';
React.render(<App history={history} />, document.getElementById('mount'));
|
examples/huge-apps/routes/Calendar/components/Calendar.js
|
calebmichaelsanchez/react-router
|
import React from 'react';
class Calendar extends React.Component {
render () {
var events = [{
id: 0, title: 'essay due'
}];
return (
<div>
<h2>Calendar</h2>
<ul>
{events.map(event => (
<li key={event.id}>{event.title}</li>
))}
</ul>
</div>
);
}
}
export default Calendar;
|
src/web/Line/Line.js
|
Krizzu/react-progressor
|
import React from 'react';
import propTypes from 'prop-types';
import { Container, Track, CompletedTrack } from './helpers/subComponents';
class LineProgressor extends React.Component {
valueInterpolate = (val) => {
const { width = 150 } = this.props;
return ((val / 100) * width);
}
render() {
const {
width,
height,
progress,
trackColor,
progressColor,
transitionFunc,
transitionDuration,
} = this.props;
// Calculate a width of progress based on passed 'progress' prop
const interpolatedProgress = this.valueInterpolate(progress);
// if this calculated width is bigger than width passed, do not exceed it
const currentProgress = this.valueInterpolate(progress) > width ? width : interpolatedProgress;
return (
<Container
style={{ width, height }}
>
<Track
style={{ width, height, backgroundColor: trackColor }}
/>
<CompletedTrack
func={transitionFunc}
time={transitionDuration}
style={{ height, width: currentProgress, backgroundColor: progressColor }}
/>
</Container>
);
}
}
// Default values for props
LineProgressor.defaultProps = {
width: 150,
height: 5,
progress: 0,
trackColor: '#eee',
progressColor: '#8DE969',
transitionFunc: 'linear',
transitionDuration: 200,
};
// Prop type checking
LineProgressor.propTypes = {
width: propTypes.number.isRequired,
height: propTypes.number,
progress: propTypes.number.isRequired,
trackColor: propTypes.string,
progressColor: propTypes.string,
transitionFunc: propTypes.string,
transitionDuration: propTypes.number,
};
export default LineProgressor;
|
app/jsx/bundles/terms_of_service_modal.js
|
djbender/canvas-lms
|
/*
* Copyright (C) 2017 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import ready from '@instructure/ready'
import React from 'react'
import ReactDOM from 'react-dom'
import TermsOfServiceModal from '../shared/TermsOfServiceModal'
ready(() => {
let container = document.querySelector('#terms_of_service_preview_link')
if (container) {
ReactDOM.render(<TermsOfServiceModal preview />, container)
} else {
container = document.querySelectorAll('.terms_of_service_link')
if (container.length) {
for (let i = 0; i < container.length; i++) {
ReactDOM.render(<TermsOfServiceModal />, container[i])
}
}
}
})
|
assets/javascripts/kitten/components/graphics/icons/burger-icon/index.js
|
KissKissBankBank/kitten
|
import React from 'react'
import classNames from 'classnames'
import PropTypes from 'prop-types'
import styled from 'styled-components'
import COLORS from '../../../../constants/colors-config'
import deprecated from 'prop-types-extra/lib/deprecated'
const StyledItem = styled.svg`
overflow: visible;
fill: var(--burgerIcon-mainColor, ${COLORS.font1});
:hover,
button:hover & {
fill: var(--burgerIcon-hoverColor, ${COLORS.primary1});
}
rect {
transition: transform 0.2s ease-out, fill 0.15s;
}
&.k-BurgerIcon--isActive {
.k-BurgerIcon__bun {
transform: translateX(2px);
}
.k-BurgerIcon__patty {
transform: translateX(-2px);
}
}
&.k-BurgerIcon--isAnimatedOnHover {
&:hover,
button:hover &,
&:focus,
button:focus & {
.k-BurgerIcon__bun {
transform: translateX(2px);
}
.k-BurgerIcon__patty {
transform: translateX(-2px);
}
}
}
`
export const BurgerIcon = ({
mainColor,
hoverColor,
isActive,
iconTitle,
title,
width,
height,
isAnimatedOnHover,
style,
className,
...props
}) => (
<StyledItem
role="img"
aria-label={iconTitle || title}
xmlns="http://www.w3.org/2000/svg"
viewBox="0 0 12 10"
width={width}
height={height}
style={{
...style,
'--burgerIcon-mainColor': mainColor,
'--burgerIcon-hoverColor': hoverColor,
}}
className={classNames('k-BurgerIcon', className, {
'k-BurgerIcon--isActive': isActive,
'k-BurgerIcon--isAnimatedOnHover': isAnimatedOnHover,
})}
{...props}
>
{(iconTitle || title) && <title>{iconTitle || title}</title>}
<rect y="0" width="12" height="2" className="k-BurgerIcon__bun" />
<rect y="4" width="12" height="2" className="k-BurgerIcon__patty" />
<rect y="8" width="12" height="2" className="k-BurgerIcon__bun" />
</StyledItem>
)
BurgerIcon.propTypes = {
mainColor: PropTypes.string,
hoverColor: PropTypes.string,
isActive: PropTypes.bool,
iconTitle: deprecated(PropTypes.string, 'Prefere use `title` prop instead'),
title: PropTypes.string,
width: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
height: PropTypes.oneOfType([PropTypes.number, PropTypes.string]),
}
BurgerIcon.defaultProps = {
mainColor: COLORS.font1,
hoverColor: COLORS.primary1,
isActive: false,
title: null,
width: 12,
height: 10,
isAnimatedOnHover: false,
}
|
app/javascript/mastodon/features/compose/components/upload.js
|
masto-donte-com-br/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import Icon from 'mastodon/components/icon';
export default class Upload extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
onUndo: PropTypes.func.isRequired,
onOpenFocalPoint: PropTypes.func.isRequired,
isEditingStatus: PropTypes.func.isRequired,
};
handleUndoClick = e => {
e.stopPropagation();
this.props.onUndo(this.props.media.get('id'));
}
handleFocalPointClick = e => {
e.stopPropagation();
this.props.onOpenFocalPoint(this.props.media.get('id'));
}
render () {
const { media, isEditingStatus } = this.props;
const focusX = media.getIn(['meta', 'focus', 'x']);
const focusY = media.getIn(['meta', 'focus', 'y']);
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
return (
<div className='compose-form__upload' tabIndex='0' role='button'>
<Motion defaultStyle={{ scale: 0.8 }} style={{ scale: spring(1, { stiffness: 180, damping: 12 }) }}>
{({ scale }) => (
<div className='compose-form__upload-thumbnail' style={{ transform: `scale(${scale})`, backgroundImage: `url(${media.get('preview_url')})`, backgroundPosition: `${x}% ${y}%` }}>
<div className='compose-form__upload__actions'>
<button className='icon-button' onClick={this.handleUndoClick}><Icon id='times' /> <FormattedMessage id='upload_form.undo' defaultMessage='Delete' /></button>
{!isEditingStatus && (<button className='icon-button' onClick={this.handleFocalPointClick}><Icon id='pencil' /> <FormattedMessage id='upload_form.edit' defaultMessage='Edit' /></button>)}
</div>
{(media.get('description') || '').length === 0 && (
<div className='compose-form__upload__warning'>
<button className='icon-button' onClick={this.handleFocalPointClick}><Icon id='info-circle' /> <FormattedMessage id='upload_form.description_missing' defaultMessage='No description added' /></button>
</div>
)}
</div>
)}
</Motion>
</div>
);
}
}
|
src/pages/AnswerQuestion/AnswerQuestion.js
|
imcvampire/simple-online-form
|
import React from 'react'
import {
Container,
} from 'react-grid-system'
import { RaisedButton } from 'material-ui'
import axios from 'axios'
import isEqual from 'lodash.isequal'
import Question from '../../components/Question'
import {
MultipleChoiceQuestion,
MultipleSelectionQuestion,
} from '../../utils/constant'
class AnswerQuestion extends React.Component {
constructor() {
super()
this.state = {
questionList: [],
isSubmitting: false,
}
}
componentDidMount() {
axios.get('/api/questions').then(({ data }) => {
this.setState((state) => ({
...state,
questionList: data.map((question) => ({
...question,
selected: question.kind === MultipleChoiceQuestion ? null : [],
isWrong: false,
}))
}))
})
}
updateSelectedAnswer = index => value => this.setState((state) => {
const questionList = state.questionList.slice()
questionList[index].selected = value
questionList[index].isWrong = false
return {
...state,
questionList,
}
})
hasWrongAnswer = () => this.state.questionList.some(({ isWrong }) => isWrong)
submit = () => {
this.setState((state) => ({
...state,
questionList: state.questionList.map((question) => {
let isWrong = false
if (question.kind === MultipleChoiceQuestion) {
if (question.selected !== question.correctAnswers) isWrong = true
} else if (question.kind === MultipleSelectionQuestion) {
if (!isEqual(question.correctAnswers.sort(), question.selected.sort())) isWrong = true
}
return {
...question,
isWrong,
}
})
}), () => {
if (this.hasWrongAnswer()) return
alert('Your answer is correct!')
this.setState((state) => ({
...state,
isSubmitting: false,
}))
})
}
render() {
return (
<Container>
{
this.state.questionList.map((value, index) => (
<Question
{...value}
key={value._id}
updateSelectedAnswer={this.updateSelectedAnswer(index)}
/>
))
}
<RaisedButton
label="Submit"
fullWidth={true}
primary={true}
disabled={this.state.isSubmitting || this.hasWrongAnswer()}
onClick={this.submit}
/>
</Container>
)
}
}
export default AnswerQuestion
|
ui/routes.js
|
danjac/random-movies
|
import React from 'react';
import { Router, Route, IndexRoute } from 'react-router';
import { App, Movie, MovieList, NotFound } from './components';
export default function (history) {
return (
<Router history={history}>
<Route path="/" component={App}>
<IndexRoute component={MovieList} />
<Route path="/movie/:id/" component={Movie} />
<Route path="*" component={NotFound} />
</Route>
</Router>
);
}
|
packages/react/src/components/DataTable/__tests__/TableCell-test.js
|
carbon-design-system/carbon-components
|
/**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { mount } from 'enzyme';
import { Table, TableBody, TableRow, TableCell } from '../';
describe('DataTable.TableCell', () => {
it('should render', () => {
const wrapper = mount(
<Table>
<TableBody>
<TableRow>
<TableCell className="custom-class" />
</TableRow>
</TableBody>
</Table>
);
expect(wrapper).toMatchSnapshot();
});
});
|
src/EventCell.js
|
intljusticemission/react-big-calendar
|
import PropTypes from 'prop-types'
import React from 'react'
import clsx from 'clsx'
import * as dates from './utils/dates'
class EventCell extends React.Component {
render() {
let {
style,
className,
event,
selected,
isAllDay,
onSelect,
onDoubleClick,
localizer,
continuesPrior,
continuesAfter,
accessors,
getters,
children,
components: { event: Event, eventWrapper: EventWrapper },
slotStart,
slotEnd,
...props
} = this.props
let title = accessors.title(event)
let tooltip = accessors.tooltip(event)
let end = accessors.end(event)
let start = accessors.start(event)
let allDay = accessors.allDay(event)
let showAsAllDay =
isAllDay || allDay || dates.diff(start, dates.ceil(end, 'day'), 'day') > 1
let userProps = getters.eventProp(event, start, end, selected)
const content = (
<div className="rbc-event-content" title={tooltip || undefined}>
{Event ? (
<Event
event={event}
continuesPrior={continuesPrior}
continuesAfter={continuesAfter}
title={title}
isAllDay={allDay}
localizer={localizer}
slotStart={slotStart}
slotEnd={slotEnd}
/>
) : (
title
)}
</div>
)
return (
<EventWrapper {...this.props} type="date">
<div
{...props}
tabIndex={0}
style={{ ...userProps.style, ...style }}
className={clsx('rbc-event', className, userProps.className, {
'rbc-selected': selected,
'rbc-event-allday': showAsAllDay,
'rbc-event-continues-prior': continuesPrior,
'rbc-event-continues-after': continuesAfter,
})}
onClick={e => onSelect && onSelect(event, e)}
onDoubleClick={e => onDoubleClick && onDoubleClick(event, e)}
>
{typeof children === 'function' ? children(content) : content}
</div>
</EventWrapper>
)
}
}
EventCell.propTypes = {
event: PropTypes.object.isRequired,
slotStart: PropTypes.instanceOf(Date),
slotEnd: PropTypes.instanceOf(Date),
selected: PropTypes.bool,
isAllDay: PropTypes.bool,
continuesPrior: PropTypes.bool,
continuesAfter: PropTypes.bool,
accessors: PropTypes.object.isRequired,
components: PropTypes.object.isRequired,
getters: PropTypes.object.isRequired,
localizer: PropTypes.object,
onSelect: PropTypes.func,
onDoubleClick: PropTypes.func,
}
export default EventCell
|
src/main/script/Index.js
|
TomG713/willitconnect
|
/* eslint-env browser */
import React from 'react';
import ReactDOM from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux'
import thunk from 'redux-thunk';
import EntryBox from './EntryBox';
import reducers from './reducers';
require('bootstrap/dist/css/bootstrap.min.css');
require('bootstrap/dist/css/bootstrap-theme.min.css');
const store = createStore(
reducers,
applyMiddleware(thunk),
);
ReactDOM.render(
<Provider store={store}>
<EntryBox />
</Provider>,
document.getElementById('content')
);
mixpanel.track('page loaded');
|
src/Avatar/Avatar.spec.js
|
hwo411/material-ui
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import Avatar from './Avatar';
import getMuiTheme from '../styles/getMuiTheme';
describe('<Avatar />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
const testChildren = <div className="unique">Hello World</div>;
it('renders children by default', () => {
const wrapper = shallowWithContext(
<Avatar>{testChildren}</Avatar>
);
assert.ok(wrapper.contains(testChildren), 'should contain the children');
});
it('renders children and an icon if passed in', () => {
const icon = <div className="testIcon" />;
const wrapper = shallowWithContext(
<Avatar icon={icon}>{testChildren}</Avatar>
);
assert.ok(wrapper.contains(testChildren), 'should contain the children');
// Finding by class as avatar clones element and changes the props
assert.ok(wrapper.find('.testIcon').length, 'should contain the icon');
});
it('only renders an image when the src prop is set', () => {
const wrapper = shallowWithContext(
<Avatar src="face.jpg">{testChildren}</Avatar>
);
assert.notOk(!wrapper.contains(testChildren), 'should not contain the children');
assert.ok(wrapper.is('img'), 'should be an image');
assert.ok(wrapper.is({src: 'face.jpg'}), 'should have the src passed into props');
wrapper.setProps({src: 'meow.jpg'});
assert.ok(wrapper.is({src: 'meow.jpg'}), 'should have changed the src');
});
});
|
frontend/src/Movie/Index/Posters/Options/MovieIndexPosterOptionsModalContent.js
|
Radarr/Radarr
|
import _ from 'lodash';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import Form from 'Components/Form/Form';
import FormGroup from 'Components/Form/FormGroup';
import FormInputGroup from 'Components/Form/FormInputGroup';
import FormLabel from 'Components/Form/FormLabel';
import Button from 'Components/Link/Button';
import ModalBody from 'Components/Modal/ModalBody';
import ModalContent from 'Components/Modal/ModalContent';
import ModalFooter from 'Components/Modal/ModalFooter';
import ModalHeader from 'Components/Modal/ModalHeader';
import { inputTypes } from 'Helpers/Props';
import translate from 'Utilities/String/translate';
const posterSizeOptions = [
{ key: 'small', value: translate('Small') },
{ key: 'medium', value: translate('Medium') },
{ key: 'large', value: translate('Large') }
];
class MovieIndexPosterOptionsModalContent extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
detailedProgressBar: props.detailedProgressBar,
size: props.size,
showTitle: props.showTitle,
showMonitored: props.showMonitored,
showQualityProfile: props.showQualityProfile,
showCinemaRelease: props.showCinemaRelease,
showReleaseDate: props.showReleaseDate,
showSearchAction: props.showSearchAction
};
}
componentDidUpdate(prevProps) {
const {
detailedProgressBar,
size,
showTitle,
showMonitored,
showQualityProfile,
showCinemaRelease,
showReleaseDate,
showSearchAction
} = this.props;
const state = {};
if (detailedProgressBar !== prevProps.detailedProgressBar) {
state.detailedProgressBar = detailedProgressBar;
}
if (size !== prevProps.size) {
state.size = size;
}
if (showTitle !== prevProps.showTitle) {
state.showTitle = showTitle;
}
if (showMonitored !== prevProps.showMonitored) {
state.showMonitored = showMonitored;
}
if (showQualityProfile !== prevProps.showQualityProfile) {
state.showQualityProfile = showQualityProfile;
}
if (showCinemaRelease !== prevProps.showCinemaRelease) {
state.showCinemaRelease = showCinemaRelease;
}
if (showReleaseDate !== prevProps.showReleaseDate) {
state.showReleaseDate = showReleaseDate;
}
if (showSearchAction !== prevProps.showSearchAction) {
state.showSearchAction = showSearchAction;
}
if (!_.isEmpty(state)) {
this.setState(state);
}
}
//
// Listeners
onChangePosterOption = ({ name, value }) => {
this.setState({
[name]: value
}, () => {
this.props.onChangePosterOption({ [name]: value });
});
};
//
// Render
render() {
const {
onModalClose
} = this.props;
const {
detailedProgressBar,
size,
showTitle,
showMonitored,
showQualityProfile,
showCinemaRelease,
showReleaseDate,
showSearchAction
} = this.state;
return (
<ModalContent onModalClose={onModalClose}>
<ModalHeader>
{translate('PosterOptions')}
</ModalHeader>
<ModalBody>
<Form>
<FormGroup>
<FormLabel>{translate('PosterSize')}</FormLabel>
<FormInputGroup
type={inputTypes.SELECT}
name="size"
value={size}
values={posterSizeOptions}
onChange={this.onChangePosterOption}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('DetailedProgressBar')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="detailedProgressBar"
value={detailedProgressBar}
helpText={translate('DetailedProgressBarHelpText')}
onChange={this.onChangePosterOption}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('ShowTitle')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="showTitle"
value={showTitle}
helpText={translate('ShowTitleHelpText')}
onChange={this.onChangePosterOption}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('ShowMonitored')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="showMonitored"
value={showMonitored}
helpText={translate('ShowMonitoredHelpText')}
onChange={this.onChangePosterOption}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('ShowQualityProfile')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="showQualityProfile"
value={showQualityProfile}
helpText={translate('ShowQualityProfileHelpText')}
onChange={this.onChangePosterOption}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('ShowCinemaRelease')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="showCinemaRelease"
value={showCinemaRelease}
helpText={translate('showCinemaReleaseHelpText')}
onChange={this.onChangePosterOption}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('ShowReleaseDate')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="showReleaseDate"
value={showReleaseDate}
helpText={translate('ShowReleaseDateHelpText')}
onChange={this.onChangePosterOption}
/>
</FormGroup>
<FormGroup>
<FormLabel>{translate('ShowSearch')}</FormLabel>
<FormInputGroup
type={inputTypes.CHECK}
name="showSearchAction"
value={showSearchAction}
helpText={translate('ShowSearchHelpText')}
onChange={this.onChangePosterOption}
/>
</FormGroup>
</Form>
</ModalBody>
<ModalFooter>
<Button
onPress={onModalClose}
>
{translate('Close')}
</Button>
</ModalFooter>
</ModalContent>
);
}
}
MovieIndexPosterOptionsModalContent.propTypes = {
size: PropTypes.string.isRequired,
showTitle: PropTypes.bool.isRequired,
showMonitored: PropTypes.bool.isRequired,
showQualityProfile: PropTypes.bool.isRequired,
detailedProgressBar: PropTypes.bool.isRequired,
showCinemaRelease: PropTypes.bool.isRequired,
showReleaseDate: PropTypes.bool.isRequired,
showSearchAction: PropTypes.bool.isRequired,
onChangePosterOption: PropTypes.func.isRequired,
onModalClose: PropTypes.func.isRequired
};
export default MovieIndexPosterOptionsModalContent;
|
docs/app/Examples/modules/Dropdown/Usage/DropdownExampleMultipleCustomLabel.js
|
shengnian/shengnian-ui-react
|
import React from 'react'
import { Dropdown } from 'shengnian-ui-react'
const options = [
{ key: 1, text: 'One', value: 1 },
{ key: 2, text: 'Two', value: 2 },
{ key: 3, text: 'Three', value: 3 },
]
const renderLabel = label => ({
color: 'blue',
content: `Customized label - ${label.text}`,
icon: 'check',
})
const DropdownExampleMultipleCustomLabel = () => (
<Dropdown
multiple
selection
fluid
options={options}
placeholder='Choose an option'
renderLabel={renderLabel}
/>
)
export default DropdownExampleMultipleCustomLabel
|
src/svg-icons/av/videocam-off.js
|
lawrence-yu/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';
AvVideocamOff.muiName = 'SvgIcon';
export default AvVideocamOff;
|
src/Parser/Druid/Balance/Modules/Items/Tier20_2set.js
|
hasseboulen/WoWAnalyzer
|
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import HIT_TYPES from 'Parser/Core/HIT_TYPES';
import getDamageBonus from 'Parser/Mage/Shared/Modules/GetDamageBonus';
import ItemDamageDone from 'Main/ItemDamageDone';
const DAMAGE_BONUS = 0.15;
/**
* Balance Druid Tier20 2set
* Starsurge Critial Strike Damage increased by 30% (additive).
*/
class Tier20_2set extends Analyzer {
static dependencies = {
combatants: Combatants,
};
damage = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.BALANCE_DRUID_T20_2SET_BONUS_BUFF.id);
}
on_byPlayer_damage(event) {
if (event.hitType !== HIT_TYPES.CRIT || event.ability.guid !== SPELLS.STARSURGE_MOONKIN.id) {
return;
}
this.damage += getDamageBonus(event, DAMAGE_BONUS);
}
item() {
return {
id: SPELLS.BALANCE_DRUID_T20_2SET_BONUS_BUFF.id,
icon: <SpellIcon id={SPELLS.BALANCE_DRUID_T20_2SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.BALANCE_DRUID_T20_2SET_BONUS_BUFF.id} />,
result: (
<dfn data-tip={`
This does not take into account any potential damage gained from having 30 more maximum Astral Power.
`}>
<ItemDamageDone amount={this.damage} />,
</dfn>
),
};
}
}
export default Tier20_2set;
|
spec/components/app_bar.js
|
soyjavi/react-toolbox
|
import React from 'react';
import AppBar from '../../components/app_bar';
const AppBarTest = () => (
<section>
<h5>AppBar</h5>
<br/>
<AppBar title='Title' />
<br/>
<AppBar leftIcon='menu' title='Title' />
<br/>
<AppBar leftIcon='arrow_back' title='Title' rightIcon='close' />
<br/>
<AppBar>
Custom content
</AppBar>
</section>
);
export default AppBarTest;
|
app/javascript/mastodon/components/load_more.js
|
palon7/mastodon
|
import React from 'react';
import { FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
export default class LoadMore extends React.PureComponent {
static propTypes = {
onClick: PropTypes.func,
visible: PropTypes.bool,
}
static defaultProps = {
visible: true,
}
render() {
const { visible } = this.props;
return (
<button className='load-more' disabled={!visible} style={{ opacity: visible ? 1 : 0 }} onClick={this.props.onClick}>
<FormattedMessage id='status.load_more' defaultMessage='Load more' />
</button>
);
}
}
|
src/svg-icons/action/line-weight.js
|
barakmitz/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLineWeight = (props) => (
<SvgIcon {...props}>
<path d="M3 17h18v-2H3v2zm0 3h18v-1H3v1zm0-7h18v-3H3v3zm0-9v4h18V4H3z"/>
</SvgIcon>
);
ActionLineWeight = pure(ActionLineWeight);
ActionLineWeight.displayName = 'ActionLineWeight';
ActionLineWeight.muiName = 'SvgIcon';
export default ActionLineWeight;
|
docs/src/app/components/pages/components/Checkbox/ExampleSimple.js
|
spiermar/material-ui
|
import React from 'react';
import Checkbox from 'material-ui/Checkbox';
import ActionFavorite from 'material-ui/svg-icons/action/favorite';
import ActionFavoriteBorder from 'material-ui/svg-icons/action/favorite-border';
const styles = {
block: {
maxWidth: 250,
},
checkbox: {
marginBottom: 16,
},
};
const CheckboxExampleSimple = () => (
<div style={styles.block}>
<Checkbox
label="Simple"
style={styles.checkbox}
/>
<Checkbox
label="Checked by default"
defaultChecked={true}
style={styles.checkbox}
/>
<Checkbox
checkedIcon={<ActionFavorite />}
uncheckedIcon={<ActionFavoriteBorder />}
label="Custom icon"
style={styles.checkbox}
/>
<Checkbox
label="Disabled unchecked"
disabled={true}
style={styles.checkbox}
/>
<Checkbox
label="Disabled checked"
checked={true}
disabled={true}
style={styles.checkbox}
/>
<Checkbox
label="Label on the left"
labelPosition="left"
style={styles.checkbox}
/>
</div>
);
export default CheckboxExampleSimple;
|
src/components/Form/FancySelect/Dropdown.js
|
ilxanlar/cathode
|
import React from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
import BaseDropdown from '../../Dropdown/Dropdown';
import { selectableHelper } from '../../../helpers/utils';
class DropdownRaw extends React.Component {
state = {
focusedKey: 0
};
__mounted = false;
optionsRef = null;
focusedOptionRef = null;
byDropdown = false;
componentDidMount() {
this.__mounted = true;
window.addEventListener('keydown', this.handleControls.bind(this));
window.addEventListener('click', this.handleClickAnywhere);
}
componentWillUnmount() {
this.__mounted = false;
window.removeEventListener('keydown', this.handleControls.bind(this));
window.removeEventListener('click', this.handleClickAnywhere);
}
handleFocusedOptionRef(key, node) {
if (key === this.state.focusedKey) {
this.focusedOptionRef = node;
}
}
handleControls(event) {
if (this.__mounted) {
const { focusedKey } = this.state;
const { options } = this.props;
const maxHoverKey = options.length - 1;
let newFocusKey = focusedKey;
switch (event.keyCode) {
case 13: // Enter
event.preventDefault();
if (focusedKey > -1 && focusedKey <= maxHoverKey) {
this.handleEnterOption(options[focusedKey]);
}
break;
case 27: // Escape
event.preventDefault();
this.handleHide();
break;
case 38: // Up
event.preventDefault();
newFocusKey = focusedKey - 1;
while (options[newFocusKey] && this.getOptionDisabled(options[newFocusKey])) {
if (--newFocusKey < 0) {
break;
}
}
if (newFocusKey >= 0) {
this.setState({ focusedKey: newFocusKey }, this.handleScroll.bind(this));
}
break;
case 40: // Down
event.preventDefault();
newFocusKey = focusedKey + 1;
while (options[newFocusKey] && this.getOptionDisabled(options[newFocusKey])) {
if (++newFocusKey > maxHoverKey) {
break;
}
}
if (focusedKey < maxHoverKey) {
this.setState({ focusedKey: newFocusKey }, this.handleScroll.bind(this));
}
break;
default:
break;
}
}
}
handleClickAnywhere = (event) => {
if (!this.byDropdown && this.props.onClickOutside) {
this.props.onClickOutside();
}
this.byDropdown = false;
};
handleClickOnDropdown = () => {
this.byDropdown = true;
};
handleHide() {
if (this.props.onEscapeKey) {
this.props.onEscapeKey();
}
}
handleScroll() {
if (this.focusedOptionRef) {
while (this.focusedOptionRef.getBoundingClientRect().top < this.optionsRef.getBoundingClientRect().top) {
this.optionsRef.scrollTop -= 100;
}
while (this.optionsRef.getBoundingClientRect().bottom < this.focusedOptionRef.getBoundingClientRect().bottom) {
this.optionsRef.scrollTop += 100;
}
}
}
handleClickOption(option, disabled) {
if (!disabled && this.props.onClick) {
this.props.onClick(option);
}
if (disabled && this.props.onClickDisabled) {
this.props.onClickDisabled(option);
}
}
handleEnterOption(option) {
const disabled = this.getOptionDisabled(option);
if (!disabled && this.props.onEnterKey) {
this.props.onEnterKey(option);
}
}
getOptionLabel = (option) => selectableHelper.label(option, this.props.optionLabel);
getOptionDisabled = (option) => selectableHelper.disabled(option, this.props.optionDisabled);
getOptionActive = (option) => this.props.optionActive(option);
render() {
const { focusedKey } = this.state;
const { options, className } = this.props;
return (
<BaseDropdown.Container
className={className}
onClick={this.handleClickOnDropdown}
innerRef={node => this.optionsRef = node}
>
{
options.map((option, key) => {
const label = this.getOptionLabel(option);
const disabled = this.getOptionDisabled(option);
const active = this.getOptionActive(option);
const focus = key === focusedKey;
return (
<BaseDropdown.Item
key={key}
disabled={disabled}
active={active}
focus={focus}
innerRef={this.handleFocusedOptionRef.bind(this, key)}
onClick={this.handleClickOption.bind(this, option, disabled)}
>
{label}
</BaseDropdown.Item>
);
})
}
</BaseDropdown.Container>
);
}
}
const Dropdown = styled(DropdownRaw)`
${BaseDropdown.Item} {
${props => props.loading ? `opacity: ${props.theme.common.opacityLoading};` : undefined}
}
`;
Dropdown.propTypes = {
loading: PropTypes.bool,
// options: PropTypes.array,
// optionLabel: PropTypes.func.isRequired,
// optionDisabled: PropTypes.func.isRequired,
optionActive: PropTypes.func.isRequired,
onClick: PropTypes.func,
onClickDisabled: PropTypes.func,
onEnterKey: PropTypes.func,
onEscapeKey: PropTypes.func,
onClickEmptyArea: PropTypes.func,
onClickOutside: PropTypes.func
};
Dropdown.defaultProps = {
options: []
};
export default Dropdown;
|
packages/reactor-tests/src/tests/rel/RelUpdate.js
|
sencha/extjs-reactor
|
import React, { Component } from 'react';
import { Container, Button, Menu, MenuItem } from '@extjs/ext-react';
export default class RelUpdate extends Component {
state = {
showMenu: false
}
toggleMenu = () => {
this.setState({ showMenu: !this.state.showMenu })
}
render() {
const { showMenu } = this.state;
return (
<Container id="RelUpdate">
<div>THis tests that configs can be updated by adding and removing child components. Clicking the toggle menu button should add then remove the menu from the "Menu" button.</div>
<Button text="Toggle Menu" handler={this.toggleMenu}/>
<Button text="Menu">
{ showMenu && (
<Menu itemId="menu" indented={false}>
<MenuItem text="Option 1"/>
<MenuItem text="Option 2"/>
<MenuItem text="Option 3"/>
</Menu>
)}
</Button>
</Container>
)
}
}
|
app/components/devices.component.js
|
karlitos/Android-Adb-Tweaker
|
import React from 'react';
class DeviceListItem extends React.Component {
render() {
return (
<li className="list-group-item">
<div className="media-body device-list-element">
<span className="icon icon-mobile device-list-device-icon pull-left"></span>
<dl className="inline-flex-description-list">
<dt><strong>Manufacturer</strong></dt><dd>{this.props.listItem.manufacturer}</dd>
<dt><strong>Name</strong></dt><dd>{this.props.listItem.name}</dd>
<dt><strong>Model</strong></dt><dd>{this.props.listItem.model}</dd>
</dl>
<div className="radio">
<label>
<input type="radio"
value={this.props.listItem.id}
onChange={this.props.onSelectDevice}
checked={this.props.checked}/>
Select
</label>
</div>
</div>
</li>
);
}
}
class Devices extends React.Component {
handleSelectDeviceChange(changeEvent) {
this.props.selectDevice(changeEvent.target.value);
};
buttonIsChecked(deviceId){
return deviceId == this.props.selectedDevice ? true : false;
}
render(){
let deviceListElements = null;
if (this.props.deviceList.length < 1) {
deviceListElements = (<li className="list-group-item no-devices-list-item">
<div className="media-body">No connected devices</div>
</li>);
} else {
deviceListElements = (<form>
{this.props.deviceList.map((item) => {
return <DeviceListItem key={item.id}
listItem={item}
onSelectDevice={::this.handleSelectDeviceChange}
checked={::this.buttonIsChecked(item.id)}/>
}
)}
</form>)
} // end else
return(
<ul className="list-group list-group-not-stretch">
<li className="list-group-header list-group-header-with-gradient">
<button className="btn btn-large btn-default pull-right"
onClick={this.props.listDevices}>
<span className="icon icon-text icon-arrows-ccw"></span>
List devices
</button>
<h4>Connected devices</h4>
</li>
{deviceListElements}
</ul>
)
}
}
/*Devices.defaultProps = {
deviceList: ['No device detected']
};*/
export default Devices
|
frontend/app/js/components/service/index.js
|
serverboards/serverboards
|
import React from 'react'
import ServiceCards from 'app/containers/service/cards'
import ServiceTable from 'app/containers/service/table'
import Loading from 'app/components/loading'
import Empty from './empty'
import Tip from '../tip'
import {i18n} from 'app/utils/i18n'
import ServiceDetails from 'app/containers/service/details'
class ServicesView extends React.Component{
constructor(props){
super(props)
this.state = {
selected_service: undefined
}
}
handleSelectService(selected_service){
this.setState({selected_service})
}
componentWillReceiveProps(newprops){
if (!this.state.selected_service)
return
for (const s of newprops.services){
const ssuuid = this.state.selected_service.uuid
if (s.uuid == ssuuid){
this.setState({selected_service: s})
}
}
}
render(){
const props=this.props
const selected_service = this.state.selected_service
return (
(props.services.length == 0) ? (
<Empty/>
) : (
<div className="ui expand two column grid grey background" style={{margin:0}}>
<div className="ui column">
<div className="ui round pane white background">
{props.mode == "list" ? (
<ServiceTable
services={props.services}
project={props.project}
selected_uuid={selected_service && selected_service.uuid}
onSelectService={this.handleSelectService.bind(this)}
/>
) : (
<ServiceCards
services={props.services}
project={props.project}
selected_uuid={selected_service && selected_service.uuid}
onSelectService={this.handleSelectService.bind(this)}
/>
)}
</div>
</div>
<div className="ui column">
<div className="ui round pane white background">
{selected_service ? (
<ServiceDetails
key={selected_service.uuid}
service={selected_service}
/>
) : (
<Tip
subtitle={i18n("Use account connections to manage your services.")}
description={i18n(`
Select a service to manage from the left list, or create a new one pressing the
add button on bottom left corner.
Clicking over a service shows you more options to perform on the service, as
update the details, or directly access to related tools.
`)}
/>
) }
</div>
</div>
</div>
)
)
}
}
export default ServicesView
|
app/js/__tests__/app-container.js
|
jaydurant/GetCarrot
|
jest.unmock('../components/app-container');
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import AppContainer from '../components/app-container';
describe('AppContainer',() => {
const renderer = TestUtils.createRenderer();
renderer.render(<AppContainer />);
let RenderedTree = renderer.getRenderOutput();
let MenuContainer = RenderedTree.props.children[0];
const AppContent = RenderedTree.props.children[1];
const DoctorContent = AppContent.props.children[0].props.children;
const ChatThread = AppContent.props.children[1].props.children;
it('displays app content', () => {
expect(DoctorContent.props.doctor).toBe(undefined);
expect(ChatThread.props.chat).toEqual([]);
expect(typeof ChatThread.props.onchoice).toEqual('function');
});
it('registers menu closed', () => {
expect(MenuContainer.props.toggle).toBe(false);
});
//you will need to comment out componentDidUpdate as shallow render does not support refs
it('registers menu open --see comments', () => {
MenuContainer.props.clickToggle();
RenderedTree = renderer.getRenderOutput();
MenuContainer = RenderedTree.props.children[0];
expect(MenuContainer.props.toggle).toBe(true);
});
});
|
src/controls/ColorPicker/__test__/colorPickerTest.js
|
michalko/draft-wyswig
|
/* @flow */
import React from 'react';
import {
EditorState,
convertFromHTML,
ContentState,
} from 'draft-js';
import { expect, assert } from 'chai';
import { mount } from 'enzyme';
import ColorPicker from '..';
import defaultToolbar from '../../../config/defaultToolbar';
import ModalHandler from '../../../event-handler/modals';
import localeTranslations from '../../../i18n';
describe('ColorPicker test suite', () => {
const contentBlocks = convertFromHTML('<div>test</div>');
const contentState = ContentState.createFromBlockArray(contentBlocks);
const editorState = EditorState.createWithContent(contentState);
it('should have a div when rendered', () => {
expect(mount(
<ColorPicker
onChange={() => {}}
editorState={editorState}
config={defaultToolbar.colorPicker}
translations={localeTranslations.en}
modalHandler={new ModalHandler()}
/>,
).html().startsWith('<div')).to.equal(true);
});
it('should correctly set default state values', () => {
const control = mount(
<ColorPicker
onChange={() => {}}
editorState={editorState}
config={defaultToolbar.colorPicker}
translations={localeTranslations.en}
modalHandler={new ModalHandler()}
/>,
);
const colorPicker = control.find('ColorPicker');
const state = colorPicker.node.state;
assert.isNotTrue(state.expanded);
assert.isUndefined(state.currentColor);
assert.isUndefined(state.currentBgColor);
});
it('should set variable signalExpanded to true when first child is clicked', () => {
const control = mount(
<ColorPicker
onChange={() => {}}
editorState={editorState}
config={defaultToolbar.colorPicker}
translations={localeTranslations.en}
modalHandler={new ModalHandler()}
/>,
);
const colorPicker = control.find('ColorPicker');
assert.isNotTrue(colorPicker.node.signalExpanded);
control.find('Option').simulate('click');
assert.isTrue(colorPicker.node.signalExpanded);
});
});
|
actor-apps/app-web/src/app/components/ActivitySection.react.js
|
amezcua/actor-platform
|
import React from 'react';
import classNames from 'classnames';
import { ActivityTypes } from 'constants/ActorAppConstants';
import ActivityStore from 'stores/ActivityStore';
import UserProfile from 'components/activity/UserProfile.react';
import GroupProfile from 'components/activity/GroupProfile.react';
const getStateFromStores = () => {
return {
activity: ActivityStore.getActivity(),
isOpen: ActivityStore.isOpen()
};
};
class ActivitySection extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
ActivityStore.addChangeListener(this.onChange);
}
componentWillUnmount() {
ActivityStore.removeChangeListener(this.onChange);
}
render() {
const { activity, isOpen } = this.state;
if (activity !== null) {
const activityClassName = classNames('activity', {
'activity--shown': isOpen
});
let activityBody;
switch (activity.type) {
case ActivityTypes.USER_PROFILE:
activityBody = <UserProfile user={activity.user}/>;
break;
case ActivityTypes.GROUP_PROFILE:
activityBody = <GroupProfile group={activity.group}/>;
break;
default:
}
return (
<section className={activityClassName}>
{activityBody}
</section>
);
} else {
return null;
}
}
onChange = () => {
this.setState(getStateFromStores());
};
}
export default ActivitySection;
|
src/controls/lookup2/lookup.js
|
thinktopography/reframe
|
import Format from '../../utils/format'
import PropTypes from 'prop-types'
import Search from './search'
import React from 'react'
import _ from 'lodash'
class Lookup extends React.Component {
static contextTypes = {
form: PropTypes.object
}
static propTypes = {
active: PropTypes.any,
defaultValue: PropTypes.any,
endpoint: PropTypes.string,
format: PropTypes.oneOfType([
PropTypes.element,
PropTypes.func
]),
label: PropTypes.string,
multiple: PropTypes.bool,
options: PropTypes.array,
placeholder: PropTypes.string,
selected: PropTypes.array,
text: PropTypes.string,
tabIndex: PropTypes.number,
value: PropTypes.string,
onBegin: PropTypes.func,
onChange: PropTypes.func,
onEnd: PropTypes.func,
onFetch: PropTypes.func,
onReady: PropTypes.func,
onRemove: PropTypes.func,
onSelect: PropTypes.func
}
static defaultProps = {
format: ({ value }) => <div className="reframe-lookup2-token">{ value }</div>,
label: 'Record',
multiple: false,
placeholder: null,
value: 'value',
text: 'text'
}
render() {
const { placeholder, selected, tabIndex, format, text } = this.props
return (
<div className={ this._getClass() } tabIndex={ tabIndex }>
<div className="reframe-lookup2-items" onClick={ this._handleBegin.bind(this) }>
{ selected.map((item, index) => (
<div className="reframe-lookup2-item" key={ `selected_${index}` }>
<div className="reframe-lookup2-item-content">
<div className="reframe-lookup2-item-token">
<Format { ...item } format={ format } value={ _.get(item, text) } />
</div>
<div className="reframe-lookup2-item-remove" onClick={ this._handleRemove.bind(this, index) }>
<i className="fa fa-fw fa-times-circle" />
</div>
</div>
</div>
)) }
{ selected.length === 0 && placeholder &&
<div className="reframe-lookup2-placeholder">{ placeholder }</div>
}
</div>
</div>
)
}
componentDidMount() {
const { defaultValue, endpoint, multiple, value, onFetch, onReady } = this.props
const query = value === 'id' ? { $ids: defaultValue } : { $filter: { [value]: { $in: defaultValue } } }
if(defaultValue && (!multiple || defaultValue.length > 0)) onFetch(endpoint, query)
onReady()
}
componentDidUpdate(prevProps) {
const { form } = this.context
const { active, selected } = this.props
if(!prevProps.active && active) form.push(<Search { ...this._getSearch() } />)
if(prevProps.active && !active) form.pop()
if(!_.isEqual(selected, prevProps.selected)) {
this._handleChange()
}
}
_getClass() {
const { multiple } = this.props
const classes = ['reframe-lookup2-field']
if(multiple) classes.push('multiple')
return classes.join(' ')
}
_getSearch() {
const { endpoint, format, label, multiple, options, selected, text, value } = this.props
return {
endpoint,
format,
label,
multiple,
options,
selected,
text,
value,
onCancel: this._handleEnd.bind(this),
onDone: this._handleEnd.bind(this),
onSelect: this._handleSelect.bind(this)
}
}
_getValue() {
const { multiple, selected, value } = this.props
const values = selected.map(item => _.get(item, value))
return multiple ? values : values[0]
}
_handleBegin() {
this.props.onBegin()
}
_handleEnd() {
this.props.onEnd()
}
_handleRemove(index, e) {
e.stopPropagation()
this.props.onRemove(index)
}
_handleSelect(items) {
const { onSelect } = this.props
onSelect(items)
}
_handleChange() {
const { onChange } = this.props
return onChange(this._getValue())
}
}
export default Lookup
|
test/helpers/shallowRenderHelper.js
|
chickencyj/gallery-by-react
|
/**
* Function to get the shallow output for a given component
* As we are using phantom.js, we also need to include the fn.proto.bind shim!
*
* @see http://simonsmith.io/unit-testing-react-components-without-a-dom/
* @author somonsmith
*/
import React from 'react';
import TestUtils from 'react-addons-test-utils';
/**
* Get the shallow rendered component
*
* @param {Object} component The component to return the output for
* @param {Object} props [optional] The components properties
* @param {Mixed} ...children [optional] List of children
* @return {Object} Shallow rendered output
*/
export default function createComponent(component, props = {}, ...children) {
const shallowRenderer = TestUtils.createRenderer();
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]));
return shallowRenderer.getRenderOutput();
}
|
app/javascript/mastodon/features/account_timeline/index.js
|
ashfurrow/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { lookupAccount, fetchAccount } from '../../actions/accounts';
import { expandAccountFeaturedTimeline, expandAccountTimeline } from '../../actions/timelines';
import StatusList from '../../components/status_list';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import HeaderContainer from './containers/header_container';
import ColumnBackButton from '../../components/column_back_button';
import { List as ImmutableList } from 'immutable';
import ImmutablePureComponent from 'react-immutable-pure-component';
import { FormattedMessage } from 'react-intl';
import MissingIndicator from 'mastodon/components/missing_indicator';
import TimelineHint from 'mastodon/components/timeline_hint';
import { me } from 'mastodon/initial_state';
import { connectTimeline, disconnectTimeline } from 'mastodon/actions/timelines';
const emptyList = ImmutableList();
const mapStateToProps = (state, { params: { acct, id }, withReplies = false }) => {
const accountId = id || state.getIn(['accounts_map', acct]);
if (!accountId) {
return {
isLoading: true,
};
}
const path = withReplies ? `${accountId}:with_replies` : accountId;
return {
accountId,
remote: !!(state.getIn(['accounts', accountId, 'acct']) !== state.getIn(['accounts', accountId, 'username'])),
remoteUrl: state.getIn(['accounts', accountId, 'url']),
isAccount: !!state.getIn(['accounts', accountId]),
statusIds: state.getIn(['timelines', `account:${path}`, 'items'], emptyList),
featuredStatusIds: withReplies ? ImmutableList() : state.getIn(['timelines', `account:${accountId}:pinned`, 'items'], emptyList),
isLoading: state.getIn(['timelines', `account:${path}`, 'isLoading']),
hasMore: state.getIn(['timelines', `account:${path}`, 'hasMore']),
suspended: state.getIn(['accounts', accountId, 'suspended'], false),
blockedBy: state.getIn(['relationships', accountId, 'blocked_by'], false),
};
};
const RemoteHint = ({ url }) => (
<TimelineHint url={url} resource={<FormattedMessage id='timeline_hint.resources.statuses' defaultMessage='Older posts' />} />
);
RemoteHint.propTypes = {
url: PropTypes.string.isRequired,
};
export default @connect(mapStateToProps)
class AccountTimeline extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.shape({
acct: PropTypes.string,
id: PropTypes.string,
}).isRequired,
accountId: PropTypes.string,
dispatch: PropTypes.func.isRequired,
statusIds: ImmutablePropTypes.list,
featuredStatusIds: ImmutablePropTypes.list,
isLoading: PropTypes.bool,
hasMore: PropTypes.bool,
withReplies: PropTypes.bool,
blockedBy: PropTypes.bool,
isAccount: PropTypes.bool,
suspended: PropTypes.bool,
remote: PropTypes.bool,
remoteUrl: PropTypes.string,
multiColumn: PropTypes.bool,
};
_load () {
const { accountId, withReplies, dispatch } = this.props;
dispatch(fetchAccount(accountId));
if (!withReplies) {
dispatch(expandAccountFeaturedTimeline(accountId));
}
dispatch(expandAccountTimeline(accountId, { withReplies }));
if (accountId === me) {
dispatch(connectTimeline(`account:${me}`));
}
}
componentDidMount () {
const { params: { acct }, accountId, dispatch } = this.props;
if (accountId) {
this._load();
} else {
dispatch(lookupAccount(acct));
}
}
componentDidUpdate (prevProps) {
const { params: { acct }, accountId, dispatch } = this.props;
if (prevProps.accountId !== accountId && accountId) {
this._load();
} else if (prevProps.params.acct !== acct) {
dispatch(lookupAccount(acct));
}
if (prevProps.accountId === me && accountId !== me) {
dispatch(disconnectTimeline(`account:${me}`));
}
}
componentWillUnmount () {
const { dispatch, accountId } = this.props;
if (accountId === me) {
dispatch(disconnectTimeline(`account:${me}`));
}
}
handleLoadMore = maxId => {
this.props.dispatch(expandAccountTimeline(this.props.accountId, { maxId, withReplies: this.props.withReplies }));
}
render () {
const { statusIds, featuredStatusIds, isLoading, hasMore, blockedBy, suspended, isAccount, multiColumn, remote, remoteUrl } = this.props;
if (!isAccount) {
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<MissingIndicator />
</Column>
);
}
if (!statusIds && isLoading) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
let emptyMessage;
if (suspended) {
emptyMessage = <FormattedMessage id='empty_column.account_suspended' defaultMessage='Account suspended' />;
} else if (blockedBy) {
emptyMessage = <FormattedMessage id='empty_column.account_unavailable' defaultMessage='Profile unavailable' />;
} else if (remote && statusIds.isEmpty()) {
emptyMessage = <RemoteHint url={remoteUrl} />;
} else {
emptyMessage = <FormattedMessage id='empty_column.account_timeline' defaultMessage='No posts found' />;
}
const remoteMessage = remote ? <RemoteHint url={remoteUrl} /> : null;
return (
<Column>
<ColumnBackButton multiColumn={multiColumn} />
<StatusList
prepend={<HeaderContainer accountId={this.props.accountId} />}
alwaysPrepend
append={remoteMessage}
scrollKey='account_timeline'
statusIds={(suspended || blockedBy) ? emptyList : statusIds}
featuredStatusIds={featuredStatusIds}
isLoading={isLoading}
hasMore={hasMore}
onLoadMore={this.handleLoadMore}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
timelineId='account'
/>
</Column>
);
}
}
|
test/PaginationSpec.js
|
Firfi/meteor-react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Pagination from '../src/Pagination';
describe('Pagination', function () {
it('Should have class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Pagination>Item content</Pagination>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithClass(instance, 'pagination'));
});
it('Should show the correct active button', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Pagination
items={5}
activePage={3} />
);
let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li');
assert.equal(pageButtons.length, 5);
React.findDOMNode(pageButtons[2]).className.should.match(/\bactive\b/);
});
it('Should call onSelect when page button is selected', function (done) {
function onSelect(event, selectedEvent) {
assert.equal(selectedEvent.eventKey, 2);
done();
}
let instance = ReactTestUtils.renderIntoDocument(
<Pagination items={5} onSelect={onSelect} />
);
ReactTestUtils.Simulate.click(
ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'a')[1]
);
});
it('Should only show part of buttons and active button in the middle of buttons when given maxButtons', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Pagination
items={30}
activePage={10}
maxButtons={9} />
);
let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li');
// 9 visible page buttons and 1 ellipsis button
assert.equal(pageButtons.length, 10);
// active button is the second one
assert.equal(React.findDOMNode(pageButtons[0]).firstChild.innerText, '6');
React.findDOMNode(pageButtons[4]).className.should.match(/\bactive\b/);
});
it('Should show the ellipsis, first, last, prev and next button', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Pagination
first={true}
last={true}
prev={true}
next={true}
maxButtons={3}
activePage={10}
items={20} />
);
let pageButtons = ReactTestUtils.scryRenderedDOMComponentsWithTag(instance, 'li');
// add first, last, prev, next and ellipsis button
assert.equal(pageButtons.length, 8);
assert.equal(React.findDOMNode(pageButtons[0]).innerText, '«');
assert.equal(React.findDOMNode(pageButtons[1]).innerText, '‹');
assert.equal(React.findDOMNode(pageButtons[5]).innerText, '...');
assert.equal(React.findDOMNode(pageButtons[6]).innerText, '›');
assert.equal(React.findDOMNode(pageButtons[7]).innerText, '»');
});
});
|
node_modules/react-bootstrap/es/Label.js
|
WatkinsSoftwareDevelopment/HowardsBarberShop
|
import _Object$values from 'babel-runtime/core-js/object/values';
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, bsStyles, getClassSet, splitBsProps } from './utils/bootstrapUtils';
import { State, Style } from './utils/StyleConfig';
var Label = function (_React$Component) {
_inherits(Label, _React$Component);
function Label() {
_classCallCheck(this, Label);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Label.prototype.hasContent = function hasContent(children) {
var result = false;
React.Children.forEach(children, function (child) {
if (result) {
return;
}
if (child || child === 0) {
result = true;
}
});
return result;
};
Label.prototype.render = function render() {
var _props = this.props,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = _extends({}, getClassSet(bsProps), {
// Hack for collapsing on IE8.
hidden: !this.hasContent(children)
});
return React.createElement(
'span',
_extends({}, elementProps, {
className: classNames(className, classes)
}),
children
);
};
return Label;
}(React.Component);
export default bsClass('label', bsStyles([].concat(_Object$values(State), [Style.DEFAULT, Style.PRIMARY]), Style.DEFAULT, Label));
|
src/js/components/icons/base/DocumentThreat.js
|
odedre/grommet-final
|
/**
* @description DocumentThreat SVG Icon.
* @property {string} a11yTitle - Accessibility Title. If not set uses the default title of the status icon.
* @property {string} colorIndex - The color identifier to use for the stroke color.
* If not specified, this component will default to muiTheme.palette.textColor.
* @property {xsmall|small|medium|large|xlarge|huge} size - The icon size. Defaults to small.
* @property {boolean} responsive - Allows you to redefine what the coordinates.
* @example
* <svg width="24" height="24" ><path d="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L17,23 M18,1 L18,6 L23,6 M9,23 C11.7614237,23 14,20.7614237 14,18 C14,15.2385763 11.7614237,13 9,13 C6.23857625,13 4,15.2385763 4,18 C4,20.7614237 6.23857625,23 9,23 Z M9,11 C9,11 9,10 9,9 C9,8 9,7 11,7 C13,7 13.0000001,8 13,9 C12.9999999,10 13,10.9999998 15,10.9999999 C17,11.0000001 17,11 17,11 M8,11 L10,11 L10,13 L8,13 L8,11 Z"/></svg>
*/
// (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}-document-threat`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'document-threat');
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="M4.99787498,6.99999999 L4.99787498,0.999999992 L19.4999998,0.999999992 L22.9999998,4.50000005 L23,23 L17,23 M18,1 L18,6 L23,6 M9,23 C11.7614237,23 14,20.7614237 14,18 C14,15.2385763 11.7614237,13 9,13 C6.23857625,13 4,15.2385763 4,18 C4,20.7614237 6.23857625,23 9,23 Z M9,11 C9,11 9,10 9,9 C9,8 9,7 11,7 C13,7 13.0000001,8 13,9 C12.9999999,10 13,10.9999998 15,10.9999999 C17,11.0000001 17,11 17,11 M8,11 L10,11 L10,13 L8,13 L8,11 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'DocumentThreat';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
public/js/src/main.js
|
jiadams/wjf-portfolio
|
import React from 'react'; // eslint-disable-line no-unused-vars
import ReactDOM from 'react-dom';
import WorksBox from './components/works-box'; // eslint-disable-line no-unused-vars
(function( $ ) { // eslint-disable-line no-unused-vars
'use strict';
/**
* All of the code for your public-facing JavaScript source
* should reside in this file.
*
* Note: It has been assumed you will write jQuery code here, so the
* $ function reference has been prepared for usage within the scope
* of this function.
*
* This enables you to define handlers, for when the DOM is ready:
*
* $(function() {
*
* });
*
* When the window is loaded:
*
* $( window ).load(function() {
*
* });
*
* ...and/or other possibilities.
*
* Ideally, it is not considered best practise to attach more than a
* single DOM-ready or window-load handler for a particular page.
* Although scripts in the WordPress core, Plugins and Themes may be
* practising this, we should strive to set a better example in our own work.
*/
// init Masonry after all images have loaded
ReactDOM.render(
<WorksBox />,
document.getElementById('works-box')
);
})( jQuery );
|
example/src/pages/MapProps.js
|
ethanselzer/react-touch-position
|
import React, { Component } from 'react';
import {
Col,
Grid,
Jumbotron,
Row
} from 'react-bootstrap';
import Helmet from 'react-helmet';
import MapProps from '../components/MapProps';
import Header from '../components/Header';
import 'bootstrap/dist/css/bootstrap.css';
import '../../styles/app.css';
class MapChildPropsPage extends Component {
render() {
return (
<div>
<Helmet title="Map Child Props | React Touch Position" />
<Header {...this.props}/>
<Jumbotron>
<Grid>
<Row>
<Col sm={12}>
<h2>Map Child Props - API Example</h2>
</Col>
</Row>
<Row>
<Col sm={5}>
<ul className="summary__list">
<li>Implement mapChildProps to model child component props to your custom shape</li>
<li>Easily make react-touch-position conform to the API of your components</li>
</ul>
</Col>
<Col sm={5}>
<ul className="summary__list">
<li>Type: Function</li>
<li>
<a href="https://github.com/ethanselzer/react-touch-position/blob/master/example/src/components/MapProps.js">
Example Code
</a>
</li>
</ul>
</Col>
</Row>
</Grid>
</Jumbotron>
<Grid>
<Row>
<Col sm={6} md={4} lg={4}>
<MapProps/>
</Col>
<Col sm={6} md={8} lg={8}>
<a
className="highlighter"
href="https://github.com/ethanselzer/react-touch-position/blob/master/example/src/components/MapProps.js"
style={{height: '525px'}}
>
<iframe
src="map-child-props.html"
frameBorder="0"
className="code-frame"
/>
</a>
</Col>
</Row>
</Grid>
</div>
);
}
}
export default MapChildPropsPage;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.