path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/sims/sims-structure.js | FranckCo/Operation-Explorer | import React, { Component } from 'react';
import SortableTree from 'react-sortable-tree';
import FileExplorerTheme from 'react-sortable-tree-theme-file-explorer';
import { getDataTree, getAttrId } from 'utils/tree-utils';
import 'react-sortable-tree/style.css';
import './sims-structure.css';
const updateMas = (data, mas) =>
data.map(d => {
if (d.id === mas) return { ...d, expanded: !d.expanded };
else if (d.children) return { ...d, children: updateMas(d.children, mas) };
return d;
});
class TreeMenu extends Component {
constructor(props) {
super(props);
this.state = { dataTree: getDataTree(props.structure) };
this.expandMas = mas => {
const { dataTree } = this.state;
this.setState({
dataTree: updateMas(dataTree, mas),
});
};
}
render() {
const { dataTree } = this.state;
return (
<div style={{ width: '100%', height: '70vh' }} className="tree">
<SortableTree
treeData={dataTree}
onChange={dataTree => this.setState({ dataTree })}
canDrag={false}
canDrop={() => false}
generateNodeProps={rowInfo =>
rowInfo.node.label && {
buttons: [
rowInfo.node.presentational ? (
<button
onClick={() => this.expandMas(rowInfo.node.id)}
className="buttonLikeDiv"
>
{rowInfo.node.label}
</button>
) : (
<button
onClick={() =>
rowInfo.node.id &&
this.props.changeActiveAttr(getAttrId(rowInfo.node.id))
}
className="buttonLikeLink"
>
{rowInfo.node.label}
</button>
),
],
}
}
theme={FileExplorerTheme}
/>
</div>
);
}
}
export default TreeMenu;
|
client/node_modules/uu5g03/doc/main/client/src/data/source/uu5-bricks-outline-modal.js | UnicornCollege/ucl.itkpd.configurator | import React from 'react';
import {BaseMixin, ElementaryMixin} from '../common/common.js';
import {Modal} from './bricks.js';
export default React.createClass({
//@@viewOn:mixins
mixins: [
BaseMixin,
ElementaryMixin
],
//@@viewOff:mixins
//@@viewOn:statics
statics: {
tagName: 'UU5.Bricks.Outline.Modal',
classNames: {
main: 'uu5-bricks-outline-modal'
}
},
//@@viewOff:statics
//@@viewOn:propTypes
//@@viewOff:propTypes
//@@viewOn:getDefaultProps
//@@viewOff:getDefaultProps
//@@viewOn:standardComponentLifeCycle
getInitialState: function () {
return {
tag: null,
props: null
};
},
//@@viewOff:standardComponentLifeCycle
//@@viewOn:interface
open: function (tag, props, setStateCallback) {
this.setState({ shown: true, tag: tag, props: props }, setStateCallback);
return this;
},
close: function (setStateCallback) {
this.setState({ shown: false, tag: null, props: null }, setStateCallback);
return this;
},
//@@viewOff:interface
//@@viewOn:overridingMethods
//@@viewOff:overridingMethods
//@@viewOn:componentSpecificHelpers
//@@viewOff:componentSpecificHelpers
//@@viewOn:render
render: function () {
return (
<Modal {...this.getMainPropsToPass()} shown={this.state.shown} header={this.state.tag}>
<pre>{this.state.props}</pre>
</Modal>
);
}
//@@viewOff:render
}); |
packages/components/src/List/Toolbar/ColumnChooserButton/ColumnChooser/ColumnChooserRow/ColumnChooserRow.component.js | Talend/ui | import React from 'react';
import PropTypes from 'prop-types';
import Label from './RowLabel';
import Checkbox from './RowCheckbox';
import cssModule from '../ColumnChooser.scss';
import { getTheme } from '../../../../../theme';
const theme = getTheme(cssModule);
const ColumnChooserRow = ({ children, className }) => (
<div className={theme('tc-column-chooser-row', className)}>{children}</div>
);
ColumnChooserRow.propTypes = {
children: PropTypes.oneOfType([PropTypes.element, PropTypes.arrayOf(PropTypes.element)]),
className: PropTypes.string,
};
ColumnChooserRow.Checkbox = Checkbox;
ColumnChooserRow.Label = Label;
export default ColumnChooserRow;
|
src/index.js | dmfarcas/dragomirna-biking | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import './index.css';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/app/containers/widgets/QuickEmail.js | ucokfm/admin-lte-react | import React from 'react';
const QuickEmail = () => (
<div className="box box-info">
<div className="box-header">
<i className="fa fa-envelope"></i>
<h3 className="box-title">Quick Email</h3>
<div className="pull-right box-tools">
<button
type="button"
className="btn btn-info btn-sm"
data-widget="remove"
data-toggle="tooltip"
title="Remove"
>
<i className="fa fa-times"></i>
</button>
</div>
</div>
<div className="box-body">
<form action="#" method="post">
<div className="form-group">
<input
type="email"
className="form-control"
name="emailto"
placeholder="Email to:"
/>
</div>
<div className="form-group">
<input
type="text"
className="form-control"
name="subject"
placeholder="Subject"
/>
</div>
<div>
<textarea
className="textarea"
placeholder="Message"
style={{
width: '100%',
height: 125,
fontSize: 14,
lineHeight: 18,
border: '1px solid #dddddd',
padding: 10,
}}
>
</textarea>
</div>
</form>
</div>
<div className="box-footer clearfix">
<button
type="button"
className="pull-right btn btn-default"
id="sendEmail"
>
Send <i className="fa fa-arrow-circle-right"></i>
</button>
</div>
</div>
);
export default QuickEmail;
|
packages/xo-web/src/common/form/number.js | vatesfr/xo-web | import PropTypes from 'prop-types'
import React from 'react'
import { injectState, provideState } from 'reaclette'
import decorate from '../apply-decorators'
// it provide `data-*` to add params to the `onChange`
const Number_ = decorate([
provideState({
initialState: () => ({
displayedValue: '',
}),
effects: {
onChange(_, { target: { value } }) {
const { state, props } = this
state.displayedValue = value = value.trim()
if (value === '') {
value = undefined
} else {
value = +value
if (Number.isNaN(value)) {
return
}
}
const params = {}
let empty = true
Object.keys(props).forEach(key => {
if (key.startsWith('data-')) {
empty = false
params[key.slice(5)] = props[key]
}
})
props.onChange(value, empty ? undefined : params)
},
},
computed: {
value: ({ displayedValue }, { value }) => {
const numericValue = +displayedValue
if (displayedValue === '' || (!Number.isNaN(numericValue) && numericValue !== value)) {
return value === undefined ? '' : String(value)
}
return displayedValue
},
},
}),
injectState,
({ state, effects, value, className = 'form-control', ...props }) => (
<input {...props} className={className} onChange={effects.onChange} type='number' value={state.value} />
),
])
Number_.propTypes = {
onChange: PropTypes.func.isRequired,
value: PropTypes.number,
}
export default Number_
|
src/index.js | calebeno/LearnReduxTakeTwo | /* eslint-disable import/default */
import React from 'react';
import { render } from 'react-dom';
// store configuration
import configureStore from './store/configureStore';
// import css
import './index.css';
// import react router
import { Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import routes from './routes';
import { Provider } from 'react-redux';
// import initial state
import comments from './data/comments';
import posts from './data/posts';
const defaultState = {
posts,
comments
};
const store = configureStore(defaultState);
const history = syncHistoryWithStore(browserHistory, store);
const router = (
<Provider store={store}>
<Router history={history} routes={routes} />
</Provider>
);
render(router, document.getElementById('app'));
|
client/app/scenes/home.js | kirinami/portfolio | import React from 'react';
import Navbar from '../components/navbar';
import Header from '../components/header';
import Footer from '../components/footer';
import { projects } from '../data';
export default function Home() {
return (
<div className="home--component">
<Navbar/>
<Header/>
<div className="container-fluid">
<div className="about">
<div className="row">
<div className="col-md-12">
<div className="heading heading-header">
<h3 className="title">About Us</h3>
<div className="line line-black"/>
</div>
</div>
</div>
<div className="row">
<div className="col-md-3 col-sm-6 col-xs-12">
<div className="item item-1">
<div className="icon">
<i className="icon fa fa-fw fa-codepen"/>
</div>
<h4>Customizations</h4>
<div>Meteor is free HTML website template by Tooplate. Feel free to use this layout for
your project.
</div>
</div>
</div>
<div className="col-md-3 col-sm-6 col-xs-12">
<div className="item item-2">
<div className="icon">
<i className="fa fa-fw fa-codepen"/>
</div>
<h4>Creative Ideas</h4>
<div>Biodiesel schltz suculents phone cliche ramps snackwave coloring book tumeric poke,
typewriter.
</div>
</div>
</div>
<div className="col-md-3 col-sm-6 col-xs-12">
<div className="item item-3">
<div className="icon">
<i className="fa fa-fw fa-codepen"/>
</div>
<h4>Good Profit</h4>
<div>Biodiesel schltz suculents phone cliche ramps snackwave coloring book tumeric poke,
typewriter.
</div>
</div>
</div>
<div className="col-md-3 col-sm-6 col-xs-12">
<div className="item item-4">
<div className="icon">
<i className="fa fa-fw fa-codepen"/>
</div>
<h4>Open To Public</h4>
<div>Biodiesel schltz suculents phone cliche ramps snackwave coloring book tumeric poke,
typewriter.
</div>
</div>
</div>
</div>
</div>
</div>
<div className="container-full">
<div className="row">
<div className="col-md-12">
<div className="heading heading-header">
<h3 className="title">Portfolio</h3>
<div className="line line-black"/>
</div>
</div>
</div>
{projects.map((project, i) => (
<div key={project._id} className={`section skew ${i % 2 ? 'skew-left' : 'skew-right'}`}>
<div className="background" style={{ backgroundImage: `url('${project.image}')` }}/>
<div className="content">
<div className="heading">
<h3 className="title">{project.title}</h3>
<div className="line"/>
<div className="description">{project.description}</div>
</div>
<div className="technologies">
<ul className="nav">
{project.technologies.map(technology => (
<li key={technology._id}>
<img src={technology.image} alt={technology.title}/>
</li>
))}
</ul>
</div>
</div>
</div>
))}
</div>
<Footer/>
</div>
);
}
|
packages/reactor/src/renderWhenReady.js | sencha/extjs-reactor | import React from 'react';
const launchQueue = [];
/**
* Higher order function that returns a component that waits for a ExtReact to be ready before rendering.
* @param {class} Component
* @return {class}
*/
export default function renderWhenReady(Component) {
return class ExtReactRenderWhenReady extends React.Component {
static isExtJSComponent = true;
constructor() {
super();
this.state = {
ready: Ext.isReady
}
}
componentWillMount() {
if (!this.state.ready) {
launchQueue.push(this);
}
}
render() {
return this.state.ready === true && (
<Component {...this.props}/>
);
}
}
}
Ext.onReady(() => {
for (let queued of launchQueue) {
queued.setState({ ready: true });
}
}); |
packages/reactor-kitchensink/src/examples/Trees/Tree/Tree.js | sencha/extjs-reactor | import React, { Component } from 'react';
import { Tree } from '@extjs/ext-react';
import data from './data';
export default class TreeExample extends Component {
store = Ext.create('Ext.data.TreeStore', {
rootVisible: true,
root: data
})
render() {
return (
<Tree store={this.store} shadow/>
)
}
} |
src/components/user/index.js | abhijitrakas/react-redux-setup | import React from 'react'
import { connect } from 'react-redux';
import AddUserForm from './add';
import * as userActions from '../../actions/users/createUsers';
import Table from '../common/table/Table';
class Users extends React.Component
{
constructor(props) {
super(props);
this.formSubmit = this.formSubmit.bind(this);
this.inputChange = this.inputChange.bind(this);
this.state = {'email': '', 'username': ''};
}
inputChange(event) {
this.setState({[event.target.name]:event.target.value});
}
formSubmit(event) {
event.preventDefault();
this.props.createUser(this.state);
}
render() {
let inputVal = this.state;
let column = {two: 'Email', first:'Username'};
return (
<div>
<div className="row">
<div className="col-md-6">
<h3>Users Page</h3>
<div><Table classes="table table-bordered" titleList={column} dataSet={this.props.users} /></div>
</div>
<div className="col-md-6">
<h3>Add User</h3>
<div>
<AddUserForm handleForm={this.formSubmit} dataVal={inputVal} inptChange={this.inputChange} />
</div>
</div>
</div>
</div>
);
}
}
const mapStateToProps = (state, ownProps) => ({
users: state.users
});
const mapDispatchToProps = (dispatch) => ({
createUser: user => dispatch(userActions.createUser(user))
});
export default connect(mapStateToProps, mapDispatchToProps)(Users); |
portfolio/src/index.js | BeshoyHindy/BeshoyHindy.github.io | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker();
|
src/components/ClothingElement.js | shaunsaker/real-dope | import React from 'react';
import { Button } from 'react-bootstrap';
export default class ClothingElement extends React.Component
{
static get propTypes()
{
return {
clothing: React.PropTypes.object
};
}
render()
{
return (
<div className="clothingElement flex-hz flex-space-between padding-small">
<div className="flex-2">
<p className="text-light">{this.props.name}</p>
</div>
<div className="flex-1">
<p className="text-light">{this.props.space}</p>
</div>
<div className="flex-1">
<p className="text-light">{this.props.price}</p>
</div>
<Button bsSize="xs" bsStyle="primary" className="flex-1" data-name={this.props.name} data-space={this.props.space} data-price={this.props.price} data-id={this.props.id} onClick={this.props.handleClick}>
<p className="text-light">Buy</p>
</Button>
</div>
)
}
} |
code/workspaces/web-app/src/components/stacks/PaginationControlTextField.js | NERC-CEH/datalab | import React from 'react';
import TextField from '@material-ui/core/TextField';
import { makeStyles } from '@material-ui/core/styles';
import PropTypes from 'prop-types';
import theme from '../../theme';
const useStyles = makeStyles(() => ({
pageNumberInput: {
maxWidth: '3em',
margin: 0,
},
}));
const PaginationControlTextField = (
{ pageInputValue, setPageInputValue, changePageToUserInput },
) => {
const classes = useStyles();
return (
<TextField
className={classes.pageNumberInput}
inputProps={{
style: {
textAlign: 'center',
padding: theme.spacing(1),
},
}}
variant="outlined" margin="dense" size="small"
value={pageInputValue}
onChange={event => setPageInputValue(event.target.value)}
onBlur={() => changePageToUserInput()}
onKeyPress={event => event.key === 'Enter' && changePageToUserInput()}
/>
);
};
PaginationControlTextField.propTypes = {
pageInputValue: PropTypes.oneOfType(
[PropTypes.number, PropTypes.string],
).isRequired,
setPageInputValue: PropTypes.func.isRequired,
changePageToUserInput: PropTypes.func.isRequired,
};
export default PaginationControlTextField;
|
src/index.js | abasallo/to-do-front | import React from 'react'
import { render } from 'react-dom'
import { createStore, applyMiddleware } from 'redux'
import { Provider } from 'react-redux'
import thunk from 'redux-thunk'
import injectTapEventPlugin from 'react-tap-event-plugin'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider'
import rootReducer from './reducers'
import State from './State'
import InitialDataFetchAction from './actions/InitialDataFetchAction'
import AppContainer from './containers/AppContainer'
import Auth0Service from './services/Auth0Service'
injectTapEventPlugin()
const store = createStore(rootReducer, new State(), applyMiddleware(thunk))
render(
<Provider store={ store }>
<MuiThemeProvider>
<AppContainer/>
</MuiThemeProvider>
</Provider>,
document.getElementById('root')
)
if (!Auth0Service.getAccessToken())
Auth0Service.login()
else
store.dispatch(InitialDataFetchAction.thunk())
|
node_modules/react-bootstrap/es/Clearfix.js | acalabano/get-committed | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import PropTypes from 'prop-types';
import elementType from 'prop-types-extra/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
import capitalize from './utils/capitalize';
import { DEVICE_SIZES } from './utils/StyleConfig';
var propTypes = {
componentClass: elementType,
/**
* Apply clearfix
*
* on Extra small devices Phones
*
* adds class `visible-xs-block`
*/
visibleXsBlock: PropTypes.bool,
/**
* Apply clearfix
*
* on Small devices Tablets
*
* adds class `visible-sm-block`
*/
visibleSmBlock: PropTypes.bool,
/**
* Apply clearfix
*
* on Medium devices Desktops
*
* adds class `visible-md-block`
*/
visibleMdBlock: PropTypes.bool,
/**
* Apply clearfix
*
* on Large devices Desktops
*
* adds class `visible-lg-block`
*/
visibleLgBlock: PropTypes.bool
};
var defaultProps = {
componentClass: 'div'
};
var Clearfix = function (_React$Component) {
_inherits(Clearfix, _React$Component);
function Clearfix() {
_classCallCheck(this, Clearfix);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Clearfix.prototype.render = function render() {
var _props = this.props,
Component = _props.componentClass,
className = _props.className,
props = _objectWithoutProperties(_props, ['componentClass', 'className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
DEVICE_SIZES.forEach(function (size) {
var propName = 'visible' + capitalize(size) + 'Block';
if (elementProps[propName]) {
classes['visible-' + size + '-block'] = true;
}
delete elementProps[propName];
});
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return Clearfix;
}(React.Component);
Clearfix.propTypes = propTypes;
Clearfix.defaultProps = defaultProps;
export default bsClass('clearfix', Clearfix); |
client/src/components/timepicker.js | euqen/spreadsheet-core | 'use strict';
import React from 'react';
import $ from 'jquery';
import 'timepicker';
export default class TimePicker extends React.Component {
render() {
return (
<div className="input-group bootstrap-timepicker timepicker">
<input id="timepicker"
className="form-control"
data-provide="timepicker"
data-template="modal"
data-minute-step="5"
data-modal-backdrop="true"
data-show-meridian="false"
type="text"
name="time"
onChange={this.props.onChange}
placeholder="Time"
/>
</div>
);
}
} |
frontend/src/Movie/Index/Posters/MovieIndexPosters.js | Radarr/Radarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { Grid, WindowScroller } from 'react-virtualized';
import Measure from 'Components/Measure';
import MovieIndexItemConnector from 'Movie/Index/MovieIndexItemConnector';
import dimensions from 'Styles/Variables/dimensions';
import getIndexOfFirstCharacter from 'Utilities/Array/getIndexOfFirstCharacter';
import hasDifferentItemsOrOrder from 'Utilities/Object/hasDifferentItemsOrOrder';
import MovieIndexPoster from './MovieIndexPoster';
import styles from './MovieIndexPosters.css';
// Poster container dimensions
const columnPadding = parseInt(dimensions.movieIndexColumnPadding);
const columnPaddingSmallScreen = parseInt(dimensions.movieIndexColumnPaddingSmallScreen);
const progressBarHeight = parseInt(dimensions.progressBarSmallHeight);
const detailedProgressBarHeight = parseInt(dimensions.progressBarMediumHeight);
const additionalColumnCount = {
small: 3,
medium: 2,
large: 1
};
function calculateColumnWidth(width, posterSize, isSmallScreen) {
const maxiumColumnWidth = isSmallScreen ? 172 : 182;
const columns = Math.floor(width / maxiumColumnWidth);
const remainder = width % maxiumColumnWidth;
if (remainder === 0 && posterSize === 'large') {
return maxiumColumnWidth;
}
return Math.floor(width / (columns + additionalColumnCount[posterSize]));
}
function calculateRowHeight(posterHeight, sortKey, isSmallScreen, posterOptions) {
const {
detailedProgressBar,
showTitle,
showMonitored,
showQualityProfile,
showReleaseDate
} = posterOptions;
const nextAiringHeight = 19;
const heights = [
posterHeight,
detailedProgressBar ? detailedProgressBarHeight : progressBarHeight,
nextAiringHeight,
isSmallScreen ? columnPaddingSmallScreen : columnPadding
];
if (showTitle) {
heights.push(19);
}
if (showMonitored) {
heights.push(19);
}
if (showQualityProfile) {
heights.push(19);
}
if (showReleaseDate) {
heights.push(19);
}
switch (sortKey) {
case 'studio':
case 'added':
case 'path':
case 'sizeOnDisk':
heights.push(19);
break;
case 'qualityProfileId':
if (!showQualityProfile) {
heights.push(19);
}
break;
default:
// No need to add a height of 0
}
return heights.reduce((acc, height) => acc + height, 0);
}
function calculatePosterHeight(posterWidth) {
return Math.ceil((250 / 170) * posterWidth);
}
class MovieIndexPosters extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
width: 0,
columnWidth: 182,
columnCount: 1,
posterWidth: 162,
posterHeight: 238,
rowHeight: calculateRowHeight(238, null, props.isSmallScreen, {}),
scrollRestored: false
};
this._isInitialized = false;
this._grid = null;
this._padding = props.isSmallScreen ? columnPaddingSmallScreen : columnPadding;
}
componentDidUpdate(prevProps, prevState) {
const {
items,
sortKey,
posterOptions,
jumpToCharacter,
isSmallScreen,
isMovieEditorActive,
scrollTop
} = this.props;
const {
width,
columnWidth,
columnCount,
rowHeight,
scrollRestored
} = this.state;
if (prevProps.sortKey !== sortKey ||
prevProps.posterOptions !== posterOptions) {
this.calculateGrid(width, isSmallScreen);
}
if (this._grid &&
(prevState.width !== width ||
prevState.columnWidth !== columnWidth ||
prevState.columnCount !== columnCount ||
prevState.rowHeight !== rowHeight ||
hasDifferentItemsOrOrder(prevProps.items, items) ||
prevState.isMovieEditorActive !== isMovieEditorActive)) {
// recomputeGridSize also forces Grid to discard its cache of rendered cells
this._grid.recomputeGridSize();
}
if (this._grid && scrollTop !== 0 && !scrollRestored) {
this.setState({ scrollRestored: true });
this._grid.scrollToPosition({ scrollTop });
}
if (jumpToCharacter != null && jumpToCharacter !== prevProps.jumpToCharacter) {
const index = getIndexOfFirstCharacter(items, jumpToCharacter);
if (this._grid && index != null) {
const row = Math.floor(index / columnCount);
this._grid.scrollToCell({
rowIndex: row,
columnIndex: 0
});
}
}
if (this._grid && scrollTop !== 0) {
this._grid.scrollToPosition({ scrollTop });
}
}
//
// Control
setGridRef = (ref) => {
this._grid = ref;
};
calculateGrid = (width = this.state.width, isSmallScreen) => {
const {
sortKey,
posterOptions
} = this.props;
const columnWidth = calculateColumnWidth(width, posterOptions.size, isSmallScreen);
const columnCount = Math.max(Math.floor(width / columnWidth), 1);
const posterWidth = columnWidth - this._padding * 2;
const posterHeight = calculatePosterHeight(posterWidth);
const rowHeight = calculateRowHeight(posterHeight, sortKey, isSmallScreen, posterOptions);
this.setState({
width,
columnWidth,
columnCount,
posterWidth,
posterHeight,
rowHeight
});
};
cellRenderer = ({ key, rowIndex, columnIndex, style }) => {
const {
items,
sortKey,
posterOptions,
showRelativeDates,
shortDateFormat,
timeFormat,
selectedState,
isMovieEditorActive,
onSelectedChange
} = this.props;
const {
posterWidth,
posterHeight,
columnCount
} = this.state;
const {
detailedProgressBar,
showTitle,
showMonitored,
showQualityProfile,
showCinemaRelease,
showReleaseDate
} = posterOptions;
const movieIdx = rowIndex * columnCount + columnIndex;
const movie = items[movieIdx];
if (!movie) {
return null;
}
return (
<div
className={styles.container}
key={key}
style={{
...style,
padding: this._padding
}}
>
<MovieIndexItemConnector
key={movie.id}
component={MovieIndexPoster}
sortKey={sortKey}
posterWidth={posterWidth}
posterHeight={posterHeight}
detailedProgressBar={detailedProgressBar}
showTitle={showTitle}
showMonitored={showMonitored}
showQualityProfile={showQualityProfile}
showReleaseDate={showReleaseDate}
showCinemaRelease={showCinemaRelease}
showRelativeDates={showRelativeDates}
shortDateFormat={shortDateFormat}
timeFormat={timeFormat}
movieId={movie.id}
qualityProfileId={movie.qualityProfileId}
isSelected={selectedState[movie.id]}
onSelectedChange={onSelectedChange}
isMovieEditorActive={isMovieEditorActive}
/>
</div>
);
};
//
// Listeners
onMeasure = ({ width }) => {
this.calculateGrid(width, this.props.isSmallScreen);
};
//
// Render
render() {
const {
isSmallScreen,
scroller,
items,
selectedState
} = this.props;
const {
width,
columnWidth,
columnCount,
rowHeight
} = this.state;
const rowCount = Math.ceil(items.length / columnCount);
return (
<Measure
whitelist={['width']}
onMeasure={this.onMeasure}
>
<WindowScroller
scrollElement={isSmallScreen ? undefined : scroller}
>
{({ height, registerChild, onChildScroll, scrollTop }) => {
if (!height) {
return <div />;
}
return (
<div ref={registerChild}>
<Grid
ref={this.setGridRef}
className={styles.grid}
autoHeight={true}
height={height}
columnCount={columnCount}
columnWidth={columnWidth}
rowCount={rowCount}
rowHeight={rowHeight}
width={width}
onScroll={onChildScroll}
scrollTop={scrollTop}
overscanRowCount={2}
cellRenderer={this.cellRenderer}
selectedState={selectedState}
scrollToAlignment={'start'}
isScrollingOptOut={true}
/>
</div>
);
}
}
</WindowScroller>
</Measure>
);
}
}
MovieIndexPosters.propTypes = {
items: PropTypes.arrayOf(PropTypes.object).isRequired,
sortKey: PropTypes.string,
posterOptions: PropTypes.object.isRequired,
jumpToCharacter: PropTypes.string,
scrollTop: PropTypes.number.isRequired,
scroller: PropTypes.instanceOf(Element).isRequired,
showRelativeDates: PropTypes.bool.isRequired,
shortDateFormat: PropTypes.string.isRequired,
isSmallScreen: PropTypes.bool.isRequired,
timeFormat: PropTypes.string.isRequired,
selectedState: PropTypes.object.isRequired,
onSelectedChange: PropTypes.func.isRequired,
isMovieEditorActive: PropTypes.bool.isRequired
};
export default MovieIndexPosters;
|
projects/twitch-web/src/components/Streams.js | unindented/twitch-x | import React from 'react'
import TopStreams from '../containers/TopStreams'
export default function Streams () {
return (
<TopStreams
limit={25}
columns={5}
/>
)
}
|
static/src/components/Home/index.js | dom-o/hangboard-helper | import React from 'react';
export const Home = () =>
<section>
<div className="container text-center">
<h1>Hello</h1>
</div>
</section>;
|
app/javascript/mastodon/components/modal_root.js | koba-lab/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import 'wicg-inert';
import { createBrowserHistory } from 'history';
import { multiply } from 'color-blend';
export default class ModalRoot extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
children: PropTypes.node,
onClose: PropTypes.func.isRequired,
backgroundColor: PropTypes.shape({
r: PropTypes.number,
g: PropTypes.number,
b: PropTypes.number,
}),
ignoreFocus: PropTypes.bool,
};
activeElement = this.props.children ? document.activeElement : null;
handleKeyUp = (e) => {
if ((e.key === 'Escape' || e.key === 'Esc' || e.keyCode === 27)
&& !!this.props.children) {
this.props.onClose();
}
}
handleKeyDown = (e) => {
if (e.key === 'Tab') {
const focusable = Array.from(this.node.querySelectorAll('button:not([disabled]), [href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), [tabindex]:not([tabindex="-1"])')).filter((x) => window.getComputedStyle(x).display !== 'none');
const index = focusable.indexOf(e.target);
let element;
if (e.shiftKey) {
element = focusable[index - 1] || focusable[focusable.length - 1];
} else {
element = focusable[index + 1] || focusable[0];
}
if (element) {
element.focus();
e.stopPropagation();
e.preventDefault();
}
}
}
componentDidMount () {
window.addEventListener('keyup', this.handleKeyUp, false);
window.addEventListener('keydown', this.handleKeyDown, false);
this.history = this.context.router ? this.context.router.history : createBrowserHistory();
}
componentWillReceiveProps (nextProps) {
if (!!nextProps.children && !this.props.children) {
this.activeElement = document.activeElement;
this.getSiblings().forEach(sibling => sibling.setAttribute('inert', true));
}
}
componentDidUpdate (prevProps) {
if (!this.props.children && !!prevProps.children) {
this.getSiblings().forEach(sibling => sibling.removeAttribute('inert'));
// Because of the wicg-inert polyfill, the activeElement may not be
// immediately selectable, we have to wait for observers to run, as
// described in https://github.com/WICG/inert#performance-and-gotchas
Promise.resolve().then(() => {
if (!this.props.ignoreFocus) {
this.activeElement.focus({ preventScroll: true });
}
this.activeElement = null;
}).catch(console.error);
this._handleModalClose();
}
if (this.props.children && !prevProps.children) {
this._handleModalOpen();
}
if (this.props.children) {
this._ensureHistoryBuffer();
}
}
componentWillUnmount () {
window.removeEventListener('keyup', this.handleKeyUp);
window.removeEventListener('keydown', this.handleKeyDown);
}
_handleModalOpen () {
this._modalHistoryKey = Date.now();
this.unlistenHistory = this.history.listen((_, action) => {
if (action === 'POP') {
this.props.onClose();
}
});
}
_handleModalClose () {
if (this.unlistenHistory) {
this.unlistenHistory();
}
const { state } = this.history.location;
if (state && state.mastodonModalKey === this._modalHistoryKey) {
this.history.goBack();
}
}
_ensureHistoryBuffer () {
const { pathname, state } = this.history.location;
if (!state || state.mastodonModalKey !== this._modalHistoryKey) {
this.history.push(pathname, { ...state, mastodonModalKey: this._modalHistoryKey });
}
}
getSiblings = () => {
return Array(...this.node.parentElement.childNodes).filter(node => node !== this.node);
}
setRef = ref => {
this.node = ref;
}
render () {
const { children, onClose } = this.props;
const visible = !!children;
if (!visible) {
return (
<div className='modal-root' ref={this.setRef} style={{ opacity: 0 }} />
);
}
let backgroundColor = null;
if (this.props.backgroundColor) {
backgroundColor = multiply({ ...this.props.backgroundColor, a: 1 }, { r: 0, g: 0, b: 0, a: 0.7 });
}
return (
<div className='modal-root' ref={this.setRef}>
<div style={{ pointerEvents: visible ? 'auto' : 'none' }}>
<div role='presentation' className='modal-root__overlay' onClick={onClose} style={{ backgroundColor: backgroundColor ? `rgba(${backgroundColor.r}, ${backgroundColor.g}, ${backgroundColor.b}, 0.7)` : null }} />
<div role='dialog' className='modal-root__container'>{children}</div>
</div>
</div>
);
}
}
|
src/components/App.js | sjackson212/A6DotCom | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
const ContextType = {
// Enables critical path CSS rendering
// https://github.com/kriasoft/isomorphic-style-loader
insertCss: PropTypes.func.isRequired,
// Universal HTTP client
fetch: PropTypes.func.isRequired,
};
/**
* The top-level React component setting context (global) variables
* that can be accessed from all the child components.
*
* https://facebook.github.io/react/docs/context.html
*
* Usage example:
*
* const context = {
* history: createBrowserHistory(),
* store: createStore(),
* };
*
* ReactDOM.render(
* <App context={context}>
* <Layout>
* <LandingPage />
* </Layout>
* </App>,
* container,
* );
*/
class App extends React.PureComponent {
static propTypes = {
context: PropTypes.shape(ContextType).isRequired,
children: PropTypes.element.isRequired,
};
static childContextTypes = ContextType;
getChildContext() {
return this.props.context;
}
render() {
// NOTE: If you need to add or modify header, footer etc. of the app,
// please do that inside the Layout component.
return React.Children.only(this.props.children);
}
}
export default App;
|
src/index.js | mweststrate/mobservable-reactive2015-demo | import ReactDOM from 'react-dom';
import React from 'react';
import {observable, asReference} from 'mobx';
import {observer} from 'mobx-react';
import store from './stores/domain-state';
import Canvas from './components/canvas';
const storeInstance = observable(asReference(store));
let storeInstanceId = 0; // forces full re-render so that all components have the correct store
const HotReloadWrapper = observer(() =>
<Canvas store={storeInstance.get()} key={storeInstanceId} />
);
ReactDOM.render(
<HotReloadWrapper />,
document.getElementById('root')
);
/**
Replace the storeInstance if a new domain-state is available
*/
if (module.hot) {
// accept update of dependency
module.hot.accept("./stores/domain-state", function() {
// obtain new store
const newStore = require("./stores/domain-state").default;
// replace store instance
storeInstanceId++;
storeInstance.set(newStore);
});
}
|
1-react-basics/src/index.js | mariusz-malinowski/tutorial-react | import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(
<App />,
document.getElementById('root')
);
|
src/DatePicker.js | buildo/react-semantic-datepicker | import React from 'react';
import moment from 'moment';
import t from 'tcomb';
import { props } from 'tcomb-react';
import { format, valueLink, skinnable } from './utils';
import { Value, Mode } from './utils/model';
import DayPicker from './daypicker/DayPicker';
import MonthPicker from './monthpicker/MonthPicker';
import YearPicker from './yearpicker/YearPicker';
import cx from 'classnames';
@valueLink
@format
@skinnable()
@props({
onChange: t.maybe(t.Function),
value: t.maybe(Value),
valueLink: t.maybe(t.interface({
value: t.maybe(Value),
requestChange: t.Function
})),
defaultValue: t.maybe(Value),
minDate: t.maybe(Value),
maxDate: t.maybe(Value),
locale: t.maybe(t.String),
startMode: t.maybe(Mode),
startDate: t.maybe(Value),
fixedMode: t.maybe(t.Boolean),
returnFormat: t.maybe(t.String),
floating: t.maybe(t.Boolean),
closeOnClickOutside: t.maybe(t.Boolean), // used only with DatePickerInput
className: t.maybe(t.String),
prevIconClassName: t.maybe(t.String),
nextIconClassName: t.maybe(t.String),
position: t.maybe(t.enums.of(['top', 'bottom'])),
style: t.maybe(t.Object),
placeholder: t.maybe(t.String)
})
export default class DatePicker extends React.Component {
static defaultProps = {
startMode: 'day',
className: '',
prevIconClassName: 'icon-rc-datepicker icon-rc-datepicker_prev',
nextIconClassName: 'icon-rc-datepicker icon-rc-datepicker_next',
style: {},
position: 'bottom'
}
constructor(props) {
super(props);
if (props.locale) {
moment.locale(props.locale);
if (process.env.NODE_ENV !== 'production' && moment.locale() !== props.locale) {
console.warn(`Setting "${props.locale}" as locale failed. Did you import it correctly?`); // eslint-disable-line no-console
}
}
this.state = this.getStateFromProps(props);
}
getStateFromProps = (_props) => {
const { value } = this.getValueLink(_props);
const { defaultValue, startDate, startMode } = _props;
const date = typeof value === 'string' ? this.parsePropDateString(value) : moment(value);
const initialDate = defaultValue ?
typeof defaultValue === 'string' ? this.parsePropDateString(defaultValue) : moment(defaultValue) :
typeof startDate === 'string' ? this.parsePropDateString(startDate) : moment(startDate);
const visibleDate = value ? date.clone() : initialDate; // must be copy, otherwise they get linked
return {
date: value ? date.clone() : undefined,
visibleDate,
mode: startMode
};
}
onChangeVisibleDate = (date) => {
this.setState({ visibleDate: date });
}
onChangeSelectedDate = (date) => {
this.setState({
visibleDate: date.clone(), // must be copy, otherwise they get linked
date
}, () => this.getValueLink().requestChange(date.toDate()));
}
onChangeMode = (mode) => {
setTimeout(() => this.setState({ mode }));
}
changeYear = (year) => {
this.setState({ visibleDate: this.state.visibleDate.clone().year(year) });
}
changeMonth = (month) => {
this.setState({ visibleDate: this.state.visibleDate.clone().month(month) });
}
getLocals({ className, style, floating, minDate, maxDate, fixedMode, prevIconClassName, nextIconClassName, position }) {
const { mode, date, visibleDate } = this.state;
return {
style,
className: cx('react-datepicker', className, { floating, 'position-top': position === 'top' }),
dayPickerProps: mode === Mode('day') && {
date, visibleDate,
minDate, maxDate,
mode,
fixedMode,
prevIconClassName,
nextIconClassName,
changeMonth: this.changeMonth,
onSelectDate: this.onChangeSelectedDate,
onChangeMode: this.onChangeMode
},
monthPickerProps: mode === Mode('month') && {
date, visibleDate,
minDate, maxDate,
mode,
fixedMode,
prevIconClassName,
nextIconClassName,
changeYear: this.changeYear,
onSelectDate: this.onChangeSelectedDate,
onChangeMode: this.onChangeMode,
onChangeVisibleDate: this.onChangeVisibleDate
},
yearPickerProps: mode === Mode('year') && {
date, visibleDate,
minDate, maxDate,
mode,
fixedMode,
prevIconClassName,
nextIconClassName,
changeYear: this.changeYear,
onSelectDate: this.onChangeSelectedDate,
onChangeMode: this.onChangeMode,
onChangeVisibleDate: this.onChangeVisibleDate
}
};
}
template({ className, style, dayPickerProps, monthPickerProps, yearPickerProps }) {
return (
<div {...{ className, style }}>
{dayPickerProps && <DayPicker {...dayPickerProps} />}
{monthPickerProps && <MonthPicker {...monthPickerProps} />}
{yearPickerProps && <YearPicker {...yearPickerProps} />}
</div>
);
}
componentWillReceiveProps(nextProps) {
if (this.getValueLink(nextProps).value !== this.getValueLink().value) {
this.setState(this.getStateFromProps(nextProps));
}
}
}
|
src/components/Navigation/Navigation.js | onelink-translations/react-localization | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import { defineMessages, FormattedMessage } from 'react-intl';
import cx from 'classnames';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Navigation.css';
import Link from '../Link';
const messages = defineMessages({
about: {
id: 'navigation.about',
defaultMessage: 'About',
description: 'About link in header',
},
contact: {
id: 'navigation.contact',
defaultMessage: 'Contact',
description: 'Contact link in header',
},
login: {
id: 'navigation.login',
defaultMessage: 'Log in',
description: 'Log in link in header',
},
or: {
id: 'navigation.separator.or',
defaultMessage: 'or',
description: 'Last separator in list, lowercase "or"',
},
signup: {
id: 'navigation.signup',
defaultMessage: 'Sign up',
description: 'Sign up link in header',
},
});
class Navigation extends React.Component {
render() {
return (
<div className={s.root} role="navigation">
<Link className={s.link} to="/about">
<FormattedMessage {...messages.about} />
</Link>
<Link className={s.link} to="/contact">
<FormattedMessage {...messages.contact} />
</Link>
<span className={s.spacer}> | </span>
<Link className={s.link} to="/login">
<FormattedMessage {...messages.login} />
</Link>
<span className={s.spacer}>
<FormattedMessage {...messages.or} />
</span>
<Link className={cx(s.link, s.highlight)} to="/register">
<FormattedMessage {...messages.signup} />
</Link>
</div>
);
}
}
export default withStyles(s)(Navigation);
|
src/svg-icons/action/euro-symbol.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionEuroSymbol = (props) => (
<SvgIcon {...props}>
<path d="M15 18.5c-2.51 0-4.68-1.42-5.76-3.5H15v-2H8.58c-.05-.33-.08-.66-.08-1s.03-.67.08-1H15V9H9.24C10.32 6.92 12.5 5.5 15 5.5c1.61 0 3.09.59 4.23 1.57L21 5.3C19.41 3.87 17.3 3 15 3c-3.92 0-7.24 2.51-8.48 6H3v2h3.06c-.04.33-.06.66-.06 1 0 .34.02.67.06 1H3v2h3.52c1.24 3.49 4.56 6 8.48 6 2.31 0 4.41-.87 6-2.3l-1.78-1.77c-1.13.98-2.6 1.57-4.22 1.57z"/>
</SvgIcon>
);
ActionEuroSymbol = pure(ActionEuroSymbol);
ActionEuroSymbol.displayName = 'ActionEuroSymbol';
ActionEuroSymbol.muiName = 'SvgIcon';
export default ActionEuroSymbol;
|
src/views/NotFoundView/NotFoundView.js | Grobim/eggheadReduxTutorial | import React from 'react';
import { Link } from 'react-router';
export class NotFoundView extends React.Component {
render () {
return (
<div className='container text-center'>
<h1>This is a demo 404 page!</h1>
<hr />
<Link to='/'>Back To Home View</Link>
</div>
);
}
}
export default NotFoundView;
|
project/List11/lthree.js | DangrMiao/House | /**
* Sample React Native App
* https://github.com/facebook/react-native
*/
'use strict';
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
export default class lthree extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native 3!
</Text>
<Text style={styles.instructions}>
To get started, edit index.android.js
</Text>
<Text style={styles.instructions}>
Shake or press menu button for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
|
src/server/server-side-render.js | jukkah/comicstor | import React from 'react';
import { renderToString } from 'react-dom/server';
import { StaticRouter } from 'react-router-dom';
import { createStore } from 'redux'
import getMuiTheme from 'material-ui/styles/getMuiTheme'
import getStore from './store'
import Routes from '../client/Routes';
const assets = require(process.env.RAZZLE_ASSETS_MANIFEST);
export default () => {
return (req, res, next) => {
return serverSideRender(req, res, next).catch(e => {
if (!res.headersSent) res.status(500)
res.send('Server error')
console.error('[500]', e)
})
}
}
const serverSideRender = async (req, res, next) => {
const context = await getContext(req)
const content = render({ context, location: req.url })
if (context.url) {
res.redirect(301, context.url);
} else {
res.status(context.status || 200)
res.send(template({
body: content,
title: context.title,
state: context.store.getState().toJS()
}));
}
}
const getContext = async (req) => {
return {
title: 'Comicstor App',
store: await getClientStore(),
theme: getTheme(req),
}
}
const getClientStore = async () => {
const reducer = state => state
const serverStore = await getStore
return createStore(reducer, serverStore.getState())
}
const getTheme = (req) => {
return getMuiTheme({}, {
userAgent: req.headers['user-agent'],
})
}
const render = ({ context, location }) => {
return renderToString(
<StaticRouter location={location} context={context}>
<Routes store={context.store} muiTheme={context.theme} />
</StaticRouter>
)
}
const template = ({ title = '', body = '', state = {} }) => {
const styles = assets.client.css
? `<link rel="stylesheet" href="${assets.client.css}">`
: ''
return (`
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>${title}</title>
<meta httpEquiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet">
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet" integrity="sha384-wvfXpqpZZVQGK6TAh5PVlGOfQNHSoD2xbE+QkPxCAFlNEevoEH3Sl0sibVcOQVnN" crossorigin="anonymous">
${styles}
<script async src="${assets.client.js}"></script>
</head>
<body style="margin:0">
<div id="root">${body}</div>
<script>
// WARNING: See the following for security issues around embedding JSON in HTML:
// http://redux.js.org/docs/recipes/ServerRendering.html#security-considerations
window.__PRELOADED_STATE__ = ${JSON.stringify(state).replace(/</g, '\\u003c')};
</script>
</body>
</html>
`);
}
|
src/svg-icons/action/settings-input-svideo.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionSettingsInputSvideo = (props) => (
<SvgIcon {...props}>
<path d="M8 11.5c0-.83-.67-1.5-1.5-1.5S5 10.67 5 11.5 5.67 13 6.5 13 8 12.33 8 11.5zm7-5c0-.83-.67-1.5-1.5-1.5h-3C9.67 5 9 5.67 9 6.5S9.67 8 10.5 8h3c.83 0 1.5-.67 1.5-1.5zM8.5 15c-.83 0-1.5.67-1.5 1.5S7.67 18 8.5 18s1.5-.67 1.5-1.5S9.33 15 8.5 15zM12 1C5.93 1 1 5.93 1 12s4.93 11 11 11 11-4.93 11-11S18.07 1 12 1zm0 20c-4.96 0-9-4.04-9-9s4.04-9 9-9 9 4.04 9 9-4.04 9-9 9zm5.5-11c-.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.5zm-2 5c-.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.5z"/>
</SvgIcon>
);
ActionSettingsInputSvideo = pure(ActionSettingsInputSvideo);
ActionSettingsInputSvideo.displayName = 'ActionSettingsInputSvideo';
ActionSettingsInputSvideo.muiName = 'SvgIcon';
export default ActionSettingsInputSvideo;
|
docs/src/app/components/pages/components/GridList/Page.js | barakmitz/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import gridListReadmeText from './README';
import gridListExampleSimpleCode from '!raw!./ExampleSimple';
import GridListExampleSimple from './ExampleSimple';
import gridListExampleComplexCode from '!raw!./ExampleComplex';
import GridListExampleComplex from './ExampleComplex';
import gridListCode from '!raw!material-ui/GridList/GridList';
import gridTileCode from '!raw!material-ui/GridList/GridTile';
const descriptions = {
simple: 'A simple example of a scrollable `GridList` containing a [Subheader](/#/components/subheader).',
complex: 'This example demonstrates "featured" tiles, using the `rows` and `cols` props to adjust the size of the ' +
'tile. The tiles have a customised title, positioned at the top and with a custom gradient `titleBackground`.',
};
const GridListPage = () => (
<div>
<Title render={(previousTitle) => `Grid List - ${previousTitle}`} />
<MarkdownElement text={gridListReadmeText} />
<CodeExample
title="Simple example"
description={descriptions.simple}
code={gridListExampleSimpleCode}
>
<GridListExampleSimple />
</CodeExample>
<CodeExample
title="Complex example"
description={descriptions.complex}
code={gridListExampleComplexCode}
>
<GridListExampleComplex />
</CodeExample>
<PropTypeDescription header="### GridList Properties" code={gridListCode} />
<PropTypeDescription header="### GridTile Properties" code={gridTileCode} />
</div>
);
export default GridListPage;
|
app/jsx/theme_editor/RangeInput.js | venturehive/canvas-lms | /*
* Copyright (C) 2015 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import $ from 'jquery'
var RangeInput = React.createClass({
propTypes: {
min: PropTypes.number.isRequired,
max: PropTypes.number.isRequired,
defaultValue: PropTypes.number.isRequired,
labelText: PropTypes.string.isRequired,
name: PropTypes.string.isRequired,
step: PropTypes.number,
formatValue: PropTypes.func,
onChange: PropTypes.func
},
getDefaultProps: function() {
return {
step: 1,
onChange: function(){},
formatValue: val => val
};
},
getInitialState: function() {
return { value: this.props.defaultValue };
},
/* workaround for https://github.com/facebook/react/issues/554 */
componentDidMount: function() {
// https://connect.microsoft.com/IE/Feedback/Details/856998
$(this.refs.rangeInput.getDOMNode()).on('input change', this.handleChange);
},
componentWillUnmount: function() {
$(this.refs.rangeInput.getDOMNode()).off('input change', this.handleChange);
},
/* end workaround */
handleChange: function(event) {
this.setState({ value: event.target.value });
this.props.onChange(event.target.value);
},
render: function() {
var {
labelText,
formatValue,
onChange,
value,
...props
} = this.props;
return (
<label className="RangeInput">
<div className="RangeInput__label">
{labelText}
</div>
<div className="RangeInput__control">
<input className="RangeInput__input"
ref="rangeInput"
type="range"
role="slider"
aria-valuenow={this.props.defaultValue}
aria-valuemin={this.props.min}
aria-valuemax={this.props.max}
aria-valuetext={formatValue(this.state.value)}
onChange={function() {}}
{...props} />
<output htmlFor={this.props.name} className="RangeInput__value">
{ formatValue(this.state.value) }
</output>
</div>
</label>
);
}
});
export default RangeInput
|
src/appReact/components/Map/LeftNav.js | devmessias/brasillivre | import React from 'react';
import ChainBroken from 'react-icons/lib/fa/chain-broken';
import Marker from 'react-icons/lib/fa/map-marker';
import Fire from 'react-icons/lib/fa/fire';
import Edit from 'react-icons/lib/md/edit';
import {Action} from './../../actions/Action.js';
class LeftNav extends React.Component {
_toogleHeatMap(){Action('ToogleHeatMap','Map')};
_toogleMarkers(){Action('ToogleMarkers','Map')};
_openConfig(){Action('OpenModal','Config')};
render(){
return (
<section className='leftNav'>
<div
onClick={this._openConfig}
className='btnCircle red relative'>
<Edit
className='centrar'/>
</div>
<div
onClick={this._toogleMarkers}
className='btnCircle white'>
<Marker
className='centrar'/>
</div>
<div
onClick={this._toogleHeatMap}
className='btnCircle red relative'>
<Fire
className='centrar'/>
</div>
</section>
);
}
}
export default LeftNav;
|
src/js/components/Users.js | bryanjacquot/theme-designer-capstone | import React, { Component } from 'react';
import Section from 'grommet/components/Section';
import Anchor from 'grommet/components/Anchor';
import Meter from 'grommet/components/Meter';
import Pdf from 'grommet/components/icons/base/DocumentPdf';
export default class Users extends Component {
constructor() {
super();
}
render () {
return (
<Section>
<a name="users" />
<h2>Users</h2>
<p>
The <b>primary stakeholders</b> of the Grommet Theme Designer are
designers who create themes for websites and applications. For
the scope of this project, this user group will be further subdivided
into designers who use the OS X operating system and the Sketch
design tool. My initial survey indicated 60% of the primary
stakeholders use OS X as their primary operating system as
shown in Figure 1.
</p>
<figure>
<Meter important={0} series={[
{"label": "OS X", "value": 60, "colorIndex": "graph-1"},
{"label": "Windows", "value": 20, "colorIndex": "graph-2"},
{"label": "iOS", "value": 20, "colorIndex": "graph-3"}
]} stacked={true} units="%" type="circle" legend={true}/>
<figcaption>Figure 1. Primary operating system used by designers (n=5).</figcaption>
</figure>
<p>
Primary stakeholders will generally have formal training in graphic
design, web development, or related field. Those surveyed described
their occupation as either “Software and web development” or “Arts,
design, and user experience” as shown in Figure 2.
</p>
<figure>
<Meter important={0} series={[
{"label": "Arts, design, and user experience", "value": 60, "colorIndex": "graph-1"},
{"label": "Software and web development", "value": 40, "colorIndex": "graph-2"}
]} stacked={true} units="%" type="circle" legend={true}/>
<figcaption>Figure 2. Occupations of primary stakeholders (n=5).</figcaption>
</figure>
<p>
The <b>secondary stakeholders</b> of this system are website and
application developers who receive the theme output by the system.
</p>
<p>
There are two groups of <b>tertiary stakeholders</b> of this system who
have no direct involvement with the project but will be affected by its
outcome. The first are employers who have designers on staff who create
custom themes as part of their job responsibilities. The second group of
tertiary stakeholders is the users of websites and applications designed
with the theme designer.
</p>
<h3>User Needs</h3>
<p>
There were four key unmet user needs I uncovered in my research. First, of
the designers I interviewed, <i>none</i> of them had taken accessibility standards
into account when designing themes. “I didn’t start doing accessibility
stuff until started working here [Hewlett Packard Enterprise]” (PS3, 2016).
</p>
<p>
The second unmet user need I uncovered was the lack of tooling and control for
element styling. There is a strong tendency for designers to defer element
styling to developers. PS2 described the, “major influence [on element styling]
is from technology. In fact, 80-90% of element styling is driven by
technology stack used by developers.” PS1 described element styling as,
“Chaotic and hap-hazard; we couldn’t keep up with what dev was doing”
(PS1, 2016).
</p>
<p>
Third, the significance of the review task emerged from my research. This
task is critical because it enables collaboration and feedback from
stakeholders and supports iterative design and refinement. I uncovered
designers often spend significant time applying colors, fonts, and element
designs in full pages so they can see their designs in context. However,
the manual nature of this task limits the designer’s ability to quickly
explore variations of the theme.
</p>
<p>
Fourth, there is a user need to improve the handoff between the designer and
developer. The handoff involves delivery of assets in a format familiar
to designers such as Adobe Photoshop or Illustrator, or Sketch. However,
this format is not directly usable by developers; it requires analysis
and interpretation which is time consuming and lacks precision. Even
using a platform such as Axure which provides interactive HTML prototypes
requires interpretation by developers because HTML, CSS, and JavaScript
in Axure is not designed to be used by developers beyond the visual and
interaction design.
</p>
<Anchor icon={<Pdf/>} href="https://github.com/bryanjacquot/theme-designer-capstone/raw/master/docs/M2-JacquotBryan.pdf" label="User Needs Document" primary={true} />
<Anchor icon={<Pdf/>} href="https://github.com/bryanjacquot/theme-designer-capstone/raw/master/docs/M2-JacquotBryan-SurveyRawData.pdf" label="User Survey Raw Data" primary={true} />
</Section>
);
}
};
|
client/react/panel/inputs/ConfirmationButton.js | uclaradio/uclaradio | // UserEditableDateTimeField.js
import React from 'react';
import { Button, ButtonGroup } from 'react-bootstrap';
/**
* Allows user to confirm a button submission
*
* @prop confirm: text to display on button when confirming
* @prop submit: text to display on button when submitting
* @prop onSubmit -> function(): parent's function to call when submitting
*/
const ConfirmationButton = React.createClass({
getInitialState() {
return { unlock: false };
},
toggleUnlock() {
this.setState({ unlock: !this.state.unlock });
},
render() {
return (
<div className="confirmationButton centered">
{this.state.unlock ? (
<ButtonGroup>
<Button className="delete" onClick={this.props.onSubmit}>
{this.props.submit}
</Button>
<Button onClick={this.toggleUnlock}>Cancel</Button>
</ButtonGroup>
) : (
<Button className="delete" onClick={this.toggleUnlock}>
{this.props.confirm}
</Button>
)}
</div>
);
},
});
export default ConfirmationButton;
|
src/routes/study/ballots/index.js | Skoli-Code/DerangeonsLaChambre | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Ballots from './Ballots';
import fetch from '../../../core/fetch';
import history from '../../../core/history';
const routeParams = {
key: 1,
title: 'Scrutins'
};
const render = async(index) => {
const resp = await fetch('/graphql', {
method: 'post',
headers: {
Accept: 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify({
query: `{ballots{
list{
id,order,title,subtitle,legend_title,content,
meta{
... on TwitterMeta{name,content}
... on FacebookMeta{property,content}
}
results{party{id,order,name,color},seats}},
parties{id,order,name,color}
}}`
})
});
if (resp.status !== 200) {
throw new Error(resp.statusText);
}
const {data} = await resp.json();
if (!data){
return undefined;
}
const ballots = data.ballots;
if(ballots && !index){
index = 0;
// history.push('/etude/scrutins/0')
}
const ballot = ballots.list[index];
const onBallotChange = (i)=>{
const path = '/etude/scrutins/'+i;
history.push(path);
};
return Object.assign({}, routeParams, {
componentProps: {
onBallotChange: onBallotChange,
ballots: ballots.list,
parties: ballots.parties,
activeBallot: index
},
component: Ballots,
meta: ballot.meta
});
};
export default {
path : '/scrutins',
async action(context) {
if(context){
return context.next();
} else {
return render();
}
},
children : [
{
path: '/',
async action(){
return render();
}
}, {
path: '/:index',
async action(context) {
return render(+context.params.index);
}
}
]
};
|
frontend/src/Wanted/CutoffUnmet/CutoffUnmet.js | lidarr/Lidarr | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import LoadingIndicator from 'Components/Loading/LoadingIndicator';
import FilterMenu from 'Components/Menu/FilterMenu';
import ConfirmModal from 'Components/Modal/ConfirmModal';
import PageContent from 'Components/Page/PageContent';
import PageContentBody from 'Components/Page/PageContentBody';
import PageToolbar from 'Components/Page/Toolbar/PageToolbar';
import PageToolbarButton from 'Components/Page/Toolbar/PageToolbarButton';
import PageToolbarSection from 'Components/Page/Toolbar/PageToolbarSection';
import PageToolbarSeparator from 'Components/Page/Toolbar/PageToolbarSeparator';
import Table from 'Components/Table/Table';
import TableBody from 'Components/Table/TableBody';
import TablePager from 'Components/Table/TablePager';
import { align, icons, kinds } from 'Helpers/Props';
import getFilterValue from 'Utilities/Filter/getFilterValue';
import hasDifferentItems from 'Utilities/Object/hasDifferentItems';
import getSelectedIds from 'Utilities/Table/getSelectedIds';
import removeOldSelectedState from 'Utilities/Table/removeOldSelectedState';
import selectAll from 'Utilities/Table/selectAll';
import toggleSelected from 'Utilities/Table/toggleSelected';
import CutoffUnmetRowConnector from './CutoffUnmetRowConnector';
function getMonitoredValue(props) {
const {
filters,
selectedFilterKey
} = props;
return getFilterValue(filters, selectedFilterKey, 'monitored', false);
}
class CutoffUnmet extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this.state = {
allSelected: false,
allUnselected: false,
lastToggled: null,
selectedState: {},
isConfirmSearchAllCutoffUnmetModalOpen: false,
isInteractiveImportModalOpen: false
};
}
componentDidUpdate(prevProps) {
if (hasDifferentItems(prevProps.items, this.props.items)) {
this.setState((state) => {
return removeOldSelectedState(state, prevProps.items);
});
}
}
//
// Control
getSelectedIds = () => {
return getSelectedIds(this.state.selectedState);
}
//
// Listeners
onSelectAllChange = ({ value }) => {
this.setState(selectAll(this.state.selectedState, value));
}
onSelectedChange = ({ id, value, shiftKey = false }) => {
this.setState((state) => {
return toggleSelected(state, this.props.items, id, value, shiftKey);
});
}
onSearchSelectedPress = () => {
const selected = this.getSelectedIds();
this.props.onSearchSelectedPress(selected);
}
onToggleSelectedPress = () => {
const albumIds = this.getSelectedIds();
this.props.batchToggleCutoffUnmetAlbums({
albumIds,
monitored: !getMonitoredValue(this.props)
});
}
onSearchAllCutoffUnmetPress = () => {
this.setState({ isConfirmSearchAllCutoffUnmetModalOpen: true });
}
onSearchAllCutoffUnmetConfirmed = () => {
this.props.onSearchAllCutoffUnmetPress();
this.setState({ isConfirmSearchAllCutoffUnmetModalOpen: false });
}
onConfirmSearchAllCutoffUnmetModalClose = () => {
this.setState({ isConfirmSearchAllCutoffUnmetModalOpen: false });
}
//
// Render
render() {
const {
isFetching,
isPopulated,
error,
items,
isArtistFetching,
isArtistPopulated,
selectedFilterKey,
filters,
columns,
totalRecords,
isSearchingForCutoffUnmetAlbums,
isSaving,
onFilterSelect,
...otherProps
} = this.props;
const {
allSelected,
allUnselected,
selectedState,
isConfirmSearchAllCutoffUnmetModalOpen
} = this.state;
const isAllPopulated = isPopulated && isArtistPopulated;
const isAnyFetching = isFetching || isArtistFetching;
const itemsSelected = !!this.getSelectedIds().length;
const isShowingMonitored = getMonitoredValue(this.props);
return (
<PageContent title="Cutoff Unmet">
<PageToolbar>
<PageToolbarSection>
<PageToolbarButton
label="Search Selected"
iconName={icons.SEARCH}
isDisabled={!itemsSelected || isSearchingForCutoffUnmetAlbums}
onPress={this.onSearchSelectedPress}
/>
<PageToolbarButton
label={isShowingMonitored ? 'Unmonitor Selected' : 'Monitor Selected'}
iconName={isShowingMonitored ? icons.UNMONITORED : icons.MONITORED}
isDisabled={!itemsSelected}
isSpinning={isSaving}
onPress={this.onToggleSelectedPress}
/>
<PageToolbarSeparator />
<PageToolbarButton
label="Search All"
iconName={icons.SEARCH}
isDisabled={!items.length}
isSpinning={isSearchingForCutoffUnmetAlbums}
onPress={this.onSearchAllCutoffUnmetPress}
/>
<PageToolbarSeparator />
</PageToolbarSection>
<PageToolbarSection alignContent={align.RIGHT}>
<FilterMenu
alignMenu={align.RIGHT}
selectedFilterKey={selectedFilterKey}
filters={filters}
customFilters={[]}
onFilterSelect={onFilterSelect}
/>
</PageToolbarSection>
</PageToolbar>
<PageContentBody>
{
isAnyFetching && !isAllPopulated &&
<LoadingIndicator />
}
{
!isAnyFetching && error &&
<div>
Error fetching cutoff unmet
</div>
}
{
isAllPopulated && !error && !items.length &&
<div>
No cutoff unmet items
</div>
}
{
isAllPopulated && !error && !!items.length &&
<div>
<Table
columns={columns}
selectAll={true}
allSelected={allSelected}
allUnselected={allUnselected}
{...otherProps}
onSelectAllChange={this.onSelectAllChange}
>
<TableBody>
{
items.map((item) => {
return (
<CutoffUnmetRowConnector
key={item.id}
isSelected={selectedState[item.id]}
columns={columns}
{...item}
onSelectedChange={this.onSelectedChange}
/>
);
})
}
</TableBody>
</Table>
<TablePager
totalRecords={totalRecords}
isFetching={isFetching}
{...otherProps}
/>
<ConfirmModal
isOpen={isConfirmSearchAllCutoffUnmetModalOpen}
kind={kinds.DANGER}
title="Search for all Cutoff Unmet albums"
message={
<div>
<div>
Are you sure you want to search for all {totalRecords} Cutoff Unmet albums?
</div>
<div>
This cannot be cancelled once started without restarting Lidarr.
</div>
</div>
}
confirmLabel="Search"
onConfirm={this.onSearchAllCutoffUnmetConfirmed}
onCancel={this.onConfirmSearchAllCutoffUnmetModalClose}
/>
</div>
}
</PageContentBody>
</PageContent>
);
}
}
CutoffUnmet.propTypes = {
isFetching: PropTypes.bool.isRequired,
isPopulated: PropTypes.bool.isRequired,
error: PropTypes.object,
items: PropTypes.arrayOf(PropTypes.object).isRequired,
isArtistFetching: PropTypes.bool.isRequired,
isArtistPopulated: PropTypes.bool.isRequired,
selectedFilterKey: PropTypes.string.isRequired,
filters: PropTypes.arrayOf(PropTypes.object).isRequired,
columns: PropTypes.arrayOf(PropTypes.object).isRequired,
totalRecords: PropTypes.number,
isSearchingForCutoffUnmetAlbums: PropTypes.bool.isRequired,
isSaving: PropTypes.bool.isRequired,
onFilterSelect: PropTypes.func.isRequired,
onSearchSelectedPress: PropTypes.func.isRequired,
batchToggleCutoffUnmetAlbums: PropTypes.func.isRequired,
onSearchAllCutoffUnmetPress: PropTypes.func.isRequired
};
export default CutoffUnmet;
|
react/LanguageIcon/LanguageIcon.iconSketch.js | seekinternational/seek-asia-style-guide | import React from 'react';
import LanguageIcon from './LanguageIcon';
export const symbols = {
'LanguageIcon': <LanguageIcon />
};
|
public/src/js/components/buckets/comp-bucketCreation.js | asarode/learn-buckets | import React from 'react';
import LinkInput from './comp-linkInput';
import BucketActions from '../../actions/actions-buckets';
import { Navigation } from 'react-router';
class BucketCreation extends React.Component {
constructor(props) {
super(props);
this.state = {
title: '',
description: '',
links: [{
title: '',
url: '',
type: 'article'
}]
};
}
render() {
return (
<div className="row">
<div className="col-xs-12">
<button className="lb-button-minor" onClick={() => this.context.router.transitionTo('/buckets')}>← Back</button>
</div>
<form className="col-xs-12 lb-form">
<input type="text" placehoder="Title" onChange={() => this.handleTitleChange()}/>
<input type="text" placeholder="Description" onChange={() => this.handleDescriptionChange()}/>
{this.LinkInputs()}
<button className="lb-button-minor" onClick={() => this.addLinkSpot()}>+ New link</button>
<button type="submit" onClick={() => this.handleSubmit()}>Create Bucket</button>
</form>
</div>
);
}
addLinkSpot() {
this.state.links.push({
title: '',
url: '',
type: 'article'
});
this.setState({
links: this.state.links
});
console.log("Added: ", this.state.links);
}
removeLinkSpot(e) {
console.log(e.target);
}
LinkInputs() {
let linkInputs = this.state.links.map((link, index) => {
return (
<LinkInput
key={index}
index={index}
onTitleChange={() => this.handleLinkTitleChange(index)}
onUrlChange={() => this.handleLinkUrlChange(index)}
onTypeChange={() => this.handleTypeChange(index)}
onRemoveClick={() => this.handleLinkRemove(index)} />
);
});
return linkInputs;
}
handleTitleChange() {
this.state.title = event.target.value
this.setState({
title: this.state.title
});
}
handleDescriptionChange() {
this.state.description = event.target.value
this.setState({
description: this.state.description
});
}
handleLinkTitleChange(index) {
this.state.links[index].title = event.target.value
this.setState({
links: this.state.links
});
}
handleLinkUrlChange(index) {
this.state.links[index].url = event.target.value
this.setState({
links: this.state.links
});
}
handleTypeChange(index) {
this.state.links[index].type = event.target.value
this.setState({
links: this.state.links
});
}
handleLinkRemove(index) {
this.state.links.splice(index, 1);
this.setState({
links: this.state.links
});
}
handleSubmit() {
BucketActions.addBucket(this.state);
this.context.router.transitionTo('/buckets');
}
}
BucketCreation.PropTypes = {
className: React.PropTypes.object
};
BucketCreation.defaultProps = {
className: {}
};
BucketCreation.contextTypes = {
router: React.PropTypes.func.isRequired
}
export default BucketCreation;
|
examples/with-flow/pages/contact.js | BlancheXu/test | // @flow
import React from 'react'
import Page from '../components/Page'
export default () => (
<Page title='Contact us'>
<div>Contact</div>
</Page>
)
|
src/svg-icons/image/filter-none.js | kasra-co/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilterNone = (props) => (
<SvgIcon {...props}>
<path d="M3 5H1v16c0 1.1.9 2 2 2h16v-2H3V5zm18-4H7c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V3c0-1.1-.9-2-2-2zm0 16H7V3h14v14z"/>
</SvgIcon>
);
ImageFilterNone = pure(ImageFilterNone);
ImageFilterNone.displayName = 'ImageFilterNone';
ImageFilterNone.muiName = 'SvgIcon';
export default ImageFilterNone;
|
src/svg-icons/communication/chat-bubble-outline.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationChatBubbleOutline = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-2 .9-2 2v18l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm0 14H6l-2 2V4h16v12z"/>
</SvgIcon>
);
CommunicationChatBubbleOutline = pure(CommunicationChatBubbleOutline);
CommunicationChatBubbleOutline.displayName = 'CommunicationChatBubbleOutline';
CommunicationChatBubbleOutline.muiName = 'SvgIcon';
export default CommunicationChatBubbleOutline;
|
lib/Components/DailyCard/DailyCard.js | francylang/weathrly | import React from 'react';
import './DailyCard.css';
const DailyCard = props => {
return (
<div className="card" key={props.tenDayKey}>
<h2 className="day">{props.dayTime}</h2>
<i className={`wi wi-wu-${props.dayIcon} dailyWeatherIcons`}></i>
<h2 className="dayCondition">{props.dayCondition}</h2>
<h2 className="dayHigh" >{props.dayTempHigh}<span className="deg">°</span>
/ {props.dayTempLow}
<span className="deg">°</span>
</h2>
</div>
);
};
export default DailyCard;
|
src/components/FooterBar/GuestFooterContent.js | u-wave/web | import React from 'react';
import { useDispatch } from 'react-redux';
import { useTranslator } from '@u-wave/react-translate';
import Button from '@mui/material/Button';
import { openLoginDialog, openRegisterDialog } from '../../actions/DialogActionCreators';
import { toggleSettings } from '../../actions/OverlayActionCreators';
import SettingsButton from './SettingsButton';
const {
useCallback,
} = React;
function GuestFooterContent() {
const { t } = useTranslator();
const dispatch = useDispatch();
const handleToggleSettings = useCallback(() => {
dispatch(toggleSettings());
}, [dispatch]);
const handleOpenLoginDialog = useCallback(() => {
dispatch(openLoginDialog());
}, [dispatch]);
const handleOpenRegisterDialog = useCallback(() => {
dispatch(openRegisterDialog());
}, [dispatch]);
return (
<>
<SettingsButton onClick={handleToggleSettings} />
<div className="FooterBar-guest">
{t('login.message')}
</div>
<Button
variant="contained"
color="primary"
className="FooterAuthButton FooterAuthButton--login"
onClick={handleOpenLoginDialog}
>
{t('login.login')}
</Button>
<Button
variant="contained"
color="primary"
className="FooterAuthButton FooterAuthButton--register"
onClick={handleOpenRegisterDialog}
>
{t('login.register')}
</Button>
</>
);
}
export default GuestFooterContent;
|
MobileApp/MessageHub/components/searchViews/SearchItem.js | FresnoState/mobilestudentintranet | import React, { Component } from 'react';
import {
View,
Text,
Dimensions
} from 'react-native';
import {Icon} from 'native-base';
const { width, height } = Dimensions.get('window');
export default class SearchItem extends Component {
constructor(props) {
super(props);
}
render() {
return (
<View style={{padding: 10, paddingLeft: 20, paddingRight: 20, flexDirection: 'row', borderTopWidth: 0.5, borderColor: '#8b8b90'}}>
<Text style={[styles.itemText, {paddingLeft: 10}]}>{this.props.term}</Text>
</View>
);
}
} |
app/Resources/static-src/app/common/component/multi-input/input-group.js | richtermark/SMEAGOnline | import React, { Component } from 'react';
import { trim } from '../../unit';
import { send } from '../../server';
import Options from './options';
import postal from 'postal';
export default class InputGroup extends Component {
constructor(props) {
super(props);
this.state = {
itemName: "",
searched: true,
resultful: false,
searchResult: [],
}
this.subscribeMessage();
}
subscribeMessage() {
postal.subscribe({
channel: "courseInfoMultiInput",
topic: "addMultiInput",
callback: () => {
console.log('add');
this.handleAdd();
}
});
}
selectChange(name, data) {
if (data) {
this.context.addItem(name, data);
}
this.setState({
itemName: '',
});
}
onFocus(event) {
//在这种情况下,重新开启搜索功能;
this.setState({
searched: true,
})
}
handleNameChange(event) {
// let value = trim(event.currentTarget.value);
let value = event.currentTarget.value;
this.setState({
itemName: value,
searchResult: [],
resultful: false,
});
if (!this.context.searchable.enable || value.length < 0 || !this.state.searched) {
return;
}
setTimeout(() => {
send(this.context.searchable.url + value, searchResult => {
if (this.state.itemName.length > 0) {
console.log({ 'searchResult': searchResult });
this.setState({
searchResult: searchResult,
resultful: true,
});
}
});
}, 100)
}
handleAdd() {
if (trim(this.state.itemName).length > 0) {
this.context.addItem(this.state.itemName, this.state.itemData);
}
this.setState({
itemName: '',
searchResult: [],
resultful: false,
})
}
render() {
return (
<div className="input-group">
<input className="form-control" value={this.state.itemName} onChange={event => this.handleNameChange(event)} onFocus={event => this.onFocus(event)} />
{this.context.searchable.enable && this.state.resultful && <Options searchResult={this.state.searchResult} selectChange={(event, name) => this.selectChange(event, name)} resultful={this.state.resultful} />}
{this.context.addable && <span className="input-group-btn"><a className="btn btn-default" onClick={() => this.handleAdd()}>添加</a></span>}
</div>
);
}
}
InputGroup.contextTypes = {
addItem: React.PropTypes.func,
addable: React.PropTypes.bool,
searchable: React.PropTypes.shape({
enable: React.PropTypes.bool,
url: React.PropTypes.string,
}),
};
|
src/header/Header.js | ericyd/surfplot-ui | 'use strict';
import React from 'react';
import Nav from './Nav';
import './Header.scss';
export default function Header (props) {
return (
<header className='header'>
<img src='img/open_surface.svg' className='header__logo' alt='Surf Plot JS logo' />
<Nav />
</header>
);
}
|
src/components/Forms/GameSearch.js | Franco84/pubstomp | import React, { Component } from 'react';
import {Field, reduxForm} from 'redux-form'
import {Button} from 'react-bootstrap'
class GameSearch extends Component {
renderField(field) {
const { meta: {touched, error} } = field
const className = `form-group ${touched && error ? 'has-danger' : ''}`
return (
<div className={className}>
<input
className="form-control"
placeholder={field.placeholder}
type={field.type}
{...field.input}
/>
</div>
)
}
onSubmit(value) {
this.props.changeQuery(value.game_search)
}
render() {
const {handleSubmit, pristine, submitting} = this.props
return (
<form>
<Field
placeholder=" Search for games.."
name="game_search"
type="text"
component={this.renderField}
/>
<div className="flex-div">
<Button className="margin-button" onClick={handleSubmit(this.onSubmit.bind(this))} disabled={pristine || submitting} type="submit" bsStyle="primary" bsSize="small">Submit</Button>
</div>
</form>
);
}
}
export default reduxForm({
form: 'GameSearch'
})(GameSearch)
|
src/Navbar/Navbar.js | kashjs/muszoo-react | import React from 'react';
import PropTypes from 'prop-types';
import {TapAnimationContent} from '../TapAnimation/TapAnimation';
export class MZNavbar extends React.Component {
render() {
let className = 'mz-navbar ' + this.props.className;
return <nav className={className}>{this.props.children}</nav>
}
}
MZNavbar.propTypes = {
className: PropTypes.string
};
MZNavbar.defaultProps = {
className: ''
};
export class MZNavbarGroup extends React.Component {
render() {
let className = 'mz-navbar-group ' + this.props.className;
return <div className={className}>{this.props.children}</div>
}
}
MZNavbarGroup.propTypes = {
className: PropTypes.string
};
MZNavbarGroup.defaultProps = {
className: ''
};
export class MZNavbarBrand extends React.Component {
render() {
let className = 'mz-navbar-brand ' + this.props.className;
return <div className={className}>{this.props.children}</div>
}
}
MZNavbarBrand.propTypes = {
className: PropTypes.string
};
MZNavbarBrand.defaultProps = {
className: ''
};
export class MZNavbarItem extends React.Component {
render() {
let className = 'mz-navbar-item ' + this.props.className;
return <div onClick={this.props.onClick} className={className}>
<TapAnimationContent>
<a type="button" href={this.props.href}>{this.props.children}</a>
</TapAnimationContent>
</div>
}
}
MZNavbarItem.propTypes = {
className: PropTypes.string,
href: PropTypes.string
};
MZNavbarItem.defaultProps = {
className: ''
}; |
src/decorators/withViewport.js | HereIsJohnny/issuetracker | /*! 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;
|
assets/jqwidgets/demos/react/app/complexinput/exponentialnotation/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxComplexInput from '../../../jqwidgets-react/react_jqxcomplexinput.js';
import JqxExpander from '../../../jqwidgets-react/react_jqxexpander.js';
import JqxButton from '../../../jqwidgets-react/react_jqxbuttons.js';
import JqxDropDownList from '../../../jqwidgets-react/react_jqxdropdownlist.js';
class App extends React.Component {
componentDidMount() {
this.refs.notationsList.on('change', (event) => {
let args = event.args;
if (args) {
let label = args.item.label;
if (label === 'decimal') {
label = 'default';
}
this.refs.myComplexInput.decimalNotation(label);
}
});
this.refs.getRealDecimal.on('click', () => {
let decimalValue = this.refs.myComplexInput.getReal();
alert('Decimal value: ' + decimalValue);
});
this.refs.getRealExponential.on('click', () => {
let exponentialValue = this.refs.myComplexInput.getDecimalNotation('real', 'exponential');
alert('Exponential notation: ' + exponentialValue);
});
this.refs.getRealScientific.on('click', () => {
let scientificValue = this.refs.myComplexInput.getDecimalNotation('real', 'scientific');
alert('Scientific notation: ' + scientificValue);
});
this.refs.getRealEngineering.on('click', () => {
let engineeringValue = this.refs.myComplexInput.getDecimalNotation('real', 'engineering');
alert('Engineering notation: ' + engineeringValue);
});
this.refs.getImaginaryDecimal.on('click', () => {
let decimalValue = this.refs.myComplexInput.getImaginary();
alert('Decimal value: ' + decimalValue);
});
this.refs.getImaginaryExponential.on('click', () => {
let exponentialValue = this.refs.myComplexInput.getDecimalNotation('imaginary', 'exponential');
alert('Exponential notation: ' + exponentialValue);
});
this.refs.getImaginaryScientific.on('click', () => {
let scientificValue = this.refs.myComplexInput.getDecimalNotation('imaginary', 'scientific');
alert('Scientific notation: ' + scientificValue);
});
this.refs.getImaginaryEngineering.on('click', () => {
let engineeringValue = this.refs.myComplexInput.getDecimalNotation('imaginary', 'engineering');
alert('Engineering notation: ' + engineeringValue);
});
}
render() {
let source = ['decimal', 'exponential', 'scientific', 'engineering'];
return (
<div>
<JqxComplexInput ref='myComplexInput' style={{ float: 'left' }}
width={250} height={25} value={'330000 - 200i'}
spinButtons={true} decimalNotation={'exponential'}
/>
<JqxExpander style={{ float: 'left', marginLeft: 50 }}
width={400} height={400} toggleMode={'none'} showArrow={false}
>
<div>jqxComplexInput Notation Settings</div>
<div style={{ paddingLeft: 15 }}>
<h4>Choose notation:</h4>
<JqxDropDownList ref='notationsList' style={{ marginTop: 20 }}
width={200} height={25} autoDropDownHeight={true}
source={source} selectedIndex={1}
/>
<div style={{ marginTop: 20 }}>
<h4>Real part</h4>
<JqxButton ref='getRealDecimal' style={{ display: 'inline-block' }}
value='Get decimal value' width={175}
/>
<JqxButton ref='getRealExponential' style={{ marginLeft: 5, display: 'inline-block' }}
value='Get exponential notation' width={175}
/>
<br /><br />
<JqxButton ref='getRealScientific' style={{ display: 'inline-block' }}
value='Get scientific notation' width={175}
/>
<JqxButton ref='getRealEngineering' style={{ marginLeft: 5, display: 'inline-block' }}
value='Get engineering notation' width={175}
/>
</div>
<div style={{ marginTop: 20 }}>
<h4>Imaginary part</h4>
<JqxButton ref='getImaginaryDecimal' style={{ display: 'inline-block' }}
value='Get decimal value' width={175}
/>
<JqxButton ref='getImaginaryExponential' style={{ marginLeft: 5, display: 'inline-block' }}
value='Get exponential notation' width={175}
/>
<br /><br />
<JqxButton ref='getImaginaryScientific' style={{ display: 'inline-block' }}
value='Get scientific notation' width={175}
/>
<JqxButton ref='getImaginaryEngineering' style={{ marginLeft: 5, display: 'inline-block' }}
value='Get engineering notation' width={175}
/>
</div>
</div>
</JqxExpander>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
app/components/landing/RatesXL/index.js | vkurzweg/aloha | /**
*
* Rates
*
*/
import React from 'react';
// import styled from 'styled-components';
import { Card, CardActions, CardMedia, CardTitle, CardText } from 'material-ui/Card';
import FlatButton from 'material-ui/FlatButton';
import { Link } from 'react-router';
import Btn from 'components/landing/Btn';
import { Image } from 'cloudinary-react';
function Rates(props) {
let color = '#ECECEC';
props.hover ? color = '#7C4DFF' : color;
let src = 'camera_white';
props.hover ? src = 'camera_purple' : src;
return (
<div style={{ display: 'block', width: '100%', margin: '0 auto' }}>
<div className="container" style={{ backgroundColor: '#FF80AB', width: '100%' }}>
<div className="row">
<div className="col-sm-6" >
<h4 style={{ marginTop: '1%', padding: '3%', textAlign: 'center', color: '#7C4DFF', textTransform: 'uppercase', letterSpacing: '2px' }}>All lessons last 90 minutes (water time)</h4>
</div>
<div className="col-sm-6" >
<h4 style={{ marginTop: '1%', padding: '3%', textAlign: 'center', color: '#7C4DFF', textTransform: 'uppercase', letterSpacing: '2px' }}>Surfboard & wetsuit included</h4>
</div>
</div>
</div>
<div className="container" style={{ backgroundColor: '#ECECEC', width: '100%' }}>
<div className="row" style={{ marginTop: '5%' }}>
<div className="col-sm-6" style={{ display: 'block', margin: '0 auto', marginBottom: '2%' }}>
<Card style={{ display: 'block', margin: '0 auto', width: '60%', marginLeft: '25%' }}>
<CardMedia>
<Image className="item" cloudName="kurzweg" publicId="cuteness_overload_kkto2i" width="400" quality="auto" responsive />
</CardMedia>
<CardTitle title="Standard Group Lesson" subtitle="$85/person" />
<CardText style={{ textAlign: 'center', fontSize: '20px', }}>
1 instructor for up to 4 people
<hr style={{ marginTop: '2%', marginBottom: '2%' }} />
We create the group if you don't have at least 3 people
<hr style={{ marginTop: '2%', marginBottom: '2%' }} />
Most popular option!
</CardText>
</Card>
</div>
<div className="col-sm-6" style={{ display: 'block', margin: '0 auto', marginBottom: '2%' }}>
<Card style={{ display: 'block', margin: '0 auto', width: '60%' }}>
<CardMedia>
<Image className="item" cloudName="kurzweg" publicId="duo2_ktikxn" width="400" quality="auto" responsive />
</CardMedia>
<CardTitle title="Private Lesson (2 ppl)" subtitle="$255"/>
<CardText style={{ textAlign: 'center', fontSize: '20px', marginBottom: '4%' }}>
1 instructor for 2 people
<hr style={{ marginTop: '2%', marginBottom: '2%' }} />
Perfect for couples or children and their parents!
</CardText>
</Card>
</div>
</div>
</div>
<div style={{ backgroundColor: '#ECECEC' }}>
<Link to="/gallery" style={{ textDecoration: 'none' }}><div onMouseEnter={props.toggleColor} onMouseLeave={props.toggleColor} style={{ border: 'none', borderRadius: '3px', backgroundColor: '#FF80AB', width: '30%', margin: '0 auto', padding: '2%' }}>
<Image cloudName="kurzweg" publicId={src} width="auto" responsive alt="surf photography" style={{ display: 'block', margin: '0 auto' }} />
<p style={{ color, textAlign: 'center', fontSize: '22px', padding: '1%' }}>Add photography to your lesson from $85</p>
</div></Link>
<div style={{ marginTop: '3%', paddingBottom: '5%' }}>
<Link style={{ textDecoration: 'none', cursor: 'pointer' }} to="/rates" ><Btn>All rates & packages</Btn></Link>
</div>
</div>
</div>
);
}
Rates.propTypes = {
};
export default Rates;
|
modules/gui/src/widget/keybinding.js | openforis/sepal | import {add, remove} from './keybindings'
import {compose} from 'compose'
import {connect} from 'store'
import PropTypes from 'prop-types'
import React from 'react'
import _ from 'lodash'
class Keybinding extends React.Component {
constructor(props) {
super(props)
this.createKeybinding()
const {onEnable, onDisable} = props
onEnable(() => this.keybinding.enabled = true)
onDisable(() => this.keybinding.enabled = false)
add(this.keybinding)
}
createKeybinding() {
const {disabled, priority} = this.props
this.keybinding = {
disabled,
priority,
enabled: true,
handler: this.handle.bind(this),
handles: key => _.keys(this.props.keymap).includes(key)
}
}
getDefaultHandler() {
const {keymap} = this.props
return keymap.default
}
getCustomHandler(key) {
const {keymap} = this.props
return keymap[key]
}
getHandler(key) {
return this.getCustomHandler(key) || this.getDefaultHandler()
}
handle(event, key) {
const handler = this.getHandler(key)
if (handler) {
handler(event)
event.preventDefault()
}
}
render() {
const {children} = this.props
return children || null
}
componentDidUpdate() {
const {disabled, priority} = this.props
this.keybinding.disabled = disabled
this.keybinding.priority = priority
}
componentWillUnmount() {
remove(this.keybinding)
}
}
export default compose(
Keybinding,
connect()
)
Keybinding.propTypes = {
disabled: PropTypes.any,
keymap: PropTypes.object,
priority: PropTypes.any
}
|
blueprints/smart/files/__root__/containers/__name__.js | Rkiouak/react-redux-python-stocks | import React from 'react'
import { connect } from 'react-redux'
import { bindActionCreators } from 'redux'
type Props = {
}
export class <%= pascalEntityName %> extends React.Component {
props: Props;
render() {
return (
<div></div>
)
}
}
const mapStateToProps = (state) => {
return {}
}
const mapDispatchToProps = (dispatch) => {
return {}
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(<%= pascalEntityName %>)
|
docs/app/Examples/modules/Dropdown/Variations/DropdownExampleScrolling.js | Rohanhacker/Semantic-UI-React | import React from 'react'
import { Dropdown } from 'semantic-ui-react'
import { getOptions } from '../common'
const DropdownExampleScrolling = () => (
<Dropdown placeholder='Select choice' scrolling options={getOptions(15)} />
)
export default DropdownExampleScrolling
|
src/svg-icons/content/add-box.js | IsenrichO/mui-with-arrows | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentAddBox = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-2 10h-4v4h-2v-4H7v-2h4V7h2v4h4v2z"/>
</SvgIcon>
);
ContentAddBox = pure(ContentAddBox);
ContentAddBox.displayName = 'ContentAddBox';
ContentAddBox.muiName = 'SvgIcon';
export default ContentAddBox;
|
src/js/components/MuiButton.js | Robert-W/immutable-flux-todo | /*eslint-disable no-unused-expressions */
import ReactDOM from 'react-dom';
import React from 'react';
let timeoutDuration = 1500,
timer;
//- Base Styles
let buttonStyles = {
display: 'inline-block',
position: 'relative',
cursor: 'pointer'
};
let muiClickStyle = (type) => {
let style = {
position: 'absolute',
overflow: 'hidden',
height: '100%',
width: '100%',
zIndex: 1,
left: 0,
top: 0
};
if (type === 'circle') {
style.borderRadius = '50%';
style.zIndex = 5;
}
return style;
};
export default class MuiButton extends React.Component {
constructor (props) {
super(props);
this.state = { ripples: [] };
}
animate (evt) {
let target = ReactDOM.findDOMNode(this);
let size = Math.max(target.clientHeight, target.clientWidth);
let left = evt.pageX - target.offsetLeft - (size / 2);
let top = evt.pageY - target.offsetTop - (size / 2);
let ripples = this.state.ripples;
//- Push the ripple node into the stack
ripples.push(<Ripple key={ripples.length} top={top} left={left} size={size} />);
this.setState({ ripples: ripples });
//- Remove this animation once completed
clearTimeout(timer);
timer = setTimeout(() => {
this.setState({ ripples: [] });
}, timeoutDuration);
}
render () {
return (
<button className={this.props.className || ''} style={buttonStyles} {...this.props}>
<span ref='wrapper' style={muiClickStyle(this.props.shape)} onClick={::this.animate}>
{this.state.ripples}
</span>
{this.props.children}
</button>
);
}
}
class Ripple extends React.Component {
constructor (props) {
super(props);
this.state = { transform: 'scale(0)', opacity: 1 };
}
componentDidMount() {
let node = ReactDOM.findDOMNode(this);
//- Force the default styles to take effect, simply reading a value from
//- computed style will flush pending changes so they are applied
window.getComputedStyle(node).opacity;
this.setState({ transform: 'scale(2)', opacity: 0 });
}
generateStyles() {
return {
transition: 'opacity 2s cubic-bezier(0.23, 1, 0.32, 1) 0ms, transform 2s cubic-bezier(0.23, 1, 0.32, 1) 0ms',
backgroundColor: 'rgba(0, 0, 0, 0.15)',
transform: this.state.transform,
height: `${this.props.size}px`,
width: `${this.props.size}px`,
opacity: this.state.opacity,
left: this.props.left,
position: 'absolute',
borderRadius: '50%',
top: this.props.top
};
}
render () {
return (
<div className='muiRipple' style={this.generateStyles()} />
);
}
}
|
fixtures/nesting/src/modern/lazyLegacyRoot.js | mosoft521/react | import React from 'react';
import {useContext, useMemo, useRef, useState, useLayoutEffect} from 'react';
import {__RouterContext} from 'react-router';
import {ReactReduxContext} from 'react-redux';
import ThemeContext from './shared/ThemeContext';
let rendererModule = {
status: 'pending',
promise: null,
result: null,
};
export default function lazyLegacyRoot(getLegacyComponent) {
let componentModule = {
status: 'pending',
promise: null,
result: null,
};
return function Wrapper(props) {
const createLegacyRoot = readModule(rendererModule, () =>
import('../legacy/createLegacyRoot')
).default;
const Component = readModule(componentModule, getLegacyComponent).default;
const containerRef = useRef(null);
const rootRef = useRef(null);
// Populate every contexts we want the legacy subtree to see.
// Then in src/legacy/createLegacyRoot we will apply them.
const theme = useContext(ThemeContext);
const router = useContext(__RouterContext);
const reactRedux = useContext(ReactReduxContext);
const context = useMemo(
() => ({
theme,
router,
reactRedux,
}),
[theme, router, reactRedux]
);
// Create/unmount.
useLayoutEffect(() => {
if (!rootRef.current) {
rootRef.current = createLegacyRoot(containerRef.current);
}
const root = rootRef.current;
return () => {
root.unmount();
};
}, [createLegacyRoot]);
// Mount/update.
useLayoutEffect(() => {
if (rootRef.current) {
rootRef.current.render(Component, props, context);
}
}, [Component, props, context]);
return <div style={{display: 'contents'}} ref={containerRef} />;
};
}
// This is similar to React.lazy, but implemented manually.
// We use this to Suspend rendering of this component until
// we fetch the component and the legacy React to render it.
function readModule(record, createPromise) {
if (record.status === 'fulfilled') {
return record.result;
}
if (record.status === 'rejected') {
throw record.result;
}
if (!record.promise) {
record.promise = createPromise().then(
value => {
if (record.status === 'pending') {
record.status = 'fulfilled';
record.promise = null;
record.result = value;
}
},
error => {
if (record.status === 'pending') {
record.status = 'rejected';
record.promise = null;
record.result = error;
}
}
);
}
throw record.promise;
}
|
client/app/scripts/components/node-details.js | paulbellamy/scope | import debug from 'debug';
import React from 'react';
import classNames from 'classnames';
import { connect } from 'react-redux';
import { Map as makeMap } from 'immutable';
import { clickCloseDetails, clickShowTopologyForNode } from '../actions/app-actions';
import { brightenColor, getNeutralColor, getNodeColorDark } from '../utils/color-utils';
import { isGenericTable, isPropertyList } from '../utils/node-details-utils';
import { resetDocumentTitle, setDocumentTitle } from '../utils/title-utils';
import MatchedText from './matched-text';
import NodeDetailsControls from './node-details/node-details-controls';
import NodeDetailsGenericTable from './node-details/node-details-generic-table';
import NodeDetailsPropertyList from './node-details/node-details-property-list';
import NodeDetailsHealth from './node-details/node-details-health';
import NodeDetailsInfo from './node-details/node-details-info';
import NodeDetailsRelatives from './node-details/node-details-relatives';
import NodeDetailsTable from './node-details/node-details-table';
import Warning from './warning';
const log = debug('scope:node-details');
function getTruncationText(count) {
return 'This section was too long to be handled efficiently and has been truncated'
+ ` (${count} extra entries not included). We are working to remove this limitation.`;
}
class NodeDetails extends React.Component {
constructor(props, context) {
super(props, context);
this.handleClickClose = this.handleClickClose.bind(this);
this.handleShowTopologyForNode = this.handleShowTopologyForNode.bind(this);
}
handleClickClose(ev) {
ev.preventDefault();
this.props.clickCloseDetails(this.props.nodeId);
}
handleShowTopologyForNode(ev) {
ev.preventDefault();
this.props.clickShowTopologyForNode(this.props.topologyId, this.props.nodeId);
}
componentDidMount() {
this.updateTitle();
}
componentWillUnmount() {
resetDocumentTitle();
}
renderTools() {
const showSwitchTopology = this.props.nodeId !== this.props.selectedNodeId;
const topologyTitle = `View ${this.props.label} in ${this.props.topologyId}`;
return (
<div className="node-details-tools-wrapper">
<div className="node-details-tools">
{showSwitchTopology && <span
title={topologyTitle}
className="fa fa-long-arrow-left"
onClick={this.handleShowTopologyForNode}>
<span>Show in <span>{this.props.topologyId.replace(/-/g, ' ')}</span></span>
</span>}
<span title="Close details" className="fa fa-close" onClick={this.handleClickClose} />
</div>
</div>
);
}
renderLoading() {
const node = this.props.nodes.get(this.props.nodeId);
const label = node ? node.get('label') : this.props.label;
// NOTE: If we start the fa-spin animation before the node details panel has been
// mounted, the spinner is displayed blurred the whole time in Chrome (possibly
// caused by a bug having to do with animating the details panel).
const spinnerClassName = classNames('fa fa-circle-o-notch', { 'fa-spin': this.props.mounted });
const nodeColor = (node ?
getNodeColorDark(node.get('rank'), label, node.get('pseudo')) :
getNeutralColor());
const tools = this.renderTools();
const styles = {
header: {
backgroundColor: nodeColor
}
};
return (
<div className="node-details">
{tools}
<div className="node-details-header" style={styles.header}>
<div className="node-details-header-wrapper">
<h2 className="node-details-header-label truncate">
{label}
</h2>
<div className="node-details-relatives truncate">
Loading...
</div>
</div>
</div>
<div className="node-details-content">
<div className="node-details-content-loading">
<span className={spinnerClassName} />
</div>
</div>
</div>
);
}
renderNotAvailable() {
const tools = this.renderTools();
return (
<div className="node-details">
{tools}
<div className="node-details-header node-details-header-notavailable">
<div className="node-details-header-wrapper">
<h2 className="node-details-header-label">
{this.props.label}
</h2>
<div className="node-details-relatives truncate">
n/a
</div>
</div>
</div>
<div className="node-details-content">
<p className="node-details-content-info">
<strong>{this.props.label}</strong> is not visible to Scope when it
is not communicating.
Details will become available here when it communicates again.
</p>
</div>
</div>
);
}
render() {
if (this.props.notFound) {
return this.renderNotAvailable();
}
if (this.props.details) {
return this.renderDetails();
}
return this.renderLoading();
}
renderDetails() {
const { details, nodeControlStatus, nodeMatches = makeMap() } = this.props;
const showControls = details.controls && details.controls.length > 0;
const nodeColor = getNodeColorDark(details.rank, details.label, details.pseudo);
const {error, pending} = nodeControlStatus ? nodeControlStatus.toJS() : {};
const tools = this.renderTools();
const styles = {
controls: {
backgroundColor: brightenColor(nodeColor)
},
header: {
backgroundColor: nodeColor
}
};
return (
<div className="node-details">
{tools}
<div className="node-details-header" style={styles.header}>
<div className="node-details-header-wrapper">
<h2 className="node-details-header-label truncate" title={details.label}>
<MatchedText text={details.label} match={nodeMatches.get('label')} />
</h2>
<div className="node-details-header-relatives">
{details.parents && <NodeDetailsRelatives
matches={nodeMatches.get('parents')}
relatives={details.parents} />}
</div>
</div>
</div>
{showControls && <div className="node-details-controls-wrapper" style={styles.controls}>
<NodeDetailsControls
nodeId={this.props.nodeId}
controls={details.controls}
pending={pending}
error={error} />
</div>}
<div className="node-details-content">
{details.metrics && <div className="node-details-content-section">
<div className="node-details-content-section-header">Status</div>
<NodeDetailsHealth metrics={details.metrics} />
</div>}
{details.metadata && <div className="node-details-content-section">
<div className="node-details-content-section-header">Info</div>
<NodeDetailsInfo rows={details.metadata} matches={nodeMatches.get('metadata')} />
</div>}
{details.connections && details.connections.map(connections => (
<div className="node-details-content-section" key={connections.id}>
<NodeDetailsTable
{...connections}
nodes={connections.connections}
nodeIdKey="nodeId"
/>
</div>
))}
{details.children && details.children.map(children => (
<div className="node-details-content-section" key={children.topologyId}>
<NodeDetailsTable {...children} />
</div>
))}
{details.tables && details.tables.length > 0 && details.tables.map((table) => {
if (table.rows.length > 0) {
return (
<div className="node-details-content-section" key={table.id}>
<div className="node-details-content-section-header">
{table.label && table.label.length > 0 && table.label}
{table.truncationCount > 0 && <span
className="node-details-content-section-header-warning">
<Warning text={getTruncationText(table.truncationCount)} />
</span>}
</div>
{this.renderTable(table)}
</div>
);
}
return null;
})}
</div>
</div>
);
}
renderTable(table) {
const { nodeMatches = makeMap() } = this.props;
if (isGenericTable(table)) {
return (
<NodeDetailsGenericTable
rows={table.rows} columns={table.columns}
matches={nodeMatches.get('tables')}
/>
);
} else if (isPropertyList(table)) {
return (
<NodeDetailsPropertyList
rows={table.rows} controls={table.controls}
matches={nodeMatches.get('property-lists')}
/>
);
}
log(`Undefined type '${table.type}' for table ${table.id}`);
return null;
}
componentDidUpdate() {
this.updateTitle();
}
updateTitle() {
setDocumentTitle(this.props.details && this.props.details.label);
}
}
function mapStateToProps(state, ownProps) {
const currentTopologyId = state.get('currentTopologyId');
return {
nodeMatches: state.getIn(['searchNodeMatches', currentTopologyId, ownProps.id]),
nodes: state.get('nodes'),
selectedNodeId: state.get('selectedNodeId'),
};
}
export default connect(
mapStateToProps,
{ clickCloseDetails, clickShowTopologyForNode }
)(NodeDetails);
|
src/Toast/testkit/Toast.js | nirhart/wix-style-react | import React from 'react';
import ReactDOM from 'react-dom';
import Toast from '../Toast';
import ReactTestUtils from 'react-addons-test-utils';
import $ from 'jquery';
const byDataHook = hook => `[data-hook|="${hook}"]`;
const toastDriverFactory = ({element}) => {
const $component = $(element);
const styleStringToObj = input =>
input //"key1: value1;key2: value2;"
.replace(' ', '')
.split(';')
.filter(val => val !== '')
.reduce((result, next) => {
const [k, v] = next.split(':');
result[k] = v;
return result;
}, {});
return {
hasId: id => $component.attr('id') === id,
getToastText: () => $component.find(byDataHook('toast-text')).text(),
clickOnClose: () => ReactTestUtils.Simulate.click($component.find(byDataHook('toast-close'))[0]),
hasTheme: theme => $component.hasClass(theme),
toastExists: () => $component.parent().find(byDataHook('toast')).length > 0,
getTopProperty: () => styleStringToObj($component.attr('style')).top,
hasLocation: location => $component.get(0).classList.contains(location)
};
};
const componentFactory = (props = {}) => {
let element;
const {children, ...otherProps} = props;
const wrapperDiv = document.createElement('div');
ReactDOM.render(<div ref={r => element = r}><Toast {...otherProps}>{children}</Toast></div>, wrapperDiv);
return {element: element.childNodes[0], wrapper: wrapperDiv};
};
const toastTestkitFactory = ({wrapper, id}) => {
const element = $(wrapper).find(`#${id}`)[0];
return toastDriverFactory({element, wrapper});
};
export {toastTestkitFactory, componentFactory, toastDriverFactory};
|
docs/src/app/components/pages/components/Dialog/Page.js | igorbt/material-ui | import React from 'react';
import Title from 'react-title-component';
import CodeExample from '../../../CodeExample';
import PropTypeDescription from '../../../PropTypeDescription';
import MarkdownElement from '../../../MarkdownElement';
import dialogReadmeText from './README';
import DialogExampleSimple from './ExampleSimple';
import dialogExampleSimpleCode from '!raw!./ExampleSimple';
import DialogExampleModal from './ExampleModal';
import dialogExampleModalCode from '!raw!./ExampleModal';
import DialogExampleCustomWidth from './ExampleCustomWidth';
import dialogExampleCustomWidthCode from '!raw!./ExampleCustomWidth';
import DialogExampleDialogDatePicker from './ExampleDialogDatePicker';
import dialogExampleDialogDatePickerCode from '!raw!./ExampleDialogDatePicker';
import DialogExampleScrollable from './ExampleScrollable';
import DialogExampleScrollableCode from '!raw!./ExampleScrollable';
import DialogExampleAlert from './ExampleAlert';
import DialogExampleAlertCode from '!raw!./ExampleAlert';
import dialogCode from '!raw!material-ui/Dialog/Dialog';
const DialogPage = () => (
<div>
<Title render={(previousTitle) => `Dialog - ${previousTitle}`} />
<MarkdownElement text={dialogReadmeText} />
<CodeExample
title="Simple dialog"
code={dialogExampleSimpleCode}
>
<DialogExampleSimple />
</CodeExample>
<CodeExample
title="Modal dialog"
code={dialogExampleModalCode}
>
<DialogExampleModal />
</CodeExample>
<CodeExample
title="Styled dialog"
code={dialogExampleCustomWidthCode}
>
<DialogExampleCustomWidth />
</CodeExample>
<CodeExample
title="Nested dialogs"
code={dialogExampleDialogDatePickerCode}
>
<DialogExampleDialogDatePicker />
</CodeExample>
<CodeExample
title="Scrollable dialog"
code={DialogExampleScrollableCode}
>
<DialogExampleScrollable />
</CodeExample>
<CodeExample
title="Alert dialog"
code={DialogExampleAlertCode}
>
<DialogExampleAlert />
</CodeExample>
<PropTypeDescription code={dialogCode} />
</div>
);
export default DialogPage;
|
App/index.android.js | DupK/dashboard-epitech | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React from 'react';
import { AppRegistry } from 'react-native';
import Main from './src/features/main';
import monitorNetworkConnection from './src/shared/NetworkConnection';
//observe any network changes and let ui react according to these changes
monitorNetworkConnection();
/* Modules */
AppRegistry.registerComponent('Dashboard', () => Main);
|
src/components/BoardSettings.js | rhernandez-applaudostudios/tic-tac-toe | import React from 'react';
function BoardSettings({ onInputChange, status, createGame, size}) {
return (
<div className="settings">
<div className="settings-label">
Select the size of the board:
<input
type="number"
min="3"
max="15"
step="1"
value={size}
name="board-size"
onChange={(event) => onInputChange(event.target.value)} />
</div>
<div>
<button className="btn" onClick={(event) => createGame()}>New Game</button>
</div>
</div>
);
}
export default BoardSettings; |
app/packs/src/components/generic/GenericElDropTarget.js | ComPlat/chemotion_ELN | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import uuid from 'uuid';
import { DropTarget } from 'react-dnd';
import Aviator from 'aviator';
import { Tooltip, OverlayTrigger, Popover } from 'react-bootstrap';
import UIStore from '../stores/UIStore';
const handleSampleClick = (type, id) => {
const { currentCollection, isSync } = UIStore.getState();
if (!isNaN(id)) type += `/${id}`;
const collectionUrl = `${currentCollection.id}/${type}`;
Aviator.navigate(isSync ? `/scollection/${collectionUrl}` : `/collection/${collectionUrl}`);
};
const show = (opt, iconClass) => {
if (opt.value && opt.value.el_id) {
const tips = opt.value.el_tip && opt.value.el_tip.split('@@');
const tip1 = (tips && tips.length >= 1 && tips[0]) || '';
const tip2 = (tips && tips.length >= 2 && tips[1]) || '';
const tit = (<div>{tip1}<br />{tip2}</div>);
const pop = (
<Popover id="popover-svg" title={tit} style={{ maxWidth: 'none', maxHeight: 'none' }}>
<img src={opt.value.el_svg} style={{ height: '26vh', width: '26vh' }} alt="" />
</Popover>
);
let label = opt.value.el_label;
const simg = (path, tip, txt) => ((path && path !== '') ? (
<div className="s-img">
<OverlayTrigger trigger={['hover']} placement="left" rootClose onHide={null} overlay={pop}>
<img src={path} alt="" />
</OverlayTrigger> <span className="data">{txt}</span>
</div>
) : (<OverlayTrigger placement="top" overlay={<Tooltip id={uuid.v4()}>{tip1}<br />{tip2}</Tooltip>}><div className="data">{txt}</div></OverlayTrigger>));
if (opt.value.el_type === 'sample') {
if (opt.value.is_new !== true) {
label = (
<a role="link" onClick={() => handleSampleClick(opt.value.el_type, opt.value.el_id)} style={{ cursor: 'pointer' }}>
<span className="reaction-material-link">{label}</span>
</a>
);
}
}
return simg(opt.value.el_svg, opt.value.el_tip, label);
}
return (<span className={`icon-${iconClass} indicator`} />);
};
const source = (type, props, id) => {
let isAssoc = false;
const taggable = (props && props.tag && props.tag.taggable_data) || {};
if (taggable.element && taggable.element.id === id) {
isAssoc = false;
} else {
isAssoc = !!(taggable.reaction_id || taggable.wellplate_id || taggable.element);
}
switch (type) {
case 'molecule':
return {
el_id: props.molecule.id,
el_type: 'molecule',
el_label: props.molecule_name_label,
el_tip: `${props.molecule.inchikey}@@${props.molecule.cano_smiles}`,
};
case 'sample':
return {
el_id: props.id,
is_new: true,
cr_opt: isAssoc == true ? 1 : 0,
isAssoc,
el_type: 'sample',
el_label: props.short_label,
el_tip: props.short_label,
};
default:
return {
el_id: props.id,
is_new: true,
cr_opt: 0,
el_type: props.type,
el_label: props.short_label,
el_tip: props.short_label,
};
}
};
const dropTarget = {
drop(targetProps, monitor) {
const sourceProps = monitor.getItem().element;
const sourceTag = source(targetProps.opt.type.split('_')[1], sourceProps, targetProps.opt.id);
targetProps.onDrop(sourceTag);
},
canDrop(targetProps, monitor) {
return true;
},
};
const dropCollect = (connect, monitor) => ({
connectDropTarget: connect.dropTarget(),
isOver: monitor.isOver(),
canDrop: monitor.canDrop()
});
class GenericElDropTarget extends Component {
render() {
const {
connectDropTarget, isOver, canDrop, opt
} = this.props;
const iconClass = (opt.dndItems && opt.dndItems[0] === 'molecule' ? 'sample' : opt.dndItems[0]);
const className = `target${isOver ? ' is-over' : ''}${canDrop ? ' can-drop' : ''}`;
return connectDropTarget(<div className={className}>{show(opt, iconClass)}</div>);
}
}
export default
DropTarget(props => props.opt.dndItems, dropTarget, dropCollect)(GenericElDropTarget);
GenericElDropTarget.propTypes = {
connectDropTarget: PropTypes.func.isRequired,
isOver: PropTypes.bool.isRequired,
canDrop: PropTypes.bool.isRequired,
};
|
modules/IndexLink.js | meraki/react-router | import React from 'react'
import Link from './Link'
/**
* An <IndexLink> is used to link to an <IndexRoute>.
*/
const IndexLink = React.createClass({
render() {
return <Link {...this.props} onlyActiveOnIndex={true} />
}
})
export default IndexLink
|
client/src/app/routes/forms/jcrop/components/OptionRadio.js | zraees/sms-project | import React from 'react'
import {connect} from 'react-redux'
import {setOptions} from '../actions/options'
import OptionRadioBtn from './OptionRadioBtn'
const mapStateToProps= (state, props)=>({
label: props.label,
options: props.options,
group: props.group,
checked: props.checked
});
const mapDispatchToProps= (dispatch, props) =>({
onSet: ()=> {
dispatch(setOptions(props.options))
}
});
const OptionRadio = connect(mapStateToProps, mapDispatchToProps)(OptionRadioBtn);
export default OptionRadio |
blueocean-material-icons/src/js/components/svg-icons/editor/vertical-align-top.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const EditorVerticalAlignTop = (props) => (
<SvgIcon {...props}>
<path d="M8 11h3v10h2V11h3l-4-4-4 4zM4 3v2h16V3H4z"/>
</SvgIcon>
);
EditorVerticalAlignTop.displayName = 'EditorVerticalAlignTop';
EditorVerticalAlignTop.muiName = 'SvgIcon';
export default EditorVerticalAlignTop;
|
src/client/get-router.js | Restuta/rcn.io | import React from 'react'
import { Router, browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import configureStore from 'shared/configure-store.js'
import { syncHistoryWithStore } from 'react-router-redux'
import routes from './routes'
import analytics from 'utils/analytics'
const store = configureStore()
const getStore = () => store
const history = syncHistoryWithStore(browserHistory, store)
history.listen(location => analytics.page())
//overriding Router function to pass custom props to a child components, building a higer order function to
//provide containerWidth to inner-clojure
const buildCreateElement = containerW =>
(Component, props) => <Component {...props} containerWidth={containerW}/>
const getRouter = containerWidth => {
return <Router history={history} routes={routes} createElement={buildCreateElement(containerWidth)} />
}
const getConfiguredWithStoreRouter = containerWidth => {
return (
<Provider store={store}>
{getRouter(containerWidth)}
</Provider>
)
}
export {
getRouter,
getConfiguredWithStoreRouter,
getStore,
}
|
app/imports/ui/components/DocumentEditor.js | ericvrp/GameCollie | /* eslint-disable max-len, no-return-assign */
import React from 'react';
import PropTypes from 'prop-types';
import { FormGroup, ControlLabel, FormControl, Button } from 'react-bootstrap';
import documentEditor from '../../modules/document-editor.js';
export default class DocumentEditor extends React.Component {
componentDidMount() {
documentEditor({ component: this });
setTimeout(() => { document.querySelector('[name="title"]').focus(); }, 0);
}
render() {
const { doc } = this.props;
return (<form
ref={ form => (this.documentEditorForm = form) }
onSubmit={ event => event.preventDefault() }
>
<FormGroup>
<ControlLabel>Title</ControlLabel>
<FormControl
type="text"
name="title"
defaultValue={ doc && doc.title }
placeholder="Oh, The Places You'll Go!"
/>
</FormGroup>
<FormGroup>
<ControlLabel>Body</ControlLabel>
<FormControl
componentClass="textarea"
name="body"
defaultValue={ doc && doc.body }
placeholder="Congratulations! Today is your day. You're off to Great Places! You're off and away!"
/>
</FormGroup>
<Button type="submit" bsStyle="success">
{ doc && doc._id ? 'Save Changes' : 'Add Document' }
</Button>
</form>);
}
}
DocumentEditor.propTypes = {
doc: PropTypes.object,
};
|
examples/huge-apps/routes/Course/components/Course.js | upraised/react-router | import React from 'react';
import Dashboard from './Dashboard';
import Nav from './Nav';
var styles = {};
styles.sidebar = {
float: 'left',
width: 200,
padding: 20,
borderRight: '1px solid #aaa',
marginRight: 20
};
class Course extends React.Component {
render () {
let { children, params } = this.props;
let course = COURSES[params.courseId];
return (
<div>
<h2>{course.name}</h2>
<Nav course={course} />
{children && children.sidebar && children.main ? (
<div>
<div className="Sidebar" style={styles.sidebar}>
{children.sidebar}
</div>
<div className="Main" style={{padding: 20}}>
{children.main}
</div>
</div>
) : (
<Dashboard />
)}
</div>
);
}
}
export default Course;
|
hosted-demo/src/index.js | learnapollo/pokedex-react | import React from 'react'
import ReactDOM from 'react-dom'
import Pokedex from './components/Pokedex'
import PokemonPage from './components/PokemonPage'
import AddPokemonCard from './components/AddPokemonCard'
import { Router, Route, browserHistory, IndexRedirect } from 'react-router'
import ApolloClient, { createNetworkInterface } from 'apollo-client'
import { ApolloProvider } from 'react-apollo'
import 'tachyons'
import './index.css'
const client = new ApolloClient({
networkInterface: createNetworkInterface({ uri: 'https://api.graph.cool/simple/v1/ciwjew0qz0l8d0122v7smvmxu'}),
dataIdFromObject: o => o.id
})
ReactDOM.render((
<ApolloProvider client={client}>
<Router history={browserHistory}>
<Route path='/' component={Pokedex}>
<IndexRedirect to='/1' />
<Route path='/:page' component={Pokedex} />
</Route>
<Route path='/view/:pokemonId' component={PokemonPage} />
<Route path='/create/:trainerId' component={AddPokemonCard} />
</Router>
</ApolloProvider>
),
document.getElementById('root')
)
|
react/features/toolbox/components/ToolbarButton.web.js | KalinduDN/kalindudn.github.io | /* @flow */
import React from 'react';
import { connect } from 'react-redux';
import { translate } from '../../base/i18n';
import UIUtil from '../../../../modules/UI/util/UIUtil';
import AbstractToolbarButton from './AbstractToolbarButton';
import { getButtonAttributesByProps } from '../functions';
declare var APP: Object;
declare var interfaceConfig: Object;
/**
* Represents a button in Toolbar on React.
*
* @class ToolbarButton
* @extends AbstractToolbarButton
*/
class ToolbarButton extends AbstractToolbarButton {
_createRefToButton: Function;
_onClick: Function;
/**
* Toolbar button component's property types.
*
* @static
*/
static propTypes = {
...AbstractToolbarButton.propTypes,
/**
* Object describing button.
*/
button: React.PropTypes.object.isRequired,
/**
* Used to dispatch an action when the button is clicked.
*/
dispatch: React.PropTypes.func,
/**
* Handler for component mount.
*/
onMount: React.PropTypes.func,
/**
* Handler for component unmount.
*/
onUnmount: React.PropTypes.func,
/**
* Translation helper function.
*/
t: React.PropTypes.func,
/**
* Indicates the position of the tooltip.
*/
tooltipPosition:
React.PropTypes.oneOf([ 'bottom', 'left', 'right', 'top' ])
};
/**
* Initializes new ToolbarButton instance.
*
* @param {Object} props - The read-only properties with which the new
* instance is to be initialized.
*/
constructor(props: Object) {
super(props);
// Bind methods to save the context
this._createRefToButton = this._createRefToButton.bind(this);
this._onClick = this._onClick.bind(this);
}
/**
* Sets shortcut/tooltip
* after mounting of the component.
*
* @inheritdoc
* @returns {void}
*/
componentDidMount(): void {
this._setShortcutAndTooltip();
if (this.props.onMount) {
this.props.onMount();
}
}
/**
* Invokes on unmount handler if it was passed to the props.
*
* @inheritdoc
* @returns {void}
*/
componentWillUnmount(): void {
if (this.props.onUnmount) {
this.props.onUnmount();
}
}
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render(): ReactElement<*> {
const { button } = this.props;
const attributes = getButtonAttributesByProps(button);
const popups = button.popups || [];
return (
<a
{ ...attributes }
onClick = { this._onClick }
ref = { this._createRefToButton }>
{ this._renderInnerElementsIfRequired() }
{ this._renderPopups(popups) }
</a>
);
}
/**
* Creates reference to current toolbar button.
*
* @param {HTMLElement} element - HTMLElement representing the toolbar
* button.
* @returns {void}
* @private
*/
_createRefToButton(element: HTMLElement): void {
this.button = element;
}
/**
* Wrapper on on click handler props for current button.
*
* @param {Event} event - Click event object.
* @returns {void}
* @private
*/
_onClick(event: Event): void {
const {
button,
onClick
} = this.props;
const {
enabled,
unclickable
} = button;
if (enabled && !unclickable && onClick) {
const action = onClick(event);
if (action) {
this.props.dispatch(action);
}
}
}
/**
* If toolbar button should contain children elements
* renders them.
*
* @returns {ReactElement|null}
* @private
*/
_renderInnerElementsIfRequired(): ReactElement<*> | null {
if (this.props.button.html) {
return this.props.button.html;
}
return null;
}
/**
* Renders popup element for toolbar button.
*
* @param {Array} popups - Array of popup objects.
* @returns {Array}
* @private
*/
_renderPopups(popups: Array<*> = []): Array<*> {
return popups.map(popup => {
let gravity = 'n';
if (popup.dataAttrPosition) {
gravity = popup.dataAttrPosition;
}
const title = this.props.t(popup.dataAttr, popup.dataInterpolate);
return (
<div
className = { popup.className }
data-popup = { gravity }
id = { popup.id }
key = { popup.id }
title = { title } />
);
});
}
/**
* Sets shortcut and tooltip for current toolbar button.
*
* @private
* @returns {void}
*/
_setShortcutAndTooltip(): void {
const { button, tooltipPosition } = this.props;
const name = button.buttonName;
if (UIUtil.isButtonEnabled(name)) {
if (!button.unclickable) {
if (button.tooltipText) {
UIUtil.setTooltipText(this.button,
button.tooltipText,
tooltipPosition);
} else {
UIUtil.setTooltip(this.button,
button.tooltipKey,
tooltipPosition);
}
}
if (button.shortcut) {
APP.keyboardshortcut.registerShortcut(
button.shortcut,
button.shortcutAttr,
button.shortcutFunc,
button.shortcutDescription
);
}
}
}
}
export default translate(connect()(ToolbarButton));
|
app/javascript/mastodon/components/status_content.js | TheInventrix/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import PropTypes from 'prop-types';
import { isRtl } from '../rtl';
import { FormattedMessage } from 'react-intl';
import Permalink from './permalink';
import classnames from 'classnames';
const MAX_HEIGHT = 642; // 20px * 32 (+ 2px padding at the top)
export default class StatusContent extends React.PureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map.isRequired,
expanded: PropTypes.bool,
onExpandedToggle: PropTypes.func,
onClick: PropTypes.func,
collapsable: PropTypes.bool,
};
state = {
hidden: true,
collapsed: null, // `collapsed: null` indicates that an element doesn't need collapsing, while `true` or `false` indicates that it does (and is/isn't).
};
_updateStatusLinks () {
const node = this.node;
if (!node) {
return;
}
const links = node.querySelectorAll('a');
for (var i = 0; i < links.length; ++i) {
let link = links[i];
if (link.classList.contains('status-link')) {
continue;
}
link.classList.add('status-link');
let mention = this.props.status.get('mentions').find(item => link.href === item.get('url'));
if (mention) {
link.addEventListener('click', this.onMentionClick.bind(this, mention), false);
link.setAttribute('title', mention.get('acct'));
if (String(mention.get('acct')).indexOf('@') < 0) {
link.classList.add('local-mention');
}
} else if (link.textContent[0] === '#' || (link.previousSibling && link.previousSibling.textContent && link.previousSibling.textContent[link.previousSibling.textContent.length - 1] === '#')) {
link.addEventListener('click', this.onHashtagClick.bind(this, link.text), false);
} else {
link.setAttribute('title', link.href);
}
link.setAttribute('target', '_blank');
link.setAttribute('rel', 'noopener');
}
if (
this.props.collapsable
&& this.props.onClick
&& this.state.collapsed === null
&& node.clientHeight > MAX_HEIGHT
&& this.props.status.get('spoiler_text').length === 0
) {
this.setState({ collapsed: true });
}
}
componentDidMount () {
this._updateStatusLinks();
}
componentDidUpdate () {
this._updateStatusLinks();
}
onMentionClick = (mention, e) => {
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/accounts/${mention.get('id')}`);
}
}
onHashtagClick = (hashtag, e) => {
hashtag = hashtag.replace(/^#/, '').toLowerCase();
if (this.context.router && e.button === 0 && !(e.ctrlKey || e.metaKey)) {
e.preventDefault();
this.context.router.history.push(`/timelines/tag/${hashtag}`);
}
}
handleMouseDown = (e) => {
this.startXY = [e.clientX, e.clientY];
}
handleMouseUp = (e) => {
if (!this.startXY) {
return;
}
const [ startX, startY ] = this.startXY;
const [ deltaX, deltaY ] = [Math.abs(e.clientX - startX), Math.abs(e.clientY - startY)];
if (e.target.localName === 'button' || e.target.localName === 'a' || (e.target.parentNode && (e.target.parentNode.localName === 'button' || e.target.parentNode.localName === 'a'))) {
return;
}
if (deltaX + deltaY < 5 && e.button === 0 && this.props.onClick) {
this.props.onClick();
}
this.startXY = null;
}
handleSpoilerClick = (e) => {
e.preventDefault();
if (this.props.onExpandedToggle) {
// The parent manages the state
this.props.onExpandedToggle();
} else {
this.setState({ hidden: !this.state.hidden });
}
}
handleCollapsedClick = (e) => {
e.preventDefault();
this.setState({ collapsed: !this.state.collapsed });
}
setRef = (c) => {
this.node = c;
}
render () {
const { status } = this.props;
if (status.get('content').length === 0) {
return null;
}
const hidden = this.props.onExpandedToggle ? !this.props.expanded : this.state.hidden;
const content = { __html: status.get('contentHtml') };
const spoilerContent = { __html: status.get('spoilerHtml') };
const directionStyle = { direction: 'ltr' };
const classNames = classnames('status__content', {
'status__content--with-action': this.props.onClick && this.context.router,
'status__content--with-spoiler': status.get('spoiler_text').length > 0,
'status__content--collapsed': this.state.collapsed === true,
});
if (isRtl(status.get('search_index'))) {
directionStyle.direction = 'rtl';
}
const readMoreButton = (
<button className='status__content__read-more-button' onClick={this.props.onClick} key='read-more'>
<FormattedMessage id='status.read_more' defaultMessage='Read more' /><i className='fa fa-fw fa-angle-right' />
</button>
);
if (status.get('spoiler_text').length > 0) {
let mentionsPlaceholder = '';
const mentionLinks = status.get('mentions').map(item => (
<Permalink to={`/accounts/${item.get('id')}`} href={item.get('url')} key={item.get('id')} className='mention'>
@<span>{item.get('username')}</span>
</Permalink>
)).reduce((aggregate, item) => [...aggregate, item, ' '], []);
const tagLinks = status.get('tags').map(item => (
<Permalink to={`/timeline/tag/${item.get('name')}`} href={item.get('name')} key={item.get('id')} className='hashtag'>
#<span>{item.get('name')}</span>
</Permalink>
)).reduce((aggregate, item) => [...aggregate, item, ' '], []);
const toggleText = hidden ? <FormattedMessage id='status.show_more' defaultMessage='Show more' /> : <FormattedMessage id='status.show_less' defaultMessage='Show less' />;
if (hidden) {
mentionsPlaceholder = <div>{mentionLinks} {tagLinks}</div>;
}
return (
<div className={classNames} ref={this.setRef} tabIndex='0' style={directionStyle} onMouseDown={this.handleMouseDown} onMouseUp={this.handleMouseUp}>
<p style={{ marginBottom: hidden && status.get('mentions').isEmpty() ? '0px' : null }}>
<span dangerouslySetInnerHTML={spoilerContent} />
{' '}
<button tabIndex='0' className={`status__content__spoiler-link ${hidden ? 'status__content__spoiler-link--show-more' : 'status__content__spoiler-link--show-less'}`} onClick={this.handleSpoilerClick}>{toggleText}</button>
</p>
{mentionsPlaceholder}
<div tabIndex={!hidden ? 0 : null} className={`status__content__text ${!hidden ? 'status__content__text--visible' : ''}`} style={directionStyle} dangerouslySetInnerHTML={content} />
</div>
);
} else if (this.props.onClick) {
const output = [
<div
ref={this.setRef}
tabIndex='0'
key='content'
className={classNames}
style={directionStyle}
dangerouslySetInnerHTML={content}
onMouseDown={this.handleMouseDown}
onMouseUp={this.handleMouseUp}
/>,
];
if (this.state.collapsed) {
output.push(readMoreButton);
}
return output;
} else {
return (
<div
tabIndex='0'
ref={this.setRef}
className='status__content'
style={directionStyle}
dangerouslySetInnerHTML={content}
/>
);
}
}
}
|
app/javascript/mastodon/features/list_editor/components/search.js | sylph-sin-tyaku/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { defineMessages, injectIntl } from 'react-intl';
import { fetchListSuggestions, clearListSuggestions, changeListSuggestions } from '../../../actions/lists';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
search: { id: 'lists.search', defaultMessage: 'Search among people you follow' },
});
const mapStateToProps = state => ({
value: state.getIn(['listEditor', 'suggestions', 'value']),
});
const mapDispatchToProps = dispatch => ({
onSubmit: value => dispatch(fetchListSuggestions(value)),
onClear: () => dispatch(clearListSuggestions()),
onChange: value => dispatch(changeListSuggestions(value)),
});
export default @connect(mapStateToProps, mapDispatchToProps)
@injectIntl
class Search extends React.PureComponent {
static propTypes = {
intl: PropTypes.object.isRequired,
value: PropTypes.string.isRequired,
onChange: PropTypes.func.isRequired,
onSubmit: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
};
handleChange = e => {
this.props.onChange(e.target.value);
}
handleKeyUp = e => {
if (e.keyCode === 13) {
this.props.onSubmit(this.props.value);
}
}
handleClear = () => {
this.props.onClear();
}
render () {
const { value, intl } = this.props;
const hasValue = value.length > 0;
return (
<div className='list-editor__search search'>
<label>
<span style={{ display: 'none' }}>{intl.formatMessage(messages.search)}</span>
<input
className='search__input'
type='text'
value={value}
onChange={this.handleChange}
onKeyUp={this.handleKeyUp}
placeholder={intl.formatMessage(messages.search)}
/>
</label>
<div role='button' tabIndex='0' className='search__icon' onClick={this.handleClear}>
<Icon id='search' className={classNames({ active: !hasValue })} />
<Icon id='times-circle' aria-label={intl.formatMessage(messages.search)} className={classNames({ active: hasValue })} />
</div>
</div>
);
}
}
|
packages/react-vis/src/plot/series/horizontal-bar-series.js | uber-common/react-vis | // Copyright (c) 2016 - 2017 Uber Technologies, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
import React from 'react';
import AbstractSeries from './abstract-series';
import BarSeries from './bar-series';
class HorizontalBarSeries extends AbstractSeries {
static getParentConfig(attr) {
const isDomainAdjustmentNeeded = attr === 'y';
const zeroBaseValue = attr === 'x';
return {
isDomainAdjustmentNeeded,
zeroBaseValue
};
}
render() {
return (
<BarSeries
{...this.props}
linePosAttr="y"
valuePosAttr="x"
lineSizeAttr="height"
valueSizeAttr="width"
/>
);
}
}
HorizontalBarSeries.displayName = 'HorizontalBarSeries';
export default HorizontalBarSeries;
|
components/Roster.js | cindytung/calwtcrew | import React from 'react';
import '../css/Roster.scss';
const Roster = ({ rosterName, names, sides, years, hometowns, majors }) => (
<div className="roster-container">
<header>
<h1>{rosterName}</h1>
</header>
<div className="column-container">
<div className="roster__column">
<h3>Name</h3>
{names.map((name) => (
<div className="roster__item">
{name}
</div>
))}
</div>
<div className="roster__column">
<h3>Side</h3>
{sides.map((side) => (
<div className="roster__item">
{side}
</div>
))}
</div>
<div className="roster__column">
<h3>Year</h3>
{years.map((year) => (
<div className="roster__item">
{year}
</div>
))}
</div>
<div className="roster__column">
<h3>Hometown</h3>
{hometowns.map((hometown) => (
<div className="roster__item">
{hometown}
</div>
))}
</div>
<div className="roster__column">
<h3>Major</h3>
{majors.map((major) => (
<div className="roster__item">
{major}
</div>
))}
</div>
</div>
</div>
);
Roster.propTypes = {
rosterName: React.PropTypes.string.isRequired,
names: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
sides: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
years: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
hometowns: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
majors: React.PropTypes.arrayOf(React.PropTypes.string).isRequired,
};
export default Roster;
|
app/src/components/PartyLevelHeader.js | open-austin/budgetparty | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedNumber } from 'react-intl';
import { constants } from '../config/constants';
const getSign = (number) => {
let sign = '';
if (number.percentChange > 0) {
sign = '+';
} else if (number.percentChange < 0) {
sign = '-';
}
return sign;
};
const PartyLevelHeader = (props) => {
const { service, services, department, departments } = props;
const isServiceComplete = department ? false : service.status === 'complete';
const isUnstarted = department && department.amount === null;
const isInProgress = department && department.amount !== null;
const imgCssClass = isServiceComplete
? 'PartyLevelHeader__image--complete'
: 'PartyLevelHeader__image';
const handleReset = (deptId, departments, service, services) => {
props.resetBudgetAmount(deptId, departments, service, services);
};
const renderFinishedOverlay = (serv) => {
const sign = getSign(serv);
return (
<div className="PartyLevelHeader__overlay--green">
<span className="PartyLevelHeader__status">You Did It!</span>
<h2 className="PartyLevelHeader__value">
<FormattedNumber
value={service.amount}
style="currency" //eslint-disable-line
currency="USD"
minimumFractionDigits={0}
maximumFractionDigits={0}
/>
</h2>
<span className="PartyLevelHeader__change">
{sign} {Math.abs(service.percentChange)}% from Last Year
</span>
</div>
);
};
const renderInProgressOverlay = (dept) => {
const sign = getSign(dept);
return (
<div className="PartyLevelHeader__overlay--grey">
<span className="PartyLevelHeader__change">
{sign} {Math.abs(dept.percentChange)}% from Last Year
</span>
<h2 className="PartyLevelHeader__value">
<FormattedNumber
value={dept.amount}
style="currency" //eslint-disable-line
currency="USD"
minimumFractionDigits={0}
maximumFractionDigits={0}
/>
</h2>
<span
className="PartyLevelHeader__reset"
onClick={handleReset.bind(this, dept.deptId, departments, service, services)}
>
Reset
</span>
</div>
);
};
const renderStartingOverlay = (dept) => {
return (
<div className="PartyLevelHeader__overlay--grey">
<span className="PartyLevelHeader__change">Proposed Department Budget</span>
<h2 className="PartyLevelHeader__value">
<FormattedNumber
value={dept.lastYearAmount}
style="currency" //eslint-disable-line
currency="USD"
minimumFractionDigits={0}
maximumFractionDigits={0}
/>
</h2>
</div>
);
};
return (
<div className="PartyLevelHeader">
{isServiceComplete && renderFinishedOverlay(service, department)}
{isInProgress && renderInProgressOverlay(department)}
{isUnstarted && renderStartingOverlay(department)}
<img
src={`/images/${service.image.split('.')[0]}_full.svg`}
alt={service.title}
className={imgCssClass}
/>
</div>
);
};
export default PartyLevelHeader;
PartyLevelHeader.propTypes = {
service: PropTypes.shape({
completeSections: PropTypes.number,
departments: PropTypes.arrayOf(PropTypes.number),
desc: PropTypes.string,
image: PropTypes.string,
index: PropTypes.number,
percentChange: PropTypes.number,
status: PropTypes.string,
title: PropTypes.string,
}).isRequired,
services: PropTypes.arrayOf(PropTypes.object).isRequired,
department: PropTypes.shape({
amount: PropTypes.number,
amount2015: PropTypes.number,
deptId: PropTypes.number,
description: PropTypes.string,
explainYourSpending: PropTypes.string,
lastYearAmount: PropTypes.number,
learnMore: PropTypes.string,
name: PropTypes.string,
percentChange: PropTypes.number,
url: PropTypes.string,
}),
resetBudgetAmount: PropTypes.func,
};
|
app/components/steps/ProcessingScreen.js | rolandaugusto/react-atm-simulator | import React from 'react';
import styles from './../../App.css';
export default class ProcessingScreen extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div className={styles.bap}>
{this.props.message}
</div>
);
}
}
|
src/routes.js | TeamOculus/theater | import React from 'react';
import {Route, IndexRoute } from 'react-router';
import App from './components/app';
import Home from './components/home';
import Theater from './components/theater';
import Space from './components/space';
import Eightbit from './components/eightbit';
import City from './components/city';
import Underwater from './components/underwater';
export default (
<Route path='/' component={App}>
<IndexRoute component={Home} />
<Route path='theater' component={Theater} />
<Route path='space' component={Space} />
<Route path='eightbit' component={Eightbit} />
<Route path='city' component={City} />
<Route path='underwater' component={Underwater} />
</Route>
)
|
pages/api/bottom-navigation.js | AndriusBil/material-ui | // @flow
import React from 'react';
import withRoot from 'docs/src/modules/components/withRoot';
import MarkdownDocs from 'docs/src/modules/components/MarkdownDocs';
import markdown from './bottom-navigation.md';
function Page() {
return <MarkdownDocs markdown={markdown} />;
}
export default withRoot(Page);
|
src/StatsCarousel1/index.js | DuckyTeam/ducky-components | import LabelStatistics from '../LabelStatistics';
import LabelHorisontal from '../LabelHorisontal';
import classNames from 'classnames';
import Spacer from '../Spacer';
import React from 'react';
import PropTypes from 'prop-types';
import styles from './styles.css';
function StatsCarousel1(props) {
return (
<span className={styles.wrapper}>
<div className={styles.labelWrapper}>
<LabelHorisontal
icon={props.icon}
text={props.labelText}
theme={props.theme}
/>
</div>
<Spacer size={'double'} />
<div className={styles.innerWrapper}>
<div className={classNames(styles.previous, {
[styles.darkPrevious]: props.theme === 'dark'})}
>
<LabelStatistics
bgcolor={props.theme}
statistics={props.statOne}
textcontent={props.textOne}
/>
</div>
<LabelStatistics
bgcolor={props.theme}
statistics={props.statTwo}
textcontent={props.textTwo}
/>
</div>
</span>
);
}
StatsCarousel1.propTypes = {
icon: PropTypes.string,
labelText: PropTypes.string,
statOne: PropTypes.number,
statTwo: PropTypes.number,
textOne: PropTypes.string,
textTwo: PropTypes.string,
theme: PropTypes.string
};
export default StatsCarousel1;
|
src/components/controlbar/ControlBar.js | Tomczik76/gradus-ad-parnassum-front-end | import React, { Component } from 'react';
import { Navbar, Nav, NavItem, NavDropdown, MenuItem } from 'react-bootstrap';
export default class ControlBar extends Component {
render() {
return (
<Navbar>
<Nav>
<NavItem eventKey={1} href="#">Link</NavItem>
<NavItem eventKey={2} href="#">Link</NavItem>
<NavDropdown eventKey={3} title="Dropdown" id="basic-nav-dropdown">
<MenuItem eventKey="1">Action</MenuItem>
<MenuItem eventKey="2">Another action</MenuItem>
<MenuItem eventKey="3">Something else here</MenuItem>
<MenuItem divider />
<MenuItem eventKey="4">Separated link</MenuItem>
</NavDropdown>
</Nav>
</Navbar>
);
}
}
|
src/divider/Divider.js | martinezguillaume/react-native-elements | import React from 'react';
import { View, StyleSheet } from 'react-native';
import colors from '../config/colors';
import ViewPropTypes from '../config/ViewPropTypes';
let styles = {};
const Divider = ({ style }) =>
<View style={[styles.container, style && style]} />;
Divider.propTypes = {
style: ViewPropTypes.style,
};
styles = StyleSheet.create({
container: {
height: 1,
backgroundColor: colors.grey5,
},
});
export default Divider;
|
f2e/src/js/compoents/mockMap/mockMap.js | NyaaFinder/nyaacat | /**
* Created by john on 15/10/25.
*/
// 一个组件是一个模块,自己带有自己的样式
import React from 'react';
import AppActions from'../../actions/AppActions';
import AppStore from'../../stores/AppStore';
import '../map/map.less';
var mockMap = React.createClass({
getInitialState: function() {
return {};
},
componentDidMount: function() {
},
componentWillUnmount: function() {
},
render: function() {
return (
<div className="mock">
<img id="mock" src="./mock.png" />
</div>
);
}
});
export default mockMap;
|
src/components/ECharts/lineChart.js | joe-sky/flarej | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { registerComponent } from 'nornj';
import EChartsEnhance from './EChartsEnhance';
import 'echarts/lib/chart/line';
import template from './ECharts.t.html';
class LineChart extends Component {
static propTypes = {
type: PropTypes.string
};
static defaultProps = {
type: 'line'
};
constructor(props) {
super(props);
this.chart = React.createRef();
}
render() {
return template.chart(this);
}
}
const ecLineChart = EChartsEnhance(LineChart);
registerComponent({ 'ec-LineChart': ecLineChart });
export default ecLineChart;
|
src/components/Home.js | slkjse9/slkjse9.github.io | import React from 'react';
// import GithubForm from './forms/github/GithubForm';
// import BlogRecent from './forms/blog/RecentList';
import GithubRecent from './forms/github/RecentList';
import Dashboard from './forms/Dashboard';
class Home extends React.Component {
render() {
return (
<div className="content-home">
<br />Hello, my name is Heejun Byeon. I am a college student and
I am interested in computer science and programming.
<h3>Projects</h3>
{/* <GithubRecent userName="slkjse9" standardDate={5259492000} /> */}
<GithubRecent userName="slkjse9" standardDate={Date.now()} />
{/* <h2>Activity</h2> */}
<br />
<h3>Github Feed</h3>
<Dashboard userName="slkjse9" />
{/* <div className="content-home-github-recent-title">
<h2>Recent Works</h2>
<h3>updated in 2 months</h3>
</div> */}
{/* <h3>Recent</h3>
<GithubForm contentType="recent"/> */}
{/* <h3>Lifetime</h3>
{/* <GithubForm contentType="life"/> */}
{/* <div className="content-home-blog-recent-title">
<h2>Recent Posts</h2>
<h3>written in 2 months</h3>
</div>
<BlogRecent /> */}
</div>
);
}
}
export default Home;
|
src/shared/components/BalanceTotal/index.js | rvboris/financebutler | import React from 'react';
import { connect } from 'react-redux';
import { createSelector } from 'reselect';
import { get } from 'lodash';
import MoneyFormat from '../MoneyFormat';
const BalanceTotal = ({ total, currencyId }) => (
<MoneyFormat sum={total} currencyId={currencyId} />
);
BalanceTotal.propTypes = {
total: React.PropTypes.number.isRequired,
currencyId: React.PropTypes.string.isRequired,
};
const processSelector = createSelector(
state => get(state, 'balance.process', false),
process => process,
);
const totalSelector = createSelector(
state => get(state, 'balance.total', 0),
total => total,
);
const currencySelector = createSelector(
state => get(state, 'balance.currency'),
currency => currency,
);
const selector = createSelector(
totalSelector,
currencySelector,
processSelector,
(total, currencyId, process) => ({
total,
currencyId,
process,
}),
);
export default connect(selector)(BalanceTotal);
|
src/routes/PortfolioRoute/components/PortfolioRoute.js | easingthemes/notamagic | import React from 'react';
import Gallery from 'components/Gallery';
import Parallax from 'components/Paralax';
import Achievement from 'components/Achievement';
export const PortfolioRoute = () => (
<div>
<Parallax />
<Gallery />
<Achievement />
</div>
)
export default PortfolioRoute
|
docs-ui/components/form-old-fields.stories.js | beeftornado/sentry | import React from 'react';
import {withInfo} from '@storybook/addon-info';
import {Form as LegacyForm, PasswordField, BooleanField} from 'app/components/forms';
export default {
title: 'Core/Forms/Old/Fields',
};
export const _PasswordField = withInfo({
text: 'Password input',
propTablesExclude: [LegacyForm],
})(() => (
<LegacyForm>
<PasswordField hasSavedValue name="password" label="password" />
</LegacyForm>
));
_PasswordField.story = {
name: 'PasswordField',
};
export const _BooleanField = withInfo({
text: 'Boolean field (i.e. checkbox)',
propTablesExclude: [LegacyForm],
})(() => (
<LegacyForm>
<BooleanField name="field" />
<BooleanField name="disabled-field" disabled disabledReason="This is off." />
</LegacyForm>
));
_BooleanField.story = {
name: 'BooleanField',
};
|
dev/js/page/home.js | WALLE729/react_webpack | 'use strict';
import React from 'react'
import ReactDOM from 'react-dom'
import Listhome from './../components/homeList.js'
import "../../css/common/base.css"
// import "../../css/common/bootstrap.css"
import "../../css/page/home.less"
ReactDOM.render(
<Listhome />,
document.getElementById('home')
); |
examples/browser/create-splunk-react-app/src/index.js | splunk/splunk-sdk-javascript | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
ReactDOM.render(
<React.StrictMode>
<App />
</React.StrictMode>,
document.getElementById('root')
);
// If you want your app to work offline and load faster, you can change
// unregister() to register() below. Note this comes with some pitfalls.
// Learn more about service workers: https://bit.ly/CRA-PWA
serviceWorker.unregister();
|
website/src/components/title.js | explosion/spaCy | import React from 'react'
import PropTypes from 'prop-types'
import classNames from 'classnames'
import Button from './button'
import Tag from './tag'
import { OptionalLink } from './link'
import { InlineCode } from './code'
import { H1, Label, InlineList, Help } from './typography'
import Icon from './icon'
import classes from '../styles/title.module.sass'
const MetaItem = ({ label, url, children, help }) => (
<span>
<Label className={classes.label}>{label}:</Label>
<OptionalLink to={url}>{children}</OptionalLink>
{help && (
<>
{' '}
<Help>{help}</Help>
</>
)}
</span>
)
export default function Title({
id,
title,
tag,
version,
teaser,
source,
image,
apiDetails,
children,
...props
}) {
const hasApiDetails = Object.values(apiDetails || {}).some(v => v)
const metaIconProps = { className: classes.metaIcon, width: 18 }
return (
<header className={classes.root}>
{(image || source) && (
<div className={classes.corner}>
{source && (
<Button to={source} icon="code">
Source
</Button>
)}
{image && (
<div className={classes.image}>
<img src={image} width={100} height={100} alt="" />
</div>
)}
</div>
)}
<H1 className={classes.h1} id={id} {...props}>
{title}
</H1>
{(tag || version) && (
<div className={classes.tags}>
{tag && <Tag spaced>{tag}</Tag>}
{version && (
<Tag variant="new" spaced>
{version}
</Tag>
)}
</div>
)}
{hasApiDetails && (
<InlineList Component="div" className={classes.teaser}>
{apiDetails.stringName && (
<MetaItem
label="String name"
//help="String name of the component to use with nlp.add_pipe"
>
<InlineCode>{apiDetails.stringName}</InlineCode>
</MetaItem>
)}
{apiDetails.baseClass && (
<MetaItem label="Base class" url={apiDetails.baseClass.slug}>
<InlineCode>{apiDetails.baseClass.title}</InlineCode>
</MetaItem>
)}
{apiDetails.trainable != null && (
<MetaItem label="Trainable">
<span aria-label={apiDetails.trainable ? 'yes' : 'no'}>
{apiDetails.trainable ? (
<Icon name="yes" variant="success" {...metaIconProps} />
) : (
<Icon name="no" {...metaIconProps} />
)}
</span>
</MetaItem>
)}
</InlineList>
)}
{teaser && <div className={classNames('heading-teaser', classes.teaser)}>{teaser}</div>}
{children}
</header>
)
}
Title.propTypes = {
title: PropTypes.string,
tag: PropTypes.string,
teaser: PropTypes.node,
source: PropTypes.string,
image: PropTypes.string,
children: PropTypes.node,
}
|
IQMail_App/src/components/common/Header.js | victorditadi/IQApp | import React from 'react';
import { Text, View } from 'react-native';
const Header = (props) => {
const { textStyle, viewStyle } = styles;
return (
<View style={viewStyle}>
<Text style={textStyle}>{props.headerText}</Text>
</View>
);
};
const styles = {
viewStyle: {
backgroundColor: '#F8F8F8',
justifyContent: 'center',
alignItems: 'center',
height: 60,
paddingTop: 15,
shadowColor: '#000',
shadowOffset: { width: 0, height: 2 },
shadowOpacity: 0.2,
elevation: 2,
position: 'relative'
},
textStyle: {
fontSize: 20
}
};
export { Header };
|
node_modules/react-bootstrap/es/Accordion.js | WatkinsSoftwareDevelopment/HowardsBarberShop | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PanelGroup from './PanelGroup';
var Accordion = function (_React$Component) {
_inherits(Accordion, _React$Component);
function Accordion() {
_classCallCheck(this, Accordion);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Accordion.prototype.render = function render() {
return React.createElement(
PanelGroup,
_extends({}, this.props, { accordion: true }),
this.props.children
);
};
return Accordion;
}(React.Component);
export default Accordion; |
app/javascript/mastodon/features/standalone/community_timeline/index.js | PlantsNetwork/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import StatusListContainer from '../../ui/containers/status_list_container';
import {
refreshCommunityTimeline,
expandCommunityTimeline,
} from '../../../actions/timelines';
import Column from '../../../components/column';
import ColumnHeader from '../../../components/column_header';
import { defineMessages, injectIntl } from 'react-intl';
import { connectCommunityStream } from '../../../actions/streaming';
const messages = defineMessages({
title: { id: 'standalone.public_title', defaultMessage: 'A look inside...' },
});
@connect()
@injectIntl
export default class CommunityTimeline extends React.PureComponent {
static propTypes = {
dispatch: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
};
handleHeaderClick = () => {
this.column.scrollTop();
}
setRef = c => {
this.column = c;
}
componentDidMount () {
const { dispatch } = this.props;
dispatch(refreshCommunityTimeline());
this.disconnect = dispatch(connectCommunityStream());
}
componentWillUnmount () {
if (this.disconnect) {
this.disconnect();
this.disconnect = null;
}
}
handleLoadMore = () => {
this.props.dispatch(expandCommunityTimeline());
}
render () {
const { intl } = this.props;
return (
<Column ref={this.setRef}>
<ColumnHeader
icon='users'
title={intl.formatMessage(messages.title)}
onClick={this.handleHeaderClick}
/>
<StatusListContainer
timelineId='community'
loadMore={this.handleLoadMore}
scrollKey='standalone_public_timeline'
trackScroll={false}
/>
</Column>
);
}
}
|
src/containers/DevTools.js | juanda99/react-redux-material-ui | import React from 'react'
import { createDevTools } from 'redux-devtools'
import LogMonitor from 'redux-devtools-log-monitor'
import DockMonitor from 'redux-devtools-dock-monitor'
export default createDevTools(
<DockMonitor
toggleVisibilityKey='ctrl-x'
changePositionKey='ctrl-q' >
<LogMonitor />
</DockMonitor>
)
|
src/components/Menu/Menu.js | MarynaHapon/Data-root-react | import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Menu.css';
import Navigation from '../Navigation'
import Link from '../Link';
import logoUrl from './logo-small.svg';
class Menu extends React.Component {
render() {
return (
<div className={s.root}>
<div className={s.container}>
<div className={s.wrapper}>
<div>
<img src={logoUrl} srcSet={`${logoUrl}`} width="48" height="133" alt="logo" />
</div>
<div className={s.textWrapper}>
<span className={s.menuTitle}>Мастерня</span>
<div>
<a className={s.phone} href="tel:+380664455900">+38 066 445 59 00</a>
<p className={s.address}>м. Мукачево, вул. Переяславська, 1</p>
</div>
</div>
</div>
<div>
<Navigation />
</div>
</div>
</div>
);
}
}
export default withStyles(s)(Menu); |
app/javascript/mastodon/features/notifications/components/column_settings.js | SerCom-KC/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { FormattedMessage } from 'react-intl';
import ClearColumnButton from './clear_column_button';
import SettingToggle from './setting_toggle';
export default class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
pushSettings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
onClear: PropTypes.func.isRequired,
};
onPushChange = (path, checked) => {
this.props.onChange(['push', ...path], checked);
}
render () {
const { settings, pushSettings, onChange, onClear } = this.props;
const alertStr = <FormattedMessage id='notifications.column_settings.alert' defaultMessage='Desktop notifications' />;
const showStr = <FormattedMessage id='notifications.column_settings.show' defaultMessage='Show in column' />;
const soundStr = <FormattedMessage id='notifications.column_settings.sound' defaultMessage='Play sound' />;
const showPushSettings = pushSettings.get('browserSupport') && pushSettings.get('isSubscribed');
const pushStr = showPushSettings && <FormattedMessage id='notifications.column_settings.push' defaultMessage='Push notifications' />;
const pushMeta = showPushSettings && <FormattedMessage id='notifications.column_settings.push_meta' defaultMessage='This device' />;
return (
<div>
<div className='column-settings__row'>
<ClearColumnButton onClick={onClear} />
</div>
<div role='group' aria-labelledby='notifications-follow'>
<span id='notifications-follow' className='column-settings__section'><FormattedMessage id='notifications.column_settings.follow' defaultMessage='New followers:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'follow']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'follow']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'follow']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'follow']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-favourite'>
<span id='notifications-favourite' className='column-settings__section'><FormattedMessage id='notifications.column_settings.favourite' defaultMessage='Favourites:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'favourite']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'favourite']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'favourite']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'favourite']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-mention'>
<span id='notifications-mention' className='column-settings__section'><FormattedMessage id='notifications.column_settings.mention' defaultMessage='Mentions:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'mention']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'mention']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'mention']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'mention']} onChange={onChange} label={soundStr} />
</div>
</div>
<div role='group' aria-labelledby='notifications-reblog'>
<span id='notifications-reblog' className='column-settings__section'><FormattedMessage id='notifications.column_settings.reblog' defaultMessage='Boosts:' /></span>
<div className='column-settings__row'>
<SettingToggle prefix='notifications_desktop' settings={settings} settingPath={['alerts', 'reblog']} onChange={onChange} label={alertStr} />
{showPushSettings && <SettingToggle prefix='notifications_push' settings={pushSettings} settingPath={['alerts', 'reblog']} meta={pushMeta} onChange={this.onPushChange} label={pushStr} />}
<SettingToggle prefix='notifications' settings={settings} settingPath={['shows', 'reblog']} onChange={onChange} label={showStr} />
<SettingToggle prefix='notifications' settings={settings} settingPath={['sounds', 'reblog']} onChange={onChange} label={soundStr} />
</div>
</div>
</div>
);
}
}
|
src/svg-icons/communication/business.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationBusiness = (props) => (
<SvgIcon {...props}>
<path d="M12 7V3H2v18h20V7H12zM6 19H4v-2h2v2zm0-4H4v-2h2v2zm0-4H4V9h2v2zm0-4H4V5h2v2zm4 12H8v-2h2v2zm0-4H8v-2h2v2zm0-4H8V9h2v2zm0-4H8V5h2v2zm10 12h-8v-2h2v-2h-2v-2h2v-2h-2V9h8v10zm-2-8h-2v2h2v-2zm0 4h-2v2h2v-2z"/>
</SvgIcon>
);
CommunicationBusiness = pure(CommunicationBusiness);
CommunicationBusiness.displayName = 'CommunicationBusiness';
CommunicationBusiness.muiName = 'SvgIcon';
export default CommunicationBusiness;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.