path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
client/src/components/NoAccess.js | JasonProcka/venos |
// --- Imports ----
// >>> React
import React from 'react';
// Show a Page that says that you have no access to the current area
export default class NoAccess extends React.Component {
render() {
return (
<div>
{`You do not have access for here`}
</div>
);
}
}
|
src/components/PXBottomSheetCancelButton.js | alphasp/pxview | import React from 'react';
import { View, StyleSheet } from 'react-native';
import { withTheme, Text } from 'react-native-paper';
import IonicIcon from 'react-native-vector-icons/Ionicons';
import PXTouchable from './PXTouchable';
const styles = StyleSheet.create({
bottomSheetListItem: {
flexDirection: 'row',
justifyContent: 'flex-start',
alignItems: 'center',
height: 48,
},
bottomSheetCancelIcon: {
marginLeft: 3,
},
bottomSheetCancelText: {
marginLeft: 36,
},
});
const PXBottomSheetCancelButton = ({ onPress, text, textStyle, theme }) => (
<PXTouchable onPress={onPress}>
<View style={styles.bottomSheetListItem}>
<IonicIcon
name="md-close"
size={24}
style={styles.bottomSheetCancelIcon}
color={theme.colors.text}
/>
<Text style={[styles.bottomSheetCancelText, textStyle]}>{text}</Text>
</View>
</PXTouchable>
);
export default withTheme(PXBottomSheetCancelButton);
|
spec/javascripts/jsx/assignments/GradeSummary/components/GradersTableSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2018 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import {mount} from 'enzyme'
import {Provider} from 'react-redux'
import * as GradeActions from 'jsx/assignments/GradeSummary/grades/GradeActions'
import * as StudentActions from 'jsx/assignments/GradeSummary/students/StudentActions'
import GradersTable from 'jsx/assignments/GradeSummary/components/GradersTable'
import configureStore from 'jsx/assignments/GradeSummary/configureStore'
QUnit.module('GradeSummary GradersTable', suiteHooks => {
let provisionalGrades
let store
let storeEnv
let wrapper
suiteHooks.beforeEach(() => {
storeEnv = {
assignment: {
courseId: '1201',
gradesPublished: false,
id: '2301',
muted: true,
title: 'Example Assignment'
},
currentUser: {
graderId: 'teach',
id: '1105'
},
graders: [
{graderId: '1101', graderName: 'Miss Frizzle'},
{graderId: '1102', graderName: 'Mr. Keating'},
{graderId: '1103', graderName: 'Mrs. Krabappel'},
{graderId: '1104', graderName: 'Mr. Feeny'}
]
}
provisionalGrades = [
{
grade: 'A',
graderId: '1101',
id: '4601',
score: 9.5,
selected: false,
studentId: '1111'
},
{
grade: 'B',
graderId: '1102',
id: '4602',
score: 8.4,
selected: false,
studentId: '1112'
},
{
grade: 'C',
graderId: '1103',
id: '4603',
score: 7.6,
selected: false,
studentId: '1113'
},
{
grade: 'B+',
graderId: '1104',
id: '4604',
score: 8.9,
selected: false,
studentId: '1114'
}
]
})
suiteHooks.afterEach(() => {
wrapper.unmount()
})
function mountComponent() {
store = configureStore(storeEnv)
wrapper = mount(
<Provider store={store}>
<GradersTable />
</Provider>
)
}
function mountAndFinishLoading() {
mountComponent()
store.dispatch(GradeActions.addProvisionalGrades(provisionalGrades))
store.dispatch(StudentActions.setLoadStudentsStatus(StudentActions.SUCCESS))
wrapper.update()
}
function getGraderRow(graderId) {
const {graderName} = storeEnv.graders.find(grader => grader.graderId === graderId)
const rows = wrapper
.find('View Grid GridRow')
.filterWhere(row => row.find('label').length > 0 && row.find('label').text() === graderName)
return rows.at(0)
}
function getAcceptGradesColumnHeader() {
return wrapper.find('div').findWhere(element => element.text() === 'Accept Grades')
}
test('includes a row for each grader', () => {
mountComponent()
strictEqual(wrapper.find('.grader-label').length, 4)
})
test('displays grader names in the row headers', () => {
mountComponent()
const rowHeaders = wrapper.find('.grader-label')
deepEqual(
rowHeaders.map(header => header.text()),
storeEnv.graders.map(grader => grader.graderName)
)
})
QUnit.module('"Accept Grades" column', hooks => {
hooks.beforeEach(() => {
mountComponent()
})
test('is not displayed when grades have not started loading', () => {
notOk(getAcceptGradesColumnHeader().exists())
})
test('is not displayed when grades have started loading', () => {
store.dispatch(StudentActions.setLoadStudentsStatus(StudentActions.STARTED))
notOk(getAcceptGradesColumnHeader().exists())
})
test('is not displayed when not all provisional grades have loaded', () => {
store.dispatch(StudentActions.setLoadStudentsStatus(StudentActions.STARTED))
store.dispatch(GradeActions.addProvisionalGrades(provisionalGrades))
notOk(getAcceptGradesColumnHeader().exists())
})
test('is displayed when grades have finished loading and at least one grader can be bulk-selected', () => {
mountAndFinishLoading()
ok(getAcceptGradesColumnHeader().exists())
})
test('is not displayed when grades have finished loading and no graders can be bulk-selected', () => {
provisionalGrades.forEach(grade => {
grade.studentId = '1111'
})
mountAndFinishLoading()
notOk(getAcceptGradesColumnHeader().exists())
})
test('is displayed when grades have finished loading and all students have a selected grade', () => {
provisionalGrades.forEach(grade => {
grade.selected = true
})
mountAndFinishLoading()
ok(getAcceptGradesColumnHeader().exists())
})
})
QUnit.module('"Accept Grades" button', () => {
function getGraderAcceptGradesButton(graderId) {
return getGraderRow(graderId).find('AcceptGradesButton')
}
test('receives the "accept grades" status for the related grader', () => {
mountAndFinishLoading()
store.dispatch(
GradeActions.setBulkSelectProvisionalGradesStatus('1101', GradeActions.STARTED)
)
wrapper.update()
const button = getGraderAcceptGradesButton('1101')
equal(button.prop('acceptGradesStatus'), GradeActions.STARTED)
})
test('accepts grades for the related grader when clicked', () => {
sandbox
.stub(GradeActions, 'acceptGraderGrades')
.callsFake(graderId =>
GradeActions.setBulkSelectProvisionalGradesStatus(graderId, GradeActions.STARTED)
)
mountAndFinishLoading()
const button = getGraderAcceptGradesButton('1101')
button.prop('onClick')()
equal(store.getState().grades.bulkSelectProvisionalGradeStatuses[1101], GradeActions.STARTED)
})
test('receives the grade selection details for the related grader', () => {
mountAndFinishLoading()
const button = getGraderAcceptGradesButton('1103')
deepEqual(button.prop('selectionDetails').provisionalGradeIds, ['4603'])
})
})
})
|
src/Main/News/Articles/2017-01-31-About/index.js | enragednuke/WoWAnalyzer | import React from 'react';
import RegularArticle from 'Main/News/RegularArticle';
import MasteryRadiusImage from 'Main/Images/mastery-radius.png';
export const title = "About WoWAnalyzer the World of Warcraft analyzer";
export default (
<RegularArticle title={title} published="2017-01-31">
<img src={MasteryRadiusImage} alt="Mastery radius" className="pull-right" style={{ margin: 15 }} />
WoWAnalyzer is a comprehensive tool for analyzing your performance based on important metrics for your spec. You will need a Warcraft Logs report with advanced combat logging enabled to start. Private logs can not be used, if your guild has private logs you will have to <a href="https://www.warcraftlogs.com/help/start/">upload your own logs</a> or change the existing logs to the <i>unlisted</i> privacy option instead.<br /><br />
Here are some interesting examples: <a href="/report/hNqbFwd7Mx3G1KnZ/18-Mythic+Antoran+High+Command+-+Kill+(6:51)/Taffly" className="Paladin">Holy Paladin</a>, <a href="/report/wmfhYRxTpvZyHLdF/1-Mythic+Garothi+Worldbreaker+-+Kill+(4:48)/Hassebewlen" className="Priest">Shadow Priest</a>, <a href="/report/mtjvg4FQ6A8RGz1V/3-Mythic+Garothi+Worldbreaker+-+Kill+(6:18)/Paranema" className="Shaman">Restoration Shaman</a>, <a href="/report/wXPNHQqrjmVbafJL/38-Mythic+Garothi+Worldbreaker+-+Kill+(5:05)/Maareczek" className="Hunter">Marksmanship Hunter</a>, <a href="/report/2MNkGb36FW1gX8zx/15-Mythic+Imonar+the+Soulhunter+-+Kill+(7:45)/Anom" className="Monk">Mistweaver Monk</a>, <a href="/report/t3wKdDkB7fZqbmWz/1-Normal+Garothi+Worldbreaker+-+Kill+(4:24)/Sref" className="Mage">Frost Mage</a>, <a href="/report/72t9vbcAqdpVRfBQ/12-Mythic+Garothi+Worldbreaker+-+Kill+(6:15)/Maxweii" className="DeathKnight">Unholy Death Knight</a> and <a href="/report/hxzFPBaWLJrG1NQR/24-Heroic+Imonar+the+Soulhunter+-+Kill+(3:38)/Putro" className="Hunter">Beast Mastery Hunter</a>. Let us know if you want your logs to be featured here.
<br /><br />
Feature requests and bug reports are welcome! On <a href="https://discord.gg/AxphPxU">Discord</a> or create an issue <a href="https://github.com/WoWAnalyzer/WoWAnalyzer/issues">here</a>.
</RegularArticle>
);
|
packages/docs/components/Examples/hashtag/gettingStarted.js | nikgraf/draft-js-plugin-editor | // It is important to import the Editor which accepts plugins.
import Editor from '@draft-js-plugins/editor';
import createHashtagPlugin from '@draft-js-plugins/hashtag';
import React from 'react';
// Creates an Instance. At this step, a configuration object can be passed in
// as an argument.
const hashtagPlugin = createHashtagPlugin();
// The Editor accepts an array of plugins. In this case, only the hashtagPlugin
// is passed in, although it is possible to pass in multiple plugins.
const MyEditor = ({ editorState, onChange }) => (
<Editor
editorState={editorState}
onChange={onChange}
plugins={[hashtagPlugin]}
/>
);
export default MyEditor;
|
client/components/Shared/LoadingScreen/index.js | vcu-lcc/nomad | /*
Copyright (C) 2017 Darren Chan
This program 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, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import {
ProgressCircle,
Text
} from 'react-desktop/windows';
class LoadingScreen extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div
style={{
display: 'flex',
alignItems: 'center'
}}
>
<ProgressCircle
size={80}
/>
<Text
padding="0px 24px 0px 24px"
height={60}
verticalAlignment="center"
>
<span
style={{
fontSize: 'x-large'
}}
>
{this.props.children}
</span>
</Text>
</div>
);
}
}
export default LoadingScreen; |
src/modules/client/routes.js | belng/pure | /* @flow */
import fs from 'fs';
import path from 'path';
import handlebars from 'handlebars';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import ServerHTML from './ServerHTML';
import RichText from '../../ui/components/views/Core/RichText';
import promisify from '../../lib/promisify';
import { convertURLToRoute } from '../../lib/Route';
import { bus, cache, config } from '../../core-server';
const PLAY_STORE_LINK = `https://play.google.com/store/apps/details?id=${config.package_name}`;
const promo = handlebars.compile(fs.readFileSync(path.join(__dirname, '../../../templates/promo.hbs')).toString());
const getEntityAsync = promisify(cache.getEntity.bind(cache));
const queryEntityAsync = promisify(cache.query.bind(cache));
bus.on('http/init', app => {
app.use(function *(next) {
const query = this.request.query;
let room, thread;
if (query && query.download_app) {
this.response.redirect(query.referrer ? `${PLAY_STORE_LINK}&referrer=${query.referrer}` : PLAY_STORE_LINK);
return;
}
const { name, props } = convertURLToRoute(this.request.href);
let title, description;
if (props) {
switch (name) {
case 'room': {
room = yield getEntityAsync(props.room);
if (room) {
title = `The ${room.name} community is on ${config.app_name}.`;
description = `Install the ${config.app_name} app to join.`;
}
break;
}
case 'chat': {
/* $FlowFixMe */
[ thread, room ] = yield Promise.all([ getEntityAsync(props.thread), getEntityAsync(props.room) ]);
if (thread) {
title = thread.name;
description = thread.body;
}
break;
}
}
}
const response: {
room: ?Object;
thread?: Object;
texts?: Array<Object>;
user?: Object;
playstore: string;
facebook: string;
} = {
room,
playstore: PLAY_STORE_LINK + (this.request.search ? ('&referrer=' + encodeURIComponent(this.request.search.substr(1))) : ''),
facebook: `https://www.facebook.com/sharer/sharer.php?u=${this.request.href}`,
twitter: `http://twitter.com/share?text=${encodeURIComponent(title || '')}&url=${encodeURIComponent(this.request.href)}`,
};
let image = `${this.request.origin}/s/assets/preview-thumbnail.png`;
if (thread) {
if (thread.counts.children < 10 || !thread.counts.children) thread.showAll = true;
else thread.more = thread.counts.children - 10;
const queryTexts = yield queryEntityAsync({
type: 'text',
filter: {
parents_first: thread.id
},
order: 'createTime',
}, [ -Infinity, Infinity ]);
response.texts = (queryTexts && queryTexts.arr ? queryTexts.arr.slice(0, 10) : []).map(text => ({
...text,
html: ReactDOMServer.renderToStaticMarkup(<RichText text={text.body} />),
}));
if (thread.meta && thread.meta.photo) {
image = thread.meta.photo.thumbnail_url;
description = thread.counts && thread.counts.follower ? thread.counts.follower + 'people talking' : '';
} else if (thread.meta && thread.meta.oembed) {
const oEmbed = thread.meta.oembed;
image = oEmbed.thumbnail_url;
if (oEmbed.description) {
description += '. ' + oEmbed.description;
}
}
response.thread = thread;
response.user = {
id: thread.creator || '',
picture: `/i/picture?user=${thread.creator || ''}&size=48`
};
}
// console.log('response: ', response)
this.body = '<!DOCTYPE html>' + ReactDOMServer.renderToStaticMarkup(
<ServerHTML
locale='en'
title={title || config.app_name}
description={description || ''}
body={promo(response)}
image={image}
permalink={this.request.href}
styles={[
'//fonts.googleapis.com/css?family=Alegreya+Sans:300,500,900|Lato:400,700',
'/s/styles/home.css'
]}
analytics={config.analytics}
/>
);
yield *next;
});
});
|
src/containers/AttributesPanel.js | eveafeline/D3-ID3-Naomi | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { getScatterPlot, updateWidth } from '../actions/ScatterPlotActions';
import { getD3ParserObj, updateValue } from '../actions/D3ParserActions';
import { ScatterPlotReducer, D3ParserReducer } from '../reducers/index';
import AttrListItem from '../components/attributes/d3-parsed/AttrListItem';
import Dimensions from '../components/attributes/scatter-plot/Dimensions';
import Axes from '../components/attributes/scatter-plot/Axes';
import LocalAttributes from '../components/attributes/scatter-plot/LocalAttributes';
import Data from '../components/attributes/scatter-plot/Data';
const d3parser = require('../d3-parser/d3parser');
import { editor } from '../components/editor/textEditor';
import fs from 'fs';
const { ipcRenderer } = require('electron');
class AttributesPanel extends Component {
componentDidMount() {
let fileUpLoadBtn = document.getElementById('upload-file');
fileUpLoadBtn.addEventListener('change', (event) => {
setTimeout(() => {
this.props.getD3ParserObj();
this.forceUpdate();
}, 0)
});
ipcRenderer.on('updateAttr', (event) => {
this.props.getD3ParserObj();
this.forceUpdate();
});
}
handleSubmit(e, obj) {
e.preventDefault();
let d3string = JSON.stringify(obj, null, '\t')
fs.writeFileSync('./src/d3ParserObj.js', d3string);
let htmlString = d3parser.reCode(JSON.parse(d3string));
fs.writeFileSync('./src/components/temp/temp.html', htmlString);
editor.setValue(htmlString);
document.querySelector('webview').reload();
ipcRenderer.send('updateNewWebView');
}
render() {
// State from ScatterPlotReducer
const ScatterPlotObj = this.props.ScatterPlotReducer;
// Attributes For Scatter Plot
const margin = ScatterPlotObj.margin;
const width = ScatterPlotObj.width;
const height = ScatterPlotObj.height;
const responsiveResize = ScatterPlotObj.responsiveResize;
const axes = ScatterPlotObj.axes;
const gridLines = ScatterPlotObj.gridLines;
const regressionLine = ScatterPlotObj.regressionLine;
const toolTip = ScatterPlotObj.toolTip;
const scatterPlot = ScatterPlotObj.scatterPlot;
const data = ScatterPlotObj.data;
const D3ParserObj = this.props.D3ParserReducer;
if (D3ParserObj.length > 0) {
const attrObj = D3ParserObj.filter((el, i) => {
if (typeof el === 'object' && el.hasOwnProperty('args')) {
el.id = i;
return true;
}
});
const attrList = attrObj.map(obj => {
return <AttrListItem key={obj.id} updateValue={this.props.updateValue} info={obj} />
});
return (
<div className="pane-one-fourth">
<header className="toolbar toolbar-header attr-main-header">
<h1 className="title main-header">Attributes Panel</h1>
<button className="btn btn-primary generate-btn" id="d3parser" onClick={(e)=>getD3ParserObj()}>
Generate
</button>
</header>
<div id="attr-panel">
<div className="parsed-attr-container">
<form id="attrForm" onSubmit={(e) => this.handleSubmit(e, D3ParserObj)}>
{attrList}
</form>
</div>
</div>
<div className="submit-btn">
<button type="submit" className="btn btn-default attr-submit-btn" form="attrForm">Save</button>
</div>
</div>
)
}
return (
<div className="pane-one-fourth">
<header className="toolbar toolbar-header attr-main-header">
<h1 className="title main-header">Attributes Panel</h1>
<button className="btn btn-default generate-btn" id="d3parser" onClick={(e) => getD3ParserObj()}>
Generate
</button>
</header>
<div id="attr-panel">
<Dimensions
margin={margin}
width={width}
height={height}
responsiveResize={responsiveResize}
controlWidth={this.props.updateWidth}
/>
<Axes axes={axes} />
<LocalAttributes
gridLines={gridLines}
regressionLine={regressionLine}
tooTip={toolTip}
scatterPlot={scatterPlot} />
<Data />
</div>
<div className="submit-btn">
<button className="btn btn-default attr-submit-btn" type="submit">Save</button>
</div>
</div>
);
}
}
function mapStateToProps({ ScatterPlotReducer, D3ParserReducer }) {
return { ScatterPlotReducer, D3ParserReducer }
}
function mapDispatchToProps(dispatch) {
return bindActionCreators({ getScatterPlot, updateWidth, getD3ParserObj, updateValue }, dispatch);
}
// function mapDispatchToProps(dispatch) {
// return {
// actions: bindActionCreators(Object.assign({}, getScatterPlot, updateWidth), dispatch)
// }
// }
//example from react-redux api
// function mapDispatchToProps(dispatch) {
// return {
// actions: bindActionCreators(Object.assign({}, todoActionCreators, counterActionCreators), dispatch)
// }
// }
export default connect(mapStateToProps, mapDispatchToProps)(AttributesPanel);
|
src/svg-icons/device/bluetooth.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBluetooth = (props) => (
<SvgIcon {...props}>
<path d="M17.71 7.71L12 2h-1v7.59L6.41 5 5 6.41 10.59 12 5 17.59 6.41 19 11 14.41V22h1l5.71-5.71-4.3-4.29 4.3-4.29zM13 5.83l1.88 1.88L13 9.59V5.83zm1.88 10.46L13 18.17v-3.76l1.88 1.88z"/>
</SvgIcon>
);
DeviceBluetooth = pure(DeviceBluetooth);
DeviceBluetooth.displayName = 'DeviceBluetooth';
DeviceBluetooth.muiName = 'SvgIcon';
export default DeviceBluetooth;
|
node_modules/react-router/es6/RoutingContext.js | cylcharles/webpack | 'use strict';
var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } }
function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import invariant from 'invariant';
import React, { Component } from 'react';
import { isReactChildren } from './RouteUtils';
import getRouteParams from './getRouteParams';
var _React$PropTypes = React.PropTypes;
var array = _React$PropTypes.array;
var func = _React$PropTypes.func;
var object = _React$PropTypes.object;
/**
* A <RoutingContext> renders the component tree for a given router state
* and sets the history object and the current location in context.
*/
var RoutingContext = (function (_Component) {
_inherits(RoutingContext, _Component);
function RoutingContext() {
_classCallCheck(this, RoutingContext);
_Component.apply(this, arguments);
}
RoutingContext.prototype.getChildContext = function getChildContext() {
var _props = this.props;
var history = _props.history;
var location = _props.location;
return { history: history, location: location };
};
RoutingContext.prototype.createElement = function createElement(component, props) {
return component == null ? null : this.props.createElement(component, props);
};
RoutingContext.prototype.render = function render() {
var _this = this;
var _props2 = this.props;
var history = _props2.history;
var location = _props2.location;
var routes = _props2.routes;
var params = _props2.params;
var components = _props2.components;
var element = null;
if (components) {
element = components.reduceRight(function (element, components, index) {
if (components == null) return element; // Don't create new children; use the grandchildren.
var route = routes[index];
var routeParams = getRouteParams(route, params);
var props = {
history: history,
location: location,
params: params,
route: route,
routeParams: routeParams,
routes: routes
};
if (isReactChildren(element)) {
props.children = element;
} else if (element) {
for (var prop in element) {
if (element.hasOwnProperty(prop)) props[prop] = element[prop];
}
}
if (typeof components === 'object') {
var elements = {};
for (var key in components) {
if (components.hasOwnProperty(key)) {
// Pass through the key as a prop to createElement to allow
// custom createElement functions to know which named component
// they're rendering, for e.g. matching up to fetched data.
elements[key] = _this.createElement(components[key], _extends({
key: key }, props));
}
}
return elements;
}
return _this.createElement(components, props);
}, element);
}
!(element === null || element === false || React.isValidElement(element)) ? process.env.NODE_ENV !== 'production' ? invariant(false, 'The root route must render a single element') : invariant(false) : undefined;
return element;
};
return RoutingContext;
})(Component);
RoutingContext.propTypes = {
history: object.isRequired,
createElement: func.isRequired,
location: object.isRequired,
routes: array.isRequired,
params: object.isRequired,
components: array.isRequired
};
RoutingContext.defaultProps = {
createElement: React.createElement
};
RoutingContext.childContextTypes = {
history: object.isRequired,
location: object.isRequired
};
export default RoutingContext; |
src/Parser/Monk/Mistweaver/Modules/Items/T20_4set.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import Combatants from 'Parser/Core/Modules/Combatants';
import Analyzer from 'Parser/Core/Analyzer';
import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing';
import ItemHealingDone from 'Main/ItemHealingDone';
import { ABILITIES_AFFECTED_BY_HEALING_INCREASES } from '../../Constants';
const XUENS_BATTLEGEAR_4_PIECE_BUFF_HEALING_INCREASE = 0.12;
class T20_4set extends Analyzer {
static dependencies = {
combatants: Combatants,
};
healing = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.XUENS_BATTLEGEAR_4_PIECE_BUFF.id);
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if (ABILITIES_AFFECTED_BY_HEALING_INCREASES.indexOf(spellId) === -1) {
return;
}
if (!this.combatants.selected.hasBuff(SPELLS.DANCE_OF_MISTS.id, event.timestamp)) {
return;
}
this.healing += calculateEffectiveHealing(event, XUENS_BATTLEGEAR_4_PIECE_BUFF_HEALING_INCREASE);
}
item() {
return {
id: `spell-${SPELLS.XUENS_BATTLEGEAR_4_PIECE_BUFF.id}`,
icon: <SpellIcon id={SPELLS.XUENS_BATTLEGEAR_4_PIECE_BUFF.id} />,
title: <SpellLink id={SPELLS.XUENS_BATTLEGEAR_4_PIECE_BUFF.id} />,
result: (
<dfn data-tip={`The actual effective healing contributed by the Tier 20 4 piece effect.<br />Buff Uptime: ${((this.combatants.selected.getBuffUptime(SPELLS.DANCE_OF_MISTS.id) / this.owner.fightDuration) * 100).toFixed(2)}%`}>
<ItemHealingDone amount={this.healing} />
</dfn>
),
};
}
}
export default T20_4set;
|
src/index.js | millerman86/CouponProject | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
import {Provider} from 'react-redux';
import {createStore} from 'redux';
import rootReducer from './Redux';
import App from './App.js'
// This accepts the reducer and initialState as two arguments
let store = createStore(rootReducer);
injectTapEventPlugin();
ReactDOM.render(
<MuiThemeProvider>
<Provider store={store}>
<App />
</Provider>
</MuiThemeProvider>,
document.getElementById('root')
);
// const unsubscribe = store.subscribe(() => console.log(store.getState()));
//
//
//
// console.log(store.getState());
|
src/components/todoFooter.js | mweststrate/mobservable-react-todomvc | import React from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import {action} from 'mobx';
import {pluralize} from '../utils';
import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from '../constants';
@observer
export default class TodoFooter extends React.Component {
render() {
const todoStore = this.props.todoStore;
if (!todoStore.activeTodoCount && !todoStore.completedCount)
return null;
const activeTodoWord = pluralize(todoStore.activeTodoCount, 'item');
return (
<footer className="footer">
<span className="todo-count">
<strong>{todoStore.activeTodoCount}</strong> {activeTodoWord} left
</span>
<ul className="filters">
{this.renderFilterLink(ALL_TODOS, "", "All")}
{this.renderFilterLink(ACTIVE_TODOS, "active", "Active")}
{this.renderFilterLink(COMPLETED_TODOS, "completed", "Completed")}
</ul>
{ todoStore.completedCount === 0
? null
: <button
className="clear-completed"
onClick={this.clearCompleted}>
Clear completed
</button>
}
</footer>
);
}
renderFilterLink(filterName, url, caption) {
return (<li>
<a href={"#/" + url}
className={filterName === this.props.viewStore.todoFilter ? "selected" : ""}>
{caption}
</a>
{' '}
</li>)
}
@action
clearCompleted = () => {
this.props.todoStore.clearCompleted();
};
}
TodoFooter.propTypes = {
viewStore: PropTypes.object.isRequired,
todoStore: PropTypes.object.isRequired
}
|
javascript/react-skill-verification-test/react-top-and-newest-articles/src/index.js | rootulp/hackerrank | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
const ARTICLES = [
{
title: "A message to our customers",
upvotes: 12,
date: "2020-01-24",
},
{
title: "Alphabet earnings",
upvotes: 22,
date: "2019-11-23",
},
{
title: "Artificial Mountains",
upvotes: 2,
date: "2019-11-22",
},
{
title: "Scaling to 100k Users",
upvotes: 72,
date: "2019-01-21",
},
{
title: "the Emu War",
upvotes: 24,
date: "2019-10-21",
},
{
title: "What's SAP",
upvotes: 1,
date: "2019-11-21",
},
{
title: "Simple text editor has 15k monthly users",
upvotes: 7,
date: "2010-12-31",
},
];
ReactDOM.render(<App articles={ARTICLES} />, document.getElementById('root'));
registerServiceWorker();
|
src/containers/ServiceBookingCaledarPage.js | onlinebooking/booking-frontend | import React from 'react';
import { connect } from 'react-redux';
import moment from 'moment';
import BookingCalendar from '../components/BookingCalendar';
import ErrorAlert from '../components/ErrorAlert';
import BookingSteps from '../components/BookingSteps';
import { getBookingAvailblesCalendarDates } from '../selectors/calendar';
import { push } from 'react-router-redux';
import { loadBookingRanges, setBookingCalendarDate } from '../actions/booking';
function loadData(props) {
const calendarDate = moment(props.location.query.date, 'YYYY-MM-DD', true);
if (calendarDate.isValid()) {
props.setBookingCalendarDate(calendarDate.format('YYYY-MM-DD'));
}
props.loadBookingRanges();
}
class ServiceBookingCaledarPage extends React.Component {
componentWillMount() {
loadData(this.props);
}
componentWillReceiveProps(nextProps) {
if (nextProps.params.shopDomainName !== this.props.params.shopDomainName ||
nextProps.params.serviceId !== this.props.params.serviceId ||
nextProps.location.query.date !== this.props.location.query.date) {
loadData(nextProps);
}
}
constructor(props) {
super(props);
this.onEventClick = this.onEventClick.bind(this);
this.onCalendarChange = this.onCalendarChange.bind(this);
}
onCalendarChange(calendarDate) {
const date = calendarDate.format('YYYY-MM-DD');
if (date != this.props.calendarDate) {
// Set in store and update location
this.props.setBookingCalendarDate(date, true);
}
}
onEventClick(event) {
// Go to booking date page
const { shop, service, push } = this.props;
const bookingDate = event.date.format('YYYY-MM-DD');
push(`/${shop.domain_name}/booking/${service.id}/at/${bookingDate}`);
}
render() {
return (
<div className="container-fluid">
<BookingSteps step={1} />
<div className="panel panel-primary booking-calendar-container">
<div className="panel-heading panel-heading-calendar">
Seleziona una data {this.renderLoading()}
</div>
<div className="panel-body panel-body-calendar">
{this.renderError()}
<BookingCalendar
events={this.props.availableDates}
calendarDate={this.props.calendarDate}
onEventClick={this.onEventClick}
onCalendarChange={this.onCalendarChange} />
</div>
</div>
</div>
);
}
renderLoading() {
const visibility = this.props.loading ? 'visible' : 'hidden';
return <div className="booking-calendar-loader" style={{visibility}}>Loading...</div>;
}
renderError() {
const { error } = this.props;
if (error) {
return <ErrorAlert
title={"Errore nel recupero dei giorni disponibili, riprova più tardi."}
{...error}
/>;
}
}
}
function mapStateToProps(state) {
const { calendarDate, ranges } = state.booking;
return {
calendarDate,
loading: ranges.isFetching,
error: ranges.error,
availableDates: getBookingAvailblesCalendarDates(state),
};
}
export default connect(mapStateToProps, {
setBookingCalendarDate,
loadBookingRanges,
push,
})(ServiceBookingCaledarPage);
|
node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | LJ-Solutions/lj-tools2 | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
examples/todomvc/containers/TodoApp.js | jackielii/redux-devtools | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/TodoActions';
class TodoApp extends Component {
render() {
const { todos, actions } = this.props;
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
function mapState(state) {
return {
todos: state.todos
};
}
function mapDispatch(dispatch) {
return {
actions: bindActionCreators(TodoActions, dispatch)
};
}
export default connect(mapState, mapDispatch)(TodoApp);
|
frontend/jqwidgets/jqwidgets-react/react_jqxexpander.js | liamray/nexl-js | /*
jQWidgets v5.7.2 (2018-Apr)
Copyright (c) 2011-2018 jQWidgets.
License: https://jqwidgets.com/license/
*/
import React from 'react';
const JQXLite = window.JQXLite;
export const jqx = window.jqx;
export default class JqxExpander extends React.Component {
componentDidMount() {
let options = this.manageAttributes();
this.createComponent(options);
};
manageAttributes() {
let properties = ['animationType','arrowPosition','collapseAnimationDuration','disabled','expanded','expandAnimationDuration','height','headerPosition','initContent','rtl','showArrow','theme','toggleMode','width'];
let options = {};
for(let item in this.props) {
if(item === 'settings') {
for(let itemTwo in this.props[item]) {
options[itemTwo] = this.props[item][itemTwo];
}
} else {
if(properties.indexOf(item) !== -1) {
options[item] = this.props[item];
}
}
}
return options;
};
createComponent(options) {
if(!this.style) {
for (let style in this.props.style) {
JQXLite(this.componentSelector).css(style, this.props.style[style]);
}
}
if(this.props.className !== undefined) {
let classes = this.props.className.split(' ');
for (let i = 0; i < classes.length; i++ ) {
JQXLite(this.componentSelector).addClass(classes[i]);
}
}
if(!this.template) {
JQXLite(this.componentSelector).html(this.props.template);
}
JQXLite(this.componentSelector).jqxExpander(options);
};
setOptions(options) {
JQXLite(this.componentSelector).jqxExpander('setOptions', options);
};
getOptions() {
if(arguments.length === 0) {
throw Error('At least one argument expected in getOptions()!');
}
let resultToReturn = {};
for(let i = 0; i < arguments.length; i++) {
resultToReturn[arguments[i]] = JQXLite(this.componentSelector).jqxExpander(arguments[i]);
}
return resultToReturn;
};
on(name,callbackFn) {
JQXLite(this.componentSelector).on(name,callbackFn);
};
off(name) {
JQXLite(this.componentSelector).off(name);
};
animationType(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('animationType', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('animationType');
}
};
arrowPosition(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('arrowPosition', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('arrowPosition');
}
};
collapseAnimationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('collapseAnimationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('collapseAnimationDuration');
}
};
disabled(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('disabled', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('disabled');
}
};
expanded(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('expanded', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('expanded');
}
};
expandAnimationDuration(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('expandAnimationDuration', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('expandAnimationDuration');
}
};
height(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('height', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('height');
}
};
headerPosition(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('headerPosition', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('headerPosition');
}
};
initContent(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('initContent', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('initContent');
}
};
rtl(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('rtl', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('rtl');
}
};
showArrow(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('showArrow', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('showArrow');
}
};
theme(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('theme', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('theme');
}
};
toggleMode(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('toggleMode', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('toggleMode');
}
};
width(arg) {
if (arg !== undefined) {
JQXLite(this.componentSelector).jqxExpander('width', arg)
} else {
return JQXLite(this.componentSelector).jqxExpander('width');
}
};
collapse() {
JQXLite(this.componentSelector).jqxExpander('collapse');
};
disable() {
JQXLite(this.componentSelector).jqxExpander('disable');
};
destroy() {
JQXLite(this.componentSelector).jqxExpander('destroy');
};
enable() {
JQXLite(this.componentSelector).jqxExpander('enable');
};
expand() {
JQXLite(this.componentSelector).jqxExpander('expand');
};
focus() {
JQXLite(this.componentSelector).jqxExpander('focus');
};
getContent() {
return JQXLite(this.componentSelector).jqxExpander('getContent');
};
getHeaderContent() {
return JQXLite(this.componentSelector).jqxExpander('getHeaderContent');
};
invalidate() {
JQXLite(this.componentSelector).jqxExpander('invalidate');
};
refresh() {
JQXLite(this.componentSelector).jqxExpander('refresh');
};
performRender() {
JQXLite(this.componentSelector).jqxExpander('render');
};
setHeaderContent(headerContent) {
JQXLite(this.componentSelector).jqxExpander('setHeaderContent', headerContent);
};
setContent(content) {
JQXLite(this.componentSelector).jqxExpander('setContent', content);
};
render() {
let id = 'jqxExpander' + JQXLite.generateID();
this.componentSelector = '#' + id;
return (
<div id={id}>{this.props.value}{this.props.children}</div>
)
};
};
|
Example/index.ios.js | SudoPlz/react-native-amplitude-analytics | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import Amplitude from 'react-native-amplitude-analytics';
export default class Example extends Component {
render() {
const trackSessionEvents = true; // https://amplitude.zendesk.com/hc/en-us/articles/115003970027#tracking-events
const amplitude = new Amplitude("Your Amplitude ID goes here", trackSessionEvents);
alert(`amplitude: ${JSON.stringify(amplitude)}`)
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
Hello Amplitute
</Text>
<Text style={styles.instructions}>
Your analytics should now be up and running
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('Example', () => Example);
|
share/components/Common/ErrorMessages.js | caojs/password-manager-server | import React from 'react';
import FaExclamation from 'react-icons/lib/fa/exclamation-triangle';
import { injectProps } from '../../helpers/decorators';
import style from './errorMessages.css';
export default class ErrorMessages extends React.Component {
@injectProps
render({ errors }) {
return (
<ul className={style.main}>
<li className={style.icon}>
<FaExclamation className="icon"/>
</li>
{errors.map((e, index) => (
<li className={style.item} key={index}>{e.get('message')}</li>
))}
</ul>
);
}
}
|
test/test_helper.js | merry75/ReduxBookLibrary | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/components/app.js | codingkapoor/technology-jukebox | import React, { Component } from 'react';
import _ from 'lodash';
import UltimatePagination from 'react-ultimate-pagination-bootstrap-4';
import Projects from '../../projects.json';
import SearchBar from './search-bar';
import ProjectList from './project-list';
export default class App extends Component {
constructor(props) {
super(props);
this.technologiesSearchPool = getTechnologiesSearchPool();
const projectsPerPage = 10;
const currentPage = 1;
const projects = Projects;
const totalPages = Math.ceil(Projects.length / projectsPerPage);
const currentProjects = getCurrentProjects(currentPage, projectsPerPage, projects);
this.state = {
projects,
currentProjects,
projectsPerPage,
currentPage,
totalPages,
boundaryPagesRange: 1,
siblingPagesRange: 1,
hidePreviousAndNextPageLinks: false,
hideFirstAndLastPageLinks: true,
hideEllipsis: false
};
}
projectSearch(term) {
let filteredProjects = Projects;
if(term) {
filteredProjects = _.filter(Projects, (o) => { return o.stack.map(_.toUpper).includes(_.toUpper(term)) });
}
if(filteredProjects.length) {
const { projectsPerPage } = this.state;
const currentPage = 1;
const currentProjects = getCurrentProjects(currentPage, projectsPerPage, filteredProjects);
const totalPages = Math.ceil(filteredProjects.length / projectsPerPage);
this.setState({
projects: filteredProjects,
totalPages,
currentProjects,
currentPage
});
}
}
onPageChangeFromPagination(newPage) {
const { projects, projectsPerPage } = this.state;
const currentProjects = getCurrentProjects(newPage, projectsPerPage, projects);
this.setState({
currentPage: newPage,
currentProjects
});
}
render() {
return (
<div>
<h3 className = "jukebox-header col-lg-12">Technology Jukebox</h3>
<SearchBar onSearchTermChange = { this.projectSearch.bind(this) } technologiesSearchPool = { this.technologiesSearchPool } />
<ProjectList projects = { this.state.currentProjects } currentPage = { this.state.currentPage }/>
<div className = "col-lg-offset-5">
<UltimatePagination
currentPage = { this.state.currentPage }
totalPages = { this.state.totalPages }
boundaryPagesRange = { this.state.boundaryPagesRange }
siblingPagesRange = { this.state.siblingPagesRange }
hidePreviousAndNextPageLinks = { this.state.hidePreviousAndNextPageLinks }
hideFirstAndLastPageLinks = { this.state.hideFirstAndLastPageLinks }
hideEllipsis = { this.state.hideEllipsis }
onChange = { this.onPageChangeFromPagination.bind(this) }
/>
</div>
</div>
);
}
}
function getTechnologiesSearchPool() {
var arr = Projects.map(x => { return x.stack });
var flattenedArr = Array.from(new Set(_.flatten(arr)));
return flattenedArr.map(x => { return { "name": x } });
}
function getCurrentProjects(currentPage, projectsPerPage, projects) {
const indexOfLastProject = currentPage * projectsPerPage;
const indexOfFirstProject = indexOfLastProject - projectsPerPage;
const currentProjects = projects.slice(indexOfFirstProject, indexOfLastProject);
return currentProjects;
}
|
actor-apps/app-web/src/app/components/activity/GroupProfile.react.js | fengchenlianlian/actor-platform | import React from 'react';
import DialogActionCreators from 'actions/DialogActionCreators';
import LoginStore from 'stores/LoginStore';
import PeerStore from 'stores/PeerStore';
import DialogStore from 'stores/DialogStore';
import GroupStore from 'stores/GroupStore';
import InviteUserActions from 'actions/InviteUserActions';
import AvatarItem from 'components/common/AvatarItem.react';
import InviteUser from 'components/modals/InviteUser.react';
import GroupProfileMembers from 'components/activity/GroupProfileMembers.react';
const getStateFromStores = (groupId) => {
const thisPeer = PeerStore.getGroupPeer(groupId);
return {
thisPeer: thisPeer,
isNotificationsEnabled: DialogStore.isNotificationsEnabled(thisPeer),
integrationToken: GroupStore.getIntegrationToken()
};
};
class GroupProfile extends React.Component {
static propTypes = {
group: React.PropTypes.object.isRequired
};
componentWillUnmount() {
DialogStore.removeNotificationsListener(this.onChange);
GroupStore.addChangeListener(this.onChange);
}
componentWillReceiveProps(newProps) {
this.setState(getStateFromStores(newProps.group.id));
}
constructor(props) {
super(props);
DialogStore.addNotificationsListener(this.onChange);
GroupStore.addChangeListener(this.onChange);
this.state = getStateFromStores(props.group.id);
}
onAddMemberClick = group => {
InviteUserActions.modalOpen(group);
}
onLeaveGroupClick = groupId => {
DialogActionCreators.leaveGroup(groupId);
}
onNotificationChange = event => {
DialogActionCreators.changeNotificationsEnabled(this.state.thisPeer, event.target.checked);
}
onChange = () => {
this.setState(getStateFromStores(this.props.group.id));
};
render() {
const group = this.props.group;
const myId = LoginStore.getMyId();
const isNotificationsEnabled = this.state.isNotificationsEnabled;
const integrationToken = this.state.integrationToken;
let memberArea;
let adminControls;
if (group.adminId === myId) {
adminControls = (
<li className="profile__list__item">
<a className="red">Delete group</a>
</li>
);
}
if (DialogStore.isGroupMember(group)) {
memberArea = (
<div>
<div className="notifications">
<label htmlFor="notifications">Enable Notifications</label>
<div className="switch pull-right">
<input checked={isNotificationsEnabled} id="notifications" onChange={this.onNotificationChange.bind(this)} type="checkbox"/>
<label htmlFor="notifications"></label>
</div>
</div>
<GroupProfileMembers groupId={group.id} members={group.members}/>
<ul className="profile__list profile__list--controls">
<li className="profile__list__item">
<a className="link__blue" onClick={this.onAddMemberClick.bind(this, group)}>Add member</a>
</li>
<li className="profile__list__item">
<a className="link__red" onClick={this.onLeaveGroupClick.bind(this, group.id)}>Leave group</a>
</li>
{adminControls}
</ul>
<InviteUser/>
</div>
);
}
return (
<div className="activity__body profile">
<div className="profile__name">
<AvatarItem image={group.bigAvatar}
placeholder={group.placeholder}
size="medium"
title={group.name}/>
<h3>{group.name}</h3>
</div>
{memberArea}
{integrationToken}
</div>
);
}
}
export default GroupProfile;
|
src/client/main.js | alihalabyah/hacker-menu | import React from 'react'
import StoryBox from './story_box.js'
React.render(
<StoryBox />,
document.getElementById('container')
)
|
src/mui/input/ReferenceInput.js | RestUI/rest-ui | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import debounce from 'lodash.debounce';
import Labeled from './Labeled';
import { crudGetOne as crudGetOneAction, crudGetMatching as crudGetMatchingAction } from '../../redux/actions/dataActions';
import { getPossibleReferences } from '../../redux/reducer/references/possibleValues';
const referenceSource = (resource, source) => `${resource}@${source}`;
const noFilter = () => true;
/**
* An Input component for choosing a reference record. Useful for foreign keys.
*
* This component fetches the possible values in the reference resource
* (using the `CRUD_GET_MATCHING` REST method), then delegates rendering
* to a subcomponent, to which it passes the possible choices
* as the `choices` attribute.
*
* Use it with a selector component as child, like `<AutocompleteInput>`,
* `<SelectInput>`, or `<RadioButtonGroupInput>`.
*
* @example
* export const CommentEdit = (props) => (
* <Edit {...props}>
* <SimpleForm>
* <ReferenceInput label="Post" source="post_id" reference="posts">
* <AutocompleteInput optionText="title" />
* </ReferenceInput>
* </SimpleForm>
* </Edit>
* );
*
* @example
* export const CommentEdit = (props) => (
* <Edit {...props}>
* <SimpleForm>
* <ReferenceInput label="Post" source="post_id" reference="posts">
* <SelectInput optionText="title" />
* </ReferenceInput>
* </SimpleForm>
* </Edit>
* );
*
* By default, restricts the possible values to 25. You can extend this limit
* by setting the `perPage` prop.
*
* @example
* <ReferenceInput
* source="post_id"
* reference="posts"
* perPage={100}>
* <SelectInput optionText="title" />
* </ReferenceInput>
*
* By default, orders the possible values by id desc. You can change this order
* by setting the `sort` prop (an object with `field` and `order` properties).
*
* @example
* <ReferenceInput
* source="post_id"
* reference="posts"
* sort={{ field: 'title', order: 'ASC' }}>
* <SelectInput optionText="title" />
* </ReferenceInput>
*
* Also, you can filter the query used to populate the possible values. Use the
* `filter` prop for that.
*
* @example
* <ReferenceInput
* source="post_id"
* reference="posts"
* filter={{ is_published: true }}>
* <SelectInput optionText="title" />
* </ReferenceInput>
*
* The enclosed component may filter results. ReferenceInput passes a `setFilter`
* function as prop to its child component. It uses the value to create a filter
* for the query - by default { q: [searchText] }. You can customize the mapping
* searchText => searchQuery by setting a custom `filterToQuery` function prop:
*
* @example
* <ReferenceInput
* source="post_id"
* reference="posts"
* filterToQuery={searchText => ({ title: searchText })}>
* <SelectInput optionText="title" />
* </ReferenceInput>
*/
export class ReferenceInput extends Component {
constructor(props) {
super(props);
const { perPage, sort, filter } = props;
// stored as a property rather than state because we don't want redraw of async updates
this.params = { pagination: { page: 1, perPage }, sort, filter };
this.debouncedSetFilter = debounce(this.setFilter.bind(this), 500);
}
componentDidMount() {
this.fetchReferenceAndOptions();
}
componentWillReceiveProps(nextProps) {
if (this.props.record.id !== nextProps.record.id) {
this.fetchReferenceAndOptions(nextProps);
}
}
setFilter = (filter) => {
if (filter !== this.params.filter) {
this.params.filter = this.props.filterToQuery(filter);
this.fetchReferenceAndOptions();
}
}
setPagination = (pagination) => {
if (pagination !== this.param.pagination) {
this.param.pagination = pagination;
this.fetchReferenceAndOptions();
}
}
setSort = (sort) => {
if (sort !== this.params.sort) {
this.params.sort = sort;
this.fetchReferenceAndOptions();
}
}
fetchReferenceAndOptions({ input, reference, source, resource } = this.props) {
const { pagination, sort, filter } = this.params;
const id = input.value;
if (id) {
this.props.crudGetOne(reference, id, null, false);
}
this.props.crudGetMatching(reference, referenceSource(resource, source), pagination, sort, filter);
}
render() {
const { input, resource, label, source, reference, referenceRecord, allowEmpty, matchingReferences, basePath, onChange, children, meta } = this.props;
if (!referenceRecord && !allowEmpty) {
return <Labeled
label={typeof label === 'undefined' ? `resources.${resource}.fields.${source}` : label}
source={source}
resource={resource}
/>;
}
return React.cloneElement(children, {
allowEmpty,
input,
label: typeof label === 'undefined' ? `resources.${resource}.fields.${source}` : label,
resource,
meta,
source,
choices: matchingReferences,
basePath,
onChange,
filter: noFilter, // for AutocompleteInput
setFilter: this.debouncedSetFilter,
setPagination: this.setPagination,
setSort: this.setSort,
});
}
}
ReferenceInput.propTypes = {
addField: PropTypes.bool.isRequired,
allowEmpty: PropTypes.bool.isRequired,
basePath: PropTypes.string,
children: PropTypes.element.isRequired,
crudGetMatching: PropTypes.func.isRequired,
crudGetOne: PropTypes.func.isRequired,
filter: PropTypes.object,
filterToQuery: PropTypes.func.isRequired,
input: PropTypes.object.isRequired,
label: PropTypes.string,
matchingReferences: PropTypes.array,
meta: PropTypes.object,
onChange: PropTypes.func,
perPage: PropTypes.number,
reference: PropTypes.string.isRequired,
referenceRecord: PropTypes.object,
resource: PropTypes.string.isRequired,
sort: PropTypes.shape({
field: PropTypes.string,
order: PropTypes.oneOf(['ASC', 'DESC']),
}),
source: PropTypes.string,
};
ReferenceInput.defaultProps = {
allowEmpty: false,
filter: {},
filterToQuery: searchText => ({ q: searchText }),
matchingReferences: [],
perPage: 25,
sort: { field: 'id', order: 'DESC' },
referenceRecord: null,
};
function mapStateToProps(state, props) {
const referenceId = props.input.value;
return {
referenceRecord: state.admin[props.reference].data[referenceId],
matchingReferences: getPossibleReferences(state, referenceSource(props.resource, props.source), props.reference, referenceId),
};
}
const ConnectedReferenceInput = connect(mapStateToProps, {
crudGetOne: crudGetOneAction,
crudGetMatching: crudGetMatchingAction,
})(ReferenceInput);
ConnectedReferenceInput.defaultProps = {
addField: true,
};
export default ConnectedReferenceInput;
|
src/components/Help/InfoBanner/index.js | ProteinsWebTeam/interpro7-client | import React from 'react';
import T from 'prop-types';
import { foundationPartial } from 'styles/foundation';
import style from './style.css';
import ipro from 'styles/interpro-new.css';
const f = foundationPartial(style, ipro);
const infoTopics = {
InterProScan: {
text:
'InterProScan is a sequence analysis application (nucleotide and protein sequences) that combines different protein signature recognition methods into one resource.',
image: 'image-tool-ipscan',
},
IDA: {
text:
'The InterPro Domain Architecture (IDA) tool allows you to search the InterPro database with a particular set of domains, and returns all of the domain architectures and associated proteins that match the query.',
image: 'image-tool-ida',
},
TextSearch: {
text:
'InterPro text search is powered by the EBI Search, a scalable text search engine that provides easy and uniform access to the biological data resources hosted at the European Bioinformatics Institute (EMBL-EBI).',
image: 'image-tool-textsearch',
},
default: {},
};
export const InfoBanner = ({ topic } /*: {topic: string} */) => {
const current = infoTopics[topic] || infoTopics.default;
return (
<div className={f('help-banner', 'flex-card')}>
<div className={f('card-image', current.image)}>
<div className={f('card-tag', 'tag-tool')}>{topic}</div>
</div>
<div className={f('card-content')}>
<div className={f('card-description')}>{current.text}</div>
</div>
</div>
);
};
InfoBanner.propTypes = {
topic: T.string,
};
export default React.memo(InfoBanner);
|
node_modules/eslint-config-airbnb/test/test-react-order.js | DigixGlobal/truffle-lightwallet-provider | import test from 'tape';
import { CLIEngine } from 'eslint';
import eslintrc from '../';
import reactRules from '../rules/react';
import reactA11yRules from '../rules/react-a11y';
const cli = new CLIEngine({
useEslintrc: false,
baseConfig: eslintrc,
rules: {
// It is okay to import devDependencies in tests.
'import/no-extraneous-dependencies': [2, { devDependencies: true }],
},
});
function lint(text) {
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
const linter = cli.executeOnText(text);
return linter.results[0];
}
function wrapComponent(body) {
return `
import React from 'react';
export default class MyComponent extends React.Component {
/* eslint no-empty-function: 0, class-methods-use-this: 0 */
${body}
}
`;
}
test('validate react prop order', (t) => {
t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => {
t.plan(2);
t.deepEqual(reactRules.plugins, ['react']);
t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']);
});
t.test('passes a good component', (t) => {
t.plan(3);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
someMethod() {}
renderDogs() {}
render() { return <div />; }`));
t.notOk(result.warningCount, 'no warnings');
t.notOk(result.errorCount, 'no errors');
t.deepEquals(result.messages, [], 'no messages in results');
});
t.test('order: when random method is first', (t) => {
t.plan(2);
const result = lint(wrapComponent(`
someMethod() {}
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
t.test('order: when random method after lifecycle methods', (t) => {
t.plan(2);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
someMethod() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
});
|
src/components/antd/badge/index.js | hyd378008136/olymComponents | var __rest = (this && this.__rest) || function (s, e) {
var t = {};
for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
t[p] = s[p];
if (s != null && typeof Object.getOwnPropertySymbols === "function")
for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) if (e.indexOf(p[i]) < 0)
t[p[i]] = s[p[i]];
return t;
};
import React from 'react';
import PropTypes from 'prop-types';
import Animate from 'rc-animate';
import ScrollNumber from './ScrollNumber';
import classNames from 'classnames';
import warning from '../_util/warning';
export default class Badge extends React.Component {
render() {
const _a = this.props, { count, showZero, prefixCls, scrollNumberPrefixCls, overflowCount, className, style, children, dot, status, text } = _a, restProps = __rest(_a, ["count", "showZero", "prefixCls", "scrollNumberPrefixCls", "overflowCount", "className", "style", "children", "dot", "status", "text"]);
const isDot = dot || status;
let displayCount = count > overflowCount ? `${overflowCount}+` : count;
// dot mode don't need count
if (isDot) {
displayCount = '';
}
const isZero = displayCount === '0' || displayCount === 0;
const isEmpty = displayCount === null || displayCount === undefined || displayCount === '';
const hidden = (isEmpty || (isZero && !showZero)) && !isDot;
const scrollNumberCls = classNames({
[`${prefixCls}-dot`]: isDot,
[`${prefixCls}-count`]: !isDot,
});
const badgeCls = classNames(className, prefixCls, {
[`${prefixCls}-status`]: !!status,
[`${prefixCls}-not-a-wrapper`]: !children,
});
warning(!(children && status), '`Badge[children]` and `Badge[status]` cannot be used at the same time.');
// <Badge status="success" />
if (!children && status) {
const statusCls = classNames({
[`${prefixCls}-status-dot`]: !!status,
[`${prefixCls}-status-${status}`]: true,
});
return (React.createElement("span", { className: badgeCls },
React.createElement("span", { className: statusCls }),
React.createElement("span", { className: `${prefixCls}-status-text` }, text)));
}
const scrollNumber = hidden ? null : (React.createElement(ScrollNumber, { prefixCls: scrollNumberPrefixCls, "data-show": !hidden, className: scrollNumberCls, count: displayCount, title: count, style: style }));
const statusText = (hidden || !text) ? null : (React.createElement("span", { className: `${prefixCls}-status-text` }, text));
return (React.createElement("span", Object.assign({}, restProps, { className: badgeCls }),
children,
React.createElement(Animate, { component: "", showProp: "data-show", transitionName: children ? `${prefixCls}-zoom` : '', transitionAppear: true }, scrollNumber),
statusText));
}
}
Badge.defaultProps = {
prefixCls: 'ant-badge',
scrollNumberPrefixCls: 'ant-scroll-number',
count: null,
showZero: false,
dot: false,
overflowCount: 99,
};
Badge.propTypes = {
count: PropTypes.oneOfType([
PropTypes.string,
PropTypes.number,
]),
showZero: PropTypes.bool,
dot: PropTypes.bool,
overflowCount: PropTypes.number,
};
|
src/svg-icons/image/adjust.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageAdjust = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.49 2 2 6.49 2 12s4.49 10 10 10 10-4.49 10-10S17.51 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8zm3-8c0 1.66-1.34 3-3 3s-3-1.34-3-3 1.34-3 3-3 3 1.34 3 3z"/>
</SvgIcon>
);
ImageAdjust = pure(ImageAdjust);
ImageAdjust.displayName = 'ImageAdjust';
ImageAdjust.muiName = 'SvgIcon';
export default ImageAdjust;
|
app/Routes.js | antoligy/healthbeacon | import React from 'react';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import App from './App';
import HomePage from './pages/HomePage';
import DashboardPage from './pages/DashboardPage';
import DetailsPage from './pages/DetailsPage';
import Login from './pages/Login';
import Logout from './pages/Logout';
import NotFoundPage from './pages/NotFoundPage';
import requireAuth from './utils/requireAuth';
export default (
<Router history={hashHistory}>
<Route path="/" component={App}>
<IndexRoute component={HomePage} />
<Route path="dashboard" component={DashboardPage} onEnter={requireAuth} />
<Route path="details" onEnter={requireAuth}>
<IndexRoute component={DetailsPage} />
</Route>
<Route path="login" component={Login} />
<Route path="logout" component={Logout} />
<Route path="*" component={NotFoundPage} />
</Route>
</Router>
);
|
components/NewRecord.js | praida/admin | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import '../styles/new-record.scss'
class NewRecord extends React.Component {
constructor (props) {
super(props)
this.addNewRecord = this.addNewRecord.bind(this)
this.changeOldField = this.changeOldField.bind(this)
this.changeNewField = this.changeNewField.bind(this)
this.removeNewRow = this.removeNewRow.bind(this)
}
addNewRecord (event) {
this.props.dispatch({
type: 'addNewRecord'
})
}
changeOldField (rowNb, field) {
return (event) => {
this.props.dispatch({
type: 'editNewRecordOldField',
rowNb,
field,
value: event.target.value
})
}
}
changeNewField (rowNb, idx) {
return (event) => {
this.props.dispatch({
type: 'editNewRecordNewField',
rowNb,
idx,
value: event.target.value
})
}
}
removeNewRow (idx) {
return () => {
this.props.dispatch({
type: 'removeNewRow',
idx
})
}
}
render () {
const nbFields = this.props.fields.length
const nbFieldsTotal = nbFields + this.props.newFields.length
const makeOldFields = (rowNb) => {
return this.props.fields.map((field, idx) => {
const classes = ['oldField']
const deleted = this.props.deletedFields[field._id]
if (deleted) {
classes.push('fieldDeleted')
}
return (
<td
key={field._id}
className={classes.join(' ')}
>
<input
type="text"
defaultValue={this.props.add[rowNb][field._id]}
onChange={this.changeOldField(rowNb, field)}
disabled={deleted}
/>
</td>
)
})
}
const makeNewFields = (rowNb) => {
const newFields = this.props.newFields.map((newField, idx) => {
const classes = ['newField']
const disabled = newField === ''
if (disabled) {
classes.push('disabled')
}
return (
<td
key={`newField_${idx}`}
className={classes.join(' ')}
>
<input
type="text"
defaultValue={this.props.add[rowNb] && this.props.add[rowNb].newFields && this.props.add[rowNb].newFields[idx]}
onChange={this.changeNewField(rowNb, idx)}
disabled={disabled}
/>
</td>
)
});
return newFields
}
const newRecords = this.props.add.map((item, idx) => {
const classes = ['newRecord']
if (item.isDeleted) {
classes.push('isDeleted')
}
return (
<tr
key={`newRecord_${idx}:${this.props.ts}`}
className={classes.join(' ')}
>
{makeOldFields(idx)}
{makeNewFields(idx)}
<td className="action-col">
<span className="action-icon" onClick={this.removeNewRow(idx)}>⊗</span>
</td>
</tr>
)
})
const recordAdder = nbFieldsTotal === 0
? null
: (
<tr>
<td
className="addNewRecordButton"
colSpan={nbFieldsTotal}
onClick={this.addNewRecord}
>
⊕
</td>
</tr>
)
return (
<tbody>
{newRecords}
{recordAdder}
</tbody>
)
}
}
NewRecord.propTypes = {
dispatch: PropTypes.func.isRequired,
fields: PropTypes.array.isRequired,
newFields: PropTypes.array.isRequired,
deletedFields: PropTypes.object.isRequired,
add: PropTypes.array.isRequired
}
module.exports = exports = connect()(NewRecord) |
rojak-ui-web/src/app/candidate/Candidate.js | pyk/rojak | import React from 'react'
import { connect } from 'react-redux'
import { fetchCandidate } from './actions'
import Card from '../kit/Card'
import SocialMedia from '../kit/SocialMedia'
class Candidate extends React.Component {
static propTypes = {
id: React.PropTypes.number.isRequired,
candidate: React.PropTypes.object.isRequired,
fetchCandidate: React.PropTypes.func.isRequired
}
componentWillMount () {
const { id, fetchCandidate } = this.props
fetchCandidate(id)
}
componentWillReceiveProps (nextProps) {
const { id, fetchCandidate } = nextProps
if (this.props.id !== id) {
fetchCandidate(id)
}
}
render () {
const { candidate } = this.props
return (
<div>
<h2>
{candidate.full_name} ({candidate.alias_name})
</h2>
<Card style={{ margin: '10px auto' }}>
<div className="uk-grid">
<div className="uk-width-1-3">
<img alt={candidate.alias_name} src={candidate.photo_url} />
</div>
<div className="uk-width-1-3">
<dl style={{ lineHeight: '26px' }}>
<dt>Nama lengkap</dt>
<dd>{candidate.full_name}</dd>
<dt>Tempat, tanggal lahir</dt>
<dd>{candidate.date_of_birth}, {candidate.place_of_birth}</dd>
<dt>Agama</dt>
<dd>{candidate.religion}</dd>
<dt>Website</dt>
<dd><a href={candidate.website_url} target="_blank">{candidate.website_url}</a></dd>
</dl>
</div>
<div className="uk-width-1-3">
<SocialMedia
instagram={candidate.instagram_username}
twitter={candidate.twitter_username}
facebook={candidate.fbpage_username}
style={{ float: 'right' }} />
</div>
</div>
</Card>
<br />
</div>
)
}
}
const mapStateProps = (state) => ({
candidate: state.candidates.candidate
})
export default connect(mapStateProps, { fetchCandidate })(Candidate)
|
src/svg-icons/navigation/expand-less.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationExpandLess = (props) => (
<SvgIcon {...props}>
<path d="M12 8l-6 6 1.41 1.41L12 10.83l4.59 4.58L18 14z"/>
</SvgIcon>
);
NavigationExpandLess = pure(NavigationExpandLess);
NavigationExpandLess.displayName = 'NavigationExpandLess';
NavigationExpandLess.muiName = 'SvgIcon';
export default NavigationExpandLess;
|
packages/ringcentral-widgets-docs/src/app/pages/Components/LocalePicker/Demo.js | ringcentral/ringcentral-js-widget | import React from 'react';
// eslint-disable-next-line
import LocalePicker from 'ringcentral-widgets/components/LocalePicker';
const props = {};
props.value = 'test string';
props.options = ['test string'];
props.onChange = () => null;
/**
* A example of `LocalePicker`
*/
const LocalePickerDemo = () => <LocalePicker {...props} />;
export default LocalePickerDemo;
|
staticfiles/js/components/Culprit/Culprit.a38d08dcbdb9.js | alemneh/negativity-purger | import React from 'react';
import styles from './Culprit.css';
const Culprit = ({ culprit }) => {
return (
<li className={styles.culprit}>
<div><img src={culprit.pic_url} /></div>
<div>
<h3>{ culprit.name }</h3>
<small><b>Negative tweets:</b> {culprit.number_of_tweets}</small>
<p>Tweets by { culprit.name } on average are { parseInt(-(culprit.polarity * 100)/culprit.number_of_tweets) }% negative.</p>
</div>
</li>
);
};
export default Culprit;
|
server.js | JigneshRaval/React_Webpack_Express_ES6 | // server.js
// Example of React.js + Express.js Server-side rendering ( Isomorphic JS Example )
// SERVER
//==================================================
import express from 'express';
const app = express();
// SETUP REACT
//==================================================
import React from 'react';
import {
renderToString
}
from 'react-dom/server';
import HelloWorld from './lib/src/test.jsx'
var ReactComponent = React.createFactory(HelloWorld);
// WEBPACK MIDDLEWARE ( Just to compile text.jsx in to browser understandable JS using babel, because browser can not understand ES6 and JSX syntex)
//==================================================
import webpackMiddleware from 'webpack-dev-middleware';
import webpack from 'webpack';
import config from './webpack.config.js';
const compiler = webpack(config);
//app.use(express.static(__dirname + 'build/public'));
app.use(webpackMiddleware(compiler));
// ROUTE
//==================================================
app.get('/', function response(req, res) {
var staticMarkup = renderToString(ReactComponent({ count: 7, phrase :"News Archive" })); // renderToString will render React code from test.jsx file to browser
res.send(staticMarkup);
//res.sendFile('index.html');
});
app.listen(3000); |
actor-apps/app-web/src/app/components/Login.react.js | gale320/actor-platform | import _ from 'lodash';
import React from 'react';
import classNames from 'classnames';
import { Styles, RaisedButton, TextField } from 'material-ui';
import { AuthSteps } from 'constants/ActorAppConstants';
import Banner from 'components/common/Banner.react';
import LoginActionCreators from 'actions/LoginActionCreators';
import LoginStore from 'stores/LoginStore';
import ActorTheme from 'constants/ActorTheme';
const ThemeManager = new Styles.ThemeManager();
let getStateFromStores = function () {
return ({
step: LoginStore.getStep(),
errors: LoginStore.getErrors(),
smsRequested: LoginStore.isSmsRequested(),
signupStarted: LoginStore.isSignupStarted(),
codeSent: false
});
};
class Login extends React.Component {
static contextTypes = {
router: React.PropTypes.func
};
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
componentWillUnmount() {
LoginStore.removeChangeListener(this.onChange);
}
componentDidMount() {
this.handleFocus();
}
componentDidUpdate() {
this.handleFocus();
}
constructor(props) {
super(props);
this.state = _.assign({
phone: '',
name: '',
code: ''
}, getStateFromStores());
ThemeManager.setTheme(ActorTheme);
if (LoginStore.isLoggedIn()) {
window.setTimeout(() => this.context.router.replaceWith('/'), 0);
} else {
LoginStore.addChangeListener(this.onChange);
}
}
onChange = () => {
this.setState(getStateFromStores());
}
onPhoneChange = event => {
this.setState({phone: event.target.value});
}
onCodeChange = event => {
this.setState({code: event.target.value});
}
onNameChange = event => {
this.setState({name: event.target.value});
}
onRequestSms = event => {
event.preventDefault();
LoginActionCreators.requestSms(this.state.phone);
}
onSendCode = event => {
event.preventDefault();
LoginActionCreators.sendCode(this.context.router, this.state.code);
}
onSignupRequested = event => {
event.preventDefault();
LoginActionCreators.sendSignup(this.context.router, this.state.name);
}
onWrongNumberClick = event => {
event.preventDefault();
LoginActionCreators.wrongNumberClick();
}
handleFocus = () => {
switch (this.state.step) {
case AuthSteps.PHONE_WAIT:
this.refs.phone.focus();
break;
case AuthSteps.CODE_WAIT:
this.refs.code.focus();
break;
case AuthSteps.SIGNUP_NAME_WAIT:
this.refs.name.focus();
break;
default:
return;
}
}
render() {
let requestFormClassName = classNames('login__form', 'login__form--request', {
'login__form--done': this.state.step > AuthSteps.PHONE_WAIT,
'login__form--active': this.state.step === AuthSteps.PHONE_WAIT
});
let checkFormClassName = classNames('login__form', 'login__form--check', {
'login__form--done': this.state.step > AuthSteps.CODE_WAIT,
'login__form--active': this.state.step === AuthSteps.CODE_WAIT
});
let signupFormClassName = classNames('login__form', 'login__form--signup', {
'login__form--active': this.state.step === AuthSteps.SIGNUP_NAME_WAIT
});
return (
<section className="login-new row center-xs middle-xs">
<Banner/>
<div className="login-new__welcome col-xs row center-xs middle-xs">
<img alt="Actor messenger"
className="logo"
src="assets/img/logo.png"
srcSet="assets/img/logo@2x.png 2x"/>
<article>
<h1 className="login-new__heading">Welcome to <strong>Actor</strong></h1>
<p>
Actor Messenger brings all your business network connections into one place,
makes it easily accessible wherever you go.
</p>
<p>
Our aim is to make your work easier, reduce your email amount,
make the business world closer by reducing time to find right contacts.
</p>
</article>
<footer>
<div className="pull-left">
Actor Messenger © 2015
</div>
<div className="pull-right">
<a href="//actor.im/ios">iPhone</a>
<a href="//actor.im/android">Android</a>
</div>
</footer>
</div>
<div className="login-new__form col-xs-6 col-md-4 row center-xs middle-xs">
<div>
<h1 className="login-new__heading">Sign in</h1>
<form className={requestFormClassName} onSubmit={this.onRequestSms}>
<TextField className="login__form__input"
disabled={this.state.step > AuthSteps.PHONE_WAIT}
errorText={this.state.errors.phone}
floatingLabelText="Phone number"
onChange={this.onPhoneChange}
ref="phone"
type="text"
value={this.state.phone}/>
<footer className="text-center">
<RaisedButton label="Request code" type="submit"/>
</footer>
</form>
<form className={checkFormClassName} onSubmit={this.onSendCode}>
<TextField className="login__form__input"
disabled={this.state.step > AuthSteps.CODE_WAIT}
errorText={this.state.errors.code}
floatingLabelText="Auth code"
onChange={this.onCodeChange}
ref="code"
type="text"
value={this.state.code}/>
<footer className="text-center">
<RaisedButton label="Check code" type="submit"/>
</footer>
</form>
<form className={signupFormClassName} onSubmit={this.onSignupRequested}>
<TextField className="login__form__input"
errorText={this.state.errors.signup}
floatingLabelText="Your name"
onChange={this.onNameChange}
ref="name"
type="text"
value={this.state.name}/>
<footer className="text-center">
<RaisedButton label="Sign up" type="submit"/>
</footer>
</form>
</div>
</div>
</section>
);
}
}
export default Login;
|
dva/dva-quickstart/src/routes/Products.js | imuntil/React | import React from 'react'
import { connect } from 'dva'
import ProductList from '../components/ProductList'
const Products = ({ dispatch, products }) => {
function handleDelete(id) {
dispatch({
type: 'products/delete',
payload: id
})
}
return (
<div>
<h2>List of Products</h2>
<ProductList onDelete={handleDelete} products={products} />
</div>
)
}
export default connect(({ products}) => ({
products
}))(Products)
|
src/svg-icons/communication/call-end.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationCallEnd = (props) => (
<SvgIcon {...props}>
<path d="M12 9c-1.6 0-3.15.25-4.6.72v3.1c0 .39-.23.74-.56.9-.98.49-1.87 1.12-2.66 1.85-.18.18-.43.28-.7.28-.28 0-.53-.11-.71-.29L.29 13.08c-.18-.17-.29-.42-.29-.7 0-.28.11-.53.29-.71C3.34 8.78 7.46 7 12 7s8.66 1.78 11.71 4.67c.18.18.29.43.29.71 0 .28-.11.53-.29.71l-2.48 2.48c-.18.18-.43.29-.71.29-.27 0-.52-.11-.7-.28-.79-.74-1.69-1.36-2.67-1.85-.33-.16-.56-.5-.56-.9v-3.1C15.15 9.25 13.6 9 12 9z"/>
</SvgIcon>
);
CommunicationCallEnd = pure(CommunicationCallEnd);
CommunicationCallEnd.displayName = 'CommunicationCallEnd';
CommunicationCallEnd.muiName = 'SvgIcon';
export default CommunicationCallEnd;
|
src/Parser/Shaman/Enhancement/Modules/ShamanCore/FuryOfAir.js | enragednuke/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage } from 'common/format';
import Analyzer from 'Parser/Core/Analyzer';
import Combatants from 'Parser/Core/Modules/Combatants';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
const FURY_OF_AIR_MAELSTROM_COST = SPELLS.FURY_OF_AIR_TALENT.maelstrom;
const FURY_ID = SPELLS.FURY_OF_AIR_TALENT.id;
class FuryOfAir extends Analyzer {
static dependencies = {
combatants: Combatants,
};
furyUptime = 0;
maelstromUsed = 0;
applyTime = 0;
on_initialized() {
this.active = this.combatants.selected.hasTalent(SPELLS.FURY_OF_AIR_TALENT.id);
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (spellId === FURY_ID) {
this.applyTime = event.timestamp;
this.maelstromUsed += FURY_OF_AIR_MAELSTROM_COST;
}
}
on_removebuff(event) {
const spellId = event.ability.guid;
if (spellId === FURY_ID) {
this.furyUptime += Math.floor((event.timestamp - this.applyTime) / 1000);
this.applyTime = 0;
}
}
on_finished() {
if (this.applyTime !== 0) {
this.furyUptime += Math.floor((this.owner.fight.end_time - this.applyTime) / 1000);
}
this.maelstromUsed = this.furyUptime * FURY_OF_AIR_MAELSTROM_COST;
}
suggestions(when) {
const furyofairUptime = this.combatants.selected.getBuffUptime(FURY_ID) / this.owner.fightDuration;
when(furyofairUptime).isLessThan(0.95)
.addSuggestion((suggest, actual, recommended) => {
return suggest('Try to make sure the Fury of Air is always up, when it drops you should refresh it as soon as possible')
.icon(SPELLS.FURY_OF_AIR_TALENT.icon)
.actual(`${formatPercentage(actual)}% uptime`)
.recommended(`${(formatPercentage(recommended, 0))}% is recommended`)
.regular(recommended)
.major(recommended - 0.05);
});
}
statistic() {
const furyofairUptime = this.combatants.selected.getBuffUptime(FURY_ID) / this.owner.fightDuration;
return (
(<StatisticBox
icon={<SpellIcon id={FURY_ID} />}
value={`${formatPercentage(furyofairUptime)} %`}
label="Fury of Air uptime"
tooltip="One of your highest priorities, get as close to 100% as possible"
/>)
);
}
statisticOrder = STATISTIC_ORDER.CORE(6);
}
export default FuryOfAir;
|
redux-demo/todomvc/src/index.js | zhangjunhd/react-examples | import React from 'react'
import { render } from 'react-dom'
import { createStore } from 'redux'
import { Provider } from 'react-redux'
import App from './containers/App'
import reducer from './reducers'
import 'todomvc-app-css/index.css'
const store = createStore(reducer)
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
)
|
src/components/DiscussionInput/DiscussionInput.js | nambawan/g-old | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import withStyles from 'isomorphic-style-loader/withStyles';
import MarkdownIt from 'markdown-it';
import { defineMessages, FormattedMessage } from 'react-intl';
// import Calendar from '../Calendar';
import { createDiscussion } from '../../actions/discussion';
import s from './DiscussionInput.css';
import {
getTags,
getIsDiscussionFetching,
getDiscussionError,
} from '../../reducers';
import Button from '../Button';
import FormField from '../FormField';
import Box from '../Box';
import Layer from '../Layer';
import Discussion from '../Discussion';
import { ICONS } from '../../constants';
import { nameValidation, createValidator } from '../../core/validation';
import Notification from '../Notification';
import history from '../../history';
const messages = defineMessages({
empty: {
id: 'form.error-empty',
defaultMessage: "You can't leave this empty",
description: 'Help for empty fields',
},
wrongSelect: {
id: 'form.error-select',
defaultMessage: 'You selection is not correct. Click on a suggestion',
description:
'Help for selection, when input does not match with a suggestion',
},
past: {
id: 'form.error-past',
defaultMessage: 'Time already passed',
description: 'Help for wrong time settings',
},
success: {
id: 'notification.success',
defaultMessage: 'Success!',
description: 'Should notify a successful action',
},
submit: {
id: 'command.submit',
defaultMessage: 'Submit',
description: 'Short command for sending data to the server',
},
visit: {
id: 'command.visit',
defaultMessage: 'Visit',
description: 'Short command to visit something',
},
});
const standardValues = {
textArea: { val: '', selection: [0, 0] },
settings: {
pollOption: { value: '1' },
title: '',
body: '',
spokesman: null,
},
tags: {},
showInput: false,
tagId: 'xt0',
currentTagIds: [],
spokesmanValue: undefined,
clearSpokesman: false,
errors: {
title: {
touched: false,
},
body: {
touched: false,
},
dateTo: {
touched: false,
},
timeTo: {
touched: false,
},
spokesman: {
touched: false,
},
},
};
const formFields = ['title', 'body'];
class DiscussionInput extends React.Component {
static propTypes = {
createDiscussion: PropTypes.func.isRequired,
// intl: PropTypes.shape({}).isRequired,
// locale: PropTypes.string.isRequired,
maxTags: PropTypes.number.isRequired,
isPending: PropTypes.bool.isRequired,
errorMessage: PropTypes.string,
success: PropTypes.string,
tags: PropTypes.arrayOf(
PropTypes.shape({
text: PropTypes.string,
id: PropTypes.string,
}),
).isRequired,
workTeamId: PropTypes.string.isRequired,
workTeam: PropTypes.shape({}),
updates: PropTypes.shape({
success: PropTypes.bool,
error: PropTypes.bool,
}),
};
static defaultProps = {
errorMessage: null,
success: null,
updates: null,
workTeam: null,
};
constructor(props) {
super(props);
this.state = {
...standardValues,
};
this.onTextChange = this.onTextChange.bind(this);
this.onTextSelect = this.onTextSelect.bind(this);
this.onSubmit = this.onSubmit.bind(this);
this.onModeChange = this.onModeChange.bind(this);
this.onTRefChange = this.onTRefChange.bind(this);
this.onTitleChange = this.onTitleChange.bind(this);
this.handleTagInputChange = this.handleTagInputChange.bind(this);
this.handleKeys = this.handleKeys.bind(this);
this.onStrong = this.onStrong.bind(this);
this.onItalic = this.onItalic.bind(this);
this.onAddLink = this.onAddLink.bind(this);
this.handleValueChanges = this.handleValueChanges.bind(this);
this.toggleSettings = this.toggleSettings.bind(this);
this.handleValidation = this.handleValidation.bind(this);
this.visibleErrors = this.visibleErrors.bind(this);
this.handleBlur = this.handleBlur.bind(this);
this.md = new MarkdownIt({
// html: true,
linkify: true,
});
const testValues = {
title: { fn: 'name' },
body: { fn: 'name' },
};
this.Validator = createValidator(
testValues,
{
name: nameValidation,
},
this,
obj => obj.state.settings,
);
}
componentWillReceiveProps({ workTeam, updates = {} }) {
let newUpdates = {};
if (updates.success && !this.props.updates.success) {
newUpdates = standardValues;
newUpdates.success = updates.success;
newUpdates.error = false;
}
if (updates.error && !this.props.updates.error) {
newUpdates.error = true;
newUpdates.success = false;
}
this.setState({ ...workTeam, ...newUpdates });
}
onTextChange(e) {
this.setState(prevState => {
return {
markup: this.md.render(prevState.textArea.val),
textArea: { ...prevState.textArea, val: e.target.value },
};
});
}
onTextSelect(e) {
this.setState({
textSelection: [e.target.selectionStart, e.target.selectionEnd],
});
}
onTitleChange(e) {
this.setState({ title: { val: e.target.value } });
}
onModeChange(e) {
this.setState({ value: e.target.value });
}
onStrong() {
if (this.isSomethingSelected()) this.insertAtSelection('****', '****');
}
onItalic() {
if (this.isSomethingSelected()) this.insertAtSelection('*', '*');
}
onAddLink() {
const url = prompt('URL', 'https://');
if (url) {
this.insertAtSelection(
this.isSomethingSelected() ? '[' : '[link',
`](${url})`,
);
}
}
onTRefChange(e) {
this.setState({ thresholdRef: e.target.value });
}
onSubmit() {
// TODO validate
if (this.handleValidation(formFields)) {
const { body, title } = this.state.settings;
this.props.createDiscussion({
title: title.trim(),
content: this.md.render(body),
workTeamId: this.props.workTeamId,
});
}
}
handleSpokesmanValueChange(e) {
this.setState({ spokesmanValue: e.value });
}
visibleErrors(errorNames) {
return errorNames.reduce((acc, curr) => {
const err = `${curr}Error`;
if (this.state.errors[curr].touched) {
acc[err] = (
<FormattedMessage {...messages[this.state.errors[curr].errorName]} />
);
}
return acc;
}, {});
}
handleValidation(fields) {
const validated = this.Validator(fields);
this.setState({ errors: { ...this.state.errors, ...validated.errors } });
return validated.failed === 0;
}
handleBlur(e) {
const field = e.target.name;
if (this.state.settings[field]) {
this.handleValidation([field]);
}
}
handleValueChanges(e) {
let value;
switch (e.target.name) {
case 'dateTo':
case 'dateFrom':
case 'timeFrom':
case 'timeTo':
case 'threshold':
case 'thresholdRef':
case 'tagInput':
case 'title':
case 'body':
case 'spokesman':
case 'pollOption': {
value = e.target.value; // eslint-disable-line
break;
}
case 'withStatements':
case 'unipolar':
case 'secret': {
value = e.target.checked;
break;
}
default:
throw Error(`Element not recognized: ${e.target.name}`);
}
this.setState({
settings: { ...this.state.settings, [e.target.name]: value },
});
}
toggleSettings() {
this.setState({ displaySettings: !this.state.displaySettings });
}
isSomethingSelected() {
return this.state.textSelection[0] !== this.state.textSelection[1];
}
insertAtSelection(pre, post) {
let val = this.state.settings.body;
let sel = this.state.textSelection;
val = `${val.substring(0, sel[0])}${pre}${val.substring(
sel[0],
sel[1],
)}${post}${val.substring(sel[1])}`;
sel = [val.length, val.length];
this.setState({
...this.state,
settings: {
...this.state.settings,
body: val,
},
textSelection: sel,
});
}
handleTagInputChange(e) {
this.setState({ [e.target.name]: e.target.value });
}
handleKeys(e) {
if (e.key === 'Enter') {
if (this.state.tagInput) {
this.setState({
tags: { ...this.state.tags, [this.state.tagId]: this.state.tagInput },
showInput: false,
});
}
}
}
render() {
const { title, body } = this.state.settings;
const { titleError, bodyError } = this.visibleErrors(formFields);
const { error } = this.state;
const { updates = {} } = this.props;
return (
<div className={s.root}>
{/* <Calendar lang={this.props.locale} /> */}
<Box column pad>
<FormField label="Title" error={titleError}>
<input
name="title"
onBlur={this.handleBlur}
type="text"
value={title}
onChange={this.handleValueChanges}
/>
</FormField>
<FormField
error={bodyError}
label="Body"
help={
<Box pad>
<Button
onClick={this.onStrong}
plain
icon={<strong>A</strong>}
/>
<Button onClick={this.onItalic} plain icon={<i>A</i>} />
<Button
plain
onClick={this.onAddLink}
icon={
<svg
viewBox="0 0 24 24"
width="24px"
height="24px"
role="img"
aria-label="link"
>
<path
fill="none"
stroke="#000"
strokeWidth="2"
d={ICONS.link}
/>
</svg>
}
/>
</Box>
}
>
<textarea
className={s.textInput}
name="body"
value={body}
onChange={this.handleValueChanges}
onSelect={this.onTextSelect}
onBlur={this.handleBlur}
/>
</FormField>
{this.state.showPreview && (
<Layer
onClose={() => {
this.setState({ showPreview: false });
}}
>
<Box tag="article" column pad align padding="medium">
<Discussion
{...{
id: '0000',
createdAt: new Date(),
title:
title.trim().length < 3
? 'Title is missing!'
: title.trim(),
content:
this.md.render(body).length < 3
? 'Body is missing'
: this.md.render(body),
}}
/>
</Box>
</Layer>
)}
<Box pad>
<Button
primary
label={<FormattedMessage {...messages.submit} />}
onClick={this.onSubmit}
disabled={this.props.isPending}
/>
<Button
label="Preview"
onClick={() => {
this.setState({ showPreview: true });
}}
/>
</Box>
<p>
{error && <Notification type="error" message={updates.error} />}
</p>
{this.state.success && (
<Notification
type="success"
message={<FormattedMessage {...messages.success} />}
action={
<Button
plain
reverse
icon={
<svg
viewBox="0 0 24 24"
width="24px"
height="24px"
role="img"
>
<path
fill="none"
stroke="#000"
strokeWidth="2"
d="M2,12 L22,12 M13,3 L22,12 L13,21"
/>
</svg>
}
onClick={() => {
history.push(
`/workteams/${this.props.workTeamId}/discussions/${
this.state.success
}`,
);
}}
label={<FormattedMessage {...messages.visit} />}
/>
}
/>
)}
</Box>
</div>
);
}
}
const mapStateToProps = state => ({
tags: getTags(state),
isPending: getIsDiscussionFetching(state, '0000'),
errorMessage: getDiscussionError(state, '0000'),
});
const mapDispatch = {
createDiscussion,
};
DiscussionInput.contextTypes = {
intl: PropTypes.object,
};
export default connect(
mapStateToProps,
mapDispatch,
)(withStyles(s)(DiscussionInput));
|
es2015plus/react/src/components/Select/index.js | lshig/forms-challenge | import React from 'react';
import PropTypes from 'prop-types';
export default function Select({ name, label, onChange, options }) {
return (
<div className="select">
<select id={name} name={name} onChange={onChange}>
<option key={label} value="">
{label}
</option>
{options.map((item, index) => (
<option key={index} value={item}>
{item}
</option>
))}
</select>
<div className="select__arrow" />
</div>
);
}
Select.propTypes = {
label: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
options: PropTypes.array.isRequired
};
|
docs/src/PageFooter.js | deerawan/react-bootstrap | import React from 'react';
import packageJSON from '../../package.json';
let version = packageJSON.version;
if (/docs/.test(version)) {
version = version.split('-')[0];
}
const PageHeader = React.createClass({
render() {
return (
<footer className="bs-docs-footer" role="contentinfo">
<div className="container">
<div className="bs-docs-social">
<ul className="bs-docs-social-buttons">
<li>
<iframe className="github-btn"
src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true"
width={95}
height={20}
title="Star on GitHub" />
</li>
<li>
<iframe className="github-btn"
src="https://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true"
width={92}
height={20}
title="Fork on GitHub" />
</li>
<li>
<iframe
src="https://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true"
width={230}
height={20}
allowTransparency="true"
frameBorder="0"
scrolling="no">
</iframe>
</li>
</ul>
</div>
<p>Code licensed under <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE" target="_blank">MIT</a>.</p>
<ul className="bs-docs-footer-links muted">
<li>Currently v{version}</li>
<li>·</li>
<li><a href="https://github.com/react-bootstrap/react-bootstrap/">GitHub</a></li>
<li>·</li>
<li><a href="https://github.com/react-bootstrap/react-bootstrap/issues?state=open">Issues</a></li>
<li>·</li>
<li><a href="https://github.com/react-bootstrap/react-bootstrap/releases">Releases</a></li>
</ul>
</div>
</footer>
);
}
});
export default PageHeader;
|
ui/src/frontend/component/Home.js | Virtustream-OSS/packrat | import React from 'react';
const Home = ( { match } ) => (
<div><h1>Packrat</h1></div>
);
export default Home
|
app/components/Icons/icons/icon-twitter.js | code4romania/monitorizare-vot-votanti-client | import React from 'react';
function LogoTwitter() {
return (
<svg viewBox="0 0 16 16" xmlns="http://www.w3.org/2000/svg" fillRule="evenodd" clipRule="evenodd" strokeLinejoin="round" strokeMiterlimit="1.414">
<path d="M16 3.038c-.59.26-1.22.437-1.885.517.677-.407 1.198-1.05 1.443-1.816-.634.375-1.337.648-2.085.795-.598-.638-1.45-1.036-2.396-1.036-1.812 0-3.282 1.468-3.282 3.28 0 .258.03.51.085.75C5.152 5.39 2.733 4.084 1.114 2.1.83 2.583.67 3.147.67 3.75c0 1.14.58 2.143 1.46 2.732-.538-.017-1.045-.165-1.487-.41v.04c0 1.59 1.13 2.918 2.633 3.22-.276.074-.566.114-.865.114-.21 0-.416-.02-.617-.058.418 1.304 1.63 2.253 3.067 2.28-1.124.88-2.54 1.404-4.077 1.404-.265 0-.526-.015-.783-.045 1.453.93 3.178 1.474 5.032 1.474 6.038 0 9.34-5 9.34-9.338 0-.143-.004-.284-.01-.425.64-.463 1.198-1.04 1.638-1.7z" fillRule="nonzero" />
</svg>
);
}
export default LogoTwitter;
|
src/containers/Home/Home.js | bamtron5/ReactRedux | import React, { Component } from 'react';
import { Link } from 'react-router';
import { CounterButton, GithubButton } from 'components';
export default class Home extends Component {
render() {
const styles = require('./Home.scss');
// require the logo image both from client and server
const logoImage = require('./logo.png');
return (
<div className={styles.home}>
<div className={styles.masthead}>
<div className="container">
<div className={styles.logo}>
<p>
<img src={logoImage}/>
</p>
</div>
<h1>React Redux Example</h1>
<h2>All the modern best practices in one example.</h2>
<p>
<a className={styles.github} href="https://github.com/erikras/react-redux-universal-hot-example"
target="_blank">
<i className="fa fa-github"/> View on Github
</a>
</p>
<GithubButton user="erikras"
repo="react-redux-universal-hot-example"
type="star"
width={160}
height={30}
count large/>
<GithubButton user="erikras"
repo="react-redux-universal-hot-example"
type="fork"
width={160}
height={30}
count large/>
<p className={styles.humility}>
Created and maintained by <a href="https://twitter.com/erikras" target="_blank">@erikras</a>.
</p>
</div>
</div>
<div className="container">
<div className={styles.counterContainer}>
<CounterButton multireducerKey="counter1"/>
<CounterButton multireducerKey="counter2"/>
<CounterButton multireducerKey="counter3"/>
</div>
<p>This starter boilerplate app uses the following technologies:</p>
<ul>
<li>
<del>Isomorphic</del>
{' '}
<a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal</a> rendering
</li>
<li>Both client and server make calls to load data from separate API server</li>
<li><a href="https://github.com/facebook/react" target="_blank">React</a></li>
<li><a href="https://github.com/rackt/react-router" target="_blank">React Router</a></li>
<li><a href="http://expressjs.com" target="_blank">Express</a></li>
<li><a href="http://babeljs.io" target="_blank">Babel</a> for ES6 and ES7 magic</li>
<li><a href="http://webpack.github.io" target="_blank">Webpack</a> for bundling</li>
<li><a href="http://webpack.github.io/docs/webpack-dev-middleware.html" target="_blank">Webpack Dev Middleware</a>
</li>
<li><a href="https://github.com/glenjamin/webpack-hot-middleware" target="_blank">Webpack Hot Middleware</a></li>
<li><a href="https://github.com/rackt/redux" target="_blank">Redux</a>'s futuristic <a
href="https://facebook.github.io/react/blog/2014/05/06/flux.html" target="_blank">Flux</a> implementation
</li>
<li><a href="https://github.com/gaearon/redux-devtools" target="_blank">Redux Dev Tools</a> for next
generation DX (developer experience).
Watch <a href="https://www.youtube.com/watch?v=xsSnOQynTHs" target="_blank">Dan Abramov's talk</a>.
</li>
<li><a href="https://github.com/rackt/redux-router" target="_blank">Redux Router</a> Keep
your router state in your Redux store
</li>
<li><a href="http://eslint.org" target="_blank">ESLint</a> to maintain a consistent code style</li>
<li><a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state
in Redux
</li>
<li><a href="https://github.com/erikras/multireducer" target="_blank">multireducer</a> combine several
identical reducer states into one key-based reducer</li>
<li><a href="https://github.com/webpack/style-loader" target="_blank">style-loader</a> and <a
href="https://github.com/jtangelder/sass-loader" target="_blank">sass-loader</a> to allow import of
stylesheets
</li>
<li><a href="https://github.com/shakacode/bootstrap-sass-loader" target="_blank">bootstrap-sass-loader</a> and <a
href="https://github.com/gowravshekar/font-awesome-webpack" target="_blank">font-awesome-webpack</a> to customize Bootstrap and FontAwesome
</li>
<li><a href="http://socket.io/">socket.io</a> for real-time communication</li>
</ul>
<h3>Features demonstrated in this project</h3>
<dl>
<dt>Multiple components subscribing to same redux store slice</dt>
<dd>
The <code>App.js</code> that wraps all the pages contains an <code>InfoBar</code> component
that fetches data from the server initially, but allows for the user to refresh the data from
the client. <code>About.js</code> contains a <code>MiniInfoBar</code> that displays the same
data.
</dd>
<dt>Server-side data loading</dt>
<dd>
The <Link to="/widgets">Widgets page</Link> demonstrates how to fetch data asynchronously from
some source that is needed to complete the server-side rendering. <code>Widgets.js</code>'s
<code>fetchData()</code> function is called before the widgets page is loaded, on either the server
or the client, allowing all the widget data to be loaded and ready for the page to render.
</dd>
<dt>Data loading errors</dt>
<dd>
The <Link to="/widgets">Widgets page</Link> also demonstrates how to deal with data loading
errors in Redux. The API endpoint that delivers the widget data intentionally fails 33% of
the time to highlight this. The <code>clientMiddleware</code> sends an error action which
the <code>widgets</code> reducer picks up and saves to the Redux state for presenting to the user.
</dd>
<dt>Session based login</dt>
<dd>
On the <Link to="/login">Login page</Link> you can submit a username which will be sent to the server
and stored in the session. Subsequent refreshes will show that you are still logged in.
</dd>
<dt>Redirect after state change</dt>
<dd>
After you log in, you will be redirected to a Login Success page. This <strike>magic</strike> logic
is performed in <code>componentWillReceiveProps()</code> in <code>App.js</code>, but it could
be done in any component that listens to the appropriate store slice, via Redux's <code>@connect</code>,
and pulls the router from the context.
</dd>
<dt>Auth-required views</dt>
<dd>
The aforementioned Login Success page is only visible to you if you are logged in. If you try
to <Link to="/loginSuccess">go there</Link> when you are not logged in, you will be forwarded back
to this home page. This <strike>magic</strike> logic is performed by the
<code>onEnter</code> hook within <code>routes.js</code>.
</dd>
<dt>Forms</dt>
<dd>
The <Link to="/survey">Survey page</Link> uses the
still-experimental <a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to
manage form state inside the Redux store. This includes immediate client-side validation.
</dd>
<dt>WebSockets / socket.io</dt>
<dd>
The <Link to="/chat">Chat</Link> uses the socket.io technology for real-time
commnunication between clients. You need to <Link to="/login">login</Link> first.
</dd>
</dl>
<h3>From the author</h3>
<p>
I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015,
all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as
quickly as they have come into it, but I personally believe that this stack is the future of web development
and will survive for several years. I'm building my new projects like this, and I recommend that you do,
too.
</p>
<p>Thanks for taking the time to check this out.</p>
<p>– Erik Rasmussen</p>
</div>
</div>
);
}
}
|
fields/types/select/SelectFilter.js | andreufirefly/keystone | import React from 'react';
import { Checkbox, FormField, SegmentedControl } from 'elemental';
import PopoutList from '../../../admin/client/components/Popout/PopoutList';
const INVERTED_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true },
];
function getDefaultValue () {
return {
inverted: INVERTED_OPTIONS[0].value,
value: [],
};
}
var SelectFilter = React.createClass({
propTypes: {
field: React.PropTypes.object,
filter: React.PropTypes.shape({
inverted: React.PropTypes.boolean,
value: React.PropTypes.array,
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
toggleInverted (inverted) {
this.updateFilter({ inverted });
},
toggleAllOptions () {
const { field, filter } = this.props;
if (filter.value.length < field.ops.length) {
this.updateFilter({ value: field.ops.map(i => i.value) });
} else {
this.updateFilter({ value: [] });
}
},
selectOption (option) {
const value = this.props.filter.value.concat(option.value);
this.updateFilter({ value });
},
removeOption (option) {
const value = this.props.filter.value.filter(i => i !== option.value);
this.updateFilter({ value });
},
updateFilter (value) {
this.props.onChange({ ...this.props.filter, ...value });
},
renderOptions () {
return this.props.field.ops.map((option, i) => {
const selected = this.props.filter.value.indexOf(option.value) > -1;
return (
<PopoutList.Item
key={`item-${i}-${option.value}`}
icon={selected ? 'check' : 'dash'}
isSelected={selected}
label={option.label}
onClick={() => {
if (selected) this.removeOption(option);
else this.selectOption(option);
}}
/>
);
});
},
render () {
const { field, filter } = this.props;
const allSelected = filter.value.length;
const indeterminate = filter.value.lenght === field.ops.length;
return (
<div>
<FormField>
<SegmentedControl equalWidthSegments options={INVERTED_OPTIONS} value={filter.inverted} onChange={this.toggleInverted} />
</FormField>
<FormField style={{ borderBottom: '1px dashed rgba(0,0,0,0.1)', paddingBottom: '1em' }}>
<Checkbox autofocus onChange={this.toggleAllOptions} label="Select all options" checked={allSelected} indeterminate={indeterminate} />
</FormField>
{this.renderOptions()}
</div>
);
},
});
module.exports = SelectFilter;
|
src/svg-icons/maps/directions.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsDirections = (props) => (
<SvgIcon {...props}>
<path d="M21.71 11.29l-9-9c-.39-.39-1.02-.39-1.41 0l-9 9c-.39.39-.39 1.02 0 1.41l9 9c.39.39 1.02.39 1.41 0l9-9c.39-.38.39-1.01 0-1.41zM14 14.5V12h-4v3H8v-4c0-.55.45-1 1-1h5V7.5l3.5 3.5-3.5 3.5z"/>
</SvgIcon>
);
MapsDirections = pure(MapsDirections);
MapsDirections.displayName = 'MapsDirections';
MapsDirections.muiName = 'SvgIcon';
export default MapsDirections;
|
wwwroot/app/src/components/App/App.js | AlinCiocan/PlanEatSave | import React, { Component } from 'react';
import '../../utils/WindowResizeEventOptimized';
import './App.css';
class App extends Component {
render() {
var _this = this;
return (
<div className="full-height">
{React.Children.map(this.props.children, (child => React.cloneElement(child, { router: _this.props.router })))}
</div>
);
}
}
export default App;
|
pages/contacts.js | xzin/homepage | import React from 'react'
import { Link } from 'react-router'
import { prefixLink } from 'gatsby-helpers'
import Helmet from 'react-helmet'
import { config } from 'config'
const styles={
link:{
fontFamily:'Ubuntu',
color:'black',
textDecoration:'none'
}
}
export default class Index extends React.Component {
render() {
return (
<div>
<h1>
Contacts
</h1>
<p><a style={styles.link} href='mailto:holatchahl@gmail.com'>Email: holatchahl@gmail.com</a></p>
<p><a style={styles.link} href='skype:aitops'>Skype: aitops</a></p>
</div>
)
}
}
|
app/containers/PostHousePage/index.js | coocooooo/webapp | /**
* House Page -- the detail of the House
*
* copyright(c) coocooooo
*/
import React from 'react';
import Helmet from 'react-helmet';
import styled from 'styled-components';
import cx from 'classnames';
import { Form, Container } from 'semantic-ui-react';
import WrappedRegistrationForm from './Form';
const Article = styled.article`
`;
// sm:48em/ md:64em/ lg:7em/ 1em 16px
export const Row = function (props) {
const { children, className } = props;
const classes = cx(
'row',
className,
);
return <div className={classes}>{children}</div>
};
export const MainArea = function (props) {
const { children, className } = props;
const classes = cx(
'col-lg-8',
'col-md-8',
'col-sm-12',
'col-xs-12',
className,
);
return <div className={classes}>{children}</div>;
};
class PostHouse extends React.PureComponent {
render() {
return (
<Article>
<Helmet
title="Post House Page"
meta={[
{ name: "description", content: "post the base infomation of the house"}
]}
/>
<Helmet
title="SignIn Page"
meta={[
{ name: "description", content: "for user to sign in"}
]}
/>
<Container>
<Row>
<MainArea>
<WrappedRegistrationForm />
</MainArea>
</Row>
</Container>
</Article>
);
}
}
export default PostHouse;
|
src/articles/2018-01-31-1st-Anniversary/Timeline.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import './Timeline.css';
const Timeline = ({ children }) => (
<div className="timeline year-recap">
{children}
</div>
);
Timeline.propTypes = {
children: PropTypes.node.isRequired,
};
export default Timeline;
|
app/react-icons/fa/angle-left.js | scampersand/sonos-front | import React from 'react';
import IconBase from 'react-icon-base';
export default class FaAngleLeft extends React.Component {
render() {
return (
<IconBase viewBox="0 0 40 40" {...this.props}>
<g><path d="m26.5 12.1q0 0.3-0.2 0.6l-8.8 8.7 8.8 8.8q0.2 0.2 0.2 0.5t-0.2 0.5l-1.1 1.1q-0.3 0.3-0.6 0.3t-0.5-0.3l-10.4-10.4q-0.2-0.2-0.2-0.5t0.2-0.5l10.4-10.4q0.3-0.2 0.5-0.2t0.6 0.2l1.1 1.1q0.2 0.2 0.2 0.5z"/></g>
</IconBase>
);
}
}
|
src/components/Thead.js | ua-oira/react-super-responsive-table | import React from 'react';
import T from 'prop-types';
import allowed from '../utils/allowed';
const Thead = (props) => {
const { children } = props;
return (
<thead data-testid="thead" {...allowed(props)}>
{React.cloneElement(children, { inHeader: true })}
</thead>
);
};
Thead.propTypes = {
children: T.node,
};
Thead.defaultProps = {
children: undefined,
};
export default Thead;
|
src/ReactBoilerplate/Scripts/containers/Register/Register.js | theonlylawislove/react-dot-net | import React, { Component } from 'react';
import { RegisterForm } from 'components';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
class Register extends Component {
componentWillReceiveProps(nextProps) {
if (!this.props.user && nextProps.user) {
this.props.pushState('/');
}
}
render() {
return (
<div>
<h2>Register</h2>
<h4>Create a new account.</h4>
<hr />
<RegisterForm />
</div>
);
}
}
export default connect(
state => ({ user: state.auth.user, externalLogin: state.externalLogin }),
{ pushState: push }
)(Register);
|
src/containers/toast.js | ThatCrazyIrishGuy/less-to-palette | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { Snackbar } from 'react-toolbox/lib/snackbar';
export class Toast extends Component {
constructor(props) {
super(props);
this.state = {
active: false,
message: ''
};
this.handleSnackbarClick = this.handleSnackbarClick.bind(this);
this.handleSnackbarTimeout = this.handleSnackbarTimeout.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState(nextProps.toast);
}
handleSnackbarClick() {
this.setState({ active: false });
}
handleSnackbarTimeout() {
this.setState({ active: false });
}
render() {
return (
<section>
<Snackbar
action="Dismiss"
active={this.state.active}
label={this.state.message}
timeout={2000}
onClick={this.handleSnackbarClick}
onTimeout={this.handleSnackbarTimeout}
type="cancel"
/>
</section>
);
}
}
Toast.propTypes = {
toast: React.PropTypes.object // eslint-disable-line react/forbid-prop-types
};
Toast.defaultProps = {
toast: {
active: false,
message: ''
}
};
function mapStateToProps({ toast }) {
return { toast };
}
export default connect(mapStateToProps)(Toast);
|
src/components/Home.js | billie66/demo2 | import React, { Component } from 'react';
class Home extends Component {
render() {
return (
<div className="home">
<div className="slogan">
welcome to stage two
</div>
</div>
);
}
}
export default Home;
|
docs/src/PageFooter.js | andrew-d/react-bootstrap | import React from 'react';
import packageJSON from '../../package.json';
let version = packageJSON.version;
if (/docs/.test(version)) {
version = version.split('-')[0];
}
const PageHeader = React.createClass({
render() {
return (
<footer className='bs-docs-footer' role='contentinfo'>
<div className='container'>
<div className='bs-docs-social'>
<ul className='bs-docs-social-buttons'>
<li>
<iframe className='github-btn'
src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=watch&count=true'
width={95}
height={20}
title='Star on GitHub' />
</li>
<li>
<iframe className='github-btn'
src='http://ghbtns.com/github-btn.html?user=react-bootstrap&repo=react-bootstrap&type=fork&count=true'
width={92}
height={20}
title='Fork on GitHub' />
</li>
<li>
<iframe
src="http://platform.twitter.com/widgets/follow_button.html?screen_name=react_bootstrap&show_screen_name=true"
width={230}
height={20}
allowTransparency="true"
frameBorder='0'
scrolling='no'>
</iframe>
</li>
</ul>
</div>
<p>Code licensed under <a href='https://github.com/react-bootstrap/react-bootstrap/blob/master/LICENSE' target='_blank'>MIT</a>.</p>
<ul className='bs-docs-footer-links muted'>
<li>Currently v{version}</li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/'>GitHub</a></li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/issues?state=open'>Issues</a></li>
<li>·</li>
<li><a href='https://github.com/react-bootstrap/react-bootstrap/releases'>Releases</a></li>
</ul>
</div>
</footer>
);
}
});
export default PageHeader;
|
geonode/monitoring/frontend/monitoring/src/components/organisms/geonode-status/index.js | tomkralidis/geonode | /*
#########################################################################
#
# Copyright (C) 2019 OSGeo
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
#########################################################################
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import HoverPaper from '../../atoms/hover-paper';
import CPU from '../../cels/cpu';
import Memory from '../../cels/memory';
import styles from './styles';
import actions from './actions';
const mapStateToProps = (state) => ({
cpu: state.geonodeCpuSequence.response,
memory: state.geonodeMemorySequence.response,
interval: state.interval.interval,
services: state.services.hostgeonode,
timestamp: state.interval.timestamp,
});
@connect(mapStateToProps, actions)
class GeonodeStatus extends React.Component {
static propTypes = {
cpu: PropTypes.object,
getCpu: PropTypes.func.isRequired,
getMemory: PropTypes.func.isRequired,
memory: PropTypes.object,
resetCpu: PropTypes.func.isRequired,
resetMemory: PropTypes.func.isRequired,
services: PropTypes.array,
timestamp: PropTypes.instanceOf(Date),
interval: PropTypes.number,
half: PropTypes.bool,
}
static defaultProps = {
half: true,
}
constructor(props) {
super(props);
this.state = {
host: '',
};
this.get = (
host = this.state.host,
interval = this.props.interval,
) => {
this.props.getCpu(host, interval);
this.props.getMemory(host, interval);
};
this.reset = () => {
this.props.resetCpu();
this.props.resetMemory();
};
}
componentWillMount() {
// this.get();
}
componentWillReceiveProps(nextProps) {
if (nextProps && nextProps.services && nextProps.timestamp) {
let host = nextProps.services[0].name;
let firstTime = false;
if (this.state.host === '') {
firstTime = true;
this.setState({ host });
} else {
host = this.state.host;
}
if (firstTime || nextProps.timestamp !== this.props.timestamp) {
this.get(host, nextProps.interval);
}
}
}
componentWillUnmount() {
this.reset();
}
render() {
let cpuData = [];
let memoryData = [];
if (
this.props.cpu
&& this.props.cpu.data
&& this.props.cpu.data.data
) {
cpuData = this.props.cpu.data.data.map(element => ({
name: element.valid_from,
'CPU used': element.data.length > 0 ? Math.floor(element.data[0].val) : 0,
}));
}
if (
this.props.memory
&& this.props.memory.data
&& this.props.memory.data.data
) {
memoryData = this.props.memory.data.data.map(element => ({
name: element.valid_from,
'MEM used': element.data.length > 0 ? Math.floor(element.data[0].val) : 0,
}));
}
const contentStyle = this.props.half
? styles.content
: { ...styles.content, width: '100%' };
const hosts = this.props.services
? this.props.services.map((host) =>
<MenuItem
key={host.name}
value={host.name}
primaryText={ `${host.name} [${host.host}]`}
/>
)
: undefined;
return (
<HoverPaper style={contentStyle}>
<h3>GeoNode status</h3>
<SelectField
floatingLabelText="Host"
value={this.state.host}
onChange={this.handleChange}
>
{hosts}
</SelectField>
<div style={styles.stat}>
<CPU data={cpuData} />
<Memory data={memoryData} />
</div>
</HoverPaper>
);
}
}
export default GeonodeStatus;
|
react-youtube-adaptive-loading/src/containers/Search/Search.js | GoogleChromeLabs/adaptive-loading | import React from 'react';
import './Search.scss';
import {getYoutubeLibraryLoaded} from '../../store/reducers/api';
import {getSearchNextPageToken, getSearchResults} from '../../store/reducers/search';
import * as searchActions from '../../store/actions/search';
import {bindActionCreators} from 'redux';
import {connect} from 'react-redux';
import {getSearchParam} from '../../services/url';
import {VideoList} from '../../components/VideoList/VideoList';
import {withRouter} from 'react-router-dom';
class Search extends React.Component {
render() {
return (<VideoList
bottomReachedCallback={this.bottomReachedCallback}
showLoader={true}
videos={this.props.searchResults}/>);
}
getSearchQuery() {
return getSearchParam(this.props.location, 'search_query');
}
componentDidMount() {
if (!this.getSearchQuery()) {
// redirect to home component if search query is not there
this.props.history.push('/');
}
this.searchForVideos();
}
componentDidUpdate(prevProps) {
if (prevProps.youtubeApiLoaded !== this.props.youtubeApiLoaded) {
this.searchForVideos();
}
}
searchForVideos() {
const searchQuery = this.getSearchQuery();
if (this.props.youtubeApiLoaded) {
this.props.searchForVideos(searchQuery);
}
}
bottomReachedCallback = () => {
if(this.props.nextPageToken) {
this.props.searchForVideos(this.getSearchQuery(), this.props.nextPageToken, 25);
}
};
}
function mapDispatchToProps(dispatch) {
const searchForVideos = searchActions.forVideos.request;
return bindActionCreators({searchForVideos}, dispatch);
}
function mapStateToProps(state, props) {
return {
youtubeApiLoaded: getYoutubeLibraryLoaded(state),
searchResults: getSearchResults(state, props.location.search),
nextPageToken: getSearchNextPageToken(state, props.location.search),
};
}
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(Search));
|
examples/expo/App.js | kimxogus/react-native-version-check | import React, { Component } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import VersionCheck from 'react-native-version-check-expo';
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
text: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
export default class example extends Component {
state = {
currentVersion: null,
latestVersion: null,
isNeeded: false,
storeUrl: '',
};
componentDidMount() {
VersionCheck.needUpdate({
latestVersion: '1.0.0',
}).then(res => this.setState(res));
VersionCheck.getStoreUrl().then(res => {
//App Store ID for iBooks.
this.setState({ storeUrl: res });
});
}
render() {
return (
<View style={styles.container}>
<Text style={styles.text}>
Current Version: {this.state.currentVersion}
</Text>
<Text style={styles.text}>
Latest Version: {this.state.latestVersion}
</Text>
<Text style={styles.text}>
Is update needed?: {String(this.state.isNeeded)}
</Text>
<View>
<Text style={styles.text}>Store Url:</Text>
<Text
style={[styles.text, styles.linkText]}
onPress={() => Linking.openURL(this.state.storeUrl)}
>
{String(this.state.storeUrl)}
</Text>
</View>
</View>
);
}
}
|
examples/real-world/index.js | cornedor/redux | import 'babel-core/polyfill';
import React from 'react';
import BrowserHistory from 'react-router/lib/BrowserHistory';
import { Provider } from 'react-redux';
import { Router, Route } from 'react-router';
import configureStore from './store/configureStore';
import App from './containers/App';
import UserPage from './containers/UserPage';
import RepoPage from './containers/RepoPage';
const history = new BrowserHistory();
const store = configureStore();
React.render(
<Provider store={store}>
{() =>
<Router history={history}>
<Route path="/" component={App}>
<Route path="/:login/:name"
component={RepoPage} />
<Route path="/:login"
component={UserPage} />
</Route>
</Router>
}
</Provider>,
document.getElementById('root')
);
|
jenkins-design-language/src/js/components/material-ui/svg-icons/action/visibility-off.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionVisibilityOff = (props) => (
<SvgIcon {...props}>
<path d="M12 7c2.76 0 5 2.24 5 5 0 .65-.13 1.26-.36 1.83l2.92 2.92c1.51-1.26 2.7-2.89 3.43-4.75-1.73-4.39-6-7.5-11-7.5-1.4 0-2.74.25-3.98.7l2.16 2.16C10.74 7.13 11.35 7 12 7zM2 4.27l2.28 2.28.46.46C3.08 8.3 1.78 10.02 1 12c1.73 4.39 6 7.5 11 7.5 1.55 0 3.03-.3 4.38-.84l.42.42L19.73 22 21 20.73 3.27 3 2 4.27zM7.53 9.8l1.55 1.55c-.05.21-.08.43-.08.65 0 1.66 1.34 3 3 3 .22 0 .44-.03.65-.08l1.55 1.55c-.67.33-1.41.53-2.2.53-2.76 0-5-2.24-5-5 0-.79.2-1.53.53-2.2zm4.31-.78l3.15 3.15.02-.16c0-1.66-1.34-3-3-3l-.17.01z"/>
</SvgIcon>
);
ActionVisibilityOff.displayName = 'ActionVisibilityOff';
ActionVisibilityOff.muiName = 'SvgIcon';
export default ActionVisibilityOff;
|
src/components/EditForm/index.js | Apozhidaev/terminal.mobi | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { back } from 'store/services/history/actions';
import { security } from 'config';
import { encrypt, getPBKDF2 } from 'helpers/crypto';
import Content from './Content';
import Resources from './Resources';
import Attachments from './Attachments';
import Parents from './Parents';
import StatePanel from '../StatePanel';
class EditForm extends Component {
constructor(props) {
super(props);
const { slot, create } = this.props;
const { model, parents } = slot;
this.state = {
summary: model.summary || '',
root: model.root || false,
parents: create && parents.length && parents,
};
this.handleBackClick = this.handleBackClick.bind(this);
this.handleSaveClick = this.handleSaveClick.bind(this);
this.handleInputChange = this.handleInputChange.bind(this);
this.handleContentChange = this.handleContentChange.bind(this);
this.handleResourcesChange = this.handleResourcesChange.bind(this);
this.handleParentsChange = this.handleParentsChange.bind(this);
}
handleBackClick() {
const { onBack } = this.props;
onBack();
}
handleSaveClick() {
const { onBack, onSave, slot, slotKeys } = this.props;
const fields = {};
if (slot.model.summary !== this.state.summary) {
fields.summary = this.state.summary;
}
if (this.state.content) {
if (this.state.content.value) {
let contentValue;
if (this.state.content.encrypted) {
const key = this.state.content.password
? getPBKDF2(security.issueSalt, this.state.content.password)
: slotKeys[slot.model.id];
contentValue = encrypt(key, security.issueIV, this.state.content.value);
} else {
contentValue = this.state.content.value;
}
if (slot.model.content) {
fields.content = {};
if (slot.model.content.value !== contentValue) {
fields.content.value = contentValue;
}
if (!slot.model.content.encrypted !== !this.state.content.encrypted) {
fields.content.encrypted = this.state.content.encrypted;
}
} else {
fields.content = {
value: contentValue,
};
if (this.state.content.encrypted) {
fields.content.encrypted = true;
}
}
} else if (slot.model.content) {
fields.content = null;
}
}
if (!!slot.model.root !== this.state.root) {
fields.root = this.state.root;
}
if (this.state.resources) {
fields.resources = this.state.resources;
}
if (this.state.parents) {
fields.parents = this.state.parents;
}
if (Object.keys(fields).length) {
onSave(fields);
}
onBack();
}
handleInputChange(event) {
const target = event.target;
const value = target.type === 'checkbox'
? target.checked
: target.value;
const name = target.name;
this.setState({
[name]: value,
});
}
handleContentChange(content) {
this.setState({ content });
}
handleResourcesChange(resources) {
this.setState({ resources });
}
handleParentsChange(parents) {
this.setState({ parents });
}
render() {
const { slot } = this.props;
return (
<div>
<div className="row">
<div className="col">
<div className="btn-toolbar justify-content-between" role="toolbar">
<div className="btn-group my-2" role="group">
<button type="button" className="btn btn-secondary" onClick={this.handleBackClick}>
↩
</button>
</div>
<div className="btn-group my-2" role="group">
<button
type="button"
className="btn btn-outline-secondary"
onClick={this.handleBackClick}
>
cancel
</button>
<button
type="button"
className="btn btn-outline-primary"
onClick={this.handleSaveClick}
{...{ disabled: !this.state.summary }}
>save</button>
</div>
</div>
</div>
</div>
<div className="row mb-3">
<div className="col-md-2">
<StatePanel />
</div>
<div className="col-md-10">
<div className="card">
<div className="card-body">
<div className="form-group">
<label htmlFor="edit-form_summary-id" className="lead text-primary">
summary<span className="text-danger">*</span>
</label>
<input
type="text"
className="form-control"
id="edit-form_summary-id"
name="summary"
placeholder="summary..."
value={this.state.summary}
onChange={this.handleInputChange}
/>
</div>
<Content slot={slot} onChange={this.handleContentChange} />
</div>
<div className="card-body">
<label htmlFor="edit-form_root-checkbox" className="custom-control custom-checkbox">
<input
id="edit-form_root-checkbox"
type="checkbox"
className="custom-control-input"
name="root"
checked={this.state.root}
onChange={this.handleInputChange}
/>
<span className="custom-control-indicator mt-1" />
<span className="custom-control-description lead text-primary">root</span>
</label>
</div>
<div className="card-body">
<Resources
values={slot.model.resources}
onChange={this.handleResourcesChange}
/>
</div>
<div className="card-body">
<Attachments />
</div>
<div className="card-body">
<Parents
slot={slot}
onChange={this.handleParentsChange}
/>
</div>
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = state => ({
decryptedContents: state.app.book.decryptedContents,
slotKeys: state.app.book.slotKeys,
});
const mapDispatchToProps = ({
onBack: back,
});
export default connect(mapStateToProps, mapDispatchToProps)(EditForm);
|
jsx/app/MyAwesomeReactComponent.js | NickTaporuk/webpack_starterkit_project | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
const MyAwesomeReactComponent = () => (
<RaisedButton label="Default" />
); |
dashboard-ui/app/components/footer/footer.js | CloudBoost/cloudboost | 'use strict';
import React from 'react';
import Footerlist from './footerlist';
const Footer = React.createClass({
render: function () {
return (
<div className='footer navbar-fixed-bottom'>
<div className='container'>
<Footerlist />
</div>
</div>
);
}
});
export default Footer;
|
app/Georgism-Medium.js | bullines/wwgs | import React from 'react';
import GeorgismRepo from './georgism-repo.js'
import styles from './App.css';
export default class GeorgismMedium extends React.Component {
constructor(props) {
super(props);
this. handleGetWisdomButtonClick = this. handleGetWisdomButtonClick.bind(this);
this.state = { georgeism: GeorgismRepo.getRandom() }
}
handleGetWisdomButtonClick() {
this.setState({ georgeism: GeorgismRepo.getRandom()});
}
render() {
return (
<div className="georgism-medium-component" >
<div className= "row vertical-align" >
<div className="col-lg-12 col-centered">
<button type="button" onClick= { this.handleGetWisdomButtonClick } className= "btn btn-primary btn-lg sharp" >Get George Wisdom</button>
</div>
</div>
<div className= "row vertical-align">
<div className="col-lg-12 col-centered georgism-text"><p><span>{ this.state.georgeism.text } < /span></p></div>
</div>
<div className="row vertical-align">
<div className="col-lg-12 col-centered georgism-context"><p> <span>{ this.state.georgeism.context } < /span></p ></div>
</div>
</div>
);
}
} |
react/features/base/react/components/web/MultiSelectAutocomplete.js | jitsi/jitsi-meet | // @flow
import AKInlineDialog from '@atlaskit/inline-dialog';
import { MultiSelectStateless } from '@atlaskit/multi-select';
import _debounce from 'lodash/debounce';
import React, { Component } from 'react';
import logger from '../../logger';
import InlineDialogFailure from './InlineDialogFailure';
/**
* The type of the React {@code Component} props of
* {@link MultiSelectAutocomplete}.
*/
type Props = {
/**
* The default value of the selected item.
*/
defaultValue: Array<Object>,
/**
* Optional footer to show as a last element in the results.
* Should be of type {content: <some content>}.
*/
footer: Object,
/**
* Indicates if the component is disabled.
*/
isDisabled: boolean,
/**
* Text to display while a query is executing.
*/
loadingMessage: string,
/**
* The text to show when no matches are found.
*/
noMatchesFound: string,
/**
* The function called immediately before a selection has been actually
* selected. Provides an opportunity to do any formatting.
*/
onItemSelected: Function,
/**
* The function called when the selection changes.
*/
onSelectionChange: Function,
/**
* The placeholder text of the input component.
*/
placeholder: string,
/**
* The service providing the search.
*/
resourceClient: { makeQuery: Function, parseResults: Function },
/**
* Indicates if the component should fit the container.
*/
shouldFitContainer: boolean,
/**
* Indicates if we should focus.
*/
shouldFocus: boolean,
/**
* Indicates whether the support link should be shown in case of an error.
*/
showSupportLink: Boolean,
};
/**
* The type of the React {@code Component} state of
* {@link MultiSelectAutocomplete}.
*/
type State = {
/**
* Indicates if the dropdown is open.
*/
isOpen: boolean,
/**
* The text that filters the query result of the search.
*/
filterValue: string,
/**
* Indicates if the component is currently loading results.
*/
loading: boolean,
/**
* Indicates if there was an error.
*/
error: boolean,
/**
* The list of result items.
*/
items: Array<Object>,
/**
* The list of selected items.
*/
selectedItems: Array<Object>
};
/**
* A MultiSelect that is also auto-completing.
*/
class MultiSelectAutocomplete extends Component<Props, State> {
/**
* Initializes a new {@code MultiSelectAutocomplete} instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props: Props) {
super(props);
const defaultValue = this.props.defaultValue || [];
this.state = {
isOpen: false,
filterValue: '',
loading: false,
error: false,
items: [],
selectedItems: [ ...defaultValue ]
};
this._onFilterChange = this._onFilterChange.bind(this);
this._onRetry = this._onRetry.bind(this);
this._onSelectionChange = this._onSelectionChange.bind(this);
this._sendQuery = _debounce(this._sendQuery.bind(this), 200);
}
/**
* Sets the items to display as selected.
*
* @param {Array<Object>} selectedItems - The list of items to display as
* having been selected.
* @returns {void}
*/
setSelectedItems(selectedItems: Array<Object> = []) {
this.setState({ selectedItems });
}
/**
* Renders the content of this component.
*
* @returns {ReactElement}
*/
render() {
const shouldFitContainer = this.props.shouldFitContainer || false;
const shouldFocus = this.props.shouldFocus || false;
const isDisabled = this.props.isDisabled || false;
const placeholder = this.props.placeholder || '';
const noMatchesFound = this.props.noMatchesFound || '';
return (
<div>
<MultiSelectStateless
filterValue = { this.state.filterValue }
footer = { this.props.footer }
icon = { null }
isDisabled = { isDisabled }
isLoading = { this.state.loading }
isOpen = { this.state.isOpen }
items = { this.state.items }
loadingMessage = { this.props.loadingMessage }
noMatchesFound = { noMatchesFound }
onFilterChange = { this._onFilterChange }
onRemoved = { this._onSelectionChange }
onSelected = { this._onSelectionChange }
placeholder = { placeholder }
selectedItems = { this.state.selectedItems }
shouldFitContainer = { shouldFitContainer }
shouldFocus = { shouldFocus } />
{ this._renderError() }
</div>
);
}
_onFilterChange: (string) => void;
/**
* Sets the state and sends a query on filter change.
*
* @param {string} filterValue - The filter text value.
* @private
* @returns {void}
*/
_onFilterChange(filterValue) {
this.setState({
// Clean the error if the filterValue is empty.
error: this.state.error && Boolean(filterValue),
filterValue,
isOpen: Boolean(this.state.items.length) && Boolean(filterValue),
items: filterValue ? this.state.items : [],
loading: Boolean(filterValue)
});
if (filterValue) {
this._sendQuery(filterValue);
}
}
_onRetry: () => void;
/**
* Retries the query on retry.
*
* @private
* @returns {void}
*/
_onRetry() {
this._sendQuery(this.state.filterValue);
}
_onSelectionChange: (Object) => void;
/**
* Updates the selected items when a selection event occurs.
*
* @param {Object} item - The selected item.
* @private
* @returns {void}
*/
_onSelectionChange(item) {
const existing
= this.state.selectedItems.find(k => k.value === item.value);
let selectedItems = this.state.selectedItems;
if (existing) {
selectedItems = selectedItems.filter(k => k !== existing);
} else {
selectedItems.push(this.props.onItemSelected(item));
}
this.setState({
isOpen: false,
selectedItems
});
if (this.props.onSelectionChange) {
this.props.onSelectionChange(selectedItems);
}
}
/**
* Renders the error UI.
*
* @returns {ReactElement|null}
*/
_renderError() {
if (!this.state.error) {
return null;
}
const content = (
<div className = 'autocomplete-error'>
<InlineDialogFailure
onRetry = { this._onRetry }
showSupportLink = { this.props.showSupportLink } />
</div>
);
return (
<AKInlineDialog
content = { content }
isOpen = { true } />
);
}
_sendQuery: (string) => void;
/**
* Sends a query to the resourceClient.
*
* @param {string} filterValue - The string to use for the search.
* @returns {void}
*/
_sendQuery(filterValue) {
if (!filterValue) {
return;
}
this.setState({
error: false
});
const resourceClient = this.props.resourceClient || {
makeQuery: () => Promise.resolve([]),
parseResults: results => results
};
resourceClient.makeQuery(filterValue)
.then(results => {
if (this.state.filterValue !== filterValue) {
this.setState({
error: false
});
return;
}
const itemGroups = [
{
items: resourceClient.parseResults(results)
}
];
this.setState({
items: itemGroups,
isOpen: true,
loading: false,
error: false
});
})
.catch(error => {
logger.error('MultiSelectAutocomplete error in query', error);
this.setState({
error: true,
loading: false,
isOpen: false
});
});
}
}
export default MultiSelectAutocomplete;
|
src/components/util/Terminate.js | mailvelope/mailvelope | /**
* Copyright (C) 2019 Mailvelope GmbH
* Licensed under the GNU Affero General Public License version 3
*/
import React from 'react';
import './Terminate.scss';
export default function Terminate() {
return (
<div className="terminate">
<div className="backdrop"></div>
<div className="symbol"><span className="icon icon-bolt" /></div>
</div>
);
}
|
assets/jqwidgets/demos/react/app/passwordinput/righttoleftlayout/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxPasswordInput from '../../../jqwidgets-react/react_jqxpasswordinput.js';
class App extends React.Component {
render() {
let localization = {
showPasswordString: "צג סיסמא",
hidePasswordString: "סתר סיסמא",
passwordStrengthString: "חוזק סיסמא",
tooShort: "קצר מדי",
weak: "חלש", fair: "הוגן",
good: "טוב", strong: "חזק"
};
return (
<JqxPasswordInput ref='passwordInput'
width={200} height={25}
placeHolder={'הזן את הסיסמה:'}
rtl={true}
showStrength={true}
localization={localization}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
frontend/components/CurrentSearch.js | datoszs/czech-lawyers | import React from 'react';
import PropTypes from 'prop-types';
import styles from './CurrentSearch.less';
const CurrentSearch = ({query, legend}) => (
<div className={styles.main}><span className={styles.legend}>{legend}</span> {query}</div>
);
CurrentSearch.propTypes = {
query: PropTypes.string.isRequired,
legend: PropTypes.string.isRequired,
};
export default CurrentSearch;
|
app/javascript/mastodon/features/ui/components/column.js | narabo/mastodon | import React from 'react';
import ColumnHeader from './column_header';
import PropTypes from 'prop-types';
import { debounce } from 'lodash';
const easingOutQuint = (x, t, b, c, d) => c*((t=t/d-1)*t*t*t*t + 1) + b;
const scrollTop = (node) => {
const startTime = Date.now();
const offset = node.scrollTop;
const targetY = -offset;
const duration = 1000;
let interrupt = false;
const step = () => {
const elapsed = Date.now() - startTime;
const percentage = elapsed / duration;
if (percentage > 1 || interrupt) {
return;
}
node.scrollTop = easingOutQuint(0, elapsed, offset, targetY, duration);
requestAnimationFrame(step);
};
step();
return () => {
interrupt = true;
};
};
class Column extends React.PureComponent {
static propTypes = {
heading: PropTypes.string,
icon: PropTypes.string,
children: PropTypes.node,
active: PropTypes.bool,
hideHeadingOnMobile: PropTypes.bool,
};
handleHeaderClick = () => {
const scrollable = this.node.querySelector('.scrollable');
if (!scrollable) {
return;
}
this._interruptScrollAnimation = scrollTop(scrollable);
}
handleScroll = debounce(() => {
if (typeof this._interruptScrollAnimation !== 'undefined') {
this._interruptScrollAnimation();
}
}, 200)
setRef = (c) => {
this.node = c;
}
render () {
const { heading, icon, children, active, hideHeadingOnMobile } = this.props;
let columnHeaderId = null;
let header = '';
if (heading) {
columnHeaderId = heading.replace(/ /g, '-');
header = <ColumnHeader icon={icon} active={active} type={heading} onClick={this.handleHeaderClick} hideOnMobile={hideHeadingOnMobile} columnHeaderId={columnHeaderId}/>;
}
return (
<div
ref={this.setRef}
role='region'
aria-labelledby={columnHeaderId}
className='column'
onScroll={this.handleScroll}>
{header}
{children}
</div>
);
}
}
export default Column;
|
app/javascript/mastodon/features/public_timeline/index.js | danhunsaker/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import PropTypes from 'prop-types';
import StatusListContainer from '../ui/containers/status_list_container';
import Column from '../../components/column';
import ColumnHeader from '../../components/column_header';
import { expandPublicTimeline } from '../../actions/timelines';
import { addColumn, removeColumn, moveColumn } from '../../actions/columns';
import ColumnSettingsContainer from './containers/column_settings_container';
import { connectPublicStream } from '../../actions/streaming';
const messages = defineMessages({
title: { id: 'column.public', defaultMessage: 'Federated timeline' },
});
const mapStateToProps = (state, { columnId }) => {
const uuid = columnId;
const columns = state.getIn(['settings', 'columns']);
const index = columns.findIndex(c => c.get('uuid') === uuid);
const onlyMedia = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyMedia']) : state.getIn(['settings', 'public', 'other', 'onlyMedia']);
const onlyRemote = (columnId && index >= 0) ? columns.get(index).getIn(['params', 'other', 'onlyRemote']) : state.getIn(['settings', 'public', 'other', 'onlyRemote']);
const timelineState = state.getIn(['timelines', `public${onlyMedia ? ':media' : ''}`]);
return {
hasUnread: !!timelineState && timelineState.get('unread') > 0,
onlyMedia,
onlyRemote,
};
};
export default @connect(mapStateToProps)
@injectIntl
class PublicTimeline extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static defaultProps = {
onlyMedia: false,
};
static propTypes = {
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
multiColumn: PropTypes.bool,
hasUnread: PropTypes.bool,
onlyMedia: PropTypes.bool,
onlyRemote: PropTypes.bool,
};
handlePin = () => {
const { columnId, dispatch, onlyMedia, onlyRemote } = this.props;
if (columnId) {
dispatch(removeColumn(columnId));
} else {
dispatch(addColumn(onlyRemote ? 'REMOTE' : 'PUBLIC', { other: { onlyMedia, onlyRemote } }));
}
}
handleMove = (dir) => {
const { columnId, dispatch } = this.props;
dispatch(moveColumn(columnId, dir));
}
handleHeaderClick = () => {
this.column.scrollTop();
}
componentDidMount () {
const { dispatch, onlyMedia, onlyRemote } = this.props;
dispatch(expandPublicTimeline({ onlyMedia, onlyRemote }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote }));
}
componentDidUpdate (prevProps) {
if (prevProps.onlyMedia !== this.props.onlyMedia || prevProps.onlyRemote !== this.props.onlyRemote) {
const { dispatch, onlyMedia, onlyRemote } = this.props;
this.disconnect();
dispatch(expandPublicTimeline({ onlyMedia, onlyRemote }));
this.disconnect = dispatch(connectPublicStream({ onlyMedia, onlyRemote }));
}
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
setRef = c => {
this.column = c;
}
handleLoadMore = maxId => {
const { dispatch, onlyMedia, onlyRemote } = this.props;
dispatch(expandPublicTimeline({ maxId, onlyMedia, onlyRemote }));
}
render () {
const { intl, shouldUpdateScroll, columnId, hasUnread, multiColumn, onlyMedia, onlyRemote } = this.props;
const pinned = !!columnId;
return (
<Column bindToDocument={!multiColumn} ref={this.setRef} label={intl.formatMessage(messages.title)}>
<ColumnHeader
icon='globe'
active={hasUnread}
title={intl.formatMessage(messages.title)}
onPin={this.handlePin}
onMove={this.handleMove}
onClick={this.handleHeaderClick}
pinned={pinned}
multiColumn={multiColumn}
>
<ColumnSettingsContainer columnId={columnId} />
</ColumnHeader>
<StatusListContainer
timelineId={`public${onlyRemote ? ':remote' : ''}${onlyMedia ? ':media' : ''}`}
onLoadMore={this.handleLoadMore}
trackScroll={!pinned}
scrollKey={`public_timeline-${columnId}`}
emptyMessage={<FormattedMessage id='empty_column.public' defaultMessage='There is nothing here! Write something publicly, or manually follow users from other servers to fill it up' />}
shouldUpdateScroll={shouldUpdateScroll}
bindToDocument={!multiColumn}
/>
</Column>
);
}
}
|
test/helpers/shallowRenderHelper.js | codemonkey-victor/snakes | /**
* 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();
}
|
components/Markdown/Markdown.story.js | rdjpalmer/bloom | import React from 'react';
import { storiesOf } from '@storybook/react';
import Markdown from './Markdown';
import guide from './markdown-guide.md';
storiesOf('Markdown', module)
.add('<Markdown />', () => (
<Markdown>{ guide }</Markdown>
));
|
frontend/src/Routes.js | tdv-casts/website | // @flow
import React from 'react';
import { Switch, Route } from 'react-router-dom';
import SearchCastByDate from './components/pages/SearchCastByDate';
import ListOfShows from './components/pages/ListOfShows';
import SubmitCast from './components/pages/SubmitCast';
import Error404 from './components/pages/Error404';
const Routes = () => (
<Switch>
<Route exact path="/" component={SearchCastByDate} />
<Route exact path="/shows/:location/:day/:month/:year/:time" component={SearchCastByDate} />
<Route exact path="/shows/new" component={SubmitCast} />
<Route exact path="/shows" component={ListOfShows} />
<Route component={Error404} />
</Switch>
);
export default Routes; |
fields/types/geopoint/GeoPointField.js | ratecity/keystone | import Field from '../Field';
import React from 'react';
import {
FormInput,
Grid,
} from '../../../admin/client/App/elemental';
module.exports = Field.create({
displayName: 'GeopointField',
statics: {
type: 'Geopoint',
},
focusTargetRef: 'lat',
handleLat (event) {
const { value = [], path, onChange } = this.props;
const newVal = event.target.value;
onChange({
path,
value: [value[0], newVal],
});
},
handleLong (event) {
const { value = [], path, onChange } = this.props;
const newVal = event.target.value;
onChange({
path,
value: [newVal, value[1]],
});
},
renderValue () {
const { value } = this.props;
if (value && value[1] && value[0]) {
return <FormInput noedit>{value[1]}, {value[0]}</FormInput>; // eslint-disable-line comma-spacing
}
return <FormInput noedit>(not set)</FormInput>;
},
renderField () {
const { value = [], path } = this.props;
return (
<Grid.Row xsmall="one-half" gutter={10}>
<Grid.Col>
<FormInput
autoComplete="off"
name={this.getInputName(path + '[1]')}
onChange={this.handleLat}
placeholder="Latitude"
ref="lat"
value={value[1]}
/>
</Grid.Col>
<Grid.Col width="one-half">
<FormInput
autoComplete="off"
name={this.getInputName(path + '[0]')}
onChange={this.handleLong}
placeholder="Longitude"
ref="lng"
value={value[0]}
/>
</Grid.Col>
</Grid.Row>
);
},
});
|
RNDemo/RNComment/node_modules/react-native/local-cli/templates/HelloNavigation/views/MainNavigator.js | 995996812/Web | 'use strict';
/**
* This is an example React Native app demonstrates ListViews, text input and
* navigation between a few screens.
* https://github.com/facebook/react-native
*/
import React, { Component } from 'react';
import { StackNavigator } from 'react-navigation';
import HomeScreenTabNavigator from './HomeScreenTabNavigator';
import ChatScreen from './chat/ChatScreen';
/**
* Top-level navigator. Renders the application UI.
*/
const MainNavigator = StackNavigator({
Home: {
screen: HomeScreenTabNavigator,
},
Chat: {
screen: ChatScreen,
},
});
export default MainNavigator;
|
app/javascript/mastodon/features/ui/components/columns_area.js | palon7/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import { links, getIndex, getLink } from './tabs_bar';
import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import BundleColumnError from './bundle_column_error';
import { Compose, Notifications, HomeTimeline, CommunityTimeline, PublicTimeline, HashtagTimeline, FavouritedStatuses } from '../../ui/util/async-components';
import { scrollRight } from '../../../scroll';
const componentMap = {
'COMPOSE': Compose,
'HOME': HomeTimeline,
'NOTIFICATIONS': Notifications,
'PUBLIC': PublicTimeline,
'COMMUNITY': CommunityTimeline,
'HASHTAG': HashtagTimeline,
'FAVOURITES': FavouritedStatuses,
};
@injectIntl
export default class ColumnsArea extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
columns: ImmutablePropTypes.list.isRequired,
singleColumn: PropTypes.bool,
children: PropTypes.node,
};
state = {
shouldAnimate: false,
}
componentWillReceiveProps() {
this.setState({ shouldAnimate: false });
}
componentDidMount() {
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
}
componentDidUpdate(prevProps) {
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.setState({ shouldAnimate: true });
if (this.props.children !== prevProps.children && !this.props.singleColumn) {
scrollRight(this.node);
}
}
handleSwipe = (index) => {
this.pendingIndex = index;
const nextLinkTranslationId = links[index].props['data-preview-title-id'];
const currentLinkSelector = '.tabs-bar__link.active';
const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;
// HACK: Remove the active class from the current link and set it to the next one
// React-router does this for us, but too late, feeling laggy.
document.querySelector(currentLinkSelector).classList.remove('active');
document.querySelector(nextLinkSelector).classList.add('active');
}
handleAnimationEnd = () => {
if (typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
setRef = (node) => {
this.node = node;
}
renderView = (link, index) => {
const columnIndex = getIndex(this.context.router.history.location.pathname);
const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
const icon = link.props['data-preview-icon'];
const view = (index === columnIndex) ?
React.cloneElement(this.props.children) :
<ColumnLoading title={title} icon={icon} />;
return (
<div className='columns-area' key={index}>
{view}
</div>
);
}
renderLoading = () => {
return <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { columns, children, singleColumn } = this.props;
const { shouldAnimate } = this.state;
const columnIndex = getIndex(this.context.router.history.location.pathname);
this.pendingIndex = null;
if (singleColumn) {
return columnIndex !== -1 ? (
<ReactSwipeableViews index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }}>
{links.map(this.renderView)}
</ReactSwipeableViews>
) : <div className='columns-area'>{children}</div>;
}
return (
<div className='columns-area' ref={this.setRef}>
{columns.map(column => {
const params = column.get('params', null) === null ? null : column.get('params').toJS();
return (
<BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading} error={this.renderError}>
{SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn />}
</BundleContainer>
);
})}
{React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}
</div>
);
}
}
|
app/javascript/mastodon/features/compose/components/character_counter.js | im-in-space/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { length } from 'stringz';
export default class CharacterCounter extends React.PureComponent {
static propTypes = {
text: PropTypes.string.isRequired,
max: PropTypes.number.isRequired,
};
checkRemainingText (diff) {
if (diff < 0) {
return <span className='character-counter character-counter--over'>{diff}</span>;
}
return <span className='character-counter'>{diff}</span>;
}
render () {
const diff = this.props.max - length(this.props.text);
return this.checkRemainingText(diff);
}
}
|
src/components/structures/LeftPanel.js | aperezdc/matrix-react-sdk | /*
Copyright 2015, 2016 OpenMarket Ltd
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { MatrixClient } from 'matrix-js-sdk';
import { KeyCode } from '../../Keyboard';
import sdk from '../../index';
import dis from '../../dispatcher';
import VectorConferenceHandler from '../../VectorConferenceHandler';
import SettingsStore from '../../settings/SettingsStore';
var LeftPanel = React.createClass({
displayName: 'LeftPanel',
// NB. If you add props, don't forget to update
// shouldComponentUpdate!
propTypes: {
collapsed: PropTypes.bool.isRequired,
},
contextTypes: {
matrixClient: PropTypes.instanceOf(MatrixClient),
},
getInitialState: function() {
return {
searchFilter: '',
};
},
componentWillMount: function() {
this.focusedElement = null;
},
shouldComponentUpdate: function(nextProps, nextState) {
// MatrixChat will update whenever the user switches
// rooms, but propagating this change all the way down
// the react tree is quite slow, so we cut this off
// here. The RoomTiles listen for the room change
// events themselves to know when to update.
// We just need to update if any of these things change.
if (
this.props.collapsed !== nextProps.collapsed ||
this.props.disabled !== nextProps.disabled
) {
return true;
}
if (this.state.searchFilter !== nextState.searchFilter) {
return true;
}
return false;
},
_onFocus: function(ev) {
this.focusedElement = ev.target;
},
_onBlur: function(ev) {
this.focusedElement = null;
},
_onKeyDown: function(ev) {
if (!this.focusedElement) return;
let handled = true;
switch (ev.keyCode) {
case KeyCode.TAB:
this._onMoveFocus(ev.shiftKey);
break;
case KeyCode.UP:
this._onMoveFocus(true);
break;
case KeyCode.DOWN:
this._onMoveFocus(false);
break;
case KeyCode.ENTER:
this._onMoveFocus(false);
if (this.focusedElement) {
this.focusedElement.click();
}
break;
default:
handled = false;
}
if (handled) {
ev.stopPropagation();
ev.preventDefault();
}
},
_onMoveFocus: function(up) {
let element = this.focusedElement;
// unclear why this isn't needed
// var descending = (up == this.focusDirection) ? this.focusDescending : !this.focusDescending;
// this.focusDirection = up;
let descending = false; // are we currently descending or ascending through the DOM tree?
let classes;
do {
const child = up ? element.lastElementChild : element.firstElementChild;
const sibling = up ? element.previousElementSibling : element.nextElementSibling;
if (descending) {
if (child) {
element = child;
} else if (sibling) {
element = sibling;
} else {
descending = false;
element = element.parentElement;
}
} else {
if (sibling) {
element = sibling;
descending = true;
} else {
element = element.parentElement;
}
}
if (element) {
classes = element.classList;
if (classes.contains("mx_LeftPanel")) { // we hit the top
element = up ? element.lastElementChild : element.firstElementChild;
descending = true;
}
}
} while (element && !(
classes.contains("mx_RoomTile") ||
classes.contains("mx_SearchBox_search") ||
classes.contains("mx_RoomSubList_ellipsis")));
if (element) {
element.focus();
this.focusedElement = element;
this.focusedDescending = descending;
}
},
onHideClick: function() {
dis.dispatch({
action: 'hide_left_panel',
});
},
onSearch: function(term) {
this.setState({ searchFilter: term });
},
collectRoomList: function(ref) {
this._roomList = ref;
},
render: function() {
const RoomList = sdk.getComponent('rooms.RoomList');
const TagPanel = sdk.getComponent('structures.TagPanel');
const BottomLeftMenu = sdk.getComponent('structures.BottomLeftMenu');
const CallPreview = sdk.getComponent('voip.CallPreview');
let topBox;
if (this.context.matrixClient.isGuest()) {
const LoginBox = sdk.getComponent('structures.LoginBox');
topBox = <LoginBox collapsed={ this.props.collapsed }/>;
} else {
const SearchBox = sdk.getComponent('structures.SearchBox');
topBox = <SearchBox collapsed={ this.props.collapsed } onSearch={ this.onSearch } />;
}
const classes = classNames(
"mx_LeftPanel",
{
"collapsed": this.props.collapsed,
},
);
const tagPanelEnabled = !SettingsStore.getValue("TagPanel.disableTagPanel");
const tagPanel = tagPanelEnabled ? <TagPanel /> : <div />;
const containerClasses = classNames(
"mx_LeftPanel_container", "mx_fadable",
{
"mx_LeftPanel_container_collapsed": this.props.collapsed,
"mx_LeftPanel_container_hasTagPanel": tagPanelEnabled,
"mx_fadable_faded": this.props.disabled,
},
);
return (
<div className={containerClasses}>
{ tagPanel }
<aside className={classes} onKeyDown={ this._onKeyDown } onFocus={ this._onFocus } onBlur={ this._onBlur }>
{ topBox }
<CallPreview ConferenceHandler={VectorConferenceHandler} />
<RoomList
ref={this.collectRoomList}
collapsed={this.props.collapsed}
searchFilter={this.state.searchFilter}
ConferenceHandler={VectorConferenceHandler} />
<BottomLeftMenu collapsed={this.props.collapsed}/>
</aside>
</div>
);
}
});
module.exports = LeftPanel;
|
src/app.js | phnz/kitematic | require.main.paths.splice(0, 0, process.env.NODE_PATH);
import remote from 'remote';
var Menu = remote.require('menu');
import React from 'react';
import SetupStore from './stores/SetupStore';
import ipc from 'ipc';
import machine from './utils/DockerMachineUtil';
import metrics from './utils/MetricsUtil';
import template from './menutemplate';
import webUtil from './utils/WebUtil';
import hubUtil from './utils/HubUtil';
var urlUtil = require('./utils/URLUtil');
var app = remote.require('app');
import request from 'request';
import docker from './utils/DockerUtil';
import hub from './utils/HubUtil';
import Router from 'react-router';
import routes from './routes';
import routerContainer from './router';
import repositoryActions from './actions/RepositoryActions';
hubUtil.init();
if (hubUtil.loggedin()) {
repositoryActions.repos();
}
repositoryActions.recommended();
webUtil.addWindowSizeSaving();
webUtil.addLiveReload();
webUtil.addBugReporting();
webUtil.disableGlobalBackspace();
Menu.setApplicationMenu(Menu.buildFromTemplate(template()));
metrics.track('Started App');
metrics.track('app heartbeat');
setInterval(function () {
metrics.track('app heartbeat');
}, 14400000);
var router = Router.create({
routes: routes
});
router.run(Handler => React.render(<Handler/>, document.body));
routerContainer.set(router);
SetupStore.setup().then(() => {
Menu.setApplicationMenu(Menu.buildFromTemplate(template()));
docker.init();
if (!hub.prompted() && !hub.loggedin()) {
router.transitionTo('login');
} else {
router.transitionTo('search');
}
}).catch(err => {
metrics.track('Setup Failed', {
step: 'catch',
message: err.message
});
throw err;
});
ipc.on('application:quitting', () => {
if (localStorage.getItem('settings.closeVMOnQuit') === 'true') {
machine.stop();
}
});
// Event fires when the app receives a docker:// URL such as
// docker://repository/run/redis
ipc.on('application:open-url', opts => {
request.get('https://kitematic.com/flags.json', (err, response, body) => {
if (err || response.statusCode !== 200) {
return;
}
var flags = JSON.parse(body);
if (!flags) {
return;
}
urlUtil.openUrl(opts.url, flags, app.getVersion());
});
});
module.exports = {
router: router
};
|
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/Nav.js | GoogleCloudPlatform/prometheus-engine | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';
const propTypes = {
tabs: PropTypes.bool,
pills: PropTypes.bool,
vertical: PropTypes.oneOfType([PropTypes.bool, PropTypes.string]),
horizontal: PropTypes.string,
justified: PropTypes.bool,
fill: PropTypes.bool,
navbar: PropTypes.bool,
card: PropTypes.bool,
tag: tagPropType,
className: PropTypes.string,
cssModule: PropTypes.object,
};
const defaultProps = {
tag: 'ul',
vertical: false,
};
const getVerticalClass = (vertical) => {
if (vertical === false) {
return false;
} else if (vertical === true || vertical === 'xs') {
return 'flex-column';
}
return `flex-${vertical}-column`;
};
const Nav = (props) => {
const {
className,
cssModule,
tabs,
pills,
vertical,
horizontal,
justified,
fill,
navbar,
card,
tag: Tag,
...attributes
} = props;
const classes = mapToCssModules(classNames(
className,
navbar ? 'navbar-nav' : 'nav',
horizontal ? `justify-content-${horizontal}` : false,
getVerticalClass(vertical),
{
'nav-tabs': tabs,
'card-header-tabs': card && tabs,
'nav-pills': pills,
'card-header-pills': card && pills,
'nav-justified': justified,
'nav-fill': fill,
}
), cssModule);
return (
<Tag {...attributes} className={classes} />
);
};
Nav.propTypes = propTypes;
Nav.defaultProps = defaultProps;
export default Nav;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/notification/network-check.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const NotificationNetworkCheck = (props) => (
<SvgIcon {...props}>
<path d="M15.9 5c-.17 0-.32.09-.41.23l-.07.15-5.18 11.65c-.16.29-.26.61-.26.96 0 1.11.9 2.01 2.01 2.01.96 0 1.77-.68 1.96-1.59l.01-.03L16.4 5.5c0-.28-.22-.5-.5-.5zM1 9l2 2c2.88-2.88 6.79-4.08 10.53-3.62l1.19-2.68C9.89 3.84 4.74 5.27 1 9zm20 2l2-2c-1.64-1.64-3.55-2.82-5.59-3.57l-.53 2.82c1.5.62 2.9 1.53 4.12 2.75zm-4 4l2-2c-.8-.8-1.7-1.42-2.66-1.89l-.55 2.92c.42.27.83.59 1.21.97zM5 13l2 2c1.13-1.13 2.56-1.79 4.03-2l1.28-2.88c-2.63-.08-5.3.87-7.31 2.88z"/>
</SvgIcon>
);
NotificationNetworkCheck.displayName = 'NotificationNetworkCheck';
NotificationNetworkCheck.muiName = 'SvgIcon';
export default NotificationNetworkCheck;
|
components/card/CardTitle.js | showings/react-toolbox | import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import { themr } from 'react-css-themr';
import { CARD } from '../identifiers';
import InjectAvatar from '../avatar/Avatar';
const factory = (Avatar) => {
const CardTitle = ({ avatar, children, className, subtitle, theme, title, ...other }) => {
const classes = classnames(theme.cardTitle, {
[theme.small]: avatar,
[theme.large]: !avatar,
}, className);
return (
<div className={classes} {...other}>
{typeof avatar === 'string' ? <Avatar image={avatar} theme={theme} /> : avatar}
<div>
{title && <h5 className={theme.title}>{title}</h5>}
{children && typeof children === 'string' && (
<h5 className={theme.title}>{children}</h5>
)}
{subtitle && <p className={theme.subtitle}>{subtitle}</p>}
{children && typeof children !== 'string' && children}
</div>
</div>
);
};
CardTitle.propTypes = {
avatar: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
children: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
PropTypes.array,
]),
className: PropTypes.string,
subtitle: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
theme: PropTypes.shape({
large: PropTypes.string,
title: PropTypes.string,
small: PropTypes.string,
subtitle: PropTypes.string,
}),
title: PropTypes.oneOfType([
PropTypes.string,
PropTypes.element,
]),
};
return CardTitle;
};
const CardTitle = factory(InjectAvatar);
export default themr(CARD)(CardTitle);
export { CardTitle };
export { factory as cardTitleFactory };
|
packages/lore-hook-dialogs-bootstrap/src/blueprints/destroy/Wizard/forms/Confirmation.js | lore/lore-forms | import React from 'react';
import createReactClass from 'create-react-class';
import PropTypes from 'prop-types';
export default createReactClass({
displayName: 'Confirmation',
propTypes: {
callbacks: PropTypes.object
},
render: function() {
const { modelName } = this.props;
const {
title = `Delete ${_.capitalize(modelName)}`,
description = '',
successMessage = `${_.capitalize(modelName)} deleted.`,
callbacks
} = this.props;
return (
<div>
<div className="modal-header">
<button type="button" className="close" onClick={this.onCancel}>
<span>×</span>
</button>
{title ? (
<h4 className="modal-title">
{title}
</h4>
) : null}
{description ? (
<p className="help-block">
{description}
</p>
) : null}
</div>
<div className="modal-body">
{successMessage}
</div>
<div className="modal-footer">
<button
className="btn btn-primary"
onClick={callbacks.onCancel}
>
Close
</button>
</div>
</div>
);
}
});
|
src/containers/pages/decks/deck/right-container/sections/comments/section-footer-commentbox.js | vFujin/HearthLounge | import React from 'react';
import PropTypes from 'prop-types';
import SectionFooterHeader from './section-footer-header';
import TextEditor from '../../../../../../../components/text-editor/text-editor';
const SectionFooterCommentBox = ({deckCommentControlled, handleTextEditorBBcodeClick, previewIsActive, deckCommentPostingStatus, handleInputChange, handleHideCommentClick, handlePreviewClick, handlePostCommentClick}) => {
return (
<div className="section_footer--wrapper">
<SectionFooterHeader handleHideCommentClick={handleHideCommentClick}
previewIsActive={previewIsActive}
deckCommentPostingStatus={deckCommentPostingStatus}
handlePreviewClick={handlePreviewClick}
handlePostCommentClick={handlePostCommentClick}/>
<TextEditor editorId="deckCommentControlled"
previewId="deckComment"
handleInputChange={handleInputChange}
value={deckCommentControlled}
handleTagInsertion={handleTextEditorBBcodeClick}/>
</div>
)
};
export default SectionFooterCommentBox;
SectionFooterCommentBox.propTypes = {
deckCommentControlled: PropTypes.string,
updateComment: PropTypes.func,
handleInputChange: PropTypes.func,
handleHideCommentClick: PropTypes.func,
handlePreviewClick: PropTypes.func,
handlePostCommentClick: PropTypes.func,
}; |
V2-Node/esquenta.v2/UI/src/views/Users/User.js | leandrocristovao/esquenta | import React, { Component } from 'react';
import { Card, CardBody, CardHeader, Col, Row, Table } from 'reactstrap';
import usersData from './UsersData'
class User extends Component {
render() {
const user = usersData.find( user => user.id.toString() === this.props.match.params.id)
const userDetails = user ? Object.entries(user) : [['id', (<span><i className="text-muted icon-ban"></i> Not found</span>)]]
return (
<div className="animated fadeIn">
<Row>
<Col lg={6}>
<Card>
<CardHeader>
<strong><i className="icon-info pr-1"></i>User id: {this.props.match.params.id}</strong>
</CardHeader>
<CardBody>
<Table responsive striped hover>
<tbody>
{
userDetails.map(([key, value]) => {
return (
<tr>
<td>{`${key}:`}</td>
<td><strong>{value}</strong></td>
</tr>
)
})
}
</tbody>
</Table>
</CardBody>
</Card>
</Col>
</Row>
</div>
)
}
}
export default User;
|
src/popup/components/Message/index.js | fluany/fluany | /**
* @fileOverview A component to show messages/feedback to the user
* @name index.js<Message>
* @license GNU General Public License v3.0
*/
import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { changeMessage } from 'actions/flags'
const Message = ({ onChangeMessage, message }) => {
const onClose = () => onChangeMessage({ error: false, success: false })
return (
<div
className={`error-container ${
message.error ? 'error' : message.success ? 'success' : ''
}`}
>
<div className='error-close' onClick={onClose} />
<svg className='alert-icon'>
<use xlinkHref={message.error ? '#icon-alert' : '#icon-smiley'} />
</svg>
<p className='error-message'>{message.info}</p>
</div>
)
}
const mapStateToProps = state => ({
message: state.flags.message
})
function mapDispatchToProps (dispatch) {
return {
onChangeMessage: message => dispatch(changeMessage(message))
}
}
const { func, object } = PropTypes
/**
* PropTypes
* @property {Function} onChangeMessage A function to dispatch action to show message
* @property {Object} message The information of the message(if is error, success, and the message text)
*/
Message.propTypes = {
onChangeMessage: func.isRequired,
message: object.isRequired
}
export default connect(mapStateToProps, mapDispatchToProps)(Message)
|
Self/FlexDemo2.js | CoderJJMa/React-native-learn | import React, { Component } from 'react';
import { View,Text } from 'react-native';
/**
* 弹性(Flex)宽高
在组件样式中使用flex可以使其在可利用的空间中动态地扩张或收缩。
一般而言我们会使用flex:1来指定某个组件扩张以撑满所有剩余的空间。
如果有多个并列的子组件使用了flex:1,则这些子组件会平分父容器中剩余的空间。如果这些并列的子组件的flex值不一样,则谁的值更大,
谁占据剩余空间的比例就更大(即占据剩余空间的比等于并列组件间flex值的比)。
组件能够撑满剩余空间的前提是其父容器的尺寸不为零。
如果父容器既没有固定的width和height,也没有设定flex,则父容器的尺寸为零。其子组件如果使用了flex,也是无法显示的。
*/
// class FlexDemo2 extends Component {
// render() {
// return (
// // 试试去掉父View中的`flex: 1`。
// // 则父View不再具有尺寸,因此子组件也无法再撑开。
// // 然后再用`height: 300`来代替父View的`flex: 1`试试看?
// <View style={{/*flex: 1*/height:300,backgroundColor:'#874621'}}>
// <View style={{flex: 0.1, backgroundColor: 'powderblue'}} />
// <View style={{flex: 0.2, backgroundColor: 'skyblue'}} />
// <View style={{flex: 0.3, backgroundColor: 'steelblue'}} />
// </View>
// );
// }
// };
// export default class FlexDirectionBasics extends Component {
// render() {
// return (
// // 尝试把`flexDirection`改为`column`看看
// <View style={{flex: 1, flexDirection: 'row'}}>
// <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
// </View>
// );
// }
// };
// export default class JustifyContentBasics extends Component {
// render() {
// return (
// // 尝试把`justifyContent`改为`center`看看
// // 尝试把`flexDirection`改为`row`看看
// <View style={{
// flex: 1,
// flexDirection: 'row',
// justifyContent: 'center',
// flexWrap:'wrap'
// }}>
// <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
// <View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
// </View>
// );
// }
// };
export default class AlignItemsBasics extends Component {
render() {
return (
// 尝试把`alignItems`改为`flex-start`看看
// 尝试把`justifyContent`改为`flex-end`看看
// 尝试把`flexDirection`改为`row`看看
<View style={{
flex: 1,
flexDirection: 'column',
justifyContent: 'flex-end',
alignItems: 'flex-start',
}}>
<View style={{width: 50, height: 50, backgroundColor: 'powderblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'skyblue'}} />
<View style={{width: 50, height: 50, backgroundColor: 'steelblue'}} />
</View>
);
}
};
|
comment-app/src/CommentApp.js | kcf5521/Web-front-end-Demo | import React, { Component } from 'react';
import CommentInput from './CommentInput'
import CommentList from './CommentList'
class CommentApp extends Component {
constructor () {
super()
this.state = {
comments: []
}
}
//加载评论
componentWillMount () {
this._loadComments()
}
//将评论放到this.state中
_loadComments () {
let comments = localStorage.getItem('comments')
if (comments) {
//从一个字符串中解析出json对象
comments = JSON.parse(comments)
this.setState({ comments })
}
}
_saveComments (comments) {
//从一个对象中解析出字符串
localStorage.setItem('comments', JSON.stringify(comments))
}
handleSubmitComment (comment) {
if (!comment) return
if (!comment.username) return alert('请输入用户名')
if (!comment.content) return alert('请输入评论内容')
const comments = this.state.comments
comments.push(comment)//
this.setState({ comments })
this._saveComments(comments)
}
render() {
return (
<div className="wrapper">
<CommentInput onSubmit={this.handleSubmitComment.bind(this)} />
<CommentList comments={this.state.comments}/>
</div>
);
}
}
export default CommentApp;
|
ki1st-xtqb/src/main/webapp/front/app/components/App.js | chosenki/chosenki-2016 | import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'
const App = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
)
export default App
|
js/components/pages/NotFound.react.js | beiciye/login-flow | import React, { Component } from 'react';
import { Link } from 'react-router';
class NotFound extends Component {
render() {
return(
<article>
<h1>Page not found.</h1>
<Link to="/" className="btn">Home</Link>
</article>
);
}
}
export default NotFound;
|
src/index.js | dyegolara/sismo-frontend | import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, Redirect, browserHistory } from 'react-router'
import './index.css'
import './bulma.css'
import App from './App'
import NewReport from './newReport'
import registerServiceWorker from './registerServiceWorker'
const $app = document.getElementById('root')
const routes = (
<Route>
<Route path='/personas' component={App} />
<Route path='/personas/nuevo-reporte' component={NewReport} />
<Route path='/edificios' component={App} />
<Route path='/albergues' component={App} />
<Route path='/donaciones' component={App} />
<Route path='/mapa' component={App} />
<Redirect from='/' to='/personas' />
</Route>
)
ReactDOM.render(<Router routes={routes} history={browserHistory} />, $app)
registerServiceWorker()
|
src/js/components/ui/UserTopData/UserTopData.js | nekuno/client | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './UserTopData.scss';
export default class UserTopData extends Component {
static propTypes = {
username : PropTypes.string.isRequired,
usernameColor: PropTypes.string,
location : PropTypes.object,
age : PropTypes.string.isRequired,
subColor : PropTypes.string
};
render() {
const {username, location, age, usernameColor, subColor} = this.props;
return (
<div className={styles.userTopData}>
<div className={styles.username} style={{color: usernameColor}}>{username}</div>
<div className={styles.ageCity} style={{color: subColor}}>{location ? location.locality || location.country || 'N/A' : 'N/A'} • {age}</div>
</div>
);
}
}
UserTopData.defaultProps = {
usernameColor: 'white',
subColor : 'white'
}; |
lib/Navigation/Tabs/tabFour/views/TabFourScreenTwo.js | Ezeebube5/Nairasense | import React from 'react';
import { View, Text } from 'react-native';
export default class TabFourScreenTwo extends React.Component {
static navigationOptions = {
tabBarLabel: 'Audio'}
render() {
return (
<View
style={{
flex: 1,
backgroundColor: 'white',
alignItems: 'center',
justifyContent: 'center'
}}
>
<Text>{ 'Tab Four en Two' }</Text>
</View>
);
}
}
|
mob5/src/components/Contacts/ContactList/Footer.js | leGoupil/mob5 | import React from 'react';
import { View, Text, StyleSheet, TouchableOpacity } from 'react-native';
const styles = StyleSheet.create({
container: {
flex: 1,
padding: 8,
alignItems: 'center',
justifyContent: 'center',
},
button: {
borderColor: '#8E8E8E',
borderWidth: StyleSheet.hairlineWidth,
paddingHorizontal: 20,
paddingVertical: 10,
borderRadius: 5,
},
text: {
color: '#8E8E8E',
},
});
export default class Footer extends React.Component {
render() {
const { refresh } = this.props.itemProps;
const action = () => {
refresh();
};
return (
<View style={styles.container}>
<TouchableOpacity style={styles.button} onPress={action}>
<Text style={styles.text}>Raffraichir</Text>
</TouchableOpacity>
</View>
)
}
}
|
src/svg-icons/alert/error.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AlertError = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1 15h-2v-2h2v2zm0-4h-2V7h2v6z"/>
</SvgIcon>
);
AlertError = pure(AlertError);
AlertError.displayName = 'AlertError';
AlertError.muiName = 'SvgIcon';
export default AlertError;
|
src/decorators/withViewport.js | jmattfong/jmattfong.com | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.