path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/esm/components/form/field/components/radio-set.js | KissKissBankBank/kitten | import React from 'react';
import { RadioSet } from '../../../form/radio-set';
export var FieldRadioSet = function FieldRadioSet(props) {
return /*#__PURE__*/React.createElement("div", {
className: "k-u-margin-top-single"
}, /*#__PURE__*/React.createElement(RadioSet, props));
}; |
src/index.js | jessicamvs/blog | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import { createStore, applyMiddleware } from 'redux';
import { BrowserRouter, Route, Switch } from 'react-router-dom';
import promise from 'redux-promise';
import reducers from './reducers';
import PostsIndex from './components/posts-index';
import PostsNew from './components/posts-new';
import PostsShow from './components/posts-show';
const createStoreWithMiddleware = applyMiddleware(promise)(createStore);
ReactDOM.render(
<Provider store={createStoreWithMiddleware(reducers)}>
<BrowserRouter>
<div>
<Switch>
<Route path="/posts/new" component={PostsNew} />
<Route path="/posts/:id" component={PostsShow} />
<Route path="/" component={PostsIndex} />
</Switch>
</div>
</BrowserRouter>
</Provider>
, document.querySelector('.container')
);
|
wrappers/yaml.js | elliotec/LnL | import React from 'react'
import yaml from 'js-yaml'
import Helmet from 'react-helmet'
import { config } from 'config'
module.exports = React.createClass({
propTypes () {
return {
route: React.PropTypes.object,
}
},
render () {
const data = this.props.route.page.data
return (
<div>
<Helmet
title={`${config.siteTitle} | ${data.title}`}
/>
<h1>{data.title}</h1>
<p>Raw view of yaml file</p>
<pre dangerouslySetInnerHTML={{ __html: yaml.safeDump(data) }} />
</div>
)
},
})
|
js/jqwidgets/demos/react/app/chart/donutseries/app.js | luissancheza/sice | import React from 'react';
import ReactDOM from 'react-dom';
import JqxChart from '../../../jqwidgets-react/react_jqxchart.js';
class App extends React.Component {
render() {
let data_source_mobile =
{
datatype: 'csv',
datafields: [
{ name: 'Browser' },
{ name: 'Share' }
],
url: '../sampledata/mobile_browsers_share_dec2011.txt'
};
let dataAdapter_mobile = new $.jqx.dataAdapter(data_source_mobile, { async: false, autoBind: true, loadError: (xhr, status, error) => { alert('Error loading "' + data_source_mobile.url + '" : ' + error); } });
let data_source_desktop =
{
datatype: 'csv',
datafields: [
{ name: 'Browser' },
{ name: 'Share' }
],
url: '../sampledata/desktop_browsers_share_dec2011.txt'
};
let dataAdapter_desktop = new $.jqx.dataAdapter(data_source_desktop, { async: false, autoBind: true, loadError: (xhr, status, error) => { alert('Error loading "' + data_source_desktop.url + '" : ' + error); } });
let legendLayout = { left: 520, top: 170, width: 300, height: 200, flow: 'vertical' };
let padding = { left: 5, top: 5, right: 5, bottom: 5 };
let titlePadding = { left: 0, top: 0, right: 0, bottom: 10 };
let seriesGroups =
[
{
type: 'donut',
offsetX: 250,
source: dataAdapter_mobile,
xAxis:
{
formatSettings: { prefix: 'Mobile ' }
},
series:
[
{
dataField: 'Share',
displayText: 'Browser',
labelRadius: 120,
initialAngle: 10,
radius: 130,
innerRadius: 90,
centerOffset: 0,
formatSettings: { sufix: '%', decimalPlaces: 1 }
}
]
},
{
type: 'donut',
offsetX: 250,
source: dataAdapter_desktop,
colorScheme: 'scheme02',
xAxis:
{
formatSettings: { prefix: 'Desktop ' }
},
series:
[
{
dataField: 'Share',
displayText: 'Browser',
labelRadius: 120,
initialAngle: 10,
radius: 70,
innerRadius: 30,
centerOffset: 0,
formatSettings: { sufix: '%', decimalPlaces: 1 }
}
]
}
];
return (
<JqxChart style={{ width: 850, height: 500 }}
title={'Mobile & Desktop browsers share'} description={'(source: wikipedia.org)'}
showLegend={true} enableAnimations={true} padding={padding}
titlePadding={titlePadding} source={data_source_desktop} showBorderLine={true}
legendLayout={legendLayout} columnSeriesOverlap={false} seriesGroups={seriesGroups}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/device/wifi-lock.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceWifiLock = (props) => (
<SvgIcon {...props}>
<path d="M20.5 9.5c.28 0 .55.04.81.08L24 6c-3.34-2.51-7.5-4-12-4S3.34 3.49 0 6l12 16 3.5-4.67V14.5c0-2.76 2.24-5 5-5zM23 16v-1.5c0-1.38-1.12-2.5-2.5-2.5S18 13.12 18 14.5V16c-.55 0-1 .45-1 1v4c0 .55.45 1 1 1h5c.55 0 1-.45 1-1v-4c0-.55-.45-1-1-1zm-1 0h-3v-1.5c0-.83.67-1.5 1.5-1.5s1.5.67 1.5 1.5V16z"/>
</SvgIcon>
);
DeviceWifiLock = pure(DeviceWifiLock);
DeviceWifiLock.displayName = 'DeviceWifiLock';
DeviceWifiLock.muiName = 'SvgIcon';
export default DeviceWifiLock;
|
src/modules/connect/connectDetail/components/ConnectDetailImageBox.js | Florenz23/sangoo_04 |
import React, { Component } from 'react';
import { Container, Header, Title, Content, Button, Icon, List, ListItem, Text, Thumbnail, Left, Right, Body } from 'native-base';
import { View } from 'react-native'
import styles from '../../styles/imageBox';
import realm from '../../db_ini'
import { findInDb, findInDbTagText } from '../../../../db/db_helper'
const _getContact = (contactId) => {
const contacts = realm.objects('User')
const searchResult = contacts.filtered(`userId = "${contactId}"`)
const recent_contact = searchResult[0]
return recent_contact
}
const renderSurename = (contact) => {
const searchResult = contact.userData[0].personalData.filtered(`tagDescription = "Vorname"`)[0]
if (searchResult) {
return searchResult.tagText
}
}
const renderName = (contact) => {
const searchResult = contact.publicSharedData[0].personalData.filtered(`tagDescription = "Name"`)[0]
if (searchResult) {
return searchResult.tagText
}
}
//TODO hier das ...64 Bild aus der Datenbank auslesen, also kein require mehr
const renderData = (contactId) => {
const contact = _getContact(contactId)
console.log(contact.userData[0].personalData)
return (
<ListItem avatar style={{backgroundColor:'white'}}>
<Left>
<Thumbnail source={{uri: findInDbTagText(contact.userData[0].personalData,"tagDescription","Image")}} />
</Left>
<Body>
<Text>{renderSurename(contact)} {renderName(contact)}</Text>
</Body>
</ListItem>
)
}
const ConnectDetailImageBox = (props) => {
const {children} = props
return (
<View>
{renderData(children)}
</View>
)
}
export default ConnectDetailImageBox
|
src/client/story.js | Drooids/hacker-menu | import React from 'react'
export default class Story extends React.Component {
markAsRead () {
this.props.onMarkAsRead(this.props.story.id)
}
openUrl (url) {
this.props.onUrlClick(url)
}
handleYurlOnClick (e) {
e.preventDefault()
this.openUrl(this.props.story.yurl)
}
handleByOnClick (e) {
e.preventDefault()
this.openUrl(this.props.story.by_url)
}
handleUrlClick (e) {
e.preventDefault()
this.markAsRead()
this.openUrl(this.props.story.url)
}
render () {
var story = this.props.story
var storyState
if (story.hasRead) {
storyState = 'story read'
} else {
storyState = 'story'
}
return (
<div className={storyState}>
<span className='badge clickable' onClick={this.handleYurlOnClick.bind(this)}>{story.score}</span>
<div className='media-body'>
<span className='story-title clickable' onClick={this.handleUrlClick.bind(this)}>{story.title}</span>
<span className='story-host'>{story.host}</span>
<p className='story-poster'>
<span className='icon-comment clickable' onClick={this.handleYurlOnClick.bind(this)}>
{story.descendants}
</span> –
<span className='clickable' onClick={this.handleByOnClick.bind(this)}>
{story.by}
</span> –
<span className='clickable' onClick={this.handleYurlOnClick.bind(this)}>
{story.timeAgo}
</span>
</p>
</div>
</div>
)
}
}
Story.propTypes = {
onUrlClick: React.PropTypes.func.isRequired,
onMarkAsRead: React.PropTypes.func.isRequired,
story: React.PropTypes.object.isRequired
}
|
src/svg-icons/content/gesture.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ContentGesture = (props) => (
<SvgIcon {...props}>
<path d="M4.59 6.89c.7-.71 1.4-1.35 1.71-1.22.5.2 0 1.03-.3 1.52-.25.42-2.86 3.89-2.86 6.31 0 1.28.48 2.34 1.34 2.98.75.56 1.74.73 2.64.46 1.07-.31 1.95-1.4 3.06-2.77 1.21-1.49 2.83-3.44 4.08-3.44 1.63 0 1.65 1.01 1.76 1.79-3.78.64-5.38 3.67-5.38 5.37 0 1.7 1.44 3.09 3.21 3.09 1.63 0 4.29-1.33 4.69-6.1H21v-2.5h-2.47c-.15-1.65-1.09-4.2-4.03-4.2-2.25 0-4.18 1.91-4.94 2.84-.58.73-2.06 2.48-2.29 2.72-.25.3-.68.84-1.11.84-.45 0-.72-.83-.36-1.92.35-1.09 1.4-2.86 1.85-3.52.78-1.14 1.3-1.92 1.3-3.28C8.95 3.69 7.31 3 6.44 3 5.12 3 3.97 4 3.72 4.25c-.36.36-.66.66-.88.93l1.75 1.71zm9.29 11.66c-.31 0-.74-.26-.74-.72 0-.6.73-2.2 2.87-2.76-.3 2.69-1.43 3.48-2.13 3.48z"/>
</SvgIcon>
);
ContentGesture = pure(ContentGesture);
ContentGesture.displayName = 'ContentGesture';
ContentGesture.muiName = 'SvgIcon';
export default ContentGesture;
|
app/views/components/item-column/no-search-results.js | jeffreymoya/sprintly-kanban | import React from 'react';
import FilterActions from '../../../actions/filter-actions';
import ProductStore from '../../../stores/product-store';
var NoSearchResults = React.createClass({
propsTypes: {
product: React.PropTypes.object.isRequired
},
clearFilters() {
let product = ProductStore.getProduct(this.props.product.id);
FilterActions.clear(product.members, product.tags);
},
render() {
return (
<div className='no-search-results'>
<div className="content">
<div className="row">
<div className="col-sm-12">
<h1>No Results!</h1>
<h5>Try filtering again or reset your filters.</h5>
</div>
<div className="item-card__title col-sm-12">
<button style={ {width: "100%"} } className="btn btn-primary clear-filters" onClick={this.clearFilters}>Clear Filters</button>
</div>
</div>
</div>
</div>
)
}
})
module.exports = NoSearchResults;
|
client/scripts/components/config/questionnaire-config/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import React from 'react';
import {DragDropContext} from 'react-dnd';
import HTML5Backend from 'react-dnd-html5-backend';
import NewQuestion from '../new-question';
import Question from '../question';
import NewQuestionButton from '../new-question-button';
import {QUESTION_TYPE, QUESTIONNAIRE_TYPE} from '../../../../../coi-constants';
import PanelWithButtons from '../panel-with-buttons';
import ConfigActions from '../../../actions/config-actions';
import AddSection from '../../add-section';
class QuestionnaireConfig extends React.Component {
constructor() {
super();
this.questionMoved = this.questionMoved.bind(this);
this.subQuestionMoved = this.subQuestionMoved.bind(this);
this.makeMainQuestion = this.makeMainQuestion.bind(this);
this.makeSubQuestion = this.makeSubQuestion.bind(this);
this.subQuestionMovedToParent = this.subQuestionMovedToParent.bind(this);
this.newQuestionStarted = this.newQuestionStarted.bind(this);
this.addNewQuestion = this.addNewQuestion.bind(this);
this.newQuestionCancelled = this.newQuestionCancelled.bind(this);
this.heightChanged = this.heightChanged.bind(this);
this.updateHeights = this.updateHeights.bind(this);
this.state = {
questionHeights: {}
};
}
componentDidMount() {
this.updateHeights();
}
componentDidUpdate() {
this.updateHeights();
}
updateHeights() {
let questionDomElements = document.querySelectorAll('.qstn');
if (questionDomElements.length <= 0) {
return;
}
questionDomElements = Array.from(questionDomElements);
const questionHeights = this.state.questionHeights;
let shouldRefresh = false;
questionDomElements.forEach(question => {
if (!question.id) {
return;
}
const questionId = question.id.replace('qstn', '');
if (question.clientHeight !== questionHeights[questionId]) {
questionHeights[questionId] = question.clientHeight;
shouldRefresh = true;
}
});
if (shouldRefresh) {
this.setState({ questionHeights });
}
}
subQuestionMoved(draggedQuestionId, targetId) {
const draggedQuestion = this.findQuestion(draggedQuestionId);
const targetQuestion = this.findQuestion(targetId);
const parentOfDraggedQuestion = this.findParentOfSubQuestion(draggedQuestionId);
const parentOfTargetQuestion = this.findParentOfSubQuestion(targetId);
if (
this.isMoving ||
draggedQuestion === targetQuestion ||
!parentOfDraggedQuestion ||
!parentOfTargetQuestion
) {
return;
}
if (parentOfDraggedQuestion === parentOfTargetQuestion) {
const swapValue = draggedQuestion.question.order;
draggedQuestion.question.order = targetQuestion.question.order;
targetQuestion.question.order = swapValue;
}
else {
this.subQuestionMovedToParent(draggedQuestionId, parentOfTargetQuestion.id);
}
this.setIsMovingFlag();
ConfigActions.updateQuestions(this.props.questionnaireCategory, this.props.questions);
}
subQuestionMovedToParent(draggedQuestionId, targetId) {
const draggedQuestion = this.findQuestion(draggedQuestionId);
if (!draggedQuestion || this.isMoving || draggedQuestion.parent === targetId) {
return;
}
const parent = this.findQuestion(targetId);
if (parent.question.type !== QUESTION_TYPE.YESNO) {
return;
}
draggedQuestion.parent = targetId;
const otherSubquestions = this.findSubQuestions(targetId);
if (otherSubquestions.length > 0) {
draggedQuestion.question.order = 1 + otherSubquestions.reduce((previousValue, subQuestion) => {
return Math.max(previousValue, subQuestion.question.order);
}, 1);
}
else {
draggedQuestion.question.order = 1;
}
this.setIsMovingFlag();
ConfigActions.updateQuestions(this.props.questionnaireCategory, this.props.questions);
}
setIsMovingFlag() {
this.isMoving = true;
setTimeout(() => {
delete this.isMoving;
}, 200);
}
questionMoved(draggedQuestionId, targetId) {
const draggedQuestion = this.findQuestion(draggedQuestionId);
const targetQuestion = this.findQuestion(targetId);
if (this.isMoving || draggedQuestion === targetQuestion || targetQuestion.parent) {
return;
}
this.setIsMovingFlag();
const swapValue = draggedQuestion.question.order;
draggedQuestion.question.order = targetQuestion.question.order;
targetQuestion.question.order = swapValue;
ConfigActions.updateQuestions(this.props.questionnaireCategory, this.props.questions);
}
findNewParentQuestion(question) {
return this.props.questions.find(toTest => {
return !toTest.parent && toTest.question.order === question.question.order - 1;
});
}
makeSubQuestion(id) {
const question = this.findQuestion(id);
if (!question || question.parent) {
return;
}
const subQuestions = this.findSubQuestions(id);
if (subQuestions.length > 0) {
return;
}
// Find closest previous main question
const parent = this.findNewParentQuestion(question);
if (parent) {
// Can only be a sub question if the parent is a yes/no question
if (parent.question.type !== QUESTION_TYPE.YESNO) {
return;
}
this.props.questions.filter(toTest => {
return !toTest.parent && toTest.question.order > question.question.order;
}).forEach(toBumpUp => {
toBumpUp.question.order -= 1;
});
// set new order value on the question
const otherSubquestions = this.findSubQuestions(parent.id);
if (otherSubquestions.length > 0) {
question.question.order = 1 + otherSubquestions.reduce((previousValue, subQuestion) => {
return Math.max(previousValue, subQuestion.question.order);
}, 1);
} else {
question.question.order = 1;
}
question.parent = parent.id;
question.question.displayCriteria = 'Yes';
ConfigActions.updateQuestions(this.props.questionnaireCategory, this.props.questions);
setTimeout(this.updateHeights, 200);
}
}
findQuestion(id) {
return this.props.questions.find(questionToTest => {
return questionToTest.id === id;
});
}
findParentOfSubQuestion(subQuestionId) {
const question = this.findQuestion(subQuestionId);
if (question.parent) {
return this.findQuestion(question.parent);
}
}
makeMainQuestion(subQuestionId) {
const question = this.findQuestion(subQuestionId);
const parent = this.findQuestion(question.parent);
if (question && parent) {
question.parent = null;
this.props.questions.filter(toTest => {
return !toTest.parent && toTest.question.order > parent.question.order;
}).forEach(toBump => {
toBump.question.order += 1;
});
question.question.order = parent.question.order + 1;
ConfigActions.updateQuestions(this.props.questionnaireCategory, this.props.questions);
setTimeout(this.updateHeights, 200);
}
}
findQuestionHeight(question) {
if (this.state.questionHeights[question.id] !== undefined) {
return this.state.questionHeights[question.id] + 24;
}
const initHeightOfAQuestion = 139;
const initHeightOfExpandedQuestion = 285;
const initHeightOfExpandedMultiSelect = 390;
if (this.isOpen(question.id)) {
const editState = this.props.questionsBeingEdited[question.id];
if (editState.question.type === QUESTION_TYPE.MULTISELECT) {
return initHeightOfExpandedMultiSelect;
}
return initHeightOfExpandedQuestion;
}
return initHeightOfAQuestion;
}
isOpen(id) {
return this.props.questionsBeingEdited[id] !== undefined;
}
findSubQuestions(parentId) {
return this.props.questions.filter(question => {
return question.parent === parentId;
});
}
canBeSubQuestion(question) {
if (question.parent) {
return false;
}
const potentialParent = this.findNewParentQuestion(question);
if (!potentialParent || potentialParent.question.type !== QUESTION_TYPE.YESNO) {
return false;
}
return true;
}
newQuestionCancelled() {
ConfigActions.cancelNewQuestion(this.props.questionnaireCategory);
}
addNewQuestion() {
ConfigActions.saveNewQuestion(this.props.questionnaireCategory);
}
newQuestionStarted() {
ConfigActions.startNewQuestion(this.props.questionnaireCategory);
}
heightChanged(questionId) {
const domElement = document.querySelector(`#qstn${questionId}`);
const questionHeights = this.state.questionHeights;
questionHeights[questionId] = domElement.clientHeight;
this.setState({ questionHeights });
}
render() {
const newQuestionButtons = [
{
label: '+ Add',
onClick: this.addNewQuestion
},
{
label: 'Cancel',
onClick: this.newQuestionCancelled
}
];
let newQuestion;
let newQuestionSection;
let nextQuestionYPosition = 0;
const questionsJSX = [];
if (this.props.newQuestion) {
newQuestion = (
<PanelWithButtons title="Questionnaire" buttons={newQuestionButtons}>
<NewQuestion
question={this.props.newQuestion}
questionnaireCategory={this.props.questionnaireCategory}
/>
</PanelWithButtons>
);
}
else {
let message;
if (this.props.questionnaireCategory === QUESTIONNAIRE_TYPE.SCREENING) {
message = 'Only parent-level, Yes/No questions can be used in screening questionnaire validations as configured in Screening Validations in General Configuration.'; //eslint-disable-line max-len
}
newQuestionSection = (
<AddSection
level="Warning"
button={<NewQuestionButton onClick={this.newQuestionStarted} />}
message={message}
/>
);
}
let currentQuestionNumber = 0;
Array
.from(this.props.questions)
.filter(question => {
return !question.parent;
})
.sort((a, b) => {
if (a.question.order < b.question.order) { return -1; }
else if (a.question.order === b.question.order) { return 0; }
return 1;
})
.forEach(question => {
question.question.top = nextQuestionYPosition;
nextQuestionYPosition += this.findQuestionHeight(question);
currentQuestionNumber++;
question.question.numberToShow = currentQuestionNumber;
let currentSubQuestionNumber = 0;
this
.findSubQuestions(question.id).sort((a, b) => {
return a.question.order - b.question.order;
})
.forEach(subQuestion => {
subQuestion.question.top = nextQuestionYPosition;
nextQuestionYPosition += this.findQuestionHeight(subQuestion);
currentSubQuestionNumber++;
subQuestion.question.numberToShow = `${currentQuestionNumber} - ${(String.fromCharCode(64 + currentSubQuestionNumber))}`;
});
});
this.props.questions.filter(question => {
return !question.parent;
}).forEach((question, index) => {
const canBeSubQuestion = index > 0 && this.canBeSubQuestion(question);
const questionStyle = {
cursor: canBeSubQuestion ? 'move' : 'ns-resize'
};
questionsJSX.push(
<Question
questionnaireCategory={this.props.questionnaireCategory}
editState={this.props.questionsBeingEdited[question.id]}
questionMoved={this.questionMoved}
makeSubQuestion={this.props.disableSubQuestions ? () => {} : this.makeSubQuestion}
makeMainQuestion={this.makeMainQuestion}
subQuestionMoved={this.props.disableSubQuestions ? () => {} : this.subQuestionMoved}
subQuestionMovedToParent={this.props.disableSubQuestions ? () => {} : this.subQuestionMovedToParent}
number={question.question.numberToShow}
key={question.id}
id={question.id}
text={question.question.text}
isSubQuestion={false}
top={question.question.top}
style={questionStyle}
heightChanged={this.heightChanged}
/>
);
this.findSubQuestions(question.id).forEach(subQuestion => {
questionsJSX.push(
<Question
questionnaireCategory={this.props.questionnaireCategory}
editState={this.props.questionsBeingEdited[subQuestion.id]}
questionMoved={this.questionMoved}
makeSubQuestion={this.props.disableSubQuestions ? () => {} : this.makeSubQuestion}
makeMainQuestion={this.makeMainQuestion}
subQuestionMoved={this.props.disableSubQuestions ? () => {} : this.subQuestionMoved}
subQuestionMovedToParent={this.props.disableSubQuestions ? () => {} : this.subQuestionMovedToParent}
number={subQuestion.question.numberToShow}
key={subQuestion.id}
id={subQuestion.id}
text={subQuestion.question.text}
isSubQuestion={true}
top={subQuestion.question.top}
style={{cursor: 'move'}}
displayCriteria={subQuestion.question.displayCriteria}
heightChanged={this.heightChanged}
/>
);
});
});
return (
<div className={this.props.className}>
{newQuestionSection}
{newQuestion}
<div style={{position: 'relative', marginTop: 16, minHeight: nextQuestionYPosition}}>
{questionsJSX}
</div>
</div>
);
}
}
QuestionnaireConfig.defaultProps = {
questions: []
};
export default DragDropContext(HTML5Backend)(QuestionnaireConfig); //eslint-disable-line new-cap
|
src/main/resources/assets/javascripts/app.js | AdRoll/airpal | /**
* App Bootstrap
*/
import 'es6-shim';
import 'whatwg-fetch';
import AirpalApp from './components/AirpalApp.jsx';
import React from 'react';
// Start the main app
React.render(
<AirpalApp />,
document.querySelector('.js-react-app')
);
|
client/showDevTools.js | auth0-extensions/auth0-user-invite-extension | import React from 'react';
import { render } from 'react-dom';
import DevTools from './containers/DevTools';
module.exports = (store) => {
const popup = window.open(null, 'Redux DevTools', 'menubar=no,location=no,resizable=yes,scrollbars=no,status=no');
popup.location.reload();
setTimeout(() => {
popup.document.write('<div id="react-devtools-root"></div>');
render(
<DevTools store={store} />,
popup.document.getElementById('react-devtools-root')
);
}, 10);
};
|
tilapp/src/containers/Scenes/Book/Index/index.js | tilap/tilapp | import React, { Component } from 'react';
import { connect } from 'react-redux';
import PropTypes from 'prop-types';
import { Alert } from 'react-native';
import { View, Container, Content } from 'native-base';
import merge from 'deep-assign';
import BookSheet from '~/components/BookSheet/';
import FooterAction from '~/components/FooterAction';
import styles from './styles';
class BookScene extends Component {
renderFooterAction() {
const { navigation, isLoggedIn } = this.props;
const { bookScreenType = '' } = navigation.state.params;
if (bookScreenType === 'sell') {
if (isLoggedIn) {
return (
<FooterAction
text="Sell this book"
onPress={() => navigation.navigate('BookSell')}
/>
);
} else {
return (
<FooterAction
text="Sell this book"
onPress={() => Alert.alert(
'',
'To sell this book you need to be logged in.',
[
{text: 'Log in', onPress: () => navigation.navigate('Auth', { screen: 'register' })},
{text: 'Create an account', onPress: () => navigation.navigate('Auth', { screen: 'register' })},
{text: 'Later maybe', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
],
)}
/>
);
}
}
return null;
}
render() {
const { book } = this.props;
return (
<Container>
<Content>
<View style={styles.wrapper}>
<BookSheet {...book} />
</View>
</Content>
{ this.renderFooterAction() }
</Container>
);
}
}
BookScene.propTypes = {
navigation: PropTypes.any.isRequired,
book: PropTypes.object.isRequired,
isLoggedIn: PropTypes.bool.isRequired,
};
BookScene.navigationOptions = (props) => merge({}, (props.navigationOptions || {}), {
title: 'Book',
});
const mapStateToProps = ({ services: { book, account: { isLoggedIn } } }) => {
return { book, isLoggedIn };
};
export default connect(mapStateToProps)(BookScene);
|
react-dev/containers/header.js | DeryLiu/DeryLiu.github.io | import React, { Component } from 'react';
import classnames from 'classnames';
import { connect } from 'react-redux';
import AppBar from 'material-ui/AppBar';
import { fetchSiteInfo } from '../actions/index';
import Menu from '../components/menu';
import { RightBar } from '../components/right_menu_bar';
class Header extends Component {
constructor(props) {
super(props);
this.state = { open: false, width: 1200, height: null };
}
//push out menu for static post content
toggleStaticPostContent = () => {
const staticContent = document.getElementById('single-post-content');
if (staticContent) {
staticContent.classList.toggle('expanded');
}
}
// items for the menu, add or remove depending on your routes
handleToggle = () => {
this.setState({ open: !this.state.open });
this.toggleStaticPostContent();
};
hideMenuButton = () => {
if (this.state.open) {
return false;
}
return true;
}
render() {
return (
<div>
<AppBar
className='app-bar'
onLeftIconButtonTouchTap={this.handleToggle}
showMenuIconButton={this.hideMenuButton()}
iconElementRight={
<RightBar config={this.props.config} handleThemeSwitch={this.props.handleThemeSwitch} />}
/>
<Menu open={this.state.open} handleToggle={this.handleToggle} config={this.props.config} location={this.props.location} />
{<div className={classnames('app-content', { expanded: this.state.open })}> { this.props.children } </div>}
</div>
);
}
}
function mapStateToProps(state) {
return { config: state.siteInfo.all };
}
export default connect(mapStateToProps, { fetchSiteInfo })(Header);
|
src/routes/admin/index.js | MxMcG/tourlookup-react | /**
* 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 Admin from './Admin';
const title = 'Admin Page';
const isAdmin = false;
function action() {
if (!isAdmin) {
return { redirect: '/login' };
}
return {
chunks: ['admin'],
title,
component: (
<Layout>
<Admin title={title} />
</Layout>
),
};
}
export default action;
|
frontend/src/Routes.js | cthit/singIT | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import Start from './components/start';
import App from './App';
const routes = (
<Route path="/" component={App}>
<IndexRoute component={Start}/>
</Route>
);
export default routes; |
packages/material-ui-icons/src/FastRewind.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let FastRewind = props =>
<SvgIcon {...props}>
<path d="M11 18V6l-8.5 6 8.5 6zm.5-6l8.5 6V6l-8.5 6z" />
</SvgIcon>;
FastRewind = pure(FastRewind);
FastRewind.muiName = 'SvgIcon';
export default FastRewind;
|
examples/counter/containers/CounterApp.js | witer5/redux | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'redux/react';
import Counter from '../components/Counter';
import * as CounterActions from '../actions/CounterActions';
@connect(state => ({
counter: state.counter
}))
export default class CounterApp extends Component {
render() {
const { counter, dispatch } = this.props;
return (
<Counter counter={counter}
{...bindActionCreators(CounterActions, dispatch)} />
);
}
}
|
boxroom/archive/backup-js-glow-2018-01-28/boxroom/archive/js-surface-2018-01-27/src/main/js-surface-react-native.js | mcjazzyfunky/js-surface | import adaptReactifiedDefineComponent from './adaption/adaptReactifiedDefineComponent';
import Config from './config/Config';
import ElementInspector from './helper/ElementInspector';
import React from 'react';
import ReactNative from 'react-native';
const
defineComponent = adaptReactifiedDefineComponent({
createElement: React.createElement,
ComponentClass: React.Component
}),
createElement = (...args) => {
const type = args[0];
if (type && type.isComponentFactory) {
args[0] = type.type;
}
return React.createElement.apply(null, args);
},
isElement = React.isValidElement,
mount = ComponentClass => {
ReactNative.AppRegistry.registerComponent(
'AppMainComponent', () => ComponentClass);
},
Adapter = Object.freeze({
name: 'react',
api: { React, ReactNative }
}),
inspectElement = obj => {
let ret = null;
if (React.isElement(obj)) {
ret = new ElementInspector(obj.type, obj.props);
}
return ret;
};
export {
createElement,
defineComponent,
inspectElement,
isElement,
mount,
Adapter,
Config
};
|
src/Portal.js | glortho/react-overlays | import React from 'react';
import mountable from 'react-prop-types/lib/mountable';
import ownerDocument from './utils/ownerDocument';
import getContainer from './utils/getContainer';
/**
* The `<Portal/>` component renders its children into a new "subtree" outside of current component hierarchy.
* You can think of it as a declarative `appendChild()`, or jQuery's `$.fn.appendTo()`.
* The children of `<Portal/>` component will be appended to the `container` specified.
*/
let Portal = React.createClass({
displayName: 'Portal',
propTypes: {
/**
* A Node, Component instance, or function that returns either. The `container` will have the Portal children
* appended to it.
*/
container: React.PropTypes.oneOfType([
mountable,
React.PropTypes.func
])
},
componentDidMount() {
this._renderOverlay();
},
componentDidUpdate() {
this._renderOverlay();
},
componentWillUnmount() {
this._unrenderOverlay();
this._unmountOverlayTarget();
},
_mountOverlayTarget() {
if (!this._overlayTarget) {
this._overlayTarget = document.createElement('div');
this.getContainerDOMNode()
.appendChild(this._overlayTarget);
}
},
_unmountOverlayTarget() {
if (this._overlayTarget) {
this.getContainerDOMNode()
.removeChild(this._overlayTarget);
this._overlayTarget = null;
}
},
_renderOverlay() {
let overlay = !this.props.children
? null
: React.Children.only(this.props.children);
// Save reference for future access.
if (overlay !== null) {
this._mountOverlayTarget();
this._overlayInstance = React.render(overlay, this._overlayTarget);
} else {
// Unrender if the component is null for transitions to null
this._unrenderOverlay();
this._unmountOverlayTarget();
}
},
_unrenderOverlay() {
if (this._overlayTarget) {
React.unmountComponentAtNode(this._overlayTarget);
this._overlayInstance = null;
}
},
render() {
return null;
},
getMountNode(){
return this._overlayTarget;
},
getOverlayDOMNode() {
if (!this.isMounted()) {
throw new Error('getOverlayDOMNode(): A component must be mounted to have a DOM node.');
}
if (this._overlayInstance) {
if (this._overlayInstance.getWrappedDOMNode) {
return this._overlayInstance.getWrappedDOMNode();
} else {
return React.findDOMNode(this._overlayInstance);
}
}
return null;
},
getContainerDOMNode() {
return getContainer(this.props.container, ownerDocument(this).body);
}
});
export default Portal;
|
src/tabsets/TabsetsListItem.js | dash-/netjumpio-tabs-web | ///
// Dependencies
///
import React, { Component } from 'react';
import * as types from './types';
import CardsListItem from '../elements/CardsListItem';
import ButtonsList from '../elements/ButtonsList';
import ButtonsListMenu from '../elements/ButtonsListMenu';
import ButtonsListMenuItem from '../elements/ButtonsListMenuItem';
import TabSetsLogo from '../elements/TabSetsLogo';
import * as actions from './actions';
///
// View
///
class TabsetsListItemView extends Component {
processItem(item) {
return item.set('href', '/app/tabsets/' + this.props.item.get('id'));
}
render() {
const defaultLogoIcon = (
<TabSetsLogo />
);
return (
<CardsListItem
item={this.processItem(this.props.item)}
defaultLogoIcon={defaultLogoIcon}
width="2x"
horizontal
>
<ButtonsList>
<ButtonsListMenu id="tabsetsItemMenu">
<ButtonsListMenuItem
icon="pencil"
title="Edit"
action={actions.editItemPrompt(this.props.item.toJS())}
/>
<ButtonsListMenuItem
icon="times"
title="Delete"
action={actions.removeItemStart(this.props.item.toJS())}
/>
</ButtonsListMenu>
</ButtonsList>
</CardsListItem>
);
}
}
TabsetsListItemView.propTypes = {
item: types.ListItem.isRequired,
};
export default TabsetsListItemView;
|
server/priv/js/components/Duration.react.js | alinpopa/mzbench | import React from 'react';
import moment from 'moment';
class Duration extends React.Component {
constructor(props) {
super(props);
this.state = { duration: this._calculate(props.bench), timeout: undefined };
}
componentDidMount() {
this._createTimer(this.props.bench);
}
componentWillUnmount() {
this._clearTimer();
}
componentWillReceiveProps(props) {
this._clearTimer();
this._createTimer(props.bench);
}
_clearTimer() {
if (undefined != this.state.timeout) {
clearTimeout(this.state.timeout);
}
}
_createTimer(bench) {
let timeout = bench.isRunning() ? setTimeout(() => this._createTimer(bench), 1000) : undefined;
this.setState({ duration: this._calculate(bench), timeout: timeout });
}
_calculate(bench) {
let startTime = moment(bench.start_time);
let lastActiveTime = bench.isRunning() ? moment() : moment(bench.finish_time);
return lastActiveTime.diff(startTime);
}
renderChildren() {
return React.Children.map(this.props.children, (child) => {
return React.cloneElement(child, { duration: this.state.duration });
});
}
render() {
return (<div>{this.renderChildren()}</div>);
}
};
Duration.propTypes = {
bench: React.PropTypes.object.isRequired
};
export default Duration;
|
src/views/pages/Errors/NotFound/index.js | munza/react-reducks-starter | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { routeTo } from '../../../../utils';
import './styles.css';
class NotFoundPage extends Component {
render() {
return (
<div className="error">
<div className="error-header">
<h1>404 Not Found</h1>
</div>
<div className="error-intro">
URL path <strong><code>{this.props.location.pathname}</code></strong> does not exists!
</div>
<br/>
<Link to={routeTo('home')}>Go to Homepage</Link>
</div>
);
}
}
export default NotFoundPage;
|
app/Resources/reactcory/src/components/App.js | zlatko58/symfony-react | /* eslint-disable import/no-named-as-default */
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {connect} from 'react-redux';
import {bindActionCreators} from 'redux';
import * as actions from '../actions/contactsActions';
import MuiThemeProvider from "material-ui/styles/MuiThemeProvider";
import injectTapEventPlugin from "react-tap-event-plugin";
import '../styles/App.css';
import Form from "./Form";
import Table from "./Table";
injectTapEventPlugin();
class App extends Component {
constructor(props, context) {
super(props, context);
this.state = {
data: []
};
}
render() {
return (
<MuiThemeProvider>
<div className="App">
<Form
saveContacts={this.props.actions.saveContact}
onSubmit={submission =>
this.setState({
data: [...this.state.data, submission]
})}
/>
<br />
<br />
<Table
data={this.state.data}
header={[
{
name: "Name",
prop: "name"
},
{
name: "Email",
prop: "email"
},
{
name: "Message",
prop: "message"
}
]}
/>
</div>
</MuiThemeProvider>
);
}
}
App.propTypes = {
actions: PropTypes.object.isRequired,
contacts: PropTypes.object.isRequired
};
function mapStateToProps(state) {
return {
contacts: state.contacts
};
}
function mapDispatchToProps(dispatch) {
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(
mapStateToProps,
mapDispatchToProps
)(App);
|
egghead.io/create-react-app/src/Lifecycle.js | andrisazens/learning_react | import React, { Component } from 'react';
import ReactDom from 'react-dom';
class App extends Component {
constructor() {
super();
this.state = { val: 0 }
this.update = this.update.bind(this)
}
update() {
this.setState({ val: this.state.val + 1 });
}
componentWillMount() {
console.log("componentWillMount");
this.setState({m:2});
}
render() {
console.log("render");
return <button onClick={this.update}>{ this.state.val * this.state.m }</button>
}
componentDidMount() {
console.log("componentDidMount");
//console.log(ReactDom.findDOMNode(this));
this.inc = setInterval(this.update, 500);
}
componentWillUnmount() {
console.log("componentWillUnmount");
clearInterval(this.inc);
}
}
class Wrapper extends Component {
mount() {
ReactDom.render(<App/>, document.getElementById("a"))
}
unmount() {
ReactDom.unmountComponentAtNode(document.getElementById("a"))
}
render() {
return (
<div>
<button onClick={this.mount.bind(this) }>Mount</button>
<button onClick={this.unmount.bind(this) }>Unmount</button>
<div id="a"></div>
</div>
)
}
}
export default Wrapper;
|
src/index.js | CCSF-Coders/CampusConnect | import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/App';
const root = document.getElementById('root');
ReactDOM.render(
<App />,
root
);
if (module.hot) {
module.hot.accept('./components/App', () => {
const NextApp = require('./components/App').default
ReactDOM.render(
<NextApp />,
root
)
})
}
|
examples/huge-apps/routes/Course/components/Nav.js | chunwei/react-router | import React from 'react';
import { Link } from 'react-router';
import AnnouncementsRoute from '../routes/Announcements';
import AssignmentsRoute from '../routes/Assignments';
import GradesRoute from '../routes/Grades';
const styles = {};
styles.nav = {
borderBottom: '1px solid #aaa'
};
styles.link = {
display: 'inline-block',
padding: 10,
textDecoration: 'none',
};
styles.activeLink = Object.assign({}, styles.link, {
//color: 'red'
});
class Nav extends React.Component {
render () {
var { course } = this.props;
var pages = [
['announcements', 'Announcements'],
['assignments', 'Assignments'],
['grades', 'Grades'],
];
return (
<nav style={styles.nav}>
{pages.map((page, index) => (
<Link
key={page[0]}
activeStyle={index === 0 ?
Object.assign({}, styles.activeLink, { paddingLeft: 0 }) :
styles.activeLink}
style={index === 0 ?
Object.assign({}, styles.link, { paddingLeft: 0 }) :
styles.link }
to={`/course/${course.id}/${page[0]}`}
>{page[1]}</Link>
))}
</nav>
);
}
}
export default Nav;
|
components/DoneButton.ios.js | FuYaoDe/react-native-app-intro | import React from 'react'
import {
Text,
View,
TouchableOpacity,
Animated
} from 'react-native';
export const DoneButton = ({
styles, onDoneBtnClick, onNextBtnClick,
rightTextColor, isDoneBtnShow,
doneBtnLabel, nextBtnLabel,
doneFadeOpacity, skipFadeOpacity, nextOpacity
}) => {
return (
<View style={styles.btnContainer}>
<Animated.View style={[styles.full, { height: 0 }, {
opacity: doneFadeOpacity,
transform: [{
translateX: skipFadeOpacity.interpolate({
inputRange: [0, 1],
outputRange: [0, 20],
}),
}],
}]}
>
<View style={styles.full}>
<Text style={[styles.controllText, {
color: rightTextColor, paddingRight: 30,
}]}>
{doneBtnLabel}
</Text>
</View>
</Animated.View>
<Animated.View style={[styles.full, { height: 0 }, { opacity: nextOpacity }]}>
<TouchableOpacity style={styles.full}
onPress={ isDoneBtnShow ? onDoneBtnClick : onNextBtnClick}>
<Text style={[styles.nextButtonText, { color: rightTextColor }]}>
{nextBtnLabel}
</Text>
</TouchableOpacity>
</Animated.View>
</View>
)
}
export default DoneButton
|
docs/src/app/components/pages/components/SvgIcon/ExampleSimple.js | pomerantsev/material-ui | import React from 'react';
import {blue500, red500, greenA200} from 'material-ui/styles/colors';
import SvgIcon from 'material-ui/SvgIcon';
const iconStyles = {
marginRight: 24,
};
const HomeIcon = (props) => (
<SvgIcon {...props}>
<path d="M10 20v-6h4v6h5v-8h3L12 3 2 12h3v8z" />
</SvgIcon>
);
const SvgIconExampleSimple = () => (
<div>
<HomeIcon style={iconStyles} />
<HomeIcon style={iconStyles} color={blue500} />
<HomeIcon style={iconStyles} color={red500} hoverColor={greenA200} />
</div>
);
export default SvgIconExampleSimple;
|
docs/src/sections/BadgeSection.js | Terminux/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function BadgeSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="badges">Badges</Anchor> <small>Badge</small>
</h2>
<p>Easily highlight new or unread items by adding a <code>{"<Badge>"}</code> to links, Bootstrap navs, and more.</p>
<ReactPlayground codeText={Samples.Badge} />
<div className="bs-callout bs-callout-info">
<h4>Cross-browser compatibility</h4>
<p>Unlike regular Bootstrap badges self collapse even in Internet Explorer 8.</p>
</div>
<h3><Anchor id="badges-props">Props</Anchor></h3>
<PropTable component="Badge"/>
</div>
);
}
|
src/app/components/task/Task.js | meedan/check-web | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import Relay from 'react-relay/classic';
import { FormattedMessage } from 'react-intl';
import config from 'config'; // eslint-disable-line require-path-exists/exists
import Box from '@material-ui/core/Box';
import Button from '@material-ui/core/Button';
import IconButton from '@material-ui/core/IconButton';
import Card from '@material-ui/core/Card';
import CardHeader from '@material-ui/core/CardHeader';
import CardContent from '@material-ui/core/CardContent';
import Collapse from '@material-ui/core/Collapse';
import Typography from '@material-ui/core/Typography';
import EditIcon from '@material-ui/icons/Edit';
import KeyboardArrowDown from '@material-ui/icons/KeyboardArrowDown';
import CircularProgress from '@material-ui/core/CircularProgress';
import { MetadataText, MetadataFile, MetadataDate, MetadataNumber, MetadataLocation, MetadataMultiselect, MetadataUrl } from '@meedan/check-ui';
import styled from 'styled-components';
import moment from 'moment';
import EditTaskDialog from './EditTaskDialog';
import TaskActions from './TaskActions';
import TaskLog from './TaskLog';
import SingleChoiceTask from './SingleChoiceTask';
import MultiSelectTask from './MultiSelectTask';
import ShortTextRespondTask from './ShortTextRespondTask';
import NumberRespondTask from './NumberRespondTask';
import GeolocationRespondTask from './GeolocationRespondTask';
import GeolocationTaskResponse from './GeolocationTaskResponse';
import DatetimeRespondTask from './DatetimeRespondTask';
import DatetimeTaskResponse from './DatetimeTaskResponse';
import FileUploadRespondTask from './FileUploadRespondTask';
import GenericUnknownErrorMessage from '../GenericUnknownErrorMessage';
import { FormattedGlobalMessage } from '../MappedMessage';
import Message from '../Message';
import NavigateAwayDialog from '../NavigateAwayDialog';
import Can, { can } from '../Can';
import ParsedText from '../ParsedText';
import UserAvatars from '../UserAvatars';
import Sentence from '../Sentence';
import ConfirmProceedDialog from '../layout/ConfirmProceedDialog';
import ProfileLink from '../layout/ProfileLink';
import AttributionDialog from '../user/AttributionDialog';
import CheckContext from '../../CheckContext';
import { getErrorMessage } from '../../helpers';
import UpdateTaskMutation from '../../relay/mutations/UpdateTaskMutation';
import UpdateDynamicMutation from '../../relay/mutations/UpdateDynamicMutation';
import DeleteAnnotationMutation from '../../relay/mutations/DeleteAnnotationMutation';
import DeleteDynamicMutation from '../../relay/mutations/DeleteDynamicMutation';
import {
Row,
units,
black16,
black87,
separationGray,
checkBlue,
} from '../../styles/js/shared';
import CheckArchivedFlags from '../../CheckArchivedFlags';
const StyledWordBreakDiv = styled.div`
width: 100%;
hyphens: auto;
overflow-wrap: break-word;
word-break: break-word;
.task {
box-shadow: none;
border: 0;
border-bottom: 1px solid ${separationGray};
border-radius: 0;
margin-bottom: 0 !important;
.task__card-header {
padding: ${units(3)} 0;
flex-direction: row-reverse;
display: flex;
align-items: flex-start;
.task__card-expand {
margin: ${units(0)} ${units(1)} 0 0;
}
.task__card-description {
padding: ${units(2)} 0 0 0;
}
}
}
.task__card-text {
padding-bottom: 0 !important;
padding-top: 0 !important;
}
`;
const StyledTaskTitle = styled.span`
line-height: ${units(3)};
font-weight: 500;
color: ${black87};
`;
const StyledTaskResponses = styled.div`
.task__resolved {
border-bottom: 1px solid ${black16};
padding-bottom: ${units(1)};
margin-bottom: ${units(1)};
}
`;
const StyledAnnotatorInformation = styled.span`
display: inline-block;
p {
font-size: 9px;
color: #979797;
}
`;
const StyledRequired = styled.span`
color: red;
`;
const StyledMapEditor = styled.div`
#map-edit {
width: 100%;
height: 500px;
}
`;
const StyledMultiselect = styled.div`
.Mui-checked + .MuiFormControlLabel-label.Mui-disabled {
color: black;
}
.Mui-checked {
color: ${checkBlue} !important;
}
`;
const StyledFieldInformation = styled.div`
margin-bottom: ${units(2)};
`;
const StyledMetadataButton = styled.div`
button {
background-color: #f4f4f4;
margin-top: ${units(1)};
display: none;
}
button:hover {
background-color: #ddd;
}
`;
function getResponseData(response) {
const data = {};
if (response) {
data.by = [];
data.byPictures = [];
if (response.attribution) {
response.attribution.edges.forEach((user) => {
const u = user.node;
data.by.push(<ProfileLink teamUser={u.team_user || null} />);
data.byPictures.push(u);
});
}
if (response.content) {
const fields = JSON.parse(response.content);
if (Array.isArray(fields)) {
fields.forEach((field) => {
if (
/^response_/.test(field.field_name) &&
field.value &&
field.value !== ''
) {
data.response = field.value;
}
});
}
}
}
return data;
}
/* eslint jsx-a11y/click-events-have-key-events: 0 */
class Task extends Component {
constructor(props) {
super(props);
let textValue;
if (props.task.type === 'multiple_choice' || props.task.type === 'single_choice') {
textValue = this.getMultiselectInitialValue(props.task);
} else {
textValue = props.task.first_response_value;
}
this.state = {
editingQuestion: false,
message: null,
deleteResponse: null,
deletingTask: false,
editingResponse: false,
editingAttribution: false,
expand: true,
isSaving: false,
textValue,
};
}
getMultiselectInitialValue = (node) => {
let initialDynamic;
try {
if (node.type === 'multiple_choice') {
initialDynamic = JSON.parse(
JSON.parse(node?.first_response?.content)[0].value,
);
} else if (node.type === 'single_choice') {
initialDynamic = JSON.parse(node?.first_response?.content)[0].value;
}
} catch (exception) {
if (node.type === 'multiple_choice') {
initialDynamic = { selected: [] };
} else if (node.type === 'single_choice') {
initialDynamic = '';
}
}
return initialDynamic;
}
getAssignment() {
const assignment = document.getElementById(
`attribution-${this.props.task.dbid}`,
);
if (assignment) {
return assignment.value;
}
return null;
}
getCurrentUser() {
return new CheckContext(this).getContextStore().currentUser;
}
fail = (transaction) => {
const message = getErrorMessage(
transaction,
<GenericUnknownErrorMessage />,
);
this.setState({ message, isSaving: false });
};
handleAction = (action, value) => {
switch (action) {
case 'edit_question':
this.setState({ editingQuestion: true });
break;
case 'edit_response':
this.setState({ editingResponse: value });
break;
case 'edit_assignment':
this.setState({ editingAssignment: true });
break;
case 'edit_attribution':
this.setState({ editingAttribution: true });
break;
case 'delete':
this.setState({ deletingTask: true });
break;
case 'delete_response':
this.setState({ deleteResponse: value });
break;
default:
}
};
handleCancelEditResponse = () => this.setState({ editingResponse: false });
handleSubmitResponse = (response, file) => {
const { media, task } = this.props;
this.setState({ isSaving: true });
const onSuccess = () => {
this.setState({ message: null, isSaving: false });
};
const fields = {};
fields[`response_${task.type}`] = response;
const parentType = task.annotated_type
.replace(/([a-z])([A-Z])/, '$1_$2')
.toLowerCase();
Relay.Store.commitUpdate(
new UpdateTaskMutation({
operation: 'answer',
annotated: media,
parent_type: parentType,
file,
user: this.getCurrentUser(),
task: {
id: task.id,
fields,
annotation_type: `task_response_${task.type}`,
},
}),
{ onSuccess, onFailure: this.fail },
);
};
handleUpdateMultiselectMetadata = (textValue) => {
const { task } = this.props;
this.setState({ textValue });
const matchingTaskIndex = this.props.localResponses.findIndex(item => item.node.dbid === task.dbid);
// deep copy the local responses object
const mutatedLocalResponses = JSON.parse(JSON.stringify(this.props.localResponses));
if (task.type === 'single_choice') {
mutatedLocalResponses[matchingTaskIndex].node.first_response_value = textValue;
} else {
// value is an object, we transform it to a string separated by ', '
let tempValue = textValue.selected.join(', ');
if (textValue.other) {
tempValue += `, ${textValue.other}`;
}
mutatedLocalResponses[matchingTaskIndex].node.first_response_value = tempValue;
}
this.props.setLocalResponses([...mutatedLocalResponses]);
};
handleUpdateResponse = (edited_response, file, responseObj) => {
const { media, task } = this.props;
this.setState({ isSaving: true });
const onSuccess = () =>
this.setState({
message: null,
editingResponse: false,
isSaving: false,
});
const onFailure = (transaction) => {
this.setState({ editingResponse: true });
this.fail(transaction);
};
const fields = {};
fields[`response_${task.type}`] = edited_response;
Relay.Store.commitUpdate(
new UpdateDynamicMutation({
annotated: media,
task,
parent_type: 'task',
file,
dynamic: {
// in some legacy data cases we can lack an 'editingResponse' id, but in those cases there's always a responseObj id
id: this.state.editingResponse.id || responseObj.id,
fields,
},
}),
{ onSuccess, onFailure },
);
this.setState({ message: null, editingResponse: false });
};
handleUpdateTask = (editedTask) => {
const { media, task } = this.props;
const onSuccess = () => {
this.setState({ message: null, editingQuestion: false });
};
const onFailure = (transaction) => {
this.setState({ editingQuestion: true });
this.fail(transaction);
};
const taskObj = {
id: task.id,
label: editedTask.label,
json_schema: editedTask.jsonschema,
description: editedTask.description,
assigned_to_ids: this.getAssignment(),
};
const parentType = task.annotated_type
.replace(/([a-z])([A-Z])/, '$1_$2')
.toLowerCase();
Relay.Store.commitUpdate(
new UpdateTaskMutation({
operation: 'update',
annotated: media,
parent_type: parentType,
user: this.getCurrentUser(),
task: taskObj,
}),
{ onSuccess, onFailure },
);
this.setState({ message: null, editingQuestion: false });
};
handleUpdateAssignment = (value) => {
const { task } = this.props;
task.assigned_to_ids = value;
const onSuccess = () =>
this.setState({ message: null, editingAssignment: false });
const parentType = task.annotated_type
.replace(/([a-z])([A-Z])/, '$1_$2')
.toLowerCase();
Relay.Store.commitUpdate(
new UpdateTaskMutation({
operation: 'assign',
user: this.getCurrentUser(),
annotated: this.props.media,
parent_type: parentType,
task,
}),
{ onSuccess, onFailure: this.fail },
);
};
handleUpdateAttribution = (value) => {
const onSuccess = () =>
this.setState({ message: null, editingAttribution: false });
Relay.Store.commitUpdate(
new UpdateDynamicMutation({
annotated: this.props.media,
parent_type: 'project_media',
dynamic: {
id: this.props.task.first_response.id,
set_attribution: value,
},
}),
{ onSuccess, onFailure: this.fail },
);
};
submitDeleteTask = () => {
const { task, media } = this.props;
this.setState({ isSaving: true });
const onSuccess = () => {
this.setState({ deletingTask: false, isSaving: false });
};
Relay.Store.commitUpdate(
new DeleteAnnotationMutation({
parent_type: 'project_media',
annotated: media,
id: task.id,
}),
{ onSuccess, onFailure: this.fail },
);
};
submitDeleteTaskResponse = (deleteId) => {
const { task } = this.props;
const { deleteResponse } = this.state;
this.setState({ isSaving: true });
const onSuccess = () => {
this.setState({ deleteResponse: null, isSaving: false });
};
let id = null;
if (task.fieldset === 'metadata') {
id = deleteId;
} else {
({ id } = deleteResponse);
}
Relay.Store.commitUpdate(
new DeleteDynamicMutation({
parent_type: 'task',
annotated: task,
id,
}),
{ onSuccess, onFailure: this.fail },
);
};
generateMessages = about => (
{
MetadataLocation: {
customize: (
<FormattedMessage
id="metadata.location.customize"
defaultMessage="Customize place name"
description="This is a label that appears on a text field, related to a pin on a map. The user may type any text of their choice here and name the place they are pinning. They can also modify suggested place names here."
/>
),
coordinates: (
<FormattedMessage
id="metadata.location.coordinates"
defaultMessage="Latitude, longitude"
description="This is a label that appears on a text field, related to a pin on a map. This contains the latitude and longitude coordinates of the map pin. If the user changes these numbers, the map pin moves. If the user moves the map pin, the numbers update to reflect the new pin location."
/>
),
coordinatesHelper: (
<FormattedMessage
id="metadata.location.coordinates.helper"
defaultMessage={'Should be a comma-separated pair of latitude and longitude coordinates like "-12.9, -38.15". Drag the map pin if you are having difficulty.'}
description="This is a helper message that appears when someone enters text in the 'Latitude, longitude' text field that cannot be parsed as a valid pair of latitude and longitude coordinates. It tells the user that they need to provide valid coordinates and gives an example. It also tells them that they can do a drag action with the mouse on the visual map pin as an alternative to entering numbers in this field."
/>
),
search: (
<FormattedMessage
id="metadata.location.search"
defaultMessage="Search the map"
description="This is a label that appears on a text field. If the user begins to type a location they will receive a list of suggested place names."
/>
),
},
MetadataFile: {
dropFile: (
<FormattedMessage
id="metadata.file.dropFile"
defaultMessage="Drag and drop a file here, or click to upload a file (max size: {fileSizeLabel}, allowed extensions: {extensions})"
description="This message appears in a rectangle, instructing the user that they can use their mouse to drag and drop a file, or click to pull up a file selector menu. This also tells them the maximum allowed file size, and the valid types of files that the user can upload. The `fileSizeLabel` variable will read something like '1.0 MB', and the 'extensions' variable is a list of valid file extensions. Neither will be localized."
values={{
fileSizeLabel: about ? about.file_max_size : '',
extensions: about ? about.file_extensions?.join(', ') : '',
}}
/>
),
errorTooManyFiles: (
<FormattedMessage
id="metadata.file.tooManyFiles"
defaultMessage="You can only upload one file here. Please try uploading one file."
description="This message appears when a user tries to add two or more files at once to the file upload widget."
/>
),
errorInvalidFile: (
<FormattedMessage
id="metadata.file.invalidFile"
defaultMessage="This is not a valid file. Please try again with a different file."
description="This message appears when a user tries to add two or more files at once to the file upload widget."
/>
),
errorFileTooBig: (
<FormattedMessage
id="metadata.file.tooBig"
defaultMessage="This file is too big. The maximum allowed file size is {fileSizeLabel}. Please try again with a different file."
description="This message appears when a user tries to upload a file that is too big. The 'fileSizeLabel' will read something like '1.0 MB' and will not be localized."
values={{
fileSizeLabel: about ? about.file_max_size : '',
}}
/>
),
errorFileType: (
<FormattedMessage
id="metadata.file.wrongType"
defaultMessage="This is not an accepted file type. Accepted file types include: {extensions}. Please try again with a different file."
description="This message appears when a user tries to upload a file that is the wrong file type. The 'extensions' variable will be a list of file extensions (PDF, PNG, etc) and will not be localized."
values={{
extensions: about ? about.file_extensions?.join(', ') : '',
}}
/>
),
},
MetadataUrl: {
helperText: (
<FormattedMessage
id="metadata.url.helperText"
defaultMessage="Must be a valid URL"
description="A message that appears underneath a text box when a user enters text that a web browser would not interpret as a URL."
/>
),
},
}
);
renderTaskResponse(responseObj, response, by, byPictures, showEditIcon) {
const { task, about } = this.props;
const messages = task.fieldset === 'metadata' ? this.generateMessages(about) : {};
const EditButton = () => (
<StyledMetadataButton>
<Button onClick={() => this.handleAction('edit_response', responseObj)} className="metadata-edit">
<FormattedMessage
id="metadata.edit"
defaultMessage="Edit"
description="This is a label that appears on a button next to an item that the user can edit. The label indicates that if the user presses this button, the item will become editable."
/>
</Button>
</StyledMetadataButton>
);
const CancelButton = () => (
<StyledMetadataButton>
<Button
className="metadata-cancel"
onClick={() => {
this.setState({ editingResponse: false });
this.setState({ textValue: this.getMultiselectInitialValue(task) || task.first_response_value || '' });
}}
>
<FormattedMessage
id="metadata.cancel"
defaultMessage="Cancel"
description="This is a label that appears on a button next to an item that the user is editing. The label indicates that if the user presses this button, the user will 'cancel' the editing action and all changes will revert."
/>
</Button>
</StyledMetadataButton>
);
const SaveButton = (props) => {
const {
disabled,
uploadables,
mutationPayload,
required,
empty,
anyInvalidUrls,
} = props;
const payload =
mutationPayload?.response_multiple_choice ||
mutationPayload?.response_single_choice ||
null;
return (
<StyledMetadataButton>
<Button
className="metadata-save"
data-required={required}
data-empty={empty}
data-urlerror={anyInvalidUrls}
onClick={() => {
let tempTextValue;
const isEmptyUrlArray = () => task.type === 'url' && this.state.textValue.filter(item => item.url !== '' || item.title !== '').length === 0;
// if multiple choice, textValue is an object, we transform it to a string separated by ', '
if (task.type === 'multiple_choice') {
tempTextValue = this.state.textValue.selected.join(', ');
if (this.state.textValue.other) {
tempTextValue += `, ${this.state.textValue.other}`;
}
} else {
tempTextValue = this.state.textValue;
}
// in the case of multiple/single choice we need to set the textTempValue of an empty annotation to null rather than empty string, so it matches the state of first_response_value
if (task.type === 'multiple_choice' || task.type === 'single_choice') {
if (tempTextValue === '') {
tempTextValue = null;
}
}
// if there's a blank submission, and an existing submission exists, treat as a delete action
if (!payload && (!this.state.textValue || isEmptyUrlArray()) && task.first_response_value) {
this.submitDeleteTaskResponse(task.first_response.id);
} else if (tempTextValue === task?.first_response_value) {
// if the current submission hasn't changed at all, do nothing
} else if (responseObj) {
// if there is a pre-existing response, we must be updating a record
this.handleUpdateResponse(
payload || this.state.textValue,
uploadables ? uploadables['file[]'] : null,
responseObj,
);
} else {
this.handleSubmitResponse(
payload || this.state.textValue,
uploadables ? uploadables['file[]'] : null,
);
}
}}
disabled={disabled}
>
<FormattedMessage
id="metadata.save"
defaultMessage="Save"
description="This is a label that appears on a button next to an item that the user is editing. The label indicates that if the user presses this button, the user will save the changes they have been making."
/>
</Button>
</StyledMetadataButton>
);
};
const DeleteButton = (props) => {
const { onClick } = props;
return (
<StyledMetadataButton>
<Button
className="metadata-delete"
onClick={() => {
if (onClick) {
onClick();
}
this.submitDeleteTaskResponse(task.first_response.id);
}}
>
<FormattedMessage
id="metadata.delete"
defaultMessage="Delete"
description="This is a label that appears on a button next to an item that the user can delete. The label indicates that if the user presses this button, the item will be deleted."
/>
</Button>
</StyledMetadataButton>
);
};
const FieldInformation = () => (
<StyledFieldInformation>
<Typography variant="h6">{task.label}<StyledRequired>{task.team_task.required ? ' *' : null}</StyledRequired></Typography>
<Typography variant="subtitle2">
<ParsedText text={task.description} />
</Typography>
</StyledFieldInformation>
);
const ProgressLabel = ({ fileName }) => (
<Typography variant="body1" gutterBottom>
<FormattedMessage
id="metadata.uploadProgressLabel"
defaultMessage="Saving {file}…"
description="This is a label that appears while a file upload is ongoing."
values={{ file: fileName }}
/>
</Typography>
);
const AnnotatorInformation = () => {
let updated_at;
try {
updated_at = JSON.parse(responseObj.content)[0]?.updated_at;
} catch (exception) {
updated_at = null;
}
const timeAgo = moment(updated_at).fromNow();
return (
responseObj && responseObj.annotator ? (
<StyledAnnotatorInformation>
<Typography variant="body1">
Saved {timeAgo} by{' '}
<a
href={`/check/user/${responseObj.annotator.user.dbid}`}
>
{responseObj.annotator.user.name}
</a>
</Typography>
</StyledAnnotatorInformation>)
: null
);
};
if (
this.state.editingResponse && responseObj &&
this.state.editingResponse.id === responseObj.id
) {
const editingResponseData = getResponseData(this.state.editingResponse);
const editingResponseText = editingResponseData.response;
return (
<div className="task__editing">
<form name={`edit-response-${this.state.editingResponse.id}`}>
{task.type === 'free_text' && task.fieldset === 'metadata' ? (
<MetadataText
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
) : null}
{task.type === 'free_text' && task.fieldset === 'tasks' ? (
<ShortTextRespondTask
fieldset={task.fieldset}
task={task}
response={editingResponseText}
onSubmit={this.handleUpdateResponse}
onDismiss={this.handleCancelEditResponse}
/>
) : null}
{task.type === 'number' && task.fieldset === 'tasks' ? (
<NumberRespondTask
fieldset={task.fieldset}
task={task}
response={editingResponseText}
onSubmit={this.handleUpdateResponse}
onDismiss={this.handleCancelEditResponse}
/>
) : null}
{task.type === 'number' && task.fieldset === 'metadata' ? (
<MetadataNumber
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
) : null}
{task.type === 'geolocation' && task.fieldset === 'metadata' ? (
<StyledMapEditor>
<MetadataLocation
node={task}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
mapboxApiKey={config.mapboxApiKey}
messages={messages.MetadataLocation}
/>
</StyledMapEditor>
) : null}
{task.type === 'geolocation' && task.fieldset === 'tasks' ? (
<GeolocationRespondTask
fieldset={task.fieldset}
response={editingResponseText}
onSubmit={this.handleUpdateResponse}
onDismiss={this.handleCancelEditResponse}
/>
) : null}
{task.type === 'datetime' && task.fieldset === 'metadata' ? (
<MetadataDate
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
) : null}
{task.type === 'datetime' && task.fieldset === 'tasks' ? (
<DatetimeRespondTask
fieldset={task.fieldset}
response={editingResponseText}
timezones={task.jsonoptions}
onSubmit={this.handleUpdateResponse}
onDismiss={this.handleCancelEditResponse}
/>
) : null}
{task.type === 'single_choice' && task.fieldset === 'metadata' ? (
<MetadataMultiselect
isSingle
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={this.handleUpdateMultiselectMetadata}
/>
) : null}
{task.type === 'single_choice' && task.fieldset === 'tasks' ? (
<SingleChoiceTask
fieldset={task.fieldset}
mode="edit_response"
response={editingResponseText}
jsonoptions={task.jsonoptions}
onDismiss={this.handleCancelEditResponse}
onSubmit={this.handleUpdateResponse}
/>
) : null}
{task.type === 'multiple_choice' && task.fieldset === 'metadata' ? (
<MetadataMultiselect
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={this.handleUpdateMultiselectMetadata}
/>
) : null}
{task.type === 'multiple_choice' && task.fieldset === 'tasks' ? (
<MultiSelectTask
fieldset={task.fieldset}
mode="edit_response"
jsonresponse={editingResponseText}
jsonoptions={task.jsonoptions}
onDismiss={this.handleCancelEditResponse}
onSubmit={this.handleUpdateResponse}
/>
) : null}
{task.type === 'file_upload' && task.fieldset === 'metadata' ? (
<MetadataFile
node={task}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
extensions={about.file_extensions || []}
fileSizeMax={about.file_max_size_in_bytes}
messages={messages.MetadataFile}
/>
) : null}
{task.type === 'file_upload' && task.fieldset === 'tasks' ? (
<FileUploadRespondTask
fieldset={task.fieldset}
task={task}
response={editingResponseText}
onSubmit={this.handleUpdateResponse}
onDismiss={this.handleCancelEditResponse}
/>
) : null}
{task.type === 'url' && task.fieldset === 'metadata' ? (
<MetadataUrl
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
messages={messages.MetadataUrl}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
) : null}
</form>
</div>
);
}
let fileUploadPath = null;
if (
task.type === 'file_upload' &&
responseObj &&
responseObj.file_data &&
responseObj.file_data.file_urls &&
responseObj.file_data.file_urls.length
) {
[fileUploadPath] = responseObj.file_data.file_urls;
}
return (
<StyledWordBreakDiv className="task__resolved">
{task.type === 'free_text' && task.fieldset === 'tasks' ?
<div className="task__response">
<ParsedText text={response} />
</div>
: null}
{task.type === 'free_text' && task.fieldset === 'metadata' ? (
<div className="task__response">
<MetadataText
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
</div>
) : null}
{task.type === 'number' && task.fieldset === 'tasks' ? (
<div className="task__response" style={{ textAlign: 'right' }}>
{response}
</div>
) : null}
{task.type === 'number' && task.fieldset === 'metadata' ? (
<div className="task__response">
<MetadataNumber
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
</div>
) : null}
{task.type === 'geolocation' && task.fieldset === 'tasks' ? (
<div className="task__response">
<GeolocationTaskResponse response={response} />
</div>
) : null}
{task.type === 'geolocation' && task.fieldset === 'metadata' ? (
<StyledMapEditor>
<div className="task__response">
<MetadataLocation
node={task}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={!!task?.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
mapboxApiKey={config.mapboxApiKey}
messages={messages.MetadataLocation}
/>
</div>
</StyledMapEditor>
) : null}
{task.type === 'datetime' && task.fieldset === 'metadata' ? (
<div className="task__response">
<MetadataDate
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
</div>
) : null}
{task.type === 'datetime' && task.fieldset === 'tasks' ? (
<div className="task__response">
<DatetimeTaskResponse response={response} />
</div>
) : null}
{task.type === 'single_choice' && task.fieldset === 'tasks' ? (
<SingleChoiceTask
mode="show_response"
response={response}
jsonoptions={task.jsonoptions}
/>
) : null}
{task.type === 'single_choice' && task.fieldset === 'metadata' ? (
<div className="task__response">
<StyledMultiselect>
<MetadataMultiselect
isSingle
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={this.handleUpdateMultiselectMetadata}
/>
</StyledMultiselect>
</div>
) : null}
{task.type === 'multiple_choice' && task.fieldset === 'tasks' ? (
<MultiSelectTask
mode="show_response"
jsonresponse={response}
jsonoptions={task.jsonoptions}
/>
) : null}
{task.type === 'multiple_choice' && task.fieldset === 'metadata' ? (
<div className="task__response">
<StyledMultiselect>
<MetadataMultiselect
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={this.handleUpdateMultiselectMetadata}
/>
</StyledMultiselect>
</div>
) : null}
{task.type === 'file_upload' && task.fieldset === 'tasks' ? (
<div className="task__response">
<Box component="p" textAlign="center">
{fileUploadPath ? (
<Box
component="a"
href={fileUploadPath}
target="_blank"
rel="noreferrer noopener"
color={checkBlue}
>
{response}
</Box>
) : (
<CircularProgress />
)}
</Box>
</div>
) : null}
{task.type === 'file_upload' && task.fieldset === 'metadata' ? (
<div className="task__response">
{ this.state.isSaving ?
<NavigateAwayDialog
hasUnsavedChanges={this.state.isSaving}
title={
<FormattedMessage
id="task.uploadWarningTitle"
defaultMessage="There is an ongoing file upload"
description="Warning to prevent user from navigating away while upload is running"
/>
}
body={
<FormattedMessage
id="task.uploadWarningBody"
defaultMessage="Navigating away from this page may cause the interruption of the file upload."
description="Warning to prevent user from navigating away while upload is running"
/>
}
/> : null
}
<MetadataFile
node={task}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
ProgressLabel={ProgressLabel}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
isSaving={this.state.isSaving}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
extensions={about.file_extensions || []}
fileSizeMax={about.file_max_size_in_bytes}
messages={messages.MetadataFile}
/>
</div>
) : null}
{task.type === 'url' && task.fieldset === 'metadata' ? (
<MetadataUrl
node={task}
classes={{}}
DeleteButton={DeleteButton}
CancelButton={CancelButton}
SaveButton={SaveButton}
EditButton={EditButton}
AnnotatorInformation={AnnotatorInformation}
FieldInformation={FieldInformation}
hasData={task.first_response_value}
isEditing={this.props.isEditing}
messages={messages.MetadataUrl}
disabled={!this.props.isEditing}
required={task.team_task.required}
metadataValue={
this.state.textValue
}
setMetadataValue={(textValue) => {
this.setState({ textValue });
}}
/>
) : null}
{by && byPictures && task.fieldset !== 'metadata' ? (
<Box
className="task__resolver"
display="flex"
alignItems="center"
justifyContent="space-between"
mt={1}
>
<Box component="small" display="flex">
<UserAvatars users={byPictures} />
<Box component="span" lineHeight="24px" px={1}>
<FormattedMessage
id="task.answeredBy"
defaultMessage="Completed by {byName}"
values={{ byName: <Sentence list={by} /> }}
/>
</Box>
</Box>
{showEditIcon && can(responseObj.permissions, 'update Dynamic') ? (
<EditIcon
style={{ width: 16, height: 16, cursor: 'pointer' }}
onClick={() => this.handleAction('edit_response', responseObj)}
/>
) : null}
</Box>
) : null}
</StyledWordBreakDiv>
);
}
render() {
const { task: teamTask, media } = this.props;
const task = { ...teamTask };
const isTask = task.fieldset === 'tasks';
const data = getResponseData(task.first_response);
const { response, by, byPictures } = data;
const currentUser = this.getCurrentUser();
const isArchived = !(media.archived === CheckArchivedFlags.NONE);
task.cannotAct =
!response &&
!can(media.permissions, 'create Task') &&
!can(task.permissions, 'destroy Task');
let taskAssigned = false;
const taskAnswered = !!response;
const assignments = task.assignments.edges;
const assignmentComponents = [];
assignments.forEach((assignment) => {
assignmentComponents.push(
<ProfileLink teamUser={assignment.node.team_user || null} />,
);
if (currentUser && assignment.node.dbid === currentUser.dbid) {
taskAssigned = true;
}
});
const taskAssignment = task.assignments.edges.length > 0 && !response && task.fieldset === 'tasks' ? (
<Box
className="task__assigned"
display="flex"
alignItems="center"
width="420px"
m={2}
justifyContent="space-between"
>
<Box component="small" display="flex">
<UserAvatars users={assignments} />
<Box component="span" lineHeight="24px" px={1}>
<FormattedMessage
id="task.assignedTo"
defaultMessage="Assigned to {name}"
values={{
name: <Sentence list={assignmentComponents} />,
}}
/>
</Box>
</Box>
</Box>
) : null;
const zeroAnswer = task.responses.edges.length === 0;
const taskActions = !isArchived ? (
<Box display="flex" alignItems="center">
{taskAssignment}
{data.by ? (
<Box
className="task__resolver"
display="flex"
alignItems="center"
margin={2}
>
<Box component="small" display="flex">
<UserAvatars users={byPictures} />
<Box component="span" lineHeight="24px" px={1}>
{response ? (
<FormattedMessage
id="task.answeredBy"
defaultMessage="Completed by {byName}"
values={{ byName: <Sentence list={by} /> }}
/>
) : null}
</Box>
</Box>
</Box>
) : null}
<Box marginLeft="auto">
<TaskActions
task={task}
media={media}
response={response}
onSelect={this.handleAction}
/>
</Box>
</Box>
) : null;
const taskQuestion = (
<div className="task__question">
<div className="task__label-container">
<Row>
<StyledTaskTitle className="task__label">
{task.label}
</StyledTaskTitle>
</Row>
</div>
</div>
);
let taskBody = null;
if (!isArchived) {
if (!response || task.responses.edges.length > 1) {
taskBody = (
<div>
<StyledTaskResponses>
{task.responses.edges.map((singleResponse) => {
const singleResponseData = getResponseData(singleResponse.node);
return this.renderTaskResponse(
singleResponse.node,
singleResponseData.response,
singleResponseData.by,
singleResponseData.byPictures,
true,
);
})}
</StyledTaskResponses>
{zeroAnswer && task.fieldset === 'metadata' ? (
<Can permissions={media.permissions} permission="create Dynamic">
<div>
<form name={`task-response-${task.id}`}>
<div className="task__response-inputs">
{
this.renderTaskResponse(
task.first_response,
response,
false,
false,
false,
)
}
</div>
</form>
</div>
</Can>
) : null}
{zeroAnswer && task.fieldset === 'tasks' ? (
<Can permissions={media.permissions} permission="create Dynamic">
<div>
<form name={`task-response-${task.id}`}>
<div className="task__response-inputs">
{task.type === 'free_text' ? (
<ShortTextRespondTask
task={task}
fieldset={task.fieldset}
onSubmit={this.handleSubmitResponse}
/>
) : null}
{task.type === 'number' ? (
<NumberRespondTask
task={task}
fieldset={task.fieldset}
onSubmit={this.handleSubmitResponse}
/>
) : null}
{task.type === 'geolocation' ? (
<GeolocationRespondTask
fieldset={task.fieldset}
onSubmit={this.handleSubmitResponse}
/>
) : null}
{task.type === 'datetime' ? (
<DatetimeRespondTask
timezones={task.jsonoptions}
fieldset={task.fieldset}
onSubmit={this.handleSubmitResponse}
/>
) : null}
{task.type === 'single_choice' ? (
<SingleChoiceTask
fieldset={task.fieldset}
mode="respond"
response={response}
jsonoptions={task.jsonoptions}
onSubmit={this.handleSubmitResponse}
/>
) : null}
{task.type === 'multiple_choice' ? (
<MultiSelectTask
fieldset={task.fieldset}
mode="respond"
jsonresponse={response}
jsonoptions={task.jsonoptions}
onSubmit={this.handleSubmitResponse}
/>
) : null}
{task.type === 'file_upload' ? (
<FileUploadRespondTask
fieldset={task.fieldset}
task={task}
onSubmit={this.handleSubmitResponse}
/>
) : null}
</div>
</form>
</div>
</Can>
) : null}
</div>
);
} else {
taskBody = this.renderTaskResponse(
task.first_response,
response,
false,
false,
false,
);
}
}
task.project_media = Object.assign({}, this.props.media);
delete task.project_media.tasks;
const taskDescription = task.description ? (
<div className="task__card-description">
<ParsedText text={task.description} />
</div>
) : null;
const className = ['task', `task-type__${task.type}`];
if (taskAnswered) {
className.push('task__answered-by-current-user');
}
if (taskAssigned) {
className.push('task__assigned-to-current-user');
}
if (task.fieldset === 'metadata') {
return (
<div>
{taskBody}
</div>
);
}
return (
// Task cards
<StyledWordBreakDiv>
<Box clone mb={1}>
<Card
id={`task-${task.dbid}`}
className={className.join(' ')}
style={{ marginBottom: units(1) }}
>
<CardHeader
className="task__card-header"
disableTypography
title={taskQuestion}
subheader={taskDescription}
id={`task__label-${task.id}`}
action={
<IconButton
className="task__card-expand"
onClick={() => this.setState({ expand: !this.state.expand })}
>
<KeyboardArrowDown />
</IconButton>
}
/>
<Collapse in={this.state.expand} timeout="auto">
<CardContent className="task__card-text">
<Message message={this.state.message} />
<Box marginBottom={2}>{taskBody}</Box>
</CardContent>
{taskActions}
{isTask ? <TaskLog task={task} response={response} /> : null}
</Collapse>
</Card>
</Box>
{this.state.editingQuestion ? (
<EditTaskDialog
task={task}
message={this.state.message}
taskType={task.type}
onDismiss={() => this.setState({ editingQuestion: false })}
onSubmit={this.handleUpdateTask}
noOptions
/>
) : null}
{this.state.editingAssignment ? (
<AttributionDialog
taskType={task.type}
open={this.state.editingAssignment}
title={
<FormattedMessage
id="tasks.editAssignment"
defaultMessage="Edit assignment"
/>
}
blurb={
<FormattedMessage
id="tasks.attributionSlogan"
defaultMessage='For the task, "{label}"'
values={{ label: task.label }}
/>
}
selectedUsers={assignments}
onDismiss={() => this.setState({ editingAssignment: false })}
onSubmit={this.handleUpdateAssignment}
/>
) : null}
{this.state.editingAttribution ? (
<AttributionDialog
taskType={task.type}
open={this.state.editingAttribution}
title={
<FormattedMessage
id="tasks.editAttribution"
defaultMessage="Edit attribution"
/>
}
blurb={
<FormattedMessage
id="tasks.attributionSlogan"
defaultMessage='For the task, "{label}"'
values={{ label: task.label }}
/>
}
selectedUsers={task.first_response.attribution.edges}
onDismiss={() => this.setState({ editingAttribution: false })}
onSubmit={this.handleUpdateAttribution}
/>
) : null}
<ConfirmProceedDialog
body={
<Typography variant="body1" component="p">
<FormattedMessage
id="task.confirmDelete"
defaultMessage="Are you sure you want to delete this task?"
/>
</Typography>
}
isSaving={this.state.isSaving}
onCancel={() => this.setState({ deletingTask: false })}
onProceed={this.submitDeleteTask}
open={this.state.deletingTask}
proceedLabel={<FormattedGlobalMessage messageKey="delete" />}
title={
<FormattedMessage
id="task.confirmDeleteTitle"
defaultMessage="Delete task?"
/>
}
/>
<ConfirmProceedDialog
body={
<Typography variant="body1" component="p">
<FormattedMessage
id="task.confirmDeleteResponse"
defaultMessage="Are you sure you want to delete this answer?"
/>
</Typography>
}
isSaving={this.state.isSaving}
onCancel={() => this.setState({ deleteResponse: null })}
onProceed={this.submitDeleteTaskResponse}
open={this.state.deleteResponse}
proceedLabel={<FormattedGlobalMessage messageKey="delete" />}
title={
<FormattedMessage
id="task.confirmDeleteResponseTitle"
defaultMessage="Delete answer?"
/>
}
/>
</StyledWordBreakDiv>
);
}
}
Task.contextTypes = {
store: PropTypes.object,
};
export default Relay.createContainer(Task, {
initialVariables: {
teamSlug: null,
},
prepareVariables: vars => ({
...vars,
teamSlug: /^\/([^/]+)/.test(window.location.pathname)
? window.location.pathname.match(/^\/([^/]+)/)[1]
: null,
}),
fragments: {
task: () => Relay.QL`
fragment on Task {
id,
dbid,
label,
type,
annotated_type
description,
fieldset,
permissions,
jsonoptions,
json_schema,
options,
pending_suggestions_count,
suggestions_count,
log_count,
team_task_id,
team_task {
required,
},
responses(first: 10000) {
edges {
node {
id,
dbid,
permissions,
content,
file_data,
attribution(first: 10000) {
edges {
node {
id
dbid
name
team_user(team_slug: $teamSlug) {
${ProfileLink.getFragment('teamUser')},
},
source {
id
dbid
image
}
}
}
}
annotator {
name,
profile_image,
user {
id,
dbid,
name,
is_active
team_user(team_slug: $teamSlug) {
${ProfileLink.getFragment('teamUser')},
},
source {
id,
dbid,
image,
}
}
}
}
}
}
assignments(first: 10000) {
edges {
node {
name
id
dbid
team_user(team_slug: $teamSlug) {
${ProfileLink.getFragment('teamUser')},
},
source {
id
dbid
image
}
}
}
}
first_response_value,
first_response {
id,
dbid,
permissions,
content,
file_data,
attribution(first: 10000) {
edges {
node {
id
dbid
name
team_user(team_slug: $teamSlug) {
${ProfileLink.getFragment('teamUser')},
},
source {
id
dbid
image
}
}
}
}
annotator {
name,
profile_image,
user {
id,
dbid,
name,
is_active
team_user(team_slug: $teamSlug) {
${ProfileLink.getFragment('teamUser')},
},
source {
id,
dbid,
image,
}
}
}
}
}
`,
},
});
|
src/components/TodoApp.js | jhegedus42/egghead-redux-playaround | // @flow
import {AddTodo} from './AddTodo.js'
import React from 'react';
import {VisibleTodoList} from './VisibleTodoList.js'
import {Footer} from './Footer.js'
import {Provider} from 'react-redux';
export const TodoApp = () :React$Element<any> => {
return (
<div>
<AddTodo />
<VisibleTodoList />
<Footer />
</div>
);
}
Provider.childContextTypes={
store:React.PropTypes.object
};
|
packages/icons/src/md/device/WifiLock.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdWifiLock(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M41 19c.56 0 1.09.08 1.63.16L48 12c-6.69-5.02-15-8-24-8S6.69 6.98 0 12l24 32 7-9.33V29c0-5.52 4.48-10 10-10zm5 13c1.1 0 2 .9 2 2v8c0 1.1-.9 2-2 2H36c-1.1 0-2-.9-2-2v-8c0-1.1.9-2 2-2v-3c0-2.76 2.24-5 5-5s5 2.24 5 5v3zm-2 0v-3c0-1.66-1.34-3-3-3s-3 1.34-3 3v3h6z" />
</IconBase>
);
}
export default MdWifiLock;
|
website/components/Navbar/utils/makeSection.js | naustudio/keystone | import React from 'react';
import Item from '../Item';
export default function makeSection (currentPath, layer, depth) {
return layer.map((section, idx) => {
const sectionStyles = depth === 1 ? styles.section : styles.subsection;
return (
<ul key={idx} css={[styles.menu, styles[`menu_depth_${depth}`]]}>
<li css={sectionStyles}>{section.section}</li>
{section.items ? section.items.map(function (item) {
const newPath = currentPath + section.slug;
if (item.items) {
return makeSection(newPath, [item], (depth + 1));
}
return (
<Item
depth={depth}
key={item.slug}
title={item.label}
url={newPath + item.slug}
/>
);
}) : null}
</ul>
);
});
};
const styles = {
menu: {
listStyle: 'none',
margin: 0,
// paddingRight: '1em',
},
menu_depth_1: {},
menu_depth_2: {},
section: {
fontSize: '1.7em',
margin: '1.8em 0 0.5em',
opacity: 0.6,
padding: `0 1rem`,
textTransform: 'uppercase',
},
subsection: {
fontSize: '1.3em',
margin: '1em 0 0.2em',
opacity: 0.6,
padding: `0 1rem 0 2rem`,
textTransform: 'uppercase',
},
};
|
src/TabbedArea.js | zanjs/react-bootstrap | import React from 'react';
import Tabs from './Tabs';
import TabPane from './TabPane';
import ValidComponentChildren from './utils/ValidComponentChildren';
import deprecationWarning from './utils/deprecationWarning';
const TabbedArea = React.createClass({
componentWillMount() {
deprecationWarning(
'TabbedArea', 'Tabs',
'https://github.com/react-bootstrap/react-bootstrap/pull/1091'
);
},
render() {
const {children, ...props} = this.props;
const tabs = ValidComponentChildren.map(children, function(child) {
const {tab: title, ...others} = child.props;
return <TabPane title={title} {...others} />;
});
return (
<Tabs {...props}>{tabs}</Tabs>
);
}
});
export default TabbedArea;
|
5.1.3/src/index.js | erikras/redux-form-docs | import React from 'react'
import { render } from 'react-dom'
import { Provider } from 'react-redux'
import store from 'redux/store'
import DevTools from './components/DevTools'
import component from './routes'
import Perf from 'react-addons-perf'
import devToolsEnabled from './devToolsEnabled'
const dest = document.getElementById('content')
window.Perf = Perf
render(
(<Provider store={store}>
<div>
{component}
{devToolsEnabled && !window.devToolsExtension && <DevTools/>}
</div>
</Provider>),
dest
)
|
src/components/review_widget_component.js | allenyin55/reading_with_Annie | import React from 'react';
import moment from 'moment-timezone';
import { Link } from 'react-router';
const ReviewWidget = ({ review, reviewer, profile,uniqueKey, onDeleteReview}) =>{
const PSTTime =moment.tz(review.dateedited, "Zulu").tz("America/Los_Angeles").format();
if (reviewer.name === profile.name) {
return (
<div className="list-group-item list-group-item-action flex-column align-items-start"
key={uniqueKey}>
<div className="d-flex w-100 justify-content-start">
<img className="p-2 align-self-start headShot" src={reviewer.picture}/>
<div className="p-2">
<h5 className="mb-1">{reviewer.name}'s review</h5>
<p className="mb-1">{review.review}</p>
<small>edited on {PSTTime.substring(0, 10)}</small>
</div>
<Link className="ml-auto p-2" to={location.pathname + "/edit/" + uniqueKey}>
Edit Review
</Link>
<div className="p-2" id="delete_review" onClick={onDeleteReview}>
Delete
</div>
</div>
</div>
);
}
else {
return (
<div className="list-group-item list-group-item-action flex-column align-items-start"
key={uniqueKey}>
<div className="d-flex w-100 justify-content-start">
<img className="align-self-start headShot" src={reviewer.picture}/>
<div className="p-2">
<h5 className="mb-1">{reviewer.name}'s review</h5>
<p className="mb-1">{review.review}</p>
<small>edited on {PSTTime.substring(0, 10)}</small>
</div>
</div>
</div>
);
}
};
export default ReviewWidget; |
example/redux/src/components/SignUp.js | iansinnott/react-static-webpack-plugin | /* @flow */
import React from 'react';
import classnames from 'classnames/bind';
import s from './SignUp.styl';
const cx = classnames.bind(s);
export class LogIn extends React.Component {
render() {
return (
<div className={cx('page')}>
<div className={cx('siteTitle')}>
<h1>Log In</h1>
</div>
<p>Log in now. It's fast and free!</p>
</div>
);
}
}
export class SignUp extends React.Component {
render() {
return (
<div className={cx('page')}>
<div className={cx('siteTitle')}>
<h1>Sign Up</h1>
</div>
<p>Sign up right here.</p>
</div>
);
}
}
|
src/index.js | CyberThugs/JavaScript-Applications-Team-Project | ///////////////////////////////////////////
// jquery and tether for bootstrap to use
// alternative is to link them in index.html
import jquery from 'jquery';
window.$ = window.jQuery = jquery;
window.Tether = require('tether');
require('bootstrap/dist/js/bootstrap');
import configureStore from './store/configureStore';
import App from './containers/app/App';
import './index.css';
const store = configureStore();
import 'bootstrap/dist/css/bootstrap.css';
import 'font-awesome/css/font-awesome.css';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
setTimeout(function() {
ReactDOM.render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('wrapper')
);
}, 0);
|
docs/app/Examples/modules/Dropdown/Types/DropdownExamplePointingTwo.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Dropdown, Menu } from 'semantic-ui-react'
const DropdownExamplePointingTwo = () => (
<Menu vertical>
<Menu.Item>
Home
</Menu.Item>
<Dropdown text='Messages' pointing='left' className='link item'>
<Dropdown.Menu>
<Dropdown.Item>Inbox</Dropdown.Item>
<Dropdown.Item>Starred</Dropdown.Item>
<Dropdown.Item>Sent Mail</Dropdown.Item>
<Dropdown.Item>Drafts (143)</Dropdown.Item>
<Dropdown.Divider />
<Dropdown.Item>Spam (1009)</Dropdown.Item>
<Dropdown.Item>Trash</Dropdown.Item>
</Dropdown.Menu>
</Dropdown>
<Menu.Item>
Browse
</Menu.Item>
<Menu.Item>
Help
</Menu.Item>
</Menu>
)
export default DropdownExamplePointingTwo
|
src/components/Profiles/ShareFamilyProfile.js | RahulDesai92/PHR | import React, { Component } from 'react';
import { Text,
View,
StyleSheet,
ActivityIndicator,
Image,
ScrollView,
KeyboardAvoidingView ,
TouchableOpacity
} from 'react-native';
import { NavigationActions } from 'react-navigation';
import customstyles from '../../../assets/styles/customstyles';
import customtext from '../../utils/customtext';
// import LoginForm from './LoginForm';
import colors from '../../utils/colors';
import { TextField } from 'react-native-material-textfield';
//import MaterialIcon from 'react-native-vector-icons/MaterialIcons';
import { RaisedTextButton } from 'react-native-material-buttons';
import Toast from 'react-native-simple-toast';
import environment from '../../utils/environment';
/*importing and using from const*/
const {
loginscreenLogoContainer,
loginscreenLogo,
loginTitle
} = customstyles;
const { login_welcome } = customtext;
const { username_label,
password_label,
login_label,
create_account_text,
create_account_link
} = customtext;
const { loginscreenregisterInput,
loginscreenregisterContainer,
loginscreenCreateAccountWrapper,
loginscreenCreateAccountText,
loginscreenCreateAccountLinkText,
loginscreenLoginContainer
} = customstyles;
const { white,
black,
electricBlue
} = colors;
const { base_url } = environment;
var member;
export default class LoginScreen extends Component {
constructor() {
super();
this.onFocus = this.onFocus.bind(this);
this.onSubmitLogin = this.onSubmitLogin.bind(this);
this.onChangeText = this.onChangeText.bind(this);
this.onSubmitUserName = this.onSubmitUserName.bind(this);
// this.onSubmitPassword = this.onSubmitPassword.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onAccessoryPress = this.onAccessoryPress.bind(this);
this.onRegistration = this.onRegistration.bind(this);
this.usernameRef = this.updateRef.bind(this, 'username');
// this.passwordRef = this.updateRef.bind(this, 'password');
this.renderPasswordAccessory = this.renderPasswordAccessory.bind(this);
this.state = {
username: '',
// password: '',
secureTextEntry: true,
};
}
validateEmail(value) {
let regex = /\w[-._\w]*@[-._\w]*\w\.\w{2,5}/;
if (regex.test(value) === true) {
return true;
} else {
return false;
}
}
onAccessoryPress() {
this.setState(({ secureTextEntry }) => ({ secureTextEntry: !secureTextEntry }));
}
onSubmitUserName() {
this.username.focus();
}
onBlur() {
let errors = {};
this.setState({ errors });
}
onFocus() {
let { errors = {} } = this.state;
for (let name in errors) {
let ref = this[name];
if (ref && ref.isFocused()) {
delete errors[name];
}
}
}
onChangeText(text) {
['username']
.map((name) => ({ name, ref: this[name] }))
.forEach(({ name, ref }) => {
if (ref.isFocused()) {
this.setState({ [name]: text });
}
});
}
onSubmitLogin(token) {
var token;
let errors = {};
['username']
.forEach((name) => {
let value = this[name].value();
if (!value) {
errors[name] = 'Should not be empty';
} else {
if ('password' === name && value.length < 6) {
errors[name] = 'Too short';
}
// if ('username' === name && !validateEmail.test(value)) {
// errors[name] = 'Invalid Email ID';
//}
}
});
this.setState({ errors });
return fetch('http://192.168.0.20:8000/fmshareReports', {
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
},
body: JSON.stringify({
email: this.state.username,
token:token,
rapidID:member
})
})
.then((response) => response.json())
.then((responseJson) => {
var message = responseJson.message;
console.log('token'+ token);
console.log("message"+responseJson.message);
if (message === 'Invalid Request !') {
Toast.show(message);
}
else {
console.log("Homepage");
Toast.show(message);
this.props.navigation.navigate('HomePage',{token:token});
}
})
.catch((error) => {
console.error(error);
});
}
updateRef(name, ref) {
this[name] = ref;
}
renderPasswordAccessory() {
let { secureTextEntry } = this.state;
let name = secureTextEntry?
'visibility':
'visibility-off';
/* return (
<MaterialIcon
size={24}
name={name}
color={TextField.defaultProps.baseColor}
onPress={this.onAccessoryPress}
suppressHighlighting
/>
);*/
}
onRegistration(){
console.log("Registerpage");
this.props.navigation.navigate('RegisterPage');
}
static navigationOptions = {
header: null,
}
render() {
var {params} = this.props.navigation.state;
//var phone = params.Phone
var token = params.token
member = params.member
let { errors = {}, secureTextEntry, ...data } = this.state;
let { username = 'username' } = data;
let { password = 'password' } = data;
return (
<KeyboardAvoidingView behavior="padding" style={loginscreenregisterContainer}>
<View style={loginscreenLogoContainer}>
<Image
style={loginscreenLogo}
source={require('../../../assets/images/fuegologo.jpg')}
/>
<Text style={loginTitle}>Please Enter Email To Share</Text>
</View>
<ScrollView>
<View style={loginscreenregisterInput}>
<TextField
ref={this.usernameRef}
value={data.username}
keyboardType='email-address'
autoCapitalize='none'
autoCorrect={false}
enablesReturnKeyAutomatically={true}
onFocus={this.onFocus}
onChangeText={this.onChangeText}
onSubmitEditing={this.onSubmitUserName}
returnKeyType='next'
label="Email"
error={errors.username}
tintColor={black}
textColor={black}
onBlur={this.onBlur}
/>
<View style={loginscreenLoginContainer}>
<RaisedTextButton
//onPress={this.onSubmitLogin}
onPress={()=>this.onSubmitLogin(token)}
title="Share"
color={electricBlue}
titleColor={white}
/>
</View>
</View>
</ScrollView>
{ /* Due to parent child relation of (this.props.navigation.navigate)
page is not navigating from LoginScreen to RegisterScreen */}
{/* <LoginForm /> */}
</KeyboardAvoidingView>
);
}
} |
src/containers/WorldsBetween.js | mattschwartz/mattschwartz | import React from 'react'
import StoneQuest from '../components/StoneQuest/StoneQuest'
import '../styles/worldsBetween.css'
import backgroundImage from '../res/stonequestPreview.png'
class WorldsBetween extends React.Component {
componentDidMount() {
document.title = 'Worlds Between Blood'
}
render() {
return (
<div className="worlds-between">
<div className="banner" style={{ backgroundImage: `url(${backgroundImage})` }}>
<div className="overlay" />
</div>
<div className="container">
<div className="title-container">
<h1 className="heading">Worlds Between Blood</h1>
<hr className="divider" />
<div className="subheading">written and designed by Matt Schwartz</div>
</div>
<h3 className="section-header">About</h3>
<p><em>As it pertains to the on-going work of</em> <strong>Worlds Between Blood</strong>:</p>
<p>Details about the story and game mechanics are still too early in development to disclose at this time. The story points that I have already began working on are exciting enough for me to want to delay exposing these details for fear of ruining the story for anyone. I am just as excited to read it as I am to write it.</p>
<p>The mechanics of the game are still forming and will evolve with the story itself. It is vital to me that the mechanics and the story are complements. Thus, this page mostly exists as homage to the project I started many years ago: StoneQuest.</p>
<StoneQuest />
</div>
</div>
)
}
}
export default WorldsBetween
|
tp-4/euge/src/pages/home/HomePage.js | jpgonzalezquinteros/sovos-reactivo-2017 | import React from 'react';
import { Layout, Icon } from 'antd';
const { Header, Content } = Layout;
const HomePage = () => (
<Layout>
<Header style={{ background: '#fff', padding: 0 }}>
<Icon
className="trigger"
/>
</Header>
<Content style={{ margin: '24px 16px', padding: 24, background: '#fff', minHeight: 280 }}>
Content
</Content>
</Layout>
);
export default HomePage;
|
src/components/CityList.js | tienwei/weather-app | import React from 'react';
import PropTypes from 'prop-types';
import City from './City';
import './CityList.css';
const CityList = ({isFetching, cities = [], error = null}) => {
let resultView;
if(error) {
resultView = <tr><td colSpan={3}><b style={{color: 'red'}}>{error.message}</b></td></tr>;
} else {
resultView = cities.map(city =>
<City key={city.id}
{...city}
/>
);
}
const listView = isFetching
? (<p>Fetching data...</p>)
: (
<table className='weather-board'>
<thead>
<tr>
<th>Name</th>
<th>°C</th>
<th>Condition</th>
</tr>
</thead>
<tbody>
{resultView}
</tbody>
</table>
);
return (<div style={{display: 'flex', justifyContent: 'center'}}>{listView}</div>)
}
CityList.PropTypes = {
cities: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
name: PropTypes.string.isRequired,
temperature: PropTypes.number.isRequired,
condition: PropTypes.string.isRequired
}).isRequired).isRequired
}
export default CityList;
|
assets/jqwidgets/demos/react/app/grid/positioning/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxGrid from '../../../jqwidgets-react/react_jqxgrid.js';
import JqxRadioButton from '../../../jqwidgets-react/react_jqxradiobutton.js';
class App extends React.Component {
componentDidMount() {
this.refs.top.on('checked', () => {
this.refs.myGrid.everpresentrowposition('top');
});
this.refs.bottom.on('checked', () => {
this.refs.myGrid.everpresentrowposition('bottom');
});
this.refs.topAbove.on('checked', () => {
this.refs.myGrid.everpresentrowposition('topAboveFilterRow');
});
}
render() {
let source =
{
localdata: generatedata(20),
datafields:
[
{ name: 'name', type: 'string' },
{ name: 'productname', type: 'string' },
{ name: 'available', type: 'bool' },
{ name: 'date', type: 'date' },
{ name: 'quantity', type: 'number' }
],
datatype: 'array'
};
let dataAdapter = new $.jqx.dataAdapter(source);
let columns =
[
{ text: 'Name', columntype: 'textbox', filtertype: 'input', datafield: 'name', width: 215 },
{ text: 'Product', filtertype: 'checkedlist', datafield: 'productname', width: 220 },
{ text: 'Ship Date', datafield: 'date', filtertype: 'range', width: 210, cellsalign: 'right', cellsformat: 'd' },
{ text: 'Qty.', datafield: 'quantity', filtertype: 'number', cellsalign: 'right' }
];
return (
<div>
<JqxGrid ref='myGrid'
width={850} source={dataAdapter} filterable={true}
showeverpresentrow={true} showfilterrow={true} editable={true}
everpresentrowposition={'top'} columns={columns}
selectionmode={'multiplecellsadvanced'}
/>
<br />
<JqxRadioButton ref='top' checked={true}>Top Position</JqxRadioButton>
<JqxRadioButton ref='topAbove'>Top Position Above Filter Row</JqxRadioButton>
<JqxRadioButton ref='bottom'>Bottom Position</JqxRadioButton>
</div>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/svg-icons/editor/border-left.js | xmityaz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let EditorBorderLeft = (props) => (
<SvgIcon {...props}>
<path d="M11 21h2v-2h-2v2zm0-4h2v-2h-2v2zm0-12h2V3h-2v2zm0 4h2V7h-2v2zm0 4h2v-2h-2v2zm-4 8h2v-2H7v2zM7 5h2V3H7v2zm0 8h2v-2H7v2zm-4 8h2V3H3v18zM19 9h2V7h-2v2zm-4 12h2v-2h-2v2zm4-4h2v-2h-2v2zm0-14v2h2V3h-2zm0 10h2v-2h-2v2zm0 8h2v-2h-2v2zm-4-8h2v-2h-2v2zm0-8h2V3h-2v2z"/>
</SvgIcon>
);
EditorBorderLeft = pure(EditorBorderLeft);
EditorBorderLeft.displayName = 'EditorBorderLeft';
EditorBorderLeft.muiName = 'SvgIcon';
export default EditorBorderLeft;
|
src/containers/SecurityCheckerPage.js | great-design-and-systems/cataloguing-app | import * as actions from '../actions/SecurityActions';
import PropTypes from 'prop-types';
import React from 'react';
import { bindActionCreators } from 'redux';
import { browserHistory } from 'react-router';
import { connect } from 'react-redux';
export class SecurityCheckerPage extends React.Component {
constructor(props) {
super(props);
this.thisIsRoleAllowed = this.isRoleAllowed.bind(this);
}
componentDidMount() {
if (!this.props.security.isAuthenticated) {
browserHistory.replace('/login');
} else if (!this.isRoleAllowed()) {
this.props.actions.notAuthorizedAccess(this.props.router.getCurrentLocation().pathname);
this.props.router.goBack();
}
}
componentDidUpdate() {
if (!this.isRoleAllowed()) {
this.props.actions.notAuthorizedAccess(this.props.router.getCurrentLocation().pathname);
this.props.router.goBack();
}
}
isRoleAllowed() {
const Component = this.props.children.type.WrappedComponent;
const { access } = Component.defaultProps;
return access.indexOf(this.props.security.role) > -1;
}
render() {
if (this.props.security.isAuthenticated) {
if (this.thisIsRoleAllowed()) {
return this.props.children;
}
else {
return null;
}
} else {
return null;
}
}
}
SecurityCheckerPage.propTypes = {
security: PropTypes.object.isRequired,
children: PropTypes.element,
router: PropTypes.object.isRequired,
actions: PropTypes.object.isRequired
};
function mapStateToProps(state) {
return { security: state.security };
}
function mapDispatchToProps(dispatch) {
return { actions: bindActionCreators(actions, dispatch) };
}
export const ConnectSecurityCheckerPage = connect(mapStateToProps, mapDispatchToProps)(SecurityCheckerPage);
|
enrolment-ui/src/modules/Projects/ProjectTerminationModal.js | overture-stack/enrolment | import React from 'react';
import { connect } from 'react-redux';
import { Modal } from 'react-bootstrap';
import { withRouter } from 'react-router-dom';
import { toggleProjectTerminationModal } from './redux';
import ModalTerminationForm from './components/ModalTerminationForm';
import { fetchProjects, terminateProject, uiResetProjectsTab } from '../Projects/redux';
import { fetchApplications } from '../Applications/redux';
import { fetchAllProjectUsers } from '../ProjectUsers/redux';
const ProjectTerminationModal = props => {
const {
projectTerminationModal: { showModal },
toggleModal,
fetchApplications,
fetchProjects,
fetchAllProjectUsers,
resetProjectsTabUi,
terminateProject,
location: { pathname }
} = props;
const onSuccess = () => {
fetchApplications();
fetchProjects();
toggleModal();
// If we're on dashboard, reload the project users as well
if (pathname === "/dashboard") {
fetchAllProjectUsers();
}
// If we're on the project tab, deselect the project
if (pathname === "/projects") {
resetProjectsTabUi();
}
};
const onSubmit = data => {
terminateProject(data.project, onSuccess);
};
return (
<Modal
centered
show={showModal}
onHide={toggleModal}
>
<Modal.Header>
<Modal.Title>Project Termination</Modal.Title>
</Modal.Header>
<ModalTerminationForm onSubmit={onSubmit} />
</Modal>
);
};
ProjectTerminationModal.displayName = 'ProjectTerminationModal';
const mapStateToProps = state => {
return {
projectTerminationModal: state.projectTerminationModal,
profile: state.profile.data,
};
};
const mapDispatchToProps = dispatch => {
return {
fetchApplications: () => fetchApplications(dispatch),
fetchProjects: () => fetchProjects(dispatch),
fetchAllProjectUsers: () => fetchAllProjectUsers(dispatch),
resetProjectsTabUi: () => dispatch(uiResetProjectsTab()),
toggleModal: () => dispatch(toggleProjectTerminationModal()),
terminateProject: (id, next) => terminateProject(dispatch, id, next),
};
};
export default withRouter(connect(mapStateToProps, mapDispatchToProps)(ProjectTerminationModal));
|
frontend/client/index.js | rkuykendall/weeklypulls | import React from 'react';
import ReactDOM from 'react-dom';
import App from './components/app';
import Store from './store';
const store = new Store();
ReactDOM.render(<App store={store} />, document.getElementById('root'));
|
gui/src/app/containers/loading-spinner-container.js | mbonvini/LambdaSim | import React from 'react';
import { connect } from 'react-redux';
import LoadingSpinner from '../components/loading-spinner';
import log from 'loglevel';
const LoadingSpinnerContainer = React.createClass({
render: function() {
return (
<LoadingSpinner loading={this.props.loading}/>
);
}
});
const mapStateToProps = function(store) {
return {
loading: store.loading
};
};
export default connect(mapStateToProps)(LoadingSpinnerContainer); |
src/components/droptoolbutton/Droptoolbutton.js | Convicted202/PixelShape | import './droptoolbutton.styl';
import React, { Component } from 'react';
import decorateWithKeyBindings from '../../helpers/KeyBindings';
import classNames from 'classnames';
import { toolHotkeys } from '../../defaults/tools';
// TODO: might need to use more generic reusable Toolbutton.js component
// for active button and dropdown buttons
class DropToolButton extends Component {
constructor (props) {
super(props);
this.state = {
activeTool: this.props.tool,
activeIcon: this.props.icon
};
this.dropdownLength = this.props.dropdownTools && this.props.dropdownTools.length;
this.toolWidth = 70;
}
componentDidMount () {
if (this.props.dropdownTools) {
this.props.dropdownTools.forEach(toolObj => {
this.bindKey(toolHotkeys[toolObj.tool], this.setActiveTool.bind(this, toolObj));
});
} else
this.bindKey(toolHotkeys[this.props.tool], this.props.setTool.bind(null, this.props.tool));
}
setActiveTool (toolObj) {
this.setState({
activeTool: toolObj.tool,
activeIcon: toolObj.icon
});
this.props.setTool(toolObj.tool);
}
getActiveTool () {
const classes = classNames(
'toolbutton__active-button',
{
'tooltipshift': this.props.dropdownTools && this.props.dropdownTools.length
}
);
return (
<div className={classes} onClick={this.props.setTool.bind(null, this.state.activeTool)} data-tooltip={this.props.name} data-shortcut={`(${toolHotkeys[this.props.tool]})`}>
<svg className="toolbutton__icon" viewBox="0 0 24 24" width="40" height="40">
<use xlinkHref={`#${this.state.activeIcon}`}></use>
</svg>
</div>
);
}
getDropdownTools () {
return this.props.dropdownTools
.map((toolObj, key) => {
const classes = classNames(
'toolbutton-dropdown__toolbutton',
'tooltip-bottom',
{
'active': this.state.activeTool === toolObj.tool
});
return (
<li
key={key}
className={classes}
onClick={this.setActiveTool.bind(this, toolObj)}
data-tooltip={toolObj.name}
data-shortcut={`(${toolHotkeys[toolObj.tool]})`}>
<svg className="toolbutton-dropdown__toolbutton__icon" viewBox="0 0 24 24" width="40" height="40">
<use xlinkHref={`#${toolObj.icon}`}></use>
</svg>
</li>
);
});
}
getDropDown () {
if (this.props.dropdownTools) {
return (
<ul
className="toolbutton-dropdown"
style={{ width: `${this.dropdownLength * this.toolWidth}px` }}>
{ this.getDropdownTools() }
</ul>
);
}
return null;
}
render () {
const classes = classNames(
'toolbutton',
'tooltip-right',
{
'active': this.state.activeTool === this.props.activeTool
});
return (
<li className={classes}>
{ this.getActiveTool() }
{ this.getDropDown() }
</li>
);
}
}
export default decorateWithKeyBindings(DropToolButton);
|
src/svg-icons/device/battery-90.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceBattery90 = (props) => (
<SvgIcon {...props}>
<path fillOpacity=".3" d="M17 5.33C17 4.6 16.4 4 15.67 4H14V2h-4v2H8.33C7.6 4 7 4.6 7 5.33V8h10V5.33z"/><path d="M7 8v12.67C7 21.4 7.6 22 8.33 22h7.33c.74 0 1.34-.6 1.34-1.33V8H7z"/>
</SvgIcon>
);
DeviceBattery90 = pure(DeviceBattery90);
DeviceBattery90.displayName = 'DeviceBattery90';
DeviceBattery90.muiName = 'SvgIcon';
export default DeviceBattery90;
|
src/main/resources/code/react/Apps/ManageRadars/Pages/ManageAssociatedRadarTemplatesPage/index.js | artieac/technologyradar | import React from 'react';
import ReactDOM from 'react-dom';
import Reflux from 'reflux';
import createReactClass from 'create-react-class';
import { connect } from "react-redux";
import { addAssociatedRadarTemplatesToState, addSharedRadarTemplatesToState, addSelectedRadarTemplateToState } from '../../redux/RadarTemplateReducer';
import { addCurrentUserToState} from '../../../redux/CommonUserReducer';
import ViewRadarTemplateControl from './ViewRadarTemplateControl';
import { RadarTemplateRepository } from '../../../../Repositories/RadarTemplateRepository';
import { UserRepository } from '../../../../Repositories/UserRepository';
import DivTableComponent from '../../../../components/DivTableComponent';
import { radarTemplateColumns } from './radarTemplateColumns';
class ManageAssociatedRadarTemplatesPage extends React.Component{
constructor(props){
super(props);
this.state = {
};
this.radarTemplateRepository = new RadarTemplateRepository();
this.userRepository = new UserRepository();
this.handleGetOtherUsersSharedRadarTemplatesSuccess = this.handleGetOtherUsersSharedRadarTemplatesSuccess.bind(this);
this.handleGetAssociatedRadarTemplatesSuccess = this.handleGetAssociatedRadarTemplatesSuccess.bind(this);
this.handleGetCurrentUserSuccess = this.handleGetCurrentUserSuccess.bind(this);
this.viewRadarTemplate = this.viewRadarTemplate.bind(this);
this.handleAssociateRadarTemplateChange = this.handleAssociateRadarTemplateChange.bind(this);
this.handleAssociatedRadarTemplateSuccess = this.handleAssociatedRadarTemplateSuccess.bind(this);
this.canAssociateRadarTemplates = this.canAssociateRadarTemplates.bind(this);
}
componentDidMount(){
var clearedRadarTemplate = {};
this.props.storeSelectedRadarTemplate(clearedRadarTemplate);
this.userRepository.getUser(this.handleGetCurrentUserSuccess);
}
handleGetCurrentUserSuccess(currentUser){
this.props.storeCurrentUser(currentUser);
this.radarTemplateRepository.getAssociatedRadarTemplates(currentUser.id, this.handleGetAssociatedRadarTemplatesSuccess);
}
handleGetAssociatedRadarTemplatesSuccess(associatedRadarTemplates){
this.props.storeAssociatedRadarTemplates(associatedRadarTemplates);
this.radarTemplateRepository.getOtherUsersSharedRadarTemplates(this.props.currentUser.id, this.handleGetOtherUsersSharedRadarTemplatesSuccess);
}
handleGetOtherUsersSharedRadarTemplatesSuccess(sharedRadarTemplates){
for(var i = 0; i < this.props.associatedRadarTemplates.length; i++){
var associatedRadarTemplate = this.props.associatedRadarTemplates[i];
var foundMatch = false;
for(var j = 0; j < sharedRadarTemplates.length; j++){
if(associatedRadarTemplate.id == sharedRadarTemplates[j].id){
foundMatch = true;
}
}
if(foundMatch == false){
sharedRadarTemplates.push(associatedRadarTemplate);
}
}
this.props.storeSharedRadarTemplates(sharedRadarTemplates);
if(sharedRadarTemplates.length > 0){
this.props.storeSelectedRadarTemplate(sharedRadarTemplates[0]);
}
this.forceUpdate();
}
viewRadarTemplate(event, rowData){
this.props.storeSelectedRadarTemplate(rowData);
this.forceUpdate();
}
handleAssociateRadarTemplateChange(event, rowData){
const { currentUser, associatedRadarTemplates} = this.props;
if(event.target.checked==true){
if(this.canAssociateRadarTemplates(currentUser, associatedRadarTemplates)==true){
this.radarTemplateRepository.associateRadarTemplate(currentUser.id, rowData.id, true, this.handleAssociatedRadarTemplateSuccess);
this.forceUpdate();
}
else{
alert("You are only allowed to use " + this.props.currentUser.canHaveNAssociatedRadarTemplates + " types from other users. Please uncheck another before trying to add this one.");
}
} else {
this.radarTemplateRepository.associateRadarTemplate(currentUser.id, rowData.id, false, this.handleAssociatedRadarTemplateSuccess);
this.forceUpdate();
}
}
handleAssociatedRadarTemplateSuccess(){
this.radarTemplateRepository.getAssociatedRadarTemplates(this.props.currentUser.id, this.props.storeAssociatedRadarTemplates);
}
canAssociateRadarTemplates(currentUser, associatedRadarTemplates) {
var retVal = false;
if(currentUser !== undefined && associatedRadarTemplates !== undefined){
if(associatedRadarTemplates.length < currentUser.canHaveNAssociatedRadarTemplates){
retVal = true;
}
}
return retVal;
}
render() {
const { currentUser, sharedRadarTemplates, associatedRadarTemplates } = this.props;
return (
<div className="bodyContent">
<div className="contentPageTitle">
<label>Associate Radar Templates From Others</label>
</div>
<p>Discover Radar Templates that others have created</p>
<div className="row">
<div className="col-md-6">
<DivTableComponent data={sharedRadarTemplates} cols={ radarTemplateColumns(currentUser, associatedRadarTemplates, this.viewRadarTemplate, this.handleAssociateRadarTemplateChange) } />
</div>
<div className="col-md-6">
<ViewRadarTemplateControl parentContainer={this} editMode={false}/>
</div>
</div>
</div>
);
}
};
function mapStateToProps(state) {
return {
sharedRadarTemplates: state.radarTemplateReducer.sharedRadarTemplates,
associatedRadarTemplates: state.radarTemplateReducer.associatedRadarTemplates,
currentUser: state.userReducer.currentUser
};
}
const mapDispatchToProps = dispatch => {
return {
storeSharedRadarTemplates : sharedRadarTemplates => { dispatch(addSharedRadarTemplatesToState(sharedRadarTemplates))},
storeSelectedRadarTemplate : radarTemplate => { dispatch(addSelectedRadarTemplateToState(radarTemplate))},
storeAssociatedRadarTemplates : associatedRadarTemplates => { dispatch(addAssociatedRadarTemplatesToState(associatedRadarTemplates))},
storeCurrentUser : currentUser => { dispatch(addCurrentUserToState(currentUser))}
}
};
export default connect(mapStateToProps, mapDispatchToProps)(ManageAssociatedRadarTemplatesPage); |
reactJS/my-music-player-project/src/components/MusicPlayer.js | CoderKevinZhang/web-front-end-practice | import React from 'react';
// set duration of current music
let duration = '-';
class MusicPlayer extends React.Component {
constructor(props) {
super(props);
this.state = {
progress: '-'
};
this.changeProgress = this.changeProgress.bind(this);
}
componentDidMount() {
$('#play').bind($.jPlayer.event.timeupdate, (e) => {
duration = e.jPlayer.status.duration;
this.setState({
progress: e.jPlayer.status.currentPercentAbsolute
});
});
}
componentWillUnmount() {
$('#play').unbind($.jPlayer.event.timeupdate);
}
changeProgress(e) {
let progressBar = this.refs.progressBar,
realProgress = (e.clientX - progressBar.getBoundingClientRect().left) / progressBar.clientWidth;
$('#play').jPlayer('play', duration * realProgress);
}
render() {
let dotLeft = this.state.progress * this.props.barWidth / 100 + 88;
return (
<div className="music-player">
{/* Widget: Music Player Progress Bar --start */}
<div className="progress-bar" onClick={this.changeProgress} ref="progressBar"
style={{width: `${this.props.barWidth}px`, left: `${this.props.barLeft}px`}}>
<div className="progress" style={{width: `${this.state.progress}%`, background: this.props.barColor}}></div>
</div>
<div className="progress-dot" style={{left: `${dotLeft}px`}}></div>
<div id="play"></div>
{/* Widget: Music Player Progress Bar --end */}
{/*Widget: Music Player Play Widgets --start*/}
<div className="player-widgets">
<a href="#" className="step-backward"><i className="fa fa-step-backward fa-2x" aria-hidden="true"></i></a>
<a href="#" className="play"><i className="fa fa-play fa-2x" aria-hidden="true"></i></a>
<a href="#" className="step-forward"><i className="fa fa-step-forward fa-2x" aria-hidden="true"></i></a>
<a href="#" className="pause"><i className="fa fa-pause fa-2x" aria-hidden="true"></i></a>
<a href="#" className="random"><i className="fa fa-random fa-2x" aria-hidden="true"></i></a>
<a href="#" className="repeat"><img src="../images/repeat.png"/></a>
<a href="#" className="repeat-one"><img src="../images/repeat-one.png"/></a>
</div>
{/*Widget: Music Player Play Widgets --end*/}
</div>
);
}
}
MusicPlayer.defaultProps = {
barColor: '#d81e06',
barWidth: 600
};
export default MusicPlayer;
|
samples/react/app/components/Header/index.js | IntelliSearch/search-client | import React from 'react';
import { FormattedMessage } from 'react-intl';
import A from './A';
import Img from './Img';
import NavBar from './NavBar';
import HeaderLink from './HeaderLink';
import Banner from './banner.jpg';
import messages from './messages';
/* eslint-disable react/prefer-stateless-function */
class Header extends React.Component {
render() {
return (
<div>
<A href="https://twitter.com/mxstbr">
<Img src={Banner} alt="react-boilerplate - Logo" />
</A>
<NavBar>
<HeaderLink to="/">
<FormattedMessage {...messages.home} />
</HeaderLink>
<HeaderLink to="/features">
<FormattedMessage {...messages.features} />
</HeaderLink>
</NavBar>
</div>
);
}
}
export default Header;
|
features/apimgt/org.wso2.carbon.apimgt.publisher.feature/src/main/resources/publisher/source/index.js | thusithak/carbon-apimgt | /*
* Copyright (c) 2017, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* WSO2 Inc. licenses this file to you under the Apache License,
* Version 2.0 (the "License"); you may not use this file except
* in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import ReactDOM from 'react-dom'
import React from 'react'
import Publisher from "./src/App.js"
import 'typeface-roboto'
import 'material-design-icons'
import 'material-ui-icons'
import {MuiThemeProvider, createMuiTheme} from 'material-ui/styles';
const theme = createMuiTheme({
palette: {
type: 'light', // Switching the dark mode on is a single property value change.
},
});
ReactDOM.render(<MuiThemeProvider theme={theme}>
<Publisher/>
</MuiThemeProvider>, document.getElementById("react-root")); |
src/components/controller.js | LaserWeb/lw.controller | // Copyright 2017 Todd Fleming
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
import React from 'react';
import ReactDOM from 'react-dom';
import { StringInput, NumberInput, SelectInput, Field } from './fields';
import Log from './log';
import CommandField from './command-field';
function adjustFeed(settings, feed) {
if (settings.toolFeedUnits === 'mm/s')
return feed * 60;
else
return feed;
}
function formatNumber(value) {
if (isNaN(value))
return ' NaN';
else
return (value < 0 ? '-' : ' ') + (' ' + Math.abs(value).toFixed(2)).slice(-7);
}
function numberSetting(name, settings, dispatchSetSettingsAttrs) {
return { type: Field, props: { Input: NumberInput, attrs: settings, setAttrs: dispatchSetSettingsAttrs, name } }
}
export class WPosField extends React.Component {
componentWillMount() {
this.onChange = this.onChange.bind(this);
this.onBlur = this.onBlur.bind(this);
this.onKeyDown = this.onKeyDown.bind(this);
}
getValue() {
return this.props.com['wpos-' + this.props.axis];
}
componentDidMount() {
this.componentDidUpdate();
}
componentDidUpdate() {
if (this.changed)
return;
let node = ReactDOM.findDOMNode(this);
let v = formatNumber(this.getValue());
if (node.value != v)
node.value = v;
}
onChange(e) {
this.changed = true;
}
onBlur(e) {
if (!this.changed)
return;
let { axis, com, comComponent } = this.props;
let cmd = 'G10 L20 P0';
for (let a of com.axes)
if (a === axis)
cmd += ' ' + a + (e.target.value || 0);
else
cmd += ' ' + a + (com['wpos-' + a] || 0);
comComponent.runCommand(cmd);
e.target.value = formatNumber(e.target.value);
this.changed = false;
}
onKeyDown(e) {
if (e.key === 'Enter') {
e.preventDefault();
e.stopPropagation();
this.onBlur(e);
} else if (e.key === 'Escape' && this.changed) {
e.preventDefault();
e.stopPropagation();
this.changed = false;
this.componentDidUpdate(e);
}
}
render() {
let { axis, com, comComponent, ...rest } = this.props;
return <input onChange={this.onChange} onBlur={this.onBlur} onKeyDown={this.onKeyDown} {...rest} />;
}
}; // WPosField
function getFields(controller) {
let { settings, com, comComponent, dispatchSetSettingsAttrs } = controller.props;
return {
'log': { type: Log },
'command': {
type: CommandField,
props: {
onExec: cmd => comComponent.runCommand(cmd),
ref: field => controller.commandField = field,
disabled: !com.serverConnected || !com.machineConnected || com.playing
}
},
'open-gcode': { type: 'input', style: { opacity: 0 }, props: { type: 'file', accept: '.gcode', value: '', onChange: e => controller.loadGcode(e) } },
'ctlJog1Dist': numberSetting('ctlJog1Dist', settings, dispatchSetSettingsAttrs),
'ctlJog2Dist': numberSetting('ctlJog2Dist', settings, dispatchSetSettingsAttrs),
'ctlJog3Dist': numberSetting('ctlJog3Dist', settings, dispatchSetSettingsAttrs),
'ctlJogKeyboardDist': numberSetting('ctlJogKeyboardDist', settings, dispatchSetSettingsAttrs),
'ctlJog1Feed': numberSetting('ctlJog1Feed', settings, dispatchSetSettingsAttrs),
'ctlJog2Feed': numberSetting('ctlJog2Feed', settings, dispatchSetSettingsAttrs),
'ctlJog3Feed': numberSetting('ctlJog3Feed', settings, dispatchSetSettingsAttrs),
'ctlJogKeyboardFeed': numberSetting('ctlJogKeyboardFeed', settings, dispatchSetSettingsAttrs),
'wpos-x': { type: WPosField, props: { axis: 'x', com, comComponent, disabled: !controller.values['enable-modify-offsets'] } },
'wpos-y': { type: WPosField, props: { axis: 'y', com, comComponent, disabled: !controller.values['enable-modify-offsets'] } },
'wpos-z': { type: WPosField, props: { axis: 'z', com, comComponent, disabled: !controller.values['enable-modify-offsets'] } },
'wpos-a': { type: WPosField, props: { axis: 'a', com, comComponent, disabled: !controller.values['enable-modify-offsets'] } },
};
};
const buttons = {
'home-all': { click(controller, { comComponent, settings }) { comComponent.runCommand(settings.gcodeHoming) } },
'run-job': { click(controller, { comComponent }) { comComponent.runJob(controller.gcode.content) } },
'pause-job': { click(controller, { comComponent }) { comComponent.pauseJob() } },
'resume-job': { click(controller, { comComponent }) { comComponent.resumeJob() } },
'abort-job': { click(controller, { comComponent }) { comComponent.abortJob() } },
'clear-alarm': { click(controller, { comComponent }) { comComponent.clearAlarm(2) } },
'set-zero': { click(controller, { comComponent }) { comComponent.setZero('all') } },
'check-size': { click(controller, { comComponent }) { console.log('!!!check-size'); } },
'jog': {
click(controller, { comComponent, settings }, { }, { axis, index, negative }) {
comComponent.jog(
axis,
settings['ctlJog' + index + 'Dist'] * (negative ? -1 : 1),
adjustFeed(settings, settings['ctlJog' + index + 'Feed']))
}
},
'set-axis-0': {
click(controller, { comComponent, com }, { }, { axis }) {
let cmd = 'G10 L20 P0';
for (let a of com.axes)
if (a === axis)
cmd += ' ' + a + 0;
else
cmd += ' ' + a + (com['wpos-' + a] || 0);
comComponent.runCommand(cmd);
}
},
'set-axis-div2': {
click(controller, { comComponent, com }, { }, { axis }) {
let cmd = 'G10 L20 P0';
for (let a of com.axes)
if (a === axis)
cmd += ' ' + a + (com['wpos-' + a] || 0) / 2;
else
cmd += ' ' + a + (com['wpos-' + a] || 0);
comComponent.runCommand(cmd);
}
},
};
export default class Controller extends React.Component {
constructor() {
super();
this.state = {
width: 0,
height: 0,
contentWidth: 0,
contentHeight: 0,
elements: [],
visibility: 'hidden'
};
this.transform = '';
this.buttons = {};
this.values = {};
}
componentWillMount() {
this.onKeyDown = this.onKeyDown.bind(this);
}
componentDidMount() {
this.mounted = true;
let node = ReactDOM.findDOMNode(this);
this.iframe = node.children[0];
let checkResize = () => {
if (!this.mounted)
return;
let { width, height } = node.getBoundingClientRect();
let newState = { width, height };
if (newState.width !== this.state.width || newState.height !== this.state.height)
this.setState(newState);
requestAnimationFrame(checkResize);
};
checkResize();
this.receiveMessage = e => {
if (e.source !== this.iframe.contentWindow)
return;
if (e.data.type === 'loaded')
this.setState({
contentWidth: e.data.width, contentHeight: e.data.height,
elements: e.data.elements
});
else if (e.data.type === 'ackSetTransform' && this.state.visibility !== 'visible')
this.setState({ visibility: 'visible' });
else if (e.data.type === 'mouse') {
let button = this.buttons[e.data.id];
if (button) {
let event = button.button[e.data.event];
if (event)
event(this, this.props, e.data, button.elem);
}
}
// console.log(e.data);
};
window.addEventListener("message", this.receiveMessage, false);
}
componentWillUnmount() {
this.mounted = false;
window.removeEventListener("message", this.receiveMessage, false);
}
shouldComponentUpdate(nextProps, nextState) {
if (nextState.elements.length && (this.settings !== nextProps.settings || this.com !== nextProps.com || this.gcode !== nextProps.gcode)) {
let settings = this.settings = nextProps.settings;
let com = this.com = nextProps.com;
let gcode = this.gcode = nextProps.gcode;
let locked = !com.serverConnected || !com.machineConnected || com.alarm;
let values = this.values = {
...settings, ...com,
'mpos-x': com['wpos-x'] + com['work-offset-x'],
'mpos-y': com['wpos-y'] + com['work-offset-y'],
'mpos-z': com['wpos-z'] + com['work-offset-z'],
'mpos-a': com['wpos-a'] + com['work-offset-a'],
'gcodeLoaded': gcode.content.length > 0,
locked,
'enable-home-all': !locked && !com.playing && settings.gcodeHoming !== '',
'enable-run-job': !locked && !com.playing && gcode.content.length > 0,
'enable-pause-job': !locked && com.playing && !com.paused,
'enable-resume-job': !locked && com.playing && com.paused,
'enable-abort-job': !locked && com.playing,
'enable-clear-alarm': com.serverConnected && com.machineConnected && com.alarm,
'enable-modify-offsets': !locked && (!com.playing || com.m0),
'enable-check-size': !locked && !com.playing,
'enable-jog': !locked && (!com.playing || com.m0),
};
this.iframe.contentWindow.postMessage({ type: 'setValues', values }, '*');
return true;
}
if (nextState !== this.state)
return true;
return false;
}
componentWillUpdate(nextProps, nextState) {
let { width, height, contentWidth, contentHeight } = nextState;
let transform = '';
if (width && height && contentWidth && contentHeight)
transform = 'scale(' + Math.min(width / contentWidth, height / contentHeight) + ')';
if (this.transform !== transform) {
this.transform = transform;
if (this.iframe)
this.iframe.contentWindow.postMessage({ type: 'setTransform', transform }, '*');
}
}
onKeyDown(e) {
if (e.key === 'Escape' && this.commandField) {
e.preventDefault();
e.stopPropagation();
ReactDOM.findDOMNode(this.commandField).focus();
}
}
render() {
let { width, height, contentWidth, contentHeight, elements } = this.state;
let controls = [];
let fields = getFields(this);
for (let elem of elements) {
if (elem.type === 'field') {
let { name, left, top, width, height, font } = elem;
let field = fields[name] || { type: 'input', props: { value: "unrecognized", readOnly: true } };
controls.push(<field.type
key={elem.id} {...field.props}
style={{ position: 'absolute', left, top, width, height, font, ...field.style }} />);
} else if (elem.type === 'button') {
if (buttons[elem.action])
this.buttons[elem.id] = { elem, button: buttons[elem.action] };
}
}
return (
<div onKeyDown={this.onKeyDown} style={{
position: 'absolute', left: 0, top: 0, width: '100%', height: '100%',
visibility: this.state.visibility
}}>
<iframe
width={width} height={height} style={{ border: 'none' }}
referrerPolicy='no-referrer' sandbox='allow-scripts'
src={this.props.src}
/>
<div style={{
position: 'absolute', left: 0, top: 0, transformOrigin: 'top left',
transform: this.transform, visibility: this.state.visibility
}}>
{controls}
</div>
</div>);
}
loadGcode(e) {
for (let file of e.target.files) {
let reader = new FileReader;
reader.onload = () => this.props.dispatchSetGcode(reader.result);
reader.readAsText(file);
}
}
} // Controller
|
src/svg-icons/image/filter-vintage.js | owencm/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFilterVintage = (props) => (
<SvgIcon {...props}>
<path d="M18.7 12.4c-.28-.16-.57-.29-.86-.4.29-.11.58-.24.86-.4 1.92-1.11 2.99-3.12 3-5.19-1.79-1.03-4.07-1.11-6 0-.28.16-.54.35-.78.54.05-.31.08-.63.08-.95 0-2.22-1.21-4.15-3-5.19C10.21 1.85 9 3.78 9 6c0 .32.03.64.08.95-.24-.2-.5-.39-.78-.55-1.92-1.11-4.2-1.03-6 0 0 2.07 1.07 4.08 3 5.19.28.16.57.29.86.4-.29.11-.58.24-.86.4-1.92 1.11-2.99 3.12-3 5.19 1.79 1.03 4.07 1.11 6 0 .28-.16.54-.35.78-.54-.05.32-.08.64-.08.96 0 2.22 1.21 4.15 3 5.19 1.79-1.04 3-2.97 3-5.19 0-.32-.03-.64-.08-.95.24.2.5.38.78.54 1.92 1.11 4.2 1.03 6 0-.01-2.07-1.08-4.08-3-5.19zM12 16c-2.21 0-4-1.79-4-4s1.79-4 4-4 4 1.79 4 4-1.79 4-4 4z"/>
</SvgIcon>
);
ImageFilterVintage = pure(ImageFilterVintage);
ImageFilterVintage.displayName = 'ImageFilterVintage';
ImageFilterVintage.muiName = 'SvgIcon';
export default ImageFilterVintage;
|
examples/reset-values/app.js | yesmeck/formsy-react | import React from 'react';
import ReactDOM from 'react-dom';
import { Form } from 'formsy-react';
import MyInput from './../components/Input';
import MySelect from './../components/Select';
const user = {
name: 'Sam',
free: true,
hair: 'brown'
};
const App = React.createClass({
submit(data) {
alert(JSON.stringify(data, null, 4));
},
resetForm() {
this.refs.form.reset();
},
render() {
return (
<Formsy.Form ref="form" onSubmit={this.submit} className="form">
<MyInput name="name" title="Name" value={user.name} />
<MyInput name="free" title="Free to hire" type="checkbox" value={user.free} />
<MySelect name="hair" title="Hair" value={user.hair}
options={[
{ value: "black", title: "Black" },
{ value: "brown", title: "Brown" },
{ value: "blonde", title: "Blonde" },
{ value: "red", title: "Red" }
]}
/>
<div className="buttons">
<button type="reset" onClick={this.resetForm}>Reset</button>
<button type="submit">Submit</button>
</div>
</Formsy.Form>
);
}
});
ReactDOM.render(<App/>, document.getElementById('example'));
|
src/containers/NotFound/NotFound.js | madeagency/reactivity | // @flow
import React from 'react'
import Helmet from 'react-helmet'
import Status from 'components/RouterStatus/Status'
const NotFound = () => (
<Status code={404}>
<div>
<Helmet
title="Not Found"
meta={[{ name: 'description', content: 'Not Found' }]}
/>
<h1>This Page is no longer with us.</h1>
<p>Its in a better place now...</p>
</div>
</Status>
)
export default NotFound
|
src/App.js | Marcoga/react-dnd-test | import React, { Component } from 'react';
import Person from './components/Person';
import Classroom from './components/Classroom';
import HTML5Backend from 'react-dnd/modules/backends/HTML5';
import { DragDropContext } from 'react-dnd';
require('../node_modules/bootstrap/dist/css/bootstrap.min.css');
@DragDropContext(HTML5Backend)
export default class App extends Component {
constructor(props) {
super(props);
this.state = {
students: []
};
}
render() {
const { items } = this.props;
return (
<div className='container'>
<h1>React DnD Test</h1>
<ul>
{items.map(item =>
<li>
<Person name={item.name} />
</li>
)}
</ul>
<Classroom
students={this.state.students}
addStudent={(student) => this.setState({students: [...this.state.students, items.filter(item => item.name === student.id)[0]]})}
/>
</div>
);
}
}
|
ui/js/pages/form/FormDate.js | ericsoderberg/pbc-web | import React from 'react';
import PropTypes from 'prop-types';
import FormField from '../../components/FormField';
import DateInput from '../../components/DateInput';
const FormDate = (props) => {
const { error, field, formTemplateField, onChange } = props;
return (
<FormField label={formTemplateField.name}
help={formTemplateField.help}
error={error}>
<DateInput name={formTemplateField.name}
value={field.value || ''}
onChange={date => onChange({
templateFieldId: formTemplateField._id,
value: date,
})} />
</FormField>
);
};
FormDate.propTypes = {
error: PropTypes.string,
field: PropTypes.object,
formTemplateField: PropTypes.object.isRequired,
onChange: PropTypes.func.isRequired,
};
FormDate.defaultProps = {
error: undefined,
field: {},
};
export default FormDate;
|
src/svg-icons/social/pages.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let SocialPages = (props) => (
<SvgIcon {...props}>
<path d="M3 5v6h5L7 7l4 1V3H5c-1.1 0-2 .9-2 2zm5 8H3v6c0 1.1.9 2 2 2h6v-5l-4 1 1-4zm9 4l-4-1v5h6c1.1 0 2-.9 2-2v-6h-5l1 4zm2-14h-6v5l4-1-1 4h5V5c0-1.1-.9-2-2-2z"/>
</SvgIcon>
);
SocialPages = pure(SocialPages);
SocialPages.displayName = 'SocialPages';
SocialPages.muiName = 'SvgIcon';
export default SocialPages;
|
src/core/Module.js | gianmarcotoso/redux-seed | import React from 'react'
class Module {
constructor(name, reducer, routes) {
const _name = name
Object.defineProperty(this, 'name', {
enumerable: true,
get: () => _name
})
const _reducer = reducer
Object.defineProperty(this, 'reducer', {
enumerable: true,
get: () => _reducer
})
const _routes = routes
Object.defineProperty(this, 'routes', {
enumerable: true,
get: () => _routes
})
}
submoduleOf(parent) {
this.parent = parent
}
}
export default Module
|
src/routes/dashboard/components/browser.js | hhj679/mybition-web | import React from 'react'
import PropTypes from 'prop-types'
import { Table, Tag } from 'antd'
import styles from './browser.less'
import { color } from '../../../utils'
const status = {
1: {
color: color.green,
},
2: {
color: color.red,
},
3: {
color: color.blue,
},
4: {
color: color.yellow,
},
}
function Browser ({ data }) {
const columns = [
{
title: 'name',
dataIndex: 'name',
className: styles.name,
}, {
title: 'percent',
dataIndex: 'percent',
className: styles.percent,
render: (text, it) => <Tag color={status[it.status].color}>{text}%</Tag>,
},
]
return <Table pagination={false} showHeader={false} columns={columns} rowKey={(record, key) => key} dataSource={data} />
}
Browser.propTypes = {
data: PropTypes.array,
}
export default Browser
|
docs/src/GettingStartedPage.js | sheep902/react-bootstrap | import React from 'react';
import CodeExample from './CodeExample';
import NavMain from './NavMain';
import PageHeader from './PageHeader';
import PageFooter from './PageFooter';
import Anchor from './Anchor';
export default class Page extends React.Component {
render() {
return (
<div>
<NavMain activePage="getting-started" />
<PageHeader
title="Getting started"
subTitle="An overview of React-Bootstrap and how to install and use." />
<div className="container bs-docs-container">
<div className="row">
<div className="col-md-9" role="main">
<div className="bs-docs-section">
<h2 className="page-header"><Anchor id="setup">Setup</Anchor></h2>
<p className="lead">You can import the lib as AMD modules, CommonJS modules, or as a global JS script.</p>
<p>First add the Bootstrap CSS to your project; check <a href="http://getbootstrap.com/getting-started/" name="Bootstrap Docs">here</a> if you have not already done that. Note that:</p>
<ul>
<li>Because many folks use custom Bootstrap themes, we do not directly depend on Bootstrap. It is up to you to to determine how you get and link to the Bootstrap CSS and fonts.</li>
<li>React-Bootstrap doesn't depend on a very precise version of Bootstrap. Just pull the latest and, in case of trouble, take hints on the version used by this documentation page. Then, have Bootstrap in your dependencies and ensure your build can read your Less/Sass/SCSS entry point.</li>
</ul>
<p>Then:</p>
<h3><Anchor id="commonjs">CommonJS</Anchor></h3>
<div className="highlight">
<CodeExample
codeText={
`$ npm install react
$ npm install react-bootstrap`
}
/>
<br />
<CodeExample
mode="javascript"
codeText={
`var Alert = require('react-bootstrap/lib/Alert');
// or
var Alert = require('react-bootstrap').Alert;`
}
/>
</div>
<h3><Anchor id="es6">ES6</Anchor></h3>
<div className="highlight">
<CodeExample
codeText={
`$ npm install react
$ npm install react-bootstrap`
}
/>
<br />
<CodeExample
mode="javascript"
codeText={
`import Button from 'react-bootstrap/lib/Button';
// or
import { Button } from 'react-bootstrap';`
}
/>
</div>
<h3><Anchor id="amd">AMD</Anchor></h3>
<div className="highlight">
<CodeExample
codeText={
`$ bower install react
$ bower install react-bootstrap`
}
/>
<br />
<CodeExample
mode="javascript"
codeText={
`define(['react-bootstrap'], function(ReactBootstrap) { var Alert = ReactBootstrap.Alert; ... });`
}
/>
</div>
<h3 className="page-header"><Anchor id="browser-globals">Browser globals</Anchor></h3>
<p>The bower repo contains <code>react-bootstrap.js</code> and <code>react-bootstrap.min.js</code> with all components exported in the <code>window.ReactBootstrap</code> object.</p>
<div className="highlight">
<CodeExample
mode="htmlmixed"
codeText={
`<script src="https://cdnjs.cloudflare.com/ajax/libs/react/<react-version>/react.js"></script>
<script src="path/to/react-bootstrap-bower/react-bootstrap.min.js"></script>
<script>
var Alert = ReactBootstrap.Alert;
</script>`
}
/>
</div>
</div>
<div className="bs-docs-section">
<h2 className="page-header"><Anchor id="browser-support">Browser support</Anchor></h2>
<p>We aim to support all browsers supported by both <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">React</a> and <a href="http://getbootstrap.com/getting-started/#support">Bootstrap</a>.</p>
<p>Unfortunately, due to the lack of resources and the will of dedicating the efforts to modern browsers and getting closer to Bootstrap's features, we will not be testing <code>react-bootstrap</code> against IE8 anymore.
<br/>We will however continue supporting IE8 as long as people submit PRs addressing compatibility issues with it.</p>
<p>React requires <a href="http://facebook.github.io/react/docs/working-with-the-browser.html#browser-support-and-polyfills">polyfills for non-ES5 capable browsers.</a></p>
<div className="highlight">
<CodeExample
mode="htmlmixed"
codeText={
`<!--[if lt IE 9]>
<script>
(function(){
var ef = function(){};
window.console = window.console || {log:ef,warn:ef,error:ef,dir:ef};
}());
</script>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/html5shiv/3.7.2/html5shiv-printshiv.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-shim.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/es5-shim/3.4.0/es5-sham.js"></script>
<![endif]-->`
}
/>
</div>
</div>
</div>
</div>
</div>
<PageFooter />
</div>
);
}
shouldComponentUpdate() {
return false;
}
}
|
src/notebook/components/status-bar.js | 0u812/nteract | /* @flow */
import React from 'react';
import moment from 'moment';
type Props = {
notebook: any,
lastSaved: Date,
kernelSpecDisplayName: string,
executionState: string,
};
export default class StatusBar extends React.Component {
props: Props;
shouldComponentUpdate(nextProps: Props): boolean {
if (this.props.notebook !== nextProps.notebook ||
this.props.lastSaved !== nextProps.lastSaved ||
this.props.executionState !== nextProps.executionState) {
return true;
}
return false;
}
render(): ?React.Element<any> {
const name = this.props.kernelSpecDisplayName || 'Loading...';
return (
<div className="status-bar">
<span className="pull-right">
{
this.props.lastSaved ?
<p> Last saved {moment(this.props.lastSaved).fromNow()} </p> :
<p> Not saved yet </p>
}
</span>
<span className="pull-left">
<p>{name} | {this.props.executionState}</p>
</span>
</div>
);
}
}
|
src/Col.js | bvasko/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import styleMaps from './styleMaps';
import CustomPropTypes from './utils/CustomPropTypes';
const Col = React.createClass({
propTypes: {
/**
* The number of columns you wish to span
*
* for Extra small devices Phones (<768px)
*
* class-prefix `col-xs-`
*/
xs: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Small devices Tablets (≥768px)
*
* class-prefix `col-sm-`
*/
sm: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Medium devices Desktops (≥992px)
*
* class-prefix `col-md-`
*/
md: React.PropTypes.number,
/**
* The number of columns you wish to span
*
* for Large devices Desktops (≥1200px)
*
* class-prefix `col-lg-`
*/
lg: React.PropTypes.number,
/**
* Move columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-offset-`
*/
xsOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-offset-`
*/
smOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-offset-`
*/
mdOffset: React.PropTypes.number,
/**
* Move columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-offset-`
*/
lgOffset: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Extra small devices Phones
*
* class-prefix `col-xs-push-`
*/
xsPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Small devices Tablets
*
* class-prefix `col-sm-push-`
*/
smPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Medium devices Desktops
*
* class-prefix `col-md-push-`
*/
mdPush: React.PropTypes.number,
/**
* Change the order of grid columns to the right
*
* for Large devices Desktops
*
* class-prefix `col-lg-push-`
*/
lgPush: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Extra small devices Phones
*
* class-prefix `col-xs-pull-`
*/
xsPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Small devices Tablets
*
* class-prefix `col-sm-pull-`
*/
smPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Medium devices Desktops
*
* class-prefix `col-md-pull-`
*/
mdPull: React.PropTypes.number,
/**
* Change the order of grid columns to the left
*
* for Large devices Desktops
*
* class-prefix `col-lg-pull-`
*/
lgPull: React.PropTypes.number,
/**
* You can use a custom element for this component
*/
componentClass: CustomPropTypes.elementType
},
getDefaultProps() {
return {
componentClass: 'div'
};
},
render() {
let ComponentClass = this.props.componentClass;
let classes = {};
Object.keys(styleMaps.SIZES).forEach( key => {
let size = styleMaps.SIZES[key];
let prop = size;
let classPart = size + '-';
if (this.props[prop]) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Offset';
classPart = size + '-offset-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Push';
classPart = size + '-push-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
prop = size + 'Pull';
classPart = size + '-pull-';
if (this.props[prop] >= 0) {
classes['col-' + classPart + this.props[prop]] = true;
}
}, this);
return (
<ComponentClass {...this.props} className={classNames(this.props.className, classes)}>
{this.props.children}
</ComponentClass>
);
}
});
export default Col;
|
src/App.js | adadesions/jackson-project | import React, { Component } from 'react';
import stringify from 'json-stable-stringify';
import triangulate from 'delaunay-triangulate';
import async from 'async';
import './App.css';
// Components
import Sidebar from './components/Sidebar';
import DisplayScreen from './components/DisplayScreen';
import Footer from './components/Footer';
const { dialog } = window.require('electron').remote;
const fs = window.require('fs');
const YAML = require('json2yaml');
class App extends Component {
constructor( props ) {
super( props );
this.state = {
leftImg : '/monaLisa.jpg',
rightImg : '/monaLisa.jpg',
imgStack: [],
pointLeftStore: [],
pointRightStore: [],
circleLeftStore: [],
circleRightStore: [],
circleRadius: 4,
logging: [{
date: new Date().toLocaleString(),
log: "Hello! Welcome to Jackson Project by Development team"
}]
}
}
openFile( screenId ) {
const dialogProp = {
defaultPath: '~/Desktop',
properties: ['openFile', 'openDirectory'],
filters: [
{name: 'Images', extensions: ['jpg', 'png', 'gif', 'jpeg']},
],
};
dialog.showOpenDialog( dialogProp, (filename) => {
if( filename === undefined){
return -1;
}
let substr = filename[0].split("/");
let nameWiteExtension = substr[substr.length-1];
let sperateNameAndExtension = nameWiteExtension.split(".");
let onlyName = sperateNameAndExtension[0];
let onlyExtension = sperateNameAndExtension[ sperateNameAndExtension.length - 1 ];
filename = 'file://'+filename;
if( screenId === 'left-screen') {
this.setState({
leftImg: filename,
leftImgFilename: onlyName,
leftImgExtension: onlyExtension,
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Open file at leftscreen, ${filename}`
})
});
}
else{
this.setState({
rightImg: filename,
rightImgFilename: onlyName,
rightImgExtension: onlyExtension,
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Open file at rightscreen, ${filename}`
})
});
}
});
}
saveToJSON() {
let pointLeftStore = this.state.pointLeftStore;
let pointRightStore = this.state.pointRightStore;
let [ pointLeftArray, pointRightArray ] = [ pointLeftStore, pointRightStore ].map( (store) => {
return store.map( point => {
point.z = 0;
return [point.x , point.y];
});
});
let leftDelaunay = triangulate(pointLeftArray);
let rightDelaunay = triangulate(pointRightArray);
let leftOFF = {
format: 'OFF',
orientation: 'left',
filename: this.state.leftImgFilename,
extension: this.state.leftImgExtension,
fullAddress: this.state.leftImg,
pairedWith: this.state.rightImgFilename + '.' + this.state.rightImgExtension,
vertices: pointLeftStore.length, // number of points
faces: leftDelaunay.length, // number of face ( triangle )
vertexSet: pointLeftStore,
faceSet: leftDelaunay,
data: this.state.leftImgData
}
let rightOFF = {
format: 'OFF',
orientation: 'right',
filename: this.state.rightImgFilename,
extension: this.state.rightImgExtension,
fullAddress: this.state.rightImg,
pairedWith: this.state.leftImgFilename + '.' + this.state.leftImgExtension,
vertices: pointRightStore.length, // number of points
faces: rightDelaunay.length, // number of face ( triangle )
vertexSet: pointRightStore,
faceSet: rightDelaunay,
data: this.state.rightImgData
}
let saveProperites = {
defaultPath: ' ',
title: 'Save Mesh Faces',
}
dialog.showSaveDialog(saveProperites, (filename) => {
if( filename === undefined ){
return -1;
}
let modifiedAddress = filename.split('.')[0];
async.map([ leftOFF, rightOFF ], (obj) => {
let addressJSON = modifiedAddress + obj.filename + '.json';
let addressYAML = modifiedAddress + obj.filename + '.yaml';
let jObj = stringify( obj, { space: 3, cmp: (a,b) => -1 });
let yObj = YAML.stringify(obj)
fs.writeFile(addressJSON, jObj, (err) => err ? console.log(err) : console.log('Saved JSON'));
fs.writeFile(addressYAML, yObj, (err) => err ? console.log(err) : console.log('Saved YAML'));
this.setState({
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Saved JSON and YAML at ${filename}`
})
});
});
});
}
updateDelaunay() {
let pointLeftStore = this.state.pointLeftStore;
let pointRightStore = this.state.pointRightStore;
let [ pointLeftArray, pointRightArray ] = [ pointLeftStore, pointRightStore ].map( (store) => {
return store.map( point => {
point.z = 0;
return [point.x , point.y];
});
});
let leftDelaunay = triangulate(pointLeftArray);
let rightDelaunay = triangulate(pointRightArray);
this.setState({
leftDelaunay,
rightDelaunay
});
}
createCircle(e) {
let elem = document.getElementById(e.target.id).parentElement;
let canvasBounding = elem.getBoundingClientRect();
let id = ( Math.random() + 1).toString(36).substr(2, 8);
let tPoint = {
id,
x: Math.floor(Math.abs(e.clientX - canvasBounding.left)),
y: Math.floor(Math.abs(e.clientY - canvasBounding.top)),
draggable: false
};
if(elem.id === 'left-screen'){
let cpTPoint = JSON.parse(JSON.stringify(tPoint));;
cpTPoint.id = ( Math.random() + 2).toString(36).substr(2, 8);
this.setState({
pointLeftStore: this.state.pointLeftStore.concat(tPoint),
// pointRightStore: this.state.pointRightStore.concat(cpTPoint),
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Created new marker at (${tPoint.x}, ${tPoint.y}) on leftscreen`
})
});
}
else if(elem.id === 'right-screen'){
this.setState({
pointRightStore: this.state.pointRightStore.concat(tPoint),
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Created new marker at (${tPoint.x}, ${tPoint.y}) on rightscreen`
})
});
}
this.updateDelaunay();
}
dragStartCircle(e) {
let pointStore, targetIndex;
let elem = e.target.parentElement;
let isLeftscreen = elem.id === 'left-screen';
pointStore = isLeftscreen ? this.state.pointLeftStore : this.state.pointRightStore;
targetIndex = pointStore.findIndex( point => point.id === e.target.id );
pointStore[targetIndex].draggable = !pointStore[targetIndex].draggable;
let x = pointStore[targetIndex].x;
let y = pointStore[targetIndex].y;
if( isLeftscreen ){
this.setState({
pointLeftStore: pointStore,
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Marker(${x}, ${y}) at leftscreen, draggable = ${pointStore[targetIndex].draggable}`
})
});
}
else{
this.setState({
pointRightStore: pointStore,
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Marker(${x}, ${y}) at rightscreen, draggable = ${pointStore[targetIndex].draggable}`
})
});
}
}
moveCircle(e) {
e.preventDefault();
let elem = e.target.parentElement;
let pointStore, targetIndex;
let isLeftscreen = elem.id === 'left-screen';
pointStore = isLeftscreen ? this.state.pointLeftStore : this.state.pointRightStore;
targetIndex = pointStore.findIndex( point => point.id === e.target.id );
let draggable = pointStore[targetIndex].draggable;
if( !draggable ){
return -1;
}
let canvasBounding = elem.getBoundingClientRect();
let tPoint = {
x: e.clientX*0.9999 - canvasBounding.left,
y: e.clientY*0.9999 - canvasBounding.top
}
pointStore[targetIndex].x = tPoint.x;
pointStore[targetIndex].y = tPoint.y;
if( isLeftscreen ){
this.setState({
pointLeftStore: pointStore
});
}
else{
this.setState({
pointRightStore: pointStore
});
}
this.updateDelaunay();
}
deleteCircle(e) {
let parent = e.target.parentElement;
let isLeftscreen = parent.id === 'left-screen';
let pointStore = isLeftscreen ? this.state.pointLeftStore : this.state.pointRightStore;
let targetIndex = pointStore.findIndex( point => point.id === e.target.id);
pointStore.splice(targetIndex, 1);
if( isLeftscreen ){
this.setState({
pointLeftStore: pointStore,
});
}
else{
this.setState({
pointRightStore: pointStore,
});
}
this.updateDelaunay();
}
clearMarkers(screenId) {
if( screenId === 'left-screen'){
this.setState({
pointLeftStore: [],
circleLeftStore: [],
leftDelaunay: [],
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Remove all makers at Left screen`
})
});
}
else if( screenId === 'right-screen' ){
this.setState({
pointRightStore: [],
rightDelaunay: [],
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Remove all makers at Right screen`
})
});
}
else{
this.setState({
pointLeftStore: [],
pointRightStore: [],
leftDelaunay: [],
rightDelaunay: [],
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Remove all makers at both screens`
})
});
}
}
changeRadius(radius) {
this.setState({
circleRadius: radius,
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Change marker radius to ${radius}`
})
});
}
openMesh() {
const dialogProp = {
defaultPath: '~/Desktop',
properties: ['openFile', 'openDirectory'],
filters: [
{name: 'Images', extensions: ['json', 'yaml', 'yml']},
],
};
dialog.showOpenDialog( dialogProp, (filename) => {
if( filename === undefined){
return -1;
}
let json = JSON.parse(fs.readFileSync( filename[0] , 'utf8'));
let verticesObj = json.vertexSet;
let verticesArr = verticesObj.map( (obj) => [ obj.x , obj.y ] );
let leftDelaunay = triangulate(verticesArr);
this.setState({
leftDelaunay,
pointLeftStore: verticesObj,
logging: this.state.logging.concat({
date: new Date().toLocaleString(),
log: `Open mesh template from ${filename}`
})
});
});
}
showLogging() {
let elem = document.getElementById("logging");
if( elem ){
elem.scrollIntoView(false);
elem.scrollTop = elem.scrollHeight;
}
return this.state.logging.map( (logObj, index) => {
return (
<p key={index}>
<b>[{logObj.date}]</b> - {logObj.log}
</p>
);
});
}
render() {
return (
<div className="window">
<div className="window-content">
<div className="pane-group">
<Sidebar
statusObj={ this.state }
changeRadius={ this.changeRadius.bind(this) }
openMesh={ this.openMesh.bind(this) }
/>
<div className="pane">
{/* Workingspace */}
<div className="face-canvas">
<DisplayScreen
id="left-screen"
currentImg={ this.state.leftImg }
pointStore={ this.state.pointLeftStore }
click={ (e) => this.createCircle(e) }
openFile={ () => this.openFile('left-screen') }
fullAddress= { this.state.leftImg }
delaunay= { this.state.leftDelaunay }
clearMarkers= { () => this.clearMarkers('left-screen') }
circleRadius={ this.state.circleRadius }
onMove= { (e) => this.moveCircle(e) }
onClick= { (e) => this.dragStartCircle(e) }
onDoubleClick= { (e) => this.deleteCircle(e) }
/>
<div className="line-between-screen"></div>
<DisplayScreen
id="right-screen"
currentImg={ this.state.rightImg }
pointStore={ this.state.pointRightStore }
click={ (e) => this.createCircle(e) }
openFile={ () => this.openFile('right-screen') }
fullAddress= { this.state.rightImg }
delaunay= { this.state.rightDelaunay }
clearMarkers= { () => this.clearMarkers('right-screen') }
circleRadius={ this.state.circleRadius }
onMove= { (e) => this.moveCircle(e) }
onClick= { (e) => this.dragStartCircle(e) }
onDoubleClick= { (e) => this.deleteCircle(e) }
/>
</div>
{/* End Workingspace */}
<div id="logging">
{ this.showLogging() }
</div>
</div>
</div>
</div>
{/* Footer */}
<Footer
clearMarkers={ this.clearMarkers.bind(this) }
saveToJSON={ this.saveToJSON.bind(this) }
/>
{/* End Footer */}
</div>
);
}
}
export default App;
|
src/behaviours/autoInitialisedForm.js | codaco/Network-Canvas | import React from 'react';
import PropTypes from 'prop-types';
import { fromPairs, map } from 'lodash';
// TODO: Seems like this knowledge should be part of the field component?
const typeInitalValue = (field) => {
switch (field.type) {
case 'CheckboxGroup':
case 'ToggleGroup':
return fromPairs(map(field.options, option => [option, false]));
default:
return '';
}
};
const initialValues = fields =>
fromPairs(map(fields, field => [field.name, typeInitalValue(field)]));
/**
* Renders a redux form that contains fields according to a `fields` config.
*/
const autoInitialisedForm = (WrappedComponent) => {
const AutoInitialisedForm = props => (
<WrappedComponent initialValues={initialValues(props.fields)} {...props} />
);
AutoInitialisedForm.propTypes = {
fields: PropTypes.array.isRequired,
};
return AutoInitialisedForm;
};
export default autoInitialisedForm;
|
packages/metadata-react/src/FrmSuperLogin/SocialLink.js | oknosoft/metadata.js | import React from 'react';
import Tabs from '@material-ui/core/Tabs';
import Tab from '@material-ui/core/Tab';
import TextField from '@material-ui/core/TextField';
import Button from '@material-ui/core/Button';
import Typography from '@material-ui/core/Typography';
import {red, blue} from '@material-ui/core/colors';
import {YandexIcon, GoogleIcon, GitHubIcon, FacebookIcon} from './assets/icons';
import superlogin from './client';
import classes from './FrmSuperLogin.css';
// https://github.com/micky2be/superlogin-client
export default class TabsLogin extends React.Component {
constructor(props) {
super(props);
this.state = {
value: 'a',
};
}
tabChange = (value) => {
if (value === 'a' || value === 'b') {
this.setState({
value: value,
});
}
};
buttonTouchTap(provider) {
return function () {
superlogin.socialAuth(provider);
}
}
render() {
return (
<div className={classes.paper}>
<div >
<Tabs
value={this.state.value}
onChange={this.tabChange}
>
<Tab label="Вход" value="a">
<div className={classes.sub_paper}>
<TextField
hintText="login"
floatingLabelText="Имя пользователя"
/><br />
<TextField
hintText="password"
floatingLabelText="Пароль"
variant="password"
/><br />
<RaisedButton label="Забыли пароль?" className={classes.button}/>
<RaisedButton label="Войти" disabled={true} className={classes.button}/>
</div>
<div className={classes.sub_paper}>
<Typography variant="h6" color="inherit" >Вы можете авторизоваться при помощи учетных
записей социальных сетей:</Typography>
<RaisedButton
label="Google"
className={classes.button}
labelStyle={{width: 110, textAlign: 'left', display: 'inline-block'}}
icon={<GoogleIcon viewBox="0 0 256 262" style={{height: 18, fill: blue[500]}}/>}
onClick={this.buttonTouchTap("google")}
/><br />
<RaisedButton
label="Yandex"
className={classes.button}
labelStyle={{width: 110, textAlign: 'left', display: 'inline-block'}}
icon={<YandexIcon viewBox="0 0 180 190" style={{height: 18, fill: red[500]}}/>}
onClick={this.buttonTouchTap("yandex")}
/><br />
<RaisedButton
label="Facebook"
className={classes.button}
labelStyle={{width: 110, textAlign: 'left', display: 'inline-block'}}
icon={<FacebookIcon viewBox="0 0 420 420" style={{height: 18, fill: '#3A559F'}}/>}
onClick={this.buttonTouchTap("facebook")}
/><br />
<RaisedButton
label="В контакте"
className={classes.button}
labelStyle={{width: 110, textAlign: 'left', display: 'inline-block'}}
icon={<GitHubIcon viewBox="0 0 256 250" style={{height: 18, fill: 'darkslategrey'}}/>}
onClick={this.buttonTouchTap("vkontakte")}
/>
{/*
<RaisedButton
label="GitHub"
className={classes.button}
labelStyle={{width: 110, textAlign: 'left', display: 'inline-block'}}
icon={<GitHubIcon viewBox="0 0 256 250" style={{width: 18, height: 18}}/>}
onClick={this.buttonTouchTap("github")}
/>
*/}
</div>
</Tab>
<Tab label="Регистрация" value="b">
<div style={{padding: 18}}>
<TextField
hintText="name"
fullWidth
margin="dense"
floatingLabelText="Полное имя"
/><br />
<TextField
hintText="login"
fullWidth
margin="dense"
floatingLabelText="Имя пользователя"
/><br />
<TextField
hintText="email"
fullWidth
margin="dense"
floatingLabelText="Электронная почта"
/><br />
<TextField
hintText="password"
fullWidth
margin="dense"
floatingLabelText="Пароль"
variant="password"
/><br />
<TextField
hintText="confirm_password"
fullWidth
margin="dense"
floatingLabelText="Подтвердить пароль"
variant="password"
/>
</div>
</Tab>
</Tabs>
</div>
</div>
);
}
}
|
20161210/RN-test/app/test02/myListView1.js | fengnovo/react-native | import React, { Component } from 'react';
import { Text, View, ListView,
RefreshControl,
TouchableHighlight, StyleSheet } from 'react-native';
class MyListView extends React.Component {
constructor(props) {
super(props);
this._onScrollBeginDrag = this._onScrollBeginDrag.bind(this);
this._onScrollEndDrag = this._onScrollEndDrag.bind(this);
this._onMomentumScrollBegin = this._onMomentumScrollBegin.bind(this);
this._onMomentumScrollEnd = this._onMomentumScrollEnd.bind(this);
this._onRefresh = this._onRefresh.bind(this);
}
_onScrollBeginDrag() {
console.log('开始拖拽');
}
_onScrollEndDrag() {
console.log('结束拖拽');
}
_onMomentumScrollBegin() {
console.log('开始滑动');
}
_onMomentumScrollEnd() {
console.log('滑动结束');
}
_onRefresh () {
console.log('刷新');
}
render() {
return (
<View style={styles.container}>
<ScrollView
style={styles.scrollView}
showVerticalScrollIndicator={true}
onScrollBeginDrag={this._onScrollBeginDrag}
onScrollEndDrag={this._onScrollEndDrag}
onMomentumScrollBegin={this._onMomentumScrollBegin}
onMomentumScrollEnd={this._onMomentumScrollEnd}
refreshControl={
<RefreshControl
refreshing={false}
onRefresh={this._onRefresh}
colors={['#ff0000', '#00ff00','#0000ff','#3ad564']}
progressBackgroundColor="#ffffff"
title="正在刷新..."
/>
}
>
<View style={styles.view1}>
</View>
<View style={styles.view2}>
</View>
<View style={styles.view3}>
</View>
</ScrollView>
</View>
)
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "cyan"
},
scrollView : {
marginTop: 25,
backgroundColor: "#cccccc"
},
view1 : {
margin: 15,
flex: 1,
height: 300,
backgroundColor: "yellow"
},
view2 : {
margin: 15,
flex: 1,
height: 300,
backgroundColor: "blue"
},
view3 : {
margin: 15,
flex: 1,
height: 300,
backgroundColor: "green"
},
});
export default MyListView |
react/src/index.js | ozlerhakan/rapid | import React from 'react';
import ReactDOM from 'react-dom';
import HomePage from './components/HomePage';
import '../node_modules/bootstrap/dist/css/bootstrap.min.css'
import '../node_modules/font-awesome/css/font-awesome.min.css'
import './custom.css';
ReactDOM.render(
<HomePage />,
document.getElementById('root')
);
|
app/jsx/custom_help_link_settings/CustomHelpLinkMenu.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import I18n from 'i18n!custom_help_link'
import {Menu} from '@instructure/ui-menu'
import {Button} from '@instructure/ui-buttons'
import {AccessibleContent} from '@instructure/ui-a11y'
import {IconPlusLine} from '@instructure/ui-icons'
import CustomHelpLinkPropTypes from './CustomHelpLinkPropTypes'
import CustomHelpLinkConstants from './CustomHelpLinkConstants'
export default class CustomHelpLinkMenu extends React.Component {
static propTypes = {
links: PropTypes.arrayOf(CustomHelpLinkPropTypes.link).isRequired,
onChange: PropTypes.func
}
static defaultProps = {
onChange: () => {}
}
handleChange = (e, link) => {
if (link.is_disabled) {
e.preventDefault()
return
}
if (typeof this.props.onChange === 'function') {
e.preventDefault()
this.props.onChange(link)
}
}
focus = () => {
this.addButton.focus()
}
focusable = () => this.addButton
handleAddLinkSelection = (e, selected) => {
const item = selected[0]
if (item === 'add_custom_link') {
this.handleChange(e, {...CustomHelpLinkConstants.DEFAULT_LINK})
} else {
this.handleChange(e, this.props.links.filter(l => l.text === item)[0])
}
}
render() {
return (
<div className="HelpMenuOptions__Container">
<Menu
trigger={
<Button
ref={c => {
this.addButton = c
}}
>
<AccessibleContent alt={I18n.t('Add Link')}>
<IconPlusLine className="HelpMenuOptions__ButtonIcon" />
{I18n.t('Link')}
</AccessibleContent>
</Button>
}
>
<Menu.Group label={I18n.t('Add help menu links')} onSelect={this.handleAddLinkSelection}>
<Menu.Item key="add_custom_link" value="add_custom_link">
{I18n.t('Add Custom Link')}
</Menu.Item>
{this.props.links.map(link => (
<Menu.Item key={link.text} value={link.text} disabled={link.is_disabled}>
{link.text}
</Menu.Item>
))}
</Menu.Group>
</Menu>
</div>
)
}
}
|
app/components/AddCharacter.js | benjaminmbrown/eve-faces | import React from 'react';
import AddCharacterStore from '../stores/AddCharacterStore';
import AddCharacterActions from '../stores/AddCharacterActions';
class AddCharacter extends React.Component{
constructor(props){
super(props);
this.state = AddCharacterStore.getState();
this.onChange = this.onChange.bind(this);
}
componentDidMount(){
AddCharacterStore.listen(this.onChange);
}
componentWillUnmount(){
AddCharacterStore.unlisten(this.onChange);
}
onChange(state){
this.setState(state);
}
handleSubmit(event){
event.preventDefault();
var name = this.state.name.trim();
var gender = this.state.gender;
if(!name){
AddCharacterActions.invalidName();
this.refs.nameTextField.getDOMNode.focus();
}
if(!gender){
AddCharacterActions.invalidGender():
}
if(name && gender){
AddCharacterActions.addCharacter(name,gender);
}
}
render() {
return (
<div className='container'>
<div className='row flipInX animated'>
<div className='col-sm-8'>
<div className='panel panel-default'>
<div className='panel-heading'>Add Character</div>
<div className='panel-body'>
<form onSubmit={this.handleSubmit.bind(this)}>
<div className={'form-group ' + this.state.nameValidationState}>
<label className='control-label'>Character Name</label>
<input type='text' className='form-control' ref='nameTextField' value={this.state.name}
onChange={AddCharacterActions.updateName} autoFocus/>
<span className='help-block'>{this.state.helpBlock}</span>
</div>
<div className={'form-group ' + this.state.genderValidationState}>
<div className='radio radio-inline'>
<input type='radio' name='gender' id='female' value='Female' checked={this.state.gender === 'Female'}
onChange={AddCharacterActions.updateGender}/>
<label htmlFor='female'>Female</label>
</div>
<div className='radio radio-inline'>
<input type='radio' name='gender' id='male' value='Male' checked={this.state.gender === 'Male'}
onChange={AddCharacterActions.updateGender}/>
<label htmlFor='male'>Male</label>
</div>
</div>
<button type='submit' className='btn btn-primary'>Submit</button>
</form>
</div>
</div>
</div>
</div>
</div>
);
}
}
export default AddCharacter; |
src/Parser/BrewmasterMonk/Modules/Spells/IronSkinBrew.js | mwwscott0/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
import SpellIcon from 'common/SpellIcon';
import { formatPercentage, formatThousands } from 'common/format';
import Module from 'Parser/Core/Module';
import Combatants from 'Parser/Core/Modules/Combatants';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
const debug = false;
class IronSkinBrew extends Module {
static dependencies = {
combatants: Combatants,
}
lastIronSkinBrewBuffApplied = 0;
hitsWithIronSkinBrew = 0;
damageWithIronSkinBrew = 0;
hitsWithoutIronSkinBrew = 0;
damageWithoutIronSkinBrew = 0;
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if (SPELLS.IRONSKIN_BREW_BUFF.id === spellId) {
this.lastIronSkinBrewBuffApplied = event.timestamp;
}
}
on_byPlayer_removebuff(event) {
const spellId = event.ability.guid;
if (SPELLS.IRONSKIN_BREW_BUFF.id === spellId) {
this.lastIronSkinBrewBuffApplied = 0;
}
}
on_toPlayer_damage(event) {
if (event.ability.guid !== SPELLS.STAGGER_TAKEN.id) {
if (this.lastIronSkinBrewBuffApplied > 0) {
this.hitsWithIronSkinBrew += 1;
this.damageWithIronSkinBrew += event.amount + (event.absorbed || 0) + (event.overkill || 0);
} else {
this.hitsWithoutIronSkinBrew += 1;
this.damageWithoutIronSkinBrew += event.amount + (event.absorbed || 0) + (event.overkill || 0);
}
}
}
on_toPlayer_absorbed(event) {
if (event.ability.guid === SPELLS.STAGGER.id) {
if (this.lastIronSkinBrewBuffApplied > 0) {
this.damageWithIronSkinBrew -= event.amount;
} else {
this.damageWithoutIronSkinBrew -= event.amount;
}
}
}
on_finished() {
if (debug) {
console.log(`Hits with IronSkinBrew ${this.hitsWithIronSkinBrew}`);
console.log(`Damage with IronSkinBrew ${this.damageWithIronSkinBrew}`);
console.log(`Hits without IronSkinBrew ${this.hitsWithoutIronSkinBrew}`);
console.log(`Damage without IronSkinBrew ${this.damageWithoutIronSkinBrew}`);
console.log(`Total damage ${this.damageWithIronSkinBrew + this.damageWithoutIronSkinBrew + this.staggerDot}`);
}
}
suggestions(when) {
const isbUptimePercentage = this.combatants.selected.getBuffUptime(SPELLS.IRONSKIN_BREW_BUFF.id) / this.owner.fightDuration;
when(isbUptimePercentage).isLessThan(0.9)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span> Your <SpellLink id={SPELLS.IRONSKIN_BREW.id} /> uptime was {formatPercentage(isbUptimePercentage)}%, unless there are extended periods of downtime it should be near 100%.</span>)
.icon(SPELLS.IRONSKIN_BREW.icon)
.actual(`${formatPercentage(actual)}% uptime`)
.recommended(`${Math.round(formatPercentage(recommended))}% or more is recommended`)
.regular(recommended - 0.1).major(recommended - 0.2);
});
}
statistic() {
const isbUptime = this.combatants.selected.getBuffUptime(SPELLS.IRONSKIN_BREW_BUFF.id) / this.owner.fightDuration;
const hitsMitigatedPercent = this.hitsWithIronSkinBrew / (this.hitsWithIronSkinBrew + this.hitsWithoutIronSkinBrew);
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.IRONSKIN_BREW.id} />}
value={`${formatPercentage(isbUptime)}%`}
label="Ironskin Brew uptime"
tooltip={`Ironskin Brew breakdown (these values are direct damage and does not include damage added to stagger):
<ul>
<li>You were hit <b>${this.hitsWithIronSkinBrew}</b> times with your Ironskin Brew buff (<b>${formatThousands(this.damageWithIronSkinBrew)}</b> damage).</li>
<li>You were hit <b>${this.hitsWithoutIronSkinBrew}</b> times <b><i>without</i></b> your Ironskin Brew buff (<b>${formatThousands(this.damageWithoutIronSkinBrew)}</b> damage).</li>
</ul>
<b>${formatPercentage(hitsMitigatedPercent)}%</b> of attacks were mitigated with Ironskin Brew.`}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
}
export default IronSkinBrew;
|
components/Cards/CondensedSpaceCard/CondensedSpaceCard.js | NGMarmaduke/bloom | import PropTypes from 'prop-types';
import React from 'react';
import cx from 'classnames';
import css from './CondensedSpaceCard.css';
import LeftRight from '../../LeftRight/LeftRight';
import FittedImage from '../../FittedImage/FittedImage';
const CondensedSpaceCard = (props) => {
const {
href,
images,
name,
price,
priceFromLabel,
priceUnit,
className,
} = props;
/* eslint-disable react/jsx-no-target-blank */
return (
<a
href={ href }
className={ cx(css.root, className) }
title={ name }
target="_blank"
>
<LeftRight
primarySide="left"
leftChildren={
images.length > 0 && (
<FittedImage
className={ css.image }
src={ images[0].src }
alt={ images[0].alt }
/>
)
}
rightChildren={
<div className={ css.body }>
<div className={ css.name }>
{ priceFromLabel && <span className={ css.priceFromLabel }>{ priceFromLabel }</span> }
<span className={ css.price }>{ price }</span>
{ '\u00a0' }
<span className={ css.priceUnit }>{ priceUnit }</span>
</div>
<div className={ css.name }>{ name }</div>
</div>
}
/>
</a>
);
/* eslint-enable react/jsx-no-target-blank */
};
CondensedSpaceCard.propTypes = {
href: PropTypes.string,
images: PropTypes.array,
name: PropTypes.string,
price: PropTypes.string,
className: PropTypes.string,
priceFromLabel: PropTypes.string,
priceUnit: PropTypes.string,
};
CondensedSpaceCard.defaultProps = {
images: [],
};
export default CondensedSpaceCard;
|
src/containers/ColourPicker/RgbForm.js | colouroscope/colouroscope | import React from 'react'
import { connect } from 'react-redux'
import { setRgbColour, setPreviewColour } from '../../actions/index'
import tinycolor from 'tinycolor2'
const mapStateToProps = ({ picker }) => {
return {
rgb: picker.rgb
}
}
const mergeProps = (stateProps, { dispatch }, ownProps) => {
return {
...stateProps,
...ownProps,
onRgbChange: (e) => {
let { name, value } = e.target
let { rgb } = stateProps
rgb = { ...rgb, [name]: value }
dispatch(setRgbColour(rgb))
value = parseFloat(value)
if(!isNaN(value)) {
rgb = { ...rgb, [name]: value }
if(tinycolor(rgb).isValid()){
dispatch(setPreviewColour(rgb))
}
}
}
}
}
let RgbForm = ({rgb, onRgbChange }) => (
<div className="form-group row">
<label htmlFor="rgb-r-input" className="col-2 col-form-label">RGB</label>
<div className="col-10">
<div className="row">
<div className="col-4">
<input className="form-control" type="text" value={rgb.r} id="rgb-r-input" name="r" onChange={onRgbChange} />
</div>
<div className="col-4">
<input className="form-control" type="text" value={rgb.g} id="rgb-g-input" name="g" onChange={onRgbChange} />
</div>
<div className="col-4">
<input className="form-control" type="text" value={rgb.b} id="rgb-b-input" name="b" onChange={onRgbChange} />
</div>
</div>
</div>
</div>
)
RgbForm = connect(
mapStateToProps,
null,
mergeProps,
)(RgbForm)
export default RgbForm
|
examples/form/src/index.js | jas-chen/redux | import React from 'react'
import ReactDOM from 'react-dom'
import { createStore, bindActionCreators } from 'typed-redux'
import Form from './components/Form'
import form from './reducers'
import { ChangeName, ChangeRemember } from './actions'
const store = createStore(form)
const rootEl = document.getElementById('root')
const actions = bindActionCreators({
changeName: name => new ChangeName(name),
changeRemember: remember => new ChangeRemember(remember)
}, store.dispatch);
const render = () => {
const { name, remember } = store.getState()
ReactDOM.render(
<Form
name={name}
remember={remember}
onChangeName={actions.changeName}
onChangeRember={actions.changeRemember}
/>,
rootEl
)
}
render()
store.subscribe(render)
|
src/Interleave/index.js | pinebit/react-cr | import React from 'react';
import PropTypes from 'prop-types';
import Wrapper from '../Wrapper';
const Interleave = ({ separator, first, last, children, ...wrapperProps }) => {
if (!children || !separator) {
return null;
}
const content = [];
children.forEach((child, index) => {
const key = child.key;
if (key) {
content.push(child);
const lastChild = index === children.length - 1;
if (!lastChild) {
content.push(React.cloneElement(separator, { key: `${key}_separator` }));
}
}
});
return (
<Wrapper {...wrapperProps}>
{first && React.cloneElement(separator, { key: 'first_separator' })}
{content}
{last && React.cloneElement(separator, { key: 'last_separator' })}
</Wrapper>
);
};
Interleave.propTypes = {
separator: PropTypes.node.isRequired,
first: PropTypes.bool,
last: PropTypes.bool,
children: PropTypes.oneOfType([
PropTypes.arrayOf(PropTypes.node),
PropTypes.node
]).isRequired
};
export default Interleave;
|
src/Collapse.js | chilts/react-bootstrap | import React from 'react';
import Transition from 'react-overlays/lib/Transition';
import domUtils from './utils/domUtils';
import CustomPropTypes from './utils/CustomPropTypes';
import deprecationWarning from './utils/deprecationWarning';
import createChainedFunction from './utils/createChainedFunction';
let capitalize = str => str[0].toUpperCase() + str.substr(1);
// reading a dimension prop will cause the browser to recalculate,
// which will let our animations work
let triggerBrowserReflow = node => node.offsetHeight;
const MARGINS = {
height: ['marginTop', 'marginBottom'],
width: ['marginLeft', 'marginRight']
};
function getDimensionValue(dimension, elem){
let value = elem[`offset${capitalize(dimension)}`];
let margins = MARGINS[dimension];
return (value +
parseInt(domUtils.css(elem, margins[0]), 10) +
parseInt(domUtils.css(elem, margins[1]), 10)
);
}
class Collapse extends React.Component {
constructor(props, context){
super(props, context);
this.onEnterListener = this.handleEnter.bind(this);
this.onEnteringListener = this.handleEntering.bind(this);
this.onEnteredListener = this.handleEntered.bind(this);
this.onExitListener = this.handleExit.bind(this);
this.onExitingListener = this.handleExiting.bind(this);
}
render() {
let enter = createChainedFunction(this.onEnterListener, this.props.onEnter);
let entering = createChainedFunction(this.onEnteringListener, this.props.onEntering);
let entered = createChainedFunction(this.onEnteredListener, this.props.onEntered);
let exit = createChainedFunction(this.onExitListener, this.props.onExit);
let exiting = createChainedFunction(this.onExitingListener, this.props.onExiting);
return (
<Transition
ref="transition"
{...this.props}
aria-expanded={this.props.role ? this.props.in : null}
className={this._dimension() === 'width' ? 'width' : ''}
exitedClassName="collapse"
exitingClassName="collapsing"
enteredClassName="collapse in"
enteringClassName="collapsing"
onEnter={enter}
onEntering={entering}
onEntered={entered}
onExit={exit}
onExiting={exiting}
onExited={this.props.onExited}
>
{ this.props.children }
</Transition>
);
}
/* -- Expanding -- */
handleEnter(elem){
let dimension = this._dimension();
elem.style[dimension] = '0';
}
handleEntering(elem){
let dimension = this._dimension();
elem.style[dimension] = this._getScrollDimensionValue(elem, dimension);
}
handleEntered(elem){
let dimension = this._dimension();
elem.style[dimension] = null;
}
/* -- Collapsing -- */
handleExit(elem){
let dimension = this._dimension();
elem.style[dimension] = this.props.getDimensionValue(dimension, elem) + 'px';
}
handleExiting(elem){
let dimension = this._dimension();
triggerBrowserReflow(elem);
elem.style[dimension] = '0';
}
_dimension(){
return typeof this.props.dimension === 'function'
? this.props.dimension()
: this.props.dimension;
}
//for testing
_getTransitionInstance(){
return this.refs.transition;
}
_getScrollDimensionValue(elem, dimension){
return elem[`scroll${capitalize(dimension)}`] + 'px';
}
}
// Explicitly copied from Transition for doc generation.
// TODO: Remove duplication once #977 is resolved.
Collapse.propTypes = {
/**
* Show the component; triggers the expand or collapse animation
*/
in: React.PropTypes.bool,
/**
* Unmount the component (remove it from the DOM) when it is collapsed
*/
unmountOnExit: React.PropTypes.bool,
/**
* Run the expand animation when the component mounts, if it is initially
* shown
*/
transitionAppear: React.PropTypes.bool,
/**
* Duration of the collapse animation in milliseconds, to ensure that
* finishing callbacks are fired even if the original browser transition end
* events are canceled
*/
timeout: React.PropTypes.number,
/**
* duration
* @private
*/
duration: CustomPropTypes.all([
React.PropTypes.number,
(props)=> {
if (props.duration != null){
deprecationWarning('Collapse `duration`', 'the `timeout` prop');
}
return null;
}
]),
/**
* Callback fired before the component expands
*/
onEnter: React.PropTypes.func,
/**
* Callback fired after the component starts to expand
*/
onEntering: React.PropTypes.func,
/**
* Callback fired after the component has expanded
*/
onEntered: React.PropTypes.func,
/**
* Callback fired before the component collapses
*/
onExit: React.PropTypes.func,
/**
* Callback fired after the component starts to collapse
*/
onExiting: React.PropTypes.func,
/**
* Callback fired after the component has collapsed
*/
onExited: React.PropTypes.func,
/**
* The dimension used when collapsing, or a function that returns the
* dimension
*
* _Note: Bootstrap only partially supports 'width'!
* You will need to supply your own CSS animation for the `.width` CSS class._
*/
dimension: React.PropTypes.oneOfType([
React.PropTypes.oneOf(['height', 'width']),
React.PropTypes.func
]),
/**
* Function that returns the height or width of the animating DOM node
*
* Allows for providing some custom logic for how much the Collapse component
* should animate in its specified dimension. Called with the current
* dimension prop value and the DOM node.
*/
getDimensionValue: React.PropTypes.func,
/**
* ARIA role of collapsible element
*/
role: React.PropTypes.string
};
Collapse.defaultProps = {
in: false,
timeout: 300,
unmountOnExit: false,
transitionAppear: false,
dimension: 'height',
getDimensionValue
};
export default Collapse;
|
demo/delaunay-color-mesh.js | joelburget/d4 | import React from 'react';
import poissonDiscSampler from 'poisson-disc-sampler';
import {voronoi as d3Voronoi} from 'd3-voronoi';
import {lab} from 'd3-color';
import {polygonCentroid} from 'd3-polygon';
const width = 960;
const height = 500;
const radius = 30;
const sampler = poissonDiscSampler(width, height, radius);
const samples = [];
let sample;
while (sample = sampler()) {
samples.push(sample);
}
var voronoi = d3Voronoi()
.extent([[-1, -1], [width + 1, height + 1]]);
function color([x, y]) {
const dx = x - width / 2;
const dy = y - height / 2;
return lab(100 - (dx * dx + dy * dy) / 5000, dx / 10, dy / 10);
}
export default function Mesh() {
const paths = voronoi(samples)
.links()
.map(sample => (
<path
d={`M${sample.join('L')}Z`}
fill={color(polygonCentroid(sample))}
stroke={color(polygonCentroid(sample))}
/>
));
return (
<svg width={width} height={height}>
{paths}
</svg>
);
}
|
app/components/variable-list.js | paulsonnentag/qwery-me | import _ from 'lodash';
import React from 'react';
import {TOKEN} from '../types';
export default class VariableList extends React.Component {
render () {
var {variables, onSelect} = this.props;
return (
<div className="token-list">
{_.map(variables, _.partial(getVariable, onSelect))}
</div>
);
}
}
function getVariable (onSelect, {id, type, name}) {
return (
<button key={id}
className={'token ' + type.toLowerCase()}
onClick={() => onSelect({type: TOKEN.VARIABLE, id})}>
<div className={'small icon ' + type.toLowerCase()}/>
{name}
</button>
);
} |
test/js/AR/release_test/ARObjectMarkerTest.js | viromedia/viro |
/**
* Copyright (c) 2017-present, Viro Media, 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, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
import {
ViroARScene,
ViroARPlane,
ViroImage,
ViroARPlaneSelector,
ViroQuad,
ViroConstants,
ViroNode,
ViroBox,
ViroOmniLight,
ViroText,
ViroUtils,
ViroARTrackingTargets,
ViroARImageMarker,
ViroARObjectMarker,
} from 'react-viro';
var createReactClass = require('create-react-class');
let polarToCartesian = ViroUtils.polarToCartesian;
var ARImageMarkerTest = createReactClass({
getInitialState: function() {
return {
showObjectMarker : true,
pauseUpdates : false,
targetTwo : 0,
};
},
render: function() {
var target = targetsList[this.state.targetTwo];
return (
<ViroARScene>
{/* Image Marker component*/}
<ViroText position={polarToCartesian([6, 20, 10])} text={"Object Marker: " + (this.state.showObjectMarker ? "Visible" : "Not Visible")}
style={styles.instructionText} onClick={this._toggleShowObjectMarker} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, 20, 0])} text={"Switch Target, current: " + target}
style={styles.instructionText} onClick={this._toggleTargetTwo} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, 20, -10])} text={"Pause Updates: " + (this.state.pauseUpdates ? "Yes" : "No")}
style={styles.instructionText} onClick={this._togglePauseUpdates} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, 20, -20])} text={"Test Delete Obj Target"}
style={styles.instructionText} onClick={this._deleteTarget} transformBehaviors={["billboard"]}/>
<ViroARObjectMarker target={target}
pauseUpdates={this.state.pauseUpdates}
onAnchorFound={()=>{console.log("ARImageMarkerTest found marker!")}}
onAnchorUpdated={()=>{console.log("ARImageMarkerTest updated marker!")}}
onAnchorRemoved={()=>{console.log("ARImageMarkerTest removed marker!")}} >
<ViroBox scale={[.1,.1,.1]} position={[0, .05, 0]}/>
</ViroARObjectMarker>
{/* Release Menu */}
<ViroText position={polarToCartesian([6, -30, 0])} text={"Next test"}
style={styles.instructionText} onClick={this._goToNextTest} transformBehaviors={["billboard"]}/>
<ViroText position={polarToCartesian([6, -30, -15])} text={"Release Menu"}
style={styles.instructionText} onClick={()=>{this.props.arSceneNavigator.replace("ARReleaseMenu", {scene: require("./ARReleaseMenu")})}}
transformBehaviors={["billboard"]}/>
</ViroARScene>
);
},
_deleteTarget() {
ViroARTrackingTargets.deleteTarget("to_delete")
},
_togglePauseUpdates() {
this.setState({
pauseUpdates : !this.state.pauseUpdates
})
},
_toggleShowObjectMarker() {
this.setState({
showObjectMarker : !this.state.showObjectMarker
})
},
_goToNextTest() {
this.props.arSceneNavigator.replace("ARSceneAndNavigatorTest", {scene:require("./ARSceneAndNavigatorTest")})
},
_toggleTargetTwo() {
console.log("[ARImageMarkerTest] toggling target two!");
this.setState({
targetTwo : (this.state.targetTwo == targetsList.length - 1) ? 0 : this.state.targetTwo + 1
})
}
});
var styles = StyleSheet.create({
instructionText: {
fontFamily: 'Arial',
fontSize: 25,
width: 2,
color: '#cccccc',
flex: 1,
textAlignVertical: 'center',
textAlign: 'center',
},
});
var newTargets = {
google_home : {
source : require("./res/ar_targets/google_home.arobject"),
type : 'Object'
},
alcohol_bottle : {
source : require("./res/ar_targets/alcohol_bottle.arobject"),
type : 'Object'
},
diet_coke : {
source : require("./res/ar_targets/diet_coke.arobject"),
type : 'Object'
},
to_delete : {
source : require("./res/ar_targets/google_home.arobject"),
type : 'Object'
}
}
ViroARTrackingTargets.createTargets(newTargets);
var targetsList = ['alcohol_bottle', 'google_home', 'diet_coke'];
module.exports = ARImageMarkerTest;
|
src/main/js/builder/assets/containers/WagerInput.js | Bernardo-MG/dreadball-toolkit-webpage | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { setWager } from 'builder/assets/actions';
import ObservableNumberInput from 'components/ObservableNumberInput';
import { selectWagers } from 'builder/assets/selectors';
const WagerInput = (props) =>
<ObservableNumberInput id={props.id} name={props.name} value={props.value} min={props.min} max={props.max} onChange={props.onChange} />;
WagerInput.propTypes = {
onChange: PropTypes.func.isRequired,
id: PropTypes.string,
name: PropTypes.string,
min: PropTypes.number,
max: PropTypes.number,
value: PropTypes.number
};
const mapStateToProps = (state) => {
return {
value: selectWagers(state)
};
};
const mapDispatchToProps = (dispatch) => {
return {
onChange: bindActionCreators(setWager, dispatch)
};
};
export default connect(
mapStateToProps,
mapDispatchToProps
)(WagerInput);
|
src/components/Test.js | ttrentham/Griddle | import React from 'react';
export default class Test extends React.Component {
render() {
return <div>Hi from component</div>;
}
}
|
test/integration/production/pages/svg-image.js | JeromeFitz/next.js | import React from 'react'
import Image from 'next/image'
const Page = () => {
return (
<div>
<h1>SVG with a script tag attempting XSS</h1>
<Image id="img" src="/xss.svg" width="100" height="100" />
<p id="msg">safe</p>
</div>
)
}
export default Page
|
examples/with-aphrodite/pages/index.js | nahue/next.js | import React from 'react'
import { StyleSheet, css } from 'aphrodite'
export default () => (
<div className={css(styles.root)}>
<h1 className={css(styles.title)}>My page</h1>
</div>
)
const styles = StyleSheet.create({
root: {
width: 80,
height: 60,
background: 'white',
':hover': {
background: 'black'
}
},
title: {
marginLeft: 5,
color: 'black',
fontSize: 22,
':hover': {
color: 'white'
}
}
})
|
client/src/Assistant/ApartmentFeatureInputs/RangeSelectionGroup.js | ciex/mietlimbo | // @flow
import React from 'react'
import autoBind from 'react-autobind'
import { intlShape } from 'react-intl'
import './Styles.css'
export type GroupData = {
positive: Array<string>,
negative: Array<string>
};
// Properties passed to a RangeSelectionGroup
type RangeSelectionGroupProps = {
changed: Object => any,
inputComponents: Object,
domain: string,
data: GroupData
};
// Properties passed by a RangeSelectionGroup to its input components
export type RangeInputProps = {
changed: (string, string) => any,
intl: intlShape,
value: boolean,
directValue: GroupData,
directChanged: {[string]: any} => any
};
/**
* Return numeric balance between pos and neg feature groups
*
* @param {[type]} props: GroupData Group data set
* @return {number} Balance
*/
export const groupBalance = (props: GroupData) =>
// eslint-disable-next-line eqeqeq
props == undefined ? 0 : props.positive.length - props.negative.length
class RangeSelectionGroup extends React.Component {
groupData: GroupData;
constructor(props: RangeSelectionGroupProps) {
super(props)
autoBind(this)
}
/**
* Handler to be called from input components when their data changes.
*
* @param {[type]} name: string Field name
* @param {[type]} positive: boolean True if positive feature
* @param {[type]} value: boolean True if feature applies
* @param {[type]} cb: ?( Optional callback
* @return {[type]} [description]
*/
handleChange(name: string, positive: boolean, value: boolean, cb: ?() => any) {
const cat = positive === true ? 'positive' : 'negative'
// If `value` is true, a feature was added, otherwise a feature was removed
const newFeatureList = this.props.data[cat].slice()
if (value === true) {
if (newFeatureList.indexOf(name) >= 0) {
// Don't store the same feature twice
// eslint-disable-next-line eqeqeq
if(cb != undefined) cb()
return
}
newFeatureList.splice(-1, 0, name)
} else {
const position = this.props.data[cat].indexOf(name)
if (position < 0) {
// Stop here if the feature to be removed is not on the list
// eslint-disable-next-line eqeqeq
if(cb != undefined) cb()
return
}
newFeatureList.splice(position, 1)
}
const updatedData = Object.assign({}, this.props.data, {
positive: positive === true ? newFeatureList : this.props.data.positive,
negative: positive === false ? newFeatureList : this.props.data.negative
})
this.props.changed({[this.props.domain]: updatedData}, cb)
}
/**
* Render the input group
*
* @return {[type]} [description]
*/
render() {
// The index of checked fields allows passing in the current value to the input
// componenet below by checking whether it's included in this index
const checkedFields = this.props.data === undefined ? []
: this.props.data.negative.concat(this.props.data.positive)
const inputElements = Object.keys(this.props.inputComponents).map(
k => React.createElement(
this.props.inputComponents[k],
{
changed: this.handleChange,
key: k,
value: (checkedFields.indexOf(k) >= 0),
directValue: this.props.data,
directChanged: this.props.changed
},
null)
)
return <div className="RangeSelectionGroup">{inputElements}</div>
}
}
export default RangeSelectionGroup |
node_modules/react-router/es6/RouteUtils.js | TarikHuber/react-redux-material-starter-kit | 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; };
import React from 'react';
function isValidChild(object) {
return object == null || React.isValidElement(object);
}
export function isReactChildren(object) {
return isValidChild(object) || Array.isArray(object) && object.every(isValidChild);
}
function createRoute(defaultProps, props) {
return _extends({}, defaultProps, props);
}
export function createRouteFromReactElement(element) {
var type = element.type;
var route = createRoute(type.defaultProps, element.props);
if (route.children) {
var childRoutes = createRoutesFromReactChildren(route.children, route);
if (childRoutes.length) route.childRoutes = childRoutes;
delete route.children;
}
return route;
}
/**
* Creates and returns a routes object from the given ReactChildren. JSX
* provides a convenient way to visualize how routes in the hierarchy are
* nested.
*
* import { Route, createRoutesFromReactChildren } from 'react-router'
*
* const routes = createRoutesFromReactChildren(
* <Route component={App}>
* <Route path="home" component={Dashboard}/>
* <Route path="news" component={NewsFeed}/>
* </Route>
* )
*
* Note: This method is automatically used when you provide <Route> children
* to a <Router> component.
*/
export function createRoutesFromReactChildren(children, parentRoute) {
var routes = [];
React.Children.forEach(children, function (element) {
if (React.isValidElement(element)) {
// Component classes may have a static create* method.
if (element.type.createRouteFromReactElement) {
var route = element.type.createRouteFromReactElement(element, parentRoute);
if (route) routes.push(route);
} else {
routes.push(createRouteFromReactElement(element));
}
}
});
return routes;
}
/**
* Creates and returns an array of routes from the given object which
* may be a JSX route, a plain object route, or an array of either.
*/
export function createRoutes(routes) {
if (isReactChildren(routes)) {
routes = createRoutesFromReactChildren(routes);
} else if (routes && !Array.isArray(routes)) {
routes = [routes];
}
return routes;
} |
app/containers/App/index.js | codermango/BetCalculator | /**
*
* 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)
*/
import React from 'react';
import Helmet from 'react-helmet';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
// Import the CSS reset, which HtmlWebpackPlugin transfers to the build folder
import 'sanitize.css/sanitize.css';
import styles from './styles.css';
function App(props) {
return (
<MuiThemeProvider>
<div className={styles.wrapper}>
<Helmet
titleTemplate="%s - React.js Boilerplate"
defaultTitle="React.js Boilerplate"
meta={[
{ name: 'description', content: 'A React.js Boilerplate application' },
]}
/>
{React.Children.toArray(props.children)}
</div>
</MuiThemeProvider>
);
}
App.propTypes = {
children: React.PropTypes.node,
};
export default App;
|
js/src/dapps/signaturereg.js | immartian/musicoin | // Copyright 2015, 2016 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import ReactDOM from 'react-dom';
import React from 'react';
import injectTapEventPlugin from 'react-tap-event-plugin';
injectTapEventPlugin();
import Application from './signaturereg/Application';
import '../../assets/fonts/Roboto/font.css';
import '../../assets/fonts/RobotoMono/font.css';
import './style.css';
ReactDOM.render(
<Application />,
document.querySelector('#container')
);
|
app/react/src/demo/Welcome.js | jribeiro/storybook | import React from 'react';
import PropTypes from 'prop-types';
import glamorous from 'glamorous';
const Main = glamorous.article({
margin: 15,
maxWidth: 600,
lineHeight: 1.4,
fontFamily: '"Helvetica Neue", Helvetica, "Segoe UI", Arial, freesans, sans-serif',
});
const Title = glamorous.h1({});
const Note = glamorous.p({
opacity: 0.5,
});
const InlineCode = glamorous.code({
fontSize: 15,
fontWeight: 600,
padding: '2px 5px',
border: '1px solid #eae9e9',
borderRadius: 4,
backgroundColor: '#f3f2f2',
color: '#3a3a3a',
});
const Link = glamorous.a({
color: '#1474f3',
textDecoration: 'none',
borderBottom: '1px solid #1474f3',
paddingBottom: 2,
});
const Welcome = props =>
<Main>
<Title>Welcome to storybook</Title>
<p>This is a UI component dev environment for your app.</p>
<p>
We've added some basic stories inside the
{' '}
<InlineCode>src/stories</InlineCode>
{' '}
directory.
<br />
A story is a single state of one or more UI components. You can have as many stories as
you want.
<br />
(Basically a story is like a visual test case.)
</p>
<p>
See these sample
{' '}
<Link onClick={props.showApp} role="button" tabIndex="0">stories</Link>
{' '}
for a component called
{' '}
<InlineCode>Button</InlineCode>
.
</p>
<p>
Just like that, you can add your own components as stories.
<br />
You can also edit those components and see changes right away.
<br />
(Try editing the <InlineCode>Button</InlineCode> stories
located at <InlineCode>src/stories/index.js</InlineCode>.)
</p>
<p>
Usually we create stories with smaller UI components in the app.<br />
Have a look at the
{' '}
<Link
href="https://storybook.js.org/basics/writing-stories"
target="_blank"
rel="noopener noreferrer"
>
Writing Stories
</Link>
{' '}
section in our documentation.
</p>
<Note>
<b>NOTE:</b>
<br />
Have a look at the
{' '}
<InlineCode>.storybook/webpack.config.js</InlineCode>
{' '}
to add webpack
loaders and plugins you are using in this project.
</Note>
</Main>;
Welcome.displayName = 'Welcome';
Welcome.propTypes = {
showApp: PropTypes.func,
};
Welcome.defaultProps = {
// eslint-disable-next-line no-console
showApp: () => console.log('Welcome to storybook!'),
};
export { Welcome as default };
|
packages/arwes/src/List/List.js | romelperez/prhone-ui | import React from 'react';
import PropTypes from 'prop-types';
import cx from 'classnames';
export default function List(props) {
const { theme, classes, node, className, children, ...etc } = props;
const cls = cx(classes.root, className);
return React.createElement(node, { className: cls, ...etc }, children);
}
List.propTypes = {
theme: PropTypes.any.isRequired,
classes: PropTypes.any.isRequired,
/**
* The list node type, e.g. ul.
*/
node: PropTypes.oneOf(['ul', 'ol', 'dl'])
};
List.defaultProps = {
node: 'ul'
};
|
src/js/Components/Team/TeamStats.js | dhenson02/fan2c | 'use strict';
import React from 'react';
class TeamStats extends React.Component {
constructor ( props ) {
super(props);
}
shouldComponentUpdate ( nextProps ) {
return nextProps.stats.id !== this.props.stats.id;
}
render () {
let stats = this.props.stats;
let ties = stats.h2ht !== '0' ?
<li>Ties: {stats.h2ht}</li> :
null;
let pf = parseInt(stats.pf, 10);
let pa = parseInt(stats.pa, 10);
let ratio = Math.round(100 * (pa / pf));
let ratioClass = ratio < 81 ?
'success' :
( ratio < 90 ? 'warning' : 'danger' );
return (
<ul>
<li>Wins: {stats.h2hw}</li>
<li>Losses: {stats.h2hl}</li>
{ties}
<li>Points scored: {pf}</li>
<li>Points against: {pa}</li>
<li className={`label label-${ratioClass}`}>Reverse Ratio: {ratio}%</li>
</ul>
);
}
}
export default TeamStats;
|
example/examples/FitToCoordinates.js | Gogowego/react-native-maps | import React from 'react';
import {
StyleSheet,
View,
Dimensions,
TouchableOpacity,
Text,
} from 'react-native';
import MapView from 'react-native-maps';
const { width, height } = Dimensions.get('window');
const ASPECT_RATIO = width / height;
const LATITUDE = 37.78825;
const LONGITUDE = -122.4324;
const LATITUDE_DELTA = 0.0922;
const LONGITUDE_DELTA = LATITUDE_DELTA * ASPECT_RATIO;
const SPACE = 0.01;
function createMarker(modifier = 1) {
return {
latitude: LATITUDE - (SPACE * modifier),
longitude: LONGITUDE - (SPACE * modifier),
};
}
const MARKERS = [
createMarker(),
createMarker(2),
createMarker(3),
createMarker(4),
];
const DEFAULT_PADDING = { top: 40, right: 40, bottom: 40, left: 40 };
class FitToCoordinates extends React.Component {
fitPadding() {
this.map.fitToCoordinates([MARKERS[2], MARKERS[3]], {
edgePadding: { top: 100, right: 100, bottom: 100, left: 100 },
animated: true,
});
}
fitBottomTwoMarkers() {
this.map.fitToCoordinates([MARKERS[2], MARKERS[3]], {
edgePadding: DEFAULT_PADDING,
animated: true,
});
}
fitAllMarkers() {
this.map.fitToCoordinates(MARKERS, {
edgePadding: DEFAULT_PADDING,
animated: true,
});
}
render() {
return (
<View style={styles.container}>
<MapView
ref={ref => { this.map = ref; }}
style={styles.map}
initialRegion={{
latitude: LATITUDE,
longitude: LONGITUDE,
latitudeDelta: LATITUDE_DELTA,
longitudeDelta: LONGITUDE_DELTA,
}}
>
{MARKERS.map((marker, i) => (
<MapView.Marker
key={i}
coordinate={marker}
/>
))}
</MapView>
<View style={styles.buttonContainer}>
<TouchableOpacity
onPress={() => this.fitPadding()}
style={[styles.bubble, styles.button]}
>
<Text>Fit Bottom Two Markers with Padding</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.fitBottomTwoMarkers()}
style={[styles.bubble, styles.button]}
>
<Text>Fit Bottom Two Markers</Text>
</TouchableOpacity>
<TouchableOpacity
onPress={() => this.fitAllMarkers()}
style={[styles.bubble, styles.button]}
>
<Text>Fit All Markers</Text>
</TouchableOpacity>
</View>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
...StyleSheet.absoluteFillObject,
justifyContent: 'flex-end',
alignItems: 'center',
},
map: {
...StyleSheet.absoluteFillObject,
},
bubble: {
backgroundColor: 'rgba(255,255,255,0.7)',
paddingHorizontal: 18,
paddingVertical: 12,
borderRadius: 20,
},
button: {
marginTop: 12,
paddingHorizontal: 12,
alignItems: 'center',
marginHorizontal: 10,
},
buttonContainer: {
flexDirection: 'column',
marginVertical: 20,
backgroundColor: 'transparent',
},
});
module.exports = FitToCoordinates;
|
src/svg-icons/hardware/cast.js | barakmitz/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let HardwareCast = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.1 0-2 .9-2 2v3h2V5h18v14h-7v2h7c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zM1 18v3h3c0-1.66-1.34-3-3-3zm0-4v2c2.76 0 5 2.24 5 5h2c0-3.87-3.13-7-7-7zm0-4v2c4.97 0 9 4.03 9 9h2c0-6.08-4.93-11-11-11z"/>
</SvgIcon>
);
HardwareCast = pure(HardwareCast);
HardwareCast.displayName = 'HardwareCast';
HardwareCast.muiName = 'SvgIcon';
export default HardwareCast;
|
app/components/SteelDayPage/SteelDayPage.js | tenhaus/bbwelding | import React from 'react';
import Radium from 'radium';
import _ from 'lodash';
import AltActions from '../../actions/AltActions';
import SteelDayStore from '../../stores/SteelDayStore';
import Page from '../Page/Page';
import Style from './_SteelDayPage.Style';
import FlyerImage from './images/Steel_Day_Flyer-01.jpg';
import Flyer from './images/Steel_Day_Flyer_for_website.pdf';
class SteelDayPage extends React.Component {
constructor() {
super();
this.onFormChanged = this.onFormChanged.bind(this);
this.submitForm = this.submitForm.bind(this);
this.renderFormErrors = this.renderFormErrors.bind(this);
this.renderForm = this.renderForm.bind(this);
this.onRegistrationChanged = this.onRegistrationChanged.bind(this);
this.state = {
name: '',
showNameError: false,
url: '',
email: '',
showEmailError: false,
phone: '',
showPhoneError: false,
store: SteelDayStore.getState()
};
}
componentDidMount() {
SteelDayStore.listen(this.onRegistrationChanged);
}
componentWillUnmount() {
SteelDayStore.unlisten(this.onRegistrationChanged);
}
onRegistrationChanged() {
console.log('changed', SteelDayStore.getState());
this.setState({
store: SteelDayStore.getState()
});
}
onFormChanged() {
this.setState({
name: React.findDOMNode(this.refs.nameInput).value,
url: React.findDOMNode(this.refs.urlInput).value,
email: React.findDOMNode(this.refs.emailInput).value,
phone: React.findDOMNode(this.refs.phoneInput).value,
});
}
submitForm(event) {
event.preventDefault();
var name = this.state.name.trim().length === 0;
var email = this.state.email.trim().length === 0;
var phone = this.state.phone.trim().length === 0;
this.setState({
showNameError: name,
showEmailError: email,
showPhoneError: phone
});
// Validation didn't pass
if(name || email || phone) return;
AltActions.submitSteelDayForm(
this.state.name,
this.state.url,
this.state.email,
this.state.phone
);
}
renderFormErrors() {
if(this.state.showNameError || this.state.showEmailError || this.state.showPhoneError) {
return (
<div style={Style.errorContent}>
<p>Registration failed</p>
<ul>
{this.state.showNameError ? <li>Please provide a name</li> : null}
{this.state.showPhoneError ? <li>Please provide your phone number</li> : null}
{this.state.showEmailError ? <li>Please provide your email address</li> : null}
</ul>
</div>
);
}
}
renderForm() {
let formErrors = this.renderFormErrors();
return (
<div style={Style.formContent}>
<h2>Register Here</h2>
{formErrors}
<form>
<div className='control-group required'>
<label htmlFor='name'>Name</label>
<input id='name' value={this.state.name} ref='nameInput'
onChange={this.onFormChanged} />
<p className='hint'>Name is mandatory</p>
</div>
<div className='control-group'>
<label htmlFor='url'>Comany Name</label>
<input id='url' value={this.state.url} ref='urlInput'
onChange={this.onFormChanged} />
<p className='hint'>Your primary site</p>
</div>
<div className='control-group required'>
<label htmlFor='email'>Email</label>
<input id='email' value={this.state.email} ref='emailInput'
onChange={this.onFormChanged} />
<p className='hint'>Your email will not be published</p>
</div>
<div className='control-group required'>
<label htmlFor='phone'>Phone</label>
<input id='phone' value={this.state.phone} ref='phoneInput'
onChange={this.onFormChanged} />
<p className='hint'>Mobile or land-line</p>
</div>
<button style={Style.button} type='submit'
onClick={this.submitForm}>Register</button>
</form>
</div>
);
}
renderConfirmation() {
return (
<h1 style={Style.confirmation}>Thank you for registering!</h1>
);
}
render() {
let registrationContent = null;
if(this.state.store.registered) {
registrationContent = this.renderConfirmation();
}
else {
registrationContent = this.renderForm();
}
return (
<Page title='Register now for Steel Day 2016!'>
<div style={Style.split} key='split'>
<div style={Style.content}>
<p>Attendees will tour a modern 35,000 sq ft fabrication shop with advanced CNC machinery and witness demonstrations of interoperability between engineering, detailing, estimating, production control and bar coding softwares including: Bluebeam, SDS/2, Fabsuite and P2 Systems, Infosight Corporation, Shop Data, and Peddinghaus equipment. Attendees will learn about the processes steel fabricators go through from receiving the steel through to shipping steel to the job site. There will be an AISC representative present to give a presentation, Structural Steel: Innovations for your Next Project. You will receive a certificate of attendance (credit) for this class.</p>
<p><span style={Style.lineHead}>Date:</span>Friday, September 30th, 2016</p>
<p><span style={Style.lineHead}>Time/Length:</span>10:00 am – 3:00 pm</p>
<p><span style={Style.lineHead}>Location:</span>4640 North Point Blvd, Edgemere, MD 21219</p>
<p><span style={Style.lineHead}>Directions:</span>Directions can be found <a href='/#/contact'>here</a></p>
<p><span style={Style.lineHead}>Food:</span>Lunch will be provided from 12:00 noon – 2:00 pm</p>
<p><span style={Style.lineHead}>Dress Code:</span>Business casual/jeans welcome. (Ladies no open toed or high heeled shoes)</p>
<p><span style={Style.lineHead}>Safety Gear:</span>Long pants and closed toe shoes required for facility tours. (safety glasses will be provided)</p>
<p><span style={Style.lineHead}>Of Interest To:</span>Architects, Engineer, Contractors, Students, Developers – all welcome!</p>
{registrationContent}
</div>
<div style={Style.image} key="image">
<a href={Flyer} title="Steel Day Flyer 2016" target="_blank">
<img src={FlyerImage} alt="Steel Day Flyer 2016"/>
</a>
</div>
</div>
</Page>
);
}
}
export default Radium(SteelDayPage);
|
src/routes.js | VolodiaGP/DW_Front | import React from 'react';
import {IndexRoute, Route} from 'react-router';
import { isLoaded as isAuthLoaded, load as loadAuth } from 'redux/modules/auth';
import {
App,
Chat,
Home,
Widgets,
About,
Login,
LoginSuccess,
Survey,
NotFound,
Pagination,
Map,
Region,
Search,
InvestObject
} from 'containers';
export default (store) => {
const requireLogin = (nextState, replace, cb) => {
function checkAuth() {
const { auth: { user }} = store.getState();
if (!user) {
// oops, not logged in, so can't be here!
replace('/');
}
cb();
}
if (!isAuthLoaded(store.getState())) {
store.dispatch(loadAuth()).then(checkAuth);
} else {
checkAuth();
}
};
/**
* Please keep routes in alphabetical order
*/
return (
<Route path="/" component={App}>
{ /* Home (main) route */ }
<IndexRoute component={Home}/>
{ /* Routes requiring login */ }
<Route onEnter={requireLogin}>
<Route path="chat" component={Chat}/>
<Route path="loginSuccess" component={LoginSuccess}/>
</Route>
{ /* Routes */ }
<Route path="map" component={Map}/>
<Route path="about" component={About}/>
<Route path="login" component={Login}/>
<Route path="pagination" component={Pagination}/>
<Route path="survey" component={Survey}/>
<Route path="widgets" component={Widgets}/>
<Route path="region/:id" component={Region} />
<Route path="search" component={Search} />
<Route path="invest_object/:id" component={InvestObject} />
{ /* Catch all route */ }
<Route path="*" component={NotFound} status={404} />
</Route>
);
};
|
examples/huge-apps/routes/Course/routes/Announcements/routes/Announcement/components/Announcement.js | omerts/react-router | import React from 'react';
class Announcement extends React.Component {
//static loadProps (params, cb) {
//cb(null, {
//announcement: COURSES[params.courseId].announcements[params.announcementId]
//});
//}
render () {
//var { title, body } = this.props.announcement;
var { courseId, announcementId } = this.props.params;
var { title, body } = COURSES[courseId].announcements[announcementId];
return (
<div>
<h4>{title}</h4>
<p>{body}</p>
</div>
);
}
}
export default Announcement;
|
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.