path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
src/components/Layout.js | Arunvirat/Logi-heroes | 'use strict';
import React from 'react';
import { Link } from 'react-router';
export default class Layout extends React.Component {
getDate()
{
return new Date().toLocaleDateString();
}
render() {
return (
<div className="app-container">
<header>
<div className="datediv">
<label>{this.getDate()}</label>
</div>
<div>
<Link to="/">
<label className="logo logoheading">Logi Heroes</label>
</Link>
</div>
</header>
<div className="app-content">{this.props.children}</div>
<footer>
<p>
Know your clan's positions and keep up the momentum <strong>I love the winning, I can take the losing, but most of all I Love to play. </strong> and <strong>Participate to win gifts</strong>.
</p>
</footer>
</div>
);
}
}
|
internals/templates/containers/NotFoundPage/index.js | MaleSharker/Qingyan | /**
* NotFoundPage
*
* This is the page we show when the user visits a url that doesn't have a 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 NotFound extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
render() {
return (
<h1>
<FormattedMessage {...messages.header} />
</h1>
);
}
}
|
src/views/GestionsComponents/Stocks/GestionDesStocks.js | Cruis-R/GestionOutil | import React, { Component } from 'react';
import { BootstrapTable, TableHeaderColumn } from 'react-bootstrap-table';
export default class GestionDesUtilisateurs extends Component {
render(){
const data = [];
return(
<div className="animated fadeIn">
<div className="row">
<div className="col-lg-12">
<div className="card">
<div className="card-header">
<i className="fa fa-align-justify"></i> Gestion des Utilisateurs
</div>
<div className="card-block">
<BootstrapTable
data={ data }
headerStyle = { { "backgroundColor" : "rgb(142, 194, 231)" } }>
<TableHeaderColumn
dataField="name"
isKey
dataSort
width="70px"
>
Name
</TableHeaderColumn>
<TableHeaderColumn
dataField="status"
dataSort
width="70px">
Status
</TableHeaderColumn>
<TableHeaderColumn
dataField="updateTime"
dataSort
width="120px">
UpdateTime
</TableHeaderColumn>
</BootstrapTable>
</div>
</div>
</div>
</div>
</div>
);
}
}
|
packages/react-scripts/fixtures/kitchensink/src/features/env/PublicUrl.js | GreenGremlin/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
export default () => (
<span id="feature-public-url">{process.env.PUBLIC_URL}.</span>
);
|
src/containers/MasterWindow.js | metasfresh/metasfresh-webui-frontend | import PropTypes from 'prop-types';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { push } from 'react-router-redux';
import { forEach, get } from 'lodash';
import { addNotification } from '../actions/AppActions';
import {
addRowData,
attachFileAction,
clearMasterData,
fireUpdateData,
sortTab,
updateTabRowsData,
} from '../actions/WindowActions';
import { connectWS, disconnectWS } from '../utils/websockets';
import { getTab, getRowsData } from '../api';
import MasterWindow from '../components/app/MasterWindow';
/**
* @file Class based component.
* @module MasterWindow
* @extends Component
*/
class MasterWindowContainer extends Component {
static contextTypes = {
router: PropTypes.object.isRequired,
};
componentDidUpdate(prevProps) {
const { master, modal, params, addRowData } = this.props;
if (prevProps.master.websocket !== master.websocket && master.websocket) {
// websockets are responsible for pushing info about any updates to the data
// displayed in tabs. This is the only place we're updating this apart of
// initial load (so contrary to what we used to do, we're not handling responses
// from any user actions now, like batch entry for instance)
disconnectWS.call(this);
// ^^ - for the case where we come from different area like Phonecall Schedule and then
// we go via it to Sales Order master.websocket is changed and by doing that we assure that
// communication is set on the right master.websocket . disconnectWS clears the WS
connectWS.call(this, master.websocket, async (msg) => {
this.onWebsocketEvent(msg);
});
}
// When closing modal, we need to update the stale tab
// TODO: Check if we still need to do this since all the changes in tabs should be handled
// via websockets now.
if (
!modal.visible &&
modal.visible !== prevProps.modal.visible &&
master.includedTabsInfo &&
master.layout
) {
const tabId = master.layout.activeTab;
getTab(tabId, params.windowType, master.docId).then((tab) => {
addRowData({ [tabId]: tab }, 'master');
});
}
}
async onWebsocketEvent(event) {
const { includedTabsInfo, stale } = event;
const activeTab = includedTabsInfo
? Object.values(includedTabsInfo).find((tabInfo) =>
this.isActiveTab(tabInfo.tabId)
)
: null;
// Document header got staled
if (stale) {
const { params, fireUpdateData } = this.props;
fireUpdateData({
windowId: params.windowType,
documentId: params.docId,
doNotFetchIncludedTabs: true,
});
}
// Active included tab got staled
if (activeTab) {
// Full tab got staled
if (activeTab.stale) {
this.refreshActiveTab();
}
// Some included rows got staled
else {
const { staleRowIds } = activeTab;
await this.getTabRow(activeTab.tabId, staleRowIds).then((res) => {
this.mergeDataIntoIncludedTab(res);
});
}
}
}
getTabRow(tabId, rows) {
const {
params: { windowType, docId },
} = this.props;
return getRowsData({
entity: 'window',
docType: windowType,
docId,
tabId: tabId,
rows,
}).catch(() => ({ rows, tabId }));
}
isActiveTab(tabId) {
const { master } = this.props;
return tabId === master.layout.activeTab;
}
mergeDataIntoIncludedTab(response) {
const { updateTabRowsData } = this.props;
const { data } = response;
const changedTabs = {};
let rowsById = null;
let removedRows = null;
let tabId;
// removed row
if (!data) {
removedRows = removedRows || {};
removedRows[response.rowId] = true;
tabId = !tabId && response.tabId;
} else {
rowsById = rowsById || {};
const rowZero = data[0];
tabId = !tabId && rowZero.tabId;
data.forEach((row) => {
rowsById[row.rowId] = { ...row };
});
}
changedTabs[tabId] = get(changedTabs, `${tabId}`, {});
if (rowsById) {
changedTabs[tabId].changed = {
...get(changedTabs, `${tabId}.changed`, {}),
...rowsById,
};
}
if (removedRows) {
changedTabs[tabId].removed = {
...get(changedTabs, `${tabId}.removed`, {}),
...removedRows,
};
}
forEach(changedTabs, (rowsChanged, tabId) => {
updateTabRowsData('master', tabId, rowsChanged);
});
}
refreshActiveTab() {
const { master, params, addRowData } = this.props;
const activeTabId = master.layout.activeTab;
if (!activeTabId) {
return;
}
const tabLayout =
master.layout.tabs &&
master.layout.tabs.filter((tab) => tab.tabId === activeTabId)[0];
const orderBy = tabLayout.orderBy;
let sortingOrder = null;
if (orderBy && orderBy.length) {
const ordering = orderBy[0];
sortingOrder = (ordering.ascending ? '+' : '-') + ordering.fieldName;
}
getTab(activeTabId, params.windowType, master.docId, sortingOrder).then(
(tab) => {
addRowData({ [activeTabId]: tab }, 'master');
}
);
}
componentWillUnmount() {
const { clearMasterData } = this.props;
clearMasterData();
disconnectWS.call(this);
}
render() {
return <MasterWindow {...this.props} />;
}
}
/**
* @typedef {object} Props Component props
* @prop {object} modal
* @prop {object} master
* @prop {array} breadcrumb
* @prop {func} dispatch
* @prop {object} rawModal
* @prop {string} indicator
* @prop {object} me
* @prop {object} [pluginModal]
* @prop {object} [overlay]
* @prop {bool} [allowShortcut]
* @prop {*} [params]
* @prop {*} [includedView]
* @prop {*} [processStatus]
* @prop {*} [enableTutorial]
* @prop {*} [location]
* @prop {func} addNotification
* @prop {func} addRowData
* @prop {func} attachFileAction
* @prop {func} sortTab
* @prop {func} push
* @prop {func} clearMasterData
* @prop {func} fireUpdateData
* @prop {func} updateTabRowsdata
*/
MasterWindowContainer.propTypes = {
modal: PropTypes.object.isRequired,
master: PropTypes.object.isRequired,
breadcrumb: PropTypes.array.isRequired,
rawModal: PropTypes.object.isRequired,
indicator: PropTypes.string.isRequired,
me: PropTypes.object.isRequired,
pluginModal: PropTypes.object,
overlay: PropTypes.object,
allowShortcut: PropTypes.bool,
params: PropTypes.any,
includedView: PropTypes.any,
processStatus: PropTypes.any,
enableTutorial: PropTypes.any,
location: PropTypes.any,
clearMasterData: PropTypes.func,
addNotification: PropTypes.func,
addRowData: PropTypes.func,
attachFileAction: PropTypes.func,
fireUpdateData: PropTypes.func,
sortTab: PropTypes.func,
updateTabRowsData: PropTypes.func,
push: PropTypes.func,
};
/**
* @method mapStateToProps
* @summary ToDo: Describe the method.
* @param {object} state
*/
const mapStateToProps = (state) => ({
master: state.windowHandler.master,
modal: state.windowHandler.modal,
rawModal: state.windowHandler.rawModal,
pluginModal: state.windowHandler.pluginModal,
overlay: state.windowHandler.overlay,
indicator: state.windowHandler.indicator,
includedView: state.listHandler.includedView,
allowShortcut: state.windowHandler.allowShortcut,
enableTutorial: state.appHandler.enableTutorial,
processStatus: state.appHandler.processStatus,
me: state.appHandler.me,
breadcrumb: state.menuHandler.breadcrumb,
});
export default connect(
mapStateToProps,
{
addNotification,
addRowData,
attachFileAction,
clearMasterData,
fireUpdateData,
sortTab,
updateTabRowsData,
push,
}
)(MasterWindowContainer);
|
projects/twitch-ui/src/utils/renderer.js | unindented/twitch-x | import React from 'react'
import renderer from 'react-test-renderer'
import {ThemeProvider} from 'styled-components'
import themes from '../themes'
export function renderWithTheme (node, theme = 'default') {
return renderer.create(
<ThemeProvider theme={themes[theme]}>
{node}
</ThemeProvider>
)
}
|
src/docs/examples/TextInputStyledComponents/ExampleError.js | vonZ/rc-vvz | import React from 'react';
import TextInputStyledComponents from 'ps-react/TextInputStyledComponents';
/** Required TextBox with error */
export default class ExampleError extends React.Component {
render() {
return (
<TextInputStyledComponents
htmlId="example-optional"
label="First Name"
name="firstname"
onChange={() => {}}
required
error="First name is required."
/>
)
}
}
|
src/TextField/EnhancedTextarea.js | skarnecki/material-ui | import React from 'react';
import EventListener from 'react-event-listener';
const rowsHeight = 24;
function getStyles(props, context, state) {
return {
root: {
position: 'relative', // because the shadow has position: 'absolute'
},
textarea: {
height: state.height,
width: '100%',
resize: 'none',
font: 'inherit',
padding: 0,
cursor: props.disabled ? 'default' : 'initial',
},
shadow: {
resize: 'none',
// Overflow also needed to here to remove the extra row
// added to textareas in Firefox.
overflow: 'hidden',
// Visibility needed to hide the extra text area on ipads
visibility: 'hidden',
position: 'absolute',
height: 'initial',
},
};
}
class EnhancedTextarea extends React.Component {
static propTypes = {
defaultValue: React.PropTypes.any,
disabled: React.PropTypes.bool,
onChange: React.PropTypes.func,
onHeightChange: React.PropTypes.func,
rows: React.PropTypes.number,
rowsMax: React.PropTypes.number,
shadowStyle: React.PropTypes.object,
/**
* Override the inline-styles of the root element.
*/
style: React.PropTypes.object,
textareaStyle: React.PropTypes.object,
value: React.PropTypes.string,
valueLink: React.PropTypes.object,
};
static defaultProps = {
rows: 1,
};
static contextTypes = {
muiTheme: React.PropTypes.object.isRequired,
};
state = {
height: this.props.rows * rowsHeight,
};
componentDidMount() {
this.syncHeightWithShadow();
}
componentWillReceiveProps(nextProps) {
if (nextProps.value !== this.props.value) {
this.syncHeightWithShadow(nextProps.value);
}
}
handleResize = (event) => {
this.syncHeightWithShadow(undefined, event);
};
getInputNode() {
return this.refs.input;
}
setValue(value) {
this.getInputNode().value = value;
this.syncHeightWithShadow(value);
}
syncHeightWithShadow(newValue, event) {
const shadow = this.refs.shadow;
if (newValue !== undefined) {
shadow.value = newValue;
}
let newHeight = shadow.scrollHeight;
if (this.props.rowsMax >= this.props.rows) {
newHeight = Math.min(this.props.rowsMax * rowsHeight, newHeight);
}
newHeight = Math.max(newHeight, rowsHeight);
if (this.state.height !== newHeight) {
this.setState({
height: newHeight,
});
if (this.props.onHeightChange) {
this.props.onHeightChange(event, newHeight);
}
}
}
handleChange = (event) => {
this.syncHeightWithShadow(event.target.value);
if (this.props.hasOwnProperty('valueLink')) {
this.props.valueLink.requestChange(event.target.value);
}
if (this.props.onChange) {
this.props.onChange(event);
}
};
render() {
const {
onChange, // eslint-disable-line no-unused-vars
onHeightChange, // eslint-disable-line no-unused-vars
rows, // eslint-disable-line no-unused-vars
shadowStyle,
style,
textareaStyle,
valueLink, // eslint-disable-line no-unused-vars
...other,
} = this.props;
const {prepareStyles} = this.context.muiTheme;
const styles = getStyles(this.props, this.context, this.state);
const rootStyles = Object.assign({}, styles.root, style);
const textareaStyles = Object.assign({}, styles.textarea, textareaStyle);
const shadowStyles = Object.assign({}, textareaStyles, styles.shadow, shadowStyle);
if (this.props.hasOwnProperty('valueLink')) {
other.value = this.props.valueLink.value;
}
return (
<div style={prepareStyles(rootStyles)}>
<EventListener elementName="window" onResize={this.handleResize} />
<textarea
ref="shadow"
style={prepareStyles(shadowStyles)}
tabIndex="-1"
rows={this.props.rows}
defaultValue={this.props.defaultValue}
readOnly={true}
value={this.props.value}
valueLink={this.props.valueLink}
/>
<textarea
{...other}
ref="input"
rows={this.props.rows}
style={prepareStyles(textareaStyles)}
onChange={this.handleChange}
/>
</div>
);
}
}
export default EnhancedTextarea;
|
imports/ui/components/friends/FriendsList.js | KyneSilverhide/expense-manager | /* eslint-disable no-confusing-arrow */
import React from 'react';
import { browserHistory } from 'react-router';
import { Bert } from 'meteor/themeteorchef:bert';
import FontAwesome from 'react-fontawesome';
import Dialog, {
DialogActions,
DialogContent,
DialogContentText,
DialogTitle,
} from 'material-ui/Dialog';
import List, { ListItem, ListItemText, ListItemSecondaryAction } from 'material-ui/List';
import Slide from 'material-ui/transitions/Slide';
import Button from 'material-ui/Button';
import IconButton from 'material-ui/IconButton';
import { removeFriend } from '../../../api/friends/friend.methods.js';
import { sortByMail } from '../../../modules/sorting.js';
import FriendAvatar from './FriendAvatar';
const handleEdit = (_id) => {
browserHistory.push(`/friends/${_id}/edit`);
};
export default class FriendsList extends React.Component {
constructor(props) {
super(props);
this.state = { showDeleteDialog: false, selectedFriend: null };
}
showDeleteDialog(friend) {
this.setState({ showDeleteDialog: true, selectedFriend: friend });
}
closeDeleteDialog() {
this.setState({ showDeleteDialog: false });
}
handleRemove() {
if (this.state.selectedFriend) {
removeFriend.call({ _id: this.state.selectedFriend._id }, (error) => {
if (error) {
Bert.alert(error.reason, 'danger');
} else {
Bert.alert('Friend has been removed', 'success');
this.closeDeleteDialog();
browserHistory.push('/friends');
}
});
}
}
friendIsNotUser(friend) {
return friend.userId !== Meteor.userId();
}
render() {
const { friends } = this.props;
return friends.length > 0
? <List>
{friends.sort(sortByMail).map(friend => (
<ListItem key={friend._id}>
<FriendAvatar friend={friend} />
<ListItemText
inset
primary={`${friend.firstname} ${friend.lastname}`}
secondary={friend.email}
/>
<ListItemSecondaryAction>
{this.friendIsNotUser(friend) &&
<IconButton onClick={() => handleEdit(friend._id)}>
<FontAwesome name="pencil" />
</IconButton>}
{this.friendIsNotUser(friend) &&
<IconButton className="btn-danger" onClick={() => this.showDeleteDialog(friend)}>
<FontAwesome name="trash" />
</IconButton>}
</ListItemSecondaryAction>
</ListItem>
))}
<Dialog
open={this.state.showDeleteDialog}
transition={Slide}
onRequestClose={() => this.closeDeleteDialog()}
>
<DialogTitle>
{
`Are you sure you want to delete "${this.state.selectedFriend && this.state.selectedFriend.email}"`
}
</DialogTitle>
<DialogContent>
<DialogContentText>
Deleting a friend may break unpaid expenses
</DialogContentText>
</DialogContent>
<DialogActions>
<Button onClick={() => this.closeDeleteDialog()} color="primary">
<FontAwesome name="undo" /> Cancel
</Button>
<Button onClick={() => this.handleRemove()} color="primary">
<FontAwesome name="trash" /> Delete
</Button>
</DialogActions>
</Dialog>
</List>
: <List><ListItem>You don't have any friends...yet</ListItem></List>;
}
}
FriendsList.propTypes = {
friends: React.PropTypes.array,
};
|
ui/js/pages/calendar/Calendar.js | ericsoderberg/pbc-web | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import { connect } from 'react-redux';
import moment from 'moment-timezone';
import {
loadCalendar, loadCategory, unloadCalendar, unloadCategory,
} from '../../actions';
import PageHeader from '../../components/PageHeader';
import Button from '../../components/Button';
import CalendarGrid from '../../components/CalendarGrid';
import ItemContext from '../../components/ItemContext';
import Loading from '../../components/Loading';
import LeftIcon from '../../icons/Left';
import RightIcon from '../../icons/Right';
import { searchToObject } from '../../utils/Params';
const LEFT_KEY = 37;
const RIGHT_KEY = 39;
const DATE_FORMAT = 'YYYY-MM-DD';
class Calendar extends Component {
constructor() {
super();
this._load = this._load.bind(this);
this._changeDate = this._changeDate.bind(this);
this._onChangeMonth = this._onChangeMonth.bind(this);
this._onChangeYear = this._onChangeYear.bind(this);
this._onSearch = this._onSearch.bind(this);
this._onFilter = this._onFilter.bind(this);
this._onKeyDown = this._onKeyDown.bind(this);
this._onMore = this._onMore.bind(this);
this.state = {
activeCalendars: {},
days: {},
calendars: [],
searchText: '',
};
}
componentDidMount() {
const { calendar, dispatch } = this.props;
if (calendar && calendar.name) {
document.title = `${calendar.name} Calendar`;
} else {
document.title = 'Calendar';
}
this.setState(this._stateFromProps(this.props), this._load);
// Load the possible calendars
dispatch(loadCategory('calendars', { select: 'name', sort: 'name' }));
window.addEventListener('keydown', this._onKeyDown);
}
componentWillReceiveProps(nextProps) {
this.setState({ loading: false, loadingMore: false });
if (nextProps.match.params.id !== this.props.match.params.id ||
nextProps.location.search !== this.props.location.search) {
this.setState(this._stateFromProps(nextProps), this._load);
}
if (nextProps.calendar && nextProps.calendar.name) {
document.title = `${nextProps.calendar.name} Calendar`;
}
}
componentDidUpdate() {
const { loading } = this.state;
if (this._needScrollToFocus && !loading) {
this._needScrollToFocus = false;
this._scrollToFocus();
}
}
componentWillUnmount() {
const { dispatch } = this.props;
dispatch(unloadCalendar());
dispatch(unloadCategory('calendars'));
window.removeEventListener('keydown', this._onKeyDown);
}
_stateFromProps(props) {
const { location } = props;
const query = searchToObject(location.search);
let focus;
if (query.focus) {
focus = moment(query.focus, DATE_FORMAT, true);
if (!focus.isValid()) {
focus = undefined;
}
}
let date = focus;
if (!date) {
if (query.date) {
date = moment(query.date, DATE_FORMAT, true);
if (!date.isValid()) {
date = undefined;
}
}
if (!date) {
date = moment().startOf('day');
}
}
const state = {
date,
focus,
searchText: query.search,
};
this._needScrollToFocus = query.focus !== undefined;
return state;
}
_load() {
const { dispatch, match: { params: { id } } } = this.props;
const { activeCalendars, date, months, searchText } = this.state;
this.setState({ loading: true }, () => {
const ids = Object.keys(activeCalendars);
dispatch(loadCalendar({ date, searchText, id, ids, months }));
});
}
_setLocation() {
const { history } = this.props;
const { date, focus, searchText } = this.state;
// update browser location
const searchParams = [];
if (searchText) {
searchParams.push(`search=${encodeURIComponent(searchText)}`);
}
if (focus) {
searchParams.push(
`focus=${encodeURIComponent(focus.format(DATE_FORMAT))}`);
} else if (date) {
searchParams.push(`date=${encodeURIComponent(date.format(DATE_FORMAT))}`);
}
history.replace({
pathname: window.location.pathname,
search: `?${searchParams.join('&')}`,
});
}
_scrollToFocus() {
const focusWeek = document.querySelector('.calendar__week--focus');
if (focusWeek) {
const rect = focusWeek.getBoundingClientRect();
document.body.scrollTop = rect.top;
}
}
_changeDate(date) {
return () => {
this.setState({ date, focus: undefined }, () => {
this._setLocation();
this._load();
});
};
}
_onChangeMonth(event) {
const date = moment(this.state.date);
date.month(event.target.value);
this.setState({ date, focus: undefined }, () => {
this._setLocation();
this._load();
});
}
_onChangeYear(event) {
const date = moment(this.state.date);
date.year(event.target.value);
this.setState({ date, focus: undefined }, () => {
this._setLocation();
this._load();
});
}
_onSearch(event) {
const searchText = event.target.value;
this.setState({ searchText });
// throttle when user is typing
clearTimeout(this._getTimer);
this._getTimer = setTimeout(() => this._setLocation(), 100);
}
_onFilter(event) {
const { history } = this.props;
const value = event.target.value;
const search = (value && value !== 'All') ? `?name=${value}` : undefined;
history.replace({ pathname: '/calendar', search });
}
_onMore() {
this.setState({ months: 3, loadingMore: true }, this._load);
}
_onKeyDown(event) {
const { calendar } = this.state;
const key = (event.keyCode ? event.keyCode : event.which);
if (LEFT_KEY === key) {
this.setState({ date: moment(calendar.previous) }, this._get);
} else if (RIGHT_KEY === key) {
this.setState({ date: moment(calendar.next) }, this._get);
}
}
_toggleCalendar(id) {
return () => {
const nextActiveCalendars = { ...this.state.activeCalendars };
if (nextActiveCalendars[id]) {
delete nextActiveCalendars[id];
} else {
nextActiveCalendars[id] = true;
}
this.setState({ activeCalendars: nextActiveCalendars },
this._load);
};
}
_renderFilter() {
const { calendars } = this.props;
const { activeCalendars } = this.state;
const controls = calendars.map(calendar => (
<div key={calendar._id} className="filter-item box--row box--static">
<input id={calendar._id}
name={calendar._id}
type="checkbox"
checked={activeCalendars[calendar._id] || false}
onChange={this._toggleCalendar(calendar._id)} />
<label htmlFor={calendar._id}>{calendar.name}</label>
</div>
));
controls.unshift(
<div key="all" className="filter-item box--row box--static">
<input id="all-calendars"
name="all-calendars"
type="checkbox"
checked={Object.keys(activeCalendars).length === 0}
onChange={() => this.setState({ activeCalendars: {} },
this._load)} />
<label htmlFor="all-calendars">All</label>
</div>,
);
return (
<div className="page-header__drop box--column">
{controls}
</div>
);
}
render() {
const { calendar, match: { params: { id } }, session } = this.props;
const { filterActive, loadingMore, searchText, loading } = this.state;
let contents;
if (calendar) {
const date = moment(calendar.date);
let filter;
if (filterActive) {
filter = this._renderFilter();
}
const actions = [];
if (id) {
actions.push(
<Link key="add"
to={`/events/add?calendarId=${encodeURIComponent(calendar._id)}`}>
Add
</Link>,
);
actions.push(
<Link key="edit" to={`/calendars/${calendar._id}/edit`}>
Edit
</Link>,
);
} else {
actions.push(
<span key="filter" className="page-header__dropper">
<Button className="page-header__dropper-control"
label="Calendars"
onClick={() => this.setState({
filterActive: !this.state.filterActive })} />
{filter}
</span>,
);
}
const months = [];
const monthDate = moment(date).startOf('year');
while (monthDate.year() === date.year()) {
months.push(
<option key={monthDate.month()}>{monthDate.format('MMMM')}</option>,
);
monthDate.add(1, 'month');
}
const years = [];
const now = moment();
const yearDate = moment().subtract(3, 'years');
while (yearDate.year() <= (now.year() + 2)) {
years.push(
<option key={yearDate.year()}>{yearDate.format('YYYY')}</option>,
);
yearDate.add(1, 'year');
}
const grid = loading ? <Loading /> : <CalendarGrid weeks={calendar.weeks} />;
let more;
if (loadingMore) {
more = <Loading />;
} else if (session && session.userId.administrator &&
calendar.weeks && calendar.weeks.length < 7) {
more = <Button plain={true} onClick={this._onMore}>more</Button>;
}
let itemContext;
if (id && calendar) {
itemContext = (
<ItemContext filter={{ 'sections.calendarId': calendar._id }} />
);
}
contents = (
<main>
<PageHeader title={(calendar || {}).name || 'Calendar'}
homer={true}
searchText={searchText}
onSearch={this._onSearch}
actions={actions} />
<div className="calendar__header">
<button type="button"
className="button-icon"
onClick={this._changeDate(moment(calendar.previous))}>
<LeftIcon className="button__indicator" />
</button>
<span>
<select value={moment(calendar.date).format('MMMM')}
onChange={this._onChangeMonth}>
{months}
</select>
<select value={moment(calendar.date).format('YYYY')}
onChange={this._onChangeYear}>
{years}
</select>
</span>
<button type="button"
className="button-icon"
onClick={this._changeDate(moment(calendar.next))}>
<RightIcon className="button__indicator" />
</button>
</div>
{grid}
{more}
{itemContext}
</main>
);
} else {
contents = <Loading />;
}
return contents;
}
}
Calendar.propTypes = {
calendar: PropTypes.object,
calendars: PropTypes.array,
dispatch: PropTypes.func.isRequired,
history: PropTypes.any.isRequired,
location: PropTypes.object.isRequired,
match: PropTypes.shape({
params: PropTypes.shape({
id: PropTypes.string,
}).isRequired,
}).isRequired,
session: PropTypes.shape({
userId: PropTypes.shape({
administrator: PropTypes.bool,
domainIds: PropTypes.arrayOf(PropTypes.string),
}),
}),
};
Calendar.defaultProps = {
calendar: undefined,
calendars: undefined,
session: undefined,
};
const select = state => ({
calendar: state.calendar,
calendars: (state.calendars || {}).items,
session: state.session,
});
export default connect(select)(Calendar);
|
src/renderer/components/search-notifications.js | sirbrillig/gitnews-menubar | import React from 'react';
import Gridicon from 'gridicons';
export default function SearchNotifications({ searchValue, setSearchTo }) {
return <SearchField setSearchTo={setSearchTo} searchValue={searchValue} />;
}
function SearchField({ setSearchTo, searchValue }) {
return (
<div className="notifications__search-area">
<Gridicon icon="search" size={36} className="search-icon" />
<input
className="notifications__search"
type="search"
placeholder="Search"
onChange={event => setSearchTo(event.target.value)}
value={searchValue}
/>
</div>
);
}
|
ui/js/dfv/src/fields/paragraph/index.js | pods-framework/pods | import React from 'react';
import classnames from 'classnames';
import PropTypes from 'prop-types';
import { toBool } from 'dfv/src/helpers/booleans';
import { FIELD_COMPONENT_BASE_PROPS } from 'dfv/src/config/prop-types';
import './paragraph.scss';
const Paragraph = ( {
fieldConfig = {},
onBlur,
onChange,
setValue,
value,
setHasBlurred,
} ) => {
const {
htmlAttr: htmlAttributes = {},
name,
paragraph_max_length: maxLength,
paragraph_placeholder: placeholder = fieldConfig.placeholder,
readonly: readOnly,
} = fieldConfig;
// Default implementation if onChange is omitted from props
const handleChange = ( event ) => setValue( event.target.value );
const handleBlur = ( event ) => {
if ( onBlur ) {
onBlur( event );
}
setHasBlurred();
};
return (
<textarea
value={ value || '' }
id={ htmlAttributes.id || `pods-form-ui-${ name }` }
name={ htmlAttributes.name || name }
className={ classnames( 'pods-form-ui-field pods-form-ui-field-type-paragraph', htmlAttributes.class ) }
maxLength={ 0 < parseInt( maxLength, 10 ) ? parseInt( maxLength, 10 ) : undefined }
placeholder={ placeholder }
onChange={ onChange || handleChange }
onBlur={ handleBlur }
readOnly={ toBool( readOnly ) }
>
{ value }
</textarea>
);
};
Paragraph.propTypes = {
...FIELD_COMPONENT_BASE_PROPS,
value: PropTypes.string,
};
export default Paragraph;
|
src/frontend/app.js | Bernie-2016/ground-control | import 'babel/polyfill'
import jQuery from 'jquery'
import React from 'react'
import ReactDOM from 'react-dom'
import Relay from 'react-relay'
import {StyleRoot} from 'radium'
import EventCreate from './components/EventCreate.js'
import DummyEventCreate from './components/DummyEventCreate.js'
import {Redirect, IndexRoute, IndexRedirect, Route, Router} from 'react-router'
import ReactRouterRelay from 'react-router-relay'
import injectTapEventPlugin from 'react-tap-event-plugin'
import AdminDashboard from './components/AdminDashboard'
import AdminEventEmailCreationForm from './components/AdminEventEmailCreationForm'
import AdminEventsSection from './components/AdminEventsSection'
import AdminEventUploadRsvps from './components/AdminEventUploadRsvps'
import ConstituentLookup from './components/ConstituentLookup'
import AdminCallAssignmentsSection from './components/AdminCallAssignmentsSection'
import AdminCallAssignmentCreationForm from './components/AdminCallAssignmentCreationForm'
import FastFwdForm from './components/FastFwdForm'
import EventsDashboard from './components/EventsDashboard'
import EventView from './components/EventView'
import EventDataUpload from './components/EventDataUpload'
import GCTextField from './components/forms/GCTextField'
import GCRichTextField from './components/forms/GCRichTextField'
import GCPhoneField from './components/forms/GCPhoneField'
import GCDateField from './components/forms/GCDateField'
import GCDateTimeField from './components/forms/GCDateTimeField'
import GCTimeField from './components/forms/GCTimeField'
import GCPasswordField from './components/forms/GCPasswordField'
import GCRadioButtonsField from './components/forms/GCRadioButtonsField'
import GCSelectField from './components/forms/GCSelectField'
import GCCheckboxesField from './components/forms/GCCheckboxesField'
import GCBooleanField from './components/forms/GCBooleanField'
import GCToggleField from './components/forms/GCToggleField'
import CallAssignmentsDashboard from './components/CallAssignmentsDashboard'
import AdminCallAssignment from './components/AdminCallAssignment'
import CallAssignment from './components/CallAssignment'
import CallAssignmentsSection from './components/CallAssignmentsSection'
import Dashboard from './components/Dashboard'
import Signup from './components/Signup'
import NotFound from './components/NotFound'
import Unauthorized from './components/Unauthorized'
import Form from 'react-formal'
import {createHistory} from 'history'
import GCNetworkLayer from './relay-extensions/GCNetworkLayer'
import log from './log'
import Loading from './components/Loading'
import SlackInviteIndex from './components/SlackInviteIndex'
import SlackInvite from './components/SlackInvite'
import UserAccountDashboard from './components/UserAccountDashboard'
import UserAccountChangePasswordForm from './components/UserAccountChangePasswordForm'
window.jQuery = jQuery
window.log = log
window.onerror = (msg, file, line, col, error) => {
if (!error) {
log.error('Uncaught exception with null error object')
return
}
log.error(error)
if (window.location.href.split('/')[2].split(':')[0] !== 'localhost')
setTimeout(() => {
alert('Whoops! Something went wrong. We\'re looking into it, but in the meantime please refresh your browser.')
document.location.reload(true)
}, 2000)
}
injectTapEventPlugin()
Relay.injectNetworkLayer(new GCNetworkLayer('/graphql'), {
fetchTimeout: 30000, // Timeout after 30s.
})
Form.addInputTypes({
string: GCTextField,
richtext: GCRichTextField,
number: GCTextField,
email: GCTextField,
boolean: GCBooleanField,
radio: GCRadioButtonsField,
select: GCSelectField,
array: GCCheckboxesField,
password: GCPasswordField,
date: GCDateField,
time: GCTimeField,
datetime: GCDateTimeField,
phone: GCPhoneField
})
const ListContainerQueries = {
listContainer: () => Relay.QL`query { listContainer }`
}
const CallAssignmentQueries = {
callAssignment: () => Relay.QL`query { callAssignment(id: $id) }`
}
const CurrentUserQueries = {
currentUser: () => Relay.QL`query { currentUser }`
}
const EventQueries = {
event: () => Relay.QL`query { event(id: $id) }`
}
const FastFwdRequest = {
fastFwdRequest: () => Relay.QL`query{ fastFwdRequest(id: $id) }`
}
let history = createHistory()
ReactDOM.render(
<StyleRoot>
<Router
history={history}
createElement={ReactRouterRelay.createElement}>
<Route
path='/admin'
component={AdminDashboard}
queries={ListContainerQueries}
>
<Route
path='call-assignments'
component={AdminCallAssignmentsSection}
queries={ListContainerQueries}
>
<IndexRoute
component={AdminCallAssignmentCreationForm}
queries={ListContainerQueries}
/>
<Route
path=':id'
component={AdminCallAssignment}
queries={CallAssignmentQueries}
/>
</Route>
<Route
path='events/:id/emails/create'
component={AdminEventEmailCreationForm}
queries={{
...ListContainerQueries,
...EventQueries,
...CurrentUserQueries
}}
renderLoading={() => <Loading />}
/>
<Route
path='events/upload-rsvps'
component={AdminEventUploadRsvps}
/>
<Route
path='events'
component={AdminEventsSection}
queries={{
...CurrentUserQueries,
...ListContainerQueries
}}
renderLoading={() => <Loading />}
/>
<Route
path='constituent-lookup'
component={ConstituentLookup}
queries={{
...ListContainerQueries
}}
renderLoading={() => <Loading />}
/>
</Route>
<Route
path='/signup'
component={Signup}
/>
<Route
path='/'
component={Dashboard}
queries={CurrentUserQueries}
>
<IndexRedirect to='/events' />
<Route
path='events/create/v2'
component={EventCreate}
queries={CurrentUserQueries}
renderLoading={() => <Loading />}
/>
<Route
path='events/create'
component={DummyEventCreate}
renderLoading={() => window.location.reload() }
/>
<Route
path='call'
component={CallAssignmentsDashboard}
queries={CurrentUserQueries}
>
<IndexRoute
component={CallAssignmentsSection}
queries={CurrentUserQueries}
/>
<Route
path=':id'
component={CallAssignment}
queries={{
...CallAssignmentQueries,
...CurrentUserQueries
}}
renderLoading={() => <Loading />}
/>
</Route>
<Route
path='events'
component={CallAssignmentsDashboard}
queries={CurrentUserQueries}
>
<IndexRoute
component={EventsDashboard}
queries={{
...CurrentUserQueries,
}}
/>
<Route
path=':id'
component={EventView}
queries={{
...EventQueries
}}
renderLoading={() => <Loading />}
/>
{/*<Route
path=':id/upload'
component={EventDataUpload}
queries={{
...EventQueries,
...ListContainerQueries,
...CurrentUserQueries
}}
renderLoading={() => <Loading />}
/>*/}
<Route
path=':id/request-email'
component={FastFwdForm}
queries={{
...EventQueries,
...CurrentUserQueries
}}
renderLoading={() => <Loading />}
/>
</Route>
<Route
path='account'
component={UserAccountDashboard}
queries={CurrentUserQueries}
>
<IndexRoute
component={UserAccountChangePasswordForm}
/>
</Route>
</Route>
<Route
path='slack'
>
<IndexRoute
component={SlackInviteIndex}
/>
<Route
path=':team'
component={SlackInvite}
renderLoading={() => <Loading />}
/>
</Route>
<Route path='/unauthorized' component={Unauthorized}/>
<Route path="*" component={NotFound}/>
</Router>
</StyleRoot>,
document.getElementById('root')
)
|
src/ModalTitle.js | chilts/react-bootstrap | import React from 'react';
import classNames from 'classnames';
class ModalTitle extends React.Component {
render() {
return (
<h4
{...this.props}
className={classNames(this.props.className, this.props.modalClassName)}>
{ this.props.children }
</h4>
);
}
}
ModalTitle.propTypes = {
/**
* A css class applied to the Component
*/
modalClassName: React.PropTypes.string
};
ModalTitle.defaultProps = {
modalClassName: 'modal-title'
};
export default ModalTitle;
|
lib/components/MessageView.js | davidbecker6081/ConnectME | import React, { Component } from 'react';
import Message from './Message';
import moment from 'moment';
import firebase, {
referenceMessages,
database,
retrieveFromDatabase,
pushMessage,
} from '../firebase';
class MessageView extends Component {
constructor() {
super();
this.state = {
message: '',
};
}
componentDidMount() {
const {
retrieveMessagesFromFirebase,
loggedInUser,
userDataFacebook,
messageFriendData,
} = this.props;
const { fullName, id: userId } = userDataFacebook;
const { name: friendName, id: friendId } = messageFriendData;
this.props.resetMessages();
retrieveFromDatabase(fullName, friendId).then(snapshot => {
if (snapshot.val()) {
retrieveMessagesFromFirebase(snapshot.val());
}
});
retrieveFromDatabase(friendName, userId).then(snapshot => {
if (snapshot.val()) {
retrieveMessagesFromFirebase(snapshot.val());
}
});
}
renderMessageHistory() {
const { messages, messageFriendData, loggedInUser, userDataFacebook } = this.props;
return messages.length > 0
? (messages.map(message => {
return <Message key={message.date} {...message} loggedInUser={loggedInUser} />;
}))
: (<div className="default-message-individual">Send a Message...</div>);
}
sendNewMessage() {
const { userDataFacebook, messageFriendData, sendMessage } = this.props;
const { message } = this.state;
const newMessage = {
recipient: {
name: messageFriendData.name,
id: messageFriendData.id,
},
sender: {
name: userDataFacebook.fullName,
id: '0000000000',
},
message,
date: moment(Date.now()).format('MMMM Do YYYY, h:mm:ss a'),
};
const { fullName: userName } = userDataFacebook;
const { id: friendId } = messageFriendData;
pushMessage(userName, friendId, newMessage).then(() => {
sendMessage(newMessage);
});
}
render() {
const { messageFriendData, loggedInUser } = this.props;
const isDisabled = !this.state.message;
return (
<section className="messages-wrapper">
<h3>Messages</h3>
{!messageFriendData.name && (
<div className="message-default">Select a Friend to Message</div>
)}
{messageFriendData.name && (
<div className="message-container">
<h5>
<span>{messageFriendData.name}</span>
<span>{loggedInUser.userName}</span>
</h5>
<ul className="message-list">{this.renderMessageHistory()}</ul>
<input
type="text"
value={this.state.message}
onChange={e => {
this.setState({
message: e.target.value,
});
}}
/>
<button
disabled={isDisabled}
onClick={() => {
this.sendNewMessage();
this.setState({
message: '',
});
}}
>
Send Message
</button>
</div>
)}
</section>
);
}
}
export default MessageView;
|
src/index.js | viralganatra/react-scrolling-lock | import React, { Component } from 'react';
import invariant from 'invariant';
export default function ScrollLockHOC({ className } = {}) {
return function ScrollLockDecorate(WrappedComponent) {
invariant(
typeof WrappedComponent === 'function',
`Expected "WrappedComponent" provided as the first argument to ScrollLockHOC
to be a function. Instead, received ${typeof WrappedComponent}.`,
);
function getDisplayName() {
return WrappedComponent.displayName || WrappedComponent.name || 'Component';
}
return class ScrollLock extends Component {
static displayName = `withScrollLockHOC(${getDisplayName()})`;
onScroll = (event) => {
const { containerNode } = this;
const { scrollTop, scrollHeight, clientHeight } = containerNode;
const wheelDelta = event.deltaY;
const isDeltaPositive = wheelDelta > 0;
if (isDeltaPositive && wheelDelta > scrollHeight - clientHeight - scrollTop) {
containerNode.scrollTop = scrollHeight;
event.preventDefault();
} else if (!isDeltaPositive && -wheelDelta > scrollTop) {
containerNode.scrollTop = 0;
event.preventDefault();
}
}
containerRef = (node) => {
this.containerNode = node ? node.firstChild : node;
}
getContainerProps() {
let props = {
style: {
display: 'inline-block',
},
};
if (className !== undefined) {
props = { className };
}
return props;
}
render() {
const containerProps = this.getContainerProps();
return (
<div
{...containerProps}
onWheel={this.onScroll}
ref={this.containerRef}
>
<WrappedComponent {...this.props} />
</div>
);
}
};
};
}
|
packages/bonde-admin/src/mobilizations/widgets/__plugins__/donation/components/settings-menu.js | ourcities/rebu-client | import PropTypes from 'prop-types'
import React from 'react'
import { FormattedMessage } from 'react-intl'
import * as paths from '@/paths'
import { Tabs, Tab } from '@/components/navigation/tabs'
import { SettingsPageMenuLayout } from '@/components/layout'
const SettingsMenu = ({ mobilization, widget, location }) => {
const donationPath = paths.donation(mobilization.id, widget.id) + '/settings'
const donationAdjustmentsPath = paths.donation(mobilization.id, widget.id)
const donationAutofirePath = paths.donationAutofire(mobilization.id, widget.id)
const donationFinishPath = paths.donationFinish(mobilization.id, widget.id)
return (
<SettingsPageMenuLayout
title={
<FormattedMessage
id='donation.components--settings-menu.title'
defaultMessage='Configure sua caixa de doação'
/>
}
>
<Tabs>
<Tab
path={donationAdjustmentsPath}
isActive={donationAdjustmentsPath === location.pathname}
text={
<FormattedMessage
id='donation.components--settings-menu.tabs.adjusts'
defaultMessage='Ajustes'
/>
}
/>
<Tab
path={donationPath}
isActive={donationPath === location.pathname}
text={
<FormattedMessage
id='donation.components--settings-menu.tabs.info'
defaultMessage='Dados para doação'
/>
}
/>
<Tab
path={donationAutofirePath}
isActive={donationAutofirePath === location.pathname}
text={
<FormattedMessage
id='donation.components--settings-menu.tabs.autofire'
defaultMessage='Mensagem agradecimento'
/>
}
/>
<Tab
path={donationFinishPath}
isActive={donationFinishPath === location.pathname}
text={
<FormattedMessage
id='donation.components--settings-menu.tabs.post-action'
defaultMessage='Pós-doação'
/>
}
/>
</Tabs>
</SettingsPageMenuLayout>
)
}
SettingsMenu.propTypes = {
mobilization: PropTypes.shape({ id: PropTypes.number.isRequired }).isRequired,
widget: PropTypes.shape({ id: PropTypes.number.isRequired }).isRequired,
location: PropTypes.shape({ pathname: PropTypes.string.isRequired }).isRequired
}
export default SettingsMenu
|
app/react/routes/index.js | stanleycyang/isomorphic-react-router | import React from 'react'
import { Route, IndexRoute } from 'react-router'
/* Import components */
import App from '../container'
import Home from '../components'
import Login from '../components/Login'
import NoMatch from '../components/NoMatch'
export default (
<Route name="app" component={ App } path='/'>
<IndexRoute component={ Home } />
<Route component={ Login } path='login' />
{/* 404 */}
<Route path='*' component={ NoMatch } />
</Route>
)
|
js/Observation.js | nathanjameshill/ReefWatchPrototype | import React from 'react';
import validator from 'bootstrap-validator';
import { Modal, Button, FormGroup, Col, ControlLabel, FormControl, HelpBlock, Checkbox } from 'react-bootstrap';
import DateTimeField from 'react-bootstrap-datetimepicker';
import moment from "moment";
import config from '../config'
import Typeahead from 'react-bootstrap-typeahead';
import CloudCover from './components/CloudCover';
import SelectBox from './components/SelectBox';
import * as Data from "../data/data"
import * as Services from "../data/services";
var Observation = React.createClass({
getInitialState: function() {
const observationId = this.props.params.observationId;
if(observationId) {
//need to redirect to error page
console.log("Error no observation found")
}
console.log("observationId");
console.log(observationId);
var initialState = {};
initialState.observation = {};
initialState.observation.time = moment("1970-01-01 00:00");
initialState.observationId = observationId;
console.log("GetObservation Call");
Services.GetObservation(observationId, (result) => {
console.log("Return Observation");
console.log(result);
this.setState({observation: result})
});
initialState.volunteers = [];
console.log("GetReefWatchVolunteers Call");
Services.GetReefWatchVolunteers((result) => {
console.log("Return Volunteers");
console.log(result);
this.setState({volunteers: result});
});
initialState.beaufordWindScale = [];
console.log("GetBeaufortScale Call");
Services.GetBeaufortScale((result) => {
console.log("Return BeaufortScale");
console.log(result);
this.setState({beaufordWindScale: result});
});
initialState.cloudCover = [];
console.log("GetCloudCover Call");
Services.GetCloudCover((result) => {
console.log("Return CloudCover");
console.log(result);
this.setState({cloudCover: result});
});
initialState.rainfall = [];
console.log("GetRainfall Call");
Services.GetRainfall((result) => {
console.log("Return rainfall");
console.log(result);
this.setState({rainfall: result});
});
console.log("windDirections Call");
initialState.windDirections = Data.loadWindDirections();
console.log("Return windDirections");
console.log(initialState.windDirections);
initialState.validationState = {
"observationTimeState": null,
"otherLocationState": null,
"weatherCommentState": null,
"recentExceptionalWeatherState": null,
"rainfallIdState": null,
"volunteersState": null,
"beaufordWindScaleIdState": null,
"cloudCoverIdState": null,
"exceptionalWeatherConditionsState": null
};
initialState.cloudCover = 0;
return initialState;
},
handleTime: function (timeValue) {
var observation = this.state.observation;
observation.time = moment(parseInt(timeValue)).format('HH:mm'); // eslint-disable-line radix
this.setState({observation: observation});
Services.SaveObservation(this.state.observation.id, this.state.observation, function(result) {
console.log("SaveTime")
console.log(result)
});
},
handleChange: function(e) {
var observation = this.state.observation;
observation[e.target.name] = e.target.value;
this.setState({observation: observation});
},
handleVolunteersChange: function(selectedItems, e) {
Services.GetVolunteers(this.state.observation.id, function (result) {
if (result) {
result.foreach(function (item) {
}, this);
}
})
},
render() {
return (
<div className="container">
<h2>Observation</h2>
<form id="formObservation" data-toggle="validator" onSubmit={this.submit} role="form">
<FormGroup controlId="observationTime" validationState={this.state.validationState['observationTimeState']}>
<ControlLabel controlId="observationTime">Observation Time</ControlLabel>
<DateTimeField
mode="time"
id="observationTime"
date={this.state.observation.observationTime}
inputProps={{required:"required", name:"observationTime"}}
onChange={this.handleTime}
/>
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
<FormGroup controlId="otherLocation" validationState={this.state.validationState['otherLocationState']}>
<ControlLabel controlId="otherLocation">Other Location</ControlLabel>
<FormControl
required
type="text"
value={this.state.observation.otherLocation}
placeholder=""
onChange={this.handleChange}
id="otherLocation"
name="otherLocation"
/>
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
<FormGroup controlId="volunteers" validationState={this.state.validationState['volunteersState']}>
<ControlLabel controlId="volunteers">Volunteers</ControlLabel>
<Typeahead
ref="volunteerType"
labelKey="name"
onChange={this.handleVolunteersChange}
options={this.state.volunteers}
id="volunteers"
allowNew={true}
multiple={true}
selected={this.state.observation.volunteers}
/>
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
<FormGroup controlId="weatherComment" validationState={this.state.validationState['weatherCommentState']}>
<ControlLabel controlId="weatherComment">Weather Comment </ControlLabel>
<FormControl
required
type="text"
value={this.state.observation.weatherComment}
placeholder="weatherComment"
onChange={this.handleChange}
id="weatherComment"
name="weatherComment"
/>
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
<FormGroup controlId="beaufordWindScale" validationState={this.state.validationState['beaufordWindScaleIdState']}>
<ControlLabel controlId="beaufordWindScale">Beauford Wind Scale (1-5)</ControlLabel>
<SelectBox id="beaufordWindScale" fields={["id", "scaleDescription"]} onChange={this.handleChange} name="beaufordWindScale" data={this.state.beaufordWindScale} />
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
<FormGroup controlId="rainfall" validationState={this.state.validationState['windDirectionState']}>
<ControlLabel controlId="rainfall">Rainfall</ControlLabel>
<SelectBox id="rainfall" fields={["id", "type"]} onChange={this.handleChange} name="rainfall" data={this.state.rainfall} />
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
<FormGroup controlId="cloudCoverId" validationState={this.state.validationState['cloudCoverIdState']}>
<ControlLabel controlId="cloudCover">Cloud Cover</ControlLabel>
<CloudCover
id="cloudCover"
cloudCoverValue={this.state.cloudCoverId}
required
/>
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
<FormGroup controlId="" validationState={this.state.validationState['exceptionalWeatherConditionsState']}>
<ControlLabel controlId="exceptionalWeatherConditions">Recent Exceptional Weather Conditions</ControlLabel>
<FormControl componentClass="textarea" placeholder="textarea" value={this.state.observation.exceptionalWeatherConditions}
placeholder="Any recent tidal, weather, or other unusual events (e.g. hevy rain shortly before survey, storm, heatwave, wind held tide higher than expected)"
onChange={this.handleChange} name="exceptionalWeatherConditions" />
<FormControl.Feedback />
<HelpBlock></HelpBlock>
</FormGroup>
</form>
</div>
);
}
})
export default Observation;
|
docs/app/index.js | vageeshb/Semantic-UI-React | import React from 'react'
import ReactDOM from 'react-dom'
import App from './App'
// ----------------------------------------
// Rendering
// ----------------------------------------
const mountNode = document.createElement('div')
document.body.appendChild(mountNode)
const render = (NewApp) => ReactDOM.render(<NewApp />, mountNode)
// ----------------------------------------
// HMR
// ----------------------------------------
if (__DEV__) {
// When the application source code changes, re-render the whole thing.
if (module.hot) {
module.hot.accept('./App', () => {
// restore scroll
const { scrollLeft, scrollTop } = document.scrollingElement
ReactDOM.unmountComponentAtNode(mountNode)
try {
render(require('./App').default)
document.scrollingElement.scrollTop = scrollTop
document.scrollingElement.scrollLeft = scrollLeft
} catch (e) {
console.error(e) // eslint-disable-line no-console
}
})
}
}
// ----------------------------------------
// Start the app
// ----------------------------------------
render(App)
|
src/modules/pages/feeds/js/index.js | lenxeon/react |
require('../../../../css/panel.less')
require('../css/index.less')
import React from 'react';
import {Router, Route, Redirect, Link, History} from 'react-router';
let {createActiveRouteComponent} = require('../../NavLink');
let FeedListWidget = require('./FeedListWidget');
let FeedStore = require('./feedStore');
var NavLink = createActiveRouteComponent('li');
class Feeds extends React.Component {
mixins: [ History ]
constructor(props) {
super(props);
this.state = {
foo: "bar"
};
}
state: {
foo: "bar"
}
componentDidMount() {
let {
location, params, route, routeParams
} = this.props;
let {
query
} = location;
}
componentWillReceiveProps() {
this.setState({
loaded: false,
})
}
componentDidUpdate() {
// console.log('componentDidUpdate');
}
componentDidMount() {
// console.log('componentDidMount');
// if (this.isMounted()) {
// }
}
render(){
let taskData = [];
for (let i=0;i<7;i++){
taskData.push(i);
}
let tasks = taskData.map((i)=>{
return(
<li className="clear">
<span className="time">08:00</span>
<span className="event ellipsis"><Link to={`/calendar/${i}`}>市场人员收集数据和管理商机的利器</Link></span>
<span className="handler rgt">
<i className="fa fa-info-circle"></i>
</span>
</li>
)
})
let {location, params, route, routeParams} = this.props;
let { pathname, query } = location;
return(
<div className="body-wrap">
<div className="feeds">
<div className="pure-u-18-24">
<div className="clear sub-box card shadow">
<p className="W_swficon ficon_swtxt">
<em className="spac1">有什么新</em>
<em className="spac2">鲜</em>
<em className="spac3">事想告诉大家</em>
<em className="spac4">?</em>
</p>
<div className="sub-box-out-wrap">
<textarea className="TextArea Block Gray_a" contenteditable="true" rows="1" data-mentions-input="true">
</textarea>
</div>
</div>
<ul className="nav nav-tabs clear card shadow mt-10">
<NavLink to="/feeds" query={{'cat':'all', 'page':1,'size':30}} activeClassName="active">
<i className="fa fa-paper-plane-o mr-5"></i>所有
</NavLink>
<NavLink to="/feeds" query={{'cat':'atme', 'page':1,'size':30}} activeClassName="active">
<i className="fa fa-at mr-5"></i>提到我的
</NavLink>
<NavLink to="/feeds" query={{'cat':'follow', 'page':1,'size':30}} activeClassName="active">
<i className="fa fa-thumb-tack mr-5"></i>我关注的
</NavLink>
<NavLink to="/feeds" query={{'cat':'hots', 'page':1,'size':30}} activeClassName="active">
<i className="fa fa-comments-o mr-5"></i>热门
</NavLink>
</ul>
{this.props.children ? (
<div className="children">
{this.props.children}
</div>
) : (
<div className="feeds-list-box">
<FeedListWidget {...query}/>
</div>
)
}
</div>
<div className="pure-u-6-24">
<div className="ml-15 card shadow widget-calendar">
<div className="header clear">
<span className="title lft">我的日程</span>
<span className="info rgt"><span className="num mr-5">9</span>个待处理事件</span>
</div>
<div className="week">
<ul className="clear">
<li className="current" data-tip="周四" >
<div className="weekIndex current" >
17
</div></li>
<li data-tip="周五" >
<div className="weekIndex" >
18
</div></li>
<li data-tip="周六" >
<div className="weekIndex" >
19
</div></li>
<li data-tip="周日" >
<div className="weekIndex" >
20
</div></li>
<li data-tip="周一" >
<div className="weekIndex" >
21
</div></li>
<li data-tip="周二" >
<div className="weekIndex" >
22
</div></li>
<li data-tip="周三" >
<div className="weekIndex" >
23
</div></li>
<li data-tip="周四" >
<div className="weekIndex" >
24
</div>
</li>
</ul>
</div>
<div className="detail">
<ul>
{tasks}
</ul>
</div>
<div className="action mt-5">
<div className="lft btn">
<span className="ico">C</span>
<span className="text ml-5">创建新日程</span>
</div>
</div>
</div>
</div>
</div>
</div>
)
}
};
export default Feeds; |
Swift Playgrounds/Challenges/LinkedIn Placements 2017/Caesar Cipher- Encryption/Caesar Cipher- Encryption.playground/Resources/index.ios.js | jeevanRao7/Swift_Playgrounds | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class AwesomeProject extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('AwesomeProject', () => AwesomeProject);
|
app/javascript/flavours/glitch/features/video/index.js | im-in-space/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import { is } from 'immutable';
import { throttle, debounce } from 'lodash';
import classNames from 'classnames';
import { isFullscreen, requestFullscreen, exitFullscreen } from 'flavours/glitch/util/fullscreen';
import { displayMedia, useBlurhash } from 'flavours/glitch/util/initial_state';
import Icon from 'flavours/glitch/components/icon';
import Blurhash from 'flavours/glitch/components/blurhash';
const messages = defineMessages({
play: { id: 'video.play', defaultMessage: 'Play' },
pause: { id: 'video.pause', defaultMessage: 'Pause' },
mute: { id: 'video.mute', defaultMessage: 'Mute sound' },
unmute: { id: 'video.unmute', defaultMessage: 'Unmute sound' },
hide: { id: 'video.hide', defaultMessage: 'Hide video' },
expand: { id: 'video.expand', defaultMessage: 'Expand video' },
close: { id: 'video.close', defaultMessage: 'Close video' },
fullscreen: { id: 'video.fullscreen', defaultMessage: 'Full screen' },
exit_fullscreen: { id: 'video.exit_fullscreen', defaultMessage: 'Exit full screen' },
});
export const formatTime = secondsNum => {
let hours = Math.floor(secondsNum / 3600);
let minutes = Math.floor((secondsNum - (hours * 3600)) / 60);
let seconds = secondsNum - (hours * 3600) - (minutes * 60);
if (hours < 10) hours = '0' + hours;
if (minutes < 10) minutes = '0' + minutes;
if (seconds < 10) seconds = '0' + seconds;
return (hours === '00' ? '' : `${hours}:`) + `${minutes}:${seconds}`;
};
export const findElementPosition = el => {
let box;
if (el.getBoundingClientRect && el.parentNode) {
box = el.getBoundingClientRect();
}
if (!box) {
return {
left: 0,
top: 0,
};
}
const docEl = document.documentElement;
const body = document.body;
const clientLeft = docEl.clientLeft || body.clientLeft || 0;
const scrollLeft = window.pageXOffset || body.scrollLeft;
const left = (box.left + scrollLeft) - clientLeft;
const clientTop = docEl.clientTop || body.clientTop || 0;
const scrollTop = window.pageYOffset || body.scrollTop;
const top = (box.top + scrollTop) - clientTop;
return {
left: Math.round(left),
top: Math.round(top),
};
};
export const getPointerPosition = (el, event) => {
const position = {};
const box = findElementPosition(el);
const boxW = el.offsetWidth;
const boxH = el.offsetHeight;
const boxY = box.top;
const boxX = box.left;
let pageY = event.pageY;
let pageX = event.pageX;
if (event.changedTouches) {
pageX = event.changedTouches[0].pageX;
pageY = event.changedTouches[0].pageY;
}
position.y = Math.max(0, Math.min(1, (pageY - boxY) / boxH));
position.x = Math.max(0, Math.min(1, (pageX - boxX) / boxW));
return position;
};
export const fileNameFromURL = str => {
const url = new URL(str);
const pathname = url.pathname;
const index = pathname.lastIndexOf('/');
return pathname.slice(index + 1);
};
export default @injectIntl
class Video extends React.PureComponent {
static propTypes = {
preview: PropTypes.string,
frameRate: PropTypes.string,
src: PropTypes.string.isRequired,
alt: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
sensitive: PropTypes.bool,
currentTime: PropTypes.number,
onOpenVideo: PropTypes.func,
onCloseVideo: PropTypes.func,
letterbox: PropTypes.bool,
fullwidth: PropTypes.bool,
detailed: PropTypes.bool,
inline: PropTypes.bool,
editable: PropTypes.bool,
alwaysVisible: PropTypes.bool,
cacheWidth: PropTypes.func,
intl: PropTypes.object.isRequired,
visible: PropTypes.bool,
onToggleVisibility: PropTypes.func,
deployPictureInPicture: PropTypes.func,
preventPlayback: PropTypes.bool,
blurhash: PropTypes.string,
autoPlay: PropTypes.bool,
volume: PropTypes.number,
muted: PropTypes.bool,
componentIndex: PropTypes.number,
};
static defaultProps = {
frameRate: '25',
};
state = {
currentTime: 0,
duration: 0,
volume: 0.5,
paused: true,
dragging: false,
containerWidth: this.props.width,
fullscreen: false,
hovered: false,
muted: false,
revealed: this.props.visible !== undefined ? this.props.visible : (displayMedia !== 'hide_all' && !this.props.sensitive || displayMedia === 'show_all'),
};
componentWillReceiveProps (nextProps) {
if (!is(nextProps.visible, this.props.visible) && nextProps.visible !== undefined) {
this.setState({ revealed: nextProps.visible });
}
}
setPlayerRef = c => {
this.player = c;
if (this.player) {
this._setDimensions();
}
}
_setDimensions () {
const width = this.player.offsetWidth;
if (width && width != this.state.containerWidth) {
if (this.props.cacheWidth) {
this.props.cacheWidth(width);
}
this.setState({
containerWidth: width,
});
}
}
setVideoRef = c => {
this.video = c;
if (this.video) {
this.setState({ volume: this.video.volume, muted: this.video.muted });
}
}
setSeekRef = c => {
this.seek = c;
}
setVolumeRef = c => {
this.volume = c;
}
handleClickRoot = e => e.stopPropagation();
handlePlay = () => {
this.setState({ paused: false });
this._updateTime();
}
handlePause = () => {
this.setState({ paused: true });
}
_updateTime () {
requestAnimationFrame(() => {
if (!this.video) return;
this.handleTimeUpdate();
if (!this.state.paused) {
this._updateTime();
}
});
}
handleTimeUpdate = () => {
this.setState({
currentTime: this.video.currentTime,
duration:this.video.duration,
});
}
handleVolumeMouseDown = e => {
document.addEventListener('mousemove', this.handleMouseVolSlide, true);
document.addEventListener('mouseup', this.handleVolumeMouseUp, true);
document.addEventListener('touchmove', this.handleMouseVolSlide, true);
document.addEventListener('touchend', this.handleVolumeMouseUp, true);
this.handleMouseVolSlide(e);
e.preventDefault();
e.stopPropagation();
}
handleVolumeMouseUp = () => {
document.removeEventListener('mousemove', this.handleMouseVolSlide, true);
document.removeEventListener('mouseup', this.handleVolumeMouseUp, true);
document.removeEventListener('touchmove', this.handleMouseVolSlide, true);
document.removeEventListener('touchend', this.handleVolumeMouseUp, true);
}
handleMouseVolSlide = throttle(e => {
const { x } = getPointerPosition(this.volume, e);
if(!isNaN(x)) {
this.setState({ volume: x }, () => {
this.video.volume = x;
});
}
}, 15);
handleMouseDown = e => {
document.addEventListener('mousemove', this.handleMouseMove, true);
document.addEventListener('mouseup', this.handleMouseUp, true);
document.addEventListener('touchmove', this.handleMouseMove, true);
document.addEventListener('touchend', this.handleMouseUp, true);
this.setState({ dragging: true });
this.video.pause();
this.handleMouseMove(e);
e.preventDefault();
e.stopPropagation();
}
handleMouseUp = () => {
document.removeEventListener('mousemove', this.handleMouseMove, true);
document.removeEventListener('mouseup', this.handleMouseUp, true);
document.removeEventListener('touchmove', this.handleMouseMove, true);
document.removeEventListener('touchend', this.handleMouseUp, true);
this.setState({ dragging: false });
this.video.play();
}
handleMouseMove = throttle(e => {
const { x } = getPointerPosition(this.seek, e);
const currentTime = this.video.duration * x;
if (!isNaN(currentTime)) {
this.setState({ currentTime }, () => {
this.video.currentTime = currentTime;
});
}
}, 15);
seekBy (time) {
const currentTime = this.video.currentTime + time;
if (!isNaN(currentTime)) {
this.setState({ currentTime }, () => {
this.video.currentTime = currentTime;
});
}
}
handleVideoKeyDown = e => {
// On the video element or the seek bar, we can safely use the space bar
// for playback control because there are no buttons to press
if (e.key === ' ') {
e.preventDefault();
e.stopPropagation();
this.togglePlay();
}
}
handleKeyDown = e => {
const frameTime = 1 / this.getFrameRate();
switch(e.key) {
case 'k':
e.preventDefault();
e.stopPropagation();
this.togglePlay();
break;
case 'm':
e.preventDefault();
e.stopPropagation();
this.toggleMute();
break;
case 'f':
e.preventDefault();
e.stopPropagation();
this.toggleFullscreen();
break;
case 'j':
e.preventDefault();
e.stopPropagation();
this.seekBy(-10);
break;
case 'l':
e.preventDefault();
e.stopPropagation();
this.seekBy(10);
break;
case ',':
e.preventDefault();
e.stopPropagation();
this.seekBy(-frameTime);
break;
case '.':
e.preventDefault();
e.stopPropagation();
this.seekBy(frameTime);
break;
}
// If we are in fullscreen mode, we don't want any hotkeys
// interacting with the UI that's not visible
if (this.state.fullscreen) {
e.preventDefault();
e.stopPropagation();
if (e.key === 'Escape') {
exitFullscreen();
}
}
}
togglePlay = () => {
if (this.state.paused) {
this.setState({ paused: false }, () => this.video.play());
} else {
this.setState({ paused: true }, () => this.video.pause());
}
}
toggleFullscreen = () => {
if (isFullscreen()) {
exitFullscreen();
} else {
requestFullscreen(this.player);
}
}
componentDidMount () {
document.addEventListener('fullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
document.addEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
window.addEventListener('scroll', this.handleScroll);
window.addEventListener('resize', this.handleResize, { passive: true });
}
componentWillUnmount () {
window.removeEventListener('scroll', this.handleScroll);
window.removeEventListener('resize', this.handleResize);
document.removeEventListener('fullscreenchange', this.handleFullscreenChange, true);
document.removeEventListener('webkitfullscreenchange', this.handleFullscreenChange, true);
document.removeEventListener('mozfullscreenchange', this.handleFullscreenChange, true);
document.removeEventListener('MSFullscreenChange', this.handleFullscreenChange, true);
if (!this.state.paused && this.video && this.props.deployPictureInPicture) {
this.props.deployPictureInPicture('video', {
src: this.props.src,
currentTime: this.video.currentTime,
muted: this.video.muted,
volume: this.video.volume,
});
}
}
componentDidUpdate (prevProps) {
if (this.player && this.player.offsetWidth && this.player.offsetWidth != this.state.containerWidth && !this.state.fullscreen) {
if (this.props.cacheWidth) this.props.cacheWidth(this.player.offsetWidth);
this.setState({
containerWidth: this.player.offsetWidth,
});
}
if (this.video && this.state.revealed && this.props.preventPlayback && !prevProps.preventPlayback) {
this.video.pause();
}
}
handleResize = debounce(() => {
if (this.player) {
this._setDimensions();
}
}, 250, {
trailing: true,
});
handleScroll = throttle(() => {
if (!this.video) {
return;
}
const { top, height } = this.video.getBoundingClientRect();
const inView = (top <= (window.innerHeight || document.documentElement.clientHeight)) && (top + height >= 0);
if (!this.state.paused && !inView) {
this.video.pause();
if (this.props.deployPictureInPicture) {
this.props.deployPictureInPicture('video', {
src: this.props.src,
currentTime: this.video.currentTime,
muted: this.video.muted,
volume: this.video.volume,
});
}
this.setState({ paused: true });
}
}, 150, { trailing: true })
handleFullscreenChange = () => {
this.setState({ fullscreen: isFullscreen() });
}
handleMouseEnter = () => {
this.setState({ hovered: true });
}
handleMouseLeave = () => {
this.setState({ hovered: false });
}
toggleMute = () => {
const muted = !this.video.muted;
this.setState({ muted }, () => {
this.video.muted = muted;
});
}
toggleReveal = () => {
if (this.state.revealed) {
this.setState({ paused: true });
}
if (this.props.onToggleVisibility) {
this.props.onToggleVisibility();
} else {
this.setState({ revealed: !this.state.revealed });
}
}
handleLoadedData = () => {
const { currentTime, volume, muted, autoPlay } = this.props;
if (currentTime) {
this.video.currentTime = currentTime;
}
if (volume !== undefined) {
this.video.volume = volume;
}
if (muted !== undefined) {
this.video.muted = muted;
}
if (autoPlay) {
this.video.play();
}
}
handleProgress = () => {
const lastTimeRange = this.video.buffered.length - 1;
if (lastTimeRange > -1) {
this.setState({ buffer: Math.ceil(this.video.buffered.end(lastTimeRange) / this.video.duration * 100) });
}
}
handleVolumeChange = () => {
this.setState({ volume: this.video.volume, muted: this.video.muted });
}
handleOpenVideo = () => {
this.video.pause();
this.props.onOpenVideo({
startTime: this.video.currentTime,
autoPlay: !this.state.paused,
defaultVolume: this.state.volume,
componentIndex: this.props.componentIndex,
});
}
handleCloseVideo = () => {
this.video.pause();
this.props.onCloseVideo();
}
getFrameRate () {
if (this.props.frameRate && isNaN(this.props.frameRate)) {
// The frame rate is returned as a fraction string so we
// need to convert it to a number
return this.props.frameRate.split('/').reduce((p, c) => p / c);
}
return this.props.frameRate || 25;
}
render () {
const { preview, src, inline, onOpenVideo, onCloseVideo, intl, alt, letterbox, fullwidth, detailed, sensitive, editable, blurhash } = this.props;
const { containerWidth, currentTime, duration, volume, buffer, dragging, paused, fullscreen, hovered, muted, revealed } = this.state;
const progress = Math.min((currentTime / duration) * 100, 100);
const playerStyle = {};
const computedClass = classNames('video-player', { inactive: !revealed, detailed, inline: inline && !fullscreen, fullscreen, editable, letterbox, 'full-width': fullwidth });
let { width, height } = this.props;
if (inline && containerWidth) {
width = containerWidth;
height = containerWidth / (16/9);
playerStyle.height = height;
} else if (inline) {
return (<div className={computedClass} ref={this.setPlayerRef} tabindex={0}></div>);
}
let preload;
if (this.props.currentTime || fullscreen || dragging) {
preload = 'auto';
} else if (detailed) {
preload = 'metadata';
} else {
preload = 'none';
}
let warning;
if (sensitive) {
warning = <FormattedMessage id='status.sensitive_warning' defaultMessage='Sensitive content' />;
} else {
warning = <FormattedMessage id='status.media_hidden' defaultMessage='Media hidden' />;
}
return (
<div
className={computedClass}
style={playerStyle}
ref={this.setPlayerRef}
onMouseEnter={this.handleMouseEnter}
onMouseLeave={this.handleMouseLeave}
onClick={this.handleClickRoot}
onKeyDown={this.handleKeyDown}
tabIndex={0}
>
<Blurhash
hash={blurhash}
className={classNames('media-gallery__preview', {
'media-gallery__preview--hidden': revealed,
})}
dummy={!useBlurhash}
/>
{(revealed || editable) && <video
ref={this.setVideoRef}
src={src}
poster={preview}
preload={preload}
loop
role='button'
tabIndex='0'
aria-label={alt}
title={alt}
width={width}
height={height}
volume={volume}
onClick={this.togglePlay}
onKeyDown={this.handleVideoKeyDown}
onPlay={this.handlePlay}
onPause={this.handlePause}
onLoadedData={this.handleLoadedData}
onProgress={this.handleProgress}
onVolumeChange={this.handleVolumeChange}
/>}
<div className={classNames('spoiler-button', { 'spoiler-button--hidden': revealed || editable })}>
<button type='button' className='spoiler-button__overlay' onClick={this.toggleReveal}>
<span className='spoiler-button__overlay__label'>{warning}</span>
</button>
</div>
<div className={classNames('video-player__controls', { active: paused || hovered })}>
<div className='video-player__seek' onMouseDown={this.handleMouseDown} ref={this.setSeekRef}>
<div className='video-player__seek__buffer' style={{ width: `${buffer}%` }} />
<div className='video-player__seek__progress' style={{ width: `${progress}%` }} />
<span
className={classNames('video-player__seek__handle', { active: dragging })}
tabIndex='0'
style={{ left: `${progress}%` }}
onKeyDown={this.handleVideoKeyDown}
/>
</div>
<div className='video-player__buttons-bar'>
<div className='video-player__buttons left'>
<button type='button' title={intl.formatMessage(paused ? messages.play : messages.pause)} aria-label={intl.formatMessage(paused ? messages.play : messages.pause)} className='player-button' onClick={this.togglePlay} autoFocus={detailed}><Icon id={paused ? 'play' : 'pause'} fixedWidth /></button>
<button type='button' title={intl.formatMessage(muted ? messages.unmute : messages.mute)} aria-label={intl.formatMessage(muted ? messages.unmute : messages.mute)} className='player-button' onClick={this.toggleMute}><Icon id={muted ? 'volume-off' : 'volume-up'} fixedWidth /></button>
<div className={classNames('video-player__volume', { active: this.state.hovered })} onMouseDown={this.handleVolumeMouseDown} ref={this.setVolumeRef}>
<div className='video-player__volume__current' style={{ width: `${volume * 100}%` }} />
<span
className={classNames('video-player__volume__handle')}
tabIndex='0'
style={{ left: `${volume * 100}%` }}
/>
</div>
{(detailed || fullscreen) && (
<span className='video-player__time'>
<span className='video-player__time-current'>{formatTime(Math.floor(currentTime))}</span>
<span className='video-player__time-sep'>/</span>
<span className='video-player__time-total'>{formatTime(Math.floor(duration))}</span>
</span>
)}
</div>
<div className='video-player__buttons right'>
{(!onCloseVideo && !editable && !fullscreen && !this.props.alwaysVisible) && <button type='button' title={intl.formatMessage(messages.hide)} aria-label={intl.formatMessage(messages.hide)} className='player-button' onClick={this.toggleReveal}><Icon id='eye-slash' fixedWidth /></button>}
{(!fullscreen && onOpenVideo) && <button type='button' title={intl.formatMessage(messages.expand)} aria-label={intl.formatMessage(messages.expand)} className='player-button' onClick={this.handleOpenVideo}><Icon id='expand' fixedWidth /></button>}
{onCloseVideo && <button type='button' title={intl.formatMessage(messages.close)} aria-label={intl.formatMessage(messages.close)} className='player-button' onClick={this.handleCloseVideo}><Icon id='compress' fixedWidth /></button>}
<button type='button' title={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} aria-label={intl.formatMessage(fullscreen ? messages.exit_fullscreen : messages.fullscreen)} className='player-button' onClick={this.toggleFullscreen}><Icon id={fullscreen ? 'compress' : 'arrows-alt'} fixedWidth /></button>
</div>
</div>
</div>
</div>
);
}
}
|
src/components/ComposerDisplay.js | BenGoldstein88/redux-chartmaker | import React from 'react';
export default class ComposerDisplay extends React.Component {
// static propTypes = {
// name: React.PropTypes.string,
// };
constructor(props) {
super(props);
this.state = {
clicked: false,
styles: {
editStyle: {
margin: '0 auto',
fontSize: '1em',
textAlign: 'center',
marginBottom: '0',
transition: 'font-size .3s',
cursor: "url('/assets/images/edit.png'), text"
},
showStyle: {
margin: '0 auto',
fontSize: '1.2em',
textAlign: 'center',
marginBottom: '0',
transition: 'font-size .3s',
cursor: 'default'
}
}
}
this.handleClick = this.handleClick.bind(this);
this.handleChange = this.handleChange.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
handleClick(e) {
e.preventDefault()
e.stopPropagation()
if(this.props.filter === "EDIT") {
this.props.markBeatAsClicked(-1, -1, -1)
this.props.markSectionAsClicked(-1)
this.props.markMultiplierAsClicked(-1)
this.props.markChartInfoAsClicked("COMPOSER")
}
}
handleChange(e) {
this.props.setComposer(e.target.value)
}
handleKeyDown(e) {
if(e.key==='Enter') {
this.props.markChartInfoAsClicked("NONE")
}
if(e.key==='ArrowDown' || e.key==='Tab') {
e.preventDefault()
this.props.markChartInfoAsClicked("ARRANGER")
}
if(e.key==='ArrowUp') {
this.props.markChartInfoAsClicked("TITLE")
}
}
render() {
var style
var thingToDisplay
if(this.props.filter==='EDIT') {
style = this.state.styles.editStyle
} else {
style = this.state.styles.showStyle
}
if(this.props.currentChartInfo==='COMPOSER') {
thingToDisplay = <input style={{
fontSize: '1.1em',
textAlign: 'center',
border: 'none',
backgroundColor: 'inherit'
}} className={'composer-input'} onKeyDown={this.handleKeyDown} onChange={this.handleChange} placeholder={this.props.composer} autoFocus/>
} else {
thingToDisplay = <p className={'composer-p'}>{this.props.composer}</p>
}
return (
<div style={style} onClick={this.handleClick} >
{thingToDisplay}
</div>
);
}
}
|
src/svg-icons/maps/local-car-wash.js | pancho111203/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalCarWash = (props) => (
<SvgIcon {...props}>
<path d="M17 5c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zm-5 0c.83 0 1.5-.67 1.5-1.5 0-1-1.5-2.7-1.5-2.7s-1.5 1.7-1.5 2.7c0 .83.67 1.5 1.5 1.5zM7 5c.83 0 1.5-.67 1.5-1.5C8.5 2.5 7 .8 7 .8S5.5 2.5 5.5 3.5C5.5 4.33 6.17 5 7 5zm11.92 3.01C18.72 7.42 18.16 7 17.5 7h-11c-.66 0-1.21.42-1.42 1.01L3 14v8c0 .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 18c-.83 0-1.5-.67-1.5-1.5S5.67 15 6.5 15s1.5.67 1.5 1.5S7.33 18 6.5 18zm11 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 13l1.5-4.5h11L19 13H5z"/>
</SvgIcon>
);
MapsLocalCarWash = pure(MapsLocalCarWash);
MapsLocalCarWash.displayName = 'MapsLocalCarWash';
MapsLocalCarWash.muiName = 'SvgIcon';
export default MapsLocalCarWash;
|
src/index.js | nicolasthy/showify-electron | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { Router, Route, IndexRoute, hashHistory } from 'react-router';
import promise from 'redux-promise';
import requireAuth from './components/require_auth';
import App from './components/app';
import Home from './components/home';
import Login from './components/login';
import Series from './components/series';
import ShowsItem from './components/shows/show_item'
import reducers from './reducers';
const createStoreWithMiddleware = applyMiddleware(
promise
)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<Router history={hashHistory}>
<Route path="/" component={requireAuth(App)}>
<IndexRoute component={requireAuth(Home)} />
<Route path="series" component={requireAuth(Series)} />
<Route path="series/:id" component={requireAuth(ShowsItem)} />
</Route>
<Route path="login" component={Login} />
</Router>
</Provider>
, document.querySelector('.render-target'));
|
admin/client/Signin/Signin.js | naustudio/keystone | /**
* The actual Sign In view, with the login form
*/
import assign from 'object-assign';
import classnames from 'classnames';
import React from 'react';
import xhr from 'xhr';
import Alert from './components/Alert';
import Brand from './components/Brand';
import UserInfo from './components/UserInfo';
import LoginForm from './components/LoginForm';
var SigninView = React.createClass({
getInitialState () {
return {
email: '',
password: '',
isAnimating: false,
isInvalid: false,
invalidMessage: '',
signedOut: window.location.search === '?signedout',
};
},
componentDidMount () {
// Focus the email field when we're mounted
if (this.refs.email) {
this.refs.email.select();
}
},
handleInputChange (e) {
// Set the new state when the input changes
const newState = {};
newState[e.target.name] = e.target.value;
this.setState(newState);
},
handleSubmit (e) {
e.preventDefault();
// If either password or mail are missing, show an error
if (!this.state.email || !this.state.password) {
return this.displayError('Please enter an email address and password to sign in.');
}
xhr({
url: `${Keystone.adminPath}/api/session/signin`,
method: 'post',
json: {
email: this.state.email,
password: this.state.password,
},
headers: assign({}, Keystone.csrf.header),
}, (err, resp, body) => {
if (err || body && body.error) {
return body.error === 'invalid csrf'
? this.displayError('Something went wrong; please refresh your browser and try again.')
: this.displayError('The email and password you entered are not valid.');
} else {
// Redirect to where we came from or to the default admin path
if (Keystone.redirect) {
top.location.href = Keystone.redirect;
} else {
top.location.href = this.props.from ? this.props.from : Keystone.adminPath;
}
}
});
},
/**
* Display an error message
*
* @param {String} message The message you want to show
*/
displayError (message) {
this.setState({
isAnimating: true,
isInvalid: true,
invalidMessage: message,
});
setTimeout(this.finishAnimation, 750);
},
// Finish the animation and select the email field
finishAnimation () {
// TODO isMounted was deprecated, find out if we need this guard
if (!this.isMounted()) return;
if (this.refs.email) {
this.refs.email.select();
}
this.setState({
isAnimating: false,
});
},
render () {
const boxClassname = classnames('auth-box', {
'auth-box--has-errors': this.state.isAnimating,
});
return (
<div className="auth-wrapper">
<Alert
isInvalid={this.state.isInvalid}
signedOut={this.state.signedOut}
invalidMessage={this.state.invalidMessage}
/>
<div className={boxClassname}>
<h1 className="u-hidden-visually">{this.props.brand ? this.props.brand : 'Keystone'} Sign In </h1>
<div className="auth-box__inner">
<Brand
logo={this.props.logo}
brand={this.props.brand}
/>
{this.props.user ? (
<UserInfo
adminPath={this.props.from ? this.props.from : Keystone.adminPath}
signoutPath={`${Keystone.adminPath}/signout`}
userCanAccessKeystone={this.props.userCanAccessKeystone}
userName={this.props.user.name}
/>
) : (
<LoginForm
email={this.state.email}
handleInputChange={this.handleInputChange}
handleSubmit={this.handleSubmit}
isAnimating={this.state.isAnimating}
password={this.state.password}
/>
)}
</div>
</div>
<div className="auth-footer">
<span>Powered by </span>
<a href="http://keystonejs.com" target="_blank" title="The Node.js CMS and web application platform (new window)">KeystoneJS</a>
</div>
</div>
);
},
});
module.exports = SigninView;
|
docs/src/pages/components/grid/CSSGrid.js | lgollut/material-ui | import React from 'react';
import { makeStyles } from '@material-ui/core/styles';
import Typography from '@material-ui/core/Typography';
import Paper from '@material-ui/core/Paper';
import Divider from '@material-ui/core/Divider';
import Grid from '@material-ui/core/Grid';
const useStyles = makeStyles((theme) => ({
container: {
display: 'grid',
gridTemplateColumns: 'repeat(12, 1fr)',
gridGap: theme.spacing(3),
},
paper: {
padding: theme.spacing(1),
textAlign: 'center',
color: theme.palette.text.secondary,
whiteSpace: 'nowrap',
marginBottom: theme.spacing(1),
},
divider: {
margin: theme.spacing(2, 0),
},
}));
export default function CSSGrid() {
const classes = useStyles();
return (
<div>
<Typography variant="subtitle1" gutterBottom>
Material-UI Grid:
</Typography>
<Grid container spacing={3}>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={3}>
<Paper className={classes.paper}>xs=3</Paper>
</Grid>
<Grid item xs={8}>
<Paper className={classes.paper}>xs=8</Paper>
</Grid>
<Grid item xs={4}>
<Paper className={classes.paper}>xs=4</Paper>
</Grid>
</Grid>
<Divider className={classes.divider} />
<Typography variant="subtitle1" gutterBottom>
CSS Grid Layout:
</Typography>
<div className={classes.container}>
<div style={{ gridColumnEnd: 'span 3' }}>
<Paper className={classes.paper}>xs=3</Paper>
</div>
<div style={{ gridColumnEnd: 'span 3' }}>
<Paper className={classes.paper}>xs=3</Paper>
</div>
<div style={{ gridColumnEnd: 'span 3' }}>
<Paper className={classes.paper}>xs=3</Paper>
</div>
<div style={{ gridColumnEnd: 'span 3' }}>
<Paper className={classes.paper}>xs=3</Paper>
</div>
<div style={{ gridColumnEnd: 'span 8' }}>
<Paper className={classes.paper}>xs=8</Paper>
</div>
<div style={{ gridColumnEnd: 'span 4' }}>
<Paper className={classes.paper}>xs=4</Paper>
</div>
</div>
</div>
);
}
|
src/containers/Home/Home.js | lanceharper/react-redux-universal-hot-example | import React, { Component } from 'react';
import { Link } from 'react-router';
import { CounterButton, GithubButton } from 'components';
export default class Home extends Component {
render() {
const styles = require('./Home.scss');
// require the logo image both from client and server
const logoImage = require('./logo.png');
return (
<div className={styles.home}>
<div className={styles.masthead}>
<div className="container">
<div className={styles.logo}>
<p>
<img src={logoImage}/>
</p>
</div>
<h1>React Redux Example</h1>
<h2>All the modern best practices in one example.</h2>
<p>
<a className={styles.github} href="https://github.com/erikras/react-redux-universal-hot-example"
target="_blank">
<i className="fa fa-github"/> View on Github
</a>
</p>
<GithubButton user="erikras"
repo="react-redux-universal-hot-example"
type="star"
width={160}
height={30}
count large/>
<GithubButton user="erikras"
repo="react-redux-universal-hot-example"
type="fork"
width={160}
height={30}
count large/>
<p className={styles.humility}>
Created and maintained by <a href="https://twitter.com/erikras" target="_blank">@erikras</a>.
</p>
</div>
</div>
<div className="container">
<div className={styles.counterContainer}>
<CounterButton/>
</div>
<p>This starter boilerplate app uses the following technologies:</p>
<ul>
<li>
<del>Isomorphic</del>
{' '}
<a href="https://medium.com/@mjackson/universal-javascript-4761051b7ae9">Universal</a> rendering
</li>
<li>Both client and server make calls to load data from separate API server</li>
<li><a href="https://github.com/facebook/react" target="_blank">React</a></li>
<li><a href="https://github.com/rackt/react-router" target="_blank">React Router</a></li>
<li><a href="http://expressjs.com" target="_blank">Express</a></li>
<li><a href="http://babeljs.io" target="_blank">Babel</a> for ES6 and ES7 magic</li>
<li><a href="http://webpack.github.io" target="_blank">Webpack</a> for bundling</li>
<li><a href="http://webpack.github.io/docs/webpack-dev-middleware.html" target="_blank">Webpack Dev Middleware</a>
</li>
<li><a href="https://github.com/glenjamin/webpack-hot-middleware" target="_blank">Webpack Hot Middleware</a></li>
<li><a href="https://github.com/gaearon/redux" target="_blank">Redux</a>'s futuristic <a
href="https://facebook.github.io/react/blog/2014/05/06/flux.html" target="_blank">Flux</a> implementation
</li>
<li><a href="https://github.com/gaearon/redux-devtools" target="_blank">Redux Dev Tools</a> for next
generation DX (developer experience).
Watch <a href="https://www.youtube.com/watch?v=xsSnOQynTHs" target="_blank">Dan Abramov's talk</a>.
</li>
<li><a href="http://eslint.org" target="_blank">ESLint</a> to maintain a consistent code style</li>
<li><a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to manage form state
in Redux
</li>
<li><a href="https://github.com/webpack/style-loader" target="_blank">style-loader</a> and <a
href="https://github.com/jtangelder/sass-loader" target="_blank">sass-loader</a> to allow import of
stylesheets
</li>
</ul>
<h3>Features demonstrated in this project</h3>
<dl>
<dt>Multiple components subscribing to same redux store slice</dt>
<dd>
The <code>App.js</code> that wraps all the pages contains an <code>InfoBar</code> component
that fetches data from the server initially, but allows for the user to refresh the data from
the client. <code>About.js</code> contains a <code>MiniInfoBar</code> that displays the same
data.
</dd>
<dt>Server-side data loading</dt>
<dd>
The <Link to="/widgets">Widgets page</Link> demonstrates how to fetch data asynchronously from
some source that is needed to complete the server-side rendering. <code>Widgets.js</code>'s
<code>fetchData()</code> function is called from <code>universalRouter.js</code> before
the widgets page is loaded, on either the server or the client, allowing all the widget data
to be loaded and ready for the page to render.
</dd>
<dt>Data loading errors</dt>
<dd>
The <Link to="/widgets">Widgets page</Link> also demonstrates how to deal with data loading
errors in Redux. The API endpoint that delivers the widget data intentionally fails 33% of
the time to highlight this. The <code>clientMiddleware</code> sends an error action which
the <code>widgets</code> reducer picks up and saves to the Redux state for presenting to the user.
</dd>
<dt>Session based login</dt>
<dd>
On the <Link to="/login">Login page</Link> you can submit a username which will be sent to the server
and stored in the session. Subsequent refreshes will show that you are still logged in.
</dd>
<dt>Redirect after state change</dt>
<dd>
After you log in, you will be redirected to a Login Success page. This <strike>magic</strike> logic
is performed in <code>componentWillReceiveProps()</code> in <code>App.js</code>, but it could
be done in any component that listens to the appropriate store slice, via Redux's <code>@connect</code>,
and pulls the router from the context.
</dd>
<dt>Auth-required views</dt>
<dd>
The aforementioned Login Success page is only visible to you if you are logged in. If you try
to <Link to="/loginSuccess">go there</Link> when you are not logged in, you will be forwarded back
to this home page. This <strike>magic</strike> logic is performed by the
<code>RequireLogin</code> component, which generates an <code>onEnter()</code> function given
the Redux store, and then it simply wraps any routes that need to be secured.
</dd>
<dt>Forms</dt>
<dd>
The <Link to="/survey">Survey page</Link> uses the
still-experimental <a href="https://github.com/erikras/redux-form" target="_blank">redux-form</a> to
manage form state inside the Redux store. This includes immediate client-side validation.
</dd>
</dl>
<h3>From the author</h3>
<p>
I cobbled this together from a wide variety of similar "starter" repositories. As I post this in June 2015,
all of these libraries are right at the bleeding edge of web development. They may fall out of fashion as
quickly as they have come into it, but I personally believe that this stack is the future of web development
and will survive for several years. I'm building my new projects like this, and I recommend that you do,
too.
</p>
<p>Thanks for taking the time to check this out.</p>
<p>– Erik Rasmussen</p>
</div>
</div>
);
}
}
|
internals/templates/appContainer.js | boogunote/mevoco-client | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* 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 neccessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
import styles from './styles.css';
export default class App extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div className={styles.container}>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
examples/async/index.js | nickhudkins/redux | import 'babel-core/polyfill';
import React from 'react';
import Root from './containers/Root';
React.render(
<Root />,
document.getElementById('root')
);
|
docs/app/Examples/modules/Checkbox/States/CheckboxExampleReadOnly.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Checkbox } from 'semantic-ui-react'
const CheckboxExampleReadOnly = () => (
<Checkbox label='This checkbox is read-only' readOnly />
)
export default CheckboxExampleReadOnly
|
client/userinterface/Inventory.js | benstuijts/darkage-framework | import React from 'react';
import InventoryStore from '../stores/InventoryStore';
import * as InventoryActions from '../actions/InventoryActions';
/* components */
import ListGroup from './ListGroup';
import IconGrid from './IconGrid';
class Inventory extends React.Component {
constructor() {
super();
this.getInventory = this.getInventory.bind(this);
this.state = {
inventory: InventoryStore.getAll()
}
}
componentWillMount() {
// eventlisteners stores
InventoryStore.on("change", this.getInventory );
}
componentWillUnmount() {
// unbind eventlisteners stores
InventoryStore.removeListener("change", this.getInventory );
}
getInventory() {
this.setState({
inventory: InventoryStore.getAll()
});
}
createInventoryItem() {
console.log('button clicked');
InventoryActions.createInventoryItem({
id: Date.now(),
name: 'steen',
hoeveelheid: Math.round(Math.random()*100),
max: Math.round(Math.random()*100),
});
}
render() {
return (
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="panel-title"><i class={this.props.icon}></i> {this.props.title}</h3>
</div>
<div class="panel-body">
<IconGrid items={this.state.inventory} />
<ListGroup items={this.state.inventory}/>
</div>
<div class="btn-group">
<button onClick={this.createInventoryItem.bind(this)} class="btn btn-primary">Add one</button>
</div>
</div>
);
}
}
export default Inventory;
|
src/svg-icons/action/view-week.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionViewWeek = (props) => (
<SvgIcon {...props}>
<path d="M6 5H3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm14 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1zm-7 0h-3c-.55 0-1 .45-1 1v12c0 .55.45 1 1 1h3c.55 0 1-.45 1-1V6c0-.55-.45-1-1-1z"/>
</SvgIcon>
);
ActionViewWeek = pure(ActionViewWeek);
ActionViewWeek.displayName = 'ActionViewWeek';
export default ActionViewWeek;
|
library/src/pivotal-ui-react/draggable-list/draggable-list.js | sjolicoeur/pivotal-ui | import React from 'react';
import classnames from 'classnames';
import move from './move_helper';
import {Icon} from 'pui-react-iconography';
import {mergeProps} from 'pui-react-helpers';
import PropTypes from 'prop-types';
import 'pui-css-lists';
const childrenIndices = children => children.map((child, i) => i);
export class DraggableList extends React.Component {
static propTypes = {
onDragEnd: PropTypes.func,
innerClassName: PropTypes.string
}
constructor(props, context) {
super(props, context);
this.state = {
itemIndices: childrenIndices(props.children),
draggingId: null
};
}
componentWillReceiveProps(nextProps) {
if(nextProps.children) {
this.setState({
itemIndices: childrenIndices(nextProps.children),
draggingId: null
});
}
}
dragStart = (draggingId, {dataTransfer}) => {
dataTransfer.effectAllowed = 'move';
try {
dataTransfer.dropEffect = 'move';
dataTransfer.setData('text/plain', '');
} catch(err) {
dataTransfer.setData('text', '');
}
setTimeout(() => this.setState({draggingId}), 0);
}
dragEnd = () => {
this.setState({draggingId: null});
this.props.onDragEnd && this.props.onDragEnd(this.state.itemIndices);
}
dragEnter = e => {
const {draggingId, itemIndices} = this.state;
const endDraggingId = Number(e.currentTarget.getAttribute('data-dragging-id'));
if(draggingId === null || Number.isNaN(endDraggingId)) return;
const startIndex = itemIndices.indexOf(draggingId);
const endIndex = itemIndices.indexOf(endDraggingId);
move(itemIndices, startIndex, endIndex);
this.setState({itemIndices});
}
render() {
const items = [];
let grabbed;
const {children, innerClassName, onDragEnd, ...others} = this.props;
React.Children.forEach(children, function(child, draggingId) {
grabbed = this.state.draggingId === draggingId;
items.push(React.cloneElement(child, {
grabbed,
onDragStart: this.dragStart.bind(this, draggingId),
onDragEnd: this.dragEnd,
onDragEnter: this.dragEnter,
draggingId,
key: draggingId,
className: innerClassName
}));
}, this);
const sortedItems = this.state.itemIndices.map(i => items[i]);
const props = mergeProps(others, {
className: {
'list-draggable': true,
dragging: this.state.draggingId !== null
}
});
return <ul {...props}>{sortedItems}</ul>;
}
}
export class DraggableListItem extends React.Component {
static propTypes = {
draggingId: PropTypes.number,
onMouseEnter: PropTypes.func,
onMouseLeave: PropTypes.func,
onDragStart: PropTypes.func,
onDragEnter: PropTypes.func,
onDragEnd: PropTypes.func,
grabbed: PropTypes.bool,
className: PropTypes.string
}
constructor(props, context) {
super(props, context);
this.state = {hover: false};
}
onMouseEnter = () => this.setState({hover: true})
onMouseLeave = () => this.setState({hover: false})
render() {
const {hover} = this.state;
const {grabbed, onDragStart, onDragEnd, onDragEnter, draggingId, children} = this.props;
const {onMouseEnter, onMouseLeave} = this;
const className = classnames({'pan': true, grabbed, hover});
const innerClassName = classnames(this.props.className, 'draggable-item-content');
const props = {
className, onMouseEnter, onMouseLeave, onDragStart, onDragEnd, onDragEnter,
onDragOver: e => e.preventDefault(),
draggable: !grabbed,
'data-dragging-id': draggingId
};
return (<li {...props} aria-dropeffect="move">
<div className={innerClassName}>
<div className="draggable-grip mhs" aria-grabbed={grabbed} role="button">
<Icon src="grip"/>
<span className="sr-only">Drag to reorder</span>
</div>
<span className="draggable-child">{children}</span>
</div>
</li>);
}
}
|
src/svg-icons/image/crop-din.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageCropDin = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/>
</SvgIcon>
);
ImageCropDin = pure(ImageCropDin);
ImageCropDin.displayName = 'ImageCropDin';
ImageCropDin.muiName = 'SvgIcon';
export default ImageCropDin;
|
src/website/app/pages/RenderProps/examples/ThemeAccess.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import LiveProvider from '../../../LiveProvider';
import styled from '@emotion/styled';
import { withTheme } from 'emotion-theming';
import Menu from '../../../../../library/Menu';
import { menuItemTheme } from '../../../../../library/Menu/themes';
export default function ThemeAccess() {
const liveProviderProps = {
scope: {
styled,
Menu,
menuItemTheme,
React,
withTheme
},
source: `
() => {
// import { menuItemTheme } from 'mineral-ui/Menu';
const StyledDiv = withTheme(
styled('div')(({ theme: baseTheme }) => {
const theme = menuItemTheme(baseTheme);
return {
backgroundColor: theme.color_gray_40,
margin: theme.space_stack_xs,
padding: theme.MenuItem_paddingVertical + ' ' + theme.MenuItem_paddingHorizontal
};
})
);
class CustomItem extends React.PureComponent {
render() {
return <StyledDiv {...this.props} />;
}
}
const item = ({ props }) => <CustomItem {...props} />;
return (
<Menu
item={item}
data={[
{ text: 'Item 1' },
{ text: 'Item 2' },
{ text: 'Item 3' }
]} />
);
}
`
};
return <LiveProvider {...liveProviderProps} />;
}
|
Website/src/components/Header/DesktopNavBar.js | ameyjain/WallE- | import React, { Component } from 'react';
import { connect } from 'react-redux'
export default class DesktopNavBar extends Component {
render() {
return (
<div>
<header id="header" className="alt">
<h1><a href="/">Wall-e Inc.</a></h1>
<nav>
<a href="/">Home</a>
<a href="/checkout">Buy Now</a>
<a href="/contact">Contact</a>
<a href="/contact">FAQ</a>
</nav>
</header>
</div>
)
}
}
|
src/container/ErrorPage/index.js | ztplz/CNode-react-native | /**
* React Native App
* https://github.com/ztplz/CNode-react-native
* email: mysticzt@gmail.com
*/
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet
} from 'react-native';
import NetErrorPage from '../../components/ErrorPage';
class NetErrorPage extends Component {
static navigationOptions = {
title: '错误',
headerTintColor: '#ffffff',
headerStyle: {
backgroundColor: '#878fe0',
},
};
render() {
return (
<NetErrorPage />
)
}
}
export default NetErrorPage;
|
src/layout/footer.js | bokuweb/re-bulma | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from '../../build/styles';
import { getCallbacks } from '../helper/helper';
export default class Footer extends Component {
static propTypes = {
children: PropTypes.any,
style: PropTypes.object,
className: PropTypes.string,
};
static defaultProps = {
style: {},
className: '',
};
createClassName() {
return [
styles.footer,
this.props.className,
].join(' ').trim();
}
render() {
return (
<footer
{...getCallbacks(this.props)}
className={this.createClassName()}
style={this.props.style}
>
{this.props.children}
</footer>
);
}
}
|
docs/app/Examples/modules/Progress/Variations/index.js | mohammed88/Semantic-UI-React | import React from 'react'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
const ProgressVariationsExamples = () => (
<ExampleSection title='Variations'>
<ComponentExample
title='Inverted'
description='A progress bar can have its colors inverted.'
examplePath='modules/Progress/Variations/ProgressExampleInverted'
/>
<ComponentExample
title='Attached'
description='A progress bar can show progress of an element.'
examplePath='modules/Progress/Variations/ProgressExampleAttached'
/>
<ComponentExample
title='Size'
description='A progress bar can vary in size.'
examplePath='modules/Progress/Variations/ProgressExampleSize'
/>
<ComponentExample
title='Color'
description='A progress bar can have different colors.'
examplePath='modules/Progress/Variations/ProgressExampleColor'
/>
<ComponentExample
title='Inverted Color'
description='These colors can also be inverted for improved contrast on dark backgrounds.'
examplePath='modules/Progress/Variations/ProgressExampleInvertedColor'
/>
</ExampleSection>
)
export default ProgressVariationsExamples
|
src/page_views/shared/Header.js | max-su/max-su.github.io | import React from 'react';
import MaxSuJPG from 'src/assets/images/max.jpg';
import { BackgroundClass,
HeaderText,
HeaderButtonBackground,
HeaderButtonText } from 'src/assets/style_constants.js';
import 'src/assets/styles/_header.scss';
export default function Header() {
return (
<header className="center-align">
<div className={BackgroundClass} id="header">
<img className="circle responsive-img" id="header_icon" src={MaxSuJPG} alt="Max Su" />
<h3 className={`${HeaderText}`}>Max Su</h3>
<p className={`flow-text ${HeaderButtonBackground} ${HeaderButtonText}`}>Software Engineer</p>
</div>
</header>
);
}
|
src/components/home/HomePage.js | santiaro90/pluralsight-react-redux | import React from 'react';
import { Link } from 'react-router';
class HomePage extends React.Component {
render() {
return (
<div className="jumbotron">
<h1>Pluralsight Administration</h1>
<p>React, Redux and React Router in ES6 for ultra-responsive
web apps.</p>
<Link className="btn btn-primary btn-lg" to="about">Learn more</Link>
</div>
);
}
}
export default HomePage;
|
src/components/Parameters.js | SpikeO/isomorphic-flux-react-react-router | import ObjectActions from '../actions/ObjectActions';
import ObjectStore from '../stores/ObjectStore';
import React, { Component } from 'react';
class Parameters extends Component {
constructor(props) {
super(props);
this.state = ObjectStore.getObject(this.props.params.id);
}
handleChange(event) {
var object = this.state;
object.description = event.target.value;
this.setState(object);
}
save() {
ObjectActions.updateDescription(this.state.id, this.state.description);
}
render() {
return (
<div>
<h2>This is the Parameters component.</h2>
<p>
Parameter value is {this.props.params.id}.
</p>
<p>
Object description:
</p>
<p>
<textarea value={this.state.description} onChange={this.handleChange.bind(this)} />
<button onClick={this.save.bind(this)}>
Save
</button>
</p>
</div>
);
}
}
Parameters.propTypes = {
params: React.PropTypes.shape({
id: React.PropTypes.string
})
}
export default Parameters;
|
examples/app.js | americanpanorama/panorama | 'use strict';
import React, { Component } from 'react';
import { PanoramaDispatcher, PanoramaEventTypes } from '../src/PanoramaDispatcher';
import AreaChartExample from './components/example-areachart';
import BarChartExample from './components/example-barchart';
import D3ChoroplethExample from './components/example-d3Choropleth';
import Donut from './components/example-donut';
import IntroManagerExample from './components/example-introManager';
import ItemSelectorExample from './components/example-itemSelector';
import LeafletChoropleth from './components/example-leafletChoropleth';
import LegendExample from './components/example-legend';
import LineChartExample from './components/example-linechart';
import PunchcardExample from './components/example-punchcard';
import NavigationExample from './components/example-navigation';
import ScatterplotExample from './components/example-scatterplot';
import TexturalListExample from './components/example-texturalList';
class App extends Component {
static displayName = 'App';
constructor (props) {
super(props);
this.state = {};
this.onLegendSelected = this.onLegendSelected.bind(this);
this.onItemSelected = this.onItemSelected.bind(this);
this.onChartSliderSelected = this.onChartSliderSelected.bind(this);
}
componentWillMount () {
// @panorama/toolkit offers a global dispatcher that can be used instead of passing callbacks to child components.
// This option can be useful when your component hierarchy is multiple levels deep, and the component
// that needs to handle a change is multiple levels above the component dispatching the event.
PanoramaDispatcher.addListener(PanoramaEventTypes.Legend.selected, this.onLegendSelected);
PanoramaDispatcher.addListener(PanoramaEventTypes.ItemSelector.selected, this.onItemSelected);
PanoramaDispatcher.addListener(PanoramaEventTypes.ChartSlider.selected, this.onChartSliderSelected);
}
onLegendSelected (value, index) {
console.log('via PanoramaDispatcher: Legend selected: { value:' + value + ', index:' + index + ' }');
}
onItemSelected (value, index) {
console.log('via PanoramaDispatcher: ItemSelector selected: { value:' + value + ', index:' + index + ' }');
}
onChartSliderSelected (value) {
console.log('via PanoramaDispatcher: ChartSlider selected: { value:' + value + ' }');
}
render () {
return (
<div>
<h1>Panorama Toolkit examples</h1>
<hr />
<h2>Area Chart</h2>
<AreaChartExample />
<h2>Bar Chart</h2>
<BarChartExample />
<h2>Choropleth</h2>
<D3ChoroplethExample />
<h2><a name="donut">Donut</a></h2>
<Donut />
<h2>IntroManager</h2>
<IntroManagerExample />
<h2>ItemSelector</h2>
<ItemSelectorExample { ...this.state.itemSelector } />
<h2>Leaflet Choropleth</h2>
<LeafletChoropleth />
<h2>Legend</h2>
<LegendExample { ...this.state.legend } />
<h2>Line Chart</h2>
<LineChartExample />
<h2>Punchcard</h2>
<PunchcardExample />
<h2>Navigation</h2>
<NavigationExample />
<h2>Scatter Plot</h2>
<ScatterplotExample />
<h2>Textural List</h2>
<TexturalListExample />
</div>
);
}
}
export default App; |
src/components/SelectorLanguageFlags/SelectorLanguageFlags.js | WDAqua/frontEnd | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-2016 Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React, { Component } from 'react';
import {connect} from 'react-redux'
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './SelectorLanguageFlags.scss';
import ReactSuperSelect from 'react-super-select';
import {setLanguage} from '../../actions/language';
import {setKnowledgebase} from '../../actions/knowledgebase';
@connect((store) => {
return {
language: store.lang.language,
knowledgebase: store.knowledgebase.knowledgebase,
}
})
class LanguageSelectorFlags extends Component {
initialFlag = {
id: this.props.language,
name: this.props.language,
}
options = [
{
id: "en",
name: "English",
},{
id: "de",
name: "Deutsch",
},{
id: "fr",
name: "Francais",
},{
id: "it",
name: "Italiano",
},{
id: "es",
name: "Español",
},{
id: "pt",
name: "Português",
}, {
id: "zh",
name: "Chinese",
}
// },{
// id: "ar",
// name: "Arabic",
// }
];
flags = {
de: require('./images/flags/germany.png'),
en: require('./images/flags/united-kingdom.png'),
fr: require('./images/flags/france.png'),
it: require('./images/flags/italy.png'),
es: require('./images/flags/spain.png'),
pt: require('./images/flags/portugal.png'),
zh: require('./images/flags/china.png'),
ar: require('./images/flags/arab.png'),
};
flagTemplate(item, search) {
console.log("item flag");
console.log(item);
return(
<div key="item.name">
<img className={s.img} src={this.flags[item.id]}/>
<span>{item.name}</span>
</div>);
}
flagSelected(item) {
var selected = [];
for (var i=0; i<item.length; i++){
selected.push(<img key={i} className={s.img} src={this.flags[item[i].id]}/>)
}
return(
<div key="item">
{selected}
</div>);
}
handleChange(option){
this.props.dispatch(setLanguage([option.id]));
if (option.id=="zh"){
this.props.dispatch(setKnowledgebase(["wikidata"]));
}
if (option.id=="ar"){
this.props.dispatch(setKnowledgebase(["wikidata"]));
}
}
render() {
return (
<ReactSuperSelect onChange={this.handleChange.bind(this)} customSelectedValueTemplateFunction={this.flagSelected.bind(this)} customOptionTemplateFunction={this.flagTemplate.bind(this)} dataSource={this.options} initialValue={this.initialFlag} clearable={false} deselectOnSelectedOptionClick={false} />
);
}
}
export default withStyles(LanguageSelectorFlags, s);
|
fields/components/DateInput.js | udp/keystone | import moment from 'moment';
import DayPicker from 'react-day-picker';
import React from 'react';
import Popout from '../../admin/src/components/Popout';
import { FormInput } from 'elemental';
function isSameDay(d1, d2) {
if (!_.isDate(d1)) {
d1 = new Date();
}
if (!_.isDate(d2)) {
d2 = new Date();
}
d1.setHours(0, 0, 0, 0);
d2.setHours(0, 0, 0, 0);
return d1.getTime() === d2.getTime();
}
module.exports = React.createClass({
displayName: 'DateInput',
// set default properties
getDefaultProps () {
return {
format: 'YYYY-MM-DD'
};
},
getInitialState () {
return {
selectedDay: this.props.value,
id: Math.round(Math.random() * 100000),
pickerIsOpen: false
};
},
// componentWillReceiveProps: function(newProps) {
// console.log(moment(newProps.value).format("ddd MMMM DD YYYY hh:mm:ss a Z"));
// if (newProps.value === this.state.selectedDay) return;
// this.setState({
// selectedDay: moment(newProps.value).format("ddd MMMM DD YYYY hh:mm:ss a Z")
// });
// },
handleChange (e, day) {
this.setState({
selectedDay: day
}, () => {
setTimeout(() => {
this.setState({
pickerIsOpen: false
});
}, 200);
});
},
handleFocus (e) {
this.setState({
pickerIsOpen: true
});
},
handleBlur (e) {
},
render () {
let { selectedDay } = this.state;
let modifiers = {
'selected': (day) => isSameDay(selectedDay, day)
};
return (
<div>
<FormInput
autoComplete="off"
id={this.state.id}
name={this.props.name}
onBlur={this.handleBlur}
onFocus={this.handleFocus}
onChange={this.handleChange}
placeholder={this.props.format}
value={moment(selectedDay).format(this.props.format)} />
<Popout
isOpen={this.state.pickerIsOpen}
onCancel={() => this.setState({ pickerIsOpen: false })}
relativeToID={this.state.id}
width={260}>
<DayPicker
modifiers={ modifiers }
onDayClick={ this.handleChange }
style={{ marginBottom: 9 }}
tabIndex={-1} />
</Popout>
</div>
);
// return <FormInput name={this.props.name} value={this.state.value} placeholder={this.props.format} onChange={this.handleChange} onBlur={this.handleBlur} autoComplete="off" />;
}
});
|
src/admin/client/routes/logout.js | cezerin/cezerin | import React from 'react';
import * as auth from 'lib/auth';
export default class Logout extends React.Component {
componentWillMount() {
auth.removeToken();
}
render() {
return null;
}
}
|
src/svg-icons/action/payment.js | rhaedes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPayment = (props) => (
<SvgIcon {...props}>
<path d="M20 4H4c-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 14H4v-6h16v6zm0-10H4V6h16v2z"/>
</SvgIcon>
);
ActionPayment = pure(ActionPayment);
ActionPayment.displayName = 'ActionPayment';
export default ActionPayment;
|
docs/src/PureText.js | picidaejs/picidaejs | // import React from 'react'
const PureText = () =>
<div>Text</div>;
|
src/routes/contact/index.js | bharathbhsp/refactored-funicular | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import Layout from '../../components/Layout';
import Contact from './Contact';
const title = 'Contact Us';
function action() {
return {
chunks: ['contact'],
title,
component: (
<Layout>
<Contact title={title} />
</Layout>
),
};
}
export default action;
|
src/app/components/project/rings/RingsView.js | tscok/birds2 | import React from 'react';
const RingsView = React.createClass({
render() {
return (
<div>
<h1>RingsView</h1>
</div>
);
}
});
export default RingsView; |
frontend/src/components/home/HomePage.js | raulGX/recipeblog | import React from 'react';
class HomePage extends React.Component {
render() {
return (
<div className="jumbotron">
<h1>Home</h1>
</div>
);
}
}
export default HomePage;
|
src/components/comment_list.js | kors-mk5/react-starter | import React, { Component } from 'react';
import { connect } from 'react-redux';
const CommentList = (props) => {
const list = props.comments.map(comment => <li key={comment}>{comment}</li>);
return(
<ul className="comment-list">{list}</ul>
);
};
function mapStateToProps(state) {
return {comments: state.comments};
}
export default connect(mapStateToProps)(CommentList); |
src/Parser/ElementalShaman/Modules/Features/Maelstrom/CastEfficiencyComponent.js | mwwscott0/WoWAnalyzer | // Based on Main/CastEfficiency.js
import React from 'react';
import PropTypes from 'prop-types';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
const CastEfficiency = ({ categories, abilities }) => {
if (!abilities) {
return <div>Loading...</div>;
}
return (
<div style={{ marginTop: -10, marginBottom: -10 }}>
<table className="data-table" style={{ marginTop: 10, marginBottom: 10 }}>
{Object.keys(categories).map(key => (
<tbody key={key}>
<tr>
<th>{categories[key]}</th>
<th className="text-center">Casts</th>
<th className="text-center">{key === 'spend' ? <dfn data-tip="Approxomatly.">Spend</dfn> : ''}</th>
<th className="text-center">{key === 'generated' ? <dfn data-tip="Approxomatly.">Generated</dfn> : ''}</th>
<th className="text-center"><dfn data-tip="Approxomatly.">Wasted</dfn></th>
<th />
</tr>
{abilities
.filter(item => item.ability.category === categories[key])
.map(({ ability, casts, spend, created, wasted, canBeImproved }) => {
const name = ability.name;
return (
<tr key={name}>
<td style={{ width: '35%' }}>
<SpellLink id={ability.spellId} style={{ color: '#fff' }}>
<SpellIcon id={ability.spellId} noLink /> {name}
</SpellLink>
</td>
<td className="text-center" style={{ minWidth: 80 }}>
{casts}
</td>
<td className="text-center" style={{ minWidth: 80 }}>
{spend || ''}
</td>
<td className="text-center" style={{ minWidth: 80 }}>
{created || ''}
</td>
<td className="text-center" style={{ minWidth: 80 }}>
{wasted || ''}
</td>
<td style={{ width: '25%', color: 'orange' }}>
{canBeImproved && !ability.noCanBeImproved && 'Can be improved.'}
</td>
</tr>
);
})}
</tbody>
))}
</table>
</div>
);
};
CastEfficiency.propTypes = {
abilities: PropTypes.arrayOf(PropTypes.shape({
ability: PropTypes.shape({
name: PropTypes.string.isRequired,
category: PropTypes.string.isRequired,
spellId: PropTypes.number.isRequired,
}).isRequired,
})).isRequired,
categories: PropTypes.shape(),
};
export default CastEfficiency;
|
react-app/src/index.js | danieluy/www.danielsosa.uy | import React from 'react';
import ReactDOM from 'react-dom';
import { Router, Route, IndexRoute, browserHistory } from 'react-router';
import App from './App';
import Home from './sections/home/Home';
import Img from './sections/img/Img';
import Arq from './sections/arq/Arq';
import Dev from './sections/dev/Dev';
import DevHome from './sections/dev/dev-home/DevHome';
import DevWork from './sections/dev/dev-work/DevWork';
import DevAcademic from './sections/dev/dev-academic/DevAcademic';
import DevContact from './sections/dev/dev-contact/DevContact';
import DevStuff from './sections/dev/dev-stuff/DevStuff';
ReactDOM.render(
<Router history={browserHistory}>
<Route path="/" component={App}>
<IndexRoute component={Home} />
<Route path="/dev" component={Dev}>
<IndexRoute component={DevHome} />
<Route path="/dev/work" component={DevWork}></Route>
<Route path="/dev/academic" component={DevAcademic}></Route>
<Route path="/dev/contact" component={DevContact}></Route>
<Route path="/dev/stuff" component={DevStuff}></Route>
</Route>
<Route path="/arq" component={Arq} />
<Route path="/renders" component={Img} />
{/* <Route path="/*" component={Error404} /> */}
</Route>
</Router>
, document.getElementById('root')
); |
react-router-es6-example/node_modules/react-router/es6/Link.js | akhilaantony/React-Stylisted | 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 warning from './routerWarning';
import invariant from 'invariant';
import { routerShape } from './PropTypes';
var _React$PropTypes = React.PropTypes;
var bool = _React$PropTypes.bool;
var object = _React$PropTypes.object;
var string = _React$PropTypes.string;
var func = _React$PropTypes.func;
var 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 createLocationDescriptor(to, _ref) {
var query = _ref.query;
var hash = _ref.hash;
var state = _ref.state;
if (query || hash || state) {
return { pathname: to, query: query, hash: hash, state: state };
}
return 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',
contextTypes: {
router: routerShape
},
propTypes: {
to: oneOfType([string, object]),
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;
!this.context.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();
var _props = this.props;
var to = _props.to;
var query = _props.query;
var hash = _props.hash;
var state = _props.state;
var location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
this.context.router.push(location);
},
render: function render() {
var _props2 = this.props;
var to = _props2.to;
var query = _props2.query;
var hash = _props2.hash;
var state = _props2.state;
var activeClassName = _props2.activeClassName;
var activeStyle = _props2.activeStyle;
var onlyActiveOnIndex = _props2.onlyActiveOnIndex;
var props = _objectWithoutProperties(_props2, ['to', 'query', 'hash', 'state', 'activeClassName', 'activeStyle', 'onlyActiveOnIndex']);
process.env.NODE_ENV !== 'production' ? warning(!(query || hash || state), 'the `query`, `hash`, and `state` props on `<Link>` are deprecated, use `<Link to={{ pathname, query, hash, state }}/>. http://tiny.cc/router-isActivedeprecated') : void 0;
// Ignore if rendered outside the context of router, simplifies 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 location = createLocationDescriptor(to, { query: query, hash: hash, state: state });
props.href = router.createHref(location);
if (activeClassName || activeStyle != null && !isEmptyObject(activeStyle)) {
if (router.isActive(location, 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; |
components/Header.react.js | pierreavizou/universal-routed-flux-demo | import React from 'react';
import TodoActions from '../flux-infra/actions/TodoActions';
import TodoTextInput from './TodoTextInput.react';
export default class Header extends React.Component{
constructor(props){
super(props);
}
/**
* @return {object}
*/
render () {
return (
<header id="header">
<h1>Universal todos</h1>
<TodoTextInput
id="new-todo"
placeholder="What needs to be done?"
onSave={this._onSave}
saveOnBlur={false}
/>
</header>
);
}
/**
* Event handler called within TodoTextInput.
* Defining this here allows TodoTextInput to be used in multiple places
* in different ways.
* @param {string} text
*/
_onSave (text) {
if (text.trim()){
TodoActions.create(text);
}
}
}
|
src/containers/list_podcast_episodes.js | rdenadai/mockingbird | import { css } from '../css';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import Avatar from 'material-ui/Avatar';
import FontIcon from 'material-ui/FontIcon';
import {blueGrey800} from 'material-ui/styles/colors';
import Divider from 'material-ui/Divider';
import {List, ListItem} from 'material-ui/List';
import IconButton from 'material-ui/IconButton';
const uuid = require('uuid');
import {
downloadEpisodeAudio
} from '../actions/podcast';
import Loading from '../components/loading';
const listCSS = {
diplay: 'block',
height: '100%',
overflow: 'auto'
};
const downloadIcon = `${css.fontAwesome.fa} ${css.fontAwesome['fa-download']}`;
class EpisodeList extends Component {
constructor(props) {
super(props);
}
onClickListItem(id, collectionId, audioUrl, audioExtension, audioSize) {
console.log(id);
console.log(collectionId);
console.log(audioUrl);
console.log(audioSize);
this.props.downloadEpisodeAudio(collectionId, id, audioExtension);
}
renderPodcastEpisodesList = (episode) => {
const saved = this.props.saved;
const id = episode.id;
const collectionId = episode.collectionId;
const title = episode.title;
const description = episode.description;
const audioUrl = episode.audio_url;
const audioExtension = episode.audio_extension;
const audioSize = episode.audio_size;
// const duration = episode.duration;
// const published = episode.published;
let rightIconButton = null;
if(saved) {
rightIconButton = (
<IconButton
touch={true}
onClick={this.onClickListItem.bind(this, id, collectionId, audioUrl, audioExtension, audioSize)}
tooltip="download"
tooltipPosition="bottom-left">
<FontIcon className={downloadIcon} color={blueGrey800} />
</IconButton>
);
}
const avatar = (
<Avatar className={css.baseCSS.avatarCSS} size={55} src={this.props.image} />
);
return (
<div key={uuid()}>
<ListItem
key={id}
leftAvatar={avatar}
rightIconButton={rightIconButton}
primaryText={title}
secondaryText={<small><div dangerouslySetInnerHTML={{__html: description }} /></small>}
secondaryTextLines={2} />
<Divider key={uuid()} inset={true} />
</div>
);
}
render() {
const dados = this.props.dados;
if(!!dados) {
return (
<List style={listCSS}>
{dados.episodes.map(this.renderPodcastEpisodesList)}
</List>
);
}
return <Loading />;
}
}
EpisodeList.propTypes = {
messages: React.PropTypes.object,
dados: React.PropTypes.object,
saved: React.PropTypes.bool,
image: React.PropTypes.string,
downloadEpisodeAudio: React.PropTypes.func
};
// React-Redux integration...
function mapStateToProps(state) {
return {
messages: state.messages
};
}
const mapDispatchToProps = { downloadEpisodeAudio };
export default connect(mapStateToProps, mapDispatchToProps)(EpisodeList);
|
app/components/ConnectDapp/ApproveTransaction.js | CityOfZion/neon-wallet | // @flow
import React from 'react'
import classNames from 'classnames'
import { isEmpty } from 'lodash-es'
import { JsonRpcRequest } from '@json-rpc-tools/utils'
import { useWalletConnect } from '../../context/WalletConnect/WalletConnectContext'
import { ROUTES } from '../../core/constants'
import CloseButton from '../CloseButton'
import FullHeightPanel from '../Panel/FullHeightPanel'
import WallletConnect from '../../assets/icons/wallet_connect.svg'
import styles from '../../containers/ConnectDapp/styles.scss'
import CheckMarkIcon from '../../assets/icons/confirm-circle.svg'
import DialogueBox from '../DialogueBox'
import WarningIcon from '../../assets/icons/warning.svg'
import Confirm from '../../assets/icons/confirm_connection.svg'
import Deny from '../../assets/icons/deny_connection.svg'
import { TX_STATE_TYPE_MAPPINGS } from '../../containers/ConnectDapp/mocks'
import CopyToClipboard from '../CopyToClipboard'
import Tooltip from '../Tooltip'
import DoraIcon from '../../assets/icons/dora_icon_light.svg'
import DoraIconDark from '../../assets/icons/dora_icon_dark.svg'
import Info from '../../assets/icons/info.svg'
import Up from '../../assets/icons/chevron-up.svg'
import Down from '../../assets/icons/chevron-down.svg'
const electron = require('electron').remote
const WITNESS_SCOPE = {
'0': 'None',
'1': 'CalledByEntry',
'16': 'CustomContracts',
'32': 'CustomGroups',
'128': 'Global',
}
const ApproveTransaction = ({
request,
peer,
isHardwareLogin,
resetState,
history,
showSuccessNotification,
setLoading,
loading,
fee,
theme,
requestParamsVisible,
setRequestParamsVisible,
net,
}: {
request: JsonRpcRequest,
peer: any,
isHardwareLogin: boolean,
resetState: () => any,
history: any,
showSuccessNotification: ({ message: string }) => any,
setLoading: boolean => any,
loading: boolean,
fee: string,
theme: string,
requestParamsVisible: { [key: number]: boolean },
setRequestParamsVisible: ({ [key: number]: boolean }) => any,
net: string,
}) => {
const walletConnectCtx = useWalletConnect()
const shouldDisplayReqParams = invocation => !!invocation.args.length
const getParamDefinitions = invocation => {
if (invocation.contract && invocation.contract.abi) {
return invocation.contract.abi.methods.find(
method => method.name === invocation.operation,
).parameters
}
return new Array(invocation.args.length)
.fill()
.map((_, i) => ({ name: i, type: 'unknown' }))
}
const renderParam = (arg: any, definition: any) => (
<React.Fragment>
<div className={styles.parameterName}>{definition.name}:</div>
<div
className={
arg.type === 'Array' ? styles.parameterArray : styles.parameterValue
}
style={{
borderColor:
TX_STATE_TYPE_MAPPINGS[definition && definition.type] &&
TX_STATE_TYPE_MAPPINGS[definition && definition.type].color,
}}
>
{arg.type !== 'Array' && (
<React.Fragment>
<span>{arg.value || 'null'}</span>
<CopyToClipboard text={String((arg && arg.value) || 'null')} />
</React.Fragment>
)}
{arg.type === 'Array' &&
arg.value.map((element, j) => (
<div>
<div className={styles.arrayValue}>
<div className={styles.index}>{j}</div>
<span>{element && element.value}</span>
</div>
<CopyToClipboard text={String(element && element.value)} />
</div>
))}
</div>
<div className={styles.parameterType}>{definition.type}</div>
</React.Fragment>
)
const handleOpenDoraLink = hash => {
if (hash) {
return electron.shell.openExternal(
net === 'MainNet'
? `https://dora.coz.io/contract/neo3/mainnet/${hash}`
: `https://dora.coz.io/contract/neo3/testnet_rc4/${hash}`,
)
}
return null
}
return (
<FullHeightPanel
headerText="Wallet Connect"
renderCloseButton={() => (
<CloseButton
routeTo={ROUTES.DASHBOARD}
onClick={() => {
walletConnectCtx.rejectRequest(request)
resetState()
history.push(ROUTES.DASHBOARD)
}}
/>
)}
renderHeaderIcon={() => (
<div className={styles.walletConnectIcon}>
<WallletConnect />
</div>
)}
renderInstructions={false}
>
<div
className={classNames([
styles.approveConnectionContainer,
styles.approveRequestContainer,
])}
>
<img src={peer && peer.metadata.icons[0]} />
<h3>{peer && peer.metadata.name} wants to call </h3>
{isHardwareLogin && (
<DialogueBox
icon={
<WarningIcon
className={styles.warningIcon}
height={60}
width={60}
/>
}
renderText={() => (
<div>
To sign this transaction with your ledger, enable custom
contract data in the Neo N3 app settings. Read more about how to
enable this setting{' '}
<a
onClick={() => {
electron.shell.openExternal(
'https://medium.com/proof-of-working/signing-custom-transactions-with-ledger-29723f6eaa4',
)
}}
>
here
</a>.
</div>
)}
className={styles.warningDialogue}
/>
)}
{request &&
request.request.params.invocations.map((invocation, i) => (
<React.Fragment key={i}>
<div className={styles.contractName}>
<div className={classNames([])}>{invocation.contract.name}</div>
</div>
<div className={styles.connectionDetails}>
<div
className={classNames([
styles.detailsLabel,
styles.detailRow,
])}
>
<label>hash</label>
<div className={styles.scriptHash}>
{invocation.scriptHash}{' '}
{theme === 'Light' ? (
<DoraIcon
onClick={() =>
handleOpenDoraLink(invocation.scriptHash)
}
/>
) : (
<DoraIconDark
onClick={() =>
handleOpenDoraLink(invocation.scriptHash)
}
/>
)}
</div>
</div>
<div
className={classNames([
styles.detailsLabel,
styles.detailRow,
styles.noBorder,
])}
>
<label>method</label>
<div>{invocation.operation}</div>
</div>
{shouldDisplayReqParams(invocation) ? (
<div
className={classNames([
styles.details,
styles.radius,
styles.pointer,
])}
>
<div
className={classNames([
styles.radius,
styles.detailsLabel,
styles.noBorder,
styles.noPadding,
])}
onClick={() =>
setRequestParamsVisible({
...requestParamsVisible,
[i]: !requestParamsVisible[i],
})
}
>
<label>request parameters</label>
<div>{requestParamsVisible[i] ? <Up /> : <Down />}</div>
</div>
{requestParamsVisible[i] && (
<div className={styles.requestParams}>
{invocation.args.map((p: any, i: number) => {
const paramDefinitions = getParamDefinitions(
invocation,
)
return (
<div
className={styles.methodParameter}
style={{
backgroundColor:
TX_STATE_TYPE_MAPPINGS[
paramDefinitions[i] &&
paramDefinitions[i].type
] &&
TX_STATE_TYPE_MAPPINGS[
paramDefinitions[i] &&
paramDefinitions[i].type
].color,
borderColor:
TX_STATE_TYPE_MAPPINGS[
paramDefinitions[i] &&
paramDefinitions[i].type
] &&
TX_STATE_TYPE_MAPPINGS[
paramDefinitions[i] &&
paramDefinitions[i].type
].color,
}}
>
{renderParam(p, paramDefinitions[i])}
</div>
)
})}
</div>
)}
</div>
) : null}
</div>
<br />
</React.Fragment>
))}
{request &&
request.request.params.signers && (
<div
className={classNames([
styles.detailsLabel,
styles.detailRow,
styles.sigRow,
])}
>
<label>signature scope</label>
<div>
{
WITNESS_SCOPE[
String(request.request.params.signers[0].scopes)
]
}
{WITNESS_SCOPE[
String(request.request.params.signers[0].scopes)
] === 'Global' && <WarningIcon />}
</div>
</div>
)}
<div
className={classNames([
styles.detailsLabel,
styles.detailRow,
styles.feeRow,
])}
>
<label>fee</label>
<div className={styles.fee}>
{fee} GAS
<Tooltip title="Other network fees may apply">
<Info />{' '}
</Tooltip>
</div>
</div>
<div className={styles.confirmation}>
Please confirm you would like to proceed
<div>
<Confirm
onClick={async () => {
if (!loading) {
setLoading(true)
await walletConnectCtx.approveRequest(request)
setLoading(false)
}
}}
/>
<Deny
onClick={() => {
if (!loading) {
showSuccessNotification({
message: `You have denied request from ${
peer ? peer.metadata.name : 'unknown dApp'
}.`,
})
walletConnectCtx.rejectRequest(request)
resetState()
history.push(ROUTES.DASHBOARD)
}
}}
/>
</div>
</div>
</div>
</FullHeightPanel>
)
}
export default ApproveTransaction
|
webui/src/config/routes.js | DroneEmployee/drone-employee-connect | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from '../shared/containers/app';
import NotFound from '../shared/components/app/notFound';
import * as Modules from '../routes/containers';
import * as Hardware from '../routes/hardware';
export default () => (
<div>
<Route path="/" component={App}>
<Route path="hardware" component={Hardware.Page}>
<IndexRoute component={Hardware.Main} />
</Route>
<Route component={Modules.Page}>
<IndexRoute component={Modules.Main} />
<Route path="new" component={Modules.New} />
<Route path="modules/:name" component={Modules.Show} />
</Route>
</Route>
<Route path="*" component={NotFound} />
</div>
);
|
components/AppName.js | isogon/styled-mdl-website | import React from 'react'
import styled from 'styled-components'
const Title = styled.h1`
margin: 0;
font-weight: 800;
font-size: 14px;
position: relative;
margin: 0px;
text-transform: uppercase;
letter-spacing: 1px;
color: white;
`
export default () => <Title>STYLED MDL</Title>
|
src/src/components/notas.js | Hexamagnus/Front-End | import React, { Component } from 'react';
import './notas.css';
class Notas extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className="col-md-12">
<div className="col-md-12">
<a className="btn btn-info btn-lg btn-agregar" href="#" onClick={() => this.props.agregarNotaNueva()}>+</a>
</div>
{this.props.notas.map((nota, index) => {
return (
<div className="col-md-12">
<a className="btn btn-info btn-lg btn-nota" href="#" onClick={() => this.props.cambiarNotaActual(nota)}>
{nota.titulo} ({nota.fecha_modificacion})
</a>
</div>
)
})
}
</div>
);
}
};
export default Notas; |
packages/material-ui-icons/src/VolumeOff.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let VolumeOff = props =>
<SvgIcon {...props}>
<path d="M16.5 12c0-1.77-1.02-3.29-2.5-4.03v2.21l2.45 2.45c.03-.2.05-.41.05-.63zm2.5 0c0 .94-.2 1.82-.54 2.64l1.51 1.51C20.63 14.91 21 13.5 21 12c0-4.28-2.99-7.86-7-8.77v2.06c2.89.86 5 3.54 5 6.71zM4.27 3L3 4.27 7.73 9H3v6h4l5 5v-6.73l4.25 4.25c-.67.52-1.42.93-2.25 1.18v2.06c1.38-.31 2.63-.95 3.69-1.81L19.73 21 21 19.73l-9-9L4.27 3zM12 4L9.91 6.09 12 8.18V4z" />
</SvgIcon>;
VolumeOff = pure(VolumeOff);
VolumeOff.muiName = 'SvgIcon';
export default VolumeOff;
|
packages/icons/src/md/editor/FormatIndentIncrease.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdFormatIndentIncrease(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M6 42h36v-4H6v4zm0-26v16l8-8-8-8zm16 18h20v-4H22v4zM6 6v4h36V6H6zm16 12h20v-4H22v4zm0 8h20v-4H22v4z" />
</IconBase>
);
}
export default MdFormatIndentIncrease;
|
Animate/react-motion-demo/src/components/Container.js | imuntil/React | import React from 'react'
import ReactCSSTransitionGroup from 'react-addons-css-transition-group'
// import style from './Container.css';
export default class Container extends React.Component {
constructor(props, context) {
super(props, context);
}
componentWillMount() {
// document.body.style.margin = '0px'
// // 这是防止页面被拖拽
// document.body.addEventListener('touchmove', (ev) => {
// ev.preventDefault();
// })
}
render() {
return (
<ReactCSSTransitionGroup
transitionName='transitionWrapper'
component='div'
// className={style.transitionWrapper}
transitionEnterTimeout={5000}
transitionLeaveTimeout={3000}>
<div
key={this.props.location.pathname} style={{position:'absolute', width: '100%'}}>
{
this.props.children
}
</div>
</ReactCSSTransitionGroup>
)
}
} |
src/views/components/ButtonCard.js | physiii/open-automation | import React from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {doServiceAction, setServiceSettings} from '../../state/ducks/services-list/operations.js';
import ServiceCardBase from './ServiceCardBase.js';
import Switch from './Switch.js';
import SliderControl from './SliderControl.js';
import './ButtonCard.css';
export class ButtonCard extends React.Component {
constructor (props) {
super(props);
this.handleSettingsChange = this.handleSettingsChange.bind(this);
this.settings = {...props.service.settings};
this.state = {
slider_value: this.getPercentage100(props.service.settings.get('sensitivity')),
is_changing: false
};
}
handleSettingsChange () {
this.settings = {
...this.settings
};
this.props.saveSettings(this.settings);
}
toggleMode () {
if (this.settings.sensitivity > 0) {
this.settings.sensitivity = 0;
} else {
this.settings.sensitivity = 1;
}
this.handleSettingsChange();
}
onCardClick () {
this.toggleMode();
}
handleInput (value) {
this.settings.sensitivity = this.getPercentage1(value);
this.handleSettingsChange();
}
handleChange (value) {
this.settings.sensitivity = this.getPercentage1(value);
this.handleSettingsChange();
}
getPercentage1 (value) {
return Math.round(value) / 100;
}
getPercentage100 (value) {
return Math.round(value * 100);
}
render () {
const isConnected = this.props.service.state.get('connected'),
currentMode = this.state.is_changing
? this.state.slider_value
: this.getPercentage100(this.settings.sensitivity);
return (
<ServiceCardBase
name={this.settings.name || 'Button'}
status={isConnected && Number.isFinite(currentMode)
? currentMode + '%'
: 'Unknown'}
isConnected={isConnected}
onCardClick={this.toggleMode.bind(this)}
{...this.props}>
<div styleName="container">
<Switch
isOn={this.settings.sensitivity > 0}
showLabels={true}
disabled={!isConnected} />
<div styleName="sliderWrapper" onClick={(event) => event.stopPropagation()}>
<SliderControl
value={currentMode}
onInput={this.handleInput.bind(this)}
onChange={this.handleChange.bind(this)}
disabled={!isConnected} />
</div>
</div>
</ServiceCardBase>
);
}
}
ButtonCard.propTypes = {
service: PropTypes.object,
doAction: PropTypes.func,
saveSettings: PropTypes.func
};
const mergeProps = (stateProps, {dispatch}, ownProps) => ({
...ownProps,
...stateProps,
doAction: (serviceId, action) => dispatch(doServiceAction(serviceId, action)),
saveSettings: (settings) => dispatch(setServiceSettings(ownProps.service.id, settings, ownProps.service.settings.toObject()))
});
export default connect(null, null, mergeProps)(ButtonCard);
|
js/app.js | pletcher/mission-hacks | import 'babel-polyfill'
import '../css/app.css'
import { browserHistory } from 'react-router'
import { Provider } from 'react-redux'
import { RelayRouter } from 'react-router-relay'
import cookies from 'lib/cookies'
import React from 'react'
import ReactDOM from 'react-dom'
import Relay from 'react-relay'
import routes from 'routes'
import store from 'store'
Relay.injectNetworkLayer(
new Relay.DefaultNetworkLayer('/graphql', {
headers: {
Authorization: `Bearer ${cookies.get('jwt')}`,
},
})
)
ReactDOM.render(
<Provider store={store}>
<RelayRouter history={browserHistory} routes={routes} />
</Provider>,
document.getElementById('root')
)
|
pages/index.js | gr8fuljoe5/skeeball-scorecard | import React, { Component } from 'react';
import Tables from '../components/Tables/Tables.js'
export default class extends Component {
render() {
return (
<div>
<Tables/>
</div>
);
}
}
|
src/components/Schemes/Weave/index.js | nobus/weaver | import React, { Component } from 'react';
import WeaveElement from '../WeaveElement';
import './style.css';
import '../../../styles/index.css';
class Weave extends Component {
render() {
const {currentState, onClick, offClick} = this.props;
const indents = [];
for (let i = 0; i < currentState.settings.ro; i++) {
const colIndents = [];
for (let j = 0; j < currentState.settings.ry; j++)
colIndents.push(<WeaveElement
currentState={currentState}
onClick={onClick}
offClick={offClick}
row={j} col={i} key={j}
/>);
indents.push(
<div className='column' key={i}>
{colIndents}
</div>
);
}
const elementSize = parseInt(currentState.settings.elementSize, 10);
const style = {
width: (currentState.settings.ro * elementSize) + 2,
height: (currentState.settings.ry * elementSize) + 2
};
return (
<div className='Weave' style={style}>
{indents}
</div>
);
}
}
export default Weave;
|
src/components/Fixture/Team.js | footballhackday/hackday-example | 'use strict';
import React, { Component } from 'react';
export default class Team extends Component {
onClick(event) {
event.preventDefault();
this.props.onClick();
}
render() {
let team = this.props.team;
return (
<strong>
<a href="#" onClick={this.onClick.bind(this)}>{team.name}</a>
<span> {team.score} </span>
</strong>
);
}
}
|
client/util/react-intl-test-helper.js | leranf/hotwireCarRentalSearch | /**
* Components using the react-intl module require access to the intl context.
* This is not available when mounting single components in Enzyme.
* These helper functions aim to address that and wrap a valid,
* English-locale intl context around them.
*/
import React from 'react';
import { IntlProvider, intlShape } from 'react-intl';
import { mount, shallow } from 'enzyme';
// You can pass your messages to the IntlProvider. Optional: remove if unneeded.
const messages = require('../../Intl/localizationData/en');
// Create the IntlProvider to retrieve context for wrapping around.
const intlProvider = new IntlProvider({ locale: 'en', messages }, {});
export const { intl } = intlProvider.getChildContext();
/**
* When using React-Intl `injectIntl` on components, props.intl is required.
*/
const nodeWithIntlProp = node => {
return React.cloneElement(node, { intl });
};
export const shallowWithIntl = node => {
return shallow(nodeWithIntlProp(node), { context: { intl } });
};
export const mountWithIntl = node => {
return mount(nodeWithIntlProp(node), {
context: { intl },
childContextTypes: { intl: intlShape },
});
};
|
src/components/TechsPage.js | W01fw00d/w01fw00d_portfolio | import React, { Component } from 'react';
import '../stylesheets/TechsPage.css';
import react_logo from '../assets/logos/react.svg';
import backbone_logo from '../assets/logos/backbone.png';
import node_logo from '../assets/logos/node.png';
import cucumber_logo from '../assets/logos/cucumber.png';
import selenium_logo from '../assets/logos/selenium.png';
import angular_logo from '../assets/logos/angular.png';
import ionic_logo from '../assets/logos/ionic.png';
import laravel_logo from '../assets/logos/laravel.png';
import android_logo from '../assets/logos/android.png';
import git_logo from '../assets/logos/git.png';
import js6_logo from '../assets/logos/js6.png';
import htmlCss_logo from '../assets/logos/html_css.png';
import java_logo from '../assets/logos/java.png';
import python_logo from '../assets/logos/python.png';
import php_logo from '../assets/logos/php.png';
const techs = [
{type: 'framework', name: 'React', logo: react_logo, url: 'https://reactjs.org/'},
{type: 'framework', name: 'Backbone', logo: backbone_logo, url: 'http://backbonejs.org/'},
{type: 'framework', name: 'Node', logo: node_logo, url: 'https://nodejs.org/en/'},
{type: 'framework', name: 'Cucumber & Gherkin', logo: cucumber_logo, url: 'https://cucumber.io/'},
{type: 'framework', name: 'Selenium', logo: selenium_logo, url: 'http://www.seleniumhq.org/'},
{type: 'framework', name: 'Angular', logo: angular_logo, url: 'https://angular.io/'},
{type: 'framework', name: 'Ionic', logo: ionic_logo, url: 'https://ionicframework.com/'},
{type: 'framework', name: 'Laravel', logo: laravel_logo, url: 'https://laravel.com/'},
{type: 'framework', name: 'Android', logo: android_logo, url: 'https://www.android.com/'},
{type: 'framework', name: 'Git', logo: git_logo},
{type: 'language', name: 'ECMAScript 6', logo: js6_logo, url: 'http://es6-features.org/'},
{type: 'language', name: 'HTML5 & CSS3', logo: htmlCss_logo, url: 'https://www.w3.org/TR/html5/'},
{type: 'language', name: 'Java', logo: java_logo, url: 'https://www.java.com/'},
{type: 'language', name: 'Python', logo: python_logo, url: 'https://www.python.org/'},
{type: 'language', name: 'PHP', logo: php_logo, url: 'http://php.net/'}
];
class TechsPage extends Component {
render () {
let leftPositions = [],
topPositions = [];
const techsTags = techs.map((tech, index) => {
let imgStyle = {
left: this.getRandomNumber(leftPositions, window.innerWidth), //1200
bottom: this.getRandomNumber(topPositions, window.innerHeight - 150), //300
};
return (
<a key={index} target="_blank" href={tech.url}>
<img key={index} src={tech.logo} title={tech.name} className="tech-logo" alt="logo" style={imgStyle} />
</a>
);
});
return (
<div className="TechsPage">
{techsTags}
</div>
);
}
getRandomNumber(occupiedPositions, parentMaxNumber) {
const logoHeight = 120,
maxNumber = parentMaxNumber - logoHeight,
minNumber = 0;
let randomNumber = Math.random() * (maxNumber - minNumber) + minNumber;
occupiedPositions.push(randomNumber);
return randomNumber;
}
}
export default TechsPage; |
websrc/components/project/ProjectPage.js | Ricky-Nz/react-relay-example | import React from 'react';
import Relay from 'react-relay';
import { TitleBar, ParallaxBanner, PageFooter } from '../';
import ProjectSegments from './ProjectSegments';
import ProjectPager from './ProjectPager';
class ProjectPage extends React.Component {
componentDidMount() {
setTimeout(() => window.scrollTo(0, 0), 10);
}
render() {
const { project, projects } = this.props.app;
return (
<div>
<TitleBar title='Arc Studio Project' fixedTop/>
<ParallaxBanner style={{marginTop: 50}} height={400} imageUrl={project.banner}/>
<ProjectSegments project={project}/>
<br/><br/>
<ProjectPager app={this.props.app} currentId={this.props.params.id}/>
<br/><br/>
<PageFooter/>
</div>
);
}
}
export default Relay.createContainer(ProjectPage, {
initialVariables: {
id: null
},
fragments: {
app: () => Relay.QL`
fragment on App {
project(id: $id) {
banner,
${ProjectSegments.getFragment('project')}
},
${ProjectPager.getFragment('app')}
}
`
}
}); |
frontend/src/App.js | lcanal/demspirals | import React, { Component } from 'react';
import { Navbar,Nav,NavItem } from 'react-bootstrap';
import { Link,Route,BrowserRouter as Router } from 'react-router-dom';
import { LinkContainer } from 'react-router-bootstrap';
import Home from './components/Home';
import TopOverall from './components/TopOverall';
import TopPosition from './components/TopPosition';
import './css/App.css';
class App extends Component {
render() {
return (
<Router basename={process.env.PUBLIC_URL}>
<div className="App">
<Navbar collapseOnSelect>
<Navbar.Header>
<Navbar.Brand>
<Link to="/">Home</Link>
</Navbar.Brand>
<Navbar.Toggle />
</Navbar.Header>
<Navbar.Collapse>
<Nav>
<LinkContainer to="/app/topOverall">
<NavItem eventKey={1} href="/app/topOverall">Top Overall</NavItem>
</LinkContainer>
<LinkContainer to="/app/topQB">
<NavItem eventKey={2} href="/app/topQB">Top Quarterbacks</NavItem>
</LinkContainer>
<LinkContainer to="/app/topWR">
<NavItem eventKey={3} href="/app/topWR">Top Wideouts</NavItem>
</LinkContainer>
<LinkContainer to="/app/topRB">
<NavItem eventKey={4} href="/app/topRB">Top Rushers</NavItem>
</LinkContainer>
<LinkContainer to="/app/topTE">
<NavItem eventKey={5} href="/app/topTE">Top Tight Ends</NavItem>
</LinkContainer>
</Nav>
</Navbar.Collapse>
</Navbar>
<Route exact path="/" component={Home} />
<Route path="/app/topOverall" component={TopOverall} />
<Route path="/app/topQB" component={() => <TopPosition position="qb" />}/>
<Route path="/app/topWR" component={() => <TopPosition position="wr" />}/>
<Route path="/app/topRB" component={() => <TopPosition position="rb" />}/>
<Route path="/app/topTE" component={() => <TopPosition position="te" />}/>
</div>
</Router>
);
}
}
export default App;
|
src/components/common/svg-icons/action/perm-device-information.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionPermDeviceInformation = (props) => (
<SvgIcon {...props}>
<path d="M13 7h-2v2h2V7zm0 4h-2v6h2v-6zm4-9.99L7 1c-1.1 0-2 .9-2 2v18c0 1.1.9 2 2 2h10c1.1 0 2-.9 2-2V3c0-1.1-.9-1.99-2-1.99zM17 19H7V5h10v14z"/>
</SvgIcon>
);
ActionPermDeviceInformation = pure(ActionPermDeviceInformation);
ActionPermDeviceInformation.displayName = 'ActionPermDeviceInformation';
ActionPermDeviceInformation.muiName = 'SvgIcon';
export default ActionPermDeviceInformation;
|
src/ProgressBar/index.js | christianalfoni/ducky-components | import React from 'react';
import PropTypes from 'prop-types';
import styles from './styles.css';
import classNames from 'classnames';
function ProgressBar(props) {
const optBackground = (
<div
className={classNames(styles.inactive, styles[props.size])}
/>
);
return (
<div
className={classNames(styles.wrapper, props.className, styles[props.size])}
onClick={props.onClick}
>
<div className={styles.progressWrapper}>
{(props.percent > 0)
? <div
className={classNames(styles.progress, styles[props.size])}
style={{width: `${props.percent}%`, backgroundColor: props.color}}
>
</div>
: optBackground}
</div>
{props.children}
</div>
);
}
ProgressBar.propTypes = {
children: PropTypes.node,
className: PropTypes.string,
color: PropTypes.string,
onClick: PropTypes.func,
percent: PropTypes.number,
size: PropTypes.oneOf(['standard', 'wide'])
};
export default ProgressBar;
|
app/static/src/diagnostic/EquipmentForm_modules/AditionalEqupmentParameters_modules/TransformerParams.js | vsilent/Vision | import React from 'react';
import FormControl from 'react-bootstrap/lib/FormControl';
import FormGroup from 'react-bootstrap/lib/FormGroup';
import ControlLabel from 'react-bootstrap/lib/ControlLabel';
import {findDOMNode} from 'react-dom';
import {hashHistory} from 'react-router';
import {Link} from 'react-router';
import Checkbox from 'react-bootstrap/lib/Checkbox';
import OverlayTrigger from 'react-bootstrap/lib/OverlayTrigger';
import Tooltip from 'react-bootstrap/lib/Tooltip';
import HelpBlock from 'react-bootstrap/lib/HelpBlock';
const TextField = React.createClass({
_onChange: function (e) {
this.props.onChange(e);
},
render: function () {
let tooltip = <Tooltip id={this.props.label}>{this.props.label}</Tooltip>;
var label = (this.props.label != null) ? this.props.label : "";
var name = (this.props.name != null) ? this.props.name : "";
var type = (this.props["data-type"] != null) ? this.props["data-type"]: undefined;
var len = (this.props["data-len"] != null) ? this.props["data-len"]: undefined;
var choice = (this.props["data-choice"] != null) ? this.props["data-choice"]: undefined;
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var value = (this.props["value"] != null) ? this.props["value"]: "";
return (
<OverlayTrigger overlay={tooltip} placement="top">
<FormGroup validationState={validationState}>
<ControlLabel>{label}</ControlLabel>
<FormControl type="text"
placeholder={label}
name={name}
data-type={type}
data-len={len}
data-choice={choice}
onChange={this._onChange}
value={value}
/>
<HelpBlock className="warning">{error}</HelpBlock>
<FormControl.Feedback />
</FormGroup>
</OverlayTrigger>
);
}
});
var SelectField = React.createClass({
handleChange: function (e) {
this.props.onChange(e);
},
getInitialState: function () {
return {
items: [],
isVisible: false,
value: -1
};
},
isVisible: function () {
return this.state.isVisible;
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.source + '/';
this.serverRequest = $.authorizedGet(source, function (result) {
this.setState({items: (result['result'])});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var label = (this.props.label != null) ? this.props.label : "";
var value = (this.props.value != null) ? this.props.value : "";
var name = (this.props.name != null) ? this.props.name : "";
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var required = this.props.required ? this.props.required : null;
var menuItems = [];
for (var key in this.state.items) {
menuItems.push(<option key={this.state.items[key].id}
value={this.state.items[key].id}>{`${this.state.items[key].name ? this.state.items[key].name : this.state.items[key].model}`}</option>);
}
return (
<FormGroup validationState={validationState}>
<ControlLabel>{label}</ControlLabel>
<FormControl componentClass="select"
onChange={this.handleChange}
value={value}
name={name}
required={required}
>
<option value="">{required ? this.props.label + " *" : this.props.label}</option>);
{menuItems}
</FormControl>
<HelpBlock className="warning">{error}</HelpBlock>
</FormGroup>
);
}
});
var BushSerialSelectField = React.createClass({
handleChange: function (event, index, value) {
this.setState({
value: event.target.value
});
},
getInitialState: function () {
return {
items: [],
isVisible: false,
value: -1
};
},
isVisible: function () {
return this.state.isVisible;
},
componentDidMount: function () {
var source = '/api/v1.0/' + this.props.source + '/';
this.serverRequest = $.authorizedGet(source, function (result) {
this.setState({items: (result['result'])});
}.bind(this), 'json');
},
componentWillUnmount: function () {
this.serverRequest.abort();
},
setVisible: function () {
this.state.isVisible = true;
},
render: function () {
var label = (this.props.label != null) ? this.props.label : "";
var value = (this.props.value != null) ? this.props.value : "";
var name = (this.props.name != null) ? this.props.name : "";
var validationState = (this.props.errors[name]) ? 'error' : null;
var error = this.props.errors[name];
var menuItems = [];
for (var key in this.state.items) {
menuItems.push(<option key={this.state.items[key].id}
value={this.state.items[key].id}>{`${this.state.items[key].name}`}</option>);
}
return (
<FormGroup validationState={validationState}>
<FormControl componentClass="select"
onChange={this.handleChange}
defaultValue={value}
name={name}
>
<option>{this.props.label}</option>);
{menuItems}
</FormControl>
<HelpBlock className="warning">{error}</HelpBlock>
</FormGroup>
);
}
});
var TransformerParams = React.createClass({
getInitialState: function () {
return {
'phase_number':'', 'threephase':'', 'fluid_volume':'', 'fluid_type_id':'',
'fluid_level_id':'', 'gassensor_id':'', 'bushing_serial1_id':'', 'bushing_serial2_id':'',
'bushing_serial3_id':'', 'bushing_serial4_id':'', 'bushing_serial5_id':'', 'bushing_serial6_id':'',
'bushing_serial7_id':'', 'bushing_serial8_id':'', 'bushing_serial9_id':'', 'bushing_serial10_id':'',
'bushing_serial11_id':'', 'bushing_serial12_id':'', 'mvaforced11':'', 'mvaforced12':'', 'mvaforced13':'',
'mvaforced14':'', 'imp_base1':'', 'imp_base2':'', 'impbasedmva3':'', 'impbasedmva4':'', 'mvaforced21':'', 'mvaforced22':'',
'mvaforced23':'', 'mvaforced24':'', 'mvaactual':'', 'mvaractual':'',
'mwreserve':'', 'mvareserve':'', 'mwultime':'', 'mvarultime':'',
'ratio_tag1':'', 'ratio_tag2':'', 'ratio_tag3':'', 'ratio_tag4':'',
'static_shield1':'', 'static_shield2':'', 'ratio_tag5':'', 'ratio_tag6':'',
'ratio_tag7':'', 'ratio_tag8':'', 'static_shield3':'', 'static_shield4':'',
'bushing_neutral1':'', 'bushing_neutral2':'', 'bushing_neutral3':'', 'bushing_neutral4':'',
'windings':'', 'winding_metal1':'', 'winding_metal2':'', 'winding_metal3':'', 'winding_metal4':'', 'primary_winding_connection':'', 'secondary_winding_connection':'',
'tertiary_winding_connection':'', 'quaternary_winding_connection':'', 'based_transformer_power':'', 'autotransformer':'',
'bil1':'', 'bil2':'', 'ltc1':'', 'ltc2':'',
'first_cooling_stage_power':'', 'second_cooling_stage_power':'',
'bil3':'', 'bil4':'', 'ltc3':'', 'third_cooling_stage_power':'',
'temperature_rise':'', 'cooling_rating':'', 'primary_tension':'', 'secondary_tension':'',
'tertiary_tension':'', 'impedance1':'', 'impedance2':'', 'impedance3':'', 'impedance4':'',
'formula_ratio1':'', 'formula_ratio2':'', 'formula_ratio3':'',
'sealed':'', 'welded_cover':'','id':'',
'errors': {}
}
},
handleChange: function(e){
var state = this.state;
if (e.target.type == "checkbox"){
state[e.target.name] = e.target.checked;
}
else
state[e.target.name] = e.target.value;
this.setState(state);
},
load:function() {
this.setState(this.props.equipment_item)
},
render: function () {
var errors = (Object.keys(this.state.errors).length) ? this.state.errors : this.props.errors;
return (
<div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Phase Number"
name="phase_number"
value={this.state.phase_number}
errors={errors}
data-choice={['1', '3', '6']}/>
</div>
<div className="col-md-2">
<Checkbox name="threephase" checked={this.state.threephase} onChange={this.handleChange}><b>Three Phase</b></Checkbox>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Fluid Volume"
name="fluid_volume"
value={this.state.fluid_volume}
errors={errors}
data-type="float"/>
</div>
{/*
<div className="col-md-2">
<SelectField
source="fluid_type"
label="Fluid Type"
value={this.state.fluid_type_id}
errors={errors}
name="fluid_type_id"
required={(this.props.edited)}/>
</div>
*/}
{/*<div className="col-md-2">
<SelectField
source="fluid_level"
label="Fluid Level"
value={this.state.fluid_level_id}
errors={errors}
name="fluid_level_id"/>
</div>*/}
<div className="col-md-2">
<SelectField onChange={this.handleChange}
source="gas_sensor"
label="Gas Sensor"
value={this.state.gassensor_id}
errors={errors}
name="gassensor_id"
required={(this.props.edited)}/>
</div>
</div>
{/*<div className="row">
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 1"
value={this.state.bushing_serial1_id}
errors={errors}
name="bushing_serial1_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 2"
value={this.state.bushing_serial2_id}
errors={errors}
name="bushing_serial2_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 3"
value={this.state.bushing_serial3_id}
errors={errors}
name="bushing_serial3_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 4"
value={this.state.bushing_serial4}
errors={errors}
name="bushing_serial4_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 5"
value={this.state.bushing_serial5_id}
errors={errors}
name="bushing_serial5_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 1"
value={this.state.bushing_serial6_id}
errors={errors}
name="bushing_serial6_id"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 7"
value={this.state.bushing_serial7}
errors={errors}
name="bushing_serial7_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 8"
value={this.state.bushing_serial8_id}
errors={errors}
name="bushing_serial8_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 9"
value={this.state.bushing_serial9_id}
errors={errors}
name="bushing_serial9_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 10"
value={this.state.bushing_serial10_id}
errors={errors}
name="bushing_serial10_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 11"
value={this.state.bushing_serial11_id}
errors={errors}
name="bushing_serial11_id"/>
</div>
<div className="col-md-2">
<BushSerialSelectField
source="bushing"
label="Bushing Serial 12"
value={this.state.bushing_serial12_id}
errors={errors}
name="bushing_serial12_id"/>
</div>
</div> */}
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 11"
name="mvaforced11"
value={this.state.mvaforced11}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 12"
name="mvaforced12"
value={this.state.mvaforced12}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 13"
name="mvaforced13"
value={this.state.mvaforced13}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 14"
name="mvaforced14"
value={this.state.mvaforced14}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Base Impedance 1"
name="imp_base1"
value={this.state.imp_base1}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Base Impedance 2"
name="imp_base2"
value={this.state.imp_base2}
errors={errors}
data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 21"
name="mvaforced21"
value={this.state.mvaforced21}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 22"
name="mvaforced22"
value={this.state.mvaforced22}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 23"
name="mvaforced23"
value={this.state.mvaforced23}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Forced 24"
name="mvaforced24"
value={this.state.mvaforced24}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Base Impedance 3"
name="impbasedmva3"
value={this.state.impbasedmva3}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Base Impedance 4"
name="impbasedmva4"
value={this.state.impbasedmva4}
errors={errors}
data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mva Actual"
name="mvaactual"
value={this.state.mvaactual}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Mvar Actual"
name="mvaractual"
value={this.state.mvaractual}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Reserve Mw"
name="mwreserve"
value={this.state.mwreserve}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Reserve Mva"
name="mvarreserve"
value={this.state.mvarreserve}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ultime Mw"
name="mwultime"
value={this.state.mwultime}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ultime Mvar"
name="mvarultime"
value={this.state.mvarultime}
errors={errors}
data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 1"
name="ratio_tag1"
value={this.state.ratio_tag1}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 2"
name="ratio_tag2"
value={this.state.ratio_tag2}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 3"
name="ratio_tag3"
value={this.state.ratio_tag3}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 4"
name="ratio_tag4"
value={this.state.ratio_tag4}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<Checkbox name="static_shield1" checked={this.state.static_shield1} onChange={this.handleChange}><b>Static Shield 1</b></Checkbox>
</div>
<div className="col-md-2">
<Checkbox name="static_shield2" checked={this.state.static_shield2} onChange={this.handleChange}><b>Static Shield 2</b></Checkbox>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 5"
name="ratio_tag5"
value={this.state.ratio_tag5}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 6"
name="ratio_tag6"
value={this.state.ratio_tag6}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 7"
name="ratio_tag7"
value={this.state.ratio_tag7}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ratio Tag 8"
name="ratio_tag8"
value={this.state.ratio_tag8}
errors={errors}
data-len="20"/>
</div>
<div className="col-md-2">
<Checkbox name="static_shield3" checked={this.state.static_shield3} onChange={this.handleChange}><b>Static Shield 3</b></Checkbox>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Static Shield 4"
name="static_shield4"
value={this.state.static_shield4}
errors={errors}
data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Bushing Neutral 1"
name="bushing_neutral1"
value={this.state.bushing_neutral1}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Bushing Neutral 2"
name="bushing_neutral2"
value={this.state.bushing_neutral2}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Bushing Neutral 3"
name="bushing_neutral3"
value={this.state.bushing_neutral3}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Bushing Neutral 4"
name="bushing_neutral4"
value={this.state.bushing_neutral4}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Windings"
name="windings"
value={this.state.windings}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Winding Metal 1"
name="winding_metal1"
value={this.state.winding_metal1}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Winding Metal 2"
name="winding_metal2"
value={this.state.winding_metal2}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Winding Metal 3"
name="winding_metal3"
value={this.state.winding_metal3}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Winding Metal 4"
name="winding_metal4"
value={this.state.winding_metal4}
errors={errors}
data-type="int"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Primary Winding Connection"
name="primary_winding_connection"
value={this.state.primary_winding_connection}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Secondary Winding Connection"
name="secondary_winding_connection"
value={this.state.secondary_winding_connection}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Tertiary Winding Connection"
name="tertiary_winding_connection"
value={this.state.tertiary_winding_connection}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Quaternary Winding Connection"
name="quaternary_winding_connection"
value={this.state.quaternary_winding_connection}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Based Power"
name="based_transformer_power"
value={this.state.based_transformer_power}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<Checkbox name="autotransformer" checked={this.state.autotransformer} onChange={this.handleChange}><b>Autotransformer</b></Checkbox>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="BIL 1"
name="bil1"
value={this.state.bil1}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="BIL 2"
name="bil2"
value={this.state.bil2}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ltc 1"
name="ltc1"
value={this.state.ltc1}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ltc 2"
name="ltc2"
value={this.state.ltc2}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="First Cooling Stage Power"
name="first_cooling_stage_power"
value={this.state.first_cooling_stage_power}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Second Cooling Stage Power"
name="second_cooling_stage_power"
value={this.state.second_cooling_stage_power}
errors={errors}
data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="BIL 3"
name="bil3"
value={this.state.bil3}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="BIL 4"
name="bil4"
value={this.state.bil4}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Ltc 3"
name="ltc3"
value={this.state.ltc3}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Third colling stage power"
name="third_cooling_stage_power"
value={this.state.third_cooling_stage_power}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Temperature Rise"
name="temperature_rise"
value={this.state.temperature_rise}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Cooling Rating"
name="cooling_rating"
value={this.state.cooling_rating}
errors={errors}
data-type="int"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Primary Tension"
name="primary_tension"
value={this.state.primary_tension}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Secondary Tension"
name="secondary_tension"
value={this.state.secondary_tension}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Tertiary Tension"
name="tertiary_tension"
value={this.state.tertiary_tension}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Impedance 1"
name="impedance1"
value={this.state.impedance1}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Impedance 2"
name="impedance2"
value={this.state.impedance2}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Impedance 3"
name="impedance3"
value={this.state.impedance3}
errors={errors}
data-type="float"/>
</div>
</div>
<div className="row">
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Formula Ratio 1"
name="formula_ratio"
value={this.state.formula_ratio}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Formula Ratio 2"
name="formula_ratio2"
value={this.state.formula_ratio2}
errors={errors}
data-type="int"/>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Formula Ratio 3"
name="formula_ratio3"
value={this.state.formula_ratio3}
errors={errors}
data-type="float"/>
</div>
<div className="col-md-2 ">
<Checkbox name="sealed" checked={this.state.sealed} onChange={this.handleChange}><b>Sealed</b></Checkbox>
</div>
<div className="col-md-2">
<Checkbox name="welded_cover" checked={this.state.welded_cover} onChange={this.handleChange}><b>Welded Cover</b></Checkbox>
</div>
<div className="col-md-2">
<TextField onChange={this.handleChange}
label="Impedance 4"
name="impedance4"
value={this.state.impedance4}
errors={errors}
data-type="float"/>
</div>
</div>
</div>
)
}
});
export default TransformerParams; |
src/main.js | yoshiyoshi7/react2chv2 | import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import './styles/main.scss'
import { MuiThemeProvider } from 'material-ui/styles';
import injectTapEventPlugin from 'react-tap-event-plugin';
// Needed for onTouchTap
// http://stackoverflow.com/a/34015469/988941
injectTapEventPlugin();
// 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(
<MuiThemeProvider>
<App store={store} routes={routes} />
</MuiThemeProvider>,
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()
|
app/containers/ViewerWidget/index.js | belongapp/belong | import React from 'react';
import { Link } from 'react-router';
import Relay, { updateNetworkLayer } from 'relay/index';
import { clearStorage, loggedIn, loggedOut } from 'containers/Viewer/lib';
import UserWidget from 'components/UserWidget';
import styles from './styles.css';
import buttonStyles from 'components/Button/styles.css';
class ViewerWidget extends React.Component { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
className: React.PropTypes.string,
viewer: React.PropTypes.shape({
user: React.PropTypes.object,
}).isRequired,
};
render() {
return (
<span className={this.props.className}>
{this.props.viewer.user && <UserWidget user={this.props.viewer.user} />}
{loggedOut() && <Link to="/login" className={`${buttonStyles.button} ${styles.loginButton}`}>
Log In
</Link>}
{loggedIn() && <div className={styles.dropDown}>
<button className={styles.dropDownButton}>▼</button>
<div className={styles.dropDownContent}>
<Link to="/" onClick={logout}>
Log Out
</Link>
</div>
</div>}
</span>
);
}
}
export default Relay.createContainer(ViewerWidget, {
fragments: {
viewer: () => Relay.QL`
fragment on Viewer {
user {
${UserWidget.getFragment('user')}
}
}
`,
},
});
function logout() {
clearStorage();
updateNetworkLayer();
window.location.pathname = '/';
}
|
demo/src/index.js | zachcoyle/redux-looking-glass | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import Demo from './Demo';
import registerServiceWorker from './registerServiceWorker';
import store from './configureStore'
ReactDOM.render(
<Provider store={store}>
<Demo />
</Provider>,
document.getElementById('demo')
);
registerServiceWorker();
|
src/svg-icons/maps/ev-station.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsEvStation = (props) => (
<SvgIcon {...props}>
<path d="M19.77 7.23l.01-.01-3.72-3.72L15 4.56l2.11 2.11c-.94.36-1.61 1.26-1.61 2.33 0 1.38 1.12 2.5 2.5 2.5.36 0 .69-.08 1-.21v7.21c0 .55-.45 1-1 1s-1-.45-1-1V14c0-1.1-.9-2-2-2h-1V5c0-1.1-.9-2-2-2H6c-1.1 0-2 .9-2 2v16h10v-7.5h1.5v5c0 1.38 1.12 2.5 2.5 2.5s2.5-1.12 2.5-2.5V9c0-.69-.28-1.32-.73-1.77zM18 10c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zM8 18v-4.5H6L10 6v5h2l-4 7z"/>
</SvgIcon>
);
MapsEvStation = pure(MapsEvStation);
MapsEvStation.displayName = 'MapsEvStation';
MapsEvStation.muiName = 'SvgIcon';
export default MapsEvStation;
|
static/scripts/components/Home.js | minhuaF/bcb-koa2 | import React from 'react';
import { Link } from 'react-router';
import Footer from './Footer.js';
// 无状态组件 首页的无状态是暂时的
const Home = React.createClass({
render: function(){
return (
<div style={{marginTop: -93 + 'px'}}>
<Link to="/signin"><header className="home-banner"></header></Link>
<section className="home-item white">
<ul className="clearfix">
<li className="ico-welfare">
<Link to='/daywelfare'></Link>
<p>每日福利</p>
</li>
<li className="ico-college">
<a href="#"></a>
<p>理财学院</p>
</li>
<li className="ico-safe">
<Link to='/security'></Link>
<p>安全保障</p>
</li>
<li className="ico-love">
<Link to='/collectlove'></Link>
<p>聚爱</p>
</li>
</ul>
</section>
<section className="notice white clearfix">
<i></i>
<p>陈**投资了<span>1000元</span>,黄**投资了<span>200元</span>,叶88投资fdsafsd</p>
<b></b>
</section>
<section className="project">
<h2>精品项目</h2>
<ul className="prt-list">
<li className="white dropdown">
<header>
<h3>新手标 201507090701</h3>
<span>本息保障</span>
</header>
<div className="dropdown clearfix">
<section>
<p>8.0<span>+0.5</span></p>
<p>年化收益率(%)</p>
</section>
<table>
<tbody><tr>
<td>期限</td>
<td>1天</td>
</tr>
<tr>
<td>可投</td>
<td>987,3895元</td>
</tr>
<tr>
<td>进度</td>
<td className="progress-box">
<div className="progress dropdown">
<div className="progressbar" style={{width:'100%;'}}></div>
<span className="progresstext">售罄</span>
</div>
</td>
</tr>
</tbody></table>
</div>
<a href="#"></a>
</li>
<li className="white dropdown">
<header>
<h3>新标预告 201507090701</h3>
<span>本息保障</span>
</header>
<div className="dropdown clearfix">
<section>
<p>8.0</p>
<p>年化收益率(%)</p>
</section>
<a href="#" className="btn-reserve">立即预约</a>
</div>
<a href="#"></a>
</li>
<li className="white dropdown">
<header>
<h3>新标预告 201507090701</h3>
<span>本息保障</span>
</header>
<div className="dropdown clearfix">
<section>
<p>8.0</p>
<p>年化收益率(%)</p>
</section>
<a href="#" className="btn-reserve btn-already">已预约</a>
</div>
<a href="#"></a>
</li>
<li className="white dropdown">
<header>
<h3>新手标 201507090701</h3>
<span>本息保障</span>
</header>
<div className="dropdown clearfix">
<section>
<p>8.0<span>+0.5</span></p>
<p>年化收益率(%)</p>
</section>
<p className="rookie"></p>
<table>
<tbody><tr>
<td>期限</td>
<td>1天</td>
</tr>
<tr>
<td>可投</td>
<td>987,3895元</td>
</tr>
<tr>
<td>进度</td>
<td className="progress-box">
<div className="progress dropdown">
<div className="progressbar" style={{width:'75%;'}}></div>
<span className="progresstext">75%</span>
</div>
</td>
</tr>
</tbody></table>
</div>
<a href="#"></a>
</li>
</ul>
</section>
<Footer name="home"/>
</div>
);
}
});
module.exports = Home; |
draft-js-emoji-plugin/src/components/EmojiSuggestionsPortal/index.js | koaninc/draft-js-plugins | import React, { Component } from 'react';
export default class EmojiSuggestionsPortal extends Component {
componentWillMount() {
this.props.store.register(this.props.offsetKey);
this.updatePortalClientRect(this.props);
// trigger a re-render so the EmojiSuggestions becomes active
this.props.setEditorState(this.props.getEditorState());
}
componentWillReceiveProps(nextProps) {
this.updatePortalClientRect(nextProps);
}
componentWillUnmount() {
this.props.store.unregister(this.props.offsetKey);
}
updatePortalClientRect(props) {
this.props.store.updatePortalClientRect(
props.offsetKey,
() => (
this.searchPortal.getBoundingClientRect()
),
);
}
render() {
return (
<span
className={this.key}
ref={(element) => { this.searchPortal = element; }}
>
{this.props.children}
</span>
);
}
}
|
src/scripts/navbar.js | ButuzGOL/constructor | import React from 'react';
import Radium from 'radium';
import uniqid from 'uniqid';
import groupBy from 'lodash.groupby';
import variables from './styles/variables';
import Div from './base/div';
import A from './base/a';
import Nav from './nav';
@Radium
export default class NavBar extends React.Component {
static propTypes = {
items: React.PropTypes.array.isRequired,
brand: React.PropTypes.shape({
label: React.PropTypes.string,
href: React.PropTypes.string
})
};
state = {
opened: null
};
constructor(props) {
super(props);
this.props = this.mapProps(props);
}
getStyles() {
return {
wrapper: {
base: {
background: variables.navbarBackground,
color: variables.navbarColor
},
after: {
content: '',
display: 'table',
clear: 'both'
},
before: {
content: '',
display: 'table'
}
},
base: {
margin: 0,
padding: 0,
listStyle: 'none',
float: 'left'
},
li: {
float: 'left',
position: 'relative'
},
a: {
base: {
display: 'block',
boxSizing: 'border-box',
textDecoration: 'none',
height: variables.navbarNavHeight,
padding: `0 ${variables.navbarNavPaddingHorizontal}`,
lineHeight: variables.navbarNavLineHeight,
color: variables.navbarNavColor,
fontSize: variables.navbarNavFontSize,
fontFamily: variables.navbarNavFontFamily,
fontWeight: variables.navbarNavFontWeight,
':hover': {
backgroundColor: variables.navbarNavHoverBackground,
color: variables.navbarNavHoverColor,
outline: 'none',
textDecoration: 'none'
},
':focus': {
backgroundColor: variables.navbarNavHoverBackground,
color: variables.navbarNavHoverColor,
outline: 'none'
},
':active': {
backgroundColor: variables.navbarNavActiveBackground,
color: variables.navbarNavActiveColor
}
},
active: {
backgroundColor: variables.navbarNavActiveBackground,
color: variables.navbarNavActiveColor
},
subLabel: {
base: {
// lineHeight: variables.navbarNavLineHeight - variables.navbarNavSubtitleFontSize - variables.navbarNavSubtitleOffset
lineHeight: '28px'
},
sub: {
// marginTop: ((variables.navbarNavLineHeight - variables.navbarNavSubtitleFontSize - variables.navbarNavFontSize) / -2) + variables.navbarNavSubtitleOffset,
marginTop: '-6px',
fontSize: variables.navbarNavSubtitleFontSize,
// lineHeight: variables.navbarNavSubtitleFontSize + variables.navbarNavSubtitleOffset
lineHeight: '12px'
}
}
},
brand: {
before: {
content: '',
display: 'inline-block',
height: '100%',
verticalAlign: 'middle'
},
base: {
boxSizing: 'border-box',
display: 'block',
height: variables.navbarNavHeight,
padding: `0 ${variables.navbarNavPaddingHorizontal}`,
float: 'left',
fontSize: variables.navbarBrandFontSize,
color: variables.navbarBrandColor,
textDecoration: 'none',
':hover': {
color: variables.navbarBrandColor,
textDecoration: 'none'
}
}
},
positions: {
right: {
float: 'right'
}
},
dropdown: {
base: {
display: 'none',
position: 'absolute',
top: '100%',
left: 0,
zIndex: variables.dropdownZIndex,
boxSizing: 'border-box',
width: variables.dropdownWidth,
padding: variables.dropdownPadding,
fontSize: variables.dropdownFontSize,
verticalAlign: 'top',
marginTop: variables.dropdownNavbarMargin,
background: variables.dropdownNavbarBackground,
color: variables.dropdownNavbarColor
},
open: {
display: 'block',
animation: `${variables.dropdownAnimation} 0.2s ease-in-out`,
transformOrigin: '0 0'
}
}
};
}
renderItems(items) {
const styles = this.getStyles();
return (
<ul style={styles.base}>
{items.map((item) => {
return (
<li
onMouseEnter={this.handleToggle.bind(this, item.id)}
onMouseLeave={this.handleToggle.bind(this, item.id)}
style={styles.li}>
<A
style={[
styles.a.base,
item.subLabel && styles.a.subLabel.base,
(item.active || this.state.opened === item.id) && styles.a.active
]}
href="#">
{item.label}
{item.subLabel ? (
<Div style={styles.a.subLabel.sub}>
{item.subLabel}
</Div>
) : null}
</A>
{item.children ? (
<Div style={[
styles.dropdown.base,
this.state.opened === item.id && styles.dropdown.open
]}>
<Nav
type="dropdown"
items={item.children} />
</Div>
) : null}
</li>
);
})}
</ul>
);
}
render() {
const styles = this.getStyles();
const props = this.props;
const groupedItems = groupBy(props.items, 'position');
return (
<Div style={styles.wrapper.base}>
<Div style={styles.wrapper.before} />
{props.brand ? (
<A
style={styles.brand.base}
href={props.brand.href}>
<Div style={styles.brand.before} />
{props.brand.label}
</A>
) : null}
{this.renderItems(groupedItems.undefined)}
{groupedItems.right.length ? (
<Div style={styles.positions.right}>
{this.renderItems(groupedItems.right)}
</Div>
) : null}
<Div style={styles.wrapper.after} />
</Div>
);
}
handleToggle(id) {
let opened = null;
if (!this.state.opened) {
opened = id;
}
this.setState({
opened
});
}
mapProps(props) {
props.items.forEach((item) => item.id = uniqid());
return props;
}
}
|
tests/react_children/component.js | AgentME/flow | // @flow
import React from 'react';
import type {Node} from 'react';
class MyComponent extends React.Component<{children: Node}, void> {
render(): Node {
// OK: Can pass a node down like so.
return <MyComponent>{this.props.children}</MyComponent>;
}
}
class MyComponentOptional extends React.Component<{children?: Node}, void> {}
<MyComponent />; // Error: `children` is required.
<MyComponent></MyComponent>; // Error: `children` is required.
<MyComponent> </MyComponent>; // OK: `children` may be a string.
<MyComponent>{}</MyComponent>; // Error: `children` is required.
<MyComponentOptional />; // OK: `children` is optional.
<MyComponentOptional></MyComponentOptional>; // OK: `children` is optional.
<MyComponentOptional> </MyComponentOptional>; // OK: `children` may be a string.
<MyComponentOptional>{}</MyComponentOptional>; // OK: `children` is optional.
// OK: The `ReactNode` allows any children.
<MyComponent>
{}
{undefined}
{null}
{true}
{false}
{0}
{42}
{'hello world'}
foobar
<buz />
{[undefined, null, true, false, 0, 42, 'hello world', 'foobar', <buz />]}
</MyComponent>;
// Error: Arbitrary objects are not allowed as children with `ReactNode`.
<MyComponent>
{{a: 1, b: 2, c: 3}}
</MyComponent>;
|
lesson-2/idea-journal/solution/src/components/NewNoteModal.js | msd-code-academy/lessons | import React from 'react'
import Modal from 'react-modal'
import * as shortId from 'shortid'
import '../styles/NewNoteModal.css'
class NewNoteModal extends React.Component {
constructor() {
super()
this.state = {
modalIsOpen: false,
note: {}
}
}
toggleModal = () => {
this.setState({
modalIsOpen: !this.state.modalIsOpen
})
}
handleChange = (field) => (e) => {
let note = this.state.note
note[field] = e.target.value
this.setState({note})
}
handleFormSubmit = (e) => {
e.preventDefault()
const {onAddNote} = this.props
const {note} = this.state
onAddNote({...note, uuid: shortId.generate()})
this.toggleModal()
}
render() {
const {modalIsOpen} = this.state
return (
<div className="NewNoteModal">
<a onClick={this.toggleModal}>ADD NOTE</a>
<Modal
isOpen={modalIsOpen}
onRequestClose={this.toggleModal}
className="NewNoteModal-modal-window"
overlayClassName="NewNoteModal-modal-overlay">
<h2>Add a new note</h2>
<form onSubmit={this.handleFormSubmit}>
<div>
<label htmlFor="title">Title</label>
<input type="text" id="title" onChange={this.handleChange('title')} />
</div>
<div className="NewNoteModal-textarea">
<label htmlFor="text">Text</label>
<textarea rows="4" id="text" onChange={this.handleChange('text')} />
</div>
<button type="submit">Submit</button>
</form>
</Modal>
</div>
)
}
}
export default NewNoteModal
|
src/pages/index.js | pixelstack/pixelstack.com | import React from 'react'
import Link from 'gatsby-link'
import logoSrc from '../assets/logo.svg'
const IndexPage = () => (
<section className='home-content'>
<img className='brand__logo' src={logoSrc} />
<p>Building solutions to your digital problems<br />through websites and web applications</p>
<ul className='contact-list'>
<li><a href="mailto:hello@pixelstack.com">Contact</a></li>
<li><a href="https://twitter.com/pixelstackcom" target="_blank">Twitter</a></li>
</ul>
</section>
)
export default IndexPage
|
node_modules/reflexbox/docs/components/GithubButton.js | HasanSa/hackathon |
import React from 'react'
const GithubButton = ({ user, repo, ...props }) => (
<div style={{ height: 20 }}>
<iframe src={`https://ghbtns.com/github-btn.html?user=${user}&repo=${repo}&type=star&count=true`}
frameBorder='0'
scrolling='0'
width='100px'
height='20px' />
</div>
)
GithubButton.defaultProps = {
user: 'jxnblk',
repo: 'reflexbox'
}
export default GithubButton
|
components/timeline/demo/index.js | TDFE/td-ui | /**
* Created by kongliang on 19/06/2017.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import Icon from '../../icon';
const MOUNT_NODE = document.getElementById('app');
let render = () => {
let Timeline = require('../index').default;
function Demo() {
return (
<div>
<Timeline pending={<a href="#">See more</a>}>
<Timeline.Item color="red">Create a services site 2015-09-01</Timeline.Item>
<Timeline.Item>Solve initial network problems 2015-09-01</Timeline.Item>
<Timeline.Item dot={<Icon type="sort" style={{ fontSize: '16px' }} />} color="red">Technical testing 2015-09-01</Timeline.Item>
<Timeline.Item>Network problems being solved 2015-09-01</Timeline.Item>
</Timeline>
</div>
);
}
ReactDOM.render(<Demo />, MOUNT_NODE);
};
try {
render();
} catch (e) {
console.log(e);
}
if (module.hot) {
module.hot.accept(['../index'], () => {
setTimeout(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE);
render();
});
});
}
|
frontend/app_v2/src/common/icons/Print.js | First-Peoples-Cultural-Council/fv-web-ui | import React from 'react'
import PropTypes from 'prop-types'
/**
* @summary Print
* @component
*
* @param {object} props
*
* @returns {node} jsx markup
*/
function Print({ styling }) {
return (
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100" className={styling}>
<title>Print</title>
<path d="M35.203 67.521h29.594a1.5 1.5 0 100-3H35.203a1.5 1.5 0 100 3zM34.21 76.359h31.58a1.5 1.5 0 100-3H34.21a1.5 1.5 0 100 3zM66.783 82.197H33.217a1.5 1.5 0 100 3h33.566a1.5 1.5 0 000-3z" />
<path d="M85.484 23.86H77V7a2 2 0 00-2-2H25a2 2 0 00-2 2v16.86h-8.484A9.516 9.516 0 005 33.374v27.968a9.516 9.516 0 009.516 9.516h7.257l-3.81 21.797A2 2 0 0019.933 95h60.134a2 2 0 001.97-2.344l-3.81-21.797h7.257A9.516 9.516 0 0095 61.343V33.375a9.516 9.516 0 00-9.516-9.516zM27 9h46v14.86H27zm-4.688 82l6.026-34.47h43.323L77.687 91zm62.153-53.07A3.535 3.535 0 1188 34.395a3.535 3.535 0 01-3.535 3.535z" />
</svg>
)
}
// PROPTYPES
const { string } = PropTypes
Print.propTypes = {
styling: string,
}
export default Print
|
src/js/key-demo-app.js | training4developers/react_redux_12122016 | /* @flow */
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap-loader';
import '../css/styles.scss';
type ItemListItemProps = {
item: string
};
type ItemListItemState = {
item: string
};
class ItemListItem extends React.PureComponent {
props: ItemListItemProps;
state: ItemListItemState;
static propTypes = {
item: React.PropTypes.string
};
constructor(props) {
super(props);
console.log('constructor: ', props.item);
this.state = {
item: props.item
};
}
render() {
return <li>{this.props.item} | {this.state.item}</li>;
}
}
type ItemListProps = {
items: string[]
};
type ItemListState = {
items: string[]
};
class ItemList extends React.PureComponent {
props: ItemListProps;
state: ItemListState;
constructor(props) {
super(props);
this.state = {
items: props.items.concat()
};
}
componentDidMount() {
setTimeout(() => {
console.log('timeout expired');
//this.state.items.shift();
this.setState({
items: this.state.items.slice(1)
//items: this.state.items
});
}, 3000);
}
render() {
return <ul>
{this.state.items.map(item => <ItemListItem key={item} item={item} />)}
</ul>;
}
}
ReactDOM.render(<ItemList items={['a','b','c','d']} />, document.querySelector('main'));
|
packages/react-scripts/fixtures/kitchensink/src/index.js | paweljedrzejczyk/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*/
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
|
app/javascript/mastodon/features/list_adder/components/list.js | ashfurrow/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import ImmutablePureComponent from 'react-immutable-pure-component';
import ImmutablePropTypes from 'react-immutable-proptypes';
import IconButton from '../../../components/icon_button';
import { defineMessages, injectIntl } from 'react-intl';
import { removeFromListAdder, addToListAdder } from '../../../actions/lists';
import Icon from 'mastodon/components/icon';
const messages = defineMessages({
remove: { id: 'lists.account.remove', defaultMessage: 'Remove from list' },
add: { id: 'lists.account.add', defaultMessage: 'Add to list' },
});
const MapStateToProps = (state, { listId, added }) => ({
list: state.get('lists').get(listId),
added: typeof added === 'undefined' ? state.getIn(['listAdder', 'lists', 'items']).includes(listId) : added,
});
const mapDispatchToProps = (dispatch, { listId }) => ({
onRemove: () => dispatch(removeFromListAdder(listId)),
onAdd: () => dispatch(addToListAdder(listId)),
});
export default @connect(MapStateToProps, mapDispatchToProps)
@injectIntl
class List extends ImmutablePureComponent {
static propTypes = {
list: ImmutablePropTypes.map.isRequired,
intl: PropTypes.object.isRequired,
onRemove: PropTypes.func.isRequired,
onAdd: PropTypes.func.isRequired,
added: PropTypes.bool,
};
static defaultProps = {
added: false,
};
render () {
const { list, intl, onRemove, onAdd, added } = this.props;
let button;
if (added) {
button = <IconButton icon='times' title={intl.formatMessage(messages.remove)} onClick={onRemove} />;
} else {
button = <IconButton icon='plus' title={intl.formatMessage(messages.add)} onClick={onAdd} />;
}
return (
<div className='list'>
<div className='list__wrapper'>
<div className='list__display-name'>
<Icon id='list-ul' className='column-link__icon' fixedWidth />
{list.get('title')}
</div>
<div className='account__relationship'>
{button}
</div>
</div>
</div>
);
}
}
|
src/components/ModalWrapper/ModalWrapper.js | carbon-design-system/carbon-components-react | /**
* Copyright IBM Corp. 2016, 2018
*
* This source code is licensed under the Apache-2.0 license found in the
* LICENSE file in the root directory of this source tree.
*/
import PropTypes from 'prop-types';
import React from 'react';
import Modal from '../Modal';
import Button from '../Button';
import { ButtonTypes } from '../../prop-types/types';
export default class ModalWrapper extends React.Component {
static propTypes = {
status: PropTypes.string,
handleOpen: PropTypes.func,
children: PropTypes.node,
id: PropTypes.string,
buttonTriggerText: PropTypes.node,
buttonTriggerClassName: PropTypes.string,
modalLabel: PropTypes.string,
modalHeading: PropTypes.string,
modalText: PropTypes.string,
passiveModal: PropTypes.bool,
withHeader: PropTypes.bool,
modalBeforeContent: PropTypes.bool,
primaryButtonText: PropTypes.string,
secondaryButtonText: PropTypes.string,
handleSubmit: PropTypes.func,
disabled: PropTypes.bool,
renderTriggerButtonIcon: PropTypes.oneOfType([
PropTypes.func,
PropTypes.object,
]),
triggerButtonIconDescription: PropTypes.string,
triggerButtonKind: ButtonTypes.buttonKind,
shouldCloseAfterSubmit: PropTypes.bool,
};
static defaultProps = {
primaryButtonText: 'Save',
secondaryButtonText: 'Cancel',
triggerButtonIconDescription: 'Provide icon description if icon is used',
triggerButtonKind: 'primary',
disabled: false,
selectorPrimaryFocus: '[data-modal-primary-focus]',
onKeyDown: () => {},
};
triggerButton = React.createRef();
state = {
isOpen: false,
};
handleOpen = () => {
this.setState({
isOpen: true,
});
};
handleClose = () => {
this.setState({ isOpen: false }, () => this.triggerButton.current.focus());
};
handleOnRequestSubmit = () => {
const { handleSubmit, shouldCloseAfterSubmit } = this.props;
if (handleSubmit()) {
if (shouldCloseAfterSubmit) {
this.handleClose();
}
}
};
render() {
const {
children,
onKeyDown,
buttonTriggerText,
buttonTriggerClassName,
renderTriggerButtonIcon,
triggerButtonIconDescription,
triggerButtonKind,
disabled,
handleSubmit, // eslint-disable-line no-unused-vars
shouldCloseAfterSubmit, // eslint-disable-line no-unused-vars
selectorPrimaryFocus,
...other
} = this.props;
const props = {
...other,
selectorPrimaryFocus,
open: this.state.isOpen,
onRequestClose: this.handleClose,
onRequestSubmit: this.handleOnRequestSubmit,
};
return (
<div
role="presentation"
onKeyDown={evt => {
if (evt.which === 27) {
this.handleClose();
onKeyDown(evt);
}
}}>
<Button
className={buttonTriggerClassName}
disabled={disabled}
kind={triggerButtonKind}
renderIcon={renderTriggerButtonIcon}
iconDescription={triggerButtonIconDescription}
onClick={this.handleOpen}
ref={this.triggerButton}>
{buttonTriggerText}
</Button>
<Modal {...props}>{children}</Modal>
</div>
);
}
}
|
docs/src/PropTable.js | Sipree/react-bootstrap | import _ from 'lodash-compat';
import React from 'react';
import Glyphicon from '../../src/Glyphicon';
import Label from '../../src/Label';
import Table from '../../src/Table';
let cleanDocletValue = str => str.trim().replace(/^\{/, '').replace(/\}$/, '');
let capitalize = str => str[0].toUpperCase() + str.substr(1);
function getPropsData(component, metadata) {
let componentData = metadata[component] || {};
let props = componentData.props || {};
if (componentData.composes) {
componentData.composes.forEach(other => {
if (other !== component) {
props = _.merge({}, getPropsData(other, metadata), props);
}
});
}
if (componentData.mixins) {
componentData.mixins.forEach( other => {
if (other !== component && componentData.composes.indexOf(other) === -1) {
props = _.merge({}, getPropsData(other, metadata), props);
}
});
}
return props;
}
const PropTable = React.createClass({
contextTypes: {
metadata: React.PropTypes.object
},
componentWillMount() {
this.propsData = getPropsData(this.props.component, this.context.metadata);
},
render() {
let propsData = this.propsData;
if (!Object.keys(propsData).length) {
return <div className="text-muted"><em>There are no public props for this component.</em></div>;
}
return (
<Table bordered striped className="prop-table">
<thead>
<tr>
<th>Name</th>
<th>Type</th>
<th>Default</th>
<th>Description</th>
</tr>
</thead>
<tbody>
{ this._renderRows(propsData) }
</tbody>
</Table>
);
},
_renderRows(propsData) {
return Object.keys(propsData)
.sort()
.filter(propName => propsData[propName].type && !propsData[propName].doclets.private )
.map(propName => {
let propData = propsData[propName];
return (
<tr key={propName} className="prop-table-row">
<td>
{propName} {this.renderRequiredLabel(propData)}
</td>
<td>
<div>{this.getType(propData)}</div>
</td>
<td>{propData.defaultValue}</td>
<td>
{ propData.doclets.deprecated
&& <div className="prop-desc-heading">
<strong className="text-danger">{'Deprecated: ' + propData.doclets.deprecated + ' '}</strong>
</div>
}
{ this.renderControllableNote(propData, propName) }
<div className="prop-desc" dangerouslySetInnerHTML={{__html: propData.descHtml }} />
</td>
</tr>
);
});
},
renderRequiredLabel(prop) {
if (!prop.required) {
return null;
}
return (
<Label>required</Label>
);
},
renderControllableNote(prop, propName) {
let controllable = prop.doclets.controllable;
let isHandler = this.getDisplayTypeName(prop.type.name) === 'function';
if (!controllable) {
return false;
}
let text = isHandler ? (
<span>
controls <code>{controllable}</code>
</span>
) : (
<span>
controlled by: <code>{controllable}</code>,
initial prop: <code>{'default' + capitalize(propName)}</code>
</span>
);
return (
<div className="prop-desc-heading">
<small>
<em className="text-info">
<Glyphicon glyph="info-sign"/>
{ text }
</em>
</small>
</div>
);
},
getType(prop) {
let type = prop.type || {};
let name = this.getDisplayTypeName(type.name);
let doclets = prop.doclets || {};
switch (name) {
case 'object':
return name;
case 'union':
return type.value.reduce((current, val, i, list) => {
let item = this.getType({ type: val });
if (React.isValidElement(item)) {
item = React.cloneElement(item, {key: i});
}
current = current.concat(item);
return i === (list.length - 1) ? current : current.concat(' | ');
}, []);
case 'array':
let child = this.getType({ type: type.value });
return <span>{'array<'}{ child }{'>'}</span>;
case 'enum':
return this.renderEnum(type);
case 'custom':
return cleanDocletValue(doclets.type || name);
default:
return name;
}
},
getDisplayTypeName(typeName) {
if (typeName === 'func') {
return 'function';
} else if (typeName === 'bool') {
return 'boolean';
}
return typeName;
},
renderEnum(enumType) {
const enumValues = enumType.value || [];
const renderedEnumValues = [];
enumValues.forEach(function renderEnumValue(enumValue, i) {
if (i > 0) {
renderedEnumValues.push(
<span key={`${i}c`}>, </span>
);
}
renderedEnumValues.push(
<code key={i}>{enumValue}</code>
);
});
return (
<span>one of: {renderedEnumValues}</span>
);
}
});
export default PropTable;
|
blueocean-material-icons/src/js/components/svg-icons/maps/local-grocery-store.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsLocalGroceryStore = (props) => (
<SvgIcon {...props}>
<path d="M7 18c-1.1 0-1.99.9-1.99 2S5.9 22 7 22s2-.9 2-2-.9-2-2-2zM1 2v2h2l3.6 7.59-1.35 2.45c-.16.28-.25.61-.25.96 0 1.1.9 2 2 2h12v-2H7.42c-.14 0-.25-.11-.25-.25l.03-.12.9-1.63h7.45c.75 0 1.41-.41 1.75-1.03l3.58-6.49c.08-.14.12-.31.12-.48 0-.55-.45-1-1-1H5.21l-.94-2H1zm16 16c-1.1 0-1.99.9-1.99 2s.89 2 1.99 2 2-.9 2-2-.9-2-2-2z"/>
</SvgIcon>
);
MapsLocalGroceryStore.displayName = 'MapsLocalGroceryStore';
MapsLocalGroceryStore.muiName = 'SvgIcon';
export default MapsLocalGroceryStore;
|
tests/react_native_tests/test_data/native_code/PickerDialog/app/components/Mobile/component.js | ibhubs/sketch-components | /**
* @flow
*/
import React from 'react'
import PropTypes from 'prop-types'
import { observer } from 'mobx-react/native'
import styles from './styles'
import Picker from '@rn/commons/app/components/Picker'
import styled from 'styled-components/native'
import { View } from 'react-native'
const Mobile = (props) => (
<MobileStyledView>
<Picker
labelKey={'name'}
options={[{'id':1,'name':'Revanth'},{'id':2,'name':'Sunny'},{'id':3,'name':'Anesh'},{'id':4,'name':'Vedavidh'},{'id':5,'name':'Lokesh'}]}
style={styles.menuStyle}
valueKey={'id'}
></Picker>
</MobileStyledView>
)
export const MobileStyledView = styled.View`
flex: 1;
`
export default observer(Mobile) |
src/svg-icons/action/invert-colors.js | ngbrown/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionInvertColors = (props) => (
<SvgIcon {...props}>
<path d="M17.66 7.93L12 2.27 6.34 7.93c-3.12 3.12-3.12 8.19 0 11.31C7.9 20.8 9.95 21.58 12 21.58c2.05 0 4.1-.78 5.66-2.34 3.12-3.12 3.12-8.19 0-11.31zM12 19.59c-1.6 0-3.11-.62-4.24-1.76C6.62 16.69 6 15.19 6 13.59s.62-3.11 1.76-4.24L12 5.1v14.49z"/>
</SvgIcon>
);
ActionInvertColors = pure(ActionInvertColors);
ActionInvertColors.displayName = 'ActionInvertColors';
ActionInvertColors.muiName = 'SvgIcon';
export default ActionInvertColors;
|
src/svg-icons/maps/tram.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsTram = (props) => (
<SvgIcon {...props}>
<path d="M19 16.94V8.5c0-2.79-2.61-3.4-6.01-3.49l.76-1.51H17V2H7v1.5h4.75l-.76 1.52C7.86 5.11 5 5.73 5 8.5v8.44c0 1.45 1.19 2.66 2.59 2.97L6 21.5v.5h2.23l2-2H14l2 2h2v-.5L16.5 20h-.08c1.69 0 2.58-1.37 2.58-3.06zm-7 1.56c-.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-4.5H7V9h10v5z"/>
</SvgIcon>
);
MapsTram = pure(MapsTram);
MapsTram.displayName = 'MapsTram';
MapsTram.muiName = 'SvgIcon';
export default MapsTram;
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.