path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
client/routes/UserMgmt/components/UserMgmtPanel.js | patzj/ims | import React from 'react';
import UserMgmtTable from '../containers/UserMgmtTable';
export const UserMgmtPanel = () => {
return (
<div className="col-xs-10 col-xs-offset-1">
<h2 className="pull-left"><span className="glyphicon glyphicon glyphicon-user"></span> User Management</h2>
<div className="pull-right" style={{marginTop: '20px'}}>
<button className="btn btn-success" data-toggle="modal" data-target="#new-user-modal">
<span className="glyphicon glyphicon-plus-sign"></span> New User
</button>
</div>
<UserMgmtTable />
</div>
);
};
export default UserMgmtPanel;
|
lib/DebuggerView.js | ghgofort/Bart | 'use babel';
import React from 'react';
import ReactDOM from 'react-dom';
import EventEmitter from 'events';
const noop = function() {};
class StackView extends React.Component {
render() {
if (this.props.thread === 'spin') {
return <span className='loading loading-spinner-tiny inline-block'></span>;
} else if (this.props.thread) {
return (
<div className="block">
<ul className='list-group'>
{this.props.thread.threadInfo.call_stack.map((stack, index) =>
<li
key={index}
className={(this.props.selected || 0) === index ? "list-item selected" : "list-item"}
onClick={this.props.onSelectFrame ? () => this.props.onSelectFrame(index) : noop}
title={stack.location.script_path}
>
<span>{stack.location.script_path.split('/').pop()}</span>
<span>:{stack.location.line_number}</span>
<span> {stack.location.function_name}</span>
</li>
)}
</ul>
</div>
);
} else {
return (<div className="block">No active thread</div>);
}
}
}
class VarView extends React.Component {
constructor() {
super();
this.state = {opened: false, pending: false, values: null}
}
toggleOpened() {
this.setState({opened: !this.state.opened});
if (!this.state.values && this.props.thread) {
this.setState({pending: true});
this.props.thread.getMembers(this.props.path, this.props.selected).then(data => {
this.setState({pending: false, values: data});
});
}
}
render() {
var pending = '';
if (this.state.pending) {
pending = <span className='loading loading-spinner-tiny inline-block'></span>;
}
var vals = '';
if (this.state.values && this.state.opened) {
vals =
(<ul className='list-tree'>
{this.state.values.map((value, index) =>
<li className="list-nested-item" key={index}>
<VarView
type={value.type}
value={value.value}
name={value.name}
path={this.props.path + '.' + value.name}
thread={this.props.thread}
selected={this.props.selected}
/>
</li>
)}
</ul>);
}
return (
<div className="bart_pad_tree">
<div className='list-item'>
<span className={this.props.type.includes('dw.') || this.props.type.includes('Object') ? 'icon icon-chevron-right' : ''}
onClick={this.toggleOpened.bind(this)}
></span>
<span title={this.props.type} >{this.props.name}</span>
<span> = {this.props.value}</span>
</div>
{pending} {vals}
</div>
)
}
}
class VariablesView extends React.Component {
render() {
if (this.props.values === 'spin') {
return <div className='b-bart_variables right'>
<span className='loading loading-spinner-tiny inline-block'></span>
</div>;
} if (this.props.values) {
return (
<div className="b-bart_variables right">
<ul className='list-tree'>
{this.props.values.map((value, key) =>
<li className="list-nested-item" key={key} >
<VarView type={value.type} value={value.value} name={value.name} path={value.name}
thread={this.props.thread} selected={this.props.selected}
/>
</li>
)}
</ul>
</div>);
} else {
return (<div className="b-bart_variables right">No variables</div>);
}
}
}
class MainView extends React.Component {
constructor() {
super();
this.state = {thread: null, selectedFrame: 0};
}
emit(eventName, data) {
this.emitter.emit(eventName, data);
}
componentDidMount() {
this.emitter = new EventEmitter();
}
on(event, fn) {
this.emitter.on(event, fn);
}
onSelectFrame(frameNo) {
this.emit('selectFrame', frameNo);
this.setState({selectedFrame: +frameNo});
}
render() {
return (
<div className="b-bart-debugger_panel block" contentEditable="true">
<atom-panel class="b-bart_parent_stack left">
<div className="inline-block btn-group">
<button onClick={this.emit.bind(this, 'close')} className="icon icon-remove-close btn" title="close debugger F12"></button>
<button onClick={this.emit.bind(this, 'stop')} className="icon icon-primitive-square btn" title="stop"></button>
<button onClick={this.emit.bind(this, 'resume')} className="icon icon-playback-play btn" title="resume F8"></button>
<button onClick={this.emit.bind(this, 'stepover')} className="icon icon-jump-right btn" title="step over F10"></button>
<button onClick={this.emit.bind(this, 'stepin')} className="icon icon-jump-down btn" title="step in F11"></button>
<button onClick={this.emit.bind(this, 'stepout')} className="icon icon-jump-up btn" title="step out SHIFT-F11"></button>
</div>
<StackView thread={this.state.thread} onSelectFrame={this.onSelectFrame.bind(this)} selected={this.state.selectedFrame}/>
</atom-panel>
<VariablesView values={this.state.values} thread={this.state.thread} selected={this.state.selectedFrame} />
<div className="clearboth"/>
</div>
);
}
}
export default class DebuggerView {
constructor() {
this.el = document.createElement('div');
this.el.className = 'b-bart-debugger';
this.container = document.createElement('div');
this.el.appendChild(this.container);
this.mainView = ReactDOM.render(<MainView />, this.container);
}
updateThread (maybeThread) {
this.mainView.setState({thread: maybeThread});
}
updateValues (maybeValues) {
this.mainView.setState({values: maybeValues});
}
on(eventName, cb) {
this.mainView.on(eventName, cb);
}
getElement () {
return this.el;
}
destroy() {
React.unmountComponentAtNode(this.container);
}
}
|
src/decorators/withViewport.js | wildcard/react-starter | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
client/app/components/Todos.js | pho3nixf1re/fullstack-workshop | import React from 'react'
import store from '../store'
import Loading from './Loading'
const styles = {
row: {
display: 'flex'
},
remove: {
marginRight: 10
}
}
const Todos = ({ loading, todos }) => {
if (loading) {
return <Loading />
}
return (
<div>
{todos.map(({ id, description }) => (
<div key={id} style={styles.row}>
<a
href='#'
onClick={() => store.trigger('todos:remove', { id })}
style={styles.remove}
>X</a>
<div>{description}</div>
</div>
))}
</div>
)
}
export default Todos
|
packages/reactor-kitchensink/src/examples/Charts/3DColumn/NegativeValues/NegativeValues.js | dbuhrman/extjs-reactor | import React, { Component } from 'react';
import { Container } from '@extjs/ext-react';
import { Cartesian } from '@extjs/ext-react-charts';
import ChartToolbar from '../../ChartToolbar';
export default class NegativeValues extends Component {
store = Ext.create('Ext.data.Store', {
fields: ['quarter', 'consumer', 'gaming', 'phone', 'corporate'],
data: [
{ quarter: 'Q1 2012', consumer: 7, gaming: 3, phone: 5, corporate: -7},
{ quarter: 'Q2 2012', consumer: 7, gaming: 4, phone: 6, corporate: -4},
{ quarter: 'Q3 2012', consumer: 8, gaming: 5, phone: 7, corporate: -3},
{ quarter: 'Q4 2012', consumer: 10, gaming: 3, phone: 8, corporate: -1},
{ quarter: 'Q1 2013', consumer: 6, gaming: 1, phone: 7, corporate: -2},
{ quarter: 'Q2 2013', consumer: 7, gaming: -4, phone: 8, corporate: -1},
{ quarter: 'Q3 2013', consumer: 8, gaming: -6, phone: 9, corporate: 0 },
{ quarter: 'Q4 2013', consumer: 10, gaming: -3, phone: 11, corporate: 2 },
{ quarter: 'Q1 2014', consumer: 6, gaming: 2, phone: 9, corporate: -1},
{ quarter: 'Q2 2014', consumer: 6, gaming: 6, phone: 10, corporate: -6},
{ quarter: 'Q3 2014', consumer: 8, gaming: 9, phone: 12, corporate: -7},
{ quarter: 'Q4 2014', consumer: 9, gaming: 11, phone: 11, corporate: -4}
]
})
onSeriesRender = (sprite, config, data, index) => {
const isNegative = data.store.getAt(index).get('gaming') < 0;
if (isNegative) {
return {
fillStyle: '#974144' // dark red
};
}
}
render() {
return (
<Container padding={!Ext.os.is.Phone && 10} layout="fit">
<ChartToolbar downloadChartRef={this.refs.chart}/>
<Cartesian
shadow
ref="chart"
theme="muted"
store={this.store}
insetPadding="40 40 20 20"
innerPadding="0 3 0 0"
interactions="itemhighlight"
animation={{
easing: 'backOut',
duration: 500
}}
axes={[{
type: 'numeric3d',
position: 'left',
fields: 'gaming',
grid: {
odd: {
fillStyle: 'rgba(255, 255, 255, 0.06)'
},
even: {
fillStyle: 'rgba(0, 0, 0, 0.05)'
}
}
}, {
type: 'category3d',
position: 'bottom',
fields: 'quarter',
grid: true,
label: {
rotate: {
degrees: -60
}
}
}]}
series={[{
type: 'bar3d',
xField: 'quarter',
yField: 'gaming',
highlight: true,
renderer: this.onSeriesRender
}]}
/>
</Container>
)
}
} |
src/entypo/EmojiHappy.js | cox-auto-kc/react-entypo | import React from 'react';
import EntypoIcon from '../EntypoIcon';
const iconClass = 'entypo-svgicon entypo--EmojiHappy';
let EntypoEmojiHappy = (props) => (
<EntypoIcon propClass={iconClass} {...props}>
<path d="M10,0.4C4.698,0.4,0.4,4.698,0.4,10C0.4,15.302,4.698,19.6,10,19.6c5.301,0,9.6-4.298,9.6-9.601C19.6,4.698,15.301,0.4,10,0.4z M10,17.599c-4.197,0-7.6-3.402-7.6-7.6S5.802,2.4,10,2.4c4.197,0,7.601,3.402,7.601,7.6S14.197,17.599,10,17.599z M7.501,9.75C8.329,9.75,9,8.967,9,8s-0.672-1.75-1.5-1.75s-1.5,0.783-1.5,1.75S6.672,9.75,7.501,9.75z M12.5,9.75C13.329,9.75,14,8.967,14,8s-0.672-1.75-1.5-1.75S11,7.034,11,8S11.672,9.75,12.5,9.75z M14.341,11.336c-0.363-0.186-0.815-0.043-1.008,0.32c-0.034,0.066-0.869,1.593-3.332,1.593c-2.451,0-3.291-1.513-3.333-1.592c-0.188-0.365-0.632-0.514-1.004-0.329c-0.37,0.186-0.52,0.636-0.335,1.007c0.05,0.099,1.248,2.414,4.672,2.414c3.425,0,4.621-2.316,4.67-2.415C14.855,11.967,14.707,11.524,14.341,11.336z"/>
</EntypoIcon>
);
export default EntypoEmojiHappy;
|
demos/demo/src/components/Project/Input.js | bdjnk/cerebral | import React from 'react'
import {connect} from 'cerebral/react'
import {props, signal, state} from 'cerebral/tags'
import translations from '../../common/compute/translations'
export default connect(
{
// autoFocus
enterPressed: signal`projects.enterPressed`,
escPressed: signal`projects.escPressed`,
// field
// placeholderKey
value: state`projects.$draft.${props`field`}`,
valueChanged: signal`projects.formValueChanged`,
t: translations
},
function Input ({autoFocus, enterPressed, escPressed, field, placeholderKey, value, valueChanged, t}) {
const onKeyDown = e => {
switch (e.key) {
case 'Enter': enterPressed(); break
case 'Escape': escPressed(); break
default: break // noop
}
}
const onChange = e => {
valueChanged({key: field, value: e.target.value})
}
return (
<input className='input' type='text'
autoFocus={autoFocus}
placeholder={t[placeholderKey]}
onKeyDown={onKeyDown}
onChange={onChange}
value={value || ''}
name={field}
/>
)
}
)
|
packages/example/mobx-example/src/components/todoFooter.js | Raathigesh/wiretap | import React from 'react';
import PropTypes from 'prop-types';
import {observer} from 'mobx-react';
import {pluralize} from '../utils';
import { ALL_TODOS, ACTIVE_TODOS, COMPLETED_TODOS } from '../constants';
@observer
export default class TodoFooter extends React.Component {
render() {
const todoStore = this.props.todoStore;
if (!todoStore.activeTodoCount && !todoStore.completedCount)
return null;
const activeTodoWord = pluralize(todoStore.activeTodoCount, 'item');
return (
<footer className="footer">
<span className="todo-count">
<strong>{todoStore.activeTodoCount}</strong> {activeTodoWord} left
</span>
<ul className="filters">
{this.renderFilterLink(ALL_TODOS, "", "All")}
{this.renderFilterLink(ACTIVE_TODOS, "active", "Active")}
{this.renderFilterLink(COMPLETED_TODOS, "completed", "Completed")}
</ul>
{ todoStore.completedCount === 0
? null
: <button
className="clear-completed"
onClick={this.clearCompleted}>
Clear completed
</button>
}
</footer>
);
}
renderFilterLink(filterName, url, caption) {
return (<li>
<a href={"#/" + url}
className={filterName === this.props.viewStore.todoFilter ? "selected" : ""}>
{caption}
</a>
{' '}
</li>)
}
clearCompleted = () => {
this.props.todoStore.clearCompleted();
};
}
TodoFooter.propTypes = {
viewStore: PropTypes.object.isRequired,
todoStore: PropTypes.object.isRequired
}
|
JS Web/ReactJS/Event and Forms/src/index.js | mitaka00/SoftUni | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
modules/line-chart/index.js | rma-consulting/rc-d3 | import React from 'react';
import ReactFauxDOM from 'react-faux-dom';
import {
event as lastEvent,
select,
axisBottom,
axisLeft,
axisRight,
line,
timeFormat
} from 'd3';
import {
createUniqueID,
reduce,
calculateMargin,
createValueGenerator,
createDomainRangeGenerator,
defaultColors,
defaultStyles,
getAxisStyles,
createCircularTicks
} from '../shared';
import interpolateLine from '../interpolate';
import PropTypes from 'prop-types';
import { Style } from 'radium';
import merge from 'lodash.merge';
import { timeParse as parse } from 'd3-time-format';
const dateParser = {};
export default class LineChart extends React.Component {
static get propTypes() {
return {
data: PropTypes.array.isRequired,
width: PropTypes.number,
height: PropTypes.number,
xType: PropTypes.string,
yType: PropTypes.string,
datePattern: PropTypes.string,
interpolate: PropTypes.string,
style: PropTypes.object,
margin: PropTypes.object,
axes: PropTypes.bool,
grid: PropTypes.bool,
verticalGrid: PropTypes.bool,
xDomainRange: PropTypes.array,
yDomainRange: PropTypes.array,
tickTimeDisplayFormat: PropTypes.string,
yTicks: PropTypes.number,
xTicks: PropTypes.number,
dataPoints: PropTypes.bool,
lineColors: PropTypes.array,
axisLabels: PropTypes.shape({
x: PropTypes.string,
y: PropTypes.string
}),
yAxisOrientRight: PropTypes.bool,
mouseOverHandler: PropTypes.func,
mouseOutHandler: PropTypes.func,
mouseMoveHandler: PropTypes.func,
clickHandler: PropTypes.func
};
}
static get defaultProps() {
return {
width: 200,
height: 150,
datePattern: '%d-%b-%y',
interpolate: 'linear',
axes: false,
xType: 'linear',
yType: 'linear',
lineColors: [],
axisLabels: {
x: '',
y: ''
},
mouseOverHandler: () => {},
mouseOutHandler: () => {},
mouseMoveHandler: () => {},
clickHandler: () => {}
};
}
constructor(props) {
super(props);
this.uid = createUniqueID(props);
}
componentDidMount() {
const lineChart = this.refs.lineChart;
createCircularTicks(lineChart);
}
componentDidUpdate() {
const lineChart = this.refs.lineChart;
createCircularTicks(lineChart);
}
createSvgNode({ m, w, h }) {
const node = new ReactFauxDOM.Element('svg');
node.setAttribute('width', w + m.left + m.right);
node.setAttribute('height', h + m.top + m.bottom);
return node;
}
createSvgRoot({ node, m }) {
return select(node)
.append('g')
.attr('transform', `translate(${m.left}, ${m.top})`);
}
createXAxis({ root, m, w, h, x }) {
const {
xType,
axisLabels: { x: label },
xTicks,
grid,
verticalGrid,
tickTimeDisplayFormat,
yAxisOrientRight
} = this.props;
const axis = axisBottom(x);
if (xType === 'time' && tickTimeDisplayFormat) {
axis
.tickFormat(timeFormat(tickTimeDisplayFormat));
}
if (grid && verticalGrid) {
axis
.tickSize(-h, 6)
.tickPadding(15);
} else {
axis
.tickSize(0)
.tickPadding(15);
}
if (xTicks) {
axis.ticks(xTicks);
}
const group = root
.append('g')
.attr('class', 'x axis')
.attr('transform', `translate(0, ${h})`);
group
.call(axis);
if (label) {
group
.append('text')
.attr('class', 'label')
.attr('y', m.bottom - 10)
.attr('x', yAxisOrientRight ? 0 : w)
.style('text-anchor',
(yAxisOrientRight)
? 'start'
: 'end')
.text(label);
}
}
createYAxis({ root, m, w, y }) {
const {
yType,
axisLabels: { y: label },
yTicks,
grid,
tickTimeDisplayFormat,
yAxisOrientRight
} = this.props;
const axis = yAxisOrientRight ? axisRight(y) : axisLeft(y);
if (yType === 'time' && tickTimeDisplayFormat) {
axis
.tickFormat(timeFormat(tickTimeDisplayFormat));
}
if (grid) {
axis
.tickSize(-w, 6)
.tickPadding(12);
} else {
axis
.tickPadding(10);
}
if (yTicks) {
axis.ticks(yTicks);
}
const group = root
.append('g')
.attr('class', 'y axis')
.attr('transform',
(yAxisOrientRight)
? `translate(${w}, 0)`
: 'translate(0, 0)');
group
.call(axis);
if (label) {
group
.append('text')
.attr('class', 'label')
.attr('transform', 'rotate(-90)')
.attr('x', 0)
.attr('y',
(yAxisOrientRight)
? -20 + m.right
: 0 - m.left)
.attr('dy', '.9em')
.style('text-anchor', 'end')
.text(label);
}
}
createLinePathChart({ root, x, y, xValue, yValue, colors }) {
const {
data,
interpolate
} = this.props;
const getStroke = (d, i) => colors[i];
const linePath = line()
.curve(interpolateLine(interpolate))
.x((d) => x(xValue(d)))
.y((d) => y(yValue(d)));
const group = root
.append('g')
.attr('class', 'lineChart');
group
.selectAll('path')
.data(data)
.enter()
.append('path')
.attr('class', 'line')
.style('stroke', getStroke)
.attr('d', linePath);
}
createPoints({ root, x, y, colors }) {
const {
data,
xType,
yType,
mouseOverHandler,
mouseOutHandler,
mouseMoveHandler,
clickHandler
} = this.props;
/*
* We don't really need to do this, but it
* avoids obscure "this" below
*/
const calculateDate = (v) => this.parseDate(v);
const getStroke = (d, i) => colors[i];
/*
* Creating the calculation functions
*/
const calculateCX = (d) => (
(xType === 'time')
? x(calculateDate(d.x))
: x(d.x));
const calculateCY = (d) => (
(yType === 'time')
? y(calculateDate(d.y))
: y(d.y));
const mouseover = (d) => mouseOverHandler(d, lastEvent);
const mouseout = (d) => mouseOutHandler(d, lastEvent);
const mousemove = (d) => mouseMoveHandler(d, lastEvent);
const click = (d) => clickHandler(d, lastEvent);
const group = root
.append('g')
.attr('class', 'dataPoints');
data.forEach((item) => {
item.forEach((d) => {
/*
* Applying the calculation functions
*/
group
.datum(d)
.append('circle')
.attr('class', 'data-point')
.style('strokeWidth', '2px')
.style('stroke', getStroke)
.style('fill', 'white')
.attr('cx', calculateCX)
.attr('cy', calculateCY)
.on('mouseover', mouseover)
.on('mouseout', mouseout)
.on('mousemove', mousemove)
.on('click', click);
});
});
}
createStyle() {
const {
style,
grid,
verticalGrid,
yAxisOrientRight
} = this.props;
const uid = this.uid;
const scope = `.line-chart-${uid}`;
const axisStyles = getAxisStyles(grid, verticalGrid, yAxisOrientRight);
const rules = merge({}, defaultStyles, style, axisStyles);
return (
<Style
scopeSelector={scope}
rules={rules}
/>
);
}
parseDate(v) {
const {
datePattern
} = this.props;
const datePatternParser = (
dateParser[datePattern] || (
dateParser[datePattern] = parse(datePattern)));
return datePatternParser(v);
}
calculateChartParameters() {
const {
data,
axes,
xType,
yType,
xDomainRange,
yDomainRange,
margin,
width,
height,
lineColors,
yAxisOrientRight
} = this.props;
/*
* We could "bind"!
*/
const parseDate = (v) => this.parseDate(v);
/*
* 'w' and 'h' are the width and height of the graph canvas
* (excluding axes and other furniture)
*/
const m = calculateMargin(axes, margin, yAxisOrientRight);
const w = reduce(width, m.left, m.right);
const h = reduce(height, m.top, m.bottom);
const x = createDomainRangeGenerator('x', xDomainRange, data, xType, w, parseDate);
const y = createDomainRangeGenerator('y', yDomainRange, data, yType, h, parseDate);
const xValue = createValueGenerator('x', xType, parseDate);
const yValue = createValueGenerator('y', yType, parseDate);
const colors = lineColors.concat(defaultColors);
const node = this.createSvgNode({ m, w, h });
const root = this.createSvgRoot({ node, m });
return {
m,
w,
h,
x,
y,
xValue,
yValue,
colors,
node,
root
};
}
render() {
const {
axes,
dataPoints
} = this.props;
const p = this.calculateChartParameters();
if (axes) {
this.createXAxis(p);
this.createYAxis(p);
}
this.createLinePathChart(p);
if (dataPoints) {
this.createPoints(p);
}
const uid = this.uid;
const className = `line-chart-${uid}`;
const {
node
} = p;
return (
<div ref="lineChart" className={className}>
{this.createStyle()}
{node.toReact()}
</div>
);
}
}
|
src/components/Logo/Logo.js | askd/animakit | import React from 'react';
import PropTypes from 'prop-types';
import styles from './Logo.css';
const Logo = (props) =>
<div className={ `${styles.logo} ${props.className}` } />
;
Logo.propTypes = {
className: PropTypes.string,
};
export default Logo;
|
admin/src/components/Portal.js | kwangkim/keystone | import React from 'react';
module.exports = React.createClass({
displayName: 'Portal',
portalElement: null,
render: () => null,
componentDidMount() {
let p = document.createElement('div');
document.body.appendChild(p);
this.portalElement = p;
this.componentDidUpdate();
},
componentWillUnmount() {
document.body.removeChild(this.portalElement);
},
componentDidUpdate() {
React.render(<div {...this.props}>{this.props.children}</div>, this.portalElement);
}
});
|
app/index.js | beverku/wtimer-react | import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
// import { browserHistory } from 'react-router';
// import { syncHistoryWithStore } from 'react-router-redux';
import { AppContainer } from 'react-hot-loader';
import HelloWorld from './HelloWorld';
// const history = syncHistoryWithStore(browserHistory, store);
render(
<AppContainer>
<HelloWorld history={history} />
</AppContainer>,
document.getElementById('app')
);
if (module.hot) {
module.hot.accept('./HelloWorld', () => {
const NewHelloWorld = require('./HelloWorld').default;
render(
<AppContainer>
<NewHelloWorld history={history} />
</AppContainer>,
document.getElementById('app')
);
});
}
|
src/svg-icons/image/brightness-4.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrightness4 = (props) => (
<SvgIcon {...props}>
<path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"/>
</SvgIcon>
);
ImageBrightness4 = pure(ImageBrightness4);
ImageBrightness4.displayName = 'ImageBrightness4';
ImageBrightness4.muiName = 'SvgIcon';
export default ImageBrightness4;
|
app/javascript/mastodon/components/load_gap.js | primenumber/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { injectIntl, defineMessages } from 'react-intl';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
load_more: { id: 'status.load_more', defaultMessage: 'Load more' },
});
export default @injectIntl
class LoadGap extends React.PureComponent {
static propTypes = {
disabled: PropTypes.bool,
maxId: PropTypes.string,
onClick: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleClick = () => {
this.props.onClick(this.props.maxId);
}
render () {
const { disabled, intl } = this.props;
return (
<button className='load-more load-gap' disabled={disabled} onClick={this.handleClick} aria-label={intl.formatMessage(messages.load_more)}>
<Icon id='ellipsis-h' />
</button>
);
}
}
|
client/modules/Theme/components/List/List.js | b3j0f/lechangement | import './List.css';
import React, { Component } from 'react';
import SelectField from 'material-ui/SelectField';
import MenuItem from 'material-ui/MenuItem';
import Theme from '../Item/Item';
class List extends Component {
constructor(props) {
super(props);
this.state = {
allthemes: props.allthemes,
themes: props.themes
}
}
render() {
const themes = this.state.themes;
const allthemes = this.state.allthemes;
return (
<div className="theme-list">
<SelectField multiple={true} value={themes} className="themes-select">
{
allthemes.map(
(theme) => {
return
<MenuItem value={theme.name} primaryText={theme.name}>
<Theme theme={theme}/>
</MenuItem>
}
)
}
</SelectField>
</div>
)
}
}
List.propTypes = {
themes: PropTypes.arrayOf(PropTypes.string).isRequired,
allthemes: PropTypes.arrayOf(PropTypes.shape({
name: PropTypes.string.isRequired,
img: PropTypes.string
})).isRequired
}
export default List;
|
node_modules/nuka-carousel/src/decorators.js | HasanSa/hackathon | 'use strict';
import React from 'react';
const DefaultDecorators = [
{
component: React.createClass({
render() {
return (
<button
style={this.getButtonStyles(this.props.currentSlide === 0 && !this.props.wrapAround)}
onClick={this.handleClick}>PREV</button>
)
},
handleClick(e) {
e.preventDefault();
this.props.previousSlide();
},
getButtonStyles(disabled) {
return {
border: 0,
background: 'rgba(0,0,0,0.4)',
color: 'white',
padding: 10,
outline: 0,
opacity: disabled ? 0.3 : 1,
cursor: 'pointer'
}
}
}),
position: 'CenterLeft'
},
{
component: React.createClass({
render() {
return (
<button
style={this.getButtonStyles(this.props.currentSlide + this.props.slidesToScroll >= this.props.slideCount && !this.props.wrapAround)}
onClick={this.handleClick}>NEXT</button>
)
},
handleClick(e) {
e.preventDefault();
this.props.nextSlide();
},
getButtonStyles(disabled) {
return {
border: 0,
background: 'rgba(0,0,0,0.4)',
color: 'white',
padding: 10,
outline: 0,
opacity: disabled ? 0.3 : 1,
cursor: 'pointer'
}
}
}),
position: 'CenterRight'
},
{
component: React.createClass({
render() {
var self = this;
var indexes = this.getIndexes(self.props.slideCount, self.props.slidesToScroll);
return (
<ul style={self.getListStyles()}>
{
indexes.map(function(index) {
return (
<li style={self.getListItemStyles()} key={index}>
<button
style={self.getButtonStyles(self.props.currentSlide === index)}
onClick={self.props.goToSlide.bind(null, index)}>
•
</button>
</li>
)
})
}
</ul>
)
},
getIndexes(count, inc) {
var arr = [];
for (var i = 0; i < count; i += inc) {
arr.push(i);
}
return arr;
},
getListStyles() {
return {
position: 'relative',
margin: 0,
top: -10,
padding: 0
}
},
getListItemStyles() {
return {
listStyleType: 'none',
display: 'inline-block'
}
},
getButtonStyles(active) {
return {
border: 0,
background: 'transparent',
color: 'black',
cursor: 'pointer',
padding: 10,
outline: 0,
fontSize: 24,
opacity: active ? 1 : 0.5
}
}
}),
position: 'BottomCenter'
}
];
export default DefaultDecorators;
|
app/components/Waiting/index.js | zillding/hangouts | /**
*
* Waiting
*
*/
import React from 'react';
import Icon from 'material-ui/svg-icons/social/people';
import { Flex } from 'react-flex';
import styles from './styles.css';
const iconStyle = {
height: 46,
width: 46,
};
const Waiting = () => (
<Flex
column
justifyContent="center"
className={styles.waiting}
>
<Flex>
<Icon style={iconStyle} />
<h1 className={styles.text}>
Waiting for other users to join...
</h1>
</Flex>
</Flex>
);
export default Waiting;
|
app/components/Header/index.js | dmalik/livepoll | import React from 'react';
import MegaphoneIcon from '../MegaphoneIcon';
import styles from './styles.css';
function Header(props) {
return (
<header>
<div className={styles.headerSection}>
<div className={styles.iconBox}><MegaphoneIcon size="3em" /> </div>
<div className={styles.arrowBox}> > </div>
<div className={styles.questionBox}>{props.question}</div>
</div>
</header>
);
}
Header.propTypes = {
question: React.PropTypes.string,
};
export default Header;
|
src/components/ModelWrapper/ModelWrapper.js | Zoomdata/nhtsa-dashboard-2.2 | import styles from './ModelWrapper.css';
import React, { Component } from 'react';
import ModelHeader from '../ModelHeader/ModelHeader';
import ModelBarChart from '../ModelBarChart/ModelBarChart';
export default class ModelWrapper extends Component {
render() {
return <div className={styles.root}>
<ModelHeader />
<ModelBarChart />
</div>
}
} |
frontend/src/components/shared/preloader/index.js | Kilte/cindy | import React from 'react';
import './index.css';
const Preloader = () => <div className="preloader"></div>;
export default Preloader;
|
client/src/components/Icon/Icon.js | nealtodd/wagtail | import PropTypes from 'prop-types';
import React from 'react';
/**
* Abstracts away the actual icon implementation (font icons, SVG icons, CSS sprite).
* Provide a `title` as an accessible label intended for screen readers.
*/
const Icon = ({ name, className, title }) => (
<span>
<span className={`icon icon-${name} ${className || ''}`} aria-hidden></span>
{title ? (
<span className="visuallyhidden">
{title}
</span>
) : null}
</span>
);
Icon.propTypes = {
name: PropTypes.string.isRequired,
className: PropTypes.string,
title: PropTypes.string,
};
Icon.defaultProps = {
className: null,
title: null,
};
export default Icon;
|
react/Paragraph/Paragraph.js | seekinternational/seek-asia-style-guide | import styles from './Paragraph.less';
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
export default function Paragraph({ children, className, ...restProps }) {
return (
<p {...restProps} className={classnames(styles.root, className)}>
{children}
</p>
);
}
Paragraph.propTypes = {
children: PropTypes.node.isRequired,
className: PropTypes.string
};
|
src/scenes/UserConsole/components/Header/Header.js | adeira/connector-frontend | import React from 'react';
import styles from './Header.css';
import MainMenu from './../MainMenu/MainMenu';
import Authenticator from 'services/Authenticator';
import {browserHistory} from 'react-router'
class Header extends React.Component {
handleLogout() {
Authenticator.deauthenticateUser();
browserHistory.push('/'); //redirect to the homepage
}
render() {
return (
<div className={styles.header}>
<div className="wrapper--fluid">
<h1>
Adeira<span>∿</span><strong>connector</strong>
<small>user console</small>
</h1>
<a className={styles.header__logoutLink} onClick={this.handleLogout}>
Log Out
</a>
</div>
<MainMenu/>
</div>
);
}
}
export default Header;
|
src/applications/static-pages/widget-creators/resources-and-support-search.js | department-of-veterans-affairs/vets-website | // Node modules.
import React from 'react';
import ReactDOM from 'react-dom';
export default (store, widgetType) => {
const root = document.querySelector(`[data-widget-type="${widgetType}"]`);
if (root) {
import(/* webpackChunkName: "resources-and-support-search" */
'applications/resources-and-support/components/StandaloneSearchFormWidget').then(
module => {
const App = module.default;
ReactDOM.render(<App />, root);
},
);
}
};
|
src/components/Video.js | RicardoG2016/WRFD-project-site | import React, { Component } from 'react';
import '../App.css';
class Video extends Component {
componentDidMount(){
window.scrollTo(0, 0);
}
render() {
return (
<div className="video">
<h3 className="Header">Stop the Burning</h3>
<iframe className="yt-video" src="https://www.youtube.com/embed/iPdp-_ZwMTU?ecver=2" frameBorder="0" allowFullScreen></iframe>
</div>
);
}
}
export default Video;
|
src/docs/examples/RegistrationForm/ExampleRegistrationForm.js | tlraridon/ps-react-train-tlr | import React from 'react';
import RegistrationForm from 'ps-react-train-tlr/RegistrationForm';
export default class ExampleRegistrationForm extends React.Component {
onSubmit = (user) => {
console.log(user);
}
render() {
return <RegistrationForm onSubmit={this.onSubmit} confirmationMessage='Success!' />
}
} |
src/views/BlocksGrid.js | abachman/my-new-tab | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { Responsive, WidthProvider } from 'react-grid-layout'
import Actions from 'actions'
import Link from './Blocks/Link'
import Weather from './Blocks/Weather'
import Clock from './Blocks/Clock'
import Bookmarks from './Blocks/Bookmarks'
import Template from './Blocks/Template'
import Bare from './Blocks/Bare'
import log from '../utils/logger'
// lib
import 'react-resizable/css/styles.css'
import 'react-grid-layout/css/styles.css'
// custom
import 'stylesheets/Grid.css'
import 'stylesheets/Blocks.css'
const ResponsiveReactGridLayout = WidthProvider(Responsive)
// Dynamic Column Allocation
const STEP = 80
const COLS = {}
const BREAKPOINTS = {}
for (let i = 1; i < 16; i += 2) {
const lbl = 'col_' + i
COLS[lbl] = i
BREAKPOINTS[lbl] = i * STEP
}
class BlocksGrid extends React.Component {
static propTypes = {
blocks: PropTypes.object.isRequired,
}
constructor(props) {
super(props)
this.state = {
layout: {},
breakpoint: null,
ready: false,
}
this.onLayoutChange = this.onLayoutChange.bind(this)
this.onBreakpointChange = this.onBreakpointChange.bind(this)
}
componentDidMount() {
setTimeout(() => {
this.setState({ ready: true })
}, 1000)
}
updateBlockItem(item) {
const id = item.i
this.props.dispatch(
Actions.updateBlock(id, {
coords: { ...item },
})
)
}
onLayoutChange(layout, layouts) {
log('onLayoutChange', layout, layouts)
this.props.dispatch(Actions.updateLayouts(layouts))
}
onBreakpointChange(breakpoint) {
log('onBreakpointChange', breakpoint)
this.props.dispatch(Actions.setBreakpoint(breakpoint))
}
selectView(block) {
let blockView
switch (block.type) {
case 'clock':
blockView = <Clock block={block} />
break
case 'weather':
blockView = <Weather block={block} />
break
case 'bookmarks':
blockView = <Bookmarks block={block} />
break
case 'feed':
case 'link':
blockView = <Link block={block} />
break
case 'userscript':
blockView = <Bare block={block} />
break
case 'template':
blockView = <Template block={block} />
break
default:
blockView = <Link block={block} />
break
}
return blockView
}
renderBlocks() {
return Object.entries(this.props.blocks).map((kv, idx) => {
const id = kv[0],
block = kv[1]
return <div key={id}>{this.selectView(block)}</div>
})
}
render() {
const { editing } = this.props
const className = 'grid-layout ' + (this.state.ready ? 'ready' : 'unready')
return (
<ResponsiveReactGridLayout
className={className}
autoSize={true}
measureBeforeMount={true}
isDraggable={editing}
isResizable={editing}
breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
cols={{ lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 }}
layouts={this.props.layouts}
containerPadding={[0, 0]}
onLayoutChange={this.onLayoutChange}
onBreakpointChange={this.onBreakpointChange}
compactType={this.props.compacting ? 'vertical' : null}
rowHeight={80}
>
{this.renderBlocks()}
</ResponsiveReactGridLayout>
)
}
}
const mapStateToProps = (state) => {
return {
blocks: state.blocks,
layouts: state.layouts,
editing: state.layout.editing,
compacting: state.layout.compacting,
}
}
export default connect(mapStateToProps)(BlocksGrid)
|
b_stateMachine/complex_templates/jsx/wizard/summary.js | Muzietto/react-playground | 'use strict';
import React from 'react';
// NB props.handlers[0] is meant for the wizard restart link
export default function summary(props) {
return (
<div className="summary">
<div
className={_class_name(1)}
onClick={props.handlers && props.handlers[1]}>
1
</div>
<div
className={_class_name(2)}
onClick={props.handlers && props.handlers[2]}>
2
</div>
<div
className={_class_name(3)}
onClick={props.handlers && props.handlers[3]}>
3
</div>
</div>
);
function _class_name(pos) {
return dictionary(pos)
+ ((props.step >= pos) ? ' enabled' : '')
+ ((props.handlers && props.handlers.length > pos) ? ' cursor_pointer' : '');
function dictionary(pos) {
return ['zeroth', 'first', 'second', 'third'][pos];
}
}
}
|
source/shared/components/about/index.js | nRewik/react-railgun | import React from 'react'
import { connect } from 'react-redux'
const About = () => {
return (
<div>
react-railgun is an elegant universal react-redux starter kit.
<div>Greatly inspired by {' '}
<a href='https://github.com/cloverfield-tools/universal-react-boilerplate'>
cloverfield-tools/universal-react-boilerplate
</a>
</div>
</div>
)
}
// Connect props to component
export default connect()(About)
|
docs/src/app/components/pages/components/DatePicker/ExampleToggle.js | pradel/material-ui | import React from 'react';
import DatePicker from 'material-ui/DatePicker';
import TextField from 'material-ui/TextField';
import Toggle from 'material-ui/Toggle';
const optionsStyle = {
maxWidth: 255,
marginRight: 'auto',
};
export default class DatePickerExampleToggle extends React.Component {
constructor(props) {
super(props);
const minDate = new Date();
const maxDate = new Date();
minDate.setFullYear(minDate.getFullYear() - 1);
minDate.setHours(0, 0, 0, 0);
maxDate.setFullYear(maxDate.getFullYear() + 1);
maxDate.setHours(0, 0, 0, 0);
this.state = {
minDate: minDate,
maxDate: maxDate,
autoOk: false,
disableYearSelection: false,
};
}
handleChangeMinDate = (event) => {
this.setState({
minDate: new Date(event.target.value),
});
};
handleChangeMaxDate = (event) => {
this.setState({
maxDate: new Date(event.target.value),
});
};
handleToggle = (event, toggled) => {
this.setState({
[event.target.name]: toggled,
});
};
render() {
return (
<div>
<DatePicker
hintText="Ranged Date Picker"
autoOk={this.state.autoOk}
minDate={this.state.minDate}
maxDate={this.state.maxDate}
disableYearSelection={this.state.disableYearSelection}
/>
<div style={optionsStyle}>
<TextField
floatingLabelText="Min Date"
value={this.state.minDate.toDateString()}
onChange={this.handleChangeMinDate}
/>
<TextField
floatingLabelText="Max Date"
value={this.state.maxDate.toDateString()}
onChange={this.handleChangeMaxDate}
/>
<Toggle
name="autoOk"
value="autoOk"
label="Auto Accept"
toggled={this.state.autoOk}
onToggle={this.handleToggle}
/>
<Toggle
name="disableYearSelection"
value="disableYearSelection"
label="Disable Year Selection"
toggled={this.state.disableYearSelection}
onToggle={this.handleToggle}
/>
</div>
</div>
);
}
}
|
src/components/Index.js | vihanchaudhry/cake-showdown | import React from 'react'
import Showdown from '../containers/Showdown'
import Rankings from '../containers/Rankings'
const Index = () => (
<div>
<Showdown />
<Rankings />
</div>
)
export default Index
|
resources/js/ChatRoom.js | milon/node-chat-room | import React from 'react';
import ReactDOM from 'react-dom';
import MessageBox from './MessageBox';
var socket = io.connect();
var ChatRoom = ReactDOM.render(<MessageBox socket={socket} />, document.querySelector('#msg-body'));
socket.on('message', function(data){
console.log(data);
ChatRoom.newMessage(data);
});
|
src/layouts/CoreLayout.js | react-li/React-Redux-material-ui-Starter-Kit | import React from 'react';
import 'styles/core.scss';
export default class CoreLayout extends React.Component {
static propTypes = {
children : React.PropTypes.element
}
render () {
return (
<div className='page-container'>
<div className='view-container'>
{this.props.children}
</div>
</div>
);
}
}
|
src/widths_mixins.js | djforth/morse-react-mixins | // Libraries
// import React from 'react';
import ReactDOM from 'react-dom';
import _ from 'lodash';
import includes from 'lodash/includes';
let attrs = [
'padding-left',
'padding-right',
'margin-left',
'margin-right',
'border-left-width',
'border-right-width',
'width',
];
let elements = [];
let elmSizes = [];
function getValue(v) {
return Number(v.replace(/[a-z]|%/g, ''));
}
function getTrueWidth(e) {
let elm = window.getComputedStyle(e, null);
let n = 0;
_.forEach(attrs, attr => {
let v = getValue(elm.getPropertyValue(attr));
n += v;
});
addElement(e, n);
return n;
}
function addElement(elm, w) {
if (includes(_.map(elmSizes, e => e.elm), elm)) {
elmSizes = _.map(elmSizes, e => {
if (e.elm.isEqualNode(elm)) e.width = w;
return e;
});
} else {
elmSizes.push({ elm: elm, width: w });
}
}
/* eslint-disable no-invalid-this */
export default {
getTrueWidth: getTrueWidth,
convertRefs: refs => {
elements = _.values(refs);
return this;
},
convertDomlist: function(list) {
elements = Array.prototype.slice.call(list);
return this;
},
convertReactComps: function(refs) {
elements = _.map(_.values(refs), r => {
if (_.isElement(r)) return r;
return ReactDOM.findDOMNode(r);
});
},
getAllWidths: function() {
return elmSizes;
},
getWidths: function(list) {
let items;
let width;
items = _.isArray(list) ? list : elements;
if (items.length === 0) return 0;
width = _.reduce(
items,
function(p, c) {
let n = _.isNumber(p) ? p : getTrueWidth(p);
n += getTrueWidth(c);
return n;
},
0
);
return width;
},
};
/* eslint-enable no-invalid-this */
|
packages/wix-style-react/src/Layout/docs/examples/Form.js | wix/wix-style-react | import React from 'react';
import { style, classes } from '../styles.st.css';
import {
Layout,
Cell,
Card,
FormField,
Input,
InputArea,
Checkbox,
Text,
Button,
RadioGroup,
} from 'wix-style-react';
export default () => (
<div className={style(classes.exampleContainer)}>
<Layout>
{/* Big area, the main content */}
<Cell span={8}>
<Layout>
<Cell>
<Card>
<Card.Header title="Various Inputs" />
<Card.Divider />
<Card.Content>
<Layout>
<Cell>{field('Your Best Joke:', InputArea)}</Cell>
<Cell>{field('Your Email:')}</Cell>
</Layout>
{divider()}
<Layout>
<Cell span={6}>{field('First Name:')}</Cell>
<Cell span={6}>{field('Second Name:')}</Cell>
</Layout>
{divider()}
<Layout gap="10px">
<Cell span={3} vertical>
<Text>Home Address:</Text>
</Cell>
<Cell span={9} vertical>
{field('')}
</Cell>
</Layout>
{divider()}
<Layout gap="10px">
<Cell>
<Text>Get In Touch</Text>
</Cell>
{['Name', 'Email', 'Phone No.'].map(label => (
<Cell
key={label}
span={4}
vertical
children={<Input placeholder={label} />}
/>
))}
</Layout>
{divider()}
<Layout>
<Cell span={8} vertical>
<Checkbox>I Accept to Decline</Checkbox>
</Cell>
<Cell span={4}>
<Button>Useless Button</Button>
</Cell>
</Layout>
</Card.Content>
</Card>
</Cell>
{['left', 'right'].map(direction => (
<Cell span={6} key={direction}>
{card(`something on the ${direction}`, 'Anything goes')}
</Cell>
))}
{['left', 'middle', 'right'].map(direction => (
<Cell span={4} key={direction}>
{card(`something on the ${direction}`, 'Anything goes')}
</Cell>
))}
</Layout>
</Cell>
{/* sidebar */}
<Cell span={4}>
<Card>
<Card.Header title="Additional Info" />
<Card.Divider />
<Card.Content>
<Text>{'No need for <Layout> for just column'}</Text>
{divider()}
<RadioGroup>
{'Mixing and matching components is easy!'
.split(' ')
.map(word => (
<RadioGroup.Radio key={word}>{word}</RadioGroup.Radio>
))}
</RadioGroup>
{divider()}
<Button>I Agree!</Button>
</Card.Content>
</Card>
</Cell>
</Layout>
</div>
);
function field(label, component = Input) {
return <FormField label={label}>{React.createElement(component)}</FormField>;
}
function divider() {
return <div style={{ height: '30px' }} />;
}
function card(title, children) {
return (
<Card>
<Card.Header title={title} />
<Card.Divider />
<Card.Content children={children} />
</Card>
);
}
|
examples/todomvc/index.js | iansinnott/redux | import 'babel/polyfill';
import React from 'react';
import Root from './containers/Root';
import 'todomvc-app-css/index.css';
React.render(
<Root />,
document.getElementById('root')
);
|
pootle/static/js/admin/components/User/UserEdit.js | Finntack/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import React from 'react';
import UserForm from './UserForm';
const UserEdit = React.createClass({
propTypes: {
collection: React.PropTypes.object.isRequired,
model: React.PropTypes.object,
onAdd: React.PropTypes.func.isRequired,
onDelete: React.PropTypes.func.isRequired,
onSuccess: React.PropTypes.func.isRequired,
},
render() {
return (
<div className="item-edit">
<div className="hd">
<h2>{gettext('Edit User')}</h2>
<button
onClick={this.props.onAdd}
className="btn btn-primary"
>
{gettext('Add User')}
</button>
</div>
<div className="bd">
{!this.props.model ?
<p>{gettext('Use the search form to find the user, then click on a user to edit.')}</p> :
<UserForm
key={this.props.model.id}
model={this.props.model}
collection={this.props.collection}
onSuccess={this.props.onSuccess}
onDelete={this.props.onDelete}
/>
}
</div>
</div>
);
},
});
export default UserEdit;
|
clients/packages/admin-client/src/mobilizations/components/list/items/fund-raising.js | nossas/bonde-client | import PropTypes from 'prop-types'
import React from 'react'
import { FormattedMessage } from 'react-intl'
const FundRaising = ({ total_fund_raising: totalFundRaising }) => (
<div className='fund-raising px3 col col-2'>
<FormattedMessage
id='mobilizations.components--list.items.fund-raising.currency'
defaultMessage='R$'
/>
{' '}{totalFundRaising || '-'}
</div>
)
FundRaising.propTypes = {
total_fund_raising: PropTypes.oneOfType([PropTypes.string, PropTypes.number])
}
export default FundRaising
const Header = () => (
<div className='fund-raising-header px3 col col-2'>
<FormattedMessage
id='mobilizations.components--list.items.fund-raising.header.text'
defaultMessage='Arrecadações'
/>
</div>
)
FundRaising.Header = Header
|
app/containers/TodoListScene.js | uiheros/react-native-redux-todo-list | import NavigationBar from 'react-native-navbar';
import React, { Component } from 'react';
import {
View,
ScrollView,
} from 'react-native';
import { connect } from 'react-redux';
import { themeable } from '../themes';
import { toggleTodo, setVisibilityFilter } from '../actions';
import Todos from '../components/Todos';
import Filter from '../components/Filter';
import NewTodo from './AddTodoScene';
class TodoListScene extends Component {
constructor(props) {
super(props);
this.addNewTodo = this.addNewTodo.bind(this);
}
addNewTodo() {
this.props.navigator.push({
component: NewTodo
});
}
render() {
const {
todos,
style,
navBarStyle,
statusBarTintColor,
statusBarStyle,
navBarBtnTextColor,
onFilterPress,
onTodoPress,
activeOnly
} = this.props;
return (
<View style={style}>
<NavigationBar
statusBar={{tintColor: statusBarTintColor, style: statusBarStyle}}
title={{ title: 'Tasks' }}
rightButton={{ title: 'Add', handler: this.addNewTodo, tintColor: navBarBtnTextColor }}
style={navBarStyle}
/>
<ScrollView horizontal={false}>
<Todos todos={todos} onTodoPress={onTodoPress}/>
</ScrollView>
<Filter activeOnly={activeOnly} onPress={onFilterPress} />
</View>
);
}
}
const getVisibleTodos = (todos, filter) => {
switch (filter) {
case 'SHOW_ALL':
return todos;
case 'SHOW_ACTIVE':
return todos.filter(t => !t.completed);
}
};
const mapStateToProps = (state) => {
return {
todos: getVisibleTodos(state.todos, state.visibilityFilter),
activeOnly: state.visibilityFilter === 'SHOW_ACTIVE'
};
};
const mapDispatchToProps = (dispatch) => {
return {
onTodoPress: (id) => {
dispatch(toggleTodo(id));
},
onFilterPress: (activeOnly) => {
const filter = activeOnly ? 'SHOW_ACTIVE' : 'SHOW_ALL';
dispatch(setVisibilityFilter(filter));
}
};
};
const TodoListSceneContainer = connect(
mapStateToProps,
mapDispatchToProps
)(TodoListScene);
const ThemableTodoListScene = themeable(TodoListSceneContainer, (theme) => {
const {styles, variables} = theme;
return {
style: styles.container,
navBarStyle: styles.navBar,
statusBarTintColor: variables.colorNavBg,
statusBarStyle: variables.statusBarStyle,
navBarBtnTextColor: variables.colorNavbarText,
filterStyle: styles.filterItem,
filterTextStyle: styles.filterTextStyle
};
});
export default ThemableTodoListScene;
|
app/components/routes/Collection/index.js | robcalcroft/cybelle | import React from 'react';
import Container from 'common/Container';
export default class Home extends React.Component {
constructor() {
super();
}
renderBoxContainer() {
let numberOfRows = 10;
let key = 0;
let boxContainers = [];
let selectedBoxes = [1, 34, 65, 67, 97];
while(numberOfRows--) {
let rowNumber = numberOfRows;
boxContainers.push(
<div className='boxes-container' key={key++}>
{this.renderBoxes(rowNumber, selectedBoxes)}
</div>
);
}
return boxContainers.reverse();
}
renderBoxes(rowNumber, selectedBoxes) {
let numberOfBoxes = 10;
let key = 0;
let boxes = [];
while(numberOfBoxes--) {
let columnNumber = numberOfBoxes;
let boxNumber = parseInt(`${rowNumber}${columnNumber}`) + 1;
boxes.push(
<div
className={selectedBoxes.indexOf(boxNumber) === -1 ? 'box' : 'box-sold'}
data-boxnumber={boxNumber}
key={key++}>
{boxNumber}
</div>
);
}
return boxes.reverse();
}
render() {
return (
<Container page='collection'>
<div className='row'>
<div className='col l2 hide-on-med-and-down'>
{/*<img width='100%' height='450' src={require('assets/model-m.png')} alt='' />*/}
</div>
<div className='col s12 offset-l1 l6'>
{this.renderBoxContainer()}
</div>
<div className='col l2 offset-l1 hide-on-med-and-down'>
{/*<img width='100%' height='450' src={require('assets/model-w.png')} className='right' alt='' />*/}
</div>
</div>
</Container>
);
}
}
|
googlemaps/index.ios.js | DaveWJ/LearningReact | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class googlemaps extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('googlemaps', () => googlemaps);
|
src/scenes/App/scenes/MapOverview/scenes/Leaderboards/components/Leaderboard/components/LeaderboardAdminDropdown/index.js | jsza/tempus-website | import React from 'react'
import P from 'prop-types'
import IP from 'react-immutable-proptypes'
import {CLASSINDEX_TO_NAME} from 'root/constants/TFClasses'
import {withRouter} from 'react-router'
import {Route} from 'react-router-dom'
import {DropdownButton, MenuItem} from 'react-bootstrap'
import {LinkContainer} from 'react-router-bootstrap'
import './styles.styl'
function LeaderboardAdminDropdown({ zoneInfo, playerClass, location, match }) {
const addRunURL = `${match.url}/addrun/${CLASSINDEX_TO_NAME[playerClass].toLowerCase()}`
return (
<div className="MapOverview-LeaderboardContainer-Leaderboard-LeaderboardAdminDropdown">
<DropdownButton
id="LeaderboardAdminDropdown"
pullRight
title={<span className="icon-container"><i className="fas fa-user-secret" /></span>}
bsStyle="default"
noCaret className="btn-dark">
<LinkContainer to={addRunURL}>
<MenuItem>
<i className="fas fa-plus fa-large" /> Add run
</MenuItem>
</LinkContainer>
</DropdownButton>
</div>
)
}
LeaderboardAdminDropdown.propTypes = {
zoneInfo: IP.map,
playerClass: P.number
}
export default withRouter(LeaderboardAdminDropdown)
|
src/Main/PlayerBreakdown.js | enragednuke/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import SPECS from 'common/SPECS';
class PlayerBreakdown extends React.Component {
static propTypes = {
report: PropTypes.object.isRequired,
playersById: PropTypes.object.isRequired,
};
calculatePlayerBreakdown(stats, playersById) {
const statsByTargetId = stats.statsByTargetId;
const friendlyStats = [];
Object.keys(statsByTargetId)
.forEach((targetId) => {
const playerStats = statsByTargetId[targetId];
const playerInfo = playersById[targetId];
if (playerInfo) {
friendlyStats.push({
...playerInfo,
...playerStats,
masteryEffectiveness: playerStats.healingFromMastery / (playerStats.maxPotentialHealingFromMastery || 1),
healingReceivedPercentage: playerStats.healingReceived / stats.totalHealingWithMasteryAffectedAbilities,
});
}
});
return friendlyStats;
}
render() {
const { report, playersById } = this.props;
const friendlyStats = this.calculatePlayerBreakdown(report, playersById);
const highestHealingFromMastery = friendlyStats.reduce((highest, player) => Math.max(highest, player.healingFromMastery), 1);
return (
<table className="data-table">
<thead>
<tr>
<th>Name</th>
<th colSpan="2">Mastery effectiveness</th>
<th colSpan="2"><dfn data-tip="This is the amount of healing done with abilities that are affected by mastery. Things like beacons are NOT included.">Healing done</dfn></th>
</tr>
</thead>
<tbody>
{friendlyStats && friendlyStats
.sort((a, b) => b.masteryEffectiveness - a.masteryEffectiveness)
.map((player) => {
const combatants = player.combatant;
if (!combatants) {
console.error('Missing combatant:', player);
return null; // pet or something
}
const spec = SPECS[combatants.specId];
const specClassName = spec.className.replace(' ', '');
// We want the performance bar to show a full bar for whatever healing done percentage is highest to make
// it easier to see relative amounts.
const performanceBarHealingReceivedPercentage = player.healingFromMastery / highestHealingFromMastery;
const actualHealingReceivedPercentage = player.healingFromMastery / (report.totalHealingFromMastery || 1);
return (
<tr key={player.combatant.name}>
<td style={{ width: '20%' }}>
<img src={`/specs/${specClassName}-${spec.specName.replace(' ', '')}.jpg`} alt="Spec logo" />{' '}
{player.combatant.name}
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'right' }}>
{(Math.round(player.masteryEffectiveness * 10000) / 100).toFixed(2)}%
</td>
<td style={{ width: '40%' }}>
<div className="flex performance-bar-container">
<div
className={`flex-sub performance-bar ${specClassName}-bg`}
style={{ width: `${player.masteryEffectiveness * 100}%` }}
/>
</div>
</td>
<td style={{ width: 50, paddingRight: 5, textAlign: 'right' }}>
{(Math.round(actualHealingReceivedPercentage * 10000) / 100).toFixed(2)}%
</td>
<td style={{ width: '40%' }}>
<div className="flex performance-bar-container">
<div
className={`flex-sub performance-bar ${specClassName}-bg`}
style={{ width: `${performanceBarHealingReceivedPercentage * 100}%` }}
/>
</div>
</td>
</tr>
);
})}
</tbody>
</table>
);
}
}
export default PlayerBreakdown;
|
components/FeaturedProject.js | adamkrogh/adamkrogh.com | import React from 'react';
import { Link } from 'react-router';
import { prefixLink } from 'gatsby-helpers';
import styled from 'styled-components';
const StyledProject = styled(Link)`
display: block;
margin: 45px 0;
img {
margin-bottom: 20px;
}
@media (max-width: 767px) {
.hover-underline {
text-decoration: underline;
}
}
`;
const Description = styled.p`
margin-bottom: 0.7rem;
`;
const Categories = styled.div`
font-style: italic;
line-height: 1.1;
font-size: 0.9em;
color: #767676;
`;
class FeaturedProject extends React.Component {
render() {
const { page } = this.props;
const { title, description, category, image } = page.data;
return (
<StyledProject to={prefixLink(page.path)}>
<div className="row align-items-center featured">
<div className="col-md-5">
<img
src={require(`assets/${image}`)}
className="img-fluid"
alt={title}
/>
</div>
<div className="col-md-5 offset-md-1 featured-body mt-sm-0">
<header>
<h3 className="h2 hover-underline inverse">
{title}
</h3>
</header>
<Description
dangerouslySetInnerHTML={{ __html: description }}
/>
<Categories>{category}</Categories>
</div>
</div>
</StyledProject>
);
}
}
export default FeaturedProject;
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | christophemilliere/angular2 | import React from 'react';
import { render } from 'react-dom';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
render(<HelloWorld />, document.getElementById('react-root'));
|
src/index.js | galsen0/hair-dv-front | // Set up your application entry point here...
import 'babel-polyfill';
import React from 'react';
import { render } from 'react-dom';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import 'semantic-ui-css/semantic.css';
import './styles.scss';
render(
<Router routes={routes} history={browserHistory} />,
document.getElementById('app')
);
|
src/pages/AgendaScreen.js | LinDing/two-life | import React, { Component } from 'react';
import {
StyleSheet,
Image,
TouchableOpacity,
Dimensions,
Navigator,
AsyncStorage,
DeviceEventEmitter,
TouchableWithoutFeedback
} from 'react-native';
import {Agenda} from 'react-native-calendars';
import * as Animatable from 'react-native-animatable';
import { createAnimatableComponent, View, Text } from 'react-native-animatable';
import ItemPage from './ItemPage';
import DairyPage from './DairyPage';
import CommonNav from '../common/CommonNav';
import NavigationBar from "../common/NavigationBar";
import TextPingFang from "../common/TextPingFang";
import {HOST} from '../util/config';
import HttpUtils from '../util/HttpUtils';
const WIDTH = Dimensions.get("window").width;
const INNERWIDTH = WIDTH - 16;
const HEIGHT = Dimensions.get("window").height;
const URL = HOST + 'notes/show';
export default class AgendaScreen extends Component {
constructor(props) {
super(props);
this.state = {
items: {},
show: false,
user: this.props.user,
partner: this.props.partner
};
}
render() {
var nowtimestamp = new Date().getTime();
var nowtime = this.timeToString(nowtimestamp);
return (
<View style={styles.container} animation="fadeIn">
<NavigationBar
title={"日记"}
leftButton={
<Image source={require('../../res/images/update_white.png')} />
}
rightButton={
<TouchableOpacity
onPress={()=>{
this.state.items = {};
this.loadData(this.state.user.uid, this.state.user.user_other_id);
}}>
<Image source={require('../../res/images/update_icon.png')}/>
</TouchableOpacity>
}
/>
<Agenda
items={this.state.items}
loadItemsForMonth={this.loadItems.bind(this)}
selected={nowtime}
renderItem={this.renderItem.bind(this)}
renderEmptyDate={this.renderEmptyDate.bind(this)}
rowHasChanged={this.rowHasChanged.bind(this)}
theme={{
backgroundColor: "rgb(242,246,250)"
}}
//renderDay={(day, item) => (<Text>{day ? day.day: 'item'}</Text>)}
/>
</View>
);
}
componentWillMount() {
this.loadData(this.state.user.uid, this.state.user.user_other_id);
this.subscription = DeviceEventEmitter.addListener('homepageDidChange',() => {
console.log('通知');
this.state.items = {};
this.loadData(this.state.user.uid, this.state.user.user_other_id);
this.setState({
show: !this.state.show
})
})
}
componentWillUnmount() {
this.subscription.remove();
}
loadData(uid, user_id) {
for (let i = -365; i < 365; i++) {
const time = 1496707200000 + i * 24 * 60 * 60 * 1000;
const strTime = this.timeToString(time);
if (!this.state.items[strTime]) {
this.state.items[strTime] = []
}
}
HttpUtils.post(URL, {
uid: uid,
token: this.state.user.token,
timestamp: this.state.user.timestamp,
user_id: user_id,
sex: this.state.user.user_sex
}).then((res)=>{
console.log(res);
res.data.map((note)=>{
console.log(note);
var note_time = note.note_date;
var note_date = this.timeToString(note_time);
console.log(note_time);
console.log(note_date);
if (!this.state.items[note_date]) {
this.state.items[note_date] = []
this.state.items[note_date].push({
title: note.note_title,
content: note.note_content,
hight: 70,
male: note.male,
note_id: note.note_id,
note_time: note.note_date,
me: note.me,
location: note.note_location,
images: note.note_images
})
} else {
this.state.items[note_date].push({
title: note.note_title,
content: note.note_content,
hight: 70,
male: note.male,
note_id: note.note_id,
note_time: note.note_date,
me: note.me,
location: note.note_location,
images: note.note_images
})
}
})
console.log(this.state.items);
const newItems = {};
Object.keys(this.state.items).forEach(key => {newItems[key] = this.state.items[key];});
this.setState({
items: newItems
});
}).catch((error)=>{
console.log(error);
});
}
loadItems(day) {
setTimeout(() => {
// for (let i = 0; i < 365; i++) {
// const time = day.timestamp + i * 24 * 60 * 60 * 1000;
// const strTime = this.timeToString(time);
// console.log('time:' + time);
// if (!this.state.items[strTime]) {
// this.state.items[strTime] = [];
// for (let j = 0; j < 1; j++) {
// this.state.items[strTime].push({
// title: 'Item for ' + strTime,
// content: 'content',
// height: 70
// });
// }
// }
// }
// console.log(this.state.items);
// const newItems = {};
// Object.keys(this.state.items).forEach(key => {newItems[key] = this.state.items[key];});
// this.setState({
// items: newItems
// });
}, 1000);
console.log(`Load Items for ${day.year}-${day.month}`);
}
onJump(page, params) {
this.props.navigator.push({
component: page,
params: params
})
}
renderItem(item) {
return (
<TouchableOpacity
onPress={()=>{
this.onJump(DairyPage, {
note_id: item.note_id,
note_time: item.note_time,
me: item.me,
title: item.title,
content: item.content,
user: this.state.user,
partner: this.state.partner,
note_images: item.images,
note_location: item.location
});
}}>
<View
animation="bounceInRight"
delay={100}
style={[item.male=='male'?styles.item_male:styles.item_female, {height: item.height}]}>
<TextPingFang style={item.male=='male'?styles.font_male_title:styles.font_female_title}>
{item.title}
</TextPingFang>
<TextPingFang style={item.male=='male'?styles.font_male:styles.font_female}>
{item.content}
</TextPingFang>
</View>
</TouchableOpacity>
);
}
renderEmptyDate() {
return (
<View style={styles.emptyDate}><TextPingFang>今天没有写日记哦~</TextPingFang></View>
);
}
rowHasChanged(r1, r2) {
// return r1.name !== r2.name;
}
timeToString(time) {
const date = new Date(time);
return date.toISOString().split('T')[0];
}
}
const styles = StyleSheet.create({
container:{
height:HEIGHT,
backgroundColor:"rgb(242,246,250)"
},
item_male: {
backgroundColor: '#45b0f9',
flex: 1,
borderRadius: 5,
padding: 10,
marginRight: 10,
marginTop: 5
},
item_female: {
backgroundColor: 'pink',
flex: 1,
borderRadius: 5,
padding: 10,
marginRight: 10,
marginTop: 5
},
font_male: {
color: 'white',
height: 20
},
font_female: {
color: 'white',
height: 20
},
font_male_title: {
color: 'white',
fontSize: 18,
fontWeight: 'bold',
},
font_female_title: {
color: 'white',
fontSize: 18,
fontWeight: 'bold',
},
emptyDate: {
height: 15,
flex:1,
paddingTop: 30
}
});
|
src/components/withViewport.js | DarkLicornor/personalWebsite | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 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, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = { width: 1366, height: 768 }; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = { width: window.innerWidth, height: window.innerHeight };
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? { width: window.innerWidth, height: window.innerHeight } : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport} />;
}
handleResize(value) {
this.setState({ viewport: value }); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
fujion-react-parent/fujion-react-example/src/main/webjar/pomodoro.es6.js | fujion/fujion-framework |
import React, { Component } from 'react';
class ImageComponent extends Component {
render() {
return React.createElement('img', {
src : 'webjars/fujion-react-example/assets/img/pomodoro.png',
alt : 'Pomodoro'
});
}
}
class CounterComponent extends Component {
formatTime() {
return format(this.props.minutes) + ':' + format(this.props.seconds);
function format(value) {
return (value + 100).toString().substring(1);
}
}
render() {
return React.createElement('h1', {}, this.formatTime());
}
}
class ButtonComponent extends Component {
render() {
return React.createElement('button', {
className : 'btn btn-danger',
onClick : this.props.onClick
}, this.props.buttonLabel);
}
}
// Return the class for the top level component.
class PomodoroComponent extends Component {
constructor() {
super();
this.state = this.getBaselineState();
}
getBaselineState() {
return {
isPaused : true,
minutes : 24,
seconds : 59,
buttonLabel : 'Start'
}
}
componentDidMount() {
this.timer = setInterval(() => this.tick(), 1000);
}
componentWillUnmount() {
clearInterval(this.timer);
delete this.timer;
}
resetPomodoro() {
this.setState(this.getBaselineState());
}
tick() {
if (!this.state.isPaused) {
const newState = {};
newState.buttonLabel = 'Pause';
newState.seconds = this.state.seconds - 1;
if (newState.seconds < 0) {
newState.seconds = 59;
newState.minutes = this.state.minutes - 1;
if (newState.minutes < 0) {
return this.resetPomodoro();
}
}
this.setState(newState);
}
}
togglePause() {
const newState = {};
newState.isPaused = !this.state.isPaused;
if (this.state.minutes < 24 || this.state.seconds < 59) {
newState.buttonLabel = newState.isPaused ? 'Resume' : 'Pause';
}
this.setState(newState);
}
render() {
return React.createElement('div', {
className : 'text-center'
}, [
React.createElement(ImageComponent, {
key : 'image'
}),
React.createElement(CounterComponent, {
key : 'counter',
minutes : this.state.minutes,
seconds : this.state.seconds
}),
React.createElement(ButtonComponent, {
key : 'button',
buttonLabel : this.state.buttonLabel,
onClick : this.togglePause.bind(this)
})
]);
}
}
// Must export component to be instantiated as ReactComponent
export { PomodoroComponent as ReactComponent };
|
src/pages/services.js | nvasquez97/CataVasken | import React from 'react';
class Services extends React.Component {
render(){
return(
<div>
<div className="panelH container">
<img src="/imgs/GirlDuringToilette.jpg" style={{width:'100%'}} className="img-responsive" title="Conservation" alt="Holmes Panel Conservation"/>
<p className="minnesota">
Late 18th century copy of Titian's <em>Portrait d'une Femme à sa Toilette</em>, ca. 1515, by an unknown French artist
</p>
</div>
<div className="container">
<div className="col-md-6">
<p className="descHome colum">
<strong>ArtisAegis, LLC</strong> provides the following services: <br /><br />
</p>
<ul>
<li>
<p className="descHome">
Examination and treatment of paintings and frames
</p>
</li>
<li>
<p className="descHome">
Condition assessment of art objects for loan or purchase
</p>
</li>
<li>
<p className="descHome">
Collection surveys
</p>
</li>
<li>
<p className="descHome">
Lectures and teaching
</p>
</li>
<li>
<p className="descHome">
Storage and exhibition recommendations
</p>
</li>
<li>
<p className="descHome">
Disaster remediation
</p>
</li>
</ul>
</div>
<div className="col-md-6">
<p className="descHome">
ArtisAegis, LLC emphasizes preventive care in order to minimize the need for future restoration treatments for your work of art. All treatments reflect current conservation practice, employ minimally invasive treatment methods as a standard of care, and seek to preserve the structural, aesthetic, and historical integrity of works of art.
<br /><br />
All works are evaluated on an individual basis; treatment decisions cannot be made without first examining a work of art.
</p>
</div>
</div>
<div className="container panelH">
<div className="col-md-2 col-sm-0">
</div>
<div className="col-md-8 col-sm-12">
<p className="descHome centerText">
<u>Please note</u>: The inherent market worth of a given artwork has no impact on the cost of treatment. All works of art are treated as equals and receive the same attention to detail regardless of their monetary value.
</p>
</div>
<div>
</div>
</div>
</div>
);
}
}
export default Services; |
examples/with-i18next/components/Post.js | giacomorebonato/next.js | import React from 'react'
import { translate } from 'react-i18next'
class Post extends React.Component {
constructor (props) {
super(props)
this.t = props.t
}
render () {
return (
<div>
{this.t('namespace1:greatMorning')}
</div>
)
}
}
export default translate(['namespace1'])(Post)
|
src/components/SSORedirect.js | folio-org/stripes-core | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withRouter, Redirect } from 'react-router';
import queryString from 'query-string';
class SSORedirect extends Component {
getParams() {
const search = this.props.location.search;
if (!search) return undefined;
return queryString.parse(search) || {};
}
getUrl() {
const params = this.getParams();
return params?.fwd ?? '';
}
render() {
const forwardUrl = this.getUrl();
return (
<Redirect to={forwardUrl} />
);
}
}
SSORedirect.propTypes = {
location: PropTypes.shape({
search: PropTypes.string,
}).isRequired,
};
export default withRouter(SSORedirect);
|
public/scripts/views/Banner.js | shantanuraj/dash | import React from 'react';
class Banner extends React.Component {
render() {
return (
<div style={styles.banner}>
<p>Welcome to <img src="/images/dash.png" width={40} height={40}/></p>
</div>
);
}
}
var styles = {
banner: {
display: 'flex',
backgroundColor: '#065150',
color: 'white',
textAlign: 'center',
height: '88%',
},
};
export default Banner; |
containers/ResultsScreen.js | fridl8/cold-bacon-client | import React, { Component } from 'react';
import { Text, Image, View, FlatList } from 'react-native';
import styles from './styles/ResultsScreenStyle';
import { StackNagivator } from 'react-navigation';
import GeneralButton from '../components/GeneralButton';
import buttonStyles from '../components/styles/ButtonStyle';
import LaunchScreen from './LaunchScreen';
export default class ResultsScreen extends Component {
constructor(props) {
super(props);
this.state = {
isLoading: true,
}
}
// componentDidMount() {
// return fetch(serverBaseUrl+'/games/'+this.props.navigation.state.params.game_id+'/paths.json')
// method: 'post',
// .then((response) => response.json())
// .then((responseJson) => {
// this.setState({
// isLoading: false,
// pathsObject: responseJson,
// })
// console.log(this.state.pathsObject);
// })
// .catch((error) => {
// console.error(error);
// })
// }
componentDidMount() {
return fetch(serverBaseUrl+'/games/'+this.props.navigation.state.params.game_id+'/paths', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
traceable_type: this.props.navigation.state.params.traceable_type,
traceable_id: this.props.navigation.state.params.traceable_id,
}),
})
.then((response) => response.json())
.then((responseJson) => {
this.setState({
isLoading: false,
pathsObject: responseJson,
baconNumber: ( responseJson.paths_chosen.length - 1 ) / 2,
})
console.log(this.state.pathsObject);
})
.catch((error) => {
console.error(error)
})
}
renderItem({ item }) {
return (
<Text style={styles.resultText}>{item.name}</Text>
);
}
renderRestartButton() {
const { navigate } = this.props.navigation;
return (
<View style={styles.buttonView}>
<GeneralButton text='Main Menu' textStyle={ buttonStyles.generalButtonText } touchStyle={ buttonStyles.mainMenu } onPress={ () => navigate('LaunchScreen') } />
</View>
);
}
_keyExtractor = (item, index) => item.id + Math.floor(Math.random() * 1000000000);
render() {
const { navigate } = this.props.navigation;
if (this.state.isLoading) {
return (
<View>
<Text>Loading...</Text>
</View>
)
}
return (
<View>
<View style={styles.baconNumberBox}>
<Text style={styles.baconNumberText}>{ this.state.baconNumber + String.fromCharCode(176) + ' ' }</Text>
</View>
<View style={styles.buttonView}>
<GeneralButton text='Main Menu' textStyle={ buttonStyles.generalButtonText } touchStyle={ buttonStyles.mainMenu } onPress={ () => navigate('LaunchScreen') } />
</View>
<View style={styles.endingPaths}>
<View>
<FlatList
data={ this.state.pathsObject.paths_chosen }
renderItem={ this.renderItem }
keyExtractor={ this._keyExtractor }
/>
</View>
</View>
</View>
)
}
}
|
map/src/containers/Map/MapFooter.js | teikei/teikei | import React from 'react'
import i18n from '../../i18n'
const MapFooter = () => (
<footer className="map-footer">
<ul className="map-footer__navigation">
<li>
<a
href="http://ernte-teilen.org/"
target="_blank"
rel="noopener noreferrer"
>
ernte-teilen.org
</a>
</li>
<li>
<a
href="http://ernte-teilen.org/datenschutz/"
target="_blank"
rel="noopener noreferrer"
>
{i18n.t('nav.privacy')}
</a>
</li>
<li>
<a
href="http://ernte-teilen.org/impressum/"
target="_blank"
rel="noopener noreferrer"
>
{i18n.t('nav.imprint')}
</a>
</li>
</ul>
<ul className="map-footer__attribution">
<li>
{i18n.t('nav.map_data')}
<a
href="https://www.mapbox.com/about/maps/"
target="_blank"
rel="noopener noreferrer"
>
© MapBox
</a>
</li>
<li>
<a
href="http://www.openstreetmap.org/about/"
target="_blank"
rel="noopener noreferrer"
>
© OpenStreetMap
</a>
</li>
<li>
<strong>
<a
href="https://www.mapbox.com/map-feedback/"
target="_blank"
rel="noopener noreferrer"
>
Improve this map
</a>
</strong>
</li>
</ul>
</footer>
)
export default MapFooter
|
src/client/pages/NotFound.js | jukkah/comicstor | import React from 'react'
import Route from 'react-router-dom/Route'
const Status = ({ code, children }) => (
<Route render={({ staticContext }) => {
if (staticContext) {
staticContext.status = code
}
return children
}}/>
)
const NotFound = () => (
<Status code={404}>
<div>
<h1>Sorry, can’t find that.</h1>
</div>
</Status>
)
export default NotFound
|
src/components/Gallery.js | ZachGawlik/print-to-resist | import PropTypes from 'prop-types';
import React from 'react';
import FilterBar from './FilterBar';
import ListingTile from './ListingTile';
import '../styles/Gallery.css';
class Gallery extends React.Component {
componentDidMount() {
if (!this.props.listings.length) {
this.props.getListings();
}
}
render() {
const {
listings,
galleryFilters,
setColorFilter,
setTagFilter,
toggleActiveOnly
} = this.props;
return (
<div className="Gallery" id="gallery">
<h2>Spread the word!</h2>
<p>Select a page to post around your city</p>
<FilterBar
galleryFilters={galleryFilters}
setColorFilter={setColorFilter}
setTagFilter={setTagFilter}
toggleActiveOnly={toggleActiveOnly}
/>
<div>
{listings.map(listing =>
<div className="Gallery__tile" key={listing.listingId}>
<ListingTile
deadline={listing.deadline}
listingId={listing.listingId}
setTagFilter={setTagFilter}
tags={listing.tags}
thumbnailId={listing.thumbnailId}
title={listing.title}
/>
</div>
)}
</div>
</div>
);
}
}
Gallery.propTypes = {
galleryFilters: PropTypes.shape({
colorOption: PropTypes.string.isRequired,
activeOnly: PropTypes.bool.isRequired,
tag: PropTypes.string
}).isRequired,
getListings: PropTypes.func.isRequired,
listings: PropTypes.array.isRequired,
setColorFilter: PropTypes.func.isRequired,
setTagFilter: PropTypes.func.isRequired,
toggleActiveOnly: PropTypes.func.isRequired
};
export default Gallery;
|
examples/master-detail/app.js | meraki/react-router | import React from 'react'
import { render, findDOMNode } from 'react-dom'
import { browserHistory, Router, Route, IndexRoute, Link } from 'react-router'
import ContactStore from './ContactStore'
import './app.css'
const App = React.createClass({
getInitialState() {
return {
contacts: ContactStore.getContacts(),
loading: true
}
},
componentWillMount() {
ContactStore.init()
},
componentDidMount() {
ContactStore.addChangeListener(this.updateContacts)
},
componentWillUnmount() {
ContactStore.removeChangeListener(this.updateContacts)
},
updateContacts() {
if (!this.isMounted())
return
this.setState({
contacts: ContactStore.getContacts(),
loading: false
})
},
render() {
const contacts = this.state.contacts.map(function (contact) {
return <li key={contact.id}><Link to={`/contact/${contact.id}`}>{contact.first}</Link></li>
})
return (
<div className="App">
<div className="ContactList">
<Link to="/contact/new">New Contact</Link>
<ul>
{contacts}
</ul>
</div>
<div className="Content">
{this.props.children}
</div>
</div>
)
}
})
const Index = React.createClass({
render() {
return <h1>Address Book</h1>
}
})
const Contact = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
getStateFromStore(props) {
const { id } = props ? props.params : this.props.params
return {
contact: ContactStore.getContact(id)
}
},
getInitialState() {
return this.getStateFromStore()
},
componentDidMount() {
ContactStore.addChangeListener(this.updateContact)
},
componentWillUnmount() {
ContactStore.removeChangeListener(this.updateContact)
},
componentWillReceiveProps(nextProps) {
this.setState(this.getStateFromStore(nextProps))
},
updateContact() {
if (!this.isMounted())
return
this.setState(this.getStateFromStore())
},
destroy() {
const { id } = this.props.params
ContactStore.removeContact(id)
this.context.router.push('/')
},
render() {
const contact = this.state.contact || {}
const name = contact.first + ' ' + contact.last
const avatar = contact.avatar || 'http://placecage.com/50/50'
return (
<div className="Contact">
<img height="50" src={avatar} key={avatar} />
<h3>{name}</h3>
<button onClick={this.destroy}>Delete</button>
</div>
)
}
})
const NewContact = React.createClass({
contextTypes: {
router: React.PropTypes.object.isRequired
},
createContact(event) {
event.preventDefault()
ContactStore.addContact({
first: findDOMNode(this.refs.first).value,
last: findDOMNode(this.refs.last).value
}, (contact) => {
this.context.router.push(`/contact/${contact.id}`)
})
},
render() {
return (
<form onSubmit={this.createContact}>
<p>
<input type="text" ref="first" placeholder="First name" />
<input type="text" ref="last" placeholder="Last name" />
</p>
<p>
<button type="submit">Save</button> <Link to="/">Cancel</Link>
</p>
</form>
)
}
})
const NotFound = React.createClass({
render() {
return <h2>Not found</h2>
}
})
render((
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Index} />
<Route path="contact/new" component={NewContact} />
<Route path="contact/:id" component={Contact} />
<Route path="*" component={NotFound} />
</Route>
</Router>
), document.getElementById('example'))
|
src/components/input/toggle/index.js | KleeGroup/focus-components | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Translation from '../../../behaviours/translation';
import Material from '../../../behaviours/material';
import filterProps from '../../../utils/filter-html-attributes';
const propTypes = {
label: PropTypes.string,
onChange: PropTypes.func.isRequired,
value: PropTypes.bool.isRequired
};
const defaultProps = {
value: false
};
const displayName = 'InputToggle';
@Translation
@Material('mdlHolder')
class InputToggle extends Component {
getValue = () => {
const domElement = ReactDOM.findDOMNode(this.refs.toggle);
return domElement.checked;
};
handleOnChange = ({ target: { checked } }) => {
const { onChange } = this.props;
onChange(checked);
};
render() {
const validInputProps = filterProps(this.props);
const { label, value } = validInputProps;
validInputProps.onChange = this.handleOnChange;
validInputProps.checked = value;
const inputProps = { ...validInputProps };
return (
<label className='mdl-switch mdl-js-switch mdl-js-ripple-effect' data-focus='input-toggle' ref='mdlHolder'>
<input className='mdl-switch__input' ref='toggle' type='checkbox' {...inputProps} />
{label && <span className='mdl-switch__label'>{this.i18n(label)}</span>}
</label>
);
}
}
InputToggle.propTypes = propTypes;
InputToggle.defaultProps = defaultProps;
InputToggle.displayName = displayName;
export default InputToggle;
|
app/javascript/mastodon/components/permalink.js | rutan/mastodon | import React from 'react';
import PropTypes from 'prop-types';
export default class Permalink extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
className: PropTypes.string,
href: PropTypes.string.isRequired,
to: PropTypes.string.isRequired,
children: PropTypes.node,
onInterceptClick: PropTypes.func,
};
handleClick = e => {
if (this.props.onInterceptClick && this.props.onInterceptClick()) {
e.preventDefault();
return;
}
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(this.props.to);
}
}
render () {
const { href, children, className, onInterceptClick, ...other } = this.props;
return (
<a target='_blank' href={href} onClick={this.handleClick} {...other} className={`permalink${className ? ' ' + className : ''}`}>
{children}
</a>
);
}
}
|
packages/material/src/inputs/Checkbox.native.js | wq/wq.app | import React from 'react';
import { useField } from 'formik';
import { Checkbox as PaperCheckbox, useTheme } from 'react-native-paper';
import { Text, View } from 'react-native';
import PropTypes from 'prop-types';
export default function Checkbox({ name, label }) {
const theme = useTheme(),
[, meta, helpers] = useField(name),
{ value } = meta,
{ setValue } = helpers;
function toggleChecked() {
setValue(!value);
}
return (
<View
style={{ flexDirection: 'row', alignItems: 'center', padding: 8 }}
>
<PaperCheckbox.Android
status={value ? 'checked' : 'unchecked'}
onPress={toggleChecked}
/>
<Text
style={{ color: theme.colors.text, fontSize: 16, flex: 1 }}
onPress={toggleChecked}
>
{label}
</Text>
</View>
);
}
Checkbox.propTypes = {
name: PropTypes.string,
label: PropTypes.string
};
|
blueocean-material-icons/src/js/components/svg-icons/image/wb-incandescent.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ImageWbIncandescent = (props) => (
<SvgIcon {...props}>
<path d="M3.55 18.54l1.41 1.41 1.79-1.8-1.41-1.41-1.79 1.8zM11 22.45h2V19.5h-2v2.95zM4 10.5H1v2h3v-2zm11-4.19V1.5H9v4.81C7.21 7.35 6 9.28 6 11.5c0 3.31 2.69 6 6 6s6-2.69 6-6c0-2.22-1.21-4.15-3-5.19zm5 4.19v2h3v-2h-3zm-2.76 7.66l1.79 1.8 1.41-1.41-1.8-1.79-1.4 1.4z"/>
</SvgIcon>
);
ImageWbIncandescent.displayName = 'ImageWbIncandescent';
ImageWbIncandescent.muiName = 'SvgIcon';
export default ImageWbIncandescent;
|
actor-apps/app-web/src/app/components/activity/GroupProfileMembers.react.js | nguyenhongson03/actor-platform | import _ from 'lodash';
import React from 'react';
import ReactMixin from 'react-mixin';
import addons from 'react/addons';
import DialogActionCreators from 'actions/DialogActionCreators';
import LoginStore from 'stores/LoginStore';
import AvatarItem from 'components/common/AvatarItem.react';
const {addons: { PureRenderMixin }} = addons;
@ReactMixin.decorate(PureRenderMixin)
class GroupProfileMembers extends React.Component {
static propTypes = {
groupId: React.PropTypes.number,
members: React.PropTypes.array.isRequired
};
constructor(props) {
super(props);
}
onClick(id) {
DialogActionCreators.selectDialogPeerUser(id);
}
onKickMemberClick(groupId, userId) {
DialogActionCreators.kickMember(groupId, userId);
}
render() {
const groupId = this.props.groupId;
const members = this.props.members;
const myId = LoginStore.getMyId();
let membersList = _.map(members, (member, index) => {
let controls;
let canKick = member.canKick;
if (canKick === true && member.peerInfo.peer.id !== myId) {
controls = (
<div className="controls pull-right">
<a onClick={this.onKickMemberClick.bind(this, groupId, member.peerInfo.peer.id)}>Kick</a>
</div>
);
}
return (
<li className="group_profile__members__list__item" key={index}>
<a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}>
<AvatarItem image={member.peerInfo.avatar}
placeholder={member.peerInfo.placeholder}
title={member.peerInfo.title}/>
</a>
<a onClick={this.onClick.bind(this, member.peerInfo.peer.id)}>
{member.peerInfo.title}
</a>
{controls}
</li>
);
}, this);
return (
<ul className="group_profile__members__list">
{membersList}
</ul>
);
}
}
export default GroupProfileMembers;
|
fay-admin/src/app/bundle/components/Bundle.js | love-fay/fay-sso | /**
* Created by feichongzheng on 17/9/12.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Bundle extends Component {
static propTypes = {
load: PropTypes.any,
children: PropTypes.any,
};
state = {
// short for "module" but that's a keyword in js, so "mod"
mod: null,
};
componentWillMount () {
this.load(this.props);
}
componentWillReceiveProps (nextProps) {
if (nextProps.load !== this.props.load) {
this.load(nextProps);
}
}
load (props) {
this.setState({
mod: null,
});
props.load((mod) => {
this.setState({
// handle both es imports and cjs
mod: mod['default'] ? mod['default'] : mod,
});
});
}
render () {
return this.state.mod ? this.props.children(this.state.mod) : <div></div>;
}
}
export default Bundle;
|
app/Success/index.js | mskcc-clinbx/python-jwt-react-login-flow | import React from 'react';
import { getToken } from '../authentication';
import Modal from '../Modal';
import './Success.css';
import { sendLoginInformation } from '../Login';
class Success extends React.Component {
state = {
status: '',
authModal: false,
secondsElapsed: 0,
email: '',
password: '',
}
componentDidMount() {
this.validateTokenViaGet();
this.interval = setInterval(() => this.tick(), 1000)
}
componentWillUnmount() {
clearInterval(this.interval);
}
tick() {
this.setState((prevState) => ({
secondsElapsed: prevState.secondsElapsed + 1
}));
if(this.state.secondsElapsed % 10 == 0 && !this.props.authModal) {
this.validateTokenViaGet();
}
}
onChange = event => {
this.setState({
[event.target.id]: event.target.value,
});
}
validateTokenViaGet() {
const API_HEADERS_AND_MODE = {
headers: {
'Authorization': `Bearer ${getToken()}`,
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'cors',
};
const API_SETTINGS = {
settings: {
method: 'GET'
}
};
return fetch('http://localhost:5001/test_get_with_validation', {
...API_HEADERS_AND_MODE,
...API_SETTINGS
}).then(res => {
if (res.status >= 400) {
this.setState({
authModal: true
});
return res.json().then(err => {
throw err;
});
}
this.setState({
authModal: false,
});
return res.json();
}).then(data => {
this.setState({
status: data,
});
})
}
reAuthenticate = (email, password) => {
const { router } = this.props;
const API_HEADERS_AND_MODE = {
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
mode: 'cors',
};
const API_SETTINGS = {
settings: {
method: 'POST',
body: JSON.stringify({
username: email,
password: password
})
}
}
return fetch('http://localhost:5000/auth/login', {
...API_HEADERS_AND_MODE,
...API_SETTINGS.settings
}).then(res => {
if (res.status >= 400) {
return res.json().then(err => {
throw err;
});
}
return res.json();
}).then(data => {
localStorage.setItem('token', data.result.auth_token)
if (!!localStorage.token) {
this.setState({
authModal: false
})
router.push('/success')
}
})
}
render() {
const token = getToken();
const { status, email, password } = this.state;
return (
<div>
<div>
<h2> Your token is: </h2>
<h1>{token}</h1>
</div>
<h3>Your Status: {status}</h3>
<Modal visible={this.state.authModal}>
<div className="auth-modal-holder">
<div className="email-icon-modal" />
<input
type="text"
id="email"
placeholder="Email"
className="email"
value={this.state.email}
onChange={this.onChange}
/>
<div className="password-icon-modal" />
<input
type="password"
id="password"
placeholder="Password"
className="password"
value={this.state.password}
onChange={this.onChange}
/>
<div className="auth-modal-button-container">
<button className="auth-modal-button-go" onClick={() => this.reAuthenticate(email, password)}>Login </button>
</div>
</div>
</Modal>
</div>
)
}
}
export default Success;
|
src/app/components/team/SlackConfig/index.js | meedan/check-web | import React from 'react';
import Relay from 'react-relay/classic';
import { createFragmentContainer, graphql } from 'react-relay/compat';
import PropTypes from 'prop-types';
import { FormattedMessage, injectIntl } from 'react-intl';
import Box from '@material-ui/core/Box';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardContent from '@material-ui/core/CardContent';
import Dialog from '@material-ui/core/Dialog';
import IconButton from '@material-ui/core/IconButton';
import Switch from '@material-ui/core/Switch';
import SettingsIcon from '@material-ui/icons/Settings';
import styled from 'styled-components';
import UserUtil from '../../user/UserUtil';
import Message from '../../Message';
import SlackConfigDialog from './SlackConfigDialog';
import CheckContext from '../../../CheckContext';
import UpdateTeamMutation from '../../../relay/mutations/UpdateTeamMutation';
import globalStrings from '../../../globalStrings';
import { getErrorMessage } from '../../../helpers';
import { stringHelper } from '../../../customHelpers';
import {
title1,
} from '../../../styles/js/shared';
class SlackConfig extends React.Component {
constructor(props) {
super(props);
this.state = {
openDialog: false,
};
}
getCurrentUser() {
return new CheckContext(this).getContextStore().currentUser;
}
handleCloseDialog = () => {
this.setState({ openDialog: false });
}
handleOpenDialog = () => {
this.setState({
openDialog: true,
});
}
handleToggleSwitch = () => {
const enabled = typeof this.state.enabled !== 'undefined' && this.state.enabled !== null
? this.state.enabled
: Boolean(parseInt(this.props.team.get_slack_notifications_enabled, 10));
this.setState({ enabled: !enabled }, this.handleSubmit);
}
handleSubmit() {
const enabled = typeof this.state.enabled !== 'undefined' && this.state.enabled !== null
? this.state.enabled
: Boolean(parseInt(this.props.team.get_slack_notifications_enabled, 10));
const onFailure = (transaction) => {
const fallbackMessage = this.props.intl.formatMessage(globalStrings.unknownError, { supportEmail: stringHelper('SUPPORT_EMAIL') });
const message = getErrorMessage(transaction, fallbackMessage);
return this.setState({ message });
};
const onSuccess = () => {
this.handleCloseDialog();
};
Relay.Store.commitUpdate(
new UpdateTeamMutation({
id: this.props.team.id,
slack_notifications_enabled: enabled ? '1' : '0',
}),
{ onSuccess, onFailure },
);
}
render() {
const { team } = this.props;
const enabled = typeof this.state.enabled !== 'undefined' && this.state.enabled !== null
? this.state.enabled
: Boolean(parseInt(this.props.team.get_slack_notifications_enabled, 10));
const StyledCardHeader = styled(CardHeader)`
span {
font: ${title1} !important;
}
`;
if (UserUtil.myRole(this.getCurrentUser(), team.slug) !== 'admin') {
return null;
}
return (
<div>
<Card>
<StyledCardHeader
avatar={
<img src="/images/slack.svg" height="32" width="32" alt="Slack" />
}
title={
<span>Slack</span>
}
action={
<IconButton
className="slack-config__settings"
onClick={this.handleOpenDialog.bind(this)}
disabled={!enabled}
>
<SettingsIcon />
</IconButton>
}
/>
<Message message={this.state.message} />
<CardContent>
<Box display="flex" alignItems="center" justifyContent="space-between">
<FormattedMessage
id="slackConfig.text"
defaultMessage="Send notifications to Slack channels when items are added to specific folders"
/>
<Switch
className="slack-config__switch"
checked={enabled}
onClick={this.handleToggleSwitch}
/>
</Box>
</CardContent>
</Card>
<Dialog
open={this.state.openDialog}
onClose={this.handleCloseDialog}
maxWidth="lg"
>
<SlackConfigDialog teamSlug={this.props.team.slug} onCancel={this.handleCloseDialog} />
</Dialog>
</div>
);
}
}
SlackConfig.contextTypes = {
store: PropTypes.object,
};
SlackConfig.propTypes = {
team: PropTypes.shape({
id: PropTypes.string.isRequired,
get_slack_notifications_enabled: PropTypes.number.isRequired,
slug: PropTypes.string.isRequired,
}).isRequired,
};
export { SlackConfig };
export default createFragmentContainer(injectIntl(SlackConfig), graphql`
fragment SlackConfig_team on Team {
id
slug
get_slack_notifications_enabled
}
`);
|
webpack/components/pf3Table/components/TableSelectionHeaderCell.js | Katello/katello | import React from 'react';
import PropTypes from 'prop-types';
import { Table } from 'patternfly-react';
import { noop } from 'foremanReact/common/helpers';
const TableSelectionHeaderCell = ({
id, label, checked, onChange, ...props
}) => (
<Table.SelectionHeading aria-label={label}>
<Table.Checkbox
id={id}
label={label}
checked={checked}
onChange={onChange}
{...props}
/>
</Table.SelectionHeading>
);
TableSelectionHeaderCell.propTypes = {
id: PropTypes.string,
label: PropTypes.string,
checked: PropTypes.bool,
onChange: PropTypes.func,
};
TableSelectionHeaderCell.defaultProps = {
id: 'selectAll',
label: '',
checked: false,
onChange: noop,
};
export default TableSelectionHeaderCell;
|
app/src/pages/Deneme/deneme.js | fikrimuhal/animated-potato | import React from 'react'
export default React.createClass({
render() {
return (
<svg>
<circle cx={50} cy={50} r={10} fill="red"/>
</svg>
)
}
}) |
src/containers/DevTools/DevTools.js | fforres/coworks | import React from 'react';
import { createDevTools } from 'redux-devtools';
import LogMonitor from 'redux-devtools-log-monitor';
import DockMonitor from 'redux-devtools-dock-monitor';
export default createDevTools(
<DockMonitor toggleVisibilityKey="H"
changePositionKey="Q">
<LogMonitor />
</DockMonitor>
);
|
investninja-web-ui-admin/src/components/Widget/index.js | InvestNinja/InvestNinja-web-ui | import React, { Component } from 'react';
import { Panel } from 'react-bootstrap';
import Link from '../Link';
class StatWidget extends Component{ // eslint-disable-line
static propTypes = {
style: React.PropTypes.string,
count: React.PropTypes.string,
headerText: React.PropTypes.string,
icon: React.PropTypes.string,
footerText: React.PropTypes.string,
}
render() {
return (
<Panel
className="stat"
className={this.props.style}
header={<div className="row">
<div className="col-xs-3">
<i
className={this.props.icon}
/>
</div>
<div className="col-xs-9 text-right">
<div className="huge">
{
this.props.count
}
</div>
<div>
{
this.props.headerText
}
</div>
</div>
</div>}
footer={
<Link
to={
this.props.linkTo // eslint-disable-line
}
>
<span className="pull-left">
{
this.props.footerText
}
</span>
<span className="pull-right"><i className="fa fa-arrow-circle-right" /></span>
<div className="clearfix" />
</Link>}
/>
);
}
}
export default StatWidget;
|
src/svg-icons/notification/system-update.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationSystemUpdate = (props) => (
<SvgIcon {...props}>
<path d="M17 1.01L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14zm-1-6h-3V8h-2v5H8l4 4 4-4z"/>
</SvgIcon>
);
NotificationSystemUpdate = pure(NotificationSystemUpdate);
NotificationSystemUpdate.displayName = 'NotificationSystemUpdate';
NotificationSystemUpdate.muiName = 'SvgIcon';
export default NotificationSystemUpdate;
|
components/Deck/DeckLandingPage.js | slidewiki/slidewiki-platform | import React from 'react';
import {Card} from 'semantic-ui-react';;
import { NavLink } from 'fluxible-router';
import { Grid, Divider, Button, Header, Image, Icon, Item, Label, Menu, Segment, Container } from 'semantic-ui-react';
import PropTypes from 'prop-types';
import { connectToStores } from 'fluxible-addons-react';
import ContentStore from '../../stores/ContentStore';
import DeckPageStore from '../../stores/DeckPageStore';
import DeckViewStore from '../../stores/DeckViewStore';
import ContentLikeStore from '../../stores/ContentLikeStore';
import ContentModulesStore from '../../stores/ContentModulesStore';
import TranslationStore from '../../stores/TranslationStore';
import SimilarContentStore from '../../stores/SimilarContentStore';
import CustomDate from './util/CustomDate';
import {getLanguageDisplayName, getLanguageName, isEmpty} from '../../common';
import { flagForLocale } from '../../configs/locales';
import { Microservices } from '../../configs/microservices';
import CCBYSA from '../common/CC-BY-SA';
import ReportModal from '../Report/ReportModal';
import openReportModal from '../../actions/report/openReportModal';
import TagList from './ContentModulesPanel/TagsPanel/TagList';
import PresentationsPanel from './InfoPanel/PresentationsPanel';
import ActivityFeedPanel from './ActivityFeedPanel/ActivityFeedPanel';
import { getEducationLevel } from '../../lib/isced';
import lodash from 'lodash';
import slugify from 'slugify';
import {FormattedMessage, defineMessages} from 'react-intl';
import setDocumentTitle from '../../actions/setDocumentTitle';
class DeckLandingPage extends React.Component {
getPresentationHref() {
let selector = this.props.DeckPageStore.selector;
let presentationUrlParts = ['/presentation', selector.id, this.props.DeckPageStore.deckSlug || '_'];
if (selector.spath.search(';') !== -1) {
// if a subdeck is selected - use its selector
presentationUrlParts.push(selector.spath.substring(0, selector.spath.search(';')));
} else {
// if it is the main/root deck - use that id
presentationUrlParts.push(selector.id);
}
if (selector.stype === 'slide'){
// if it is a slide, also add ID of slide
presentationUrlParts.push(selector.sid);
}
let presLocation = presentationUrlParts.join('/');
if (this.props.TranslationStore.currentLang) {
presLocation += '?language=' + (this.props.TranslationStore.currentLang);
}
return presLocation;
}
getPlaceholder() {
return (
<Container fluid>
<Divider hidden/>
<Grid padded='vertically' divided='vertically' stackable>
<Grid.Column only="tablet computer" tablet={1} computer={2}>
</Grid.Column>
<Grid.Column mobile={16} tablet={14} computer={12}>
<Grid.Row>
<Segment>
<Grid stackable>
<Grid.Column width={4}>
<div className="ui placeholder">
<div className="rectangular image"></div>
</div>
</Grid.Column>
<Grid.Column width={12}>
<Grid.Row>
<div className="ui placeholder">
<div className="header">
<div className="long line"></div>
<div className="long line"></div>
</div>
</div>
</Grid.Row>
<Divider hidden />
<Grid stackable>
<Grid.Row columns={2}>
<Grid.Column>
<div className="ui placeholder">
<div className="line"></div>
<div className="line"></div>
<div className="line"></div>
</div>
</Grid.Column>
<Grid.Column>
<div className="ui placeholder">
<div className="line"></div>
<div className="line"></div>
</div>
</Grid.Column>
</Grid.Row>
<Divider hidden />
<Grid.Row>
<Grid.Column>
<div className="ui placeholder">
<div className="header">
<div className="line"></div>
</div>
<div className="paragraph">
<div className="line"></div>
<div className="line"></div>
</div>
</div>
</Grid.Column>
</Grid.Row>
<Divider hidden />
<Grid.Row>
<Grid.Column>
<div className="ui placeholder">
<div className="header">
<div className="line"></div>
</div>
<div className="paragraph">
<div className="line"></div>
</div>
</div>
</Grid.Column>
</Grid.Row>
</Grid>
</Grid.Column>
</Grid>
</Segment>
</Grid.Row>
<Grid.Row>
<div className="ui bottom attached tabular menu" style={{'background': '#e0e1e2'}}>
<div className="ui icon buttons huge attached">
<Button icon size="huge">
<Icon name="line graph" />
</Button>
<Button icon size="huge">
<Icon name="warning circle" />
</Button>
</div>
<div className="right inverted menu">
<div className="ui icon buttons huge attached">
<Button icon size="huge">
<Icon name="open folder" />
</Button>
<Button icon size="huge">
<Icon name="play circle" />
</Button>
<Button icon size="huge">
<Icon name="record" />
</Button>
</div>
</div>
</div>
</Grid.Row>
<Divider hidden />
<Grid divided='vertically' stackable>
<Grid.Column only="tablet computer" width={12}>
<Segment attached='top' >
<div className="ui placeholder">
<div className="header">
<div className="line"></div>
</div>
<div className="paragraph">
<div className="long line"></div>
</div>
</div>
</Segment>
<Segment attached>
<div className="ui placeholder">
<div className="header">
<div className="line"></div>
</div>
<div className="paragraph">
<div className="long line"></div>
</div>
</div>
</Segment>
<Segment attached='bottom'>
<div className="ui placeholder">
<div className="header">
<div className="line"></div>
</div>
<div className="paragraph">
<div className="long line"></div>
</div>
</div>
</Segment>
</Grid.Column>
<Grid.Column only="tablet computer" width={4}>
<Segment>
<div className="ui fluid placeholder">
</div>
</Segment>
<Segment attached='bottom'>
<a href='https://creativecommons.org/licenses/by-sa/4.0/' target='_blank' role="img" aria-label="Creative Commons License logo">
<CCBYSA size='small' />
</a>
<FormattedMessage id='deck.landingpage.license_text' defaultMessage='This work is licensed under'/> <a href='https://creativecommons.org/licenses/by-sa/4.0/' target='_blank'>Creative Commons Attribution-ShareAlike 4.0 International License</a>
</Segment>
</Grid.Column>
</Grid>
</Grid.Column>
<Grid.Column only="tablet computer" tablet={1} computer={2}>
</Grid.Column>
</Grid>
</Container>
);
}
componentDidMount() {
this.setTitle();
}
componentDidUpdate(prevProps) {
if (this.props.DeckViewStore.deckData.title !== prevProps.DeckViewStore.deckData.title) {
this.setTitle();
}
}
setTitle = () => {
this.context.executeAction(setDocumentTitle, {
title: this.context.intl.formatMessage({
id: 'DeckLandingPage.title',
defaultMessage: 'Presentation information'
}) + ' | ' + this.props.DeckViewStore.deckData.title
});
}
render() {
let deckData = this.props.DeckViewStore.deckData;
if (lodash.isEmpty(deckData)) return this.getPlaceholder();
let firstSlide = (this.props.DeckViewStore.slidesData && this.props.DeckViewStore.slidesData.children && this.props.DeckViewStore.slidesData.children[0]);
const totalSlides = lodash.get(this.props.DeckViewStore.slidesData, 'children.length', undefined);
let deckThumbURL = firstSlide && `${Microservices.file.uri}/thumbnail/slide/${firstSlide.id}`;
if (deckThumbURL && firstSlide.theme) {
deckThumbURL += '/' + firstSlide.theme;
}
//let deckThumbAlt = firstSlide && (firstSlide.title ? firstSlide.title + ' | ' + firstSlide.id : firstSlide.id);
let deckThumbAlt = `Example of presentation: ${deckData.title}`;
let deckSlug = this.props.DeckPageStore.deckSlug || '_';
let selector = this.props.DeckPageStore.selector;
let openDeckUrl = ['', 'deck', selector.id , deckSlug, 'deck', selector.id].join('/');
if (this.props.TranslationStore.currentLang) {
openDeckUrl += '?language=' + (this.props.TranslationStore.currentLang);
}
let presentationUrl = this.getPresentationHref();
let deckStatsUrl = ['', 'deck', selector.id , deckSlug, 'stats'].join('/');
let deckTags = deckData.tags || [];
let deckTopics = deckData.topics || [];
let deckVariantSlugs = this.props.TranslationStore.nodeVariants.reduce((result, variant) => {
result[variant.language] = variant.title ? slugify(variant.title).toLowerCase() : deckSlug;
return result;
}, {});
let deckLanguages = [this.props.TranslationStore.treeLanguage, ...this.props.TranslationStore.treeTranslations];
let owner = this.props.DeckViewStore.ownerData;
let creator = this.props.DeckViewStore.creatorData;
let originInfo = null;
let originCreator = this.props.DeckViewStore.originCreatorData;
if (deckData.origin) {
originInfo = (
<div className="meta" tabIndex="0">
<strong>Origin: </strong>
<NavLink href={['/deck', deckData.origin.id + '-' + deckData.origin.revision, deckData.origin.slug].join('/')}>{deckData.origin.title}</NavLink>
{originCreator ? ' by ' : ''}
{originCreator && <a href={'/user/' + originCreator.username}>{originCreator.displayName || originCreator.username}</a>}
{/* TODO check if this URL is working with languages! */}
</div>
);
}
const ColPadding = {
paddingLeft: '0px'
};
let interestedInDecks = 'No decks to show';
if (this.props.SimilarContentStore.contents && this.props.SimilarContentStore.contents.length >= 1) {
interestedInDecks = this.props.SimilarContentStore.contents.map((deck, i) => {
return <Grid.Column key={i} width={5}>
<div className="ui card">
<NavLink href={`/deck/${deck.deckId}`}>
<div className="ui image fluid bordered">
<img src={`${Microservices.file.uri}/thumbnail/slide/${deck.firstSlideId}`} aria-hidden="true" tabIndex="-1" alt=' ' />
</div>
<h4 className="header">
{deck.title}
</h4>
</NavLink>
</div>
</Grid.Column>;
});
interestedInDecks = <Grid stackable> {interestedInDecks} </Grid>;
}
const messages = defineMessages({
tooltipStats: {
id: 'deck.landing.tooltip.stats',
defaultMessage: 'Deck Stats'
},
tooltipOpen: {
id: 'deck.landing.tooltip.open',
defaultMessage: 'Open Deck'
},
tooltipSlideshow: {
id: 'deck.landing.tooltip.slideshow',
defaultMessage: 'Open Slideshow'
},
});
return (
<div>
<Container fluid>
<Grid padded='vertically' divided='vertically' stackable>
<Grid.Column only="tablet computer" tablet={1} computer={2}>
</Grid.Column>
<Grid.Column mobile={16} tablet={14} computer={12}>
<Grid.Row>
<Segment attached="top">
<Grid stackable>
<Grid.Column width={4}>
<NavLink className="image" aria-hidden tabIndex='-1' href={openDeckUrl}>
<Image src={deckThumbURL} alt={deckThumbAlt}
size='large' bordered spaced />
</NavLink>
</Grid.Column>
<Grid.Column width={12}>
<div className="row">
<Header as="h1" id="main">
<NavLink href={openDeckUrl}>{deckData.title}</NavLink>
<span className="sr-only"><FormattedMessage id='deck.landing.deckStatus.text' defaultMessage='Deck status'/>: </span>
{(!deckData.hidden) ? <Label as="span" color='green'><FormattedMessage id='deck.landing.deckStatus.published' defaultMessage='Published'/></Label> : <Label as="span" color='pink'>Unlisted</Label>}</Header>
</div>
<Divider hidden />
<div className="ui stackable grid container">
<div className="two column row">
<div className="column" style={ColPadding}>
<div className="item">
<div className="meta"><strong><FormattedMessage id='deck.landing.creator' defaultMessage='Creator'/>:</strong> <NavLink href={'/user/' + creator.username}>{creator.displayName || creator.username}</NavLink></div>
{originInfo}
<div className="meta"><strong><FormattedMessage id='deck.landing.lastModified' defaultMessage='Last Modified'/>: </strong>{CustomDate.format(deckData.lastUpdate, 'Do MMMM YYYY')}</div>
</div>
</div>
<div className="column">
<h2 className="sr-only"><FormattedMessage id='deck.landing.deckMetadata' defaultMessage='Deck metadata'/></h2>
<div className="row">
<div className="ui medium labels" >
<div className="ui label" >
<i className="comments icon" aria-label="Default language"></i>{getLanguageDisplayName(deckData.language)}
</div>
<div className="ui label" >
<i className="block layout icon" aria-label="Number of slides"></i>{totalSlides}
</div>
{ deckData.educationLevel &&
<div className="ui label" >
<i className="university icon" aria-label="Education Level"></i>{getEducationLevel(deckData.educationLevel)}
</div>
}
</div>
</div>
<div className="row">
<div className="ui medium labels">
<div className="ui label" >
<i className="fork icon" aria-label="Number of forks"></i>{deckData.forkCount}</div>
<div className="ui label" >
<i className="thumbs up icon" aria-label="Number of likes"></i>{this.props.ContentLikeStore.usersWhoLikedDeck.length}</div>
<div className="ui label" >
<i className="share alternate icon" aria-label="Number of shares"></i>{deckData.shareCount}</div>
<div className="ui label" >
<i className="download icon" aria-label="Number of downloads"></i>{deckData.downloadCount}</div>
</div>
</div>
</div>
</div>
<div className="row" >
<div className="item">
<div className="meta"><strong><FormattedMessage id='deck.landing.description' defaultMessage='Description'/>:</strong>
<div className="description" >{deckData.description}</div>
</div>
</div>
</div>
<div className="row" >
{ deckTopics.length > 0 &&
<div className="item">
<div className="meta"><strong><FormattedMessage id='deck.landing.subject' defaultMessage='Subject'/>: </strong></div>
<div className="description">{ deckTopics.map((t, i) =>
<span key={i}>
{ !!i && ',\xa0' }
<a target="_blank" href={`/deckfamily/${t.tagName}`}>{t.defaultName || t.tagName}</a>
</span>
) }
</div>
</div>
}
</div>
</div>
</Grid.Column>
</Grid>
</Segment>
<div className="ui bottom attached menu" style={{'background': '#e0e1e2'}} id="navigation">
<div className="ui icon buttons huge attached">
<NavLink href={deckStatsUrl} tabIndex={-1} >
<Button icon size="huge" aria-label="Deck Stats" data-tooltip={this.context.intl.formatMessage(messages.tooltipStats)}>
<Icon name="line graph" />
</Button>
</NavLink>
</div>
<ReportModal/>
<div className="right inverted menu">
<div className="ui icon buttons huge attached">
<NavLink href={openDeckUrl} tabIndex={-1} >
<Button icon size="huge" aria-label="Open Deck" data-tooltip={this.context.intl.formatMessage(messages.tooltipOpen)}>
<Icon name="open folder" />
</Button>
</NavLink>
<a target="_blank" href={presentationUrl} tabIndex={-1} >
<Button icon size="huge" aria-label="Open slideshow in new tab" data-speech-id="openSlideshow" data-tooltip={this.context.intl.formatMessage(messages.tooltipSlideshow)}>
<Icon name="play circle" />
</Button>
</a>
<PresentationsPanel deckPage={true} />
</div>
</div>
</div>
</Grid.Row>
<Divider hidden />
<Grid divided='vertically' stackable>
<Grid.Column only="tablet computer" width={12}>
<Segment attached='top' >
<Header size="small" as="h3"><FormattedMessage id='deck.landing.available_languages.text' defaultMessage='Available in the following languages'/>:</Header>
{ deckLanguages.map((lang, i) =>
<span key={i}>
{!!i && ',\xa0'}
<NavLink href={['', 'deck', selector.id , deckVariantSlugs[lang] || '_'].join('/') + '?language=' + lang}>
<i className={ (flagForLocale(lang) || 'icon') + ' flag' }/>
{ getLanguageDisplayName(lang) }
</NavLink>
</span>
) }
</Segment>
<Segment attached>
<Header size="small" as="h3"><FormattedMessage id='deck.landing.tags.text' defaultMessage='Tags'/>:</Header>
{(deckTags.length === 0) ? <div><FormattedMessage id='deck.landing.tags.not_available' defaultMessage='There are no tags assigned to this deck.'/></div> : <TagList items={deckTags} editable={false}/>}
</Segment>
<Segment attached='bottom'>
<Header size="small" as="h3"><FormattedMessage id='deck.other_interesting.text' defaultMessage='You may also be interested in'/>:</Header>
{interestedInDecks}
</Segment>
</Grid.Column>
<Grid.Column only="tablet computer" width={4}>
<Segment>
<ActivityFeedPanel /></Segment>
<Segment attached='bottom'>
<a href='https://creativecommons.org/licenses/by-sa/4.0/' target='_blank' role="img" aria-label="Creative Commons License logo">
<CCBYSA size='small' />
</a>
<FormattedMessage id='deck.landing.landingpage.license_text' defaultMessage='This work is licensed under'/> <a href='https://creativecommons.org/licenses/by-sa/4.0/' target='_blank'>Creative Commons Attribution-ShareAlike 4.0 International License</a>
</Segment>
</Grid.Column>
</Grid>
</Grid.Column>
<Grid.Column only="tablet computer" tablet={1} computer={2}>
</Grid.Column>
</Grid>
</Container>
</div>
);
}
}
DeckLandingPage.contextTypes = {
intl: PropTypes.object.isRequired,
executeAction: PropTypes.func.isRequired
};
DeckLandingPage = connectToStores(DeckLandingPage, [
ContentStore,
ContentLikeStore,
DeckPageStore,
DeckViewStore,
TranslationStore,
ContentModulesStore,
SimilarContentStore,
], (context, props) => {
return {
ContentStore: context.getStore(ContentStore).getState(),
ContentLikeStore: context.getStore(ContentLikeStore).getState(),
DeckPageStore: context.getStore(DeckPageStore).getState(),
DeckViewStore: context.getStore(DeckViewStore).getState(),
TranslationStore: context.getStore(TranslationStore).getState(),
ContentModulesStore: context.getStore(ContentModulesStore).getState(),
SimilarContentStore: context.getStore(SimilarContentStore).getState(),
};
});
export default DeckLandingPage;
|
src/pages/Login/Login.js | Minishlink/DailyScrum | // @flow
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { StyleSheet, View, Button, Linking, Platform, Dimensions } from 'react-native';
import { isEmpty } from 'lodash';
import SplashScreen from 'react-native-splash-screen';
import SafariView from 'react-native-safari-view';
import LottieAnimation from 'lottie-react-native';
import { Page, Text } from '../../components';
import appStyle from '../../appStyle';
import { Trello, Analytics } from '../../services';
import { login } from '../../modules/auth';
import { isLoggedInSelector } from '../../modules/auth/reducer';
import Navigation from '../../services/Navigation';
import { IOSDownload, AndroidDownload } from '../../components/AppDownload';
class Login extends Component<Props> {
componentDidMount() {
// check if tokens exist in store
if (this.props.isLoggedIn) {
Navigation.redirectAfterLogin();
return;
}
SplashScreen.hide();
// if not we login Scrumble if we have the trello Token
const trelloToken = this.props.navigation.state.params && this.props.navigation.state.params.token;
if (!trelloToken) return;
this.login(trelloToken);
}
componentWillReceiveProps(nextProps: Props) {
const currentTrelloToken = this.props.navigation.state.params && this.props.navigation.state.params.token;
const nextTrelloToken = nextProps.navigation.state.params && nextProps.navigation.state.params.token;
if (!currentTrelloToken && nextTrelloToken) {
this.login(nextTrelloToken);
}
}
login = (token: string) => {
Platform.OS === 'ios' && SafariView.dismiss();
Analytics.logEvent('login_trello_ok'); // are users unwilling to authorize Trello access?
this.props.login(token); // let's log the user in Scrumble
};
triggerLogin = () => {
Analytics.logEvent('login_trello_trigger'); // are users unwilling to login with Trello?
const loginUrl = Trello.getLoginURL();
if (Platform.OS === 'ios') {
SafariView.isAvailable()
.then(() =>
SafariView.show({
url: loginUrl,
})
)
.catch(() => Linking.openURL(loginUrl));
} else if (Platform.OS === 'web') {
window.location.assign(loginUrl);
} else {
Linking.openURL(loginUrl);
}
};
renderAppDownloads = () => (
<Text style={styles.appDownloads}>
or download the app for <IOSDownload textStyle={styles.appDownload} /> or{' '}
<AndroidDownload textStyle={styles.appDownload} />
</Text>
);
render() {
if (this.props.isLoggedIn || !isEmpty(this.props.navigation.state.params)) {
return <Page isLoading />;
}
return (
<Page>
<View style={styles.container}>
<LottieAnimation
source={require('../../../assets/lottie/sun_happy.json')}
style={styles.logo}
loop
autoPlay
/>
<Text style={styles.title}>DailyScrum</Text>
<Text style={styles.description}>Your mobile daily dose of Scrum</Text>
<Button onPress={this.triggerLogin} title="Login with Trello" />
{Platform.OS === 'web' && this.renderAppDownloads()}
</View>
</Page>
);
}
}
type Props = {
navigation: any,
login: Function,
isLoggedIn: boolean,
};
const dimensions = Dimensions.get('window');
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
logo: {
width: dimensions.width >= dimensions.height ? dimensions.width * 0.3 : undefined,
height: dimensions.height > dimensions.width ? dimensions.height * 0.3 : undefined,
},
title: {
marginTop: 10,
fontSize: appStyle.font.size.big,
},
description: {
marginBottom: 40,
},
appDownloads: {
marginTop: 10,
},
appDownload: {
textDecorationLine: 'underline',
},
});
const mapStateToProps = state => ({
isLoggedIn: isLoggedInSelector(state),
});
const mapDispatchToProps = {
login,
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Login);
|
src/features/ViewMenuPopups/Shape.js | erhathaway/cellular_automata | import React from 'react';
import styled from 'react-emotion';
import { inject, observer } from 'mobx-react';
import { Container, Title, DimensionLineItem } from './Views';
const DimensionContainer = styled('div')`
display: flex;
width: 80%;
justify-content: center;
margin-bottom: 10px;
`;
export default inject('automataStore')(observer((props) => {
const { automataStore: { populationShape } } = props;
const numberOfDimensions = populationShape.keys.length;
return (
<Container {...props} height={`${110 + numberOfDimensions * 40}px`} width="300px">
<Title>
{'Population Size Per Dimension'}
</Title>
{ populationShape.keys.map(name => (
<DimensionContainer key={`poup-population-shape-container-${name}`}>
<DimensionLineItem dimensionName={name} />
</DimensionContainer>
))}
</Container>
);
}));
|
docs/src/app/components/pages/components/Snackbar/Page.js | IsenrichO/mui-with-arrows | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import SnackbarReadmeText from './README';
import SnackbarExampleSimple from './ExampleSimple';
import SnackbarExampleSimpleCode from '!raw!./ExampleSimple';
import SnackbarExampleAction from './ExampleAction';
import SnackbarExampleActionCode from '!raw!./ExampleAction';
import SnackbarExampleTwice from './ExampleTwice';
import SnackbarExampleTwiceCode from '!raw!./ExampleTwice';
import SnackbarCode from '!raw!material-ui/Snackbar/Snackbar';
const descriptions = {
simple: '`Snackbar` is a controlled component, and is displayed when `open` is `true`. Click away from the ' +
'Snackbar to close it, or wait for `autoHideDuration` to expire.',
action: 'A single `action` can be added to the Snackbar, and triggers `onActionTouchTap`. Edit the textfield to ' +
'change `autoHideDuration`',
consecutive: 'Changing `message` causes the Snackbar to animate - it isn\'t necessary to close and reopen the ' +
'Snackbar with the open prop.',
};
const SnackbarPage = () => {
return (
<div>
<Title render={(previousTitle) => `Snackbar - ${previousTitle}`} />
<MarkdownElement text={SnackbarReadmeText} />
<CodeExample
title="Simple example"
description={descriptions.simple}
code={SnackbarExampleSimpleCode}
>
<SnackbarExampleSimple />
</CodeExample>
<CodeExample
title="Example action"
description={descriptions.action}
code={SnackbarExampleActionCode}
>
<SnackbarExampleAction />
</CodeExample>
<CodeExample
title="Consecutive Snackbars"
description={descriptions.consecutive}
code={SnackbarExampleTwiceCode}
>
<SnackbarExampleTwice />
</CodeExample>
<PropTypeDescription code={SnackbarCode} />
</div>
);
};
export default SnackbarPage;
|
src/encoded/static/components/viz/AreaChart.js | hms-dbmi/fourfront | 'use strict';
import React from 'react';
import PropTypes from 'prop-types';
import _ from 'underscore';
import memoize from 'memoize-one';
import url from 'url';
import * as d3 from 'd3';
import ReactTooltip from 'react-tooltip';
import DropdownItem from 'react-bootstrap/esm/DropdownItem';
import DropdownButton from 'react-bootstrap/esm/DropdownButton';
import { console, layout, ajax, memoizedUrlParse, logger } from '@hms-dbmi-bgm/shared-portal-components/es/components/util';
import { format as formatDateTime } from '@hms-dbmi-bgm/shared-portal-components/es/components/ui/LocalizedTime';
/**
* Various utilities for helping to draw area charts.
*
* @module
*/
/**
* Requests URIs defined in `props.searchURIs`, saves responses to own state, then passes down responses into child component(s).
* Can be extended.
*/
export class StatsViewController extends React.PureComponent {
static defaultProps = {
'searchURIs' : {},
'shouldRefetchAggs' : function(pastProps, nextProps){
return pastProps.session !== nextProps.session;
}
};
constructor(props){
super(props);
this.performAggRequests = this.performAggRequests.bind(this);
this.stateToChildProps = this.stateToChildProps.bind(this);
this.state = {
'mounted' : false,
'loadingStatus' : 'loading',
..._.object(Object.keys(props.searchURIs).map(function(k){ return [ 'resp' + k, null ]; }))
};
}
componentDidMount(){
setTimeout(()=>{
this.performAggRequests();
}, 100);
this.setState({ 'mounted' : true });
}
componentWillUnmount(){
this.setState({ 'mounted' : false });
}
componentDidUpdate(pastProps){
const { shouldRefetchAggs } = this.props;
if (shouldRefetchAggs(pastProps, this.props)){
this.setState({ 'loadingStatus' : 'loading' });
this.performAggRequests();
}
}
performAggRequests(){
const { searchURIs, href } = this.props;
const resultStateToSet = {};
const hrefParts = href && memoizedUrlParse(href); // href may not be passed in.
const ownHost = hrefParts && hrefParts.host;
const chartUrisAsPairs = _.pairs(searchURIs);
const chartUrisLen = chartUrisAsPairs.length;
const failureCallback = () => this.setState({ 'loadingStatus' : 'failed' });
let uponAllRequestsCompleteCallback = () => {
this.setState(_.extend({ 'loadingStatus' : 'complete' }, resultStateToSet));
};
if (chartUrisLen > 1) {
uponAllRequestsCompleteCallback = _.after(chartUrisLen, uponAllRequestsCompleteCallback);
}
const uponSingleRequestsCompleteCallback = function(key, uri, resp){
if (resp && resp.code === 404){
failureCallback();
return;
}
resultStateToSet['resp' + key] = resp;
uponAllRequestsCompleteCallback();
};
chartUrisAsPairs.forEach(([key, uri]) => {
if (typeof uri === 'function') uri = uri(this.props);
const uriHost = ownHost && url.parse(uri).host;
ajax.load(
uri, (r) => uponSingleRequestsCompleteCallback(key, uri, r), 'GET', failureCallback,
// If testing from localhost and connecting to data.4dn (e.g. for testing), clear out some headers
// to enable CORS
null, {}, ownHost && uriHost !== ownHost ? ['Authorization', 'Content-Type'] : []
);
});
}
stateToChildProps(state = this.state){
return _.object(_.pairs(state).filter(([key, value])=>{
// Which key:value pairs to pass to children.
if (key === 'mounted' || key === 'loadingStatus') return true;
if (!state.mounted/* || state.loadingStatus !== 'complete'*/) return false; // Don't pass responses in until finished.
return true;
}));
}
render(){
const { children } = this.props;
const childProps = _.extend(_.omit(this.props, 'children'), this.stateToChildProps(this.state));
return React.Children.map(children, function(c){ return React.cloneElement(c, childProps); });
}
}
/** Extend & implement own render method. */
export class StatsChartViewAggregator extends React.PureComponent {
static propTypes = {
'aggregationsToChartData' : PropTypes.object.isRequired,
'shouldReaggregate' : PropTypes.func,
'children' : PropTypes.node.isRequired
};
constructor(props){
super(props);
this.getRefWidth = this.getRefWidth.bind(this);
this.handleToggle = this.handleToggle.bind(this);
this.handleToggleSmoothEdges = this.handleToggleSmoothEdges.bind(this);
this.generateAggsToState = this.generateAggsToState.bind(this);
this.state = _.extend(this.generateAggsToState(props, {}), {
'chartToggles' : {},
'smoothEdges' : false
});
this.elemRef = React.createRef();
}
componentDidUpdate(pastProps){
const { shouldReaggregate } = this.props;
var updateState = false,
keys = _.keys(this.props),
i, k;
for (i = 0; i < keys.length; i++){
k = keys[i];
// eslint-disable-next-line react/destructuring-assignment
if (pastProps[k] !== this.props[k]){
if (k !== 'aggregationsToChartData' && k !== 'externalTermMap'){
var k4 = k.slice(0,4);
if (k4 !== 'resp'){
continue;
}
}
// eslint-disable-next-line react/destructuring-assignment
if (!this.props[k]) continue;
console.warn('StatsChartViewBase > Will re-aggregate chart data based on change of ', k);
updateState = true;
break;
}
}
if (typeof shouldReaggregate === 'function' && !updateState){
updateState = shouldReaggregate(pastProps, this.props);
}
if (updateState){
this.setState((currState) => this.generateAggsToState(this.props, currState));
}
}
getRefWidth(){
return this.elemRef && this.elemRef.current && this.elemRef.current.clientWidth;
}
handleToggle(key, cb){
this.setState(function(currState){
var nextTogglesState = _.extend({}, currState.chartToggles);
nextTogglesState[key] = !(nextTogglesState[key]);
return { 'chartToggles' : nextTogglesState };
}, cb);
}
handleToggleSmoothEdges(smoothEdges, cb){
this.setState(function(currState){
if (typeof smoothEdges === 'boolean'){
if (smoothEdges === currState.smoothEdges){
return null;
}
return { smoothEdges };
} else {
smoothEdges = !currState.smoothEdges;
return { smoothEdges };
}
});
}
generateAggsToState(props, state){
return _.object(_.map(_.keys(props.aggregationsToChartData), (key) =>
[
key,
props.aggregationsToChartData[key].function(
props['resp' + props.aggregationsToChartData[key].requires],
_.extend({}, props, state)
)
]
));
}
render(){
const { children } = this.props;
const width = this.getRefWidth() || null;
const childProps = _.extend(
{ width, 'onChartToggle' : this.handleToggle, 'onSmoothEdgeToggle' : this.handleToggleSmoothEdges },
this.props, this.state
);
let extendedChildren;
if (Array.isArray(children)){
extendedChildren = React.Children.map(children, (child) => React.cloneElement(child, childProps));
} else {
extendedChildren = React.cloneElement(children, childProps);
}
return <div className="stats-aggregation-container" ref={this.elemRef}>{ extendedChildren }</div>;
}
}
/**
* Optionally wrap a class or sub-class instance of StatsViewController (or ancestor which passes down props)
* with this component and place a GroupByDropdown later in rendering tree to use/accept these props.
* By default, change of 'groupBy' will cause StatsViewController to refetch aggregations/responses.
*/
export class GroupByController extends React.PureComponent {
static getDerivedStateFromProps(props, state){
const { groupByOptions, initialGroupBy } = props;
const { currentGroupBy } = state;
if (typeof groupByOptions[currentGroupBy] === 'undefined'){
if (typeof groupByOptions[initialGroupBy] === 'undefined'){
logger.error('Changed props.groupByOptions but state.currentGroupBy and props.initialGroupBy are now both invalid.');
throw new Error('Changed props.groupByOptions but state.currentGroupBy and props.initialGroupBy are now both invalid.');
} else {
return { 'currentGroupBy' : initialGroupBy };
}
}
return null;
}
static defaultProps = {
'groupByOptions' : {
'award.center_title' : <span><i className="icon icon-fw fas icon-university"/> Center</span>,
'award.project' : <span><i className="icon icon-fw fas icon-university"/> Project</span>,
'lab.display_title' : <span><i className="icon icon-fw fas icon-users"/> Lab</span>,
//'status' : <span><i className="icon icon-fw icon-circle"/> <span className="text-600">Current</span> Status</span>,
'experiments_in_set.experiment_type.display_title' : <span><i className="icon fas icon-fw icon-chart-bar"/> Experiment Type</span>
},
'initialGroupBy' : 'award.center_title'
}
constructor(props){
super(props);
this.handleGroupByChange = this.handleGroupByChange.bind(this);
this.state = { 'currentGroupBy' : props.initialGroupBy };
}
handleGroupByChange(field){
this.setState(function(currState){
if (currState.currentGroupBy === field){
return null;
}
return { 'currentGroupBy' : field };
});
}
render(){
var { children } = this.props,
{ currentGroupBy } = this.state,
childProps = _.extend(_.omit(this.props, 'children', 'initialGroupBy'),{ currentGroupBy, 'handleGroupByChange' : this.handleGroupByChange });
if (Array.isArray(children)){
return <div>{ React.Children.map(children, (c) => React.cloneElement(c, childProps) ) }</div>;
} else {
return React.cloneElement(children, childProps);
}
}
}
export class GroupByDropdown extends React.PureComponent {
static defaultProps = {
'title' : "Group By",
'buttonStyle' : {
'marginLeft' : 12,
'textAlign' : 'left'
},
'outerClassName' : "dropdown-container mb-15",
'id' : "select_primary_charts_group_by"
}
constructor(props){
super(props);
this.onSelect = _.throttle(this.onSelect.bind(this), 1000);
}
onSelect(eventKey, evt){
const { handleGroupByChange } = this.props;
if (typeof handleGroupByChange !== 'function'){
throw new Error("No handleGroupByChange function passed to GroupByDropdown.");
}
handleGroupByChange(eventKey);
}
render(){
const { groupByOptions, currentGroupBy, title, loadingStatus, buttonStyle, outerClassName, children, id } = this.props;
const optionItems = _.map(_.pairs(groupByOptions), ([field, title]) =>
<DropdownItem eventKey={field} key={field} active={field === currentGroupBy}>{ title }</DropdownItem>
);
const selectedValueTitle = loadingStatus === 'loading' ? <i className="icon icon-fw icon-spin fas icon-circle-notch"/> : groupByOptions[currentGroupBy];
return (
<div className={outerClassName}>
<span className="text-500">{ title }</span>
<DropdownButton id={id} title={selectedValueTitle} onSelect={this.onSelect} style={buttonStyle} disabled={optionItems.length < 2}>
{ optionItems }
</DropdownButton>
{ children }
</div>
);
}
}
/** Wraps AreaCharts or AreaChartContainers in order to provide shared color scales. */
export class ColorScaleProvider extends React.PureComponent {
static defaultProps = {
'className' : 'chart-group clearfix',
'width' : null,
'chartMargin' : { 'top': 30, 'right': 2, 'bottom': 30, 'left': 50 },
// Only relevant if --not-- providing own colorScale and letting this component create/re-create one.
'resetScalesWhenChange' : null,
'resetScaleLegendWhenChange' : null,
'colorScale' : null
};
constructor(props){
super(props);
this.resetColorScale = this.resetColorScale.bind(this);
this.updateColorStore = this.updateColorStore.bind(this);
var colorScale = props.colorScale || d3.scaleOrdinal(d3.schemeCategory10.concat(d3.schemePastel1));
this.state = { colorScale, 'colorScaleStore' : {} };
}
componentDidUpdate(pastProps){
const { resetScalesWhenChange, resetScaleLegendWhenChange } = this.props;
if (resetScalesWhenChange !== pastProps.resetScalesWhenChange){
console.warn("Color scale reset");
this.resetColorScale();
} else if (resetScaleLegendWhenChange !== pastProps.resetScaleLegendWhenChange){
console.warn("Color scale reset (LEGEND ONLY)");
this.resetColorScale(true);
}
}
resetColorScale(onlyResetLegend=false){
if (onlyResetLegend){
this.setState({ 'colorScaleStore' : {} });
return;
}
const { colorScale : propColorScale } = this.props;
let colorScale;
const colorScaleStore = {};
if (typeof propColorScale === 'function'){
colorScale = propColorScale; // Does nothing.
} else {
colorScale = d3.scaleOrdinal(d3.schemeCategory10.concat(d3.schemePastel1));
}
this.setState({ colorScale, colorScaleStore });
}
updateColorStore(term, color){
this.setState(function({ colorScaleStore }){
if (colorScaleStore && colorScaleStore[term] && colorScaleStore[term] === color){
return null;
}
var nextColorScaleStore = _.clone(colorScaleStore);
nextColorScaleStore[term] = color;
return { 'colorScaleStore' : nextColorScaleStore };
});
}
render(){
const { children, className } = this.props;
const newChildren = React.Children.map(children, (child, childIndex) => {
if (!child) return null;
if (typeof child.type === 'string') {
return child; // Not component instance
}
return React.cloneElement(
child,
_.extend({}, _.omit(this.props, 'children'), { 'updateColorStore' : this.updateColorStore }, this.state)
);
});
return <div className={className || null}>{ newChildren }</div>;
}
}
export class HorizontalD3ScaleLegend extends React.Component {
constructor(props){
super(props);
this.renderColorItem = this.renderColorItem.bind(this);
}
shouldComponentUpdate(nextProps, nextState){
const { colorScaleStore } = this.props;
//if (nextProps.colorScale !== this.props.colorScale){
if (nextProps.colorScaleStore !== colorScaleStore){
var currTerms = _.keys(colorScaleStore),
nextTerms = _.keys(nextProps.colorScaleStore);
// Don't update if no terms in next props; most likely means colorScale[Store] has been reset and being repopulated.
if (currTerms.length > 0 && nextTerms.length === 0){
return false;
}
}
//}
// Emulates PureComponent
var propKeys = _.keys(nextProps);
for (var i = 0; i < propKeys.length; i++){
// eslint-disable-next-line react/destructuring-assignment
if (nextProps[propKeys[i]] !== this.props[propKeys[i]]) {
return true;
}
}
return false;
}
renderColorItem([term, color], idx, all){
return (
<div className="col-sm-4 col-md-3 col-lg-2 mb-03 text-truncate" key={term}>
<div className="color-patch" style={{ 'backgroundColor' : color }} data-term={term} />
{ term }
</div>
);
}
render(){
var { colorScale, colorScaleStore } = this.props;
if (!colorScale || !colorScaleStore) return null;
return (
<div className="legend mb-27">
<div className="row">{ _.map(_.sortBy(_.pairs(colorScaleStore), function([term, color]){ return term.toLowerCase(); }), this.renderColorItem) }</div>
</div>
);
}
}
export class ChartTooltip extends React.PureComponent {
constructor(props){
super(props);
this.state = _.extend({
'leftPosition' : 0,
'visible' : false,
'mounted' : false,
'contentFxn' : null,
'topPosition' : 0
}, props.initialState || {});
}
render(){
var { margin } = this.props,
{ leftPosition, visible, contentFxn, topPosition, chartWidth, chartHeight } = this.state;
return (
<div className="chart-tooltip" style={_.extend(_.pick(margin, 'left', 'top'), {
'transform' : 'translate(' + Math.min(leftPosition, chartWidth - 5) + 'px, 0px)',
'display' : visible ? 'block' : 'none',
'bottom' : margin.bottom + 5
})}>
<div className="line"/>
<div className="line-notch" style={{ 'top' : topPosition }}>
{ chartWidth && topPosition < chartHeight ? [
<div key="before" className="horiz-line-before" style={{ 'width' : (leftPosition - 5), 'left' : -(leftPosition - 5) }}/>,
<div key="after" className="horiz-line-after" style={{ 'right' : - ((chartWidth - leftPosition) - 4) }}/>
] : null }
</div>
{ contentFxn && contentFxn(this.props, this.state) }
</div>
);
}
}
export class AreaChart extends React.PureComponent {
static mergeStackedDataForExtents(d3Data){
return d3.merge(_.map(d3Data, function(d2){
return _.map(d2, function(d){
return d.data;
});
}));
}
static calculateXAxisExtents(mergedData, xDomain){
var xExtents = [null, null];
if (xDomain && xDomain[0]){
xExtents[0] = xDomain[0];
} else {
xExtents[0] = d3.min(mergedData, function(d){ return d.date; });
}
if (xDomain && xDomain[1]){
xExtents[1] = xDomain[1];
} else {
xExtents[1] = d3.max(mergedData, function(d){ return d.date; });
}
return xExtents;
}
static calculateYAxisExtents(mergedData, yDomain){
var yExtents = [null, null];
if (yDomain && typeof yDomain[0] === 'number'){
yExtents[0] = yDomain[0];
} else {
yExtents[0] = d3.min(mergedData, function(d){ return d.total; });
}
if (yDomain && typeof yDomain[1] === 'number'){
yExtents[1] = yDomain[1];
} else {
yExtents[1] = d3.max(mergedData, function(d){ return d.total; });
}
return yExtents;
}
static childKeysFromData(data){
return Array.from(_.reduce(data, function(m,d){
_.forEach(d.children || [], function(child){ m.add(child.term); });
return m;
}, new Set()));
}
/** Convert timestamps to D3 date objects. */
static correctDatesInData(origData, d3TimeFormat = '%Y-%m-%d'){
const parseTime = d3.utcParse(d3TimeFormat);
return _.map(origData, (d) => {
var formattedDate = (new Date(d.date.slice(0,10))).toISOString().slice(0,10);
return _.extend({}, d, {
'date' : parseTime(formattedDate),
'origDate' : formattedDate
});
});
}
static stackData(origData, d3TimeFormat = '%Y-%m-%d'){
const stackGen = d3.stack().value(function(d, key){
var currChild = _.findWhere(d.children || [], { 'term' : key });
if (currChild) return currChild.total;
return 0;
});
stackGen.keys(AreaChart.childKeysFromData(origData));
const formattedDateData = AreaChart.correctDatesInData(origData, d3TimeFormat);
return stackGen(formattedDateData);
}
static getDerivedStateFromProps(props, state){
return {
'colorScale' : props.colorScale || state.colorScale || d3.scaleOrdinal(d3.schemeCategory10)
};
}
static defaultProps = {
'chartMargin' : { 'top': 30, 'right': 2, 'bottom': 30, 'left': 50 },
'data' : null,
'd3TimeFormat' : '%Y-%m-%d', // TODO: Remove prop?
'stackChildren' : true,
'height' : 300,
'yAxisLabel' : 'Count',
'yAxisScale' : 'Linear', // Must be one of 'Linear', 'Log', 'Pow'
'yAxisPower' : null,
'xDomain' : [ new Date('2017-03-01'), null ],
'yDomain' : [ 0, null ],
'curveFxn' : d3.curveStepAfter,
'transitionDuration' : 1500,
'colorScale' : null, // d3.scaleOrdinal(d3.schemeCategory10)
'tooltipDataProperty' : 'total',
'shouldDrawNewChart' : function(pastProps, nextProps, pastState, nextState){
var shouldDrawNewChart = false;
if (pastProps.data !== nextProps.data) shouldDrawNewChart = true;
if (pastProps.curveFxn !== nextProps.curveFxn) shouldDrawNewChart = true;
if (pastProps.colorScale !== nextProps.colorScale) shouldDrawNewChart = true;
if (shouldDrawNewChart) console.info('Will redraw chart');
return shouldDrawNewChart;
}
};
constructor(props){
super(props);
_.bindAll(this, 'getInnerChartWidth', 'getInnerChartHeight', 'xScale', 'yScale',
'commonDrawingSetup', 'drawNewChart', 'updateTooltip', 'removeTooltip', 'updateExistingChart'
);
this.updateExistingChart = _.debounce(this.updateExistingChart, 500);
// Tiny performance boost via memoizing
this.mergeStackedDataForExtents = memoize(AreaChart.mergeStackedDataForExtents);
this.calculateXAxisExtents = memoize(AreaChart.calculateXAxisExtents);
this.calculateYAxisExtents = memoize(AreaChart.calculateYAxisExtents);
this.childKeysFromData = memoize(AreaChart.childKeysFromData);
this.stackData = memoize(AreaChart.stackData);
// Will be cached here later from d3.select(this.refs..)
this.svg = null;
this.state = {
'drawingError' : false,
'drawn' : false
};
this.svgRef = React.createRef();
this.tooltipRef = React.createRef();
}
componentDidMount(){
requestAnimationFrame(this.drawNewChart);
}
componentDidUpdate(pastProps, pastState){
const { shouldDrawNewChart : shouldDrawNewChartFxn } = this.props;
const shouldDrawNewChart = shouldDrawNewChartFxn(pastProps, this.props);
if (shouldDrawNewChart){
setTimeout(()=>{ // Wait for other UI stuff to finish updating, e.g. element widths.
requestAnimationFrame(()=>{
this.destroyExistingChart();
this.drawNewChart();
});
}, 300);
} else {
setTimeout(this.updateExistingChart, 300);
}
}
getXAxisGenerator(useChartWidth = null){
const { xDomain, data, d3TimeFormat } = this.props;
const stackedData = this.stackData(data, d3TimeFormat);
const mergedDataForExtents = this.mergeStackedDataForExtents(stackedData);
const xExtents = this.calculateXAxisExtents(mergedDataForExtents, xDomain);
const chartWidth = useChartWidth || this.innerWidth || this.getInnerChartWidth();
const yearDiff = (xExtents[1] - xExtents[0]) / (60 * 1000 * 60 * 24 * 365);
const widthPerYear = chartWidth / yearDiff;
if (widthPerYear < 3600){
var monthsTick;
if (widthPerYear < 50) monthsTick = 24;
else if (widthPerYear >= 50 && widthPerYear < 200) monthsTick = 12;
else if (widthPerYear >= 200 && widthPerYear < 300) monthsTick = 6;
else if (widthPerYear >= 300 && widthPerYear < 400) monthsTick = 4;
else if (widthPerYear >= 400 && widthPerYear < 500) monthsTick = 3;
else if (widthPerYear >= 500 && widthPerYear < 750) monthsTick = 2;
else if (widthPerYear >= 750) monthsTick = 1;
return function(x){
return d3.axisBottom(x).ticks(d3.utcMonth.every(monthsTick));
};
} else if (widthPerYear >= 3600){
var widthPerMonth = widthPerYear / 12, daysTick;
if (widthPerMonth > 1500){
daysTick = 1;
} else if (widthPerMonth > 1000){
daysTick = 3;
} else if (widthPerMonth > 600){
daysTick = 7;
} else {
daysTick = 14;
}
return function(x){
return d3.axisBottom(x).ticks(d3.utcDay.every(daysTick));
};
}
}
getInnerChartWidth(){
var { width, margin } = this.props;
this.svg = this.svg || d3.select(this.svgRef.current);
this.innerWidth = ( width || parseInt( this.svg.style('width') ) ) - margin.left - margin.right;
return this.innerWidth;
}
getInnerChartHeight(){
var { height, margin } = this.props;
this.svg = this.svg || d3.select(this.svgRef.current);
this.innerHeight = ( height || parseInt( this.svg.style('height') ) ) - margin.top - margin.bottom;
return this.innerHeight;
}
xScale(width){
const { xDomain, data, d3TimeFormat } = this.props;
//const { stackedData } = this.state;
const stackedData = this.stackData(data, d3TimeFormat);
const mergedDataForExtents = this.mergeStackedDataForExtents(stackedData);
const xExtents = this.calculateXAxisExtents(mergedDataForExtents, xDomain);
return d3.scaleUtc().rangeRound([0, width]).domain(xExtents);
}
yScale(height){
const { yAxisScale, yAxisPower, yDomain, data, d3TimeFormat } = this.props;
//const { stackedData } = this.state;
const stackedData = this.stackData(data, d3TimeFormat);
const mergedDataForExtents = this.mergeStackedDataForExtents(stackedData);
const yExtents = this.calculateYAxisExtents(mergedDataForExtents, yDomain);
const scale = d3['scale' + yAxisScale]().rangeRound([height, 0]).domain(yExtents);
if (yAxisScale === 'Pow' && yAxisPower !== null){
scale.exponent(yAxisPower);
}
return scale;
}
commonDrawingSetup(){
const { curveFxn, data, d3TimeFormat } = this.props;
const stackedData = this.stackData(data, d3TimeFormat);
const svg = this.svg || d3.select(this.svgRef.current);
const width = this.getInnerChartWidth();
const height = this.getInnerChartHeight();
const x = this.xScale(width);
const y = this.yScale(height);
const bottomAxisGenerator = this.getXAxisGenerator(width)(x);
const area = d3.area()
.x ( function(d){ return x(d.date || d.data.date); } )
.curve(curveFxn)
//.x0 ( function(d){ return x(d.date || d.data.date); } )
//.x1 ( function(d){ return x(d.date || d.data.date) + 10; } )
.y0( function(d){ return Array.isArray(d) ? y(d[0]) : y(0); } )
.y1( function(d){ return Array.isArray(d) ? y(d[1]) : y(d.total || d.data.total); } );
const rightAxisGenerator = d3.axisRight(y).tickSize(width);
const rightAxisFxn = function(g){
g.call(rightAxisGenerator);
g.select('.domain').remove();
g.selectAll('.tick > text').remove();
g.selectAll('.tick > line')
.attr("class", "right-axis-tick-line")
.attr('opacity', 0.2)
.attr("stroke", "#777")
.attr("stroke-dasharray", "2,2");
};
this.svg = svg;
return { svg, x, y, width, height, area, bottomAxisGenerator, rightAxisFxn, stackedData };
}
/**
* Draws D3 area chart using the DOM a la https://bl.ocks.org/mbostock/3883195 in the rendered <svg> element.
*
* TODO: We should try to instead render out <path>, <g>, etc. SVG elements directly out of React to be more Reactful and performant.
* But this can probably wait (?).
*/
drawNewChart(){
if (!this.svgRef.current) {
this.setState({ 'drawingError' : true });
return;
}
if (this.drawnD3Elements) {
logger.error('Drawn chart already exists. Exiting.');;
this.setState({ 'drawingError' : true });
return;
}
const { yAxisLabel, margin, updateColorStore } = this.props;
const { stackedData, svg, y, height, area, bottomAxisGenerator, rightAxisFxn } = this.commonDrawingSetup();
const drawn = { svg };
const { colorScale } = this.state;
drawn.root = svg.append("g").attr('transform', "translate(" + margin.left + "," + margin.top + ")");
drawn.layers = drawn.root.selectAll('.layer')
.data(stackedData)
.enter()
.append('g')
.attr('class', 'layer');
drawn.path = drawn.layers.append('path')
.attr('class', 'area')
.attr('data-term', function(d){
return (d.data || d).key;
})
.style('fill', function(d){
var term = (d.data || d).key,
color = colorScale(term);
if (typeof updateColorStore === 'function'){
updateColorStore(term, color);
}
return color;
})
.attr('d', area);
this.drawAxes(drawn, { height, bottomAxisGenerator, y, yAxisLabel, rightAxisFxn });
this.drawnD3Elements = drawn;
setTimeout(function(){
ReactTooltip.rebuild();
}, 10);
}
updateTooltip(evt){
const { chartMargin, yAxisLabel, dateRoundInterval, tooltipDataProperty, data, d3TimeFormat } = this.props;
const { colorScale } = this.state;
const stackedData = this.stackData(data, d3TimeFormat);
const svg = this.svg || d3.select(this.svgRef.current); // SHOULD be same as evt.target.
const tooltip = this.tooltipRef.current;
let [ mX, mY ] = d3.clientPoint(svg.node(), evt); // [x: number, y: number]
const chartWidth = this.innerWidth || this.getInnerChartWidth();
const chartHeight = this.innerHeight || this.getInnerChartHeight();
const currentTerm = (evt && evt.target.getAttribute('data-term')) || null;
const tdp = tooltipDataProperty || 'total';
let dateFormatFxn = function(aDate){ return formatDateTime(aDate, 'date-sm'); };
if (dateRoundInterval === 'month'){
dateFormatFxn = function(aDate){
return formatDateTime(aDate, 'date-month');
};
} else if (dateRoundInterval === 'week'){
// TODO maybe. Currently just keeps day format.
} else if (dateRoundInterval === 'year'){
dateFormatFxn = function(aDate){
return aDate.getFullYear();
};
}
mX -= (chartMargin.left || 0);
mY -= (chartMargin.top || 0);
if (mX < 0 || mY < 0 || mX > chartWidth + 1 || mY > chartHeight + 1){
return this.removeTooltip();
}
var xScale = this.xScale(chartWidth),
yScale = this.yScale(chartHeight),
hovDate = xScale.invert(mX),
dateString = dateFormatFxn(hovDate),
leftPosition = xScale(hovDate),
isToLeft = leftPosition > (chartWidth / 2),
maxTermsVisible = Math.floor((chartHeight - 60) / 18),
stackedLegendItems = _.filter(_.map(stackedData, function(sD){
return _.find(sD, function(stackedDatum, i, all){
var curr = stackedDatum.data,
next = (all[i + 1] && all[i + 1].data) || null;
if (hovDate > curr.date && (!next || next.date >= hovDate)){
return true;
}
return false;
});
})),
total = parseInt(((stackedLegendItems.length > 0 && stackedLegendItems[0].data && stackedLegendItems[0].data[tdp]) || 0) * 100) / 100,
termChildren = _.sortBy(_.filter((stackedLegendItems.length > 0 && stackedLegendItems[0].data && stackedLegendItems[0].data.children) || [], function(c){
if (c.term === null) return false;
return c && c[tdp] > 0;
}), function(c){ return -c[tdp]; }),
isEmpty = termChildren.length === 0,
topPosition = yScale(total);
// It's anti-pattern for component to update its children using setState instead of passing props as done here.
// However _this_ component is a PureComponent which redraws or at least transitions D3 chart upon any update,
// so performance/clarity-wise this approach seems more desirable.
tooltip.setState({
leftPosition, topPosition, chartWidth, chartHeight,
'visible' : true,
'contentFxn' : function(tProps, tState){
if (termChildren.length > maxTermsVisible){
var lastTermIdx = maxTermsVisible - 1,
currentActiveItemIndex = _.findIndex(termChildren, function(c){ return c.term === currentTerm; });
if (currentActiveItemIndex && currentActiveItemIndex > lastTermIdx){
var temp = termChildren[lastTermIdx];
termChildren[lastTermIdx] = termChildren[currentActiveItemIndex];
termChildren[currentActiveItemIndex] = temp;
}
var termChildrenRemainder = termChildren.slice(maxTermsVisible),
totalForRemainder = 0;
_.forEach(termChildrenRemainder, function(r){
totalForRemainder += r[tdp];
});
termChildren = termChildren.slice(0, maxTermsVisible);
var newChild = { 'term' : termChildrenRemainder.length + " More...", "noColor" : true };
newChild[tdp] = totalForRemainder;
termChildren.push(newChild);
}
return (
<div className={"label-bg" + (isToLeft ? ' to-left' : '')}>
<h5 className={"text-500 mt-0 clearfix" + (isEmpty ? ' mb-0' : ' mb-11')}>
{ dateString }{ total ? <span className="text-700 text-large pull-right" style={{ marginTop: -2 }}> { total }</span> : null }
</h5>
{ !isEmpty ?
<table className="current-legend">
<tbody>
{ _.map(termChildren, function(c, i){
return (
<tr key={c.term || i} className={currentTerm === c.term ? 'active' : null}>
<td className="patch-cell">
<div className="color-patch" style={{ 'backgroundColor' : c.noColor ? 'transparent' : colorScale(c.term) }}/>
</td>
<td className="term-name-cell">{ c.term }</td>
<td className="term-name-total">
{ c[tdp] % 1 > 0 ? Math.round(c[tdp] * 100) / 100 : c[tdp] }
{ yAxisLabel && yAxisLabel !== 'Count' ? ' ' + yAxisLabel : null }
</td>
</tr>
);
}) }
</tbody>
</table>
: null }
</div>
);
}
});
}
removeTooltip(){
const tooltip = this.tooltipRef.current;
tooltip.setState({ 'visible' : false });
}
drawAxes(drawn, reqdFields){
var { height, bottomAxisGenerator, y, yAxisLabel, rightAxisFxn } = reqdFields;
if (!drawn){
drawn = this.drawnD3Elements || {};
}
drawn.xAxis = drawn.root.append('g')
.attr("transform", "translate(0," + height + ")")
.call(bottomAxisGenerator);
drawn.yAxis = drawn.root.append('g')
.call(d3.axisLeft(y));
drawn.yAxis.append('text')
.attr("fill", "#000")
.attr("x", 0)
.attr("y", -20)
.attr("dy", "0.71em")
.attr("text-anchor", "end")
.text(yAxisLabel);
drawn.rightAxis = drawn.root.append('g').call(rightAxisFxn);
return drawn;
}
/**
* Use to delete SVG before drawing a new one,
* e.g. in response to a _big_ change that can't easily 'update'.
*/
destroyExistingChart(){
var drawn = this.drawnD3Elements;
if (!drawn || !drawn.svg) {
logger.error('No D3 SVG to clear.');
return;
}
drawn.svg.selectAll('*').remove();
delete this.drawnD3Elements;
}
updateExistingChart(){
// TODO:
// If width or height has changed, transition existing DOM elements to larger dimensions
// If data has changed.... decide whether to re-draw graph or try to transition it.
if (!this.drawnD3Elements) {
logger.error('No existing elements to transition.');
throw new Error('No existing elements to transition.');
}
const { transitionDuration } = this.props;
const { stackedData, y, height, area, bottomAxisGenerator, rightAxisFxn } = this.commonDrawingSetup();
const drawn = this.drawnD3Elements;
requestAnimationFrame(()=>{
drawn.xAxis
.transition().duration(transitionDuration)
.attr("transform", "translate(0," + height + ")")
.call(bottomAxisGenerator);
drawn.yAxis
.transition().duration(transitionDuration)
.call(d3.axisLeft(y));
drawn.rightAxis.remove();
drawn.rightAxis = drawn.root.append('g').call(rightAxisFxn);
drawn.root.selectAll('.layer')
.data(stackedData)
.selectAll('path.area')
.transition()
.duration(transitionDuration)
.attr('d', area);
});
}
render(){
var { data, width, height, transitionDuration, margin } = this.props;
if (!data || this.state.drawingError) {
return <div>Error</div>;
}
return (
<div className="area-chart-inner-container" onMouseMove={this.updateTooltip} onMouseOut={this.removeTooltip}>
<svg ref={this.svgRef} className="area-chart" width={width || "100%"} height={height || null} style={{
height, 'width' : width || '100%',
'transition' : 'height ' + (transitionDuration / 1000) + 's' + (height >= 500 ? ' .75s' : ' 1.025s')
}} />
<ChartTooltip margin={margin} ref={this.tooltipRef} />
</div>
);
}
}
export function LoadingIcon(props){
const { children } = props;
return (
<div className="mt-5 mb-5 text-center">
<i className="icon icon-fw icon-spin icon-circle-notch icon-2x fas" style={{ opacity : 0.5 }}/>
<h5 className="text-400">{ children }</h5>
</div>
);
}
LoadingIcon.defaultProps = { 'children' : "Loading Chart Data" };
export function ErrorIcon(props){
const { children } = props;
return (
<div className="mt-5 mb-5 text-center">
<i className="icon icon-fw icon-times icon-2x fas"/>
<h5 className="text-400">{ children }</h5>
</div>
);
}
ErrorIcon.defaultProps = { 'children' : "Loading failed. Please try again later." };
export class AreaChartContainer extends React.Component {
static isExpanded(props){
const { windowWidth, chartToggles, id } = props;
const gridState = layout.responsiveGridState(windowWidth);
if (gridState && gridState !== 'xl') return false;
return !!((chartToggles || {})[id]);
}
static defaultProps = {
'colorScale' : null,
'extraButtons' : []
};
constructor(props){
super(props);
this.buttonSection = this.buttonSection.bind(this);
this.toggleExpanded = _.throttle(this.toggleExpanded.bind(this), 1000);
this.expandButton = this.expandButton.bind(this);
this.elemRef = React.createRef();
}
componentDidMount(){
const { width } = this.props;
if (typeof width === 'number' && width) return;
setTimeout(()=>{ // Update w. new width.
this.forceUpdate();
}, 0);
}
componentDidUpdate(pastProps){
const { defaultColSize, width } = this.props;
if (
!(typeof width === 'number' && width) &&
(pastProps.defaultColSize !== defaultColSize || AreaChartContainer.isExpanded(pastProps) !== AreaChartContainer.isExpanded(this.props))
){
setTimeout(()=>{ // Update w. new width.
this.forceUpdate();
}, 0);
}
}
toggleExpanded(e){
const { onToggle, id } = this.props;
return typeof onToggle === 'function' && id && onToggle(id);
}
getRefWidth(){
return this.elemRef && this.elemRef.current && this.elemRef.current.clientWidth;
}
expandButton(){
const { windowWidth } = this.props;
const gridState = layout.responsiveGridState(windowWidth);
if (gridState !== 'xl') return null;
const expanded = AreaChartContainer.isExpanded(this.props);
return (
<button type="button" className="btn btn-outline-dark btn-sm" onClick={this.toggleExpanded}>
<i className={"icon icon-fw fas icon-search-" + (expanded ? 'minus' : 'plus')}/>
</button>
);
}
buttonSection(){
const { extraButtons } = this.props;
return (
<div className="pull-right">
{ extraButtons }
{ this.expandButton() }
</div>
);
}
render(){
const { title, children, width, defaultHeight, colorScale, chartMargin, updateColorStore } = this.props;
const expanded = AreaChartContainer.isExpanded(this.props);
const useWidth = width || this.getRefWidth();
const chartInnerWidth = expanded ? useWidth * 3 : useWidth;
const useHeight = expanded ? 500 : (defaultHeight || AreaChart.defaultProps.height);
let visualToShow;
if (typeof useWidth === 'number' && useWidth){
visualToShow = React.cloneElement(children, {
colorScale, updateColorStore,
'width' : chartInnerWidth,
'height' : useHeight,
'margin' : chartMargin || children.props.margin || null
});
} else {
// If no width yet, just for stylistic purposes, don't render chart itself.
visualToShow = <LoadingIcon>Initializing...</LoadingIcon>;
}
return (
<div className="mt-2">
<div className="text-300 clearfix">
{ this.buttonSection() }
{ title }
</div>
<div ref={this.elemRef} style={{ 'overflowX' : expanded ? 'scroll' : 'auto', 'overflowY' : 'hidden' }}>
{ visualToShow }
</div>
</div>
);
}
}
|
src/docs/examples/TextInputStyledComponents/ExampleError.js | ThomasBem/ps-react-thomasbem | import React from 'react';
import TextInput from 'ps-react/TextInputStyledComponents';
/** Required TextBox with error */
export default class ExampleOptional extends React.Component {
render() {
return (
<TextInput
htmlId="example-optional"
label="First Name"
name="firstname"
onChange={() => {}}
required
error="First name is required."
/>
)
}
} |
src/component/view-cover/index.js | Cadburylion/personal-portfolio | import React from 'react'
import User from '../user/index.js'
import {connect} from 'react-redux'
import {Route} from 'react-router-dom'
import {withRouter} from 'react-router'
import {NavLink} from 'react-router-dom'
import FontAwesome from 'react-fontawesome'
import * as route from '../../action/route.js'
import * as viewActions from '../../action/viewActions.js'
import './style.scss'
import About from '../about/index.js'
import Contact from '../contact/index.js'
import Portfolio from '../portfolio/index.js'
class ViewCover extends React.Component{
constructor(props){
super(props)
this.state={
background: this.props.backgrounds.background,
}
this.handleKeyPress = this.handleKeyPress.bind(this)
}
componentWillMount(){
document.addEventListener('keypress', this.handleKeyPress)
}
handleKeyPress(e){
this.props.entered && !this.props.focus && e.key === 'i' ? this.props.handleCover() : undefined
}
render(){
let dashboardOpen = this.props.coverOpen ? 'open' : ''
let mainBackground = {
backgroundImage: 'url(' + `${this.props.backgrounds.background}` + ')',
}
return (
<div className={`view-cover-main ${this.props.coverOpen ? 'view-cover-main-open' : ''}`} style={mainBackground}>
{!this.props.entered ? <div className='user-container'> <User /> </div>
: <div className='view-cover-content'>
{this.props.pageActive ?
<NavLink to={this.props.route === '/about' ? '/contact'
: this.props.route === '/portfolio' ? '/about'
: this.props.route === '/contact' ? '/portfolio'
: '/'
} className='left'>
<div className='arrow'>
{'<'}
</div>
</NavLink>
: undefined
}
<div className='basic-info'>
<a className={'name'} href='https://docs.google.com/document/d/1bLo8ln0GXKTPMceAKzwvaifaj8mm2Y2_cXog9_Ssu60/export?format=pdf'>
Name: <span>Matthew Parker</span>
</a>
<div className={`developer`}>
Developer: React & Full-Stack JavaScript
</div>
<div className={`status`}>
Status: Available for hire
</div>
</div>
<div className={`dashboard-bar ${dashboardOpen}`} onClick={this.props.handleCover}>
<div className='hint-text'>
{this.props.backgrounds.background === 'https://i.imgur.com/589GAGa.gif'
? `Below deck`
: this.props.backgrounds.background === 'https://i.imgur.com/HjStYze.gif'
? `Above deck`
: this.props.backgrounds.background === 'https://i.imgur.com/4KJPU8C.gif'
? `Train`
: this.props.backgrounds.background === 'https://i.imgur.com/vvTO3np.gif'
? `Waterfalls`
: this.props.backgrounds.background === 'https://i.imgur.com/XTCAUql.gif'
? `Forest`
: ``
}
</div>
<FontAwesome name='arrow-right' />
<div className='i-text'>{`[ i ] to ${this.props.coverOpen ? 'close' : 'open'} dashboard`}</div>
</div>
<div className='pixelart-to-css'></div>
<div className='page-container'>
<Route exact path='/about' component={About} />
<Route exact path='/portfolio' component={Portfolio} />
<Route exact path='/contact' component={Contact} />
</div>
{this.props.pageActive ?
<NavLink to={this.props.route === '/about' ? '/portfolio'
: this.props.route === '/portfolio' ? '/contact'
: this.props.route === '/contact' ? '/about'
: '/'
}
className='right'>
<div className='arrow'>
{'>'}
</div>
</NavLink>
: undefined
}
</div>
}
</div>
)
}
}
let mapStateToProps = (state) => ({
pageActive: state.pageActive,
route: state.route,
focus: state.focus,
entered: state.enterSite,
coverOpen: state.coverToggle,
backgrounds: state.setBackground,
})
let mapDispatchToProps = (dispatch) => ({
shareRoute: () => dispatch(route.route()),
handleCover: (toggle) => dispatch(viewActions.cover(toggle)),
setBackground: (background) => dispatch(viewActions.background(background)),
})
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ViewCover))
|
packages/theme-patternfly-org/components/propsTable/propsTable.js | patternfly/patternfly-org | import React from 'react';
import { Badge } from '@patternfly/react-core';
import {
Table,
TableHeader,
TableBody,
cellWidth
} from '@patternfly/react-table';
import { AutoLinkHeader } from '../autoLinkHeader/autoLinkHeader';
import { PropTypeWithLinks } from './propTypeWithLinks';
import { css } from '@patternfly/react-styles';
import accessibleStyles from '@patternfly/react-styles/css/utilities/Accessibility/accessibility';
export const PropsTable = ({
title,
rows,
allPropComponents
}) => {
const columns = [
{ title: 'Name', transforms: [cellWidth(20)] },
{ title: 'Type', transforms: [cellWidth(20)] },
{ title: 'Default', transforms: [] },
{ title: 'Description', transforms: [] }
];
return (
<React.Fragment>
<AutoLinkHeader size="h3">
{title}
</AutoLinkHeader>
<Table
className="pf-u-mt-md pf-u-mb-lg"
variant="compact"
aria-label={title}
caption={<div><span className="ws-prop-required">*</span>required</div>}
cells={columns}
gridBreakPoint="grid-lg"
rows={rows
// Sort required rows first
.sort((a,b) => a.required === b.required
? 0
: a.required ? -1 : 1)
.map((row, idx) => ({
cells: [
<div className="pf-m-break-word">
{row.deprecated && 'Deprecated: '}
{row.name}
{row.required ? (
<React.Fragment key={`${row.name}-required-prop`}>
<span aria-hidden="true" key={`${row.name}-asterisk`} className="ws-prop-required">
*
</span>
<span key={`${row.name}-required`} className={css(accessibleStyles.screenReader)}>
required
</span>
</React.Fragment>
) : ''}
{row.beta && (
<Badge key={`${row.name}-${idx}`} className="ws-beta-badge pf-u-ml-sm">
Beta
</Badge>
)}
</div>,
<div className="pf-m-break-word">
<PropTypeWithLinks type={row.type} allPropComponents={allPropComponents} />
</div>,
<div className="pf-m-break-word">
{row.defaultValue}
</div>,
<div className="pf-m-break-word">
{row.description}
</div>
]
}))
}
>
<TableHeader />
<TableBody />
</Table>
</React.Fragment>
);
}
|
utils/tester.js | seeden/react-provide-props | import TestUtils from 'react-addons-test-utils';
import React from 'react';
const jsdom = require('jsdom');
function renderComponent(react, props) {
global.document = jsdom.jsdom('<!DOCTYPE html><html><body></body></html>');
global.window = document.defaultView;
global.navigator = {userAgent: 'node.js'};
const rendered = TestUtils.renderIntoDocument(React.createElement(react, props));
return TestUtils.findRenderedComponentWithType(rendered, react);
}
export function renderJSX(jsx, context, node) {
return renderComponent(React.createClass({
displayName: 'TestJSX',
render: () => jsx,
}), undefined, context);
}
|
client/src/header/DemoButton.js | ziel5122/autograde | import PropTypes from 'prop-types';
import React from 'react';
import { connect } from 'react-redux';
import { Link } from 'react-router-dom';
const linkStyle = {
textDecoration: 'none',
};
const style = {
color: 'whitesmoke',
fontSize: '16px',
lineHeight: '16px',
padding: '12px',
};
const DemoButton = ({ loggedIn }) => (
loggedIn ? null : (
<div>
<Link to="/demo" style={linkStyle}>
<div className="demoButton" style={style}>
demo
</div>
</Link>
<style jsx>{`
.demoButton {
cursor: hand;
cursor: pointer;
}
.demoButton:hover {
background: rgba(106, 90, 205, .25);
}
`}</style>
</div>
)
);
DemoButton.propTypes = {
loggedIn: PropTypes.bool.isRequired,
};
const mapStateToProps = ({ login: { loggedIn } }) => ({
loggedIn,
});
export default connect(mapStateToProps)(DemoButton);
|
src/js/components/icons/base/FormCalendar.js | linde12/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import CSSClassnames from '../../../utils/CSSClassnames';
import Intl from '../../../utils/Intl';
import Props from '../../../utils/Props';
const CLASS_ROOT = CSSClassnames.CONTROL_ICON;
const COLOR_INDEX = CSSClassnames.COLOR_INDEX;
export default class Icon extends Component {
render () {
const { className, colorIndex } = this.props;
let { a11yTitle, size, responsive } = this.props;
let { intl } = this.context;
const classes = classnames(
CLASS_ROOT,
`${CLASS_ROOT}-form-calendar`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'form-calendar');
const restProps = Props.omit(this.props, Object.keys(Icon.propTypes));
return <svg {...restProps} version="1.1" viewBox="0 0 24 24" width="24px" height="24px" role="img" className={classes} aria-label={a11yTitle}><path fill="none" stroke="#000" strokeWidth="2" d="M6,19 L18,19 L18,8 L6,8 L6,19 Z M15,8 L15,5 L15,8 Z M9,8 L9,5 L9,8 Z M6,11.5 L18,11.5 L6,11.5 Z"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'FormCalendar';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
app/NewsHeader.js | jamesburton/newsappreactnative | import React from 'react';
import {Text, View} from 'react-native';
var NewsHeader = () => <Text style={{color:'#fff', fontSize: 18}}>Example News App</Text>;
module.exports = NewsHeader; |
src/client/routes.js | lassecapel/este-isomorphic-app | import React from 'react';
import App from './app/app.react';
import SearchPageRoute from './routes/search-page-route.react';
import Todos from './pages/todos.react';
import NotFound from './pages/notfound.react';
import {DefaultRoute, NotFoundRoute, Route} from 'react-router';
export default (
<Route handler={App} path="/">
<DefaultRoute handler={SearchPageRoute} name="search" />
<NotFoundRoute handler={NotFound} name="not-found" />
<Route handler={Todos} name="todos" />
</Route>
);
|
app/javascript/mastodon/features/compose/containers/sensitive_button_container.js | riku6460/chikuwagoddon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import IconButton from '../../../components/icon_button';
import { changeComposeSensitivity } from '../../../actions/compose';
import Motion from '../../ui/util/optional_motion';
import spring from 'react-motion/lib/spring';
import { injectIntl, defineMessages } from 'react-intl';
const messages = defineMessages({
marked: { id: 'compose_form.sensitive.marked', defaultMessage: 'Media is marked as sensitive' },
unmarked: { id: 'compose_form.sensitive.unmarked', defaultMessage: 'Media is not marked as sensitive' },
});
const mapStateToProps = state => ({
visible: state.getIn(['compose', 'media_attachments']).size > 0,
active: state.getIn(['compose', 'sensitive']),
disabled: state.getIn(['compose', 'spoiler']),
});
const mapDispatchToProps = dispatch => ({
onClick () {
dispatch(changeComposeSensitivity());
},
});
class SensitiveButton extends React.PureComponent {
static propTypes = {
visible: PropTypes.bool,
active: PropTypes.bool,
disabled: PropTypes.bool,
onClick: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
render () {
const { visible, active, disabled, onClick, intl } = this.props;
return (
<Motion defaultStyle={{ scale: 0.87 }} style={{ scale: spring(visible ? 1 : 0.87, { stiffness: 200, damping: 3 }) }}>
{({ scale }) => {
const icon = active ? 'eye-slash' : 'eye';
const className = classNames('compose-form__sensitive-button', {
'compose-form__sensitive-button--visible': visible,
});
return (
<div className={className} style={{ transform: `scale(${scale})` }}>
<IconButton
className='compose-form__sensitive-button__icon'
title={intl.formatMessage(active ? messages.marked : messages.unmarked)}
icon={icon}
onClick={onClick}
size={18}
active={active}
disabled={disabled}
style={{ lineHeight: null, height: null }}
inverted
/>
</div>
);
}}
</Motion>
);
}
}
export default connect(mapStateToProps, mapDispatchToProps)(injectIntl(SensitiveButton));
|
app/components/ui/UserProfile.js | feat7/OurGroup | 'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
View,
Text,
Alert,
Button
} from 'react-native';
import { Actions } from 'react-native-router-flux'
const FBSDK = require('react-native-fbsdk');
const {
GraphRequest,
GraphRequestManager,
} = FBSDK;
class UserProfile extends Component {
constructor() {
super();
this.state = {
userData: {
id: "",
name: ""
},
groupData: {
}
}
this._responseInfoCallback = this._responseInfoCallback.bind(this)
this._responseGroupCallback = this._responseGroupCallback.bind(this)
this.getUserData = this.getUserData.bind(this)
this.getGroupData = this.getGroupData.bind(this)
this.getUserData();
this.getGroupData();
}
//getters
getUserData() {
const infoRequest = new GraphRequest(
'/me',
{
parameters: {
fields: {
string: 'email,name,first_name,middle_name,last_name,birthday'
}
}
},
this._responseInfoCallback,
);
new GraphRequestManager().addRequest(infoRequest).start();
}
getGroupData() {
const infoRequest = new GraphRequest(
'/586400221495560/feed',
{
parameters: {
fields: {
string: 'attachments,message'
}
}
},
this._responseGroupCallback,
);
new GraphRequestManager().addRequest(infoRequest).start();
}
//Callbacks
_responseInfoCallback(error: ?Object, result: ?Object) {
if (error) {
alert('Error fetching data: ' + JSON.stringify(error));
} else {
this.setState({
userData: result
})
// Alert.alert('Success fetching data: ' + JSON.stringify(result));
}
}
_responseGroupCallback(error: ?Object, result: ?Object) {
if (error) {
alert('Error fetching data: ' + JSON.stringify(error));
} else {
this.setState({
groupData: result
})
console.log(this.state)
// Alert.alert('Success fetching data: ' + JSON.stringify(result));
}
}
componentWillMount() {
}
componentDidMount() {
}
render() {
const goToFeedList = () => Actions.FeedList({state: this.state});
return (
<View style={styles.container}>
<Text style={styles.title}>{this.state.userData.name}!</Text>
<Text style={styles.text}>Logged In successfully! with id {this.state.userData.id}</Text>
<Button onPress={goToFeedList}
title="React Native Community"
color="#841584"
></Button>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
backgroundColor: '#27ae60',
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
title: {
fontWeight: 'normal',
fontSize: 25,
color: '#fff'
},
text: {
color: '#fff',
padding: 2,
},
btn: {
color: '#fff',
backgroundColor: '#ff0000'
},
button: {
}
});
export default UserProfile; |
src/svg-icons/image/grid-on.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageGridOn = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zM8 20H4v-4h4v4zm0-6H4v-4h4v4zm0-6H4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4zm6 12h-4v-4h4v4zm0-6h-4v-4h4v4zm0-6h-4V4h4v4z"/>
</SvgIcon>
);
ImageGridOn = pure(ImageGridOn);
ImageGridOn.displayName = 'ImageGridOn';
ImageGridOn.muiName = 'SvgIcon';
export default ImageGridOn;
|
src/app/components/player-artwork.js | pashist/soundcloud-like-player | import React from 'react';
import PlayerArtworkFollow from './player-artwork-follow';
export default class PlayerArtwork extends React.Component {
render() {
let size = window.window.devicePixelRatio > 1 ? '500x500' : '200x200';
let imgUrl = this.getImageUrl(size);
return (
<div className="artwork">
<div className="image" style={{backgroundImage:`url(${imgUrl})`}}></div>
{this.props.showFollowButton && <PlayerArtworkFollow />}
</div>
)
}
getImageUrl(size = '200x200') {
const defaultUrl = 'http://a1.sndcdn.com/images/default_artwork_large.png';
let url;
if (this.props.track) {
url = this.props.track.artwork_url || this.props.track.user.avatar_url;
if (url) {
url = url.replace(/large\./, `t${size}.`);
}
}
return url || defaultUrl;
}
} |
examples/real-world/routes.js | dieface/redux | import React from 'react'
import { Route } from 'react-router'
import App from './containers/App'
import UserPage from './containers/UserPage'
import RepoPage from './containers/RepoPage'
export default (
<Route path="/" component={App}>
<Route path="/:login/:name"
component={RepoPage} />
<Route path="/:login"
component={UserPage} />
</Route>
)
|
src/index.js | kaifn/kaifn-page | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
docs/src/app/components/pages/components/Menu/Page.js | verdan/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import menuReadmeText from './README';
import MenuExampleSimple from './ExampleSimple';
import menuExampleSimpleCode from '!raw!./ExampleSimple';
import MenuExampleDisable from './ExampleDisable';
import menuExampleDisableCode from '!raw!./ExampleDisable';
import MenuExampleIcons from './ExampleIcons';
import menuExampleIconsCode from '!raw!./ExampleIcons';
import MenuExampleSecondary from './ExampleSecondary';
import menuExampleSecondaryCode from '!raw!./ExampleSecondary';
import MenuExampleNested from './ExampleNested';
import menuExampleNestedCode from '!raw!./ExampleNested';
import menuCode from '!raw!material-ui/Menu/Menu';
import menuItemCode from '!raw!material-ui/MenuItem/MenuItem';
const descriptions = {
simple: 'Two simple examples. The menu widths adjusts to accommodate the content in keyline increments.',
disabled: 'The `disabled` property disables a `MenuItem`. ' +
'`Menu` supports a more compact vertical spacing using the `desktop` property. ' +
'The [Divider](/#/components/divider) can be used to separate `MenuItems`.',
icons: '`MenuItem` supports icons through the `leftIcon` and `rightIcon` properties.',
secondary: '`MenuItem` supports a `secondaryText` property.',
nested: 'Cascading menus can be configured using the `menuItems` property of the `MenuItem` component.',
};
const MenuPage = () => (
<div>
<Title render={(previousTitle) => `Menu - ${previousTitle}`} />
<MarkdownElement text={menuReadmeText} />
<CodeExample
title="Simple examples"
description={descriptions.simple}
code={menuExampleSimpleCode}
>
<MenuExampleSimple />
</CodeExample>
<CodeExample
title="Disabled items"
description={descriptions.disabled}
code={menuExampleDisableCode}
>
<MenuExampleDisable />
</CodeExample>
<CodeExample
title="Icons"
description={descriptions.icons}
code={menuExampleIconsCode}
>
<MenuExampleIcons />
</CodeExample>
<CodeExample
title="Secondary text"
description={descriptions.secondary}
code={menuExampleSecondaryCode}
>
<MenuExampleSecondary />
</CodeExample>
<CodeExample
title="Nested menus"
description={descriptions.nested}
code={menuExampleNestedCode}
>
<MenuExampleNested />
</CodeExample>
<PropTypeDescription header="### Menu Properties" code={menuCode} />
<PropTypeDescription header="### MenuItem Properties" code={menuItemCode} />
</div>
);
export default MenuPage;
|
src/components/auth/signout.js | ercekal/client-side-auth-react | import React, { Component } from 'react';
import { connect } from 'react-redux';
import * as actions from '../../actions'
class Signout extends Component {
componentWillMount(){
this.props.signoutUser();
}
render() {
return <div>See you soon!</div>;
}
}
export default connect(null, actions)(Signout);
|
packages/base-shell/src/providers/SimpleValues/with.js | TarikHuber/react-most-wanted | import Context from './Context'
import React from 'react'
const withContainer = (Component) => {
const ChildComponent = (props) => {
return (
<Context.Consumer>
{(values) => {
return <Component {...values} {...props} />
}}
</Context.Consumer>
)
}
return ChildComponent
}
export default withContainer
|
admin/client/components/Navigation/PrimaryNavigation.js | Tangcuyu/keystone | import React from 'react';
import { Container } from 'elemental';
var PrimaryNavItem = React.createClass({
displayName: 'PrimaryNavItem',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
href: React.PropTypes.string.isRequired,
label: React.PropTypes.string,
title: React.PropTypes.string,
},
render () {
return (
<li className={this.props.className} data-section-label={this.props.label}>
<a href={this.props.href} title={this.props.title} tabIndex="-1">
{this.props.children}
</a>
</li>
);
},
});
var PrimaryNavigation = React.createClass({
displayName: 'PrimaryNavigation',
propTypes: {
brand: React.PropTypes.string,
currentSectionKey: React.PropTypes.string,
sections: React.PropTypes.array.isRequired,
signoutUrl: React.PropTypes.string,
},
getInitialState () {
return {};
},
componentDidMount () {
this.handleResize();
window.addEventListener('resize', this.handleResize);
},
componentWillUnmount () {
window.removeEventListener('resize', this.handleResize);
},
handleResize () {
this.setState({
navIsVisible: window.innerWidth >= 768,
});
},
renderSignout () {
if (!this.props.signoutUrl) return null;
return (
<PrimaryNavItem label="octicon-sign-out" href={this.props.signoutUrl} title="Sign Out">
<span className="octicon octicon-sign-out" />
</PrimaryNavItem>
);
},
renderFrontLink () {
return (
<ul className="app-nav app-nav--primary app-nav--right">
<PrimaryNavItem label="octicon-globe" href={Keystone.backUrl} title={'Front page - ' + this.props.brand}>
<span className="octicon octicon-globe" />
</PrimaryNavItem>
{this.renderSignout()}
</ul>
);
},
renderBrand () {
// TODO: support navbarLogo from keystone config
return (
<PrimaryNavItem label="octicon-home" className={this.props.currentSectionKey === 'dashboard' ? 'active' : null} href={Keystone.adminPath} title={'Dashboard - ' + this.props.brand}>
<span className="octicon octicon-home" />
</PrimaryNavItem>
);
},
renderNavigation () {
if (!this.props.sections || !this.props.sections.length) return null;
return this.props.sections.map((section) => {
const href = section.lists[0].external ? section.lists[0].path : `${Keystone.adminPath}/${section.lists[0].path}`;
const className = (this.props.currentSectionKey && this.props.currentSectionKey === section.key) ? 'active' : null;
return (
<PrimaryNavItem key={section.key} label={section.label} className={className} href={href}>
{section.label}
</PrimaryNavItem>
);
});
},
render () {
if (!this.state.navIsVisible) return null;
return (
<nav className="primary-navbar">
<Container clearfix>
<ul className="app-nav app-nav--primary app-nav--left">
{this.renderBrand()}
{this.renderNavigation()}
</ul>
{this.renderFrontLink()}
</Container>
</nav>
);
},
});
module.exports = PrimaryNavigation;
|
src/ctl/ui/src/components/HelpTooltip.js | m3db/m3db | import React from 'react';
import {Popover, Icon} from 'antd';
import {getHelpText} from '../utils/helpText';
export default function HelpTooltip({helpTextKey, title, ...rest}) {
return (
<Popover
title={title}
content={<div style={{maxWidth: 200}}>{getHelpText(helpTextKey)}</div>}
trigger="click"
{...rest}>
<Icon
style={{cursor: 'pointer', color: 'rgba(0,0,0,0.3)'}}
type="question-circle-o"
/>
</Popover>
);
}
|
test/tools/renderPage.js | nerdchacha/react-hoverintent | import { mount } from 'enzyme'
import React from 'react'
function renderPage (component) {
return mount(
<div>
{component}
</div>
)
}
module.exports = renderPage
|
src/index.js | aryalprakash/omgyoutube | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import { createStore, applyMiddleware } from 'redux'
import Main from './Components/Main';
import App from './Components/App';
import Home from './Components/Home';
import Watch from './Components/Watch';
import Movie from './Components/Movie';
import MovieTorrents from './Components/MovieTorrents';
import Search from './Components/Search';
import Channel from './Components/Channel.js'
import Playlist from './Components/Playlist.js'
import Collection from './Components/Collection.js'
import PlayMenu from './Components/PlayMenu.js'
import Youtube from './reducers/reducer.js';
import { render } from 'react-dom';
import { Router, Route, Link, browserHistory, hashHistory, useRouterHistory } from 'react-router';
import { createHashHistory } from 'history'
import thunk from 'redux-thunk'
import Helmet from "react-helmet";
require("../css/style.css");
const store = createStore(
Youtube,
applyMiddleware(thunk)
);
//const appHistory = useRouterHistory(createHashHistory)({ queryKey: false })
render((
<Provider store={store}>
<div className="main">
<div className="header">
</div>
<div className="center">
<div className="">
<Router history={browserHistory}>
<Route name="main" component={Main}>
<Route path="/" component={App} />
<Route path="/watch/v=:videoID" component={Watch}/>
<Route path="/movie/v=:videoID" component={Movie}/>
<Route path="/search/:query" component={Search}/>
<Route path="/movie-torrents" component={MovieTorrents}/>
<Route path="/channel/:channel/:type" component={Channel}/>
<Route path="/playlist/:playlist" component={Playlist}/>
<Route path="/collection/:collection/:playlist" component={Collection}/>
<Route name="playmenu" path="/playmenu" component={PlayMenu}/>
<Route path="*" component={Home}/>
</Route>
</Router>
</div>
</div>
<div className="footer">
<div className="footer-content">Made with <a href="/#/search/love">{'<'}3</a> in <a className="channel-link" href="/#/search/Nepal">Nepal</a></div>
<div className="social-links">
<a href="https://facebook.com/OMGYoutubeApp" target="_blank" title="Like us on Facebook"><div className="social facebook"><img src="/img/facebook.png" width="100%" /></div></a>
<a href="https://twitter.com/OMGYoutubeApp" target="_blank" title="Follow us on Twitter"> <div className="social twitter"><img src="/img/twitter.png" width="100%" /></div></a>
<a href="https://instagram.com/OMGYoutubeApp" target="_blank" title="Follow us on Instagram"> <div className="social instagram"><img src="/img/instagram.png" width="100%" /></div></a>
</div>
</div>
</div>
</Provider>), document.getElementById('root'))
//ReactDOM.render(<App />, document.getElementById('root'));
|
containers/OrderList.js | goominc/goommerce-seller-native | 'use strict';
import React from 'react';
import { ListView, StyleSheet, Text, View } from 'react-native';
import { connect } from 'react-redux';
import { orderActions } from 'goommerce-redux';
import _ from 'lodash';
import EmptyView from '../components/EmptyView';
import OrderCell from '../components/OrderCell';
import RefreshableList from '../components/RefreshableList';
import RefreshableView from '../components/RefreshableView';
import routes from '../routes';
const OrderList = React.createClass({
dataSource: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
}),
onSelect(order) {
const { brandId, push, status, updateBrandOrderStatus } = this.props;
const title = `링크# ${order.orderName || _.padStart(order.id, 3, '0').substr(-3)} 주문내역`;
if (status === 'new' && _.find(order.orderProducts, { status: 100 })) {
updateBrandOrderStatus(brandId, order.id, 100, 101).then(
() => push(routes.order(title, { brandId, orderId: order.id }))
);
} else {
push(routes.order(title, { brandId, orderId: order.id }));
}
},
renderRow(order, sectionID, rowID, highlightRow) {
const { onSelect, status } = this.props;
return (
<OrderCell
key={order.id}
order={order}
status={status}
onHighlight={() => highlightRow(sectionID, rowID)}
onUnhighlight={() => highlightRow(null, null)}
onSelect={() => (onSelect ? onSelect(order) : this.onSelect(order))}
/>
);
},
renderSectionHeader(sectionData, sectionID) {
return (
<View style={styles.section}>
<Text style={[styles.sectionText, { width: 60 }]}>
주문자명
</Text>
<Text style={[styles.sectionText, { flex: 1 }]}>
주문내용
</Text>
<Text style={[styles.sectionText, { width: 60 }]}>
날짜
</Text>
</View>
);
},
renderSeparator(sectionID, rowID, adjacentRowHighlighted) {
var style = styles.rowSeparator;
if (adjacentRowHighlighted) {
style = [style, styles.rowSeparatorHide];
}
return (
<View key={'SEP_' + sectionID + '_' + rowID} style={style}/>
);
},
render() {
const { orders, status, onRefresh } = this.props;
if (_.isEmpty(orders)) {
const text = _.get({
new: '신규주문이 없습니다.',
ready: '포장완료된 주문이 없습니다.',
awaiting: '입금대기 주문이 없습니다.',
}, status, '주문이 없습니다');
return (
<RefreshableView onRefresh={() => onRefresh && onRefresh()} contentContainerStyle={{ flex: 1 }}>
<EmptyView text={text} />
</RefreshableView>
);
}
// FIXME: possible performance issue...
const dataSource = this.dataSource.cloneWithRows(orders);
return (
<RefreshableList
dataSource={dataSource}
renderRow={this.renderRow}
renderSectionHeader={this.renderSectionHeader}
renderSeparator={this.renderSeparator}
onRefresh={() => onRefresh && onRefresh()}
/>
);
},
});
const styles = StyleSheet.create({
rowSeparator: {
backgroundColor: 'rgba(0, 0, 0, 0.1)',
height: 1,
},
rowSeparatorHide: {
opacity: 0.0,
},
scrollSpinner: {
marginVertical: 20,
},
section: {
flexDirection: 'row',
alignItems: 'center',
borderBottomWidth: 1,
borderBottomColor: 'rgba(0, 0, 0, 0.1)',
backgroundColor: 'white',
paddingVertical: 7,
paddingHorizontal: 12,
},
sectionText: {
fontSize: 11,
color: '#4C4C4C',
textAlign: 'center',
},
});
export default connect(null, orderActions)(OrderList);
|
server/sonar-web/src/main/js/components/controls/Favorite.js | lbndev/sonarqube | /*
* SonarQube
* Copyright (C) 2009-2017 SonarSource SA
* mailto:info 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 FavoriteBase from './FavoriteBase';
import { addFavorite, removeFavorite } from '../../api/favorites';
export default class Favorite extends React.Component {
static propTypes = {
favorite: React.PropTypes.bool.isRequired,
component: React.PropTypes.string.isRequired,
className: React.PropTypes.string
};
render() {
const { favorite, component, ...other } = this.props;
return (
<FavoriteBase
{...other}
favorite={favorite}
addFavorite={() => addFavorite(component)}
removeFavorite={() => removeFavorite(component)}
/>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.