path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/charts/Scatterplot.js
|
rsamec/react-pathjs-chart
|
import React from 'react';
import _ from 'lodash';
import Options from '../component/Options.js';
import fontAdapt from '../fontAdapter.js';
import styleSvg from '../styleSvg';
var Stock = require('paths-js/stock');
var Axis = require('../component/Axis');
var Path = require('paths-js/path');
export default class Scatterplot extends React.Component {
constructor(props) {
super(props);
this.state = {finished:true};
}
getMaxAndMin(chart, key,scale) {
var maxValue;
var minValue;
_.each(chart.curves, function (serie) {
var values = _.map(serie.item, function (item) {
return item[key]
});
var max = _.max(values);
if (maxValue === undefined || max > maxValue) maxValue = max;
var min = _.min(values);
if (minValue === undefined || min < minValue) minValue = min;
});
return {
minValue: minValue,
maxValue: maxValue,
min:scale(minValue),
max:scale(maxValue)
}
}
onEnter(index,event) {
this.props.data[0][index].selected = true;
this.setState({data: this.props.data});
}
onLeave(index,event){
this.props.data[0][index].selected = false;
this.setState({data:this.props.data});
}
render() {
var noDataMsg = this.props.noDataMessage || "No data available";
if (this.props.data === undefined) return (<span>{noDataMsg}</span>);
var options = new Options(this.props);
var palette = this.props.palette || ["#3E90F0", "#7881C2", "#707B82"];
var accessor = function (key) {
return function (x) {
return x[key];
}
};
var chart = Stock({
data: this.props.data,
xaccessor: accessor(this.props.xKey),
yaccessor: accessor(this.props.yKey),
width: options.chartWidth,
height: options.chartHeight,
closed: false
});
var chartArea = {
x:this.getMaxAndMin(chart,this.props.xKey,chart.xscale),
y:this.getMaxAndMin(chart,this.props.yKey,chart.yscale),
margin:options.margin
};
var sec = options.animate.fillTransition || 0;
var fillOpacityStyle = {fillOpacity:this.state.finished?1:0,transition: this.state.finished?'fill-opacity ' + sec + 's':''};
var textStyle = fontAdapt(options.label);
var colors = styleSvg({},options);
var points = _.map(chart.curves, function (c, i) {
return _.map(c.line.path.points(),function(p,j) {
var item = c.item[j];
return (<g key={'k' + j} transform={"translate(" + p[0] + "," + p[1] + ")"}>
<circle {...colors} cx={0} cy={0} r={options.r || 5} style={fillOpacityStyle} onMouseEnter={this.onEnter.bind(this,j)} onMouseLeave={this.onLeave.bind(this,j)}/>
{item.selected?<text style={textStyle} transform="translate(15, 5)" text-anchor="start">{item.title}</text>:null}
</g>)
},this)
},this);
return (<svg ref="vivus" width={options.width} height={options.height}>
<g transform={"translate(" + options.margin.left + "," + options.margin.top + ")"}>
{ points }
<Axis scale ={chart.xscale} options={options.axisX} chartArea={chartArea} />
<Axis scale ={chart.yscale} options={options.axisY} chartArea={chartArea} />
</g>
</svg>);
}
}
Scatterplot.defaultProps= {
xKey:'',
yKey:'',
options: {
width: 600,
height: 600,
margin: {top: 40, left: 60, bottom: 30, right: 30},
fill: "#2980B9",
stroke: "#3E90F0",
animate: {
type: 'delayed',
duration: 200,
fillTransition:3
},
label: {
fontFamily: 'Arial',
fontSize: 14,
bold: true,
color: '#34495E'
},
axisX: {
showAxis: true,
showLines: true,
showLabels: true,
showTicks: true,
zeroAxis: false,
orient: 'bottom',
label: {
fontFamily: 'Arial',
fontSize: 14,
bold: true,
color: '#34495E'
}
},
axisY: {
showAxis: true,
showLines: true,
showLabels: true,
showTicks: true,
zeroAxis: false,
orient: 'left',
label: {
fontFamily: 'Arial',
fontSize: 14,
bold: true,
color: '#34495E'
}
}
}
}
|
src/server.js
|
ThatCheck/AutoLib
|
import Express from 'express';
import React from 'react';
import ReactDOM from 'react-dom/server';
import config from './config';
import favicon from 'serve-favicon';
import compression from 'compression';
import httpProxy from 'http-proxy';
import path from 'path';
import createStore from './redux/create';
import ApiClient from './helpers/ApiClient';
import Html from './helpers/Html';
import PrettyError from 'pretty-error';
import http from 'http';
import SocketIo from 'socket.io';
import cookie from 'react-cookie';import {IntlProvider} from 'react-intl';
import { intlDataHash, getCurrentLocale } from './utils/intl';
import {ReduxRouter} from 'redux-router';
import createHistory from 'history/lib/createMemoryHistory';
import {reduxReactRouter, match} from 'redux-router/server';
import {Provider} from 'react-redux';
import qs from 'query-string';
import getRoutes from './routes';
import getStatusFromRoutes from './helpers/getStatusFromRoutes';
import BodyClassName from 'react-body-classname';
/**
* Flatten the message locales
* @param ob
* @returns {*}
*/
function flattenMessages(ob) {
const toReturn = {};
for (let i in ob) {
if (!ob.hasOwnProperty(i)) continue;
if (typeof ob[i] === 'object') {
const flatObject = flattenMessages(ob[i]);
for (let x in flatObject) {
if (!flatObject.hasOwnProperty(x)) continue;
toReturn[i + '.' + x] = flatObject[x];
}
} else {
toReturn[i] = ob[i];
}
}
return toReturn;
}
const pretty = new PrettyError();
const app = new Express();
const server = new http.Server(app);
const proxy = httpProxy.createProxyServer({
target: 'http://' + config.apiHost + ':' + config.apiPort,
ws: true
});
var areIntlLocalesSupported = require('intl-locales-supported');
var localesMyAppSupports = config.locales;
if (global.Intl) {
// Determine if the built-in `Intl` has the locale data we need.
if (!areIntlLocalesSupported(localesMyAppSupports)) {
// `Intl` exists, but it doesn't have the data we need, so load the
// polyfill and replace the constructors with need with the polyfill's.
require('intl');
Intl.NumberFormat = IntlPolyfill.NumberFormat;
Intl.DateTimeFormat = IntlPolyfill.DateTimeFormat;
}
} else {
// No `Intl`, so use and load the polyfill.
global.Intl = require('intl');
}
app.use(compression());
app.use(favicon(path.join(__dirname, '..', 'static', 'favicon.ico')));
app.use(Express.static(path.join(__dirname, '..', 'static')));
// Proxy to API server
app.use('/api', (req, res) => {
proxy.web(req, res);
});
// added the error handling to avoid https://github.com/nodejitsu/node-http-proxy/issues/527
proxy.on('error', (error, req, res) => {
let json;
if (error.code !== 'ECONNRESET') {
console.error('proxy error', error);
}
if (!res.headersSent) {
res.writeHead(500, {'content-type': 'application/json'});
}
json = {error: 'proxy_error', reason: error.message};
res.end(JSON.stringify(json));
});
app.use((req, res) => {
cookie.plugToRequest(req, res);
if (__DEVELOPMENT__) {
// Do not cache webpack stats: the script file would change since
// hot module replacement is enabled in the development env
webpackIsomorphicTools.refresh();
}
BodyClassName.rewind();
const lang = cookie.load('locale') || 'fr';
const localeFromRoute = getCurrentLocale(lang);
const locale = intlDataHash[localeFromRoute].locale;
const localeFileName = intlDataHash[localeFromRoute].file;
const localeMessages = flattenMessages(require(`./intl/${localeFromRoute}`));
const localeData = require(`react-intl/dist/locale-data/${localeFileName}`);
const client = new ApiClient(req);
const store = createStore(reduxReactRouter, getRoutes, createHistory, client);
function hydrateOnClient() {
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html locale={locale} localeData={localeData} localeMessages={localeMessages} assets={webpackIsomorphicTools.assets()} store={store}/>));
}
if (__DISABLE_SSR__) {
hydrateOnClient();
return;
}
store.dispatch(match(req.originalUrl, (error, redirectLocation, routerState) => {
if (redirectLocation) {
res.redirect(redirectLocation.pathname + redirectLocation.search);
} else if (error) {
console.error('ROUTER ERROR:', pretty.render(error));
res.status(500);
hydrateOnClient();
} else if (!routerState) {
res.status(500);
hydrateOnClient();
} else {
// Workaround redux-router query string issue:
// https://github.com/rackt/redux-router/issues/106
if (routerState.location.search && !routerState.location.query) {
routerState.location.query = qs.parse(routerState.location.search);
}
store.getState().router.then(() => {
const component = (
<Provider store={store} key="provider">
<IntlProvider locale={locale} messages={localeMessages}>
<ReduxRouter/>
</IntlProvider>
</Provider>
);
const status = getStatusFromRoutes(routerState.routes);
if (status) {
res.status(status);
}
res.send('<!doctype html>\n' +
ReactDOM.renderToString(<Html locale={locale} localeData={localeData} localeMessages={localeMessages} assets={webpackIsomorphicTools.assets()} component={component} store={store}/>));
}).catch((err) => {
console.error('DATA FETCHING ERROR:', pretty.render(err));
res.status(500);
hydrateOnClient();
});
}
}));
});
if (config.port) {
if (config.isProduction) {
const io = new SocketIo(server);
io.path('/api/ws');
}
server.listen(config.port, (err) => {
if (err) {
console.error(err);
}
console.info('----\n==> ✅ %s is running, talking to API server on %s.', config.app.title, config.apiPort);
console.info('==> 💻 Open http://%s:%s in a browser to view the app.', config.host, config.port);
});
} else {
console.error('==> ERROR: No PORT environment variable has been specified');
}
|
src/components/common/svg-icons/notification/sim-card-alert.js
|
abzfarah/Pearson.NAPLAN.GnomeH
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationSimCardAlert = (props) => (
<SvgIcon {...props}>
<path d="M18 2h-8L4.02 8 4 20c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-5 15h-2v-2h2v2zm0-4h-2V8h2v5z"/>
</SvgIcon>
);
NotificationSimCardAlert = pure(NotificationSimCardAlert);
NotificationSimCardAlert.displayName = 'NotificationSimCardAlert';
NotificationSimCardAlert.muiName = 'SvgIcon';
export default NotificationSimCardAlert;
|
plugins/react/frontend/components/form/RandomButton/index.js
|
pure-ui/styleguide
|
import React from 'react';
import Button from '../Button';
import styles from './styles.css';
const RandomButton = ({ groupType = 'right', ...otherProps }) => (
<Button {...otherProps} groupType={groupType}>
<svg
className={styles.svg}
width="16px"
height="13px"
viewBox="0 0 16 13"
version="1.1"
>
<g stroke="none" strokeWidth="1" fill="none" fill-rule="evenodd">
<g transform="translate(1.000000, 0.000000)">
<path
d="M10.9831425,0.248038552 L10.9831425,5.66105236 L15.0588235,2.95454545 L10.9831425,0.248038552 Z" // eslint-disable-line max-len
fill="#999999"
/>
<path
d="M10.9831425,7.33894764 L10.9831425,12.7519614 L15.0588235,10.0454545 L10.9831425,7.33894764 Z" // eslint-disable-line max-len
fill="#999999"
/>
<path
d="M0.739722594,10.0454545 L3.48285708,10.0454545 C4.03747416,10.0454545 4.72728114,9.66421648 5.01712405,9.20418863 L8.42469998,3.79581137 C8.71743515,3.33119303 9.40462323,2.95454545 9.95374013,2.95454545 L11.6791444,2.95454545" // eslint-disable-line max-len
stroke="#979797"
strokeWidth="2"
strokeLinecap="square"
/>
<path
d="M0.739722594,10.0454545 L3.48285708,10.0454545 C4.03747416,10.0454545 4.72728114,9.66421648 5.01712405,9.20418863 L8.42469998,3.79581137 C8.71743515,3.33119303 9.40462323,2.95454545 9.95374013,2.95454545 L11.6791444,2.95454545" // eslint-disable-line max-len
stroke="#979797"
strokeWidth="2"
strokeLinecap="square"
transform="translate(6.209433, 6.500000) scale(1, -1) translate(-6.209433, -6.500000) "
/>
</g>
</g>
</svg>
</Button>
);
export default RandomButton;
|
client/js/components/profile.js
|
D3VBAS3/DevBase
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
import logout from './../actions/logout';
import { browserHistory } from 'react-router';
import DbTable from './db-table';
import StepBox from './stepBox';
import fetch from 'isomorphic-fetch';
class Profile extends Component {
constructor() {
super();
this.handleLogOut = this.handleLogOut.bind(this);
this.state = {
profile_token: '',
profile_username: ''
}
}
componentDidMount() {
if (localStorage.getItem('devBase_user_token') === null) {
browserHistory.push('/');
} else {
this.setState({
profile_token: localStorage.getItem('devBase_user_token'),
profile_username: localStorage.getItem('devBase_username')
});
}
}
handleLogOut() {
this.props.dispatch(logout());
}
handleReset() {
// fetch post request to drop table
// fetch('/login',{
// method: 'post',
// headers: {
// 'Content-Type': 'application/json'
// },
// body: JSON.stringify(userData)
// })
// .then((response) => {
// if (response.status !== 200) {
// console.log('ERRROORRR not 200');
// throw new Error(response.statusText);
// }
// return response.json();
// })
// .then((data) => {
// dispatch(loginSuccess(data.token, data.username));
// browserHistory.push('/profile');
// })
}
render() {
return (
<div>
<div>
<button onClick={this.handleLogOut}>LOG OUT</button>
</div>
<DbTable />
<StepBox username={this.state.profile_username} token={this.state.profile_token}/>
<button onClick={this.handleReset}>Reset</button>
</div>
)
}
}
export default connect()(Profile);
|
server/sonar-web/src/main/js/apps/account/projects/propTypes.js
|
Builders-SonarSource/sonarqube-bis
|
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
const { shape, string, array, arrayOf } = React.PropTypes;
export const projectType = shape({
id: string.isRequired,
key: string.isRequired,
name: string.isRequired,
lastAnalysisDate: string,
description: string,
links: array.isRequired,
qualityGate: string
});
export const projectsListType = arrayOf(projectType);
|
packages/icons/src/md/action/HourglassEmpty.js
|
suitejs/suitejs
|
import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdHourglassEmpty(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M12 5h24v10l-9 9 9 9v10H12V33l9-9-9-9V5zm20 29l-8-8-8 8v5h16v-5zm-8-12l8-8V9H16v5l8 8z" />
</IconBase>
);
}
export default MdHourglassEmpty;
|
node_modules/@material-ui/core/esm/DialogActions/DialogActions.js
|
pcclarke/civ-techs
|
import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import clsx from 'clsx';
import withStyles from '../styles/withStyles';
import '../Button'; // So we don't have any override priority issue.
export var styles = {
/* Styles applied to the root element. */
root: {
display: 'flex',
alignItems: 'center',
padding: 8,
justifyContent: 'flex-end'
},
/* Styles applied to the root element if `disableSpacing={false}`. */
spacing: {
'& > * + *': {
marginLeft: 8
}
}
};
var DialogActions = React.forwardRef(function DialogActions(props, ref) {
var _props$disableSpacing = props.disableSpacing,
disableSpacing = _props$disableSpacing === void 0 ? false : _props$disableSpacing,
classes = props.classes,
className = props.className,
other = _objectWithoutProperties(props, ["disableSpacing", "classes", "className"]);
return React.createElement("div", _extends({
className: clsx(classes.root, !disableSpacing && classes.spacing, className),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? DialogActions.propTypes = {
/**
* The content of the component.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* @ignore
*/
className: PropTypes.string,
/**
* If `true`, the actions do not have additional margin.
*/
disableSpacing: PropTypes.bool
} : void 0;
export default withStyles(styles, {
name: 'MuiDialogActions'
})(DialogActions);
|
packages/reactor-modern-boilerplate/src/index.js
|
dbuhrman/extjs-reactor
|
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import { launch } from '@extjs/reactor';
import App from './App'
let viewport;
const render = (Component, target) => {
ReactDOM.render(
<AppContainer>
<Component/>
</AppContainer>,
target
)
}
launch(target => render(App, viewport = target));
if (module.hot) {
module.hot.accept('./App', () => render(App, viewport));
}
|
test/WellSpec.js
|
aabenoja/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Well from '../src/Well';
describe('Well', function () {
it('Should output a well with content', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Well>
<strong>Content</strong>
</Well>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
it('Should have a well class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Well>
Content
</Well>
);
assert.ok(instance.getDOMNode().className.match(/\bwell\b/));
});
it('Should accept bsSize arguments', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Well bsSize='small'>
Content
</Well>
);
assert.ok(instance.getDOMNode().className.match(/\bwell-sm\b/));
});
});
|
react/mortgage/src/components/TableMortgage.js
|
webmaster444/webmaster444.github.io
|
import React from 'react';
import { connect } from 'react-redux';
import payments from '../selectors/payments';
import Table from './Table';
export const TableMortgage = (({payments, className})=> {
let output=payments.slice(1)
.filter(year=>year.balance>0 || year.interestYearly>0)
.reduce((acc, year, index) => {
return {
interestTotal:acc.interestTotal+year.interestYearly,
overpaymentTotal:acc.overpaymentTotal+year.overpayment,
rows:acc.rows.concat([
[year.partial?year.partial + "m":index+1,
Math.round(year.interestYearly||0),
Math.round(year.overpayment),
Math.round(year.balance)]])
}
}, {interestTotal:0, overpaymentTotal:0, rows:[]});
return <Table className={className}
headings={["Years", "Interest", "Overpayment", "Balance"]}
rows={output.rows}
totals={[" ",Math.round(output.interestTotal), Math.round(output.overpaymentTotal)," "]} />;
});
export default connect(state=>({ ...payments(state) }))(TableMortgage)
|
src/components/Menu/MenuList.js
|
sk-iv/iva-app
|
import React from 'react';
import PropTypes from 'prop-types';
import { findDOMNode } from 'react-dom';
import keycode from 'keycode';
import contains from 'dom-helpers/query/contains';
import activeElement from 'dom-helpers/activeElement';
import ownerDocument from 'dom-helpers/ownerDocument';
import List from '../List';
class MenuList extends React.Component {
state = {
currentTabIndex: undefined,
};
componentDidMount() {
this.resetTabIndex();
}
componentWillUnmount() {
clearTimeout(this.blurTimer);
}
setTabIndex(index: number) {
this.setState({ currentTabIndex: index });
}
list = undefined;
selectedItem = undefined;
blurTimer = undefined;
handleBlur = (event: SyntheticUIEvent<>) => {
this.blurTimer = setTimeout(() => {
if (this.list) {
const list = findDOMNode(this.list);
const currentFocus = activeElement(ownerDocument(list));
if (!contains(list, currentFocus)) {
this.resetTabIndex();
}
}
}, 30);
if (this.props.onBlur) {
this.props.onBlur(event);
}
};
handleKeyDown = (event: SyntheticUIEvent<>) => {
const list = findDOMNode(this.list);
const key = keycode(event);
const currentFocus = activeElement(ownerDocument(list));
if (
(key === 'up' || key === 'down') &&
(!currentFocus || (currentFocus && !contains(list, currentFocus)))
) {
if (this.selectedItem) {
findDOMNode(this.selectedItem).focus();
} else {
list.firstChild.focus();
}
} else if (key === 'down') {
event.preventDefault();
if (currentFocus.nextElementSibling) {
currentFocus.nextElementSibling.focus();
}
} else if (key === 'up') {
event.preventDefault();
if (currentFocus.previousElementSibling) {
currentFocus.previousElementSibling.focus();
}
}
if (this.props.onKeyDown) {
this.props.onKeyDown(event, key);
}
};
handleItemFocus = (event: SyntheticUIEvent<>) => {
const list = findDOMNode(this.list);
if (list) {
for (let i = 0; i < list.children.length; i += 1) {
if (list.children[i] === event.currentTarget) {
this.setTabIndex(i);
break;
}
}
}
};
focus() {
const { currentTabIndex } = this.state;
const list = findDOMNode(this.list);
if (!list || !list.children || !list.firstChild) {
return;
}
if (currentTabIndex && currentTabIndex >= 0) {
list.children[currentTabIndex].focus();
} else {
list.firstChild.focus();
}
}
resetTabIndex() {
const list = findDOMNode(this.list);
const currentFocus = activeElement(ownerDocument(list));
const items = [...list.children];
const currentFocusIndex = items.indexOf(currentFocus);
if (currentFocusIndex !== -1) {
return this.setTabIndex(currentFocusIndex);
}
if (this.selectedItem) {
return this.setTabIndex(items.indexOf(findDOMNode(this.selectedItem)));
}
return this.setTabIndex(0);
}
render() {
const { children, className, onBlur, onKeyDown, ...other } = this.props;
return (
<List
data-mui-test="MenuList"
role="menu"
rootRef={node => {
this.list = node;
}}
className={className}
onKeyDown={this.handleKeyDown}
onBlur={this.handleBlur}
{...other}
>
{React.Children.map(children, (child, index) => {
if (!React.isValidElement(child)) {
return null;
}
return React.cloneElement(child, {
tabIndex: index === this.state.currentTabIndex ? 0 : -1,
ref: child.props.selected
? node => {
this.selectedItem = node;
}
: undefined,
onFocus: this.handleItemFocus,
});
})}
</List>
);
}
}
MenuList.propTypes = {
/**
* MenuList contents, normally `MenuItem`s.
*/
children: PropTypes.node,
/**
* @ignore
*/
className: PropTypes.string,
/**
* @ignore
*/
onBlur: PropTypes.func,
/**
* @ignore
*/
onKeyDown: PropTypes.func,
};
export default MenuList;
|
ext/lib/admin/admin-topics-form/view.js
|
RosarioCiudad/democracyos
|
import React from 'react'
import { render as ReactRender } from 'react-dom'
import closest from 'component-closest'
import confirm from 'democracyos-confirmation'
import Datepicker from 'democracyos-datepicker'
import debug from 'debug'
import o from 'component-dom'
import t from 't-component'
import page from 'page'
import moment from 'moment'
import tagsInput from 'tags-input'
import { dom as render } from 'lib/render/render'
import Richtext from 'lib/richtext/richtext'
import urlBuilder from 'lib/url-builder'
import FormView from 'lib/form-view/form-view'
import topicStore from 'lib/stores/topic-store/topic-store'
import * as serializer from './body-serializer'
import ForumTagsSearch from 'lib/admin/admin-topics-form/tag-autocomplete/component'
import linkTemplate from './link.jade'
import Attrs from './attrs/component'
import template from './template.jade'
import templateIdeas from './template-ideas.jade'
import user from 'lib/user/user.js'
const log = debug('democracyos:admin-topics-form')
/**
* Creates a password edit view
*/
let created = false
export default class TopicForm extends FormView {
constructor (topic, forum, tags) {
const locals = {
form: { title: null, action: null, method: null, type: null },
topic: topic || { clauses: [] },
tags: tags,
moment: moment,
forum,
urlBuilder
}
if (topic) {
locals.form.type = 'edit'
locals.form.action = '/api/v2/topics/' + topic.id
locals.form.title = 'admin-topics-form.title.edit'
locals.form.method = 'put'
topic.body = serializer.toHTML(topic.clauses)
.replace(/<a/g, '<a rel="noopener noreferer" target="_blank"')
} else {
locals.form.type = 'create'
locals.form.action = '/api/v2/topics'
locals.form.title = 'admin-topics-form.title.create'
locals.form.method = 'post'
locals.form.forum = forum.id
}
if (forum.name === 'ideas') {
super(templateIdeas, locals)
} else {
super(template, locals)
}
this.topic = topic
this.tags = tags
this.forum = forum
this.forumAdminUrl =
':forum/admin'.replace(':forum', forum ? `/${forum.name}` : '')
if (tags.length === 0) return
this.renderDateTimePickers()
if (created) {
this.messages([t('admin-topics-form.message.onsuccess')])
created = false
}
this.pubButton = this.find('a.make-public')
this.privButton = this.find('a.make-private')
var body = this.find('textarea[name=body]')
this.richtext = new Richtext(body)
}
/**
* Turn on event bindings
*/
switchOn () {
this.bind('click', '.add-link', this.bound('onaddlinkclick'))
this.bind('click', '.forum-tag', this.bound('onaddforumtagclick'))
this.bind('click', '[data-remove-link]', this.bound('onremovelinkclick'))
this.bind('click', '.save', this.bound('onsaveclick'))
this.bind('click', '.auto-save', this.bound('onsaveclick'))
this.bind('click', '.make-public', this.bound('onmakepublicclick'))
this.bind('click', '.make-private', this.bound('onmakeprivateclick'))
this.bind('click', '.delete-topic', this.bound('ondeletetopicclick'))
this.bind('click', '.archivar', this.bound('onclosetopicclick'))
this.bind('click', '.abrir', this.bound('onopentopicclick'))
this.bind('click', '[data-clear-closing-at]', this.bound('onclearclosingat'))
this.bind('change', '.method-input', this.bound('onmethodchange'))
this.on('success', this.onsuccess)
const actionMethod =
this.topic && this.topic.action ? this.topic.action.method : ''
const pollOptions = this.find('.poll-options')
this.find('.method-input option').forEach(function (option) {
if (option.value === actionMethod) option.selected = true
})
if (actionMethod === 'poll') pollOptions.removeClass('hide')
const tags = this.el[0].querySelectorAll('input[type="tags"]')
Array.prototype.forEach.call(tags, tagsInput)
if (this.forum.name !== 'presupuesto') {
ReactRender((
<ForumTagsSearch
tags={this.topic && this.topic.tags && this.topic.tags}
initialTags={this.forum.initialTags}
forum={this.forum.id} />
), this.el[0].querySelector('.tags-autocomplete'))
}
if (this.forum.topicsAttrs.length > 0) {
const attrsWrapper = this.el[0].querySelector('[data-attrs]')
ReactRender(
<Attrs forum={this.forum} topic={this.topic} />,
attrsWrapper
)
}
}
/**
* Handle `error` event with
* logging and display
*
* @param {String} error
* @api private
*/
onsuccess (res) {
log('Topic successfully saved')
topicStore.parse(res.body.results.topic)
.then((topic) => {
if (this.topic) topicStore.unset(this.topic.id)
topicStore.set(topic.id, topic)
if (!this.forum.privileges.canChangeTopics) {
return page(urlBuilder.for('site.topic', {
forum: this.forum.name,
id: topic.id
}))
}
this.topic = topic
created = true
document.querySelector('#content').scrollTop = 0
// Forcefully re-render the form
page(urlBuilder.for('admin.topics.id', {
forum: this.forum.name,
id: this.topic.id
}))
})
.catch((err) => { throw err })
}
/**
* Renders datepicker and timepicker
* elements inside view's `el`
*
* @return {TopicForm|Element}
* @api public
*/
renderDateTimePickers () {
if (this.forum.name !== 'presupuesto') {
this.closingAt = this.find('[name=closingAt]', this.el)
this.closingAtTime = this.find('[name=closingAtTime]')
this.dp = new Datepicker(this.closingAt[0])
return this
}
}
onaddlinkclick (evt) {
evt.preventDefault()
return this.addLink()
}
addLink () {
const links = o('.topic-links', this.el)
const link = render(linkTemplate, {
link: {}
})
links.append(o(link))
}
onremovelinkclick (evt) {
const btn = evt.target
const link = closest(btn, '[data-link]')
link.parentNode.removeChild(link)
}
onsaveclick (ev) {
ev.preventDefault()
if (this.dp && this.dp.popover) {
this.dp.popover.hide()
}
if (this.find('.method-input')[0].value === 'poll' && this.find('.poll-options > input')[0].value === '') {
this.messages(t('admin-topics-form.message.validation.pollOptions-required'), 'error')
return
}
this.find('form input[type=submit]')[0].click()
}
postserialize (data = {}) {
if (data['links[][text]']) {
data.links = data['links[][text]'].map((text, i) => ({
_id: data['links[][_id]'][i] || undefined,
url: data['links[][url]'][i],
text
}))
delete data['links[][_id]']
delete data['links[][text]']
delete data['links[][url]']
}
if (data.closingAt && data.closingAtTime) {
data.closingAt = new Date(`${data.closingAt} ${data.closingAtTime}`)
delete data.closingAtTime
}
/* console.log(data.body)*/
data.clauses = serializer.toArray(data.body)
/* console.log(data.clauses)*/
delete data.body
if (data['action.options']) {
data['action.options'] = data['action.options'].split(',')
}
if (data.tags) {
data.tags = data.tags.split(',')
} else {
data.tags = []
}
return data
}
onmakepublicclick (ev) {
ev.preventDefault()
var view = this
this.pubButton.addClass('disabled')
topicStore.publish(this.topic.id)
.then(() => {
view.pubButton.removeClass('disabled').addClass('hide')
view.privButton.removeClass('hide')
})
.catch((err) => {
console.log(err)
view.pubButton.removeClass('disabled')
log('Found error %o', err)
})
}
onmakeprivateclick (ev) {
ev.preventDefault()
var view = this
this.privButton.addClass('disabled')
var id = this.topic.id
topicStore.unpublish(id)
.then(() => {
view.privButton.removeClass('disabled')
view.privButton.addClass('hide')
view.pubButton.removeClass('hide')
})
.catch((err) => {
view.pubButton.removeClass('disabled')
log('Found error %o', err)
})
}
ondeletetopicclick (ev) {
ev.preventDefault()
const _t = (s) => t(`admin-topics-form.delete-topic.confirmation.${s}`)
const onconfirmdelete = (ok) => {
if (!ok) return
topicStore.destroy(this.topic.id)
.then(() => {
if (this.forum.visibility === 'collaborative') {
page(urlBuilder.for('site.forum', { forum: this.forum.name }))
} else {
page(urlBuilder.for('admin', { forum: this.forum.name }))
}
})
.catch((err) => {
log('Found error %o', err)
})
}
confirm(_t('title'), _t('body'))
.cancel(_t('cancel'))
.ok(_t('ok'))
.modal()
.closable()
.effect('slide')
.show(onconfirmdelete)
}
onclearclosingat (ev) {
ev.preventDefault()
this.closingAt.value('')
if (this.dp && this.dp.popover) {
this.dp.popover.hide()
this.dp = new Datepicker(this.closingAt[0])
}
}
onmethodchange (e) {
const action = e.target.value === 'poll' ? 'removeClass' : 'addClass'
this.find('.poll-options')[action]('hide')
}
onclosetopicclick = (e) => {
window.fetch(`/ext/api/${this.forum.name}/${this.topic.id}/status`, { method: 'DELETE', credentials: 'include' })
.then((res) => res.json())
.then((res) => {
if (res.status === 200) {
window.location.reload()
}
})
}
onopentopicclick = (e) => {
window.fetch(`/ext/api/${this.forum.name}/${this.topic.id}/status`, { method: 'POST', credentials: 'include' })
.then((res) => res.json())
.then((res) => {
if (res.status === 200) {
window.location.reload()
}
})
}
onaddforumtagclick (e) {
if (this.find('input[name="tags"]')[0].value.length === 0) {
this.find('input[name="tags"]')[0].value = `${e.target.dataset.value}`
} else if (!~this.find('input[name="tags"]')[0].value.indexOf(e.target.dataset.value)) {
this.find('input[name="tags"]')[0].value += `,${e.target.dataset.value}`
} else {
return
}
let span = document.createElement('span')
span.setAttribute('data-tag', e.target.dataset.value)
span.textContent = e.target.dataset.value
span.className = 'tag'
this.find('.tags-autocomplete .tags-input').prepend(span)
}
}
|
src/js/Main/components/UseCases.js
|
fr3nchN/proactive
|
import React from 'react'
import links from "./../links"
import ContentUseCases from "./../../../content/community/ContentUseCases"
const UseCaseCard = ({ useCaseItem }) => {
return (
<div className="card">
<img className="card-img-top" src={useCaseItem.image} alt={useCaseItem.name} />
<div className="card-body text-center">
<h4 className="card-title">{useCaseItem.name}</h4>
<p className="card-text text-muted">{useCaseItem.description}</p>
<a href={useCaseItem.link} className="btn btn-outline-secondary" target="_blank">Download</a>
</div>
</div>
)
};
const UseCases = () => {
return (
<div>
<div className="row justify-content-md-center">
<div className="col-md-8 text-center">
<h2>Use Cases</h2>
<hr />
</div>
</div>
<div className="card-deck">
{ ContentUseCases.map((useCaseItem) => (
<UseCaseCard key={useCaseItem.key} useCaseItem={useCaseItem} />
)) }
</div>
</div>
)
};
export default UseCases;
|
src/components/Box/Header.js
|
falmar/react-adm-lte
|
import React from 'react'
import PropTypes from 'prop-types'
import classnames from 'classnames'
const Header = ({title, border, children}) => {
const className = {
'with-border': border
}
return (
<div className={classnames('box-header', className)}>
{title && <h3 className='box-title'>{title}</h3>}
{children}
</div>
)
}
Header.propTypes = {
title: PropTypes.node,
border: PropTypes.bool,
children: PropTypes.node
}
export default Header
|
components/Index.js
|
migutw42/base16-viewer
|
import React from 'react';
import ThemeItem from './ThemeItem';
import Head from './Head'
const style = {
container: {
display: "flex",
flex: 1
},
main: {
width: "750px"
},
side: {
flex: 1
}
};
export default class Index extends React.Component {
constructor (props) {
super(props);
this.state = {
searchWord: '',
themes: []
};
}
componentDidMount () {
if (this.state.themes.length === 0) {
this.fetchThemes().then(({themes}) =>{
this.setState({themes});
})
}
}
fetchThemes () {
return (async () => {
const res = await fetch('./static/themes.json');
const json = await res.json();
return {themes: json.themes}
})();
}
updateSearchWord(searchWord) {
this.setState({searchWord});
}
render () {
const {
themes,
searchWord
} = this.state;
return (
<div style={style.container}>
<Head/>
<div style={style.side}></div>
<div style={style.main}>
<div>
<h1>base16-viewer</h1>
</div>
<div>
<input type="text" onInput={(e)=> this.updateSearchWord(e.target.value)}/>
</div>
<div>
{themes.map((theme) => (
<ThemeItem key={theme} theme={theme} visible={theme.includes(searchWord)} />
))}
</div>
</div>
<div style={style.side}></div>
</div>
);
}
}
|
Sources/ewsnodejs-server/node_modules/@material-ui/styles/esm/ServerStyleSheets/ServerStyleSheets.js
|
nihospr01/OpenSpeechPlatform-UCSD
|
import _extends from "@babel/runtime/helpers/esm/extends";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import React from 'react';
import { SheetsRegistry } from 'jss';
import StylesProvider from '../StylesProvider';
import createGenerateClassName from '../createGenerateClassName';
var ServerStyleSheets = /*#__PURE__*/function () {
function ServerStyleSheets() {
var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
_classCallCheck(this, ServerStyleSheets);
this.options = options;
}
_createClass(ServerStyleSheets, [{
key: "collect",
value: function collect(children) {
// This is needed in order to deduplicate the injection of CSS in the page.
var sheetsManager = new Map(); // This is needed in order to inject the critical CSS.
this.sheetsRegistry = new SheetsRegistry(); // A new class name generator
var generateClassName = createGenerateClassName();
return /*#__PURE__*/React.createElement(StylesProvider, _extends({
sheetsManager: sheetsManager,
serverGenerateClassName: generateClassName,
sheetsRegistry: this.sheetsRegistry
}, this.options), children);
}
}, {
key: "toString",
value: function toString() {
return this.sheetsRegistry ? this.sheetsRegistry.toString() : '';
}
}, {
key: "getStyleElement",
value: function getStyleElement(props) {
return /*#__PURE__*/React.createElement('style', _extends({
id: 'jss-server-side',
key: 'jss-server-side',
dangerouslySetInnerHTML: {
__html: this.toString()
}
}, props));
}
}]);
return ServerStyleSheets;
}();
export { ServerStyleSheets as default };
|
src/App/views/Home/index.js
|
ryanswapp/react-starter-template
|
import React from 'react';
import CSSModules from 'react-css-modules';
import style from './style';
class Home extends React.Component {
constructor(props) {
super(props);
this.state = {
features: [
'React, Redux',
'React Router',
'Redux Simple Router',
'Node Sass, Bootstrap Sass'
]
};
}
render() {
const { features } = this.state;
return (
<div className="container">
<h1 styleName="h1">React Starter Template</h1>
<ul className="list-group">
{ features.map((feature, i) => {
return <li key={ i } className="list-group-item">{ i + 1 }) { feature }</li>;
})}
</ul>
</div>
);
}
};
export default CSSModules(Home, style);
|
src/MorphTransitionNative.js
|
gorangajic/react-svg-morph
|
import React from 'react';
import MorphTransition from './MorphTransition';
import {
Surface,
Transform,
Shape,
} from 'ReactNativeART';
export default
class MorphTransitionNative extends MorphTransition {
render() {
var width = this.props.width;
var height = this.props.height;
return (
<Surface width={width} height={height} style={{width: width, height: height}} {...this.props}>
{this.state.current.map((item, index) => {
var rotate = item.trans.rotate;
var transform = new Transform().rotate(rotate[0], rotate[1], rotate[2]);
return (
<Shape style={item.style} d={item.path} fill="#000000" {...item.attrs} transform={transform} key={index} />
);
})}
</Surface>
);
}
}
|
src/SparklinesNormalBand.js
|
samsface/react-sparklines
|
import React from 'react';
import DataProcessor from './DataProcessor';
export default class SparklinesNormalBand extends React.Component {
static propTypes = {
style: React.PropTypes.object
};
static defaultProps = {
style: { fill: 'red', fillOpacity: .1 }
};
render() {
const { points, margin, style } = this.props;
const ypoints = points.map(p => p.y);
const mean = DataProcessor.calculateFromData(ypoints, 'mean');
const stdev = DataProcessor.calculateFromData(ypoints, 'stdev');
return (
<rect x={points[0].x} y={mean - stdev + margin}
width={points[points.length - 1].x - points[0].x} height={stdev * 2}
style={style} />
)
}
}
|
src/components/icon/components/collapse.js
|
fmsouza/wcode
|
import React from 'react';
// Icon taken from: https://github.com/spiffcode/ghedit
export const Collapse = (props) => (
<svg xmlns='http://www.w3.org/2000/svg' width='16' height='16' viewBox='-1 0 16 16' {...props}>
<path fill='#C5C5C5' d='M14 1v9h-1V2H5V1h9zM3 3v1h8v8h1V3H3zm7 2v9H1V5h9zM8 7H3v5h5V7z'/>
<path fill='#75BEFF' d='M4 9h3v1H4z'/>
</svg>
);
|
src/DatePicker/DatePicker.spec.js
|
mit-cml/iot-website-source
|
/* eslint-env mocha */
import React from 'react';
import {shallow} from 'enzyme';
import {assert} from 'chai';
import DatePicker from './DatePicker';
import getMuiTheme from '../styles/getMuiTheme';
import TextField from '../TextField';
describe('<DatePicker />', () => {
const muiTheme = getMuiTheme();
const shallowWithContext = (node) => shallow(node, {context: {muiTheme}});
describe('formatDate', () => {
it('should use the default format', () => {
const date = new Date(1448967059892); // Tue, 01 Dec 2015 10:50:59 GMT
const wrapper = shallowWithContext(
<DatePicker value={date} />
);
assert.strictEqual(wrapper.find(TextField).props().value, '2015-12-01',
'should format the date to ISO 8601 (YYYY-MM-DD)');
});
});
});
|
src/index.js
|
hieudt/redux-tic-tac-toe
|
import React from 'react';
import App from './containers/App';
import '../bower_components/bootstrap/dist/css/bootstrap.css';
import '../bower_components/font-awesome/css/font-awesome.css'
import '../css/main.css';
React.render(<App />, document.getElementById('root'));
|
src/resources/EditorResources.js
|
DelvarWorld/some-game
|
import React from 'react';
import THREE from 'three';
const gameWidth = 600;
const gameHeight = 600;
export default [
<meshBasicMaterial
key={ 84940 }
resourceId="selectionWireframe"
color={0x66ff00}
wireframe
/>,
<shape
resourceId="row"
key={ 84941 }
>
<moveTo
x={-gameWidth / 2}
y={0}
/>
<lineTo
x={gameHeight / 2}
y={0}
/>
</shape>,
<shape
resourceId="col"
key={ 84942 }
>
<moveTo
x={0}
y={-gameWidth / 2}
/>
<lineTo
x={0}
y={gameHeight / 2}
/>
</shape>,
<lineBasicMaterial
key={ 84943 }
resourceId="gridLineMaterial"
color={0x222222}
linewidth={0.5}
/>,
<meshBasicMaterial
key={ 84944 }
resourceId="gridFloorMaterial"
color={0xffffff}
opacity={0.4}
transparent
/>,
<meshPhongMaterial
key={ 84945 }
resourceId="ghostMaterial"
color={0xff0000}
opacity={0.5}
side={ THREE.DoubleSide }
transparent
/>,
];
|
ui/src/views/deviceprofiles/ListDeviceProfiles.js
|
jcampanell-cablelabs/lora-app-server
|
import React, { Component } from 'react';
import { Link } from 'react-router';
import Pagination from "../../components/Pagination";
import DeviceProfileStore from "../../stores/DeviceProfileStore";
import SessionStore from "../../stores/SessionStore";
class DeviceProfileRow extends Component {
render() {
return(
<tr>
<td><Link to={`organizations/${this.props.organizationID}/device-profiles/${this.props.deviceProfile.deviceProfileID}`}>{this.props.deviceProfile.name}</Link></td>
</tr>
);
}
}
class ListDeviceProfiles extends Component {
constructor() {
super();
this.state = {
pageSize: 20,
deviceProfiles: [],
isAdmin: false,
pageNumber: 1,
pages: 1,
};
this.updatePage = this.updatePage.bind(this);
}
componentDidMount() {
this.updatePage(this.props);
SessionStore.on("change", () => {
this.setState({
isAdmin: SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID),
});
});
}
updatePage(props) {
this.setState({
isAdmin: SessionStore.isAdmin() || SessionStore.isOrganizationAdmin(this.props.params.organizationID),
});
const page = (props.location.query.page === undefined) ? 1 : props.location.query.page;
DeviceProfileStore.getAllForOrganizationID(props.params.organizationID, this.state.pageSize, (page-1) * this.state.pageSize, (totalCount, deviceProfiles) => {
this.setState({
deviceProfiles: deviceProfiles,
pageNumber: page,
pages: Math.ceil(totalCount / this.state.pageSize),
});
window.scrollTo(0, 0);
});
}
render() {
const DeviceProfileRows = this.state.deviceProfiles.map((deviceProfile, i) => <DeviceProfileRow key={deviceProfile.deviceProfileID} deviceProfile={deviceProfile} organizationID={this.props.params.organizationID} />);
return(
<div className="panel panel-default">
<div className={`panel-heading clearfix ${this.state.isAdmin ? '' : 'hidden'}`}>
<div className="btn-group pull-right">
<Link to={`organizations/${this.props.params.organizationID}/device-profiles/create`}><button type="button" className="btn btn-default btn-sm">Create device-profile</button></Link>
</div>
</div>
<div className="panel-body">
<table className="table table-hover">
<thead>
<tr>
<th>Name</th>
</tr>
</thead>
<tbody>
{DeviceProfileRows}
</tbody>
</table>
</div>
<Pagination pages={this.state.pages} currentPage={this.state.pageNumber} pathname={`organizations/${this.props.params.organizationID}/device-profiles`} />
</div>
);
}
}
export default ListDeviceProfiles;
|
examples/SimpleExample/__tests__/index.ios.js
|
Gabrn/react-native-persistent-job
|
import 'react-native';
import React from 'react';
import Index from '../index.ios.js';
// Note: test renderer must be required after react-native.
import renderer from 'react-test-renderer';
it('renders correctly', () => {
const tree = renderer.create(
<Index />
);
});
|
src/decorators/withViewport.js
|
deslee/deslee-react-flux
|
/*! 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 '../../node_modules/react/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', 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});
}
};
}
export default withViewport;
|
docs/src/pages/layout/grid/CenteredGrid.js
|
dsslimshaddy/material-ui
|
// @flow weak
import React from 'react';
import PropTypes from 'prop-types';
import { withStyles } from 'material-ui/styles';
import Paper from 'material-ui/Paper';
import Grid from 'material-ui/Grid';
const styles = theme => ({
root: {
flexGrow: 1,
marginTop: 30,
},
paper: {
padding: 16,
textAlign: 'center',
color: theme.palette.text.secondary,
},
});
function CenteredGrid(props) {
const classes = props.classes;
return (
<div className={classes.root}>
<Grid container spacing={24}>
<Grid item xs={12}>
<Paper className={classes.paper}>xs=12</Paper>
</Grid>
<Grid item xs={6}>
<Paper className={classes.paper}>xs=6</Paper>
</Grid>
<Grid item xs={6}>
<Paper className={classes.paper}>xs=6</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
</Grid>
</div>
);
}
CenteredGrid.propTypes = {
classes: PropTypes.object.isRequired,
};
export default withStyles(styles)(CenteredGrid);
|
app/routes.js
|
dolfelt/markdeck
|
import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './editor/containers/App';
import MainPanel from './editor/containers/MainPanel';
export default (
<Route path="/" component={App}>
<IndexRoute component={MainPanel} />
</Route>
);
|
src/client/assets/javascripts/app/DevTools.js
|
Sevas727/ReactTest3
|
import React from 'react';
import { createDevTools } from 'redux-devtools';
// Monitors are separate packages, and you can make a custom one
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
import SliderMonitor from 'redux-slider-monitor';
// createDevTools takes a monitor and produces a DevTools component
export default createDevTools(
<DockMonitor toggleVisibilityKey="ctrl-h"
changePositionKey="ctrl-q"
changeMonitorKey="ctrl-m">
<LogMonitor theme="nicinabox" />
<SliderMonitor keyboardEnabled />
</DockMonitor>
);
|
liferay-gsearch-workspace/modules/gsearch-react-web/src/main/resources/META-INF/resources/lib/containers/Filters/Filter/ScopeFilter.js
|
peerkar/liferay-gsearch
|
import React from 'react'
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import { Dropdown } from 'semantic-ui-react'
import { RequestParameterNames } from '../../../constants/requestparameters';
import { scopeOptions, defaultScope } from '../../../constants/scope';
import { search } from "../../../store/actions/search";
import { getScope } from '../../../store/reducers/search';
/**
* Redux mapping.
*
* @param {Object} dispatch
*/
function mapDispatchToProps(dispatch) {
const getSearchResults = search.request;
return bindActionCreators({ getSearchResults }, dispatch);
}
/**
* Redux mapping.
*
* @param {Object} state
*/
function mapStateToProps(state) {
return {
scope: getScope(state)
};
}
/**
* Scope filter component.
*/
class ScopeFilter extends React.Component {
constructor(props) {
super(props);
// Bind functions to this instance.
this.handleItemSelect = this.handleItemSelect.bind(this);
}
/**
* Handle item selection event.
*
* @param {Object} event
* @param {String} value
*/
handleItemSelect(event, { value }) {
this.props.getSearchResults({ [RequestParameterNames.SCOPE]: value })
}
/**
* Render
*/
render() {
const { scope } = this.props;
return (
<Dropdown
compact
defaultValue={defaultScope}
className='gsearch-filter'
onChange={this.handleItemSelect}
options={scopeOptions}
value={scope}
/>
)
}
}
export default connect(mapStateToProps, mapDispatchToProps)(ScopeFilter);
|
app/containers/LanguageProvider/index.js
|
romanvieito/ball-simpler
|
/*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { makeSelectLocale } from './selectors';
export class LanguageProvider extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} key={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: PropTypes.string,
messages: PropTypes.object,
children: PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
makeSelectLocale(),
(locale) => ({ locale })
);
export default connect(mapStateToProps)(LanguageProvider);
|
src/components/topic/TopicsApp.js
|
mitmedialab/MediaCloud-Web-Tools
|
import PropTypes from 'prop-types';
import React from 'react';
import { injectIntl } from 'react-intl';
import AppContainer from '../AppContainer';
import messages from '../../resources/messages';
import PageTitle from '../common/PageTitle';
const TopicsApp = (props) => {
const { formatMessage } = props.intl;
return (
<div>
<PageTitle />
<AppContainer
name="topics"
title={formatMessage(messages.topicsToolName)}
description={formatMessage(messages.topicsToolDescription)}
>
{props.children}
</AppContainer>
</div>
);
};
TopicsApp.propTypes = {
children: PropTypes.node,
intl: PropTypes.object.isRequired,
};
export default injectIntl(TopicsApp);
|
examples/todomvc/test/components/Footer.spec.js
|
gajus/redux
|
import expect from 'expect'
import React from 'react'
import TestUtils from 'react-addons-test-utils'
import Footer from '../../components/Footer'
import { SHOW_ALL, SHOW_ACTIVE } from '../../constants/TodoFilters'
function setup(propOverrides) {
const props = Object.assign({
completedCount: 0,
activeCount: 0,
filter: SHOW_ALL,
onClearCompleted: expect.createSpy(),
onShow: expect.createSpy()
}, propOverrides)
const renderer = TestUtils.createRenderer()
renderer.render(<Footer {...props} />)
const output = renderer.getRenderOutput()
return {
props: props,
output: output
}
}
function getTextContent(elem) {
const children = Array.isArray(elem.props.children) ?
elem.props.children : [ elem.props.children ]
return children.reduce(function concatText(out, child) {
// Children are either elements or text strings
return out + (child.props ? getTextContent(child) : child)
}, '')
}
describe('components', () => {
describe('Footer', () => {
it('should render container', () => {
const { output } = setup()
expect(output.type).toBe('footer')
expect(output.props.className).toBe('footer')
})
it('should display active count when 0', () => {
const { output } = setup({ activeCount: 0 })
const [ count ] = output.props.children
expect(getTextContent(count)).toBe('No items left')
})
it('should display active count when above 0', () => {
const { output } = setup({ activeCount: 1 })
const [ count ] = output.props.children
expect(getTextContent(count)).toBe('1 item left')
})
it('should render filters', () => {
const { output } = setup()
const [ , filters ] = output.props.children
expect(filters.type).toBe('ul')
expect(filters.props.className).toBe('filters')
expect(filters.props.children.length).toBe(3)
filters.props.children.forEach(function checkFilter(filter, i) {
expect(filter.type).toBe('li')
const a = filter.props.children
expect(a.props.className).toBe(i === 0 ? 'selected' : '')
expect(a.props.children).toBe({
0: 'All',
1: 'Active',
2: 'Completed'
}[i])
})
})
it('should call onShow when a filter is clicked', () => {
const { output, props } = setup()
const [ , filters ] = output.props.children
const filterLink = filters.props.children[1].props.children
filterLink.props.onClick({})
expect(props.onShow).toHaveBeenCalledWith(SHOW_ACTIVE)
})
it('shouldnt show clear button when no completed todos', () => {
const { output } = setup({ completedCount: 0 })
const [ , , clear ] = output.props.children
expect(clear).toBe(undefined)
})
it('should render clear button when completed todos', () => {
const { output } = setup({ completedCount: 1 })
const [ , , clear ] = output.props.children
expect(clear.type).toBe('button')
expect(clear.props.children).toBe('Clear completed')
})
it('should call onClearCompleted on clear button click', () => {
const { output, props } = setup({ completedCount: 1 })
const [ , , clear ] = output.props.children
clear.props.onClick({})
expect(props.onClearCompleted).toHaveBeenCalled()
})
})
})
|
src/index.js
|
mimccio/komi
|
import React from 'react'
import ReactDOM from 'react-dom'
import './index.css'
import App from './App'
import registerServiceWorker from './registerServiceWorker'
ReactDOM.render(<App name='hello' />, document.getElementById('root'))
registerServiceWorker()
|
examples/counter/index.js
|
Lucifier129/redux
|
import React from 'react';
import Root from './containers/Root';
React.render(
<Root />,
document.getElementById('root')
);
|
src/app/js/colors/Rect.js
|
skratchdot/colorify
|
import React, { Component } from 'react';
import onecolor from 'onecolor';
// 0: color space, 1: property name, 2: number of gradients
const values = {
h: ['hsl', '_hue', 360],
s: ['hsl', '_saturation', 3],
l: ['hsl', '_lightness', 3],
r: ['rgb', '_red', 2],
g: ['rgb', '_green', 2],
b: ['rgb', '_blue', 2],
a: ['rgb', '_alpha', 2],
};
class Rect extends Component {
handleRange = (e) => {
let newColor;
const type = this.props.type;
if (
typeof this.props.onColorChange === 'function' &&
typeof type === 'string' &&
Object.prototype.hasOwnProperty.call(values, type)
) {
newColor = this.props.color[values[type][0]]();
newColor[values[type][1]] = parseFloat(e.target.value);
newColor = onecolor(newColor);
this.props.onColorChange(newColor);
}
}
render() {
let value = 0;
const type = this.props.type;
const style = {};
let info;
let background;
if (
typeof type === 'string' &&
Object.prototype.hasOwnProperty.call(values, type)
) {
info = values[type];
value = this.props.color[info[0]]()[info[1]];
background = [];
if (info[0] === 'hsl') {
for (let i = 0; i < info[2]; i++) {
const h =
type === 'h' ? (i / 359) * 360 : this.props.color.hsl()._hue * 360;
const s =
type === 's'
? (i / 2) * 100
: this.props.color.hsl()._saturation * 100;
const l =
type === 'l'
? (i / 2) * 100
: this.props.color.hsl()._lightness * 100;
background.push(`hsla(${h},${s}%,${l}%,${this.props.color.alpha()})`);
}
} else {
for (let i = 0; i < info[2]; i++) {
const r = Math.round(
type === 'r' ? i * 255 : this.props.color.rgb()._red * 255
);
const g = Math.round(
type === 'g' ? i * 255 : this.props.color.rgb()._green * 255
);
const b = Math.round(
type === 'b' ? i * 255 : this.props.color.rgb()._blue * 255
);
const a = type === 'a' ? i : this.props.color.alpha();
background.push(`rgba(${r},${g},${b},${a})`);
}
}
style.background = `linear-gradient(to right, ${background.join(',')})`;
}
return (
<div className="color-rect">
<div className="color-rect-alpha"></div>
<input
type="range"
min="0"
max="1"
step="0.001"
value={value}
style={style}
onChange={this.handleRange}
onInput={this.handleRange}
/>
</div>
);
}
}
export default Rect;
|
src/components/Button/demo/icon/index.js
|
lebra/lebra-components
|
import React, { Component } from 'react';
import { render } from 'react-dom';
import Button from '../../index';
import './index.less';
export default class BaseDemo extends Component {
render() {
return (
<div>
<Button iconType="iconfont icon-add" shape="squared"></Button>
<Button iconType="iconfont icon-add">确定</Button>
</div> )
}
}
let root = document.getElementById('app');
render(<BaseDemo />, root);
|
react/src/components/dashboard/coinTile/coinTile.js
|
pbca26/EasyDEX-GUI
|
import React from 'react';
import { connect } from 'react-redux';
import {
getCoinTitle,
getModeInfo,
isKomodoCoin,
} from '../../../util/coinHelper';
import CoinTileItem from './coinTileItem';
import translate from '../../../translate/translate';
import CoinTileRender from './coinTile.render';
class CoinTile extends React.Component {
constructor() {
super();
this.state = {
toggledSidebar: false,
};
this.renderTiles = this.renderTiles.bind(this);
this.toggleSidebar = this.toggleSidebar.bind(this);
}
toggleSidebar() {
this.setState({
toggledSidebar: !this.state.toggledSidebar,
});
}
renderTiles() {
const modes = [
'native',
'spv',
'eth',
];
const allCoins = this.props.allCoins;
let items = [];
if (allCoins) {
for (let i = 0; i < modes.length; i++) {
allCoins[modes[i]].sort();
for (let j = 0; j < allCoins[modes[i]].length; j++) {
const _coinMode = getModeInfo(modes[i]);
const modecode = _coinMode.code;
const modetip = _coinMode.tip;
const modecolor = _coinMode.color;
const _coinTitle = getCoinTitle(allCoins[modes[i]][j].toUpperCase());
const coinlogo = allCoins[modes[i]][j].toUpperCase();
const coinname = translate(((modes[i] === 'spv' || modes[i] === 'native') && isKomodoCoin(allCoins[modes[i]][j]) ? 'ASSETCHAINS.' : 'CRYPTO.') + allCoins[modes[i]][j].toUpperCase());
const data = {
coinlogo,
coinname,
coin: allCoins[modes[i]][j],
mode: modes[i],
modecolor,
modetip,
modecode,
};
items.push(
<CoinTileItem
key={ `coin-tile-${modes[i]}-${allCoins[modes[i]][j]}` }
i={ i * (j + 1) }
item={ data } />
);
}
}
}
return items;
}
render() {
return CoinTileRender.call(this);
}
}
const mapStateToProps = (state) => {
return {
allCoins: state.Main.coins,
};
};
export default connect(mapStateToProps)(CoinTile);
|
example/google.js
|
jukra/react-leaflet-google-sunenergia
|
import React from 'react';
import { Map, TileLayer, LayersControl } from 'react-leaflet'
import {GoogleLayer} from '../src'
const { BaseLayer} = LayersControl;
const key = 'AIzaSyDEG4lyorD61vnJoAHG0FkQERZ-McElZyg';
const terrain = 'TERRAIN';
const road = 'ROADMAP';
const satellite = 'SATELLITE';
const hydrid = 'HYBRID';
//// Google's map type. Valid values are 'roadmap', 'satellite' or 'terrain'. 'hybrid' is not really supported.
export default class GoogleExample extends React.Component {
constructor() {
super();
}
render() {
return (
<Map center={[42.09618442380296, -71.5045166015625]} zoom={2} zoomControl={true}>
<LayersControl position='topright'>
<BaseLayer name='OpenStreetMap.Mapnik'>
<TileLayer url="http://{s}.tile.osm.org/{z}/{x}/{y}.png"/>
</BaseLayer>
<BaseLayer checked name='Google Maps Roads'>
<GoogleLayer googlekey={key} maptype={road} />
</BaseLayer>
<BaseLayer name='Google Maps Terrain'>
<GoogleLayer googlekey={key} maptype={terrain} />
</BaseLayer>
<BaseLayer name='Google Maps Satellite'>
<GoogleLayer googlekey={key} maptype={satellite} />
</BaseLayer>
<BaseLayer name='Google Maps Hydrid'>
<GoogleLayer googlekey={key} maptype={hydrid} libraries={['geometry', 'places']} />
</BaseLayer>
<BaseLayer name='Google Maps with Libraries'>
<GoogleLayer googlekey={key} maptype={hydrid} libraries={['geometry', 'places']} />
</BaseLayer>
</LayersControl>
</Map>
)
}
}
|
src/main.js
|
sheridp2/triviapp
|
import React from 'react';
import ReactDOM from 'react-dom';
import './style.scss';
import App from './component/app';
ReactDOM.render(<App />, document.getElementById('root'));
|
examples/huge-apps/components/App.js
|
kelsadita/react-router
|
import React from 'react';
import Dashboard from './Dashboard';
import GlobalNav from './GlobalNav';
class App extends React.Component {
render() {
var courses = COURSES;
return (
<div>
<GlobalNav />
<div style={{ padding: 20 }}>
{this.props.children || <Dashboard courses={courses} />}
</div>
</div>
);
}
}
export default App;
|
examples/universal/client/index.js
|
wescravens/redux
|
import 'babel-core/polyfill';
import React from 'react';
import { Provider } from 'react-redux';
import configureStore from '../common/store/configureStore';
import App from '../common/containers/App';
const initialState = window.__INITIAL_STATE__;
const store = configureStore(initialState);
const rootElement = document.getElementById('app');
React.render(
<Provider store={store}>
{() => <App/>}
</Provider>,
rootElement
);
|
examples/huge-apps/components/App.js
|
clloyd/react-router
|
/*globals COURSES:true */
import React from 'react'
import Dashboard from './Dashboard'
import GlobalNav from './GlobalNav'
class App extends React.Component {
render() {
return (
<div>
<GlobalNav />
<div style={{ padding: 20 }}>
{this.props.children || <Dashboard courses={COURSES} />}
</div>
</div>
)
}
}
export default App
|
src/routes/home/Home.js
|
0xcdc/rfb-client-app
|
import useStyles from 'isomorphic-style-loader/useStyles';
import React from 'react';
import PropTypes from 'prop-types';
import s from './Home.css';
import SearchBar from '../../components/SearchBar';
export default function Home({ clients }) {
useStyles(s);
return <SearchBar clients={clients} />;
}
Home.propTypes = {
clients: PropTypes.arrayOf(
PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
householdId: PropTypes.number.isRequired,
householdSize: PropTypes.number.isRequired,
cardColor: PropTypes.string.isRequired,
lastVisit: PropTypes.string,
note: PropTypes.string,
}),
).isRequired,
};
|
src/index.js
|
guilherme-toti/react-highlight-overlay
|
import React from 'react'
class HighlightOverlay extends React.Component {
constructor(props) {
super(props)
this.state = {
width: 0,
height: 0
}
}
componentDidMount() {
this.updateWindowSize()
window.onresize = () => this.updateWindowSize()
}
updateWindowSize = () => {
const { width, height } = this.getBodySize()
this.setState({
width: width,
height: height
})
}
componentDidUpdate = () => {
this.updateCanvas()
}
getBodySize = () => {
return document.body.getBoundingClientRect()
}
updateCanvas = () => {
let context = this.refs.canvas.getContext('2d')
context.save()
this.drawBackground(context)
context.globalCompositeOperation = 'destination-out'
for (let index = 0; index < this.props.targets.length; index++) {
this.drawHighlight(context, this.props.targets[index])
}
context.restore()
}
drawBackground = (context) => {
const { width, height } = this.getBodySize()
context.clearRect(0, 0, width, height)
context.beginPath()
context.rect(0, 0, width, height)
context.fillStyle = this.props.backgroundColor
context.fill()
}
drawHighlight = (context, target) => {
const targetObject = document.querySelector(target)
if (!targetObject) {
setTimeout(() => {
this.drawHighlight(context, target)
}, 200)
return
}
const { top, left, width, height } = targetObject.getBoundingClientRect()
context.beginPath()
context.rect(left, top, width, height)
context.fillStyle = 'white'
context.fill()
}
render = () => {
return (
<canvas
ref="canvas"
width={ this.state.width }
height={ this.state.height }
style={{
top: 0,
left: 0,
position: 'absolute',
zIndex: this.props.zIndex
}}
/>
)
}
}
HighlightOverlay.propTypes = {
targets: React.PropTypes.array,
zIndex: React.PropTypes.number,
backgroundColor: React.PropTypes.string
}
HighlightOverlay.defaultProps = {
targets: [],
zIndex: 1400,
backgroundColor: 'rgba(0, 0, 0, 0.6)'
}
module.exports = HighlightOverlay
|
src/ListComposite/index.js
|
DuckyTeam/ducky-components
|
import Icon from '../Icon';
import React from 'react';
import PropTypes from 'prop-types';
import Typography from '../Typography';
import classNames from 'classnames';
import styles from './styles.css';
function ListComposite(props) {
const title = (
props.challenge ? props.challengeName : 'Hashtag'
);
const supplementInfo = (
props.challenge ? ' deltagere' : ' poster'
);
return (
<div className={classNames(styles.wrapper, {[props.className]: props.className})}>
<Icon
className={styles.icon}
icon={props.challenge ? 'icon-trophy' : 'icon-local_offer'}
size={"standard"}
/>
<div className={styles.composite}>
<Typography className={styles.typo}
type="bodyTextTitle"
>
{title}
</Typography>
<Typography className={styles.typo}
type="caption2Normal"
>
{props.info} {supplementInfo}
</Typography>
</div>
</div>
);
}
ListComposite.propTypes = {
challenge: PropTypes.bool,
challengeName: PropTypes.string,
className: PropTypes.string,
info: PropTypes.number
};
export default ListComposite;
|
modules/pages/client/components/Foundation.component.js
|
Trustroots/trustroots
|
// External dependencies
import { Trans, useTranslation } from 'react-i18next';
import React from 'react';
// Internal dependencies`
import { userType } from '@/modules/users/client/users.prop-types';
import Board from '@/modules/core/client/components/Board.js';
import ManifestoText from './ManifestoText.component.js';
export default function Foundation({ user }) {
const { t } = useTranslation('pages');
return (
<>
<Board names="nordiclights">
<div className="container">
<div className="row">
<div className="col-xs-12 text-center">
<br />
<br />
<i className="icon-3x icon-heart-o"></i>
<br />
<br />
<h2>{t('Trustroots Foundation')}</h2>
</div>
</div>
</div>
</Board>
<section className="container container-spacer">
<div className="row">
<div className="col-xs-12 col-sm-offset-1 col-sm-10 col-md-offset-2 col-md-8">
<p className="lead">
{t(`Trustroots is owned and operated by Trustroots Foundation, a non-profit
Limited by Guarantee (LBG) under section 60 exemption, registered in the
United Kingdom in March 2015.`)}
</p>
<ul className="list-inline">
<li>
<a href="https://beta.companieshouse.gov.uk/company/09489825">
{t('Details')}
</a>
</li>
<li>
<a href="https://ideas.trustroots.org/wordpress/wp-content/uploads/2015/03/Trustroots-Articles-2015.pdf">
{t('Foundation’s Articles')}
</a>{' '}
<small className="text-muted">(pdf)</small>
</li>
<li>
<a href="/faq/foundation">{t('FAQ')}</a>
</li>
<li>
<a href="https://ideas.trustroots.org/2015/03/10/announcing-trustroots-foundation/">
{t('Announcement')}
</a>{' '}
<small className="text-muted">
({t('{{date, LL}}', { date: new Date(2015, 2, 10) })})
</small>
</li>
<li>
<a href="/support">{t('Contact us')}</a>
</li>
<li>
<a href="/volunteering">{t('Volunteering')}</a>
</li>
</ul>
</div>
</div>
{/* /.row */}
</section>
{/* /.container */}
{/* Board */}
<section className="container container-spacer">
<hr />
<div className="row">
<div className="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 text-center">
<h2 id="board">{t('Board')}</h2>
<p>
<Trans t={t} ns="pages">
We are a group of hospitality exchange enthusiasts with
backgrounds in some notable projects. The same people who also
brought you <a href="https://hitchwiki.org/">Hitchwiki</a>,{' '}
<a href="https://trashwiki.org/">Trashwiki</a>,{' '}
<a href="https://nomadwihki.org/">Nomadwiki</a> & more.
</Trans>
</p>
<p>
{t(
'All current board members are also members of the founding team. We will have non-founding members in the board at some point.',
)}
</p>
<br />
<br />
</div>
</div>
<div className="row">
<div className="col-xs-12 col-sm-4">
{/* Mikael */}
<div className="media">
<a className="pull-left" href="https://mikaelkorpela.fi/">
<img
className="media-object img-circle"
src="//gravatar.com/avatar/d0229f23745d3c266f81c6b0cd014a38?s=200"
width="100"
alt="Mikael"
/>
</a>
<div className="media-body">
<h4 className="media-heading">Mikael</h4>
<p className="text-color-links">
<Trans t={t} ns="pages">
Working on big freegan/travel projects such as{' '}
<a href="https://hitchwiki.org/">Hitchwiki</a>,{' '}
<a href="http://hitchgathering.org/">
Hitchgathering festival
</a>
, <a href="https://trashwiki.org/">Trashwiki</a> and{' '}
<a href="https://nomadwiki.org/">Nomadwiki</a> since 2008.
In the past has volunteered for BeWelcome (2013). Active
open source contributor and visionary free/gift-economics
activist. A developer at{' '}
<a href="https://automattic.com/">Automattic</a>.
</Trans>
</p>
<p>
<ul className="list-inline">
<li>
<a href="https://www.mikaelkorpela.fi/">
mikaelkorpela.fi
</a>
</li>
<li>
<a href="/profile/mikael">{t('Trustroots profile')}</a>
</li>
</ul>
</p>
</div>
</div>
<br />
<br />
</div>
<div className="col-xs-12 col-sm-4">
{/* Natalia */}
<div className="media">
<img
className="media-object img-circle pull-left"
src="/img/team-natalia.jpg"
width="100"
alt="Natalia"
/>
<div className="media-body">
<h4 className="media-heading">Natalia</h4>
<p className="text-color-links">
{t(
'Coming from a multinational business background, Natalia is an enthusiastic of the share and gift economy. Veteran globetrotter and volunteer for different NGOs from hospex as Couchsurfing to nonprofit lobbying orgs.',
)}
</p>
<p>
<ul className="list-inline">
<li>
<a href="https://www.linkedin.com/in/natalia-s%C3%A1enz-alban%C3%A9s-38469227/">
LinkedIn
</a>
</li>
<li>
<a href="/profile/natalia_sevilla">
{t('Trustroots profile')}
</a>
</li>
</ul>
</p>
</div>
</div>
</div>
</div>
<hr />
<div className="row">
<div className="col-xs-12 col-sm-8 col-sm-offset-2 col-md-6 col-md-offset-3 text-center">
<h2>{t('Past board members')}</h2>
<p>
{t(
'Callum, Carlos and Kasper were also part of the founding team.',
)}
</p>
<br />
<br />
</div>
</div>
<div className="row">
<div className="col-xs-12 col-sm-4 col-sm-offset-2">
{/* Callum */}
<div className="media">
<a className="pull-left" href="https://www.callum-macdonald.com/">
<img
className="media-object img-circle"
src="//gravatar.com/avatar/1e2eebc68bae7e891391688ad1c331d1?s=100"
width="100"
alt=""
/>
</a>
<div className="media-body">
<h4 className="media-heading">Callum</h4>
<p className="text-color-links">
{t(
'Long term nomad and technology expert. Volunteered for BeWelcome BoD in 2013 and for CouchSurfing in 2007.',
)}
</p>
<p>
<ul className="list-inline">
<li>
<a href="https://www.callum-macdonald.com/">
callum-macdonald.com
</a>
</li>
<li>
<a href="/profile/chmac">{t('Trustroots profile')}</a>
</li>
</ul>
</p>
</div>
</div>
</div>
<div className="col-xs-12 col-sm-4">
{/* Carlos */}
<div className="media">
<img
className="media-object img-circle pull-left"
src="/img/team-carlos.jpg"
width="100"
alt="Carlos"
/>
<div className="media-body">
<h4 className="media-heading">Carlos</h4>
<p className="text-color-links">
{t(
'Love to travel, passionate and enthusiastic about share economy and hospitality exchange as human development tools. Volunteered CouchSurfing from 2008 to 2010 as well as other NGOs.',
)}
</p>
<p>
<ul className="list-inline">
<li>
<a href="https://www.linkedin.com/in/carlosmcardenas/">
LinkedIn
</a>
</li>
<li>
<a href="/profile/carlos">{t('Trustroots profile')}</a>
</li>
</ul>
</p>
</div>
</div>
</div>
<div className="col-xs-12 col-sm-4">
{/* Kasper */}
<div className="media">
<a className="pull-left" href="https://guaka.org/">
<img
className="media-object img-circle"
src="/img/team-kasper.png"
width="100"
alt="Kasper"
/>
</a>
<div className="media-body">
<h4 className="media-heading">Kasper</h4>
<p className="text-color-links">
<Trans t={t} ns="pages">
Founded multiple popular and trusted websites such as{' '}
<a href="https://hitchwiki.org/">Hitchwiki</a>,{' '}
<a href="https://trashwiki.org/">Trashwiki</a>,{' '}
<a href="https://nomadwiki.org/">Nomadwiki</a>,{' '}
<a href="https://couchwiki.org/">Couchwiki</a> and{' '}
<a href="https://deletionpedia.org/">Deletionpedia</a>.{' '}
Volunteered for CouchSurfing as a tech team coordinator in
2006 and 2007 and for{' '}
<a href="https://www.bewelcome.org/">BeWelcome</a> since
2007. Loves paradoxes, makes money with{' '}
<a href="https://moneyless.org/">moneyless.org</a>.
</Trans>
</p>
<p>
<ul className="list-inline">
<li>
<a href="https://guaka.org/">guaka.org</a>
</li>
<li>
<a href="/profile/guaka">{t('Trustroots profile')}</a>
</li>
</ul>
</p>
</div>
</div>
</div>
</div>
<hr />
</section>
<section className="vision-footer">
<div className="container">
<div className="row" id="mission-vision-values">
<div className="col-xs-12 text-center hidden-xs">
<h2>{t('Vision, Mission & Values')}</h2>
<br />
<br />
</div>
<div className="col-sm-4 text-center">
<h3 id="vision">{t('Vision')}</h3>
<p className="lead">
<em>“{t('A world that encourages trust and adventure.')}”</em>
</p>
</div>
<div className="col-sm-4 text-center">
<h3 id="mission">{t('Mission')}</h3>
<p className="lead">
{t(`Trustroots seeks to be a platform for sharing and getting people
together. We aim to connect likeminded people together. We encourage
trust, adventure and intercultural connections.`)}
</p>
</div>
<div className="col-sm-4 text-center">
<h3 id="values">{t('Values')}</h3>
<ul className="list-unstyled lead">
<li>{t('Trust')}</li>
<li>{t('Adventure')}</li>
<li>{t('Transparency')}</li>
<li>{t('Freedom')}</li>
</ul>
</div>
</div>
{/* /.row */}
</div>
{/* /.container */}
</section>
{/* Manifesto */}
<Board
className="board-primary board-inset"
names="jungleroad"
id="manifesto"
>
<div className="container">
<div className="row">
<div className="col-md-offset-3 col-md-6 text-center lead font-brand-light">
<ManifestoText></ManifestoText>
{!user && (
<p>
<br />
<br />
<a
href="/signup"
className="btn btn-lg btn-action btn-inverse"
>
{t('Join Trustroots')}
</a>
</p>
)}
</div>
</div>
</div>
</Board>
</>
);
}
Foundation.propTypes = {
user: userType,
};
|
packages/material-ui-icons/src/Lock.js
|
cherniavskii/material-ui
|
import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<g><path d="M18 8h-1V6c0-2.76-2.24-5-5-5S7 3.24 7 6v2H6c-1.1 0-2 .9-2 2v10c0 1.1.9 2 2 2h12c1.1 0 2-.9 2-2V10c0-1.1-.9-2-2-2zm-6 9c-1.1 0-2-.9-2-2s.9-2 2-2 2 .9 2 2-.9 2-2 2zm3.1-9H8.9V6c0-1.71 1.39-3.1 3.1-3.1 1.71 0 3.1 1.39 3.1 3.1v2z" /></g>
, 'Lock');
|
components/Layout/Navigation.js
|
gadflying/profileSite
|
/**
* React Static Boilerplate
* https://github.com/kriasoft/react-static-boilerplate
*
* Copyright © 2015-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Link from '../Link';
import s from './Header.css';
class Navigation extends React.Component {
componentDidMount() {
window.componentHandler.upgradeElement(this.root);
}
componentWillUnmount() {
window.componentHandler.downgradeElements(this.root);
}
render() {
return (
<nav className="mdl-navigation" ref={node => (this.root = node)}>
<Link className="mdl-navigation__link ${s.substitle}" to="/">Home</Link>
<Link className="mdl-navigation__link ${s.substitle}" to="/about">Works</Link>
<Link className="mdl-navigation__link ${s.substitle}" to="/about">Blogs</Link>
<Link className="mdl-navigation__link ${s.substitle}" to="/about">Contact</Link>
</nav>
);
}
}
export default Navigation;
|
docs/src/HomePage.js
|
blue68/react-bootstrap
|
import React from 'react';
import NavMain from './NavMain';
import PageFooter from './PageFooter';
import Grid from '../../src/Grid';
import Alert from '../../src/Alert';
import Glyphicon from '../../src/Glyphicon';
import Label from '../../src/Label';
export default class HomePage extends React.Component {
render() {
return (
<div>
<NavMain activePage="home" />
<main className="bs-docs-masthead" id="content" role="main">
<div className="container">
<span className="bs-docs-booticon bs-docs-booticon-lg bs-docs-booticon-outline"></span>
<p className="lead">The most popular front-end framework, rebuilt for React.</p>
</div>
</main>
<Grid>
<Alert bsStyle="warning">
<p><Glyphicon glyph="bullhorn" /> We are actively working to reach a 1.0.0 release, and we would love your help to get there.</p>
<p><Glyphicon glyph="check" /> Check out the <a href="https://github.com/react-bootstrap/react-bootstrap/wiki#100-roadmap">1.0.0 Roadmap</a> and <a href="https://github.com/react-bootstrap/react-bootstrap/blob/master/CONTRIBUTING.md">Contributing Guidelines</a> to see where you can help out.</p>
<p><Glyphicon glyph="sunglasses" /> A great place to start is any <a target="_blank" href="https://github.com/react-bootstrap/react-bootstrap/issues?q=is%3Aopen+is%3Aissue+label%3A%22help+wanted%22">issues</a> with a <Label bsStyle="success">help-wanted</Label> label.</p>
<p><Glyphicon glyph="ok" /> We are open to pull requests that address bugs, improve documentation, enhance accessibility,</p>
<p>add test coverage, or bring us closer to feature parity with <a target="_blank" href="http://getbootstrap.com/">Bootstrap</a>.</p>
<p><Glyphicon glyph="user" /> We actively seek to invite frequent pull request authors to join the organization. <Glyphicon glyph="thumbs-up" /></p>
</Alert>
<Alert bsStyle="danger">
<p><Glyphicon glyph="warning-sign" /> The project is under active development, and APIs will change. </p>
<p><Glyphicon glyph="bullhorn" /> Prior to the 1.0.0 release, breaking changes should result in a Minor version bump.</p>
</Alert>
<Alert bsStyle="info">
<p><Glyphicon glyph="bullhorn" /> If you want to try / play with <b>React-0.14</b> betas, we cut releases from the <b>react-14</b> branch. They're on the <b>react-pre</b> tag.</p>
<p><kbd>$ npm install react-bootstrap@react-pre</kbd></p>
</Alert>
</Grid>
<PageFooter />
</div>
);
}
}
|
src/Label.js
|
rapilabs/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Label = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render() {
let classes = this.getBsClassSet();
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Label;
|
client/components/Flass/Upload/QuestionInsertion/Quiz/QuizWrapper/QuizWrapperComponent.js
|
Nexters/flass
|
import React from 'react';
import PropTypes from 'prop-types';
import './QuizWrapperComponentStyles.scss';
const propTypes = {
children: PropTypes.element.isRequired
};
const defaultProps = {};
const QuizWrapperComponent = ({ children }) => (
<div className="quiz-wrapper">
{ children }
</div>
);
QuizWrapperComponent.propTypes = propTypes;
QuizWrapperComponent.defaultProps = defaultProps;
export default QuizWrapperComponent;
|
examples-native/crna-kitchen-sink/storybook/stories/Button/index.ios.js
|
storybooks/react-storybook
|
import React from 'react';
import PropTypes from 'prop-types';
import { TouchableHighlight } from 'react-native';
export default function Button({ onPress, children }) {
return <TouchableHighlight onPress={onPress}>{children}</TouchableHighlight>;
}
Button.defaultProps = {
children: null,
onPress: () => {},
};
Button.propTypes = {
children: PropTypes.node,
onPress: PropTypes.func,
};
|
src/svg-icons/maps/local-phone.js
|
jacklam718/react-svg-iconx
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalPhone = (props) => (
<SvgIcon {...props}>
<path d="M6.62 10.79c1.44 2.83 3.76 5.14 6.59 6.59l2.2-2.2c.27-.27.67-.36 1.02-.24 1.12.37 2.33.57 3.57.57.55 0 1 .45 1 1V20c0 .55-.45 1-1 1-9.39 0-17-7.61-17-17 0-.55.45-1 1-1h3.5c.55 0 1 .45 1 1 0 1.25.2 2.45.57 3.57.11.35.03.74-.25 1.02l-2.2 2.2z"/>
</SvgIcon>
);
MapsLocalPhone = pure(MapsLocalPhone);
MapsLocalPhone.displayName = 'MapsLocalPhone';
MapsLocalPhone.muiName = 'SvgIcon';
export default MapsLocalPhone;
|
test/templates/Check.snap.js
|
sullenor/teatime-test-utils
|
import Check from 'teatime-components/component/Check';
import React from 'react';
export default () => (
<Check
id='checks-id'
label='checks label'
name='check-control'/>
);
|
fields/types/Field.js
|
dryna/keystone-twoje-urodziny
|
import classnames from 'classnames';
import evalDependsOn from '../utils/evalDependsOn.js';
import React from 'react';
import { findDOMNode } from 'react-dom';
import { FormField, FormInput, FormNote } from '../../admin/client/App/elemental';
import blacklist from 'blacklist';
import CollapsedFieldLabel from '../components/CollapsedFieldLabel';
function isObject (arg) {
return Object.prototype.toString.call(arg) === '[object Object]';
}
function validateSpec (spec) {
if (!spec) spec = {};
if (!isObject(spec.supports)) {
spec.supports = {};
}
if (!spec.focusTargetRef) {
spec.focusTargetRef = 'focusTarget';
}
return spec;
}
var Base = module.exports.Base = {
getInitialState () {
return {};
},
getDefaultProps () {
return {
adminPath: Keystone.adminPath,
inputProps: {},
labelProps: {},
valueProps: {},
size: 'full',
};
},
getInputName (path) {
// This correctly creates the path for field inputs, and supports the
// inputNamePrefix prop that is required for nested fields to work
return this.props.inputNamePrefix
? `${this.props.inputNamePrefix}[${path}]`
: path;
},
valueChanged (event) {
this.props.onChange({
path: this.props.path,
value: event.target.value,
});
},
shouldCollapse () {
return this.props.collapse && !this.props.value;
},
shouldRenderField () {
if (this.props.mode === 'create') return true;
return !this.props.noedit;
},
focus () {
if (!this.refs[this.spec.focusTargetRef]) return;
findDOMNode(this.refs[this.spec.focusTargetRef]).focus();
},
renderNote () {
if (!this.props.note) return null;
return <FormNote html={this.props.note} />;
},
renderField () {
const { autoFocus, value, inputProps } = this.props;
return (
<FormInput {...{
...inputProps,
autoFocus,
autoComplete: 'off',
name: this.getInputName(this.props.path),
onChange: this.valueChanged,
ref: 'focusTarget',
value,
}} />
);
},
renderValue () {
return <FormInput noedit>{this.props.value}</FormInput>;
},
renderUI () {
var wrapperClassName = classnames(
'field-type-' + this.props.type,
this.props.className,
{ 'field-monospace': this.props.monospace }
);
return (
<FormField htmlFor={this.props.path} label={this.props.label} className={wrapperClassName} cropLabel>
<div className={'FormField__inner field-size-' + this.props.size}>
{this.shouldRenderField() ? this.renderField() : this.renderValue()}
</div>
{this.renderNote()}
</FormField>
);
},
};
var Mixins = module.exports.Mixins = {
Collapse: {
componentWillMount () {
this.setState({
isCollapsed: this.shouldCollapse(),
});
},
componentDidUpdate (prevProps, prevState) {
if (prevState.isCollapsed && !this.state.isCollapsed) {
this.focus();
}
},
uncollapse () {
this.setState({
isCollapsed: false,
});
},
renderCollapse () {
if (!this.shouldRenderField()) return null;
return (
<FormField>
<CollapsedFieldLabel onClick={this.uncollapse}>+ Add {this.props.label.toLowerCase()}</CollapsedFieldLabel>
</FormField>
);
},
},
};
module.exports.create = function (spec) {
spec = validateSpec(spec);
var field = {
spec: spec,
displayName: spec.displayName,
mixins: [Mixins.Collapse],
statics: {
getDefaultValue: function (field) {
return field.defaultValue || '';
},
},
render () {
if (!evalDependsOn(this.props.dependsOn, this.props.values)) {
return null;
}
if (this.state.isCollapsed) {
return this.renderCollapse();
}
return this.renderUI();
},
};
if (spec.statics) {
Object.assign(field.statics, spec.statics);
}
var excludeBaseMethods = {};
if (spec.mixins) {
spec.mixins.forEach(function (mixin) {
Object.keys(mixin).forEach(function (name) {
if (Base[name]) {
excludeBaseMethods[name] = true;
}
});
});
}
Object.assign(field, blacklist(Base, excludeBaseMethods));
Object.assign(field, blacklist(spec, 'mixins', 'statics'));
if (Array.isArray(spec.mixins)) {
field.mixins = field.mixins.concat(spec.mixins);
}
return React.createClass(field);
};
|
node_modules/react-bootstrap/es/Radio.js
|
FoxMessenger/nyt-react
|
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import warning from 'warning';
import { bsClass, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
inline: PropTypes.bool,
disabled: PropTypes.bool,
/**
* Only valid if `inline` is not set.
*/
validationState: PropTypes.oneOf(['success', 'warning', 'error', null]),
/**
* Attaches a ref to the `<input>` element. Only functions can be used here.
*
* ```js
* <Radio inputRef={ref => { this.input = ref; }} />
* ```
*/
inputRef: PropTypes.func
};
var defaultProps = {
inline: false,
disabled: false
};
var Radio = function (_React$Component) {
_inherits(Radio, _React$Component);
function Radio() {
_classCallCheck(this, Radio);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Radio.prototype.render = function render() {
var _props = this.props,
inline = _props.inline,
disabled = _props.disabled,
validationState = _props.validationState,
inputRef = _props.inputRef,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['inline', 'disabled', 'validationState', 'inputRef', 'className', 'style', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var input = React.createElement('input', _extends({}, elementProps, {
ref: inputRef,
type: 'radio',
disabled: disabled
}));
if (inline) {
var _classes2;
var _classes = (_classes2 = {}, _classes2[prefix(bsProps, 'inline')] = true, _classes2.disabled = disabled, _classes2);
// Use a warning here instead of in propTypes to get better-looking
// generated documentation.
process.env.NODE_ENV !== 'production' ? warning(!validationState, '`validationState` is ignored on `<Radio inline>`. To display ' + 'validation state on an inline radio, set `validationState` on a ' + 'parent `<FormGroup>` or other element instead.') : void 0;
return React.createElement(
'label',
{ className: classNames(className, _classes), style: style },
input,
children
);
}
var classes = _extends({}, getClassSet(bsProps), {
disabled: disabled
});
if (validationState) {
classes['has-' + validationState] = true;
}
return React.createElement(
'div',
{ className: classNames(className, classes), style: style },
React.createElement(
'label',
null,
input,
children
)
);
};
return Radio;
}(React.Component);
Radio.propTypes = propTypes;
Radio.defaultProps = defaultProps;
export default bsClass('radio', Radio);
|
blog/src/Menu/SubMenu.js
|
Robert2333/kilakila-react
|
import React from 'react'
const PropTypes=require('prop-types');
class SubMenu extends React.Component{
getItem(){
const {children} = this.props;
const item = React.Children.map(children, (child,id) => {
if (!child) {
alert('没有子元素')
return;
}
else {
const props = {
subId:this.props.subId,
id:this.props.subId.toString()+id.toString(),
}
return React.cloneElement(child,props)
}
})
return item;
}
render(){
const {subId,title} = this.props;
return(
<div>
<h4 onClick={()=>this.context.onSelect(subId.toString())}>{title}</h4>
<ul>{this.getItem()}</ul>
</div>
)
}
}
SubMenu.contextTypes={
onSelect:PropTypes.func,
}
export default SubMenu;
|
examples/src/app.js
|
javier-garcia-anfix/react-select
|
/* eslint react/prop-types: 0 */
import React from 'react';
import Select from 'react-select';
import CustomRenderField from './components/CustomRenderField';
import MultiSelectField from './components/MultiSelectField';
import RemoteSelectField from './components/RemoteSelectField';
import SelectedValuesField from './components/SelectedValuesField';
import StatesField from './components/StatesField';
import UsersField from './components/UsersField';
import ValuesAsNumbersField from './components/ValuesAsNumbersField';
import DisabledUpsellOptions from './components/DisabledUpsellOptions';
var FLAVOURS = [
{ label: 'Chocolate', value: 'chocolate' },
{ label: 'Vanilla', value: 'vanilla' },
{ label: 'Strawberry', value: 'strawberry' },
{ label: 'Cookies and Cream', value: 'cookiescream' },
{ label: 'Peppermint', value: 'peppermint' }
];
var FLAVOURS_WITH_DISABLED_OPTION = FLAVOURS.slice(0);
FLAVOURS_WITH_DISABLED_OPTION.unshift({ label: 'Caramel (You don\'t like it, apparently)', value: 'caramel', disabled: true });
function logChange() {
console.log.apply(console, [].concat(['Select value changed:'], Array.prototype.slice.apply(arguments)));
}
React.render(
<div>
<StatesField label="States" searchable />
<UsersField label="Users (custom options/value)" hint="This example uses Gravatar to render user's image besides the value and the options" />
<ValuesAsNumbersField label="Values as numbers" />
<MultiSelectField label="Multiselect"/>
<SelectedValuesField label="Clickable labels (labels as links)" options={FLAVOURS} hint="Open the console to see click behaviour (data/event)" />
<SelectedValuesField label="Disabled option" options={FLAVOURS_WITH_DISABLED_OPTION} hint="You savage! Caramel is the best..." />
<DisabledUpsellOptions label="Disable option with an upsell link"/>
<SelectedValuesField label="Option Creation (tags mode)" options={FLAVOURS} allowCreate hint="Enter a value that's not in the list, then hit enter" />
<CustomRenderField label="Custom render options/values" />
<CustomRenderField label="Custom render options/values (multi)" multi delimiter="," />
<RemoteSelectField label="Remote Options" hint='Type anything in the remote example to asynchronously load options. Valid alternative results are "A", "AA", and "AB"' />
</div>,
document.getElementById('example')
);
|
vitrail_tests/test_vitrail.js
|
CANTUS-Project/vitrail
|
// -*- coding: utf-8 -*-
// ------------------------------------------------------------------------------------------------
// Program Name: vitrail
// Program Description: HTML/CSS/JavaScript user agent for the Cantus API.
//
// Filename: vitrail_tests/test_onebox.js
// Purpose: Tests for the OneboxSearch (and related) React components.
//
// Copyright (C) 2016 Christopher Antila
//
// 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 init from '../js/nuclear/init';
import {mount, shallow} from 'enzyme';
import {Immutable} from 'nuclear-js';
import React from 'react';
import Alert from 'react-bootstrap/lib/Alert';
import Panel from 'react-bootstrap/lib/Panel';
import Table from 'react-bootstrap/lib/Table';
// import {getters} from '../js/nuclear/getters';
// import reactor from '../js/nuclear/reactor';
// import ResultList from '../js/react/result_list';
// import {SIGNALS as signals} from '../js/nuclear/signals';
jest.dontMock('../js/react/vitrail.js'); // module under test
const vitrail = require('../js/react/vitrail.js').MODULE_FOR_TESTING;
describe('AlertView', () => {
it('renders properly', () => {
const classProp = 'success';
const children = 'rawr!';
const actual = shallow(<vitrail.AlertView class={classProp}>{children}</vitrail.AlertView>);
expect(actual.type()).toBe(Panel);
expect(actual.childAt(0).type()).toBe(Alert);
expect(actual.childAt(0).prop('bsStyle')).toBe(classProp);
expect(actual.childAt(0).children().text()).toBe(children);
expect(actual.childAt(1).type()).toBe(vitrail.AlertFieldList);
});
});
describe('AlertFieldList', () => {
it('renders when no fields are given', () => {
const actual = shallow(<vitrail.AlertFieldList/>);
expect(actual.html()).toBe(null);
});
it('renders when three fields are given', () => {
const fields = Immutable.Map({
'Power Rating': '20-275W',
'Frequency Response': '30Hz-25kHz',
'Nominal Impedance': '8 Ohms',
});
const actual = shallow(<vitrail.AlertFieldList fields={fields}/>);
expect(actual.type()).toBe(Table);
expect(actual.childAt(0).type()).toBe('tbody');
const rows = actual.find('tr');
expect(rows.length).toBe(3);
rows.forEach((row) => {
const key = row.childAt(0).text().slice(0, -1);
expect(fields.get(key)).toEqual(row.childAt(1).text());
});
});
});
|
src/resources/assets/react-app/components/AuthHome.js
|
darrenmerrett/ruf
|
import React, { Component } from 'react';
class AuthHome extends Component {
render() {
return (
<div>
You are logged in!
</div>
)
}
}
export default AuthHome;
|
stories/NumberInput.js
|
felixgirault/rea11y
|
import React from 'react';
import {storiesOf, action} from '@kadira/storybook';
import {StatefulNumberInput, NumberInputControls} from '../src';
/**
*
*/
storiesOf('NumberInput', module)
.addWithInfo(
'default',
`
Keyboard interactions when the focus is inside the input:
* \`↑\` increments the value
* \`↓\` decrements the value
* \`Page up\` increments the value by a larger amount
* \`Page down\` decrements the value by a larger amount
* \`Home\` sets the value to the minimum
* \`End\` sets the value to the maximum
`,
() => (
<StatefulNumberInput onChange={action('onChange')} />
),
{
inline: true,
source: false,
propTables: false
}
)
.addWithInfo(
'controlable',
`
In addition to the keyboards interactions, buttons can be
used to increment or decrement the value.
`,
() => (
<StatefulNumberInput onChange={action('onChange')}>
<NumberInputControls />
</StatefulNumberInput>
),
{
inline: true,
source: false,
propTables: false
}
);
|
client/components/nota/SocialShare.js
|
EstebanFuentealba/biobiochile-mobile-spa
|
import React from 'react';
export default class SocialShare extends React.Component{
render() {
return (<div>
<ul className="barra-social">
<li className="s-fb">
<a href={`https://www.facebook.com/sharer.php?u=${this.props.nota.post_URL}`} className="fa fa-facebook"></a>
</li>
<li className="s-tw">
<a href={`https://twitter.com/intent/tweet?original_referer=${this.props.nota.post_URL}&text=${this.props.nota.post_title}&url=${this.props.nota.post_URL}`} data-lang="es" className="fa fa-twitter"></a>
</li>
<li className="s-gp">
<a href={`https://plus.google.com/share?url=${this.props.nota.post_URL}`} className="fa fa-google-plus"></a>
</li>
<li className="s-lin">
<a href={`https://www.linkedin.com/shareArticle?source=BioBioChile%22+rel%3D%22nofollow&title=${this.props.nota.post_title}&summary=&mini=true&url=${this.props.nota.post_URL}`} className="fa fa-linkedin"></a>
</li>
<li id="s-wp" className="s-wp">
<a href={`whatsapp://send?text=${this.props.nota.post_title} ${this.props.nota.post_URL}`}></a>
</li>
</ul>
<ul className="data-social">
<li id="s-fb" className="data-fb">0</li>
<li id="s-tw" className="data-tw">0</li>
<li id="s-gp" className="data-gp">0</li>
<li id="s-lin" className="data-lin">0</li>
<li className="data-wp">Enviar</li>
</ul>
</div>)
}
}
|
src/components/bookmark-slider.js
|
bokuweb/tomato_pasta
|
import React, { Component } from 'react';
import Slider from 'material-ui/lib/slider';
export default class BookmarkSlider extends Component {
constructor(props) {
super(props);
}
onSliderChange(e, value) {
this.props.changeBookmarkThreshold(~~value, e.clientX);
}
render() {
let x = this.props.bookmarkFilterX - 24;
x = (x > 210)? 210 : x;
x = (x < 10)? 10 : x;
return (
<div className="bookmarkslider">
<div className="bookmarkslider__count" style={{left:x}}>
<i className="bookmarkslider__icon icon-hatena" />
{this.props.bookmarkFilter}
</div>
<Slider name="bookmarkslider"
defaultValue={this.props.defaultValue}
onChange={this.onSliderChange.bind(this)}
onDragStop={this.props.onSliderChanged}
max={this.props.max}
min={this.props.min} />
</div>
);
}
}
|
src/popup/components/Logo/index.js
|
fluany/fluany
|
/**
* @fileOverview The logo component
* @name index.js<Logo>
* @license GNU General Public License v3.0
*/
import React from 'react'
const Logo = () => (
<div className='logo-content'>
<svg className='octopus-logo'>
<use xlinkHref='#octopus' />
</svg>
<h1 className='logo-title'>
<span className='flu'>flu</span>
<span className='any'>any</span>
</h1>
</div>
)
export default Logo
|
app/components/CentralStatement.js
|
freele/glossary
|
import React from 'react';
import classNames from 'classnames';
import {Decorator as Cerebral} from 'cerebral-react';
@Cerebral({
statement: ['centralStatementRef']
}, {})
class CentralStatement extends React.Component {
componentDidMount() {
this.props.signals.centralStatementUpdated();
this.props.signals.pageInited();
// $.get(this.props.source, function(result) {
// var lastGist = result[0];
// if (this.isMounted()) {
// this.setState({
// username: lastGist.owner.login,
// lastGistUrl: lastGist.html_url
// });
// }
// }.bind(this));
}
onStatementClick(word) {
// console.log('Click info', word);
this.props.signals.centralStatementUpdated({search: word});
}
renderWord(word, index) {
return (
<span key={index}>
<span className="statement-word" onClick={() => this.onStatementClick(word)}>
{word}
</span>
<span>
{' '}
</span>
</span>
);
}
render() {
return (
<div className="statement">
<label>
{this.props.statement ? this.props.statement.text.split(' ').map(this.renderWord.bind(this)) : ''}
</label>
</div>
);
}
}
export default CentralStatement;
|
frontend/src/components/Crud.js
|
purocean/yii2-template
|
import React from 'react';
import { Table } from 'antd';
import CrudActions from '../actions/CrudActions';
import CrudStore from '../stores/CrudStore';
class Component extends React.Component {
constructor(props){
super(props);
this.onChange = this.onChange.bind(this);
this.state = CrudStore.getState();
this.rowSelection = {
onChange: (selectedRowKeys, selectedRows) => {
CrudActions.rowSelectionChange(selectedRowKeys, selectedRows);
},
onSelect: (record, selected, selectedRows) => {
CrudActions.rowSelectionSelect(record, selected, selectedRows);
},
onSelectAll: (selected, selectedRows, changeRows) => {
CrudActions.rowSelectionSelectAll(selected, selectedRows, changeRows);
},
};
}
componentDidMount() {
CrudStore.listen(this.onChange);
}
componentWillUnmount() {
CrudStore.unlisten(this.onChange);
}
onChange(state) {
this.setState(state);
}
handleTableChange(pagination, filters, sorter) {
CrudActions.fetch(false, {
page: pagination.current,
sortField: sorter.field,
sortOrder: sorter.order,
...filters
});
}
render() {
return (
<div>
{this.props.panel}
{this.props.saveModal}
<Table
bordered
rowKey={record => record.id}
size={this.props.tableSize}
rowSelection={typeof this.props.rowSelection === 'undefined' ? this.rowSelection : this.props.rowSelection}
columns={this.props.tableColumns}
dataSource={this.state.list}
loading={this.state.status === 'fetching'}
pagination={this.state.pagination}
onChange={(pagination, filters, sorter) => this.handleTableChange(pagination, filters, sorter)} />
</div>
);
}
}
Component.defaultProps = {
tableSize: 'middle',
};
export default Component;
|
examples/test/components.js
|
steos/reactcards
|
import React from 'react'
import { assert } from 'chai'
import { shallow } from 'enzyme'
import { Foo, Bar } from '../components'
export function testBarComponent() {
const wrapper = shallow(<Bar/>)
assert.equal(wrapper.text(), 'a bar. drink up!')
}
export function testFooComponent() {
const wrapper = shallow(<Foo message="testing"/>)
assert.equal(wrapper.text(), "Foo says 'testing'")
}
|
examples/src/components/CustomOption.js
|
RassaLibre/react-select
|
import React from 'react';
import Gravatar from 'react-gravatar';
var Option = React.createClass({
propTypes: {
addLabelText: React.PropTypes.string,
className: React.PropTypes.string,
mouseDown: React.PropTypes.func,
mouseEnter: React.PropTypes.func,
mouseLeave: React.PropTypes.func,
option: React.PropTypes.object.isRequired,
renderFunc: React.PropTypes.func
},
render () {
var obj = this.props.option;
var size = 15;
var gravatarStyle = {
borderRadius: 3,
display: 'inline-block',
marginRight: 10,
position: 'relative',
top: -2,
verticalAlign: 'middle',
};
return (
<div className={this.props.className}
onMouseEnter={this.props.mouseEnter}
onMouseLeave={this.props.mouseLeave}
onMouseDown={this.props.mouseDown}
onClick={this.props.mouseDown}>
<Gravatar email={obj.email} size={size} style={gravatarStyle} />
{obj.value}
</div>
);
}
});
module.exports = Option;
|
src/containers/App.js
|
SuperCoac/basic-redux-boilerplate
|
import React from 'react';
import CounterContainer from './CounterContainer';
function App() {
return (
<div>
<h1>Counter</h1>
<CounterContainer />
</div>
);
}
export default App;
|
web-ui/src/login/about/welcome.js
|
pixelated/pixelated-user-agent
|
/*
* Copyright (c) 2017 ThoughtWorks, Inc.
*
* Pixelated 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.
*
* Pixelated 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 Pixelated. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
import { translate } from 'react-i18next';
import './welcome.scss';
export const Welcome = ({ t }) => (
<div className='welcome'>
<img className='welcome-logo' src='/public/images/welcome.svg' alt={t('login.welcome-image-alt')} />
<div>
<h3>{t('login.welcome-message')}</h3>
</div>
</div>
);
Welcome.propTypes = {
t: React.PropTypes.func.isRequired
};
export default translate('', { wait: true })(Welcome);
|
src/routes/index.js
|
pl12133/pl12133.github.io
|
/* eslint-disable no-unused-vars*/
import React from 'react';
/* eslint-enable no-unused-vars*/
import { Router, Route, IndexRoute } from 'react-router';
import createBrowserHistory from 'history/lib/createBrowserHistory';
import App from './App/';
import Home from './Home/';
const Routes = () => (
<Router history={createBrowserHistory()}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
</Route>
</Router>
);
export default Routes;
|
src/main.js
|
QuVideo/viva-react-template
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Button } from 'antd'
import app from './app.less'
import title from './title.less'
import antShowcase from './ant-showcase.less'
const Title = ({ content }) => {
return <h1 className={ title.normal }>{ content }</h1>
}
const AntShowcase = () => {
return (
<div className={ antShowcase.normal }>
<Button type="primary">Primary</Button>
</div>
)
}
const App = () => {
return (
<div className={ app.normal }>
<Title content="Welcome to React world." />
<AntShowcase />
</div>
)
}
ReactDOM.render(<App />, document.getElementById('root'))
if (module.hot) {
module.hot.accept()
}
|
tests/react_children/tuple.js
|
jamesgpearce/flow
|
// @flow
import React from 'react';
class Tuple
extends React.Component<{children: [boolean, string, number]}, void> {}
class TupleOne extends React.Component<{children: [boolean]}, void> {}
<Tuple />; // Error: `children` is required.
<Tuple>{true}{'foo'}{42}</Tuple>; // OK: All the tuple items.
<Tuple>{true}foo{42}</Tuple>; // OK: Mixing text with expressions.
<Tuple>{true}{'foo'}{42}{null}</Tuple>; // Error: One to many.
<Tuple> {true}foo{42}</Tuple>; // Error: Spaces add items.
<Tuple>{true}foo{42} </Tuple>; // Error: Spaces add items.
<Tuple>{[true, 'foo', 42]}</Tuple>; // OK: All the tuple items.
<Tuple>{[true, 'foo', 42]}{[true, 'foo', 42]}</Tuple>; // Error: There may only
// be one tuple.
<Tuple>{[true, 'foo', 42, null]}</Tuple>; // Error: One to many
// OK: All the tuple items on multiple liens.
<Tuple>
{true}
{'foo'}
{42}
</Tuple>;
// OK: All the tuple items mixing text and expressions.
<Tuple>
{true}
foo
{42}
</Tuple>;
<TupleOne>{true}</TupleOne>; // Error: A single expression is not an array.
<TupleOne>{[true]}</TupleOne>; // OK: This is ok.
|
app/tests/components/MainSection-test.js
|
mavo11/MVZ
|
import React from 'react';
import expect from 'expect';
import { mount } from 'enzyme';
import MainSection from '../../components/MainSection';
import TopicItem from '../../components/TopicItem';
const emptyData = [];
const topicItemData = [{
text: '',
id: '',
index: 0,
onIncrement: () => {},
onDecrement: () => {},
onDestroy: () => {}
}];
const stubFunctions = {
onIncrement: () => {},
onDecrement: () => {},
onDestroy: () => {}
};
describe('<MainSection />', () => {
describe('With Topics', () => {
it('should render <TopicItem> list items', () => {
expect(mount(<MainSection topics={topicItemData} {...stubFunctions} />).find(TopicItem).length).toBe(1);
});
});
describe('Without Topics', () => {
it('should not render <TopicItem> list items', () => {
expect(mount(<MainSection topics={emptyData} {...stubFunctions} />).find(TopicItem).length).toBe(0);
});
});
});
|
app/react/demo/src/App.js
|
enjoylife/storybook
|
import React, { Component } from 'react';
import logo from './logo.svg';
import './App.css';
class App extends Component {
render() {
return (
<div className="App">
<div className="App-header">
<img src={logo} className="App-logo" alt="logo" />
<h2>Welcome to React</h2>
</div>
<p className="App-intro">
To get started, edit <code>src/App.js</code> and save to reload.
</p>
</div>
);
}
}
export default App;
|
src/components/Button.react.js
|
Acehaidrey/addrbook
|
'use strict';
require('./css/Button.less');
import React from 'react';
import {Link} from 'react-router';
/**
* Styled button component.
*/
export default class Button extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<h5> This is my button component. </h5>
<button>
<Link to={this.props.linkName}>{this.props.buttonName}</Link>
</button>
</div>
);
}
}
|
src/routers/__tests__/validateRouteConfigMap-test.js
|
kkamperschroer/react-navigation
|
/* @flow */
import React from 'react';
import validateRouteConfigMap from '../validateRouteConfigMap';
import StackRouter from '../StackRouter';
const ListScreen = () => <div />;
const ProfileNavigator = () => <div />;
ProfileNavigator.router = StackRouter({
list: {
screen: ListScreen,
},
});
describe('validateRouteConfigMap', () => {
test('Fails on empty config', () => {
const invalidMap = {};
expect(() => validateRouteConfigMap(invalidMap)).toThrow();
});
test('Fails on bad object', () => {
const invalidMap = {
Home: {
foo: 'bar',
},
};
expect(() => validateRouteConfigMap(invalidMap)).toThrow();
});
test('Fails if both screen and getScreen are defined', () => {
const invalidMap = {
Home: {
screen: ListScreen,
getScreen: () => ListScreen,
},
};
expect(() => validateRouteConfigMap(invalidMap)).toThrow();
});
test('Succeeds on a valid config', () => {
const invalidMap = {
Home: {
screen: ProfileNavigator,
},
Chat: {
screen: ListScreen,
},
};
validateRouteConfigMap(invalidMap);
});
});
|
actor-apps/app-web/src/app/components/modals/Preferences.react.js
|
liruqi/actor-platform-v0.9
|
import _ from 'lodash';
import React from 'react';
import Modal from 'react-modal';
import ReactMixin from 'react-mixin';
import { IntlMixin, FormattedMessage } from 'react-intl';
import { Styles, FlatButton, RadioButtonGroup, RadioButton, DropDownMenu } from 'material-ui';
import { KeyCodes } from 'constants/ActorAppConstants';
import ActorTheme from 'constants/ActorTheme';
import PreferencesActionCreators from 'actions/PreferencesActionCreators';
import PreferencesStore from 'stores/PreferencesStore';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const ThemeManager = new Styles.ThemeManager();
const menuItems = [
{ payload: '1', text: 'English', value: 'en'},
{ payload: '2', text: 'Russian', value: 'ru'}
];
const getStateFromStores = () => {
const language = PreferencesStore.language;
return {
isOpen: PreferencesStore.isModalOpen,
preferences: PreferencesStore.preferences,
language: language,
selectedLanguage: _.findIndex(menuItems, {value: language})
};
};
@ReactMixin.decorate(IntlMixin)
class PreferencesModal extends React.Component {
static childContextTypes = {
muiTheme: React.PropTypes.object
};
getChildContext() {
return {
muiTheme: ThemeManager.getCurrentTheme()
};
}
constructor(props) {
super(props);
this.state = getStateFromStores();
ThemeManager.setTheme(ActorTheme);
ThemeManager.setComponentThemes({
button: {
minWidth: 60
}
});
PreferencesStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
PreferencesStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
onChange = () => {
this.setState(getStateFromStores());
};
onClose = () => {
PreferencesActionCreators.hide();
};
onDone = () => {
PreferencesActionCreators.save({
language: this.state.language,
sendByEnter: this.refs.sendByEnter.getSelectedValue()
});
this.onClose();
};
onKeyDown = event => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
};
onLanguageChange = (event, selectedIndex, menuItem) => {
this.setState({
language: menuItem.value,
selectedLanguage: _.findIndex(menuItems, {value: menuItem.value})
});
};
render() {
const preferences = this.state.preferences;
if (this.state.isOpen === true) {
return (
<Modal className="modal-new modal-new--preferences"
closeTimeoutMS={150}
isOpen={this.state.isOpen}
style={{width: 760}}>
<div className="modal-new__header">
<i className="modal-new__header__icon material-icons">settings</i>
<h3 className="modal-new__header__title">
<FormattedMessage message={this.getIntlMessage('preferencesModalTitle')}/>
</h3>
<div className="pull-right">
<FlatButton hoverColor="rgba(81,145,219,.17)"
label="Done"
labelStyle={{padding: '0 8px'}}
onClick={this.onDone}
secondary={true}
style={{marginTop: -6}}/>
</div>
</div>
<div className="modal-new__body">
<div className="preferences">
<aside className="preferences__tabs">
<a className="preferences__tabs__tab preferences__tabs__tab--active">General</a>
<a className="preferences__tabs__tab hide">Notifications</a>
<a className="preferences__tabs__tab hide">Sidebar colors</a>
<a className="preferences__tabs__tab hide">Security</a>
<a className="preferences__tabs__tab hide">Other Options</a>
</aside>
<div className="preferences__body">
<div className="preferences__list">
<div className="preferences__list__item preferences__list__item--general">
<ul>
<li>
<i className="icon material-icons">keyboard</i>
<RadioButtonGroup defaultSelected={preferences.sendByEnter}
name="send"
ref="sendByEnter">
<RadioButton label="Enter – send message, Shift + Enter – new line"
style={{marginBottom: 12}}
value="true"/>
<RadioButton label="Cmd + Enter – send message, Enter – new line"
value="false"/>
</RadioButtonGroup>
</li>
<li className="language hide">
<i className="icon material-icons">menu</i>
Language: <DropDownMenu labelStyle={{color: '#5191db'}}
menuItemStyle={{height: '40px', lineHeight: '40px'}}
menuItems={menuItems}
onChange={this.onLanguageChange}
selectedIndex={this.state.selectedLanguage}
style={{verticalAlign: 'top', height: 52}}
underlineStyle={{display: 'none'}}/>
</li>
</ul>
</div>
<div className="preferences__list__item preferences__list__item--notifications hide">
<ul>
<li>
<i className="icon material-icons">notifications</i>
<RadioButtonGroup defaultSelected="all" name="notifications">
<RadioButton label="Notifications for activity of any kind"
style={{marginBottom: 12}}
value="all"/>
<RadioButton label="Notifications for Highlight Words and direct messages"
style={{marginBottom: 12}}
value="quiet"/>
<RadioButton label="Never send me notifications"
style={{marginBottom: 12}}
value="disable"/>
</RadioButtonGroup>
<p className="hint">
You can override your desktop notification preference on a case-by-case
basis for channels and groups from the channel or group menu.
</p>
</li>
</ul>
</div>
</div>
</div>
</div>
</div>
</Modal>
);
} else {
return null;
}
}
}
export default PreferencesModal;
|
src/containers/Root.js
|
dont-fear-the-repo/fear-the-repo
|
import React from 'react';
import { Provider } from 'react-redux';
import routes from '../routes';
import { ReduxRouter } from 'redux-router';
import DevTools from './DevTools';
import { createDevToolsWindow } from '../utils';
import HTML5Backend from 'react-dnd-html5-backend';
import { DragDropContext } from 'react-dnd';
@DragDropContext(HTML5Backend)
export default class Root extends React.Component {
static propTypes = {
store: React.PropTypes.object.isRequired,
debug: React.PropTypes.bool,
debugExternal: React.PropTypes.bool
}
static defaultProps = {
debug: false,
debugExternal: false
}
renderDevTools() {
if (!this.props.debug) {
return null;
}
return this.props.debugExternal ?
createDevToolsWindow(this.props.store) : <DevTools />;
}
render() {
return (
<Provider store={this.props.store}>
<div>
<ReduxRouter>
{routes}
</ReduxRouter>
{this.renderDevTools()}
</div>
</Provider>
);
}
}
|
public/assets/js/node_modules/react-redux-form/test/field-parser-spec.js
|
ngocson8b/6jar
|
import { assert } from 'chai';
import React from 'react';
import TestUtils from 'react-addons-test-utils';
import { combineReducers, createStore } from 'redux';
import { Provider } from 'react-redux';
import { modelReducer, formReducer, Field } from '../src';
describe('<Field parser={...} />', () => {
context('standard usage', () => {
const store = createStore(combineReducers({
test: modelReducer('test', { foo: '' }),
testForm: formReducer('test', { foo: '' }),
}));
const parseValue = val => ({
data: val,
});
const field = TestUtils.renderIntoDocument(
<Provider store={store}>
<Field
model="test.foo"
parser={parseValue}
validators={{
isParsed: (val) => val
&& val.data
&& val.data === 'parse test',
}}
>
<input type="text" />
</Field>
</Provider>
);
const input = TestUtils.findRenderedDOMComponentWithTag(field, 'input');
it('should parse the changed values given a parser function', () => {
const expected = { data: 'foo' };
input.value = 'foo';
TestUtils.Simulate.change(input);
assert.deepEqual(
store.getState().test.foo,
expected);
});
it('should parse before validation', () => {
input.value = 'parse test';
assert.isFalse(
store.getState().testForm.fields.foo.validity.isParsed,
'should not be valid yet');
TestUtils.Simulate.change(input);
assert.isTrue(
store.getState().testForm.fields.foo.validity.isParsed);
});
});
it('should parse the initial value immediately', () => {
const store = createStore(combineReducers({
test: modelReducer('test', { foo: 'initial' }),
testForm: formReducer('test', { foo: 'initial' }),
}));
const parseValue = val => val.toUpperCase();
const field = TestUtils.renderIntoDocument(
<Provider store={store}>
<Field
model="test.foo"
parser={parseValue}
>
<input type="text" />
</Field>
</Provider>
);
const input = TestUtils.findRenderedDOMComponentWithTag(field, 'input');
assert.equal(input.value, 'INITIAL');
assert.equal(store.getState().test.foo, 'INITIAL');
});
});
|
test/Header.spec.js
|
StephanieEA/firebae
|
import React from 'react';
import { shallow, mount, render } from 'enzyme';
import { assert, expect } from 'chai';
import Header from '../lib/components/Header';
describe('Header', () => {
it('renders as a <header>', () => {
const wrapper = shallow(<Header />)
assert.equal(wrapper.type(), 'header');
});
it('has a title Excellent Budgeting', () => {
const wrapper = shallow(<Header />)
const header = wrapper.find('h1')
expect(header.text()).to.equal('Excellent Budgeting')
})
it('if there is no user there is no welcome message', () => {
const user = false
const wrapper = shallow(<Header user={user}/>)
expect(wrapper.find('p').text()).to.equal('')
})
it('if there is a user the welcome message will render', () => {
const user = true
const wrapper = shallow(<Header user={user}/>)
expect(wrapper.find('p').text()).to.equal('Welcome, ')
})
});
|
src/components/Embedded/intellijoe.js
|
pritchardtw/ReactPersonalSite
|
import React, { Component } from 'react';
import Project from '../project';
export default class IntelliJoe extends Component {
render() {
const images = [
"../../static/images/embedded/intellijoe/blockdiagram.png"
];
return(
<Project
title="Intelli Joe!"
description="I participated in a Milwaukee Hackathon with my co-workers. In addition to myself,
we had another Software Engineer, an Electrical Engineer, and a Mechanical Engineer.
We won the “Nerdiest Project”. I picked out all the hardware for the project and coded
some Python scripts used to toggle the Raspberry Pi GPIO. The goal was to create an IoT coffee pot. We wanted to be able to turn the pot on before leaving for the office,
so by the time we arrived we would have hot coffee waiting for us. A secondary feature is that
we could also turn the pot off from home in case we forgot to at the end of the day.
During the 8 hour hackathon we achieved the ability to turn the pot on and off via a cell phone.
This proof of concept proved out our digital datapath infrastructure. At that point we were only limited by
whatever sensors we wanted to harness to the coffee pot. Some value add features we wanted were
-Temperature Sensor - to gauge hotness
-Force Sensor - to gauge fullness
-Optical Sensor - to gauge fullness should the force sensor not work so well (because the coffee pot weighs the same whether the waters in the pot or the reservoir.)
-Switch - to gauge if the pot is in the coffee maker or currently gone."
images={images} />
);
}
}
|
src/svg-icons/device/signal-wifi-0-bar.js
|
skarnecki/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifi0Bar = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M12.01 21.49L23.64 7c-.45-.34-4.93-4-11.64-4C5.28 3 .81 6.66.36 7l11.63 14.49.01.01.01-.01z"/>
</SvgIcon>
);
DeviceSignalWifi0Bar = pure(DeviceSignalWifi0Bar);
DeviceSignalWifi0Bar.displayName = 'DeviceSignalWifi0Bar';
export default DeviceSignalWifi0Bar;
|
app/components/Component1/StaticMap.js
|
joaquinPega/ReactTutorial
|
import React from 'react';
import {
StyleSheet,
View,
Text,
Dimensions,
ScrollView,
} from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
class StaticMap extends React.Component {
constructor(props) {
super(props);
this.state = {
region: {
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
},
};
}
render() {
return (
<View style={styles.container}>
<ScrollView
style={StyleSheet.absoluteFill}
contentContainerStyle={styles.scrollview}
>
<Text>Clicking</Text>
<Text>and</Text>
<Text>dragging</Text>
<Text>the</Text>
<Text>map</Text>
<Text>will</Text>
<Text>cause</Text>
<Text>the</Text>
<MapView
provider={this.props.provider}
style={styles.map}
scrollEnabled={false}
zoomEnabled={false}
pitchEnabled={false}
rotateEnabled={false}
initialRegion={this.state.region}
>
<MapView.Marker
title="This is a title"
description="This is a description"
coordinate={this.state.region}
/>
</MapView>
<Text>parent</Text>
<Text>ScrollView</Text>
<Text>to</Text>
<Text>scroll.</Text>
<Text>When</Text>
<Text>using</Text>
<Text>a Google</Text>
<Text>Map</Text>
<Text>this only</Text>
<Text>works</Text>
<Text>if you</Text>
<Text>disable:</Text>
<Text>scroll,</Text>
<Text>zoom,</Text>
<Text>pitch,</Text>
<Text>rotate.</Text>
<Text>...</Text>
<Text>It</Text>
<Text>would</Text>
<Text>be</Text>
<Text>nice</Text>
<Text>to</Text>
<Text>have</Text>
<Text>an</Text>
<Text>option</Text>
<Text>that</Text>
<Text>still</Text>
<Text>allows</Text>
<Text>zooming.</Text>
</ScrollView>
</View>
);
}
}
StaticMap.propTypes = {
provider: MapView.ProviderPropType,
};
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
justifyContent: 'flex-end',
alignItems: 'center',
},
scrollview: {
alignItems: 'center',
paddingVertical: 40,
},
map: {
position: 'absolute',
top: 0,
left: 0,
right: 0,
bottom: 0,
},
});
module.exports = StaticMap;
|
stories/base/switch.story.js
|
WellerQu/rongcapital-ui
|
import React from 'react';
import { storiesOf } from '@storybook/react';
import { Switch } from '../../src/base';
storiesOf('base.Switch', module)
.add('initialize by default', () => (
<Switch />
))
.add('initialize switch defaults isOpen true', () => (
<Switch width={80} height={20} isOpen={true} />
))
.add('initialize switch defaults disabled true', () => (
<Switch width={80} height={20} disabled={true} />
));
|
app/javascript/mastodon/features/report/components/status_check_box.js
|
unarist/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Toggle from 'react-toggle';
import noop from 'lodash/noop';
import StatusContent from '../../../components/status_content';
import { MediaGallery, Video } from '../../ui/util/async-components';
import Bundle from '../../ui/components/bundle';
export default class StatusCheckBox extends React.PureComponent {
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
checked: PropTypes.bool,
onToggle: PropTypes.func.isRequired,
disabled: PropTypes.bool,
};
render () {
const { status, checked, onToggle, disabled } = this.props;
let media = null;
if (status.get('reblog')) {
return null;
}
if (status.get('media_attachments').size > 0) {
if (status.get('media_attachments').some(item => item.get('type') === 'unknown')) {
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const video = status.getIn(['media_attachments', 0]);
media = (
<Bundle fetchComponent={Video} loading={this.renderLoadingVideoPlayer} >
{Component => (
<Component
preview={video.get('preview_url')}
src={video.get('url')}
width={239}
height={110}
inline
sensitive={status.get('sensitive')}
onOpenVideo={noop}
/>
)}
</Bundle>
);
} else {
media = (
<Bundle fetchComponent={MediaGallery} loading={this.renderLoadingMediaGallery} >
{Component => <Component media={status.get('media_attachments')} sensitive={status.get('sensitive')} height={110} onOpenMedia={noop} />}
</Bundle>
);
}
}
return (
<div className='status-check-box'>
<div className='status-check-box__status'>
<StatusContent status={status} />
{media}
</div>
<div className='status-check-box-toggle'>
<Toggle checked={checked} onChange={onToggle} disabled={disabled} />
</div>
</div>
);
}
}
|
src/svg-icons/navigation/menu.js
|
spiermar/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NavigationMenu = (props) => (
<SvgIcon {...props}>
<path d="M3 18h18v-2H3v2zm0-5h18v-2H3v2zm0-7v2h18V6H3z"/>
</SvgIcon>
);
NavigationMenu = pure(NavigationMenu);
NavigationMenu.displayName = 'NavigationMenu';
NavigationMenu.muiName = 'SvgIcon';
export default NavigationMenu;
|
examples/js/remote/remote-sorting.js
|
powerhome/react-bootstrap-table
|
import React from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
export default class RemoteSorting extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<BootstrapTable data={ this.props.data }
remote={ true }
options={ { onSortChange: this.props.onSortChange } }>
<TableHeaderColumn dataField='id' isKey={ true }>Product ID</TableHeaderColumn>
<TableHeaderColumn dataField='name'>Product Name</TableHeaderColumn>
<TableHeaderColumn dataField='price' dataSort={ true }>Product Price</TableHeaderColumn>
</BootstrapTable>
);
}
}
|
src/components/FileSelector/FileSelector.js
|
propertybase/react-lds
|
import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
import Dropzone from 'react-dropzone';
import {
FormElement,
FormElementControl,
FormElementError,
} from '../Form';
import { Button } from '../Button';
const preventDefault = e => e.preventDefault();
const FileSelector = ({
accept,
buttonText,
id,
error,
fatalError,
label,
minSize,
maxSize,
multiple,
onDragEnter,
onDragLeave,
onDrop,
selectorText,
selectorType,
}) => {
const errorStr = fatalError || error;
const fileSelectorClasses = [
'slds-file-selector',
`slds-file-selector_${selectorType}`
];
const primaryLabelId = `${id}-primary-label`;
const secondaryLabelId = `${id}-secondary-label`;
return (
<FormElement error={errorStr}>
<span className="slds-form-element__label" id={primaryLabelId}>
{label}
</span>
<FormElementControl>
<div className={cx(fileSelectorClasses)}>
<Dropzone
accept={accept}
disabled={!!fatalError}
minSize={minSize}
maxSize={maxSize}
multiple={multiple}
onDrop={onDrop}
onDragEnter={onDragEnter}
onDragLeave={onDragLeave}
>
{({
getRootProps,
getInputProps,
isDragActive,
}) => (
<div
{...getRootProps({
className: cx([
'slds-file-selector__dropzone',
{ 'slds-has-drag-over': isDragActive && !fatalError },
])
})}
>
<input
{...getInputProps({
'aria-labelledby': `${primaryLabelId} ${secondaryLabelId}`,
className: 'slds-file-selector__input slds-assistive-text',
disabled: fatalError,
id,
})}
/>
<label
className="slds-file-selector__body"
htmlFor={id}
// Fixes dialog not working due to default `label<>input` event handling (Safari,Chrome)
onClick={preventDefault}
id={secondaryLabelId}
>
<Button
buttonEl="span"
className="slds-file-selector__button"
flavor="neutral"
icon="upload"
sprite="utility"
title={buttonText}
/>
<span className="slds-file-selector__text slds-medium-show">
{selectorText}
</span>
</label>
</div>
)}
</Dropzone>
</div>
</FormElementControl>
<FormElementError error={errorStr} id={id} />
</FormElement>
);
};
FileSelector.defaultProps = {
accept: null,
error: null,
fatalError: null,
minSize: 0,
maxSize: null,
multiple: false,
onDragEnter: null,
onDragLeave: null,
selectorType: 'files',
};
FileSelector.propTypes = {
/**
* Maps to the HTML5 `accept` attribute. Used to narrow down allowed file types
*/
accept: PropTypes.string,
/**
* Button title
*/
buttonText: PropTypes.string.isRequired,
/**
* Error displayed below form. This should be used for informational messages as it does not disable the dropzone
*/
error: PropTypes.string,
/**
* Takes precedence over `error` and _will_ disable the dropzone
*/
fatalError: PropTypes.string,
/**
* Id of this file selector
*/
id: PropTypes.string.isRequired,
/**
* Top-level label
*/
label: PropTypes.string.isRequired,
/**
* Minimum file size (in bytes)
*/
minSize: PropTypes.number,
/**
* Maximum file size (in bytes)
*/
maxSize: PropTypes.number,
/**
* Maps to the HTML5 `multiple` attribute
*/
multiple: PropTypes.bool,
/**
* `onDragEnter` passed to `Dropzone`. Called with:
* - `event`
*/
onDragEnter: PropTypes.func,
/**
* `onDragLeave` passed to `Dropzone`. Called with:
* - `event`
*/
onDragLeave: PropTypes.func,
/**
* `onDrop` passed to `Dropzone`. Called with:
* - `acceptedFiles`
* - `rejectedFiles`
* - `event`
*/
onDrop: PropTypes.func.isRequired,
/**
* Addl. text rendered next to the button
*/
selectorText: PropTypes.string.isRequired,
/**
* Toggles display style
*/
selectorType: PropTypes.oneOf(['files', 'images']),
};
export default FileSelector;
|
src/components/commons/background.js
|
jesus-chacon/cookBook
|
import React, { Component } from 'react';
import { connect } from 'react-redux';
class Background extends Component {
render() {
if (!!this.props.background && this.props.background.length > 0) {
return (
<img id="bg" src={this.props.background} alt="background image" />
);
}else {
return (
<div id="bg"></div>
);
}
}
}
const mapStateToProps = ({backgroundReducer}) => ({
background: backgroundReducer.background
});
export default connect(mapStateToProps)(Background);
|
demo/tabs/tabs.js
|
koorchik/react-mdl
|
import React from 'react';
import Tabs, { Tab } from '../../src/tabs/Tabs';
class Demo extends React.Component {
constructor(props) {
super(props);
this.state = {
activeTab: 0
};
this._handleChange = this._handleChange.bind(this);
}
_handleChange(tabId) {
this.setState({
activeTab: tabId
});
}
_getTabContent() {
var list = [];
switch(this.state.activeTab) {
case 1:
list.push('Tywin', 'Cersei', 'Jamie', 'Tyrion');
break;
case 2:
list.push('Viserys', 'Daenerys');
break;
default:
list.push('Eddard', 'Catelyn', 'Robb', 'Sansa', 'Brandon', 'Arya', 'Rickon');
break;
}
return (
<ul>
{list.map(e => <li key={e}>{e}</li>)}
</ul>
);
}
render() {
return (
<div style={{display: 'inline-block', paddingLeft: '30%'}}>
<Tabs activeTab={this.state.activeTab} onChange={this._handleChange}>
<Tab>Starks</Tab>
<Tab>Lannisters</Tab>
<Tab>Targaryens</Tab>
</Tabs>
<section>
{this._getTabContent()}
</section>
</div>
);
}
}
React.render(<Demo />, document.getElementById('app'));
|
js/components/splashscreen/index.js
|
phamngoclinh/PetOnline_vs2
|
import React, { Component } from 'react';
import { Image } from 'react-native';
const launchscreen = require('../../../images/shadow.png');
export default class SplashPage extends Component {
static propTypes = {
navigator: React.PropTypes.shape({}),
}
componentWillMount() {
const navigator = this.props.navigator;
setTimeout(() => {
navigator.replace({
id: 'login',
});
}, 1500);
}
render() { // eslint-disable-line class-methods-use-this
return (
<Image source={launchscreen} style={{ flex: 1, height: null, width: null }} />
);
}
}
|
assets/js/app.js
|
Subash/sundar-nepal.subash.me
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import 'whatwg-fetch';
import * as util from './util.js';
import 'babel-polyfill';
import Container from './container';
class App {
constructor() {
this.initializeSDK();
this.userData = {};
this.render();
}
async updateUserData(userData) {
const regenerateImage = userData.userId && this.userData.userId !== userData.userId;
this.userData = { ...this.userData, ...userData };
if (regenerateImage) await this.generateImage();
this.render();
}
async generateImage() {
const imageSize = { width: 800, height: 800 };
const imageUrls = [
`/profile-picture/${this.userData.userId}?rand=${Math.random()}`,
'/img/flag.png'
];
try {
const image = await util.mergeImages(imageUrls, imageSize);
this.updateUserData({ image });
} catch (err) {
alert('Failed to create profile picture. ' + err.message);
}
}
clearUserData() {
this.userData = {};
this.render();
}
render() {
ReactDOM.render(
<Container userData={this.userData} />,
document.getElementById('app')
);
}
showLoading() {
this.updateUserData({ loading: true });
}
hideLoading() {
this.updateUserData({ loading: false });
}
async login() {
try {
this.clearUserData();
this.showLoading();
const userData = await this._login();
await this.updateUserData(userData);
this.hideLoading();
} catch (err) {
this.hideLoading();
alert(err.message);
}
}
_login() {
return new Promise((resolve, reject) => {
FB.getLoginStatus(response => {
if (response.status === 'connected') {
resolve({
userId: response.authResponse.userID,
accessToken: response.authResponse.accessToken
});
} else {
FB.login(response => {
if (response.authResponse) {
resolve({
userId: response.authResponse.userID,
accessToken: response.authResponse.accessToken
});
} else {
reject(new Error('Failed to login with Facebook'));
}
});
}
});
});
}
initializeSDK() {
if (!global.FB) return alert('Failed to load Facebook SDK. Please temporarily disable tracking and ad blockers.');
FB.init({
appId: '519129691585992',
autoLogAppEvents: true,
xfbml: true,
version: 'v2.10'
});
}
static init() {
global.app = new App();
}
}
App.init();
|
node_modules/react-bootstrap/es/NavDropdown.js
|
chenjic215/search-doctor
|
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import Dropdown from './Dropdown';
import splitComponentProps from './utils/splitComponentProps';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = _extends({}, Dropdown.propTypes, {
// Toggle props.
title: PropTypes.node.isRequired,
noCaret: PropTypes.bool,
active: PropTypes.bool,
// Override generated docs from <Dropdown>.
/**
* @private
*/
children: PropTypes.node
});
var NavDropdown = function (_React$Component) {
_inherits(NavDropdown, _React$Component);
function NavDropdown() {
_classCallCheck(this, NavDropdown);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavDropdown.prototype.isActive = function isActive(_ref, activeKey, activeHref) {
var props = _ref.props;
var _this2 = this;
if (props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref) {
return true;
}
if (ValidComponentChildren.some(props.children, function (child) {
return _this2.isActive(child, activeKey, activeHref);
})) {
return true;
}
return props.active;
};
NavDropdown.prototype.render = function render() {
var _this3 = this;
var _props = this.props,
title = _props.title,
activeKey = _props.activeKey,
activeHref = _props.activeHref,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['title', 'activeKey', 'activeHref', 'className', 'style', 'children']);
var active = this.isActive(this, activeKey, activeHref);
delete props.active; // Accessed via this.isActive().
delete props.eventKey; // Accessed via this.isActive().
var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent),
dropdownProps = _splitComponentProps[0],
toggleProps = _splitComponentProps[1];
// Unlike for the other dropdowns, styling needs to go to the `<Dropdown>`
// rather than the `<Dropdown.Toggle>`.
return React.createElement(
Dropdown,
_extends({}, dropdownProps, {
componentClass: 'li',
className: classNames(className, { active: active }),
style: style
}),
React.createElement(
Dropdown.Toggle,
_extends({}, toggleProps, { useAnchor: true }),
title
),
React.createElement(
Dropdown.Menu,
null,
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
active: _this3.isActive(child, activeKey, activeHref)
});
})
)
);
};
return NavDropdown;
}(React.Component);
NavDropdown.propTypes = propTypes;
export default NavDropdown;
|
src/app/js/pages/About.js
|
skratchdot/colorify
|
import React, { Component } from 'react';
import { Row, Col, Well } from 'react-bootstrap';
import Page from '../Page';
import { main, links } from '../Readme';
class About extends Component {
render() {
return (
<Page pageName="About">
<Row>
<Col md={8}>
<Well dangerouslySetInnerHTML={{ __html: main }} />
</Col>
<Col md={4}>
<Well dangerouslySetInnerHTML={{ __html: links }} />
</Col>
</Row>
</Page>
);
}
}
export default About;
|
pages/index.js
|
mvasilkov/mvasilkov.ovh
|
import React from 'react'
import Link from 'next/link'
import Article from '../app/article'
export const pagePath = 'index'
export const pageTitle = 'Start page'
export default class extends React.Component {
constructor(props) {
super(props)
this.state = { email: '' }
}
componentDidMount() {
setTimeout(t => {
if (Date.now() - t > 250) {
const args = 'compmvasilkovpgmail'.split('p').sort()
this.setState({ email: `${args.pop()}@${args.pop()}.${args.pop()}` })
}
}, 256, Date.now())
}
render() {
const { email } = this.state
return (
<Article path={pagePath} title={pageTitle}>
<header>
<h1>Mark Vasilkov</h1>
<p>Computer programmer from Israel</p>
</header>
<p className="short">I work in Python, Django, JavaScript, and React.</p>
{email ?
<p className="short">Write to me: <a href={`mailto:${email}`}>{email}</a></p> :
<p className="short">{'\u200b'}</p>}
<hr />
<p className="short">This is my personal home page.</p>
<p className="short"><Link href="/contents"><a>Contents</a></Link></p>
</Article>
)
}
}
|
app/javascript/mastodon/features/favourites/index.js
|
mstdn-jp/mastodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import { fetchFavourites } from '../../actions/interactions';
import { ScrollContainer } from 'react-router-scroll-4';
import AccountContainer from '../../containers/account_container';
import Column from '../ui/components/column';
import ColumnBackButton from '../../components/column_back_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
const mapStateToProps = (state, props) => ({
accountIds: state.getIn(['user_lists', 'favourited_by', props.params.statusId]),
});
@connect(mapStateToProps)
export default class Favourites extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
accountIds: ImmutablePropTypes.list,
};
componentWillMount () {
this.props.dispatch(fetchFavourites(this.props.params.statusId));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchFavourites(nextProps.params.statusId));
}
}
render () {
const { accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='favourites'>
<div className='scrollable'>
{accountIds.map(id => <AccountContainer key={id} id={id} withNote={false} />)}
</div>
</ScrollContainer>
</Column>
);
}
}
|
server/sonar-web/src/main/js/apps/settings/components/inputs/MultiValueInput.js
|
Builders-SonarSource/sonarqube-bis
|
/*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import PrimitiveInput from './PrimitiveInput';
import { getEmptyValue } from '../../utils';
export default class MultiValueInput extends React.Component {
static propTypes = {
setting: React.PropTypes.object.isRequired,
value: React.PropTypes.array,
onChange: React.PropTypes.func.isRequired
};
ensureValue () {
return this.props.value || [];
}
handleSingleInputChange (index, value) {
const newValue = [...this.ensureValue()];
newValue.splice(index, 1, value);
this.props.onChange(newValue);
}
handleDeleteValue (e, index) {
e.preventDefault();
e.target.blur();
const newValue = [...this.ensureValue()];
newValue.splice(index, 1);
this.props.onChange(newValue);
}
prepareSetting () {
const { setting } = this.props;
const newDefinition = { ...setting.definition, multiValues: false };
return {
...setting,
definition: newDefinition,
values: undefined
};
}
renderInput (value, index, isLast) {
return (
<li key={index} className="spacer-bottom">
<PrimitiveInput
setting={this.prepareSetting()}
value={value}
onChange={this.handleSingleInputChange.bind(this, index)}/>
{!isLast && (
<div className="display-inline-block spacer-left">
<button className="js-remove-value button-clean" onClick={e => this.handleDeleteValue(e, index)}>
<i className="icon-delete"/>
</button>
</div>
)}
</li>
);
}
render () {
const displayedValue = [...this.ensureValue(), ...getEmptyValue(this.props.setting.definition)];
return (
<div>
<ul>
{displayedValue.map((value, index) => this.renderInput(value, index, index === displayedValue.length - 1))}
</ul>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.