path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/YearView.js | Kotuhan/react-date-picker | import React from 'react'
import { findDOMNode } from 'react-dom'
import Component from 'react-class'
import assign from 'object-assign'
import times from './utils/times'
import join from './join'
import toMoment from './toMoment'
import { Flex, Item } from 'react-flex'
import bemFactory from './bemFactory'
const bem = bemFactory('react-date-picker__year-view')
import {
prepareDateProps,
getInitialState,
onKeyDown,
onViewDateChange,
onActiveDateChange,
onChange,
navigate,
select,
confirm,
gotoViewDate
} from './DecadeView'
const NAV_KEYS = {
ArrowUp(mom) {
if (mom.get('month') >= 4) {
mom.add(-4, 'month')
}
return mom
},
ArrowDown(mom) {
if (mom.get('month') <= 7) {
mom.add(4, 'month')
}
return mom
},
ArrowLeft(mom) {
if (mom.get('month') >= 1) {
mom.add(-1, 'month')
}
return mom
},
ArrowRight(mom) {
if (mom.get('month') <= 10) {
mom.add(1, 'month')
}
return mom
},
Home(mom) {
return mom.startOf('year').startOf('month')
},
End(mom) {
return mom.endOf('year').startOf('month')
},
PageUp(mom) {
const month = mom.get('month') - 4
const extra4 = month - 4
if (month >= 0) {
if (extra4 >= 0) {
return mom.set('month', extra4)
}
return mom.set('month', month)
}
return mom
},
PageDown(mom) {
const month = mom.get('month') + 4
const extra4 = month + 4
if (month <= 11) {
if (extra4 <= 11) {
return mom.set('month', extra4)
}
return mom.set('month', month)
}
return mom
}
}
export default class YearView extends Component {
constructor(props) {
super(props)
this.state = getInitialState(props)
}
/**
* Returns all the days in the specified month.
*
* @param {Moment/Date/Number} value
* @return {Moment[]}
*/
getMonthsInYear(value) {
const start = this.toMoment(value).startOf('year')
return times(12).map(i => this.toMoment(start).add(i, 'month'))
}
toMoment(date) {
return toMoment(date, this.props)
}
render() {
const props = this.p = assign({}, this.props)
if (props.onlyCompareMonth) {
// props.adjustDateStartOf = null
}
const dateProps = prepareDateProps(props, this.state)
assign(props, dateProps)
const className = join(
'history-months-view',
props.className,
bem(),
props.theme && bem(null, `theme-${props.theme}`)
)
const monthsInView = this.getMonthsInYear(props.viewMoment)
const flexProps = assign({}, props)
delete flexProps.activeDate
delete flexProps.activeMoment
delete flexProps.adjustDateStartOf
delete flexProps.adjustMaxDateStartOf
delete flexProps.adjustMinDateStartOf
delete flexProps.cleanup
delete flexProps.constrainViewDate
delete flexProps.date
delete flexProps.dateFormat
delete flexProps.isYearView
delete flexProps.maxConstrained
delete flexProps.maxDate
delete flexProps.maxDateMoment
delete flexProps.minConstrained
delete flexProps.minDate
delete flexProps.minDateMoment
delete flexProps.moment
delete flexProps.monthFormat
delete flexProps.navKeys
delete flexProps.onActiveDateChange
delete flexProps.onViewDateChange
delete flexProps.onlyCompareMonth
delete flexProps.timestamp
delete flexProps.theme
delete flexProps.viewDate
delete flexProps.viewMoment
if (typeof props.cleanup == 'function') {
props.cleanup(flexProps)
}
return <Flex
inline
column
alignItems="stretch"
tabIndex={0}
{...flexProps}
onKeyDown={this.onKeyDown}
className={className}
>
{this.renderMonths(props, monthsInView)}
</Flex>
}
renderMonths(props, months) {
const nodes = months.map(monthMoment => this.renderMonth(props, monthMoment))
console.log('nodes', nodes);
const buckets = times(Math.ceil(nodes.length / 4)).map(i => {
return nodes.slice(i * 4, (i + 1) * 4)
})
const className = bem('row')
return buckets.map((bucket, i) => <Flex
alignItems="center"
flex
row
inline
key={`row_${i}`}
className={className}
>
{bucket}
</Flex>)
}
format(mom, format) {
format = format || this.props.monthFormat
return mom.format(format)
}
renderMonth(props, dateMoment) {
const index = dateMoment.get('month')
const monthText = props.monthNames ?
props.monthNames[index] || this.format(dateMoment) :
this.format(dateMoment)
const timestamp = +dateMoment
const isActiveDate = props.onlyCompareMonth && props.activeMoment ?
dateMoment.get('month') == props.activeMoment.get('month') :
timestamp === props.activeDate
const isValue = props.onlyCompareMonth && props.moment ?
dateMoment.get('month') == props.moment.get('month') :
timestamp === props.timestamp
const disabled = props.minDate != null && timestamp < props.minDate
||
props.maxDate != null && timestamp > props.maxDate
const className = join(
bem('month'),
!disabled && isActiveDate && bem('month', 'active'),
isValue && bem('month', 'value'),
disabled && bem('month', 'disabled')
)
const onClick = disabled ?
null :
this.handleClick.bind(this, {
dateMoment,
timestamp
})
return <Item
key={monthText}
className={className}
onClick={onClick}
>
<div className={'monthHistoryView'}>
{monthText}
</div>
</Item>
}
handleClick({ timestamp, dateMoment }, event) {
event.target.value = timestamp
this.select({ dateMoment, timestamp }, event)
}
onKeyDown(event) {
return onKeyDown.call(this, event)
}
confirm(date, event) {
return confirm.call(this, date, event)
}
navigate(direction, event) {
return navigate.call(this, direction, event)
}
select({ dateMoment, timestamp }, event) {
return select.call(this, { dateMoment, timestamp }, event)
}
onViewDateChange({ dateMoment, timestamp }) {
return onViewDateChange.call(this, { dateMoment, timestamp })
}
gotoViewDate({ dateMoment, timestamp }) {
return gotoViewDate.call(this, { dateMoment, timestamp })
}
onActiveDateChange({ dateMoment, timestamp }) {
return onActiveDateChange.call(this, { dateMoment, timestamp })
}
onChange({ dateMoment, timestamp }, event) {
return onChange.call(this, { dateMoment, timestamp }, event)
}
focus() {
findDOMNode(this).focus()
}
}
YearView.defaultProps = {
isYearView: true,
navKeys: NAV_KEYS,
constrainViewDate: true,
theme: 'default',
monthFormat: 'MMM',
dateFormat: 'YYYY-MM-DD',
onlyCompareMonth: true,
adjustDateStartOf: 'month',
adjustMinDateStartOf: 'month',
adjustMaxDateStartOf: 'month'
}
|
webpack/components/TemplateSyncResult/components/SyncedTemplate/StringInfoItem.js | mmoll/foreman_templates | import React from 'react';
import EllipsisWithTooltip from 'react-ellipsis-with-tooltip';
import PropTypes from 'prop-types';
import InfoItem from './InfoItem';
import { itemIteratorId } from './helpers';
const StringInfoItem = ({
template,
attr,
tooltipText,
translate,
mapAttr,
elipsed,
}) => {
const inner = (
<span>
{translate ? __(mapAttr(template, attr)) : mapAttr(template, attr)}
</span>
);
const innerContent = elipsed ? (
<EllipsisWithTooltip placement="top">{inner}</EllipsisWithTooltip>
) : (
inner
);
return (
<InfoItem itemId={itemIteratorId(template, attr)} tooltipText={tooltipText}>
{innerContent}
</InfoItem>
);
};
StringInfoItem.propTypes = {
template: PropTypes.object.isRequired,
attr: PropTypes.string.isRequired,
tooltipText: PropTypes.string,
translate: PropTypes.bool,
mapAttr: PropTypes.func,
elipsed: PropTypes.bool,
};
StringInfoItem.defaultProps = {
translate: false,
mapAttr: (template, attr) => template[attr],
elipsed: false,
tooltipText: undefined,
};
export default StringInfoItem;
|
src/svg-icons/content/unarchive.js | jacklam718/react-svg-iconx | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentUnarchive = (props) => (
<SvgIcon {...props}>
<path d="M20.55 5.22l-1.39-1.68C18.88 3.21 18.47 3 18 3H6c-.47 0-.88.21-1.15.55L3.46 5.22C3.17 5.57 3 6.01 3 6.5V19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V6.5c0-.49-.17-.93-.45-1.28zM12 9.5l5.5 5.5H14v2h-4v-2H6.5L12 9.5zM5.12 5l.82-1h12l.93 1H5.12z"/>
</SvgIcon>
);
ContentUnarchive = pure(ContentUnarchive);
ContentUnarchive.displayName = 'ContentUnarchive';
ContentUnarchive.muiName = 'SvgIcon';
export default ContentUnarchive;
|
src/index.js | Chewser/chewser_react | import React from 'react';
import ReactDom from 'react-dom';
import { Route, Router, browserHistory } from 'react-router';
import "./styles/style.css";
import Main from './components/Main/Main';
ReactDom.render(
<Router history={browserHistory}>
<Route path="/" component={Main} />
</Router>,
document.getElementById('app'));
|
src/components/MenuItem.js | TeemuTT/jyvaslounas-react | import React from 'react'
export function MenuItem({course, shouldDrawCategory}) {
return (
<div className="menuItem">
{shouldDrawCategory ? <span className="categoryName">{course.category}</span> : <span/>}
<span className="title_fi">{course.title_fi}</span>
<span>{course.desc_fi}</span>
<span>{course.price}</span>
<span>{course.properties}</span>
</div>
)
}
export default MenuItem
|
tests/lib/rules/vars-on-top.js | kentaromiura/eslint | /**
* @fileoverview Tests for vars-on-top rule.
* @author Danny Fritz
* @author Gyandeep Singh
* @copyright 2014 Danny Fritz. All rights reserved.
* @copyright 2014 Gyandeep Singh. All rights reserved.
*/
"use strict";
//------------------------------------------------------------------------------
// Requirements
//------------------------------------------------------------------------------
var rule = require("../../../lib/rules/vars-on-top"),
EslintTester = require("../../../lib/testers/rule-tester");
//------------------------------------------------------------------------------
// Tests
//------------------------------------------------------------------------------
var ruleTester = new EslintTester();
ruleTester.run("vars-on-top", rule, {
valid: [
[
"var first = 0;",
"function foo() {",
" first = 2;",
"}"
].join("\n"),
[
"function foo() {",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" if (true) {",
" first = true;",
" } else {",
" first = 1;",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" var third;",
" var fourth = 1, fifth, sixth = third;",
" var seventh;",
" if (true) {",
" third = true;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var i;",
" for (i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
[
"function foo() {",
" var outer;",
" function inner() {",
" var inner = 1;",
" var outer = inner;",
" }",
" outer = 1;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" //Hello",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" /*",
" Hello Clarice",
" */",
" var second = 1;",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var first;",
" first = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var second = 1;",
" function bar(){",
" var third;",
" third = 5;",
" }",
" first = second;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" var bar = function(){",
" var third;",
" third = 5;",
" }",
" first = 5;",
"}"
].join("\n"),
[
"function foo() {",
" var first;",
" first.onclick(function(){",
" var third;",
" third = 5;",
" });",
" first = 5;",
"}"
].join("\n"),
{
code: [
"function foo() {",
" var i = 0;",
" for (let j = 0; j < 10; j++) {",
" alert(j);",
" }",
" i = i + 1;",
"}"
].join("\n"),
ecmaFeatures: {
blockBindings: true
}
},
"'use strict'; var x; f();",
"'use strict'; 'directive'; var x; var y; f();",
"function f() { 'use strict'; var x; f(); }",
"function f() { 'use strict'; 'directive'; var x; var y; f(); }",
{code: "import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "'use strict'; import React from 'react'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import React from 'react'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import * as foo from 'mod.js'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { square, diag } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import { default as foo } from 'lib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }},
{code: "import theDefault, { named1, named2 } from 'src/mylib'; 'use strict'; var y; function f() { 'use strict'; var x; var y; f(); }", ecmaFeatures: { modules: true }}
],
invalid: [
{
code: [
"var first = 0;",
"function foo() {",
" first = 2;",
" second = 2;",
"}",
"var second = 0;"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" first = 1;",
" first = 2;",
" first = 3;",
" first = 4;",
" var second = 1;",
" second = 2;",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first;",
" if (true) {",
" var second = true;",
" }",
" first = second;",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" for (var i = 0; i < 10; i++) {",
" alert(i);",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" for (i = 0; i < first; i ++) {",
" var second = i;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" switch (first) {",
" case 10:",
" var hello = 1;",
" break;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" var hello = 1;",
" } catch (e) {",
" alert('error');",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" var i;",
" try {",
" asdf;",
" } catch (e) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" while (first) {",
" var hello = 1;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = 10;",
" do {",
" var hello = 1;",
" } while (first == 10);",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" for (var item in first) {",
" item++;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"function foo() {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: [
"var foo = () => {",
" var first = [1,2,3];",
" var item;",
" for (item in first) {",
" var hello = item;",
" }",
"}"
].join("\n"),
ecmaFeatures: { arrowFunctions: true },
errors: [
{
message: "All \"var\" declarations must be at the top of the function scope.",
type: "VariableDeclaration"
}
]
},
{
code: "'use strict'; 0; var x; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "'use strict'; var x; 'directive'; var y; f();",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; 0; var x; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
},
{
code: "function f() { 'use strict'; var x; 'directive'; var y; f(); }",
errors: [{message: "All \"var\" declarations must be at the top of the function scope.", type: "VariableDeclaration"}]
}
]
});
|
components/ui/settings/SettingsDividerLong.js | Jack3113/edtBordeaux | import React, { Component } from 'react';
import { StyleSheet, View } from 'react-native';
export default class SettingsDividerLong extends Component {
render() {
return <View style={styles.dividerStyle} />;
}
}
const styles = StyleSheet.create({
dividerStyle: {
width: '100%',
height: 1,
backgroundColor: 'rgb(220,220,223)',
},
});
|
packages/eslint-config-airbnb/test/test-react-order.js | practicefusion/javascript | import test from 'tape';
import { CLIEngine } from 'eslint';
import eslintrc from '../';
import reactRules from '../rules/react';
import reactA11yRules from '../rules/react-a11y';
const cli = new CLIEngine({
useEslintrc: false,
baseConfig: eslintrc,
rules: {
// It is okay to import devDependencies in tests.
'import/no-extraneous-dependencies': [2, { devDependencies: true }],
},
});
function lint(text) {
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeonfiles
// @see http://eslint.org/docs/developer-guide/nodejs-api.html#executeontext
const linter = cli.executeOnText(text);
return linter.results[0];
}
function wrapComponent(body) {
return `
import React from 'react';
export default class MyComponent extends React.Component {
/* eslint no-empty-function: 0, class-methods-use-this: 0 */
${body}
}
`;
}
test('validate react prop order', (t) => {
t.test('make sure our eslintrc has React and JSX linting dependencies', (t) => {
t.plan(2);
t.deepEqual(reactRules.plugins, ['react']);
t.deepEqual(reactA11yRules.plugins, ['jsx-a11y', 'react']);
});
t.test('passes a good component', (t) => {
t.plan(3);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
someMethod() {}
renderDogs() {}
render() { return <div />; }
`));
t.notOk(result.warningCount, 'no warnings');
t.notOk(result.errorCount, 'no errors');
t.deepEquals(result.messages, [], 'no messages in results');
});
t.test('order: when random method is first', (t) => {
t.plan(2);
const result = lint(wrapComponent(`
someMethod() {}
componentWillMount() {}
componentDidMount() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
t.test('order: when random method after lifecycle methods', (t) => {
t.plan(2);
const result = lint(wrapComponent(`
componentWillMount() {}
componentDidMount() {}
someMethod() {}
setFoo() {}
getFoo() {}
setBar() {}
renderDogs() {}
render() { return <div />; }
`));
t.ok(result.errorCount, 'fails');
t.equal(result.messages[0].ruleId, 'react/sort-comp', 'fails due to sort');
});
});
|
src/components/home.js | fiveinfinity/ic-crowdsale | import React from 'react';
import styles from '../stylesheets/home.css';
export const Home = (props) => {
return (
<div id="home" className={styles.home}>
<div className={styles.block}>
<div className={styles.title}>Peace of mind.</div>
<div className={styles.copy}>We want to make insurance easier. With the advent of the blockchain, we can give you insurance that you can trust. This is the only insurance that is autonomous, automatically processing claims, all with complete transparency.</div>
</div>
<div className={styles.block}>
<div className={styles.subtitle}>This is the future of insurance.</div>
</div>
</div>
);
};
|
examples/huge-apps/components/Dashboard.js | migolo/react-router | import React from 'react'
import { Link } from 'react-router'
class Dashboard extends React.Component {
render() {
const { courses } = this.props
return (
<div>
<h2>Super Scalable Apps</h2>
<p>
Open the network tab as you navigate. Notice that only the amount of
your app that is required is actually downloaded as you navigate
around. Even the route configuration objects are loaded on the fly.
This way, a new route added deep in your app will not affect the
initial bundle of your application.
</p>
<h2>Courses</h2>{' '}
<ul>
{courses.map(course => (
<li key={course.id}>
<Link to={`/course/${course.id}`}>{course.name}</Link>
</li>
))}
</ul>
</div>
)
}
}
export default Dashboard
|
app/javascript/mastodon/components/media_gallery.js | honpya/taketodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { is } from 'immutable';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from '../is_mobile';
import classNames from 'classnames';
import { autoPlayGif, displaySensitiveMedia } from '../initial_state';
const messages = defineMessages({
toggle_visible: { id: 'media_gallery.toggle_visible', defaultMessage: 'Toggle visibility' },
});
class Item extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
attachment: ImmutablePropTypes.map.isRequired,
standalone: PropTypes.bool,
index: PropTypes.number.isRequired,
size: PropTypes.number.isRequired,
onClick: PropTypes.func.isRequired,
};
static defaultProps = {
standalone: false,
index: 0,
size: 1,
};
handleMouseEnter = (e) => {
if (this.hoverToPlay()) {
e.target.play();
}
}
handleMouseLeave = (e) => {
if (this.hoverToPlay()) {
e.target.pause();
e.target.currentTime = 0;
}
}
hoverToPlay () {
const { attachment } = this.props;
return !autoPlayGif && attachment.get('type') === 'gifv';
}
handleClick = (e) => {
const { index, onClick } = this.props;
if (this.context.router && e.button === 0) {
e.preventDefault();
onClick(index);
}
e.stopPropagation();
}
render () {
const { attachment, index, size, standalone } = this.props;
let width = 50;
let height = 100;
let top = 'auto';
let left = 'auto';
let bottom = 'auto';
let right = 'auto';
if (size === 1) {
width = 100;
}
if (size === 4 || (size === 3 && index > 0)) {
height = 50;
}
if (size === 2) {
if (index === 0) {
right = '2px';
} else {
left = '2px';
}
} else if (size === 3) {
if (index === 0) {
right = '2px';
} else if (index > 0) {
left = '2px';
}
if (index === 1) {
bottom = '2px';
} else if (index > 1) {
top = '2px';
}
} else if (size === 4) {
if (index === 0 || index === 2) {
right = '2px';
}
if (index === 1 || index === 3) {
left = '2px';
}
if (index < 2) {
bottom = '2px';
} else {
top = '2px';
}
}
let thumbnail = '';
if (attachment.get('type') === 'image') {
const previewUrl = attachment.get('preview_url');
const previewWidth = attachment.getIn(['meta', 'small', 'width']);
const originalUrl = attachment.get('url');
const originalWidth = attachment.getIn(['meta', 'original', 'width']);
const hasSize = typeof originalWidth === 'number' && typeof previewWidth === 'number';
const srcSet = hasSize ? `${originalUrl} ${originalWidth}w, ${previewUrl} ${previewWidth}w` : null;
const sizes = hasSize ? `(min-width: 1025px) ${320 * (width / 100)}px, ${width}vw` : null;
const focusX = attachment.getIn(['meta', 'focus', 'x']) || 0;
const focusY = attachment.getIn(['meta', 'focus', 'y']) || 0;
const x = ((focusX / 2) + .5) * 100;
const y = ((focusY / -2) + .5) * 100;
thumbnail = (
<a
className='media-gallery__item-thumbnail'
href={attachment.get('remote_url') || originalUrl}
onClick={this.handleClick}
target='_blank'
>
<img
src={previewUrl}
srcSet={srcSet}
sizes={sizes}
alt={attachment.get('description')}
title={attachment.get('description')}
style={{ objectPosition: `${x}% ${y}%` }}
/>
</a>
);
} else if (attachment.get('type') === 'gifv') {
const autoPlay = !isIOS() && autoPlayGif;
thumbnail = (
<div className={classNames('media-gallery__gifv', { autoplay: autoPlay })}>
<video
className='media-gallery__item-gifv-thumbnail'
aria-label={attachment.get('description')}
role='application'
src={attachment.get('url')}
onClick={this.handleClick}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
autoPlay={autoPlay}
loop
muted
/>
<span className='media-gallery__gifv__label'>GIF</span>
</div>
);
}
return (
<div className={classNames('media-gallery__item', { standalone })} key={attachment.get('id')} style={{ left: left, top: top, right: right, bottom: bottom, width: `${width}%`, height: `${height}%` }}>
{thumbnail}
</div>
);
}
}
@injectIntl
export default class MediaGallery extends React.PureComponent {
static propTypes = {
sensitive: PropTypes.bool,
standalone: PropTypes.bool,
media: ImmutablePropTypes.list.isRequired,
size: PropTypes.object,
height: PropTypes.number.isRequired,
onOpenMedia: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
static defaultProps = {
standalone: false,
};
state = {
visible: !this.props.sensitive || displaySensitiveMedia,
};
componentWillReceiveProps (nextProps) {
if (!is(nextProps.media, this.props.media)) {
this.setState({ visible: !nextProps.sensitive });
}
}
handleOpen = () => {
this.setState({ visible: !this.state.visible });
}
handleClick = (index) => {
this.props.onOpenMedia(this.props.media, index);
}
handleRef = (node) => {
if (node /*&& this.isStandaloneEligible()*/) {
// offsetWidth triggers a layout, so only calculate when we need to
this.setState({
width: node.offsetWidth,
});
}
}
isStandaloneEligible() {
const { media, standalone } = this.props;
return standalone && media.size === 1 && media.getIn([0, 'meta', 'small', 'aspect']);
}
render () {
const { media, intl, sensitive, height } = this.props;
const { width, visible } = this.state;
let children;
const style = {};
if (this.isStandaloneEligible()) {
if (width) {
style.height = width / this.props.media.getIn([0, 'meta', 'small', 'aspect']);
}
} else if (width) {
style.height = width / (16/9);
} else {
style.height = height;
}
if (!visible) {
let warning;
if (sensitive) {
warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
} else {
warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
}
children = (
<button type='button' className='media-spoiler' onClick={this.handleOpen} style={style} ref={this.handleRef}>
<span className='media-spoiler__warning'>{warning}</span>
<span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span>
</button>
);
} else {
const size = media.take(4).size;
if (this.isStandaloneEligible()) {
children = <Item standalone onClick={this.handleClick} attachment={media.get(0)} />;
} else {
children = media.take(4).map((attachment, i) => <Item key={attachment.get('id')} onClick={this.handleClick} attachment={attachment} index={i} size={size} />);
}
}
return (
<div className='media-gallery' style={style} ref={this.handleRef}>
<div className={classNames('spoiler-button', { 'spoiler-button--visible': visible })}>
<IconButton title={intl.formatMessage(messages.toggle_visible)} icon={visible ? 'eye' : 'eye-slash'} overlay onClick={this.handleOpen} />
</div>
{children}
</div>
);
}
}
|
examples/components/LineExample.js | ionutmilica/react-chartjs-components | import React from 'react';
import { LineChart } from '../../src'
class LineExample extends React.Component {
render() {
const data = {
labels: ["January", "February", "March", "April", "May", "June", "July"],
datasets: [
{
label: "My First dataset",
fill: false,
lineTension: 0.1,
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
borderCapStyle: 'butt',
borderDash: [],
borderDashOffset: 0.0,
borderJoinStyle: 'miter',
pointBorderColor: "rgba(75,192,192,1)",
pointBackgroundColor: "#fff",
pointBorderWidth: 1,
pointHoverRadius: 5,
pointHoverBackgroundColor: "rgba(75,192,192,1)",
pointHoverBorderColor: "rgba(220,220,220,1)",
pointHoverBorderWidth: 2,
pointRadius: 1,
pointHitRadius: 10,
data: [65, 59, 80, 81, 56, 55, 40],
spanGaps: false,
}
]
};
return (
<LineChart data={data}/>
);
}
}
export default LineExample; |
src/app/components/list/Audit.js | cherishstand/OA-react | import React from 'react';
import {Tabs, Tab} from 'material-ui/Tabs';
import {List, ListItem} from 'material-ui/List';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import {Router, Route, browserHistory, Link} from 'react-router';
import SwipeableViews from 'react-swipeable-views';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import Setting from 'material-ui/svg-icons/action/settings';
import ArrowBaclIcon from 'material-ui/svg-icons/navigation/arrow-back';
import ContentInbox from 'material-ui/svg-icons/content/inbox';
import {blue600,blueGrey50,grey100,grey900} from 'material-ui/styles/colors';
import {dataList} from './data';
const styles = {
back:{
borderTop: '1px solid #5e95c9',
borderBottom: '1px solid #5e95c9',
borderRight: '1px solid #5e95c9',
overflow: 'hidden',
},
handline:{
fontSize: 24,
paddingTop: 16,
marginBottom: 12,
fontWeight: 400,
},
slide: {
padding: 10,
},
lable:{
'borderLeft': '1px solid #5e95c9',
position: 'relative',
zIndex: 10
},
bar:{
height:45,
backgroundColor: '#fff'
},
title:{
textAlign: 'center',
fontSize:18,
lineHeight:'45px',
color: grey900,
},
ink:{
height:50,
backgroundColor:'rgb(94, 149, 201)',
marginTop: -50,
},
boxback:{
backgroundColor: "#fff",
margin: '12px',
borderRadius: 4,
margin: 8
},
child:{
position: 'absolute',
left: 6,
top: 25
}
}
class Cell extends React.Component {
render(){
const { id , name, created_at, sales_price, sales_director} = this.props;
return(
<ListItem
key={id}
style={styles.boxback}
innerDivStyle={{padding: '6px 6px 6px 80px'}}
children={<span style={styles.child}>销售订单</span>}
primaryText={<p className="overflow">{id} ({name})</p>}
insetChildren={true}
secondaryText={
<p style={{color:'#7888af'}}>
{created_at} ¥{sales_price}<br />
{sales_director}
</p>
}
secondaryTextLines={2}
/>
)
}
}
class Audit extends React.Component {
constructor(props){
super(props);
this.state = {
slideIndex: 0,
data:[]
};
this.handleChange = this.handleChange.bind(this);
}
componentDidMount(){
this.setState({data: dataList.customer});
}
handleChange(value) {
this.setState({
slideIndex:value,
});
}
render() {
return (
<div style={{backgroundColor: '#efeef4'}}>
<div className="fiexded">
<AppBar
style={styles.bar}
title={<div style={styles.title}>审批中心</div>}
iconElementLeft={<Link to={browserHistory}><IconButton><ArrowBaclIcon color="#5e95c9"/></IconButton></Link>}
iconStyleLeft={{marginTop:0}}
/>
<Tabs onChange={this.handleChange} value={this.state.slideIndex} style={styles.back} inkBarStyle={styles.ink}>
<Tab label="已审批" value={0} style={styles.lable}/>
<Tab label="待审批" value={1} style={styles.lable}/>
<Tab label="近30天" value={2} style={styles.lable}/>
</Tabs>
</div>
<SwipeableViews index={this.state.slideIndex} onChangeIndex={this.handleChange} className='item_lists'>
<List>
{
this.state.data.map((item, index) => {
return <Cell {...item.basic} key={index}/>
})
}
</List>
<div style={styles.slide}>
</div>
<div style={styles.slide}>
</div>
</SwipeableViews>
</div>
)
}
}
export default Audit
|
client/src/App.js | Hypheme/harmonized.js-example | import React, { Component } from 'react';
import './App.css';
import Todos from './todos';
import Authors from './authors';
class App extends Component {
componentDidMount() {}
render() {
return (
<div className="App">
<div>
<Authors />
<Todos />
</div>
</div>
);
}
}
export default App;
|
src/svg-icons/image/hdr-off.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageHdrOff = (props) => (
<SvgIcon {...props}>
<path d="M17.5 15v-2h1.1l.9 2H21l-.9-2.1c.5-.2.9-.8.9-1.4v-1c0-.8-.7-1.5-1.5-1.5H16v4.9l1.1 1.1h.4zm0-4.5h2v1h-2v-1zm-4.5 0v.4l1.5 1.5v-1.9c0-.8-.7-1.5-1.5-1.5h-1.9l1.5 1.5h.4zm-3.5-1l-7-7-1.1 1L6.9 9h-.4v2h-2V9H3v6h1.5v-2.5h2V15H8v-4.9l1.5 1.5V15h3.4l7.6 7.6 1.1-1.1-12.1-12z"/>
</SvgIcon>
);
ImageHdrOff = pure(ImageHdrOff);
ImageHdrOff.displayName = 'ImageHdrOff';
ImageHdrOff.muiName = 'SvgIcon';
export default ImageHdrOff;
|
src/components/entity-crud/viewable/index.js | marcusnielsen/reactive-tournament | import React from 'react'
import {merge as objectMerge} from 'ramda'
import ConnectObserver from '../../../utils/connect-observer'
import EntityList from '../../entity-list/viewable'
import EntityForm from '../../entity-form/viewable'
import ViewState from './view-state'
import View from './view'
export default function create ({model}) {
const entityList = EntityList({model: model.children.entityList})
const entityForm_ = model.children.entityForm_
.map((entityFormModel) => {
return EntityForm({model: entityFormModel})
})
const children = {
entityList,
entityForm_
}
const viewState_ = ViewState({entityForm_})
const pureView = View({
React,
ListView: entityList.view
})
const view = ConnectObserver({
state_: viewState_,
view: pureView
})
const viewable = {
children,
viewState_,
pureView,
view
}
return objectMerge(model, viewable)
}
|
src/svg-icons/content/content-copy.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentContentCopy = (props) => (
<SvgIcon {...props}>
<path d="M16 1H4c-1.1 0-2 .9-2 2v14h2V3h12V1zm3 4H8c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h11c1.1 0 2-.9 2-2V7c0-1.1-.9-2-2-2zm0 16H8V7h11v14z"/>
</SvgIcon>
);
ContentContentCopy = pure(ContentContentCopy);
ContentContentCopy.displayName = 'ContentContentCopy';
ContentContentCopy.muiName = 'SvgIcon';
export default ContentContentCopy;
|
src/pages/build/index.js | chengjianhua/templated-operating-system | import React from 'react';
// import PropTypes from 'prop-types';
import { Provider } from 'mobx-react';
import { Route } from 'react-router-dom';
import Build from './Build';
import BuildStore from './model/BuildStore';
import StylesStore from '../../components/StyleWrapper/StylesStore';
const stylesStore = new StylesStore();
const buildStore = new BuildStore(stylesStore);
const stores = {
stylesStore,
buildStore,
};
function BuildRoot() {
return (
<Provider {...stores}>
<Route component={Build} />
</Provider>
);
}
// BuildRoot.propTypes = {
// children: PropTypes.element.isRequired,
// };
export default BuildRoot;
|
test/frontend/app/components/test-alert.js | LINKIWI/linkr | import React from 'react';
import {mount} from 'enzyme';
import test from 'tape';
import Alert, {ALERT_TYPE_ERROR} from '../../../../frontend/app/components/alert';
test('Alert renders failure message override', (t) => {
const alert = mount(
<Alert
type={ALERT_TYPE_ERROR}
title={'title'}
message={'overridden'}
failure={'failure'}
failureMessages={{
failure: 'failure message'
}}
/>
);
t.ok(alert.find('.alert').props().className.indexOf('alert alert-error text-red') !== -1,
'Alert error class is properly applied');
t.equal(alert.find('.alert-title').props().children, 'title', 'Title is rendered');
t.equal(alert.find('.alert-message').props().children, 'failure message',
'Failure message is rendered');
t.end();
});
test('Alert renders arbitrary messages as elements', (t) => {
const alert = mount(
<Alert
type={ALERT_TYPE_ERROR}
title={'title'}
message={<span>element</span>}
/>
);
t.ok(alert.find('.alert').props().className.indexOf('alert alert-error text-red') !== -1,
'Alert error class is properly applied');
t.equal(alert.find('.alert-title').props().children, 'title', 'Title is rendered');
t.equal(alert.find('.alert-message').childAt(0).props().children, 'element',
'Message element is rendered');
t.end();
});
test('Alert renders no message if not available', (t) => {
const alert = mount(
<Alert
type={ALERT_TYPE_ERROR}
title={'title'}
/>
);
t.ok(alert.find('.alert').props().className.indexOf('alert alert-error text-red') !== -1,
'Alert error class is properly applied');
t.equal(alert.find('.alert-title').props().children, 'title', 'Title is rendered');
t.notOk(alert.find('.alert-message').props().children, 'No message is displayed');
t.end();
});
|
src/icons/AndroidArrowBack.js | fbfeix/react-icons | import React from 'react';
import IconBase from './../components/IconBase/IconBase';
export default class AndroidArrowBack extends React.Component {
render() {
if(this.props.bare) {
return <g>
<g id="Icon_8_">
<g>
<path d="M427,234.625H167.296l119.702-119.702L256,85L85,256l171,171l29.922-29.924L167.296,277.375H427V234.625z"></path>
</g>
</g>
</g>;
} return <IconBase>
<g id="Icon_8_">
<g>
<path d="M427,234.625H167.296l119.702-119.702L256,85L85,256l171,171l29.922-29.924L167.296,277.375H427V234.625z"></path>
</g>
</g>
</IconBase>;
}
};AndroidArrowBack.defaultProps = {bare: false} |
resources/assets/js/components/responses/ResponsesComponent.js | jrm2k6/i-heart-reading | import React, { Component } from 'react';
class ResponsesComponent extends Component {
render() {
return (
<div style={{ flex: 1 }}>
{this.props.children}
</div>
);
}
}
export default ResponsesComponent;
|
cerberus-dashboard/src/components/CreateSDBoxForm/CreateSDBoxForm.js | Nike-Inc/cerberus-management-service | /*
* Copyright (c) 2020 Nike, inc.
*
* Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import { Component } from 'react';
import { connect } from 'react-redux';
import { reduxForm, touch } from 'redux-form';
import * as modalActions from '../../actions/modalActions';
import * as appActions from '../../actions/appActions';
import * as cNSDBActions from '../../actions/createSDBoxActions';
import CategorySelect from '../CategorySelect/CategorySelect';
import GroupsSelect from '../GroupSelect/GroupsSelect';
import validate from './validator';
import * as cms from '../../constants/cms';
import UserGroupPermissionsFieldSet from '../UserGroupPermissionsFieldSet/UserGroupPermissionsFieldSet';
import IamPrincipalPermissionsFieldSet from '../IamPrincipalPermissionsFieldSet/IamPrincipalPermissionsFieldSet';
import SDBDescriptionField from '../SDBDescriptionField/SDBDescriptionField';
import './CreateSDBoxForm.scss';
import { getLogger } from '../../utils/logger';
var log = getLogger('create-new-sdb');
const formName = 'create-new-sdb-form';
/**
* This is the smart component for the create new bucket page,
* This component contains the actual for and handle passing needed things into the dumb component views
*/
export const fields = [
'name',
'categoryId',
'description',
'owner',
'userGroupPermissions[].name',
'userGroupPermissions[].roleId',
'iamPrincipalPermissions[].iamPrincipalArn',
'iamPrincipalPermissions[].roleId'
];
class CreateSDBoxForm extends Component {
/**
* Force the domain data to load if it hasn't
*/
componentDidMount() {
if (!this.props.hasDomainDataLoaded) {
this.props.dispatch(appActions.fetchCmsDomainData(this.props.cerberusAuthToken));
}
}
render() {
const {
fields: {
name,
description,
categoryId,
owner,
userGroupPermissions,
iamPrincipalPermissions
},
categories,
handleSubmit,
isSubmitting,
hasDomainDataLoaded,
dispatch,
roles,
userGroups,
cerberusAuthToken
} = this.props;
// Lets not attempt to render everything until we have the data we need, when the domain data has loaded we can pass this
if (!hasDomainDataLoaded) {
return (<div></div>);
}
log.debug('Form props:\n' + JSON.stringify(this.props.fields, null, 2));
return (
<form id='new-sdbox-form' onSubmit={handleSubmit(data => {
dispatch(cNSDBActions.submitCreateNewSDB(data, cerberusAuthToken));
})}>
<div id="form-description" className="ncss-brand">
<h1>Create a New Safe Deposit Box</h1>
<h4>Fill out the below form to create a safe deposit box, where you can store properties securely.</h4>
</div>
<div id='name' className='ncss-form-group'>
<div className={((name.touched && name.error) ? 'ncss-input-container error' : 'ncss-input-container')}>
<label className='ncss-label'>Name</label>
<input type='text'
className='ncss-input pt2-sm pr4-sm pb2-sm pl4-sm'
placeholder='Enter an immutable name for your new Safe Deposit Box'
maxLength={`${cms.SDB_NAME_MAX_LENGTH}`}
{...name} />
{name.touched && name.error && <div className='ncss-error-msg'>{name.error}</div>}
</div>
</div>
<div id='top-section'>
<CategorySelect {...categoryId} categories={categories} handleBeingTouched={() => { dispatch(touch(formName, 'categoryId')); }} />
<div id="owner">
<label id="category-select-label" className='ncss-label'>Owner</label>
<GroupsSelect {...owner}
userGroups={userGroups}
allowCustomValues={false}
handleBeingTouched={() => {
dispatch(touch(formName, owner.name));
}} />
</div>
</div>
<SDBDescriptionField description={description} />
<UserGroupPermissionsFieldSet userGroupPermissions={userGroupPermissions}
dispatch={dispatch}
formName={formName}
userGroups={userGroups}
roles={roles} />
<IamPrincipalPermissionsFieldSet iamPrincipalPermissions={iamPrincipalPermissions}
dispatch={dispatch}
formName={formName}
roles={roles} />
<div id="submit-btn-container">
<div id='cancel-btn'
className='btn ncss-btn-accent ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
onClick={() => {
dispatch(modalActions.popModal());
}}>Cancel
</div>
<button id='submit-btn'
className='btn ncss-btn-dark-grey ncss-brand pt3-sm pr5-sm pb3-sm pl5-sm pt2-lg pb2-lg u-uppercase'
disabled={isSubmitting}>Submit
</button>
</div>
</form>
);
}
}
const mapStateToProps = state => ({
// user info
cerberusAuthToken: state.auth.cerberusAuthToken,
userGroups: state.auth.groups,
// domain data for the drop downs
hasDomainDataLoaded: state.app.cmsDomainData.hasLoaded,
categories: state.app.cmsDomainData.categories,
roles: state.app.cmsDomainData.roles,
// data for the form
isSubmitting: state.nSDB.isSubmitting,
initialValues: {
categoryId: state.nSDB.selectedCategoryId
}
});
const form = reduxForm({
form: formName,
fields: fields,
validate
})(CreateSDBoxForm);
export default connect(mapStateToProps)(form); |
postcss-with-react/appInit.js | sunitJindal/react-tutorial | import React from 'react';
import { render } from 'react-dom';
import Router from 'react-router/lib/Router';
import { createStore, applyMiddleware } from 'redux';
import { routerMiddleware } from 'react-router-redux';
import { Provider } from 'react-redux';
import thunkMiddleware from 'redux-thunk';
import { hashHistory as browserHistory } from 'react-router';
import routes from './app/routes';
import reducers from './app/reducers';
// Apply the middleware to the store
const reactRouterMiddleware = routerMiddleware(browserHistory);
// Add the reducer to your store on the `routing` key
const store = createStore(
reducers,
{},
applyMiddleware(
thunkMiddleware, // lets us dispatch() functions for API calls
reactRouterMiddleware // lets us dispatch() functions related to React-Router-Redux
)
);
render((
<Provider store={store}>
<Router
history={browserHistory}
>
{routes}
</Router>
</Provider>
), document.getElementById('container'));
|
examples/InputFields.js | jareth/react-materialize | import React from 'react';
import Input from '../src/Input';
import Row from '../src/Row';
export default
<Row>
<Input placeholder="Placeholder" s={6} label="First Name" />
<Input s={6} label="Last Name" />
<Input s={12} label="disabled" defaultValue="I am not editable" disabled />
<Input type="password" label="password" s={12} />
<Input type="email" label="Email" s={12} />
</Row>;
|
views/Service/nwdHttpClient.js | leechuanjun/TLRNProjectTemplate | 'use strict';
import React, { Component } from 'react';
import {
View,
AlertIOS,
} from 'react-native';
import NWDBaseHttp from './nwdBaseHttp';
import NWDService from './nwdService';
import NWDMacroDefine from '../Common/nwdMacroDefine';
var NWDHttpClient = {
nwdLogin: function(telephone, password, resultCallback) {
var where = '?telephone=' + telephone + '&password=' + password;
var url = NWDService.host + NWDService.login + where;
NWDBaseHttp.get(url, function(response){//{"code":"200","result":{"desc":"登录成功"}}
var code = response.code;
if (code == NWDMacroDefine._MD_Network_Success) {
resultCallback(NWDMacroDefine._MD_Result_Success);
}
else {
resultCallback(NWDMacroDefine._MD_Result_Failure);
}
}, function(err){
alert(err);
// resultCallback(NWDMacroDefine._MD_Result_Failure);
});
},
nwdRegister: function(username, telephone, password, resultCallback) {
var where = '?username=' + username + '&telephone=' + telephone + '&password=' + password;
var url = NWDService.host + NWDService.register + where;
NWDBaseHttp.get(url, function(response){
var code = response.code;
if (code == NWDMacroDefine._MD_Network_Success) {
resultCallback(NWDMacroDefine._MD_Result_Success);
}
else {
resultCallback(NWDMacroDefine._MD_Result_Failure);
}
}, function(err){
alert(err);
});
}
};
module.exports = NWDHttpClient;
|
packages/wix-style-react/src/Heading/Heading.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import Ellipsis, { extractEllipsisProps } from '../common/Ellipsis';
import { st, classes } from './Heading.st.css';
import { EllipsisCommonProps } from '../common/PropTypes/EllipsisCommon';
import { WixStyleReactContext } from '../WixStyleReactProvider/context';
export const APPEARANCES = {
H1: 'H1',
H2: 'H2',
H3: 'H3',
H4: 'H4',
H5: 'H5',
H6: 'H6',
};
const Heading = props => {
const { ellipsisProps, componentProps } = extractEllipsisProps(props);
const {
light,
appearance,
children,
dataHook,
...headingProps
} = componentProps;
return (
<WixStyleReactContext.Consumer>
{({ reducedSpacingAndImprovedLayout }) => (
<Ellipsis
{...ellipsisProps}
wrapperClassName={st(classes.root, { appearance })}
render={({ ref, ellipsisClasses }) =>
React.createElement(
appearance.toLowerCase(),
{
...headingProps,
ref,
'data-hook': dataHook,
className: st(
classes.root,
{ light, appearance, reducedSpacingAndImprovedLayout },
ellipsisClasses(props.className),
),
'data-appearance': appearance,
'data-light': light,
},
children,
)
}
/>
)}
</WixStyleReactContext.Consumer>
);
};
Heading.displayName = 'Heading';
Heading.propTypes = {
/** Applied as data-hook HTML attribute that can be used in the tests */
dataHook: PropTypes.string,
/** Any nodes to be rendered (usually text nodes) */
children: PropTypes.any,
/** Has dark or light skin */
light: PropTypes.bool,
/** Typography of the heading */
appearance: PropTypes.oneOf(Object.keys(APPEARANCES)),
...EllipsisCommonProps,
};
Heading.defaultProps = {
appearance: APPEARANCES.H1,
light: false,
...Ellipsis.defaultProps,
};
export default Heading;
|
src/components/FormFillView.js | dialob/dialob-fill-ui | /**
* Copyright 2016 ReSys OÜ
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import Page from './Page';
import * as ActionConstants from '../actions/ActionConstants';
import PropTypes from 'prop-types';
import {findItemById} from '../utils/formUtils';
import {connect} from 'react-redux';
class FormFillView extends React.Component {
static get propTypes() {
return {
status: PropTypes.string,
questionnaire: PropTypes.object,
activePageItem: PropTypes.array
};
}
render() {
const {questionnaire, activePageItem} = this.props;
let page = null;
let title = '';
if (questionnaire) {
title = questionnaire.get('label');
if (this.props.activePageItem) {
let availableItems = questionnaire.get('availableItems');
let isAllowedAction = action => questionnaire.get('allowedActions').includes(action);
let pageIndex = pageId => availableItems.findIndex(e => e === pageId);
let activeIndex = pageIndex(activePageItem[0]);
let showDisabled = !!questionnaire.getIn(['props', 'showDisabled']);
let prevPageLabel, nextPageLabel = undefined;
if (showDisabled) {
if (activeIndex > 0) {
prevPageLabel = this.props.itemById(availableItems.get(activeIndex - 1))[1].get('label');
}
if (activeIndex < availableItems.size - 1) {
nextPageLabel = this.props.itemById(availableItems.get(activeIndex + 1))[1].get('label');
}
}
let last = activeIndex == availableItems.size - 1;
let pageProps = {
page: activePageItem,
backEnabled: isAllowedAction(ActionConstants.PREVIOUS_PAGE),
forwardEnabled: isAllowedAction(ActionConstants.NEXT_PAGE),
completeEnabled: isAllowedAction(ActionConstants.COMPLETE_QUESTIONNAIRE) && last,
prevPageLabel,
nextPageLabel
};
page = <Page {...pageProps}/>;
}
}
if (this.props.status === 'UNLOADED') {
return (<div><i className='fa fa-spinner fa-spin fa-3x fa-fw'></i></div>);
} else {
return (
<div className='dialob-questionnaire'>
<span className='dialob-questionnaire-title'>{title}</span>
{page}
</div>
);
}
}
}
const FormFillViewConnected = connect(
state => {
return {
get itemById() { return itemId => findItemById(state.data, itemId) }
};
})(FormFillView);
export {
FormFillViewConnected as default,
FormFillView
}
|
docs/src/app/components/pages/components/TextField/ExampleError.js | IsenrichO/mui-with-arrows | import React from 'react';
import TextField from 'material-ui/TextField';
const TextFieldExampleError = () => (
<div>
<TextField
hintText="Hint Text"
errorText="This field is required"
/><br />
<TextField
hintText="Hint Text"
errorText="The error text can be as long as you want, it will wrap."
/><br />
<TextField
hintText="Hint Text"
errorText="This field is required"
floatingLabelText="Floating Label Text"
/><br />
<TextField
hintText="Message Field"
errorText="This field is required."
floatingLabelText="MultiLine and FloatingLabel"
multiLine={true}
rows={2}
/><br />
</div>
);
export default TextFieldExampleError;
|
client/src/javascript/components/icons/CalendarCreatedIcon.js | jfurrow/flood | import React from 'react';
import BaseIcon from './BaseIcon';
export default class CalendarCreatedIcon extends BaseIcon {
render() {
return (
<svg
className={`icon icon--calendar icon--calendar--created ${this.props.className}`}
viewBox={this.getViewBox()}>
<path d="M48,9.39V1.15H36V9.39H24.1V1.15h-12V9.39H4V58.85H56V9.39ZM40,5.29h4v7.28H40Zm-23.93,0h4v7.28h-4Zm33.38,48H9.9V16.91H49.5Z" />
<polygon points="42.88 32 33 32 33 22.12 27 22.12 27 32 17.12 32 17.12 38 27 38 27 47.88 33 47.88 33 38 42.88 38 42.88 32" />
</svg>
);
}
}
|
src/Components/Features/FeatureItems.js | michaelnagy/reactRing0 | import React from 'react'
import { Header, Icon, Grid } from 'semantic-ui-react'
const FeatureItems = () => (
<Grid columns={3} style={{marginTop:'5em', marginBottom:'5em'}}>
<Grid.Row>
<Grid.Column>
<Header as='h2' icon>
<Icon name='spy' circular color='teal'/>
15+ Heuristic databases
<Header.Subheader>
An extensive database constantly updated.
</Header.Subheader>
</Header>
</Grid.Column>
<Grid.Column>
<Header as='h2' icon>
<Icon name='refresh' circular color='teal' loading/>
20+ daily updates
<Header.Subheader>
We are amazingly fast taking care of bug and hack reports.
</Header.Subheader>
</Header>
</Grid.Column>
<Grid.Column>
<Header as='h2' icon>
<Icon name='angellist' circular color='teal'/>
100% free
<Header.Subheader>
We are free for life. Help us become a better team.
</Header.Subheader>
</Header>
</Grid.Column>
</Grid.Row>
</Grid>
)
export default FeatureItems
|
src/views/HomePage/component.js | khankuan/asset-library-demo | import React from 'react';
import Loading from '../../components/Loading';
import AssetGridView from '../../components/AssetGridView';
import DocumentTitle from 'react-document-title';
export default class HomePage extends React.Component {
static propTypes = {
HomePageStore: React.PropTypes.object,
AssetStore: React.PropTypes.object,
}
static contextTypes = {
alt: React.PropTypes.object.isRequired,
}
constructor(props) {
super(props);
}
_handleLikeChange = (asset, like) => {
if (like) {
this.context.alt.getActions('Asset').likeAsset(asset.id);
} else {
this.context.alt.getActions('Asset').unlikeAsset(asset.id);
}
}
render() {
const homePageStore = this.props.HomePageStore;
if (homePageStore.loading || !homePageStore.newestAssetIds) {
return (<Loading />);
}
const assetsMap = this.props.AssetStore.assets;
const newestAssetIds = homePageStore.newestAssetIds;
const audioAssets = newestAssetIds.audio.map(id => { return assetsMap[id]; });
const imageAssets = newestAssetIds.image.map(id => { return assetsMap[id]; });
return (
<div>
<DocumentTitle title="Welcome to Asset Library" />
<AssetGridView
name="Newest Audio"
assets={audioAssets}
onAssetLikeChange={ this._handleLikeChange } />
<AssetGridView
name="Newest Images"
assets={imageAssets}
onAssetLikeChange={ this._handleLikeChange } />
</div>
);
}
}
|
OleksiiOnSoftware.Apps.Blog/client/containers/DevTools/index.js | boades/PpmSystem | import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
const DevTools = createDevTools(
<DockMonitor
toggleVisibilityKey='ctrl-h'
changePositionKey='ctrl-q'
defaultIsVisible={false}
>
<LogMonitor theme='tomorrow' />
</DockMonitor>
)
export { DevTools }
|
UI/src/components/Groups.js | ssvictorlin/PI | import React, { Component } from 'react';
import { ScrollView, View, Image, Text, ActivityIndicator, ListView, TouchableHighlight } from 'react-native';
import { SearchBar, List, ListItem, Button, Icon } from 'react-native-elements';
import { StackNavigator } from 'react-navigation';
import { Card, CardSection } from './common';
import { get } from '../../api.js';
import firebase from 'firebase';
export default class Groups extends Component {
constructor(props) {
super(props);
this.state = {
groups: [],
loading: false,
hasTermInSearchBar: false,
term: '',
dataSource: null,
curUserName: null
};
this.groupList = [];
};
componentWillMount() {
this.fetchGroupsUserIn();
this.getCurUser();
var user = firebase.auth().currentUser;
this.fetchAllGroups(user.email);
}
fetchAllGroups = async (userEmail) => {
const response = await get('app/fetchAllGroups?userEmail=' + userEmail)
.then((response) => response.json())
.then((responseJson) => {
let ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
this.setState({
dataSource: ds.cloneWithRows(responseJson),
loading: false
}, function() {
// In this block you can do something with new state.
this.groupList = responseJson ;
});
})
.catch((error) => {
// handle error
});
}
getCurUser = async () => {
var user = firebase.auth().currentUser;
try {
const response = await get('app/readUser?userEmail=' + user.email);
const data = await response.json();
this.setState({
curUserName: data['userName']
});
}
catch(err) {
alert(err);
}
};
fetchGroupsUserIn = async () => {
this.setState({loading: true});
var user = firebase.auth().currentUser;
if (user == null) {
throw "user not signed in"
}
try {
const response = await get('app/fetchGroupsUserIn?userEmail=' + user.email);
const data = await response.json();
this.setState({
groups: data,
});
}
catch(err) {
alert(err);
}
};
SearchFilterFunction(term){
const newData = this.groupList.filter(function(item){
const itemData = item.groupName.toUpperCase()
const textData = term.toUpperCase()
return itemData.indexOf(textData) > -1
})
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newData),
term: term,
hasTermInSearchBar: true
})
if (term == '') {
this.setState({
hasTermInSearchBar: false
});
}
}
render() {
const { navigate } = this.props.navigation;
function CreateGroupList(props) {
const groups = props.groups;
if (groups.length != 0) {
const groupItems = groups.map((element, index) =>
<ListItem
key={index}
title={element.groupName}
avatar={{ uri: element.avatar }}
roundAvatar={true}
subtitle={element.objective}
onPress={() => navigate('GroupDetail', {
groupName: element.groupName,
groupEmail: element.groupEmail,
isJoined: true,
groupObjective: element.objective
})}
/>
);
return groupItems;
} else {
return (
<Text>You haven't joined any group!</Text>
);
}
}
function renderRow (rowData, sectionID) {
if (rowData.isJoined) {
return (
<ListItem
roundAvatar
key={sectionID}
title={rowData.groupName}
subtitle={rowData.subtitle}
avatar={{uri:rowData.avatar}}
rightTitle='Joined'
hideChevron={true}
onPress={() => navigate('GroupDetail', {
groupName: rowData.groupName,
groupEmail: rowData.groupEmail,
isJoind: rowData.isJoined,
groupObjective: rowData.groupObjective
})}
/>
)
} else {
return (
<ListItem
roundAvatar
key={sectionID}
title={rowData.groupName}
subtitle={rowData.subtitle}
avatar={{uri:rowData.avatar}}
rightTitle='Not Joined'
hideChevron={true}
onPress={() => navigate('GroupDetail', {
groupName: rowData.groupName,
groupEmail: rowData.groupEmail,
isJoind: rowData.isJoined,
groupObjective: rowData.groupObjective
})}
/>
)
}
}
if (this.state.loading == true) {
return (
<ActivityIndicator
animating={this.state.loading}
style={[styles.centering, {height: 80}]}
size="large"
/>
);
} else {
return (
<View style={{flex:1, backgroundColor: '#FFF'}}>
<ScrollView>
<SearchBar
lightTheme
onChangeText={(term) => this.SearchFilterFunction(term)}
placeholder='Search groups'
/>
{ this.state.hasTermInSearchBar
? <List>
<ListView
renderRow={renderRow}
dataSource={this.state.dataSource}
/>
</List>
: <CreateGroupList
groups={this.state.groups}
/>
}
</ScrollView>
<Icon
raised
name='plus'
type='font-awesome'
color='white'
size={30}
containerStyle={{backgroundColor: '#009973',
position: 'absolute',
alignSelf: 'flex-end',
bottom: 15,
right: 15}}
onPress={() => navigate('GroupForm')}
/>
</View>
);
}
}
}
const styles = {
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#FFF',
},
nameContainer: {
flexDirection: 'column',
justifyContent: 'space-around'
},
name: {
fontSize: 24
},
thumbnail: {
height: 80,
width: 80,
borderRadius: 50,
},
thumbnailContainer: {
justifyContent: 'center',
alignItems: 'center',
marginLeft: 10,
marginRight: 10
},
image: {
height: 300,
flex: 1,
width: null,
},
}
|
es6/main.js | Simproduction/react-client-webpack | import React from 'react';
import ReactDOM from 'react-dom';
import Hello from './component.jsx';
window.React = React;
window.ReactDom = React;
function main() {
ReactDOM.render(<Hello />, document.getElementById('app'));
}
main();
|
src/components/ContainerProgress.react.js | daaru00/kitematic | import React from 'react';
/*
Usage: <ContainerProgress pBar1={20} pBar2={70} pBar3={100} pBar4={20} />
*/
var ContainerProgress = React.createClass({
render: function () {
var pBar1Style = {
height: this.props.pBar1 + '%'
};
var pBar2Style = {
height: this.props.pBar2 + '%'
};
var pBar3Style = {
height: this.props.pBar3 + '%'
};
var pBar4Style = {
height: this.props.pBar4 + '%'
};
return (
<div className="container-progress">
<div className="bar-1 bar-bg">
<div className="bar-fg" style={pBar4Style}></div>
</div>
<div className="bar-2 bar-bg">
<div className="bar-fg" style={pBar3Style}></div>
</div>
<div className="bar-3 bar-bg">
<div className="bar-fg" style={pBar2Style}></div>
</div>
<div className="bar-4 bar-bg">
<div className="bar-fg" style={pBar1Style}></div>
</div>
</div>
);
}
});
module.exports = ContainerProgress;
|
example/example.js | goldenyz/react-perfect-scrollbar | import React, { Component } from 'react';
// eslint-disable-next-line
import ScrollBar from 'react-perfect-scrollbar';
// eslint-disable-next-line
import 'react-perfect-scrollbar/styles.scss';
import './example.scss';
function logEvent(type) {
console.log(`event '${type}' triggered!`);
}
const debounce = (fn, ms = 0) => {
let timeoutId;
return function wrapper(...args) {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => fn.apply(this, args), ms);
};
};
class Example extends Component {
constructor(props) {
super(props);
this.state = {
className: undefined,
onXReachEnd: null,
items: Array.from(new Array(100).keys()),
};
}
componentDidMount() {
setTimeout(() => {
this.setState({
className: 'dummy',
onXReachEnd: () => logEvent('onXReachEnd'),
});
}, 5000);
}
handleYReachEnd = () => {
logEvent('onYReachEnd');
}
handleTrigger = () => {
this.setState({
items: Array.from(new Array(100).keys()),
});
}
handleSync = debounce((ps) => {
ps.update();
console.log('debounce sync ps container in 1000ms');
}, 1000)
render() {
const { className, onXReachEnd } = this.state;
return (
<React.Fragment>
<div className="example">
<ScrollBar
className={className}
onScrollY={() => logEvent('onScrollY')}
onScrollX={() => logEvent('onScrollX')}
onScrollUp={() => logEvent('onScrollUp')}
onScrollDown={() => logEvent('onScrollDown')}
onScrollLeft={() => logEvent('onScrollLeft')}
onScrollRight={() => logEvent('onScrollRight')}
onYReachStart={() => logEvent('onYReachStart')}
onYReachEnd={this.handleYReachEnd}
onXReachStart={() => logEvent('onXReachStart')}
onXReachEnd={onXReachEnd}
component="div"
>
<div className="content" />
</ScrollBar>
</div>
<div className="example">
<button onClick={this.handleTrigger}>Trigger</button>
<ScrollBar onSync={this.handleSync}>
{this.state.items.map(e => (<div key={e}>{e}</div>))}
</ScrollBar>
</div>
</React.Fragment>
);
}
}
export default Example;
|
examples/03 - Basic auth/components/Dashboard.js | gilesvangruisen/browserify-react-live | import React from 'react';
import auth from '../vendor/auth';
export default class Dashboard extends React.Component {
render() {
var token = auth.getToken();
return (
<div>
<h1>Dashboard</h1>
<p>You made it!</p>
<p>{token}</p>
</div>
);
}
}
|
src/Parser/Warlock/Demonology/Modules/Features/AlwaysBeCasting.js | enragednuke/WoWAnalyzer | import React from 'react';
import CoreAlwaysBeCasting from 'Parser/Core/Modules/AlwaysBeCasting';
import SPELLS from 'common/SPELLS';
import { formatPercentage } from 'common/format';
import { STATISTIC_ORDER } from 'Main/StatisticBox';
import SpellLink from 'common/SpellLink';
import Wrapper from 'common/Wrapper';
class AlwaysBeCasting extends CoreAlwaysBeCasting {
get suggestionThresholds() {
return {
actual: this.downtimePercentage,
isGreaterThan: {
minor: 0.2,
average: 0.35,
major: 0.4,
},
style: 'percentage',
};
}
suggestions(when) {
when(this.suggestionThresholds)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<Wrapper>Your downtime can be improved. Try to Always Be Casting (ABC), try to reduce the delay between casting spells. Even if you have to move, try casting something instant - maybe refresh your dots or replenish your mana with <SpellLink id={SPELLS.LIFE_TAP.id} />. Make good use of your <SpellLink id={SPELLS.DEMONIC_CIRCLE_TALENT_TELEPORT.id} /> when you can.</Wrapper>)
.icon('spell_mage_altertime')
.actual(`${formatPercentage(actual)}% downtime`)
.recommended(`<${formatPercentage(recommended)}% is recommended`);
});
}
statisticOrder = STATISTIC_ORDER.CORE(1);
}
export default AlwaysBeCasting;
|
app/js/components/content/ListComponent.js | lukemarsh/tab-hq-react | 'use strict';
import React from 'react';
import ListItemComponent from './ListItemComponent';
import DropFileComponent from './DropFileComponent';
import ReorderMixin from '../../mixins/ReorderMixin';
import ModalMixin from '../../mixins/ModalMixin';
import PageComponentActions from './PageComponentActions';
import ComponentActionCreators from '../../actions/ComponentActionCreators';
import _ from 'lodash';
require('../../../styles/ListComponent.sass');
const ListComponent = React.createClass({
mixins: [ReorderMixin, ModalMixin],
getInitialState() {
return {
data: this.props.data
};
},
addLink() {
let elem = {
title: '',
url: '',
type: 'link',
order: this.state.data.links.length
};
let componentData = this.state.data;
componentData.links.push(elem);
this.updateComponent(componentData);
},
addLinkFromDrive(element, params) {
let elem = {
title: params.title,
url: params.url,
order: this.state.data.links.length,
size: params.size,
last_updated: params.last_updated,
extension: params.extension
};
let componentData = this.state.data;
componentData.links.push(elem);
this.updateComponent(componentData);
},
addImage() {
// console.log('add');
},
setDraggableData(links) {
let data = {
links: links
};
this.updateComponent(data);
},
updateComponent(componentData) {
ComponentActionCreators.updateComponent(this.props.componentId, {data: componentData});
},
delete(index) {
let componentData = this.state.data;
componentData.links.splice(index, 1);
this.updateComponent(componentData);
},
removeLink(index, item) {
let props = {
actions: this.delete.bind(this, index),
text: 'You are about to delete "' + item.title + '"'
};
ModalMixin.appendModalToBody(props);
},
updateListItem(index, listItemData) {
let componentData = this.state.data;
let links = componentData.links;
let fieldToUpdate;
let dataToUpdate;
_.forOwn(listItemData, (value, key) => {
fieldToUpdate = key;
dataToUpdate = value;
});
_.each(links, (link) => {
links[index][fieldToUpdate] = dataToUpdate;
});
this.updateComponent(componentData);
},
render() {
let links = this.state.data.links;
let component = this.props.component;
let userIsAdmin = this.props.userIsAdmin;
let classes = 'list';
if (userIsAdmin) {
classes += ' template';
}
this.loadDraggableData(this.props.data.links);
return (
<div className={classes} data-droppable='component' data-order={component.order} onDragOver={this.dragOver}>
<div onDrop={this.drop}>
<div className='files'>
{links.map((item, index) => {
return (<ListItemComponent key={index} updateListItem={this.updateListItem.bind(null, index)} dragStart={this.dragStart} dragEnd={this.dragEnd} mouseDown={this.mouseDown} item={item} onClick={this.removeLink.bind(null, index, item)} userIsAdmin={userIsAdmin}></ListItemComponent>);
}.bind(this))}
</div>
<DropFileComponent type={'link'} addLinkFromDrive={this.addLinkFromDrive} userIsAdmin={userIsAdmin} addImage={this.addImage} addLink={this.addLink}></DropFileComponent>
</div>
<PageComponentActions userIsAdmin={userIsAdmin} type={component.componentType} componentId={this.props.componentId} dragStart={this.props.dragStart} dragEnd={this.props.dragEnd} mouseDown={this.props.mouseDown} />
</div>
);
}
});
module.exports = ListComponent;
|
src/js/components/Avatar/stories/Basic.js | HewlettPackard/grommet | import React from 'react';
import { Favorite } from 'grommet-icons';
import { Avatar, Box, Grommet } from 'grommet';
import { grommet } from 'grommet/themes';
export const Basic = () => {
const src = '//s.gravatar.com/avatar/b7fb138d53ba0f573212ccce38a7c43b?s=80';
return (
<Grommet theme={grommet}>
<Box
align="center"
justify="center"
direction="row"
gap="small"
pad="large"
>
<Avatar src={src} />
<Avatar background="accent-4">
<Favorite color="accent-2" />
</Avatar>
<Avatar background="dark-2">R</Avatar>
<Avatar background="brand">SY</Avatar>
</Box>
</Grommet>
);
};
export default {
title: 'Visualizations/Avatar/Basic',
};
|
example/src/views/swipe_decker.js | kosiakMD/react-native-elements | import Expo from 'expo';
import React, { Component } from 'react';
import { StyleSheet, Text, View, Dimensions } from 'react-native';
import { Button, Card, Icon } from 'react-native-elements';
import { SwipeDeck } from 'react-native-elements';
const SCREEN_WIDTH = Dimensions.get('window').width;
const SCREEN_HEIGHT = Dimensions.get('window').height;
// test data
const DATA = [
{
id: 1,
text: 'Amanda',
age: 28,
uri: 'http://f9view.com/wp-content/uploads/2013/10/American-Beautiful-Girls-Wallpapers-Hollywood-Celebs-1920x1200px.jpg',
},
{ id: 2, text: 'Emma', age: 29, uri: 'https://i.imgur.com/FHxVpN4.jpg' },
{
id: 3,
text: 'Scarlett',
age: 25,
uri: 'https://i.ytimg.com/vi/GOJZ5TIlc3M/maxresdefault.jpg',
},
{
id: 4,
text: 'Keira',
age: 27,
uri: 'http://www.bdprimeit.com/wp-content/uploads/Keira-Knightley-Most-beautiful-Hollywood-actress.jpg',
},
{
id: 5,
text: 'Ashley',
age: 30,
uri: 'https://s-media-cache-ak0.pinimg.com/736x/4c/89/67/4c8967fac1822eeddf09670565430fd5.jpg',
},
{
id: 6,
text: 'Jennifer',
age: 24,
uri: 'https://2.bp.blogspot.com/-Vy0NVWhQfKo/Ubma2Mx2YTI/AAAAAAAAH3s/LC_u8LRfm8o/s1600/aimee-teegarden-04.jpg',
},
{
id: 7,
text: 'Sarah',
age: 28,
uri: 'https://s-media-cache-ak0.pinimg.com/736x/41/75/26/4175268906d97492e4a3175eab95c0f5.jpg',
},
];
class SwipeDecker extends Component {
renderCard(card) {
return (
<Card
key={card.id}
containerStyle={{
borderRadius: 10,
width: SCREEN_WIDTH * 0.92,
height: SCREEN_HEIGHT - 165,
}}
featuredTitle={`${card.text}, ${card.age}`}
featuredTitleStyle={{
position: 'absolute',
left: 15,
bottom: 10,
fontSize: 30,
}}
image={{ uri: card.uri }}
imageStyle={{
borderRadius: 10,
width: SCREEN_WIDTH * 0.915,
height: SCREEN_HEIGHT - 165,
}}
/>
);
}
onSwipeRight(card) {
console.log('Card liked: ' + card.text);
}
onSwipeLeft(card) {
console.log('Card disliked: ' + card.text);
}
renderNoMoreCards() {
return (
<Card
containerStyle={{
borderRadius: 10,
width: SCREEN_WIDTH * 0.92,
height: SCREEN_HEIGHT - 165,
}}
featuredTitle="No more cards"
featuredTitleStyle={{ fontSize: 25 }}
image={{ uri: 'https://i.imgflip.com/1j2oed.jpg' }}
imageStyle={{
borderRadius: 10,
width: SCREEN_WIDTH * 0.915,
height: SCREEN_HEIGHT - 165,
}}
/>
);
}
renderHeader() {
return (
<View style={styles.header}>
<View style={styles.headerLeftIcon}>
<Icon name="user" type="font-awesome" color="#ccc" size={35} />
</View>
<View style={styles.headerCenter}>
<View style={styles.headerCenterToggleContainer}>
<View style={styles.headerCenterToggleLeft}>
<Icon
name="fire"
type="material-community"
color="#fff"
size={28}
/>
</View>
<View style={styles.headerCenterToggleRight}>
<Icon name="group" type="font-awesome" color="#ccc" size={25} />
</View>
</View>
</View>
<View style={styles.headerRightIcon}>
<Icon name="comments" type="font-awesome" color="#ccc" size={35} />
</View>
</View>
);
}
renderFooter() {
return (
<View style={styles.footer}>
<View style={[styles.footerIcon, { paddingLeft: 10 }]}>
<Icon
containerStyle={{
backgroundColor: 'white',
width: 50,
height: 50,
borderRadius: 25,
}}
name="replay"
size={30}
color="orange"
/>
</View>
<View style={styles.footerIcon}>
<Icon
containerStyle={{
backgroundColor: 'white',
width: 60,
height: 60,
borderRadius: 30,
}}
name="close"
size={45}
color="red"
/>
</View>
<View style={styles.footerIcon}>
<Icon
containerStyle={{
backgroundColor: 'white',
width: 48,
height: 48,
borderRadius: 24,
}}
name="bolt"
type="font-awesome"
size={30}
color="purple"
/>
</View>
<View style={styles.footerIcon}>
<Icon
containerStyle={{
backgroundColor: 'white',
width: 60,
height: 60,
borderRadius: 30,
}}
name="favorite"
size={35}
color="green"
/>
</View>
<View style={[styles.footerIcon, { paddingRight: 10 }]}>
<Icon
containerStyle={{
backgroundColor: 'white',
width: 50,
height: 50,
borderRadius: 25,
}}
name="star"
size={30}
color="blue"
/>
</View>
</View>
);
}
render() {
return (
<View style={styles.container}>
{this.renderHeader()}
<View style={styles.deck}>
<SwipeDeck
data={DATA}
renderCard={this.renderCard}
renderNoMoreCards={this.renderNoMoreCards}
onSwipeRight={this.onSwipeRight}
onSwipeLeft={this.onSwipeLeft}
/>
</View>
{this.renderFooter()}
</View>
);
}
}
SwipeDecker.navigationOptions = {
title: 'Swipe Decker',
header: null,
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'rgba(211, 211, 211, 0.4)',
},
header: {
height: 64,
paddingTop: 35,
flexDirection: 'row',
},
headerLeftIcon: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
marginLeft: 15,
},
headerCenter: {
flex: 6,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
},
headerCenterToggleContainer: {
flexDirection: 'row',
width: 160,
height: 45,
borderRadius: 30,
borderWidth: 2,
borderColor: '#ccc',
},
headerCenterToggleLeft: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#ff0000',
borderRadius: 30,
},
headerCenterToggleRight: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
headerRightIcon: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
marginRight: 20,
},
deck: {
flex: 1,
},
footer: {
height: 64,
flexDirection: 'row',
paddingBottom: 10,
},
footerIcon: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
alignSelf: 'center',
margin: 10,
},
});
export default SwipeDecker;
|
imports/ui/components/customer/Customer.js | hwillson/shopify-hosted-payments | import React from 'react';
const shippingAddress = (payment) => {
let content = (<p>...</p>);
if (payment) {
content = (
<p>
{payment.x_customer_first_name} {payment.x_customer_last_name}
<br />
{payment.x_customer_shipping_address1}
<br />
{payment.x_customer_shipping_city}
{payment.x_customer_shipping_state}
{payment.x_customer_shipping_zip}
<br />
{payment.x_customer_shipping_country}
</p>
);
}
return content;
};
const billingAddress = (payment) => {
let content = (<p>...</p>);
if (payment) {
content = (
<p>
{payment.x_customer_first_name} {payment.x_customer_last_name}
<br />
{payment.x_customer_billing_address1}
<br />
{payment.x_customer_billing_city}
{payment.x_customer_billing_state}
{payment.x_customer_billing_zip}
<br />
{payment.x_customer_billing_country}
</p>
);
}
return content;
};
const Customer = ({ payment }) => (
<div className="content-box">
<div className="content-box__row content-box__row--no-border">
<h2>Customer information</h2>
</div>
<div className="content-box__row">
<div className="section__content">
<div className="section__content__column section__content__column--half">
<h3>Shipping address</h3>
{shippingAddress(payment)}
</div>
<div className="section__content__column section__content__column--half">
<h3>Billing address</h3>
{billingAddress(payment)}
</div>
</div>
</div>
</div>
);
Customer.propTypes = {
payment: React.PropTypes.object,
};
export default Customer;
|
Paths/React/05.Building Scalable React Apps/3-react-boilerplate-building-scalable-apps-m3-exercise-files/Before/app/containers/LanguageProvider/index.js | phiratio/Pluralsight-materials | /*
*
* LanguageProvider
*
* this component connects the redux state language locale to the
* IntlProvider component and i18n messages (loaded from `app/translations`)
*/
import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { IntlProvider } from 'react-intl';
import { selectLocale } from './selectors';
export class LanguageProvider extends React.Component { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<IntlProvider locale={this.props.locale} messages={this.props.messages[this.props.locale]}>
{React.Children.only(this.props.children)}
</IntlProvider>
);
}
}
LanguageProvider.propTypes = {
locale: React.PropTypes.string,
messages: React.PropTypes.object,
children: React.PropTypes.element.isRequired,
};
const mapStateToProps = createSelector(
selectLocale(),
(locale) => ({ locale })
);
function mapDispatchToProps(dispatch) {
return {
dispatch,
};
}
export default connect(mapStateToProps, mapDispatchToProps)(LanguageProvider);
|
clients/libs/slate-editor-list-plugin/src/UnorderedListButton.js | nossas/bonde-client | import React from 'react'
import FontAwesome from 'react-fontawesome'
import classnames from 'classnames'
import { Button } from '@slate-editor/components'
import { unorderedListStrategy, isUnorderedList } from './ListUtils'
// eslint-disable-next-line react/prop-types
const UnorderedListButton = ({ value, onChange, className, style, type }) => (
<Button
style={style}
type={type}
// eslint-disable-next-line react/prop-types
onClick={() => onChange(unorderedListStrategy(value.change()))}
className={classnames(
'slate-list-plugin--button',
{ active: isUnorderedList(value) },
className,
)}
>
<FontAwesome name="list-ul" />
</Button>
)
export default UnorderedListButton
|
app/javascript/mastodon/features/mutes/index.js | rekif/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountContainer from '../../containers/account_container';
import { fetchMutes, expandMutes } from '../../actions/mutes';
import ScrollableList from '../../components/scrollable_list';
const messages = defineMessages({
heading: { id: 'column.mutes', defaultMessage: 'Muted users' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'mutes', 'items']),
});
export default @connect(mapStateToProps)
@injectIntl
class Mutes extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
shouldUpdateScroll: PropTypes.func,
accountIds: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchMutes());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandMutes());
}, 300, { leading: true });
render () {
const { intl, shouldUpdateScroll, accountIds } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.mutes' defaultMessage="You haven't muted any users yet." />;
return (
<Column icon='volume-off' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='mutes'
onLoadMore={this.handleLoadMore}
shouldUpdateScroll={shouldUpdateScroll}
emptyMessage={emptyMessage}
>
{accountIds.map(id =>
<AccountContainer key={id} id={id} />
)}
</ScrollableList>
</Column>
);
}
}
|
benchmarks/source-agilitycms/src/components/PreviewBar.js | gatsbyjs/gatsby | import React, { Component } from 'react';
import './PreviewBar.css'
class PreviewBar extends Component {
clearPreviewMode() {
window.location.href = "?AgilityPreview=0";
}
render() {
if (this.props.isPreview === 'true') {
return (<div id="agility-preview-bar" title="You are currently in Preview Mode.">Preview Mode</div>)
} else {
return null;
}
}
}
export default PreviewBar;
|
Blog/src/js/components/Article/List.react.js | rcatlin/ryancatlin-info | import React from 'react';
import ArticleShort from '../articleShort.react';
import ArticleStore from '../../stores/ArticleStore';
import PageCount from './PageCount.react';
export default class List extends React.Component {
static get displayName() {
return 'ArticleList';
}
constructor(props) {
super(props);
this.state = {
offset: 0,
limit: 10,
articles: []
};
}
componentDidMount() {
ArticleStore.getList(
this,
this.state.offset,
this.state.limit
);
}
render() {
var article = 'undefined',
index = 'undefined',
rendered = [];
for (index in this.state.articles) {
if (this.state.articles.hasOwnProperty(index)) {
article = this.state.articles[index];
rendered.push(
<ArticleShort
createdAt={article.createdAt}
id={article.id}
key={article.id}
slug={article.slug}
title={article.title}
/>
);
}
}
return (
<div>
<h1 className="text-center">
{'Articles'}<br />
<small>
<PageCount
limit={this.state.limit}
offset={this.state.offset}
/>
</small>
</h1>
{rendered}
</div>
);
}
}
|
gui/components/ReqDetails.js | venogram/ExpressiveJS | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import jsonInterface from './../js/jsonInterface.js';
function ReqDetails(props) {
let highlightObj = jsonInterface.getRequestHighlights(props.details);
const highlights = Object.keys(highlightObj).map(key => <li>{`${key}: ${JSON.stringify(highlightObj[key], null, ' ')}`}</li>)
return (
<div className="Details ReqDetails">
<p className = "DetailsTitle"> Request Details </p>
<ul>
{highlights}
</ul>
</div>
)
}
ReqDetails.propTypes = {
details: PropTypes.object
}
module.exports = ReqDetails;
|
src/app.js | giltayar/react-starter-pack | import Counter from './counter';
import {render} from 'react-dom';
import React from 'react';
render(<Counter/>, document.getElementById('content'))
|
app/main/components/ThingList.js | BitLooter/Stuffr-frontend | import React from 'react'
import { connect } from 'react-redux'
import PropTypes from 'prop-types'
import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn } from 'material-ui/Table'
import { openThingEditor } from '../actions'
import t from '../../common/i18n'
// TODO: Height needs to be set to the height of the window
const ThingList = ({ things, openThingEditor }) =>
<Table multiSelectable height='700px' onCellClick={(row) => {
openThingEditor(things[row])
}}>
<TableHeader>
<TableRow>
<TableHeaderColumn>{t('thingList.nameHeader')}</TableHeaderColumn>
<TableHeaderColumn>{t('thingList.detailsHeader')}</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody showRowHover>
{things.map((thing) =>
<TableRow key={thing.id}>
<TableRowColumn>{thing.name}</TableRowColumn>
<TableRowColumn>{thing.details}</TableRowColumn>
</TableRow>
)}
</TableBody>
</Table>
ThingList.propTypes = {
openThingEditor: PropTypes.func.isRequired,
things: PropTypes.array.isRequired
}
const ThingListContainer = connect(
function mapStateToProps (state) {
return {things: state.database.things}
},
{openThingEditor}
)(ThingList)
export default ThingListContainer
|
node_modules/react-bootstrap/es/MediaList.js | saltypaul/SnipTodo | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var MediaList = function (_React$Component) {
_inherits(MediaList, _React$Component);
function MediaList() {
_classCallCheck(this, MediaList);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaList.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('ul', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaList;
}(React.Component);
export default bsClass('media-list', MediaList); |
src/components/marketingTypography/MarketingHeading1.js | teamleadercrm/teamleader-ui | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Box from '../box';
import cx from 'classnames';
import theme from './theme.css';
class MarketingHeading1 extends Component {
render() {
const { children, className, ...others } = this.props;
const classNames = cx(theme['heading-1'], className);
return (
<Box {...others} className={classNames} element="h1">
{children}
</Box>
);
}
}
MarketingHeading1.propTypes = {
children: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
};
export default MarketingHeading1;
|
src/svg-icons/action/settings-input-composite.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsInputComposite = (props) => (
<SvgIcon {...props}>
<path d="M5 2c0-.55-.45-1-1-1s-1 .45-1 1v4H1v6h6V6H5V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2H9v2zm-8 0c0 1.3.84 2.4 2 2.82V23h2v-4.18C6.16 18.4 7 17.3 7 16v-2H1v2zM21 6V2c0-.55-.45-1-1-1s-1 .45-1 1v4h-2v6h6V6h-2zm-8-4c0-.55-.45-1-1-1s-1 .45-1 1v4H9v6h6V6h-2V2zm4 14c0 1.3.84 2.4 2 2.82V23h2v-4.18c1.16-.41 2-1.51 2-2.82v-2h-6v2z"/>
</SvgIcon>
);
ActionSettingsInputComposite = pure(ActionSettingsInputComposite);
ActionSettingsInputComposite.displayName = 'ActionSettingsInputComposite';
ActionSettingsInputComposite.muiName = 'SvgIcon';
export default ActionSettingsInputComposite;
|
src/esm/components/graphics/icons/visa-icon/index.js | KissKissBankBank/kitten | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["className"];
import React from 'react';
import classNames from 'classnames';
export var VisaIcon = function VisaIcon(_ref) {
var className = _ref.className,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement("svg", _extends({
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 732 224.43",
width: "36",
className: classNames('k-ColorSvg', className)
}, props), /*#__PURE__*/React.createElement("title", null, "Visa"), /*#__PURE__*/React.createElement("path", {
fill: "#004686",
d: "M257.87 221.21L294.93 3.77h59.26l-37.08 217.44h-59.24zM532.06 9.13A152.88 152.88 0 0 0 478.94 0c-58.56 0-99.81 29.49-100.16 71.72-.33 31.24 29.45 48.67 51.93 59.07 23.07 10.65 30.82 17.45 30.71 27-.15 14.57-18.42 21.23-35.46 21.23-23.72 0-36.32-3.29-55.79-11.41l-7.64-3.46-8.32 48.67c13.84 6.07 39.44 11.33 66 11.61 62.3 0 102.74-29.15 103.2-74.28.22-24.74-15.57-43.56-49.76-59.08-20.71-10.06-33.4-16.77-33.27-27 0-9 10.74-18.7 33.94-18.7a109.19 109.19 0 0 1 44.39 8.35l5.31 2.5 8-47.12zM684 3.98h-45.8c-14.19 0-24.8 3.88-31 18l-88 199.25h62.23s10.18-26.79 12.48-32.67c6.8 0 67.26.09 75.9.09 1.78 7.61 7.21 32.58 7.21 32.58h55L684 3.98m-73 140.15c4.9-12.53 23.61-60.78 23.61-60.78-.35.57 4.86-12.59 7.86-20.75l4 18.74s11.34 51.91 13.72 62.79H611zM208.17 3.93l-58 148.27-6.17-30.12c-10.84-34.74-44.49-72.36-82.12-91.21l53.06 190.15 62.7-.07 93.3-217h-62.77z"
}), /*#__PURE__*/React.createElement("path", {
d: "M96.32 3.8H.76L0 8.33c74.35 18 123.54 61.49 144 113.75l-20.82-99.92c-3.59-13.77-14-17.87-26.86-18.36z",
fill: "#ef9b11"
}));
}; |
src/components/Dropzone/Dropzone.js | gabrielmf/SIR-EDU-2.0 | import React from 'react'
import Dropzone from 'react-dropzone'
import IconButton from 'material-ui/IconButton';
import './Dropzone.scss'
const preventDropOnDocument = () => {
window.addEventListener("dragover",function(e){
e = e || event;
e.preventDefault();
},false);
window.addEventListener("drop",function(e){
e = e || event;
e.preventDefault();
},false);
}
const getFilePreview = (file) => {
console.log(file);
if(file.type.includes('video')) {
return (<video src={file.preview} class="video-thumb" controls preload="metadata"/>);
}
return (<img src={file.preview} class="img-thumbnail" height="100" width="230"/>);
}
export default class DropzoneComponent extends React.Component {
constructor(props) {
super(props);
this.onOpenClick = this.onOpenClick.bind(this);
this.onDrop = this.onDrop.bind(this);
this.removeFile = this.removeFile.bind(this);
preventDropOnDocument();
this.file = this.props.initConfig || null;
}
shouldComponentUpdate(nextProps) {
return this.props.initConfig !== nextProps.initConfig;
}
onOpenClick() {
this.dropzone.open();
}
onDrop = (files) => {
this.file = files[0];
this.props.onDrop(this.props.name, files[0]);
}
removeFile() {
this.file = null;
this.props.onDrop(this.props.name, null);
}
render() {
return (
<div class="dropzone-component">
<Dropzone ref={(dropzone) => {this.dropzone = dropzone; }}
className="dropzone-box"
activeClassName="dropzone-box-active"
onDrop={this.onDrop}
accept={this.props.accept}
multiple={this.props.multiple}
disableClick={true}>
<div class="dropzone-content">
{
this.file &&
<div>
{ getFilePreview(this.file) }
<span>
<IconButton iconClassName="fa fa-times"
onTouchTap={this.removeFile}
tooltip="Remover arquivo"
tooltipPosition="bottom-right"
/>
</span>
</div> ||
<div>
<i class="fa fa-cloud-upload fa-5x" aria-hidden="true"></i>
<h5>{this.props.text}</h5>
<button type="button" class="btn btn-success" onClick={this.onOpenClick}>
Selecionar arquivo
</button>
</div>
}
</div>
</Dropzone>
</div>
);
}
} |
react/src/GridRow.js | Chalarangelo/react-mini.css | import React from 'react';
// Module constants (change according to your flavor file)
var gridRowClassName = 'row';
var gridColumnsClassNamePrefix = 'cols';
var gridColumnExtraSmallSuffix = 'xs';
var gridColumnSmallSuffix = 'sm';
var gridColumnMediumSuffix = 'md';
var gridColumnLargeSuffix = 'lg';
// GridRow component.
export function GridRow (props){
var outProps = Object.assign({},props);
if (typeof outProps.className === 'undefined') outProps.className = gridRowClassName;
else outProps.className += ' ' + gridRowClassName;
if (typeof outProps.extraSmall !== 'undefined')
if (outProps.extraSmall == 'fluid') outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnExtraSmallSuffix;
else outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnExtraSmallSuffix+'-'+outProps.extraSmall;
if (typeof outProps.small !== 'undefined')
if (outProps.small == 'fluid') outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnSmallSuffix;
else outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnSmallSuffix+'-'+outProps.small;
if (typeof outProps.medium !== 'undefined')
if (outProps.medium == 'fluid') outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnMediumSuffix;
else outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnMediumSuffix+'-'+outProps.medium;
if (typeof outProps.large !== 'undefined')
if (outProps.large == 'fluid') outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnLargeSuffix;
else outProps.className += ' ' + gridColumnsClassNamePrefix+'-'+gridColumnLargeSuffix+'-'+outProps.large;
delete outProps.extraSmall;
delete outProps.small;
delete outProps.medium;
delete outProps.large;
return React.createElement(
'div',outProps, outProps.children
);
}
|
react/src/pages/logs/components/logs-table.js | motiko/sfdc-debug-logs | import React from 'react'
import Table, {
TableBody,
TableHead,
TableRow,
TableCell
} from 'material-ui/Table'
import { withStyles } from 'material-ui/styles'
const styles = theme => ({
table: {
background: theme.palette.background.default
}
})
function LogsTable({ history, logs, classes }) {
const timeFormatter = Intl.DateTimeFormat('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric',
hour: 'numeric',
minute: 'numeric',
second: 'numeric',
hour12: false
})
const openLog = logId => {
history.push(`/logs/${logId}`)
}
const toTableRow = log => {
const timeString = timeFormatter.format(new Date(log.StartTime))
return (
<TableRow hover onClick={() => openLog(log.Id)} key={log.Id}>
<TableCell>{timeString}</TableCell>
<TableCell>{log.Operation}</TableCell>
<TableCell>{log.Status}</TableCell>
<TableCell>{log.LogUser.Name}</TableCell>
<TableCell>{log.DurationMilliseconds + 'ms'}</TableCell>
<TableCell>{`${(log.LogLength / 1000).toFixed(2)} k`}</TableCell>
</TableRow>
)
}
return (
<Table className={classes.table}>
<TableHead>
<TableRow>
<TableCell>Time</TableCell>
<TableCell>Operation</TableCell>
<TableCell>Status</TableCell>
<TableCell>User</TableCell>
<TableCell>Run Duration</TableCell>
<TableCell>Length</TableCell>
</TableRow>
</TableHead>
<TableBody>{Object.values(logs).map(toTableRow)}</TableBody>
</Table>
)
}
export default withStyles(styles)(LogsTable)
|
react/features/invite/components/dial-in-summary/web/DialInSummary.js | bgrozev/jitsi-meet | // @flow
import React, { Component } from 'react';
import { translate } from '../../../../base/i18n';
import { doGetJSON } from '../../../../base/util';
import ConferenceID from './ConferenceID';
import NumbersList from './NumbersList';
declare var config: Object;
/**
* The type of the React {@code Component} props of {@link DialInSummary}.
*/
type Props = {
/**
* Additional CSS classnames to append to the root of the component.
*/
className: string,
/**
* Whether or not numbers should include links with the telephone protocol.
*/
clickableNumbers: boolean,
/**
* The name of the conference to show a conferenceID for.
*/
room: string,
/**
* Invoked to obtain translated strings.
*/
t: Function
};
/**
* The type of the React {@code Component} state of {@link DialInSummary}.
*/
type State = {
/**
* The numeric ID of the conference, used as a pin when dialing in.
*/
conferenceID: ?string,
/**
* An error message to display.
*/
error: string,
/**
* Whether or not the app is fetching data.
*/
loading: boolean,
/**
* The dial-in numbers to be displayed.
*/
numbers: ?Array<Object> | ?Object,
/**
* Whether or not dial-in is allowed.
*/
numbersEnabled: ?boolean
}
/**
* Displays a page listing numbers for dialing into a conference and pin to
* the a specific conference.
*
* @extends Component
*/
class DialInSummary extends Component<Props, State> {
state = {
conferenceID: null,
error: '',
loading: true,
numbers: null,
numbersEnabled: null
};
/**
* Initializes a new {@code DialInSummary} instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props: Props) {
super(props);
// Bind event handlers so they are only bound once for every instance.
this._onGetNumbersSuccess = this._onGetNumbersSuccess.bind(this);
this._onGetConferenceIDSuccess
= this._onGetConferenceIDSuccess.bind(this);
this._setErrorMessage = this._setErrorMessage.bind(this);
}
/**
* Implements {@link Component#componentDidMount()}. Invoked immediately
* after this component is mounted.
*
* @inheritdoc
* @returns {void}
*/
componentDidMount() {
const getNumbers = this._getNumbers()
.then(this._onGetNumbersSuccess)
.catch(this._setErrorMessage);
const getID = this._getConferenceID()
.then(this._onGetConferenceIDSuccess)
.catch(this._setErrorMessage);
Promise.all([ getNumbers, getID ])
.then(() => {
this.setState({ loading: false });
});
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
let className = '';
let contents;
const { conferenceID, error, loading, numbersEnabled } = this.state;
if (loading) {
contents = '';
} else if (numbersEnabled === false) {
contents = this.props.t('info.dialInNotSupported');
} else if (error) {
contents = error;
} else {
className = 'has-numbers';
contents = [
conferenceID
? <ConferenceID
conferenceID = { conferenceID }
conferenceName = { this.props.room }
key = 'conferenceID' />
: null,
<NumbersList
clickableNumbers = { this.props.clickableNumbers }
conferenceID = { conferenceID }
key = 'numbers'
numbers = { this.state.numbers } />
];
}
return (
<div className = { `${this.props.className} ${className}` }>
{ contents }
</div>
);
}
/**
* Creates an AJAX request for the conference ID.
*
* @private
* @returns {Promise}
*/
_getConferenceID() {
const { room } = this.props;
const { dialInConfCodeUrl, hosts } = config;
const mucURL = hosts && hosts.muc;
if (!dialInConfCodeUrl || !mucURL || !room) {
return Promise.resolve();
}
return doGetJSON(`${dialInConfCodeUrl}?conference=${room}@${mucURL}`, true)
.catch(() => Promise.reject(this.props.t('info.genericError')));
}
/**
* Creates an AJAX request for dial-in numbers.
*
* @private
* @returns {Promise}
*/
_getNumbers() {
const { room } = this.props;
const { dialInNumbersUrl, hosts } = config;
const mucURL = hosts && hosts.muc;
let URLSuffix = '';
if (!dialInNumbersUrl) {
return Promise.reject(this.props.t('info.dialInNotSupported'));
}
// when room and mucURL are available
// provide conference when looking up dial in numbers
if (room && mucURL) {
URLSuffix = `?conference=${room}@${mucURL}`;
}
return doGetJSON(`${dialInNumbersUrl}${URLSuffix}`, true)
.catch(() => Promise.reject(this.props.t('info.genericError')));
}
_onGetConferenceIDSuccess: (Object) => void;
/**
* Callback invoked when fetching the conference ID succeeds.
*
* @param {Object} response - The response from fetching the conference ID.
* @private
* @returns {void}
*/
_onGetConferenceIDSuccess(response = {}) {
const { conference, id } = response;
if (!conference || !id) {
return;
}
this.setState({ conferenceID: id });
}
_onGetNumbersSuccess: (Object) => void;
/**
* Callback invoked when fetching dial-in numbers succeeds. Sets the
* internal to show the numbers.
*
* @param {Array|Object} response - The response from fetching
* dial-in numbers.
* @param {Array|Object} response.numbers - The dial-in numbers.
* @param {boolean} response.numbersEnabled - Whether or not dial-in is
* enabled, old syntax that is deprecated.
* @private
* @returns {void}
*/
_onGetNumbersSuccess(
response: Array<Object> | { numbersEnabled?: boolean }) {
this.setState({
numbersEnabled:
Array.isArray(response)
? response.length > 0 : response.numbersEnabled,
numbers: response
});
}
_setErrorMessage: (string) => void;
/**
* Sets an error message to display on the page instead of content.
*
* @param {string} error - The error message to display.
* @private
* @returns {void}
*/
_setErrorMessage(error) {
this.setState({
error
});
}
}
export default translate(DialInSummary);
|
client/src/utils/index.js | kaiguogit/growfolio | import React from 'react';
import numeral from 'numeral';
import Auth from '../services/Auth';
import styles from '../styles';
import log from './log';
import {DollarValue} from '../selectors/transaction';
export {log};
/**
* Wrapper function to try and catch provided callback.
*/
export const makeSafe = (fn) => {
return (...args) => {
try {
return fn.apply(null, args);
} catch (e) {
log.error('Function ', fn, ' went wrong. \n Arguments: ', args, '\nError: ', e);
}
};
};
/**
* round number by digits
* http://www.javascriptkit.com/javatutors/round.shtml
* @param {Number} digit, round at last x decimal
*/
export const round = (value, digit) => {
let multiplier = Math.pow(10, digit);
return Math.round(value * multiplier) / multiplier;
};
/**
* Convert string to number with numeral library
* @param {string|number} n
*/
export const num = (n) => numeral(n).value();
/**
* Convert value to number for single key in object.
* If it's not a finite number, i.e NaN or Infinity, use 0
* @param {string} key
* @param {object} obj
*/
export const avoidNaN = (key, obj) => {
let result;
if (key in obj) {
result = num(obj[key]);
obj[key] = isFinite(result) && result ? result : 0;
}
};
/**
* Convert value to number for provided keys in object.
* If it's not a finite number, i.e NaN or Infinity, use 0
* @param {array} keys
* @param {object} obj
*/
export const avoidNaNKeys = (keys, obj) => {
keys.forEach(key => {
avoidNaN(key, obj);
});
};
/**
* Filters
*/
export const percentage = number => {
try {
return numeral(number).format('0.00%');
}
catch(e) {
return number;
}
};
/** Create function that round number return string value
* @param {number} decimal - number of decimal digit to round
* @return {function}
*/
export const currency = decimal => number => {
if (decimal === undefined) {
decimal = 2;
}
try {
return numeral(round(number, decimal)).format(`0,0[.][${'0'.repeat(decimal)}]`);
}
catch(e) {
return number;
}
};
// http://stackoverflow.com/questions/7556591/javascript-date-object-always-one-day-off#answer-14569783
// Convert UTC to local date
// Datepicker use momentjs to parse and set the time.
// By default moment use local timezone
// so selecting 4-27 in PDT browser will create a 4-27 17:00 PDT date
// which is 4-28 00:00 GMT. It's fine as long as we display it as 4-27 as
// well.
// Therefore, remove the old timeoffset workaround.
export const date = date => {
// try {
// let doo = new Date(dateStr);
// let adjustedTime = new Date(doo.getTime() + Math.abs(doo.getTimezoneOffset()*60000));
// return adjustedTime.toLocaleDateString();
// }
// catch(e) {
// return dateStr;
// }
return date ? date.format('YYYY-MM-DD') : '';
};
export const capitalize = str => {
return str[0].toUpperCase() + str.slice(1);
};
/**
* Utilities
*/
// https://developer.mozilla.org/en/docs/Web/JavaScript/Guide/Regular_Expressions#Using_Special_Characters
export const escapeRegexCharacters = (str) => {
return str.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
};
const queryParams = (params) => {
let esc = encodeURIComponent;
return Object.keys(params)
.map(k => esc(k) + '=' + esc(params[k]))
.join('&');
};
export const makeUrl = (url, params) => {
return url += (url.indexOf('?') === -1 ? '?' : '&') + queryParams(params);
};
export const getHeaders = () => new Headers({
'Content-Type': 'application/json',
Accept: 'application/json',
Authorization: `Bearer ${Auth.getToken()}`
});
// Safely divide
// https://stackoverflow.com/questions/8072323/best-way-to-prevent-handle-divide-by-0-in-javascript
export const divide = (a, b) => {
const result = num(a) / num(b);
if (isFinite(result)) {
return result;
}
return 0;
};
/**
* Generate red or green style based on whether number is positive.
*
* @param {number} value
* @returns {object} A style object used for component style property
*/
export const redOrGreen = (value) => {
let style;
if (value > 0) {
style = styles.up;
} else if (value < 0) {
style = styles.down;
}
return style;
};
export const getDollarValue = (obj, key, displayCurrency) => {
if (obj[key] instanceof DollarValue) {
return obj[key][displayCurrency];
}
return obj[key];
};
export const coloredCell = (entry, value, refValue) => {
return (
<span style={redOrGreen(refValue)}>
{value}
</span>
);
};
|
packages/icons/src/md/image/Looks2.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdLooks2(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M38 6c2.21 0 4 1.79 4 4v28c0 2.21-1.79 4-4 4H10c-2.21 0-4-1.79-4-4V10c0-2.21 1.79-4 4-4h28zm-8 16v-4c0-2.21-1.79-4-4-4h-8v4h8v4h-4c-2.21 0-4 1.79-4 4v8h12v-4h-8v-4h4c2.21 0 4-1.79 4-4z" />
</IconBase>
);
}
export default MdLooks2;
|
examples/react-redux/src/components/ui/Container.js | rangle/redux-segment | import React from 'react';
const Container = ({ children, style = {}, className = '' }) => {
return (
<div className={ `container ${ className }` } style={{ ...styles.base, ...style }}>
<div className="clearfix">
{ children }
</div>
</div>
);
};
const styles = {
base: {},
};
export default Container;
|
src/svg-icons/device/location-searching.js | kittyjumbalaya/material-components-web | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceLocationSearching = (props) => (
<SvgIcon {...props}>
<path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
DeviceLocationSearching = pure(DeviceLocationSearching);
DeviceLocationSearching.displayName = 'DeviceLocationSearching';
DeviceLocationSearching.muiName = 'SvgIcon';
export default DeviceLocationSearching;
|
src/ui/components/IconesSuperiores.js | dartelvis/zf3 |
import React from 'react';
import PropTypes from 'prop-types';
import Toggle from 'material-ui/Toggle';
import IconButton from 'material-ui/IconButton';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
import Avatar from 'material-ui/Avatar';
import ImageSettings from 'material-ui/svg-icons/action/settings';
import ImageSair from 'material-ui/svg-icons/action/exit-to-app';
import ImageSearch from 'material-ui/svg-icons/action/search';
import { Link } from 'react-router';
import { messageActions } from '../../actions';
import { AutoComplete, Badge, Divider, Dialog, CardText } from 'material-ui';
class IconesSuperiores extends React.Component
{
constructor(props, context)
{
super(props, context);
this.renderSearch = this.renderSearch.bind(this);
this.goToProspect = this.goToProspect.bind(this);
this.onLogout = this.onLogout.bind(this);
this.onLogin = this.onLogin.bind(this);
this.state = {
prospects: [],
prospectSearch: '',
showSearch: false,
iconSearch: false,
iconSearchShow: false,
prospect: {},
searchTimeout: null,
notificacoes: [],
dialogInfo: ''
};
this.consulta = {
page: 1,
rows: 5,
total: 1,
info: '',
sidx: 'e.ts',
sord: 'desc'
};
this.search = null;
}
componentWillMount()
{
}
onLogin()
{
App.fetch.getJson(window.App.basePath + '/app/index/login').then((resp) => {
window.App.user = resp.data;
this.props.onChange(window.App);
});
}
onLogout()
{
App.fetch.getJson(window.App.basePath + '/app/index/logout').then(() => {
window.App.user = {};
this.props.onChange(window.App);
this.context.router.push({pathname: '/', state: {
oportunidade: {}
}});
});
}
goToProspect(id)
{
// this.context.router.push({pathname: '/com-prospect', state: {prospect: id}});
// this.setState({prospectSearch: ''});
}
handleDescricao(value)
{
// var searchTimeout = this.state.searchTimeout,
// prospect = this.state.prospect;
// prospect.razaosocial = value;
// prospect.nome = value;
//
//
// clearTimeout(searchTimeout);
// searchTimeout = setTimeout(() => {
// App.fetch.getJson(window.App.basePath + '/app/com-prospect/get-by-descricao', {
// body: JSON.stringify({descricao: value}),
// method: "POST"
// }).then((resp) => {
// (resp.type === 'success') && this.setState({prospects: resp.data || []});
// });
// }, 300);
// this.setState({searchTimeout: searchTimeout, prospect: prospect, prospectSearch: value});
}
render()
{
const itens = this.state.notificacoes.map((n, i) => {
return (
<div key={i}>
<a className="lv-item">
<div className="media">
<div className="pull-left p-t-5">
<button className="btn btn-icon btn-flat btn-info"
onClick={() => this.marcarLido(n.idNotifica)}
style={{boxShadow:'none'}} title="Marcar como lido">
<i className={"md "+ (n.icon) ? n.icon : 'md-flag'}></i>
</button>
</div>
<div className="media-body">
<label onClick={() => this.setState({dialogInfo: (n.msg) ? n.msg : n.title})}>
<div className="lv-title">{n.app}</div>
<small className='lv-small' style={{whiteSpace:'normal'}}>{n.title}</small>
há {n.data} dia(s).
</label>
</div>
</div>
</a>
<Divider />
</div>
);
});
return (
<div style={{float: 'left', textAlign: 'right', width: '370px'}}>
<div style={{display: 'inline-block', width: '70px'}}>
<Toggle
defaultToggled={this.props.defaultToggled}
onToggle={(e, t) => {
this.props.showHideMenu(t);
this.setState({iconSearch: !this.state.iconSearch});
}}
/>
</div>
{this.state.iconSearch && <IconButton
tooltipPosition="bottom-center"
onTouchTap={() => {
var iconSearchShow = !this.state.iconSearchShow;
this.setState({iconSearchShow: iconSearchShow});
this.props.setHeight(iconSearchShow ? 116: 66);
}}
iconStyle={{color: '#fff',fontSize: '24px'}}
tooltip="Buscar"
style={{width: '50px',height: '38px', textAlign: 'center', padding: '0'}}
><ImageSearch/></IconButton>}
<IconMenu
iconButtonElement={
<IconButton style={{padding: '0'}}>
<Avatar size={30}>{(this.props.user || '').substring(0, 1)}</Avatar>
</IconButton>
}
anchorOrigin={{horizontal: 'right', vertical: 'top'}}
targetOrigin={{horizontal: 'right', vertical: 'top'}}
>
{this.props.user ?
<MenuItem leftIcon={<ImageSair />} onTouchTap={this.onLogout} primaryText="Sair" />
: <MenuItem leftIcon={<ImageSair />} onTouchTap={this.onLogin} primaryText="Logar" />
}
</IconMenu>
{this.renderSearch()}
</div>
);
}
renderSearch()
{
return (this.state.iconSearch ?
<div style={{
height: '40px',
marginBottom: '10px',
backgroundColor: 'rgba(255, 255, 255, 0.26)',
display: (this.state.iconSearchShow ? 'block' : 'none')
}}>
<AutoComplete
hintText="Buscar"
menuCloseDelay={10}
textFieldStyle={{
top: '-18px',
left: '0',
color: '#fff',
position:'absolute',
width: '300px',
paddingLeft: '40px',
backgroundRepeat: 'no-repeat',
backgroundPosition: '10px center',
backgroundImage: 'url("' + window.App.basePath + '/img/icons/search.png")'
}}
listStyle={{
margin: '0',
cursor: 'pointer'
}}
openOnFocus={true}
maxSearchResults={5}
underlineShow={false}
fullWidth={true}
dataSource={this.state.prospects}
searchText={this.state.prospectSearch}
onUpdateInput={(v) => this.handleDescricao(v)}
inputStyle={{color: 'white', fontSize: 18, width: '100%'}}
onNewRequest={(a) => this.goToProspect(a.idComProspect)}
dataSourceConfig={{text: 'descricao', value: 'idComProspect'}}
filter={() => {return true;}}
hintStyle={{color: 'rgba(255,255,255, 0.5)', fontSize: 18, width: '100%', textAlign: 'left'}}
/>
</div>
:
<div style={{
top: '12px',
height: '40px',
width: '500px',
textAlign: 'center',
position: 'absolute',
left: 'calc(50% - 250px)',
backgroundColor: 'rgba(255, 255, 255, 0.26)'
}}>
<AutoComplete
hintText="Buscar"
menuCloseDelay={10}
textFieldStyle={{
top: '-4px',
left: '-5px',
width: '500px',
paddingLeft: '40px',
backgroundRepeat: 'no-repeat',
backgroundPosition: '10px center',
backgroundImage: 'url("' + window.App.basePath + '/img/icons/search.png")'
}}
openOnFocus={true}
listStyle={{
margin: '0',
cursor: 'pointer',
}}
fullWidth={true}
maxSearchResults={5}
underlineShow={false}
dataSource={this.state.prospects}
searchText={this.state.prospectSearch}
onUpdateInput={(v) => this.handleDescricao(v)}
inputStyle={{color: 'white', fontSize: 18, width: '100%'}}
onNewRequest={(a) => this.goToProspect(a.idComProspect)}
dataSourceConfig={{text: 'descricao', value: 'idComProspect'}}
filter={() => {return true;}}
hintStyle={{color: 'rgba(255,255,255, 0.5)', fontSize: 18, width: '100%', textAlign: 'left'}}
/>
</div>
);
}
}
IconesSuperiores.contextTypes = {
router: PropTypes.object.isRequired
};
export default IconesSuperiores;
|
src/index.js | tybolo/note | import 'normalize.css'
import './common.scss'
import React from 'react'
import ReactDOM from 'react-dom'
import { AppContainer } from 'react-hot-loader'
import App from './App'
const render = Comp => {
ReactDOM.render(
<AppContainer>
<Comp />
</AppContainer>,
document.getElementById('app')
)
}
render(App)
if (module.hot) {
module.hot.accept('./App', () => {
render(App)
})
}
|
scripts/Calculator.js | sarahedkins/calculator-app | import React, { Component } from 'react';
import '../styles/calculator.css';
export default class Calculator extends Component {
constructor(props) {
super(props);
const today = new Date();
const currentMonthIndex = today.getMonth();
const initialWant = this.getWantValue();
const initialHave = this.getHaveValue();
const initialSavings = this.getSavingsValue();
const initialToGo = (initialWant || 0) - (initialHave || 0);
const initialMonthsToGo = Math.round(
((initialWant || 0) - (initialHave || 0)) / (initialSavings || 0)
);
this.state = {
want: initialWant || 0,
have: initialHave || 0,
toGo: initialToGo || 0,
savePerMonth: initialSavings || 0,
monthsToGo: initialMonthsToGo || 0,
currentMonthIndex,
};
}
// Setters and Getters for LocalStorage
setWantValue = (val) => {
localStorage.want = val;
};
getWantValue = () => localStorage.want;
setHaveValue = (val) => {
localStorage.have = val;
};
getHaveValue = () => localStorage.have;
setSavingsValue = (val) => {
localStorage.savings = val;
};
getSavingsValue = () => localStorage.savings;
// end of Setters and Getters for LocalStorage
handleWantInput = (e) => {
this.setWantValue(e.target.value);
this.setState({
want: e.target.value,
toGo: e.target.value - this.state.have,
monthsToGo: Math.round((e.target.value - this.state.have) / this.state.savePerMonth),
});
}
handleHaveInput = (e) => {
this.setHaveValue(e.target.value);
this.setState({
have: e.target.value,
toGo: this.state.want - e.target.value,
monthsToGo: Math.round((this.state.want - e.target.value) / this.state.savePerMonth),
});
}
handleMonthInput = (e) => {
this.setSavingsValue(e.target.value);
this.setState({
savePerMonth: e.target.value,
monthsToGo: Math.round(this.state.toGo / e.target.value),
});
}
months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
render() {
return (
<div className="border">
<h1 className="header">Savings Calculator</h1>
Want: <input type="text" onChange={this.handleWantInput} value={this.state.want} />
<br />
Have: <input type="text" onChange={this.handleHaveInput} value={this.state.have} />
<br />
To Go: {this.state.toGo}
<hr />
Savings Per Month: <input type="text" onChange={this.handleMonthInput} value={this.state.savePerMonth} />
<br />
Months To Go: {this.state.monthsToGo}
<hr />
Projected Goal Month: {
this.months[(this.state.currentMonthIndex + this.state.monthsToGo) % 12]
}
</div>
);
}
}
|
basic/node_modules/react-router/es6/RouteContext.js | jintoppy/react-training | 'use strict';
import warning from './routerWarning';
import React from 'react';
var object = React.PropTypes.object;
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
var RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext: function getChildContext() {
return {
route: this.props.route
};
},
componentWillMount: function componentWillMount() {
process.env.NODE_ENV !== 'production' ? warning(false, 'The `RouteContext` mixin is deprecated. You can provide `this.props.route` on context with your own `contextTypes`. http://tiny.cc/router-routecontextmixin') : undefined;
}
};
export default RouteContext; |
src/components/tools/user-roles.js | Lokiedu/libertysoil-site | /*
This file is a part of libertysoil.org website
Copyright (C) 2016 Loki Education (Social Enterprise)
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react';
export default function UserRoles({ roles }) {
if (!roles || !roles.size) {
return null;
}
const roleElements = roles.map(role => (
<span className="user_roles__role" key={role.get('id')} title={role.get('description')}>{role.get('title')}</span>
));
return (
<div className="user_roles">
{roleElements}
</div>
);
}
|
src/js/components/icons/base/Checkmark.js | kylebyerly-hp/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}-checkmark`,
className,
{
[`${CLASS_ROOT}--${size}`]: size,
[`${CLASS_ROOT}--responsive`]: responsive,
[`${COLOR_INDEX}-${colorIndex}`]: colorIndex
}
);
a11yTitle = a11yTitle || Intl.getMessage(intl, 'checkmark');
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}><polyline fill="none" stroke="#000" strokeWidth="2" points="2 14 9 20 22 4"/></svg>;
}
};
Icon.contextTypes = {
intl: PropTypes.object
};
Icon.defaultProps = {
responsive: true
};
Icon.displayName = 'Checkmark';
Icon.icon = true;
Icon.propTypes = {
a11yTitle: PropTypes.string,
colorIndex: PropTypes.string,
size: PropTypes.oneOf(['xsmall', 'small', 'medium', 'large', 'xlarge', 'huge']),
responsive: PropTypes.bool
};
|
app/javascript/mastodon/components/avatar.js | Nyoho/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { autoPlayGif } from '../initial_state';
export default class Avatar extends React.PureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
size: PropTypes.number.isRequired,
style: PropTypes.object,
inline: PropTypes.bool,
animate: PropTypes.bool,
};
static defaultProps = {
animate: autoPlayGif,
size: 20,
inline: false,
};
state = {
hovering: false,
};
handleMouseEnter = () => {
if (this.props.animate) return;
this.setState({ hovering: true });
}
handleMouseLeave = () => {
if (this.props.animate) return;
this.setState({ hovering: false });
}
render () {
const { account, size, animate, inline } = this.props;
const { hovering } = this.state;
const src = account.get('avatar');
const staticSrc = account.get('avatar_static');
let className = 'account__avatar';
if (inline) {
className = className + ' account__avatar-inline';
}
const style = {
...this.props.style,
width: `${size}px`,
height: `${size}px`,
backgroundSize: `${size}px ${size}px`,
};
if (hovering || animate) {
style.backgroundImage = `url(${src})`;
} else {
style.backgroundImage = `url(${staticSrc})`;
}
return (
<div
className={className}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
style={style}
/>
);
}
}
|
scripts/apps/extension-points/directives/ExtensionPointDirective.js | gbbr/superdesk-client-core | import ReactDOM from 'react-dom';
import React from 'react';
/**
* @ngdoc directive
* @module superdesk.apps.extension-points
* @name extensionPointDirective
* @packageName superdesk.apps
* @description
* External superdesk apps can register components that then will be hooked into
* the core UI.
* Place this tag in a view where you'd like to add an extension:
* <span sd-extension-point="MY_TYPE"></span>
* See also ExtensionPointsService.
*/
ExtensionPointDirective.$inject = ['extensionPoints'];
export function ExtensionPointDirective(extensionPoints) {
function _buildCompoment(extension, scope) {
// for easy access put values from parent scope into ...
if (typeof extension.props.store === 'undefined') {
// ... the component's props or ...
extension.data.forEach((value) => {
extension.props[value] = scope.$parent.$eval(value);
});
} else {
// ... into the component's redux store
extension.data.forEach((value) => {
extension.props.store.getState()[value] = scope.$parent.$eval(value);
});
}
return React.createElement(extension.componentClass, extension.props);
}
return {
link: function(scope, elem, attr) {
var registeredExtensions = extensionPoints.get(attr.sdExtensionPoint);
var components = registeredExtensions.map((extension) => _buildCompoment(extension, scope));
ReactDOM.render(
<span>{components}</span>,
elem[0]
);
}
};
}
|
modules/RouteContext.js | nickaugust/react-router | import React from 'react'
const { object } = React.PropTypes
/**
* The RouteContext mixin provides a convenient way for route
* components to set the route in context. This is needed for
* routes that render elements that want to use the Lifecycle
* mixin to prevent transitions.
*/
const RouteContext = {
propTypes: {
route: object.isRequired
},
childContextTypes: {
route: object.isRequired
},
getChildContext() {
return {
route: this.props.route
}
}
}
export default RouteContext
|
actor-apps/app-web/src/app/components/modals/Contacts.react.js | fhchina/actor-platform | //
// Deprecated
//
import _ from 'lodash';
import React from 'react';
import { PureRenderMixin } from 'react/addons';
import ContactActionCreators from 'actions/ContactActionCreators';
import DialogActionCreators from 'actions/DialogActionCreators';
import ContactStore from 'stores/ContactStore';
import Modal from 'react-modal';
import AvatarItem from 'components/common/AvatarItem.react';
let appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
let getStateFromStores = () => {
return {
contacts: ContactStore.getContacts(),
isShown: ContactStore.isContactsOpen()
};
};
class Contacts extends React.Component {
componentWillMount() {
ContactStore.addChangeListener(this._onChange);
}
componentWillUnmount() {
ContactStore.removeChangeListener(this._onChange);
}
constructor() {
super();
this._onClose = this._onClose.bind(this);
this._onChange = this._onChange.bind(this);
this.state = getStateFromStores();
}
_onChange() {
this.setState(getStateFromStores());
}
_onClose() {
ContactActionCreators.hideContactList();
}
render() {
let contacts = this.state.contacts;
let isShown = this.state.isShown;
let contactList = _.map(contacts, (contact, i) => {
return (
<Contacts.ContactItem contact={contact} key={i}/>
);
});
if (contacts !== null) {
return (
<Modal className="modal contacts"
closeTimeoutMS={150}
isOpen={isShown}>
<header className="modal__header">
<a className="modal__header__close material-icons" onClick={this._onClose}>clear</a>
<h3>Contact list</h3>
</header>
<div className="modal__body">
<ul className="contacts__list">
{contactList}
</ul>
</div>
</Modal>
);
} else {
return (null);
}
}
}
Contacts.ContactItem = React.createClass({
propTypes: {
contact: React.PropTypes.object
},
mixins: [PureRenderMixin],
_openNewPrivateCoversation() {
DialogActionCreators.selectDialogPeerUser(this.props.contact.uid);
ContactActionCreators.hideContactList();
},
render() {
let contact = this.props.contact;
return (
<li className="contacts__list__item row">
<AvatarItem image={contact.avatar}
placeholder={contact.placeholder}
size="small"
title={contact.name}/>
<div className="col-xs">
<span className="title">
{contact.name}
</span>
</div>
<div className="controls">
<a className="material-icons" onClick={this._openNewPrivateCoversation}>message</a>
</div>
</li>
);
}
});
export default Contacts;
|
node_modules/react-bootstrap/es/Alert.js | CallumRocks/ReduxSimpleStarter | import _Object$values from 'babel-runtime/core-js/object/values';
import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import { bsClass, bsStyles, getClassSet, prefix, splitBsProps } from './utils/bootstrapUtils';
import { State } from './utils/StyleConfig';
import CloseButton from './CloseButton';
var propTypes = {
onDismiss: PropTypes.func,
closeLabel: PropTypes.string
};
var defaultProps = {
closeLabel: 'Close alert'
};
var Alert = function (_React$Component) {
_inherits(Alert, _React$Component);
function Alert() {
_classCallCheck(this, Alert);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Alert.prototype.render = function render() {
var _extends2;
var _props = this.props,
onDismiss = _props.onDismiss,
closeLabel = _props.closeLabel,
className = _props.className,
children = _props.children,
props = _objectWithoutProperties(_props, ['onDismiss', 'closeLabel', 'className', 'children']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var dismissable = !!onDismiss;
var classes = _extends({}, getClassSet(bsProps), (_extends2 = {}, _extends2[prefix(bsProps, 'dismissable')] = dismissable, _extends2));
return React.createElement(
'div',
_extends({}, elementProps, {
role: 'alert',
className: classNames(className, classes)
}),
dismissable && React.createElement(CloseButton, {
onClick: onDismiss,
label: closeLabel
}),
children
);
};
return Alert;
}(React.Component);
Alert.propTypes = propTypes;
Alert.defaultProps = defaultProps;
export default bsStyles(_Object$values(State), State.INFO, bsClass('alert', Alert)); |
app/javascript/mastodon/features/ui/components/media_modal.js | Ryanaka/mastodon | import React from 'react';
import ReactSwipeableViews from 'react-swipeable-views';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import Video from 'mastodon/features/video';
import classNames from 'classnames';
import { defineMessages, injectIntl } from 'react-intl';
import IconButton from 'mastodon/components/icon_button';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImageLoader from './image_loader';
import Icon from 'mastodon/components/icon';
import GIFV from 'mastodon/components/gifv';
import { disableSwiping } from 'mastodon/initial_state';
import Footer from 'mastodon/features/picture_in_picture/components/footer';
import { getAverageFromBlurhash } from 'mastodon/blurhash';
const messages = defineMessages({
close: { id: 'lightbox.close', defaultMessage: 'Close' },
previous: { id: 'lightbox.previous', defaultMessage: 'Previous' },
next: { id: 'lightbox.next', defaultMessage: 'Next' },
});
export default @injectIntl
class MediaModal extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.list.isRequired,
statusId: PropTypes.string,
index: PropTypes.number.isRequired,
onClose: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
onChangeBackgroundColor: PropTypes.func.isRequired,
currentTime: PropTypes.number,
autoPlay: PropTypes.bool,
volume: PropTypes.number,
};
state = {
index: null,
navigationHidden: false,
zoomButtonHidden: false,
};
handleSwipe = (index) => {
this.setState({ index: index % this.props.media.size });
}
handleTransitionEnd = () => {
this.setState({
zoomButtonHidden: false,
});
}
handleNextClick = () => {
this.setState({
index: (this.getIndex() + 1) % this.props.media.size,
zoomButtonHidden: true,
});
}
handlePrevClick = () => {
this.setState({
index: (this.props.media.size + this.getIndex() - 1) % this.props.media.size,
zoomButtonHidden: true,
});
}
handleChangeIndex = (e) => {
const index = Number(e.currentTarget.getAttribute('data-index'));
this.setState({
index: index % this.props.media.size,
zoomButtonHidden: true,
});
}
handleKeyDown = (e) => {
switch(e.key) {
case 'ArrowLeft':
this.handlePrevClick();
e.preventDefault();
e.stopPropagation();
break;
case 'ArrowRight':
this.handleNextClick();
e.preventDefault();
e.stopPropagation();
break;
}
}
componentDidMount () {
window.addEventListener('keydown', this.handleKeyDown, false);
this._sendBackgroundColor();
}
componentDidUpdate (prevProps, prevState) {
if (prevState.index !== this.state.index) {
this._sendBackgroundColor();
}
}
_sendBackgroundColor () {
const { media, onChangeBackgroundColor } = this.props;
const index = this.getIndex();
const blurhash = media.getIn([index, 'blurhash']);
if (blurhash) {
const backgroundColor = getAverageFromBlurhash(blurhash);
onChangeBackgroundColor(backgroundColor);
}
}
componentWillUnmount () {
window.removeEventListener('keydown', this.handleKeyDown);
this.props.onChangeBackgroundColor(null);
}
getIndex () {
return this.state.index !== null ? this.state.index : this.props.index;
}
toggleNavigation = () => {
this.setState(prevState => ({
navigationHidden: !prevState.navigationHidden,
}));
};
render () {
const { media, statusId, intl, onClose } = this.props;
const { navigationHidden } = this.state;
const index = this.getIndex();
const leftNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--left' onClick={this.handlePrevClick} aria-label={intl.formatMessage(messages.previous)}><Icon id='chevron-left' fixedWidth /></button>;
const rightNav = media.size > 1 && <button tabIndex='0' className='media-modal__nav media-modal__nav--right' onClick={this.handleNextClick} aria-label={intl.formatMessage(messages.next)}><Icon id='chevron-right' fixedWidth /></button>;
const content = media.map((image) => {
const width = image.getIn(['meta', 'original', 'width']) || null;
const height = image.getIn(['meta', 'original', 'height']) || null;
if (image.get('type') === 'image') {
return (
<ImageLoader
previewSrc={image.get('preview_url')}
src={image.get('url')}
width={width}
height={height}
alt={image.get('description')}
key={image.get('url')}
onClick={this.toggleNavigation}
zoomButtonHidden={this.state.zoomButtonHidden}
/>
);
} else if (image.get('type') === 'video') {
const { currentTime, autoPlay, volume } = this.props;
return (
<Video
preview={image.get('preview_url')}
blurhash={image.get('blurhash')}
src={image.get('url')}
width={image.get('width')}
height={image.get('height')}
frameRate={image.getIn(['meta', 'original', 'frame_rate'])}
currentTime={currentTime || 0}
autoPlay={autoPlay || false}
volume={volume || 1}
onCloseVideo={onClose}
detailed
alt={image.get('description')}
key={image.get('url')}
/>
);
} else if (image.get('type') === 'gifv') {
return (
<GIFV
src={image.get('url')}
width={width}
height={height}
key={image.get('preview_url')}
alt={image.get('description')}
onClick={this.toggleNavigation}
/>
);
}
return null;
}).toArray();
// you can't use 100vh, because the viewport height is taller
// than the visible part of the document in some mobile
// browsers when it's address bar is visible.
// https://developers.google.com/web/updates/2016/12/url-bar-resizing
const swipeableViewsStyle = {
width: '100%',
height: '100%',
};
const containerStyle = {
alignItems: 'center', // center vertically
};
const navigationClassName = classNames('media-modal__navigation', {
'media-modal__navigation--hidden': navigationHidden,
});
let pagination;
if (media.size > 1) {
pagination = media.map((item, i) => (
<button key={i} className={classNames('media-modal__page-dot', { active: i === index })} data-index={i} onClick={this.handleChangeIndex}>
{i + 1}
</button>
));
}
return (
<div className='modal-root__modal media-modal'>
<div className='media-modal__closer' role='presentation' onClick={onClose} >
<ReactSwipeableViews
style={swipeableViewsStyle}
containerStyle={containerStyle}
onChangeIndex={this.handleSwipe}
onTransitionEnd={this.handleTransitionEnd}
index={index}
disabled={disableSwiping}
>
{content}
</ReactSwipeableViews>
</div>
<div className={navigationClassName}>
<IconButton className='media-modal__close' title={intl.formatMessage(messages.close)} icon='times' onClick={onClose} size={40} />
{leftNav}
{rightNav}
<div className='media-modal__overlay'>
{pagination && <ul className='media-modal__pagination'>{pagination}</ul>}
{statusId && <Footer statusId={statusId} withOpenButton onClose={onClose} />}
</div>
</div>
</div>
);
}
}
|
apps/chat_app/web/static/js/containers/Root.js | nemanja-m/ex-chat | import React, { Component } from 'react';
import { connect } from 'react-redux';
import ChatRoom from './ChatRoom';
import Signup from './Signup';
import Login from './Login';
import AuthenticationRoute from '../components/AuthenticationRoute';
import { ConnectedRouter } from 'react-router-redux';
import { connectToSocket } from '../actions/session'
class Root extends Component {
componentDidMount() {
// Connect to Phoenix web socket.
if (!this.props.socket) {
this.props.connectToSocket();
}
}
render() {
const { currentUser } = this.props;
const authenticated = { visibility: 'AUTHENTICATED', currentUser };
const unauthenticated = { visibility: 'UNAUTHENTICATED', currentUser };
return (
<ConnectedRouter history={this.props.history}>
<div>
<AuthenticationRoute
exact path="/"
component={ChatRoom}
{...authenticated}
/>
<AuthenticationRoute
path="/signup"
component={Signup}
{...unauthenticated}
/>
<AuthenticationRoute
path="/login"
component={Login}
{...unauthenticated}
/>
</div>
</ConnectedRouter>
);
}
}
const mapStateToProps = (state) => {
return {
currentUser: state.session.currentUser,
socket: state.session.socket
};
};
const mapDispatchToProps = (dispatch) => {
return {
connectToSocket: () => { dispatch(connectToSocket()); }
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(Root);
|
src/pages/404.js | JTRiddick/jtr-webzone | import React from 'react'
const NotFoundPage = () => (
<div>
<h1>NOT FOUND</h1>
<p>You just hit a route that doesn't exist... the sadness.</p>
</div>
)
export default NotFoundPage
|
admin/client/App/components/Navigation/Mobile/ListItem.js | Pop-Code/keystone | /**
* A list item of the mobile navigation
*/
import React from 'react';
import { Link } from 'react-router';
const MobileListItem = React.createClass({
displayName: 'MobileListItem',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
href: React.PropTypes.string.isRequired,
onClick: React.PropTypes.func,
},
render () {
return (
<Link
className={this.props.className}
to={this.props.href}
onClick={this.props.onClick}
tabIndex="-1"
>
{this.props.children}
</Link>
);
},
});
module.exports = MobileListItem;
|
src/js/Tutorial/SlideShow.js | ludonow/ludo-beta-react | import React, { Component } from 'react';
import { Link } from 'react-router';
import styled from 'styled-components';
import Carousel from 'nuka-carousel';
import decorators from './decorators';
import {
desktopImageList,
mobileImageList
} from './imageList';
import { baseUrl } from '../baseurl-config';
const ImageWrapper = styled.div`
align-items: center;
border: 1px solid rgba(0,0,0,0.1);
display: flex;
height: 100%;
justify-content: center;
a, img {
height: 100%;
width: 100%;
}
`;
const Wrapper = styled.div`
margin: 20px auto;
width: 90%;
.slider-list, .slider-slide {
height: 80vh !important;
@media (max-width: 768px) {
height: 83vh !important;
}
}
@media (max-width: 768px) {
/* margin-top: 90px; */
width: 100%;
margin: 0;
.slider-decorator-2 {
bottom: -40px !important;
}
li > button {
padding: 0 2px !important;
}
}
`;
class SlideShow extends Component {
constructor() {
super();
this.state = { imageList: [] };
}
componentDidMount() {
const width = window.innerWidth || document.body.clientWidth;
const imageList = (width <= 768) ? mobileImageList : desktopImageList;
this.setState({ imageList });
}
render() {
const { imageList } = this.state;
return (
<Wrapper>
<Carousel decorators={decorators}>
{
imageList.map((image, index) => (
<ImageWrapper key={`slide-show-image-${index}`}>
{
index !== (imageList.length - 1) ?
<img src={image} />
:
<Link to={`${baseUrl}/cardList`}>
<img src={image} />
</Link>
}
</ImageWrapper>
))
}
</Carousel>
</Wrapper>
);
}
}
export default SlideShow;
|
src/app/Menu/MenuFeed.js | Sekhmet/busy | import React from 'react';
import { Link } from 'react-router';
import { FormattedMessage } from 'react-intl';
import Icon from '../../widgets/Icon';
const MenuFeed = ({ auth, category }) => {
const categoryUrl = category ? `/${category}` : '';
const channel = category || 'general';
return (
<ul className="app-nav">
<li>
<Link to={`/trending${categoryUrl}`} onlyActiveOnIndex activeClassName="active">
<Icon name="show_chart" />
<span className="hidden-xs">
{' '}<FormattedMessage id="trending" defaultMessage="Trending" />
</span>
</Link>
</li>
<li>
<Link to={`/created${categoryUrl}`} activeClassName="active">
<Icon name="fiber_new" />
<span className="hidden-xs">
{' '}<FormattedMessage id="new" defaultMessage="New" />
</span>
</Link>
</li>
<li>
<Link to={`/hot${categoryUrl}`} activeClassName="active">
<Icon name="whatshot" />
<span className="hidden-xs">
{' '}<FormattedMessage id="hot" defaultMessage="Hot" />
</span>
</Link>
</li>
<li>
<Link to={`/active${categoryUrl}`} activeClassName="active">
<Icon name="track_changes" />
<span className="hidden-xs">
{' '}<FormattedMessage id="active" defaultMessage="Active" />
</span>
</Link>
</li>
{auth.isAuthenticated &&
<li>
<Link to={`/messages/${channel}`} activeClassName="active">
<Icon name="chat_bubble_outline" />
<span className="hidden-xs">
{' '}<FormattedMessage id="chat" defaultMessage="Chat" />
</span>
</Link>
</li>
}
</ul>
);
};
export default MenuFeed;
|
src/SafeAnchor.js | xuorig/react-bootstrap | import React from 'react';
import createChainedFunction from './utils/createChainedFunction';
/**
* Note: This is intended as a stop-gap for accessibility concerns that the
* Bootstrap CSS does not address as they have styled anchors and not buttons
* in many cases.
*/
export default class SafeAnchor extends React.Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick(event) {
if (this.props.href === undefined) {
event.preventDefault();
}
}
render() {
return (
<a role={this.props.href ? undefined : 'button'}
{...this.props}
onClick={createChainedFunction(this.props.onClick, this.handleClick)}
href={this.props.href || ''}/>
);
}
}
SafeAnchor.propTypes = {
href: React.PropTypes.string,
onClick: React.PropTypes.func
};
|
storybook/createStory/CenterView/index.android.js | Fineighbor/ui-kit | import React from 'react'
import PropTypes from 'prop-types'
import { View } from 'react-native'
import style from './style'
export default function CenterView (props) {
return (
<View style={style.main}>
{props.children}
</View>
)
}
CenterView.defaultProps = {
children: null
}
CenterView.propTypes = {
children: PropTypes.node
}
|
ui/containers/not_found.js | danjac/podbaby | import React from 'react';
const PageNotFound = () => {
return (
<p className="lead">Sorry, nothing to find here.</p>
);
};
export default PageNotFound;
|
examples/src/app.js | serkanozer/react-select | /* eslint react/prop-types: 0 */
import React from 'react';
import ReactDOM from 'react-dom';
import Select from 'react-select';
import './example.less';
import Creatable from './components/Creatable';
import Contributors from './components/Contributors';
import GithubUsers from './components/GithubUsers';
import CustomComponents from './components/CustomComponents';
import CustomRender from './components/CustomRender';
import Multiselect from './components/Multiselect';
import NumericSelect from './components/NumericSelect';
import BooleanSelect from './components/BooleanSelect';
import Virtualized from './components/Virtualized';
import States from './components/States';
ReactDOM.render(
<div>
<States label="States" searchable />
<Multiselect label="Multiselect" />
<Virtualized label="Virtualized" />
<Contributors label="Contributors (Async)" />
<GithubUsers label="GitHub users (Async with fetch.js)" />
<NumericSelect label="Numeric Values" />
<BooleanSelect label="Boolean Values" />
<CustomRender label="Custom Render Methods"/>
<CustomComponents label="Custom Placeholder, Option, Value, and Arrow Components" />
<Creatable
hint="Enter a value that's NOT in the list, then hit return"
label="Custom tag creation"
/>
</div>,
document.getElementById('example')
);
|
src/content/work/assets/SubscriptionsForSaas/modules/List/Icons/Close/index.js | jmikrut/keen-2017 | import React from 'react';
import './Close.css';
export default (props) => {
let color = props.color ? props.color : '';
return (
<svg className="plus" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 12 12">
<line stroke={color} x1="8.24" y1="3.76" x2="3.76" y2="8.24"/>
<line stroke={color} x1="8.24" y1="8.24" x2="3.76" y2="3.76"/>
</svg>
);
} |
examples/amp-first/components/amp/AmpState.js | flybayer/next.js | import PropTypes from 'prop-types'
import React from 'react'
import { AmpIncludeAmpBind } from './AmpCustomElement'
/**
* Renders an amp-state element, by either adding local state via `value`
* or remote state via the `src` property.
*
* @param {Props} props
*/
export default function AmpState(props) {
return (
<>
<AmpIncludeAmpBind />
<amp-state id={props.id} src={props.src}>
{props.children && (
<script
type="application/json"
dangerouslySetInnerHTML={{
__html: JSON.stringify(props.children),
}}
/>
)}
</amp-state>
</>
)
}
AmpState.propTypes = {
id: PropTypes.string.isRequired,
children: PropTypes.any,
src: PropTypes.string,
}
|
app/javascript/mastodon/features/compose/components/navigation_bar.js | riku6460/chikuwagoddon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ActionBar from './action_bar';
import Avatar from '../../../components/avatar';
import Permalink from '../../../components/permalink';
import IconButton from '../../../components/icon_button';
import { FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class NavigationBar extends ImmutablePureComponent {
static propTypes = {
account: ImmutablePropTypes.map.isRequired,
onClose: PropTypes.func,
};
render () {
return (
<div className='navigation-bar'>
<Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}>
<span style={{ display: 'none' }}>{this.props.account.get('acct')}</span>
<Avatar account={this.props.account} size={40} />
</Permalink>
<div className='navigation-bar__profile'>
<Permalink href={this.props.account.get('url')} to={`/accounts/${this.props.account.get('id')}`}>
<strong className='navigation-bar__profile-account'>@{this.props.account.get('acct')}</strong>
</Permalink>
<a href='/settings/profile' className='navigation-bar__profile-edit'><FormattedMessage id='navigation_bar.edit_profile' defaultMessage='Edit profile' /></a>
</div>
<div className='navigation-bar__actions'>
<IconButton className='close' title='' icon='close' onClick={this.props.onClose} />
<ActionBar account={this.props.account} />
</div>
</div>
);
}
}
|
src/index.js | bdougie/react-relay-instagram-example | import React from 'react'
import Relay from 'react-relay'
import ReactDOM from 'react-dom'
import ListPage from './components/ListPage'
import CreatePage from './components/CreatePage'
import { Router, Route, browserHistory, applyRouterMiddleware } from 'react-router'
import useRelay from 'react-router-relay'
import './index.css'
// The x-graphcool-source header is to let the server know that the example app has started.
// (Not necessary for normal projects)
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer(process.env.GRAPHQL_URL, {
headers: {
'x-graphcool-source': 'example:react-relay-instagram',
},
})
)
const ViewerQueries = { viewer: () => Relay.QL`query { viewer }` }
ReactDOM.render(
<Router
forceFetch
environment={Relay.Store}
render={applyRouterMiddleware(useRelay)}
history={browserHistory}
>
<Route path='/' component={ListPage} queries={ViewerQueries} />
<Route path='/create' component={CreatePage} queries={ViewerQueries} />
</Router>
, document.getElementById('root')
)
|
app/javascript/mastodon/features/notifications/components/column_settings.js | mosaxiv/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import ClearColumnButton from './clear_column_button';
import SettingToggle from './setting_toggle';
export default class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
pushSettings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
};
onPushChange = (path, checked) => {
this.props.onChange(['push', ...path], checked);
}
render () {
const { settings, pushSettings, onChange, onClear } = this.props;
const alertStr = <FormattedMessage id='notifications.column_settings.alert' defaultMessage='Desktop notifications' />;
const showStr = <FormattedMessage id='notifications.column_settings.show' defaultMessage='Show in column' />;
const soundStr = <FormattedMessage id='notifications.column_settings.sound' defaultMessage='Play sound' />;
const showPushSettings = pushSettings.get('browserSupport') && pushSettings.get('isSubscribed');
const pushStr = showPushSettings && <FormattedMessage id='notifications.column_settings.push' defaultMessage='Push notifications' />;
const pushMeta = showPushSettings && <FormattedMessage id='notifications.column_settings.push_meta' defaultMessage='This device' />;
return (
<div>
<div className='column-settings__row'>
<ClearColumnButton onClick={onClear} />
</div>
<div role='group' aria-labelledby='notifications-follow'>
<span id='notifications-follow' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow' defaultMessage='New followers:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-favourite'>
<span id='notifications-favourite' className='column-settings__section'><FormattedMessage id='notifications.column_settings.favourite' defaultMessage='Favourites:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'favourite']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'favourite']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'favourite']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'favourite']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-mention'>
<span id='notifications-mention' className='column-settings__section'><FormattedMessage id='notifications.column_settings.mention' defaultMessage='Mentions:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'mention']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'mention']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'mention']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'mention']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-reblog'>
<span id='notifications-reblog' className='column-settings__section'><FormattedMessage id='notifications.column_settings.reblog' defaultMessage='Boosts:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'reblog']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'reblog']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'reblog']} onChange={onChange} label={soundStr} />
</div>
</div>
</div>
);
}
}
|
src/layouts/index.js | brickandgreens/bricks-and-greens-gatsby | import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import Helmet from 'react-helmet'
import './index.css'
const Header = () => (
<div
style={{
background: 'rebeccapurple',
marginBottom: '1.45rem',
}}
>
<div
style={{
margin: '0 auto',
maxWidth: 960,
padding: '1.45rem 1.0875rem',
}}
>
<h1 style={{ margin: 0 }}>
<Link
to="/"
style={{
color: 'white',
textDecoration: 'none',
}}
>
Gatsby
</Link>
</h1>
</div>
</div>
)
const TemplateWrapper = ({ children }) => (
<div>
<Helmet
title="Gatsby Default Starter"
meta={[
{ name: 'description', content: 'Sample' },
{ name: 'keywords', content: 'sample, something' },
]}
/>
<Header />
<div
style={{
margin: '0 auto',
maxWidth: 960,
padding: '0px 1.0875rem 1.45rem',
paddingTop: 0,
}}
>
{children()}
</div>
</div>
)
TemplateWrapper.propTypes = {
children: PropTypes.func,
}
export default TemplateWrapper
|
src/Button.js | wjb12/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import CustomPropTypes from './utils/CustomPropTypes';
import ButtonInput from './ButtonInput';
const Button = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
block: React.PropTypes.bool,
navItem: React.PropTypes.bool,
navDropdown: React.PropTypes.bool,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType,
href: React.PropTypes.string,
target: React.PropTypes.string,
/**
* Defines HTML button type Attribute
* @type {("button"|"reset"|"submit")}
* @defaultValue 'button'
*/
type: React.PropTypes.oneOf(ButtonInput.types)
},
getDefaultProps() {
return {
active: false,
block: false,
bsClass: 'button',
bsStyle: 'default',
disabled: false,
navItem: false,
navDropdown: false
};
},
render() {
let classes = this.props.navDropdown ? {} : this.getBsClassSet();
let renderFuncName;
classes = {
active: this.props.active,
'btn-block': this.props.block,
...classes
};
if (this.props.navItem) {
return this.renderNavItem(classes);
}
renderFuncName = this.props.href || this.props.target || this.props.navDropdown ?
'renderAnchor' : 'renderButton';
return this[renderFuncName](classes);
},
renderAnchor(classes) {
let Component = this.props.componentClass || 'a';
let href = this.props.href || '#';
classes.disabled = this.props.disabled;
return (
<Component
{...this.props}
href={href}
className={classNames(this.props.className, classes)}
role="button">
{this.props.children}
</Component>
);
},
renderButton(classes) {
let Component = this.props.componentClass || 'button';
return (
<Component
{...this.props}
type={this.props.type || 'button'}
className={classNames(this.props.className, classes)}>
{this.props.children}
</Component>
);
},
renderNavItem(classes) {
let liClasses = {
active: this.props.active
};
return (
<li className={classNames(liClasses)}>
{this.renderAnchor(classes)}
</li>
);
}
});
export default Button;
|
docs/app/Examples/elements/Loader/Types/LoaderExampleText.js | koenvg/Semantic-UI-React | import React from 'react'
import { Dimmer, Loader, Image, Segment } from 'semantic-ui-react'
const LoaderExampleText = () => (
<div>
<Segment>
<Dimmer active>
<Loader>Loading</Loader>
</Dimmer>
<Image src='http://semantic-ui.com/images/wireframe/short-paragraph.png' />
</Segment>
<Segment>
<Dimmer active inverted>
<Loader inverted>Loading</Loader>
</Dimmer>
<Image src='http://semantic-ui.com/images/wireframe/short-paragraph.png' />
</Segment>
</div>
)
export default LoaderExampleText
|
src/svg-icons/editor/monetization-on.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorMonetizationOn = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm1.41 16.09V20h-2.67v-1.93c-1.71-.36-3.16-1.46-3.27-3.4h1.96c.1 1.05.82 1.87 2.65 1.87 1.96 0 2.4-.98 2.4-1.59 0-.83-.44-1.61-2.67-2.14-2.48-.6-4.18-1.62-4.18-3.67 0-1.72 1.39-2.84 3.11-3.21V4h2.67v1.95c1.86.45 2.79 1.86 2.85 3.39H14.3c-.05-1.11-.64-1.87-2.22-1.87-1.5 0-2.4.68-2.4 1.64 0 .84.65 1.39 2.67 1.91s4.18 1.39 4.18 3.91c-.01 1.83-1.38 2.83-3.12 3.16z"/>
</SvgIcon>
);
EditorMonetizationOn = pure(EditorMonetizationOn);
EditorMonetizationOn.displayName = 'EditorMonetizationOn';
EditorMonetizationOn.muiName = 'SvgIcon';
export default EditorMonetizationOn;
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | atlanthot/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/components/time_ago.js | Helabs/handup-web | import React from 'react';
import moment from 'moment';
import TimedRender from './timed_render';
export default function TimeAgo({ time }) {
return <TimedRender contentProvider={timeFromNow} />;
function timeFromNow() {
return moment(time).fromNow();
}
}
|
src/components/Audioplayer/Track/index.js | hasibsahibzada/quran.com-frontend | /* eslint-disable jsx-a11y/no-static-element-interactions */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styled from 'styled-components';
const Container = styled.div`
height: 6px;
width: 100%;
background-color: #f7f7f7;
cursor: pointer;
margin-bottom: 5px;
`;
const Progress = styled.div`
height: 100%;
background-color: ${props => props.theme.brandPrimary};
position: relative;
padding-left: 12px;
&:after {
content: '';
height: 12px;
width: 12px;
border-radius: 10px;
position: absolute;
right: 0;
display: block;
background: #fff;
top: -3px;
box-shadow: 0 1px 2px rgba(0, 0, 0, 0.45);
transition: height 0.5s;
}
`;
export default class Track extends Component {
static propTypes = {
progress: PropTypes.number.isRequired,
onTrackChange: PropTypes.func.isRequired
};
handleClick = (event) => {
const { onTrackChange } = this.props;
const fraction =
event.nativeEvent.offsetX / this.container.getBoundingClientRect().width;
return onTrackChange(fraction);
};
render() {
const { progress } = this.props;
return (
<Container
ref={(container) => {
this.container = container;
}}
onClick={this.handleClick}
>
<Progress style={{ width: `${progress}%` }} />
</Container>
);
}
}
|
src/components/SplashScreen.js | ontappl/rn | import React from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
import {colors,} from './styles';
export const SplashScreen = () => (
<View style={styles.container}>
<Text>Ładowanie...</Text>
</View>
);
const styles = StyleSheet.create({
container: {
flex: 1,
alignItems: 'center',
justifyContent: 'center',
},
text: {
fontSize: 16,
color: colors.text.disabled,
},
});
|
webapp-src/src/Admin/SchemeMod.js | babelouest/glewlwyd | import React, { Component } from 'react';
import i18next from 'i18next';
import apiManager from '../lib/APIManager';
import messageDispatcher from '../lib/MessageDispatcher';
class SchemeMod extends Component {
constructor(props) {
super(props);
this.state = {
config: props.config,
mods: props.mods,
curMod: {},
types: props.types,
loggedIn: props.loggedIn
}
this.addMod = this.addMod.bind(this);
this.editMod = this.editMod.bind(this);
this.deleteMod = this.deleteMod.bind(this);
this.switchModStatus = this.switchModStatus.bind(this);
}
componentWillReceiveProps(nextProps) {
this.setState({
mods: nextProps.mods,
types: nextProps.types,
loggedIn: nextProps.loggedIn
});
}
addMod(e) {
messageDispatcher.sendMessage('App', {type: "add", role: "schemeMod"});
}
editMod(e, mod, index) {
messageDispatcher.sendMessage('App', {type: "edit", role: "schemeMod", mod: mod, index: index});
}
deleteMod(e, mod) {
messageDispatcher.sendMessage('App', {type: "delete", role: "schemeMod", mod: mod});
}
switchModStatus(mod) {
var action = (mod.enabled?"disable":"enable");
apiManager.glewlwydRequest("/mod/scheme/" + encodeURIComponent(mod.name) + "/" + action + "/", "PUT")
.then(() => {
messageDispatcher.sendMessage('Notification', {type: "success", message: i18next.t("admin.success-api-edit-mod")});
})
.fail((err) => {
if (err.status === 400) {
messageDispatcher.sendMessage('Notification', {type: "danger", message: JSON.stringify(err.responseJSON)});
}
messageDispatcher.sendMessage('Notification', {type: "danger", message: i18next.t("admin.error-api-edit-mod")});
})
.always(() => {
messageDispatcher.sendMessage('App', {type: "refresh", role: "schemeMod", mod: mod});
});
}
render() {
var mods = [];
this.state.mods.forEach((mod, index) => {
var module = "", switchButton = "", switchButtonSmall;
this.state.types.forEach((type) => {
if (mod.module === type.name) {
module = type.display_name;
}
});
if (mod.enabled) {
switchButton = <button type="button" className="btn btn-secondary" onClick={(e) => this.switchModStatus(mod)} title={i18next.t("admin.switch-off")}>
<i className="fas fa-toggle-on"></i>
</button>;
switchButtonSmall = <a className="dropdown-item" href="#" onClick={(e) => this.switchModStatus(mod)} alt={i18next.t("admin.switch-off")}>
<i className="fas fa-toggle-on btn-icon"></i>
{i18next.t("admin.switch-off")}
</a>
} else {
switchButton = <button type="button" className="btn btn-secondary" onClick={(e) => this.switchModStatus(mod)} title={i18next.t("admin.switch-on")}>
<i className="fas fa-toggle-off"></i>
</button>;
switchButtonSmall = <a className="dropdown-item" href="#" onClick={(e) => this.switchModStatus(mod)} alt={i18next.t("admin.switch-on")}>
<i className="fas fa-toggle-off btn-icon"></i>
{i18next.t("admin.switch-on")}
</a>
}
mods.push(<tr key={index} className={(!mod.enabled?"table-danger":"")}>
<td>{module}</td>
<td>{mod.name}</td>
<td className="d-none d-lg-table-cell">{mod.display_name||""}</td>
<td className="d-none d-lg-table-cell">{(mod.enabled?i18next.t("yes"):i18next.t("no"))}</td>
<td>
<div className="btn-group d-none d-lg-table-cell" role="group">
{switchButton}
<button type="button" className="btn btn-secondary" onClick={(e) => this.editMod(e, mod, index)} title={i18next.t("admin.edit")}>
<i className="fas fa-edit"></i>
</button>
<button type="button" className="btn btn-secondary" onClick={(e) => this.deleteMod(e, mod)} title={i18next.t("admin.delete")}>
<i className="fas fa-trash"></i>
</button>
</div>
<div className="dropdown d-block d-lg-none">
<button className="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenuNav" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
<i className="fas fa-chevron-circle-down"></i>
</button>
<div className="dropdown-menu" aria-labelledby="dropdownMenuNav">
{switchButtonSmall}
<a className="dropdown-item" href="#" onClick={(e) => this.editMod(e, mod, index)} alt={i18next.t("admin.edit")}>
<i className="fas fa-edit btn-icon"></i>
{i18next.t("admin.edit")}
</a>
<a className="dropdown-item" href="#" onClick={(e) => this.deleteMod(e, mod)} alt={i18next.t("admin.delete")}>
<i className="fas fa-trash btn-icon"></i>
{i18next.t("admin.delete")}
</a>
</div>
</div>
</td>
</tr>);
});
return (
<table className="table table-responsive table-striped">
<thead>
<tr>
<th colSpan="4">
<h4>{i18next.t("admin.scheme-mod-list-title")}</h4>
<div className="btn-group" role="group">
<button disabled={!this.state.loggedIn} type="button" className="btn btn-secondary" onClick={(e) => this.addMod(e)} title={i18next.t("admin.add")}>
<i className="fas fa-plus"></i>
</button>
</div>
</th>
</tr>
<tr>
<th>
{i18next.t("admin.type")}
</th>
<th>
{i18next.t("admin.name")}
</th>
<th className="d-none d-lg-table-cell">
{i18next.t("admin.display-name")}
</th>
<th className="d-none d-lg-table-cell">
{i18next.t("admin.enabled")}
</th>
<th>
</th>
</tr>
</thead>
<tbody>
{mods}
</tbody>
</table>
);
}
}
export default SchemeMod;
|
app/components/Settings/Settings.js | leesander1/hearmenow-electron | import React, { Component } from 'react';
// import { Link } from 'react-router';
import styles from './Settings.css';
export default class Settings extends Component {
render() {
return (
<div>
<h4>Settings</h4>
</div>
);
}
}
|
examples/auth-with-shared-root/components/PageOne.js | taion/rrtr | import React from 'react'
const PageOne = React.createClass({
render() {
return <h2>Page One!</h2>
}
})
export default PageOne
|
modules/Home/SearchBox.js | cloudytimemachine/frontend | import React from 'react'
import { Link } from 'react-router'
import SearchBox from '../Common/SearchBox'
export default React.createClass({
render() {
return (
<div className="searchBox">
<h4>Search the history for a domain or URL</h4>
<SearchBox />
</div>
)
}
})
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.