path stringlengths 5 195 | repo_name stringlengths 5 79 | content stringlengths 25 1.01M |
|---|---|---|
app/components/case_task_manager.js | uglymugs/JustNUM | import React from 'react';
import ConnectedCaseTaskList from '../containers/connected_case_task_list';
import ConnectedNewTaskForm from '../containers/connected_new_task_form';
const CaseTaskManager = () =>
<div>
<ConnectedNewTaskForm />
<ConnectedCaseTaskList />
</div>;
export default CaseTaskManager;
|
library_js/src/components/logIn.js | HoldYourBreath/Library | import React, { Component } from 'react';
import {FormGroup,
Button,
Col,
Alert,
Form,
FormControl,
ControlLabel} from 'react-bootstrap';
import { Redirect } from 'react-router';
class LogIn extends Component {
constructor(props) {
super(props);
this.state = {
errMsg: null,
signum: "",
password: "",
redirect: false
};
}
authenticate(e) {
this.props.sessionStore.validateUserSession(
this.state.signum,
this.state.password,
this.props.onAuthenticationDone);
e.preventDefault();
}
onFormInput(e) {
this.setState({[e.target.id]: e.target.value});
}
render() {
const ErrAlert = this.state.errorMsg ? <Alert bsStyle="danger"><strong>{this.state.errorMsg}</strong></Alert> : null;
if (this.state.redirect) {
return <Redirect to={'/'}/>;
}
return (
<div className="jumbotron">
<Form horizontal onSubmit={this.authenticate.bind(this)}>
<FormGroup controlId="signum">
<p>
Login using your windows credentials
</p>
</FormGroup>
{ErrAlert}
<FormGroup controlId="signum">
<Col componentClass={ControlLabel} sm={2}>
Signum
</Col>
<Col sm={10}>
<FormControl
value={this.state.signum}
onChange={this.onFormInput.bind(this)}
type="text"
placeholder="Signum" />
</Col>
</FormGroup>
<FormGroup controlId="password">
<Col componentClass={ControlLabel} sm={2}>
Password
</Col>
<Col sm={10}>
<FormControl
value={this.state.password}
onChange={this.onFormInput.bind(this)}
type="password"
placeholder="password"/>
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button type="submit">
Login
</Button>
</Col>
</FormGroup>
</Form>
</div>
);
}
}
export default LogIn; |
frontend/src/app/containers/ErrorPage.js | 6a68/idea-town | import React from 'react';
import View from '../components/View';
export default class ErrorPage extends React.Component {
render() {
return (
<View spaceBetween={true} showNewsletterFooter={false} {...this.props}>
<div className="centered-banner">
<div id="four-oh-four" className="modal delayed-fade-in">
<header className="modal-header-wrapper neutral-modal">
<h1 data-l10n-id="errorHeading" className="modal-header">Whoops!</h1>
</header>
<div className="modal-content">
<p data-l10n-id="errorMessage">Looks like we broke something. <br /> Maybe try again later.</p>
</div>
</div>
<div className="copter-wrapper">
<div className="copter fade-in-fly-up"></div>
</div>
</div>
</View>
);
}
}
ErrorPage.propTypes = {
uninstallAddon: React.PropTypes.func,
sendToGA: React.PropTypes.func,
openWindow: React.PropTypes.func
};
|
src/components/common/UserInput/index.js | mcrice123/simple-react-example | import React from 'react';
const UserInput = ({ value, placeholder, onChange, style }) => {
return(
<input value={value} placeholder={placeholder} onChange={onChange} style={style} />
);
};
export default UserInput; |
src/components/LightingAmbient.js | kelsonic/Kelsonic | // Dependencies
import 'aframe';
import React from 'react';
const LightingAmbient = () => (
<a-light
color="#fff"
type="ambient"
/>
);
export default LightingAmbient;
|
src/pages/page-2.js | whirish/website | import React from 'react'
import { Link } from 'gatsby'
import Layout from '../components/layout'
const SecondPage = () => (
<Layout>
<h1>Hi from the second page</h1>
<p>Welcome to page 2</p>
<Link to="/">Go back to the homepage</Link>
</Layout>
)
export default SecondPage
|
addons/centered/src/index.js | shilman/storybook | import React from 'react';
const style = {
position: 'fixed',
top: 0,
left: 0,
bottom: 0,
right: 0,
display: 'flex',
alignItems: 'center',
justifyContent: 'center',
};
export default function(storyFn) {
return <div style={style}>{storyFn()}</div>;
}
|
index.ios.js | jefflanzi/rn-app-template | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View
} from 'react-native';
export default class appTemplate extends Component {
render() {
return (
<View style={styles.container}>
<Text style={styles.welcome}>
Welcome to React Native!
</Text>
<Text style={styles.instructions}>
To get started, edit index.ios.js
</Text>
<Text style={styles.instructions}>
Press Cmd+R to reload,{'\n'}
Cmd+D or shake for dev menu
</Text>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
AppRegistry.registerComponent('appTemplate', () => appTemplate);
|
src/utils/CustomPropTypes.js | blue68/react-bootstrap | import React from 'react';
import warning from 'react/lib/warning';
import childrenToArray from './childrenToArray';
const ANONYMOUS = '<<anonymous>>';
/**
* Create chain-able isRequired validator
*
* Largely copied directly from:
* https://github.com/facebook/react/blob/0.11-stable/src/core/ReactPropTypes.js#L94
*/
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName) {
componentName = componentName || ANONYMOUS;
if (props[propName] == null) {
if (isRequired) {
return new Error(
`Required prop '${propName}' was not specified in '${componentName}'.`
);
}
} else {
return validate(props, propName, componentName);
}
}
let chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function errMsg(props, propName, componentName, msgContinuation) {
return `Invalid prop '${propName}' of value '${props[propName]}'` +
` supplied to '${componentName}'${msgContinuation}`;
}
function createMountableChecker() {
function validate(props, propName, componentName) {
if (typeof props[propName] !== 'object' ||
typeof props[propName].render !== 'function' && props[propName].nodeType !== 1) {
return new Error(
errMsg(props, propName, componentName,
', expected a DOM element or an object that has a `render` method')
);
}
}
return createChainableTypeChecker(validate);
}
function createKeyOfChecker(obj) {
function validate(props, propName, componentName) {
let propValue = props[propName];
if (!obj.hasOwnProperty(propValue)) {
let valuesString = JSON.stringify(Object.keys(obj));
return new Error(
errMsg(props, propName, componentName, `, expected one of ${valuesString}.`)
);
}
}
return createChainableTypeChecker(validate);
}
function createSinglePropFromChecker(arrOfProps) {
function validate(props, propName) {
const usedPropCount = arrOfProps
.map(listedProp => props[listedProp])
.reduce((acc, curr) => acc + (curr !== undefined ? 1 : 0), 0);
if (usedPropCount > 1) {
const [first, ...others] = arrOfProps;
const message = `${others.join(', ')} and ${first}`;
return new Error(
`Invalid prop '${propName}', only one of the following ` +
`may be provided: ${message}`
);
}
}
return validate;
}
function all(propTypes) {
if (propTypes === undefined) {
throw new Error('No validations provided');
}
if (!(propTypes instanceof Array)) {
throw new Error('Invalid argument must be an array');
}
if (propTypes.length === 0) {
throw new Error('No validations provided');
}
return function validate(props, propName, componentName) {
for (let i = 0; i < propTypes.length; i++) {
let result = propTypes[i](props, propName, componentName);
if (result !== undefined && result !== null) {
return result;
}
}
};
}
function createElementTypeChecker() {
function validate(props, propName, componentName) {
let errBeginning = errMsg(props, propName, componentName,
'. Expected an Element `type`');
if (typeof props[propName] !== 'function') {
if (React.isValidElement(props[propName])) {
return new Error(errBeginning + ', not an actual Element');
}
if (typeof props[propName] !== 'string') {
return new Error(errBeginning +
' such as a tag name or return value of React.createClass(...)');
}
}
}
return createChainableTypeChecker(validate);
}
export default {
deprecated(propType, explanation) {
return function validate(props, propName, componentName) {
if (props[propName] != null) {
warning(false, `"${propName}" property of "${componentName}" has been deprecated.\n${explanation}`);
}
return propType(props, propName, componentName);
};
},
isRequiredForA11y(propType) {
return function validate(props, propName, componentName) {
if (props[propName] == null) {
return new Error(
'The prop `' + propName + '` is required to make ' + componentName + ' accessible ' +
'for users using assistive technologies such as screen readers `'
);
}
return propType(props, propName, componentName);
};
},
requiredRoles(...roles) {
return createChainableTypeChecker(
function requiredRolesValidator(props, propName, component) {
let missing;
let children = childrenToArray(props.children);
let inRole = (role, child) => role === child.props.bsRole;
roles.every(role => {
if (!children.some(child => inRole(role, child))) {
missing = role;
return false;
}
return true;
});
if (missing) {
return new Error(`(children) ${component} - Missing a required child with bsRole: ${missing}. ` +
`${component} must have at least one child of each of the following bsRoles: ${roles.join(', ')}`);
}
});
},
exclusiveRoles(...roles) {
return createChainableTypeChecker(
function exclusiveRolesValidator(props, propName, component) {
let children = childrenToArray(props.children);
let duplicate;
roles.every(role => {
let childrenWithRole = children.filter(child => child.props.bsRole === role);
if (childrenWithRole.length > 1) {
duplicate = role;
return false;
}
return true;
});
if (duplicate) {
return new Error(
`(children) ${component} - Duplicate children detected of bsRole: ${duplicate}. ` +
`Only one child each allowed with the following bsRoles: ${roles.join(', ')}`);
}
});
},
/**
* Checks whether a prop provides a DOM element
*
* The element can be provided in two forms:
* - Directly passed
* - Or passed an object that has a `render` method
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
mountable: createMountableChecker(),
/**
* Checks whether a prop provides a type of element.
*
* The type of element can be provided in two forms:
* - tag name (string)
* - a return value of React.createClass(...)
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
elementType: createElementTypeChecker(),
/**
* Checks whether a prop matches a key of an associated object
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
keyOf: createKeyOfChecker,
/**
* Checks if only one of the listed properties is in use. An error is given
* if multiple have a value
*
* @param props
* @param propName
* @param componentName
* @returns {Error|undefined}
*/
singlePropFrom: createSinglePropFromChecker,
all
};
|
react-components/src/library/components/browse-page/resource-license.js | concord-consortium/rigse | import React from 'react'
import Component from '../../helpers/component'
const ResourceLicense = Component({
render: function () {
const resourceName = this.props.resourceName
const license = this.props.license_info
const credits = this.props.credits
if (!license) {
return null
}
let attributionName = 'The Concord Consortium'
let attributionUrl = 'https://concord.org/'
let licenseDescription = !credits
? license.description
: license.description.replace('the Concord Consortium', credits)
// alter attribution values when all material should be attributed to a specific project or partner
if (Portal.theme === 'ngss-assessment') {
attributionName = 'The Next Generation Science Assessment Project'
attributionUrl = 'http://nextgenscienceassessment.org/'
licenseDescription = license.description.replace('the Concord Consortium', attributionName)
}
const licenseAttribution = license.code === 'CC0'
? ''
: !credits
? <p>Suggested attribution: {resourceName} by <a href={attributionUrl}>{attributionName}</a> is licensed under <a href={license.deed}>{license.code}</a>.</p>
: <p>Suggested attribution: {resourceName} by {credits} is licensed under <a href={license.deed}>{license.code}</a>.</p>
return (
<div className='portal-pages-resource-lightbox-license'>
<hr />
<h2>License</h2>
<div>
{license.image !== '' && <img src={license.image} alt={license.code} />}
</div>
<h3>{license.code}</h3>
<p>{license.name}</p>
<p>{licenseDescription}</p>
<p><a href={license.deed}>{license.code} (human-readable summary)</a><br />
<a href={license.legal}>{license.code} (full license text)</a></p>
{licenseAttribution}
</div>
)
}
})
export default ResourceLicense
|
packages/flow-upgrade/src/upgrades/0.53.0/ReactComponentExplicitTypeArgs/__tests__/fixtures/All.js | facebook/flow | // @flow
import React from 'react';
class MyComponent extends React.Component {
static defaultProps: DefaultProps = {};
props: Props;
state: State = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
const expression = () =>
class extends React.Component {
static defaultProps: DefaultProps = {};
props: Props;
state: State = {};
defaultProps: T;
static props: T;
static state: T;
a: T;
b = 5;
c: T = 5;
method() {}
}
|
20161118/React-Native-Redux-Demo-master/App/containers/firstPage.js | fengnovo/react-native | 'use strict';
import React, { Component } from 'react';
import {
AppRegistry,
StyleSheet,
Text,
View,
Navigator,
} from 'react-native';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Button from 'react-native-button';
import { store } from '../store/index.js';
import { increment, decrement } from '../actions/actionCreator.js';
import SecondPage from './secondPage.js';
export default class FirstPage extends Component {
constructor(props) {
super(props);
}
render() {
console.log(this.props);
let counter = this.props.counter;
return(
<View style={styles.container}>
<Text style={styles.welcome}>
{counter}
</Text>
<Button
style={{fontSize: 30}}
onPress={() => this._onIncrement()}>
+
</Button>
<Button
style={{fontSize: 30}}
onPress={() => this._onDecrement()}>
-
</Button>
<Button
style={{fontSize: 30}}
onPress={() => this._onJumpNextPage()}
>
Jump
</Button>
</View>
);
}
_onIncrement() {
store.dispatch(increment());
}
_onDecrement() {
store.dispatch(decrement());
}
_onJumpNextPage() {
const { navigator } = this.props;
let nextPageName = 'SecondPage';
let nextPageComponent: SecondPage;
if(navigator) {
navigator.push({
name: 'SecondPage',
component: SecondPage,
});
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 25,
textAlign: 'center',
margin: 10,
},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},
});
|
src/Main/ChangelogTabTitle.js | hasseboulen/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
import Wrapper from 'common/Wrapper';
import CORE_CHANGELOG from '../CHANGELOG';
const SECONDS_IN_DAY = 86400;
const DAYS_CONSIDERED_RECENT = 7;
class ChangelogTabTitle extends React.PureComponent {
static contextTypes = {
config: PropTypes.shape({
changelog: PropTypes.oneOfType([PropTypes.array, PropTypes.string]).isRequired,
}).isRequired,
};
render() {
let changelog = this.context.config.changelog;
let recentChanges = 0;
if (changelog instanceof Array) {
// The changelog includes entries from the spec and core, so the count should too
changelog = [
...CORE_CHANGELOG,
...changelog,
];
// TODO: Instead of showing the amount in recent times, show the amount of new changes since last view
recentChanges = changelog.reduce((total, entry) => {
if (((+new Date() - entry.date) / 1000) < (SECONDS_IN_DAY * DAYS_CONSIDERED_RECENT)) {
total += 1;
}
return total;
}, 0);
}
return (
<Wrapper>
Changelog {recentChanges > 0 && <span className="badge">{recentChanges}</span>}
</Wrapper>
);
}
}
export default ChangelogTabTitle;
|
src/svg-icons/maps/local-movies.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let MapsLocalMovies = (props) => (
<SvgIcon {...props}>
<path d="M18 3v2h-2V3H8v2H6V3H4v18h2v-2h2v2h8v-2h2v2h2V3h-2zM8 17H6v-2h2v2zm0-4H6v-2h2v2zm0-4H6V7h2v2zm10 8h-2v-2h2v2zm0-4h-2v-2h2v2zm0-4h-2V7h2v2z"/>
</SvgIcon>
);
MapsLocalMovies = pure(MapsLocalMovies);
MapsLocalMovies.displayName = 'MapsLocalMovies';
MapsLocalMovies.muiName = 'SvgIcon';
export default MapsLocalMovies;
|
public/javascripts/rubric_assessment.js | djbender/canvas-lms | /*
* Copyright (C) 2011 - 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 I18n from 'i18n!rubric_assessment'
import $ from 'jquery'
import _ from 'lodash'
import React from 'react'
import ReactDOM from 'react-dom'
import htmlEscape from './str/htmlEscape'
import TextHelper from 'compiled/str/TextHelper'
import round from 'compiled/util/round'
import numberHelper from 'jsx/shared/helpers/numberHelper'
import './jquery.instructure_forms' /* fillFormData */
import 'jqueryui/dialog'
import './jquery.instructure_misc_plugins' /* showIf */
import './jquery.templateData'
import './vendor/jquery.scrollTo'
import 'compiled/jquery.rails_flash_notifications'
import Rubric from 'jsx/rubrics/Rubric'
import {fillAssessment, updateAssociationData} from 'jsx/rubrics/helpers'
// TODO: stop managing this in the view and get it out of the global scope submissions/show.html.erb
/* global rubricAssessment */
window.rubricAssessment = {
init() {
const $rubric_criterion_comments_dialog = $('#rubric_criterion_comments_dialog')
$('.rubric')
.delegate('.rating', 'click', function(event) {
$(this)
.parents('.criterion')
.find('.criterion_points')
.val(
$(this)
.find('.points')
.text()
)
.change()
})
.delegate('.long_description_link', 'click', function(event) {
event.preventDefault()
if (
!$(this)
.parents('.rubric')
.hasClass('editing')
) {
const data = $(this)
.parents('.criterion')
.getTemplateData({textValues: ['long_description', 'description']}),
is_learning_outcome = $(this)
.parents('.criterion')
.hasClass('learning_outcome_criterion')
$('#rubric_long_description_dialog')
.fillTemplateData({data, htmlValues: is_learning_outcome ? ['long_description'] : []})
.find('.editing')
.hide()
.end()
.find('.displaying')
.show()
.end()
.dialog({
title: I18n.t('Criterion Long Description'),
width: 400
})
}
})
.delegate('.criterion .saved_custom_rating', 'change', function() {
if (
$(this)
.parents('.rubric')
.hasClass('assessing')
) {
const val = $(this).val()
if (val && val.length > 0) {
$(this)
.parents('.custom_ratings_entry')
.find('.custom_rating_field')
.val(val)
}
}
})
.delegate('.criterion_comments_link', 'click', function(event) {
event.preventDefault()
const $rubric_criterion_comments_link = $(this)
const $criterion = $(this).parents('.criterion')
const comments = $criterion.getTemplateData({textValues: ['custom_rating']}).custom_rating
const editing = $(this).parents('.rubric.assessing').length > 0
const data = {
criterion_comments: comments,
criterion_description: $criterion.find('.description:first').text()
}
$rubric_criterion_comments_dialog.data('current_rating', $criterion)
$rubric_criterion_comments_dialog.fillTemplateData({data})
$rubric_criterion_comments_dialog.fillFormData(data)
$rubric_criterion_comments_dialog.find('.editing').showIf(editing)
$rubric_criterion_comments_dialog.find('.displaying').showIf(!editing)
$rubric_criterion_comments_dialog.dialog({
title: I18n.t('Additional Comments'),
width: 400,
close() {
$rubric_criterion_comments_link.focus()
}
})
$rubric_criterion_comments_dialog.find('textarea.criterion_comments').focus()
})
// cant use a .delegate because up above when we delegate '.rating' 'click' it calls .change() and that doesnt bubble right so it doesen't get caught
.find('.criterion_points')
.bind('keyup change blur', function(event) {
const $obj = $(event.target)
if ($obj.parents('.rubric').hasClass('assessing')) {
let val = numberHelper.parse($obj.val())
if (isNaN(val)) {
val = null
}
const $criterion = $obj.parents('.criterion')
$criterion.find('.rating.selected').removeClass('selected')
if (val || val === 0) {
$criterion.find('.criterion_description').addClass('completed')
rubricAssessment.highlightCriterionScore($criterion, val)
} else {
$criterion.find('.criterion_description').removeClass('completed')
}
let total = 0
$obj
.parents('.rubric')
.find('.criterion:visible:not(.ignore_criterion_for_scoring) .criterion_points')
.each(function() {
let criterionPoints = numberHelper.parse($(this).val(), 10)
if (isNaN(criterionPoints)) {
criterionPoints = 0
}
total += criterionPoints
})
total = window.rubricAssessment.roundAndFormat(total)
$obj
.parents('.rubric')
.find('.rubric_total')
.text(total)
}
})
$('.rubric_summary').delegate('.rating_comments_dialog_link', 'click', function(event) {
event.preventDefault()
const $rubric_rating_comments_link = $(this)
const $criterion = $(this).parents('.criterion')
const comments = $criterion.getTemplateData({textValues: ['rating_custom']}).rating_custom
const data = {
criterion_comments: comments,
criterion_description: $criterion.find('.description_title:first').text()
}
$rubric_criterion_comments_dialog.data('current_rating', $criterion)
$rubric_criterion_comments_dialog.fillTemplateData({data})
$rubric_criterion_comments_dialog.fillFormData(data)
$rubric_criterion_comments_dialog.find('.editing').hide()
$rubric_criterion_comments_dialog.find('.displaying').show()
$rubric_criterion_comments_dialog.dialog({
title: I18n.t('Additional Comments'),
width: 400,
close() {
$rubric_rating_comments_link.focus()
}
})
$rubric_criterion_comments_dialog.find('.criterion_description').focus()
})
$rubric_criterion_comments_dialog.find('.save_button').click(() => {
const comments = $rubric_criterion_comments_dialog.find('textarea.criterion_comments').val(),
$criterion = $rubric_criterion_comments_dialog.data('current_rating')
if ($criterion) {
$criterion.find('.custom_rating').text(comments)
$criterion.find('.criterion_comments').toggleClass('empty', !comments)
}
$rubric_criterion_comments_dialog.dialog('close')
})
$rubric_criterion_comments_dialog.find('.cancel_button').click(event => {
$rubric_criterion_comments_dialog.dialog('close')
})
setInterval(rubricAssessment.sizeRatings, 2500)
},
checkScoreAdjustment: ($criterion, rating, rawData) => {
const rawPoints = rawData[`rubric_assessment[criterion_${rating.criterion_id}][points]`]
const points = rubricAssessment.roundAndFormat(rating.points)
if (rawPoints > points) {
const criterionDescription = htmlEscape($criterion.find('.description_title').text())
$.flashWarning(
I18n.t(
'Extra credit not permitted on outcomes, ' +
'score adjusted to maximum possible for %{outcome}',
{outcome: criterionDescription}
)
)
}
},
highlightCriterionScore($criterion, val) {
$criterion.find('.rating').each(function() {
const rating_val = numberHelper.parse(
$(this)
.find('.points')
.text()
)
const use_range = $criterion.find('.criterion_use_range').attr('checked')
if (rating_val === val) {
$(this).addClass('selected')
} else if (use_range) {
const $nextRating = $(this).next('.rating')
let min_value = 0
if ($nextRating.find('.points').text()) {
min_value = numberHelper.parse($nextRating.find('.points').text())
}
if (rating_val > val && min_value < val) {
$(this).addClass('selected')
}
}
})
},
sizeRatings() {
const $visibleCriteria = $('.rubric .criterion:visible')
if ($visibleCriteria.length) {
const scrollTop = $.windowScrollTop()
$('.rubric .criterion:visible').each(function() {
const $this = $(this),
$ratings = $this.find('.ratings:visible')
if ($ratings.length) {
const $ratingsContainers = $ratings.find('.rating .container').css('height', ''),
maxHeight = Math.max(
$ratings.height(),
$this.find('.criterion_description .container').height()
)
// the -10 here is the padding on the .container.
$ratingsContainers.css('height', maxHeight - 10 + 'px')
}
})
$('html,body').scrollTop(scrollTop)
}
},
assessmentData($rubric) {
$rubric = rubricAssessment.findRubric($rubric)
const data = {}
if (ENV.RUBRIC_ASSESSMENT.assessment_user_id || $rubric.find('.user_id').length > 0) {
data['rubric_assessment[user_id]'] =
ENV.RUBRIC_ASSESSMENT.assessment_user_id || $rubric.find('.user_id').text()
} else {
data['rubric_assessment[anonymous_id]'] =
ENV.RUBRIC_ASSESSMENT.anonymous_id || $rubric.find('.anonymous_id').text()
}
data['rubric_assessment[assessment_type]'] =
ENV.RUBRIC_ASSESSMENT.assessment_type || $rubric.find('.assessment_type').text()
if (ENV.nonScoringRubrics && this.currentAssessment !== undefined) {
const assessment = this.currentAssessment
assessment.data.forEach(criteriaAssessment => {
const pre = `rubric_assessment[criterion_${criteriaAssessment.criterion_id}]`
const section = key => `${pre}${key}`
const points = criteriaAssessment.points.value
data[section('[rating_id]')] = criteriaAssessment.id
data[section('[points]')] = !Number.isNaN(points) ? points : undefined
data[section('[description]')] = criteriaAssessment.description
data[section('[comments]')] = criteriaAssessment.comments || ''
data[section('[save_comment]')] =
criteriaAssessment.saveCommentsForLater === true ? '1' : '0'
})
} else {
$rubric.find('.criterion:not(.blank)').each(function() {
const id = $(this).attr('id')
const pre = 'rubric_assessment[' + id + ']'
const points = numberHelper.parse(
$(this)
.find('.criterion_points')
.val()
)
data[pre + '[points]'] = !isNaN(points) ? points : undefined
if ($(this).find('.rating.selected')) {
data[pre + '[description]'] = $(this)
.find('.rating.selected .description')
.text()
data[pre + '[comments]'] = $(this)
.find('.custom_rating')
.text()
}
if ($(this).find('.custom_rating_field:visible').length > 0) {
data[pre + '[comments]'] = $(this)
.find('.custom_rating_field:visible')
.val()
data[pre + '[save_comment]'] = $(this)
.find('.save_custom_rating')
.attr('checked')
? '1'
: '0'
}
})
}
return data
},
findRubric($rubric) {
if (!$rubric.hasClass('rubric')) {
let $new_rubric = $rubric.closest('.rubric')
if ($new_rubric.length === 0) {
$new_rubric = $rubric.find('.rubric:first')
}
$rubric = $new_rubric
}
return $rubric
},
updateRubricAssociation($rubric, data) {
const summary_data = data.summary_data
if (ENV.nonScoringRubrics && this.currentAssessment !== undefined) {
const assessment = this.currentAssessment
updateAssociationData(this.currentAssociation, assessment)
} else if (summary_data && summary_data.saved_comments) {
for (const id in summary_data.saved_comments) {
const comments = summary_data.saved_comments[id],
$holder = $rubric
.find('#criterion_' + id)
.find('.saved_custom_rating_holder')
.hide(),
$saved_custom_rating = $holder.find('.saved_custom_rating')
$saved_custom_rating.find('.comment').remove()
$saved_custom_rating
.empty()
.append('<option value="">' + htmlEscape(I18n.t('[ Select ]')) + '</option>')
for (const jdx in comments) {
if (comments[jdx]) {
$saved_custom_rating.append(
'<option value="' +
htmlEscape(comments[jdx]) +
'">' +
htmlEscape(TextHelper.truncateText(comments[jdx], {max: 50})) +
'</option>'
)
$holder.show()
}
}
}
}
},
fillAssessment,
populateNewRubric(container, assessment, rubricAssociation) {
if (ENV.nonScoringRubrics && ENV.rubric) {
const assessing = container.hasClass('assessing')
const setCurrentAssessment = currentAssessment => {
rubricAssessment.currentAssessment = currentAssessment
render(currentAssessment)
}
const association = rubricAssessment.currentAssociation || rubricAssociation
rubricAssessment.currentAssociation = association
const render = currentAssessment => {
ReactDOM.render(
<Rubric
allowExtraCredit={ENV.outcome_extra_credit_enabled}
onAssessmentChange={assessing ? setCurrentAssessment : null}
rubric={ENV.rubric}
rubricAssessment={currentAssessment}
customRatings={ENV.outcome_proficiency ? ENV.outcome_proficiency.ratings : []}
rubricAssociation={rubricAssociation}
>
{null}
</Rubric>,
container.get(0)
)
}
setCurrentAssessment(
rubricAssessment.fillAssessment(ENV.rubric, assessment || {}, ENV.RUBRIC_ASSESSMENT)
)
const header = container.find('th').first()
header.attr('tabindex', -1).focus()
} else {
rubricAssessment.populateRubric(container, assessment)
}
},
populateRubric($rubric, data, submitted_data = null) {
$rubric = rubricAssessment.findRubric($rubric)
const id = $rubric.attr('id').substring(7)
if (ENV.RUBRIC_ASSESSMENT.assessment_user_id || data.user_id) {
$rubric.find('.user_id').text(ENV.RUBRIC_ASSESSMENT.assessment_user_id || data.user_id)
} else {
$rubric.find('.anonymous_id').text(ENV.RUBRIC_ASSESSMENT.anonymous_id || data.anonymous_id)
}
$rubric
.find('.assessment_type')
.text(ENV.RUBRIC_ASSESSMENT.assessment_type || data.assessment_type)
$rubric
.find('.criterion_description')
.removeClass('completed')
.removeClass('original_completed')
.end()
.find('.rating')
.removeClass('selected')
.removeClass('original_selected')
.end()
.find('.custom_rating_field')
.val('')
.end()
.find('.custom_rating_comments')
.text('')
.end()
.find('.criterion_points')
.val('')
.change()
.end()
.find('.criterion_rating_points')
.text('')
.end()
.find('.custom_rating')
.text('')
.end()
.find('.save_custom_rating')
.attr('checked', false)
$rubric.find('.criterion_comments').addClass('empty')
if (data) {
const assessment = data
let total = 0
for (const idx in assessment.data) {
var rating = assessment.data[idx]
const comments = rating.comments_enabled ? rating.comments : rating.description
if (rating.comments_enabled && rating.comments_html) {
var comments_html = rating.comments_html
} else {
var comments_html = htmlEscape(comments)
}
const $criterion = $rubric.find('#criterion_' + rating.criterion_id)
if (!rating.id) {
$criterion.find('.rating').each(function() {
const rating_val = parseFloat(
$(this)
.find('.points')
.text(),
10
)
if (rating_val == rating.points) {
rating.id = $(this)
.find('.rating_id')
.text()
}
})
}
if (submitted_data && $criterion.hasClass('learning_outcome_criterion')) {
rubricAssessment.checkScoreAdjustment($criterion, rating, submitted_data)
}
$criterion
.find('.custom_rating_field')
.val(comments)
.end()
.find('.custom_rating_comments')
.html(comments_html)
.end()
.find('.criterion_points')
.val(window.rubricAssessment.roundAndFormat(rating.points))
.change()
.end()
.find('.criterion_rating_points_holder')
.showIf(rating.points || rating.points === 0)
.end()
.find('.criterion_rating_points')
.text(window.rubricAssessment.roundAndFormat(rating.points))
.end()
.find('.custom_rating')
.text(comments)
.end()
.find('.criterion_comments')
.toggleClass('empty', !comments)
.end()
.find('.save_custom_rating')
.attr('checked', false)
if (ratingHasScore(rating)) {
$criterion
.find('.criterion_description')
.addClass('original_completed')
.end()
.find('#rating_' + rating.id)
.addClass('original_selected')
.addClass('selected')
.end()
rubricAssessment.highlightCriterionScore($criterion, rating.points)
if (!rating.ignore_for_scoring) {
total += rating.points
}
}
if (comments) $criterion.find('.criterion_comments').show()
}
total = window.rubricAssessment.roundAndFormat(total)
$rubric.find('.rubric_total').text(total)
}
},
populateNewRubricSummary(container, assessment, rubricAssociation, editData) {
const el = container.get(0)
if (ENV.nonScoringRubrics && ENV.rubric) {
ReactDOM.unmountComponentAtNode(el)
if (assessment) {
const filled = rubricAssessment.fillAssessment(
ENV.rubric,
assessment || {},
ENV.RUBRIC_ASSESSMENT
)
ReactDOM.render(
<Rubric
customRatings={ENV.outcome_proficiency ? ENV.outcome_proficiency.ratings : []}
rubric={ENV.rubric}
rubricAssessment={filled}
rubricAssociation={rubricAssociation}
isSummary
>
{null}
</Rubric>,
el
)
} else {
el.innerHTML = ''
}
} else {
rubricAssessment.populateRubricSummary(container, assessment, editData)
}
},
populateRubricSummary($rubricSummary, data, editing_data) {
$rubricSummary
.find('.criterion_points')
.text('')
.end()
.find('.rating_custom')
.text('')
if (data) {
const assessment = data
let total = 0
let $criterion = null
for (let idx = 0; idx < assessment.data.length; idx++) {
const rating = assessment.data[idx]
$criterion = $rubricSummary.find('#criterion_' + rating.criterion_id)
if (editing_data && $criterion.hasClass('learning_outcome_criterion')) {
rubricAssessment.checkScoreAdjustment($criterion, rating, editing_data)
}
$criterion
.find('.rating')
.hide()
.end()
.find('.rating_' + rating.id)
.show()
.end()
.find('.criterion_points')
.text(window.rubricAssessment.roundAndFormat(rating.points))
.end()
.find('.ignore_for_scoring')
.showIf(rating.ignore_for_scoring)
if (ratingHasScore(rating) && !$rubricSummary.hasClass('free_form')) {
$criterion
.find('.rating.description')
.show()
.text(rating.description)
.end()
}
if (rating.comments_enabled && rating.comments) {
$criterion
.find('.rating_custom')
.show()
.text(rating.comments)
}
if (rating.points && !rating.ignore_for_scoring) {
total += rating.points
}
}
total = window.rubricAssessment.roundAndFormat(total, round.DEFAULT)
$rubricSummary
.show()
.find('.rubric_total')
.text(total)
$rubricSummary.closest('.edit').show()
} else {
$rubricSummary.hide()
}
},
/**
* Returns n rounded and formatted with I18n.n.
* If n is null, undefined or empty string, empty string is returned.
*/
roundAndFormat(n) {
if (n == null || n === '') {
return ''
}
return I18n.n(round(n, round.DEFAULT))
}
}
function ratingHasScore(rating) {
return rating.points || rating.points === 0
}
$(rubricAssessment.init)
export default rubricAssessment
|
react/features/recording/components/Recording/native/HighlightButton.js | jitsi/jitsi-meet | // @flow
import React from 'react';
import type { Dispatch } from 'redux';
import { translate } from '../../../../base/i18n';
import { IconHighlight } from '../../../../base/icons';
import { Label } from '../../../../base/label';
import { connect } from '../../../../base/redux';
import BaseTheme from '../../../../base/ui/components/BaseTheme';
import AbstractHighlightButton, {
_abstractMapStateToProps,
type Props as AbstractProps
} from '../AbstractHighlightButton';
import styles from '../styles.native';
type Props = AbstractProps & {
_disabled: boolean,
/**
* Flag controlling visibility of the component.
*/
_visible: boolean,
dispatch: Dispatch<any>
};
/**
* React {@code Component} responsible for displaying an action that
* allows users to highlight a meeting moment.
*/
export class HighlightButton extends AbstractHighlightButton<Props> {
/**
* Implements React's {@link Component#render()}.
*
* @inheritdoc
* @returns {ReactElement}
*/
render() {
const {
_disabled,
_visible,
t
} = this.props;
if (!_visible || _disabled) {
return null;
}
return (
<Label
icon = { IconHighlight }
iconColor = { BaseTheme.palette.field01 }
id = 'highlightMeetingLabel'
style = { styles.highlightButton }
text = { t('recording.highlight') }
textStyle = { styles.highlightButtonText } />
);
}
}
export default translate(connect(_abstractMapStateToProps)(HighlightButton));
|
app/js/components/menu/MenuSections.js | lukemarsh/tab-hq-react | 'use strict';
import React from 'react';
import ReactDOM from 'react-dom';
import ReorderMixin from '../../mixins/ReorderMixin';
import NewSection from './NewSection';
import Section from './Section';
import _ from 'lodash';
import SectionActionCreators from '../../actions/SectionActionCreators';
import AppActionCreators from '../../actions/AppActionCreators';
import AppStore from '../../stores/AppStore';
import Reflux from 'reflux';
let currentSectionStyle = {};
const MenuSections = React.createClass({
mixins: [ReorderMixin, Reflux.connect(AppActionCreators.setScrolledToSection, 'scrolledToSection')],
setDraggableData(sections) {
let categoryId = this.props.category.id;
SectionActionCreators.updateSections(categoryId, sections);
},
handleClick(section) {
AppActionCreators.setCurrentSection(section.id);
},
render() {
let category = this.props.category;
let isVisible = this.props.isVisible;
let userIsAdmin = this.props.userIsAdmin;
let scrolledToSection = this.state.scrolledToSection;
this.loadDraggableData(this.props.category.sections);
let inlineStyles = {
display: isVisible ? 'block' : 'none'
};
if (category.sections.length) {
if (!scrolledToSection && this.props.index === 0) {
scrolledToSection = category.sections[0].id;
}
category.sections = _.sortBy(category.sections, 'order');
return (
<div onDragOver={this.dragOver} style={ inlineStyles }>
<ul>
{category.sections.map((section, index) => {
let currentSectionStyle = {
fontWeight: scrolledToSection === section.id ? 'bold' : 'normal'
};
return (
<li className='full-section' key={section.id} data-order={section.order} style={ currentSectionStyle } onClick={this.handleClick.bind(this, section)}>
<Section key={ category.title + section.title } userIsAdmin={userIsAdmin} section={section} categoryId={this.props.category.id} mouseDown={this.mouseDown} dragEnd={this.dragEnd} dragStart={this.dragStart}/>
</li>
);
})}
</ul>
<NewSection userIsAdmin={userIsAdmin} sections={category.sections} categoryId={category.id} />
</div>
);
} else {
let placeholder;
if (isVisible) {
placeholder = <NewSection userIsAdmin={userIsAdmin} sections={category.sections} categoryId={category.id} />;
}
return (
<div>
{placeholder}
</div>
);
}
}
});
module.exports = MenuSections;
|
node_modules/native-base/src/basic/Right.js | tausifmuzaffar/bisApp | import React, { Component } from 'react';
import { View } from 'react-native';
import { connectStyle } from '@shoutem/theme';
import mapPropsToStyleNames from '../Utils/mapPropsToStyleNames';
class Right extends Component {
render() {
return (
<View ref={c => this._root = c} {...this.props} />
);
}
}
Right.propTypes = {
...View.propTypes,
style: React.PropTypes.object,
};
const StyledRight = connectStyle('NativeBase.Right', {}, mapPropsToStyleNames)(Right);
export {
StyledRight as Right,
};
|
src/scene/Home/HomeMenuItem.js | Cowboy1995/JZWXZ | /**
* Copyright (c) 2017-present, Liu Jinyong
* All rights reserved.
*
* https://github.com/huanxsd/MeiTuan
* @flow
*/
//import liraries
import React, { Component } from 'react';
import { View, Text, StyleSheet, Image, TouchableOpacity } from 'react-native';
import { Heading2 } from '../../widget/Text'
import { screen, system, tool } from '../../common'
// create a component
class HomeMenuItem extends Component {
render() {
return (
<TouchableOpacity style={styles.container}
onPress={this.props.onPress}>
<Image source={this.props.icon} resizeMode='contain' style={styles.icon} />
<Heading2>
{this.props.title}
</Heading2>
</TouchableOpacity>
);
}
}
// define your styles
const styles = StyleSheet.create({
container: {
justifyContent: 'center',
alignItems: 'center',
width: screen.width / 5,
height: screen.width / 5,
},
icon: {
width: screen.width / 9,
height: screen.width / 9,
margin: 5,
}
});
//make this component available to the app
export default HomeMenuItem;
|
client/src/components/debtorConfirmation.js | CharismaticChard/CharismaticChard | import React from 'react';
import { connect } from 'react-redux';
const mapStateToProps = state => {
return {
debtors: state.final.debtors,
};
};
const mapDispatchToProps = dispatch => {
return {
};
};
const DebtorConfirmation = ({debtors}) => {
var debtorList = debtors.map((debtor, index) => (
<div key={index}>
<div className="row">
<label className="col-xs-6">Name: </label>
<p className="col-xs-6">{debtor.name}</p>
</div>
<div className="row">
<label className="col-xs-6">Phone: </label>
<p className="col-xs-6">{debtor.phone}</p>
</div>
<p className="boldP">Items</p>
{
debtor.items.map((item, index) => (
<div key={index}>
<div className="row">
<label className="col-xs-6">Name: </label>
<p className="col-xs-6">{item.name}</p>
</div>
<div className="row">
<label className="col-xs-6">Price: </label>
<p className="col-xs-6">${item.price}</p>
</div>
</div>
))
}
<div className="row">
<label className="col-xs-6">Items Total: </label>
<p className="col-xs-6">${debtor.total}</p>
</div>
<div className="row">
<label className="col-xs-6">Tax: </label>
<p className="col-xs-6">${debtor.tax}</p>
</div>
<div className="row">
<label className="col-xs-6">Tip: </label>
<p className="col-xs-6">${debtor.tip}</p>
</div>
<div className="row">
<label className="col-xs-6">Final Total: </label>
<p className="col-xs-6">${debtor.debtTotal}</p>
</div>
<hr />
</div>
));
var rending = (debtors !== null) ? debtorList : null;
return (
<div className="container">
<hr />
{rending}
</div>
);
};
export default connect(mapStateToProps, mapDispatchToProps) (DebtorConfirmation); |
views/components/MainCnt/index.js | KochiyaOcean/www.kochiyaocean.org | import React from 'react'
import { CardMedia, CardTitle, CardText } from 'react-toolbox/lib/card'
import { Button } from 'react-toolbox/lib/button'
import classnames from 'classnames'
import faStyle from 'font-awesome/css/font-awesome.css'
import avatar from './avatar.svg'
import styles from './styles'
const MainCnt = ({ children }, { __, toggle }) => {
return (
<div className={styles.maincnt}>
<CardMedia
aspectRatio="square"
image={avatar}
/>
<CardTitle
subtitle={
<div className={classnames(styles.flex, styles.center)}>
<span>@KochiyaOcean</span>
<div className={styles.right}>
<i className={classnames(faStyle.fa, faStyle['fa-map-marker'])}/> {__('Tokyo')}
</div>
</div>
}>
東風谷オーシャン
</CardTitle>
<CardText>
Just a JavaScript developer.<br />
#{__('frontend')} #JavaScript #React<br />
#{__('kancolle')} #{__('touhou')} #{__('gup')}
</CardText>
<CardText>
<div className={styles.fullwidth}>
<Button className={styles.halfwidth}
href="https://github.com/KochiyaOcean" target='_blank'>
<i className={classnames(faStyle.fa, faStyle['fa-github'])}/> {__('github')}
</Button>
<Button className={styles.halfwidth}
href="https://t.me/KochiyaOcean" target='_blank'>
<i className={classnames(faStyle.fa, faStyle['fa-telegram'])}/> {__('telegram')}
</Button>
</div>
<div className={styles.fullwidth}>
<Button className={styles.halfwidth}
href="https://www.facebook.com/KochiyaOcean" target='_blank'>
<i className={classnames(faStyle.fa, faStyle['fa-facebook-official'])}/> {__('facebook')}
</Button>
<Button className={styles.halfwidth}
href="https://twitter.com/KochiyaOcean" target='_blank'>
<i className={classnames(faStyle.fa, faStyle['fa-twitter'])}/> {__('twitter')}
</Button>
</div>
<div className={styles.fullwidth}>
<Button className={styles.halfwidth}
href="https://blog.kochiyaocean.org/" target='_blank'>
<i className={classnames(faStyle.fa, faStyle['fa-book'])}/> {__('blog')}
</Button>
<Button className={styles.halfwidth}
onClick={toggle}>
<i className={classnames(faStyle.fa, faStyle['fa-id-card-o'])}/> {__('resume')}
</Button>
</div>
</CardText>
</div>
)
}
MainCnt.contextTypes = {
__: React.PropTypes.func,
toggle: React.PropTypes.func,
}
export default MainCnt
|
mm-react/src/components/instances/InstanceSpawner.js | Ameobea/tickgrinder | //! Dialog to allow users to spawn new instances.
import { connect } from 'dva';
import React from 'react';
import { message, Tooltip, Icon, Select, Button } from 'antd';
const Option = Select.Option;
import { getInstance, InstanceShape } from '../../utils/commands';
import MacroManager from '../MacroManager';
import styles from '../../static/css/instances.css';
const MacroInfo = () => {
return (
<Tooltip title="Click here for info on spawner macros">
<Icon className={styles.infoTooltip} type="question" />
</Tooltip>
);
};
const spawnableInstances = [
{name: 'Backtester', cmd: 'SpawnBacktester'},
{name: 'Logger', cmd: 'SpawnLogger'},
{name: 'Tick Parser', cmd: 'SpawnTickParser'},
{name: 'Optimizer', cmd: 'SpawnOptimizer'},
{name: 'Redis Server', cmd: 'SpawnRedisServer'},
{name: 'FXCM Data Downloader', cmd: 'SpawnFxcmDataDownloader'},
];
const spawnChanged = (val, opt, dispatch) => {
dispatch({type: 'instances/instanceSpawnChanged', cmd: val, name: opt.props.children});
};
const spawnButtonClicked = (dispatch, living_instances, {name, cmd}) => {
let spawner_uuid = getInstance('Spawner', living_instances);
if(spawner_uuid.length === 0) {
// if no living spawner in the census list, display error message and return
message.error('No Spawner instance was detected running on the platform; unable to spawn instance!');
return;
}
let cb_action = 'instances/instanceSpawnCallback';
dispatch({type: 'platform_communication/sendCommand', channel: spawner_uuid[0].uuid, cmd: cmd, cb_action: cb_action});
};
const SingleSpawner = ({dispatch, living_instances, spawn_opt}) => {
let options = [];
for(var i=0; i<spawnableInstances.length; i++) {
let opt = (
<Option key={i} value={spawnableInstances[i].cmd} >
{spawnableInstances[i].name}
</Option>
);
options.push(opt);
}
const handleSelect = (val, opt) => spawnChanged(val, opt, dispatch);
const handleClick = () => spawnButtonClicked(dispatch, living_instances, spawn_opt);
return (
<div className={styles.singleSpawner}>
<Select
defaultValue={spawn_opt.cmd}
onSelect={handleSelect}
style={{ width: 160 }}
>
{options}
</Select>
<Button onClick={handleClick} type='primary'>
{'Spawn Instance'}
</Button>
</div>
);
};
SingleSpawner.propTypes = {
dispatch: React.PropTypes.func.isRequired,
living_instances: React.PropTypes.arrayOf(React.PropTypes.shape(InstanceShape)).isRequired,
spawn_opt: React.PropTypes.shape({name: React.PropTypes.string.isRequired, cmd: React.PropTypes.any}).isRequired,
};
const InstanceSpawner = ({dispatch, living_instances, spawn_opt}) => {
return (
<div className={styles.instanceSpawner}>
<div className={styles.header}>
{'Spawn a Single Instance'}
</div>
<SingleSpawner
dispatch={dispatch}
living_instances={living_instances}
spawn_opt={spawn_opt}
/>
<div className={styles.header}>
{'Execute a Spawner Macro'}
<MacroInfo />
</div>
<MacroManager />
</div>
);
};
InstanceSpawner.propTypes = {
dispatch: React.PropTypes.func.isRequired,
living_instances: React.PropTypes.arrayOf(React.PropTypes.shape(InstanceShape)).isRequired,
spawn_opt: React.PropTypes.shape({name: React.PropTypes.string.isRequired, cmd: React.PropTypes.any}).isRequired,
};
function mapProps(state) {
return {
living_instances: state.instances.living_instances,
spawn_opt: state.instances.selected_spawn_opt,
};
}
export default connect(mapProps)(InstanceSpawner);
|
src/containers/NotFoundPage/NotFoundPage.js | armaniExchange/wizard | // Style
import './_NotFoundPage';
// React & Redux
import React, { Component } from 'react';
class NotFoundPage extends Component {
render() {
return (
<div className="Not-Found-Page">
<h1 className="Not-Found-Page__header">404</h1>
<div className="Not-Found-Page__content">The page you are looking for is not here :(</div>
</div>
);
}
}
export default NotFoundPage;
|
client/routes/PostListView/PostListView.js | chenfanggm/steven-mern-starter-kit | import React from 'react'
import PostListContainer from './container/PostListContainer'
export const PostListView = () => (
<PostListContainer />
)
export default PostListView
|
src/pages/Account.js | DIYAbility/Capacita-Controller-Interface | import React, { Component } from 'react';
import { connect } from 'react-redux';
import { PageHeader } from 'react-bootstrap';
class Account extends Component {
render() {
return (
<div className="page">
<PageHeader>Account</PageHeader>
</div>
);
}
componentDidMount() {
this.changePage(this.props.user);
}
componentWillUpdate(nextProps) {
this.changePage(nextProps.user);
}
changePage(user) {
if (!user) {
window.location = '#signin';
}
}
}
const mapStateToProps = (state, props) => {
return state.app;
}
export default connect(mapStateToProps)(Account);
|
blueocean-material-icons/src/js/components/svg-icons/action/perm-phone-msg.js | jenkinsci/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const ActionPermPhoneMsg = (props) => (
<SvgIcon {...props}>
<path d="M20 15.5c-1.25 0-2.45-.2-3.57-.57-.35-.11-.74-.03-1.02.24l-2.2 2.2c-2.83-1.44-5.15-3.75-6.59-6.58l2.2-2.21c.28-.27.36-.66.25-1.01C8.7 6.45 8.5 5.25 8.5 4c0-.55-.45-1-1-1H4c-.55 0-1 .45-1 1 0 9.39 7.61 17 17 17 .55 0 1-.45 1-1v-3.5c0-.55-.45-1-1-1zM12 3v10l3-3h6V3h-9z"/>
</SvgIcon>
);
ActionPermPhoneMsg.displayName = 'ActionPermPhoneMsg';
ActionPermPhoneMsg.muiName = 'SvgIcon';
export default ActionPermPhoneMsg;
|
src/Main/ServiceStatus.js | hasseboulen/WoWAnalyzer | import React from 'react';
import PropTypes from 'prop-types';
const baseStatusUrl = 'https://status.wowanalyzer.com';
const STATUS = {
OPERATIONAL: 1,
PERFORMANCE_ISSUES: 2,
PARTIAL_OUTAGE: 3,
MAJOR_OUTAGE: 4,
};
class ServiceStatus extends React.PureComponent {
static propTypes = {
style: PropTypes.object,
};
constructor() {
super();
this.state = {
status: null,
};
}
componentWillMount() {
this.loadStatus()
.then(status => {
this.setState({
status,
});
});
}
loadStatus() {
const url = `${baseStatusUrl}/api/v1/components`;
return fetch(url)
.then(response => response.json())
.then(json => {
console.log('Received service status', json);
return json.data.reduce((max, component) => {
const status = Number(component.status);
if (max === null || max < status) {
return status;
}
return max;
}, null);
});
}
render() {
const { style } = this.props;
let message;
let className;
switch (this.state.status) {
case STATUS.PERFORMANCE_ISSUES:
message = 'Some systems are experiencing performance issues';
className = 'alert-info';
break;
case STATUS.PARTIAL_OUTAGE:
message = 'Some systems are experiencing issues';
className = 'alert-warning';
break;
case STATUS.MAJOR_OUTAGE:
message = 'Some systems are experiencing a major outage';
className = 'alert-danger';
break;
case STATUS.OPERATIONAL:
default:
return null;
}
return (
<div style={{ fontSize: '1.2em', fontWeight: 600, ...style }} className={`alert ${className}`}>
{message}. <a href={baseStatusUrl}>More info</a>
</div>
);
}
}
export default ServiceStatus;
|
client/src/components/Profile/components/PoliticiansListWrapper.js | verejnedigital/verejne.digital | // @flow
import React from 'react'
import {compose} from 'redux'
import {connect} from 'react-redux'
import {withRouter} from 'react-router-dom'
import {withDataProviders} from 'data-provider'
import type {ComponentType} from 'react'
import {politiciansProvider} from '../../../dataProviders/profileDataProviders'
import {
filteredPoliticiansSelector,
politicianGroupSelector,
politicianSortingOptionSelector,
} from '../../../selectors/profileSelectors'
import type {ContextRouter} from 'react-router'
import type {State, Politician} from '../../../state'
export type PoliticiansListProps = {
politicians: Array<Politician>,
politicianGroup: string,
}
const PoliticiansListWrapper = (WrappedComponent: ComponentType<PoliticiansListProps>) => {
const wrapped = (props: PoliticiansListProps) => <WrappedComponent {...props} />
return compose(
withRouter,
connect((state: State, props: ContextRouter) => ({
politicianGroup: politicianGroupSelector(state, props),
politicians: filteredPoliticiansSelector(state, props),
sortState: politicianSortingOptionSelector(state, props),
})),
withDataProviders(({politicianGroup}: PoliticiansListProps) => [
politiciansProvider(politicianGroup),
])
)(wrapped)
}
export default PoliticiansListWrapper
|
fields/types/cloudinaryimage/CloudinaryImageColumn.js | dryna/keystone-twoje-urodziny | import React from 'react';
import CloudinaryImageSummary from '../../components/columns/CloudinaryImageSummary';
import ItemsTableCell from '../../components/ItemsTableCell';
import ItemsTableValue from '../../components/ItemsTableValue';
var CloudinaryImageColumn = React.createClass({
displayName: 'CloudinaryImageColumn',
propTypes: {
col: React.PropTypes.object,
data: React.PropTypes.object,
},
renderValue: function () {
var value = this.props.data.fields[this.props.col.path];
if (!value || !Object.keys(value).length) return;
return (
<ItemsTableValue field={this.props.col.type}>
<CloudinaryImageSummary label="dimensions" image={value} />
</ItemsTableValue>
);
},
render () {
return (
<ItemsTableCell>
{this.renderValue()}
</ItemsTableCell>
);
},
});
module.exports = CloudinaryImageColumn;
|
docs/app/Examples/collections/Menu/States/index.js | jcarbo/stardust | import React from 'react'
import ExampleSection from 'docs/app/Components/ComponentDoc/ExampleSection'
import ComponentExample from 'docs/app/Components/ComponentDoc/ComponentExample'
const States = () => {
return (
<ExampleSection title='States'>
<ComponentExample
title='Hover'
description='A menu item can be hovered'
examplePath='collections/Menu/States/Hover'
/>
<ComponentExample
title='Active'
description='A menu item can be active'
examplePath='collections/Menu/States/Active'
/>
</ExampleSection>
)
}
export default States
|
src/routes.js | joehua87/redux-universal | import React from 'react'
import { Route, IndexRoute } from 'react-router'
import App from './containers/App'
import Counter from './containers/Counter'
import Home from './containers/Home'
import User from './containers/User'
import UserDetail from './containers/UserDetail'
import Category from './containers/Category'
import Tag from './containers/Tag'
import Post from './containers/Post'
export default (
<Route path="/" component={App}>
<IndexRoute component={Home}/>
<Route path="counter" component={Counter}/>
<Route path="category/:slug" component={Category}/>
<Route path="tag/:slug" component={Tag}/>
<Route path="post/:slug" component={Post}/>
<Route path="user" component={User}>
<Route path=":username" component={UserDetail}/>
</Route>
</Route>
)
|
examples/shopping-cart/src/containers/ProductsContainer.js | lifeiscontent/redux | import React from 'react'
import PropTypes from 'prop-types'
import { connect } from 'react-redux'
import { addToCart } from '../actions'
import { getVisibleProducts } from '../reducers/products'
import ProductItem from '../components/ProductItem'
import ProductsList from '../components/ProductsList'
const ProductsContainer = ({ products, addToCart }) => (
<ProductsList title="Products">
{products.map(product =>
<ProductItem
key={product.id}
product={product}
onAddToCartClicked={() => addToCart(product.id)} />
)}
</ProductsList>
)
ProductsContainer.propTypes = {
products: PropTypes.arrayOf(PropTypes.shape({
id: PropTypes.number.isRequired,
title: PropTypes.string.isRequired,
price: PropTypes.number.isRequired,
inventory: PropTypes.number.isRequired
})).isRequired,
addToCart: PropTypes.func.isRequired
}
const mapStateToProps = state => ({
products: getVisibleProducts(state.products)
})
export default connect(
mapStateToProps,
{ addToCart }
)(ProductsContainer)
|
client/views/Home/User.js | shastajs/boilerplate | import React from 'react'
import { PropTypes, connect } from 'shasta'
import {
Text, Heading,
Panel, PanelHeader, Banner, Media
} from 'rebass'
import actions from 'core/actions'
import DataComponent from 'shasta-data-view'
@connect({
user: 'api.subsets.user'
})
export default class User extends DataComponent {
static displayName = 'User'
static propTypes = {
name: PropTypes.string.isRequired,
user: PropTypes.map
}
resolveData() {
actions.github.getUser({
subset: 'user',
params: {
name: this.props.name
}
})
}
renderData({ user }) {
return (
<Panel rounded>
<PanelHeader>User Info</PanelHeader>
<Banner
style={{
maxHeight: 400,
minHeight: 0
}}
mb={0}
align="center"
backgroundImage="https://d262ilb51hltx0.cloudfront.net/max/2000/1*DZwdGMaeu-rvTroJYui6Uw.jpeg"
>
<Heading level={2}>{user.get('name')}</Heading>
<Heading level={3}>{user.get('followers')} followers</Heading>
</Banner>
</Panel>
)
}
renderErrors(errors) {
return (<Panel rounded>
<PanelHeader>User Info</PanelHeader>
<Heading>Failed to Load!</Heading>
{
errors.map((err, field) =>
<Media key={field} align="center">
<Heading level={3}>{field}</Heading>
<Text>{err.message}</Text>
</Media>
).toArray()
}
</Panel>)
}
}
|
react-notes/src/index.js | wumouren/react-demo | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import Container from './container';
import Head from './head';
import One from './one';
import Two from './two';
import Context from './context';
const higher = function(Component,data){
class Higher extends React.Component {
constructor(props) {
super(props)
this.state = {
higher: 0
}
}
componentWillMount() {
let higher = data * 2
this.setState({
higher: higher
})
}
render() {
return (
<Component higher={this.state.higher}></Component>
)
}
}
return Higher
}
let CopyOne = higher(One,30);
let CopyTwo = higher(Two, 40);
ReactDOM.render(
<div>
<Context></Context>
{/* <CopyOne></CopyOne>
<CopyTwo></CopyTwo>
<One higher={10}></One>
<Two higher={20}></Two>
<Container>
<h1>hello man</h1>
<Head></Head>
</Container> */}
</div>,
document.getElementById('root')
); |
docs/app/Examples/modules/Dropdown/Types/DropdownExampleMultipleSearchSelectionTwo.js | vageeshb/Semantic-UI-React | import React from 'react'
import { Dropdown } from 'semantic-ui-react'
import { countryOptions } from '../common'
// countryOptions = [ { value: 'af', flag: 'af', text: 'Afghanistan' }, ... ]
const DropdownExampleMultipleSearchSelectionTwo = () => (
<Dropdown placeholder='Select Country' fluid multiple search selection options={countryOptions} />
)
export default DropdownExampleMultipleSearchSelectionTwo
|
app/javascript/mastodon/features/community_timeline/components/column_settings.js | d6rkaiz/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { injectIntl, FormattedMessage } from 'react-intl';
import SettingToggle from '../../notifications/components/setting_toggle';
export default @injectIntl
class ColumnSettings extends React.PureComponent {
static propTypes = {
settings: ImmutablePropTypes.map.isRequired,
onChange: PropTypes.func.isRequired,
intl: PropTypes.object.isRequired,
columnId: PropTypes.string,
};
render () {
const { settings, onChange } = this.props;
return (
<div>
<div className='column-settings__row'>
<SettingToggle settings={settings} settingPath={['other', 'onlyMedia']} onChange={onChange} label={<FormattedMessage id='community.column_settings.media_only' defaultMessage='Media only' />} />
</div>
</div>
);
}
}
|
app/shared/background-image/BackgroundImage.js | fastmonkeys/respa-ui | import PropTypes from 'prop-types';
import React from 'react';
function BackgroundImage({
children, image, height, width,
}) {
const dimensions = height && width ? `dim=${width}x${height}` : '';
const imageUrl = dimensions ? `${image.url}?${dimensions}` : image.url;
const style = imageUrl ? { backgroundImage: `url(${imageUrl})` } : {};
return (
<div className="image-container" style={style}>
{children}
</div>
);
}
BackgroundImage.propTypes = {
children: PropTypes.node,
image: PropTypes.shape({
url: PropTypes.string,
}).isRequired,
height: PropTypes.number,
width: PropTypes.number,
};
export default BackgroundImage;
|
src/svg-icons/image/slideshow.js | nathanmarks/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageSlideshow = (props) => (
<SvgIcon {...props}>
<path d="M10 8v8l5-4-5-4zm9-5H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm0 16H5V5h14v14z"/>
</SvgIcon>
);
ImageSlideshow = pure(ImageSlideshow);
ImageSlideshow.displayName = 'ImageSlideshow';
ImageSlideshow.muiName = 'SvgIcon';
export default ImageSlideshow;
|
CompositeUi/src/views/page/organization/AddMember.js | kreta/kreta | /*
* This file is part of the Kreta package.
*
* (c) Beñat Espiña <benatespina@gmail.com>
* (c) Gorka Laucirica <gorka.lauzirika@gmail.com>
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*/
import {connect} from 'react-redux';
import debounce from 'lodash.debounce';
import React from 'react';
import AddIcon from './../../../svg/add.svg';
import CurrentOrganizationActions from './../../../actions/CurrentOrganization';
import MemberActions from './../../../actions/Member';
import Button from './../../component/Button';
import Icon from './../../component/Icon';
import Search from './../../component/SearchMember';
import UserCard from './../../component/UserCard';
@connect(state => ({currentOrganization: state.currentOrganization}))
class AddMember extends React.Component {
static propTypes = {
onMemberRemoveClicked: React.PropTypes.func,
organization: React.PropTypes.object,
};
constructor(props) {
super(props);
this.debouncedOnChangeSearch = debounce(query => {
this.filterMembersToAdd(query);
}, 200);
this.onChangeSearch = this.onChangeSearch.bind(this);
}
componentDidMount() {
this.filterMembersToAdd(null);
}
filterMembersToAdd(query) {
const {currentOrganization, dispatch} = this.props;
dispatch(
MemberActions.fetchMembersToAdd(
query,
currentOrganization.organization.organization_members.map(
item => item.id,
),
),
);
}
addMember(member) {
const {currentOrganization, dispatch} = this.props;
dispatch(
CurrentOrganizationActions.addMember(
currentOrganization.organization.id,
member.id,
),
);
}
onChangeSearch(event) {
const query = event.target ? event.target.value : null;
this.debouncedOnChangeSearch(query);
}
renderMembersToAdd() {
const {currentOrganization} = this.props;
if (currentOrganization.potential_members.length === 0) {
return <p>No users found for your search, try typing another username</p>;
}
return currentOrganization.potential_members.map((member, index) =>
<div className="MemberList" key={index}>
<UserCard
actions={
<Button
color="green"
onClick={this.addMember.bind(this, member)}
type="icon"
>
<Icon color="white" glyph={AddIcon} size="expand" />
</Button>
}
user={member}
/>
</div>,
);
}
render() {
return (
<div>
<Search onChange={this.onChangeSearch} />
{this.renderMembersToAdd()}
</div>
);
}
}
export default AddMember;
|
src/routes/NotFoundView/NotFoundView.js | robertkirsz/magic-cards-manager | import React from 'react'
import { Flex } from 'styled'
const NotFoundView = () => (
<Flex>
<h1 style={{ margin: '100px auto 0' }}>404 Not Found</h1>
</Flex>
)
export default NotFoundView
|
src/svg-icons/action/assignment-ind.js | verdan/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAssignmentInd = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-7 0c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm0 4c1.66 0 3 1.34 3 3s-1.34 3-3 3-3-1.34-3-3 1.34-3 3-3zm6 12H6v-1.4c0-2 4-3.1 6-3.1s6 1.1 6 3.1V19z"/>
</SvgIcon>
);
ActionAssignmentInd = pure(ActionAssignmentInd);
ActionAssignmentInd.displayName = 'ActionAssignmentInd';
ActionAssignmentInd.muiName = 'SvgIcon';
export default ActionAssignmentInd;
|
src/js/ui/components/settings/membership/localUser.js | hiddentao/heartnotes | import _ from 'lodash';
import Q from 'bluebird';
import React from 'react';
import Classnames from 'classnames';
import { connectRedux } from '../../../helpers/decorators';
import AttentionIcon from '../../attentionIcon';
import EnableSyncOverlay from './enableSyncOverlay';
import Button from '../../button';
var Component = React.createClass({
render: function() {
let enableButton = (
<Button onClick={this._showEnableScreen}>
Enable cloud sync
</Button>
);
return (
<div className="local-user">
<div className="subscription">
<span>Cloud sync not enabled <AttentionIcon /></span>
<span className="description">
Your diary entries are NOT backed up or synced.
</span>
</div>
{enableButton}
<EnableSyncOverlay
ref="enable"
showCancelButton={false}
{...this.props} />
</div>
);
},
_showEnableScreen: function() {
this.refs.enable.getWrappedInstance().show();
},
});
module.exports = connectRedux()(Component);
|
src/components/Interactive/ServiceNowLink/index.js | ndlib/usurper | import React from 'react'
import PropTypes from 'prop-types'
import Link from 'components/Interactive/Link'
import Config from 'shared/Configuration'
const ServiceNowLink = ({ children, isWebContent }) => {
let url = `${Config.serviceNowBaseURL}&URL=${window.location}`
if (isWebContent) {
url += '&lib_list_problem=lib_list_web_content'
}
return (
<Link to={url}>
{children}
</Link>
)
}
ServiceNowLink.propTypes = {
children: PropTypes.any,
isWebContent: PropTypes.bool,
}
export default ServiceNowLink
|
system/src/routes/PurchaseOrder/containers/EditPurchaseOrderViewContainer/index.js | axmatthew/react | import React, { Component } from 'react';
import { connect } from 'react-redux';
import purchaseOrderModule from '../../../../modules/purchase-orders';
import EditPurchaseOrderView from '../../components/EditPurchaseOrderView';
import { baseMapStateToProps } from '../../../../common/container-helpers';
class EditPurchaseOrderViewContainer extends Component {
static propTypes = Object.assign({}, EditPurchaseOrderView.propTypes, {
params: React.PropTypes.object.isRequired,
fetch: React.PropTypes.func.isRequired
});
componentDidMount() {
this.props.fetch(this.props.params._id);
}
render() {
return React.createElement(
EditPurchaseOrderView,
Object.assign({}, this.props, { params: undefined, fetch: undefined })
);
}
}
export default connect(baseMapStateToProps.bind(null, purchaseOrderModule.entityUrl, 'editView'), {
fetch: purchaseOrderModule.fetch,
// Transfer to presentation component
update: purchaseOrderModule.update
})(EditPurchaseOrderViewContainer);
|
tests/utils.js | KeywordBrain/redbox-react | import React from 'react'
const TestUtils = require('react-addons-test-utils');
export const createComponent = (component, props, ...children) => {
const shallowRenderer = TestUtils.createRenderer()
shallowRenderer.render(React.createElement(component, props, children.length > 1 ? children : children[0]))
return shallowRenderer.getRenderOutput()
}
|
packages/react-scripts/fixtures/kitchensink/template/src/features/webpack/SvgComponent.js | facebookincubator/create-react-app | /**
* Copyright (c) 2015-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
import React from 'react';
import { ReactComponent as Logo } from './assets/logo.svg';
const SvgComponent = () => {
return <Logo id="feature-svg-component" />;
};
export const SvgComponentWithRef = React.forwardRef((props, ref) => (
<Logo id="feature-svg-component-with-ref" ref={ref} />
));
export default SvgComponent;
|
app/javascript/mastodon/features/ui/components/column_loading.js | Nyoho/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Column from '../../../components/column';
import ColumnHeader from '../../../components/column_header';
import ImmutablePureComponent from 'react-immutable-pure-component';
export default class ColumnLoading extends ImmutablePureComponent {
static propTypes = {
title: PropTypes.oneOfType([PropTypes.node, PropTypes.string]),
icon: PropTypes.string,
};
static defaultProps = {
title: '',
icon: '',
};
render() {
let { title, icon } = this.props;
return (
<Column>
<ColumnHeader icon={icon} title={title} multiColumn={false} focusable={false} placeholder />
<div className='scrollable' />
</Column>
);
}
}
|
server/sonar-web/src/main/js/app/components/nav/settings/SettingsNav.js | Builders-SonarSource/sonarqube-bis | /*
* SonarQube
* Copyright (C) 2009-2016 SonarSource SA
* mailto:contact AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser 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
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
import React from 'react';
import classNames from 'classnames';
import { IndexLink, Link } from 'react-router';
import { connect } from 'react-redux';
import { translate } from '../../../../helpers/l10n';
import { areThereCustomOrganizations } from '../../../../store/rootReducer';
class SettingsNav extends React.Component {
static defaultProps = {
extensions: []
};
isSomethingActive (urls) {
const path = window.location.pathname;
return urls.some(url => path.indexOf(window.baseUrl + url) === 0);
}
isSecurityActive () {
const urls = ['/users', '/groups', '/roles/global', '/permission_templates'];
return this.isSomethingActive(urls);
}
isProjectsActive () {
const urls = ['/projects_admin', '/background_tasks'];
return this.isSomethingActive(urls);
}
isSystemActive () {
const urls = ['/updatecenter', '/system'];
return this.isSomethingActive(urls);
}
renderExtension = ({ key, name }) => {
return (
<li key={key}>
<Link to={`/admin/extension/${key}`} activeClassName="active">{name}</Link>
</li>
);
};
render () {
const isSecurity = this.isSecurityActive();
const isProjects = this.isProjectsActive();
const isSystem = this.isSystemActive();
const securityClassName = classNames('dropdown', { active: isSecurity });
const projectsClassName = classNames('dropdown', { active: isProjects });
const systemClassName = classNames('dropdown', { active: isSystem });
const configurationClassNames = classNames('dropdown', {
active: !isSecurity && !isProjects && !isSystem
});
return (
<nav className="navbar navbar-context page-container" id="context-navigation">
<div className="navbar-context-inner">
<div className="container">
<ul className="nav navbar-nav nav-crumbs">
<li>
<IndexLink to="/settings">
{translate('layout.settings')}
</IndexLink>
</li>
</ul>
<ul className="nav navbar-nav nav-tabs">
<li className={configurationClassNames}>
<a className="dropdown-toggle" data-toggle="dropdown" id="settings-navigation-configuration" href="#">
{translate('sidebar.project_settings')} <i className="icon-dropdown"/>
</a>
<ul className="dropdown-menu">
<li>
<IndexLink to="/settings" activeClassName="active">
{translate('settings.page')}
</IndexLink>
</li>
<li>
<IndexLink to="/settings/licenses" activeClassName="active">
{translate('property.category.licenses')}
</IndexLink>
</li>
<li>
<IndexLink to="/settings/encryption" activeClassName="active">
{translate('property.category.security.encryption')}
</IndexLink>
</li>
<li>
<IndexLink to="/settings/server_id" activeClassName="active">
{translate('property.category.server_id')}
</IndexLink>
</li>
<li>
<IndexLink to="/metrics" activeClassName="active">
Custom Metrics
</IndexLink>
</li>
{this.props.extensions.map(this.renderExtension)}
</ul>
</li>
<li className={securityClassName}>
<a className="dropdown-toggle" data-toggle="dropdown" href="#">
{translate('sidebar.security')} <i className="icon-dropdown"/>
</a>
<ul className="dropdown-menu">
<li>
<IndexLink to="/users" activeClassName="active">
{translate('users.page')}
</IndexLink>
</li>
{!this.props.customOrganizations && (
<li>
<IndexLink to="/groups" activeClassName="active">
{translate('user_groups.page')}
</IndexLink>
</li>
)}
{!this.props.customOrganizations && (
<li>
<IndexLink to="/roles/global" activeClassName="active">
{translate('global_permissions.page')}
</IndexLink>
</li>
)}
{!this.props.customOrganizations && (
<li>
<IndexLink to="/permission_templates" activeClassName="active">
{translate('permission_templates')}
</IndexLink>
</li>
)}
</ul>
</li>
<li className={projectsClassName}>
<a className="dropdown-toggle" data-toggle="dropdown" href="#">
{translate('sidebar.projects')} <i className="icon-dropdown"/>
</a>
<ul className="dropdown-menu">
<li>
<IndexLink to="/projects_admin" activeClassName="active">
Management
</IndexLink>
</li>
<li>
<IndexLink to="/background_tasks" activeClassName="active">
{translate('background_tasks.page')}
</IndexLink>
</li>
</ul>
</li>
<li className={systemClassName}>
<a className="dropdown-toggle" data-toggle="dropdown" href="#">
{translate('sidebar.system')} <i className="icon-dropdown"/>
</a>
<ul className="dropdown-menu">
<li>
<IndexLink to="/updatecenter" activeClassName="active">
{translate('update_center.page')}
</IndexLink>
</li>
<li>
<IndexLink to="/system" activeClassName="active">
{translate('system_info.page')}
</IndexLink>
</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
);
}
}
const mapStateToProps = state => ({
customOrganizations: areThereCustomOrganizations(state)
});
export default connect(mapStateToProps)(SettingsNav);
export const UnconnectedSettingsNav = SettingsNav;
|
Libraries/Image/Image.ios.js | Ehesp/react-native | /**
* Copyright (c) 2015-present, Facebook, Inc.
* All rights reserved.
*
* This source code is licensed under the BSD-style license found in the
* LICENSE file in the root directory of this source tree. An additional grant
* of patent rights can be found in the PATENTS file in the same directory.
*
* @providesModule Image
* @flow
*/
'use strict';
const EdgeInsetsPropType = require('EdgeInsetsPropType');
const ImageResizeMode = require('ImageResizeMode');
const ImageSourcePropType = require('ImageSourcePropType');
const ImageStylePropTypes = require('ImageStylePropTypes');
const NativeMethodsMixin = require('NativeMethodsMixin');
const NativeModules = require('NativeModules');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNativeViewAttributes = require('ReactNativeViewAttributes');
const StyleSheet = require('StyleSheet');
const StyleSheetPropType = require('StyleSheetPropType');
const flattenStyle = require('flattenStyle');
const requireNativeComponent = require('requireNativeComponent');
const resolveAssetSource = require('resolveAssetSource');
const ImageViewManager = NativeModules.ImageViewManager;
/**
* A React component for displaying different types of images,
* including network images, static resources, temporary local images, and
* images from local disk, such as the camera roll.
*
* This example shows both fetching and displaying an image from local
* storage as well as one from network.
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image } from 'react-native';
*
* export default class DisplayAnImage extends Component {
* render() {
* return (
* <View>
* <Image
* source={require('./img/favicon.png')}
* />
* <Image
* style={{width: 50, height: 50}}
* source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}
* />
* </View>
* );
* }
* }
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('DisplayAnImage', () => DisplayAnImage);
* ```
*
* You can also add `style` to an image:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, Image, StyleSheet } from 'react-native';
*
* const styles = StyleSheet.create({
* stretch: {
* width: 50,
* height: 200
* }
* });
*
* export default class DisplayAnImageWithStyle extends Component {
* render() {
* return (
* <View>
* <Image
* style={styles.stretch}
* source={require('./img/favicon.png')}
* />
* </View>
* );
* }
* }
*
* // skip these lines if using Create React Native App
* AppRegistry.registerComponent(
* 'DisplayAnImageWithStyle',
* () => DisplayAnImageWithStyle
* );
* ```
*
* ### GIF and WebP support on Android
*
* When building your own native code, GIF and WebP are not supported by default on Android.
*
* You will need to add some optional modules in `android/app/build.gradle`, depending on the needs of your app.
*
* ```
* dependencies {
* // If your app supports Android versions before Ice Cream Sandwich (API level 14)
* compile 'com.facebook.fresco:animated-base-support:1.0.1'
*
* // For animated GIF support
* compile 'com.facebook.fresco:animated-gif:1.0.1'
*
* // For WebP support, including animated WebP
* compile 'com.facebook.fresco:animated-webp:1.0.1'
* compile 'com.facebook.fresco:webpsupport:1.0.1'
*
* // For WebP support, without animations
* compile 'com.facebook.fresco:webpsupport:1.0.1'
* }
* ```
*
* Also, if you use GIF with ProGuard, you will need to add this rule in `proguard-rules.pro` :
* ```
* -keep class com.facebook.imagepipeline.animated.factory.AnimatedFactoryImpl {
* public AnimatedFactoryImpl(com.facebook.imagepipeline.bitmaps.PlatformBitmapFactory, com.facebook.imagepipeline.core.ExecutorSupplier);
* }
* ```
*
*/
// $FlowFixMe(>=0.41.0)
const Image = React.createClass({
propTypes: {
/**
* > `ImageResizeMode` is an `Enum` for different image resizing modes, set via the
* > `resizeMode` style property on `Image` components. The values are `contain`, `cover`,
* > `stretch`, `center`, `repeat`.
*/
style: StyleSheetPropType(ImageStylePropTypes),
/**
* The image source (either a remote URL or a local file resource).
*
* This prop can also contain several remote URLs, specified together with
* their width and height and potentially with scale/other URI arguments.
* The native side will then choose the best `uri` to display based on the
* measured size of the image container. A `cache` property can be added to
* control how networked request interacts with the local cache.
*
* The currently supported formats are `png`, `jpg`, `jpeg`, `bmp`, `gif`,
* `webp` (Android only), `psd` (iOS only).
*/
source: ImageSourcePropType,
/**
* A static image to display while loading the image source.
*
* - `uri` - a string representing the resource identifier for the image, which
* should be either a local file path or the name of a static image resource
* (which should be wrapped in the `require('./path/to/image.png')` function).
* - `width`, `height` - can be specified if known at build time, in which case
* these will be used to set the default `<Image/>` component dimensions.
* - `scale` - used to indicate the scale factor of the image. Defaults to 1.0 if
* unspecified, meaning that one image pixel equates to one display point / DIP.
* - `number` - Opaque type returned by something like `require('./image.jpg')`.
*
* @platform ios
*/
defaultSource: PropTypes.oneOfType([
// TODO: Tooling to support documenting these directly and having them display in the docs.
PropTypes.shape({
uri: PropTypes.string,
width: PropTypes.number,
height: PropTypes.number,
scale: PropTypes.number,
}),
PropTypes.number,
]),
/**
* When true, indicates the image is an accessibility element.
* @platform ios
*/
accessible: PropTypes.bool,
/**
* The text that's read by the screen reader when the user interacts with
* the image.
* @platform ios
*/
accessibilityLabel: PropTypes.node,
/**
* blurRadius: the blur radius of the blur filter added to the image
*/
blurRadius: PropTypes.number,
/**
* When the image is resized, the corners of the size specified
* by `capInsets` will stay a fixed size, but the center content and borders
* of the image will be stretched. This is useful for creating resizable
* rounded buttons, shadows, and other resizable assets. More info in the
* [official Apple documentation](https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIImage_Class/index.html#//apple_ref/occ/instm/UIImage/resizableImageWithCapInsets).
*
* @platform ios
*/
capInsets: EdgeInsetsPropType,
/**
* The mechanism that should be used to resize the image when the image's dimensions
* differ from the image view's dimensions. Defaults to `auto`.
*
* - `auto`: Use heuristics to pick between `resize` and `scale`.
*
* - `resize`: A software operation which changes the encoded image in memory before it
* gets decoded. This should be used instead of `scale` when the image is much larger
* than the view.
*
* - `scale`: The image gets drawn downscaled or upscaled. Compared to `resize`, `scale` is
* faster (usually hardware accelerated) and produces higher quality images. This
* should be used if the image is smaller than the view. It should also be used if the
* image is slightly bigger than the view.
*
* More details about `resize` and `scale` can be found at http://frescolib.org/docs/resizing-rotating.html.
*
* @platform android
*/
resizeMethod: PropTypes.oneOf(['auto', 'resize', 'scale']),
/**
* Determines how to resize the image when the frame doesn't match the raw
* image dimensions.
*
* - `cover`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal
* to or larger than the corresponding dimension of the view (minus padding).
*
* - `contain`: Scale the image uniformly (maintain the image's aspect ratio)
* so that both dimensions (width and height) of the image will be equal to
* or less than the corresponding dimension of the view (minus padding).
*
* - `stretch`: Scale width and height independently, This may change the
* aspect ratio of the src.
*
* - `repeat`: Repeat the image to cover the frame of the view. The
* image will keep it's size and aspect ratio. (iOS only)
*/
resizeMode: PropTypes.oneOf(['cover', 'contain', 'stretch', 'repeat', 'center']),
/**
* A unique identifier for this element to be used in UI Automation
* testing scripts.
*/
testID: PropTypes.string,
/**
* Invoked on mount and layout changes with
* `{nativeEvent: {layout: {x, y, width, height}}}`.
*/
onLayout: PropTypes.func,
/**
* Invoked on load start.
*
* e.g., `onLoadStart={(e) => this.setState({loading: true})}`
*/
onLoadStart: PropTypes.func,
/**
* Invoked on download progress with `{nativeEvent: {loaded, total}}`.
* @platform ios
*/
onProgress: PropTypes.func,
/**
* Invoked on load error with `{nativeEvent: {error}}`.
*/
onError: PropTypes.func,
/**
* Invoked when a partial load of the image is complete. The definition of
* what constitutes a "partial load" is loader specific though this is meant
* for progressive JPEG loads.
* @platform ios
*/
onPartialLoad: PropTypes.func,
/**
* Invoked when load completes successfully.
*/
onLoad: PropTypes.func,
/**
* Invoked when load either succeeds or fails.
*/
onLoadEnd: PropTypes.func,
},
statics: {
resizeMode: ImageResizeMode,
/**
* Retrieve the width and height (in pixels) of an image prior to displaying it.
* This method can fail if the image cannot be found, or fails to download.
*
* In order to retrieve the image dimensions, the image may first need to be
* loaded or downloaded, after which it will be cached. This means that in
* principle you could use this method to preload images, however it is not
* optimized for that purpose, and may in future be implemented in a way that
* does not fully load/download the image data. A proper, supported way to
* preload images will be provided as a separate API.
*
* Does not work for static image resources.
*
* @param uri The location of the image.
* @param success The function that will be called if the image was successfully found and width
* and height retrieved.
* @param failure The function that will be called if there was an error, such as failing to
* to retrieve the image.
*
* @returns void
*
* @platform ios
*/
getSize: function(
uri: string,
success: (width: number, height: number) => void,
failure?: (error: any) => void,
) {
ImageViewManager.getSize(uri, success, failure || function() {
console.warn('Failed to get size for image: ' + uri);
});
},
/**
* Prefetches a remote image for later use by downloading it to the disk
* cache
*
* @param url The remote location of the image.
*
* @return The prefetched image.
*/
prefetch(url: string) {
return ImageViewManager.prefetchImage(url);
},
/**
* Resolves an asset reference into an object which has the properties `uri`, `width`,
* and `height`. The input may either be a number (opaque type returned by
* require('./foo.png')) or an `ImageSource` like { uri: '<http location || file path>' }
*/
resolveAssetSource: resolveAssetSource,
},
mixins: [NativeMethodsMixin],
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
viewConfig: {
uiViewClassName: 'UIView',
validAttributes: ReactNativeViewAttributes.UIView
},
render: function() {
const source = resolveAssetSource(this.props.source) || { uri: undefined, width: undefined, height: undefined };
let sources;
let style;
if (Array.isArray(source)) {
style = flattenStyle([styles.base, this.props.style]) || {};
sources = source;
} else {
const {width, height, uri} = source;
style = flattenStyle([{width, height}, styles.base, this.props.style]) || {};
sources = [source];
if (uri === '') {
console.warn('source.uri should not be an empty string');
}
}
const resizeMode = this.props.resizeMode || (style || {}).resizeMode || 'cover'; // Workaround for flow bug t7737108
const tintColor = (style || {}).tintColor; // Workaround for flow bug t7737108
if (this.props.src) {
console.warn('The <Image> component requires a `source` property rather than `src`.');
}
return (
<RCTImageView
{...this.props}
style={style}
resizeMode={resizeMode}
tintColor={tintColor}
source={sources}
/>
);
},
});
const styles = StyleSheet.create({
base: {
overflow: 'hidden',
},
});
const RCTImageView = requireNativeComponent('RCTImageView', Image);
module.exports = Image;
|
src/routes/catalog/index.js | LeraSavchenko/Maysternia | /**
* 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 Catalog from './Catalog';
const title = 'Каталог продукції';
export default {
path: '/catalog',
action() {
return {
title: 'Каталог',
component: <Layout><Catalog title={title} /></Layout>,
};
},
};
|
src/components/Profile.js | kakapo2016-projects/tooth-and-pail | import React from 'react'
import cookie from 'react-cookie'
// display components
import NavBar from './NavBar'
import Header from './Header'
import HBar from './HBar'
import ProfilePhoto from './ProfilePhoto'
import ProfileName from './ProfileName'
import ProgressBar from './ProgressBar'
import DonateForm from './DonateForm'
import SobStory from './SobStory'
import SocialSharing from './SocialSharing'
import Paper from 'material-ui/lib/paper'
import RateMe from './RateMe'
import url from '../../config.js'
// material-ui helpers
import GetMuiTheme from 'material-ui/lib/styles/getMuiTheme'
import MyTheme from '../theme.js';
// database functions
import postRequest from '../postRequest.js'
import getRequest from '../getRequest.js'
import putRequest from '../putRequest.js'
export default React.createClass({
childContextTypes : {
muiTheme: React.PropTypes.object
},
getChildContext() {
return {
muiTheme: GetMuiTheme(MyTheme),
}
},
getInitialState: function () {
return {
amountDonated: 0,
name: 'Mr. Tooth',
title: 'Fun Teeth!',
imgURL: 'https://image.freepik.com/free-icon/tooth-outline_318-46885.png',
pageURL: 'https://toothandpail.herokuapp.com',
sobStory: `Hello, I'm Mr. Tooth! I keep the peace around here. Try donating a little money to somebody in need.`
}
},
handleDonation: function (donorID, recipientID, amount) {
let data = {
donorID: donorID,
recipientID: recipientID,
amount: amount
}
postRequest(url + '/donations', data, (err, res) => {
if (err) { console.log("ERROR!", err); return }
getRequest(url + '/donations/recipient/' + recipientID, (err, resp) => {
if (err) { console.log("ERROR!", err); return }
this.donationSetState(resp, recipientID)
})
})
},
componentDidMount: function () {
getRequest(url + '/recipients/' + this.props.params.recipientID, (err, resp) => {
if (err) { console.log("ERROR GETTING PROFILES!", err); return }
this.setState({
target: resp.target,
name: resp.name,
imgURL: resp.imgURL,
sobStory: resp.sobStory,
rating: resp.rating,
title: `Help fund dental care for ${resp.name}`,
pageURL: `https://toothandpail.herokuapp.com/${this.props.params.recipientID}`
})
getRequest(url + '/donations/recipient/' + this.props.params.recipientID, (err, resp) => {
if (err) { console.log("ERROR GETTING SPECFIC PROFILE!", err); return }
this.donationSetState(resp, this.props.params.recipientID)
})
})
},
updateRecipientReceived: function (totalReceived) {
let recipientData = {received : totalReceived }
putRequest(url + '/recipients/' + this.props.params.recipientID, recipientData, (err, res) => {
if (err) { console.log("ERROR UPDATING RECIPIENT!", err); return }
})
},
updateRecipientRating: function (newRate){
let donor = cookie.load('donorID')
let ratingData = {
recipientID: this.props.params.recipientID,
donorID: donor,
rating: newRate
}
getRequest(url + '/ratings/' + donor + '/recipient/' + this.props.params.recipientID, (err, resp) => {
if (err) { console.log("ERROR GETTING RATINGS!", err); return }
let cnt = 0
if (resp.length > 0) {
alert("You have already rated these teeth - Thank you!")
} else {
// create a new rating record
postRequest(url + '/ratings', ratingData, (err, respo) => {
if (err) { console.log("ERROR.......!", err); return }
alert("Thank you for rating these teeth!")
// all the ratings for this recipient are returned
// use them to calculate a new average rating
let totalValue = 0, count = 0
respo.body.map(function (x) {
totalValue += x.rating
count++
})
// find the average by dividing by count then round
var avrating = Math.floor(totalValue / count)
// update the state
this.setState({rating: avrating})
console.log('ave rating', avrating)
// update the recipients record in the database
let recipientData = { rating: avrating }
putRequest(url + '/recipients/' + this.props.params.recipientID, recipientData, (err, res) => {
if (err) { console.log("ERROR in put!", err); return }
})
})}
})
},
donationSetState: function (donations, recipientID) {
getRequest(url + '/recipients/' + this.props.params.recipientID, (err, resp) => {
if (err) { console.log("ERROR!", err); return }
var totalReceived = 0
donations.map(function (x){
totalReceived += x.amount
})
this.setState({target: resp.target, received: totalReceived, name: resp.name})
this.updateRecipientReceived(totalReceived)
})
},
render: function () {
return (
<div className='profile'>
<div>
<NavBar/>
<Header/>
<div className="row">
<div className="six columns">
<ProfilePhoto imgurl={this.state.imgURL}/>
<br />
<br />
<br />
<HBar target={this.state.target} received={this.state.received} barColor='#b71c1c'/>
</div>
<div className="six columns">
<ProfileName name={this.state.name}/>
<ProgressBar target={this.state.target} received={this.state.received}/>
<br/>
<DonateForm
handleDonation={this.handleDonation}
recipientID={this.props.params.recipientID}
target={this.state.target}
received={this.state.received}/>
<br />
<br />
<RateMe rating={this.state.rating} updateRecipientRating={this.updateRecipientRating}/>
<br />
</div>
<div className="six columns">
</div>
</div>
<div className="row">
<div className="twelve columns">
<SobStory sobstory={this.state.sobStory} />
<SocialSharing url={this.state.pageURL} title={this.state.title} media={this.state.imgURL}/>
</div>
</div>
</div>
</div>
)
}
})
|
src/js/components/TwitToServe/partial/EmailNotification.js | ajainsyn/project | import React from 'react';
import emailNotification from '../../../../assets/images/email-notification.jpg';
const EmailNotification = ({...props}) => (
<section className="section bg-blue" id="emailNotification">
<div className="container">
<div className="row align-items-center">
<div className="col-sm-6">
<div className="section-copy">
<h2 className="title">About Email Service Platform</h2>
<p>SynBaaS provides platform to <strong>build and deploy machine learning/analytics models</strong> (R and Python) as microservices and exposes the models as APIs.</p>
<p>Enterprise applications and external users can connect to the platform using <strong>REST API to score, evaluate and monitor</strong> the models.</p>
<button className="btn" onClick={props.onLaunchModel} >Launch Demo</button>
</div>
</div>
<div className="col-sm-6">
<div className="section-copy has-bgimage">
<img src={emailNotification} alt="" />
</div>
</div>
</div>
</div>
</section>
);
export default EmailNotification; |
src/modules/editor/components/popovers/addTooltip/AddTooltipMenu/AddImageButton/AddImageButton.js | CtrHellenicStudies/Commentary | import React from 'react';
import autoBind from 'react-autobind';
import { connect } from 'react-redux';
// redux
import editorActions from '../../../../../actions';
// components
import AddTooltipMenuItemButton from '../../AddTooltipMenuItemButton';
// lib
import addNewBlock from '../../../../../lib/addNewBlock';
// icons
import { MdImage } from "react-icons/md";
class AddImageButton extends React.Component {
constructor(props) {
super(props);
autoBind(this);
}
handleAddImage() {
this.refs.fileInput.click()
}
handleFileInput(e) {
const { editorState, setEditorState, setAddTooltip, addTooltip } = this.props;
const fileList = e.target.files;
const file = fileList[0];
const options = {
url: URL.createObjectURL(file),
file,
};
const newEditorState = addNewBlock(editorState, 'image', options);
setEditorState(newEditorState);
setAddTooltip({
...addTooltip,
visible: false,
menuVisible: false,
});
}
render() {
return (
<AddTooltipMenuItemButton
onClick={this.handleAddImage}
>
<MdImage />
<span>Image</span>
<input
type="file"
style={{ display: 'none' }}
ref="fileInput"
onChange={this.handleFileInput}
/>
</AddTooltipMenuItemButton>
);
}
}
const mapStateToProps = state => ({
...state.editor,
});
const mapDispatchToProps = dispatch => ({
setEditorState: (editorState) => {
dispatch(editorActions.setEditorState(editorState));
},
setAddTooltip: (addTooltip) => {
dispatch(editorActions.setAddTooltip(addTooltip));
},
});
export default connect(
mapStateToProps,
mapDispatchToProps,
)(AddImageButton);
|
src/DropdownMenu.js | dongtong/react-bootstrap | import React from 'react';
import keycode from 'keycode';
import classNames from 'classnames';
import RootCloseWrapper from 'react-overlays/lib/RootCloseWrapper';
import ValidComponentChildren from './utils/ValidComponentChildren';
import createChainedFunction from './utils/createChainedFunction';
class DropdownMenu extends React.Component {
constructor(props) {
super(props);
this.focusNext = this.focusNext.bind(this);
this.focusPrevious = this.focusPrevious.bind(this);
this.getFocusableMenuItems = this.getFocusableMenuItems.bind(this);
this.getItemsAndActiveIndex = this.getItemsAndActiveIndex.bind(this);
this.handleKeyDown = this.handleKeyDown.bind(this);
}
handleKeyDown(event) {
switch (event.keyCode) {
case keycode.codes.down:
this.focusNext();
event.preventDefault();
break;
case keycode.codes.up:
this.focusPrevious();
event.preventDefault();
break;
case keycode.codes.esc:
case keycode.codes.tab:
this.props.onClose(event);
break;
default:
}
}
focusNext() {
let { items, activeItemIndex } = this.getItemsAndActiveIndex();
if (items.length === 0) {
return;
}
if (activeItemIndex === items.length - 1) {
items[0].focus();
return;
}
items[activeItemIndex + 1].focus();
}
focusPrevious() {
let { items, activeItemIndex } = this.getItemsAndActiveIndex();
if (activeItemIndex === 0) {
items[items.length - 1].focus();
return;
}
items[activeItemIndex - 1].focus();
}
getItemsAndActiveIndex() {
let items = this.getFocusableMenuItems();
let activeElement = document.activeElement;
let activeItemIndex = items.indexOf(activeElement);
return {items, activeItemIndex};
}
getFocusableMenuItems() {
let menuNode = React.findDOMNode(this);
if (menuNode === undefined) {
return [];
}
return [].slice.call(menuNode.querySelectorAll('[tabIndex="-1"]'), 0);
}
render() {
let {children, onSelect, pullRight, className, labelledBy, open, onClose, ...props} = this.props;
const items = ValidComponentChildren.map(children, child => {
let childProps = child.props || {};
return React.cloneElement(child, {
onKeyDown: createChainedFunction(childProps.onKeyDown, this.handleKeyDown),
onSelect: createChainedFunction(childProps.onSelect, onSelect)
}, childProps.children);
});
const classes = {
'dropdown-menu': true,
'dropdown-menu-right': pullRight
};
let list = (
<ul
className={classNames(className, classes)}
role="menu"
aria-labelledby={labelledBy}
{...props}
>
{items}
</ul>
);
if (open) {
list = (
<RootCloseWrapper noWrap onRootClose={onClose}>
{list}
</RootCloseWrapper>
);
}
return list;
}
}
DropdownMenu.defaultProps = {
bsRole: 'menu',
pullRight: false
};
DropdownMenu.propTypes = {
open: React.PropTypes.bool,
pullRight: React.PropTypes.bool,
onClose: React.PropTypes.func,
labelledBy: React.PropTypes.oneOfType([
React.PropTypes.string,
React.PropTypes.number
]),
onSelect: React.PropTypes.func
};
export default DropdownMenu;
|
app/javascript/mastodon/features/status/components/card.js | rainyday/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import Immutable from 'immutable';
import ImmutablePropTypes from 'react-immutable-proptypes';
import punycode from 'punycode';
import classnames from 'classnames';
import Icon from 'mastodon/components/icon';
const IDNA_PREFIX = 'xn--';
const decodeIDNA = domain => {
return domain
.split('.')
.map(part => part.indexOf(IDNA_PREFIX) === 0 ? punycode.decode(part.slice(IDNA_PREFIX.length)) : part)
.join('.');
};
const getHostname = url => {
const parser = document.createElement('a');
parser.href = url;
return parser.hostname;
};
const trim = (text, len) => {
const cut = text.indexOf(' ', len);
if (cut === -1) {
return text;
}
return text.substring(0, cut) + (text.length > len ? '…' : '');
};
const domParser = new DOMParser();
const addAutoPlay = html => {
const document = domParser.parseFromString(html, 'text/html').documentElement;
const iframe = document.querySelector('iframe');
if (iframe) {
if (iframe.src.indexOf('?') !== -1) {
iframe.src += '&';
} else {
iframe.src += '?';
}
iframe.src += 'autoplay=1&auto_play=1';
// DOM parser creates html/body elements around original HTML fragment,
// so we need to get innerHTML out of the body and not the entire document
return document.querySelector('body').innerHTML;
}
return html;
};
export default class Card extends React.PureComponent {
static propTypes = {
card: ImmutablePropTypes.map,
maxDescription: PropTypes.number,
onOpenMedia: PropTypes.func.isRequired,
compact: PropTypes.bool,
defaultWidth: PropTypes.number,
cacheWidth: PropTypes.func,
};
static defaultProps = {
maxDescription: 50,
compact: false,
};
state = {
width: this.props.defaultWidth || 280,
embedded: false,
};
componentWillReceiveProps (nextProps) {
if (!Immutable.is(this.props.card, nextProps.card)) {
this.setState({ embedded: false });
}
}
handlePhotoClick = () => {
const { card, onOpenMedia } = this.props;
onOpenMedia(
Immutable.fromJS([
{
type: 'image',
url: card.get('embed_url'),
description: card.get('title'),
meta: {
original: {
width: card.get('width'),
height: card.get('height'),
},
},
},
]),
0,
);
};
handleEmbedClick = () => {
const { card } = this.props;
if (card.get('type') === 'photo') {
this.handlePhotoClick();
} else {
this.setState({ embedded: true });
}
}
setRef = c => {
if (c) {
if (this.props.cacheWidth) this.props.cacheWidth(c.offsetWidth);
this.setState({ width: c.offsetWidth });
}
}
renderVideo () {
const { card } = this.props;
const content = { __html: addAutoPlay(card.get('html')) };
const { width } = this.state;
const ratio = card.get('width') / card.get('height');
const height = width / ratio;
return (
<div
ref={this.setRef}
className='status-card__image status-card-video'
dangerouslySetInnerHTML={content}
style={{ height }}
/>
);
}
render () {
const { card, maxDescription, compact } = this.props;
const { width, embedded } = this.state;
if (card === null) {
return null;
}
const provider = card.get('provider_name').length === 0 ? decodeIDNA(getHostname(card.get('url'))) : card.get('provider_name');
const horizontal = (!compact && card.get('width') > card.get('height') && (card.get('width') + 100 >= width)) || card.get('type') !== 'link' || embedded;
const interactive = card.get('type') !== 'link';
const className = classnames('status-card', { horizontal, compact, interactive });
const title = interactive ? <a className='status-card__title' href={card.get('url')} title={card.get('title')} rel='noopener noreferrer' target='_blank'><strong>{card.get('title')}</strong></a> : <strong className='status-card__title' title={card.get('title')}>{card.get('title')}</strong>;
const ratio = card.get('width') / card.get('height');
const height = (compact && !embedded) ? (width / (16 / 9)) : (width / ratio);
const description = (
<div className='status-card__content'>
{title}
{!(horizontal || compact) && <p className='status-card__description'>{trim(card.get('description') || '', maxDescription)}</p>}
<span className='status-card__host'>{provider}</span>
</div>
);
let embed = '';
let thumbnail = <div style={{ backgroundImage: `url(${card.get('image')})`, width: horizontal ? width : null, height: horizontal ? height : null }} className='status-card__image-image' />;
if (interactive) {
if (embedded) {
embed = this.renderVideo();
} else {
let iconVariant = 'play';
if (card.get('type') === 'photo') {
iconVariant = 'search-plus';
}
embed = (
<div className='status-card__image'>
{thumbnail}
<div className='status-card__actions'>
<div>
<button onClick={this.handleEmbedClick}><Icon id={iconVariant} /></button>
{horizontal && <a href={card.get('url')} target='_blank' rel='noopener noreferrer'><Icon id='external-link' /></a>}
</div>
</div>
</div>
);
}
return (
<div className={className} ref={this.setRef}>
{embed}
{!compact && description}
</div>
);
} else if (card.get('image')) {
embed = (
<div className='status-card__image'>
{thumbnail}
</div>
);
} else {
embed = (
<div className='status-card__image'>
<Icon id='file-text' />
</div>
);
}
return (
<a href={card.get('url')} className={className} target='_blank' rel='noopener noreferrer' ref={this.setRef}>
{embed}
{description}
</a>
);
}
}
|
src/js/ui/components/settings/topMenu.js | hiddentao/heartnotes | import _ from 'lodash';
import React from 'react';
import Classnames from 'classnames';
import { connectRedux, routing } from '../../helpers/decorators';
import Button from '../button';
import AttentionIcon from '../attentionIcon';
import TabMenu from '../tabMenu';
var Component = React.createClass({
propTypes: {
tab: React.PropTypes.string,
},
render: function() {
const ITEMS = [
{
id: 'account',
route: '/settings',
desc: 'Account',
attention: () => {
let { diaryMgr } = this.props.data.diary;
return (!diaryMgr.auth.subscriptionActive)
? <AttentionIcon />
: null;
},
},
{
id: 'backupRestore',
route: '/settings/backupRestore',
desc: 'Backup / Export',
showIf: () => {
return !!_.get(this.props.data, 'diary.backupsEnabled');
},
},
{
id: 'feedback',
route: '/feedback',
desc: 'Feedback',
},
];
return (
<TabMenu
className="settings-top-menu"
items={ITEMS}
selectedItem={this.props.tab}
onSelect={this._onSelect} />
);
},
_onSelect: function(item) {
this.props.router.push(item.route);
},
});
module.exports = connectRedux()(routing()(Component));
|
test/integration/getserversideprops/pages/catchall/[...path].js | JeromeFitz/next.js | import React from 'react'
import Link from 'next/link'
import { useRouter } from 'next/router'
export async function getServerSideProps({ params }) {
return {
props: {
world: 'world',
params: params || {},
time: new Date().getTime(),
random: Math.random(),
},
}
}
export default ({ world, time, params, random }) => {
return (
<>
<p>hello: {world}</p>
<span>time: {time}</span>
<div id="random">{random}</div>
<div id="params">{JSON.stringify(params)}</div>
<div id="query">{JSON.stringify(useRouter().query)}</div>
<Link href="/">
<a id="home">to home</a>
</Link>
<br />
<Link href="/another">
<a id="another">to another</a>
</Link>
</>
)
}
|
index/components/SemanticQuery.js | JDRomano2/VenomKB | import React from 'react';
import {
Button,
Form,
FormGroup,
FormControl,
ControlLabel,
} from 'react-bootstrap';
class DeclareField extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div id='declare-box'>
<FormGroup controlId="testing">
<ControlLabel>Ontology class</ControlLabel>
<FormControl
componentClass="select"
placeholder="Choose an ontology class"
>
<option value="protein">Protein</option>
<option value="species">Species</option>
<option value="genome">Genome</option>
<option value="systemiceffect">SystemicEffect</option>
<option value="pfam">ProteinFamily</option>
</FormControl>
</FormGroup>
<FormGroup>
<ControlLabel>Filter</ControlLabel>
<Form componentClass="fieldset" inline>
<FormControl
type="text"
placeholder="Enter attribute"
style={{width: '35%'}}
/>
<FormControl
componentClass="select"
placeholder="Select an operator"
style={{width: '15%'}}
>
<option value="equals">equals</option>
<option value="contains">contains</option>
</FormControl>
<FormControl
type="text"
placeholder="Enter a value"
style={{width: '50%'}}
/>
</Form>
</FormGroup>
</div>
);
}
}
class AggregateField extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div id='aggregate-box'>
<FormGroup>
<ControlLabel>Aggregation function</ControlLabel>
<FormControl componentClass="select">
<option value="distinct">distinct</option>
<option value="count">count</option>
<option value="sort">sort</option>
<option value="exists">exists</option>
</FormControl>
</FormGroup>
<FormGroup>
<ControlLabel>Apply to:</ControlLabel>
<Form componentClass="fieldset" inline>
<FormControl
componentClass="select"
placeholder="Class"
style={{width: '40%'}}
>
<option value="protein">Protein</option>
<option value="species">Species</option>
<option value="genome">Genome</option>
<option value="systemiceffect">SystemicEffect</option>
<option value="pfam">ProteinFamily</option>
</FormControl>
<FormControl
type="text"
placeholder="Attribute (optional)"
style={{width: '60%'}}
/>
</Form>
</FormGroup>
</div>
);
}
}
class EditableDeclareFields extends React.Component {
constructor(props) {
super(props);
}
render() {
const declareFields = this.props.declareFields.map(() =>(
<DeclareField />
));
return (
<div id='declareFields'>
{declareFields}
</div>
);
}
}
class EditableAggregateFields extends React.Component {
constructor(props) {
super(props);
}
render() {
const aggregateFields = this.props.aggregateFields.map(() =>(
<AggregateField />
));
return (
<div id='aggregateFields'>
{aggregateFields}
</div>
);
}
}
class SemanticQuery extends React.Component {
constructor(props) {
super(props);
this.state = {
declareFields: [],
aggregateFields: [],
};
}
handleNewDeclareFieldClick = () => {
const df = {
'ontology-class': '',
'constraints': [
{
'attribute': '',
'operator': '',
'value': ''
}
],
};
this.setState({
declareFields: this.state.declareFields.concat(df),
});
}
handleDeleteDeclareFieldClick = () => {
const dfs = this.state.declareFields;
dfs.pop();
this.setState({
declareFields: dfs,
});
}
handleNewAggregateFieldClick = () => {
const af = {
'aggregation': ''
};
this.setState({
aggregateFields: this.state.aggregateFields.concat(af),
});
}
handleDeleteAggregateFieldClick = () => {
const afs = this.state.aggregateFields;
afs.pop();
this.setState({
aggregateFields: afs,
});
}
render() {
return (
<div className='jumbotron'>
<div className='container'>
<h2>Submit a Semantic API query</h2>
<p style={{'fontSize': '11pt'}}>
For an explanation of the different fields and what they mean, see the documentation: <Button bsSize="xsmall" href="about/api">Semantic API Documentation</Button>
</p>
<form>
<div id='container'>
<FormGroup
controlId="dataSelect"
>
<ControlLabel>Select a data type</ControlLabel>
<FormControl componentClass="select" placeholder="data type">
<option value="protein">Protein</option>
<option value="species">Species</option>
<option value="genome">Genome</option>
<option value="systemiceffect">SystemicEffect</option>
<option value="pfam">ProteinFamily</option>
</FormControl>
</FormGroup>
<div className="hr"/>
<FormGroup
controlId="dataDeclare"
>
<ControlLabel>Apply filters to related data types</ControlLabel>
<div>
<EditableDeclareFields
declareFields={this.state.declareFields}
/>
<Button
onClick={this.handleNewDeclareFieldClick}
>Add field</Button>
{this.state.declareFields.length > 0 &&
<Button
onClick={this.handleDeleteDeclareFieldClick}
bsStyle="danger"
>Delete field</Button>
}
</div>
</FormGroup>
<div className="hr"/>
<FormGroup
controlId="dataAggregate"
>
<ControlLabel>Run additional functions on the results (optional)</ControlLabel>
<EditableAggregateFields
aggregateFields={this.state.aggregateFields}
/>
<Button
onClick={this.handleNewAggregateFieldClick}
>Add field</Button>
{this.state.aggregateFields.length > 0 &&
<Button
onClick={this.handleDeleteAggregateFieldClick}
bsStyle="danger"
>Delete field</Button>
}
</FormGroup>
</div>
<Button type="submit" bsSize="large">Submit query</Button>
</form>
</div>
</div>
);
}
}
export default SemanticQuery;
|
src/components/user-list/user-list.js | DmitriyRelkin/redux-study | import React from 'react';
export default class extends React.Component {
constructor(props) {
super(props);
}
render() {
return (
<div>
<ul className='user-list'>
{this.props.data.length ?
(this.props.data.map((user, i) => <li key={i} id={i}>{i+1}) {' '}
{ user.name.length > 5 ? user.name.slice(0, 7) + '...' : user.name}
<button onClick={this.props.userDelete}>DELETE</button></li>))
: <span className="list-empty">List is empty</span>}
</ul>
</div>
)
}
} |
test/unit/resources/individual/resource-test.js | travi/admin.travi.org-components | import React from 'react';
import Helmet from 'react-helmet';
import {string} from '@travi/any';
import {assert} from 'chai';
import {shallow} from 'enzyme';
import PageLoading from '../../../../src/atoms/loading-indicators/page';
import {Resource} from '../../../../src/main';
suite('resource component test', () => {
const resource = {id: string(), displayName: string()};
test('that the resource is displayed', () => {
const wrapper = shallow(<Resource resource={resource} loading={false} />);
assert.isTrue(wrapper.contains(<h3>{resource.displayName}</h3>), 'heading should be displayed');
assert.isTrue(
wrapper.contains(<Helmet title={resource.displayName} />),
`expected the title to be set to '${resource.displayName}' using helmet`
);
assert.isFalse(
wrapper.containsMatchingElement(<PageLoading />),
'expected loading indicator to be hidden'
);
});
test('that a loading indicator is displayed when data is still loading', () => {
const wrapper = shallow(<Resource resource={{}} loading={true} />);
assert.isTrue(
wrapper.contains(<PageLoading />),
'expected loading indicator to be displayed'
);
assert.isTrue(
wrapper.contains(<Helmet title="Loading Resource..." />),
'expected the title to be set to "Loading Resource..." using helmet'
);
assert.isFalse(wrapper.containsMatchingElement(<h3 />), 'heading should be hidden');
});
});
|
client/index.js | bayareawebdevs/note-keeper | import React from 'react';
import ReactDOM from 'react-dom';
import Root from './components/Root';
require('../static/css/style.scss');
ReactDOM.render(<Root />, document.getElementById('root')); |
server/middleware/reactMiddleware.js | Moises404/Vimeo-React | import {RouterContext, match} from 'react-router'
import {Provider} from 'react-redux'
import React from 'react'
import configureStore from '../../client/store/configureStore'
import createLocation from 'history/lib/createLocation'
import {fetchFire, setClient} from '../../client/actions/AppActions'
import {renderToString} from 'react-dom/server'
import routes from '../../client/routes'
import MobileDetect from 'mobile-detect'
const defaultCookie = '{"firstTime": true}'
const cookieName = 'VimeoReact'
const contact404 = '@Moises404'
function hydrateInitialStore (req) {
const md = new MobileDetect(req.headers['user-agent'])
const ua = md.mobile() ? 'mobile' : 'desktop'
const cookie = JSON.parse((req.cookies[cookieName] || defaultCookie))
return (dispatch) => {
return (
Promise.all([
dispatch(fetchFire()),
dispatch(setClient({'cookie': cookie, 'agent': ua}))
])
)
}
}
function stringifyJSON(data) {
return JSON.stringify(data, (key, val) => {
if (/\u2028/.test(val)) {
return ''
}
return val;
});
}
export default function reactMiddleware (req, res) {
const location = createLocation(req.url)
match({routes, location}, (error, redirectLocation, renderProps) => {
if (error) return res.status(500).send(error.message)
if (redirectLocation) return res.redirect(302, redirectLocation.pathname + redirectLocation.search)
if (!renderProps && location.path !== '/') return res.redirect(302, '/')
if (!renderProps) return res.status(404).send(`The site is currently 404\'d, lol. Contact ${contact404} if you see this.`)
const assets = require('../../build/assets.json')
const store = configureStore()
if (!req.cookies[cookieName]) res.cookie(cookieName, defaultCookie)
return store.dispatch(hydrateInitialStore(req)).then(() => {
console.log('HYDRATE INTIAL STORE WORKED')
const initialState = stringifyJSON(store.getState())
const content = renderToString(
<Provider store={store}>
<RouterContext {...renderProps} />
</Provider>
)
return res.render('index', {content, assets, initialState})
})
})
}
|
docs/app/Examples/modules/Dropdown/Usage/DropdownExampleUncontrolled.js | aabustamante/Semantic-UI-React | import React from 'react'
import { Dropdown } from 'semantic-ui-react'
const options = [
{ key: 1, text: 'One', value: 1 },
{ key: 2, text: 'Two', value: 2 },
{ key: 3, text: 'Three', value: 3 },
]
const DropdownExampleUncontrolled = () => (
<Dropdown
selection
options={options}
placeholder='Choose an option'
/>
)
export default DropdownExampleUncontrolled
|
app/components/error.js | Goodly/TextThresher | import React, { Component } from 'react';
export default class NotFoundRoute extends Component {
constructor(props) {
super(props);
}
render() {
return (
<div className='item'>
<div className='404-message canvas-text'>
<h1>
Something went wrong...
</h1>
</div>
</div>
);
}
}
|
src/components/Page/Page.js | takahashik/todo-app | /**
* React Starter Kit (https://www.reactstarterkit.com/)
*
* Copyright © 2014-present Kriasoft, LLC. All rights reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE.txt file in the root directory of this source tree.
*/
import React from 'react';
import PropTypes from 'prop-types';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import s from './Page.css';
class Page extends React.Component {
static propTypes = {
title: PropTypes.string.isRequired,
html: PropTypes.string.isRequired,
};
render() {
const { title, html } = this.props;
return (
<div className={s.root}>
<div className={s.container}>
<h1>{title}</h1>
<div
// eslint-disable-next-line react/no-danger
dangerouslySetInnerHTML={{ __html: html }}
/>
</div>
</div>
);
}
}
export default withStyles(s)(Page);
|
app/assets/scripts/components/Image/index.js | bartoszkrawczyk2/curves.js | import React, { Component } from 'react';
import { applyCurves } from '../../core';
import './style.scss';
class ImageView extends Component {
componentDidMount() {
let img = new Image();
img.onload = () => {
this.props.loadPhoto(img, this.props.image.renderCanvas, this.props.image.renderCtx);
this.refs.canvasContainer.appendChild(this.props.image.renderCanvas);
}
img.src = this.props.image.defaultImage;
}
componentWillUpdate(nextProps, nextState) {
applyCurves(
nextProps.image.originalImage,
this.props.image.renderCanvas,
this.props.image.renderCtx,
nextProps.curves.currentCurves
);
}
render() {
return (
<div className='image-wrapper' ref='canvasContainer'></div>
);
}
}
export default ImageView; |
src/App/Containers/Index.js | focuswish/scheduletext | import React from 'react'
import Layout from '../Components/Layout'
import Input from '../Components/Input'
import Btn from '../Components/Btn'
import moment from 'moment'
import { SingleDatePicker } from 'react-dates';
require('isomorphic-fetch')
class Index extends React.Component {
constructor(props) {
super(props)
this.state = {
formState: {
to: {
value: ''
},
message: {
value: ''
},
date: {
value: ''
},
time: {
value: ''
}
},
date: null,
focused: false,
user: null
}
this.handleSubmit = this.handleSubmit.bind(this)
}
handleChange(name, e) {
var formState = this.state.formState
formState[name].value = e.target.value
this.setState({formState})
}
handleSubmit() {
var to = encodeURI(this.state.formState.to.value)
var message = encodeURI(this.state.formState.message.value)
var time = this.state.formState.time.value
var hoursMinutes = time.split(':')
var scheduledTime = moment(this.state.date).hour(hoursMinutes[0]).minute(hoursMinutes[1]).format();
var date = scheduledTime
//var date = encodeURI(scheduledTime)
fetch(`http://scheduletext.com/twilio/${to}/${date}/${message}`).then(resp => resp.json())
.then((resp) => {
console.log(resp)
})
}
render() {
var {formState} = this.state
return(
<Layout>
<div className="row">
{this.state.user ? this.state.user : null}
<Input
handleChange={this.handleChange.bind(this, 'message')}
value={formState['message'].value}
label='Message'
/>
</div>
<div className="row">
<Input
handleChange={this.handleChange.bind(this, 'to')}
value={formState['to'].value}
label='Recipient'
/>
<Input
handleChange={this.handleChange.bind(this, 'time')}
value={formState['time'].value}
label='Time (military)'
/>
<SingleDatePicker
date={this.state.date} // momentPropTypes.momentObj or null
onDateChange={date => this.setState({ date })} // PropTypes.func.isRequired
focused={this.state.focused} // PropTypes.bool
onFocusChange={({ focused }) => this.setState({ focused })} // PropTypes.func.isRequired
/>
</div>
<div className="row">
<Btn text='Submit' handleSubmit={this.handleSubmit} />
</div>
</Layout>
)
}
}
export default Index |
ui/src/components/denali/NavBarItem.js | yahoo/athenz | /*
* Copyright 2020 Verizon Media
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import React from 'react';
import PropTypes from 'prop-types';
import { css, cx } from '@emotion/css';
import { rgba } from 'polished';
import { colors } from './styles/colors';
import { cssFontSizes, cssFontFamilies } from './styles/fonts';
const makeCssNavBarItem = (props) => css`
align-items: center;
box-sizing: border-box;
display: flex;
height: 60px;
position: relative;
width: ${props.width};
label: navbar-item;
&.simple {
color: ${colors.white};
${cssFontFamilies.default};
${cssFontSizes.heading};
padding: 0 12px;
transition: ${!props.noanim ? 'all 0.2s ease-in' : undefined};
&.nav-link {
cursor: pointer;
&:hover {
color: ${rgba(colors.white, 0.75)};
}
}
&.active {
box-shadow: inset 0 -4px 0 ${colors.brand600};
}
&.nav-link.active:hover {
box-shadow: inset 0 -4px 0 ${rgba(colors.brand600, 0.75)};
}
}
& .nav-title {
align-items: center;
color: ${colors.white};
display: flex;
${cssFontFamilies.default};
${cssFontSizes.heading};
height: 100%;
padding: 0 12px;
transition: ${!props.noanim ? 'all 0.2s ease-in' : undefined};
}
&.nav-link .nav-title {
cursor: pointer;
}
&.active .nav-title,
& .active.nav-title {
box-shadow: inset 0 -4px 0 ${colors.brand600};
}
& .nav-title:hover {
color: ${rgba(colors.white, 0.75)};
}
&.nav-link.active .nav-title:hover,
&.nav-link .active.nav-title:hover {
box-shadow: inset 0 -4px 0 ${rgba(colors.brand600, 0.75)};
}
/* Logo */
& img.nav-logo {
align-items: center;
display: flex;
height: 34px;
}
/* Icons */
& .nav-icon,
&:hover .nav-icon {
width: 24px;
height: 24px;
& path,
& ellipse,
& rect,
& circle {
fill: ${colors.white};
transition: ${!props.noanim ? 'all 0.2s ease-in' : undefined};
}
}
&.nav-link:hover .nav-icon {
& path,
& ellipse,
& rect,
& circle {
fill: ${rgba(colors.white, 0.75)};
}
}
`;
class NavBarItem extends React.PureComponent {
render() {
const {
active,
className,
complex,
link,
noanim,
right,
width,
...rest
} = this.props;
const cssProps = { active, noanim, width };
const cssNavBarItem = makeCssNavBarItem(cssProps);
const classes = cx(
cssNavBarItem,
{
simple: !complex,
active,
'flush-right': right,
'nav-link': link,
},
'denali-navbar-item',
className
);
return <div {...rest} className={classes} data-testid='navbar-item' />;
}
}
NavBarItem.propTypes = {
/**
* Sets active state (blue underline).
* NOTE: An alternative is to use `type="complex"` and apply `.active` to
* the element with `.nav-title`
*/
active: PropTypes.bool,
/**
* Children to render inside `NavBarItem`
* @ignore
*/
children: PropTypes.any,
/** Additonal class to apply to the outer div */
className: PropTypes.string,
/**
* By default, `<NavBarItem>` assumes the content is a simple string. If
* `complex` is set, then the component can be another component or nested
* HTML elements. The element to be displayed should have a `.nav-title` class
* attacked to it. An example is creating a dropdown menu where the trigger is
* the display element.
*/
complex: PropTypes.bool,
/**
* Sets the item to be a link.
* NOTE: This sets only the CSS. It's up to the developer to provide the
* actual routing.
*/
link: PropTypes.bool,
/** Disable animations / transitions */
noanim: PropTypes.bool,
/**
* Flush the element to the right.
* NOTE: Only one element within `<NavBar>` should have this property set.
*/
right: PropTypes.bool,
/**
* Any valid CSS width value.
* NOTE: This includes 15px padding on the left and on the right.
*/
width: PropTypes.string,
};
NavBarItem.defaultProps = {
active: false,
complex: false,
link: false,
right: false,
};
export default NavBarItem;
|
client/components/Comments.js | dimitardanailov/reduxstagram | import React from 'react';
const Comments = React.createClass({
renderComment(comment, i) {
return (
<div className="comment" key={i}>
<p>
<strong>{comment.user}</strong>
{comment.text}
<button className="remove-comment"
onClick={this.props.removeComment.bind(null, this.props.params.postId, i)}>×</button>
</p>
</div>
)
},
handleSubmit(e) {
e.preventDefault();
const { postId } = this.props.params;
const author = this.refs.author.value;
const comment = this.refs.comment.value;
this.props.addComment(postId, author, comment);
this.refs.commentForm.reset();
},
render() {
return (
<div className="commentс">
{this.props.postComments.map(this.renderComment)}
<form ref="commentForm" className="comment-form" onSubmit={this.handleSubmit}>
<input type="text" ref="author" placeholder="author" />
<input type="text" ref="comment" placeholder="comment" />
<input type="submit" hidden />
</form>
</div>
);
}
});
export default Comments; |
src/components/Work/Work.js | GJMcGowan/personal_site | import React, { Component } from 'react';
class Work extends Component {
render() {
return (
<div className='multibox-container-top'>
<div className='col-xs-8 col-xs-offset-2 multibox-container'>
<p>I make websites, this is one of them</p>
<p>To find more examples of my work, go <a target='_blank' href='https://github.com/GJMcGowan'>here</a></p>
<p>I work at <a target='_blank' href='https://eu.deloittedigital.com/en/home'>Deloitte Digital</a> in the Front-End team</p>
</div>
<div className='col-xs-8 col-xs-offset-2 multibox-container'>
<p>
This site is made using React, which is my main interest at the moment. My day job is largely React/Redux projects.
</p>
<p>
I'm also comfortable with Angular, and I've dabbled with Vue.
</p>
<p>
I have some backend experience, largely with simple NodeJS servers. Sometimes I use Ruby & Ruby on Rails.
</p>
</div>
</div>
);
}
}
export default Work;
|
src/client/routes/Viewer/components/ViewerView.js | jaimerosales/visual-reports-bim360dc | import {
ReflexContainer,
ReflexElement,
ReflexSplitter
} from 'react-reflex'
import ContextMenuExtensionId from 'Viewing.Extension.ContextMenu'
import DualExtensionId from 'Viewing.Extension.DualViewer'
import PieExtensionId from 'Viewing.Extension.PieChart'
import BarExtensionId from 'Viewing.Extension.BarChart'
import TreeExtensionId from 'Viewing.Extension.Tree'
import WidgetContainer from 'WidgetContainer'
import {
ReactLoader
} from 'Loader'
import Toolkit from 'Viewer.Toolkit'
import Viewer from 'Viewer'
//import Tree from 'Tree'
import './ViewerView.scss'
import React from 'react'
class ViewerView extends React.Component {
/////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////
constructor() {
super()
this.onViewerCreated = this.onViewerCreated.bind(this)
this.state = {
dualExtension: null,
barExtension: null,
pieExtension: null,
treeExtension: null
}
}
componentWillMount() {
this.props.setNavbarState({
links: {
login: true
}
})
}
/////////////////////////////////////////////////////////
// Initialize viewer environment
//
/////////////////////////////////////////////////////////
initialize(options) {
return new Promise((resolve, reject) => {
Autodesk.Viewing.Initializer(options, () => {
resolve()
}, (error) => {
reject(error)
})
})
}
/////////////////////////////////////////////////////////
// Load a document from URN
//
/////////////////////////////////////////////////////////
loadDocument(urn) {
return new Promise((resolve, reject) => {
const paramUrn = !urn.startsWith('urn:') ? 'urn:' + urn : urn
Autodesk.Viewing.Document.load(paramUrn, (doc) => {
resolve(doc)
}, (error) => {
reject(error)
})
})
}
/////////////////////////////////////////////////////////
// Return viewable path: first 3d or 2d item by default
//
/////////////////////////////////////////////////////////
getViewablePath(doc, pathIdx = 0, roles = ['3d', '2d']) {
const rootItem = doc.getRootItem()
const roleArray = [...roles]
let items = []
roleArray.forEach((role) => {
items = [...items,
...Autodesk.Viewing.Document.getSubItemsWithProperties(
rootItem, {
type: 'geometry',
role
}, true)
]
})
if (!items.length || pathIdx > items.length) {
return null
}
return doc.getViewablePath(items[pathIdx])
}
assignState(state) {
return new Promise((resolve) => {
const newState = Object.assign({}, this.state, state)
this.setState(newState, () => {
resolve()
})
})
}
/////////////////////////////////////////////////////////
// viewer div and component created
//
/////////////////////////////////////////////////////////
async onViewerCreated(viewer) {
try {
let doc = null
let {
id,
urn,
path,
pathIdx
} = this.props.location.query
// check if env is initialized
// initializer cannot be invoked more than once
if (!this.props.appState.viewerEnv) {
await this.initialize({
env: 'AutodeskProduction',
useConsolidation: true
})
this.props.setViewerEnv('AutodeskProduction')
Autodesk.Viewing.setEndpointAndApi(
window.location.origin + '/lmv-proxy-2legged',
'modelDerivativeV2')
Autodesk.Viewing.Private.memoryOptimizedSvfLoading = true
//Autodesk.Viewing.Private.logger.setLevel(0)
}
if (urn) {
doc = await this.loadDocument(urn)
path = this.getViewablePath(doc, pathIdx || 0)
} else if (!path) {
const error = 'Invalid query parameter: ' +
'use id OR urn OR path in url'
throw new Error(error)
}
viewer.start()
this.loadExtensions(viewer, doc)
viewer.loadModel(path)
} catch (ex) {
console.log('Viewer Initialization Error: ')
console.log(ex)
}
}
loadExtensions(viewer, doc) {
const extOptions = (id) => {
return {
react: {
pushRenderExtension: () => {},
pushViewerPanel: () => {},
popRenderExtension: () => {},
popViewerPanel: () => {},
forceUpdate: () => {
return new Promise((resolve) => {
this.forceUpdate(() => {
resolve()
})
})
},
getComponent: () => {
return this
},
getState: () => {
return this.state[id] || {}
},
setState: (state, merge) => {
return new Promise((resolve) => {
const extState = this.state[id] || {}
var newExtState = {}
newExtState[id] = merge ? _.merge({}, extState, state) : Object.assign({}, extState, state)
this.assignState(newExtState).then(() => {
resolve(newExtState)
})
})
}
}
}
}
viewer.loadExtension(TreeExtensionId,
Object.assign({}, extOptions(TreeExtensionId), {
viewerDocument: doc
})).then((treeExtension) => {
this.assignState({
treeExtension
})
})
viewer.loadExtension(DualExtensionId,
Object.assign({}, extOptions(DualExtensionId), {
viewerDocument: doc
})).then((dualExtension) => {
this.assignState({
dualExtension
})
})
viewer.loadExtension(BarExtensionId,
Object.assign({}, extOptions(BarExtensionId), {
"chartProperties" : [
"Category",
"Flow",
"Level",
"Material",
"Reference Level",
"System Classification",
"System Name",
"System Type"
]
})).then((barExtension) => {
this.assignState({
barExtension
})
})
viewer.loadExtension(PieExtensionId,
Object.assign({}, extOptions(PieExtensionId), {
"chartProperties" : [
"Category",
"Flow",
"Level",
"Material",
"Reference Level",
"System Classification",
"System Name",
"System Type"
]
})).then((pieExtension) => {
this.assignState({
pieExtension
})
})
viewer.loadExtension(
ContextMenuExtensionId, {
buildMenu: (menu, selectedDbId) => {
return !selectedDbId ? [{
title: 'Show all objects',
target: () => {
Toolkit.isolateFull(this.viewer)
this.viewer.fitToView()
}
}] : menu
}
})
}
/////////////////////////////////////////////////////////
//
//
/////////////////////////////////////////////////////////
render() {
const {treeExtension} = this.state
const {dualExtension} = this.state
const {pieExtension} = this.state
const {barExtension} = this.state
return (
<div className="viewer-view">
<ReflexContainer orientation='vertical'>
<ReflexElement >
<WidgetContainer title="BIM 360">
{treeExtension && treeExtension.render()}
</WidgetContainer>
</ReflexElement>
<ReflexSplitter onStopResize={() => this.forceUpdate()}/>
<ReflexElement>
<ReflexContainer orientation='horizontal'>
<ReflexSplitter/>
<ReflexElement flex={0.5} propagateDimensions={true} minSize={150}>
<Viewer onViewerCreated={this.onViewerCreated}/>
</ReflexElement>
<ReflexSplitter/>
<ReflexElement minSize={39} onResizeRate={100} onResize={() => dualExtension.onResize()}>
<ReactLoader show={!dualExtension}/>
{dualExtension && dualExtension.render()}
</ReflexElement>
</ReflexContainer>
</ReflexElement>
<ReflexSplitter onStopResize={() => barExtension.onStopResize()}/>
<ReflexElement>
<ReflexContainer orientation='horizontal'>
<ReflexSplitter/>
<ReflexElement minSize={39} onStopResize={() => pieExtension.onStopResize()}>
<ReactLoader show={!pieExtension}/>
{pieExtension && pieExtension.render()}
</ReflexElement>
<ReflexSplitter/>
<ReflexElement minSize={39} onStopResize={() => barExtension.onStopResize()}>
<ReactLoader show={!barExtension}/>
{barExtension && barExtension.render()}
</ReflexElement>
</ReflexContainer>
</ReflexElement>
</ReflexContainer>
</div>
)
}
}
export default ViewerView |
src/svg-icons/image/flash-off.js | pomerantsev/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageFlashOff = (props) => (
<SvgIcon {...props}>
<path d="M3.27 3L2 4.27l5 5V13h3v9l3.58-6.14L17.73 20 19 18.73 3.27 3zM17 10h-4l4-8H7v2.18l8.46 8.46L17 10z"/>
</SvgIcon>
);
ImageFlashOff = pure(ImageFlashOff);
ImageFlashOff.displayName = 'ImageFlashOff';
ImageFlashOff.muiName = 'SvgIcon';
export default ImageFlashOff;
|
src/form/createForm.js | aulamber/generic-react-form | /*
A FAIRE
1) Ajouter linter
2) Enregistrer un état pristine de la data
3) Proposer de mettre la data à zéro
4) faire un composant de select + checkbox + textarea + radio/radiogroup
+ number + range (+ email ?) (moins important): email, url, date, color, time
5) Remettre dans l'ordre alpha tous les noms de variables + proptypes
6) optimisation des perfs (limiter au max les boucles dans les boucles avec les forEach)
7) comparer à redux form
8) tests
9) doc + readme
10) passage en module npm
*/
import React, { Component } from 'react';
import {
getFieldErrorsToDisplay,
getFinalValues,
hasFieldErrors,
initializeFields,
updateDisableStatus,
updateFieldErrors,
updateFieldValue,
updateFieldsPostSubmit,
updateFormErrors,
setParamsDefaultValues,
shouldDisplayFormErrors,
} from './utils/index';
import Input from '../form/Input'
export default function createForm({ ...params }, ComposedComponent) {
class Form extends Component {
constructor(props) {
super(props);
this.state = {
disabled: true,
displayErrorsFromStart: params.displayErrorsFromStart,
displayFormErrors: false,
fields: {},
fieldErrorsToDisplay: {},
formErrors: {},
pristine: true,
}
this.params = setParamsDefaultValues(params);
this.getInitialData = this.getInitialData.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.onFieldChange = this.onFieldChange.bind(this);
this.renderInput = this.renderInput.bind(this);
this.resetInitialData = this.resetInitialData.bind(this);
this.resetDataEmpty = this.resetDataEmpty.bind(this);
this.setFormProperties = this.setFormProperties.bind(this);
}
componentWillMount() {
const { pristine } = this.state;
const { initialFields, fieldChecks, formChecks } = this.params;
const fields = initializeFields(initialFields, fieldChecks);
const formErrors = updateFormErrors({}, formChecks, fields);
const initialData = this.setFormProperties({ fields, formErrors, pristine });
this.setState({ initialData });
}
getInitialData() {
return this.state.initialData;
}
resetInitialData() {
this.setState(this.state.initialData);
}
resetDataEmpty() {
const { fields } = this.state.initialData;
let resetFields = {};
let fieldErrorsToDisplay = {};
Object.keys(this.state.fieldErrorsToDisplay)
.forEach(field => {
fieldErrorsToDisplay = { ...fieldErrorsToDisplay, [field]: {} };
})
Object.keys(fields).forEach(field => {
resetFields = {
...resetFields,
[field]: { ...fields[field], value: '', pristine: true },
}
});
this.setState({
...this.state.initialData,
fieldErrorsToDisplay,
fields: resetFields,
displayErrorsFromStart: false,
})
}
setFormProperties({ fields, formErrors, pristine }) {
const fromStart = this.state.displayErrorsFromStart;
const state = {
disabled: updateDisableStatus(pristine, fromStart, fields, formErrors),
displayErrorsFromStart: fromStart,
displayFormErrors: shouldDisplayFormErrors(formErrors, fromStart, pristine),
fields,
fieldErrorsToDisplay: getFieldErrorsToDisplay(fields, fromStart),
formErrors,
pristine,
};
this.setState(state);
return state;
}
onFieldChange(userFunction = () => {}) {
return (name) => {
return (e) => {
const { fieldChecks, formChecks } = this.params;
const value = e.target.value;
const pristine = false;
let fields = this.state.fields;
fields = updateFieldValue(name, value, fields);
fields = updateFieldErrors(name, value, fields, fieldChecks[name]);
fields = updateFieldErrors(name, value, fields, fieldChecks.comparChecks, true);
let formErrors = this.state.formErrors;
formErrors = updateFormErrors(formErrors, formChecks, fields);
this.setFormProperties({ fields, formErrors, pristine });
userFunction();
}
}
}
handleSubmit(onSubmit = () => {}) {
return (e) => {
let fields = this.state.fields;
const { displayErrorsFromStart, formErrors } = this.state;
const finalValues = getFinalValues(fields);
const pristine = false;
if (displayErrorsFromStart) {
onSubmit(finalValues);
this.resetDataEmpty();
} else {
fields = updateFieldsPostSubmit(fields);
let fieldErrors = hasFieldErrors(fields);
if (!fieldErrors && !Object.keys(formErrors).length) {
onSubmit(finalValues);
this.resetDataEmpty();
} else {
this.setFormProperties({ fields, formErrors, pristine });
}
}
e.preventDefault();
}
}
renderInput(userProps) {
const inputProps = {
...userProps,
displayErrorsFromStart: this.state.displayErrorsFromStart,
fields: this.state.fields,
onFieldChange: this.onFieldChange,
};
return <Input { ...inputProps } />
}
render() {
console.log('this.state = ', this.state);
const formProps = {
...this.state,
formName: this.params.formName,
handleSubmit: this.handleSubmit,
renderInput: this.renderInput,
onFieldChange: this.onFieldChange,
}
return <ComposedComponent { ...formProps } />
}
}
return Form;
}
|
loader/index.js | grantila/node-pure-jsx | 'use strict';
const loaderUtils = require( 'loader-utils' );
function isSourceCodeFile( source )
{
source = source.trim( );
while ( source.startsWith( '/' ) )
{
if ( source.startsWith( '/*' ) )
source = source.substr( source.indexOf( '*/' ) + 2 ).trim( );
else
source = source.substr( source.indexOf( '\n' ) ).trim( );
}
const useStrictHeaders = [ "'use strict'", '"use strict"' ];
if (
source.startsWith( useStrictHeaders[ 0 ] ) ||
source.startsWith( useStrictHeaders[ 1 ] )
)
return true;
return false;
}
module.exports = function( source )
{
this.cacheable( );
const options = Object.assign( { }, loaderUtils.getOptions( this ) );
if ( isSourceCodeFile( source ) )
return source;
// Options
const strict = options.strict || false;
const contexts = options.contexts || [ ];
const requireReact = options.requireReact == null
? contexts.indexOf( 'React' ) === -1
: options.requireReact;
const contextsList = ( contexts.length > 0 )
? "{ " + options.contexts.join( ', ' ) + " }"
: "";
const strictHeader = !strict
? ""
: "'use strict';\n\n";
const requireReactHeader = !requireReact
? ""
: "import React from 'react'\n\n";
const mainHeader = `export default function( ${contextsList} )
{
return function( arg, key )
{
const $ = this.constructor;
const props = this.props;
const state = this.state;
return `;
const header = strictHeader + requireReactHeader + mainHeader;
const footer = `;
};
}`;
return header + source + footer;
};
|
app/screen/HomePage.js | daskinnyman/electron-QA | // @flow
import React, { Component } from 'react';
import Home from '../components/Home';
export default class HomePage extends Component {
render() {
return (
<Home />
);
}
}
|
components/User/UserNotificationsPanel/UserNotificationsPanel.js | slidewiki/slidewiki-platform | import PropTypes from 'prop-types';
import React from 'react';
import {connectToStores} from 'fluxible-addons-react';
import {navigateAction} from 'fluxible-router';
import UserNotificationsStore from '../../../stores/UserNotificationsStore';
import UserProfileStore from '../../../stores/UserProfileStore';
import UserFollowingsStore from '../../../stores/UserFollowingsStore';
import UserNotificationsList from './UserNotificationsList';
import updateUserNotificationsVisibility from '../../../actions/user/notifications/updateUserNotificationsVisibility';
import markAsReadUserNotifications from '../../../actions/user/notifications/markAsReadUserNotifications';
import deleteAllUserNotifications from '../../../actions/user/notifications/deleteAllUserNotifications';
import loadUserNotifications from '../../../actions/user/notifications/loadUserNotifications';
import loadFollowings from '../../../actions/following/loadFollowings';
import selectAllActivityTypes from '../../../actions/user/notifications/selectAllActivityTypes';
import FollowingsModal from './FollowingsModal';
import {Button} from 'semantic-ui-react';
import setDocumentTitle from '../../../actions/setDocumentTitle';
let MediaQuery = require ('react-responsive');
class UserNotificationsPanel extends React.Component {
constructor(props){
super(props);
this.state = {
showFollowingsModal: false
};
}
handleClickOnFollowingsSetting() {
this.setState({
showFollowingsModal: true
});
}
componentWillMount() {
if ((String(this.props.UserProfileStore.userid) === '')) {//the user is not loggedin
this.context.executeAction(navigateAction, {
url: '/'
});
} else {
this.context.executeAction(loadUserNotifications, { uid: this.props.UserProfileStore.userid });
this.context.executeAction(loadFollowings, { userId: this.props.UserProfileStore.userid });
}
}
componentDidMount() {
$('.ui.accordion').accordion();
this.context.executeAction(setDocumentTitle, {
title: this.context.intl.formatMessage({
id: 'userNotifications.title',
defaultMessage: 'User notifications'
})
});
}
handleChangeToggle(type, id) {
this.context.executeAction(updateUserNotificationsVisibility, {
changedType: type,
changedId: id
});
//set value of selectAll
let value = true;
this.props.UserNotificationsStore.activityTypes.forEach((at) => {if (! $('#' + at.type).prop('checked')) value = false;});
$('#all').prop('checked', value);
}
handleChangeAll() {
let value = $('#all').prop('checked');
this.props.UserNotificationsStore.activityTypes.forEach((at) => {$('#' + at.type).prop('checked', value);});
this.context.executeAction(selectAllActivityTypes, {
value: value
});
}
handleMarkAsRead() {
this.context.executeAction(markAsReadUserNotifications, {
uid: this.props.UserProfileStore.userid
});
}
handleDelete() {
swal({
title: 'Delete all notifications. Are you sure?',
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Yes, delete!'
}).then((accepted) => {
this.context.executeAction(deleteAllUserNotifications, {
uid: this.props.UserProfileStore.userid
});
}, (reason) => {/*do nothing*/}).catch(swal.noop);
}
render() {
if (String(this.props.UserProfileStore.userid) === '') {//user is not loggedin
return null;
}
const activityTypeList = this.props.UserNotificationsStore.activityTypes.map((at, index) => {
const labelName = (at.type === 'react') ? 'Like' : at.type;
const label = labelName.charAt(0).toUpperCase() + labelName.slice(1);
return (
<div className="ui item toggle checkbox" key={index} role="listitem" tabIndex="0">
<input name={at.type} id={at.type} type="checkbox" defaultChecked={at.selected} onChange={this.handleChangeToggle.bind(this, at.type, 0)} />
<label>{label}</label>
</div>
);
});
const notifications = this.props.UserNotificationsStore.notifications;
const notificationsCount = this.props.UserNotificationsStore.notifications ? this.props.UserNotificationsStore.notifications.length : 0;
const newNotificationsCount = this.props.UserNotificationsStore.newNotificationsCount;
const selector = this.props.UserNotificationsStore.selector;
const buttonMarkAsReadDisabled = newNotificationsCount === 0;
const buttonDeleteAllDisabled = notificationsCount === 0;
const buttonMarkAsReadTitle = (newNotificationsCount > 1) ? 'Mark all ' + newNotificationsCount + ' new notifications as read' : 'Mark all new notifications as read';
const buttonDeleteAllTitle = (notificationsCount > 1) ? 'Delete all ' + notificationsCount + ' notifications' : 'Delete all notifications';
let noOfDecks = (this.props.UserFollowingsStore.deckFollowings) ? this.props.UserFollowingsStore.deckFollowings.length : '';
let noOfPlaylists = (this.props.UserFollowingsStore.playlistFollowings) ? this.props.UserFollowingsStore.playlistFollowings.length : '';
let followingDisplay = (this.props.UserFollowingsStore.loading) ? 'You are subscribed to decks and playlists ' : 'You are subscribed to ' + noOfDecks + ' ' + ((noOfDecks > 1) ? 'decks' : 'deck' ) + ' and ' + noOfPlaylists + ' ' + ((noOfPlaylists > 1) ? 'playlists' : 'playlist') + ' ';
let buttons = (
<Button.Group basic >
<Button disabled={buttonMarkAsReadDisabled} aria-label='Mark all as read' onClick={this.handleMarkAsRead.bind(this)} data-tooltip={buttonMarkAsReadTitle}>
<i className="icons large">
<i className="check square outline icon" ></i>
<i className="corner check icon"></i>
</i>
</Button>
<Button disabled={buttonDeleteAllDisabled} aria-label='Delete all' onClick={this.handleDelete.bind(this)} data-tooltip={buttonDeleteAllTitle}>
<i className="icons large">
<i className="times circle outline icon" ></i>
<i className="corner remove icon"></i>
</i>
</Button>
<Button aria-label='Manage subscriptions' onClick={this.handleClickOnFollowingsSetting.bind(this)} data-tooltip={followingDisplay} >
<i className="icons large">
<i className="setting icon" ></i>
<i className="corner rss icon"></i>
</i>
</Button>
</Button.Group>);
const filters = (
<div className="five wide column">
<div className="ui basic segment">
<h4 className="ui header" id="navigation">Show activity types:</h4>
<div className="activityTypes">
<div ref="activityTypeList">
<div className="ui relaxed list" role="list" >
<div className="ui toggle checkbox">
<input name="all" id="all" type="checkbox" defaultChecked={true} onChange={this.handleChangeAll.bind(this)}/>
<label>Select all</label>
</div>
<div className="ui hidden divider" />
{activityTypeList}
</div>
</div>
</div>
</div>
</div>
);
let loadingDiv = <div className="ui basic segment">
<div className="ui active text loader">Loading</div>
</div>;
let emptyDiv = <div className="ui grid centered">
<h3>There are currently no notifications.</h3>
</div>;
let notificationsDiv='';
if(this.props.UserNotificationsStore.loading){
notificationsDiv = loadingDiv;
} else if (notifications.length === 0) {
notificationsDiv = emptyDiv;
} else {
notificationsDiv = <UserNotificationsList username={this.props.UserProfileStore.username} userid={this.props.UserProfileStore.userid} items={notifications} selector={selector} />;
}
return (
<div ref="userNotificationsPanel">
<div className="ui hidden divider" />
<div className="ui container stackable two columm grid">
<div className="six wide column">
<h1 className="ui huge header" id="main">Notifications
<div className="ui mini label" aria-label="number of new notifications"> {newNotificationsCount} </div>
</h1>
{buttons}
<div className="ui basic segment">
<MediaQuery minDeviceWidth={768}>
{filters}
</MediaQuery>
<MediaQuery maxDeviceWidth={767}>
<div className="ui accordion">
<div className="title active">
<i className="icon dropdown"></i>
Filters
</div>
<div className="content field">
{filters}
</div>
</div>
</MediaQuery>
</div>
</div>
<div className="column ten wide">
<div className="ui basic segment">
{notificationsDiv}
</div>
</div>
</div>
<FollowingsModal isOpen={this.state.showFollowingsModal} handleClose={() => this.setState({showFollowingsModal: false})} />
</div>
);
}
}
UserNotificationsPanel.contextTypes = {
intl: PropTypes.object.isRequired,
executeAction: PropTypes.func.isRequired
};
UserNotificationsPanel = connectToStores(UserNotificationsPanel, [UserNotificationsStore, UserProfileStore, UserFollowingsStore], (context, props) => {
return {
UserNotificationsStore: context.getStore(UserNotificationsStore).getState(),
UserProfileStore: context.getStore(UserProfileStore).getState(),
UserFollowingsStore: context.getStore(UserFollowingsStore).getState()
};
});
export default UserNotificationsPanel;
|
src/app/components/list/Order.js | cherishstand/OA-react | import React from 'react';
import {Link, browserHistory} from 'react-router';
import {List, ListItem, MakeSelectable} from 'material-ui/List';
import { Router, Route, hashHistory } from 'react-router';
import AppBar from 'material-ui/AppBar';
import IconButton from 'material-ui/IconButton';
import ArrowBaclIcon from 'material-ui/svg-icons/navigation/arrow-back';
import Add from 'material-ui/svg-icons/content/add';
import Search from '../public/Search';
import MenuTotal from '../public/MenuTotal';
import {CONFIG} from '../../constants/Config';
import {Tool} from '../../constants/Tools';
import Template from '../public/template'
const styles={
textColor:{
color: '#7888af',
},
back:{
backgroundColor: '#fff',
margin: '12px',
borderRadius: 4,
boxShadow:'rgba(0, 0, 0, 0.117647) 0px 1px 6px',
},
head: {
textAlign: 'center',
height: 45,
lineHeight: '45px',
backgroundColor:'rgb(255, 255, 255)',
},
title:{
height: 45,
lineHeight: '45px',
overflow: 'initial'
}
}
class Head extends React.Component {
constructor(props, context){
super(props, context)
}
render() {
return(
<AppBar
style={styles.head}
titleStyle={styles.title}
title={<MenuTotal items={CONFIG.order} {...this.context}/>}
iconStyleRight={{marginTop: 0}}
iconStyleLeft={{marginTop: 0}}
iconElementLeft={<Link to={browserHistory}><IconButton><ArrowBaclIcon color="#5e95c9"/></IconButton></Link>}
iconElementRight={<IconButton><Add color="#5e95c9"/></IconButton>}
/>
)
}
}
Head.contextTypes={
fetchPosts: React.PropTypes.any
}
class ViewCell extends React.Component {
render(){
return (
<Link to={{pathname:`/order/${this.props.salesorderid}`, query: {url: 'orders', mode: 22}}}>
<ListItem
style={styles.back}
primaryText={
<p><span style={styles.textColor}>{this.props.last_name}</span></p>
}
innerDivStyle={{padding: 8}}
secondaryText={
<p>
<span style={styles.textColor}>S{this.props.id} {this.props.modifiedtime.substring(0, 10)}</span><br />
<span ><span>金额: ¥</span>{this.props.listprice}</span>
</p>
}
secondaryTextLines={2}
/>
</Link>
)
}
}
class Order extends React.Component {
constructor(props, context){
super(props, context)
this.props.fetchPosts({url: 'orders'})
this.state = {
data: [],
currentPage: 1,
totalPage: 1,
isFetching: false,
shouldUpdata: true
}
this.getNextPage = (currentPage) => {
if(!this.state.shouldUpdata) {
return
}
this.state.shouldUpdata = false
this.props.getDate('/orders', { type: 'all', limit: 8, page: currentPage}, (res) => {
this.state.currentPage = currentPage;
this.state.shouldUpdata = true;
if(res.code === 200) {
this.setState({data: this.state.data.concat(res.data)})
} else {
console.log(res.code);
}
}, 'nextPage')
}
}
componentWillReceiveProps(nextProps){
let { data } = nextProps.state;
this.state.data = data && data.data || [];
this.state.currentPage = data && data.current || 1;
this.state.totalPage = data && data.pages || 1;
this.state.isFetching = nextProps.state.isFetching || false;
}
getChildContext(){
return{
fetchPosts: this.props.fetchPosts
}
}
render(){
const {currentPage, totalPage, shouldUpdata} = this.state
if(currentPage < totalPage) {
Tool.nextPage(this.refs.container, currentPage, totalPage, this.getNextPage, shouldUpdata)
}
return(
<div>
<div className="fiexded">
<Head />
<Search />
</div>
<div className='item_lists' ref='container'>
<List style={{paddingTop: 0}}>
{
this.state.data.map((item, index) => {
return <ViewCell {...item} key={index} />
})
}
</List>
</div>
</div>
)
}
}
Order.childContextTypes={
fetchPosts: React.PropTypes.any
}
export default Template({
component: Order
});
|
app/jsx/custom_help_link_settings/CustomHelpLinkIcons.js | venturehive/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 IconSettingsLine from 'instructure-icons/lib/Line/IconSettingsLine'
import IconFolderLine from 'instructure-icons/lib/Line/IconFolderLine'
import IconInfoLine from 'instructure-icons/lib/Line/IconInfoLine'
import IconLifePreserverLine from 'instructure-icons/lib/Line/IconLifePreserverLine'
import IconQuestionLine from 'instructure-icons/lib/Line/IconQuestionLine'
import CustomHelpLinkIconInput from './CustomHelpLinkIconInput'
export default function CustomHelpLinkIcons(props) {
const {defaultValue} = props
return (
<fieldset className="ic-Fieldset ic-Fieldset--radio-checkbox">
<legend className="ic-Legend">{I18n.t('Icon')}</legend>
<div className="ic-Form-control ic-Form-control--radio ic-Form-control--radio-inline">
<CustomHelpLinkIconInput
value="help"
defaultChecked={defaultValue === 'help'}
label={I18n.t('Question mark icon')}
>
<IconQuestionLine />
</CustomHelpLinkIconInput>
<CustomHelpLinkIconInput
value="information"
defaultChecked={defaultValue === 'information'}
label={I18n.t('Information icon')}
>
<IconInfoLine />
</CustomHelpLinkIconInput>
<CustomHelpLinkIconInput
value="folder"
defaultChecked={defaultValue === 'folder'}
label={I18n.t('Folder icon')}
>
<IconFolderLine />
</CustomHelpLinkIconInput>
<CustomHelpLinkIconInput
value="cog"
defaultChecked={defaultValue === 'cog'}
label={I18n.t('Cog icon')}
>
<IconSettingsLine />
</CustomHelpLinkIconInput>
<CustomHelpLinkIconInput
value="lifepreserver"
defaultChecked={defaultValue === 'lifepreserver'}
label={I18n.t('Life preserver icon')}
>
<IconLifePreserverLine />
</CustomHelpLinkIconInput>
</div>
</fieldset>
)
}
CustomHelpLinkIcons.propTypes = {
defaultValue: PropTypes.string
}
CustomHelpLinkIcons.defaultProps = {
defaultValue: ''
}
|
pages/illustrations/jewel/index.js | DarcyChan/darcychan.com | import React from 'react';
import { Artwork } from 'components/artwork';
import { PageContent } from 'components/page';
import { Image } from 'components/common';
/* eslint-disable quotes */
exports.data = {
id: 2,
path: `/illustrations/jewel/`,
category: `illustration`,
type: `artwork`,
preview: `preview.jpg`,
title: `Jewel`,
description: `An illustration.`,
keywords: `illustration`
};
/* eslint-enable quotes */
export default class Jewel extends React.Component {
render() {
const route = this.props.route;
return (
<Artwork route={route}>
<PageContent data={route.page.data}>
<Image
src={'images/jewel.jpg'}
alt="Jewel"
width={1328}
height={1743}
/>
</PageContent>
</Artwork>
);
}
}
|
src/svg-icons/image/healing.js | ichiohta/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageHealing = (props) => (
<SvgIcon {...props}>
<path d="M17.73 12.02l3.98-3.98c.39-.39.39-1.02 0-1.41l-4.34-4.34c-.39-.39-1.02-.39-1.41 0l-3.98 3.98L8 2.29C7.8 2.1 7.55 2 7.29 2c-.25 0-.51.1-.7.29L2.25 6.63c-.39.39-.39 1.02 0 1.41l3.98 3.98L2.25 16c-.39.39-.39 1.02 0 1.41l4.34 4.34c.39.39 1.02.39 1.41 0l3.98-3.98 3.98 3.98c.2.2.45.29.71.29.26 0 .51-.1.71-.29l4.34-4.34c.39-.39.39-1.02 0-1.41l-3.99-3.98zM12 9c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm-4.71 1.96L3.66 7.34l3.63-3.63 3.62 3.62-3.62 3.63zM10 13c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2 2c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1zm2-4c.55 0 1 .45 1 1s-.45 1-1 1-1-.45-1-1 .45-1 1-1zm2.66 9.34l-3.63-3.62 3.63-3.63 3.62 3.62-3.62 3.63z"/>
</SvgIcon>
);
ImageHealing = pure(ImageHealing);
ImageHealing.displayName = 'ImageHealing';
ImageHealing.muiName = 'SvgIcon';
export default ImageHealing;
|
src/svg-icons/communication/message.js | ruifortes/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationMessage = (props) => (
<SvgIcon {...props}>
<path d="M20 2H4c-1.1 0-1.99.9-1.99 2L2 22l4-4h14c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-2 12H6v-2h12v2zm0-3H6V9h12v2zm0-3H6V6h12v2z"/>
</SvgIcon>
);
CommunicationMessage = pure(CommunicationMessage);
CommunicationMessage.displayName = 'CommunicationMessage';
CommunicationMessage.muiName = 'SvgIcon';
export default CommunicationMessage;
|
src/svg-icons/communication/contacts.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let CommunicationContacts = (props) => (
<SvgIcon {...props}>
<path d="M20 0H4v2h16V0zM4 24h16v-2H4v2zM20 4H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm-8 2.75c1.24 0 2.25 1.01 2.25 2.25s-1.01 2.25-2.25 2.25S9.75 10.24 9.75 9 10.76 6.75 12 6.75zM17 17H7v-1.5c0-1.67 3.33-2.5 5-2.5s5 .83 5 2.5V17z"/>
</SvgIcon>
);
CommunicationContacts = pure(CommunicationContacts);
CommunicationContacts.displayName = 'CommunicationContacts';
CommunicationContacts.muiName = 'SvgIcon';
export default CommunicationContacts;
|
app/components/FormContainer.js | ahang/ContentClub | // ----------------------------
// import dependencies
// ----------------------------
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import { Redirect } from "react-router-dom";
import helpers from "../utils/helpers"
class FormContainer extends Component {
constructor(props) {
super(props);
this.state = {
boardTitle: '',
category: 'entertainment',
contentURL: '',
contentDescription: '',
openUntil: '',
isPublic: '',
user: "",
boardId: null,
redirect: false
};
this.handleFormSubmit = this.handleFormSubmit.bind(this);
this.handleClearForm = this.handleClearForm.bind(this);
this.handleBoardTitle = this.handleBoardTitle.bind(this);
this.handleCategory = this.handleCategory.bind(this);
this.handleContentURL = this.handleContentURL.bind(this);
this.handleContentDescription = this.handleContentDescription.bind(this);
this.handleOpenUntil = this.handleOpenUntil.bind(this);
this.handleIsPublic = this.handleIsPublic.bind(this);
}
handleBoardTitle(e) {
this.setState({ boardTitle: e.target.value }, () => console.log('board name:', this.state.boardTitle));
}
handleCategory(e) {
this.setState({ category: e.target.value }, () => console.log('category:', this.state.category));
}
handleContentURL(e) {
this.setState({ contentURL: e.target.value }, () => console.log('contentURL:', this.state.contentURL));
}
handleContentDescription(e) {
this.setState({ contentDescription: e.target.value }, () => console.log('contentDescription:', this.state.contentDescription));
}
handleOpenUntil(e) {
this.setState({ openUntil: e.target.value }, () => console.log('openUntil:', this.state.openUntil));
}
handleIsPublic(e) {
this.setState({ isPublic: e.target.value }, () => console.log('isPublic:', this.state.isPublic));
}
handleClearForm(e) {
e.preventDefault();
this.setState({
boardTitle: '',
category: '',
contentURL: '',
contentDescription: '',
openUntil: '',
isPublic: ''
});
}
handleFormSubmit(e) {
e.preventDefault();
const boardSubmit = {
boardTitle: this.state.boardTitle,
category: this.state.category,
contentURL: this.state.contentURL,
contentDescription: this.state.contentDescription,
openUntil: this.state.openUntil,
isPublic: this.state.isPublic
};
helpers.saveBoard(boardSubmit)
.then((result) => {
//console.log('new form was created:', boardSubmit);
//console.log(result);
this.setState({
boardId: result.data._id,
redirect: true });
}) ;
}
render() {
const { redirect } = this.state;
if (redirect) {
return <Redirect to={`/board/${this.state.boardId}`} />;
}
return (
<div className="searchContainer col-md-8 col-centered">
<div className="panel-heading">
<center>
<h1> Create a board </h1>
<h3 className="panel-title">Please provide the following information</h3>
</center>
</div>
<div className="panel-body">
<form>
<div className="form-group">
<center> Board Title:</center><input type="text" className="form-control" value={this.state.boardTitle} onChange={this.handleBoardTitle} />
</div>
<div className="form-group">
<center>Category: </center>
<select className="form-control" value={this.state.category} onChange={this.handleCategory} >
<option value="entertainment">Entertainment</option>
<option value="politics">Politics</option>
<option value="technology">Technology</option>
<option value="career">Career</option>
</select>
</div>
<div className="form-group">
<center> Content URL: </center><input type="text" className="form-control" value={this.state.contentURL} onChange={this.handleContentURL} />
</div>
<div className="form-group">
<center> Content Description: </center><input type="text" className="form-control" value={this.state.contentDescription} onChange={this.handleContentDescription} />
</div>
<div className="form-group">
<center> Open Until: </center><input type="date" className="form-control" value={this.state.openUntil} onChange={this.handleOpenUntil} />
</div>
<div className="form-group">
<center>
<button className="btn searchBtn" onClick={this.handleClearForm}>Clear</button>
<button className="btn searchBtn" type="submit" onClick={this.handleFormSubmit}>Submit</button>
</center>
</div>
</form>
</div>
</div>
);
}
}
export default FormContainer; |
fields/types/geopoint/GeoPointFilter.js | benkroeger/keystone | import React from 'react';
import {
FormField,
FormInput,
Grid,
SegmentedControl,
} from '../../../admin/client/App/elemental';
const DISTANCE_OPTIONS = [
{ label: 'Max distance (km)', value: 'max' },
{ label: 'Min distance (km)', value: 'min' },
];
function getDefaultValue () {
return {
lat: undefined,
lon: undefined,
distance: {
mode: DISTANCE_OPTIONS[0].value,
value: undefined,
},
};
}
var TextFilter = React.createClass({
propTypes: {
filter: React.PropTypes.shape({
lat: React.PropTypes.number,
lon: React.PropTypes.number,
distance: React.PropTypes.shape({
mode: React.PropTypes.string,
value: React.PropTypes.number,
}),
}),
},
statics: {
getDefaultValue: getDefaultValue,
},
getDefaultProps () {
return {
filter: getDefaultValue(),
};
},
updateFilter (value) {
this.props.onChange({ ...this.props.filter, ...value });
},
changeLat (evt) {
this.updateFilter({ lat: evt.target.value });
},
changeLon (evt) {
this.updateFilter({ lon: evt.target.value });
},
changeDistanceValue (evt) {
this.updateFilter({
distance: {
mode: this.props.filter.distance.mode,
value: evt.target.value,
},
});
},
changeDistanceMode (mode) {
this.updateFilter({
distance: {
mode,
value: this.props.filter.distance.value,
},
});
},
render () {
const { filter } = this.props;
const distanceModeVerb = filter.distance.mode === 'max' ? 'Maximum' : 'Minimum';
return (
<div>
<Grid.Row xsmall="one-half" gutter={10}>
<Grid.Col>
<FormField label="Latitude" >
<FormInput
autoFocus
onChange={this.changeLat}
placeholder={'Latitude'}
ref="latitude"
required="true"
step={0.01}
type="number"
value={filter.lat}
/>
</FormField>
</Grid.Col>
<Grid.Col>
<FormField label="Longitude">
<FormInput
onChange={this.changeLon}
placeholder={'Longitude'}
ref="longitude"
required="true"
step={0.01}
type="number"
value={filter.lon}
/>
</FormField>
</Grid.Col>
</Grid.Row>
<FormField>
<SegmentedControl
equalWidthSegments
onChange={this.changeDistanceMode}
options={DISTANCE_OPTIONS}
value={this.props.filter.distance.mode}
/>
</FormField>
<FormInput
onChange={this.changeDistanceValue}
placeholder={distanceModeVerb + ' distance from point'}
ref="distance"
type="number"
value={filter.distance.value}
/>
</div>
);
},
});
module.exports = TextFilter;
|
src/pages/contact.js | clarkcarter/clark-carter | import React from 'react'
export default () =>
<div>
<h1>Get in touch</h1>
<p>
<a href="mailto:clark@clarkcarter.com">clark@clarkcarter.com</a>
</p>
</div>
|
app/javascript/mastodon/features/ui/components/drawer_loading.js | Nyoho/mastodon | import React from 'react';
const DrawerLoading = () => (
<div className='drawer'>
<div className='drawer__pager'>
<div className='drawer__inner' />
</div>
</div>
);
export default DrawerLoading;
|
pootle/static/js/auth/components/SocialVerification.js | Yelp/pootle | /*
* Copyright (C) Pootle contributors.
*
* This file is a part of the Pootle project. It is distributed under the GPL3
* or later license. See the LICENSE file for a copy of the license and the
* AUTHORS file for copyright and authorship information.
*/
import assign from 'object-assign';
import React from 'react';
import { FormElement } from 'components/forms';
import { FormMixin } from 'mixins/forms';
import { gotoScreen, verifySocial } from '../actions';
import AuthProgress from './AuthProgress';
const SocialVerification = React.createClass({
mixins: [FormMixin],
propTypes: {
email: React.PropTypes.string.isRequired,
formErrors: React.PropTypes.object.isRequired,
isLoading: React.PropTypes.bool.isRequired,
providerName: React.PropTypes.string.isRequired,
},
getInitialState() {
// XXX: initialData required by `FormMixin`; this is really OBSCURE
this.initialData = {
password: '',
};
return {
formData: assign({}, this.initialData),
};
},
componentWillReceiveProps(nextProps) {
if (this.state.errors !== nextProps.formErrors) {
this.setState({errors: nextProps.formErrors});
}
},
/* Handlers */
handleRequestPasswordReset(e) {
e.preventDefault();
this.props.dispatch(gotoScreen('requestPasswordReset'));
},
handleFormSubmit(e) {
e.preventDefault();
this.props.dispatch(verifySocial(this.state.formData));
},
/* Others */
hasData() {
return this.state.formData.password !== '';
},
/* Layout */
render() {
if (this.props.redirectTo) {
return <AuthProgress msg={gettext('Signed in. Redirecting...')} />
}
let { errors } = this.state;
let { formData } = this.state;
let verificationMsg = interpolate(
gettext('We found a user with <span>%s</span> email in our system. Please provide the password to finish the sign in procedure. This is a one-off procedure, which will establish a link between your Pootle and %s accounts.'),
[this.props.email, this.props.providerName]
);
return (
<div className="actions">
<p dangerouslySetInnerHTML={{__html: verificationMsg}} />
<div>
<form
method="post"
onSubmit={this.handleFormSubmit}>
<div className="fields">
<FormElement
type="password"
attribute="password"
label={gettext('Password')}
handleChange={this.handleChange}
formData={formData}
errors={errors}
/>
<div className="actions password-forgotten">
<a href="#" onClick={this.handleRequestPasswordReset}>
{gettext('I forgot my password')}
</a>
</div>
{this.renderAllFormErrors()}
</div>
<div className="actions">
<div>
<input
type="submit"
className="btn btn-primary"
disabled={!this.hasData() | this.props.isLoading}
value={gettext('Sign In')}
/>
</div>
</div>
</form>
</div>
</div>
);
},
});
export default SocialVerification;
|
src/components/NotFoundPage.js | pagepress/pagepress | import React from 'react';
import { Link } from 'react-router';
const NotFoundPage = () => {
return (
<div>
<h4>
404 Page Not Found
</h4>
<Link to="/"> Go back to homepage </Link>
</div>
);
};
export default NotFoundPage;
|
assets/jqwidgets/demos/react/app/scheduler/worktime/app.js | juannelisalde/holter | import React from 'react';
import ReactDOM from 'react-dom';
import JqxScheduler from '../../../jqwidgets-react/react_jqxscheduler.js';
class App extends React.Component {
render () {
// prepare the data
let source =
{
dataType: 'json',
dataFields: [
{ name: 'id', type: 'string' },
{ name: 'status', type: 'string' },
{ name: 'about', type: 'string' },
{ name: 'address', type: 'string' },
{ name: 'company', type: 'string' },
{ name: 'name', type: 'string' },
{ name: 'style', type: 'string' },
{ name: 'calendar', type: 'string' },
{ name: 'start', type: 'date', format: 'yyyy-MM-dd HH:mm' },
{ name: 'end', type: 'date', format: 'yyyy-MM-dd HH:mm' }
],
id: 'id',
url: '../sampledata/appointments.txt'
};
let adapter = new $.jqx.dataAdapter(source);
let appointmentDataFields =
{
from: 'start',
to: 'end',
id: 'id',
description: 'about',
location: 'address',
subject: 'name',
style: 'style',
status: 'status'
};
let views =
[
{ type: 'dayView', showWeekends: false, timeRuler: { hidden: false } },
{
type: 'weekView', workTime:
{
fromDayOfWeek: 1,
toDayOfWeek: 5,
fromHour: 7,
toHour: 19
}
}
];
return (
<JqxScheduler ref='myScheduler'
width={850} height={600} source={adapter}
date={new $.jqx.date(2016, 11, 23)}
view={'weekView'} views={views}
appointmentDataFields={appointmentDataFields}
/>
)
}
}
ReactDOM.render(<App />, document.getElementById('app'));
|
src/components/Become_a_partner.js | RicardoG2016/WRFD-project-site | import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import '../App.css';
class Become_a_partner extends Component {
componentDidMount(){
window.scrollTo(0, 0);
}
render() {
return (
<div id="contact">
<div className="row">
<div className="col-sm-6 col-2 bg-inverse text-white py-2 d-flex align-items-center justify-content-center" id="left">
<div className="l-sec">
<div className="partner">
<h5 className="hidden-xs-down l-content">Become a Partner</h5>
</div>
</div>
</div>
<div className="contact-form col offset-2 offset-sm-6 py-2 text-muted" id="text">
<p style={{fontWeight: "bold", fontSize: "20px"}}>With a goal of fostering increased individual and collective global action throughout the year, June 22 is envisioned to become a day of celebration and bring attention to the importance of rainforests.</p>
<br/>
<p>Contact <span style={{fontWeight: "bolder", fontSize: "18px"}} ><a href="mailto:delainey@rainforestpartnership.org?Subject=I'd%20like%20to%20become%20a%20partner" target="_top">Delainey</a></span> if you are interested in becoming a collaborating partner or would like to receive a digital toolkit.</p>
<br/>
<p>See below for more actions to take:</p>
<ul>
<li>Use the <a href="https://twitter.com/intent/tweet?button_hashtag=WorldRainforestDay">#WorldRainforestDay</a> hashtag in all digital communications</li>
<li>Follow us on social media:
<ul>
<li>Twitter: <a href="https://twitter.com/Rainforest_Day">@rainforest_day</a></li>
<li>Instagram: <a href="https://www.instagram.com/worldrainforestday/">@worldrainforestday</a></li>
<li>Facebook: <a href="https://www.facebook.com/worldrainforestday/">@worldrainforestday</a></li>
</ul>
</li>
<li>Share with respective partners and other like organizations and invite them to promote World Rainforest Day</li>
<li>Encourage your followers to also take these simple actions or the ones listed on our site <Link to="/act">here.</Link></li>
</ul>
<br/>
</div>
</div>
</div>
);
}
}
export default Become_a_partner;
|
app/addons/replication/route.js | michellephung/couchdb-fauxton | // Licensed under the Apache License, Version 2.0 (the "License"); you may not
// use this file except in compliance with the License. You may obtain a copy of
// the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
// WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
// License for the specific language governing permissions and limitations under
// the License.
import React from 'react';
import FauxtonAPI from '../../core/api';
import ReplicationController from './container';
const ReplicationRouteObject = FauxtonAPI.RouteObject.extend({
routes: {
'replication/_create': 'createView',
'replication/_create/:dbname': 'createView',
'replication/id/:id': 'createViewFromId',
'replication': 'activityView',
'replication/_replicate': 'replicateView'
},
selectedHeader: 'Replication',
roles: ['fx_loggedIn'],
setActivityCrumbs () {
this.crumbs = [
{name: 'Replication'}
];
},
setCreateReplicationCrumbs () {
this.crumbs = [
{name: 'Replication', link: 'replication'},
{name: 'New Replication'}
];
},
createView: function (databaseName) {
const localSource = databaseName || '';
return <ReplicationController
routeLocalSource={localSource}
section={'new replication'}
/>;
},
createViewFromId: function (replicationId) {
return <ReplicationController
replicationId={replicationId}
section={'new replication'}
/>;
},
activityView: function () {
return <ReplicationController
section={"activity"}
/>;
},
replicateView: function () {
return <ReplicationController
section={"_replicate"}
/>;
}
});
export default {
RouteObjects: [ReplicationRouteObject]
};
|
src/components/event_page/event_details/participant.js | decaster3/hikester_redux | import React from 'react';
import FontAwesome from 'react-fontawesome';
export default class Participant extends React.Component {
constructor(props) {
super(props);
this.state = {
};
}
render() {
let display_style = this.props.show ? 'inline-block' : 'none';
return (
<a
className="ui image label"
style={{
display: display_style
}}>
<img src={this.props.photo} />
{this.props.name}
</a>
);
}
}
|
src/pages/eternal-archives/fiction/the-small-village-tavern/index.js | jumpalottahigh/blog.georgi-yanev.com | import React from 'react'
import { Link } from 'gatsby'
import { Helmet } from 'react-helmet'
import Layout from '../../../../components/structure/layout'
const TheSmallVillageTavernPage = () => (
<Layout>
<Helmet title="The small village tavern - Warcraft Fiction" />
<section>
<h1>The small village tavern</h1>
<div className="disclaimer-container">
<span className="year">~ year: 2003 | Georgi's age: 18</span>
<span className="disclaimer">
Unedited things the way they were in the late 90s and early 2000s
</span>
</div>
<div>
<pre>
Chapter 1 – The Very Beginning
<br />
<br />
The small village tavern, called ‘The Rune Stone’, was settled in a
small valley, between the great woods of the Silvermoon forest and the
Darrowmere lake. The poor light of an old lamp could not be enough to
lighten up the tavern’s main hall in this autumn night. The barkeeper
looked worried, for there weren’t far too many customers this night.
Only two main groups of people were symmetrically positioned in the
opposite corners of the pub. They were laughing and joking with one
another as the hours passed. Two friends, who looked like ordinary
peasants, represented one of the groups. They talked, like everyone
else did, about the recent day, passed in hard work.
<br />
In that same moment the door opened, waving the dry, passive air
changing it into night’s cool breeze. Everyone felt the refreshing
‘wind’ and looked at the old wooden door. A short old man went inside
and sat over the two peasants. They paid no attention to him, as he
ordered some beer. He kept drinking ale after ale, and kept listening
to the peasants. They, however, were so absorbed by their
conversation, that they even spoke of the old prophecies and myths and
at one point the old man even joined the conversation. Then the two
friends spoke of the ancient days and the elves. There were many, many
rumors that they spoke of. Some said that the elves still live in the
mountains of Quel’thalas, but no one saw them after the second and
last invasion of the Burning Legion. Some said that the elves joined
their old brothers – the Night Elves, and went to Kalimdor. Others
said that the elves were imprisoned in Northrend by the last band of
trolls and orcs. Yet, none knew the truth.
<br />
“This all in not true” the old man said deeply and confident in his
words.
<br />
“I can tell you the story of the High Elves.” the man said loudly.
Everybody in the tavern turned towards him.
<br />
“Leave that old man. He’s drunk” the other group of townsman looked
with sympathy at him, for they all knew that many of the old man and
women nowadays were crazed by the treacherous wars with the Burning
Legion, the Horde, and now the Undead. Many lost their families, but
when those stupid necromancers came and rose the dead … the situation
got even worse. No one liked his dead relative to walk undead and seed
chaos over his own kind. So it was very difficult for the elder people
to get accustomed to all those horrific events.
<br />
“Silence! I am the prophet, and no one will ever call me that way!”
the figure of the ‘old man’ stand up and rose as his eyes filled with
anger. <br />
“I failed once, yes, it is truth. But I think I did enough to pay my
mistakes” he sat and began his tale.
<br />
“Many centuries ago, about 10 000 years, the Dragons ruled Azeroth.
West of here there was an enormously huge land called Kalimdor. It
still exists nowadays, but the half of it has sunken into the Great
Sea. So in that same land awakened the race of the Night Elves. There
are no other elfish races different to the Night ones. The others
emerged later. I was one of the first to be born. Our race was
developing quickly and steadily for we all were immortal. There was no
death for us. We could only be killed by foe, never by the fate. No
matter our glorious development we began creating powerful magiks for
different tasks. Then the magic became part of our everyday life. We
used it for everything you could imagine – even to just pick an object
up from a distance. Foolish me, it was I who first intended to use the
elfish magiks for a more important things. Yet, I don’t quite remember
now, but I can tell that magiks were everywhere. I hope you get the
picture” the prophet interrupted his speech and bought everyone, who
listened to him, a drink. He used this short break to relax and calm
down a little.
<br />
“I invented magiks that enabled world travel. You see, truth is that
all worlds are connected to the world of the dead souls – the Twisting
Nether. By going into the Nether, and venturing deeper into the Great
Dark Beyond, you are able to visit almost any place in the universe. I
did so. I’ve been to Dreanor, too. A pity it has been destroyed,
indeed. It was very beautiful red world, full of ‘strange’ (for our
understandings) plants and animals. That is not the point of my tale,
though. It was then, when the Daemon Lord Sargeras detected our
powerful magic sources. So, the Burning Legion invaded. It took us
about 1000 years to fight for our land. Yet, the Dragons helped us and
probably thanks to them we finally defeated Sargeras and his army. We
pursued his army of fire stoned demons out of our world and far into
the universe. Of course that was a battle won, but the war was still
at hand and will always be. I understood later that those demons that
we pursued corrupted our Orcish brothers from Draenor. This is why the
war will never end. There will always be someone to corrupt the noble
people, making them a grave danger indeed ” by his last sentence, the
‘old man’ wide opened his eyes, showing their bright and dark side
alike.
<br />
“I’m beginning to have second thoughts about that old man. He could be
one of those crazed necromancers, do you think?” a farmer asked his
wife. She didn’t say a word, though, still staring at the ‘prophet’.
<br />
“So my word was about Sargeras. We entomb him west of here, not so far
from the shores of Sunken Kalimdor. No matter that ‘great’ success I
was banned from my homeland and send into exile. The small group of
the Night Elves that helped me design my invention, who have vowed not
to use magic ever again (like me) came along with me. We chose
Quel’thalas for it was the only free region except Northrend to
inhabit. As we traveled towards that destination we were told of the
awakening of the mortal races. Humans, dwarfs, gnomes, trolls and
many, many others were the first we heard about during our 6-month
journey”.
<br />
<br />
Chapter 2 – The Shores of Northrend
<br />
<br />
One day, probably 2 months after we last ‘saw’ the shores of Sunken
Kalimdor, Hyjal shouted from the top of the front mast. Everyone
trusted him, as I did for he was my very best friend, so we all looked
at the far northeast. Those were some white-colored shores. It was
strange, for we all had never seen such brightly colored land … or was
that land?
<br />
“It’s weird! Our priestess of the Moon has never told us of this land.
It is not shown on any map. But I guess our people need to rest a bit
from rowing all day and night for the last months. What do you think?”
Hyjal looked worried about what I was going to say, but his face kept
its usual cheerful looking mood.
<br />
“You decide whether we proceed, or stop for a day or two. It looks
like we’re the next of the history writers. We found a land that no
one knew it even existed, we may do other more important things in the
near future. Who knows?” I replied, smiling at my friend. I then left
him tell our people the glorious news and went to my room, for I knew
that the next day would be a difficult one. At least for me. I laid
down on my bed and thought about the upcoming great exploration of
that new land. Suddenly I remembered that we hadn’t chose its new name
yet. “I guess I’ll let Hyjal think of something. Hyjal. That name
again. My old friend was named after Kalimdor’s sacred mountain
summit. That was the place we had lived for hundreds of years after my
unsuccessful experiment, until they exiled me away from my very home.
Nonsense! It’s all my fault and I will suffer the consequences.
Tomorrow will be a great day.” With my last thought gone I fall
asleep.
<br />
As the sun rose I woke up and went outside. It was just another
beautiful sunny day and we all gathered around Hyjal to hear what
should we do.
<br />
“We cannot allow a full three-days rest in this land for it is both
unknown and we have to proceed with our journey. We can, however,
spend a day or mostly two, while our druids write down maps of this
island. It is not as much time as many of us would want, but I dare to
say it’s enough. As a matter of fact we’ve got an important problem to
solve ahead. We’ve got to find a place to live in.” Hyjal took a deep
breath and continued his speech.
<br />
“I know that many of you ask yourselves if this isn’t just the right
place to inhabit. Well, it could be but we don’t know a thing about it
yet. Now let’s get in the boats and raw to the shore. You got about 12
hours to rest, walk and do whatever you want. After that we’ll meet at
the shore again to see what the druids can tell us about that land.
Hurry up!” the crowd around Hyjal was growing larger as his speech
progressed and now there were about two times more people than the
time he started. Everyone looked happy and cheerful as if an elf in
exile could be any joyful. “You truly are a confident person, my
friend.” I thought about Hyjal and went forward to greet him.
<br />
“Did you sleep well?” my friend asked.
<br />
“You heard about the schedule, didn’t you?” he didn’t even waited to
answer his first question and asked again. I saw impatience in Hyjal’s
eyes. My friend looked eager to explore this land with every passing
moment, so I decided not to waste his time now.
<br />
“So we got only a day? Well, I hope the druids don’t waste their time.
See you later.” I turned around and went back to my room to take the
rest of my equipment. “This cannot last any long.” I thought about our
exile. “We have to find a place to live like normal elves. I don’t
know where are we supposed to go. I will ask Hyjal later. But what if
this is our new home? Or what if we go live with those newborn. With
the Humans. I’d better be going or else those questions will be the
very end of me. To every problem there is solution, every question has
his own answer and every quest could be completed as our ancients say.
Calm now!” thinking over all those topics I took my bag, some elfish
food and ran away. I was the last one at the boats, so I quickly
jumped towards one of the full ones and found a small place to sit
down. I thought again about those new races. Our druid scouts report
that there are not only new races, but the dragons had disappeared
also. Strange.
<br />
“So you made it anyway!” Hyjal put his arm on my shoulder and smiled
at me.
<br />
“I guess I did!” words are useless when two old friends understand
each other.
<br />
“RAW” I heard from behind and prepared for the splendid view that we
will probably encounter.
<br />
<br />
Chapter 3 – The Foundation of Northrend
<br />
<br />
When we finally landed on the shores of Northrend I felt weird. I was
feeling that way for the very first time. The sun was high in the sky,
but the air was still cold. The land was colored in white and was also
cold. Nevertheless we were all happy, for we knew that we were going
to discover a new land. A land unknown even to the old prophets like
my self. As I thought about all those odd things we had saw this far,
Hyjal lead us deeper inside a white forest.
<br />
“Even the trees are … different!” I could not hold my thought. Hyjal
heard me.
<br />
“Strange are these lands and we still have no idea of what is waiting
for us deeper into the tree labyrinth.” Hyjal sounded strange, but I
even did not notice that in that great moment. The captain of the ship
shouted in the same time.
<br />
“Hear me brothers! We shall settle a camp in this valley. You can use
the time until the next sunrise as you wish. The Aran Food will be
served after about 5 hours. Don’t be late or the spirits of the
Nephalem will be angry.” Our most ancient ones – the Spirits of the
Nephalem. They were named after the other great mountain summit –
Nephalem. Tradition is that the Aran Food, or also Noble Food, should
be served every three days at the sunset. That Food is represented
mostly by Kalimdor bread by plants from the Hyjal foothills and fresh
ice-cold water from the Nephalem summit’s highest lake. That same lake
was where the Nephalem brothers saved our capital forest town from
lord Auchinduin’s attacks. Lord Auchinduin was one of the Legion’s
leaders. It’s a long and admirable story, but its essence is that
unity is the key to victory. “Even now, 8000 years later, I feel the
same proud way.” the prophet looked sadly towards the tavern floor and
unexpectedly he continued his story. “Anyway, in that moment I thought
not about the ancient ones, but about the camp. The place looked nice
– on the east side we had a nice white forest, while on the opposite
we had a deep valley. Southward was the place we came from – our ship
and the Great Sea’s bay. Finally northward was yet unknown place that
looked like a swamp. The camp itself was nothing but a place full of
old centaur-fur tents. It was difficult to resist the chilling cold so
many of us stayed in the camp as guards, others like short-range
scouts and third just hid in their own tents and slept until the time
for the Aran Food came. I thought that there will be plenty of time to
sleep in the near future, when we finally establish a forest town or
at least a small valley village, so I decided to go and study this
strange land. There were pretty few warriors that chose the adventure
than the warm, cozy tent. I saw those adventurers lead by the captain
himself to depart in one group to the east. To the White Forest, as we
called it later, for it was the first white one we saw. Elfish nature!
They always choose the forests first, than any other place to explore.
You should know, that even the sacred forests of the Hyjal foothills
could be more dangerous even than the Swamps of Sorrow where I firstly
opened the…” the prophet suddenly ceased speaking. His figure
contoured in the dark tavern hall. As a few moments passed he
proceeded talking about those very ancient times. “I asked Hyjal if he
could come with me. I chose for my destination the ‘swamps’, because
there probably would be nothing to explore in the valley. The next
part is not so important about this tale. Hyjal and I went deep into
the swamps, but saw no enemy. Everything was calm as if this was Hyjal
summit itself. We had to be very cautious about our every little step
or move for the swamp was not to be underestimated. The only thing we
saw on that ‘journey’ was a deer that sunk into the swamp.
Unfortunately we were not able to help it. Hyjal tried but it appeared
that this place drains magical energies as good and fast as the
Burning Legion’s lord does. When we saw this tragic case of death I
suggested that we go back to the camp. Hyjal instantly agreed and thus
we took the way back. It was about 15 minutes before the Aran Food to
be served that we returned. The ritual was as normal as ever and after
about 2 hours of conjuring and eating our druids told us about this
land. Northrend was a small island covered with white stuff all over.
They told us about the different trees and bushes and so on. After the
maps had been written down our dryad scouts finally returned. Sad news
was what they were bearing. Although I had no doubt that this land was
inappropriate for the Night Elves to live, the dryads confirmed my
thoughts, too. Sad, for it doomed us to look for another free land to
inhabit. The next morning we calmly and melancholically walked towards
the boats and rowed to the ship. That same afternoon we set sail to
the east… Again.” the prophet stopped to take a breath. If someone
have entered the tavern by that very moment he would see how a bunch
of peasants have gathered around an old man, listening to him as
careful as possible not to miss even a word from his speech. And so
the prophet continued his story…
<br />
<br />
Chapter 4 – The Vow
<br />
<br />
“I cannot clearly tell what happened next on that journey.” The old
man began. “What I can tell, however, is that we saw no land for many
long days and nights. Just as we supposed there were only small
islands, which were impossible to inhabit even by such a slight group
of elves like us. Anyway, I used that time to let alone and think over
all my thoughts. As I did so, Hyjal and the captain commanded the
others. Hyjal was personally told by me to send sacred owls and Druids
of the Talon to explore the sea before us. Those druids were the ones
that were capable of transformation to crow form and were really fast
scouts. I finally decided what should I be able to do for my people.
One night as I was reading the ancient tomes of nature at the small
library, I met Kul’Dare. He was one of those Druids of the Talon that
were already sent to scout the sea ahead.
<br />
“Did you encounter anything?” I asked.
<br />
“No. Nothing in a very long distance, according to our maps.” he
replied coldly.
<br />
“I have decided!” my voice trembled as I began “We will venture deeper
in that continent here.” I pointed at the eastern side of the map in
the book I was currently holding. “I know that it’s dangerous but …
what could we do? There probably are no other free pieces of land in
the whole world.” Kul’Dare was staring at my eyes as if he could look
through them into my very mind.
<br />
“Did you tell this to Elune?” Elune was the captain of the ship. I was
angered.
<br />
“Elune is no one! He commands only during our sea journey! I am the
leader of this exile.” Kul’Dare did not move a bit and stood calmly as
if nothing happened.
<br />
“Calm down ancient one!” he spoke to me “I meant no harm. Truly, Elune
should only be told of this plan. As for me, I will follow you my old
friend.”
<br />
“That’s really … kind of you. I swear now to lead our race of Night
Elves in exile to a better life without even a small bit of magic! Go
now, and announce my words to the rest of our brethren.” Kul’Dare left
the room and I was let alone only with my thoughts in the library.
Strange! I felt confident and untroubled by anything. I guessed what
our destiny will be, but the vow that I made that day, I fulfilled.”
with his last words, the prophet examined closely every one of his
companions in the tavern. He looked deep into their hearts and seeing
that they are just simple, ordinary people who mean no harm to anyone,
he proceeded his story.
<br />
<br />
Chapter 5 – The Green Skins
<br />
<br />
“Yet, that day I didn’t know that the lands we were going to visit
belong to the region of Quel’thalas” the prophet looked again at the
people around him and after a few seconds he continued. “We, however,
were not so close to Quel’thalas. Not yet. The next day after my
conversation with Kul’Dare, I revealed my plan and vow to the rest of
the crew. Elune seemed to be in agreement with the plan. As for
Kul’Dare and Hyjal, well, I was never disappointed by them and just as
I expected they stood behind me once again. Hyjal was a man of honor.
All he wanted was a peaceful life. He was not of those people that ask
plenty of questions or talk all the time. I liked him. Kul’Dare, on
the other hand, was not so quiet person. Although he too was a man of
action, he was a bit more talkative person. So, after everyone knew
what we should do, I send the Druids of the Talon once again to scout
ahead. For two long days there were no news from the scouts. I began
to torture myself for I was who send them ahead. At the sunrise of the
3rd day Kul’Dare finally returned. I was stoned, for there was no one
else with him. I send five scouts, for Elune!
<br />
“Where are the others” were the only words that slipped away from my
mouth.
<br />
“Let’s go inside” said Kul’Dare and Hyjal, Elune and I went to the
library.
<br />
“So” asked Elune. Kul’Dare began slowly his report.
<br />
“We flew about 14 hours to the east. Suddenly we saw a small island
and decided to land and take a look. We couldn’t, though! As we
approached the ground strange creatures began to shoot at us with
gigantic arrows. That’s how the others died. Only Lasien survived but
he too was wounded and after about 4 hours flying back he died. The
only thing that saved me from their poisonous arrows was my speed.
Unluckily the others were not as swift as I was” I couldn’t move my
lips. I had so many, many questions that needed answers. Elune was the
first to ask one of those questions.
<br />
“What were those creatures like” he asked shortly.
<br />
“Well, we saw them not but I gathered the impression that they were
green skinned beings, as tall as we are, and very skilled fighters.
The very strange thing was that they had no bows! They just threw away
the ‘arrows’ with their own hands” Kul’Dare looked worried.
Unnaturally Hyjal took his place in the conversation.
<br />
“May I suggest something master” he asked me.
<br />
“Sure, go ahead” I answered.
<br />
“If it is possible that we send a host of our people to the dwarven
capital of Ironforge in the heart of the Red Ridge Mountains, to ask
their elders what were those creatures. I suggest that we split in two
groups. One of the groups will proceed to the lands of the northeast,
while the other will go a bit southwards to visit the dwarves and
gather some knowledge about the green-skins and the whole continent
and its creatures as a whole. We will afterwards meet at our
destination. Whatever our destination is” I hadn’t seen Hyjal in this
form of speaking for years!
<br />
“This is a sound plan Hyjal” I was still amazed when I began my
answer.
<br />
“I don’t know about anyone else but as for me Hyjal’s plan is perfect.
As a matter of fact we will need a forest to inhabit, right? But even
our ancients don’t know a thing about this continent we are about to
reach and hopefully inhabit” I stopped.
<br />
“I have another suggestion” Elune suddenly said. “What if we really do
so. I mean send scouts to the dwarven capital to learn about their
culture and the lands, rivers, woods and lakes of the continent.
Sounds like a plan! What I also suggest, though, is that the other
group land on the island that lies just ahead, just to see if those
green-skins are so invincible. Afterwards that group will catch up the
others and we all will know where to live and what creatures inhabit
this land” Elune stopped as suddenly as he started. “I am very proud
of you guys when you talk like that” I revealed my feelings. “You told
us a few nice plans and I guess this is what we will do. Elune, go and
retell the crew your plan. Hyjal you are free, go and rest I’ll talk
with you tomorrow and Kul’Dare – I want to ask you a bit more about
the green-skins” I finished my speech excited. As I let out my last
word everyone disappeared to handle his own task. I wondered for a
moment whether we would finally find a place to live.
<br />
“You were saying” Kul’Dare asked me.
<br />
“Oh, yeah” I chased away my thoughts and turned towards Kul’Dare.
</pre>
</div>
<Link to="/">Go back to the homepage</Link>
</section>
</Layout>
)
export default TheSmallVillageTavernPage
|
packages/icons/src/md/communication/StayCurrentPortrait.js | suitejs/suitejs | import React from 'react';
import IconBase from '@suitejs/icon-base';
function MdStayCurrentPortrait(props) {
return (
<IconBase viewBox="0 0 48 48" {...props}>
<path d="M33.98 2.02c2.21 0 4 1.77 4 3.98v36c0 2.21-1.79 4-4 4h-20C11.77 46 10 44.21 10 42V6c0-2.21 1.77-4 3.98-4l20 .02zm0 35.98V10h-20v28h20z" />
</IconBase>
);
}
export default MdStayCurrentPortrait;
|
test/integration/static/pages/counter.js | callumlocke/next.js | import React from 'react'
import Link from 'next/link'
let counter = 0
export default class Counter extends React.Component {
increaseCounter () {
counter++
this.forceUpdate()
}
render () {
return (
<div id='counter-page'>
<div>
<Link href='/'>
<a id='go-back'>Go Back</a>
</Link>
</div>
<p>Counter: {counter}</p>
<button
id='counter-increase'
onClick={() => this.increaseCounter()}
>
Increase
</button>
</div>
)
}
}
|
client-src/components/pager/PagerButtonsThreePane.js | minimus/final-task | import React from 'react'
import propTypes from 'prop-types'
import PagerButton from './PagerButton'
export default function PagerButtonsThreePane({ base, category, page, pages }) {
const pagesArrayFirst = [1, 2, 3]
const pagesArrayMiddle = [page - 1, page, page + 1]
const pagesArrayLast = [pages - 2, pages - 1, pages]
return (
<span id="pager-buttons-pane">
{pagesArrayFirst.map(i =>
(<PagerButton
base={base}
category={category}
page={i}
key={i}
/>))}
<span className="pager-group-divider">...</span>
{pagesArrayMiddle.map(i =>
(<PagerButton
base={base}
category={category}
page={i}
key={i}
/>))}
<span className="pager-group-divider">...</span>
{pagesArrayLast.map(i =>
(<PagerButton
base={base}
category={category}
page={i}
key={i}
/>))}
</span>
)
}
PagerButtonsThreePane.propTypes = {
base: propTypes.string.isRequired,
category: propTypes.string.isRequired,
page: propTypes.number.isRequired,
pages: propTypes.number.isRequired,
}
|
spec/javascripts/jsx/gradebook/default_gradebook/GradebookGrid/editors/TotalGradeOverrideCellEditor/ReadOnlyCellSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2018 - 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 ReactDOM from 'react-dom'
import GradeOverrideEntry from 'jsx/grading/GradeEntry/GradeOverrideEntry'
import ReadOnlyCell from 'jsx/gradebook/default_gradebook/GradebookGrid/editors/TotalGradeOverrideCellEditor/ReadOnlyCell'
QUnit.module('GradebookGrid TotalGradeOverrideCellEditor ReadOnlyCell', suiteHooks => {
let $container
let component
let props
suiteHooks.beforeEach(() => {
$container = document.body.appendChild(document.createElement('div'))
const gradeEntry = new GradeOverrideEntry()
props = {
gradeEntry,
gradeInfo: gradeEntry.parseValue('91%'),
gradeIsUpdating: false,
onGradeUpdate: sinon.stub(),
pendingGradeInfo: null
}
})
suiteHooks.afterEach(() => {
ReactDOM.unmountComponentAtNode($container)
$container.remove()
})
function mountComponent() {
component = ReactDOM.render(<ReadOnlyCell {...props} />, $container)
}
function getGrade() {
return $container.querySelector('.Grid__GradeCell__Content').textContent
}
QUnit.module('#render()', () => {
test('displays the given grade info in the input', () => {
mountComponent()
equal(getGrade(), '91%')
})
test('displays the given pending grade info in the input', () => {
props.pendingGradeInfo = props.gradeEntry.parseValue('92%')
mountComponent()
equal(getGrade(), '92%')
})
})
QUnit.module('#applyValue()', () => {
test('has no effect', () => {
mountComponent()
try {
component.applyValue()
ok('method does not cause an exception')
} catch (e) {
notOk(e, 'method must not cause an exception')
}
})
})
QUnit.module('#focus()', () => {
test('does not change focus', () => {
const previousActiveElement = document.activeElement
mountComponent()
component.focus()
strictEqual(document.activeElement, previousActiveElement)
})
})
QUnit.module('#handleKeyDown()', () => {
test('does not skip SlickGrid default behavior', () => {
mountComponent()
const event = new Event('keydown')
event.which = 9 // tab
const continueHandling = component.handleKeyDown(event)
equal(typeof continueHandling, 'undefined')
})
})
QUnit.module('#isValueChanged()', () => {
test('returns false', () => {
mountComponent()
strictEqual(component.isValueChanged(), false)
})
})
})
|
example/src/screens/types/Drawer.js | MattDavies/react-native-navigation | import React from 'react';
import { StyleSheet, View, Text } from 'react-native';
class MyClass extends React.Component {
render() {
return (
<View style={styles.container}>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
width: 300,
alignItems: 'center',
justifyContent: 'center',
backgroundColor: '#ffffff',
},
});
export default MyClass;
|
hub-ui/src/app/routes.js | lchase/hub | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import { routerActions } from 'react-router-redux'
import App from './App';
import Content from '../components/layout/Content';
import PublicPage from '../components/layout/PublicPage';
import DashboardContainer from '../dashboard/components/DashboardContainer';
import Other from '../components/Other';
import Login from '../auth/components/Login';
import Register from '../auth/components/Register';
import { UserAuthWrapper } from 'redux-auth-wrapper'
import Profile from '../components/profile/Profile';
import NotFoundPage from '../components/NotFoundPage'
const UserIsAuthenticated = UserAuthWrapper({
authSelector: state => state.auth.user, // how to get the user state
redirectAction: routerActions.replace, // the redux action to dispatch for redirect
wrapperDisplayName: 'UserIsAuthenticated' // a nice name for this auth check
});
export default (
<Route path="/" component={App}>
<Route component={UserIsAuthenticated(Content)}>
<IndexRoute component={DashboardContainer} />
<Route path="profile" component={Profile} />
<Route path="other" component={Other} />
</Route>
<Route component={PublicPage}>
<Route path="login" component={Login} />
</Route>
<Route path="register" component={Register} />
<Route path="*" component={NotFoundPage} />
</Route>
); |
app/js/components/HomeButton.js | blockstack/blockstack-portal | import React from 'react'
import { Link } from 'react-router'
const HomeButton = () => (
<Link to="/">
<div className="btn-home-button">
‹ Home
</div>
</Link>
)
export default HomeButton
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.