path
stringlengths 5
296
| repo_name
stringlengths 5
85
| content
stringlengths 25
1.05M
|
|---|---|---|
src/settings/Layout.js
|
NewSpring/Apollos
|
import React from 'react';
import PropTypes from 'prop-types';
import BackgroundView from '@ui/BackgroundView';
import { ResponsiveSideBySideView as SideBySideView, Right, Left } from '@ui/SideBySideView';
import withUser from '@data/withUser';
import UserAvatarView from '@ui/UserAvatarView';
import MediaQuery from '@ui/MediaQuery';
import styled from '@ui/styled';
import Header from '@ui/Header';
export { ProfileDetails, ProfileAddress, ChangePassword } from './forms';
const CurrentUserAvatar = withUser(UserAvatarView);
const DesktopCurrentUserAvatar = styled({ height: '100%' })(CurrentUserAvatar);
const FlexedSideBySideView = styled({ flex: 1 })(SideBySideView);
const FlexedLeft = styled({ flex: 1 })(Left);
const Layout = ({ children, title }) => (
<BackgroundView>
<Header webEnabled titleText={title} backButton />
<FlexedSideBySideView>
<FlexedLeft>{children}</FlexedLeft>
<MediaQuery minWidth="md">
<Right>
<DesktopCurrentUserAvatar allowProfileImageChange />
</Right>
</MediaQuery>
</FlexedSideBySideView>
</BackgroundView>
);
Layout.propTypes = {
children: PropTypes.node,
title: PropTypes.string,
};
export default Layout;
|
frontend/src/Settings/Profiles/Delay/DelayProfileDragSource.js
|
geogolem/Radarr
|
import classNames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { DragSource, DropTarget } from 'react-dnd';
import { findDOMNode } from 'react-dom';
import { DELAY_PROFILE } from 'Helpers/dragTypes';
import DelayProfile from './DelayProfile';
import styles from './DelayProfileDragSource.css';
const delayProfileDragSource = {
beginDrag(item) {
return item;
},
endDrag(props, monitor, component) {
props.onDelayProfileDragEnd(monitor.getItem(), monitor.didDrop());
}
};
const delayProfileDropTarget = {
hover(props, monitor, component) {
const dragIndex = monitor.getItem().order;
const hoverIndex = props.order;
const hoverBoundingRect = findDOMNode(component).getBoundingClientRect();
const hoverMiddleY = (hoverBoundingRect.bottom - hoverBoundingRect.top) / 2;
const clientOffset = monitor.getClientOffset();
const hoverClientY = clientOffset.y - hoverBoundingRect.top;
if (dragIndex === hoverIndex) {
return;
}
// When moving up, only trigger if drag position is above 50% and
// when moving down, only trigger if drag position is below 50%.
// If we're moving down the hoverIndex needs to be increased
// by one so it's ordered properly. Otherwise the hoverIndex will work.
if (dragIndex < hoverIndex && hoverClientY > hoverMiddleY) {
props.onDelayProfileDragMove(dragIndex, hoverIndex + 1);
} else if (dragIndex > hoverIndex && hoverClientY < hoverMiddleY) {
props.onDelayProfileDragMove(dragIndex, hoverIndex);
}
}
};
function collectDragSource(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
}
function collectDropTarget(connect, monitor) {
return {
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver()
};
}
class DelayProfileDragSource extends Component {
//
// Render
render() {
const {
id,
order,
isDragging,
isDraggingUp,
isDraggingDown,
isOver,
connectDragSource,
connectDropTarget,
...otherProps
} = this.props;
const isBefore = !isDragging && isDraggingUp && isOver;
const isAfter = !isDragging && isDraggingDown && isOver;
// if (isDragging && !isOver) {
// return null;
// }
return connectDropTarget(
<div
className={classNames(
styles.delayProfileDragSource,
isBefore && styles.isDraggingUp,
isAfter && styles.isDraggingDown
)}
>
{
isBefore &&
<div
className={classNames(
styles.delayProfilePlaceholder,
styles.delayProfilePlaceholderBefore
)}
/>
}
<DelayProfile
id={id}
order={order}
isDragging={isDragging}
isOver={isOver}
{...otherProps}
connectDragSource={connectDragSource}
/>
{
isAfter &&
<div
className={classNames(
styles.delayProfilePlaceholder,
styles.delayProfilePlaceholderAfter
)}
/>
}
</div>
);
}
}
DelayProfileDragSource.propTypes = {
id: PropTypes.number.isRequired,
order: PropTypes.number.isRequired,
isDragging: PropTypes.bool,
isDraggingUp: PropTypes.bool,
isDraggingDown: PropTypes.bool,
isOver: PropTypes.bool,
connectDragSource: PropTypes.func,
connectDropTarget: PropTypes.func,
onDelayProfileDragMove: PropTypes.func.isRequired,
onDelayProfileDragEnd: PropTypes.func.isRequired
};
export default DropTarget(
DELAY_PROFILE,
delayProfileDropTarget,
collectDropTarget
)(DragSource(
DELAY_PROFILE,
delayProfileDragSource,
collectDragSource
)(DelayProfileDragSource));
|
src/controls/Inline/index.js
|
michalko/draft-wyswig
|
/* @flow */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { getSelectionInlineStyle } from 'draftjs-utils';
import { RichUtils, EditorState, Modifier } from 'draft-js';
import { forEach } from '../../utils/common';
import LayoutComponent from './Component';
export default class Inline extends Component {
static propTypes = {
onChange: PropTypes.func.isRequired,
editorState: PropTypes.object.isRequired,
modalHandler: PropTypes.object,
config: PropTypes.object,
translations: PropTypes.object,
};
state: Object = {
currentStyles: {},
};
componentWillMount(): void {
const { editorState, modalHandler } = this.props;
if (editorState) {
this.setState({
currentStyles: this.changeKeys(getSelectionInlineStyle(editorState)),
});
}
modalHandler.registerCallBack(this.expandCollapse);
}
componentWillReceiveProps(properties: Object): void {
if (properties.editorState &&
this.props.editorState !== properties.editorState) {
this.setState({
currentStyles: this.changeKeys(getSelectionInlineStyle(properties.editorState)),
});
}
}
componentWillUnmount(): void {
const { modalHandler } = this.props;
modalHandler.deregisterCallBack(this.expandCollapse);
}
onExpandEvent: Function = (): void => {
this.signalExpanded = !this.state.expanded;
};
expandCollapse: Function = (): void => {
this.setState({
expanded: this.signalExpanded,
});
this.signalExpanded = false;
}
toggleInlineStyle: Function = (style: string): void => {
const newStyle = style === 'monospace' ? 'CODE' : style.toUpperCase();
const { editorState, onChange } = this.props;
let newState = RichUtils.toggleInlineStyle(
editorState,
newStyle,
);
if (style === 'subscript' || style === 'superscript') {
const removeStyle = style === 'subscript' ? 'SUPERSCRIPT' : 'SUBSCRIPT';
const contentState = Modifier.removeInlineStyle(
newState.getCurrentContent(),
newState.getSelection(),
removeStyle,
);
newState = EditorState.push(newState, contentState, 'change-inline-style');
}
if (newState) {
onChange(newState);
}
};
changeKeys = (style) => {
if (style) {
const st = {};
forEach(style, (key, value) => {
st[key === 'CODE' ? 'monospace' : key.toLowerCase()] = value;
});
return st;
}
return undefined;
}
doExpand: Function = (): void => {
this.setState({
expanded: true,
});
};
doCollapse: Function = (): void => {
this.setState({
expanded: false,
});
};
render(): Object {
const { config, translations } = this.props;
const { expanded, currentStyles } = this.state;
const InlineComponent = config.component || LayoutComponent;
return (
<InlineComponent
config={config}
translations={translations}
currentState={currentStyles}
expanded={expanded}
onExpandEvent={this.onExpandEvent}
doExpand={this.doExpand}
doCollapse={this.doCollapse}
onChange={this.toggleInlineStyle}
/>
);
}
}
// make subscript less low
|
Intermediate Front End Development Projects/twitch-client/src/App.js
|
shashank7200/FreeCodeCamp-Projects
|
import React, { Component } from 'react';
import Home from './helpers/Home'
import './App.css'
class App extends Component {
render() {
return (
<div className="App">
<Home />
</div>
);
}
}
export default App;
|
src/components/grid.js
|
JiaoJian1221/react-mdc-web
|
import React from 'react';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import "@material/layout-grid/dist/mdc.layout-grid.min.css";
const LAYOUT_GRID = 'mdc-layout-grid';
export class Grid extends React.Component {
static propTypes = {
className: PropTypes.string,
children: PropTypes.node,
}
render() {
let {className, children, ...otherProps} = this.props;
return (
<div className={classnames(LAYOUT_GRID, className)} {...otherProps}>
<div className={`${LAYOUT_GRID}__inner`}> {children} </div>
</div>
);
}
}
export class Cell extends React.Component {
static propTypes = {
align: PropTypes.oneOf(['top', 'middle', 'bottom']),
className: PropTypes.string,
col: PropTypes.number,
order: PropTypes.number,
phone: PropTypes.number,
tablet: PropTypes.number,
};
render() {
let {className, align, col, order, phone, tablet, children, ...otherProps} = this.props;
return (
<div className={classnames(`${LAYOUT_GRID}__cell`, {
[`${LAYOUT_GRID}__cell--span-${col}`]: col,
[`${LAYOUT_GRID}__cell--span-${tablet}-tablet`]: tablet,
[`${LAYOUT_GRID}__cell--span-${phone}-phone`]: phone,
[`${LAYOUT_GRID}__cell--order-${order}`]: order,
[`${LAYOUT_GRID}__cell--align-${align}`]: align,
}, className)} {...otherProps}>{children}</div>
);
}
}
|
src/Parser/GuardianDruid/Modules/Core/DamageTaken.js
|
Yuyz0112/WoWAnalyzer
|
import React from 'react';
import { formatThousands, formatNumber, formatPercentage } from 'common/format';
import MainDamageTaken from 'Parser/Core/Modules/DamageTaken';
import Icon from 'common/Icon';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
class DamageTaken extends MainDamageTaken {
statistic() {
return (
<StatisticBox
icon={<Icon icon="class_druid" alt="Damage taken" />}
value={`${formatNumber(this.totalDamage.total / this.owner.fightDuration * 1000)} DTPS`}
label='Damage taken'
tooltip={`Damage taken breakdown:
<ul>
${Object.keys(this.damageBySchool).reduce((v, type) => {
return v+=`<li>${type} damage taken ${formatThousands(this.damageBySchool[type].total)} (${formatPercentage(this.damageBySchool[type].total/this.totalDamage.total)}%)</li>`;
}, '')}
</ul>
Total damage taken ${formatThousands(this.totalDamage.total)} (${formatThousands(this.totalDamage.overkill)} overkill)`}
/>
);
}
statisticOrder = STATISTIC_ORDER.CORE(0);
}
export default DamageTaken;
|
src/renderer/views/root.js
|
minodisk/markn
|
import React from 'react'
import classnames from 'classnames'
import Head from './head'
import Body from './body'
import windowStore from '../stores/window'
import appAction from '../actions/app'
export default class RootComponent extends React.Component {
displayName = 'RootComponent'
constructor (props) {
super(props)
this.state = {
isFocused: false
}
windowStore.on('focus', this.onWindowFocus.bind(this))
windowStore.on('blur', this.onWindowBlur.bind(this))
}
onWindowFocus () {
this.setState({
isFocused: true
})
}
onWindowBlur () {
this.setState({
isFocused: false
})
}
render () {
return (
<div ref='root' className={classnames('root', {'is-focused': this.state.isFocused})}>
<Head/>
<Body/>
</div>
)
}
componentDidMount () {
appAction.ready()
}
}
|
scenes/NotesEditScene.js
|
hailey123/react-native-notes
|
import React, { Component } from 'react';
import {
View,
Text,
Navigator,
TouchableHighlight
} from 'react-native';
export default class NotesEditScene extends Component {
render() {
return (
<View>
<Text>Edit Notes Here</Text>
<Text>Editing {this.props.content}</Text>
</View>
)
}
}
|
client/pages/Sandbox.js
|
fatiherikli/komposto.org
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Layout from '../components/Layout';
import Canvas from '../components/Canvas';
import Editor from '../components/Editor';
import { messages } from '../constants';
import { parse } from '../parser';
export default class SandboxContainer extends Component {
constructor(props, context) {
super(props, context);
this.state = {
lines: [],
running: true,
};
this.onInputKeyDown = this.onInputKeyDown.bind(this);
this.onInputKeyUp = this.onInputKeyUp.bind(this);
this.updateLines = this.updateLines.bind(this);
this.externalCalls = {
'/save': this.save.bind(this),
'/fork': this.fork.bind(this),
'/undo': this.undo.bind(this),
'/help': this.help.bind(this),
'/run': this.run.bind(this),
'/pause': this.pause.bind(this),
};
}
componentDidMount() {
this.inputRef.focus();
this.setState({
lines: window.__INITIAL_DATA__.content || []
});
}
onInputKeyDown(event) {
const { lines } = this.state;
const { value } = event.target;
if (event.key === 'Enter') {
if (value in this.externalCalls) {
this.externalCalls[value]();
} else {
this.setState({
lines: parse(lines, value)
});
}
event.target.value = null;
}
}
getLineByNo(no) {
const { lines } = this.state;
return lines[lines.length - no];
}
onInputKeyUp(event) {
const { value } = event.target;
if (
value.slice(0, 1) === '/' &&
event.key !== 'Backspace'
) {
const parts = value.split(' ');
if (
parts.length === 2 &&
parts[1].length === 0
) {
const number = parts[0].slice(1);
const line = this.getLineByNo(number);
const code = line || '';
const position = value.indexOf(' ') + 1;
event.target.value = `/${number} ${code}`;
event.target.setSelectionRange(
position,
position + code.length
);
}
}
}
postMessage(message) {
parent.postMessage(JSON.stringify(message), '*');
}
save() {
this.postMessage({
message: messages.UPDATE_LINES,
lines: this.state.lines,
snapshot: this.canvasRef.takeSnapshot()
});
}
fork() {
this.postMessage({
message: messages.FORK_SKETCH,
lines: this.state.lines,
snapshot: this.canvasRef.takeSnapshot()
});
}
updateLines(lines) {
this.setState({ lines });
}
undo() {
const { lines } = this.state;
this.setState({
lines: lines.slice(1),
});
}
pause() {
this.setState({
running: false,
});
}
run() {
this.setState({
running: true,
});
}
help() {
this.postMessage({
message: messages.TOGGLE_HELP,
});
}
render() {
const { lines } = this.state;
return (
<Layout>
<Canvas
lines={ lines }
updateLines={ this.updateLines }
running={ this.state.running }
ref={ ref => this.canvasRef = ref }
/>
<Editor
lines={ lines }
onInputKeyDown={ this.onInputKeyDown }
onInputKeyUp={ this.onInputKeyUp }
inputRef={ ref => this.inputRef = ref }
/>
</Layout>
);
}
}
|
web/dashboard/src/layout/ReactPanel.js
|
unicesi/pascani-library
|
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
require("../img/close.png");
require("../img/expand.png");
require("../img/collapse.png");
class ReactPanel extends Component {
static defaultProps = {
active: false,
floating: false,
width: 'regular',
id: undefined,
onBeforeOpen: (panel) => {},
onBeforeClose: (panel) => {},
onResize: (width) => {},
claimActiveState: (panel) => {},
closePanel: (panel) => {},
}
static propTypes = {
active: React.PropTypes.bool,
floating: React.PropTypes.bool,
width: React.PropTypes.string,
id: React.PropTypes.string,
onBeforeOpen: React.PropTypes.func,
onBeforeClose: React.PropTypes.func,
onResize: React.PropTypes.func,
claimActiveState: React.PropTypes.func,
closePanel: React.PropTypes.func,
}
state = {
expanded: false,
width: undefined,
}
constructor(props) {
super(props);
}
componentWillMount() {
this.props.onBeforeOpen(this);
}
onMouseDown = (e) => {
e.stopPropagation();
e.preventDefault();
// only left mouse button
if (e.button !== 0) return;
document.addEventListener('mousemove', this.onMouseMove);
document.addEventListener('mouseup', this.onMouseUp);
}
onMouseMove = (e) => {
e.stopPropagation();
e.preventDefault();
const offset = $(this.refs.container).offset();
const width = e.pageX - offset.left + 1;
this.setState({ width: width });
this.props.onResize(width);
}
onMouseUp = (e) => {
e.stopPropagation();
e.preventDefault();
document.removeEventListener('mousemove', this.onMouseMove);
}
componentWillUnmount() {
this.props.onBeforeClose(this);
}
close = () => {
this.props.closePanel(this);
this.setState({ expanded: false });
}
expand = () => {
this.setState({ expanded: true });
this.props.claimActiveState(this);
}
collapse = () => {
this.setState({ expanded: false });
this.props.claimActiveState(this);
}
handlePanelClick = (e) => {
if(typeof e.target.className.indexOf !== "function")
return;
if (e.target.className.indexOf("close") > -1) {
this.close();
} else if (e.target.className.indexOf("expand") > -1) {
this.expand();
} else if (e.target.className.indexOf("collapse") > -1) {
this.collapse();
}
}
render() {
const classes = (!this.state.width ? `${this.props.width}` : '')
+ (this.props.floating ? " floating" : "")
+ (this.props.active ? " active" : "")
+ (this.state.expanded ? " expanded" : "");
const style = {};
if (this.state.width)
style.width = `${this.state.width}px`;
return (
<section id={this.props.id} className={"react-panel " + classes}
onClick={this.handlePanelClick} style={style} ref="container">
{this.props.children}
<div className="dragbar" onMouseDown={this.onMouseDown}></div>
</section>
);
}
}
export default ReactPanel;
|
fields/types/name/NameColumn.js
|
kumo/keystone
|
import React from 'react';
import ItemsTableCell from '../../../admin/client/components/ItemsTableCell';
import ItemsTableValue from '../../../admin/client/components/ItemsTableValue';
var NameColumn = React.createClass({
displayName: 'NameColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
linkTo: React.PropTypes.string,
},
renderValue () {
var value = this.props.data.fields[this.props.col.path];
if (!value || (!value.first && !value.last)) return '(no name)';
return [value.first, value.last].filter(i => i).join(' ');
},
render () {
return (
<ItemsTableCell>
<ItemsTableValue href={this.props.linkTo} padded interior field={this.props.col.type}>
{this.renderValue()}
</ItemsTableValue>
</ItemsTableCell>
);
}
});
module.exports = NameColumn;
|
examples/todomvc/containers/App.js
|
asaf/redux
|
import React from 'react';
import TodoApp from './TodoApp';
import { createRedux } from 'redux';
import { Provider } from 'redux/react';
import * as stores from '../stores';
const redux = createRedux(stores);
export default class App {
render() {
return (
<Provider redux={redux}>
{() => <TodoApp />}
</Provider>
);
}
}
|
node_modules/react-router/modules/IndexRedirect.js
|
SlateRobotics/slate-website
|
import React from 'react'
import warning from './routerWarning'
import invariant from 'invariant'
import Redirect from './Redirect'
import { falsy } from './PropTypes'
const { string, object } = React.PropTypes
/**
* An <IndexRedirect> is used to redirect from an indexRoute.
*/
const IndexRedirect = React.createClass({
statics: {
createRouteFromReactElement(element, parentRoute) {
/* istanbul ignore else: sanity check */
if (parentRoute) {
parentRoute.indexRoute = Redirect.createRouteFromReactElement(element)
} else {
warning(
false,
'An <IndexRedirect> does not make sense at the root of your route config'
)
}
}
},
propTypes: {
to: string.isRequired,
query: object,
state: object,
onEnter: falsy,
children: falsy
},
/* istanbul ignore next: sanity check */
render() {
invariant(
false,
'<IndexRedirect> elements are for router configuration only and should not be rendered'
)
}
})
export default IndexRedirect
|
src/CarouselItem.js
|
azmenak/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import TransitionEvents from './utils/TransitionEvents';
const CarouselItem = React.createClass({
propTypes: {
direction: React.PropTypes.oneOf(['prev', 'next']),
onAnimateOutEnd: React.PropTypes.func,
active: React.PropTypes.bool,
animateIn: React.PropTypes.bool,
animateOut: React.PropTypes.bool,
caption: React.PropTypes.node,
index: React.PropTypes.number
},
getInitialState() {
return {
direction: null
};
},
getDefaultProps() {
return {
active: false,
animateIn: false,
animateOut: false
};
},
handleAnimateOutEnd() {
if (this.props.onAnimateOutEnd && this.isMounted()) {
this.props.onAnimateOutEnd(this.props.index);
}
},
componentWillReceiveProps(nextProps) {
if (this.props.active !== nextProps.active) {
this.setState({
direction: null
});
}
},
componentDidUpdate(prevProps) {
if (!this.props.active && prevProps.active) {
TransitionEvents.addEndEventListener(
React.findDOMNode(this),
this.handleAnimateOutEnd
);
}
if (this.props.active !== prevProps.active) {
setTimeout(this.startAnimation, 20);
}
},
startAnimation() {
if (!this.isMounted()) {
return;
}
this.setState({
direction: this.props.direction === 'prev' ?
'right' : 'left'
});
},
render() {
let classes = {
item: true,
active: (this.props.active && !this.props.animateIn) || this.props.animateOut,
next: this.props.active && this.props.animateIn && this.props.direction === 'next',
prev: this.props.active && this.props.animateIn && this.props.direction === 'prev'
};
if (this.state.direction && (this.props.animateIn || this.props.animateOut)) {
classes[this.state.direction] = true;
}
return (
<div {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
{this.props.caption ? this.renderCaption() : null}
</div>
);
},
renderCaption() {
return (
<div className="carousel-caption">
{this.props.caption}
</div>
);
}
});
export default CarouselItem;
|
django/webcode/webcode/frontend/node_modules/react-bootstrap/es/DropdownButton.js
|
OpenKGB/webcode
|
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import React from 'react';
import PropTypes from 'prop-types';
import Dropdown from './Dropdown';
import splitComponentProps from './utils/splitComponentProps';
var propTypes = _extends({}, Dropdown.propTypes, {
// Toggle props.
bsStyle: PropTypes.string,
bsSize: PropTypes.string,
title: PropTypes.node.isRequired,
noCaret: PropTypes.bool,
// Override generated docs from <Dropdown>.
/**
* @private
*/
children: PropTypes.node
});
var DropdownButton = function (_React$Component) {
_inherits(DropdownButton, _React$Component);
function DropdownButton() {
_classCallCheck(this, DropdownButton);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
DropdownButton.prototype.render = function render() {
var _props = this.props,
bsSize = _props.bsSize,
bsStyle = _props.bsStyle,
title = _props.title,
children = _props.children,
props = _objectWithoutProperties(_props, ['bsSize', 'bsStyle', 'title', 'children']);
var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent),
dropdownProps = _splitComponentProps[0],
toggleProps = _splitComponentProps[1];
return React.createElement(
Dropdown,
_extends({}, dropdownProps, {
bsSize: bsSize,
bsStyle: bsStyle
}),
React.createElement(
Dropdown.Toggle,
_extends({}, toggleProps, {
bsSize: bsSize,
bsStyle: bsStyle
}),
title
),
React.createElement(
Dropdown.Menu,
null,
children
)
);
};
return DropdownButton;
}(React.Component);
DropdownButton.propTypes = propTypes;
export default DropdownButton;
|
src/components/Header.js
|
guivazcabral/site
|
import React from 'react';
import { Link } from 'react-router';
const Header = () => {
return (
<div className="content header row">
<div className="small-12 medium-12 large-12 columns">
<div className="title">
<Link to={'/'}>Guilherme Cabral</Link>
</div>
<div className="subtitle">
Front End Developer
</div>
</div>
</div>
);
};
export default Header;
|
app/components/ListaMercados.js
|
cosio55/app-informacion-bitso
|
import React, { Component } from 'react';
import 'whatwg-fetch';
import formatMoney from 'accounting-js/lib/formatMoney.js'
import styles from './ListaMercados.css';
import ItemMercado from './ItemMercado';
import nombreMercado from '../ayudas/nombreMercado.json';
class ListaMercados extends Component {
constructor(props) {
super(props);
this.state = {
items: [],
datos: []
};
}
componentDidMount() {
const that = this;
let resCoinMarket = null;
setInterval(function cadaDiezSegundos() {
fetch('https://api.coinmarketcap.com/v1/ticker/?limit=3')
.then(function (response) {
return response.json()
}).then(function (json) {
resCoinMarket = json;
fetch('https://api.bitso.com/v3/ticker/')
.then(function (response) {
return response.json()
}).then(function (resultadosBitso) {
const items = resultadosBitso.payload.map((moneda) => {
let porcentaje = null;
if (resCoinMarket.find(x => x.id === nombreMercado[moneda.book].id)) {
porcentaje = resCoinMarket.find(x => x.id === nombreMercado[moneda.book].id).percent_change_24h;
}
return {
nombre: nombreMercado[moneda.book].nombre,
book_fancy: nombreMercado[moneda.book].book_fancy,
ultimo: formatMoney(moneda.last),
porcentaje: porcentaje,
key: moneda.book,
};
});
that.setState({
items: items
});
}).catch(function (ex) {
console.log('parsing failed', ex);
})
}).catch(function (ex) {
console.log('parsing failed', ex);
});
});
}
render() {
// const { increment, incrementIfOdd, incrementAsync, decrement, counter } = this.props;
return (
<div className={styles.listaMercados}>
{this.state.items.length > 0 ? this.state.items.map((item) => {
return (<ItemMercado
nombre={item.nombre}
book_fancy={item.book_fancy}
ultimo={item.ultimo}
porcentaje={item.porcentaje}
key={item.key}
/>);
}) : <ItemMercado /> }
{}
</div>
);
}
}
export default ListaMercados;
|
src/components/common/forms/NewsletterSubscription.js
|
ESTEBANMURUZABAL/my-ecommerce-template
|
/**
* Imports
*/
import React from 'react';
import {FormattedMessage} from 'react-intl';
import config from '../../../config';
import {isValidEmail} from '../../../utils/strings';
// Flux
import IntlStore from '../../../stores/Application/IntlStore';
// Required components
import Button from '../buttons/Button';
import Text from '../typography/Text';
import InputField from './InputField';
// Translation data for this component
import intlData from './NewsletterSubscription.intl';
/**
* Component
*/
class NewsletterSubscription extends React.Component {
static contextTypes = {
getStore: React.PropTypes.func.isRequired
};
//*** Initial State ***//
state = {
newsletterEmail: undefined
};
//*** Component Lifecycle ***//
componentDidMount() {
// Component styles
require('./NewsletterSubscription.scss');
}
//*** View Controllers ***//
handleNewsletterEmailChange = (value) => {
this.setState({newsletterEmail: value});
};
handleNewsletterSubmitClick = () => {
document.getElementById('mc-embedded-subscribe').click();
};
//*** Template ***//
render() {
//
// Helper methods & variables
//
let intlStore = this.context.getStore(IntlStore);
// Return the mailchimp default subscription form that will be hidden and triggered by our UI
let mailChimpForm = () => {
return (
<form action="https://tienda765.us14.list-manage.com/subscribe/post"
method="POST" id="mc-embedded-subscribe-form" name="mc-embedded-subscribe-form" target="_blank" noValidate
style={{position: 'absolute', left: '-5000px', ariaHidden: 'true'}}>
<div id="mc_embed_signup_scroll">
<label htmlFor="MERGE0">Subscribe to our mailing list</label>
<input type="hidden" name="u" value="67b5228d8d11af7ae1311f884" />
<input type="hidden" name="id" value="18e7e3eea1" />
<input type="email" value={this.state.newsletterEmail} name="MERGE0" id="MERGE0" required />
{this.props.signupSource ?
<input type="hidden" name="SIGNUP" id="SIGNUP" value={this.props.signupSource} />
:
null
}
<div style={{position: 'absolute', left: '-5000px', ariaHidden: 'true'}}>
<input type="text" name="b_e2f7608a217091f244fd31631_9d4cb32d8c" tabIndex="-1" value="" />
</div>
<div>
<input type="submit" value="Subscribe" name="subscribe" id="mc-embedded-subscribe" />
</div>
</div>
</form>
);
};
//
// Return
//
return (
<div className="newsletter-subscription">
<div className="newsletter-subscription__description">
<Text color="white" size="small">
<FormattedMessage message={intlStore.getMessage(intlData, 'newsletterDescription')}
locales={intlStore.getCurrentLocale()} />
</Text>
</div>
<div className="newsletter-subscription__content">
{mailChimpForm()}
<div className="newsletter-subscription__content-item">
<InputField placeholder={intlStore.getMessage(intlData, 'newsletterPlaceholder')}
onChange={this.handleNewsletterEmailChange} />
</div>
<div className="newsletter-subscription__content-item">
<Button type="primary" onClick={this.handleNewsletterSubmitClick}
disabled={!isValidEmail(this.state.newsletterEmail)}>
<Text color="white" size="small">
<FormattedMessage message={intlStore.getMessage(intlData, 'newsletterSubmitButton')}
locales={intlStore.getCurrentLocale()} />
</Text>
</Button>
</div>
</div>
</div>
);
}
}
/**
* Exports
*/
export default NewsletterSubscription;
|
docs/pages/api-docs/table-sort-label.js
|
lgollut/material-ui
|
import React from 'react';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import { prepareMarkdown } from 'docs/src/modules/utils/parseMarkdown';
const pageFilename = 'api/table-sort-label';
const requireRaw = require.context('!raw-loader!./', false, /\/table-sort-label\.md$/);
export default function Page({ docs }) {
return <MarkdownDocs docs={docs} />;
}
Page.getInitialProps = () => {
const { demos, docs } = prepareMarkdown({ pageFilename, requireRaw });
return { demos, docs };
};
|
src/svg-icons/communication/phonelink-erase.js
|
lawrence-yu/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationPhonelinkErase = (props) => (
<SvgIcon {...props}>
<path d="M13 8.2l-1-1-4 4-4-4-1 1 4 4-4 4 1 1 4-4 4 4 1-1-4-4 4-4zM19 1H9c-1.1 0-2 .9-2 2v3h2V4h10v16H9v-2H7v3c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
CommunicationPhonelinkErase = pure(CommunicationPhonelinkErase);
CommunicationPhonelinkErase.displayName = 'CommunicationPhonelinkErase';
CommunicationPhonelinkErase.muiName = 'SvgIcon';
export default CommunicationPhonelinkErase;
|
test/OverlayMixinSpec.js
|
Firfi/meteor-react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import OverlayMixin from '../src/OverlayMixin';
describe('OverlayMixin', function () {
let instance;
let Overlay = React.createClass({
mixins: [OverlayMixin],
render() {
return <div />;
},
renderOverlay() {
return this.props.overlay;
}
});
afterEach(function() {
if (instance && ReactTestUtils.isCompositeComponent(instance) && instance.isMounted()) {
React.unmountComponentAtNode(React.findDOMNode(instance));
}
});
it('Should render overlay into container (DOMNode)', function() {
let container = document.createElement('div');
instance = ReactTestUtils.renderIntoDocument(
<Overlay container={container} overlay={<div id="test1" />} />
);
assert.equal(container.querySelectorAll('#test1').length, 1);
});
it('Should render overlay into container (ReactComponent)', function() {
let Container = React.createClass({
render() {
return <Overlay container={this} overlay={<div id="test1" />} />;
}
});
instance = ReactTestUtils.renderIntoDocument(
<Container />
);
assert.equal(React.findDOMNode(instance).querySelectorAll('#test1').length, 1);
});
it('Should not render a null overlay', function() {
let Container = React.createClass({
render() {
return <Overlay ref='overlay' container={this} overlay={null} />;
}
});
instance = ReactTestUtils.renderIntoDocument(
<Container />
);
assert.equal(instance.refs.overlay.getOverlayDOMNode(), null);
});
it('Should render only an overlay', function() {
let OnlyOverlay = React.createClass({
mixins: [OverlayMixin],
render() {
return null;
},
renderOverlay() {
return this.props.overlay;
}
});
let overlayInstance = ReactTestUtils.renderIntoDocument(
<OnlyOverlay overlay={<div id="test1" />} />
);
assert.equal(overlayInstance.getOverlayDOMNode().nodeName, 'DIV');
});
});
|
app/containers/GoogleMapTemplate/index.js
|
7ruth/PadStats2
|
import React from 'react';
import PropTypes from 'prop-types';
import invariant from 'invariant';
import { camelize } from '../../utils/GoogleMapsUtils/String';
import { makeCancelable } from '../../utils/GoogleMapsUtils/cancelablePromise';
import mapStyles from './GoogleMapTemplateStyles';
import rainbow from "./utils";
function diff(array1, array2) {
return array1.filter((i) => array2.indexOf(i) < 0);
}
export const defaultCategories = {
convenience_store: ["Convenience Store", "#cc0099"],
gym: ["Gym", "#d29fdb"],
grocery_or_supermarket: ["Grocery", "#2095f2"],
subway_station: ["Metro", "#00bbd3"],
school: ["School", "#009587"],
meal_takeaway: ["Takeout", "#4bae4f"],
restaurant: ["Restaurant", "#fec006"],
library: ["Library", "#785447"],
museum: ["Museum", "#c1c1c1"],
store: ["Store", "rgb(0, 0, 0)"],
transit_station: ["Transit Station", "#6639b6"]
}
// const mapStyles = {
// container: {
// position: 'relative',
// minWidth: '400px',
// minHeight: '400px',
// },
// map: {
// position: 'absolute',
// left: 0,
// right: 0,
// bottom: 0,
// top: 0,
// },
// };
// const evtNames = [
// 'ready',
// 'click',
// 'dragend',
// 'recenter',
// 'bounds_changed',
// 'center_changed',
// 'dblclick',
// 'dragstart',
// 'heading_change',
// 'idle',
// 'maptypeid_changed',
// 'mousemove',
// 'mouseout',
// 'mouseover',
// 'projection_changed',
// 'resize',
// 'rightclick',
// 'tilesloaded',
// 'tilt_changed',
// 'zoom_changed',
// ];
export { Marker } from '../../components/GoogleMapMarker/Marker';
export { InfoWindow } from '../../components/GoogleMapInfoWindow/InfoWindow';
export { HeatMap } from '../../components/GoogleMapHeatMap/HeatMap';
let directionsRendererObj = {};
let markerObject={};
let infowindow;
let infoWindowObject={};
export class Map extends React.Component {
constructor(props) {
super(props);
invariant(Object.prototype.hasOwnProperty.call(props, 'google'),
'You must include a `google` prop.');
this.listeners = {};
this.state = {
currentLocation: {
lat: this.props.initialCenter.lat,
lng: this.props.initialCenter.lng,
},
};
}
componentDidMount() {
if (this.props.centerAroundCurrentLocation) {
if (navigator && navigator.geolocation) {
this.geoPromise = makeCancelable(
new Promise((resolve, reject) => {
navigator.geolocation.getCurrentPosition(resolve, reject);
})
);
this.geoPromise.promise.then((pos) => {
const coords = pos.coords;
this.setState({
currentLocation: {
lat: coords.latitude,
lng: coords.longitude,
},
});
}).catch((e) => e);
}
}
this.loadMap();
}
componentDidUpdate(prevProps, prevState) {
if (prevProps.google !== this.props.google) {
this.loadMap();
}
if (this.props.visible !== prevProps.visible) {
this.restyleMap();
}
if (this.props.zoom !== prevProps.zoom) {
this.map.setZoom(this.props.zoom);
}
if (prevState.currentLocation !== this.state.currentLocation) {
this.recenterMap();
}
if (this.props.center !== prevProps.center) {
// new address will trigger initial look up of all the routes
this.setState({ //eslint-disable-line
currentLocation: this.props.center,
});
}
if (this.props.directionResults !== prevProps.directionResults) {
console.log("DIRECTIONS PROPS HAVE CHANGED")
// if directions changed, calculate distance and time
this.setDirections(this.props.directionResults);
}
if (this.props.categories !== prevProps.categories) {
console.log("CATEGORIES PROPS HAVE CHANGED")
this.setDirections();
}
}
componentWillUnmount() {
const { google } = this.props;
if (this.geoPromise) {
this.geoPromise.cancel();
}
Object.keys(this.listeners).forEach((e) => {
google.maps.event.removeListener(this.listeners[e]);
});
}
loadMap() {
if (this.props && this.props.google) {
const { google } = this.props;
const maps = google.maps;
const node = this.myMap;
const curr = this.state.currentLocation;
const center = new maps.LatLng(curr.lat, curr.lng);
const mapTypeIds = this.props.google.maps.MapTypeId || {};
const mapTypeFromProps = String(this.props.mapType).toUpperCase();
const mapConfig = Object.assign({}, {
mapTypeId: mapTypeIds[mapTypeFromProps],
center: center, //eslint-disable-line
zoom: this.props.zoom,
maxZoom: this.props.maxZoom,
minZoom: this.props.minZoom,
clickableIcons: this.props.clickableIcons,
disableDefaultUI: this.props.disableDefaultUI,
zoomControl: this.props.zoomControl,
mapTypeControl: this.props.mapTypeControl,
scaleControl: this.props.scaleControl,
streetViewControl: this.props.streetViewControl,
panControl: this.props.panControl,
rotateControl: this.props.rotateControl,
scrollwheel: this.props.scrollwheel,
draggable: this.props.draggable,
keyboardShortcuts: this.props.keyboardShortcuts,
disableDoubleClickZoom: this.props.disableDoubleClickZoom,
noClear: this.props.noClear,
styles: this.props.styles,
gestureHandling: this.props.gestureHandling,
});
Object.keys(mapConfig).forEach((key) => {
// Allow to configure mapConfig with 'false'
if (mapConfig[key] === null || mapConfig[key] === undefined) {
delete mapConfig[key];
}
});
this.map = new maps.Map(node, mapConfig);
// evtNames.forEach((e) => {
// this.listeners[e] = this.map.addListener(e, this.handleEvent(e));
// });
maps.event.trigger(this.map, 'ready');
this.forceUpdate();
}
}
lookupDirections(google, map, request) {
const directionsService1 = new google.maps.DirectionsService(map);
return new Promise((resolve, reject) => {
const directionsService = new google.maps.DirectionsService(map);
directionsService.route(request, (results, status, pagination) => {
if (status == google.maps.places.PlacesServiceStatus.OK) {
resolve(results, pagination);
} else {
reject(results, status);
}
})
});
}
setDirections(directionResults) {
const map = this.map;
const searchResults = this.props.searchResults;
const categories = this.props.categories;
// if no directionResults are passed in, then do a check to remove categories
if (!directionResults) {
const removedCategory = diff(Object.keys(directionsRendererObj), Object.keys(categories));
console.log('RAWR')
console.log(removedCategory);
if (removedCategory.length > 0) {
directionsRendererObj[removedCategory].setMap(null);
delete directionsRendererObj[removedCategory];
markerObject[removedCategory].setMap(null);
delete markerObject[removedCategory]
console.log("33333333333333");
console.log(directionsRendererObj);
console.log(markerObject)
}
console.log(directionsRendererObj)
return;
}
const category = directionResults.category;
console.log("HIIIIII")
console.log(defaultCategories[category][1]);
let directionRenderer = new google.maps.DirectionsRenderer({
suppressMarkers: true,
draggable: false,
scrollwheel: false,
map: map,
preserveViewport: true,
// polylineOptions: new google.maps.Polyline({strokeColor: rainbow(Math.round(Math.random() * 100),Math.round(Math.random() * 9)),})
polylineOptions: new google.maps.Polyline({strokeColor: defaultCategories[category][1]})
});
console.log('directionsRendererObj');
console.log(directionsRendererObj);
// Clean up any routes if they exist
directionsRendererObj[category] && directionsRendererObj[category].setMap(null);
// Set new directionRenderer obj
directionsRendererObj[category]=directionRenderer;
// Set marker on the map
directionsRendererObj[category].setMap(map);
// Set directions on the map
directionsRendererObj[category].setDirections(directionResults.directionResults);
// Select the poi we are rendering directions for to make a more specific marker
let routedPoi = searchResults[category].places[categories[category][0]];
// create a marker for current POI, need to provide category for look
this.createMarker(routedPoi, category);
}
createMarker(place, category) {
const map = this.map;
const {google} = this.props;
const maps = google.maps;
if (place === "undefined" || place === undefined){
return;
} else {
// Marker settings
let marker = new google.maps.Marker({
map: map,
position: place.geometry.location,
visible: false
});
//Overwrite previous marker for this category
if(markerObject[category]){
markerObject[category].setMap(null);
}
//delete any extra markers (if user unchecked a category)
if (Object.keys(markerObject).length>Object.keys(this.props.categories).length){
for (var i=0; i<Object.keys(markerObject).length; i++){
if (Object.keys(this.props.categories).indexOf(Object.keys(markerObject)[i])==-1){
markerObject[Object.keys(markerObject)[i]].setMap(null);
delete markerObject[Object.keys(markerObject)[i]]
}
}
}
// Set new marker after cleanup
markerObject[category]=marker;
// Info Window Settings
infowindow = new google.maps.InfoWindow();
infoWindowObject[category]=infowindow;
infoWindowObject[category].setContent(place.name);
infoWindowObject[category].open(map, markerObject[category]);
}
}
handleEvent(evtName) {
let timeout;
const handlerName = `on${camelize(evtName)}`;
return (e) => {
if (timeout) {
clearTimeout(timeout);
timeout = null;
}
timeout = setTimeout(() => {
if (this.props[handlerName]) {
this.props[handlerName](this.props, this.map, e);
}
}, 0);
};
}
recenterMap() {
const map = this.map;
const { google } = this.props;
const maps = google.maps;
if (!google) return;
if (map) {
let center = this.state.currentLocation;
if (!(center instanceof google.maps.LatLng)) {
center = new google.maps.LatLng(center.lat, center.lng);
}
// map.panTo(center)
map.setCenter(center);
maps.event.trigger(map, 'recenter');
}
}
restyleMap() {
if (this.map) {
const { google } = this.props;
google.maps.event.trigger(this.map, 'resize');
}
}
renderChildren() {
const { children } = this.props;
if (!children) return;
return React.Children.map(children, c => { //eslint-disable-line
return React.cloneElement(c, {
map: this.map,
google: this.props.google,
mapCenter: this.state.currentLocation,
});
});
}
render() {
const style = Object.assign({}, mapStyles.map, this.props.style, {
display: this.props.visible ? 'inherit' : 'none',
});
const containerStyles = Object.assign({},
mapStyles.container, this.props.containerStyle);
return (
<div style={containerStyles} className={this.props.className}>
<div style={style} ref={(ref) => { this.myMap = ref; }}>
Loading map...
</div>
{this.renderChildren()}
</div>
);
}
}
Map.propTypes = {
google: PropTypes.object,
zoom: PropTypes.number,
centerAroundCurrentLocation: PropTypes.bool,
center: PropTypes.object,
initialCenter: PropTypes.object,
className: PropTypes.string,
children: React.PropTypes.oneOfType([
React.PropTypes.object,
React.PropTypes.bool,
]),
style: PropTypes.object,
containerStyle: PropTypes.object,
visible: PropTypes.bool,
mapType: PropTypes.string,
maxZoom: PropTypes.number,
minZoom: PropTypes.number,
clickableIcons: PropTypes.bool,
disableDefaultUI: PropTypes.bool,
zoomControl: PropTypes.bool,
mapTypeControl: PropTypes.bool,
scaleControl: PropTypes.bool,
streetViewControl: PropTypes.bool,
panControl: PropTypes.bool,
rotateControl: PropTypes.bool,
scrollwheel: PropTypes.bool,
draggable: PropTypes.bool,
keyboardShortcuts: PropTypes.bool,
disableDoubleClickZoom: PropTypes.bool,
noClear: PropTypes.bool,
styles: PropTypes.array,
gestureHandling: PropTypes.string,
};
// evtNames.forEach((e) => { Map.propTypes[camelize(e)] = PropTypes.func; });
Map.defaultProps = {
zoom: 14,
initialCenter: {
lat: 37.774929,
lng: -122.419416,
},
center: {},
centerAroundCurrentLocation: false,
style: {},
containerStyle: {},
visible: true,
scrollwheel: false,
};
export default Map;
|
example/components/App.js
|
nrdobie/css-objectify-loader
|
import React, { Component } from 'react';
import 'whatwg-fetch';
import styles from './App.css';
export default class App extends Component {
constructor(...args) {
super(...args);
this.state = {};
}
componentDidMount() {
fetch('https://www.reddit.com/r/reactjs.json')
.then(response => response.json())
.then(json => json.data.children.map(child => child.data))
.then(posts => this.setState({ posts }));
}
render() {
if (!this.state.posts) {
return (<div>No Posts</div>);
}
return (<ul style={styles['.App']}>{this.state.posts.map(post => <li key={post.id}>{post.title}</li>)}</ul>);
}
}
|
src/svg-icons/action/line-style.js
|
tan-jerene/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionLineStyle = (props) => (
<SvgIcon {...props}>
<path d="M3 16h5v-2H3v2zm6.5 0h5v-2h-5v2zm6.5 0h5v-2h-5v2zM3 20h2v-2H3v2zm4 0h2v-2H7v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zm4 0h2v-2h-2v2zM3 12h8v-2H3v2zm10 0h8v-2h-8v2zM3 4v4h18V4H3z"/>
</SvgIcon>
);
ActionLineStyle = pure(ActionLineStyle);
ActionLineStyle.displayName = 'ActionLineStyle';
ActionLineStyle.muiName = 'SvgIcon';
export default ActionLineStyle;
|
client/src/components/inbox.js
|
TeamAusDigital/apec-connect
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { withRouter } from 'react-router';
import actions from 'state/actions';
import { connect } from 'react-redux';
import AppBarMain from '../components/AppBarMain';
import Paper from 'material-ui/Paper';
import StarRating from '../components/starRating';
import RaisedButton from 'material-ui/RaisedButton';
import {indigo,white} from './apecConnectTheme';
import Logo from '../common/assets/APEC-CONNECT-LOGO.svg';
import InboxItem from './inboxItem';
import Immutable from 'immutable';
import moment from 'moment';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import Message from 'material-ui/svg-icons/communication/message';
import {
Table,
TableBody,
TableFooter,
TableHeader,
TableHeaderColumn,
TableRow,
TableRowColumn,
} from 'material-ui/Table';
/***
This is the basic elements for a main view in the app.
***/
const colStyle = {
textAlign: 'center',
};
const paperStyle = {
padding: '5px',
textAlign: 'center',
height: '100%'
};
const buttonStyle = {
position: 'fixed',
bottom: '10px',
right: '25px',
};
const logoStyle ={
width: '100%',
maxHeight: '150px',
};
@withRouter
@connect((state) => {
return {
dispatch: state.dispatch,
ui: state.ui,
participant: state.participant,
messages: state.messages,
officials: state.officials
};
})
export default class Inbox extends React.Component {
constructor(props) {
super(props);
};
/**
* Generates the inbox items:
* # Participant messages, with or without Invoice.
* # Official announcements made by government agencies.
* @return {nodes} of rednered InboxItem components.
*/
generateInboxItems = () => {
let {messages} = this.props.messages;
// Wraps the announcements in ParticipantMessage manner. A ParticipantMessage contains:
// {sender: {}, receiver: {}, invoice: {}, message: {}}
let announcements = Immutable.List(this.props.officials.announcements).map((announce) => {
return {
message: {
metaData: announce.metaData,
message: announce.message
},
isAnnouncement: true
};
});
let messagesAndAnnouncements = announcements.concat(Immutable.List(messages)).sortBy((m) => -m.message.metaData.dateCreated);
const items = messagesAndAnnouncements.map((message, index) => <InboxItem key={index} message={message} keyID={index} />) ;
if (items.size > 0){
return items;
} else {
return <TableRow style={colStyle}><TableRowColumn colSpan={3} style={colStyle}> Inbox is Empty! </TableRowColumn></TableRow>;
}
}
componentDidMount() {
let { dispatch } = this.props;
setTimeout(function () {
dispatch(actions.getAnnouncements());
dispatch(actions.getParticipantMessages());
});
}
componentWillReceiveProps() {
clearTimeout(this.inboxRefreshTimeout);
this.refreshInbox();
}
/**
* Periodically refresh the inbox to fetch updated messages and announcements.
*/
refreshInbox = () => {
let { dispatch } = this.props;
this.inboxRefreshTimeout = setTimeout(function() {
dispatch(actions.getAnnouncements());
dispatch(actions.getParticipantMessages());
}, 5 * 1000);
}
handleNewMessage = () => {
this.props.dispatch(actions.selectParticipantMessage());
this.props.router.push('/sendMessage');
};
render() {
return (
<div>
{/** AppBarMain contains the app bar and menu drawer **/}
<AppBarMain title={'Inbox'}/>
{/** Paper containing the logo **/}
<Paper
zDepth={1}
style={paperStyle}
>
<img src={Logo} style={logoStyle} />
<br />
<br />
<Paper
zDepth={1}
style={paperStyle}
>
<Table
multiSelectable={false}
showCheckBoxes={false}
>
<TableHeader
displaySelectAll={false}
adjustForCheckbox={false}
enableSelectAll={false}
>
<TableRow>
<TableHeaderColumn>WHO</TableHeaderColumn>
<TableHeaderColumn>WHEN</TableHeaderColumn>
<TableHeaderColumn>WHAT</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody
displayRowCheckbox={false}
stripedRows={true}
>
{this.generateInboxItems()}
</TableBody>
</Table>
<div style={buttonStyle}>
<FloatingActionButton
onTouchTap={() => this.handleNewMessage()}
>
<Message />
</FloatingActionButton>
</div>
</Paper>
</Paper>
</div>
);
}
}
|
app/App.js
|
wbowling/deciderer
|
import React from 'react'
import ReactDOM from 'react-dom'
import { Router, Route, IndexRoute } from 'react-router'
import createBrowserHistory from 'history/lib/createBrowserHistory'
import MainLayout from './components/MainLayout'
import ShowPoll from './components/ShowPoll'
import CreatePoll from './components/CreatePoll'
ReactDOM.render((
<Router history={createBrowserHistory()}>
<Route path="/" component={MainLayout}>
<IndexRoute component={CreatePoll} />
<Route path=":poll" component={ShowPoll} />
</Route>
</Router>), document.getElementById('app'))
|
src/js/entry.js
|
gitwillsky/react-template
|
import React from 'react';
import {render} from 'react-dom';
|
15-react-router-v4/src/components/topics.js
|
iproduct/course-node-express-react
|
import React from 'react';
import { NavLink, Route } from 'react-router-dom';
import './Topics.css';
import { withParams } from './hocs';
import Topic from './Topic'
const Topics = ({ match, location, history, topics }) => (
<div className="Topics">
<h2>Blog Topics</h2>
<nav className="Topics-nav">
<ul>
{ topics.map(topic => (
<li key={topic.title}>
<NavLink to={`${match.url}/${topic.title}`}
className='navlink' activeClassName='active'>
{topic.title}
</NavLink>
</li>
))}
</ul>
</nav>
<Route path={`${match.url}/:topicTile`} render={ withParams(Topic, { topics }) } />
</div>
);
export default Topics;
|
src/index.js
|
CodeDraken/IdeaZone
|
import React from 'react';
import ReactDOM from 'react-dom';
import { Route, Router, IndexRoute, hashHistory } from 'react-router';
import './css/main.css';
import App from './components/App';
import IdeaPage from './components/idea-page/IdeaPage';
import SearchPage from './components/search-page/SearchPage';
import AboutPage from './components/about-page/AboutPage';
import ProfilePage from './components/profile-page/ProfilePage';
ReactDOM.render(
<Router history={hashHistory}>
<Route path="/" component={App}>
<Route path="idea" component={IdeaPage} componentName='IdeaPage' />
<Route path="profile" component={ProfilePage} componentName='ProfilePage' />
<Route path="about" component={AboutPage} componentName='AboutPage'/>
<IndexRoute component={SearchPage} componentName='SearchPage' />
</Route>
</Router>,
document.getElementById('root')
);
|
examples/files/app/List.js
|
dabbott/react-native-express
|
import React from 'react'
import { FlatList, StyleSheet, Text, TouchableOpacity } from 'react-native'
export default function List({ items, onPressItem }) {
return (
<FlatList
data={items}
keyExtractor={(item) => item.id}
renderItem={({ item, index }) => (
<TouchableOpacity
style={[styles.item, { backgroundColor: itemColor(index) }]}
onPress={() => onPressItem(item.id)}
>
<Text style={styles.title}>{item.title}</Text>
</TouchableOpacity>
)}
/>
)
}
function itemColor(index) {
return `rgba(59, 108, 212, ${Math.max(1 - index / 10, 0.4)})`
}
const styles = StyleSheet.create({
item: {
marginBottom: 1,
padding: 15,
},
title: {
color: 'white',
},
})
|
examples/shared-root/app.js
|
skevy/react-router
|
import React from 'react';
import { Router, Route, Link } from 'react-router';
var App = React.createClass({
render() {
return (
<div>
<p>
This illustrates how routes can share UI w/o sharing the URL.
When routes have no path, they never match themselves but their
children can, allowing "/signin" and "/forgot-password" to both
be render in the <code>SignedOut</code> component.
</p>
<ol>
<li><Link to="/home">Home</Link></li>
<li><Link to="/signin">Sign in</Link></li>
<li><Link to="/forgot-password">Forgot Password</Link></li>
</ol>
{this.props.children}
</div>
);
}
});
var SignedIn = React.createClass({
render() {
return (
<div>
<h2>Signed In</h2>
{this.props.children}
</div>
);
}
});
var Home = React.createClass({
render() {
return (
<h3>Welcome home!</h3>
);
}
});
var SignedOut = React.createClass({
render() {
return (
<div>
<h2>Signed Out</h2>
{this.props.children}
</div>
);
}
});
var SignIn = React.createClass({
render() {
return (
<h3>Please sign in.</h3>
);
}
});
var ForgotPassword = React.createClass({
render() {
return (
<h3>Forgot your password?</h3>
);
}
});
React.render((
<Router>
<Route path="/" component={App}>
<Route component={SignedOut}>
<Route path="signin" component={SignIn} />
<Route path="forgot-password" component={ForgotPassword} />
</Route>
<Route component={SignedIn}>
<Route path="home" component={Home} />
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
src/main.js
|
swirlycheetah/react-flux-promises
|
import React from 'react'
import EmojiComponent from './emojiComponent'
React.render(<EmojiComponent />, document.body)
|
index.js
|
Toodledo/react-infinite-calendar
|
import 'babel-polyfill'
import React from 'react'
import { render } from 'react-dom'
import InfiniteCalendar from './src/index'
var badges = {"20160612":2, "20160621":5};
var today = new Date();
var minDate = new Date(2014,0,1);
var nextweek = new Date(2016,5,29);
render(<InfiniteCalendar badges={badges} selectedDate={today} rangeSelection={true} rangeSelectionBehavior="drag" rangeSelectionEndDate={nextweek} minDate={minDate} />,
document.getElementById('root')
)
|
app/containers/PrivateRoot/Routes.js
|
danielmoraes/invoices-web-client
|
import React from 'react'
import { Redirect, Route, Switch } from 'react-router-dom'
import {
Invoice,
Invoices,
User,
Users,
SignOut
} from 'containers'
import { UserRole } from 'api/enums'
import * as routes from 'routes'
const Routes = ({ role }) => (
<Switch>
<Route path={routes.account()} component={User} />
<Route path={routes.invoice()} component={Invoice} />
<Route path={routes.invoices()} component={Invoices} />
{ role === UserRole.ADMIN && (
<Route path={routes.user()} component={User} />
) }
{ role === UserRole.ADMIN && (
<Route path={routes.users()} component={Users} />
) }
<Route path={routes.signOut()} component={SignOut} />
<Redirect to={routes.invoices()} />
</Switch>
)
export default Routes
|
app/javascript/mastodon/features/lists/index.js
|
honpya/taketodon
|
import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import { fetchLists } from '../../actions/lists';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ColumnLink from '../ui/components/column_link';
import ColumnSubheading from '../ui/components/column_subheading';
import NewListForm from './components/new_list_form';
import { createSelector } from 'reselect';
const messages = defineMessages({
heading: { id: 'column.lists', defaultMessage: 'Lists' },
subheading: { id: 'lists.subheading', defaultMessage: 'Your lists' },
});
const getOrderedLists = createSelector([state => state.get('lists')], lists => {
if (!lists) {
return lists;
}
return lists.toList().filter(item => !!item).sort((a, b) => a.get('title').localeCompare(b.get('title')));
});
const mapStateToProps = state => ({
lists: getOrderedLists(state),
});
@connect(mapStateToProps)
@injectIntl
export default class Lists extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
lists: ImmutablePropTypes.list,
intl: PropTypes.object.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchLists());
}
render () {
const { intl, lists } = this.props;
if (!lists) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
return (
<Column icon='bars' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<NewListForm />
<div className='scrollable'>
<ColumnSubheading text={intl.formatMessage(messages.subheading)} />
{lists.map(list =>
<ColumnLink key={list.get('id')} to={`/timelines/list/${list.get('id')}`} icon='bars' text={list.get('title')} />
)}
</div>
</Column>
);
}
}
|
src/components/ProjectsMain.js
|
mikalmorello/mikalmorello.github.io
|
import React from 'react';
import {
Link
} from 'react-router-dom';
import Fade from 'react-reveal/Fade';
class ProjectsMain extends React.Component {
render(){
return (
<main id="main" className="main">
<Fade>
<section id="sectionProjects" className="section section--projects">
<div className="projects projects--horizontal">
<div className="projects__container">
<article className="project-card">
<Link to="/tufts-magazine" className="project-card__content">
<h2 className="project-card__title">Tufts Magazine</h2>
<ul className="project-card__tags">
<li className="project-card__tag">Development</li>
</ul>
<div className="project-card__media">
<img src="/assets/images/project-tufts-magazine-card.jpg" alt="Tufts Magazine Thumbnail"/>
</div>
</Link>
</article>
<article className="project-card">
<Link to="/tufts-university-web-standard" className="project-card__content">
<h2 className="project-card__title">Tufts Standard</h2>
<ul className="project-card__tags">
<li className="project-card__tag">Development</li>
<li className="project-card__tag">Strategy</li>
</ul>
<div className="project-card__media">
<img src="/assets/images/project-tufts-standard-card.jpg" alt="Tufts D8 Standard Thumbnail"/>
</div>
</Link>
</article>
<article className="project-card">
<Link to="/boston-college-redesign" className="project-card__content">
<h2 className="project-card__title">Boston College Website Redesign</h2>
<ul className="project-card__tags">
<li className="project-card__tag">UX</li>
<li className="project-card__tag">Strategy</li>
</ul>
<div className="project-card__media">
<img src="/assets/images/project-boston-college-card.jpg" alt="Boston College Redesign Thumbnail"/>
</div>
</Link>
</article>
</div>
</div>
</section>
</Fade>
<Fade>
<section id="sectionOtherProject" className="section section--other-projects">
<div className="other-projects">
<div className="other-projects__divider">
<img src="/assets/images/wave-divider.svg" alt=""/>
</div>
<h2 className="other-projects__title">Other Projects</h2>
<ul className="other-projects__list">
<li className="other-projects__list-item">Tufts.edu</li>
<li className="other-projects__list-item">Tufts Summer Sessions</li>
<li className="other-projects__list-item">Tufts Dental</li>
<li className="other-projects__list-item">Tufts Global</li>
<li className="other-projects__list-item">Boston College Alumni & Friends</li>
<li className="other-projects__list-item">BC Social</li>
<li className="other-projects__list-item">BC Grouper</li>
<li className="other-projects__list-item">Eagelapps</li>
<li className="other-projects__list-item">150 on the road</li>
<li className="other-projects__list-item">CASE District 1</li>
<li className="other-projects__list-item">Accessibility Analytics</li>
</ul>
</div>
</section>
</Fade>
<Fade>
<section id="sectionContact" className="section section--contact">
<div className="contact-card contact-card--minimal">
<div className="contact-card__container">
<h2 className="contact-card__titles">
<Link to="/contact">
<span className="contact-card__title">Let's Connect</span>
</Link>
</h2>
</div>
</div>
</section>
</Fade>
</main>
)
}
}
export default ProjectsMain;
|
test/WellSpec.js
|
omerts/react-bootstrap
|
import React from 'react';
import ReactTestUtils from 'react/lib/ReactTestUtils';
import Well from '../src/Well';
describe('Well', function () {
it('Should output a well with content', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Well>
<strong>Content</strong>
</Well>
);
assert.ok(ReactTestUtils.findRenderedDOMComponentWithTag(instance, 'strong'));
});
it('Should have a well class', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Well>
Content
</Well>
);
assert.ok(React.findDOMNode(instance).className.match(/\bwell\b/));
});
it('Should accept bsSize arguments', function () {
let instance = ReactTestUtils.renderIntoDocument(
<Well bsSize='small'>
Content
</Well>
);
assert.ok(React.findDOMNode(instance).className.match(/\bwell-sm\b/));
});
});
|
src/Task.js
|
ml7757/To-Do-React
|
import React from 'react';
import jQuery from 'jquery';
import EditableItem from './EditableItem';
class Task extends React.Component{
constructor(){
super();
this.state = {
}
}
toggleChecked(event) {
this.updateTask({
id: this.props.id,
task_description: this.props.taskDescription,
duedate: this.props.dueDate,
status: this.refs.completed.checked,
project_id: this.props.projectId
});
}
changeTask(event){
console.log(event);
this.updateTask({
id: this.props.id,
task_description: event.task_description,
duedate: event.duedate,
status: this.refs.completed.checked,
project_id: this.props.projectId
});
}
getClassName() {
var _classNames = ["list-group-item task"];
if (this.state.completed) { _classNames.push("completed"); }
return _classNames.join(" ");
}
updateTask(updatedTask) {
console.log("synching state");
var component = this;
jQuery.ajax({
type: "PUT",
url: `https://checktaskmanager.herokuapp.com/projects/${updatedTask.project_id}/tasks/${updatedTask.id}`,
data: JSON.stringify({
task: updatedTask
}),
contentType: "application/json",
dataType: "json"
})
.done(function(data) {
console.log(data);
component.props.onChange();
})
.fail(function(error) {
console.log(error);
})
}
deleteTask(event){
event.preventDefault();
// we need to rename ourselves again
var component = this;
// lets assign the task id to a new variable
var taskId = component.props.id;
var projectId = component.props.projectId;
console.log(projectId);
jQuery.ajax({
method: "DELETE",
// we have to apend the task id to the url, so the server knows which task to delete.
url: `https://checktaskmanager.herokuapp.com/projects/${projectId}/tasks/${taskId}`,
contentType: "application/json",
dataType: "json"
})
.done(function(data){
// when done and the task is removed, we receive a
// 200 message from the server via ajax/JSON.
// our parent we changed via an onChange prop. This should then fire the reloadTask method in the parent
// to reload the updated tasks list from the server
console.log(data);
component.props.onChange();
});
}
render(){
return(
<li className={this.getClassName()}>
<input className="toggle checkbox" id={this.props.id} type="checkbox" ref="completed" checked={this.props.status ? "checked" : ""} onChange={this.toggleChecked.bind(this)} />
<a className="btn btn-danger btn-xs pull-right" onClick={this.deleteTask.bind(this)}>x</a>
<EditableItem id={this.props.id}
taskDescription={this.props.taskDescription}
dueDate={this.props.dueDate}
status={this.props.status}
projectId={this.props.projectId}
onClick={this.changeTask.bind(this)}
isEditable={!this.state.status}
onChange={this.changeTask.bind(this)}/>
</li>
);
}
}
export default Task;
|
third_party/prometheus_ui/base/web/ui/node_modules/@wojtekmaj/enzyme-adapter-react-17/src/detectFiberTags.js
|
GoogleCloudPlatform/prometheus-engine
|
import React from 'react';
import ReactDOM from 'react-dom';
import { fakeDynamicImport } from '@wojtekmaj/enzyme-adapter-utils';
function getFiber(element) {
const container = global.document.createElement('div');
let inst = null;
class Tester extends React.Component {
render() {
inst = this;
return element;
}
}
ReactDOM.render(React.createElement(Tester), container);
return inst._reactInternals.child;
}
function getLazyFiber(LazyComponent) {
const container = global.document.createElement('div');
let inst = null;
class Tester extends React.Component {
render() {
inst = this;
return React.createElement(LazyComponent);
}
}
class SuspenseWrapper extends React.Component {
render() {
return React.createElement(
React.Suspense,
{ fallback: false },
React.createElement(Tester),
);
}
}
ReactDOM.render(React.createElement(SuspenseWrapper), container);
return inst._reactInternals.child;
}
module.exports = function detectFiberTags() {
const supportsMode = typeof React.StrictMode !== 'undefined';
const supportsContext = typeof React.createContext !== 'undefined';
const supportsForwardRef = typeof React.forwardRef !== 'undefined';
const supportsMemo = typeof React.memo !== 'undefined';
const supportsProfiler = typeof React.unstable_Profiler !== 'undefined' || typeof React.Profiler !== 'undefined';
const supportsSuspense = typeof React.Suspense !== 'undefined';
const supportsLazy = typeof React.lazy !== 'undefined';
function Fn() {
return null;
}
class Cls extends React.Component {
render() {
return null;
}
}
let Ctx = null;
let FwdRef = null;
let LazyComponent = null;
if (supportsContext) {
Ctx = React.createContext();
}
if (supportsForwardRef) {
// React will warn if we don't have both arguments.
// eslint-disable-next-line no-unused-vars
FwdRef = React.forwardRef((props, ref) => null);
}
if (supportsLazy) {
LazyComponent = React.lazy(() => fakeDynamicImport(() => null));
}
return {
HostRoot: getFiber('test').return.return.tag, // Go two levels above to find the root
ClassComponent: getFiber(React.createElement(Cls)).tag,
Fragment: getFiber([['nested']]).tag,
FunctionalComponent: getFiber(React.createElement(Fn)).tag,
MemoSFC: supportsMemo
? getFiber(React.createElement(React.memo(Fn))).tag
: -1,
MemoClass: supportsMemo
? getFiber(React.createElement(React.memo(Cls))).tag
: -1,
HostPortal: getFiber(ReactDOM.createPortal(null, global.document.createElement('div'))).tag,
HostComponent: getFiber(React.createElement('span')).tag,
HostText: getFiber('text').tag,
Mode: supportsMode
? getFiber(React.createElement(React.StrictMode)).tag
: -1,
ContextConsumer: supportsContext
? getFiber(React.createElement(Ctx.Consumer, null, () => null)).tag
: -1,
ContextProvider: supportsContext
? getFiber(React.createElement(Ctx.Provider, { value: null }, null)).tag
: -1,
ForwardRef: supportsForwardRef
? getFiber(React.createElement(FwdRef)).tag
: -1,
Profiler: supportsProfiler
? getFiber(React.createElement((React.Profiler || React.unstable_Profiler), { id: 'mock', onRender() {} })).tag
: -1,
Suspense: supportsSuspense
? getFiber(React.createElement(React.Suspense, { fallback: false })).tag
: -1,
Lazy: supportsLazy
? getLazyFiber(LazyComponent).tag
: -1,
OffscreenComponent: supportsLazy
? getLazyFiber('div').return.return.tag // Go two levels above to find the root
: -1,
};
};
|
src/App.js
|
Software-Eng-THU-2015/pacific-rim
|
import React, { Component } from 'react';
import { Router, Route, Link } from 'react-router';
import 'normalize.css';
export default class App extends Component {
render() {
return (
<div>
{this.props.children}
</div>
);
}
}
|
src/decorators/withViewport.js
|
bootcampcamp/givingbranch
|
/*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React, { Component } from 'react'; // eslint-disable-line no-unused-vars
import EventEmitter from 'eventemitter3';
import { canUseDOM } from 'fbjs/lib/ExecutionEnvironment';
let EE;
let viewport = {width: 1366, height: 768}; // Default size for server-side rendering
const RESIZE_EVENT = 'resize';
function handleWindowResize() {
if (viewport.width !== window.innerWidth || viewport.height !== window.innerHeight) {
viewport = {width: window.innerWidth, height: window.innerHeight};
EE.emit(RESIZE_EVENT, viewport);
}
}
function withViewport(ComposedComponent) {
return class WithViewport extends Component {
constructor() {
super();
this.state = {
viewport: canUseDOM ? {width: window.innerWidth, height: window.innerHeight} : viewport,
};
}
componentDidMount() {
if (!EE) {
EE = new EventEmitter();
window.addEventListener('resize', handleWindowResize);
window.addEventListener('orientationchange', handleWindowResize);
}
EE.on(RESIZE_EVENT, this.handleResize, this);
}
componentWillUnmount() {
EE.removeListener(RESIZE_EVENT, this.handleResize, this);
if (!EE.listeners(RESIZE_EVENT, true)) {
window.removeEventListener('resize', handleWindowResize);
window.removeEventListener('orientationchange', handleWindowResize);
EE = null;
}
}
render() {
return <ComposedComponent {...this.props} viewport={this.state.viewport}/>;
}
handleResize(value) {
this.setState({viewport: value}); // eslint-disable-line react/no-set-state
}
};
}
export default withViewport;
|
src/Rating.js
|
zanjs/react-ui
|
"use strict"
import React from 'react'
import classnames from 'classnames'
import { requireCss } from './themes'
requireCss('rating')
let themes = {
// "star": [Icon, Icon],
// "heart": [img, img]
}
class Rating extends React.Component {
static displayName = 'Rating'
static propTypes = {
className: React.PropTypes.string,
icons: React.PropTypes.array,
maxValue: React.PropTypes.number,
onChange: React.PropTypes.func,
readOnly: React.PropTypes.bool,
size: React.PropTypes.number,
style: React.PropTypes.object,
theme: React.PropTypes.string,
value: React.PropTypes.number
}
static defaultProps = {
maxValue: 5
}
componentWillReceiveProps (nextProps) {
if (nextProps.value !== this.props.value) {
this.setValue(nextProps.value)
}
}
state = {
value: this.props.value,
hover: 0,
wink: false
}
handleHover (value) {
return function () {
this.setState({ hover: value })
}.bind(this)
}
handleLeave () {
this.setState({ hover: 0 })
}
setValue (value) {
this.setState({ value })
}
getValue () {
return this.state.value
}
getIcon (pos = 0) {
let icons = this.props.icons
if (!icons) {
let theme = this.props.theme || Object.keys(themes)[0]
icons = themes[theme]
}
if (!icons) {
console.warn('icons or theme not exist')
return null
}
return icons[pos]
}
getBackground () {
let items = [],
icon = this.getIcon(0)
for (let i = 0; i < this.props.maxValue; i++) {
items.push(React.cloneElement(icon, { key: i }))
}
return <div className="rct-rating-bg">{items}</div>
}
handleChange (val) {
this.setValue(val)
this.setState({ wink: true })
setTimeout(() => {
this.setState({ wink: false })
}, 1000)
setTimeout(() => {
if (this.props.onChange) {
this.props.onChange(val)
}
})
}
getHandle () {
let items = [],
icon = this.getIcon(1),
hover = this.state.hover,
wink = this.state.wink,
value = hover > 0 ? hover : this.state.value
for (let i = 0, active; i < this.props.maxValue; i++) {
active = value > i
items.push(
<span key={i}
style={{cursor: 'pointer'}}
onMouseOver={this.handleHover(i + 1)}
onClick={this.handleChange.bind(this, i + 1)}
className={classnames('rct-rating-handle', { 'active': active, 'wink': active && wink })}>
{React.cloneElement(icon)}
</span>
)
}
return <div onMouseOut={this.handleLeave.bind(this)} className="rct-rating-front">{items}</div>
}
getMute () {
let items = [],
icon = this.getIcon(1),
width = (this.state.value / this.props.maxValue * 100) + '%'
for (let i = 0; i < this.props.maxValue; i++) {
items.push(React.cloneElement(icon, { key: i }))
}
return (
<div style={{ width: width }} className="rct-rating-front">
<div className="rct-rating-inner">
{items}
</div>
</div>
)
}
render () {
let className = classnames(
this.props.className,
"rct-rating"
)
return (
<div style={this.props.style} className={className}>
{ this.getBackground() }
{ this.props.readOnly ? this.getMute() : this.getHandle() }
</div>
)
}
}
Rating.register = function (key, icons) {
themes[key] = icons
}
export default Rating
require('./FormControl').register(
'rating',
function (props) {
return <Rating {...props} />
},
Rating
)
|
ReactReduxRoutingAutoRehydrate/src/containers/BlueScreenContainer.js
|
nitindhar7/tutorials
|
/**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {Actions} from 'react-native-router-flux'
import { connect } from 'react-redux'
import { updateCopy } from '../actions'
import BlueScreen from '../presenters/BlueScreen'
const mapStateToProps = (state) => {
return {
copy: state.copy
}
}
const mapDispatchToProps = (dispatch) => {
return {
onSubmit: (text) => {
dispatch(updateCopy(text))
}
}
}
const BlueScreenContainer = connect(mapStateToProps, mapDispatchToProps)(BlueScreen)
export default BlueScreenContainer
|
examples/todos/src/components/App.js
|
heyesther/redux
|
import React from 'react'
import Footer from './Footer'
import AddTodo from '../containers/AddTodo'
import VisibleTodoList from '../containers/VisibleTodoList'
const App = () => (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
)
export default App
|
packages/mineral-ui-icons/src/IconMarkunreadMailbox.js
|
mineral-ui/mineral-ui
|
/* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconMarkunreadMailbox(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M20 6H10v6H8V4h6V0H6v6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2z"/>
</g>
</Icon>
);
}
IconMarkunreadMailbox.displayName = 'IconMarkunreadMailbox';
IconMarkunreadMailbox.category = 'action';
|
src/pages/VerifyEmailPage.js
|
ramimuurimaki/stormpath-express-react-example
|
import React from 'react';
import DocumentTitle from 'react-document-title';
import { VerifyEmailView } from 'react-stormpath';
export default class VerifyEmailPage extends React.Component {
render() {
var spToken = this.props.location.query.sptoken;
return (
<DocumentTitle title={`Verify Email`}>
<div className="container">
<div className="row">
<div className="col-xs-12">
<h3>Verify Your Account</h3>
<hr />
</div>
</div>
<VerifyEmailView spToken={spToken} />
</div>
</DocumentTitle>
);
}
}
|
src/Debounce.js
|
jaredlunde/react-cake
|
import React from 'react'
import PropTypes from 'prop-types'
import {debounce} from './utils'
/**
<Debounce wait={200} initialState={{scrollY: 0}}>
{
({debounceState, scrollY}) => (
<Scroller
onScroll={
({scrollY}) => debounceState(
prevState => scrollY > 30
? {gt30: true, scrollY}
: {gt30: false, scrollY}
)
}
>
Greater than 30? {String(gt30)}
</Scroller>
)
}
</Debounce>
*/
export default class Debounce extends React.Component {
static propTypes = {
initialState: PropTypes.object,
wait: PropTypes.number.isRequired,
immediate: PropTypes.bool
}
static defaultProps = {
wait: 100
}
constructor (props) {
super(props)
this.state = props.initialState || {}
this.debounceState = debounce(
this._setState,
props.wait,
{
'leading': props.immediate,
'trailing': !props.immediate
}
)
}
_setState = (...args) => this.setState(...args)
componentWillUnmount () {
this.debounceState.cancel()
}
render () {
return this.props.children(
Object.assign({debounceState: this.debounceState}, this.state)
)
}
}
|
app/javascript/mastodon/features/compose/components/navigation_bar.js
|
ashfurrow/mastodon
|
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,
onLogout: PropTypes.func.isRequired,
onClose: PropTypes.func,
};
render () {
return (
<div className='navigation-bar'>
<Permalink href={this.props.account.get('url')} to={`/@${this.props.account.get('acct')}`}>
<span style={{ display: 'none' }}>{this.props.account.get('acct')}</span>
<Avatar account={this.props.account} size={48} />
</Permalink>
<div className='navigation-bar__profile'>
<Permalink href={this.props.account.get('url')} to={`/@${this.props.account.get('acct')}`}>
<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} onLogout={this.props.onLogout} />
</div>
</div>
);
}
}
|
src/Label.js
|
xuorig/react-bootstrap
|
import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
const Label = React.createClass({
mixins: [BootstrapMixin],
getDefaultProps() {
return {
bsClass: 'label',
bsStyle: 'default'
};
},
render() {
let classes = this.getBsClassSet();
return (
<span {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</span>
);
}
});
export default Label;
|
docs/src/app/components/pages/components/RaisedButton/ExampleIcon.js
|
w01fgang/material-ui
|
import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import {fullWhite} from 'material-ui/styles/colors';
import ActionAndroid from 'material-ui/svg-icons/action/android';
import FontIcon from 'material-ui/FontIcon';
const style = {
margin: 12,
};
const RaisedButtonExampleIcon = () => (
<div>
<RaisedButton
icon={<ActionAndroid />}
style={style}
/>
<RaisedButton
backgroundColor="#a4c639"
icon={<ActionAndroid color={fullWhite} />}
style={style}
/>
<RaisedButton
href="https://github.com/callemall/material-ui"
target="_blank"
secondary={true}
icon={<FontIcon className="muidocs-icon-custom-github" />}
style={style}
/>
</div>
);
export default RaisedButtonExampleIcon;
|
src/components/PairedButtons/PairedButtons.js
|
InsideSalesOfficial/insidesales-components
|
import React from 'react';
import styled from 'styled-components'
import PropTypes from 'prop-types';
import Button from '../Button';
const ALIGN_RIGHT = 'align_right';
const ALIGN_LEFT = 'align_left';
const ButtonsContainer = styled.div`
display: grid;
grid-template-columns: ${props => props.gridTemplateColumns};
position: relative;
width: 100%;
`;
const StyledButton = styled(Button)`
border-radius: ${props =>
props.align === ALIGN_LEFT
? '4px 0 0 4px'
: props.align === ALIGN_RIGHT
? '0 4px 4px 0'
: '0 0 0 0'};
${props => props.align === ALIGN_RIGHT ? '' : 'border-right: none'}
`;
function onChangeCheck ({onChange, selected}) {
return function onChangeCheckHandler(option) {
return function onClick () {
if (option.value === selected) return;
onChange(option.value);
}
}
}
function renderButton ({onChange, selected, options, id, disabled, onDarkBg}) {
return function renderButtonHandler (option, index) {
const align =
index === 0
? ALIGN_LEFT
: index === options.length - 1
? ALIGN_RIGHT
: '';
return [
<StyledButton
onClick={onChangeCheck({onChange, selected})(option, index)}
key={option.value}
align={align}
id={`${id}_${option.value.replace(' ', '_')}_button`}
disabled={disabled}
label={option.label}
onDarkBg={onDarkBg}
className={option.value === selected ? 'paired_button_selected' : ''}
outline={option.value !== selected}
/>,
];
}
}
export function PairedButtons (props) {
const { options, selected, onChange, id, disabled, onDarkBg} = props;
return (
<ButtonsContainer gridTemplateColumns={'1fr '.repeat(options.length).trim()} id={id}>
{options.map(renderButton({options, selected, onChange, id, disabled, onDarkBg }))}
</ButtonsContainer>
);
}
PairedButtons.propTypes = {
onChange: PropTypes.func.isRequired,
selected: PropTypes.string,
options: PropTypes.arrayOf(
PropTypes.shape({
value: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
})
).isRequired,
id: PropTypes.string,
disabled: PropTypes.bool,
onDarkBg: PropTypes.bool,
};
export default PairedButtons;
|
packages/wix-style-react/src/SocialButton/test/SocialButton.spec.js
|
wix/wix-style-react
|
import React from 'react';
import { createRendererWithUniDriver, cleanup } from '../../../test/utils/unit';
import SocialButton from '../SocialButton';
import { socialButtonPrivateDriverFactory } from './SocialButton.private.uni.driver';
describe('SocialButton', () => {
const render = createRendererWithUniDriver(socialButtonPrivateDriverFactory);
afterEach(() => {
cleanup();
});
it('should render', async () => {
const { driver } = render(<SocialButton />);
expect(await driver.exists()).toBe(true);
});
describe('prop `text`', () => {
it('should be same [when] given', async () => {
const text = 'Share On Facebook';
const { driver } = render(<SocialButton text={text} />);
expect(await driver.getText()).toBe(text);
});
});
describe('prop `onClick`', () => {
it('should be called [when] clicked', async () => {
const onClick = jest.fn();
const { driver } = render(<SocialButton onClick={onClick} />);
await driver.click();
expect(onClick).toHaveBeenCalled();
expect(onClick).toHaveBeenCalledTimes(1);
});
it('should not be called [when] component is disabled', async () => {
const onClick = jest.fn();
const { driver } = render(<SocialButton disabled onClick={onClick} />);
await driver.click();
expect(onClick).not.toHaveBeenCalled();
expect(onClick).toHaveBeenCalledTimes(0);
});
});
});
|
client/src/components/roms/delete/Container.js
|
DjLeChuck/recalbox-manager
|
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import reactStringReplace from 'react-string-replace';
import Button from 'react-bootstrap/lib/Button';
import Glyphicon from 'react-bootstrap/lib/Glyphicon';
import Modal from 'react-bootstrap/lib/Modal';
import RomsDelete from './Delete';
import { post } from '../../../api';
class RomsDeleteContainer extends Component {
static propTypes = {
t: PropTypes.func.isRequired,
system: PropTypes.string.isRequired,
rom: PropTypes.shape({
name: PropTypes.string.isRequired,
path: PropTypes.string.isRequired,
}).isRequired,
onSuccess: PropTypes.func.isRequired,
onError: PropTypes.func.isRequired,
};
static defaultProps = {
onSuccess: () => {},
onError: () => {},
};
constructor(props) {
super(props);
this.state = {
deleting: false,
showModal: false,
};
}
open = () => this.setState({ showModal: true });
close = () => this.setState({ showModal: false });
delete = () => {
const { system, rom: { path }, onSuccess, onError } = this.props;
this.setState({ deleting: true });
post('deleteRom', {
files: [path],
system,
}).then(
() => onSuccess(path),
() => onError()
).then(() => {
this.setState({ deleting: false });
this.close();
});
};
render() {
const { t, rom: { name } } = this.props;
const { showModal, deleting } = this.state;
return (
<div>
<RomsDelete onClick={this.open} />
<Modal show={showModal} onHide={this.close}>
<Modal.Header closeButton>
<Modal.Title>{t('Attention')}</Modal.Title>
</Modal.Header>
<Modal.Body>
<p>
{reactStringReplace(t('Voulez-vous vraiment supprimer %s ?'), '%s', (match, i) => (
<strong key={i}>{name}</strong>
))}
</p>
</Modal.Body>
<Modal.Footer>
<Button onClick={this.close}>{t('Non')}</Button>
<Button bsStyle="warning" onClick={this.delete}>
{deleting &&
<Glyphicon glyph="refresh" className="glyphicon-spin" />
} {t('Oui')}
</Button>
</Modal.Footer>
</Modal>
</div>
);
}
}
export default translate()(RomsDeleteContainer);
|
client/components/app/index.js
|
01laky/isomorphic-go-react-sandbox
|
import React, { Component } from 'react';
import Helmet from 'react-helmet';
export default class App extends Component {
render() {
return <div className="container-fluid">
<Helmet title='Go isomorphic sandbox' />
{this.props.children}
</div>;
}
}
|
packages/material-ui-icons/src/DriveEta.js
|
AndriusBil/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let DriveEta = props =>
<SvgIcon {...props}>
<path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z" />
</SvgIcon>;
DriveEta = pure(DriveEta);
DriveEta.muiName = 'SvgIcon';
export default DriveEta;
|
pages/index.js
|
bigwisu/asik-sehat
|
import Head from 'next/head'
import React from 'react'
import PhotoGrid from '../components/PhotoGrid'
function IndexPage () {
return (
<div>
<Head>
<title>Asik Fit!</title>
</Head>
<PhotoGrid />
</div>
)
}
export default IndexPage
|
src/App.js
|
parzonka/react-redux-seed
|
import React from 'react'
import ReactDOM from 'react-dom'
import Layout from './Layout/Layout'
import { Provider } from 'react-redux'
import { newStore } from '../src/Store'
import 'bootstrap/dist/css/bootstrap.min.css'
const store = newStore();
window.onload = () => {
ReactDOM.render(
<Provider store={store}>
<Layout />
</Provider>,
document.querySelector('#app')
);
};
|
src/components/log.js
|
LaserWeb/lw.controller
|
import React from 'react';
import ReactDOM from 'react-dom';
// level STD, INFO, WARN, DANGER, SUCCESS
const CommandHistory_ICON = ['terminal', 'info-circle', 'exclamation-triangle', 'exclamation-circle', 'check-circle'];
const CommandHistory_CLASS = ['default', 'info', 'warning', 'danger', 'success'];
function createCommandLogLine(message, level = 0, icon = undefined) {
if (icon === undefined) icon = level;
level = isNaN(level) ? level : CommandHistory_CLASS[level];
icon = isNaN(icon) ? icon : CommandHistory_ICON[icon];
let line = document.createElement('code');
line.className = level;
line.innerHTML = `<i class="fa fa-${icon}"></i> ${message}`;
return line;
}
export default class Log extends React.Component {
componentDidMount() {
if (!window.commandLog)
window.commandLog = document.createElement('div');
ReactDOM.findDOMNode(this).appendChild(window.commandLog);
}
componentWillUnmount() {
if (window.commandLog)
ReactDOM.findDOMNode(this).removeChild(window.commandLog);
}
static write(message, level, icon) {
if (!window.commandLog)
window.commandLog = document.createElement('div');
window.commandLog.appendChild(createCommandLogLine(message, level, icon));
if (window.commandLog.parentNode) {
let node = window.commandLog.parentNode;
node.scrollTop = node.scrollHeight;
}
}
static stringify(arg) {
if (typeof arg === 'string')
return arg;
else if (Array.isArray(arg))
return arg.map(Log.stringify).join(' ');
else
return JSON.stringify(arg);
}
static log(...args) {
Log.write(Log.stringify(args));
}
static warn(...args) {
Log.write(Log.stringify(args), 2);
}
static error(...args) {
Log.write(Log.stringify(args), 3);
}
static dir(message, items, level) {
Log.write(`<details><summary>${message}</summary><p>${Log.stringify(items)}</p></details>`, level);
}
render() {
return <div className="log" {...this.props} />;
}
}
Log.STD = 0;
Log.INFO = 1;
Log.WARN = 2;
Log.DANGER = 3;
Log.SUCCESS = 4;
|
src/app/container/checkout-address-done-partial.js
|
all3dp/printing-engine-client
|
import React from 'react'
import {connect} from 'react-redux'
import compose from 'recompose/compose'
import {getStateName, getCountryName} from '../service/country'
import CheckoutStepSection from '../component/checkout-step-section'
import Link from '../component/link'
import Grid from '../component/grid'
import Column from '../component/column'
import Paragraph from '../component/paragraph'
import * as navigationAction from '../action/navigation'
const CheckoutAddressDonePartial = ({user, goToAddress, children}) => {
const shippingStateName =
user && getStateName(user.shippingAddress.countryCode, user.shippingAddress.stateCode)
const billingStateName =
(user &&
user.billingAddress &&
user.billingAddress.stateCode &&
getStateName(user.billingAddress.countryCode, user.billingAddress.stateCode)) ||
(user &&
user.shippingAddress.countryCode === user.billingAddress.countryCode &&
shippingStateName) ||
''
return (
<CheckoutStepSection
title="2. Address"
type="done"
action={
<Link
label="edit"
href="/checkout/address"
onClick={event => {
event.preventDefault()
goToAddress(true)
}}
/>
}
>
<Grid>
<Column md={6}>
<Paragraph size="s" minor>
<strong>Delivery</strong>
<br />
{user.shippingAddress.firstName} {user.shippingAddress.lastName}
<br />
{user.shippingAddress.address}
<br />
{user.shippingAddress.addressLine2 && (
<>
{user.shippingAddress.addressLine2}
<br />
</>
)}
{user.shippingAddress.zipCode} {user.shippingAddress.city}
<br />
{shippingStateName && (
<>
{shippingStateName}
<br />
</>
)}
{getCountryName(user.shippingAddress.countryCode)}
</Paragraph>
<Paragraph size="s" minor>
Contact Email: {user.emailAddress}
<br />
Contact Phone: {user.phoneNumber}
</Paragraph>
</Column>
<Column md={6}>
{user && (
<Paragraph size="s" minor>
<strong>Billing</strong>
<br />
{user.companyName ? (
<>
{user.companyName}
<br />
</>
) : null}
{user.vatId ? (
<>
{user.vatId}
<br />
</>
) : null}
{user.useDifferentBillingAddress ? (
<>
{user.billingAddress.firstName} {user.billingAddress.lastName}
<br />
{user.billingAddress.address}
<br />
{user.billingAddress.addressLine2 && (
<>
{user.billingAddress.addressLine2}
<br />
</>
)}
{user.billingAddress.zipCode} {user.billingAddress.city}
<br />
</>
) : (
<>
{user.shippingAddress.firstName} {user.shippingAddress.lastName}
<br />
{user.shippingAddress.address}
<br />
{user.shippingAddress.addressLine2 && (
<>
{user.shippingAddress.addressLine2}
<br />
</>
)}
{user.shippingAddress.zipCode} {user.shippingAddress.city}
<br />
</>
)}
{billingStateName && (
<>
{billingStateName}
<br />
</>
)}
{user.billingAddress.countryCode
? getCountryName(user.billingAddress.countryCode)
: getCountryName(user.shippingAddress.countryCode)}
</Paragraph>
)}
</Column>
</Grid>
{children}
</CheckoutStepSection>
)
}
const mapStateToProps = state => ({
user: state.core.user
})
const mapDispatchToProps = {
goToAddress: navigationAction.goToAddress
}
export default compose(
connect(
mapStateToProps,
mapDispatchToProps
)
)(CheckoutAddressDonePartial)
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/RestAndDefault.js
|
ro-savage/create-react-app
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import PropTypes from 'prop-types';
function load({ id, ...rest } = { id: 0, user: { id: 42, name: '42' } }) {
return [
{ id: id + 1, name: '1' },
{ id: id + 2, name: '2' },
{ id: id + 3, name: '3' },
rest.user,
];
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
async componentDidMount() {
const users = load();
this.setState({ users });
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-rest-and-default">
{this.state.users.map(user => <div key={user.id}>{user.name}</div>)}
</div>
);
}
}
|
test/components/Pages/Timelines-Tests.js
|
furgat/sabertoot
|
'use strict';
import React from 'react';
import { expect } from 'chai';
import { shallow, mount, render } from 'enzyme';
import sinon from 'sinon';
import Timelines from '../../../js/components/Pages/Timelines';
import Column from '../../../js/components/Timelines/Column';
describe('Page Timelines', function() {
it ('should render as .timelines', function() {
const wrapper = shallow(<Timelines />);
expect(wrapper.hasClass('timelines')).to.equal(true);
})
it ('should mount', function() {
sinon.spy(Timelines.prototype, 'componentWillMount');
const wrapper = mount(<Timelines />);
expect(Timelines.prototype.componentWillMount.calledOnce).to.equal(true);
Timelines.prototype.componentWillMount.restore();
})
describe('div .timelines', function() {
it ('should contain .navigation', function() {
const wrapper = mount(<Timelines />);
expect(wrapper.find('.navigation').length).to.equal(1);
})
it ('should contain .timelines-body', function() {
const wrapper = shallow(<Timelines />);
expect(wrapper.find('.timelines-body').length).to.equal(1);
})
it ('should render Columns from store')
})
})
|
scripts/index.js
|
linc01n/react-qr-app
|
import React from 'react';
import App from './App';
React.render(<App />, document.getElementById('root'));
|
docs/app/Examples/views/Feed/Content/FeedExampleImageLabelShorthand.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import { Feed } from 'semantic-ui-react'
const FeedExampleImageLabelShorthand = () => (
<Feed>
<Feed.Event
image='http://semantic-ui.com/images/avatar/small/elliot.jpg'
content='You added Elliot Fu to the group Coworkers'
/>
<Feed.Event>
<Feed.Label image='http://semantic-ui.com/images/avatar/small/elliot.jpg' />
<Feed.Content content='You added Elliot Fu to the group Coworkers' />
</Feed.Event>
</Feed>
)
export default FeedExampleImageLabelShorthand
|
app/javascript/mastodon/components/video_player.js
|
ebihara99999/mastodon
|
import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import IconButton from './icon_button';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { isIOS } from '../is_mobile';
const messages = defineMessages({
toggle_sound: { id: 'video_player.toggle_sound', defaultMessage: 'Toggle sound' },
toggle_visible: { id: 'video_player.toggle_visible', defaultMessage: 'Toggle visibility' },
expand_video: { id: 'video_player.expand', defaultMessage: 'Expand video' },
});
class VideoPlayer extends React.PureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
width: PropTypes.number,
height: PropTypes.number,
sensitive: PropTypes.bool,
intl: PropTypes.object.isRequired,
autoplay: PropTypes.bool,
onOpenVideo: PropTypes.func.isRequired,
};
static defaultProps = {
width: 239,
height: 110,
};
state = {
visible: !this.props.sensitive,
preview: true,
muted: true,
hasAudio: true,
videoError: false,
};
handleClick = () => {
this.setState({ muted: !this.state.muted });
}
handleVideoClick = (e) => {
e.stopPropagation();
const node = this.video;
if (node.paused) {
node.play();
} else {
node.pause();
}
}
handleOpen = () => {
this.setState({ preview: !this.state.preview });
}
handleVisibility = () => {
this.setState({
visible: !this.state.visible,
preview: true,
});
}
handleExpand = () => {
this.video.pause();
this.props.onOpenVideo(this.props.media, this.video.currentTime);
}
setRef = (c) => {
this.video = c;
}
handleLoadedData = () => {
if (('WebkitAppearance' in document.documentElement.style && this.video.audioTracks.length === 0) || this.video.mozHasAudio === false) {
this.setState({ hasAudio: false });
}
}
handleVideoError = () => {
this.setState({ videoError: true });
}
componentDidMount () {
if (!this.video) {
return;
}
this.video.addEventListener('loadeddata', this.handleLoadedData);
this.video.addEventListener('error', this.handleVideoError);
}
componentDidUpdate () {
if (!this.video) {
return;
}
this.video.addEventListener('loadeddata', this.handleLoadedData);
this.video.addEventListener('error', this.handleVideoError);
}
componentWillUnmount () {
if (!this.video) {
return;
}
this.video.removeEventListener('loadeddata', this.handleLoadedData);
this.video.removeEventListener('error', this.handleVideoError);
}
render () {
const { media, intl, width, height, sensitive, autoplay } = this.props;
let spoilerButton = (
<div className={`status__video-player-spoiler ${this.state.visible ? 'status__video-player-spoiler--visible' : ''}`}>
<IconButton overlay title={intl.formatMessage(messages.toggle_visible)} icon={this.state.visible ? 'eye' : 'eye-slash'} onClick={this.handleVisibility} />
</div>
);
let expandButton = (
<div className='status__video-player-expand'>
<IconButton overlay title={intl.formatMessage(messages.expand_video)} icon='expand' onClick={this.handleExpand} />
</div>
);
let muteButton = '';
if (this.state.hasAudio) {
muteButton = (
<div className='status__video-player-mute'>
<IconButton overlay title={intl.formatMessage(messages.toggle_sound)} icon={this.state.muted ? 'volume-off' : 'volume-up'} onClick={this.handleClick} />
</div>
);
}
if (!this.state.visible) {
if (sensitive) {
return (
<div role='button' tabIndex='0' style={{ width: `${width}px`, height: `${height}px` }} className='media-spoiler' onClick={this.handleVisibility}>
{spoilerButton}
<span className='media-spoiler__warning'><FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' /></span>
<span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span>
</div>
);
} else {
return (
<div role='button' tabIndex='0' style={{ width: `${width}px`, height: `${height}px` }} className='media-spoiler' onClick={this.handleVisibility}>
{spoilerButton}
<span className='media-spoiler__warning'><FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' /></span>
<span className='media-spoiler__trigger'><FormattedMessage id='status.sensitive_toggle' defaultMessage='Click to view' /></span>
</div>
);
}
}
if (this.state.preview && !autoplay) {
return (
<div role='button' tabIndex='0' className='media-spoiler-video' style={{ width: `${width}px`, height: `${height}px`, backgroundImage: `url(${media.get('preview_url')})` }} onClick={this.handleOpen}>
{spoilerButton}
<div className='media-spoiler-video-play-icon'><i className='fa fa-play' /></div>
</div>
);
}
if (this.state.videoError) {
return (
<div style={{ width: `${width}px`, height: `${height}px` }} className='video-error-cover' >
<span className='media-spoiler__warning'><FormattedMessage id='video_player.video_error' defaultMessage='Video could not be played' /></span>
</div>
);
}
return (
<div className='status__video-player' style={{ width: `${width}px`, height: `${height}px` }}>
{spoilerButton}
{muteButton}
{expandButton}
<video
className='status__video-player-video'
role='button'
tabIndex='0'
ref={this.setRef}
src={media.get('url')}
autoPlay={!isIOS()}
loop={true}
muted={this.state.muted}
onClick={this.handleVideoClick}
/>
</div>
);
}
}
export default injectIntl(VideoPlayer);
|
demo/src/welcome.js
|
RinconStrategies/react-web-animation
|
import React from 'react';
import { Animated } from 'react-web-animation';
const getCenterKeyFrames = () => [
{ transform: 'scale(1)', fill: '#00D8FF', opacity: 1, offset: 0 },
{ transform: 'scale(.5)', fill: '#00D822', opacity: 0.5, offset: 0.3 },
{ transform: 'scale(.667)', fill: '#002222', opacity: 0.667, offset: 0.7875 },
{ transform: 'scale(.6)', fill: '#222222', opacity: 0.6, offset: 1 },
];
const getCenterTiming = duration => ({
duration,
easing: 'ease-in-out',
delay: 5,
iterations: Infinity,
direction: 'alternate',
fill: 'forwards',
});
const getOrbitKeyFrame = () => [
{
transform: 'rotate3d(1, -1, 1, 0deg)',
stroke: '#00D8FF',
opacity: 1,
offset: 0,
},
{
transform: 'rotate3d(2, 0, 2, 30deg)',
stroke: '#00D822',
opacity: 0.5,
offset: 0.2,
},
{
transform: 'rotate3d(3, 1, 3, 60deg)',
stroke: '#002222',
opacity: 0.667,
offset: 0.4,
},
{
transform: 'rotate3d(2, 0, 2, 30deg)',
stroke: '#222222',
opacity: 0.6,
offset: 0.6,
},
{
transform: 'rotate3d(1, -1, 1, 0deg)',
stroke: '#222222',
opacity: 0.6,
offset: 1,
},
];
const getOrbitTiming = (duration, direction) => ({
duration,
easing: 'ease-in-out',
delay: 10,
iterations: Infinity,
direction,
fill: 'forwards',
});
export default () => (
<div style={{ padding: '12px' }}>
<h1 style={{ marginBottom: '0px' }}>react-web-animation</h1>
<h3 style={{ marginTop: '0px', color: '#aaa' }}>
React components that expose the Web Animations API
</h3>
<p>Check out the examples on the left. More coming soon!</p>
<p>
<a href="https://github.com/RinconStrategies/react-web-animation">
Source
</a>
</p>
<p>
<a href="https://github.com/RinconStrategies/react-web-animation/tree/master/src">
Documentation
</a>
</p>
<div style={{ textAlign: 'center' }} className="welcome-animation">
<svg
version="1.1"
x="0px"
y="0px"
width="500px"
height="500px"
viewBox="0 0 600 600"
enableBackground="new 0 0 600 600"
>
<Animated.circle
keyframes={getCenterKeyFrames()}
timing={getCenterTiming(2000)}
fill="#00D8FF"
cx="299.529"
cy="299.628"
r="50.167"
style={{ transformOrigin: '300px 300px' }}
/>
<Animated.path
keyframes={getOrbitKeyFrame()}
timing={getOrbitTiming(20000, 'alternate')}
fill="none"
stroke="#00D8FF"
strokeWidth="24"
strokeMiterlimit="10"
d="M299.529,197.628
c67.356,0,129.928,9.665,177.107,25.907c56.844,19.569,91.794,49.233,91.794,76.093c0,27.991-37.041,59.503-98.083,79.728
c-46.151,15.291-106.879,23.272-170.818,23.272c-65.554,0-127.63-7.492-174.29-23.441c-59.046-20.182-94.611-52.103-94.611-79.559
c0-26.642,33.37-56.076,89.415-75.616C167.398,207.503,231.515,197.628,299.529,197.628z"
style={{ transformOrigin: '300px 300px' }}
/>
<Animated.path
keyframes={getOrbitKeyFrame()}
timing={getOrbitTiming(15000, 'alternate')}
fill="none"
stroke="#00D8FF"
strokeWidth="24"
strokeMiterlimit="10"
d="M210.736,248.922
c33.649-58.348,73.281-107.724,110.92-140.48c45.35-39.466,88.507-54.923,111.775-41.505
c24.248,13.983,33.042,61.814,20.067,124.796c-9.81,47.618-33.234,104.212-65.176,159.601
c-32.749,56.788-70.25,106.819-107.377,139.272c-46.981,41.068-92.4,55.929-116.185,42.213
c-23.079-13.31-31.906-56.921-20.834-115.233C153.281,368.316,176.758,307.841,210.736,248.922z"
style={{ transformOrigin: '300px 300px' }}
/>
<Animated.path
keyframes={getOrbitKeyFrame()}
timing={getOrbitTiming(30000, 'alternate')}
fill="none"
stroke="#00D8FF"
strokeWidth="24"
strokeMiterlimit="10"
d="M210.821,351.482
c-33.746-58.292-56.731-117.287-66.312-166.255c-11.544-58.999-3.382-104.109,19.864-117.566
c24.224-14.024,70.055,2.244,118.14,44.94c36.356,32.28,73.688,80.837,105.723,136.173c32.844,56.733,57.461,114.209,67.036,162.582
c12.117,61.213,2.309,107.984-21.453,121.74c-23.057,13.348-65.249-0.784-110.239-39.499
C285.567,460.886,244.898,410.344,210.821,351.482z"
style={{ transformOrigin: '300px 300px' }}
/>
</svg>
</div>
</div>
);
|
packages/material/src/components/IconSubmitButton.native.js
|
wq/wq.app
|
import React from 'react';
import { useComponents } from '@wq/react';
import { useFormikContext } from 'formik';
export default function IconSubmitButton(props) {
const { IconButton } = useComponents(),
{ isSubmitting, submitForm } = useFormikContext();
return (
<IconButton disabled={isSubmitting} onPress={submitForm} {...props} />
);
}
|
examples/with-decorator/grid.example.js
|
babotech/react-ingrid
|
import {ingrid} from '../../lib'
import React from 'react'
import ReactDOM from 'react-dom'
import rndoam from 'rndoam'
let i = 0
const itemsCount = 10000
const items = rndoam.collection({
id: () => i++
}, itemsCount)
let ItemComponent = ({data}) => {
const {id} = data
const palletSize = 2
const color = id % palletSize ? `#039BE5` : `#FF5722`
const style = {
fontFamily: `Roboto`,
fontSize: `50px`,
color: `#FFFFFF`,
lineHeight: `100px`,
textAlign: `center`,
display: `block`,
width: `100%`,
height: `100%`,
backgroundColor: color
}
return (
<div style={style}>
{id}
</div>
)
}
ItemComponent = ingrid(() => ({
items,
itemWidth: 100,
itemHeight: 100
}))(ItemComponent)
const wrapperStyle = {
height: `100vh`,
width: `100vw`
}
document.addEventListener(`DOMContentLoaded`, () => {
ReactDOM.render(
<div style={wrapperStyle}>
<ItemComponent />
</div>,
document.getElementById(`app`)
)
})
|
src/client/routes.js
|
nemecec/base
|
'use strict'
import 'babel/polyfill';
import React from 'react';
import Router from 'react-router';
import App from './components/app';
import UserHome from './components/user-home';
import SignIn from './components/sign-in';
import Error from './components/error';
var DefaultRoute = Router.DefaultRoute;
var Link = Router.Link;
var Route = Router.Route;
var Redirect = Router.Redirect;
var RouteHandler = Router.RouteHandler;
var routes = (
<Route name="app" path="/" handler={App}>
<Route name="user-home" path="/home" handler={UserHome}/>
<Route name="error" path="/error" handler={Error}/>
<DefaultRoute handler={SignIn}/>
</Route>
);
module.exports = routes;
|
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js
|
browncs4sg/website
|
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/App/shared/MainMenu/index.js
|
ryanswapp/react-starter-template
|
import React from 'react';
import { connect } from 'react-redux';
import Actions from 'App/state/actions.js';
import style from './style';
import CSSModules from 'react-css-modules';
import { Link } from 'react-router';
const MainMenu = React.createClass({
componentDidMount() {
const { currentUser, dispatch } = this.props;
if (!currentUser) {
// dispatch(Actions.getCurrentUser());
//
console.log('Example of fetching the current user with an action');
}
},
render() {
return (
<nav className="navbar navbar-default">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1" aria-expanded="false">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand" href="#">React Starter Template</a>
</div>
<div className="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
{ !!this.props.currentUser ? (
<LoggedInLinks />
) : (
<LoggedOutLinks />
) }
</div>
</div>
</nav>
);
}
});
class LoggedInLinks extends React.Component {
constructor(props) {
super(props);
this.logout = this.logout.bind(this);
}
logout() {
console.log('An example logout action');
}
render() {
return (
<ul className="nav navbar-nav navbar-right">
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/users">Users</Link>
</li>
<li className="dropdown">
<a href="#" className="dropdown-toggle" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false">{ this.props.currentUser.email } <span className="caret"></span></a>
<ul className="dropdown-menu">
<li><a href="#" onClick={ this.logout }>Logout</a></li>
</ul>
</li>
</ul>
);
}
};
class LoggedOutLinks extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<ul className="nav navbar-nav navbar-right">
<li>
<Link to="/">Home</Link>
</li>
<li>
<Link to="/users">Users List</Link>
</li>
<li>
<Link to="/signup">Signup</Link>
</li>
<li>
<Link to="/login">Login</Link>
</li>
</ul>
);
}
};
export default CSSModules(MainMenu, style);
|
src/containers/auth/AuthenticateView.js
|
Jenny-L/lumohacks2017
|
/**
* Authenticate Screen
* - Entry screen for all authentication
* - User can tap to login, forget password, signup...
*
* React Native Starter App
* https://github.com/mcnamee/react-native-starter-app
*/
import React, { Component } from 'react';
import {
View,
Image,
StyleSheet,
} from 'react-native';
import { Actions } from 'react-native-router-flux';
// Consts and Libs
import { AppStyles, AppSizes, AppColors } from '@theme/';
// Components
import { Spacer, Text, Button } from '@ui/';
/* Styles ==================================================================== */
const styles = StyleSheet.create({
background: {
backgroundColor: AppColors.brand.primary,
height: AppSizes.screen.height,
width: AppSizes.screen.width,
},
logo: {
width: AppSizes.screen.width * 0.85,
resizeMode: 'contain',
},
whiteText: {
color: '#FFF',
},
});
/* Component ==================================================================== */
class Authenticate extends Component {
static componentName = 'Authenticate';
render = () => (
<View style={[AppStyles.containerCentered, AppStyles.container, styles.background]}>
<Image
source={require('../../images/logo.png')}
style={[styles.logo]}
/>
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Login'}
icon={{ name: 'lock' }}
onPress={Actions.login}
backgroundColor={'#CB009E'}
/>
</View>
</View>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]}>
<Button
title={'Sign up'}
icon={{ name: 'face' }}
onPress={Actions.signUp}
backgroundColor={'#CB009E'}
/>
</View>
</View>
<Spacer size={15} />
<Text p style={[AppStyles.textCenterAligned, styles.whiteText]}>
- or -
</Text>
<Spacer size={10} />
<View style={[AppStyles.row, AppStyles.paddingHorizontal]}>
<View style={[AppStyles.flex1]} />
<View style={[AppStyles.flex2]}>
<Button
small
title={'Skip'}
onPress={Actions.app}
raised={false}
backgroundColor={'rgba(255,255,255,0.2)'}
/>
</View>
<View style={[AppStyles.flex1]} />
</View>
<Spacer size={40} />
</View>
)
}
/* Export Component ==================================================================== */
export default Authenticate;
|
node_modules/react-smooth/demo/Gossip/app.js
|
SerendpityZOEY/Fixr-RelevantCodeSearch
|
import Animate from 'react-smooth';
import React, { Component } from 'react';
import ReactDom from 'react-dom';
const getSTEPS = onAnimationEnd => [{
duration: 1000,
style: {
opacity: 0,
},
}, {
duration: 1000,
style: {
opacity: 1,
transformOrigin: '110px 110px',
transform: 'rotate(0deg) translate(0px, 0px)',
},
easing: 'ease-in',
}, {
duration: 1000,
style: {
transform: 'rotate(500deg) translate(0px, 0px)',
},
easing: 'ease-in-out',
}, {
duration: 2000,
style: {
transformOrigin: '610px 610px',
transform: 'rotate(1440deg) translate(500px, 500px)',
},
}, {
duration: 50,
style: {
transformOrigin: 'center center',
transform: 'translate(500px, 500px) scale(1)',
},
onAnimationEnd,
}, {
duration: 1000,
style: {
transformOrigin: 'center center',
transform: 'translate(500px, 500px) scale(1.6)',
},
}];
const createPoint = (x, y) => {
const currX = x;
const currY = y;
return {
getPath: cmd => [cmd, currX, currY].join(' '),
getCircle: (props) => <circle cx={currX} cy={currY} { ...props } />,
x: currX,
y: currY,
};
};
const getArcPath = (radius, rotation, isLarge, isSweep, dx, dy) => {
return ['A', radius, radius, rotation, isLarge, isSweep, dx, dy].join(' ');
};
class Gossip extends Component {
static displayName = 'Gossip';
constructor(props, ctx) {
super(props, ctx);
this.state = { canBegin: false };
this.handleTextAniamtionBegin = this.handleTextAniamtionBegin.bind(this);
this.STEPS = getSTEPS(this.handleTextAniamtionBegin);
}
handleTextAniamtionBegin() {
this.setState({
canBegin: true,
});
}
renderPath() {
const cx = 110;
const cy = 110;
const r = 100;
const sr = r / 2;
const beginPoint = createPoint(cx, cy - r);
const endPoint = createPoint(cx, cy + r);
const move = beginPoint.getPath('M');
const A = getArcPath(sr, 0, 0, 0, cx, cy);
const A2 = getArcPath(sr, 0, 0, 1, endPoint.x, endPoint.y);
const A3 = getArcPath(r, 0, 0, 1, beginPoint.x, beginPoint.y);
return <path d={[move, A, A2, A3].join('\n')} />;
}
renderSmallCircles() {
const cx = 110;
const cy = 110;
const r = 100;
const sr = r / 2;
const tr = 5;
const centers = [createPoint(cx, cy - sr), createPoint(cx, cy + sr)];
const circles = centers.map((p, i) =>
p.getCircle({
r: tr,
fill: i ? 'white' : 'black',
key: i,
})
);
return <g className="small-circles">{circles}</g>;
}
renderText() {
return (
<Animate canBegin={this.state.canBegin}
duration={1000}
from={{ opacity: 0, transform: 'scale(1)' }}
to={{ opacity: 1, transform: 'scale(1.5)' }}
>
<g style={{ transformOrigin: 'center center' }}>
<text x="500" y="300">May you no bug this year</text>
</g>
</Animate>
);
}
render() {
return (
<svg width="1000" height="1000">
<Animate steps={this.STEPS} >
<g className="gossip">
<circle cx="110" cy="110" r="100" style={{ stroke: 'black', fill: 'white' }} />
{this.renderPath()}
{this.renderSmallCircles()}
</g>
</Animate>
{this.renderText()}
</svg>
);
}
}
ReactDom.render(<Gossip />, document.getElementById('app'));
|
docs/src/NavbarPage.js
|
jareth/react-materialize
|
import React from 'react';
import Row from '../../src/Row';
import Col from '../../src/Col';
import ReactPlayground from './ReactPlayground';
import PropTable from './PropTable';
import store from './store';
import Samples from './Samples';
import iconLinksNavbar from '../../examples/IconLinksNavbar';
import leftAlignedNavbar from '../../examples/LeftAlignedNavbar';
import rightAlignedNavbar from '../../examples/RightAlignedNavbar';
const component = 'Navbar';
class NavbarPage extends React.Component {
componentDidMount() {
store.emit('component', component);
}
render() {
return (
<Row>
<Col m={9} s={12} l={10}>
<p className='caption'>
The navbar is fully contained by an HTML5 Nav tag. Inside a recommended container div, there are 2 main parts of the navbar. A logo or brand link, and the navigations links. You can align these links to the left or right.
</p>
<h4 className='col s12'>
Right Aligned Links
</h4>
<Col s={12}>
<ReactPlayground code={ Samples.rightAlignedNavbar }>
{ rightAlignedNavbar }
</ReactPlayground>
</Col>
<h4 className='col s12'>
Left Aligned Links
</h4>
<Col s={12}>
<ReactPlayground code={ Samples.leftAlignedNavbar }>
{ leftAlignedNavbar }
</ReactPlayground>
</Col>
<h4 className='col s12'>
Icon Links
</h4>
<Col s={12}>
<ReactPlayground code={ Samples.iconLinksNavbar }>
{ iconLinksNavbar }
</ReactPlayground>
</Col>
<Col s={12}>
<PropTable component={component}/>
</Col>
</Col>
</Row>
);
}
}
export default NavbarPage;
|
admin/client/App/components/Navigation/Mobile/SectionItem.js
|
Pop-Code/keystone
|
/**
* A mobile section
*/
import React from 'react';
import MobileListItem from './ListItem';
import { Link } from 'react-router';
const MobileSectionItem = React.createClass({
displayName: 'MobileSectionItem',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
currentListKey: React.PropTypes.string,
href: React.PropTypes.string.isRequired,
lists: React.PropTypes.array,
},
// Render the lists
renderLists () {
if (!this.props.lists || this.props.lists.length <= 1) return null;
const navLists = this.props.lists.map((item) => {
// Get the link and the classname
const href = item.external ? item.path : `${Keystone.adminPath}/${item.path}`;
const className = (this.props.currentListKey && this.props.currentListKey === item.path) ? 'MobileNavigation__list-item is-active' : 'MobileNavigation__list-item';
return (
<MobileListItem key={item.path} href={href} className={className} onClick={this.props.onClick}>
{item.label}
</MobileListItem>
);
});
return (
<div className="MobileNavigation__lists">
{navLists}
</div>
);
},
render () {
return (
<div className={this.props.className}>
<Link
className="MobileNavigation__section-item"
to={this.props.href}
tabIndex="-1"
onClick={this.props.onClick}
>
{this.props.children}
</Link>
{this.renderLists()}
</div>
);
},
});
module.exports = MobileSectionItem;
|
docs/app/index.js
|
Rohanhacker/Semantic-UI-React
|
import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
// ----------------------------------------
// Rendering
// ----------------------------------------
const mountNode = document.createElement('div')
document.body.appendChild(mountNode)
const render = (NewApp) => ReactDOM.render(<NewApp />, mountNode)
// ----------------------------------------
// HMR
// ----------------------------------------
if (__DEV__) {
// When the application source code changes, re-render the whole thing.
if (module.hot) {
module.hot.accept('./App', () => {
// restore scroll
const { scrollLeft, scrollTop } = document.scrollingElement
ReactDOM.unmountComponentAtNode(mountNode)
try {
render(require('./App').default)
document.scrollingElement.scrollTop = scrollTop
document.scrollingElement.scrollLeft = scrollLeft
} catch (e) {
console.error(e) // eslint-disable-line no-console
}
})
}
}
// ----------------------------------------
// Start the app
// ----------------------------------------
render(App)
|
app/javascript/mastodon/features/ui/components/columns_area.js
|
im-in-space/mastodon
|
import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ReactSwipeableViews from 'react-swipeable-views';
import TabsBar, { links, getIndex, getLink } from './tabs_bar';
import { Link } from 'react-router-dom';
import { disableSwiping } from 'mastodon/initial_state';
import BundleContainer from '../containers/bundle_container';
import ColumnLoading from './column_loading';
import DrawerLoading from './drawer_loading';
import BundleColumnError from './bundle_column_error';
import {
Compose,
Notifications,
HomeTimeline,
CommunityTimeline,
PublicTimeline,
HashtagTimeline,
DirectTimeline,
FavouritedStatuses,
BookmarkedStatuses,
ListTimeline,
Directory,
} from '../../ui/util/async-components';
import Icon from 'mastodon/components/icon';
import ComposePanel from './compose_panel';
import NavigationPanel from './navigation_panel';
import { supportsPassiveEvents } from 'detect-passive-events';
import { scrollRight } from '../../../scroll';
const componentMap = {
'COMPOSE': Compose,
'HOME': HomeTimeline,
'NOTIFICATIONS': Notifications,
'PUBLIC': PublicTimeline,
'REMOTE': PublicTimeline,
'COMMUNITY': CommunityTimeline,
'HASHTAG': HashtagTimeline,
'DIRECT': DirectTimeline,
'FAVOURITES': FavouritedStatuses,
'BOOKMARKS': BookmarkedStatuses,
'LIST': ListTimeline,
'DIRECTORY': Directory,
};
const messages = defineMessages({
publish: { id: 'compose_form.publish', defaultMessage: 'Toot' },
});
const shouldHideFAB = path => path.match(/^\/statuses\/|^\/@[^/]+\/\d+|^\/publish|^\/explore|^\/getting-started|^\/start/);
export default @(component => injectIntl(component, { withRef: true }))
class ColumnsArea extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object.isRequired,
};
static propTypes = {
intl: PropTypes.object.isRequired,
columns: ImmutablePropTypes.list.isRequired,
isModalOpen: PropTypes.bool.isRequired,
singleColumn: PropTypes.bool,
children: PropTypes.node,
};
// Corresponds to (max-width: 600px + (285px * 1) + (10px * 1)) in SCSS
mediaQuery = 'matchMedia' in window && window.matchMedia('(max-width: 895px)');
state = {
shouldAnimate: false,
renderComposePanel: !(this.mediaQuery && this.mediaQuery.matches),
}
componentWillReceiveProps() {
if (typeof this.pendingIndex !== 'number' && this.lastIndex !== getIndex(this.context.router.history.location.pathname)) {
this.setState({ shouldAnimate: false });
}
}
componentDidMount() {
if (!this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false);
}
if (this.mediaQuery) {
if (this.mediaQuery.addEventListener) {
this.mediaQuery.addEventListener('change', this.handleLayoutChange);
} else {
this.mediaQuery.addListener(this.handleLayoutChange);
}
this.setState({ renderComposePanel: !this.mediaQuery.matches });
}
this.lastIndex = getIndex(this.context.router.history.location.pathname);
this.isRtlLayout = document.getElementsByTagName('body')[0].classList.contains('rtl');
this.setState({ shouldAnimate: true });
}
componentWillUpdate(nextProps) {
if (this.props.singleColumn !== nextProps.singleColumn && nextProps.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
}
componentDidUpdate(prevProps) {
if (this.props.singleColumn !== prevProps.singleColumn && !this.props.singleColumn) {
this.node.addEventListener('wheel', this.handleWheel, supportsPassiveEvents ? { passive: true } : false);
}
const newIndex = getIndex(this.context.router.history.location.pathname);
if (this.lastIndex !== newIndex) {
this.lastIndex = newIndex;
this.setState({ shouldAnimate: true });
}
}
componentWillUnmount () {
if (!this.props.singleColumn) {
this.node.removeEventListener('wheel', this.handleWheel);
}
if (this.mediaQuery) {
if (this.mediaQuery.removeEventListener) {
this.mediaQuery.removeEventListener('change', this.handleLayoutChange);
} else {
this.mediaQuery.removeListener(this.handleLayouteChange);
}
}
}
handleChildrenContentChange() {
if (!this.props.singleColumn) {
const modifier = this.isRtlLayout ? -1 : 1;
this._interruptScrollAnimation = scrollRight(this.node, (this.node.scrollWidth - window.innerWidth) * modifier);
}
}
handleLayoutChange = (e) => {
this.setState({ renderComposePanel: !e.matches });
}
handleSwipe = (index) => {
this.pendingIndex = index;
const nextLinkTranslationId = links[index].props['data-preview-title-id'];
const currentLinkSelector = '.tabs-bar__link.active';
const nextLinkSelector = `.tabs-bar__link[data-preview-title-id="${nextLinkTranslationId}"]`;
// HACK: Remove the active class from the current link and set it to the next one
// React-router does this for us, but too late, feeling laggy.
document.querySelector(currentLinkSelector).classList.remove('active');
document.querySelector(nextLinkSelector).classList.add('active');
if (!this.state.shouldAnimate && typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
handleAnimationEnd = () => {
if (typeof this.pendingIndex === 'number') {
this.context.router.history.push(getLink(this.pendingIndex));
this.pendingIndex = null;
}
}
handleWheel = () => {
if (typeof this._interruptScrollAnimation !== 'function') {
return;
}
this._interruptScrollAnimation();
}
setRef = (node) => {
this.node = node;
}
renderView = (link, index) => {
const columnIndex = getIndex(this.context.router.history.location.pathname);
const title = this.props.intl.formatMessage({ id: link.props['data-preview-title-id'] });
const icon = link.props['data-preview-icon'];
const view = (index === columnIndex) ?
React.cloneElement(this.props.children) :
<ColumnLoading title={title} icon={icon} />;
return (
<div className='columns-area columns-area--mobile' key={index}>
{view}
</div>
);
}
renderLoading = columnId => () => {
return columnId === 'COMPOSE' ? <DrawerLoading /> : <ColumnLoading />;
}
renderError = (props) => {
return <BundleColumnError {...props} />;
}
render () {
const { columns, children, singleColumn, isModalOpen, intl } = this.props;
const { shouldAnimate, renderComposePanel } = this.state;
const columnIndex = getIndex(this.context.router.history.location.pathname);
if (singleColumn) {
const floatingActionButton = shouldHideFAB(this.context.router.history.location.pathname) ? null : <Link key='floating-action-button' to='/publish' className='floating-action-button' aria-label={intl.formatMessage(messages.publish)}><Icon id='pencil' /></Link>;
const content = columnIndex !== -1 ? (
<ReactSwipeableViews key='content' hysteresis={0.2} threshold={15} index={columnIndex} onChangeIndex={this.handleSwipe} onTransitionEnd={this.handleAnimationEnd} animateTransitions={shouldAnimate} springConfig={{ duration: '400ms', delay: '0s', easeFunction: 'ease' }} style={{ height: '100%' }} disabled={disableSwiping}>
{links.map(this.renderView)}
</ReactSwipeableViews>
) : (
<div key='content' className='columns-area columns-area--mobile'>{children}</div>
);
return (
<div className='columns-area__panels'>
<div className='columns-area__panels__pane columns-area__panels__pane--compositional'>
<div className='columns-area__panels__pane__inner'>
{renderComposePanel && <ComposePanel />}
</div>
</div>
<div className={`columns-area__panels__main ${floatingActionButton && 'with-fab'}`}>
<TabsBar key='tabs' />
{content}
</div>
<div className='columns-area__panels__pane columns-area__panels__pane--start columns-area__panels__pane--navigational'>
<div className='columns-area__panels__pane__inner'>
<NavigationPanel />
</div>
</div>
{floatingActionButton}
</div>
);
}
return (
<div className={`columns-area ${ isModalOpen ? 'unscrollable' : '' }`} ref={this.setRef}>
{columns.map(column => {
const params = column.get('params', null) === null ? null : column.get('params').toJS();
const other = params && params.other ? params.other : {};
return (
<BundleContainer key={column.get('uuid')} fetchComponent={componentMap[column.get('id')]} loading={this.renderLoading(column.get('id'))} error={this.renderError}>
{SpecificComponent => <SpecificComponent columnId={column.get('uuid')} params={params} multiColumn {...other} />}
</BundleContainer>
);
})}
{React.Children.map(children, child => React.cloneElement(child, { multiColumn: true }))}
</div>
);
}
}
|
docs/app/Examples/collections/Table/Variations/TableExampleFixed.js
|
aabustamante/Semantic-UI-React
|
import React from 'react'
import { Table } from 'semantic-ui-react'
const TableExampleFixed = () => {
return (
<Table fixed>
<Table.Header>
<Table.Row>
<Table.HeaderCell>Name</Table.HeaderCell>
<Table.HeaderCell>Status</Table.HeaderCell>
<Table.HeaderCell>Description</Table.HeaderCell>
</Table.Row>
</Table.Header>
<Table.Body>
<Table.Row>
<Table.Cell>John</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>
John is an interesting boy but sometimes you don't really have enough room to describe everything you'd like
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jamie</Table.Cell>
<Table.Cell>Approved</Table.Cell>
<Table.Cell>
Jamie is a kind girl but sometimes you don't really have enough room to describe everything you'd like
</Table.Cell>
</Table.Row>
<Table.Row>
<Table.Cell>Jill</Table.Cell>
<Table.Cell>Denied</Table.Cell>
<Table.Cell>
Jill is an alright girl but sometimes you don't really have enough room to describe everything you'd like
</Table.Cell>
</Table.Row>
</Table.Body>
</Table>
)
}
export default TableExampleFixed
|
src/components/card.js
|
ydsood/policyPrototype
|
import React, { Component } from 'react';
import CardItem from './card_item';
import {fetchPolicy} from '../actions';
import { connect } from 'react-redux';
import { Thumbnail } from 'react-bootstrap';
class Card extends Component {
constructor(props) {
super(props);
this.state = {
isSearchResult: props.isSearchResult,
policyNumber: props.title
}
}
handleSelect() {
if (!this.state.isSearchResult) return;
this.props.fetchPolicy(this.props.title);
}
render() {
if (!this.props || this.props === undefined || this.props === {}) {
return (<div>Loading...</div>);
}
const valueList = this.props.items.filter(
(item) => { return !item.name.includes("ID")&&!item.name.includes("Code")}
)
.map((item) => {
let value = item.value;
if(typeof value === 'string' && Date.parse(value)){
console.log(item.value);
value = item.value.split('T')[0];
}
return (
<CardItem key={item.name} name={item.name} value={value}/>
);
});
return (
<div className = "card" onClick={ this.handleSelect.bind(this)}>
<Thumbnail>
<h4>{this.props.title}</h4>
<ul className="unorderdList">
{ valueList }
</ul>
</Thumbnail>
</div>
);
}
}
export default connect(null, {fetchPolicy} )(Card);
|
packages/react-native-renderer/src/ReactNativeTypes.js
|
dilidili/react
|
/**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @format
* @flow
*/
import React from 'react';
export type MeasureOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
pageX: number,
pageY: number,
) => void;
export type MeasureInWindowOnSuccessCallback = (
x: number,
y: number,
width: number,
height: number,
) => void;
export type MeasureLayoutOnSuccessCallback = (
left: number,
top: number,
width: number,
height: number,
) => void;
type BubblingEventType = {
phasedRegistrationNames: {
captured: string,
bubbled: string,
},
};
type DirectEventType = {
registrationName: string,
};
export type ReactNativeBaseComponentViewConfig = {
validAttributes: Object,
uiViewClassName: string,
bubblingEventTypes?: {[topLevelType: string]: BubblingEventType},
directEventTypes?: {[topLevelType: string]: DirectEventType},
propTypes?: Object,
};
export type ViewConfigGetter = () => ReactNativeBaseComponentViewConfig;
/**
* Class only exists for its Flow type.
*/
class ReactNativeComponent<Props> extends React.Component<Props> {
blur(): void {}
focus(): void {}
measure(callback: MeasureOnSuccessCallback): void {}
measureInWindow(callback: MeasureInWindowOnSuccessCallback): void {}
measureLayout(
relativeToNativeNode: number,
onSuccess: MeasureLayoutOnSuccessCallback,
onFail?: () => void,
): void {}
setNativeProps(nativeProps: Object): void {}
}
/**
* This type keeps ReactNativeFiberHostComponent and NativeMethodsMixin in sync.
* It can also provide types for ReactNative applications that use NMM or refs.
*/
export type NativeMethodsMixinType = {
blur(): void,
focus(): void,
measure(callback: MeasureOnSuccessCallback): void,
measureInWindow(callback: MeasureInWindowOnSuccessCallback): void,
measureLayout(
relativeToNativeNode: number,
onSuccess: MeasureLayoutOnSuccessCallback,
onFail: () => void,
): void,
setNativeProps(nativeProps: Object): void,
};
type SecretInternalsType = {
NativeMethodsMixin: NativeMethodsMixinType,
computeComponentStackForErrorReporting(tag: number): string,
// TODO (bvaughn) Decide which additional types to expose here?
// And how much information to fill in for the above types.
};
type SecretInternalsFabricType = {
NativeMethodsMixin: NativeMethodsMixinType,
};
/**
* Flat ReactNative renderer bundles are too big for Flow to parse efficiently.
* Provide minimal Flow typing for the high-level RN API and call it a day.
*/
export type ReactNativeType = {
NativeComponent: typeof ReactNativeComponent,
findNodeHandle(componentOrHandle: any): ?number,
render(
element: React$Element<any>,
containerTag: any,
callback: ?Function,
): any,
unmountComponentAtNode(containerTag: number): any,
unmountComponentAtNodeAndRemoveContainer(containerTag: number): any,
unstable_batchedUpdates: any, // TODO (bvaughn) Add types
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: SecretInternalsType,
};
export type ReactFabricType = {
NativeComponent: typeof ReactNativeComponent,
findNodeHandle(componentOrHandle: any): ?number,
render(
element: React$Element<any>,
containerTag: any,
callback: ?Function,
): any,
unmountComponentAtNode(containerTag: number): any,
__SECRET_INTERNALS_DO_NOT_USE_OR_YOU_WILL_BE_FIRED: SecretInternalsFabricType,
};
|
src/js/components/Footer/Footer.js
|
HewlettPackard/grommet
|
import React from 'react';
import { Box } from '../Box';
const Footer = ({ ...rest }) => (
<Box
as="footer"
align="center"
direction="row"
flex={false}
gap="medium"
justify="between"
{...rest}
/>
);
export { Footer };
|
demos/forms-demo/src/components/CurrentView/index.js
|
idream3/cerebral
|
import React from 'react'
import {connect} from 'cerebral/react'
import {state} from 'cerebral/tags'
import Simple from '../Simple'
const VIEWS = {
Simple
}
export default connect({
currentView: state`app.currentView`
},
function CurrentView ({currentView}) {
const View = VIEWS[currentView]
return (
<div style={{padding: 30, marginTop: 40}}>
<View />
</div>
)
})
|
src/js/components/Today.js
|
farahat80/react-open-weather
|
import React from 'react';
import PropTypes from 'prop-types';
import { getLabelsByLanguage } from '../utils';
import useStyles from './Today.styles';
const Today = ({ current, unitsLabels, lang, theme }) => {
const classes = useStyles({ theme });
const labels = getLabelsByLanguage(lang);
const hasRange =
current.temperature.min !== undefined &&
current.temperature.max !== undefined;
return (
<div className="rw-today">
<div className={classes.date}>{current.date}</div>
<div className={classes.hr} />
<div className={classes.current}>
{current.temperature.current} {unitsLabels.temperature}
</div>
{hasRange && (
<div className={classes.range}>
{current.temperature.max} / {current.temperature.min}{' '}
{unitsLabels.temperature}
</div>
)}
<div className={classes.desc}>{current.description}</div>
<div className={classes.hr} />
<div className={classes.info}>
<div>
{labels.wind}: <b>{current.wind}</b> {unitsLabels.windSpeed}
</div>
<div>
{labels.humidity}: <b>{current.humidity}</b> %
</div>
</div>
</div>
);
};
Today.propTypes = {
current: PropTypes.object.isRequired,
unitsLabels: PropTypes.object.isRequired,
lang: PropTypes.string.isRequired,
theme: PropTypes.object.isRequired,
};
export default Today;
|
modules/State.js
|
darul75/react-router
|
import React from 'react';
var { object } = React.PropTypes;
/**
* A mixin for components that need to know the path, routes, URL
* params and query that are currently active.
*
* Example:
*
* import { State } from 'react-router';
*
* var AboutLink = React.createClass({
* mixins: [ State ],
* render() {
* var className = this.props.className;
*
* if (this.isActive('about'))
* className += ' is-active';
*
* return React.createElement('a', { className: className }, this.props.children);
* }
* });
*/
var State = {
contextTypes: {
router: object.isRequired
}
};
var RouterStateMethods = [
'isActive'
];
RouterStateMethods.forEach(function (method) {
State[method] = function () {
var router = this.context.router;
return router[method].apply(router, arguments);
};
});
export default State;
|
app/javascript/mastodon/features/ui/util/reduced_motion.js
|
pixiv/mastodon
|
// Like react-motion's Motion, but reduces all animations to cross-fades
// for the benefit of users with motion sickness.
import React from 'react';
import Motion from 'react-motion/lib/Motion';
import PropTypes from 'prop-types';
const stylesToKeep = ['opacity', 'backgroundOpacity'];
const extractValue = (value) => {
// This is either an object with a "val" property or it's a number
return (typeof value === 'object' && value && 'val' in value) ? value.val : value;
};
class ReducedMotion extends React.Component {
static propTypes = {
defaultStyle: PropTypes.object,
style: PropTypes.object,
children: PropTypes.func,
}
render() {
const { style, defaultStyle, children } = this.props;
Object.keys(style).forEach(key => {
if (stylesToKeep.includes(key)) {
return;
}
// If it's setting an x or height or scale or some other value, we need
// to preserve the end-state value without actually animating it
style[key] = defaultStyle[key] = extractValue(style[key]);
});
return (
<Motion style={style} defaultStyle={defaultStyle}>
{children}
</Motion>
);
}
}
export default ReducedMotion;
|
src/svg-icons/content/create.js
|
owencm/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentCreate = (props) => (
<SvgIcon {...props}>
<path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"/>
</SvgIcon>
);
ContentCreate = pure(ContentCreate);
ContentCreate.displayName = 'ContentCreate';
ContentCreate.muiName = 'SvgIcon';
export default ContentCreate;
|
src/containers/Shuffle/config.js
|
EncontrAR/backoffice
|
import React from 'react';
import IntlMessages from '../../components/utility/intlMessages';
import Img1 from '../../image/1.jpg';
import Img2 from '../../image/2.jpg';
import Img3 from '../../image/3.jpg';
import Img4 from '../../image/4.jpg';
import Img5 from '../../image/5.jpg';
import Img6 from '../../image/6.jpg';
import Img7 from '../../image/7.jpg';
const articles = [
{
id: 'a',
timestamp: 811396800000,
desc: <IntlMessages id="shuffle.descriptionOne" />,
img: Img1,
},
{
id: 'b',
timestamp: 1108702800000,
desc: <IntlMessages id="shuffle.descriptionTwo" />,
img: Img2,
},
{
id: 'c',
timestamp: 1156564800000,
desc: <IntlMessages id="shuffle.descriptionThree" />,
img: Img3
},
{
id: 'd',
timestamp: 1256443200000,
desc: <IntlMessages id="shuffle.descriptionFour" />,
img: Img4,
},
{
id: 'e',
timestamp: 1286942400000,
desc: <IntlMessages id="shuffle.descriptionFive" />,
img: Img5,
},
{
id: 'f',
timestamp: 1331697600000,
desc: <IntlMessages id="shuffle.descriptionSix" />,
img: Img6,
},
{
id: 'g',
timestamp: 1369800000000,
desc: <IntlMessages id="shuffle.descriptionSeven" />,
img: Img7,
},
];
export default articles;
|
src/components/Loading/Loading.js
|
fforres/coworks_client_side
|
import React, { Component } from 'react';
class Loading extends Component {
render () {
return (
<div>
<center>
<h1><i className='fa fa-spinner fa-spin' /> </h1>
<h1> Loading... </h1>
</center>
</div>
);
}
}
export { Loading };
export default Loading;
|
ges-client/src/components/Dashboard.js
|
martenhz/ges
|
import React from 'react';
export default class Dashboard extends React.Component {
render() {
return (
<div>
<h1>Dashboard</h1>
</div>
)
}
}
|
src/js/components/Tabs/stories/Scrollable.js
|
grommet/grommet
|
import React from 'react';
import { Box, Heading, Tab, Tabs, Text, Paragraph } from 'grommet';
import { TreeOption } from 'grommet-icons';
const ScrollableTabs = () => (
// Uncomment <Grommet> lines when using outside of storybook
// <Grommet theme={...}>
<Box fill>
<Tabs flex>
<Tab title="Tab 1">
<Box
fill
overflow="auto"
pad="xlarge"
align="center"
background="light-2"
>
<Heading>Title</Heading>
<Paragraph>
<Text weight="bold">
This is a tab with a lot of content. If you scroll down, the tabs
header remains in view.
</Text>
</Paragraph>
<Paragraph>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam
porttitor ipsum a ligula tincidunt, tempor posuere massa gravida.
Morbi at magna lacus. Vivamus eu consequat lectus. Quisque a aliquam
risus. Ut vel dignissim nunc. Etiam rhoncus pellentesque porttitor.
Sed nec gravida nisl. Cras justo ex, condimentum at dolor vel,
lacinia efficitur dui. Nullam pellentesque metus nec felis gravida,
vel suscipit sem condimentum. Ut hendrerit varius enim. Donec congue
vestibulum neque accumsan fermentum. Nulla facilisi. Praesent ornare
id magna vitae malesuada. Aenean nulla enim, pretium ac est vel,
tristique condimentum ex. Phasellus ante enim, pellentesque ut arcu
sit amet, semper sodales dolor.
</Paragraph>
<Paragraph>
Proin sollicitudin dui eget diam mollis mattis eget id magna.
Pellentesque tristique aliquet leo, a euismod velit molestie non.
Donec lacinia, lectus quis mollis pretium, turpis erat sollicitudin
mauris, vitae luctus velit lacus eu metus. Nam pulvinar mauris vitae
massa faucibus, id semper sapien facilisis. Integer a congue ex.
Vestibulum dapibus est fermentum felis hendrerit vulputate. Fusce
libero odio, posuere sit amet mi vitae, cursus aliquam nulla. Nunc
ornare augue vitae mauris ultricies gravida. In quis enim at nisi
semper ultrices. Nunc posuere sed libero in facilisis.
</Paragraph>
<Paragraph>
Etiam sit amet ligula nunc. Pellentesque pulvinar nisl ornare dui
molestie, sed faucibus elit rhoncus. In nec pellentesque enim, eget
ultricies tortor. Phasellus tincidunt ultrices tortor vitae
malesuada. Proin rhoncus maximus mauris, a commodo tortor blandit
quis. Phasellus tincidunt luctus dapibus. Sed in imperdiet enim.
Vivamus varius ut dolor non scelerisque. Praesent volutpat ligula
sodales augue auctor tempor. Quisque eleifend eleifend turpis nec
egestas. Nunc dapibus semper commodo. Sed volutpat arcu eleifend
ipsum volutpat, eu sagittis leo hendrerit. Nulla consequat justo non
erat finibus cursus. Integer porttitor ante in ultrices semper.
</Paragraph>
<Paragraph>
Praesent vel tellus sagittis, fringilla arcu vel, sodales turpis.
Nam id accumsan nibh. Pellentesque eget diam eleifend, ultrices diam
ac, suscipit ipsum. Curabitur euismod sodales sem vel ultricies.
Proin euismod ipsum eros, ut efficitur felis pharetra finibus.
Interdum et malesuada fames ac ante ipsum primis in faucibus. Ut
tincidunt posuere augue at porttitor. Sed venenatis iaculis est, sit
amet interdum magna varius ut. In euismod scelerisque velit, vel
aliquet enim. Etiam lacinia justo nec nibh aliquam, et pulvinar eros
luctus. Fusce quis nisi eu tellus imperdiet bibendum ac id nulla.
Proin ut tincidunt libero. Phasellus sed velit eu risus hendrerit
suscipit at eget felis. Class aptent taciti sociosqu ad litora
torquent per conubia nostra, per inceptos himenaeos. Phasellus at
blandit est. Phasellus fringilla nibh ac est scelerisque, id
faucibus enim interdum.
</Paragraph>
</Box>
</Tab>
<Tab title="Tab 2">
<Box margin="small" pad="large" align="center" background="brand">
<TreeOption size="xlarge" />
</Box>
</Tab>
</Tabs>
</Box>
// </Grommet>
);
export const Scrollable = () => <ScrollableTabs />;
Scrollable.args = {
full: true,
};
export default {
title: 'Controls/Tabs/Scrollable',
};
|
techCurriculum/ui/solutions/3.1/src/components/Title.js
|
tadas412/EngineeringEssentials
|
/**
* Copyright 2017 Goldman Sachs.
* 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';
function Title() {
return (
<div>
<h1>Cards</h1>
<h2>Share your ideas</h2>
</div>
);
}
export default Title;
|
src/svg-icons/notification/event-note.js
|
verdan/material-ui
|
import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationEventNote = (props) => (
<SvgIcon {...props}>
<path d="M17 10H7v2h10v-2zm2-7h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11zm-5-5H7v2h7v-2z"/>
</SvgIcon>
);
NotificationEventNote = pure(NotificationEventNote);
NotificationEventNote.displayName = 'NotificationEventNote';
NotificationEventNote.muiName = 'SvgIcon';
export default NotificationEventNote;
|
examples/md/index.js
|
FormidableLabs/spectacle
|
import React from 'react';
import { render } from 'react-dom';
import {
Box,
Deck,
FlexBox,
FullScreen,
Progress,
MarkdownSlideSet
} from 'spectacle';
// SPECTACLE_CLI_MD_START
import mdContent from './slides.md';
// SPECTACLE_CLI_MD_END
// SPECTACLE_CLI_THEME_START
const theme = {};
// SPECTACLE_CLI_THEME_END
// SPECTACLE_CLI_TEMPLATE_START
const template = () => (
<FlexBox
justifyContent="space-between"
position="absolute"
bottom={0}
width={1}
>
<Box padding="0 1em">
<FullScreen />
</Box>
<Box padding="1em">
<Progress />
</Box>
</FlexBox>
);
// SPECTACLE_CLI_TEMPLATE_END
const Presentation = () => (
<Deck theme={theme} template={template}>
<MarkdownSlideSet>{mdContent}</MarkdownSlideSet>
</Deck>
);
render(<Presentation />, document.getElementById('root'));
|
src/containers/subtraction.js
|
shadow-Fiend/reduxTest
|
import React from 'react'
import { connect } from 'react-redux'
import { subtractionAChange } from '../actions'
import Subtraction from '../components/subtraction'
import { push } from 'react-router-redux'
const mapStateToProps = (state) => ({
...state.reducer.subtraction
})
const mapDispatchToProps = {
onAChange: subtractionAChange,
push
}
export default connect(mapStateToProps, mapDispatchToProps)(Subtraction)
|
src/filter/Filter.js
|
Synchro-TEC/apollo
|
import React from 'react';
import PropTypes from 'prop-types';
import FilterOptions from './FilterOptions';
import _isUndefined from 'lodash/isUndefined';
class Filter extends React.Component {
constructor() {
super();
this.state = {
clearFieldIsVisible: false,
};
this.doFilterBySearchField = this.doFilterBySearchField.bind(this);
this.clearAllFields = this.clearAllFields.bind(this);
this.submitForm = this.submitForm.bind(this);
this.searchFiled;
}
toggleClearField() {
this.setState({
clearFieldIsVisible: this.searchFiled.value !== '',
});
}
doFilterBySearchField() {
if (this.props.onFilter) {
this.props.onFilter(this.searchFiled.value);
}
}
clearAllFields() {
if (this.props.onClearAll) {
this.props.onClearAll(this.searchFiled.value);
}
}
clearSearchField() {
if (this.props.onFilter) {
this.searchFiled.value = '';
this.setState({ clearFieldIsVisible: false }, this.props.onFilter(this.searchFiled.value));
}
}
submitForm(e) {
e.preventDefault();
if (this.props.onFormSubmit) {
this.props.onFormSubmit(this.searchFiled.value);
}
}
render() {
const timesIconStyle = {
paddingTop: '10px',
marginLeft: '-25px',
cursor: 'pointer',
};
const {
applyFilterButtonLabel,
cancelButtonLabel,
clearFilterOptionsButtonLabel,
filterButtonLabel,
placeholder,
children,
} = this.props;
let clearFieldIcon = '';
if (this.state.clearFieldIsVisible) {
clearFieldIcon = (
<span>
<i className="fa fa-times" onClick={() => this.clearSearchField()} style={timesIconStyle} />
</span>
);
}
return (
<form className="sv-form" onSubmit={e => this.submitForm(e)}>
<div className="sv-input-group">
<span className="label at-first">
<i className="fa fa-search fa-fw" />
</span>
<input
className="on-center"
onKeyUp={() => {
this.toggleClearField();
this.doFilterBySearchField();
}}
placeholder={placeholder}
ref={searchField => (this.searchFiled = searchField)}
type="search"
/>
{clearFieldIcon}
<FilterOptions
applyFilterButtonLabel={applyFilterButtonLabel}
cancelButtonLabel={cancelButtonLabel}
clearAllFields={this.clearAllFields}
clearFilterOptionsButtonLabel={clearFilterOptionsButtonLabel}
doFilterBySearchField={this.doFilterBySearchField}
filterButtonLabel={filterButtonLabel}
hasFilterOptions={!_isUndefined(children)}
>
{this.props.children}
</FilterOptions>
</div>
</form>
);
}
}
Filter.defaultProps = {
applyFilterButtonLabel: 'Aplicar Filtro',
cancelButtonLabel: 'Cancelar',
clearFilterOptionsButtonLabel: 'Limpar Filtro',
filterButtonLabel: 'Opções',
placeholder: 'Buscar',
};
Filter.propTypes = {
applyFilterButtonLabel: PropTypes.string,
cancelButtonLabel: PropTypes.string,
clearFilterOptionsButtonLabel: PropTypes.string,
filterButtonLabel: PropTypes.string,
onClearAll: PropTypes.func,
onFilter: PropTypes.func,
onFormSubmit: PropTypes.func,
placeholder: PropTypes.string,
};
Filter.displayName = 'Filter';
export default Filter;
|
app/components/CartPage.js
|
godblessamenaka/Grace-Shopper
|
import React from 'react';
import {Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn, TableFooter} from 'material-ui/Table';
import RaisedButton from 'material-ui/RaisedButton';
// const styles = {
// propContainer: {
// width: 200,
// overflow: 'hidden',
// margin: '20px auto 0',
// },
// propToggleHeader: {
// margin: '20px auto 10px',
// },
// };
const CartPage = (props) => {
const productsInCart = props.productsInCart;
const RowsFromProducts = productsInCart.map(function(product){
return (
<TableRow key={product.id}>
<TableRowColumn><img src={'/images/main bottles/' + product.image} /> </TableRowColumn>
<TableRowColumn>{product.name}</TableRowColumn>
<TableRowColumn>{product.price}</TableRowColumn>
<TableRowColumn>{product.quantity}</TableRowColumn>
<TableRowColumn>{ (product.quantity) * (product.price) }</TableRowColumn>
</TableRow>
);
});
return (
<div>
<Table>
<TableHeader>
<TableRow>
<TableHeaderColumn>Image</TableHeaderColumn>
<TableHeaderColumn>Name</TableHeaderColumn>
<TableHeaderColumn>Price</TableHeaderColumn>
<TableHeaderColumn>Qty</TableHeaderColumn>
<TableHeaderColumn>Total</TableHeaderColumn>
</TableRow>
</TableHeader>
<TableBody>
{RowsFromProducts}
</TableBody>
</Table>
{productsInCart.length === 0 ? <RaisedButton label="Keep Shopping" fullWidth={true} /> : <RaisedButton label="Checkout" fullWidth={true} primary={true} />}
</div>
)
}
export default CartPage;
|
client/modules/App/__tests__/Components/Footer.spec.js
|
CODEINAE/todoy
|
import React from 'react';
import test from 'ava';
import { shallow } from 'enzyme';
import { Footer } from '../../components/Footer/Footer';
test('renders the footer properly', t => {
const wrapper = shallow(
<Footer />
);
t.is(wrapper.find('p').length, 2);
t.is(wrapper.find('p').first().text(), '© 2016 · Hashnode · LinearBytes Inc.');
});
|
src/core/display/App/util/View/Meta/index.js
|
JulienPradet/pigment-store
|
import React from 'react'
import styles from './meta.css'
const Meta = ({children}) => <div className={styles.meta}>{children}</div>
export default Meta
|
src/containers/Asians/TabControls/AdjudicatorTest/ViewAdjudicatorTest/1_AdjudicatorTestMotion/ViewAdjudicatorTestMotion.js
|
westoncolemanl/tabbr-web
|
import React from 'react'
import { connect } from 'react-redux'
import Card, {
CardContent,
CardActions
} from 'material-ui/Card'
import Button from 'material-ui/Button'
export default connect(mapStateToProps)(({
adjudicatorTest,
onChangeEdit
}) =>
<Card>
<CardContent>
{`Theme: ${adjudicatorTest[0].theme}`}
</CardContent>
<CardContent>
{adjudicatorTest[0].motion}
</CardContent>
<CardActions
className={'flex flex-row justify-end'}
>
<Button
children={'EDIT'}
color={'primary'}
onClick={onChangeEdit}
/>
</CardActions>
</Card>
)
function mapStateToProps (state, ownProps) {
return {
adjudicatorTest: Object.values(state.adjudicatorTest.data)
}
}
|
src/pages/App.js
|
arthurfanti/twitterCLone
|
import React from 'react'
import Banner from 'Containers/Banner'
const App = ({ children }) => {
return (
<div>
<header>
<Banner />
</header>
<main>
<div className="container">
{ children }
</div>
</main>
</div>
)
}
export default App
|
src/app.js
|
lzhang0616/mini-twitter-template
|
import React, { Component } from 'react';
/**
* Example top level component that renders a child component
*/
export default class App extends Component {
render() {
return (
<div className='container'>
<div className='row'>
</div>
</div>
);
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.