path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/svg-icons/maps/flight.js | mmrtnz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsFlight = (props) => (
<SvgIcon {...props}>
<path d="M10.18 9"/><path d="M21 16v-2l-8-5V3.5c0-.83-.67-1.5-1.5-1.5S10 2.67 10 3.5V9l-8 5v2l8-2.5V19l-2 1.5V22l3.5-1 3.5 1v-1.5L13 19v-5.5l8 2.5z"/>
</SvgIcon>
);
MapsFlight = pure(MapsFlight);
MapsFlight.displayName = 'MapsFlight';
MapsFlight.muiName = 'SvgIcon';
export default MapsFlight;
|
src/stories/eventrow.js | codefordenver/encorelink | import React from 'react';
import { storiesOf } from '@storybook/react';
import { withKnobs, boolean, date, text } from '@storybook/addon-knobs/react';
import { withInfo } from '@storybook/addon-info';
import EventRow from '../components/EventRow';
storiesOf('EventRow', module)
.addDecorator(withKnobs)
.add(
'Event row with customizable props',
withInfo('Check the knobs tab in the panel below to customize the props for this component')(() => (
<EventRow
hideCalendar={boolean('hide calendar', false)}
event={{
date: date('data.date', new Date('Jan 1, 2018 7:00 pm MST')),
endDate: date('data.endDate', new Date('Jan 1, 2018 9:00 pm MST')),
id: 5,
location: text('data.location', 'denver'),
name: text('data.name', 'music')
}}
/>
))
);
|
docs/src/examples/modules/Embed/Types/EmbedExampleVimeo.js | Semantic-Org/Semantic-UI-React | import React from 'react'
import { Embed } from 'semantic-ui-react'
const EmbedExampleVimeo = () => (
<Embed
id='125292332'
placeholder='/images/vimeo-example.jpg'
source='vimeo'
/>
)
export default EmbedExampleVimeo
|
internals/templates/containers/HomePage/index.js | FlorianVoct/monPropreMix | /*
* HomePage
*
* This is the first thing users see of our App, at the '/' route
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import { FormattedMessage } from 'react-intl';
import messages from './messages';
export default class HomePage extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/devtools/createDevToolsWindow.js | ramirezd42/schmix | /* eslint-disable */
import React from 'react';
import { render } from 'react-dom';
import DevTools from './DevTools';
/*
* Puts Redux DevTools into a separate window.
* Based on https://gist.github.com/tlrobinson/1e63d15d3e5f33410ef7#gistcomment-1560218.
*/
export default function createDevToolsWindow(store) {
// Give it a name so it reuses the same window
// const name = 'Redux DevTools';
// const win = window.open(
// null,
// name,
// 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no,width=637,height=345'
// );
//
// if (!win) {
// console.error(
// 'Couldn\'t open Redux DevTools due to a popup blocker. ' +
// 'Please disable the popup blocker for the current page.'
// );
// return;
// }
//
// Reload in case it's reusing the same window with the old content.
// win.location.reload();
// Set visible Window title.
// win.document.title = name;
// Wait a little bit for it to reload, then render.
// setTimeout(() => render(
// <DevTools store={store}/>,
// win.document.body.appendChild(document.createElement('div'))
// ), 10);
}
|
step4-router/app/js/components/Page1.js | jintoppy/react-training | import React from 'react';
class Page1 extends React.Component{
render(){
return ( < div >
This is page1
<button onClick={this.goHome.bind(this)}>Go to Home Page</button>
< /div>);
}
goHome(){
this.props.history.pushState(null,'/');
}
}
export default Page1;
|
src/svg-icons/social/pages.js | frnk94/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPages = (props) => (
<SvgIcon {...props}>
<path d="M3 5v6h5L7 7l4 1V3H5c-1.1 0-2 .9-2 2zm5 8H3v6c0 1.1.9 2 2 2h6v-5l-4 1 1-4zm9 4l-4-1v5h6c1.1 0 2-.9 2-2v-6h-5l1 4zm2-14h-6v5l4-1-1 4h5V5c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
SocialPages = pure(SocialPages);
SocialPages.displayName = 'SocialPages';
SocialPages.muiName = 'SvgIcon';
export default SocialPages;
|
src/BootstrapMixin.js | erictherobot/react-bootstrap | import React from 'react';
import styleMaps from './styleMaps';
import CustomPropTypes from './utils/CustomPropTypes';
const BootstrapMixin = {
propTypes: {
/**
* bootstrap className
* @private
*/
bsClass: CustomPropTypes.keyOf(styleMaps.CLASSES),
/**
* Style variants
* @type {("default"|"primary"|"success"|"info"|"warning"|"danger"|"link")}
*/
bsStyle: React.PropTypes.oneOf(styleMaps.STYLES),
/**
* Size variants
* @type {("xsmall"|"small"|"medium"|"large"|"xs"|"sm"|"md"|"lg")}
*/
bsSize: CustomPropTypes.keyOf(styleMaps.SIZES)
},
getBsClassSet() {
let classes = {};
let bsClass = this.props.bsClass && styleMaps.CLASSES[this.props.bsClass];
if (bsClass) {
classes[bsClass] = true;
let prefix = bsClass + '-';
let bsSize = this.props.bsSize && styleMaps.SIZES[this.props.bsSize];
if (bsSize) {
classes[prefix + bsSize] = true;
}
if (this.props.bsStyle) {
if (styleMaps.STYLES.indexOf(this.props.bsStyle) >= 0) {
classes[prefix + this.props.bsStyle] = true;
} else {
classes[this.props.bsStyle] = true;
}
}
}
return classes;
},
prefixClass(subClass) {
return styleMaps.CLASSES[this.props.bsClass] + '-' + subClass;
}
};
export default BootstrapMixin;
|
src/container/channelInfo.js | thipokKub/Clique-WebFront-Personnal | import React, { Component } from 'react';
import './css/eventDetail2.css'
import * as facultyMap from '../actions/facultyMap';
import axios from 'axios';
import { hostname } from '../actions/index';
import ReactLoading from 'react-loading';
import './css/channelInfostyle.css';
//https://codepen.io/bh/pen/JBlCc
let useCls = " toggle-vis";
const codeList = facultyMap.getCodeList();
let index = 0;
const defaultState = {
'title': null,
'about': null,
'video': null,
'channel': null,
'location': null,
'date_start': null,
'expire': null,
'date_end': null,
'picture': null,
'picture_large': null,
'year_require': null,
'faculty_require': null,
'tags': null,
'forms': null,
'isLoading': true,
'error': null
}
class channelInfo extends Component {
constructor(props) {
super(props);
this.onBtnClick = this.onBtnClick.bind(this);
this.onResetPopup = this.onResetPopup.bind(this);
this.onGetInfo = this.onGetInfo.bind(this);
this.state = defaultState;
}
onExit() {
this.props.onToggle();
}
componentDidMount() {
this.onResetPopup();
this.onGetInfo();
}
componentDidUpdate() {
console.log(this.state);
}
onGetInfo() {
this.setState({
...this.state,
'isLoading': true
});
axios.get(`${hostname}event?id=${this.props.eventId}`).then((data) => {
let rObj = {
...defaultState,
...data.data,
isLoading: false
}
this.setState(rObj);
this.onResetPopup();
return data.data;
}).then((event) => {
axios.get(`${hostname}channel?id=${event.channel}&stat=false`).then((res) => {
this.setState({
...this.state,
'channel': res.data
});
this.onResetPopup();
})
}).catch((error) => {
this.setState({
...this.state,
'error': 'Oh! Ow! Something went wrong. Please check your internet connection',
'isLoading': false
});
})
}
onResetPopup() {
Object.keys(this.refs).forEach((key) => {
if(!this.refs[key].className.includes(useCls)) this.refs[key].className += useCls;
})
}
onBtnClick(refName) {
if(this.refs[refName].className.includes(useCls)) {
this.onResetPopup();
this.refs[refName].className = this.refs[refName].className.replace(useCls, "");
} else {
this.refs[refName].className += useCls;
}
}
render() {
let eventName = (
<div className="event-name">
<h2>{this.state.title}</h2>
<div className="flex">
<img data-icon="channel-icon" alt="channel-icon" /><span> {this.state.channel_name}</span>
</div>
</div>
);
const isAdmin = (this.props.isAdmin) ? this.props.isAdmin : false;
let adminComponent = (
<div>
<div className="flex">
<div className="btn-top">EDIT</div>
<div className="btn-top">PARTICIPANTS LIST</div>
</div>
<p className="hr" />
</div>
)
let content = (
<div>
<div className="top-moving">
<div className="toggle">
{eventName}
</div>
<img className="chan-img" href="../../resource/images/poster_dummy/dummyProflie.png"/>
<div className="column">
<div className="toggle-not">
{eventName}
</div>
<div className="to-right" >
<button alt="btn-interest">INTEREST</button>
</div>
</div>
</div>
<p className="hr"></p>
<div className="event-bio">
<h3 className="display-none">Bio</h3>
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque id ipsum orci. Aliquam erat volutpat. Sed in erat quis mi laoreet vestibulum. Fusce vitae tempor nisi. Fusce aliquam dolor mi, sit amet egestas ex imperdiet fringilla. Nullam nisl quam, convallis vitae viverra in, lacinia nec lectus. Praesent nibh metus, luctus nec tortor sit amet, hendrerit congue elit. Aliquam erat volutpat. Quisque ex arcu, iaculis blandit arcu at, molestie mattis mauris. Etiam in tortor nec metus eleifend euismod. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus.
</p>
<p>
Nulla congue tincidunt sem non ullamcorper. Etiam mattis auctor tellus. Aenean ultricies lacus at elementum fermentum. Nunc hendrerit neque et nibh sodales, a malesuada orci euismod. Aliquam a pharetra purus, nec porta augue. Donec in elit non arcu commodo tristique. Integer nunc ligula, tristique eget nisl non, consectetur pharetra lacus.
</p>
<p>
Cras pellentesque enim justo, id pharetra neque pulvinar quis. Suspendisse a odio lacinia, maximus dolor et, maximus massa. Curabitur dolor nibh, pulvinar imperdiet nunc id, placerat venenatis massa. Donec vitae venenatis nisi. Ut iaculis sem a tempor ullamcorper. Ut aliquam venenatis fermentum. Nam porttitor libero sit amet nisl mattis, sed tincidunt eros tincidunt.
</p>
</div>
</div>
)
if(this.state.isLoading) content = (
<div style={{'fontSize': '30px', 'margin': 'auto', 'color': '#878787', 'textAlign': 'center'}}>
<div style={{'margin': 'auto', 'width': '50px', 'display': 'inline-block', 'position': 'relative', 'top': '12px', 'marginLeft': '5px'}}>
<ReactLoading type={'bars'} color={'#878787'} height='40px' width='40px' />
</div>
Loading
<div style={{'margin': 'auto', 'width': '50px', 'display': 'inline-block', 'position': 'relative', 'top': '12px', 'marginLeft': '5px'}}>
<ReactLoading type={'bars'} color={'#878787'} height='40' width='40' />
</div>
</div>
);
else if(this.state.error) content = (
<div className="Warning-Container">
<div className="Error-Warning-Container">
<div className="Error-Warning">
<span>
{this.state.error}
</span>
</div>
</div>
<button onClick={this.onExit.bind(this)}>
Okay
</button>
</div>
)
return (
<div className="modal-container">
<article className="event-detail-fix basic-card-no-glow">
<button className="invisible square-round" role="event-exit" onClick={this.onExit.bind(this)}>
<img src="../../resource/images/X.svg" />
</button>
{(isAdmin) ? (adminComponent) : null}
{content}
</article>
<div className="background-overlay"/>
</div>
);
}
}
channelInfo.defaultProps = {
'eventId': '594bf476e374d100140f04ec'
}
export default channelInfo;
|
addons/storyshots/stories/required_with_context/Welcome.stories.js | jribeiro/storybook | import React from 'react';
import { storiesOf } from '@storybook/react'; // eslint-disable-line
import { linkTo } from '@storybook/addon-links'; // eslint-disable-line
import { Welcome } from '@storybook/react/demo';
storiesOf('Welcome', module).add('to Storybook', () => <Welcome showApp={linkTo('Button')} />);
|
src/shared/element-react/dist/npm/es6/libs/component/index.js | thundernet8/Elune-WWW | 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 PropTypes from 'prop-types';
import classnames from 'classnames';
var Component = function (_React$Component) {
_inherits(Component, _React$Component);
function Component() {
_classCallCheck(this, Component);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
Component.prototype.classNames = function classNames() {
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return classnames(args);
};
Component.prototype.className = function className() {
for (var _len2 = arguments.length, args = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
args[_key2] = arguments[_key2];
}
return this.classNames.apply(this, args.concat([this.props.className]));
};
Component.prototype.style = function style(args) {
return Object.assign({}, args, this.props.style);
};
return Component;
}(React.Component);
export default Component;
Component.propTypes = {
className: PropTypes.string,
style: PropTypes.object
}; |
graphwalker-studio/src/main/js/Application.js | KristianKarl/graphwalker-project | import React, { Component } from 'react';
import { connect } from "react-redux";
import Container from "./components/container";
import StatusBar from "./components/statusbar";
import SideMenu from "./components/sidemenu";
import Editor from "./components/editor";
import ConfigPanel from "./components/configpanel";
import { Divider } from "@blueprintjs/core";
import Banner from "./graphwalker.inline.svg";
import PanelGroup from "react-panelgroup";
import './style.css';
class Application extends Component {
render() {
if (this.props.showBanner) {
return (
<Container column>
<Container>
<SideMenu/>
<Banner className="banner"/>
</Container>
</Container>
)
} else {
return (
<Container column>
<Container>
<SideMenu/>
{this.props.showProperties ?
<PanelGroup borderColor="#F3F3F3" panelWidths={[{ size: 400, resize: "dynamic" }, { resize: "stretch" }]}>
<ConfigPanel/>
<Editor/>
</PanelGroup>
:
<PanelGroup borderColor="#F3F3F3" panelWidths={[{ resize: "stretch" }]}>
<Editor/>
</PanelGroup>
}
</Container>
<StatusBar/>
</Container>
)
}
}
}
const mapStateToProps = ({ test: { models }, editor: { showProperties }}) => {
return {
showBanner: models.length === 0,
showProperties
}
};
export default connect(mapStateToProps)(Application);
|
src/components/Error.js | humancatfood/bat-fe-test | import React from 'react';
import PropTypes from 'prop-types';
import Snackbar from '@material-ui/core/Snackbar';
import Alert from '@material-ui/lab/Alert';
const Error = ({ onClose, severity='error', children }) => (
<Snackbar open autoHideDuration={6000} onClose={onClose}>
<Alert onClose={onClose} severity={severity}>{children}</Alert>
</Snackbar>
);
Error.propTypes = {
onClose: PropTypes.func.isRequired,
children: PropTypes.oneOfType([
PropTypes.element,
PropTypes.string,
]),
severity: PropTypes.string,
};
export default Error;
|
internals/templates/app.js | s0enke/react-boilerplate | /**
* app.js
*
* This is the entry file for the application, only setup and boilerplate
* code.
*/
import 'babel-polyfill';
/* eslint-disable import/no-unresolved */
// Load the manifest.json file and the .htaccess file
import '!file?name=[name].[ext]!./manifest.json';
import 'file?name=[name].[ext]!./.htaccess';
/* eslint-enable import/no-unresolved */
// Import all the third party stuff
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { applyRouterMiddleware, Router, browserHistory } from 'react-router';
import { syncHistoryWithStore } from 'react-router-redux';
import useScroll from 'react-router-scroll';
import LanguageProvider from 'containers/LanguageProvider';
import configureStore from './store';
// Import i18n messages
import { translationMessages } from './i18n';
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
// Create redux store with history
// this uses the singleton browserHistory provided by react-router
// Optionally, this could be changed to leverage a created history
// e.g. `const browserHistory = useRouterHistory(createBrowserHistory)();`
const initialState = {};
const store = configureStore(initialState, browserHistory);
// Sync history and store, as the react-router-redux reducer
// is under the non-default key ("routing"), selectLocationState
// must be provided for resolving how to retrieve the "route" in the state
import { selectLocationState } from 'containers/App/selectors';
const history = syncHistoryWithStore(browserHistory, store, {
selectLocationState: selectLocationState(),
});
// Set up the router, wrapping all Routes in the App component
import App from 'containers/App';
import createRoutes from './routes';
const rootRoute = {
component: App,
childRoutes: createRoutes(store),
};
const render = (translatedMessages) => {
ReactDOM.render(
<Provider store={store}>
<LanguageProvider messages={translatedMessages}>
<Router
history={history}
routes={rootRoute}
render={
// Scroll to top when going to a new page, imitating default browser
// behaviour
applyRouterMiddleware(useScroll())
}
/>
</LanguageProvider>
</Provider>,
document.getElementById('app')
);
};
// Hot reloadable translation json files
if (module.hot) {
// modules.hot.accept does not accept dynamic dependencies,
// have to be constants at compile-time
module.hot.accept('./i18n', () => {
render(translationMessages);
});
}
// Chunked polyfill for browsers without Intl support
if (!window.Intl) {
Promise.all([
System.import('intl'),
System.import('intl/locale-data/jsonp/en.js'),
]).then(() => render(translationMessages));
} else {
render(translationMessages);
}
// Install ServiceWorker and AppCache in the end since
// it's not most important operation and if main code fails,
// we do not want it installed
import { install } from 'offline-plugin/runtime';
install();
|
imports/ui/components/manage/manage-parent-categories.js | irvinlim/free4all | import React from 'react';
import Formsy from 'formsy-react';
import { Card, CardTitle, CardText, CardActions } from 'material-ui/Card';
import { Table, TableBody, TableHeader, TableHeaderColumn, TableRow, TableRowColumn } from 'material-ui/Table';
import Subheader from 'material-ui/Subheader';
import IconButton from 'material-ui/IconButton';
import FlatButton from 'material-ui/FlatButton';
import { SortableContainer, SortableElement, SortableHandle, arrayMove } from 'react-sortable-hoc';
import { ParentCategories } from '../../../api/parent-categories/parent-categories';
import { insertParentCategory, updateParentCategory, removeParentCategory, reorderParentCategory } from '../../../api/parent-categories/methods';
import * as Colors from 'material-ui/styles/colors';
import * as UsersHelper from '../../../util/users';
import * as IconsHelper from '../../../util/icons';
import * as LayoutHelper from '../../../util/layout';
import * as FormsHelper from '../../../util/forms';
const Handle = SortableHandle(() => (
<IconButton tooltip="Drag to reorder" onTouchTap={ event => event.preventDefault() }>
{ IconsHelper.icon("menu", { color: Colors.grey700, fontSize: 18 }) }
</IconButton>
));
const SortableItem = SortableElement(({ self, parentCat }) => {
if (!parentCat)
return null;
else if (parentCat._id == self.state.currentlyEditing)
return <EditRow self={self} parentCat={parentCat} />;
else
return <ItemRow self={self} parentCat={parentCat} />;
});
const ItemRow = ({ self, parentCat }) => (
<div className="sortable-row flex-row" data-id={ parentCat._id }>
<div className="col col-xs-2 col-sm-1 col-center">
{ self.state.currentlyEditing ? null : <Handle /> }
</div>
<div className="col col-xs-7 col-sm-9">
<div className="flex-row nopad">
<div className="col col-xs-12 col-sm-6">
{ parentCat.name }
</div>
<div className="col col-xs-12 col-sm-6">
{ IconsHelper.icon(parentCat.iconClass, { color: Colors.grey700, fontSize: 16, marginRight: 10 }) }
{ parentCat.iconClass }
</div>
</div>
</div>
<div className="col col-xs-3 col-sm-2 col-right">
<IconButton className="row-action" onTouchTap={ self.handleSelectEdit.bind(self) } tooltip="Edit">
{ IconsHelper.icon("edit", { color: Colors.grey700, fontSize: 18 }) }
</IconButton>
<IconButton className="row-action" onTouchTap={ self.handleDelete.bind(self) } tooltip="Delete">
{ IconsHelper.icon("delete", { color: Colors.grey700, fontSize: 18 }) }
</IconButton>
</div>
</div>
);
const EditRow = ({ self, parentCat }) => (
<Formsy.Form id="edit-row" onValidSubmit={ self.handleSaveEdit(parentCat ? parentCat._id : null) }>
<div className="sortable-row flex-row" data-id={ parentCat ? parentCat._id : null }>
<div className="col col-xs-7 col-sm-9 col-xs-offset-2 col-sm-offset-1">
<div className="flex-row nopad">
<div className="col col-xs-12 col-sm-6">
{ FormsHelper.makeTextField({
self, name: "name", required: true, style: { fontSize: 14 },
validationErrors: { isDefaultRequiredValue: "Please enter a category name." },
}) }
</div>
<div className="col col-xs-12 col-sm-6">
{ FormsHelper.makeTextField({
self, name: "iconClass", required: true, style: { fontSize: 14 },
validationErrors: { isDefaultRequiredValue: "Please enter the className for the icon." },
}) }
</div>
</div>
</div>
<div className="col col-xs-3 col-sm-2 col-right">
<IconButton type="submit" className="row-action" tooltip="Save" formNoValidate>
{ IconsHelper.icon("save", { color: Colors.grey700, fontSize: 18 }) }
</IconButton>
<IconButton className="row-action" onTouchTap={ self.handleCancelEdit.bind(self) } tooltip="Cancel edit">
{ IconsHelper.icon("cancel", { color: Colors.grey700, fontSize: 18 }) }
</IconButton>
</div>
</div>
</Formsy.Form>
);
const SortableList = SortableContainer(({ self, items }) => (
<div className="sortable-list-table">
<div className="sortable-list-header flex-row hidden-xs">
<div className="col col-xs-8 col-sm-9 col-xs-offset-1">
<div className="flex-row nopad">
<div className="col col-xs-12 col-sm-6">Category Name</div>
<div className="col col-xs-12 col-sm-6">IconClass</div>
</div>
</div>
</div>
<div className="sortable-list-body">
{ items.map((parentCatId, index) => {
const parentCat = ParentCategories.findOne(parentCatId);
return parentCat ? <SortableItem key={index} index={index} parentCat={ parentCat } self={self} /> : null;
}) }
{ self.state.currentlyEditing == "new" ? <EditRow self={self} parentCat={null} /> : null }
</div>
<div className="sortable-list-footer flex-row">
<div className="col col-xs-12 col-right">
<FlatButton label="Add New" onTouchTap={ self.handleAddNew.bind(self) } />
</div>
</div>
</div>
));
export class ManageParentCategories extends React.Component {
constructor(props) {
super(props);
this.state = {
submitted: false,
currentlyEditing: null,
};
}
onSortEnd({ oldIndex, newIndex }) {
if (oldIndex == newIndex)
return;
const oldIndexCatId = this.props.parentCategories[oldIndex]._id;
const newIndexCat = this.props.parentCategories[newIndex];
reorderParentCategory.call({ _id: oldIndexCatId, newIndex: newIndexCat.relativeOrder }, FormsHelper.bertAlerts("Parent categories reordered."));
}
handleAddNew() {
this.setState({ currentlyEditing: "new" });
}
handleSelectEdit(event) {
event.preventDefault();
const parentCatId = $(event.target).closest(".sortable-row").data('id');
this.selectEditRow(parentCatId);
}
handleCancelEdit(event) {
event.preventDefault();
const parentCatId = $(event.target).closest(".sortable-row").data('id');
this.selectEditRow(null, parentCatId);
}
handleSaveEdit(parentCatId) {
return () => {
const name = this.state.name;
const iconClass = this.state.iconClass;
if (!parentCatId) {
const maxOrderCat = ParentCategories.findOne({}, { sort: { relativeOrder: -1 } });
const relativeOrder = maxOrderCat ? maxOrderCat.relativeOrder + 1 : 0;
insertParentCategory.call({ name, iconClass, relativeOrder }, FormsHelper.bertAlerts("Parent category added."));
} else {
updateParentCategory.call({ _id: parentCatId, name, iconClass }, FormsHelper.bertAlerts("Parent category updated."));
}
this.selectEditRow(null);
};
}
handleDelete(event) {
event.preventDefault();
const _id = $(event.target).closest(".sortable-row").data('id');
removeParentCategory.call({ _id }, FormsHelper.bertAlerts("Parent category removed."));
}
selectEditRow(id) {
const parentCat = ParentCategories.findOne(id);
if (!parentCat) {
this.setState({
currentlyEditing: null,
name: null,
iconClass: null,
});
} else {
this.setState({
currentlyEditing: id,
name: parentCat.name,
iconClass: parentCat.iconClass
});
}
}
render() {
return (
<div className="flex-row">
<div className="col col-xs-12 nopad">
<Card className="card">
<CardTitle title="Manage Parent Categories" />
<CardText>
<div className="sortable-list">
<div className="flex-row nopad">
<div className="col col-xs-12 nopad">
<SortableList
self={this}
useDragHandle={true}
items={ this.props.parentCategories }
onSortEnd={ this.onSortEnd.bind(this) }
lockToContainerEdges={true}
helperClass="sortable-active"
lockAxis="y"
lockOffset={0} />
</div>
</div>
</div>
</CardText>
</Card>
</div>
</div>
);
}
}
|
src/renderer/bootstrap.js | eqot/bipresent | 'use strict';
import polyfill from 'babel/polyfill';
import React from 'react';
import ReactDOM from 'react-dom';
import {Main} from './components/main';
ReactDOM.render(React.createElement(Main), document.getElementById('app'));
var ipc = require('ipc');
ipc.on('toggle-transparent', function () {
document.querySelector('body').classList.toggle('full-transparent');
});
ipc.on('toggle-info', function () {
document.querySelector('body').classList.toggle('info-visible');
});
|
public/src/demo/ExposeComponentFunctions.js | codelegant/react-action | /**
* Author: 赖传峰
* Email: laichuanfeng@hotmail.com
* Homepage: http://laichuanfeng.com/
* Date: 2016/7/17
*/
import React from 'react';
class Todo extends React.Component {
animate() {
console.log('Pretend %s is animating', this.props.title);
}
render() {
return <div onClick={this.props.onClick} >{this.props.title}</div>;
}
}
export default class Todos extends React.Component {
constructor() {
super();
this.state = { items: ['Apple', 'Banana', 'Cranberry'] };
this.handleClick = this.handleClick.bind(this);
}
handleClick(index) {
const items = this.state.items.filter((item, i)=>index !== i);
this.setState({ items }, ()=> {
if (items.length === 1) {
this.refs.item0.animate();
}
});
}
render() {
return (
<div>
{this.state.items.map((item, i)=><Todo onClick={this.handleClick}
key={i}
title={item}
ref={'item' + i} />)}
</div>
);
}
}
|
src/svg-icons/notification/event-available.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationEventAvailable = (props) => (
<SvgIcon {...props}>
<path d="M16.53 11.06L15.47 10l-4.88 4.88-2.12-2.12-1.06 1.06L10.59 17l5.94-5.94zM19 3h-1V1h-2v2H8V1H6v2H5c-1.11 0-1.99.9-1.99 2L3 19c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V8h14v11z"/>
</SvgIcon>
);
NotificationEventAvailable = pure(NotificationEventAvailable);
NotificationEventAvailable.displayName = 'NotificationEventAvailable';
NotificationEventAvailable.muiName = 'SvgIcon';
export default NotificationEventAvailable;
|
build/devpanel.js | johnnycoyle/react-rpm | import React from 'react';
import { render } from 'react-dom';
import { AppContainer } from 'react-hot-loader';
import App from './../containers/App';
import 'react-hot-loader/patch';
render(
<AppContainer>
<App />
</AppContainer>, document.getElementById('root')
);
if (module.hot && module.hot.accept('./../containers/App', () => {
render(App)
}));
|
src/svg-icons/maps/local-atm.js | manchesergit/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalAtm = (props) => (
<SvgIcon {...props}>
<path d="M11 17h2v-1h1c.55 0 1-.45 1-1v-3c0-.55-.45-1-1-1h-3v-1h4V8h-2V7h-2v1h-1c-.55 0-1 .45-1 1v3c0 .55.45 1 1 1h3v1H9v2h2v1zm9-13H4c-1.11 0-1.99.89-1.99 2L2 18c0 1.11.89 2 2 2h16c1.11 0 2-.89 2-2V6c0-1.11-.89-2-2-2zm0 14H4V6h16v12z"/>
</SvgIcon>
);
MapsLocalAtm = pure(MapsLocalAtm);
MapsLocalAtm.displayName = 'MapsLocalAtm';
MapsLocalAtm.muiName = 'SvgIcon';
export default MapsLocalAtm;
|
src/SplitButton.js | laran/react-bootstrap | import React from 'react';
import BootstrapMixin from './BootstrapMixin';
import Button from './Button';
import Dropdown from './Dropdown';
import SplitToggle from './SplitToggle';
class SplitButton extends React.Component {
render() {
let {
children,
title,
onClick,
target,
href,
// bsStyle is validated by 'Button' component
bsStyle, // eslint-disable-line
...props } = this.props;
let { disabled } = props;
let button = (
<Button
onClick={onClick}
bsStyle={bsStyle}
disabled={disabled}
target={target}
href={href}
>
{title}
</Button>
);
return (
<Dropdown {...props}>
{button}
<SplitToggle
aria-label={title}
bsStyle={bsStyle}
disabled={disabled}
/>
<Dropdown.Menu>
{children}
</Dropdown.Menu>
</Dropdown>
);
}
}
SplitButton.propTypes = {
...Dropdown.propTypes,
...BootstrapMixin.propTypes,
/**
* @private
*/
onClick() {},
target: React.PropTypes.string,
href: React.PropTypes.string,
/**
* The content of the split button.
*/
title: React.PropTypes.node.isRequired
};
SplitButton.defaultProps = {
disabled: false,
dropup: false,
pullRight: false
};
SplitButton.Toggle = SplitToggle;
export default SplitButton;
|
pnpm-cached/.pnpm-store/1/registry.npmjs.org/react-router/4.1.1/es/Router.js | JamieMason/npm-cache-benchmark | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }
function _possibleConstructorReturn(self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } return call && (typeof call === "object" || typeof call === "function") ? call : self; }
function _inherits(subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; }
import warning from 'warning';
import invariant from 'invariant';
import React from 'react';
import PropTypes from 'prop-types';
/**
* The public API for putting history on context.
*/
var Router = function (_React$Component) {
_inherits(Router, _React$Component);
function Router() {
var _temp, _this, _ret;
_classCallCheck(this, Router);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = _possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {
match: _this.computeMatch(_this.props.history.location.pathname)
}, _temp), _possibleConstructorReturn(_this, _ret);
}
Router.prototype.getChildContext = function getChildContext() {
return {
router: _extends({}, this.context.router, {
history: this.props.history,
route: {
location: this.props.history.location,
match: this.state.match
}
})
};
};
Router.prototype.computeMatch = function computeMatch(pathname) {
return {
path: '/',
url: '/',
params: {},
isExact: pathname === '/'
};
};
Router.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
var _props = this.props,
children = _props.children,
history = _props.history;
invariant(children == null || React.Children.count(children) === 1, 'A <Router> may have only one child element');
// Do this here so we can setState when a <Redirect> changes the
// location in componentWillMount. This happens e.g. when doing
// server rendering using a <StaticRouter>.
this.unlisten = history.listen(function () {
_this2.setState({
match: _this2.computeMatch(history.location.pathname)
});
});
};
Router.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
warning(this.props.history === nextProps.history, 'You cannot change <Router history>');
};
Router.prototype.componentWillUnmount = function componentWillUnmount() {
this.unlisten();
};
Router.prototype.render = function render() {
var children = this.props.children;
return children ? React.Children.only(children) : null;
};
return Router;
}(React.Component);
Router.propTypes = {
history: PropTypes.object.isRequired,
children: PropTypes.node
};
Router.contextTypes = {
router: PropTypes.object
};
Router.childContextTypes = {
router: PropTypes.object.isRequired
};
export default Router; |
node_modules/bs-recipes/recipes/webpack.react-transform-hmr/app/js/main.js | johncorderox/Socialize | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
docs/app/Examples/collections/Grid/Variations/GridExampleColumnCount.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Grid, Image } from 'semantic-ui-react'
const GridExampleColumnCount = () => (
<Grid>
<Grid.Row columns={3}>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
</Grid.Row>
<Grid.Row columns={4}>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
</Grid.Row>
<Grid.Row columns={5}>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
<Grid.Column>
<Image src='/assets/images/wireframe/image.png' />
</Grid.Column>
</Grid.Row>
</Grid>
)
export default GridExampleColumnCount
|
src/components/icons/RainShowerIcon.js | maximgatilin/weathernow | import React from 'react';
export default function RainShowerIcon() {
return (
<svg id="Layer_1" data-name="Layer 1" xmlns="http://www.w3.org/2000/svg" viewBox="0 0 129.97 128.29"><title>rain-shower</title><path d="M1019.64,208.61h0c0-.25,0-0.5,0-0.75a36.25,36.25,0,1,0-72.51,0s0,0,0,.07a29.59,29.59,0,0,0,1.39,59.16h71.12A29.24,29.24,0,1,0,1019.64,208.61Z" transform="translate(-918.91 -171.6)" fill="#939598"/><path d="M932.39,299.9a3.77,3.77,0,0,1-3.19-5.76l29.27-46.83a3.77,3.77,0,0,1,6.39,4l-29.27,46.83A3.76,3.76,0,0,1,932.39,299.9Z" transform="translate(-918.91 -171.6)" fill="#42bfec"/><path d="M993.06,299.9a3.77,3.77,0,0,1-3.19-5.76l20.74-33.19a3.77,3.77,0,0,1,6.39,4l-20.74,33.19A3.76,3.76,0,0,1,993.06,299.9Z" transform="translate(-918.91 -171.6)" fill="#42bfec"/><path d="M961.65,299.9a3.77,3.77,0,0,1-3.2-5.75l41-66.38a3.77,3.77,0,0,1,6.41,4l-41,66.38A3.77,3.77,0,0,1,961.65,299.9Z" transform="translate(-918.91 -171.6)" fill="#42bfec"/></svg>
)
} |
app/javascript/mastodon/features/status/components/detailed_status.js | glitch-soc/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import Avatar from '../../../components/avatar';
import DisplayName from '../../../components/display_name';
import StatusContent from '../../../components/status_content';
import MediaGallery from '../../../components/media_gallery';
import { Link } from 'react-router-dom';
import { injectIntl, defineMessages, FormattedDate } from 'react-intl';
import Card from './card';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Video from '../../video';
import Audio from '../../audio';
import scheduleIdleTask from '../../ui/util/schedule_idle_task';
import classNames from 'classnames';
import Icon from 'mastodon/components/icon';
import AnimatedNumber from 'mastodon/components/animated_number';
import PictureInPicturePlaceholder from 'mastodon/components/picture_in_picture_placeholder';
import EditedTimestamp from 'mastodon/components/edited_timestamp';
const messages = defineMessages({
public_short: { id: 'privacy.public.short', defaultMessage: 'Public' },
unlisted_short: { id: 'privacy.unlisted.short', defaultMessage: 'Unlisted' },
private_short: { id: 'privacy.private.short', defaultMessage: 'Followers-only' },
direct_short: { id: 'privacy.direct.short', defaultMessage: 'Direct' },
});
export default @injectIntl
class DetailedStatus extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
status: ImmutablePropTypes.map,
onOpenMedia: PropTypes.func.isRequired,
onOpenVideo: PropTypes.func.isRequired,
onToggleHidden: PropTypes.func.isRequired,
measureHeight: PropTypes.bool,
onHeightChange: PropTypes.func,
domain: PropTypes.string.isRequired,
compact: PropTypes.bool,
showMedia: PropTypes.bool,
pictureInPicture: ImmutablePropTypes.contains({
inUse: PropTypes.bool,
available: PropTypes.bool,
}),
onToggleMediaVisibility: PropTypes.func,
};
state = {
height: null,
};
handleAccountClick = (e) => {
if (e.button === 0 && !(e.ctrlKey || e.metaKey) && this.context.router) {
e.preventDefault();
this.context.router.history.push(`/@${this.props.status.getIn(['account', 'acct'])}`);
}
e.stopPropagation();
}
handleOpenVideo = (options) => {
this.props.onOpenVideo(this.props.status.getIn(['media_attachments', 0]), options);
}
handleExpandedToggle = () => {
this.props.onToggleHidden(this.props.status);
}
_measureHeight (heightJustChanged) {
if (this.props.measureHeight && this.node) {
scheduleIdleTask(() => this.node && this.setState({ height: Math.ceil(this.node.scrollHeight) + 1 }));
if (this.props.onHeightChange && heightJustChanged) {
this.props.onHeightChange();
}
}
}
setRef = c => {
this.node = c;
this._measureHeight();
}
componentDidUpdate (prevProps, prevState) {
this._measureHeight(prevState.height !== this.state.height);
}
handleModalLink = e => {
e.preventDefault();
let href;
if (e.target.nodeName !== 'A') {
href = e.target.parentNode.href;
} else {
href = e.target.href;
}
window.open(href, 'mastodon-intent', 'width=445,height=600,resizable=no,menubar=no,status=no,scrollbars=yes');
}
render () {
const status = (this.props.status && this.props.status.get('reblog')) ? this.props.status.get('reblog') : this.props.status;
const outerStyle = { boxSizing: 'border-box' };
const { intl, compact, pictureInPicture } = this.props;
if (!status) {
return null;
}
let media = '';
let applicationLink = '';
let reblogLink = '';
let reblogIcon = 'retweet';
let favouriteLink = '';
let edited = '';
if (this.props.measureHeight) {
outerStyle.height = `${this.state.height}px`;
}
if (pictureInPicture.get('inUse')) {
media = <PictureInPicturePlaceholder />;
} else if (status.get('media_attachments').size > 0) {
if (status.getIn(['media_attachments', 0, 'type']) === 'audio') {
const attachment = status.getIn(['media_attachments', 0]);
media = (
<Audio
src={attachment.get('url')}
alt={attachment.get('description')}
duration={attachment.getIn(['meta', 'original', 'duration'], 0)}
poster={attachment.get('preview_url') || status.getIn(['account', 'avatar_static'])}
backgroundColor={attachment.getIn(['meta', 'colors', 'background'])}
foregroundColor={attachment.getIn(['meta', 'colors', 'foreground'])}
accentColor={attachment.getIn(['meta', 'colors', 'accent'])}
height={150}
/>
);
} else if (status.getIn(['media_attachments', 0, 'type']) === 'video') {
const attachment = status.getIn(['media_attachments', 0]);
media = (
<Video
preview={attachment.get('preview_url')}
frameRate={attachment.getIn(['meta', 'original', 'frame_rate'])}
blurhash={attachment.get('blurhash')}
src={attachment.get('url')}
alt={attachment.get('description')}
width={300}
height={150}
inline
onOpenVideo={this.handleOpenVideo}
sensitive={status.get('sensitive')}
visible={this.props.showMedia}
onToggleVisibility={this.props.onToggleMediaVisibility}
/>
);
} else {
media = (
<MediaGallery
standalone
sensitive={status.get('sensitive')}
media={status.get('media_attachments')}
height={300}
onOpenMedia={this.props.onOpenMedia}
visible={this.props.showMedia}
onToggleVisibility={this.props.onToggleMediaVisibility}
/>
);
}
} else if (status.get('spoiler_text').length === 0) {
media = <Card sensitive={status.get('sensitive')} onOpenMedia={this.props.onOpenMedia} card={status.get('card', null)} />;
}
if (status.get('application')) {
applicationLink = <React.Fragment> · <a className='detailed-status__application' href={status.getIn(['application', 'website'])} target='_blank' rel='noopener noreferrer'>{status.getIn(['application', 'name'])}</a></React.Fragment>;
}
const visibilityIconInfo = {
'public': { icon: 'globe', text: intl.formatMessage(messages.public_short) },
'unlisted': { icon: 'unlock', text: intl.formatMessage(messages.unlisted_short) },
'private': { icon: 'lock', text: intl.formatMessage(messages.private_short) },
'direct': { icon: 'envelope', text: intl.formatMessage(messages.direct_short) },
};
const visibilityIcon = visibilityIconInfo[status.get('visibility')];
const visibilityLink = <React.Fragment> · <Icon id={visibilityIcon.icon} title={visibilityIcon.text} /></React.Fragment>;
if (['private', 'direct'].includes(status.get('visibility'))) {
reblogLink = '';
} else if (this.context.router) {
reblogLink = (
<React.Fragment>
<React.Fragment> · </React.Fragment>
<Link to={`/@${status.getIn(['account', 'acct'])}/${status.get('id')}/reblogs`} className='detailed-status__link'>
<Icon id={reblogIcon} />
<span className='detailed-status__reblogs'>
<AnimatedNumber value={status.get('reblogs_count')} />
</span>
</Link>
</React.Fragment>
);
} else {
reblogLink = (
<React.Fragment>
<React.Fragment> · </React.Fragment>
<a href={`/interact/${status.get('id')}?type=reblog`} className='detailed-status__link' onClick={this.handleModalLink}>
<Icon id={reblogIcon} />
<span className='detailed-status__reblogs'>
<AnimatedNumber value={status.get('reblogs_count')} />
</span>
</a>
</React.Fragment>
);
}
if (this.context.router) {
favouriteLink = (
<Link to={`/@${status.getIn(['account', 'acct'])}/${status.get('id')}/favourites`} className='detailed-status__link'>
<Icon id='star' />
<span className='detailed-status__favorites'>
<AnimatedNumber value={status.get('favourites_count')} />
</span>
</Link>
);
} else {
favouriteLink = (
<a href={`/interact/${status.get('id')}?type=favourite`} className='detailed-status__link' onClick={this.handleModalLink}>
<Icon id='star' />
<span className='detailed-status__favorites'>
<AnimatedNumber value={status.get('favourites_count')} />
</span>
</a>
);
}
if (status.get('edited_at')) {
edited = (
<React.Fragment>
<React.Fragment> · </React.Fragment>
<EditedTimestamp statusId={status.get('id')} timestamp={status.get('edited_at')} />
</React.Fragment>
);
}
return (
<div style={outerStyle}>
<div ref={this.setRef} className={classNames('detailed-status', `detailed-status-${status.get('visibility')}`, { compact })}>
<a href={status.getIn(['account', 'url'])} onClick={this.handleAccountClick} className='detailed-status__display-name'>
<div className='detailed-status__display-avatar'><Avatar account={status.get('account')} size={48} /></div>
<DisplayName account={status.get('account')} localDomain={this.props.domain} />
</a>
<StatusContent status={status} expanded={!status.get('hidden')} onExpandedToggle={this.handleExpandedToggle} />
{media}
<div className='detailed-status__meta'>
<a className='detailed-status__datetime' href={status.get('url')} target='_blank' rel='noopener noreferrer'>
<FormattedDate value={new Date(status.get('created_at'))} hour12={false} year='numeric' month='short' day='2-digit' hour='2-digit' minute='2-digit' />
</a>{edited}{visibilityLink}{applicationLink}{reblogLink} · {favouriteLink}
</div>
</div>
</div>
);
}
}
|
examples/03 Nesting/Drag Sources/index.js | numso/react-dnd | import React from 'react';
import Container from './Container';
export default class NestingDragSources {
render() {
return (
<div>
<p>
<b><a href='https://github.com/gaearon/react-dnd/tree/master/examples/03%20Nesting/Drag%20Sources'>Browse the Source</a></b>
</p>
<p>
You can nest the drag sources in one another.
If a nested drag source returns <code>false</code> from <code>canDrag</code>, its parent will be asked, until a draggable source is found and activated.
Only the activated drag source will have its <code>beginDrag()</code> and <code>endDrag()</code> called.
</p>
<Container />
</div>
);
}
} |
app/javascript/mastodon/features/status/index.js | alarky/mastodon | import React from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { fetchStatus } from '../../actions/statuses';
import MissingIndicator from '../../components/missing_indicator';
import DetailedStatus from './components/detailed_status';
import ActionBar from './components/action_bar';
import Column from '../ui/components/column';
import {
favourite,
unfavourite,
reblog,
unreblog,
} from '../../actions/interactions';
import {
replyCompose,
mentionCompose,
} from '../../actions/compose';
import { deleteStatus } from '../../actions/statuses';
import { initReport } from '../../actions/reports';
import { makeGetStatus } from '../../selectors';
import { ScrollContainer } from 'react-router-scroll';
import ColumnBackButton from '../../components/column_back_button';
import StatusContainer from '../../containers/status_container';
import { openModal } from '../../actions/modal';
import { defineMessages, injectIntl } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
const messages = defineMessages({
deleteConfirm: { id: 'confirmations.delete.confirm', defaultMessage: 'Delete' },
deleteMessage: { id: 'confirmations.delete.message', defaultMessage: 'Are you sure you want to delete this status?' },
});
const makeMapStateToProps = () => {
const getStatus = makeGetStatus();
const mapStateToProps = (state, props) => ({
status: getStatus(state, Number(props.params.statusId)),
ancestorsIds: state.getIn(['contexts', 'ancestors', Number(props.params.statusId)]),
descendantsIds: state.getIn(['contexts', 'descendants', Number(props.params.statusId)]),
me: state.getIn(['meta', 'me']),
boostModal: state.getIn(['meta', 'boost_modal']),
deleteModal: state.getIn(['meta', 'delete_modal']),
autoPlayGif: state.getIn(['meta', 'auto_play_gif']),
});
return mapStateToProps;
};
@injectIntl
@connect(makeMapStateToProps)
export default class Status extends ImmutablePureComponent {
static contextTypes = {
router: PropTypes.object,
};
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
status: ImmutablePropTypes.map,
ancestorsIds: ImmutablePropTypes.list,
descendantsIds: ImmutablePropTypes.list,
me: PropTypes.number,
boostModal: PropTypes.bool,
deleteModal: PropTypes.bool,
autoPlayGif: PropTypes.bool,
intl: PropTypes.object.isRequired,
};
componentWillMount () {
this.props.dispatch(fetchStatus(Number(this.props.params.statusId)));
}
componentWillReceiveProps (nextProps) {
if (nextProps.params.statusId !== this.props.params.statusId && nextProps.params.statusId) {
this.props.dispatch(fetchStatus(Number(nextProps.params.statusId)));
}
}
handleFavouriteClick = (status) => {
if (status.get('favourited')) {
this.props.dispatch(unfavourite(status));
} else {
this.props.dispatch(favourite(status));
}
}
handleReplyClick = (status) => {
this.props.dispatch(replyCompose(status, this.context.router.history));
}
handleModalReblog = (status) => {
this.props.dispatch(reblog(status));
}
handleReblogClick = (status, e) => {
if (status.get('reblogged')) {
this.props.dispatch(unreblog(status));
} else {
if (e.shiftKey || !this.props.boostModal) {
this.handleModalReblog(status);
} else {
this.props.dispatch(openModal('BOOST', { status, onReblog: this.handleModalReblog }));
}
}
}
handleDeleteClick = (status) => {
const { dispatch, intl } = this.props;
if (!this.props.deleteModal) {
dispatch(deleteStatus(status.get('id')));
} else {
dispatch(openModal('CONFIRM', {
message: intl.formatMessage(messages.deleteMessage),
confirm: intl.formatMessage(messages.deleteConfirm),
onConfirm: () => dispatch(deleteStatus(status.get('id'))),
}));
}
}
handleMentionClick = (account, router) => {
this.props.dispatch(mentionCompose(account, router));
}
handleOpenMedia = (media, index) => {
this.props.dispatch(openModal('MEDIA', { media, index }));
}
handleOpenVideo = (media, time) => {
this.props.dispatch(openModal('VIDEO', { media, time }));
}
handleReport = (status) => {
this.props.dispatch(initReport(status.get('account'), status));
}
renderChildren (list) {
return list.map(id => <StatusContainer key={id} id={id} />);
}
render () {
let ancestors, descendants;
const { status, ancestorsIds, descendantsIds, me, autoPlayGif } = this.props;
if (status === null) {
return (
<Column>
<ColumnBackButton />
<MissingIndicator />
</Column>
);
}
if (ancestorsIds && ancestorsIds.size > 0) {
ancestors = <div>{this.renderChildren(ancestorsIds)}</div>;
}
if (descendantsIds && descendantsIds.size > 0) {
descendants = <div>{this.renderChildren(descendantsIds)}</div>;
}
return (
<Column>
<ColumnBackButton />
<ScrollContainer scrollKey='thread'>
<div className='scrollable detailed-status__wrapper'>
{ancestors}
<DetailedStatus
status={status}
autoPlayGif={autoPlayGif}
me={me}
onOpenVideo={this.handleOpenVideo}
onOpenMedia={this.handleOpenMedia}
/>
<ActionBar
status={status}
me={me}
onReply={this.handleReplyClick}
onFavourite={this.handleFavouriteClick}
onReblog={this.handleReblogClick}
onDelete={this.handleDeleteClick}
onMention={this.handleMentionClick}
onReport={this.handleReport}
/>
{descendants}
</div>
</ScrollContainer>
</Column>
);
}
}
|
jenkins-design-language/src/js/components/material-ui/svg-icons/alert/add-alert.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const AlertAddAlert = (props) => (
<SvgIcon {...props}>
<path d="M10.01 21.01c0 1.1.89 1.99 1.99 1.99s1.99-.89 1.99-1.99h-3.98zm8.87-4.19V11c0-3.25-2.25-5.97-5.29-6.69v-.72C13.59 2.71 12.88 2 12 2s-1.59.71-1.59 1.59v.72C7.37 5.03 5.12 7.75 5.12 11v5.82L3 18.94V20h18v-1.06l-2.12-2.12zM16 13.01h-3v3h-2v-3H8V11h3V8h2v3h3v2.01z"/>
</SvgIcon>
);
AlertAddAlert.displayName = 'AlertAddAlert';
AlertAddAlert.muiName = 'SvgIcon';
export default AlertAddAlert;
|
examples/FixedActionButton.js | chris-gooley/react-materialize | import React from 'react';
import Button from '../src/Button';
export default
<Button floating fab='vertical' faicon='fa fa-plus' className='red' large style={{bottom: '45px', right: '24px'}}>
<Button floating icon='insert_chart' className='red'/>
<Button floating icon='format_quote' className='yellow darken-1'/>
<Button floating icon='publish' className='green'/>
<Button floating icon='attach_file' className='blue'/>
</Button>;
|
src/containers/NotFound/NotFound.js | NetEffective/net-effective | import React from 'react';
export default function NotFound() {
return (
<div className="container">
<h1>Doh! 404!</h1>
<p>These are <em>not</em> the droids you are looking for!</p>
</div>
);
}
|
src/public/components/Hello/hello.js | wzxm/react-starter | import React from 'react';
import MyOption from './myOption.js';
require('./hello.css');
class Hello extends React.Component {
constructor(props) {
super(props);
this.state = {
selected: false
}
this.select = this.select.bind(this);
}
/**
* 这个调用时机是在组件创建,并初始化了状态之后,在第一次绘制 render() 之前。可以在这里做一些业务初始化操作,也可以设置组件状态。
* 这个函数在整个生命周期中只被调用一次。如果在这个函数里面调用setState,本次的render函数可以看到更新后的state,并且只渲染一次。
*/
// componentWillMount(){
// console.log(123);
// }
/* 调用了render方法后,组件加载成功并被成功渲染出来以后所执行的hook函数,一般会将网络请求等加载数据的操作,放在这个函数里进行,来保证不会出现UI上的错误。 */
// componentDidUpdate(){
// }
/* 返回布尔值(决定是否需要更新组件) */
// shouldComponentUpdate(nextProps, nextState) {
// }
select(event){
if(event.target.textContent === this.state.selected){
this.setState({selected: false});
} else {
this.setState({selected: event.target.textContent});
}
}
render() {
let mySelectStyle = {
border: '1px solid #999',
display: 'inline-block',
padding: '5px'
}
return (
<div style={mySelectStyle}>
<MyOption state={this.state.selected} select={this.select} value="Volvo"></MyOption>
<MyOption state={this.state.selected} select={this.select} value="Saab"></MyOption>
<MyOption state={this.state.selected} select={this.select} value="Mercedes"></MyOption>
<MyOption state={this.state.selected} select={this.select} value="Audi"></MyOption>
</div>
)
}
}
export default Hello;
|
packages/react-interactions/events/src/dom/Drag.js | flarnie/react | /**
* Copyright (c) Facebook, Inc. and its affiliates.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @flow
*/
import type {
ReactDOMResponderEvent,
ReactDOMResponderContext,
} from 'shared/ReactDOMTypes';
import type {
EventPriority,
ReactEventResponderListener,
} from 'shared/ReactTypes';
import React from 'react';
import {DiscreteEvent, UserBlockingEvent} from 'shared/ReactTypes';
const targetEventTypes = ['pointerdown'];
const rootEventTypes = ['pointerup', 'pointercancel', 'pointermove_active'];
type DragProps = {
disabled: boolean,
shouldClaimOwnership: () => boolean,
onDragStart: (e: DragEvent) => void,
onDragMove: (e: DragEvent) => void,
onDragEnd: (e: DragEvent) => void,
onDragChange: boolean => void,
};
type DragState = {|
dragTarget: null | Element | Document,
isPointerDown: boolean,
isDragging: boolean,
startX: number,
startY: number,
x: number,
y: number,
|};
// In the case we don't have PointerEvents (Safari), we listen to touch events
// too
if (typeof window !== 'undefined' && window.PointerEvent === undefined) {
targetEventTypes.push('touchstart', 'mousedown');
rootEventTypes.push(
'mouseup',
'mousemove',
'touchend',
'touchcancel',
'touchmove_active',
);
}
type EventData = {
diffX: number,
diffY: number,
};
type DragEventType = 'dragstart' | 'dragend' | 'dragchange' | 'dragmove';
type DragEvent = {|
target: Element | Document,
type: DragEventType,
timeStamp: number,
diffX?: number,
diffY?: number,
|};
function createDragEvent(
context: ReactDOMResponderContext,
type: DragEventType,
target: Element | Document,
eventData?: EventData,
): DragEvent {
return {
target,
type,
timeStamp: context.getTimeStamp(),
...eventData,
};
}
function isFunction(obj): boolean {
return typeof obj === 'function';
}
function dispatchDragEvent(
context: ReactDOMResponderContext,
listener: DragEvent => void,
name: DragEventType,
state: DragState,
eventPriority: EventPriority,
eventData?: EventData,
): void {
const target = ((state.dragTarget: any): Element | Document);
const syntheticEvent = createDragEvent(context, name, target, eventData);
context.dispatchEvent(syntheticEvent, listener, eventPriority);
}
const dragResponderImpl = {
targetEventTypes,
getInitialState(): DragState {
return {
dragTarget: null,
isPointerDown: false,
isDragging: false,
startX: 0,
startY: 0,
x: 0,
y: 0,
};
},
onEvent(
event: ReactDOMResponderEvent,
context: ReactDOMResponderContext,
props: DragProps,
state: DragState,
): void {
const {target, type, nativeEvent} = event;
switch (type) {
case 'touchstart':
case 'mousedown':
case 'pointerdown': {
if (!state.isDragging) {
const obj =
type === 'touchstart'
? (nativeEvent: any).changedTouches[0]
: nativeEvent;
const x = (state.startX = (obj: any).screenX);
const y = (state.startY = (obj: any).screenY);
state.x = x;
state.y = y;
state.dragTarget = target;
state.isPointerDown = true;
const onDragStart = props.onDragStart;
if (isFunction(onDragStart)) {
dispatchDragEvent(
context,
onDragStart,
'dragstart',
state,
DiscreteEvent,
);
}
context.addRootEventTypes(rootEventTypes);
}
break;
}
}
},
onRootEvent(
event: ReactDOMResponderEvent,
context: ReactDOMResponderContext,
props: DragProps,
state: DragState,
): void {
const {type, nativeEvent} = event;
switch (type) {
case 'touchmove':
case 'mousemove':
case 'pointermove': {
if (event.passive) {
return;
}
if (state.isPointerDown) {
const obj =
type === 'touchmove'
? (nativeEvent: any).changedTouches[0]
: nativeEvent;
const x = (obj: any).screenX;
const y = (obj: any).screenY;
state.x = x;
state.y = y;
if (x === state.startX && y === state.startY) {
return;
}
if (!state.isDragging) {
state.isDragging = true;
const onDragChange = props.onDragChange;
if (isFunction(onDragChange)) {
context.dispatchEvent(true, onDragChange, UserBlockingEvent);
}
} else {
const onDragMove = props.onDragMove;
if (isFunction(onDragMove)) {
const eventData = {
diffX: x - state.startX,
diffY: y - state.startY,
};
dispatchDragEvent(
context,
onDragMove,
'dragmove',
state,
UserBlockingEvent,
eventData,
);
}
(nativeEvent: any).preventDefault();
}
}
break;
}
case 'pointercancel':
case 'touchcancel':
case 'touchend':
case 'mouseup':
case 'pointerup': {
if (state.isDragging) {
const onDragEnd = props.onDragEnd;
if (isFunction(onDragEnd)) {
dispatchDragEvent(
context,
onDragEnd,
'dragend',
state,
DiscreteEvent,
);
}
const onDragChange = props.onDragChange;
if (isFunction(onDragChange)) {
context.dispatchEvent(false, onDragChange, UserBlockingEvent);
}
state.isDragging = false;
}
if (state.isPointerDown) {
state.dragTarget = null;
state.isPointerDown = false;
context.removeRootEventTypes(rootEventTypes);
}
break;
}
}
},
};
export const DragResponder = React.unstable_createResponder(
'Drag',
dragResponderImpl,
);
export function useDrag(
props: DragProps,
): ReactEventResponderListener<any, any> {
return React.unstable_useResponder(DragResponder, props);
}
|
src/svg-icons/editor/border-top.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderTop = (props) => (
<SvgIcon {...props}>
<path d="M7 21h2v-2H7v2zm0-8h2v-2H7v2zm4 0h2v-2h-2v2zm0 8h2v-2h-2v2zm-8-4h2v-2H3v2zm0 4h2v-2H3v2zm0-8h2v-2H3v2zm0-4h2V7H3v2zm8 8h2v-2h-2v2zm8-8h2V7h-2v2zm0 4h2v-2h-2v2zM3 3v2h18V3H3zm16 14h2v-2h-2v2zm-4 4h2v-2h-2v2zM11 9h2V7h-2v2zm8 12h2v-2h-2v2zm-4-8h2v-2h-2v2z"/>
</SvgIcon>
);
EditorBorderTop = pure(EditorBorderTop);
EditorBorderTop.displayName = 'EditorBorderTop';
EditorBorderTop.muiName = 'SvgIcon';
export default EditorBorderTop;
|
src/index.js | n1ckp/spotmybands | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, browserHistory } from 'react-router';
import routes from './routes';
import reducers from './reducers';
import promise from 'redux-promise';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={browserHistory} routes={routes} />
</Provider>
, document.querySelector('#root'));
|
src/components/Files/ListItem.js | isaacrowntree/hyde | import React, { Component } from 'react';
import './ListItem.css';
class ListItem extends Component {
constructor(props) {
super(props);
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.props.onItemClick(this.props.value);
}
format(val) {
let splitter = '\\';
if (val.split(splitter).length === 1) {
splitter = '/';
}
return val.split(splitter).slice(2).join(splitter);
}
render() {
return (
<li className="list-group-item" onClick={this.handleClick}>
{this.format(this.props.value)}
</li>
);
}
}
export default ListItem;
|
12-delayed-result/src/TodoList.js | dtanzer/react-basic-examples | import React, { Component } from 'react';
import { connect } from 'react-redux';
import TabsActions from './TabsActions';
import { AllTodosContainer } from './AllTodos';
import { NewTodoContainer } from './NewTodo';
export class TodoList extends Component {
render() {
const todosTab = (
<div>
<h1>My Todos</h1>
<AllTodosContainer />
</div>
);
const newTodoTab = (
<div>
<h1>New Todo</h1>
<NewTodoContainer />
</div>
);
const activeTab = this.props.activeTab==="all"? todosTab : newTodoTab;
return (
<div>
<div id="tabs">
<a href="#" onClick={_ => this.props.switchTab("all")}>All Todos</a> |
<a href="#" onClick={_ => this.props.switchTab("new")}>New Todo</a>
</div>
{activeTab}
</div>
);
}
}
function mapStateToProperties(state) {
return {
activeTab: state.tabs.activeTab
};
}
export const actionCreators = {
switchTab: (tab) => { return { type: TabsActions.tabSwitched, tab: tab }}
}
export const TodoListContainer = connect(mapStateToProperties, actionCreators)(TodoList);
|
src/components/Header/Header.js | workswell/smartforms | /*! React Starter Kit | MIT License | http://www.reactstarterkit.com/ */
import React from 'react';
import styles from './Header.css';
import withStyles from '../../decorators/withStyles';
import Link from '../../utils/Link';
import Navigation from '../Navigation';
@withStyles(styles)
class Header {
render() {
return (
<div className="Header">
<div className="Header-container">
<a className="Header-brand" href="/" onClick={Link.handleClick}>
<img className="Header-brandImg" src={require('./logo-small.png')} width="38" height="38" alt="React" />
<span className="Header-brandTxt">Your Company</span>
</a>
<Navigation className="Header-nav" />
<div className="Header-banner">
<h1 className="Header-bannerTitle">React</h1>
<p className="Header-bannerDesc">Complex web apps made easy</p>
</div>
</div>
</div>
);
}
}
export default Header;
|
src/components/Hint.js | serzhshakur/quest-application-reactjs | import React from 'react'
export default (props) => props.hintText ? <div>{props.hintText}</div> : null |
src/modules/Rooms/components/Chat/Messages.js | hdngr/mantenuto | /* eslint-disable */
import React from 'react';
import { connect } from 'react-redux';
const styles = require('./Chat.scss');
const Messages = (props) => {
const { messages, user, peer } = props;
if (messages.length === 0) {
return <p><em>No messages in your chat history.</em></p>
}
const list = messages.map((message, i) => {
let side;
let opposite;
let sender;
if (user && (message.user === user._id)) {
side = 'right';
opposite = 'left';
sender = user;
}
if (peer && (message.user === peer._id)) {
side = 'left';
opposite = 'right';
sender = peer;
}
const minutesAgo = (new Date().getTime() - Date.parse(message.timestamp)) / (60 * 1000);
let displayTime = `${Math.ceil(minutesAgo)} Minutes Ago`;
if (minutesAgo > 59) {
displayTime = `${Math.round(minutesAgo / (60))} Hours Ago`;
if (minutesAgo > (60 * 24 * 2) ) {
displayTime = `${Math.round(minutesAgo / (60 * 24))} Days Ago`;
}
if (minutesAgo > (60 * 24) ) {
displayTime = 'Yesterday';
}
}
return (
<li key={i} className={`${styles[side]}`}>
<div className={`${styles.ChatBody}`}>
<div>
<small className="text-muted"><span className="glyphicon glyphicon-time" />{' '}{displayTime}</small>
<strong className="primary-font">{`${sender ? sender.first : ''}`}</strong>
</div>
<p>
{ message.content }
</p>
</div>
</li>
)
})
return <ul className={styles.ChatList}>{ list }</ul>
}
const mapStateToProps = (state) => ({
messages: state.rooms.messages,
user: state.user.user,
peer: state.rooms.peer.user
// peer: state.rooms.peer
});
export default connect(mapStateToProps)(Messages)
|
src/components/video_detail.js | annsummmer/react | import React from 'react';
const VideoDetail = ({video}) => {
if(!video){
return <div>Loading...</div>
}
const videoId = video.id.videoId;
const url = `https://www.youtube.com/embed/${videoId}`;
console.log(video);
return (
<div className="vide-detail col-md-8">
<div className="embed-responsive embed-responsive-16by9">
<iframe className="embed-responsive-item" src={url}></iframe>
</div>
<div className="details">
<div>{video.snippet.title}</div>
<div>{video.snippet.description}</div>
</div>
</div>
);
}
export default VideoDetail; |
app/Child.js | KoltunovOleg/Task-React-App | import React, { Component } from 'react';
import Registration from './Registration';
import Home from './Home';
import Login from './Login';
import Users from './Users';
class Child extends Component {
render() {
var Render;
if(this.props.route && this.props.access){
switch (this.props.route) {
case '/users':
Render = <Users />;
break;
default:
Render = <Home />;
}}else{
switch (this.props.route) {
case '/registration':
Render = <Registration onchangeAccess={this.props.onchangeAccess}/>;
break;
case '/login':
Render = <Login onchangeAccess={this.props.onchangeAccess}/>;
break;
default:
Render = <Home />;
}
}
return (
<div className="col-md-8">
{Render}
</div>
);
}
}
export default Child; |
cms/react-static/src/containers/Home.js | fishjar/gabe-study-notes | import React from 'react'
import { withSiteData } from 'react-static'
//
import logoImg from '../logo.png'
export default withSiteData(() => (
<div>
<h1 style={{ textAlign: 'center' }}>Welcome to</h1>
<img src={logoImg} alt="" />
</div>
))
|
js/barber/Main.js | BarberHour/barber-hour | import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
StatusBar,
ScrollView,
Platform
} from 'react-native';
import { connect } from 'react-redux';
import ScrollableTabView from 'react-native-scrollable-tab-view';
import Toolbar from '../common/Toolbar';
import IconTabBar from '../common/IconTabBar';
import HaircutSchedule from './HaircutSchedule';
import HaircutHistory from './HaircutHistory';
import Profile from './Profile';
import PushNotifications from '../PushNotifications';
class Main extends Component {
render() {
return(
<View style={styles.container}>
<StatusBar backgroundColor='#C5C5C5' networkActivityIndicatorVisible={this.props.networkActivityIndicatorVisible} />
<Toolbar border navigator={this.props.navigator} />
<ScrollableTabView
scrollWithoutAnimation={true}
locked={true}
tabBarPosition='bottom'
renderTabBar={() => <IconTabBar titles={['Agenda', 'Cortes', 'Conta']} />}>
<View tabLabel='event' style={[styles.tabView, styles.tabViewWithoutPadding]}>
<HaircutSchedule navigator={this.props.navigator} />
</View>
<View tabLabel='scissor-2' style={[styles.tabView, styles.tabViewWithoutPadding]}>
<HaircutHistory navigator={this.props.navigator} />
</View>
<ScrollView tabLabel='shop' style={styles.tabView}>
<Profile navigator={this.props.navigator} />
</ScrollView>
</ScrollableTabView>
<PushNotifications />
</View>
);
}
}
function select(store) {
var schedulesLoading = store.schedules.isLoading || store.schedules.isRefreshing;
var appointmentsLoading = store.appointments.isLoading || store.appointments.isRefreshing;
return {
networkActivityIndicatorVisible: schedulesLoading || appointmentsLoading
};
}
export default connect(select)(Main);
var styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: 'white',
marginTop: Platform.OS === 'ios' ? 60 : 0
},
tabView: {
flex: 1,
padding: 10,
backgroundColor: 'rgba(0,0,0,0.01)',
},
tabViewWithoutPadding: {
padding: 0,
}
});
|
node_modules/react-bootstrap/es/FormControlStatic.js | ivanhristov92/bookingCalendar | 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 elementType from 'react-prop-types/lib/elementType';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var propTypes = {
componentClass: elementType
};
var defaultProps = {
componentClass: 'p'
};
var FormControlStatic = function (_React$Component) {
_inherits(FormControlStatic, _React$Component);
function FormControlStatic() {
_classCallCheck(this, FormControlStatic);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
FormControlStatic.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);
return React.createElement(Component, _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return FormControlStatic;
}(React.Component);
FormControlStatic.propTypes = propTypes;
FormControlStatic.defaultProps = defaultProps;
export default bsClass('form-control-static', FormControlStatic); |
stories/form/index.js | shulie/dh-component | import React from 'react';
import { storiesOf, action, linkTo } from '@kadira/storybook';
import withReadme from 'storybook-readme/with-readme';
import InputDemo from './input';
import FormDemo from './form';
import inputReadme from './input.md';
const addWithInfoOptions = { inline: true, propTables: false, source: false};
storiesOf('表单组件', module)
.addDecorator(withReadme(inputReadme))
.addWithInfo(
'Input',
() => (<InputDemo />), addWithInfoOptions)
.addWithInfo(
'Form',
() => (<FormDemo />), addWithInfoOptions)
|
app/javascript/mastodon/features/account_gallery/components/media_item.js | verniy6462/mastodon | import React from 'react';
import ImmutablePropTypes from 'react-immutable-proptypes';
import ImmutablePureComponent from 'react-immutable-pure-component';
import Permalink from '../../../components/permalink';
export default class MediaItem extends ImmutablePureComponent {
static propTypes = {
media: ImmutablePropTypes.map.isRequired,
};
render () {
const { media } = this.props;
const status = media.get('status');
let content, style;
if (media.get('type') === 'gifv') {
content = <span className='media-gallery__gifv__label'>GIF</span>;
}
if (!status.get('sensitive')) {
style = { backgroundImage: `url(${media.get('preview_url')})` };
}
return (
<div className='account-gallery__item'>
<Permalink
to={`/statuses/${status.get('id')}`}
href={status.get('url')}
style={style}
>
{content}
</Permalink>
</div>
);
}
}
|
app/components/ProductReviews/ReviewItem/index.js | ajfuller/react-casestudy | import React from 'react';
function formatDate(date) {
return new Date(date).toLocaleDateString('en-US', {
day: 'numeric',
month: 'short',
year: 'numeric',
});
}
const ReviewItem = (props) => (
<div>
<div style={{ color: 'red' }}>{props.overallRating}</div>
<div style={{ fontWeight: 'bold', fontSize: '15px' }}>{props.title}</div>
<div style={{ fontSize: '12px' }}>{props.review}</div>
<span style={{ fontSize: '15px', marginRight: '10px' }}>{props.screenName}</span>
<span style={{ fontSize: '15px' }}>{formatDate(props.datePosted)}</span>
</div>
);
ReviewItem.propTypes = {
overallRating: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number,
]),
title: React.PropTypes.string,
review: React.PropTypes.string,
screenName: React.PropTypes.string,
datePosted: React.PropTypes.string,
};
export default ReviewItem;
|
src/views/createRoutes.js | vbdoug/hot-react | import React from 'react';
import {Route} from 'react-router';
import App from 'views/App';
import Home from 'views/Home';
import Widgets from 'views/Widgets';
import About from 'views/About';
import Login from 'views/Login';
import RequireLogin from 'views/RequireLogin';
import LoginSuccess from 'views/LoginSuccess';
import Survey from 'views/Survey';
import NotFound from 'views/NotFound';
export default function(store) {
return (
<Route component={App}>
<Route path="/" component={Home}/>
<Route path="/widgets" component={Widgets}/>
<Route path="/about" component={About}/>
<Route path="/login" component={Login}/>
<Route component={RequireLogin} onEnter={RequireLogin.onEnter(store)}>
<Route path="/loginSuccess" component={LoginSuccess}/>
</Route>
<Route path="/survey" component={Survey}/>
<Route path="*" component={NotFound}/>
</Route>
);
}
|
data-browser-ui/public/app/components/headerComponents/filterRowsComponent.js | CloudBoost/cloudboost | import React from 'react'
import { observer } from "mobx-react"
import { Popover, PopoverAnimationVertical } from 'material-ui/Popover'
import FilterRow from './filterRowComponent.js'
@observer
class FilterRows extends React.Component {
constructor() {
super()
this.state = {
open: false,
filters: [],
andQuery: null,
orQueries: [],
finalQuery: null
}
}
componentDidMount() {
}
addFilter() {
let type = this.state.filters.length == 0 ? ['where'] : ['and', 'or']
this.state.filters.push({
type: type,
id: Math.random().toString(36).substring(7),
dataType: '',
selectedType: '',
filterType: '',
dataValue: '',
filterTypes: [],
columnType: '',
relatedTo: '',
listDataValue: []
})
this.setState(this.state)
// this.runQuery()
}
deleteFilter(id) {
this.state.filters = this.state.filters.filter(x => x.id != id)
if (this.state.filters[0]) {
this.state.filters[0].type = ['where']
}
this.setState(this.state)
// this.runQuery()
}
clearFilter() {
this.setState({
filters: [],
andQuery: null,
orQueries: [],
finalQuery: null,
open:false
})
this.props.tableStore.showLoader()
this.props.tableStore.setColumnsData()
}
runQuery() {
this.state.andQuery = null
this.state.orQueries = []
this.state.finalQuery = null
this.setState(this.state)
for (var k in this.state.filters) {
if (this.state.filters[k].filterType != '' && this.state.filters[k].dataType != '') {
this.buildQuery(this.state.filters[k])
}
}
if (this.state.finalQuery) {
this.props.tableStore.showLoader()
this.state.finalQuery.find().then((res) => {
this.props.tableStore.updateColumnsData(res)
}, (err) => {
console.log(err)
})
}
}
buildQuery(queryData) {
if (this.state.andQuery == null) {
this.state.andQuery = new CB.CloudQuery(this.props.tableStore.TABLE)
}
if (queryData.selectedType == '' || queryData.selectedType == 'and') {
this.state.andQuery[queryData.filterType](queryData.dataType, queryData.dataValue)
} else {
let query = new CB.CloudQuery(this.props.tableStore.TABLE)
this.state.orQueries.push(query[queryData.filterType](queryData.dataType, queryData.dataValue))
}
if (this.state.orQueries.length) {
this.state.finalQuery = new CB.CloudQuery.or([...this.state.orQueries, this.state.andQuery])
} else {
this.state.finalQuery = this.state.andQuery
}
this.setState(this.state)
}
handleTouchTap(event) {
// This prevents ghost click.
event.preventDefault();
this.setState({
open: true,
anchorEl: event.currentTarget
})
}
handleRequestClose() {
this.setState({
open: false
})
}
changeHandler(type, value, id, e) {
this.state.filters = this.state.filters.map((x) => {
if (x.id == id) {
if (type == 'listDataValue') {
x[type].push(value)
} else {
x[type] = value
}
}
return x
})
this.setState(this.state)
// this.runQuery()
}
removeListDataValue(index, id) {
this.state.filters = this.state.filters.map((x) => {
if (x.id == id) {
x['listDataValue'].splice(index, 1)
}
return x
})
this.setState(this.state)
// this.runQuery()
}
render() {
let filters = this.state.filters.map((x, i) => {
return <FilterRow
key={i}
tableStore={this.props.tableStore}
filterData={x}
deleteFilter={this.deleteFilter.bind(this)}
runQuery={this.runQuery.bind(this)}
changeHandler={this.changeHandler.bind(this)}
removeListDataValue={this.removeListDataValue.bind(this)}
/>
})
return (
<div className="disinb">
<button className="btn subhbtnpop" onTouchTap={this.handleTouchTap.bind(this)}><i className="fa fa-filter mr2" aria-hidden="true"></i>Filters</button>
<Popover
open={this.state.open}
anchorEl={this.state.anchorEl}
anchorOrigin={{ horizontal: 'left', vertical: 'bottom' }}
targetOrigin={{ horizontal: 'left', vertical: 'top' }}
onRequestClose={this.handleRequestClose.bind(this)}
animation={PopoverAnimationVertical}
className="popupfilterrrow"
>
<button className="btn addfilter" onClick={this.addFilter.bind(this)}>
<i className="fa fa-plus plusaddfilter" aria-hidden="true"></i>
Add Filter
</button>
{
filters.length ?
<div className="filterrowdiv">
{ filters }
</div> : <p className="nofiltertext">No filters applied to this view.</p>
}
<div className="filterbutton">
<button className="clearfilter" onClick={this.clearFilter.bind(this)}>
<i className="fa fa-ban plusaddfilter" aria-hidden="true"></i>
Clear
</button>
<button className="applyfiler" onClick={this.runQuery.bind(this)}>
<i className="fa fa-check plusaddfilter" aria-hidden="true"></i>
Apply
</button>
</div>
</Popover>
</div>
);
}
}
export default FilterRows; |
stories/DateRangePicker_calendar.js | intwarehq/react-dates | import React from 'react';
import moment from 'moment';
import { storiesOf } from '@kadira/storybook';
import { VERTICAL_ORIENTATION, ANCHOR_RIGHT } from '../constants';
import DateRangePickerWrapper from '../examples/DateRangePickerWrapper';
const TestPrevIcon = () => (
<span
style={{
border: '1px solid #dce0e0',
backgroundColor: '#fff',
color: '#484848',
padding: '3px',
}}
>
Prev
</span>
);
const TestNextIcon = () => (
<span
style={{
border: '1px solid #dce0e0',
backgroundColor: '#fff',
color: '#484848',
padding: '3px',
}}
>
Next
</span>
);
const TestCustomInfoPanel = () => (
<div
style={{
padding: '10px 21px',
borderTop: '1px solid #dce0e0',
color: '#484848',
}}
>
❕ Some useful info here
</div>
);
storiesOf('DRP - Calendar Props', module)
.addWithInfo('default', () => (
<DateRangePickerWrapper autoFocus />
))
.addWithInfo('single month', () => (
<DateRangePickerWrapper numberOfMonths={1} autoFocus />
))
.addWithInfo('3 months', () => (
<DateRangePickerWrapper numberOfMonths={3} autoFocus />
))
.addWithInfo('with custom day size', () => (
<DateRangePickerWrapper daySize={50} autoFocus />
))
.addWithInfo('anchored right', () => (
<div style={{ float: 'right' }}>
<DateRangePickerWrapper
anchorDirection={ANCHOR_RIGHT}
autoFocus
/>
</div>
))
.addWithInfo('vertical', () => (
<DateRangePickerWrapper
orientation={VERTICAL_ORIENTATION}
autoFocus
/>
))
.addWithInfo('vertical anchored right', () => (
<div style={{ float: 'right' }}>
<DateRangePickerWrapper
orientation={VERTICAL_ORIENTATION}
anchorDirection={ANCHOR_RIGHT}
autoFocus
/>
</div>
))
.addWithInfo('horizontal with portal', () => (
<DateRangePickerWrapper
withPortal
autoFocus
/>
))
.addWithInfo('horizontal with fullscreen portal', () => (
<DateRangePickerWrapper withFullScreenPortal autoFocus />
))
.addWithInfo('vertical with full screen portal', () => (
<DateRangePickerWrapper
orientation={VERTICAL_ORIENTATION}
withFullScreenPortal
autoFocus
/>
))
.addWithInfo('does not autoclose the DayPicker on date selection', () => (
<DateRangePickerWrapper
keepOpenOnDateSelect
autoFocus
/>
))
.addWithInfo('with custom month navigation', () => (
<DateRangePickerWrapper
navPrev={<TestPrevIcon />}
navNext={<TestNextIcon />}
autoFocus
/>
))
.addWithInfo('with outside days enabled', () => (
<DateRangePickerWrapper
numberOfMonths={1}
enableOutsideDays
autoFocus
/>
))
.addWithInfo('with month specified on open', () => (
<DateRangePickerWrapper
initialVisibleMonth={() => moment('04 2017', 'MM YYYY')}
autoFocus
/>
))
.addWithInfo('with info panel', () => (
<DateRangePickerWrapper
renderCalendarInfo={() => (
<TestCustomInfoPanel />
)}
autoFocus
/>
));
|
src/components/PrecisionBar.js | alexravs/midgar | import React from 'react';
const PrecisionBar = ({precision, onPrecisionChange}) => (
<input type="range" min="0" max="100" value={precision} onChange={onPrecisionChange} />
);
export default PrecisionBar;
|
components/headers.js | alligatorio/some-gators-next | import React from 'react';
import Head from 'next/head';
export default ({title}) => {
return <Head>
<title>{title}</title>
<link rel="stylesheet" href="static/styles.css" />
</Head>
}
|
src/pages/NotificationDetailPage.js | LinDing/two-life | import React, { Component } from 'react';
import {
StyleSheet,
Text,
View,
Image,
Navigator,
Dimensions,
TouchableOpacity,
WebView
} from 'react-native';
import CommonNav from '../common/CommonNav';
const WIDTH = Dimensions.get("window").width
const HEIGHT = Dimensions.get("window").height
export default class NotificationDetailPage extends Component {
static defaultProps = {}
constructor(props) {
super(props);
this.state = {};
}
render() {
console.log(this.props.url)
return (
<View style={styles.container}>
<CommonNav
title={"活动详情"}
navigator={this.props.navigator}/>
<WebView
bounces = {true}
scalesPageToFit={true}
startInLoadingState={true}
javaScriptEnabled={true}
domStorageEnabled={true}
source = {{uri:this.props.url}}
style = {styles.webview}>
</WebView>
</View>
);
}
}
const styles = StyleSheet.create({
container:{
flex: 1,
},
webview: {
width: WIDTH,
height: HEIGHT
}
}); |
src/components/Account/Reservations/presenter.js | ndlib/usurper | import React from 'react'
import PropTypes from 'prop-types'
import moment from 'moment'
import typy from 'typy'
import InlineLoading from 'components/Messages/InlineLoading'
import Table from 'components/Table'
import Link from 'components/Interactive/Link'
import AccountPageWrapper from '../AccountPageWrapper'
import styles from './style.module.css'
const ReservationsPresenter = ({ reservations, isLoading, startDate, endDate }) => {
let title = `Reservations for ${startDate.format('MMMM Do')}`
if (endDate.isValid() && !endDate.isSame(startDate)) {
title += ' – ' + endDate.format('MMMM Do')
}
const columns = [
{ path: 'space', label: 'Space' },
{ path: 'date', label: 'Date/Time' },
{ path: 'status', label: 'Status' },
{ path: 'link', label: 'Details' },
]
// Manipulate the table data so it is more presentable
const tableData = typy(reservations).safeArray.map(reservation => ({
space: reservation.space_name,
date: `${moment(reservation.fromDate).format('MMM. Do, h:mma')} – ${moment(reservation.toDate).format('h:mma')}`,
status: reservation.status,
link: (
<Link to={`https://libcal.library.nd.edu/spaces/booking/${reservation.bookId}`}>View in LibCal</Link>
),
}))
return (
<AccountPageWrapper title={title} slug='reservations' className='account-reservations'>
{isLoading
? (
<InlineLoading title='Loading account info' />
)
: (
<Table columns={columns} data={tableData} className={styles.reservationsTable} />
)}
</AccountPageWrapper>
)
}
ReservationsPresenter.propTypes = {
reservations: PropTypes.array,
isLoading: PropTypes.bool,
startDate: PropTypes.object,
endDate: PropTypes.object,
}
export default ReservationsPresenter
|
src/components/page/page.js | Numel2020/NUMEL-Transitions | /**
* Created by melvynphillips on 15/04/2017.
*/
import React from 'react';
import TransitionGroup from 'react-transition-group/TransitionGroup';
import {TweenMax} from "gsap";
import Box2 from "./box2";
export class Page extends React.Component {
constructor () {
super();
this.state = {shouldShowBox: true};
this.toggleBox = this.toggleBox.bind(this);
}
// In order to use functions at 'this' level I need to bound them to this
// use the constructor as in the above example so we can now do this.toggleBox
toggleBox () {
this.setState({
shouldShowBox: !this.state.shouldShowBox
});
};
render () {
console.log(location);
return <div className="page">
<TransitionGroup>
{ this.state.shouldShowBox && <Box2/>}
</TransitionGroup>
<button
className="toggle-btn"
onClick={this.toggleBox}
>
toggle
</button>
</div>;
}
}
export default Page; |
Full Stack Web Developer Nanodegree v2/P2 - Trivia API/frontend/src/components/Header.js | manishbisht/Udacity | import React, { Component } from 'react';
import logo from '../logo.svg';
import '../stylesheets/Header.css';
class Header extends Component {
navTo(uri){
window.location.href = window.location.origin + uri;
}
render() {
return (
<div className="App-header">
<h1 onClick={() => {this.navTo('')}}>Udacitrivia</h1>
<h2 onClick={() => {this.navTo('')}}>List</h2>
<h2 onClick={() => {this.navTo('/add')}}>Add</h2>
<h2 onClick={() => {this.navTo('/play')}}>Play</h2>
</div>
);
}
}
export default Header;
|
src/components/PlannerApp/index.js | instructure/canvas-planner | /*
* Copyright (C) 2017 - 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 they 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, { Component } from 'react';
import { connect } from 'react-redux';
import Container from '@instructure/ui-core/lib/components/Container';
import Spinner from '@instructure/ui-core/lib/components/Spinner';
import { arrayOf, oneOfType, bool, object, string, number, func } from 'prop-types';
import { momentObj } from 'react-moment-proptypes';
import Day from '../Day';
import ShowOnFocusButton from '../ShowOnFocusButton';
import StickyButton from '../StickyButton';
import LoadingFutureIndicator from '../LoadingFutureIndicator';
import LoadingPastIndicator from '../LoadingPastIndicator';
import PlannerEmptyState from '../PlannerEmptyState';
import formatMessage from '../../format-message';
import {loadFutureItems, scrollIntoPast, loadPastUntilNewActivity, togglePlannerItemCompletion, updateTodo} from '../../actions';
import {getFirstLoadedMoment} from '../../utilities/dateUtils';
import {notifier} from '../../dynamic-ui';
export class PlannerApp extends Component {
static propTypes = {
days: arrayOf(
arrayOf(
oneOfType([/* date */ string, arrayOf(/* items */ object)])
)
),
timeZone: string,
isLoading: bool,
loadingPast: bool,
loadingError: string,
allPastItemsLoaded: bool,
loadingFuture: bool,
allFutureItemsLoaded: bool,
firstNewActivityDate: momentObj,
scrollIntoPast: func,
loadPastUntilNewActivity: func,
loadFutureItems: func,
stickyOffset: number, // in pixels
stickyZIndex: number,
changeToDashboardCardView: func,
togglePlannerItemCompletion: func,
updateTodo: func,
triggerDynamicUiUpdates: func,
preTriggerDynamicUiUpdates: func,
};
static defaultProps = {
isLoading: false,
stickyOffset: 0,
triggerDynamicUiUpdates: () => {},
preTriggerDynamicUiUpdates: () => {},
};
componentWillUpdate () {
this.props.preTriggerDynamicUiUpdates(this.fixedElement);
}
componentDidUpdate () {
this.props.triggerDynamicUiUpdates(this.fixedElement);
}
fixedElementRef = (elt) => {
this.fixedElement = elt;
}
handleNewActivityClick = () => {
this.props.loadPastUntilNewActivity();
}
renderLoading () {
return <Container
display="block"
padding="xx-large medium"
textAlign="center"
>
<Spinner
title={formatMessage('Loading planner items')}
size="medium"
/>
</Container>;
}
renderNewActivity () {
if (this.props.isLoading) return;
if (!this.props.firstNewActivityDate) return;
const firstLoadedMoment = getFirstLoadedMoment(this.props.days, this.props.timeZone);
if (firstLoadedMoment.isSame(this.props.firstNewActivityDate) || firstLoadedMoment.isBefore(this.props.firstNewActivityDate)) return;
return (
<StickyButton
direction="up"
onClick={this.handleNewActivityClick}
offset={this.props.stickyOffset + 'px'}
zIndex={this.props.stickyZIndex}
>
{formatMessage("New Activity")}
</StickyButton>
);
}
renderLoadingPast () {
return <LoadingPastIndicator
loadingPast={this.props.loadingPast}
allPastItemsLoaded={this.props.allPastItemsLoaded}
loadingError={this.props.loadingError} />;
}
renderLoadMore () {
if (this.props.isLoading) return;
return <LoadingFutureIndicator
loadingFuture={this.props.loadingFuture}
allFutureItemsLoaded={this.props.allFutureItemsLoaded}
loadingError={this.props.loadingError}
onLoadMore={this.props.loadFutureItems} />;
}
renderLoadPastButton () {
return (
<ShowOnFocusButton
buttonProps={{
onClick: this.props.scrollIntoPast
}}
>
{formatMessage('Load prior dates')}
</ShowOnFocusButton>
);
}
renderNoAssignments() {
return (
<div>
{this.renderLoadPastButton()}
<PlannerEmptyState changeToDashboardCardView={this.props.changeToDashboardCardView}/>
</div>
);
}
renderBody (children) {
if (children.length === 0) {
return <div>
{this.renderNewActivity()}
{this.renderNoAssignments()}
</div>;
}
return <div className="PlannerApp">
{this.renderNewActivity()}
{this.renderLoadPastButton()}
{this.renderLoadingPast()}
{children}
{this.renderLoadMore()}
<div id="planner-app-fixed-element" ref={this.fixedElementRef} />
</div>;
}
render () {
if (this.props.isLoading) {
return this.renderBody(this.renderLoading());
}
const children = this.props.days.map(([dayKey, dayItems], dayIndex) => {
return <Day
timeZone={this.props.timeZone}
day={dayKey}
itemsForDay={dayItems}
animatableIndex={dayIndex}
key={dayKey}
toggleCompletion={this.props.togglePlannerItemCompletion}
updateTodo={this.props.updateTodo}
/>;
});
return this.renderBody(children);
}
}
const mapStateToProps = (state) => {
return {
days: state.days,
isLoading: state.loading.isLoading,
loadingPast: state.loading.loadingPast,
allPastItemsLoaded: state.loading.allPastItemsLoaded,
loadingFuture: state.loading.loadingFuture,
allFutureItemsLoaded: state.loading.allFutureItemsLoaded,
loadingError: state.loading.loadingError,
firstNewActivityDate: state.firstNewActivityDate,
timeZone: state.timeZone,
};
};
const mapDispatchToProps = {loadFutureItems, scrollIntoPast, loadPastUntilNewActivity, togglePlannerItemCompletion, updateTodo};
export default notifier(connect(mapStateToProps, mapDispatchToProps)(PlannerApp));
|
src/docs/components/ArticleDoc.js | karatechops/grommet-docs | // (C) Copyright 2014-2016 Hewlett Packard Enterprise Development LP
import React, { Component } from 'react';
import Article from 'grommet/components/Article';
import Section from 'grommet/components/Section';
import Header from 'grommet/components/Header';
import Footer from 'grommet/components/Footer';
import Anchor from 'grommet/components/Anchor';
import DocsArticle from '../../components/DocsArticle';
import Code from '../../components/Code';
Article.displayName = 'Article';
export const DESC = (<span>
A standard <Anchor
href='http://www.w3.org/TR/html5/sections.html#the-article-element'>
HTML5 article</Anchor>. It might
contain a <Anchor path='/docs/header'>Header</Anchor>, one
or more <Anchor path='/docs/section'>Sections</Anchor>, and
a <Anchor path='/docs/footer'>Footer</Anchor>.
</span>);
export default class ArticleDoc extends Component {
render () {
return (
<DocsArticle title='Article'>
<section>
<p>{DESC}</p>
<Article colorIndex='light-2'>
<Header
colorIndex="grey-5" justify="center" align="center">
Header
</Header>
<Section basis='medium' pad='large'
justify='center' align='center'>
Sections
</Section>
<Footer colorIndex="grey-5" justify="center" align="center">
Footer
</Footer>
</Article>
</section>
<section>
<h2>Properties</h2>
<dl>
<dt><code>onSelect {'{function (selected)}'}</code></dt>
<dd>Function that will be called when the article
changes the currently selected chapter.</dd>
<dt><code>selected {'{number}'}</code></dt>
<dd>The currently selected chapter using a zero based index.
Defaults to 0.</dd>
<dt><code>scrollStep true|false</code></dt>
<dd>Whether to allow keyboard control of stepped scrolling through
children. When true, directional keys will step through the
children, depending on the direction they are laid out.
If the spacebar is pressed, the children will automatically
be stepped through at an interval of ten seconds per child.</dd>
</dl>
<p>Properties for <Anchor path='/docs/box'>Box</Anchor> are
also available.</p>
</section>
<section>
<h2>Usage</h2>
<Code preamble={`import Article from 'grommet/components/Article';`}>
<Article>
{'{contents}'}
</Article>
</Code>
</section>
</DocsArticle>
);
}
};
|
src/svg-icons/image/flash-off.js | ArcanisCz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFlashOff = (props) => (
<SvgIcon {...props}>
<path d="M3.27 3L2 4.27l5 5V13h3v9l3.58-6.14L17.73 20 19 18.73 3.27 3zM17 10h-4l4-8H7v2.18l8.46 8.46L17 10z"/>
</SvgIcon>
);
ImageFlashOff = pure(ImageFlashOff);
ImageFlashOff.displayName = 'ImageFlashOff';
ImageFlashOff.muiName = 'SvgIcon';
export default ImageFlashOff;
|
src/components/isdbooking/components/bookinginfo.js | lq782655835/ReactDemo | import React from 'react';
import { Link } from 'react-router';
import { Icon, Tag, Button, Tooltip } from 'antd';
//import MockUtil from '../common/MockUtil';
class BookingInfo extends React.Component {
constructor(props) {
super(props);
this.state ={
listData: []
};
}
render(){
return (
<div className='bookinginfo animated bounceInDown' data-flex='dir:top main:center'>
<div data-flex='box:last'>
<div>
<Button className='mr10' type="primary" shape="circle" icon="shopping-cart"></Button>
<span>大众帕萨特</span>
<span> 自排|三厢|1.8L</span>
</div>
<div>
<Link to='30001/notice'>
<span className='cyellow'>预订须知</span>
</Link>
</div>
</div>
<div className='carlocation' data-flex='box:justify'>
<div>
<Button className='mr10' type="primary" shape="circle">取</Button>
<span>人民广场送车点</span>
</div>
<div data-flex='main:center'>
<span>----</span>
</div>
<div data-flex='main:right cross:center'>
<Button className='mr10' type="primary" shape="circle">还</Button>
<span>人民广场送车点</span>
</div>
</div>
<div className='cartime' data-flex='box:justify'>
<div>
<Button className='mr10' type="primary" shape="circle" icon="clock-circle-o"></Button>
<span>11月20日 20:00</span>
</div>
<div data-flex='main:center'>
<span>----</span>
</div>
<div data-flex='main:right cross:center'>
<Button className='mr10' type="primary" shape="circle" icon="clock-circle-o"></Button>
<span>11月22日 20:00</span>
</div>
</div>
</div>
);
}
}
export default BookingInfo; |
app/App.js | freele/glossary | // import React from 'react';
// import styles from './App.css';
// export default class App extends React.Component {
// constructor(props) {
// super(props);
// this.state = {test: 'foo'};
// }
// render() {
// return (
// <div className={styles.app}>
// bar test
// </div>
// );
// }
// }
import React from 'react';
import {Decorator as Cerebral} from 'cerebral-react';
import AddStatement from './components/AddStatement.js';
import StatementsList from './components/StatementsList.js';
// import StatementFooter from './components/StatementFooter.js';
import CentralStatement from './components/CentralStatement.js';
import ImageAndDropZone from './components/ImageAndDropZone.js';
var injectTapEventPlugin = require("react-tap-event-plugin");
injectTapEventPlugin();
const Dialog = require('material-ui/lib/Dialog');
const FlatButton = require('material-ui/lib/flat-button');
const TextField = require('material-ui/lib/text-field');
@Cerebral({
showFileInfoDialog: ['showFileInfoDialog'],
statements: ['statements'],
newFileInfoText: ['newFileInfoText'],
isSaving: ['isSaving'] // for later usage
}, {
visibleStatements: ['visibleStatements']
})
class App extends React.Component {
constructor() {
console.log('constructor');
super();
this.handleDialogClose = this.handleDialogClose.bind(this);
this.handleDialogSubmit = this.handleDialogSubmit.bind(this);
}
onClick(e) {
return false;
}
renderImageDropZone(index) {
return <ImageAndDropZone key={index} index={index}/>
}
handleDialogClose() {
this.props.signals.newFileInfoDialogClosed();
}
handleDialogSubmit() {
this.props.signals.newFileInfoDialogSubmitted();
}
onFileInfoChange(event) {
this.props.signals.newFileInfoChanged(true, {
text: event.target.value
});
}
render() {
let standardActions = [
<FlatButton
key={0}
label="Cancel"
secondary={true}
onTouchTap={this.handleDialogClose} />,
<FlatButton
key={1}
label="Submit"
primary={true}
onTouchTap={this.handleDialogSubmit} />
];
return (
<div className="u_h100">
<div className="centralElements" onClick={this.onClick} >
<CentralStatement/>
<AddStatement/>
</div>
<Dialog
ref="standardDialog"
title="Source"
actions={standardActions}
actionFocus="submit"
open={this.props.showFileInfoDialog}
onRequestClose={this.handleDialogClose}>
<TextField
autoComplete="off"
value={this.props.newFileInfoText}
hintText="Source or author of the file"
fullWidth={true}
onChange={(e) => this.onFileInfoChange(e)}
/>
</Dialog>
<div className="imagesLayer">
{ Array.from(Array(4).keys()).map(this.renderImageDropZone) }
</div>
</div>
);
}
}
export default App;
|
src/blog/flux/views/layouts/AppLayout.js | exseed/exseed-boilerplate | import React from 'react';
import BaseLayout from '@core/views/layouts/BaseLayout';
import Header from '../components/Header';
import Footer from '../components/Footer';
export default class AppLayout extends React.Component {
render() {
// here is the cdn for prism: http://www.jsdelivr.com/projects/prism
// jscs:disable
const scripts = [
'https://code.jquery.com/jquery-2.1.4.min.js',
'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.js',
'https://cdn.jsdelivr.net/g/prism@1.4.1(prism.js+components/prism-clike.min.js+components/prism-markdown.min.js+components/prism-markup.min.js+components/prism-css.min.js+components/prism-less.min.js+components/prism-jsx.min.js+components/prism-javascript.min.js+components/prism-json.min.js+components/prism-sql.min.js+plugins/line-numbers/prism-line-numbers.min.js+plugins/line-highlight/prism-line-highlight.min.js)',
'/blog/js/bundle.js',
'/blog/js/main.js',
];
const styles = [
'https://cdnjs.cloudflare.com/ajax/libs/semantic-ui/2.1.8/semantic.min.css',
'https://cdn.jsdelivr.net/g/prism@1.4.1(themes/prism-okaidia.css+plugins/line-numbers/prism-line-numbers.css+plugins/line-highlight/prism-line-highlight.css)',
'/blog/css/semantic-override.css',
];
// jscs:enable
return (
<BaseLayout
title="Blog"
scripts={scripts}
styles={styles} >
<Header />
{this.props.children}
<Footer />
</BaseLayout>
);
}
}; |
test/test_helper.js | davide-ravasi/redux-firebase | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/views/AboutView.js | Hortomatic/app-web | import React from 'react'
import { Link } from 'react-router'
export class AboutView extends React.Component {
render () {
return (
<div className='container text-center'>
<h1>This is the about view!</h1>
<hr />
<Link to='/'>Back To Home View</Link>
</div>
)
}
}
export default AboutView
|
node_modules/react-router/es/Link.js | SpatialMap/SpatialMapDev | var _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; };
function _objectWithoutProperties(obj, keys) { var target = {}; for (var i in obj) { if (keys.indexOf(i) >= 0) continue; if (!Object.prototype.hasOwnProperty.call(obj, i)) continue; target[i] = obj[i]; } return target; }
import React from 'react';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
import { ContextSubscriber } from './ContextUtils';
var _React$PropTypes = React.PropTypes,
bool = _React$PropTypes.bool,
object = _React$PropTypes.object,
string = _React$PropTypes.string,
func = _React$PropTypes.func,
oneOfType = _React$PropTypes.oneOfType;
function isLeftClickEvent(event) {
return event.button === 0;
}
function isModifiedEvent(event) {
return !!(event.metaKey || event.altKey || event.ctrlKey || event.shiftKey);
}
// TODO: De-duplicate against hasAnyProperties in createTransitionManager.
function isEmptyObject(object) {
for (var p in object) {
if (Object.prototype.hasOwnProperty.call(object, p)) return false;
}return true;
}
function resolveToLocation(to, router) {
return typeof to === 'function' ? to(router.location) : to;
}
/**
* A <Link> is used to create an <a> element that links to a route.
* When that route is active, the link gets the value of its
* activeClassName prop.
*
* For example, assuming you have the following route:
*
* <Route path="/posts/:postID" component={Post} />
*
* You could use the following component to link to that route:
*
* <Link to={`/posts/${post.id}`} />
*
* Links may pass along location state and/or query string parameters
* in the state/query props, respectively.
*
* <Link ... query={{ show: true }} state={{ the: 'state' }} />
*/
var Link = React.createClass({
displayName: 'Link',
mixins: [ContextSubscriber('router')],
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object, func]),
query: object,
hash: string,
state: object,
activeStyle: object,
activeClassName: string,
onlyActiveOnIndex: bool.isRequired,
onClick: func,
target: string
},
getDefaultProps: function getDefaultProps() {
return {
onlyActiveOnIndex: false,
style: {}
};
},
handleClick: function handleClick(event) {
if (this.props.onClick) this.props.onClick(event);
if (event.defaultPrevented) return;
var router = this.context.router;
!router ? process.env.NODE_ENV !== 'production' ? invariant(false, '<Link>s rendered outside of a router context cannot navigate.') : invariant(false) : void 0;
if (isModifiedEvent(event) || !isLeftClickEvent(event)) return;
// If target prop is set (e.g. to "_blank"), let browser handle link.
/* istanbul ignore if: untestable with Karma */
if (this.props.target) return;
event.preventDefault();
router.push(resolveToLocation(this.props.to, router));
},
render: function render() {
var _props = this.props,
to = _props.to,
activeClassName = _props.activeClassName,
activeStyle = _props.activeStyle,
onlyActiveOnIndex = _props.onlyActiveOnIndex,
props = _objectWithoutProperties(_props, ['to', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
// Ignore if rendered outside the context of router to simplify unit testing.
var router = this.context.router;
if (router) {
// If user does not specify a `to` prop, return an empty anchor tag.
if (to == null) {
return React.createElement('a', props);
}
var toLocation = resolveToLocation(to, router);
props.href = router.createHref(toLocation);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(toLocation, onlyActiveOnIndex)) {
if (activeClassName) {
if (props.className) {
props.className += ' ' + activeClassName;
} else {
props.className = activeClassName;
}
}
if (activeStyle) props.style = _extends({}, props.style, activeStyle);
}
}
}
return React.createElement('a', _extends({}, props, { onClick: this.handleClick }));
}
});
export default Link; |
src/popup/components/SubtitlesNavTabs.js | mazenbesher/sub_player_chrome_extension | import React from 'react';
import ReactDOM from 'react-dom';
import { subscribeToSubtitleEvents } from 'lib/components/hoc';
class SubtitleTab extends React.Component {
constructor(props) {
super(props);
}
render() {
const { subId, isSubActivated } = this.props;
return (
<a
className={
"nav-item nav-link" +
(subId == 1 ? " active" : "") +
// make subtitle tab head bold if a subtitle is active
(isSubActivated ? " active-subtitle" : "")
}
data-toggle="tab"
href={`#subtitle_${subId}`}
role="tab"
aria-controls={`subtitle_${subId}`}
aria-expanded={subId == 1 ? "true" : ""}>
Subtitle {subId}
{
(isSubActivated) ? (
<p className="sub_activated_label">
active
</p>
) : null
}
</a >
)
}
}
// first one is active
const listItems = [1, 2, 3].map(num =>
React.createElement(subscribeToSubtitleEvents(SubtitleTab), { key: num, subId: num })
);
export class SubtitlesNavTabs extends React.Component {
render() {
return (
<ul
id="subtitles_nav_tabs"
className="nav nav-tabs"
role="tablist">
{listItems}
</ul >
)
}
} |
src/svg-icons/av/replay-10.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvReplay10 = (props) => (
<SvgIcon {...props}>
<path d="M12 5V1L7 6l5 5V7c3.3 0 6 2.7 6 6s-2.7 6-6 6-6-2.7-6-6H4c0 4.4 3.6 8 8 8s8-3.6 8-8-3.6-8-8-8zm-1.1 11H10v-3.3L9 13v-.7l1.8-.6h.1V16zm4.3-1.8c0 .3 0 .6-.1.8l-.3.6s-.3.3-.5.3-.4.1-.6.1-.4 0-.6-.1-.3-.2-.5-.3-.2-.3-.3-.6-.1-.5-.1-.8v-.7c0-.3 0-.6.1-.8l.3-.6s.3-.3.5-.3.4-.1.6-.1.4 0 .6.1c.2.1.3.2.5.3s.2.3.3.6.1.5.1.8v.7zm-.9-.8v-.5s-.1-.2-.1-.3-.1-.1-.2-.2-.2-.1-.3-.1-.2 0-.3.1l-.2.2s-.1.2-.1.3v2s.1.2.1.3.1.1.2.2.2.1.3.1.2 0 .3-.1l.2-.2s.1-.2.1-.3v-1.5z"/>
</SvgIcon>
);
AvReplay10 = pure(AvReplay10);
AvReplay10.displayName = 'AvReplay10';
AvReplay10.muiName = 'SvgIcon';
export default AvReplay10;
|
index.js | MichalKononenko/OmicronClient | /**
* Created by Michal on 2015-12-07.
*/
import App from './src/app';
import React from 'react';
import React_DOM from 'react-dom';
import {Provider} from 'react-redux';
import store from './src/store';
import './index.html';
import './static/favicon.ico'
React_DOM.render(
<Provider store={store}>
<App/>
</Provider>,
document.getElementById('app-container'));
|
src/svg-icons/av/call-to-action.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvCallToAction = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h18c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H3v-3h18v3z"/>
</SvgIcon>
);
AvCallToAction = pure(AvCallToAction);
AvCallToAction.displayName = 'AvCallToAction';
AvCallToAction.muiName = 'SvgIcon';
export default AvCallToAction;
|
client/components/campaigns/ManageCampaigns.js | karuppiah7890/Mail-for-Good | import React from 'react';
import ManageCampaignsBox from '../../containers/campaigns/ManageCampaignsBox';
const ManageCampaigns = () => {
return (
<div>
<div className="content-header">
<h1>Manage campaigns
<small>Edit or delete your campaigns here</small>
</h1>
</div>
<section className="content">
<ManageCampaignsBox />
</section>
</div>
);
};
export default ManageCampaigns;
|
src/class/ErrorBoundary.js | tegon/traktflix | import PropTypes from 'prop-types';
import React from 'react';
class ErrorBoundary extends React.Component {
constructor(props) {
super(props);
this.state = {hasError: false};
}
componentDidCatch(error, info) {
console.log(error, info);
this.setState({hasError: true});
}
render() {
let content;
if (this.state.hasError) {
content = <h1>Something went wrong.</h1>;
} else {
content = this.props.children;
}
return content;
}
}
ErrorBoundary.propTypes = {
children: PropTypes.node
};
export default ErrorBoundary; |
docs/app/Examples/collections/Grid/Types/GridExampleDividedNumber.js | koenvg/Semantic-UI-React | import React from 'react'
import { Grid, Image } from 'semantic-ui-react'
const GridExampleDividedNumber = () => (
<Grid columns={3} divided>
<Grid.Row>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/media-paragraph.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/media-paragraph.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/media-paragraph.png' />
</Grid.Column>
</Grid.Row>
<Grid.Row>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/media-paragraph.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/media-paragraph.png' />
</Grid.Column>
<Grid.Column>
<Image src='http://semantic-ui.com/images/wireframe/media-paragraph.png' />
</Grid.Column>
</Grid.Row>
</Grid>
)
export default GridExampleDividedNumber
|
src/domain/group/component/GroupInfo.js | hellowin/kanca | import React from 'react';
import MediaQuery from 'react-responsive';
import groupRepo from 'infra/repo/group';
import loc from 'infra/service/location';
const selectGroup = groupId => e => {
e.preventDefault();
groupRepo.selectGroup(groupId)
.then(() => loc.push('/group/feed'));
}
const Card = props => {
const { id, name, cover, owner, privacy } = props;
return (
<div>
<MediaQuery minDeviceWidth={320} maxWidthDevice={736} minWidth={320} maxWidth={736}>
{(matches) => {
const cardStyleOnMobile = matches ? { width: '100%', float: 'left' } : { width: '20rem', float: 'left' };
return (
<div className={`card ${matches ? '' : 'mr-1'}`} style={cardStyleOnMobile}>
<div className="card-img-top" style={{
height: '100px',
backgroundImage: `url("${cover}")`,
backgroundSize: 'cover',
backgroundRepeat: 'no-repeat',
backgroundPosition: '50% 50%',
}}></div>
<div className="card-block">
<p><b>{name}</b></p>
<span className="mr-1"><i className="fa fa-lock"></i> {privacy}</span>
{owner ? <span className="mr-1"><i className="fa fa-user"></i> {owner.name}</span> : ''}
</div>
<div className="card-block pt-0" style={{ textAlign: 'right' }}>
<a href={`https://www.facebook.com/groups/${id}/`} target="_blank" className="btn btn-primary btn-sm">Open in FB</a>
<a onClick={selectGroup(id)} className="btn btn-primary btn-sm no-href-link">Select</a>
</div>
</div>
);
}}
</MediaQuery>
</div>
);
}
export default Card;
|
src/svg-icons/content/block.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentBlock = (props) => (
<SvgIcon {...props}>
<path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zM4 12c0-4.42 3.58-8 8-8 1.85 0 3.55.63 4.9 1.69L5.69 16.9C4.63 15.55 4 13.85 4 12zm8 8c-1.85 0-3.55-.63-4.9-1.69L18.31 7.1C19.37 8.45 20 10.15 20 12c0 4.42-3.58 8-8 8z"/>
</SvgIcon>
);
ContentBlock = pure(ContentBlock);
ContentBlock.displayName = 'ContentBlock';
ContentBlock.muiName = 'SvgIcon';
export default ContentBlock;
|
jenkins-design-language/src/js/components/material-ui/svg-icons/file/attachment.js | alvarolobato/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const FileAttachment = (props) => (
<SvgIcon {...props}>
<path d="M2 12.5C2 9.46 4.46 7 7.5 7H18c2.21 0 4 1.79 4 4s-1.79 4-4 4H9.5C8.12 15 7 13.88 7 12.5S8.12 10 9.5 10H17v2H9.41c-.55 0-.55 1 0 1H18c1.1 0 2-.9 2-2s-.9-2-2-2H7.5C5.57 9 4 10.57 4 12.5S5.57 16 7.5 16H17v2H7.5C4.46 18 2 15.54 2 12.5z"/>
</SvgIcon>
);
FileAttachment.displayName = 'FileAttachment';
FileAttachment.muiName = 'SvgIcon';
export default FileAttachment;
|
docs-ui/components/pieChart.stories.js | beeftornado/sentry | import React from 'react';
import {withInfo} from '@storybook/addon-info';
import PieChart from 'app/components/charts/pieChart';
export default {
title: 'DataVisualization/Charts/PieChart',
};
export const _PieChart = withInfo('PieChart')(() => (
<PieChart
startDate={new Date()}
series={[
{
seriesName: 'Browsers',
data: [
{
name: 'Chrome',
value: 3500,
},
{
name: 'Firefox',
value: 650,
},
{
name: 'Safari',
value: 250,
},
],
},
]}
/>
));
_PieChart.story = {
name: 'PieChart',
};
|
src/interface/report/Results/Timeline/Component.js | sMteX/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import { formatDuration } from 'common/format';
import DragScroll from 'interface/common/DragScroll';
import CASTS_THAT_ARENT_CASTS from 'parser/core/CASTS_THAT_ARENT_CASTS';
import Abilities from 'parser/core/modules/Abilities';
import BuffsModule from 'parser/core/modules/Buffs';
import CombatLogParser from 'parser/core/CombatLogParser';
import './Timeline.scss';
import Buffs from './Buffs';
import Casts from './Casts';
import Cooldowns from './Cooldowns';
class Timeline extends React.PureComponent {
static propTypes = {
abilities: PropTypes.instanceOf(Abilities).isRequired,
buffs: PropTypes.instanceOf(BuffsModule).isRequired,
parser: PropTypes.instanceOf(CombatLogParser).isRequired,
};
static defaultProps = {
showCooldowns: true,
showGlobalCooldownDuration: false,
};
constructor(props) {
super(props);
this.state = {
zoom: 2,
padding: 0,
};
this.setContainerRef = this.setContainerRef.bind(this);
}
get fight() {
return this.props.parser.fight;
}
get start() {
return this.fight.start_time;
}
get end() {
return this.fight.end_time;
}
get duration() {
return this.end - this.start;
}
get seconds() {
return this.duration / 1000;
}
get secondWidth() {
return 120 / this.state.zoom;
}
get totalWidth() {
return this.seconds * this.secondWidth;
}
isApplicableEvent(event) {
switch (event.type) {
case 'cast':
return this.isApplicableCastEvent(event);
case 'updatespellusable':
return this.isApplicableUpdateSpellUsableEvent(event);
default:
return false;
}
}
isApplicableCastEvent(event) {
const parser = this.props.parser;
if (!parser.byPlayer(event)) {
// Ignore pet/boss casts
return false;
}
const spellId = event.ability.guid;
if (CASTS_THAT_ARENT_CASTS.includes(spellId)) {
return false;
}
const ability = this.props.abilities.getAbility(spellId);
if (!ability || !ability.cooldown) {
return false;
}
return true;
}
isApplicableUpdateSpellUsableEvent(event) {
if (event.trigger !== 'endcooldown' && event.trigger !== 'restorecharge') {
// begincooldown is unnecessary since endcooldown includes the start time
return false;
}
return true;
}
/**
* @param {object[]} events
* @returns {Map<int, object[]>} Events grouped by spell id.
*/
getEventsBySpellId(events) {
const eventsBySpellId = new Map();
events.forEach(event => {
if (!this.isApplicableEvent(event)) {
return;
}
const spellId = this._getCanonicalId(event.ability.guid);
if (!eventsBySpellId.has(spellId)) {
eventsBySpellId.set(spellId, []);
}
eventsBySpellId.get(spellId).push(event);
});
return eventsBySpellId;
}
_getCanonicalId(spellId){
const ability = this.props.abilities.getAbility(spellId);
if (!ability) {
return spellId; // not a class ability
}
if (ability.spell instanceof Array) {
return ability.spell[0].id;
} else {
return ability.spell.id;
}
}
setContainerRef(elem) {
if (!elem || !elem.getBoundingClientRect) {
return;
}
this.setState({
padding: elem.getBoundingClientRect().x + 15, // 15 for padding
});
}
render() {
const { parser, abilities, buffs } = this.props;
const skipInterval = Math.ceil(40 / this.secondWidth);
const eventsBySpellId = this.getEventsBySpellId(parser.eventHistory);
return (
<>
<div className="container" ref={this.setContainerRef} />
<DragScroll className="spell-timeline-container">
<div
className="spell-timeline"
style={{
width: this.totalWidth + this.state.padding * 2,
paddingTop: 0,
paddingBottom: 0,
paddingLeft: this.state.padding,
paddingRight: this.state.padding, // we also want the user to have the satisfying feeling of being able to get the right side to line up
}}
>
<Buffs
start={this.start}
secondWidth={this.secondWidth}
parser={parser}
buffs={buffs}
/>
<div className="time-line">
{this.seconds > 0 && [...Array(Math.ceil(this.seconds))].map((_, second) => (
<div
key={second}
style={{ width: this.secondWidth * skipInterval }}
data-duration={formatDuration(second)}
/>
))}
</div>
<Casts
start={this.start}
secondWidth={this.secondWidth}
parser={parser}
/>
<Cooldowns
start={this.start}
end={this.end}
secondWidth={this.secondWidth}
eventsBySpellId={eventsBySpellId}
abilities={abilities}
/>
</div>
</DragScroll>
</>
);
}
}
export default Timeline;
|
webapp/src/components/geneOntologyRibbon/index.js | nathandunn/agr | import React, { Component } from 'react';
import Ribbon, { RibbonDataProvider } from 'gene-ontology-ribbon';
import '../../../node_modules/gene-ontology-ribbon/lib/index.css';
import fixRibbonPlacement from './fixRibbonPlacement';
const PlacedRibbon = fixRibbonPlacement(Ribbon);
class GeneOntologyRibbon extends Component {
render() {
const {id} = this.props;
return (
<RibbonDataProvider subject={id}>
{({title, data, dataReceived, dataError, queryID}) => (
<div>
{
dataReceived ? <PlacedRibbon data={data} queryID={queryID} title={title} /> : null
}
{
dataError ? <i className="text-muted">No Data Available</i> : null
}
{
dataReceived || dataError ? null : 'Loading...'
}
</div>
)
}
</RibbonDataProvider>
);
}
}
GeneOntologyRibbon.propTypes = {
id: React.PropTypes.string.isRequired
};
export default GeneOntologyRibbon;
|
test/test_helper.js | aquinoWill/ReduxSimpleStarter | import _$ from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import TestUtils from 'react-addons-test-utils';
import jsdom from 'jsdom';
import chai, { expect } from 'chai';
import chaiJquery from 'chai-jquery';
import { Provider } from 'react-redux';
import { createStore } from 'redux';
import reducers from '../src/reducers';
global.document = jsdom.jsdom('<!doctype html><html><body></body></html>');
global.window = global.document.defaultView;
global.navigator = global.window.navigator;
const $ = _$(window);
chaiJquery(chai, chai.util, $);
function renderComponent(ComponentClass, props = {}, state = {}) {
const componentInstance = TestUtils.renderIntoDocument(
<Provider store={createStore(reducers, state)}>
<ComponentClass {...props} />
</Provider>
);
return $(ReactDOM.findDOMNode(componentInstance));
}
$.fn.simulate = function(eventName, value) {
if (value) {
this.val(value);
}
TestUtils.Simulate[eventName](this[0]);
};
export {renderComponent, expect};
|
src/public/components/progress/radial.js | Harrns/segta | import React from 'react'
import Color from '../../color'
function clamp (n, min, max) {
return Math.max(min, Math.min(max, n))
}
export default class MyRadialProgress extends React.Component {
constructor (props) {
super(props)
this.state = {}
this.initState(props)
}
initState (props) {
Object.assign(this.state, {
value: props.value < 1 ? props.value * 100 : props.value
})
}
componentWillReceiveProps (props) {
this.initState(props)
}
generatePath (degrees) {
const radius = this.props.radius
const radians = (degrees * Math.PI / 180)
var x = Math.sin(radians) * radius
var y = Math.cos(radians) * -radius
const halfEdgeSize = this.props.edgeSize / 2
x += halfEdgeSize
y += halfEdgeSize
const largeArcSweepFlag = degrees > 180 ? 1 : 0
const startX = halfEdgeSize
const startY = halfEdgeSize - radius
return `M${startX},${startY} A${radius},${radius} 1 ${largeArcSweepFlag} 1 ${x},${y} `
}
render () {
const center = this.props.edgeSize / 2
const radius = this.props.radius
let degrees
let text = ''
let percent = clamp(this.state.value, 0, 100)
degrees = percent / 100 * 360
degrees = clamp(degrees, 0, 359.9)
text = this.props.formatText(percent)
const pathDescription = this.generatePath(degrees)
return (
<svg height={this.props.edgeSize} width={this.props.edgeSize} style={this.props.style}>
<circle cx={center} cy={center} r={radius}
stroke={this.props.circleStroke}
strokeWidth={this.props.circleStrokeWidth}
fill={this.props.circleFill}/>
<path d={pathDescription}
fill="transparent"
stroke={this.props.progressStroke}
strokeWidth={this.props.circleStrokeWidth + 1}/>
{ this.props.displayText && <text x={center} y={center} textAnchor="middle">{text}</text> }
</svg>
)
}
}
MyRadialProgress.defaultProps = {
value: 0.42,
edgeSize: 20,
radius: 5,
circleStrokeWidth: 10,
circleStroke: Color.grey,
circleFill: Color.grey,
progressStroke: Color.green,
displayText: true,
formatText: (value) => value
}
|
resources/apps/frontend/src/pages/subscriptions/create.js | johndavedecano/PHPLaravelGymManagementSystem | import React from 'react';
import {Card, CardBody} from 'reactstrap';
import Form from './form';
import Breadcrumbs from 'components/Breadcrumbs';
import {createSubscription} from 'requests/subscriptions';
class Component extends React.Component {
state = {};
get previous() {
return [
{
to: '/subscriptions',
label: 'Subscriptions',
},
];
}
onSubmit = data => {
return createSubscription(data).then(() => {
setTimeout(() => {
this.props.history.replace('/subscriptions');
}, 1000);
});
};
render() {
return (
<React.Fragment>
<Breadcrumbs previous={this.previous} active="Create Subscription" />
<Card>
<CardBody>
<Form onSubmit={this.onSubmit} isCreate />
</CardBody>
</Card>
</React.Fragment>
);
}
}
export default Component;
|
app/components/Tree/Toggle.js | adamsome/electron-nav | // @flow
import React from 'react'
import styles from './Toggle.css'
type Props = {
hide?: boolean
}
const Toggle = ({ hide }: Props) => {
const height = 8
const width = 8
const midHeight = height * 0.5
const points = `0,0 0,${height} ${width},${midHeight}`
const visibility = hide ? { visibility: 'hidden' } : null
return (
<div className={styles.container}>
<div className={styles.wrapper}>
<svg height={height} width={width} style={visibility}>
<polygon points={points} className={styles.arrow} />
</svg>
</div>
</div>
)
}
Toggle.defaultProps = {
hide: false,
}
export default Toggle
|
src/svg-icons/notification/time-to-leave.js | lawrence-yu/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationTimeToLeave = (props) => (
<SvgIcon {...props}>
<path d="M18.92 5.01C18.72 4.42 18.16 4 17.5 4h-11c-.66 0-1.21.42-1.42 1.01L3 11v8c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-1h12v1c0 .55.45 1 1 1h1c.55 0 1-.45 1-1v-8l-2.08-5.99zM6.5 15c-.83 0-1.5-.67-1.5-1.5S5.67 12 6.5 12s1.5.67 1.5 1.5S7.33 15 6.5 15zm11 0c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zM5 10l1.5-4.5h11L19 10H5z"/>
</SvgIcon>
);
NotificationTimeToLeave = pure(NotificationTimeToLeave);
NotificationTimeToLeave.displayName = 'NotificationTimeToLeave';
NotificationTimeToLeave.muiName = 'SvgIcon';
export default NotificationTimeToLeave;
|
stories/SimpleUserFormDemo.js | de44/kb-ui | import React from 'react';
import PropTypes from 'prop-types';
import kb from '../src/kb-ui';
import { withState, compose } from 'recompose';
import FormDemo from './FormDemo';
const form = kb.form().fields([
kb.field('id').readOnly(true).defaultValue('asdf-1234-qwerty-567890'),
kb.field('name'),
kb.field('email'),
kb.field('suspened', 'bool')
]);
const formDef = `const form = kb.form().fields([
kb.field('id').readOnly(true).defaultValue('asdf-1234-qwerty-567890'),
kb.field('name'),
kb.field('email'),
kb.field('suspened', 'bool')
]);`;
const model = {
email: 'user@test.com',
profile: {
bio: '<p>Hello, World!</p>',
website: {
url: 'https://github.com/de44',
text: 'de44 on Github'
}
}
};
const SimpleUserFormDemo = () => {
return (
<div className="SimpleUserFormDemo">
<FormDemo form={form} formDef={formDef} model={model} />
</div>
);
};
export default SimpleUserFormDemo;
|
src/routes/Main/components/MainPage/MainPage.js | sachinisilva/ganu-denu | import React from 'react'
import PropTypes from 'prop-types'
import ItemListContainer from '../../../Home/containers/ItemListContainer'
import {FlatButton} from 'material-ui'
import banner from '../../../../../public/banner.jpg'
export const MainPage = ({setSigninnModalVisibility, setSignupModalVisibility}) => {
const getSignInModal = () => {
setSignupModalVisibility(false)
setSigninnModalVisibility(true)
}
const getSignUpModal = () => {
setSigninnModalVisibility(false)
setSignupModalVisibility(true)
}
// add html content here for sign in
return (
<div>
<div className="gen-app-header layout__row layout__align-space-between-center">
<div className="gen-app-header-logo">
<h1>Ganu Denu</h1>
</div>
<div className="gen-app-header-nav">
<FlatButton
label="Sign In"
onClick={getSignInModal}/>
<FlatButton
label="Sign Up"
primary={true}
onClick={getSignUpModal}/>
</div>
</div>
<div className="gen-banner">
<img src={banner}/>
<div className="overlay layout__column layout__align-center-center">
<div className="layout__column layout__align-center-end">
<h1>Ganu Denu</h1>
<p>Launching soon...</p>
</div>
</div>
</div>
{/*<ItemListContainer />*/}
</div>
)
}
MainPage.propTypes = {
setSignupModalVisibility: PropTypes.func.isRequired,
setSigninnModalVisibility: PropTypes.func.isRequired
}
export default MainPage
|
examples/huge-apps/routes/Course/components/Dashboard.js | jbbr/react-router | import React from 'react';
class Dashboard extends React.Component {
render () {
return (
<div>
<h3>Course Dashboard</h3>
</div>
);
}
}
export default Dashboard;
|
force_dir/node_modules/react-bootstrap/es/PaginationButton.js | wolfiex/VisACC | 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 elementType from 'react-prop-types/lib/elementType';
import SafeAnchor from './SafeAnchor';
import createChainedFunction from './utils/createChainedFunction';
// TODO: This should be `<Pagination.Item>`.
// TODO: This should use `componentClass` like other components.
var propTypes = {
componentClass: elementType,
className: React.PropTypes.string,
eventKey: React.PropTypes.any,
onSelect: React.PropTypes.func,
disabled: React.PropTypes.bool,
active: React.PropTypes.bool,
onClick: React.PropTypes.func
};
var defaultProps = {
componentClass: SafeAnchor,
active: false,
disabled: false
};
var PaginationButton = function (_React$Component) {
_inherits(PaginationButton, _React$Component);
function PaginationButton(props, context) {
_classCallCheck(this, PaginationButton);
var _this = _possibleConstructorReturn(this, _React$Component.call(this, props, context));
_this.handleClick = _this.handleClick.bind(_this);
return _this;
}
PaginationButton.prototype.handleClick = function handleClick(event) {
var _props = this.props;
var disabled = _props.disabled;
var onSelect = _props.onSelect;
var eventKey = _props.eventKey;
if (disabled) {
return;
}
if (onSelect) {
onSelect(eventKey, event);
}
};
PaginationButton.prototype.render = function render() {
var _props2 = this.props;
var Component = _props2.componentClass;
var active = _props2.active;
var disabled = _props2.disabled;
var onClick = _props2.onClick;
var className = _props2.className;
var style = _props2.style;
var props = _objectWithoutProperties(_props2, ['componentClass', 'active', 'disabled', 'onClick', 'className', 'style']);
if (Component === SafeAnchor) {
// Assume that custom components want `eventKey`.
delete props.eventKey;
}
delete props.onSelect;
return React.createElement(
'li',
{
className: classNames(className, { active: active, disabled: disabled }),
style: style
},
React.createElement(Component, _extends({}, props, {
disabled: disabled,
onClick: createChainedFunction(onClick, this.handleClick)
}))
);
};
return PaginationButton;
}(React.Component);
PaginationButton.propTypes = propTypes;
PaginationButton.defaultProps = defaultProps;
export default PaginationButton; |
docs/src/app/components/pages/components/RaisedButton/ExampleSimple.js | frnk94/material-ui | import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
const style = {
margin: 12,
};
const RaisedButtonExampleSimple = () => (
<div>
<RaisedButton label="Default" style={style} />
<RaisedButton label="Primary" primary={true} style={style} />
<RaisedButton label="Secondary" secondary={true} style={style} />
<RaisedButton label="Disabled" disabled={true} style={style} />
<br />
<br />
<RaisedButton label="Full width" fullWidth={true} />
</div>
);
export default RaisedButtonExampleSimple;
|
app/components/AgentDetails/index.js | medevelopment/UMA | import React, { Component } from 'react';
import axios from 'axios';
import * as toastify from '../../functions/Toastify';
import styled from 'styled-components';
UploadAgentImage;
import UploadAgentImage from '../../components/UploadAgentImage';
import Avatar from '../icons/userprofile.jpg';
// Import ModeEdit from 'material-ui/svg-icons/editor/mode-edit';
import TextField from 'material-ui/TextField';
import RaisedButton from 'material-ui/RaisedButton';
// Import { RadioButton, RadioButtonGroup } from 'material-ui/RadioButton';
import FloatingActionButton from 'material-ui/FloatingActionButton';
import EditBtn from 'material-ui/svg-icons/content/create';
const stylesRB = {
block: {
maxWidth: 250
},
radioButton: {
marginBottom: 16
}
};
const ImageProfile = styled.img`
width: 100%;
`;
const SectionContainer = styled.div`
margin-bottom: 20px;
.col-md-10 {
padding-left: 35px;
margin-bottom: 50px;
}
p {
font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
}
.col-md-2 {
padding: 0px;
}
.name {
font-weight: 700 !important;
color: #484848 !important;
font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
margin: 0px !important;
word-wrap: break-word !important;
font-size: 36px !important;
line-height: 44px !important;
letter-spacing: -0.6px !important;
padding-top: 6px !important;
margin-bottom: 10px;
padding-bottom: 10px;
display: block;
}
.title {
color: #484848 !important;
font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
font-size: 17px !important;
font-weight: 300 !important;
letter-spacing: 0.2px !important;
line-height: 22px !important;
}
h2 {
font-family: Georgia;
font-size: 18px;
font-style: italic;
font-weight: bold;
padding-bottom: 10px;
margin: 0px;
}
.IconRowDivider {
border-top: 1px solid #dce0e0;
border-bottom: 1px solid #dce0e0;
display: flex;
justify-content: space-around;
padding: 10px;
img {
margin: 6px auto;
display: block;
}
p {
color: #484848 !important;
font-family: Circular,-apple-system,BlinkMacSystemFont,Roboto,Helvetica Neue,sans-serif !important;
font-size: 14px !important;
font-weight: 300 !important;
letter-spacing: 0.2px !important;
line-height: 22px !important;
}
}
`;
// Const SectionContainer = styled.div`
// margin-bottom: 20px;
// .col-md-10 {
// border-left: solid 1px #eaebec;
// padding-left: 35px;
// margin-bottom: 50px;
// }
// p {
// font-family: 'Open Sans', 'Helvetica Neue', Helvetica, Arial, sans-serif;
// }
// .col-md-2 {
// padding: 0px;
// }
// h2 {
// font-family: Georgia;
// font-size: 18px;
// font-style: italic;
// font-weight: bold;
// border-bottom: 1px #ccc solid;
// padding-bottom: 10px;
// margin: 0px;
// }
// `;
export default class AgentDetails extends React.Component {
constructor(props) {
super(props);
this.state = {
editMode: false,
loading: false,
agentId: props.agent.AgentID,
name: props.agent.Name,
image: props.agent.Image,
title: props.agent.Title,
description: props.agent.Description
};
this.setNewValueToState = this.setNewValueToState.bind(this);
}
getNewImage() {
axios.get('http://54.190.49.213/index.php/api/agents/getAgent', {
params: {
id: this.state.agentId
}
}).then(response => {
this.setState({ image: response.data[0].Image });
this.forceUpdate();
}).catch(error => {
});
}
editSection() {
this.setState({ editMode: !this.state.editMode });
}
setNewValueToState(event) {
switch (event.target.id) {
case 'name':
this.setState({ name: event.target.value });
break;
case 'image':
this.setState({ image: event.target.value });
break;
case 'title':
this.setState({ title: event.target.value });
break;
case 'description':
this.setState({ description: event.target.value });
break;
}
}
renderCardBlock() {
if (this.state.editMode) {
return (
// <div className="card-block col-md-10">
<div className="card-block">
<div className="col-md-12 editArea">
{/* Name: <TextField
id={'name'}
onChange={this.setNewValueToState}
defaultValue={this.state.name}
fullWidth={true}
/>
Email: <TextField
id={'title'}
onChange={this.setNewValueToState}
defaultValue={this.state.title}
fullWidth={true}
/>
Description: <TextField
id={'description'}
onChange={this.setNewValueToState}
defaultValue={this.state.description}
fullWidth={true}
multiLine={true}
rows={3}
/> */}
<div className="col-md-5">
Name:
</div>
<div className="col-md-7">
<TextField
id={'name'}
defaultValue={this.state.name}
onChange={this.setNewValueToState}
fullWidth={true}
/>
</div>
<div className="col-md-5">
Title:
</div>
<div className="col-md-7">
<TextField
id={'title'}
defaultValue={this.state.title}
onChange={this.setNewValueToState}
fullWidth={true}
/>
</div>
<div className="col-md-5">
Description:
</div>
<div className="col-md-7">
<TextField
defaultValue={this.state.description}
id={'description'}
onChange={this.setNewValueToState}
fullWidth={true}
multiLine={true}
rows={3}
/>
</div>
{/* Image: <TextField
id={'image'}
onChange={this.setNewValueToState}
defaultValue={this.state.image}
fullWidth={true}
/> */}
{this.renderUpdateButton()}
{this.renderUploadImage()}
</div>
</div>
);
}
// <div className="card-block col-md-10">
return (
<div className="col-md-12">
<div className="card-block col-md-3">
<ImageProfile src={this.state.image} />
</div>
<div className="col-md-7">
<p className="name">{this.state.name} </p>
<p className="title"> <b> {this.state.title} </b> </p>
<p className="card-text"><b> Description:</b> {this.state.description}</p>
</div>
</div>
);
}
updateSection(event) {
event.preventDefault();
axios({
method: 'post',
url: 'http://54.190.49.213/index.php/api/agents/editAgent',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: {
agentId: this.state.agentId,
name: this.state.name,
image: this.state.image,
title: this.state.title,
description: this.state.description
}
}).then(res => {
toastify.notifySuccess(toastify.messages.updateSuccess);
this.setState({ editMode: false });
})
.catch(error => {
toastify.notifyErorr(toastify.messages.updateError);
});
}
renderUploadImage() {
return (<UploadAgentImage id={this.state.agentId} key={0} renderFilesAgain={() => {
this.getNewImage();
}} />);
}
renderUpdateButton() {
return (
<div>
<div className="updateSectionsBtnsGroup">
<RaisedButton className="updateSectionsBtn" label="Cancel" onClick={this.editSection.bind(this)} />
<RaisedButton className="updateSectionsBtn" label="Save" primary={true} onTouchTap={this.handleToggle} onClick={this.updateSection.bind(this)} />
</div>
</div>
);
}
renderEditBtn() {
return (
<div>
<h4>
<FloatingActionButton onClick={this.editSection.bind(this)} mini={true} className="addEditBtn" >
<EditBtn />
</FloatingActionButton>
</h4>
<br />
</div>
);
}
render() {
return (
<SectionContainer>
<div>
<div className="col-md-10">
</div>
{this.renderEditBtn()}
{this.renderCardBlock()}
</div>
</SectionContainer>
);
}
}
|
src/esm/components/graphics/icons/menu-icon/index.js | KissKissBankBank/kitten | import _extends from "@babel/runtime/helpers/extends";
import _objectWithoutPropertiesLoose from "@babel/runtime/helpers/objectWithoutPropertiesLoose";
var _excluded = ["color", "title"];
import React from 'react';
import PropTypes from 'prop-types';
export var MenuIcon = function MenuIcon(_ref) {
var color = _ref.color,
title = _ref.title,
props = _objectWithoutPropertiesLoose(_ref, _excluded);
return /*#__PURE__*/React.createElement("svg", _extends({
xmlns: "http://www.w3.org/2000/svg",
viewBox: "0 0 100 100",
fill: color
}, props), title && /*#__PURE__*/React.createElement("title", null, title), /*#__PURE__*/React.createElement("path", {
d: "M0 0 v20 h100 v-20 z"
}), /*#__PURE__*/React.createElement("path", {
d: "M0 40 v20 h100 v-20 z"
}), /*#__PURE__*/React.createElement("path", {
d: "M0 80 v20 h100 v-20 z"
}));
};
MenuIcon.propTypes = {
color: PropTypes.string,
title: PropTypes.string
};
MenuIcon.defaultProps = {
color: '#222',
title: ''
}; |
src/main.js | nivas8292/myapp | import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import './styles/main.scss'
// Store Initialization
// ------------------------------------
const store = createStore(window.__INITIAL_STATE__)
// Render Setup
// ------------------------------------
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const App = require('./components/App').default
const routes = require('./routes/index').default(store)
ReactDOM.render(
<App store={store} routes={routes} />,
MOUNT_NODE
)
}
// Development Tools
// ------------------------------------
if (__DEV__) {
if (module.hot) {
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
render = () => {
try {
renderApp()
} catch (e) {
console.error(e)
renderError(e)
}
}
// Setup hot module replacement
module.hot.accept([
'./components/App',
'./routes/index',
], () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// Let's Go!
// ------------------------------------
if (!__TEST__) render()
|
index.android.js | rldona/ReactNativeCourseBeeva | import React, { Component } from 'react';
import { AppRegistry } from 'react-native';
import { App } from './src';
AppRegistry.registerComponent('ReactNativeCourseBeeva', () => App);
|
tp-3/euge/src/components/layout/Header.js | jpgonzalezquinteros/sovos-reactivo-2017 | import React from 'react';
import { NavLink } from 'react-router-dom';
import darkBaseTheme from 'material-ui/styles/baseThemes/darkBaseTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import AppBar from 'material-ui/AppBar';
// import RaisedButton from 'material-ui/RaisedButton';
const Header = () => {
const activeStyle = {
padding:3,
backgroundColor: 'grey',
border: '2px dashed red',
};
const menuStyle = {
padding:3,
backgroundColor: 'grey',
border: '2px dashed red',
};
const style = {
margin: 8,
};
const appbarstyle = {
paddingTop:1,
paddingLeft:1,
margin: 1,
};
return (
<MuiThemeProvider muiTheme={getMuiTheme(darkBaseTheme)}>
<div>
<div className="headStyle">
<AppBar style={appbarstyle} title="Sovos Reactivo" />
<div style={menuStyle}>
<NavLink exact to="/" >Dashboard</NavLink>
{' | '}
<NavLink to="/alumnos" activeStyle={activeStyle}>Alumnos</NavLink>
{' | '}
<NavLink to="/materias" activeStyle={activeStyle}>Materias</NavLink>
{' | '}
<NavLink to="/profesores" activeStyle={activeStyle}>Profesores</NavLink>
{' | '}
<NavLink to="/cursado" activeStyle={activeStyle}>Cursado</NavLink>
{' | '}
<NavLink to="/about" activeStyle={activeStyle}>About</NavLink>
</div>
</div>
</div>
</MuiThemeProvider>
);
};
export default Header;
|
src/containers/Admin/Alerts/Alerts.js | EncontrAR/backoffice | import React, { Component } from 'react';
import Table from '../../../components/uielements/table';
import Pagination from '../../../components/uielements/pagination';
import Button from '../../../components/uielements/button';
import alertActions from '../../../redux/alert/actions';
import { Row, Col } from 'antd';
import Moment from 'react-moment';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
const {
indexAlertsForCampaign
} = alertActions;
const columns = [{
title: 'Id',
dataIndex: 'id',
key: 'id'
}, {
title: 'Título',
dataIndex: 'title',
key: 'title'
}, {
title: 'Zona',
key: 'zone',
render: (text, record) => (
<span>{record.zone.label}</span>
),
}, {
title: 'Notificaciones enviadas',
dataIndex: 'notifications_sent',
key: 'notifications_sent'
}, {
title: 'Fecha de creación',
key: 'created_at',
render: (text, record) => (
<span>
<Moment format="DD/MM/YYYY">{record.created_at}</Moment>
</span>
)
}, {
title: 'Acción',
key: 'action',
render: (text, record) => (
<span>
<Link to={`/admin/alerts/${record.id}`}>Ver detalle</Link>
</span>
),
}];
const initialPage = 1
const itemsPerPage = 10
class Alerts extends Component {
componentWillMount() {
this.loadAlertsPage(initialPage)
}
loadAlertsPage = (page) => {
this.props.indexAlertsForCampaign(this.props.campaignId, page, itemsPerPage)
}
render() {
return (
<div>
<div className="isoLayoutContentWrapper">
<div className="isoLayoutContent">
<Row type="flex" justify="space-between">
<Col span={4}>
<h2>Lista de alertas</h2>
</Col>
<Col span={4}>
<Button type="primary">
<Link to={`/admin/campaigns/${this.props.campaignId}/alerts/new`} params={{ campaignId: this.props.campaignId }}>Nuevo alerta</Link>
</Button>
</Col>
</Row>
<br />
<div className="isoSimpleTable">
<Table
pagination={false}
columns={ columns }
dataSource={ this.props.alerts }
/>
</div>
<br />
<Pagination defaultPageSize={itemsPerPage}
defaultCurrent={initialPage}
total={this.props.total_pages}
onChange={this.loadAlertsPage} />
</div>
</div>
</div>
);
}
}
function mapStateToProps(state) {
const { alerts, total_pages, total_count } = state.Alert;
return {
alerts: alerts,
total_pages: total_pages,
total_count: total_count
};
}
export default connect(mapStateToProps, { indexAlertsForCampaign })(Alerts); |
src/svg-icons/device/location-searching.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceLocationSearching = (props) => (
<SvgIcon {...props}>
<path d="M20.94 11c-.46-4.17-3.77-7.48-7.94-7.94V1h-2v2.06C6.83 3.52 3.52 6.83 3.06 11H1v2h2.06c.46 4.17 3.77 7.48 7.94 7.94V23h2v-2.06c4.17-.46 7.48-3.77 7.94-7.94H23v-2h-2.06zM12 19c-3.87 0-7-3.13-7-7s3.13-7 7-7 7 3.13 7 7-3.13 7-7 7z"/>
</SvgIcon>
);
DeviceLocationSearching = pure(DeviceLocationSearching);
DeviceLocationSearching.displayName = 'DeviceLocationSearching';
DeviceLocationSearching.muiName = 'SvgIcon';
export default DeviceLocationSearching;
|
content/gocms/src/base/components/gForm/GTextArea.js | gocms-io/gocms | import React from 'react';
import CSSTransitionGroup from 'react-transition-group/CSSTransitionGroup'
import {HOC} from 'formsy-react';
class GTextArea extends React.Component {
constructor(props) {
super(props);
this.state = {
blurred: false,
dirty: false,
name: this.props.name || ""
};
this.changeValue = this.changeValue.bind(this);
this.handelBlur = this.handelBlur.bind(this);
this.enableSubmitButton = this.changeValue.bind(this);
}
componentWillReceiveProps(nextProps) {
if (!!nextProps.dirty ) {
this.setState({dirty: true});
}
if (!!nextProps.name) {
this.setState({name: nextProps.name});
}
}
changeValue(event) {
this.props.setValue(event.currentTarget.value);
if (!!this.props.onChange) {
this.props.onChange(event);
}
}
handelBlur() {
if (!!this.props.getValue()) {
this.setState({blurred: true})
}
else {
this.setState({blurred: false})
}
}
render() {
const className = this.props.showRequired() ? 'g-input-required' : this.props.showError() ? 'g-input-required' : null;
// An error message is returned ONLY if the component is invalid
// or the server has returned an error message
let errorMessage = [];
if (this.state.blurred && this.props.getErrorMessage()) {
errorMessage = this.props.getErrorMessage();
}
else if (this.state.dirty && this.props.showRequired()) {
errorMessage = "*Required";
}
return (
<div className={"g-container-col g-input " + (this.props.className || "")}>
<label htmlFor={this.state.name}>{this.props.label}
<CSSTransitionGroup transitionName="g-input-error-message-animate"
transitionEnterTimeout={500}
transitionLeaveTimeout={500}>
{errorMessage != "" ? <span className="g-input-error-message">{errorMessage}</span> : null}
</CSSTransitionGroup>
</label>
<textarea type={this.props.type}
name={this.props.name}
onChange={this.changeValue}
onBlur={this.handelBlur}
value={this.props.getValue() || ''}
/>
</div>
);
}
}
export default HOC(GTextArea);
|
src/App.js | wecandothis/react-antd-more | /*
1.根据路由器实现代码拆分,按需加载,import()
*/
import React, { Component } from 'react';
import {HashRouter as Router,Route} from "react-router-dom"
import Header from "./layout/Header"
import Footer from "./layout/Footer"
import Home from "./contains/home"
import Delit from "./components/about/delit"
import Bundle from "./bundle"
const About =()=>(
<Bundle load={()=>import('./contains/about')}>
{(About)=><About />}
</Bundle>
)
const Contact =()=>(
<Bundle load={()=>import('./contains/contact')}>
{(Contact)=><Contact />}
</Bundle>
)
const Issue =()=>(
<Bundle load={()=>import('./contains/issue')}>
{(Issue)=><Issue />}
</Bundle>
)
class App extends Component {
render(){
return <Router>
<div>
<Header />
<Route exact path="/" component={Home} />
<Route exact path="/about" component={About} />
<Route path="/contact" component={Contact} />
<Route path="/issue" component={Issue} />
<Route path="/about/:id" component={Delit} />
<Footer />
</div>
</Router>
}
}
export default App;
|
BarCollapsible.js | caroaguilar/react-native-bar-collapsible | 'use strict';
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {
Animated,
View,
Text,
TouchableHighlight
} from 'react-native';
import Icon from 'react-native-vector-icons/FontAwesome';
import styles from './style'
class BarCollapsible extends Component {
constructor(props) {
super(props);
this.state = {
fadeAnim: new Animated.Value(0),
icon: props.icon,
onPressed: null,
title: '',
children: null,
show: props.showOnStart
};
}
static propTypes = {
style: View.propTypes.style,
titleStyle: Text.propTypes.style,
tintColor: PropTypes.string,
}
static defaultProps = {
showOnStart: false,
icon: 'angle-right',
iconOpened: 'minus',
iconActive: 'plus',
iconCollapsed: 'plus',
tintColor: '#fff',
iconSize: 30
}
componentWillMount() {
const {
collapsible,
clickable,
icon,
title,
tintColor,
iconSize,
iconOpened,
iconActive,
iconCollapsed,
showOnStart,
onPressed
} = this.props;
const {fadeAnim} = this.state;
if (clickable) {
this.setState({
icon,
onPressed,
title
});
} else if (collapsible) {
this.setState({
icon: showOnStart ? iconOpened : iconActive,
iconCollapsed,
iconOpened,
title
}, Animated.timing(fadeAnim, { toValue: 1 }).start());
} else {
this.setState({title});
}
}
toggleView = () => {
const {show, iconCollapsed, iconOpened} = this.state;
this.setState({
show: !show,
icon: show ? iconCollapsed : iconOpened
});
}
renderDefault = () => {
const {titleStyle} = this.props;
const {title} = this.state;
return (
<View style={styles.bar}>
<Text style={[styles.title, titleStyle]}>
{title}
</Text>
</View>
);
}
renderCollapsible = () => {
const {
style,
iconStyle,
titleStyle,
tintColor,
iconSize,
children
} = this.props;
const {icon, fadeAnim, title} = this.state;
return (
<View>
<TouchableHighlight
style={styles.barWrapper}
underlayColor='transparent'
onPress={this.toggleView}
>
<View style={[styles.bar, style]}>
<Text style={[styles.title, titleStyle]}>
{title}
</Text>
<Icon
name={icon}
size={iconSize}
color={tintColor}
style={[styles.icon, iconStyle]}
/>
</View>
</TouchableHighlight>
{ this.state.show &&
<Animated.View
style={{opacity: fadeAnim}}
>
{children}
</Animated.View>
}
</View>
);
}
renderClickable = () => {
const {
style,
titleStyle,
tintColor,
iconSize,
iconStyle
} = this.props;
const {icon, title, onPressed} = this.state;
return (
<TouchableHighlight
style={styles.barWrapper}
underlayColor='transparent'
onPress={onPressed}
>
<View style={[styles.bar, style]}>
<Text style={[styles.title, titleStyle]}>
{title}
</Text>
<Icon
name={icon}
size={iconSize}
color={tintColor}
style={[styles.icon, iconStyle]}
/>
</View>
</TouchableHighlight>
);
}
render() {
const {clickable, collapsible} = this.props;
if (clickable) {
return this.renderClickable();
} else if (collapsible) {
return this.renderCollapsible();
} else {
return this.renderDefault();
}
}
}
export default BarCollapsible; |
renderer/hocs/withInputValidation.js | LN-Zap/zap-desktop | import React from 'react'
import PropTypes from 'prop-types'
import * as yup from 'yup'
import getDisplayName from '@zap/utils/getDisplayName'
/**
* withInputValidation - A HOC that will add validation of a `required` property to a field.
*
* @param {React.Component} Component Component to wrap
* @returns {React.Component} Wrapped component
*/
const withInputValidation = Component =>
class extends React.Component {
static displayName = `WithInputValidation(${getDisplayName(Component)})`
static propTypes = {
isDisabled: PropTypes.bool,
isRequired: PropTypes.bool,
maxLength: PropTypes.number,
minLength: PropTypes.number,
validate: PropTypes.func,
}
static defaultProps = {
isDisabled: false,
isRequired: false,
}
validate = (value = '') => {
const { isDisabled, isRequired, minLength, maxLength } = this.props
if (isDisabled) {
return undefined
}
try {
let validator = yup.string()
if (isRequired) {
validator = validator.required()
}
if (minLength) {
validator = validator.min(minLength)
}
if (maxLength) {
validator = validator.max(maxLength)
}
validator.validateSync(value)
} catch (error) {
return error.message
}
// Run any additional validation provided by the caller.
const { validate } = this.props
if (validate) {
return validate(value)
}
return undefined
}
render() {
return <Component {...this.props} validate={this.validate} />
}
}
export default withInputValidation
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.