path
stringlengths 5
195
| repo_name
stringlengths 5
79
| content
stringlengths 25
1.01M
|
---|---|---|
src/components/WorkSummary.js | computer-lab/salon94design.com | import React from 'react'
import PropTypes from 'prop-types'
import Link from 'gatsby-link'
import styled from 'emotion/react'
import cx from 'classnames'
import {
monoFontFamily,
sansfont,
childLink,
breakpoint1,
breakpoint2,
breakpoint3,
baseUl,
} from '../layouts/emotion-base'
import { designerLink, workTagLink, projectLink, capitalize } from '../util'
const Container = styled.div`
composes: ${sansfont};
font-weight: 300;
max-width: 400px;
&.detailed {
margin-bottom: 20px;
max-width: none;
}
`
const DetailSection = styled.ul`
composes: ${baseUl};
margin-bottom: 20px;
@media (${breakpoint1}) {
margin-bottom: 16px;
}
@media (${breakpoint3}) {
margin-top: 8px;
}
`
const SummaryItem = styled.li`
composes: ${childLink};
margin: 0 0 6px 0;
line-height: 1.25;
font-size: 18px;
&:last-child {
margin-bottom: 0;
}
&.designer {
font-weight: 500;
}
&.project,
&.tag {
font-size: 18px;
font-weight: 500;
}
@media (${breakpoint1}) {
font-size: 16px;
}
`
const WorkSummary = ({ designer, work, detailed, projects }) => (
<Container className={cx({ detailed })}>
<DetailSection>
{designer && (
<SummaryItem className="designer">
<Link style={{'fontWeight': 500}} to={designerLink(designer.slug)}>{designer.name}</Link>
</SummaryItem>
)}
<SummaryItem style={{'fontStyle': 'italic'}}>{work.title}</SummaryItem>
<SummaryItem>{work.when}</SummaryItem>
<SummaryItem>{work.caption}</SummaryItem>
<SummaryItem>{work.medium}</SummaryItem>
<SummaryItem>{work.dimensions}</SummaryItem>
<SummaryItem>{work.edition}</SummaryItem>
<SummaryItem>{work.price}</SummaryItem>
</DetailSection>
<DetailSection>
{projects &&
projects.length > 0 &&
projects.filter(p => !!p).map(project => (
<SummaryItem key={project.slug} className="project">
<Link to={projectLink(project)}>{project.title}</Link>
</SummaryItem>
))}
{detailed &&
work.tags &&
work.tags.map(tag => (
<SummaryItem key={tag} className="tag">
<Link to={workTagLink(tag)}>{capitalize(tag)}</Link>
</SummaryItem>
))}
</DetailSection>
</Container>
)
WorkSummary.propTypes = {
work: PropTypes.object.isRequired,
designer: PropTypes.object,
projects: PropTypes.array,
detailed: PropTypes.bool,
}
export default WorkSummary
|
client/src/components/help/Container.js | DjLeChuck/recalbox-manager | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { translate } from 'react-i18next';
import reactStringReplace from 'react-string-replace';
import { recalboxSupport } from '../../api';
import Help from './Help';
class HelpContainer extends Component {
static propTypes = {
t: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = {
stickyContent: null,
};
}
componentDidMount() {
window.location.hash = window.decodeURIComponent(window.location.hash);
if ('#launch-support' === window.location.hash) {
this.doRecalboxSupport();
}
}
doRecalboxSupport = () => {
this.setState({ callingSupport: true });
recalboxSupport().then(
result => (
this.setState({
callingSupport: false,
downloadUrl: result.url,
})
),
err => (
this.setState({
callingSupport: false,
stickyContent: err.message,
})
)
);
};
render() {
const { t } = this.props;
const supportSentence = reactStringReplace(t("Si on vous demande d'envoyer le résultat du script %s, vous pouvez le faire automatiquement ci-dessous."), '%s', (match, i) => (
<code key={i}>recalbox-support.sh</code>
));
return (
<Help {...this.state} links={[{
label: t('Le forum :'),
link: t("https://forum.recalbox.com/"),
}, {
label: t('Le chan IRC :'),
link: t("https://kiwiirc.com/client/irc.freenode.net/#recalbox"),
}, {
label: t('Le wiki :'),
link: t("https://github.com/recalbox/recalbox-os/wiki/Home-(FR)"),
}]}
callSupport={this.doRecalboxSupport} supportSentence={supportSentence} />
);
}
}
export default translate()(HelpContainer);
|
src/client/react/user/views/Instructions/InstructionCollapse.js | bwyap/ptc-amazing-g-race | import React from 'react';
import autobind from 'core-decorators/es/autobind';
import { Button, Intent, Collapse } from '@blueprintjs/core';
import MarkdownRenderer from '../../../../../../lib/react/components/MarkdownRenderer';
import '../../scss/components/_instruction-panel.scss';
@autobind
class InstructionCollapse extends React.Component {
state = {
isOpen: false,
}
toggleOpen() {
this.setState((prevState) => {
return { isOpen: !prevState.isOpen }
});
}
render() {
const { title, content } = this.props.article;
return (
<div className='instruction-collapse'>
<Button className='pt-fill' text={title} intent={Intent.PRIMARY}
iconName={this.state.isOpen?'chevron-down':'chevron-right'} onClick={this.toggleOpen}/>
<Collapse isOpen={this.state.isOpen}>
<div className='instruction-panel'>
<MarkdownRenderer className='markdown-content' src={content}/>
</div>
</Collapse>
</div>
);
}
}
export default InstructionCollapse;
|
web/static/js/layouts/main.js | wwselleck/Rekrewtor | import React from 'react'
import { Link } from 'react-router'
export default class MainLayout extends React.Component {
render () {
return (
<div>
{this.props.children}
</div>
)
}
}
|
src/components/blocks/index.js | impact-initiatives/reach-jor-zaatari-webmap | import React from 'react';
import styles from '../../styles/index.js';
import Header from '../common/header/index.js';
import Footer from '../common/footer/index.js';
import SidebarHome from '../common/home/index.js';
import MapboxGL from '../common/mapbox-gl/index.js';
import SidebarLayers from './sidebar-layers/index.js';
import SidebarInfo from './sidebar-info/index.js';
import * as language from '../../constants/languages.js';
import img from '../../constants/images.js';
import messages from '../../translations/blocks.js';
export default ({ state }) => (
<div className={`${styles.flex.verticalNormal} ${styles.inline.fontDefault}`}
dir={state.lang === language.AR ? 'rtl' : 'ltr'}>
<Header messages={messages}
state={state} />
<div className={styles.menu.content}>
<SidebarHome state={state} />
<SidebarInfo state={state} />
<SidebarLayers state={state} />
<MapboxGL />
</div>
<Footer donorLogo={img.LOGO_UNHCR} />
</div>
);
|
frontend-app/welcome-app/main/welcome-main.js | easybird/easyblog | import React from 'react';
import DraftEditor from '../../article/editor/draft-editor.js';
import Article from '../../article/article.js';
import ArticleOverview from '../../article/article-overview.js';
import ArticleList from '../../article/api/article-list/article-list.js';
import ArticlePage from '../../article/api/article-page/article-page.js';
import { getBlockStyle, styleMap, getMediaBlockObject, articleStyle} from '../../article/constants/styles.js';
import { convertToRawDraftContentState } from '../../article/helpers/convert-editor-state.js';
class WelcomeMain extends React.Component {
constructor(props) {
super(props);
this.state = {
rawDraft: props.initialRawDraft
};
this._onSaveDraft = this._onSaveDraft.bind(this);
}
_onSaveDraft(editorState) {
const rawDraft = convertToRawDraftContentState(editorState);
console.log("save raw draft: " + JSON.stringify(rawDraft));
this.setState({
rawDraft: rawDraft
})
}
render() {
const {rawDraft} = this.state;
const {initialRawDraft} = this.props;
const blockStyleFn = getBlockStyle;
const blockRendererFn = getMediaBlockObject;
const customStyleMap = styleMap;
const customArticleStyle = articleStyle;
const onSaveDraft = this._onSaveDraft;
return (
<main>
<div className="section" />
<div className= "container">
<div className= "row">
<div className= "col s12">
<DraftEditor
onSaveDraft={ onSaveDraft }
blockStyleFn={ blockStyleFn}
blockRendererFn={blockRendererFn}
customStyleMap= {customStyleMap}
articleStyle= {customArticleStyle}
initialRawDraft={initialRawDraft}
/>
</div>
<div className= "col s12 l6" style={articleStyle}>
<ArticleOverview
blockStyleFn={blockStyleFn}
blockRendererFn={blockRendererFn}
customStyleMap={customStyleMap}
rawDraft={rawDraft}
title="Small preview:"
articleUrl="http://easybird.be/blog/future-react"
/>
</div>
<div className= "col s12 l6" style={articleStyle}>
<Article
blockStyleFn={blockStyleFn}
blockRendererFn={blockRendererFn}
customStyleMap={customStyleMap}
rawDraft={rawDraft}
title="Rendered result:"
articleUrl="http://easybird.be/blog/future-react"
/>
</div>
</div>
</div>
</main>
)
}
}
WelcomeMain.propTypes = {
initialRawDraft: React.PropTypes.object
};
export default WelcomeMain; |
view/perspective/app.js | salesforce/refocus | /**
* Copyright (c) 2016, salesforce.com, inc.
* All rights reserved.
* Licensed under the BSD 3-Clause license.
* For full license text, see LICENSE.txt file in the repo root or
* https://opensource.org/licenses/BSD-3-Clause
*/
/**
* view/perspective/app.js
*
* When this page is loaded, we call "getPerspectiveNames" to load all the
* perspective names to populate the dropdown.
* If there are no perspectives, we just render the perspective overlay over an
* empty page.
* If there are perspectives, we call "whichPerspective" to figure out which
* perspective to load.
* If it's not in the URL path, either use the DEFAULT_PERSPECTIVE from global
* config OR the first perspective from the list of perspective names
* (alphabetical order), and redirect to the URL using *that* perspective name.
* Once we can identify the perspective in the URL path, we call
* "getPerspective" to load the specified perspective. When we get the
* perspective back from the server, we perform all of this async work in
* parallel:
* (1) call "setupSocketIOClient" to initialize the socket.io client
* (2) call "getHierarchy" to request the hierarchy
* (3) call "getLensPromise" to request the lens library
* (4) call "loadPerspective" to start rendering the perspective-picker
* component
* (5) call "loadExtraStuffForCreatePerspective" to start loading all the extra
* data we'll need for the "CreatePerspective" component
*
* If config var "realtimeEventThrottleMilliseconds" > 0, we start a timer to
* flush the realtime event queue on that defined interval.
*
* Whenever we get the response back with the lens, we dispatch the lens.load
* event to the lens.
*
* Whenever we get the response back with the hierarchy, we dispatch the
* lens.hierarchyLoad event to the lens. (If we happen to get the hierarchy
* back *before* the lens, hold onto it, wait for the lens, *then* dispatch the
* lens.hierarchyLoad event *after* the lens.load event.)
*
* Whenever we get all the extra data we need for "CreatePerspective", we
* re-render the perspective-picker component.
*/
import request from 'superagent';
import React from 'react';
import ReactDOM from 'react-dom';
import PerspectiveController from './PerspectiveController';
import { getValuesObject } from './utils';
const u = require('../utils');
const pu = require('./utils');
const constants = require('../constants');
const eventsQueue = require('./eventsQueue');
const emitUtils = require('../../realtime/emitUtils');
const pcValues = {};
const ZERO = 0;
const ONE = 1;
const DEBUG_REALTIME = window.location.href.split(/[&\?]/)
.includes('debug=REALTIME');
const REQ_HEADERS = {
'X-Requested-With': 'XMLHttpRequest',
Expires: '-1',
'Cache-Control': 'no-cache,no-store,must-revalidate,max-age=-1,private',
};
const DEFAULT_ERROR_MESSAGE = 'An unexpected error occurred.';
const LENS_LIBRARY_REX = /(?:\.([^.]+))?$/;
// Some API endpoints...
const GET_DEFAULT_PERSPECTIVE = '/v1/globalconfig/DEFAULT_PERSPECTIVE';
const GET_PERSPECTIVE_NAMES = '/v1/perspectives?fields=name';
// Some divs on the perspective page...
const LENS_DIV = document.getElementById('lens');
const ERROR_INFO_DIV = document.getElementById('errorInfo');
const PERSPECTIVE_CONTAINER =
document.getElementById('refocus_perspective_dropdown_container');
const SPINNER_ID = 'lens_loading_spinner';
let _realtimeApplication;
let _realtimeEventThrottleMilliseconds;
let _userSession;
let _io;
let lastUpdateTime;
let timeoutCheckInterval;
let lensEventApiVersion = 1;
const trackedAspects = {};
/**
* Add error message to the errorInfo div in the page.
* Remove the spinner.
*
* @param {Object} err - The error object
*/
function handleError(err) {
let msg = DEFAULT_ERROR_MESSAGE;
if (err.response.body.errors[ZERO].description) {
msg = err.response.body.errors[ZERO].description;
}
ERROR_INFO_DIV.innerHTML = msg;
u.removeSpinner(SPINNER_ID);
} // handleError
/**
* Handle event data, push the event data to the event queue.
*
* @param {String} eventData - Data recieved with event
* @param {String} eventTypeName - Event type
* @param {Function} trackEndToEndTime - Callback to send event receipt time back to server
*/
function handleEvent(eventData, eventTypeName, trackEndToEndTime) {
// track event receipt
const now = Date.now();
trackEndToEndTime && trackEndToEndTime(now);
lastUpdateTime = now;
// parse event data
const obj = JSON.parse(eventData)[eventTypeName];
// intercept events to support v1 lenses
if (lensEventApiVersion < 2) {
interceptV1Event(eventTypeName, obj);
}
// log event data
if (DEBUG_REALTIME) {
console.log({ // eslint-disable-line no-console
handleEventTimestamp: new Date(),
eventData: obj,
});
}
// dispatch event to lens
eventsQueue.enqueueEvent(eventTypeName, obj);
if (_realtimeEventThrottleMilliseconds === ZERO) {
eventsQueue.createAndDispatchLensEvent(eventsQueue.queue, LENS_DIV);
eventsQueue.queue.length = ZERO;
}
} // handleEvent
/**
* Intercept events to support v1 lenses.
*
* @param {String} eventTypeName - Event type
* @param {Object} eventData - object that will be sent to the lens
*/
function interceptV1Event(eventTypeName, eventData) {
if (eventTypeName === eventsQueue.eventType.INTRNL_SMPL_ADD) {
eventData.aspect = getTrackedAspectForSample(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_SMPL_DEL) {
eventData.aspect = getTrackedAspectForSample(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_SMPL_UPD) {
eventData.new.aspect = getTrackedAspectForSample(eventData.new);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_ASP_ADD) {
trackAspect(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_ASP_DEL) {
untrackAspect(eventData);
} else if (eventTypeName === eventsQueue.eventType.INTRNL_ASP_UPD) {
trackAspect(eventData.new);
}
}
/**
* Get the tracked aspect for the given sample
* @param {Object} sample - sample object
*/
function getTrackedAspectForSample(sample) {
const [absPath, aspName] = sample.name.split('|');
return trackedAspects[aspName.toLowerCase()];
}
/**
* Get the tracked aspect by name
* @param {String} aspName - aspect name
*/
function getTrackedAspect(aspName) {
return trackedAspects[aspName.toLowerCase()];
}
/**
* Add the aspect to the tracking map.
* @param {Object} aspect - aspect object
*/
function trackAspect(aspect) {
trackedAspects[aspect.name.toLowerCase()] = aspect;
}
/**
* Track all aspects
* @param {Array} aspects - array of aspects
*/
function trackAspects(aspects) {
aspects.forEach(trackAspect);
}
/**
* Remove the aspect from the tracking map.
* @param {Object} aspect - aspect object
*/
function untrackAspect(aspect) {
delete trackedAspects[aspect.name.toLowerCase()];
}
/**
* Setup the socket.io client to listen to a namespace, where the namespace is
* named for the root subject of the perspective.
*
* @param {Object} persBody - Perspective object
*/
function setupSocketIOClient(persBody) {
if (!persBody) {
throw new Error('Cannot set up socket IO client without a perspective');
}
/*
* Add the perspective name as a query param so that it's available server-
* side on connect.
*/
let socket;
if (useNewNamespaceFormat) {
const options = {
query: {
p: persBody.name,
id: u.getNamespaceString('/', persBody),
},
...constants.socketOptions,
};
const namespace = _realtimeApplication.endsWith('/') ? 'perspectives' : '/perspectives';
socket = _io.connect(`${_realtimeApplication}${namespace}`, options)
.on('connect', function() {
this.emit('auth', _userSession);
})
.on('auth error', (err) =>
console.error('Socket auth error:', err)
);
} else {
const namespace = u.getNamespaceString(_realtimeApplication, persBody) +
`?p=${persBody.name}&t=${_userSession}`;
socket = _io.connect(namespace, constants.socketOptions);
}
socket.on('connect', () => {
Object.values(eventsQueue.eventType).forEach((eventType) =>
socket.on(eventType, (data, cb) => handleEvent(data, eventType, cb))
);
/*
* TODO once we build new perspective page, we should have a way to tell
* the user that they have been disconnected from the real-time event
* stream. In the meantime, just log it in the browser.
*/
socket.on('disconnect', (msg) => {
console.log('Disconnected from real-time event stream.');
});
});
} // setupSocketIOClient
/**
* Create style tag for lens css file.
* @param {Object} library From the the lens api
* @param {String} filename name of file in lens library
*/
function injectStyleTag(library, filename) {
const style = document.createElement('style');
style.type = 'text/css';
const t = document.createTextNode(library[filename]);
style.appendChild(t);
const head = document.head ||
document.getElementsByTagName('head')[ZERO];
if (style.styleSheet) {
style.styleSheet.cssText = library[filename];
} else {
style.appendChild(document.createTextNode(library[filename]));
}
head.appendChild(style);
} // injectStyleTag
/**
* Create DOM elements for each of the files in the lens library.
*
* @param {Object} lib - Library of the response from lens api call
*/
function handleLibraryFiles(lib) {
const lensScript = document.createElement('script');
for (const filename in lib) {
const ext = (LENS_LIBRARY_REX.exec(filename)[ONE] || '').toLowerCase();
if (filename === 'lens.js') {
lensScript.appendChild(document.createTextNode(lib[filename]));
} else if (ext === 'css') {
injectStyleTag(lib, filename);
} else if (ext === 'png' || ext === 'jpg' || ext === 'jpeg') {
const image = new Image();
image.src = 'data:image/' + ext + ';base64,' + lib[filename];
document.body.appendChild(image);
} else if (ext === 'js') {
const s = document.createElement('script');
s.appendChild(document.createTextNode(lib[filename]));
document.body.appendChild(s);
}
}
/*
* Note: this 'lens.js' script should always get added as the LAST script
* since it may reference things defined in the other scripts.
*/
document.body.appendChild(lensScript);
} // handleLibraryFiles
/**
* Setup the aspect timeout check. If the lens has already been loaded,
* dispatch the "hierarchyLoad" event. If not, return the hierarchyLoad event.
*
* @param {Object} hierarchy - hierarchy response
* @param {Object} allAspects - aspects response
* @param {Object} perspective - perspective object
* @param {Boolean} gotLens
* @returns {CustomEvent} if lens is received, return undefined,
* else return hierarchyLoadEvent.
*/
function handleHierarchyEvent(hierarchy, allAspects, perspective, gotLens) {
// perspective aspects - all aspects that could potentially be included in this perspective
const perspectiveAspects = filterPerspectiveAspects(allAspects, perspective);
// track aspects to be used for intercepting v1 events
trackAspects(perspectiveAspects);
// setup auto-reload based on the lowest aspect timeout
setupAutoReload(hierarchy);
// prepare hierarchy event
const hierarchyLoadEvent = prepareHierarchyEventForLens(hierarchy, perspectiveAspects);
// dispatch to lens. if not ready, return the event, to be dispatched on lens arrival.
if (gotLens) {
LENS_DIV.dispatchEvent(hierarchyLoadEvent);
} else {
return hierarchyLoadEvent;
}
}
/**
* Filter aspects based on the perspective filters.
*
* @param {Object} allAspects
* @param {Object} perspective
*/
function filterPerspectiveAspects(allAspects, perspective) {
const nspStr = emitUtils.getPerspectiveNamespaceString(perspective);
return allAspects.filter((asp) =>
emitUtils.shouldIEmitThisObj(nspStr, asp)
);
}
function prepareHierarchyEventForLens(hierarchy, aspects) {
let eventDetail;
if (lensEventApiVersion < 2) {
eventDetail = pu.reconstructV1Hierarchy(hierarchy, aspects);
} else {
eventDetail = { hierarchy, aspects };
}
return new window.CustomEvent(
'refocus.lens.hierarchyLoad', { detail: eventDetail }
);
}
/**
* Setup an interval to check that the page is still receiving events,
* based on the lowest timeout for an aspect in the hierarchy.
*
* @param {Object} hierarchy
*/
function setupAutoReload(hierarchy) {
const minAspectTimeout = (
pu.aspectNamesInHierarchy(hierarchy)
.map(getTrackedAspect)
.filter(Boolean)
.map((a) => parseTimeout(a.timeout))
.reduce((a, b) => Math.min(a, b), Infinity)
);
lastUpdateTime = Date.now();
if (minAspectTimeout < Infinity) {
timeoutCheckInterval = setInterval(() => {
if (Date.now() - lastUpdateTime >= minAspectTimeout * 2) {
window.location.reload();
}
}, minAspectTimeout);
}
}
/**
* Parse a timeout string and convert it into ms.
* @param {String} timeoutString - a timeout string from a sample
* @returns {Number} the sample timeout in ms
*/
function parseTimeout(timeoutString) {
let timeout = timeoutString.slice(0, -1) * 1000;
const unit = timeoutString.slice(-1).toLowerCase();
switch (unit) {
case 'm':
timeout *= 60;
break;
case 'h':
timeout *= 3600;
break;
case 'd':
timeout *= 86400;
break;
}
return timeout;
}
/**
* On receiving the lens, load the lens.
* Load the hierarchy if hierarchy event is passed in.
*
* @param {Object} library the perspective's lens's library
* @param {Object} hierarchyLoadEvent undefined or
* a Custom Event
*/
function handleLensDomEvent(lensEventApiVer, library, hierarchyLoadEvent) {
handleLibraryFiles(library); // inject lens library files in perspective view
setLensEventApiVersion(lensEventApiVer); // save lens event api version
u.removeSpinner(SPINNER_ID);
/*
* Load the lens. Pass userId from cookie through to the lens, in case the
* lens wants to do any analytics by userId.
*/
const lensLoadEvent = new window.CustomEvent('refocus.lens.load', {
detail: {
userId: u.getCookie('userId'),
},
});
LENS_DIV.dispatchEvent(lensLoadEvent);
/*
* The order of events matters so if we happened to have gotten the
* hierarchy *before* the lens, then dispatch the lens.hierarchyLoad event
* now.
*/
if (hierarchyLoadEvent) {
LENS_DIV.dispatchEvent(hierarchyLoadEvent);
}
} // handleLensDomEvent
/**
* Returns the default url if page url ends with /perspectives
* Else the perspective name is in url:
* - change the document title to the name of the perspective.
* - return nothing
*
* @returns {String} if on/perspectives page, return default url.
* Else returns nothing
*/
function getPerspectiveUrl() {
let h = window.location.pathname;
let hsplit = h.split('/');
let p = hsplit.pop();
// named perspective
if (p && p !== 'perspectives') {
document.title += ' - ' + p;
return { url: '/v1/perspectives/' + p, named: true };
} else {
const object = { named: false };
object.url = GET_DEFAULT_PERSPECTIVE;
return object;
}
} // whichPerspective
window.onload = () => {
// Note: these are declared in perspective.pug:
_realtimeApplication = realtimeApplication;
_realtimeEventThrottleMilliseconds = realtimeEventThrottleMilliseconds;
_userSession = userSession;
_io = io;
if (_realtimeEventThrottleMilliseconds !== ZERO) {
eventsQueue.scheduleFlushQueue(LENS_DIV, _realtimeEventThrottleMilliseconds);
}
const accumulatorObject = {
getPromiseWithUrl: u.getPromiseWithUrl,
getPerspectiveUrl,
handleHierarchyEvent,
handleLensDomEvent,
customHandleError: (msg) => {
ERROR_INFO_DIV.innerHTML = msg;
u.removeSpinner(SPINNER_ID);
},
setupSocketIOClient,
redirectToUrl: (url) => window.location.href = url,
};
getValuesObject(accumulatorObject)
.then((valuesObject) => {
// skip loading the controller if nothing is returned
if (valuesObject) {
loadController(valuesObject);
}
})
.catch((error) => {
document.getElementById('errorInfo').innerHTML = error;
});
};
/**
* Passes data on to Controller to pass onto renderers.
*
* @param {Object} values Data returned from AJAX.
*/
function loadController(values) {
ReactDOM.render(<PerspectiveController values={ values } />,
PERSPECTIVE_CONTAINER);
}
// For Testing
function getTimeoutValues() {
return {
lastUpdateTime,
timeoutCheckInterval,
};
}
function setLensEventApiVersion(version) {
lensEventApiVersion = version;
}
// For Testing
function resetState() {
clearInterval(timeoutCheckInterval);
timeoutCheckInterval = undefined;
lastUpdateTime = undefined;
Object.keys(trackedAspects).forEach((key) =>
delete trackedAspects[key]
);
eventsQueue.queue.splice(0);
}
module.exports = {
getTimeoutValues,
handleEvent,
parseTimeout,
setupAutoReload,
exportForTesting: {
resetState,
handleHierarchyEvent,
setLensEventApiVersion,
eventsQueue,
},
};
|
app/containers/FeaturePage/index.js | KyleAWang/react-boilerplate | /*
* FeaturePage
*
* List all the features
*/
import React from 'react';
import Helmet from 'react-helmet';
import { FormattedMessage } from 'react-intl';
import H1 from 'components/H1';
import messages from './messages';
import List from './List';
import ListItem from './ListItem';
import ListItemTitle from './ListItemTitle';
export default class FeaturePage extends React.Component { // eslint-disable-line react/prefer-stateless-function
// Since state and props are static,
// there's no need to re-render this component
shouldComponentUpdate() {
return false;
}
render() {
return (
<div>
<Helmet
title="Feature Page"
meta={[
{ name: 'description', content: 'Feature page of React.js Boilerplate application' },
]}
/>
<H1>
<FormattedMessage {...messages.header} />
</H1>
<List>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.scaffoldingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.scaffoldingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.feedbackHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.feedbackMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.routingHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.routingMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.networkHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.networkMessage} />
</p>
</ListItem>
<ListItem>
<ListItemTitle>
<FormattedMessage {...messages.intlHeader} />
</ListItemTitle>
<p>
<FormattedMessage {...messages.intlMessage} />
</p>
</ListItem>
</List>
</div>
);
}
}
|
src/svg-icons/image/photo-camera.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImagePhotoCamera = (props) => (
<SvgIcon {...props}>
<circle cx="12" cy="12" r="3.2"/><path d="M9 2L7.17 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-2h-3.17L15 2H9zm3 15c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z"/>
</SvgIcon>
);
ImagePhotoCamera = pure(ImagePhotoCamera);
ImagePhotoCamera.displayName = 'ImagePhotoCamera';
ImagePhotoCamera.muiName = 'SvgIcon';
export default ImagePhotoCamera;
|
packages/material-ui-icons/src/TurnedIn.js | AndriusBil/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let TurnedIn = props =>
<SvgIcon {...props}>
<path d="M17 3H7c-1.1 0-1.99.9-1.99 2L5 21l7-3 7 3V5c0-1.1-.9-2-2-2z" />
</SvgIcon>;
TurnedIn = pure(TurnedIn);
TurnedIn.muiName = 'SvgIcon';
export default TurnedIn;
|
src/app/components/Root.js | honzachalupa/portfolio2017 | import React, { Component } from 'react';
import { BrowserRouter as Router, Route, Switch, browserHistory } from 'react-router-dom';
import update from 'immutability-helper';
import factory from './../factory';
import aspectRatioPreserver from './../modules/aspect-ratio-preserver';
import log from './../modules/logger';
import { setPageTitle } from './../helpers';
import HomePage from './../pages/Home';
import ProjectsPage from './../pages/Projects';
import AboutPage from './../pages/About';
import ProjectDetailPage from './../pages/ProjectDetail';
import ImageViewerPage from './../pages/ImageViewer';
import NotFoundPage from './../pages/NotFound';
import GoogleAnalytics from 'react-ga';
export default class Root extends Component {
constructor(props) {
super(props);
this.navigationToggler = this.navigationToggler.bind(this);
this.setNavigationItem = this.setNavigationItem.bind(this);
this.handleResize = this.handleResize.bind(this);
this.handleScroll = this.handleScroll.bind(this);
const { config } = props.apiData;
let { projects } = props.apiData;
projects = this.filterProjects(projects);
projects = this.sortProjects(projects);
config.navigationOpened = false;
config.scrolledDistance = 0;
config.projectTypes = this.getProjectTypes(projects);
this.state = {
projects,
config,
utilities: {
navigationToggler: this.navigationToggler,
setNavigationItem: this.setNavigationItem
}
};
}
componentDidMount() {
GoogleAnalytics.initialize('UA-47064928-3');
this.updateDimensions();
this.getScrolledDistance();
window.addEventListener('resize', this.handleResize);
window.addEventListener('scroll', this.handleScroll);
}
componentDidUpdate() {
factory(aspectRatioPreserver, document.querySelectorAll('[data-aspect-ratio]'));
}
componentWillUnmount() {
window.removeEventListener('resize', this.handleResize);
window.removeEventListener('scroll', this.handleScroll);
}
setNavigationItem(clickedId) {
const { navigationItems } = this.state.config;
const navigationItemsActive = navigationItems.forEach((item) => {
item.active = (item.id === clickedId);
});
this.setState({
navigationItems: update(navigationItems, {
$set: navigationItemsActive
})
});
window.scrollTo(0, 0);
}
getProjectTypes(projects) {
const types = [];
projects.forEach((project) => {
if (types.indexOf(project.type) === -1) {
types.push(project.type);
}
});
return types;
}
getScrolledDistance() {
this.setState({
config: update(this.state.config, {
$merge: {
scrolledDistance: window.pageYOffset
}
})
});
}
handleScroll() {
this.getScrolledDistance();
}
updateDimensions() {
const { screenBreakpoint } = this.state.config;
const dimensions = {
windowDimensions: {
width: window.innerWidth,
height: window.innerHeight
}
};
this.setState({
config: update(this.state.config, {
$merge: dimensions
})
});
if (dimensions.windowDimensions.width >= screenBreakpoint) {
this.setState({
config: update(this.state.config, {
$merge: {
navigationOpened: false
}
})
});
}
}
handleResize() {
this.updateDimensions();
}
navigationToggler(forceClose) {
const { navigationOpened, windowDimensions, screenBreakpoint } = this.state.config;
if (windowDimensions && windowDimensions.width < screenBreakpoint) {
this.setState({
config: update(this.state.config, {
$merge: {
navigationOpened: (forceClose === 'undefined') ? false : !navigationOpened
}
})
});
}
}
trackGoogleAnalytics() {
GoogleAnalytics.pageview(window.location.hash);
}
sortProjects(projects) {
return projects.sort((a, b) => {
return new Date(b.addedDate) - new Date(a.addedDate);
});
}
filterProjects(projects) {
const filtered = [];
projects.forEach((project) => {
if (project.hidden === undefined || project.hidden === false) {
filtered.push(project);
}
});
return filtered;
}
render() {
if (this.state && this.state.config && this.state.utilities) {
const { config, utilities, projects } = this.state;
return (
<Router history={browserHistory} onUpdate={this.trackGoogleAnalytics}>
<Switch>
<Route
exact
path="/"
render={(props) => (
<HomePage config={config} utilities={utilities} projects={projects} />
)}
/>
<Route
exact
path="/projects"
render={(props) => (
<ProjectsPage config={config} utilities={utilities} projects={projects} />
)}
/>
<Route
exact
path="/about-me"
render={(props) => (
<AboutPage config={config} utilities={utilities} />
)}
/>
<Route
exact
path="/image/:id"
render={(props) => (
<ImageViewerPage config={config} utilities={utilities} params={props.match.params} />
)}
/>
<Route
exact
path="/projects/:id"
render={(props) => (
<ProjectDetailPage config={config} utilities={utilities} projects={projects} params={props.match.params} />
)}
/>
<Route
render={() => (
<NotFoundPage config={config} utilities={utilities} />
)}
/>
</Switch>
</Router>
);
}
return (
<div>
Loading...
</div>
);
}
}
|
src/components/Map/AddTitle.js | Angular-Toast/habitat | import React, { Component } from 'react';
import { StyleSheet, Text, View, Animated, Image, Dimensions, TextInput, Button} from "react-native";
import { StackNavigator, NavigationActions } from 'react-navigation';
export default class Title extends React.Component {
static navigationOptions = {
title: 'Give your ecosystem a name!'
};
constructor(props) {
super(props);
this.state = {
title: '',
description: ''
}
}
render() {
const { navigate } = this.props.navigation;
let avatar = this.props.navigation.state.params.avatar;
let eco = this.props.navigation.state.params.eco;
return (
<View style={styles.container}>
<Image source={images[avatar][1]} style={styles.ecobuds}/>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 100}}
onChangeText={(e) => this.setState({title: e})}
value={this.state.title}
/>
<TextInput
style={{height: 40, borderColor: 'gray', borderWidth: 1, width: 200}}
onChangeText={(e) => this.setState({description: e})}
value={this.state.description}
/>
<Button
onPress={() => navigate('Location', {eco: eco, avatar: avatar, title: this.state.title, description: this.state.description})}
title="Next"
color="#841584"
/>
</View>
);
}
}
const sprites = [
[0, require("../assets/Ecosystem/toast1.png")],
[1, require("../assets/Ecosystem/tree1.png")]
]
const images = [
[0, require("../assets/Ecosystem/home.png")],
[1, require("../assets/Ecosystem/work.png")],
[2, require("../assets/Ecosystem/gym.png")]
]
const styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
},
ecobuds: {
width: 100,
height: 100
}
})
|
src/components/ConsoleTidal.js | merttoka/Siren | import React from 'react';
import { Controlled as CodeMirror } from 'react-codemirror2'
import _ from 'lodash'
import { inject, observer } from 'mobx-react';
import { save } from '../keyFunctions.js';
import 'codemirror/lib/codemirror.css';
import '../utils/lexers/haskell.js';
import '../utils/lexers/haskell.css';
// codemirror addons
import 'codemirror/addon/selection/active-line.js';
import 'codemirror/addon/edit/matchbrackets.js';
@inject('consoleStore')
@observer
export default class ConsoleTidal extends React.Component {
// GHC
handleGHCSubmit = (editor, event) => {
if (event.keyCode === 13 && event.ctrlKey) {
let expr = "";
if (editor.somethingSelected()) {
// selected text
expr = event.target.value;
}
else {
const line = editor.getCursor().line;
if (editor.getLine(line) !== "") {
let startLine = line;
let endLine = line;
// determine line numbers of the code block
while (_.trim(editor.getLine(startLine)) !== '') { startLine -= 1; }
while (_.trim(editor.getLine(endLine)) !== '') { endLine += 1; }
// the text
expr = editor.getRange({ line: startLine, ch: 0 }, { line: endLine, ch: 0 });
// coloring the background
let handle = editor.markText(
{ line: startLine, ch: 0 },
{ line: endLine, ch: 0 },
{ className: 'CodeMirror-execution' });
_.delay(() => { handle.clear(); }, 500);
}
}
// execute the line
if (expr !== "")
this.props.consoleStore.submitGHC(expr);
}
event.preventDefault();
return false;
}
saveStuff = (editor, e) => {
if(e.ctrlKey && (e.which === 83)) {
e.preventDefault();
save();
return false;
}
}
render() {
console.log("RENDER CONSOLETIDAL.JS");
const options = {
mode: '_rule_haskell',
theme: '_style',
fixedGutter: true,
scroll: false,
styleSelectedText: true,
showToken: true,
lineWrapping: true,
lineNumbers: true,
showCursorWhenSelecting: true,
// addon options
styleActiveLine: true,
matchBrackets: true,
maxScanLines: 10
};
return (<div className={'ConsoleTextBox'}>
<p>select -> ctrl+enter</p>
<CodeMirror className={"draggableCancel"}
value={this.props.consoleStore.tidal_text}
options={options}
onBeforeChange={(editor, metadata, value) => {
this.props.consoleStore.onChangeTidal(value);
}}
onChange={() => { }}
onKeyDown={this.saveStuff.bind(this)}
onKeyUp={this.handleGHCSubmit.bind(this)}
/>
</div>);
}
}
|
actor-apps/app-web/src/app/components/modals/CreateGroup.react.js | bunnyblue/actor-platform | import React from 'react';
import CreateGroupActionCreators from 'actions/CreateGroupActionCreators';
import CreateGroupStore from 'stores/CreateGroupStore';
import CreateGroupForm from './create-group/Form.react';
import Modal from 'react-modal';
import { KeyCodes } from 'constants/ActorAppConstants';
const appElement = document.getElementById('actor-web-app');
Modal.setAppElement(appElement);
const getStateFromStores = () => {
return {
isShown: CreateGroupStore.isModalOpen()
};
};
class CreateGroup extends React.Component {
constructor(props) {
super(props);
this.state = getStateFromStores();
CreateGroupStore.addChangeListener(this.onChange);
document.addEventListener('keydown', this.onKeyDown, false);
}
componentWillUnmount() {
CreateGroupStore.removeChangeListener(this.onChange);
document.removeEventListener('keydown', this.onKeyDown, false);
}
render() {
const isShown = this.state.isShown;
return (
<Modal className="modal-new modal-new--create-group" closeTimeoutMS={150} isOpen={isShown}>
<header className="modal-new__header">
<a className="modal-new__header__close material-icons" onClick={this.onClose}>clear</a>
<h3 className="modal-new__header__title">Create group</h3>
</header>
<CreateGroupForm/>
</Modal>
);
}
onChange = () => {
this.setState(getStateFromStores());
}
onClose = () => {
CreateGroupActionCreators.closeModal();
}
onKeyDown = (event) => {
if (event.keyCode === KeyCodes.ESC) {
event.preventDefault();
this.onClose();
}
}
}
CreateGroup.displayName = 'CreateGroup';
export default CreateGroup;
|
src/svg-icons/image/grid-off.js | spiermar/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageGridOff = (props) => (
<SvgIcon {...props}>
<path d="M8 4v1.45l2 2V4h4v4h-3.45l2 2H14v1.45l2 2V10h4v4h-3.45l2 2H20v1.45l2 2V4c0-1.1-.9-2-2-2H4.55l2 2H8zm8 0h4v4h-4V4zM1.27 1.27L0 2.55l2 2V20c0 1.1.9 2 2 2h15.46l2 2 1.27-1.27L1.27 1.27zM10 12.55L11.45 14H10v-1.45zm-6-6L5.45 8H4V6.55zM8 20H4v-4h4v4zm0-6H4v-4h3.45l.55.55V14zm6 6h-4v-4h3.45l.55.54V20zm2 0v-1.46L17.46 20H16z"/>
</SvgIcon>
);
ImageGridOff = pure(ImageGridOff);
ImageGridOff.displayName = 'ImageGridOff';
ImageGridOff.muiName = 'SvgIcon';
export default ImageGridOff;
|
packages/react-scripts/fixtures/kitchensink/src/features/syntax/Promises.js | lolaent/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, { Component } from 'react';
import PropTypes from 'prop-types';
function load() {
return Promise.resolve([
{ id: 1, name: '1' },
{ id: 2, name: '2' },
{ id: 3, name: '3' },
{ id: 4, name: '4' },
]);
}
export default class extends Component {
static propTypes = {
onReady: PropTypes.func.isRequired,
};
constructor(props) {
super(props);
this.state = { users: [] };
}
componentDidMount() {
load().then(users => {
this.setState({ users });
});
}
componentDidUpdate() {
this.props.onReady();
}
render() {
return (
<div id="feature-promises">
{this.state.users.map(user => (
<div key={user.id}>
{user.name}
</div>
))}
</div>
);
}
}
|
docs/src/app/components/pages/components/IconMenu/ExampleNested.js | IsenrichO/mui-with-arrows | import React from 'react';
import IconMenu from 'material-ui/IconMenu';
import MenuItem from 'material-ui/MenuItem';
import IconButton from 'material-ui/IconButton';
import Divider from 'material-ui/Divider';
import Download from 'material-ui/svg-icons/file/file-download';
import ArrowDropRight from 'material-ui/svg-icons/navigation-arrow-drop-right';
import MoreVertIcon from 'material-ui/svg-icons/navigation/more-vert';
/**
* Example of nested menus within an IconMenu.
*/
const IconMenuExampleNested = () => (
<IconMenu
iconButtonElement={<IconButton><MoreVertIcon /></IconButton>}
anchorOrigin={{horizontal: 'left', vertical: 'top'}}
targetOrigin={{horizontal: 'left', vertical: 'top'}}
>
<MenuItem
primaryText="Copy & Paste"
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem primaryText="Cut" />,
<MenuItem primaryText="Copy" />,
<Divider />,
<MenuItem primaryText="Paste" />,
]}
/>
<MenuItem
primaryText="Case Tools"
rightIcon={<ArrowDropRight />}
menuItems={[
<MenuItem primaryText="UPPERCASE" />,
<MenuItem primaryText="lowercase" />,
<MenuItem primaryText="CamelCase" />,
<MenuItem primaryText="Propercase" />,
]}
/>
<Divider />
<MenuItem primaryText="Download" leftIcon={<Download />} />
<Divider />
<MenuItem value="Del" primaryText="Delete" />
</IconMenu>
);
export default IconMenuExampleNested;
|
frontend/src/Components/Form/TextArea.js | geogolem/Radarr | import classNames from 'classnames';
import PropTypes from 'prop-types';
import React, { Component } from 'react';
import styles from './TextArea.css';
class TextArea extends Component {
//
// Lifecycle
constructor(props, context) {
super(props, context);
this._input = null;
this._selectionStart = null;
this._selectionEnd = null;
this._selectionTimeout = null;
this._isMouseTarget = false;
}
componentDidMount() {
window.addEventListener('mouseup', this.onDocumentMouseUp);
}
componentWillUnmount() {
window.removeEventListener('mouseup', this.onDocumentMouseUp);
if (this._selectionTimeout) {
this._selectionTimeout = clearTimeout(this._selectionTimeout);
}
}
//
// Control
setInputRef = (ref) => {
this._input = ref;
}
selectionChange() {
if (this._selectionTimeout) {
this._selectionTimeout = clearTimeout(this._selectionTimeout);
}
this._selectionTimeout = setTimeout(() => {
const selectionStart = this._input.selectionStart;
const selectionEnd = this._input.selectionEnd;
const selectionChanged = (
this._selectionStart !== selectionStart ||
this._selectionEnd !== selectionEnd
);
this._selectionStart = selectionStart;
this._selectionEnd = selectionEnd;
if (this.props.onSelectionChange && selectionChanged) {
this.props.onSelectionChange(selectionStart, selectionEnd);
}
}, 10);
}
//
// Listeners
onChange = (event) => {
const {
name,
onChange
} = this.props;
const payload = {
name,
value: event.target.value
};
onChange(payload);
}
onFocus = (event) => {
if (this.props.onFocus) {
this.props.onFocus(event);
}
this.selectionChange();
}
onKeyUp = () => {
this.selectionChange();
}
onMouseDown = () => {
this._isMouseTarget = true;
}
onMouseUp = () => {
this.selectionChange();
}
onDocumentMouseUp = () => {
if (this._isMouseTarget) {
this.selectionChange();
}
this._isMouseTarget = false;
}
//
// Render
render() {
const {
className,
readOnly,
autoFocus,
placeholder,
name,
value,
hasError,
hasWarning,
onBlur
} = this.props;
return (
<textarea
ref={this.setInputRef}
readOnly={readOnly}
autoFocus={autoFocus}
placeholder={placeholder}
className={classNames(
className,
readOnly && styles.readOnly,
hasError && styles.hasError,
hasWarning && styles.hasWarning
)}
name={name}
value={value}
onChange={this.onChange}
onFocus={this.onFocus}
onBlur={onBlur}
onKeyUp={this.onKeyUp}
onMouseDown={this.onMouseDown}
onMouseUp={this.onMouseUp}
/>
);
}
}
TextArea.propTypes = {
className: PropTypes.string.isRequired,
readOnly: PropTypes.bool,
autoFocus: PropTypes.bool,
placeholder: PropTypes.string,
name: PropTypes.string.isRequired,
value: PropTypes.oneOfType([PropTypes.string, PropTypes.number, PropTypes.array]).isRequired,
hasError: PropTypes.bool,
hasWarning: PropTypes.bool,
onChange: PropTypes.func.isRequired,
onFocus: PropTypes.func,
onBlur: PropTypes.func,
onSelectionChange: PropTypes.func
};
TextArea.defaultProps = {
className: styles.input,
type: 'text',
readOnly: false,
autoFocus: false,
value: ''
};
export default TextArea;
|
node_modules/react-bootstrap/es/NavDropdown.js | ivanhristov92/bookingCalendar | import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import _extends from 'babel-runtime/helpers/extends';
import classNames from 'classnames';
import React from 'react';
import Dropdown from './Dropdown';
import splitComponentProps from './utils/splitComponentProps';
import ValidComponentChildren from './utils/ValidComponentChildren';
var propTypes = _extends({}, Dropdown.propTypes, {
// Toggle props.
title: React.PropTypes.node.isRequired,
noCaret: React.PropTypes.bool,
active: React.PropTypes.bool,
// Override generated docs from <Dropdown>.
/**
* @private
*/
children: React.PropTypes.node
});
var NavDropdown = function (_React$Component) {
_inherits(NavDropdown, _React$Component);
function NavDropdown() {
_classCallCheck(this, NavDropdown);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavDropdown.prototype.isActive = function isActive(_ref, activeKey, activeHref) {
var props = _ref.props;
var _this2 = this;
if (props.active || activeKey != null && props.eventKey === activeKey || activeHref && props.href === activeHref) {
return true;
}
if (ValidComponentChildren.some(props.children, function (child) {
return _this2.isActive(child, activeKey, activeHref);
})) {
return true;
}
return props.active;
};
NavDropdown.prototype.render = function render() {
var _this3 = this;
var _props = this.props,
title = _props.title,
activeKey = _props.activeKey,
activeHref = _props.activeHref,
className = _props.className,
style = _props.style,
children = _props.children,
props = _objectWithoutProperties(_props, ['title', 'activeKey', 'activeHref', 'className', 'style', 'children']);
var active = this.isActive(this, activeKey, activeHref);
delete props.active; // Accessed via this.isActive().
delete props.eventKey; // Accessed via this.isActive().
var _splitComponentProps = splitComponentProps(props, Dropdown.ControlledComponent),
dropdownProps = _splitComponentProps[0],
toggleProps = _splitComponentProps[1];
// Unlike for the other dropdowns, styling needs to go to the `<Dropdown>`
// rather than the `<Dropdown.Toggle>`.
return React.createElement(
Dropdown,
_extends({}, dropdownProps, {
componentClass: 'li',
className: classNames(className, { active: active }),
style: style
}),
React.createElement(
Dropdown.Toggle,
_extends({}, toggleProps, { useAnchor: true }),
title
),
React.createElement(
Dropdown.Menu,
null,
ValidComponentChildren.map(children, function (child) {
return React.cloneElement(child, {
active: _this3.isActive(child, activeKey, activeHref)
});
})
)
);
};
return NavDropdown;
}(React.Component);
NavDropdown.propTypes = propTypes;
export default NavDropdown; |
packages/@vega/layout/src/components/AcceptInvite/AcceptReviewerInvite.js | VegaPublish/vega-studio | /* eslint-disable max-len */
import React from 'react'
import Button from 'part:@lyra/components/buttons/default'
import lyraClient from 'part:@lyra/base/client'
import styles from './styles/AcceptReviewerInvite.css'
import client from 'part:@lyra/base/client'
import locationStore from 'part:@lyra/base/location'
function markReviewItemAsAccepted(userId) {
const query = `*[_type == "reviewItem" && reviewer._ref == "${userId}"][0]{...}`
return lyraClient.fetch(query).then(reviewItem => {
return lyraClient
.patch(reviewItem._id)
.set({acceptState: 'accepted'})
.commit()
})
}
type Props = {
invite: any,
user: any,
venue: boolean
}
export default class AcceptReviewerInvite extends React.Component<Props> {
handleAcceptInvite = () => {
const {invite, user, venue} = this.props
const claimUrl = `/invitations/claim/${invite._id}?venueId=${venue._id}`
const maybeLogout = user ? client.auth.logout() : Promise.resolve()
maybeLogout
.then(() =>
client.request({
url: claimUrl
})
)
.then(() => markReviewItemAsAccepted(invite.target._ref))
.then(() => locationStore.actions.navigate('/'))
}
render() {
const {invite, user, venue} = this.props
return (
<div className={styles.root}>
<div>
<div className={styles.header}>
<div className={styles.headerInner} />
</div>
<h2>Invitation to review article in {venue.title}</h2>
<p>{invite.message}</p>
{user ? (
<div>
<p>
You are currently logged in as {user.name}. In order to accept
this invitation you will have to log out first.
</p>
<div className={styles.choices}>
<div>
<Button onClick={this.handleAcceptInvite} color="primary">
Logout and accept invitation to become reviewer
</Button>{' '}
</div>
<div>or</div>
<div>
<a href="/">Continue in Vega as {user.name}</a>
</div>
</div>
</div>
) : (
<Button onClick={this.handleAcceptInvite} color="primary">
Accept invitation to become reviewer
</Button>
)}
</div>
</div>
)
}
}
|
src/components/Switcher.js | jo12bar/blag | import React from 'react';
import { connect } from 'react-redux';
import { TransitionGroup, Transition } from 'transition-group';
import universal from 'react-universal-component';
import Loading from './Loading';
import Err from './Error';
import isLoading from '../selectors/isLoading';
import styles from '../css/Switcher';
const UniversalComponent = universal(({ page }) => import(`../pages/${page}`), {
minDelay: 500,
loading: Loading,
error: Err,
});
const Switcher = ({ page, direction, isLoading }) => (
<TransitionGroup
className={`${styles.switcher} ${direction}`}
duration={500}
prefix='fade'
>
<Transition key={page}>
<UniversalComponent page={page} isLoading={isLoading} />
</Transition>
</TransitionGroup>
);
const mapState = ({ page, direction, ...state }) => {
const isLoad = isLoading(state);
console.log('isLoading:', isLoad);
return ({
page,
direction,
isLoading: isLoad,
});
};
export default connect(mapState)(Switcher);
|
docs/src/sections/ProgressBarSection.js | apkiernan/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function ProgressBarSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="progress">Progress bars</Anchor> <small>ProgressBar</small>
</h2>
<p className="lead">Provide up-to-date feedback on the progress of a workflow or action with simple yet flexible progress bars.</p>
<h2><Anchor id="progress-basic">Basic example</Anchor></h2>
<p>Default progress bar.</p>
<ReactPlayground codeText={Samples.ProgressBarBasic} />
<h2><Anchor id="progress-label">With label</Anchor></h2>
<p>Add a <code>label</code> prop to show a visible percentage. For low percentages, consider adding a min-width to ensure the label's text is fully visible.</p>
<ReactPlayground codeText={Samples.ProgressBarWithLabel} />
<h2><Anchor id="progress-screenreader-label">Screenreader only label</Anchor></h2>
<p>Add a <code>srOnly</code> prop to hide the label visually.</p>
<ReactPlayground codeText={Samples.ProgressBarScreenreaderLabel} />
<h2><Anchor id="progress-contextual">Contextual alternatives</Anchor></h2>
<p>Progress bars use some of the same button and alert classes for consistent styles.</p>
<ReactPlayground codeText={Samples.ProgressBarContextual} />
<h2><Anchor id="progress-striped">Striped</Anchor></h2>
<p>Uses a gradient to create a striped effect. Not available in IE8.</p>
<ReactPlayground codeText={Samples.ProgressBarStriped} />
<h2><Anchor id="progress-animated">Animated</Anchor></h2>
<p>Add <code>active</code> prop to animate the stripes right to left. Not available in IE9 and below.</p>
<ReactPlayground codeText={Samples.ProgressBarAnimated} />
<h2><Anchor id="progress-stacked">Stacked</Anchor></h2>
<p>Nest <code><ProgressBar /></code>s to stack them.</p>
<ReactPlayground codeText={Samples.ProgressBarStacked} />
<h3><Anchor id="progress-props">ProgressBar</Anchor></h3>
<PropTable component="ProgressBar"/>
</div>
);
}
|
react_layout/setup.js | devSC/react-native | /**
* Sample React Native App
* https://github.com/facebook/react-native
* @flow
*/
import React, { Component } from 'react';
import {
StyleSheet,
Text,
View
} from 'react-native';
import FlexBoxTest from './FlexBoxTest'
import FlexBoxDice from './FlexBoxDice'
export default class setup extends Component {
render() {
return (
<View style={styles.container}>
<FlexBoxDice/>
{/*<FlexBoxTest/>*/}
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
marginTop: 64,
backgroundColor: '#F5FCFF',
},
}); |
packages/material-ui-icons/src/LinkedCamera.js | dsslimshaddy/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from 'material-ui/SvgIcon';
let LinkedCamera = props =>
<SvgIcon {...props}>
<circle cx="12" cy="14" r="3.2" /><path d="M16 3.33c2.58 0 4.67 2.09 4.67 4.67H22c0-3.31-2.69-6-6-6v1.33M16 6c1.11 0 2 .89 2 2h1.33c0-1.84-1.49-3.33-3.33-3.33V6" /><path d="M17 9c0-1.11-.89-2-2-2V4H9L7.17 6H4c-1.1 0-2 .9-2 2v12c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V9h-5zm-5 10c-2.76 0-5-2.24-5-5s2.24-5 5-5 5 2.24 5 5-2.24 5-5 5z" />
</SvgIcon>;
LinkedCamera = pure(LinkedCamera);
LinkedCamera.muiName = 'SvgIcon';
export default LinkedCamera;
|
src/client/routes/Bundle.js | Paul-Long/m-gril | import React from 'react';
export default class Bundle extends React.Component {
constructor(props) {
super(props);
this.state = {
mod: null
};
}
componentWillMount() {
this.load(this.props)
}
componentWillReceiveProps(nextProps) {
if (nextProps.load !== this.props.load) {
this.load(nextProps)
}
}
load(props) {
this.setState({mod: null});
props.load().then((mod) => {
this.setState({mod: mod.default || mod});
});
}
render() {
return this.state.mod ? this.props.children(this.state.mod) : null;
}
} |
examples/todomvc/containers/TodoApp.js | aheuermann/redux | import React, { Component } from 'react';
import { bindActionCreators } from 'redux';
import { connect } from 'react-redux';
import Header from '../components/Header';
import MainSection from '../components/MainSection';
import * as TodoActions from '../actions/todos';
class TodoApp extends Component {
render() {
const { todos, dispatch } = this.props;
const actions = bindActionCreators(TodoActions, dispatch);
return (
<div>
<Header addTodo={actions.addTodo} />
<MainSection todos={todos} actions={actions} />
</div>
);
}
}
function select(state) {
return {
todos: state.todos
};
}
export default connect(select)(TodoApp);
|
js/signin/src/components/SecretReset.js | fogfish/oauth2 | import React from 'react'
import { Button, Intent } from '@blueprintjs/core'
import { Link } from 'react-router-dom'
import Dialog from 'components/Dialog'
import AccessKey from 'components/AccessKey'
const Actions = () => (
<>
<Link className="bp3-button bp3-minimal bp3-intent-primary" to="/">
<b>Sign In Instead</b>
</Link>
<Button type="submit" intent={Intent.PRIMARY} large>Reset Password</Button>
</>
)
const SecretReset = ({ oauth2 }) => (
<Dialog
icon="fa-lock"
title="Forgot Your Password ?"
url="/oauth2/password"
Actions={Actions}
>
<p className="bp3-ui-text bp3-running-text">
Type you
<b>email</b>
address to reset your password.
We will send recovery instructions over email.
</p>
<AccessKey />
<input name="response_type" type="hidden" value="password_reset" />
<input name="client_id" type="hidden" value={oauth2.clientId} />
<input name="redirect_uri" type="hidden" value={oauth2.redirectUri} />
</Dialog>
)
export default SecretReset
|
examples/ssr-caching/pages/blog.js | BlancheXu/test | import React from 'react'
export default class extends React.Component {
static getInitialProps ({ query: { id } }) {
return { id }
}
render () {
return (
<div>
<h1>My {this.props.id} blog post</h1>
<p>
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do
eiusmod tempor incididunt ut labore et dolore magna aliqua.
</p>
</div>
)
}
}
|
fields/components/Checkbox.js | pr1ntr/keystone | import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
import { darken, fade } from '../../admin/client/utils/color';
import E from '../../admin/client/constants';
var Checkbox = React.createClass({
displayName: 'Checkbox',
propTypes: {
checked: React.PropTypes.bool,
component: React.PropTypes.node,
onChange: React.PropTypes.func,
readonly: React.PropTypes.bool,
},
getDefaultProps () {
return {
component: 'button',
};
},
getInitialState () {
return {
active: null,
focus: null,
hover: null,
};
},
componentDidMount () {
window.addEventListener('mouseup', this.handleMouseUp, false);
},
componentWillUnmount () {
window.removeEventListener('mouseup', this.handleMouseUp, false);
},
getStyles () {
const { checked, readonly } = this.props;
const { active, focus, hover } = this.state;
const checkedColor = '#3999fc';
let background = (checked && !readonly) ? checkedColor : 'white';
let borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.15) rgba(0,0,0,0.1) rgba(0,0,0,0.05)' : 'rgba(0,0,0,0.3) rgba(0,0,0,0.2) rgba(0,0,0,0.15)';
let boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 0 rgba(0,0,0,0.06)';
let color = (checked && !readonly) ? 'white' : '#bbb';
const textShadow = (checked && !readonly) ? '0 1px 0 rgba(0,0,0,0.2)' : null;
// pseudo state
if (hover && !focus && !readonly) {
borderColor = (checked) ? 'rgba(0,0,0,0.1) rgba(0,0,0,0.15) rgba(0,0,0,0.2)' : 'rgba(0,0,0,0.35) rgba(0,0,0,0.3) rgba(0,0,0,0.25)';
}
if (active) {
background = (checked && !readonly) ? darken(checkedColor, 20) : '#eee';
borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : 'rgba(0,0,0,0.4) rgba(0,0,0,0.35) rgba(0,0,0,0.3)';
boxShadow = (checked && !readonly) ? '0 1px 0 rgba(255,255,255,0.33)' : 'inset 0 1px 3px rgba(0,0,0,0.2)';
}
if (focus && !active) {
borderColor = (checked && !readonly) ? 'rgba(0,0,0,0.25) rgba(0,0,0,0.3) rgba(0,0,0,0.35)' : checkedColor;
boxShadow = (checked && !readonly) ? `0 0 0 3px ${fade(checkedColor, 15)}` : `inset 0 1px 2px rgba(0,0,0,0.15), 0 0 0 3px ${fade(checkedColor, 15)}`;
}
// noedit
if (readonly) {
background = 'rgba(255,255,255,0.5)';
borderColor = 'rgba(0,0,0,0.1)';
boxShadow = 'none';
color = checked ? checkedColor : '#bbb';
}
return {
alignItems: 'center',
background: background,
border: '1px solid',
borderColor: borderColor,
borderRadius: E.borderRadius.sm,
boxShadow: boxShadow,
color: color,
display: 'inline-block',
fontSize: 14,
height: 16,
lineHeight: '15px',
outline: 'none',
padding: 0,
textAlign: 'center',
textShadow: textShadow,
verticalAlign: 'middle',
width: 16,
msTransition: 'all 120ms ease-out',
MozTransition: 'all 120ms ease-out',
WebkitTransition: 'all 120ms ease-out',
transition: 'all 120ms ease-out',
};
},
handleKeyDown (e) {
if (e.keyCode !== 32) return;
this.toggleActive(true);
},
handleKeyUp () {
this.toggleActive(false);
},
handleMouseOver () {
this.toggleHover(true);
},
handleMouseDown () {
this.toggleActive(true);
this.toggleFocus(true);
},
handleMouseUp () {
this.toggleActive(false);
},
handleMouseOut () {
this.toggleHover(false);
},
toggleActive (pseudo) {
this.setState({ active: pseudo });
},
toggleHover (pseudo) {
this.setState({ hover: pseudo });
},
toggleFocus (pseudo) {
this.setState({ focus: pseudo });
},
handleChange () {
this.props.onChange(!this.props.checked);
},
render () {
const { checked, readonly } = this.props;
const props = blacklist(this.props, 'checked', 'component', 'onChange', 'readonly');
props.style = this.getStyles();
props.ref = 'checkbox';
props.className = classnames('octicon', {
'octicon-check': checked,
'octicon-x': (typeof checked === 'boolean') && !checked && readonly,
});
props.type = readonly ? null : 'button';
props.onKeyDown = this.handleKeyDown;
props.onKeyUp = this.handleKeyUp;
props.onMouseDown = this.handleMouseDown;
props.onMouseUp = this.handleMouseUp;
props.onMouseOver = this.handleMouseOver;
props.onMouseOut = this.handleMouseOut;
props.onClick = readonly ? null : this.handleChange;
props.onFocus = readonly ? null : () => this.toggleFocus(true);
props.onBlur = readonly ? null : () => this.toggleFocus(false);
const node = readonly ? 'span' : this.props.component;
return React.createElement(node, props);
},
});
module.exports = Checkbox;
|
js/components/card/card-showcase.js | YeisonGomez/RNAmanda |
import React, { Component } from 'react';
import { Image, Dimensions } from 'react-native';
import { connect } from 'react-redux';
import { actions } from 'react-native-navigation-redux-helpers';
import { Container, Header, Title, Content, Button, Icon, Card, CardItem, Text, Thumbnail, Left, Right, Body, IconNB } from 'native-base';
import styles from './styles';
import { Actions } from 'react-native-router-flux';
const deviceWidth = Dimensions.get('window').width;
const logo = require('../../../img/logo.png');
const cardImage = require('../../../img/drawer-cover.png');
const {
popRoute,
} = actions;
class NHCardShowcase extends Component {
static propTypes = {
popRoute: React.PropTypes.func,
navigation: React.PropTypes.shape({
key: React.PropTypes.string,
}),
}
popRoute() {
this.props.popRoute(this.props.navigation.key);
}
render() {
return (
<Container style={styles.container}>
<Header>
<Left>
<Button transparent onPress={() => Actions.pop()}>
<Icon name="arrow-back" />
</Button>
</Left>
<Body>
<Title>Card Showcase</Title>
</Body>
<Right />
</Header>
<Content padder>
<Card style={styles.mb}>
<CardItem bordered>
<Left>
<Thumbnail source={logo} />
<Body>
<Text>NativeBase</Text>
<Text note>April 15, 2016</Text>
</Body>
</Left>
</CardItem>
<CardItem>
<Body>
<Image style={{ alignSelf: 'center', height: 150, resizeMode: 'cover', width: deviceWidth / 1.18, marginVertical: 5 }} source={cardImage} />
<Text>
NativeBase is a free and, source framework that enables developers
to build high-quality mobile apps using React Native iOS and Android apps
with a fusion of ES6.
NativeBase builds a layer on top of React Native that provides you with
basic set of components for mobile application development.
</Text>
</Body>
</CardItem>
<CardItem style={{paddingVertical: 0}}>
<Left>
<Button transparent>
<Icon name="logo-github" />
<Text>1,926 stars</Text>
</Button>
</Left>
</CardItem>
</Card>
</Content>
</Container>
);
}
}
function bindAction(dispatch) {
return {
popRoute: key => dispatch(popRoute(key)),
};
}
const mapStateToProps = state => ({
navigation: state.cardNavigation,
themeState: state.drawer.themeState,
});
export default connect(mapStateToProps, bindAction)(NHCardShowcase);
|
client/components/BubbleSlider.js | IBM-Bluemix/election-insights | //------------------------------------------------------------------------------
// Copyright IBM Corp. 2016
//
// 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 Actions from '../Actions';
export default ({ numBubbles }) =>
<div className="bubble-selector">
<div className="num-bubble-label">{numBubbles + (numBubbles === 1 ? " Circle" : " Circles")}</div>
<input
className="slider"
type="range"
min="1"
max="250"
value={numBubbles}
steps="250"
onChange={e => Actions.changeNumBubbles(e.target.value)} />
<div className="help-text">(might need to adjust for screen size or if animations are laggy)</div>
</div>
|
src/components/common/svg-icons/device/signal-wifi-off.js | abzfarah/Pearson.NAPLAN.GnomeH | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let DeviceSignalWifiOff = (props) => (
<SvgIcon {...props}>
<path d="M23.64 7c-.45-.34-4.93-4-11.64-4-1.5 0-2.89.19-4.15.48L18.18 13.8 23.64 7zm-6.6 8.22L3.27 1.44 2 2.72l2.05 2.06C1.91 5.76.59 6.82.36 7l11.63 14.49.01.01.01-.01 3.9-4.86 3.32 3.32 1.27-1.27-3.46-3.46z"/>
</SvgIcon>
);
DeviceSignalWifiOff = pure(DeviceSignalWifiOff);
DeviceSignalWifiOff.displayName = 'DeviceSignalWifiOff';
DeviceSignalWifiOff.muiName = 'SvgIcon';
export default DeviceSignalWifiOff;
|
app/views/component/CommentTable.js | MaxMEllon/comelon | 'use strict';
import R from 'ramda';
import React from 'react';
import SettingStore from '../../stores/SettingStore';
import Comment from './Comment';
import {List, Paper} from 'material-ui';
const isNil = (obj) => obj != null;
const ifSystemComment = (comment) => R.test(/^(\/(.*)){1}/, comment.get('text'));
const No = (comment) => comment.getIn(['attr', 'no']);
const Id = (comment) => comment.getIn(['attr', 'id']);
const generateKey = (no, id) => {
if (isNil(no) || isNil(id)) {
return Math.random().toString(36).slice(-8);
} else {
return `${no}${id}`;
}
};
const Key = (comment) => generateKey(No(comment), Id(comment));
const Size = (components) => R.length(components);
export default class CommentTable extends React.Component {
static get propTypes() {
return {
comments: React.PropTypes.array.isRequired
};
}
static get displayName() {
return 'CommentTable';
}
constructor(props) {
super(props);
this.state = {
systemComment: false,
doTalking: false
};
}
componentDidMount() {
SettingStore.addChangeListener(this.onChangeOption);
}
componentWillUnMount() {
SettingStore.addChangeListener(this.onChangeOption);
}
onChangeOption = () => {
this.setState({
systemComment: SettingStore.getOption().systemComment,
doTalking: SettingStore.getOption().doTalking
});
}
renderComments() {
const ToSkip = R.and(! this.state.systemComment);
let components = [];
const renderComment = c => {
if (ToSkip(ifSystemComment(c))) return;
components.push(<Comment key={Key(c)} index={Size(components)} comment={c} />);
};
R.forEach(renderComment, this.props.comments);
return components;
}
render() {
return (
<List
className='CommentTableComponent'
style={{
marginTop: '64px',
marginBottom: '64px',
width: '100%',
posision: 'relative',
overflow: 'scroll'
}}
> <Paper className='CommentTableBody'>
{this.renderComments()}
</Paper>
</List>
);
}
}
// vim:ft=javascript.jsx
|
static/js/components/MapPage.js | brianhouse/okavango |
// import React, { PropTypes } from 'react'
import React from 'react'
import NotificationPanelContainer from '../containers/NotificationPanelContainer'
import ControlPanelContainer from '../containers/ControlPanelContainer.js'
const MapPage = () => {
var height = {height: window.innerWidth > 768 ? window.innerHeight - 100 : window.innerHeight - 120}
return (
<div className='page' id="mapPage" style={height}>
<ControlPanelContainer pathName={location.pathname}/>
<NotificationPanelContainer/>
</div>
)
}
// MapPage.propTypes = {
// active : PropTypes.bool.isRequired
// }
export default MapPage
|
src/app/components/resourses/planet/Components.js | mazahell/eve-react-app | import React from 'react'
import {connect} from 'react-redux'
import Helper from '../../../helpers'
import { ItemView } from '../../item'
class Components extends React.Component {
render() {
let _inputComponents = this.props.materials.map((val) => {
let itemId = val.item_id
let price = this.props.prices[this.props.type_price_input][itemId]
return (
<ItemView
key={val.item_id}
typeID={val.item_id}
name={val.item_name}
price={price}
quantity={val.quantity}
/>
)
})
let scheme = this.props.scheme
let outputPrice = this.props.prices[this.props.type_price_output][this.props.scheme.typeID]
let blockComponents = (
<div>
<div className='row'>
<div className='col-md-12'>
<table>
<thead>
<tr>
<th>Input materials ({Helper.shortNum(this.props.input_volume)} m3)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ul className='components list'>
{_inputComponents}
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
<div className="row">
<div className='col-md-12'>
<table>
<thead>
<tr>
<th>Output material ({Helper.shortNum(this.props.output_volume)} m3)</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<ul className='components list'>
<ItemView
typeID={scheme.typeID}
name={scheme.schema_name}
price={outputPrice}
quantity={scheme.quantity}
/>
</ul>
</td>
</tr>
</tbody>
</table>
</div>
</div>
</div>
)
return _inputComponents.length ? blockComponents : null
}
}
export default connect(state => state.planetReducer, {})(Components)
|
docs/src/app/components/pages/components/Paper/ExampleCircle.js | ArcanisCz/material-ui | import React from 'react';
import Paper from 'material-ui/Paper';
const style = {
height: 100,
width: 100,
margin: 20,
textAlign: 'center',
display: 'inline-block',
};
const PaperExampleCircle = () => (
<div>
<Paper style={style} zDepth={1} circle={true} />
<Paper style={style} zDepth={2} circle={true} />
<Paper style={style} zDepth={3} circle={true} />
<Paper style={style} zDepth={4} circle={true} />
<Paper style={style} zDepth={5} circle={true} />
</div>
);
export default PaperExampleCircle;
|
src/shared/components/form/textFieldUrl.js | namroodinc/truth-serum | import React from 'react';
import { observer } from 'mobx-react';
import FlatButton from 'material-ui/FlatButton';
import TextField from 'material-ui/TextField';
import parseDomain from 'parse-domain';
import {red500} from 'material-ui/styles/colors';
import DeleteForever from 'material-ui/svg-icons/action/delete';
import dataActions from '../../actions/dataActions';
import Styles from '../../../client/main.scss';
const { twitter } = Styles;
@observer
export default class TextFieldForm extends React.Component {
constructor(props) {
super(props);
this.state = {
value: ''
};
this.handleOnChange = this.handleOnChange.bind(this);
this.handleOnKeyDown = this.handleOnKeyDown.bind(this);
}
handleOnChange = (event, value) => {
this.setState({
value
});
};
handleOnKeyDown = (event) => {
const { formData } = this.props;
const rawDomain = this.state.value;
const parsedDomain = parseDomain(rawDomain);
switch (event.keyCode) {
case 13:
if (parsedDomain) {
dataActions.addUrl(formData, rawDomain, parsedDomain);
this.setState({
value: ''
});
} else {
dataActions.openSnackbar(`${rawDomain} can not be parsed as a domain`);
}
break;
}
};
handleOnDelete = (i) => {
const { formData } = this.props;
dataActions.removeUrl(formData, i);
}
handleGetAlexa = (website) => {
dataActions.getAlexa(`${website.domain}.${website.tld}`);
};
handleGetTwitterLogoColor = (handle) => {
const splitHandle = handle.split('/');
dataActions.getTwitterLogoColor(splitHandle[splitHandle.length-1]);
};
render() {
const { getAlexa, label, value } = this.props;
return (
<div
className="container__row"
>
<h3>
{label}
</h3>
<TextField
hintText={`Enter ${label}`}
onChange={this.handleOnChange}
onKeyDown={this.handleOnKeyDown}
style={{
width: '100%'
}}
value={this.state.value}
/>
{ value.length > 0 ?
<table>
<tbody>
{ value.map((u, i) =>
<tr
key={i}
>
<td>
{u.parsedDomain.domain}.{u.parsedDomain.tld}
</td>
<td>
<span
className="small-text"
>
{u.rawDomain}
</span>
</td>
{ getAlexa &&
<td>
<FlatButton
label="Alexa Ranking"
onClick={this.handleGetAlexa.bind(this, u.parsedDomain)}
/>
</td>
}
<td>
{u.parsedDomain.domain === 'twitter' &&
<FlatButton
backgroundColor={twitter}
label="Twitter Logo Color"
onClick={this.handleGetTwitterLogoColor.bind(this, u.rawDomain)}
/>
}
</td>
<td
className="with--delete"
>
<button
onClick={this.handleOnDelete.bind(this, i)}
>
<DeleteForever
color={red500}
style={{
height: 20,
padding: 0,
width: 20
}}
/>
</button>
</td>
</tr>
)}
</tbody>
</table>
:
<div
className="no-web-urls-found"
>
<div
className="no-publications-found"
>
No Website URLs found.
</div>
</div>
}
</div>
)
}
}
|
src/images/tooth-icon-small.js | kakapo2016-projects/tooth-and-pail | import React from 'react'
import IconButton from 'material-ui/lib/icon-button'
const styles = {
button: {
width: 20, height: 20,
padding: 0,
},
icon: {
width: 20, height: 20,
},
};
const ToothIcon = () => (
<IconButton style={styles.button} iconStyle={styles.icon} iconClassName="tooth-icon" />
);
export default ToothIcon
|
docs/src/app/components/pages/components/List/ExampleSimple.js | pancho111203/material-ui | import React from 'react';
import MobileTearSheet from '../../../MobileTearSheet';
import {List, ListItem} from 'material-ui/List';
import ContentInbox from 'material-ui/svg-icons/content/inbox';
import ActionGrade from 'material-ui/svg-icons/action/grade';
import ContentSend from 'material-ui/svg-icons/content/send';
import ContentDrafts from 'material-ui/svg-icons/content/drafts';
import Divider from 'material-ui/Divider';
import ActionInfo from 'material-ui/svg-icons/action/info';
const ListExampleSimple = () => (
<MobileTearSheet>
<List>
<ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
<ListItem primaryText="Starred" leftIcon={<ActionGrade />} />
<ListItem primaryText="Sent mail" leftIcon={<ContentSend />} />
<ListItem primaryText="Drafts" leftIcon={<ContentDrafts />} />
<ListItem primaryText="Inbox" leftIcon={<ContentInbox />} />
</List>
<Divider />
<List>
<ListItem primaryText="All mail" rightIcon={<ActionInfo />} />
<ListItem primaryText="Trash" rightIcon={<ActionInfo />} />
<ListItem primaryText="Spam" rightIcon={<ActionInfo />} />
<ListItem primaryText="Follow up" rightIcon={<ActionInfo />} />
</List>
</MobileTearSheet>
);
export default ListExampleSimple;
|
src/index.js | jcdesimp/GeoBean | "use strict";
/**
* Root entry file
*
* This file instantiates the root React component and
* mounts it to the DOM
*/
// import styles
import 'normalize.css';
import './css/main.scss';
import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux';
import Store from './js/store';
import App from './js/app';
/**
* Main application entry point
*/
let app_props = {
// set app props
};
ReactDOM.render(
React.createElement(
Provider,
{store: Store},
React.createElement(App, app_props)
),
document.getElementById('app-container')
);
|
src/components/Catalog/Catalog.js | LeraSavchenko/Maysternia | import React from 'react';
import withStyles from 'isomorphic-style-loader/lib/withStyles';
import Link from '../Link';
import s from './Catalog.css';
const Catalog = () =>
(
<div >
<h1 className={s.headerincatalog}>
Каталог продукції
</h1>
<div className={s.catalog}>
<div className={s.inLine}>
<div className={s.pharagraphs}>
<div>
<p className={s.title}>Внутрішнє та зовнішнє оздоблення</p>
<p className={s.title}>Складні архітектурні вироби</p>
<p className={s.title}>Садово-паркове мистецтво</p>
</div>
<div>
<Link className={s.contactButton} to="/catalog">
<div className={s.button}>
Каталог продукції
</div>
</Link>
</div>
</div>
<div>
<div className={s.linewithsmallphotos}>
<img src="./firstingallery.jpg" alt="firstingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}>Портрети</div>
</Link>
</div>
<div>
<div className={s.linewithsmallphotos}>
<img src="./secondingallery.jpg" alt="secondingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}> Скульптури </div>
</Link>
</div>
</div>
<div className={s.inLine}>
<div>
<div className={s.linewithbigphotos}>
<img src="./thirdingallery.jpg" alt="thirdingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}>Каміни</div>
</Link>
</div>
<div>
<div className={s.linewithbigphotos}>
<img src="./fourthingallery.jpg" alt="fourthingallery" href="/" />
</div>
<Link className={s.link} to='/catalog'>
<div className={s.underlined}>Столешні</div>
</Link>
</div>
</div>
</div>
</div>
);
export default withStyles(s)(Catalog);
|
node_modules/[email protected]@antd/es/badge/ScrollNumber.js | ligangwolai/blog | import _extends from 'babel-runtime/helpers/extends';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _createClass from 'babel-runtime/helpers/createClass';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import { createElement, Component } from 'react';
import omit from 'omit.js';
import classNames from 'classnames';
function getNumberArray(num) {
return num ? num.toString().split('').reverse().map(function (i) {
return Number(i);
}) : [];
}
var ScrollNumber = function (_Component) {
_inherits(ScrollNumber, _Component);
function ScrollNumber(props) {
_classCallCheck(this, ScrollNumber);
var _this = _possibleConstructorReturn(this, (ScrollNumber.__proto__ || Object.getPrototypeOf(ScrollNumber)).call(this, props));
_this.state = {
animateStarted: true,
count: props.count
};
return _this;
}
_createClass(ScrollNumber, [{
key: 'getPositionByNum',
value: function getPositionByNum(num, i) {
if (this.state.animateStarted) {
return 10 + num;
}
var currentDigit = getNumberArray(this.state.count)[i];
var lastDigit = getNumberArray(this.lastCount)[i];
// 同方向则在同一侧切换数字
if (this.state.count > this.lastCount) {
if (currentDigit >= lastDigit) {
return 10 + num;
}
return 20 + num;
}
if (currentDigit <= lastDigit) {
return 10 + num;
}
return num;
}
}, {
key: 'componentWillReceiveProps',
value: function componentWillReceiveProps(nextProps) {
var _this2 = this;
if ('count' in nextProps) {
if (this.state.count === nextProps.count) {
return;
}
this.lastCount = this.state.count;
// 复原数字初始位置
this.setState({
animateStarted: true
}, function () {
// 等待数字位置复原完毕
// 开始设置完整的数字
setTimeout(function () {
_this2.setState({
animateStarted: false,
count: nextProps.count
}, function () {
var onAnimated = _this2.props.onAnimated;
if (onAnimated) {
onAnimated();
}
});
}, 5);
});
}
}
}, {
key: 'renderNumberList',
value: function renderNumberList(position) {
var childrenToReturn = [];
for (var i = 0; i < 30; i++) {
var currentClassName = position === i ? 'current' : '';
childrenToReturn.push(React.createElement(
'p',
{ key: i.toString(), className: currentClassName },
i % 10
));
}
return childrenToReturn;
}
}, {
key: 'renderCurrentNumber',
value: function renderCurrentNumber(num, i) {
var position = this.getPositionByNum(num, i);
var removeTransition = this.state.animateStarted || getNumberArray(this.lastCount)[i] === undefined;
return createElement('span', {
className: this.props.prefixCls + '-only',
style: {
transition: removeTransition && 'none',
msTransform: 'translateY(' + -position * 100 + '%)',
WebkitTransform: 'translateY(' + -position * 100 + '%)',
transform: 'translateY(' + -position * 100 + '%)'
},
key: i
}, this.renderNumberList(position));
}
}, {
key: 'renderNumberElement',
value: function renderNumberElement() {
var _this3 = this;
var state = this.state;
if (!state.count || isNaN(state.count)) {
return state.count;
}
return getNumberArray(state.count).map(function (num, i) {
return _this3.renderCurrentNumber(num, i);
}).reverse();
}
}, {
key: 'render',
value: function render() {
var _props = this.props,
prefixCls = _props.prefixCls,
className = _props.className,
style = _props.style,
title = _props.title,
_props$component = _props.component,
component = _props$component === undefined ? 'sup' : _props$component;
// fix https://fb.me/react-unknown-prop
var restProps = omit(this.props, ['count', 'onAnimated', 'component', 'prefixCls']);
var newProps = _extends({}, restProps, { className: classNames(prefixCls, className), title: title });
// allow specify the border
// mock border-color by box-shadow for compatible with old usage:
// <Badge count={4} style={{ backgroundColor: '#fff', color: '#999', borderColor: '#d9d9d9' }} />
if (style && style.borderColor) {
newProps.style.boxShadow = '0 0 0 1px ' + style.borderColor + ' inset';
}
return createElement(component, newProps, this.renderNumberElement());
}
}]);
return ScrollNumber;
}(Component);
export default ScrollNumber;
ScrollNumber.defaultProps = {
prefixCls: 'ant-scroll-number',
count: null,
onAnimated: function onAnimated() {}
}; |
collect-webapp/frontend/src/datamanagement/pages/BackupDataImportPage/NewRecordsDataGrid.js | openforis/collect | import React from 'react'
import { DataGrid, DataGridValueFormatters } from 'common/components'
export const NewRecordsDataGrid = (props) => {
const { keyAttributeColumns, recordsToImport, selectedRecordsToImportIds, stepColumns, onSelectedIdsChange } = props
return (
<DataGrid
className="data-import-new-records"
rows={recordsToImport}
columns={[
{ field: 'entryId', hide: true },
...keyAttributeColumns,
...stepColumns,
{
field: 'recordCreationDate',
headerName: 'dataManagement.backupDataImport.createdOn',
valueFormatter: DataGridValueFormatters.dateTime,
width: 150,
},
{
field: 'recordModifiedDate',
headerName: 'dataManagement.backupDataImport.modifiedOn',
valueFormatter: DataGridValueFormatters.dateTime,
width: 150,
},
{
field: 'recordFilledAttributesCount',
headerName: 'dataManagement.backupDataImport.filledValues',
width: 120,
align: 'right',
},
]}
getRowId={(row) => row.entryId}
checkboxSelection
onSelectedIdsChange={onSelectedIdsChange}
selectionModel={selectedRecordsToImportIds}
/>
)
}
|
app/javascript/src/components/Progress.js | michelson/chaskiq | import React from 'react'
import styled from '@emotion/styled'
import { keyframes } from '@emotion/core'
// based on https://codepen.io/Siddharth11/pen/xbGrpG
const spin = keyframes`
100% {
transform: rotate(360deg);
}
`
const Loader = styled.div`
animation: ${spin} 0.5s infinite linear;
border-top-color: white;
`
export default function CircularIndeterminate ({ size }) {
const sizeVariant = size || 16
return (
<div className="flex justify-center items-center">
<Loader
className={`loader ease-linear rounded-full
border-4 border-t-4 border-gray-200 h-${sizeVariant} w-${sizeVariant}`
}
/>
</div>
)
}
|
examples/reset-values/app.js | RMSAuto/formsy-react | import React from 'react';
import ReactDOM from 'react-dom';
import { Form } from 'formsy-react';
import MyInput from './../components/Input';
import MySelect from './../components/Select';
const user = {
name: 'Sam',
free: true,
hair: 'brown'
};
const App = React.createClass({
submit(data) {
alert(JSON.stringify(data, null, 4));
},
resetForm() {
this.refs.form.reset();
},
render() {
return (
<Formsy.Form ref="form" onSubmit={this.submit} className="form">
<MyInput name="name" title="Name" value={user.name} />
<MyInput name="free" title="Free to hire" type="checkbox" value={user.free} />
<MySelect name="hair" title="Hair" value={user.hair}
options={[
{ value: "black", title: "Black" },
{ value: "brown", title: "Brown" },
{ value: "blonde", title: "Blonde" },
{ value: "red", title: "Red" }
]}
/>
<div className="buttons">
<button type="reset" onClick={this.resetForm}>Reset</button>
<button type="submit">Submit</button>
</div>
</Formsy.Form>
);
}
});
ReactDOM.render(<App/>, document.getElementById('example'));
|
examples/huge-apps/routes/Course/routes/Assignments/components/Sidebar.js | chunwei/react-router | import React from 'react';
import { Link } from 'react-router';
class Sidebar extends React.Component {
render () {
var assignments = COURSES[this.props.params.courseId].assignments
return (
<div>
<h3>Sidebar Assignments</h3>
<ul>
{assignments.map(assignment => (
<li key={assignment.id}>
<Link to={`/course/${this.props.params.courseId}/assignments/${assignment.id}`}>
{assignment.title}
</Link>
</li>
))}
</ul>
</div>
);
}
}
export default Sidebar;
|
client/scripts/subject-form.js | stas-vilchik/bdd | import React from 'react';
import $ from 'jquery';
import Marked from 'marked';
const URL = '/api/subjects';
export default React.createClass({
handleSubmit: function (e) {
e.preventDefault();
var author = React.findDOMNode(this.refs.author).value.trim();
var title = React.findDOMNode(this.refs.title).value.trim();
var description = React.findDOMNode(this.refs.description).value.trim();
if (!description || !author || !title) {
return;
}
if (this.props.subject) {
this.handleSubjectModify({ id: this.props.subject.id, author: author, description: description, title: title });
} else {
this.handleSubjectCreate({ author: author, description: description, title: title });
}
this.props.onSubmit();
React.findDOMNode(this.refs.author).value = '';
React.findDOMNode(this.refs.title).value = '';
React.findDOMNode(this.refs.description).value = '';
},
handleSubjectCreate: function (subject) {
$.ajax({
url: URL,
dataType: 'json',
type: 'POST',
data: JSON.stringify(subject),
contentType: 'application/json',
error: function (xhr, status, err) {
console.error(URL, status, err.toString());
}.bind(this)
});
},
handleSubjectModify: function (subject) {
$.ajax({
url: URL + '/' + subject.id,
dataType: 'json',
type: 'PUT',
data: JSON.stringify(subject),
contentType: 'application/json',
error: function (xhr, status, err) {
console.error(URL, status, err.toString());
}.bind(this)
});
},
cancel(e) {
e.preventDefault();
this.props.onCancel();
},
render: function () {
var author = this.props.subject ? this.props.subject.author : null;
var title = this.props.subject ? this.props.subject.title : null;
var description = this.props.subject ? this.props.subject.description : null;
var cancelButton = this.props.subject ?
<input onClick={this.cancel} className="btn btn-default" type="submit" value="Cancel"/> : null;
return (
<form onSubmit={this.handleSubmit}>
<div className="form-group">
<label htmlFor="form-author">Your Name</label>
<input className="form-control" id="form-author" type="text" ref="author" defaultValue={author}/>
</div>
<div className="form-group">
<label htmlFor="form-title">Title</label>
<input className="form-control" id="form-title" type="text" ref="title" defaultValue={title}/>
</div>
<div className="form-group">
<label htmlFor="form-description">Description</label>
<textarea className="form-control" id="form-description" type="text"
placeholder="Describe the topic you want to present" ref="description"
defaultValue={description}/>
</div>
<input className="btn btn-primary" type="submit" value="Post"/>
{cancelButton}
</form>
);
}
}); |
src/Parser/MistweaverMonk/Modules/Traits/MistsOfSheilun.js | Yuyz0112/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import { formatNumber } from 'common/format';
import Module from 'Parser/Core/Module';
import StatisticBox, { STATISTIC_ORDER } from 'Main/StatisticBox';
const debug = false;
class MistsOfSheilun extends Module {
// Implement Mists of Sheilun, Celestial Breath, and Refreshing Jade Wind
procsMistsOfSheilun = 0;
healsMistsOfSheilun = 0;
healingMistsOfSheilun = 0;
overhealingMistsOfSheilun = 0;
on_initialized() {
if(!this.owner.error) {
this.active = this.owner.selectedCombatant.traitsBySpellId[SPELLS.MISTS_OF_SHEILUN_TRAIT.id] === 1;
}
}
on_byPlayer_applybuff(event) {
const spellId = event.ability.guid;
if(spellId === SPELLS.MISTS_OF_SHEILUN_BUFF.id) {
this.procsMistsOfSheilun++;
}
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
if(spellId === SPELLS.MISTS_OF_SHEILUN.id) {
this.healsMistsOfSheilun++;
this.healingMistsOfSheilun += event.amount;
if(event.overheal) {
this.overhealingMistsOfSheilun += event.overheal;
}
}
}
statistic() {
const avgMistsOfSheilunHealing = this.healingMistsOfSheilun / this.healsMistsOfSheilun || 0;
const avgMistsOfSheilunTargets = this.healsMistsOfSheilun / this.procsMistsOfSheilun || 0;
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.MISTS_OF_SHEILUN_TRAIT.id} />}
value={`${formatNumber(avgMistsOfSheilunHealing)}`}
label={(
<dfn data-tip={`You healed an average of ${(avgMistsOfSheilunTargets).toFixed(2)} targets per Mists of Sheilun proc over your ${this.procsMistsOfSheilun} procs.`}>
Average Healing
</dfn>
)}
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
on_finished() {
if(debug) {
console.log('Mists of Sheilun Procs: ' + this.procsMistsOfSheilun);
console.log('Avg Heals per Procs: ' + (this.healsMistsOfSheilun / this.procsMistsOfSheilun));
console.log('Avg Heals Amount: ' + (this.healingMistsOfSheilun / this.healsMistsOfSheilun));
}
}
}
export default MistsOfSheilun;
|
images/client/components/image_detail.js | cristianobento/udemy-meteor-react | // Create our image list component
// Import React
import React from 'react';
import ImageScore from './image_score';
// Create our component
const ImageDetail = (props) => {
// props.image => this is the image object
// props.image.title
// props.image.link
return(
<li className="media list-group-item">
<div className="media-left">
<img src={props.image.link} alt={props.image.title} title={props.image.title} />
</div>
<div className="media-body">
<h4 className="media-heading">{props.image.title}</h4>
<p>{props.image.description}</p>
<ImageScore ups={props.image.ups} downs={props.image.downs} />
</div>
</li>
);
};
// Export our component
export default ImageDetail; |
src/svg-icons/av/hd.js | w01fgang/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let AvHd = (props) => (
<SvgIcon {...props}>
<path d="M19 3H5c-1.11 0-2 .9-2 2v14c0 1.1.89 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-8 12H9.5v-2h-2v2H6V9h1.5v2.5h2V9H11v6zm2-6h4c.55 0 1 .45 1 1v4c0 .55-.45 1-1 1h-4V9zm1.5 4.5h2v-3h-2v3z"/>
</SvgIcon>
);
AvHd = pure(AvHd);
AvHd.displayName = 'AvHd';
AvHd.muiName = 'SvgIcon';
export default AvHd;
|
src/Console.js | sgnh/react-console-wrapper | import React from 'react';
const { array, string, bool, shape } = React.PropTypes;
const Console = (props) => {
if (props.assert.assertion) {
console.assert(props.assert.assertion, props.assert.message);
}
if (props.clear) {
console.clear();
}
if (props.count) {
console.count(props.count);
}
if (props.error) {
console.error(props.error);
}
if (props.group) {
console.group();
}
if (props.groupColapsed) {
console.groupCollapsed();
}
if (props.groupEnd) {
console.groupEnd();
}
if (props.info) {
console.info(props.info);
}
if (props.log) {
console.log(props.log);
}
if (props.table.data.length) {
console.table(props.table.data, props.table.columns);
}
if (props.time) {
console.time(props.time);
}
if (props.timeEnd) {
console.timeEnd(props.timeEnd);
}
if (props.trace) {
console.trace();
}
if (props.warn) {
console.warn(props.warn);
}
return null;
};
Console.propTypes = {
assert: shape({
assertion: bool,
message: string,
}),
clear: bool,
count: string,
error: string,
group: bool,
groupColapsed: bool,
groupEnd: bool,
info: string,
log: string,
table: shape({
data: array,
columns: array,
}),
time: string,
timeEnd: string,
trace: bool,
warn: string,
};
Console.defaultProps = {
assert: {
assertion: false,
message: '',
},
clear: false,
count: '',
error: '',
group: false,
groupColapsed: false,
groupEnd: false,
info: '',
log: '',
table: {
data: [],
columns: [],
},
time: '',
timeEnd: '',
trace: false,
warn: '',
};
export default Console;
|
src/Parser/Priest/Holy/Modules/Items/Tier21_4set.js | hasseboulen/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import Analyzer from 'Parser/Core/Analyzer';
import calculateEffectiveHealing from 'Parser/Core/calculateEffectiveHealing';
import Combatants from 'Parser/Core/Modules/Combatants';
import ItemHealingDone from 'Main/ItemHealingDone';
const HOLY_PRIEST_TIER21_4SET_BUFF_EXPIRATION_BUFFER = 150; // the buff expiration can occur several MS before the heal event is logged, this is the buffer time that an IoL charge may have dropped during which it will still be considered active.
const HEALING_BONUS = 0.3;
class Tier21_4set extends Analyzer {
static dependencies = {
combatants: Combatants,
};
healing = 0;
procUsed = 0;
on_initialized() {
this.active = this.combatants.selected.hasBuff(SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id);
}
on_byPlayer_heal(event) {
const spellId = event.ability.guid;
const hasBuff = this.combatants.selected.hasBuff(SPELLS.HOLY_PRIEST_EVERLASTING_HOPE.id, event.timestamp, HOLY_PRIEST_TIER21_4SET_BUFF_EXPIRATION_BUFFER);
if (spellId === SPELLS.PRAYER_OF_HEALING.id && hasBuff) {
this.healing += calculateEffectiveHealing(event, HEALING_BONUS);
}
}
on_byPlayer_cast(event) {
const spellId = event.ability.guid;
const hasBuff = this.combatants.selected.hasBuff(SPELLS.HOLY_PRIEST_EVERLASTING_HOPE.id, event.timestamp, HOLY_PRIEST_TIER21_4SET_BUFF_EXPIRATION_BUFFER);
if (spellId === SPELLS.PRAYER_OF_HEALING.id && hasBuff) {
this.procUsed += 1;
}
}
item() {
return {
id: `spell-${SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id}`,
icon: <SpellIcon id={SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id} />,
title: <SpellLink id={SPELLS.HOLY_PRIEST_T21_4SET_BONUS_BUFF.id} />,
result: (
<dfn data-tip={`A total of ${this.procUsed} procs were used.`}>
<ItemHealingDone amount={this.healing} />
</dfn>
),
};
}
}
export default Tier21_4set;
|
circleci-demo-javascript-express-master/client/modules/App/components/Footer/Footer.js | RTHMaK/RPGOne | import React from 'react';
import { FormattedMessage } from 'react-intl';
// Import Style
import styles from './Footer.css';
// Import Images
import bg from '../../header-bk.png';
export function Footer() {
return (
<div style={{ background: `#FFF url(${bg}) center` }} className={styles.footer}>
<p>© 2016 · Hashnode · LinearBytes Inc.</p>
<p><FormattedMessage id="twitterMessage" /> : <a href="https://twitter.com/@mern_io" target="_Blank">@mern_io</a></p>
</div>
);
}
export default Footer;
|
docs/src/sections/NavSection.js | jesenko/react-bootstrap | import React from 'react';
import Anchor from '../Anchor';
import PropTable from '../PropTable';
import ReactPlayground from '../ReactPlayground';
import Samples from '../Samples';
export default function NavSection() {
return (
<div className="bs-docs-section">
<h2 className="page-header">
<Anchor id="navs">Navs</Anchor> <small>Nav, NavItem</small>
</h2>
<p>Navs come in two styles, <code>pills</code> and <code>tabs</code>. Disable a tab by adding <code>disabled</code>.</p>
<ReactPlayground codeText={Samples.NavBasic} />
<h3><Anchor id="navs-dropdown">Dropdown</Anchor></h3>
<p>Add dropdowns using the <code>NavDropdown</code> component.</p>
<ReactPlayground codeText={Samples.NavDropdown} />
<h3><Anchor id="navs-stacked">Stacked</Anchor></h3>
<p>They can also be <code>stacked</code> vertically.</p>
<ReactPlayground codeText={Samples.NavStacked} />
<h3><Anchor id="navs-justified">Justified</Anchor></h3>
<p>They can be <code>justified</code> to take the full width of their parent.</p>
<ReactPlayground codeText={Samples.NavJustified} />
<h3><Anchor id="navs-props">Props</Anchor></h3>
<h4><Anchor id="navs-props-nav">Nav</Anchor></h4>
<PropTable component="Nav"/>
<h4><Anchor id="navs-props-navitem">NavItem</Anchor></h4>
<PropTable component="NavItem"/>
</div>
);
}
|
src/client/components/SortSelector/SortSelector.js | busyorg/busy | import React from 'react';
import PropTypes from 'prop-types';
import { FormattedMessage } from 'react-intl';
import Popover from '../Popover';
import PopoverMenu, { PopoverMenuItem } from '../PopoverMenu/PopoverMenu';
import './SortSelector.less';
export default class SortSelector extends React.Component {
static Item = PopoverMenuItem;
static propTypes = {
sort: PropTypes.string,
children: PropTypes.node,
onChange: PropTypes.func,
};
static defaultProps = {
sort: null,
children: null,
onChange: () => {},
};
constructor(props) {
super(props);
this.state = {
visible: false,
};
this.handleVisibleChange = this.handleVisibleChange.bind(this);
this.handleSelect = this.handleSelect.bind(this);
}
handleVisibleChange() {
this.setState(prevState => ({ visible: !prevState.visible }));
}
handleSelect(current) {
this.setState(
{
visible: false,
},
() => {
this.props.onChange(current);
},
);
}
render() {
const { sort } = this.props;
const { visible } = this.state;
const currentSort = React.Children.map(this.props.children, c => c).find(
c => c.key === `.$${sort}`,
);
return (
<div className="SortSelector">
<span className="SortSelector__title">
<FormattedMessage id="sort_by" defaultMessage="Sort by" />
</span>
<Popover
trigger="click"
placement="bottom"
visible={visible}
onVisibleChange={this.handleVisibleChange}
content={
<PopoverMenu bold onSelect={this.handleSelect}>
{this.props.children}
</PopoverMenu>
}
>
<span className="SortSelector__current">
{currentSort && currentSort.props && currentSort.props.children}
<i className="iconfont icon-unfold" />
</span>
</Popover>
</div>
);
}
}
|
App/Components/SignUp.js | OUCHUNYU/Ralli | import usersApi from '../Utils/usersApi'
import GoogleMap from './GoogleMap'
import Firebase from 'firebase'
import React, { Component } from 'react';
import {
StyleSheet,
PropTypes,
View,
TextInput,
Text,
Dimensions,
TouchableHighlight,
Image,
AppRegistry
} from 'react-native';
let styles = StyleSheet.create({
header: {
marginBottom: 20,
fontSize: 18,
textAlign: 'center',
color: 'black'
},
wrapper: {
flex: 1
},
container: {
justifyContent: 'center',
marginTop: 50,
padding: 20,
width: null,
height: null
},
title: {
fontSize: 30,
alignSelf: 'flex-start',
marginBottom: 30,
marginTop: 25,
color: 'white',
backgroundColor: 'rgba(0,0,0,0)'
},
buttonText: {
fontSize: 18,
color: 'white',
alignSelf: 'center'
},
button: {
height: 36,
backgroundColor: '#6600ff',
borderColor: '#6600ff',
borderWidth: 1,
borderRadius: 8,
marginBottom: 10,
alignSelf: 'stretch',
justifyContent: 'center'
},
input: {
padding: 4,
height: 40,
borderColor: 'white',
borderWidth: 1,
borderRadius: 5,
margin: 5,
marginBottom: 20,
flex: 1,
color: 'white',
alignSelf: 'stretch',
backgroundColor: 'rgba(0,0,0,0.4)'
},
label: {
fontSize: 14,
backgroundColor: 'rgba(0,0,0,0)',
color: 'white'
},
spacer: {
marginVertical: 100,
backgroundColor: 'rgba(0,0,0,0)'
},
headerbar: {
flex: 1,
alignItems: 'center',
flexDirection: 'row'
}
});
class SignUp extends Component {
constructor(props) {
super(props);
this.db = new Firebase('https://ralli.firebaseio.com/users');
this.state = {
username: '',
email: '',
password: ''
};
}
signupOnPress() {
usersApi.createNewUser(this.state.email, this.state.password, this.state.username).then((res) => {
usersApi.loginUser(this.state.email, this.state.password).then((res) => {
this.db.push({
username: this.state.username,
email: this.state.email.toLowerCase(),
avatarUrl: res.password.profileImageURL,
})
usersApi.getUserByEmail(this.state.email.toLowerCase()).then((res) => {
this.props.navigator.push({
title: 'Rallies Nearby',
component: GoogleMap,
passProps: {userData: res.val()[Object.keys(res.val())[0]], userId: Object.keys(res.val())[0]}
})
})
this.setState({
username: '',
email: '',
password: ''
});
})
})
}
render() {
return (
<Image source={require('./Common/bokeh-lights.png')} style={styles.container}>
<View>
<View style={styles.headerbar}>
<Image style={styles.image} source={require('./Common/small-icon.png')} />
<Text style={styles.title}> Create Rally Account</Text>
</View>
<Text style={styles.label}>Username:</Text>
<TextInput
style={styles.input}
value={this.state.username}
onChangeText={(text) => this.setState({username: text})}/>
<Text style={styles.label}>Email:</Text>
<TextInput
style={styles.input}
value={this.state.email}
onChangeText={(text) => this.setState({email: text})}/>
<Text style={styles.label}>Password:</Text>
<TextInput
secureTextEntry={true}
style={styles.input}
value={this.state.password}
onChangeText={(text) => this.setState({password: text})}/>
<TouchableHighlight style={styles.button} onPress={this.signupOnPress.bind(this)} underlayColor='#99d9f4'>
<Text style={styles.buttonText}>Create Account</Text>
</TouchableHighlight>
<Text style={styles.spacer}> </Text>
</View>
</Image>
)
}
}
export default SignUp
|
client/src/components/LoginStatusMessage.js | wapjude/labify | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Button, StyleSheet, Text, View } from 'react-native';
import { NavigationActions } from 'react-navigation';
const styles = StyleSheet.create({
welcome: {
fontSize: 20,
textAlign: 'center',
margin: 10,
},
});
const LoginStatusMessage = ({ isLoggedIn, dispatch }) => {
if (!isLoggedIn) {
return <Text>Please log in</Text>;
}
return (
<View>
<Text style={styles.welcome}>
{'You are "logged in" right now'}
</Text>
<Button
onPress={() =>
dispatch(NavigationActions.navigate({ routeName: 'Profile' }))}
title="Profile"
/>
</View>
);
};
LoginStatusMessage.propTypes = {
isLoggedIn: PropTypes.bool.isRequired,
dispatch: PropTypes.func.isRequired,
};
const mapStateToProps = state => ({
isLoggedIn: state.auth.isLoggedIn,
});
export default connect(mapStateToProps)(LoginStatusMessage); |
blueocean-material-icons/src/js/components/svg-icons/maps/directions-bike.js | kzantow/blueocean-plugin | import React from 'react';
import SvgIcon from '../../SvgIcon';
const MapsDirectionsBike = (props) => (
<SvgIcon {...props}>
<path d="M15.5 5.5c1.1 0 2-.9 2-2s-.9-2-2-2-2 .9-2 2 .9 2 2 2zM5 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5zm5.8-10l2.4-2.4.8.8c1.3 1.3 3 2.1 5.1 2.1V9c-1.5 0-2.7-.6-3.6-1.5l-1.9-1.9c-.5-.4-1-.6-1.6-.6s-1.1.2-1.4.6L7.8 8.4c-.4.4-.6.9-.6 1.4 0 .6.2 1.1.6 1.4L11 14v5h2v-6.2l-2.2-2.3zM19 12c-2.8 0-5 2.2-5 5s2.2 5 5 5 5-2.2 5-5-2.2-5-5-5zm0 8.5c-1.9 0-3.5-1.6-3.5-3.5s1.6-3.5 3.5-3.5 3.5 1.6 3.5 3.5-1.6 3.5-3.5 3.5z"/>
</SvgIcon>
);
MapsDirectionsBike.displayName = 'MapsDirectionsBike';
MapsDirectionsBike.muiName = 'SvgIcon';
export default MapsDirectionsBike;
|
app/src/components/Tooltip/Tooltip.js | WoundedPixels/us-population | // @flow
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import * as d3 from 'd3';
import './Tooltip.css';
class Tooltip extends Component {
static update(content: Object = <empty />) {
const tooltip = d3.select('div#tooltip');
const mouse = { x: d3.event.pageX, y: d3.event.pageY };
const tooltipDimensions = tooltip.node().getBoundingClientRect();
const left = Math.min(
mouse.x + 5,
window.innerWidth - tooltipDimensions.width - 5,
);
tooltip
.style('left', `${left}px`)
.style('top', `${mouse.y - tooltipDimensions.height - 5}px`)
.style('display', content.type !== 'empty' ? 'block' : 'none');
ReactDOM.render(content, document.getElementById('tooltip'));
}
render() {
return (
<div className="Tooltip" id="tooltip" style={{ display: 'none' }}>
{this.props.children}
</div>
);
}
}
export default Tooltip;
|
examples/sidebar/app.js | dyzhu12/react-router | import React from 'react';
import { history } from 'react-router/lib/HashHistory';
import { Router, Route, Link } from 'react-router';
import data from './data';
var Category = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<h1>{category.name}</h1>
{this.props.children || (
<p>{category.description}</p>
)}
</div>
);
}
});
var CategorySidebar = React.createClass({
render() {
var category = data.lookupCategory(this.props.params.category);
return (
<div>
<Link to="/">◀︎ Back</Link>
<h2>{category.name} Items</h2>
<ul>
{category.items.map(item => (
<li><Link to={`/category/${category.name}/${item.name}`}>{item.name}</Link></li>
))}
</ul>
</div>
);
}
});
var Item = React.createClass({
render() {
var { category, item } = this.props.params;
var menuItem = data.lookupItem(category, item);
return (
<div>
<h1>{menuItem.name}</h1>
<p>${menuItem.price}</p>
</div>
);
}
});
var Index = React.createClass({
render() {
return (
<div>
<h1>Sidebar</h1>
<p>
Routes can have multiple components, so that all portions of your UI
can participate in the routing.
</p>
</div>
);
}
});
var IndexSidebar = React.createClass({
render() {
return (
<div>
<h2>Categories</h2>
<ul>
{data.getAll().map(category => (
<li><Link to={`/category/${category.name}`}>{category.name}</Link></li>
))}
</ul>
</div>
);
}
});
var App = React.createClass({
render() {
return (
<div>
<div className="Sidebar">
{this.props.sidebar || <IndexSidebar/>}
</div>
<div className="Content">
{this.props.content || <Index/>}
</div>
</div>
);
}
});
React.render((
<Router history={history}>
<Route path="/" component={App}>
<Route path="category/:category" components={{content: Category, sidebar: CategorySidebar}}>
<Route path=":item" component={Item}/>
</Route>
</Route>
</Router>
), document.getElementById('example'));
|
packages/@vega/core/src/schema/previews/FootnotePreview/index.js | VegaPublish/vega-studio | import React from 'react'
import styles from './FootnotePreview.css'
export default function FootnotePreview() {
return <span className={styles.footnoteInline}>*</span>
}
|
client/scripts/routes.js | amitava82/radiole | /**
* Created by amitava on 30/01/16.
*/
import React from 'react';
import {Route, IndexRoute, IndexRedirect} from 'react-router';
import get from 'lodash/get';
//import {ROUTE_MESSAGES} from './constants';
//import {setLoginMessage} from './redux/modules/session';
import {
HomeContainer
} from './routes/home';
import {
WatchlistContainer
} from './routes/watchlist';
import {
ReportContainer
} from './routes/report';
import {
LoginContainer
} from './routes/login';
import {
SettingsContainer
} from './routes/settings'
import Error from './routes/misc/Error';
import App from './app';
export default (store) => {
function ensureLoggedIn(nextState, replace, cb){
const {session: {isLoggedIn, user}} = store.getState();
if(!isLoggedIn){
replace({pathname: '/login'});
}else if(!user.email && this.path !== '/settings'){
replace({pathname: '/settings'});
}
cb();
}
return (
<Route path="/" component={App}>
<IndexRedirect to="/home"/>
<Route path="/login" component={LoginContainer} />
<Route path="/home" component={HomeContainer} onEnter={ensureLoggedIn} />
<Route path="/watching" component={WatchlistContainer} onEnter={ensureLoggedIn} />
<Route path="/watching/:id" component={ReportContainer} onEnter={ensureLoggedIn} />
<Route path="/settings" component={SettingsContainer} onEnter={ensureLoggedIn} />
<Route path="/error" component={Error} />
</Route>
);
}; |
scripts/apps/authoring/authoring/directives/SendItem.js | jerome-poisson/superdesk-client-core | import _ from 'lodash';
import React from 'react';
import {PreviewModal} from '../previewModal';
SendItem.$inject = ['$q', 'api', 'desks', 'notify', 'authoringWorkspace',
'superdeskFlags', '$location', 'macros', '$rootScope', 'deployConfig',
'authoring', 'send', 'editorResolver', 'confirm', 'archiveService',
'preferencesService', 'multi', 'datetimeHelper', 'config', 'privileges', 'storage', 'modal', 'gettext', 'urls'];
export function SendItem($q, api, desks, notify, authoringWorkspace,
superdeskFlags, $location, macros, $rootScope, deployConfig,
authoring, send, editorResolver, confirm, archiveService,
preferencesService, multi, datetimeHelper, config, privileges, storage, modal, gettext, urls) {
return {
scope: {
item: '=',
view: '=',
orig: '=',
_beforeSend: '&beforeSend',
_editable: '=editable',
_publish: '&publish',
_action: '=action',
mode: '@',
},
controller: function() {
this.userActions = {
send_to: 'send_to',
publish: 'publish',
duplicate_to: 'duplicate_to',
externalsource_to: 'externalsource_to',
};
},
controllerAs: 'vm',
templateUrl: 'scripts/apps/authoring/views/send-item.html',
link: function sendItemLink(scope, elem, attrs, ctrl) {
scope.mode = scope.mode || 'authoring';
scope.desks = null;
scope.stages = null;
scope.macros = null;
scope.userDesks = null;
scope.allDesks = null;
scope.task = null;
scope.selectedDesk = null;
scope.selectedStage = null;
scope.selectedMacro = null;
scope.beforeSend = scope._beforeSend || $q.when;
scope.destination_last = {send_to: null, publish: null, duplicate_to: null};
scope.origItem = angular.extend({}, scope.item);
scope.subscribersWithPreviewConfigured = [];
// key for the storing last desk/stage in the user preferences for send action.
var PREFERENCE_KEY = 'destination:active';
// key for the storing last user action (send to/publish) in the storage.
var USER_ACTION_KEY = 'send_to_user_action';
scope.$watch('item', activateItem);
scope.$watch(send.getConfig, activateConfig);
scope.publish = function() {
scope.loading = true;
var result = scope._publish();
return $q
.resolve(result)
.then(null, (e) => $q.reject(false))
.finally(() => {
scope.loading = false;
});
};
function activateConfig(config, oldConfig) {
if (scope.mode !== 'authoring' && config !== oldConfig) {
scope.isActive = !!config;
scope.item = scope.isActive ? {} : null;
scope.multiItems = multi.count ? multi.getItems() : null;
scope.config = config;
activate();
}
}
function activateItem(item) {
if (scope.mode === 'monitoring') {
superdeskFlags.flags.fetching = !!item;
}
scope.isActive = !!item;
activate();
}
function activate() {
if (scope.isActive) {
api.query('subscribers')
.then((res) => {
const allSubscribers = res['_items'];
scope.subscribersWithPreviewConfigured = allSubscribers
.map(
(subscriber) => {
subscriber.destinations = subscriber.destinations.filter(
(destination) => typeof destination.preview_endpoint_url === 'string'
&& destination.preview_endpoint_url.length > 0
);
return subscriber;
}
)
.filter((subscriber) => subscriber.destinations.length > 0);
});
desks
.initialize()
.then(fetchDesks)
.then(initialize)
.then(setDesksAndStages);
}
}
scope.preview = function() {
if (scope.$parent.save_enabled() === true) {
modal.alert({
headerText: gettext('Preview'),
bodyText: gettext(
'In order to preview the item, save the changes first.'
),
});
} else {
modal.createCustomModal()
.then(({openModal, closeModal}) => {
openModal(
<PreviewModal
subscribersWithPreviewConfigured={scope.subscribersWithPreviewConfigured}
documentId={scope.item._id}
urls={urls}
closeModal={closeModal}
gettext={gettext}
/>
);
});
}
};
scope.close = function() {
if (scope.mode === 'monitoring') {
superdeskFlags.flags.fetching = false;
}
if (scope.$parent.views) {
scope.$parent.views.send = false;
} else if (scope.item) {
scope.item = null;
}
$location.search('fetch', null);
if (scope.config) {
scope.config.reject();
}
};
scope.selectDesk = function(desk) {
scope.selectedDesk = _.cloneDeep(desk);
scope.selectedStage = null;
fetchStages();
fetchMacros();
};
scope.selectStage = function(stage) {
scope.selectedStage = stage;
};
scope.selectMacro = function(macro) {
if (scope.selectedMacro === macro) {
scope.selectedMacro = null;
} else {
scope.selectedMacro = macro;
}
};
scope.send = function(open) {
updateLastDestination();
return runSend(open);
};
scope.$on('item:nextStage', (_e, data) => {
if (scope.item && scope.item._id === data.itemId) {
var oldStage = scope.selectedStage;
scope.selectedStage = data.stage;
scope.send().then((sent) => {
if (!sent) {
scope.selectedStage = oldStage;
}
});
}
});
// events on which panel should close
var closePanelEvents = ['item:spike', 'broadcast:preview'];
angular.forEach(closePanelEvents, (event) => {
scope.$on(event, shouldClosePanel);
});
/**
* @description Closes the opened 'duplicate/send To' panel if the same item getting
* spiked or any item is opening for authoring.
* @param {Object} event
* @param {Object} data - contains the item(=itemId) that was spiked or {item: null} when
* any item opened for authoring (utilising, 'broadcast:preview' with {item: null})
*/
function shouldClosePanel(event, data) {
if (
(scope.config != null && data != null && _.includes(scope.config.itemIds, data.item))
|| (data == null || data.item == null)
) {
scope.close();
}
}
/*
* Returns true if Destination field and Send button needs to be displayed, false otherwise.
* @returns {Boolean}
*/
scope.showSendButtonAndDestination = function() {
if (scope.itemActions) {
var preCondition = scope.mode === 'ingest' ||
scope.mode === 'personal' ||
scope.mode === 'monitoring' ||
scope.mode === 'authoring' &&
scope.isSendEnabled() &&
scope.itemActions.send ||
scope.mode === 'spike';
if (scope.currentUserAction === ctrl.userActions.publish) {
return preCondition && scope.showSendAndPublish();
}
return preCondition;
}
};
/*
* Returns true if Send and Send and Continue button needs to be disabled, false otherwise.
* @returns {Boolean}
*/
scope.disableSendButton = function() {
return !scope.selectedDesk ||
scope.mode !== 'ingest' && scope.selectedStage && scope.mode !== 'spike' &&
(_.get(scope, 'item.task.stage') === scope.selectedStage._id ||
_.includes(_.map(scope.multiItems, 'task.stage'), scope.selectedStage._id));
};
/*
* Returns true if user is not a member of selected desk, false otherwise.
* @returns {Boolean}
*/
scope.disableFetchAndOpenButton = function() {
if (scope.selectedDesk) {
var _isNonMember = _.isEmpty(_.find(desks.userDesks, {_id: scope.selectedDesk._id}));
return _isNonMember;
}
};
/**
* Returns true if Publish Schedule needs to be displayed, false otherwise.
*/
scope.showPublishSchedule = function() {
return scope.item && archiveService.getType(scope.item) !== 'ingest' &&
scope.item.type !== 'composite' && !scope.item.embargo_date && !scope.item.embargo_time &&
['published', 'killed', 'corrected', 'recalled'].indexOf(scope.item.state) === -1 &&
canPublishOnDesk();
};
/**
* Returns true if timezone needs to be displayed, false otherwise.
*/
scope.showTimezone = function() {
return (scope.item.publish_schedule || scope.item.embargo) &&
(scope.showPublishSchedule() || scope.showEmbargo());
};
/**
* Returns true if Embargo needs to be displayed, false otherwise.
*/
scope.showEmbargo = function() {
// If user doesn't have embargo privilege then don't display embargo fields
if (!privileges.privileges.embargo) {
return false;
}
if (config.ui && config.ui.publishEmbargo === false) {
return false;
}
var prePublishCondition = scope.item && archiveService.getType(scope.item) !== 'ingest' &&
scope.item.type !== 'composite' && !scope.item.publish_schedule_date &&
!scope.item.publish_schedule_time;
if (prePublishCondition && authoring.isPublished(scope.item)) {
if (['published', 'corrected'].indexOf(scope.item.state) >= 0) {
return scope.origItem.embargo;
}
// for published states other than 'published', 'corrected'
return false;
}
return prePublishCondition;
};
/**
* Returns true if Embargo needs to be displayed, false otherwise.
*/
scope.isEmbargoEditable = function() {
var publishedCondition = authoring.isPublished(scope.item) && scope.item.schedule_settings &&
scope.item.schedule_settings.utc_embargo &&
datetimeHelper.greaterThanUTC(scope.item.schedule_settings.utc_embargo);
return scope.item && scope.item._editable &&
(!authoring.isPublished(scope.item) || publishedCondition);
};
/**
* Send the content to different desk/stage
* @param {Boolean} open - True to open the item.
* @return {Object} promise
*/
function runSend(open) {
scope.loading = true;
scope.item.sendTo = true;
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
if (scope.mode === 'authoring') {
return sendAuthoring(deskId, stageId, scope.selectedMacro);
} else if (scope.mode === 'archive') {
return sendContent(deskId, stageId, scope.selectedMacro, open);
} else if (scope.config) {
scope.config.promise.finally(() => {
scope.loading = false;
});
return scope.config.resolve({
desk: deskId,
stage: stageId,
macro: scope.selectedMacro ? scope.selectedMacro.name : null,
open: open,
});
} else if (scope.mode === 'ingest') {
return sendIngest(deskId, stageId, scope.selectedMacro, open);
}
}
/**
* Enable Disable the Send and Publish button.
* Send And Publish is enabled using `superdesk.config.js`.
*/
scope.showSendAndPublish = () => !config.ui || angular.isUndefined(config.ui.sendAndPublish) ||
config.ui.sendAndPublish;
/**
* Check if the Send and Publish is allowed or not.
* Following conditions are to met for Send and Publish action
* - Item is not Published i.e. not state Published, Corrected, Killed or Scheduled
* - Selected destination (desk/stage) should be different from item current location (desk/stage)
* - Mode should be authoring
* - Publish Action is allowed on that item.
* @return {Boolean}
*/
scope.canSendAndPublish = function() {
if (scope.mode !== 'authoring' || !scope.item) {
return false;
}
// Selected destination desk should be different from item current location desk
var isDestinationChanged = scope.selectedDesk && scope.item.task.desk !== scope.selectedDesk._id;
return scope.showSendAndPublish() && !authoring.isPublished(scope.item) &&
isDestinationChanged && scope.mode === 'authoring' && scope.itemActions.publish;
};
/**
* Returns true if 'send' button should be displayed. Otherwise, returns false.
* @return {boolean}
*/
scope.isSendEnabled = () => scope.item && !authoring.isPublished(scope.item);
/*
* Send the current item to different desk or stage and publish the item from new location.
*/
scope.sendAndPublish = function() {
return runSendAndPublish();
};
/*
* Returns true if 'send' action is allowed, otherwise false
* @returns {Boolean}
*/
scope.canSendItem = function() {
var itemType = [], typesList;
if (scope.multiItems) {
angular.forEach(scope.multiItems, (item) => {
itemType[item._type] = 1;
});
typesList = Object.keys(itemType);
itemType = typesList.length === 1 ? typesList[0] : null;
}
return scope.mode === 'authoring' || itemType === 'archive' || scope.mode === 'spike' ||
(scope.mode === 'monitoring' && _.get(scope, 'config.action') === scope.vm.userActions.send_to);
};
/**
* Check if it is allowed to publish on current desk
* @returns {Boolean}
*/
function canPublishOnDesk() {
return !(isAuthoringDesk() && config.features.noPublishOnAuthoringDesk);
}
/**
* If the action is correct and kill then the publish privilege needs to be checked.
*/
scope.canPublishItem = function() {
if (!scope.itemActions || !canPublishOnDesk()) {
return false;
}
if (scope._action === 'edit') {
return scope.item ? !scope.item.flags.marked_for_not_publication && scope.itemActions.publish :
scope.itemActions.publish;
} else if (scope._action === 'correct') {
return privileges.privileges.publish && scope.itemActions.correct;
} else if (scope._action === 'kill') {
return privileges.privileges.publish && scope.itemActions.kill;
}
return false;
};
/**
* Set the User Action.
*/
scope.setUserAction = function(action) {
if (scope.currentUserAction === action) {
return;
}
scope.currentUserAction = action;
storage.setItem(USER_ACTION_KEY, action);
setDesksAndStages();
};
/**
* Checks if a given item is valid to publish
*
* @param {Object} item story to be validated
* @return {Object} promise
*/
const validatePublish = (item) => api.save('validate', {act: 'publish', type: item.type, validate: item});
/**
* Sends and publishes the current item in scope
* First checks if the item is dirty and pops up save dialog if needed
* Then checks if the story is valid to publish before sending
* Then sends the story to the destination
* Then publishes it
*
* @param {Object} item story to be validated
* @return {Object} promise
*/
const runSendAndPublish = () => {
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
// send releases lock, increment version.
return scope.beforeSend({action: 'Send and Publish'})
.then(() => validatePublish(scope.item)
.then((validationResult) => {
if (_.get(validationResult, 'errors.length')) {
for (var i = 0; i < validationResult.errors.length; i++) {
notify.error('\'' + _.trim(validationResult.errors[i]) + '\'');
}
return $q.reject();
}
return sendAuthoring(deskId, stageId, scope.selectedMacro, true)
.then((item) => {
scope.loading = true;
// open the item for locking and publish
return authoring.open(scope.item._id, false);
})
.then((item) => {
// update the original item to avoid 412 error.
scope.orig._etag = scope.item._etag = item._etag;
scope.orig._locked = scope.item._locked = item._locked;
scope.orig.task = scope.item.task = item.task;
// change the desk location.
$rootScope.$broadcast('desk_stage:change');
// if locked then publish
if (item._locked) {
return scope.publish();
}
return $q.reject();
})
.then((result) => {
if (result) {
authoringWorkspace.close(false);
}
})
.catch((error) => {
notify.error(gettext('Failed to send and publish.'));
});
})
.finally(() => {
scope.loading = false;
})
);
};
/**
* Run the macro and returns to the modified item.
* @param {Object} item
* @param {String} macro
* @return {Object} promise
*/
function runMacro(item, macro) {
if (macro) {
return macros.call(macro, item, true).then((res) => angular.extend(item, res));
}
return $q.when(item);
}
/**
* Send to different location from authoring.
* @param {String} deskId - selected desk Id
* @param {String} stageId - selected stage Id
* @param {String} macro - macro to apply
* @return {Object} promise
*/
function sendAuthoring(deskId, stageId, macro) {
var msg;
scope.loading = true;
return runMacro(scope.item, macro)
.then((item) => api.find('tasks', scope.item._id)
.then((task) => {
scope.task = task;
msg = 'Send';
return scope.beforeSend({action: msg});
})
.then((result) => {
if (result && result._etag) {
scope.task._etag = result._etag;
}
return api.save('move', {}, {task: {desk: deskId, stage: stageId}}, scope.item);
})
.then((value) => {
notify.success(gettext('Item sent.'));
if (scope.currentUserAction === ctrl.userActions.send_to) {
// Remember last destination desk and stage for send_to.
var lastDestination = scope.destination_last[scope.currentUserAction];
if (!lastDestination ||
(lastDestination.desk !== deskId || lastDestination.stage !== stageId)) {
updateLastDestination();
}
}
authoringWorkspace.close(true);
return true;
}, (err) => {
if (err) {
if (angular.isDefined(err.data._message)) {
notify.error(err.data._message);
} else if (angular.isDefined(err.data._issues['validator exception'])) {
notify.error(err.data._issues['validator exception']);
}
}
}))
.finally(() => {
scope.loading = false;
});
}
/**
* Update the preferences to store last destinations
* @param {String} key
*/
function updateLastDestination() {
var updates = {};
var deskId = scope.selectedDesk._id;
var stageId = scope.selectedStage._id || scope.selectedDesk.incoming_stage;
updates[PREFERENCE_KEY] = {desk: deskId, stage: stageId};
preferencesService.update(updates, PREFERENCE_KEY);
}
/**
* Send content to different desk and stage
* @param {String} deskId
* @param {String} stageId
* @param {String} macro
* @param {Boolean} open - If true open the item.
*/
function sendContent(deskId, stageId, macro, open) {
var finalItem;
scope.loading = true;
return api.save('duplicate', {}, {desk: scope.item.task.desk}, scope.item)
.then((item) => api.find('archive', item._id))
.then((item) => runMacro(item, macro))
.then((item) => {
finalItem = item;
return api.find('tasks', item._id);
})
.then((_task) => {
scope.task = _task;
api.save('tasks', scope.task, {
task: _.extend(scope.task.task, {desk: deskId, stage: stageId}),
});
})
.then(() => {
notify.success(gettext('Item sent.'));
scope.close();
if (open) {
$location.url('/authoring/' + finalItem._id);
} else {
$rootScope.$broadcast('item:fetch');
}
})
.finally(() => {
scope.loading = false;
});
}
/**
* Fetch content from ingest to a different desk and stage
* @param {String} deskId
* @param {String} stageId
* @param {String} macro
* @param {Boolean} open - If true open the item.
*/
function sendIngest(deskId, stageId, macro, open) {
scope.loading = true;
return send.oneAs(scope.item, {
desk: deskId,
stage: stageId,
macro: macro ? macro.name : macro,
}).then((finalItem) => {
notify.success(gettext('Item fetched.'));
if (open) {
authoringWorkspace.edit(finalItem);
} else {
$rootScope.$broadcast('item:fetch');
}
})
.finally(() => {
scope.loading = false;
});
}
/**
* Fetch desk and last selected desk and stage for send_to and publish action
* @return {Object} promise
*/
function fetchDesks() {
return desks.initialize()
.then(() => {
// get all desks
scope.allDesks = desks.desks._items;
// get user desks
return desks.fetchCurrentUserDesks();
})
.then((deskList) => {
scope.userDesks = deskList;
return preferencesService.get(PREFERENCE_KEY);
})
.then((result) => {
if (result) {
scope.destination_last.send_to = {
desk: result.desk,
stage: result.stage,
};
scope.destination_last.duplicate_to = {
desk: result.desk,
stage: result.stage,
};
}
});
}
/**
* Set the last selected desk based on the user action.
* To be called after currentUserAction is set
*/
function setDesksAndStages() {
if (!scope.currentUserAction) {
return;
}
// set the desks for desk filter
if (scope.currentUserAction === ctrl.userActions.publish) {
scope.desks = scope.userDesks;
} else {
scope.desks = scope.allDesks;
}
if (scope.mode === 'ingest') {
scope.selectDesk(desks.getCurrentDesk());
} else {
// set the last selected desk or current desk
var itemDesk = desks.getItemDesk(scope.item);
var lastDestination = scope.destination_last[scope.currentUserAction];
if (itemDesk) {
if (lastDestination && !_.isNil(lastDestination.desk)) {
scope.selectDesk(desks.deskLookup[lastDestination.desk]);
} else {
scope.selectDesk(itemDesk);
}
} else if (lastDestination && !_.isNil(lastDestination.desk)) {
scope.selectDesk(desks.deskLookup[lastDestination.desk]);
} else {
scope.selectDesk(desks.getCurrentDesk());
}
}
}
/**
* Set stages and last selected stage.
*/
function fetchStages() {
if (!scope.selectedDesk) {
return;
}
scope.stages = desks.deskStages[scope.selectedDesk._id];
var stage = null;
if (scope.currentUserAction === ctrl.userActions.send_to ||
scope.currentUserAction === ctrl.userActions.duplicate_to) {
var lastDestination = scope.destination_last[scope.currentUserAction];
if (lastDestination) {
stage = _.find(scope.stages, {_id: lastDestination.stage});
} else if (scope.item.task && scope.item.task.stage) {
stage = _.find(scope.stages, {_id: scope.item.task.stage});
}
}
if (!stage) {
stage = _.find(scope.stages, {_id: scope.selectedDesk.incoming_stage});
}
scope.selectedStage = stage;
}
/**
* Fetch macros for the selected desk.
*/
function fetchMacros() {
if (!scope.selectedDesk) {
return;
}
macros.getByDesk(scope.selectedDesk.name)
.then((_macros) => {
scope.macros = _macros;
});
}
/**
* Initialize Item Actios and User Actions.
*/
function initialize() {
initializeItemActions();
initializeUserAction();
}
/**
* Initialize User Action
*/
function initializeUserAction() {
// default user action
scope.currentUserAction = storage.getItem(USER_ACTION_KEY) || ctrl.userActions.send_to;
if (scope.orig || scope.item) {
if (scope.config && scope.config.action === 'externalsourceTo') {
scope.currentUserAction = ctrl.userActions.externalsource_to;
}
// if the last action is send to but item is published open publish tab.
if (scope.config && scope.config.action === 'duplicateTo') {
scope.currentUserAction = ctrl.userActions.duplicate_to;
}
if (scope.currentUserAction === ctrl.userActions.send_to &&
scope.canPublishItem() && !scope.isSendEnabled()) {
scope.currentUserAction = ctrl.userActions.publish;
} else if (scope.currentUserAction === ctrl.userActions.publish &&
!scope.canPublishItem() && scope.showSendButtonAndDestination()) {
scope.currentUserAction = ctrl.userActions.send_to;
} else if (scope.currentUserAction === ctrl.userActions.publish &&
isAuthoringDesk() && noPublishOnAuthoringDesk()) {
scope.currentUserAction = ctrl.userActions.send_to;
}
}
}
/**
* The itemActions defined in parent scope (Authoring Directive) is made accessible via this method.
* scope.$parent isn't used as send-item directive is used in multiple places and has different
* hierarchy.
*/
function initializeItemActions() {
if (scope.orig || scope.item) {
scope.itemActions = authoring.itemActions(scope.orig || scope.item);
}
}
/**
* Test if desk of current item is authoring type.
*
* @return {Boolean}
*/
function isAuthoringDesk() {
if (!_.get(scope, 'item.task.desk')) {
return false;
}
const desk = desks.getItemDesk(scope.item);
return desk && desk.desk_type === 'authoring';
}
/**
* Test if noPublishOnAuthoringDesk config is active.
*
* @return {Boolean}
*/
function noPublishOnAuthoringDesk() {
return config.features.noPublishOnAuthoringDesk;
}
// update actions on item save
scope.$watch('orig._current_version', initializeItemActions);
},
};
}
|
js/src/modals/FirstRun/Welcome/welcome.js | nipunn1313/parity | // Copyright 2015-2017 Parity Technologies (UK) Ltd.
// This file is part of Parity.
// Parity is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
// Parity is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
// You should have received a copy of the GNU General Public License
// along with Parity. If not, see <http://www.gnu.org/licenses/>.
import React, { Component } from 'react';
import { FormattedMessage } from 'react-intl';
import imagesEthcore from '~/../assets/images/parity-logo-white.svg';
import styles from '../firstRun.css';
const LOGO_STYLE = {
float: 'right',
maxWidth: '10em',
height: 'auto',
margin: '0 1.5em'
};
export default class FirstRun extends Component {
render () {
return (
<div className={ styles.welcome }>
<img
src={ imagesEthcore }
alt='Parity Ltd.'
style={ LOGO_STYLE }
/>
<p>
<FormattedMessage
id='firstRun.welcome.greeting'
defaultMessage='Welcome to Parity, the fastest and simplest way to run your node.'
/>
</p>
<p>
<FormattedMessage
id='firstRun.welcome.description'
defaultMessage='As part of a new installation, the next few steps will guide you through the process of setting up your Parity instance and your associated accounts. Our aim is to make it as simple as possible and to get you up and running in record-time, so please bear with us. Once completed you will have -'
/>
</p>
<div>
<ul>
<li>
<FormattedMessage
id='firstRun.welcome.step.privacy'
defaultMessage='Understood our privacy policy & terms of operation'
/>
</li>
<li>
<FormattedMessage
id='firstRun.welcome.step.account'
defaultMessage='Created your first Parity account'
/>
</li>
<li>
<FormattedMessage
id='firstRun.welcome.step.recovery'
defaultMessage='Have the ability to recover your account'
/>
</li>
</ul>
</div>
<p>
<FormattedMessage
id='firstRun.welcome.next'
defaultMessage='Click Next to continue your journey.'
/>
</p>
</div>
);
}
}
|
fixtures/dom/src/components/fixtures/input-change-events/index.js | leexiaosi/react | import React from 'react';
import FixtureSet from '../../FixtureSet';
import TestCase from '../../TestCase';
import RangeKeyboardFixture from './RangeKeyboardFixture';
import RadioClickFixture from './RadioClickFixture';
import RadioGroupFixture from './RadioGroupFixture';
import InputPlaceholderFixture from './InputPlaceholderFixture';
class InputChangeEvents extends React.Component {
render() {
return (
<FixtureSet
title="Input change events"
description="Tests proper behavior of the onChange event for inputs">
<TestCase
title="Range keyboard changes"
description={`
Range inputs should fire onChange events for keyboard events
`}>
<TestCase.Steps>
<li>Focus range input</li>
<li>change value via the keyboard arrow keys</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onKeyDown</code> call count should be equal to
the <code>onChange</code> call count.
</TestCase.ExpectedResult>
<RangeKeyboardFixture />
</TestCase>
<TestCase
title="Radio input clicks"
description={`
Radio inputs should only fire change events when the checked
state changes.
`}
resolvedIn="16.0.0">
<TestCase.Steps>
<li>Click on the Radio input (or label text)</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onChange</code> call count should remain at 0
</TestCase.ExpectedResult>
<RadioClickFixture />
</TestCase>
<TestCase
title="Uncontrolled radio groups"
description={`
Radio inputs should fire change events when the value moved to
another named input
`}
introducedIn="15.6.0">
<TestCase.Steps>
<li>Click on the "Radio 2"</li>
<li>Click back to "Radio 1"</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onChange</code> call count should equal 2
</TestCase.ExpectedResult>
<RadioGroupFixture />
</TestCase>
<TestCase
title="Inputs with placeholders"
description={`
Text inputs with placeholders should not trigger changes
when the placeholder is altered
`}
resolvedIn="15.0.0"
resolvedBy="#5004"
affectedBrowsers="IE9+">
<TestCase.Steps>
<li>Click on the Text input</li>
<li>Click on the "Change placeholder" button</li>
</TestCase.Steps>
<TestCase.ExpectedResult>
The <code>onChange</code> call count should remain at 0
</TestCase.ExpectedResult>
<InputPlaceholderFixture />
</TestCase>
</FixtureSet>
);
}
}
export default InputChangeEvents;
|
src/routes.js | ivanflorentin/ProvideUI | import {Route} from 'react-router'
import React from 'react'
export default function (modelDef, models) {
const mainPath = modelDef.modelName
const modelProperName = modelDef.modelName[0].toUpperCase() +
modelDef.modelName.substring(1)
const edit = 'edit' + modelProperName
const list = 'list' + modelProperName
const display = 'display' + modelProperName
return (
<Route key={mainPath} path={mainPath}>
<Route path='edit' component={models[edit]}/>
<Route path='list' component={models[list]}/>
<Route path='display' component={models[display]}/>
</Route>
)
}
|
app/desktop/ToolbarButtonPopover/index.js | christianalfoni/webpack-bin | import React from 'react';
import {Decorator as Cerebral} from 'cerebral-view-react';
import ToolbarButton from '../ToolbarButton';
import classNames from 'classnames';
import styles from './styles.css';
@Cerebral()
class ToolbarButtonPopover extends React.Component {
onArrowBoxClick(e) {
e.stopPropagation();
}
renderPopup() {
const className = classNames(styles.arrowBox, {
[styles.arrowBoxRight]: this.props.right,
[styles.arrowBoxMiddle]: this.props.middle
});
return (
<div className={styles.popup}>
<div
className={className}
onClick={(e) => this.onArrowBoxClick(e)}>
<div className={styles.contentBox}>
{this.props.children}
</div>
</div>
</div>
);
}
render() {
return (
<div className={classNames(styles.wrapper, {[this.props.className]: this.props.className})}>
<ToolbarButton
active={this.props.show}
icon={this.props.icon}
title={this.props.title}
onClick={this.props.onClick}/>
{this.props.show ? this.renderPopup() : null}
</div>
);
}
}
export default ToolbarButtonPopover;
|
client/components/charts/balance-chart.js | ZeHiro/kresus | import React from 'react';
import Dygraph from 'dygraphs';
import { debug, round2, getChartsDefaultColors, translate as $t } from '../../helpers';
import ChartComponent from './chart-base';
import DiscoveryMessage from '../ui/discovery-message';
function createChartBalance(chartId, account, operations, theme) {
if (account === null) {
debug('ChartComponent: no account');
return;
}
let ops = operations.slice().sort((a, b) => +a.date - +b.date);
function makeKey(date) {
return `${date.getFullYear()}-${date.getMonth() + 1}-${date.getDate()}`;
}
let opmap = new Map();
// Fill all dates.
const DAY = 1000 * 60 * 60 * 24;
let firstDate = ops.length ? +ops[0].date : Date.now();
firstDate = ((firstDate / DAY) | 0) * DAY;
let today = ((Date.now() / DAY) | 0) * DAY;
for (; firstDate <= today; firstDate += DAY) {
opmap.set(makeKey(new Date(firstDate)), 0);
}
// Date (day) -> cumulated sum of amounts for this day (scalar).
for (let o of ops) {
let key = makeKey(o.date);
if (opmap.has(key)) {
opmap.set(key, opmap.get(key) + o.amount);
}
}
let balance = account.initialBalance;
let csv = 'Date,Balance\n';
for (let [date, amount] of opmap) {
balance += amount;
csv += `${date},${round2(balance)}\n`;
}
/* eslint-disable no-new */
// Create the chart
let chartsColors = getChartsDefaultColors(theme);
return new Dygraph(document.getElementById(chartId), csv, {
color: chartsColors.LINES,
axisLineColor: chartsColors.AXIS,
axes: {
x: {
axisLabelFormatter: date => {
// Undefined means the default locale
let defaultLocale;
return date.toLocaleDateString(defaultLocale, {
year: '2-digit',
month: 'short'
});
}
}
},
fillGraph: true,
showRangeSelector: true,
rangeSelectorPlotFillGradientColor: chartsColors.LINES,
rangeSelectorPlotStrokeColor: chartsColors.LINES,
// 6 months (180 days) window
dateWindow: [today - DAY * 180, today],
// 4px dashes separated by a 2px blank space
gridLinePattern: [4, 2]
});
/* eslint-enable no-new */
}
export default class BalanceChart extends ChartComponent {
redraw() {
this.container = createChartBalance(
'barchart',
this.props.account,
this.props.operations,
this.props.theme
);
}
render() {
return (
<React.Fragment>
<DiscoveryMessage message={$t('client.charts.balance_desc')} />
<div id="barchart" style={{ width: '100%' }} />
</React.Fragment>
);
}
}
|
node_modules/react-bootstrap/es/MediaList.js | superKaigon/TheCave | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import classNames from 'classnames';
import React from 'react';
import { bsClass, getClassSet, splitBsProps } from './utils/bootstrapUtils';
var MediaList = function (_React$Component) {
_inherits(MediaList, _React$Component);
function MediaList() {
_classCallCheck(this, MediaList);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
MediaList.prototype.render = function render() {
var _props = this.props,
className = _props.className,
props = _objectWithoutProperties(_props, ['className']);
var _splitBsProps = splitBsProps(props),
bsProps = _splitBsProps[0],
elementProps = _splitBsProps[1];
var classes = getClassSet(bsProps);
return React.createElement('ul', _extends({}, elementProps, {
className: classNames(className, classes)
}));
};
return MediaList;
}(React.Component);
export default bsClass('media-list', MediaList); |
src/components/TableMortgage.js | nickgreengithub/mortgagecalc | import React from 'react';
import { connect } from 'react-redux';
import payments from '../selectors/payments';
import Table from './Table';
export const TableMortgage = (({payments, className})=> {
let output=payments.slice(1)
.filter(year=>year.balance>0 || year.interestYearly>0)
.reduce((acc, year, index) => {
return {
interestTotal:acc.interestTotal+year.interestYearly,
overpaymentTotal:acc.overpaymentTotal+year.overpayment,
rows:acc.rows.concat([
[year.partial?year.partial + "m":index+1,
Math.round(year.interestYearly||0),
Math.round(year.overpayment),
Math.round(year.balance)]])
}
}, {interestTotal:0, overpaymentTotal:0, rows:[]});
return <Table className={className}
headings={["Years", "Interest", "Edited Column", "Balance"]}
rows={output.rows}
totals={[" ",Math.round(output.interestTotal), Math.round(output.overpaymentTotal)," "]} />;
});
export default connect(state=>({ ...payments(state) }))(TableMortgage)
|
src/parser/shaman/elemental/modules/core/FlameShock.js | fyruna/WoWAnalyzer | import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellIcon from 'common/SpellIcon';
import SpellLink from 'common/SpellLink';
import { formatNumber, formatPercentage } from 'common/format';
import Analyzer from 'parser/core/Analyzer';
import Enemies from 'parser/shared/modules/Enemies';
import StatisticBox, { STATISTIC_ORDER } from 'interface/others/StatisticBox';
class FlameShock extends Analyzer {
static dependencies = {
enemies: Enemies,
};
badLavaBursts = 0;
get uptime() {
return this.enemies.getBuffUptime(SPELLS.FLAME_SHOCK.id) / this.owner.fightDuration;
}
on_byPlayer_cast(event) {
if(event.ability.guid !== SPELLS.LAVA_BURST.id) {
return;
}
const target = this.enemies.getEntity(event);
if(target && !target.hasBuff(SPELLS.FLAME_SHOCK.id)){
this.badLavaBursts++;
}
}
suggestions(when) {
when(this.uptime).isLessThan(0.99)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Your <SpellLink id={SPELLS.FLAME_SHOCK.id} /> uptime can be improved.</span>)
.icon(SPELLS.FLAME_SHOCK.icon)
.actual(`${formatPercentage(actual)}% uptime`)
.recommended(`>${formatPercentage(recommended)}% is recommended`)
.regular(recommended - 0.05).major(recommended - 0.15);
});
when(this.badLavaBursts).isGreaterThan(0)
.addSuggestion((suggest, actual, recommended) => {
return suggest(<span>Make sure to apply <SpellLink id={SPELLS.FLAME_SHOCK.id} /> to your target, so your <SpellLink id={SPELLS.LAVA_BURST.id} /> is guaranteed to critically strike.</span>)
.icon(SPELLS.LAVA_BURST.icon)
.actual(`${formatNumber(this.badLavaBursts)} Lava Burst casts without Flame Shock DOT`)
.recommended(`0 is recommended`)
.major(recommended+1);
});
}
statistic() {
return (
<StatisticBox
icon={<SpellIcon id={SPELLS.FLAME_SHOCK.id} />}
value={`${formatPercentage(this.uptime)} %`}
label="Uptime"
tooltip="Flame Shock Uptime"
/>
);
}
statisticOrder = STATISTIC_ORDER.OPTIONAL();
}
export default FlameShock;
|
node_modules/redbox-react/examples/react-transform-catch-errors/index.js | edsrupp/eds-mess | import React from 'react'
import App from './components/App'
const root = document.getElementById('root')
React.render(<App />, root)
|
react-redux-tutorial/todo-reflux/src/components/todo.js | react-scott/react-learn | import React from 'react'
import Reflux from 'reflux'
import ReactMixin from 'react-mixin'
import store from '../stores/store'
import actions from '../actions/actions'
export default class Todo extends React.Component{
//组件渲染完成后,通过action获取所有的数组,刷新绑定到this.state上
componentDidMount() {
actions.getAll();
}
add(){
var item =this.refs.item.value;
this.refs.item.value='';
actions.add(item);
}
remove(i){
actions.remove(i);
}
render() {
//items用于乘放li的集合
let items;
if(this.state.list){
items=this.state.list.map( (item,i)=> {
//设置key是因为react的diff算法,是通过key来计算最小变化的
return <li key={i}>
{item.name}
<button onClick={this.remove.bind(this,i)}>remove</button>
</li>
})
}
return (
<div>
<input type="text" ref="item"/>
<button onClick={this.add.bind(this)}>add</button>
<ul>
{items}
</ul>
</div>
)
}
}
// ES6 mixin写法,通过mixin将store的与组件连接,功能是监听store带来的state变化并刷新到this.state
ReactMixin.onClass(Todo, Reflux.connect(store));
|
src/features/rekit-tools/TestCoveragePage.js | supnate/rekit-portal | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { Alert, Button } from 'antd';
import history from '../../common/history';
export class TestCoveragePage extends Component {
static propTypes = {
home: PropTypes.object.isRequired,
};
handleRunTestsClick() {
history.push('/tools/tests');
}
render() {
return (
<div className="rekit-tools-test-coverage-page">
<h2>Test coverage report
{this.props.home.testCoverage && <Button type="ghost" onClick={this.handleRunTestsClick}>Re-run tests</Button>}
</h2>
{this.props.home.testCoverage
? <iframe src="/coverage/lcov-report/index.html" />
:
<div className="no-coverage">
<Alert message="No test coverage report found." showIcon type="info" />
<p>You need to run all tests for the project to generate test coverage reoport.</p>
<p><Button type="primary" onClick={this.handleRunTestsClick}>Run tests</Button></p>
</div>
}
</div>
);
}
}
/* istanbul ignore next */
function mapStateToProps(state) {
return {
home: state.home,
};
}
export default connect(
mapStateToProps,
)(TestCoveragePage);
|
src/utils/createContextWrapper.js | gianpaj/react-bootstrap | import React from 'react';
/**
* Creates new trigger class that injects context into overlay.
*/
export default function createContextWrapper(Trigger, propName) {
return function(contextTypes) {
class ContextWrapper extends React.Component {
getChildContext() {
return this.props.context;
}
render() {
// Strip injected props from below.
const {wrapped, context, ...props} = this.props;
return React.cloneElement(wrapped, props);
}
}
ContextWrapper.childContextTypes = contextTypes;
class TriggerWithContext {
render() {
const props = {...this.props};
props[propName] = this.getWrappedOverlay();
return (
<Trigger {...props}>
{this.props.children}
</Trigger>
);
}
getWrappedOverlay() {
return (
<ContextWrapper
context={this.context}
wrapped={this.props[propName]}
/>
);
}
}
TriggerWithContext.contextTypes = contextTypes;
return TriggerWithContext;
};
}
|
NavigationReactNativeWeb/sample/twitter/createStateNavigator.js | grahammendick/navigation | import React from 'react';
import {Platform} from 'react-native';
import {StateNavigator} from 'navigation';
import {NavigationStack} from 'navigation-react-native';
export default () => {
const stateNavigator = new StateNavigator([
{key: 'home', route: '{tab?}', defaults: {tab: 'home'}},
{key: 'notifications', route: 'x/y'},
{key: 'tweet', route: 'tweet/{id}', trackCrumbTrail: true, defaultTypes: {id: 'number'}},
{key: 'timeline', route: 'timeline/{id}', trackCrumbTrail: true, defaultTypes: {id: 'number'}}
], NavigationStack.HistoryManager && new NavigationStack.HistoryManager(url => {
const {state, data} = stateNavigator.parseLink(url);
let fluent = stateNavigator.fluent().navigate('home');
if (state.key === 'home' && data.tab === 'notifications')
stateNavigator.historyManager.addHistory(fluent.url, true);
return fluent.navigate(state.key, data).url;
}));
if (Platform.OS === 'web') stateNavigator.start();
return stateNavigator;
}
|
classic/src/scenes/wbfa/generated/FASCheck.pro.js | wavebox/waveboxapp | import React from 'react'
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome'
import { faCheck } from '@fortawesome/pro-solid-svg-icons/faCheck'
export default class FASCheck extends React.Component {
render () {
return (<FontAwesomeIcon {...this.props} icon={faCheck} />)
}
}
|
packages/wix-style-react/src/Page/test/examples/SomeContentComponent2.js | wix/wix-style-react | import React from 'react';
import PropTypes from 'prop-types';
import times from '../../../utils/operators/times';
export const LongTextContent = props => {
const pages = times(props.numOfPages, (x, i) => (
<div key={i}>
<div>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam facilisis
molestie magna vitae pellentesque. Ut elementum accumsan nibh, ut
faucibus velit. Vestibulum at mollis justo. Vestibulum ante ipsum primis
in faucibus orci luctus et ultrices posuere cubilia Curae; In sapien
odio, hendrerit a iaculis ut, venenatis in ligula. Vestibulum suscipit
egestas augue, nec mattis est mollis et. Curabitur id eleifend leo.
Fusce tempor efficitur commodo.
<br />
<br />
Cras porta augue non erat imperdiet ornare. Aliquam aliquam elit nec
erat ultricies, ac blandit purus efficitur. Suspendisse sagittis id nibh
eget pulvinar. Phasellus congue ultricies interdum. Mauris vel dolor at
diam feugiat imperdiet feugiat varius eros. Aenean accumsan interdum
massa vitae semper. Maecenas tincidunt ut lectus a fringilla. In
eleifend ante in tellus consequat vestibulum. Fusce lacinia turpis quis
turpis semper venenatis. Donec faucibus felis nisi, non maximus augue
mattis ac. Ut erat sem, finibus vel gravida sed, hendrerit ac nibh.
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam et
egestas lectus. Ut vitae est maximus, viverra sem et, pharetra diam.
<br />
<br />
Vivamus quis nunc maximus elit ullamcorper ullamcorper non sit amet
metus. Mauris consequat tortor ac ante vestibulum lacinia. Vestibulum
molestie risus purus, nec faucibus odio iaculis vitae. Integer erat
magna, interdum et venenatis vel, aliquet id nunc. Vivamus nec pharetra
dui. Nam sed quam ultricies, molestie dui a, tempus felis. Pellentesque
tincidunt tortor eu tempus porttitor. Nam vitae dapibus lacus, a gravida
ligula. Vestibulum eget pulvinar mauris. Vestibulum ante ipsum primis in
faucibus orci luctus et ultrices posuere cubilia Curae; In hac habitasse
platea dictumst. Sed ultrices bibendum urna, elementum condimentum est
faucibus et. Aenean a hendrerit ipsum. Sed aliquam ligula sed magna
commodo, sit amet fringilla urna scelerisque. Phasellus at felis sed
neque euismod tincidunt vitae id leo.
<br />
<br />
Donec vel felis id mauris iaculis posuere eget eu purus. Duis id libero
dolor. Vivamus nec ornare nunc. Ut efficitur quis sem quis consectetur.
Suspendisse et justo ac sem rhoncus posuere et eget quam. Phasellus sit
amet viverra nulla, vel tincidunt ante. Duis nec commodo lorem.
<br />
<br />
Proin orci nisl, facilisis ut efficitur sit amet, sollicitudin et metus.
Nunc dictum laoreet convallis. Praesent iaculis consequat elit non
consectetur. In risus ex, efficitur non tempor ac, suscipit ut nisi.
Etiam vel vehicula eros. Sed molestie, metus sed tristique fringilla,
tortor metus facilisis justo, sit amet blandit dolor urna eget diam.
Etiam nec lorem cursus nisl finibus venenatis. Ut consequat dui non
pharetra fringilla. Nulla facilisi.
{i < props.numOfPages - 1 && [<br key="br1" />, <br key="br2" />]}
</div>
</div>
));
return <div>{pages}</div>;
};
LongTextContent.defaultProps = {
numOfPages: 5,
};
export default class SomeContentComponent2 extends React.Component {
static propTypes = {
shortContent: PropTypes.bool,
stretchVertically: PropTypes.bool,
};
getBody() {
return;
}
render() {
return (
<div
style={{
backgroundColor: 'white',
minHeight: this.props.stretchVertically ? 'inherit' : undefined,
}}
>
<LongTextContent numOfPages={this.props.shortContent ? 1 : undefined} />
</div>
);
}
}
|
app/scenes/Schedule/components/Talk/index.js | brentvatne/react-conf-app | // @flow
import React, { Component } from 'react';
import {
Animated,
Easing,
PixelRatio,
StyleSheet,
Text,
TouchableHighlight,
View,
} from 'react-native';
import Icon from '@expo/vector-icons/Ionicons';
import Avatar from '../../../../components/Avatar';
import theme from '../../../../theme';
import { lighten } from '../../../../utils/color';
type Status = 'past' | 'present' | 'future';
// ==============================
// TALK SEPARATOR
// ==============================
export function TalkSeparator({ status }: { status: Status }) {
let barColor = theme.color.gray20;
if (status === 'past') barColor = lighten(theme.color.blue, 60);
else if (status === 'present') barColor = theme.color.blue;
return (
<View
style={{
height: 1 / PixelRatio.get(),
flexDirection: 'row',
alignItems: 'stretch',
}}
underlayColor="white"
>
<View style={{ backgroundColor: barColor, width: 5 }} />
<View
style={{ backgroundColor: 'white', width: theme.fontSize.default }}
/>
<View style={{ backgroundColor: theme.color.gray20, flexGrow: 1 }} />
</View>
);
}
// ==============================
// TALK STATUSBAR
// ==============================
export function TalkStatusBar({ status, ...props }: { status: Status }) {
let barColor = theme.color.gray20;
if (status === 'past') barColor = lighten(theme.color.blue, 60);
if (status === 'present') barColor = theme.color.blue;
return (
<View
style={{
backgroundColor: barColor,
width: 5,
}}
{...props}
/>
);
}
// ==============================
// ICON HELPERS
// ==============================
function Indicator({ color, icon }) {
return (
<View
style={{
alignItems: 'center',
backgroundColor: color,
borderRadius: 14,
marginRight: 7,
height: 14,
justifyContent: 'center',
width: 14,
}}
>
<Icon
color="white"
name={icon}
size={14}
style={{ backgroundColor: 'transparent', marginBottom: -1 }}
/>
</View>
);
}
function LightningSubtitle({ text, ...props }) {
return (
<View style={styles.subtitle} {...props}>
<Indicator color={theme.color.yellow} icon="ios-flash" />
<Text style={styles.subtitleText}>{text}</Text>
</View>
);
}
function KeynoteSubtitle({ text, ...props }) {
return (
<View style={styles.subtitle} {...props}>
<Indicator color={theme.color.blue} icon="ios-key" />
<Text style={styles.subtitleText}>{text}</Text>
</View>
);
}
// ==============================
// TALK ROW
// ==============================
type Props = {
keynote: boolean,
lightning: boolean,
onPress: () => mixed,
speaker: Object,
startTime: string,
status: Status,
title: string,
};
const animationDefault = val => ({
toValue: val,
duration: 666,
easing: Easing.inOut(Easing.quad),
});
export default class Talk extends Component {
props: Props;
animValue: Animated.Value;
static defaultProps = {
status: 'future',
};
constructor(props: Props) {
super(props);
this.animValue = new Animated.Value(0);
}
componentDidMount() {
this.cycleAnimation();
}
cycleAnimation() {
Animated.sequence([
Animated.timing(this.animValue, animationDefault(1)),
Animated.timing(this.animValue, animationDefault(0)),
]).start(() => this.cycleAnimation());
}
render() {
const {
keynote,
lightning,
onPress,
speaker,
startTime,
status,
title,
...props
} = this.props;
const isPresent = status === 'present';
const touchableProps = {
activeOpacity: 1,
onPress: onPress,
style: styles.touchable,
underlayColor: theme.color.gray05,
};
const animatedStyle = {
transform: [
{
translateX: this.animValue.interpolate({
inputRange: [0, 1],
outputRange: [0, 4],
}),
},
],
};
// subtitle variants
let subtitleText = startTime;
if (speaker) subtitleText += ` - ${speaker.name}`;
let subtitle = (
<Text style={[styles.subtitle, styles.subtitleText]}>
{subtitleText}
</Text>
);
if (lightning) subtitle = <LightningSubtitle text={speaker.name} />;
else if (keynote) subtitle = <KeynoteSubtitle text={startTime} />;
// avatar variants
const avatar = Array.isArray(speaker)
? speaker.map((s, i) => {
const pull = i + 1 !== speaker.length
? { backgroundColor: 'transparent', marginRight: -16 }
: null;
return (
<Avatar key={s.name} source={s.avatar} style={pull} size={50} />
);
})
: <Avatar source={speaker && speaker.avatar} />;
// const avatar = <Avatar source={speaker.avatar} />;
return (
<TouchableHighlight {...touchableProps} {...props}>
<View style={[styles.base, styles['base__' + status]]}>
<TalkStatusBar status={status}>
{isPresent &&
<Animated.View style={animatedStyle}>
<Icon
color={theme.color.blue}
name="md-arrow-dropright"
size={34}
style={styles.statusbarIcon}
/>
</Animated.View>}
</TalkStatusBar>
<View style={[styles.content, styles['content__' + status]]}>
<View style={[styles.text, styles['text__' + status]]}>
{subtitle}
<Text style={[styles.title, styles['title__' + status]]}>
{title}
</Text>
</View>
<View style={styles.right}>
{avatar}
<Icon
color={theme.color.gray40}
name="ios-arrow-forward"
size={20}
style={styles.chevron}
/>
</View>
</View>
</View>
</TouchableHighlight>
);
}
}
const styles = StyleSheet.create({
touchable: {
backgroundColor: 'white',
},
base: {
alignItems: 'stretch',
backgroundColor: 'transparent',
flexDirection: 'row',
},
// base__present: {
// backgroundColor: fade(theme.color.blue, 3),
// },
statusbarIcon: {
backgroundColor: 'transparent',
height: 34,
left: 0,
position: 'absolute',
top: 10,
width: 34,
},
// content
content: {
alignItems: 'center',
backgroundColor: 'transparent',
flexDirection: 'row',
flexGrow: 1,
flexShrink: 1,
padding: theme.fontSize.default,
},
content__past: {
opacity: 0.5,
},
text: {
flexGrow: 1,
flexShrink: 1,
paddingRight: theme.fontSize.xsmall,
},
subtitle: {
alignItems: 'center',
flexDirection: 'row',
marginBottom: theme.fontSize.small,
},
subtitleText: {
color: theme.color.gray60,
flexShrink: 1,
fontSize: theme.fontSize.small,
fontWeight: '300',
},
title: {
color: theme.color.text,
fontSize: theme.fontSize.default,
},
// right (avatar and chevron)
right: {
alignItems: 'center',
flexDirection: 'row',
flexShrink: 0,
},
// chevron
chevron: {
marginLeft: theme.fontSize.default,
},
});
|
third_party/prometheus_ui/base/web/ui/node_modules/reactstrap/src/InputGroupAddon.js | GoogleCloudPlatform/prometheus-engine | import React from 'react';
import PropTypes from 'prop-types';
import classNames from 'classnames';
import { mapToCssModules, tagPropType } from './utils';
import InputGroupText from './InputGroupText';
const propTypes = {
tag: tagPropType,
addonType: PropTypes.oneOf(['prepend', 'append']).isRequired,
children: PropTypes.node,
className: PropTypes.string,
cssModule: PropTypes.object,
};
const defaultProps = {
tag: 'div'
};
const InputGroupAddon = (props) => {
const {
className,
cssModule,
tag: Tag,
addonType,
children,
...attributes
} = props;
const classes = mapToCssModules(classNames(
className,
'input-group-' + addonType
), cssModule);
// Convenience to assist with transition
if (typeof children === 'string') {
return (
<Tag {...attributes} className={classes}>
<InputGroupText children={children} />
</Tag>
);
}
return (
<Tag {...attributes} className={classes} children={children} />
);
};
InputGroupAddon.propTypes = propTypes;
InputGroupAddon.defaultProps = defaultProps;
export default InputGroupAddon;
|
components/events/EventsList.js | BDE-ESIEE/mobile | import React, { Component } from 'react';
import {
Text,
View,
ListView,
ActivityIndicator,
StatusBar,
RefreshControl,
Button,
TouchableOpacity
} from 'react-native';
import LinearGradient from 'react-native-linear-gradient';
import moment from 'moment';
import Icon from 'react-native-vector-icons/Ionicons';
import styles from '../styles/events.js';
import EventCard from './EventCard';
import { ifIphoneX } from 'react-native-iphone-x-helper'
import { Actions } from "react-native-router-flux";
class EventsList extends Component {
constructor (props) {
super(props);
this.state = {
events: new ListView.DataSource({
rowHasChanged: (row1, row2) => row1 !== row2,
sectionHeaderHasChanged: (s1, s2) => s1 !== s2
}),
loading: true,
refreshing: false
};
}
componentDidMount () {
this.getEvents();
}
_onRefresh() {
this.setState({refreshing: true});
this.getEvents();
}
render () {
let loadingElement;
let listElement;
if (this.state.loading) {
loadingElement = (
<View style={{flex: 1, flexDirection: 'column', justifyContent: 'center'}}>
<ActivityIndicator color='#f4373b' size='large' />
</View>
);
} else {
listElement = (
<ListView
dataSource={this.state.events}
renderRow={(event, sectionID, rowID) => <EventCard event={event} row={rowID} />}
renderSectionHeader={this.renderHeader}
refreshControl={
<RefreshControl
refreshing={this.state.refreshing}
onRefresh={this._onRefresh.bind(this)}
tintColor={'#f4373b'}
/>
}
/>
);
}
return (
<View style={styles.container}>
<StatusBar translucent backgroundColor='rgba(0,0,0,0.2)' barStyle='light-content' />
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#f4373b']}
style={{...ifIphoneX({height: 45}, {height: 25})}}
/>
<StatusBar translucent={true} backgroundColor="rgba(0,0,0,0.2)" barStyle="light-content"/>
<View>
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#f4373b']}
style={styles.topBar}>
<TouchableOpacity onPress={() => Actions.pop()}>
<Icon
name='ios-arrow-dropleft-outline'
style={styles.topBarButton}
/>
</TouchableOpacity>
<Text style={styles.topBarText}>
<Text style={styles.topBarNormalText}>Évènements</Text>
</Text>
<TouchableOpacity activeOpacity={1}>
<Icon
name='ios-arrow-dropright-outline'
style={[styles.topBarButton, {
opacity: 0.3
}]}
/>
</TouchableOpacity>
</LinearGradient>
</View>
{loadingElement}
{listElement}
</View>
);
}
renderHeader (sectionData, sectionID) {
if (sectionID === '0') {
return (
<View>
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#f4373b']}
style={styles.weekHeader}>
<Text style={styles.weekHeaderBigNumber}>{sectionData.length}</Text>
<Text style={styles.weekHeaderTextCurWeek}>Évènement{sectionData.length > 1 ? 's' : ''} cette semaine !</Text>
</LinearGradient>
</View>
);
} else {
let weekText = sectionID === '1' ? 'La semaine prochaine' : (`Dans ${sectionID} semaines`);
return (
<View>
<LinearGradient
start={{x: 0.0, y: 0}} end={{x: 1, y: 1}}
colors={['#f4373b', '#ff686b']}
style={styles.weekHeaderSmall}>
<Text style={styles.weekHeaderText}>{weekText}</Text>
</LinearGradient>
</View>
);
}
}
getEvents() {
fetch('https://bde.esiee.fr/events.json', {
method: 'GET',
headers: {
'Content-Type': 'application/json'
}
})
.then((response) => {
response.json().then((json) => {
let events = json;
let eventsByWeek = {};
events.map((event) => {
let start = moment(event.start);
// let end = moment(event.end);
if (start.isAfter()) {
let weekDiff = start.week() - moment().week();
if (!eventsByWeek[weekDiff]) {
eventsByWeek[weekDiff] = [];
}
eventsByWeek[weekDiff].push(event);
}
});
this.setState({loading: false, events: this.state.events.cloneWithRowsAndSections(eventsByWeek), refreshing: false});
});
});
}
}
module.exports = EventsList;
|
src/components/header/header.js | awaseem/Jam | import React from 'react';
function Header(props) {
return (
<div
style={{
height: props.height || '100vh',
background: `no-repeat center url(${props.image})`,
paddingTop: props.paddingTop || '250px',
paddingBottom: props.paddingBottom || '0px',
backgroundSize: 'cover',
width: '100%',
marginBottom: '50px',
color: props.textColor || '#FFF',
}}
>
{props.children}
</div>
);
}
Header.propTypes = {
children: React.PropTypes.any.isRequired,
image: React.PropTypes.string.isRequired,
paddingTop: React.PropTypes.string,
paddingBottom: React.PropTypes.string,
textColor: React.PropTypes.string,
height: React.PropTypes.string,
};
export default Header;
|
ui/src/components/ColorPicker/index.js | LearningLocker/learninglocker | import React from 'react';
import PropTypes from 'prop-types';
import { connect } from 'react-redux';
import { CirclePicker } from 'react-color';
import { compose, withProps } from 'recompose';
import { Map, List } from 'immutable';
import { MAX_CUSTOM_COLORS } from 'lib/constants/visualise';
import { activeOrgIdSelector } from 'ui/redux/modules/router';
import { VISUALISATION_COLORS } from 'ui/utils/constants';
import { withModel } from 'ui/utils/hocs';
import CustomColorPicker from './CustomColorPicker';
class ColorPicker extends React.PureComponent {
static propTypes = {
color: PropTypes.string,
model: PropTypes.instanceOf(Map), // organisation
onChange: PropTypes.func,
updateModel: PropTypes.func, // update organisation
}
constructor(props) {
super(props);
this.state = { isOpen: false };
}
onClickEdit = () => {
this.setState(prevState => ({ isOpen: !prevState.isOpen }));
}
/**
* @params {tinycolor.Instance} color
*/
onSelectCustomColor = (color) => {
this.setState({ isOpen: false });
this.props.onChange(color);
// Add new selected color to the head of customColors
const newCustomColors = this.getCustomColors()
.unshift(color.hex)
.toSet()
.toList()
.slice(0, MAX_CUSTOM_COLORS);
if (!this.getCustomColors().equals(newCustomColors)) {
this.props.updateModel({
path: ['customColors'],
value: newCustomColors,
});
}
}
/**
* @returns {immutable.List} - List of hex. e.g. List(['#FFFFFF', '#2AFEC9'])
*/
getCustomColors = () => this.props.model.get('customColors', new List());
render = () => {
const {
color,
onChange,
} = this.props;
const customColors = this.getCustomColors();
// The selected color or a color that the organisation recently selected
const trendColor = VISUALISATION_COLORS.includes(color.toUpperCase()) ? customColors.first() : color;
return (
<div style={{ display: 'flex' }}>
<CirclePicker
color={color}
colors={trendColor ? VISUALISATION_COLORS.concat(trendColor) : VISUALISATION_COLORS}
onChange={onChange}
width={'auto'} />
<div>
<div
style={{
paddingLeft: '14px',
width: '28px',
height: '28px',
display: 'flex',
alignItems: 'center',
}}
onClick={this.onClickEdit} >
<i className="icon ion-edit" />
</div>
{
this.state.isOpen && (
<div style={{ position: 'absolute', zIndex: '2' }}>
<div
style={{
position: 'fixed',
top: '0px',
right: '0px',
bottom: '0px',
left: '0px',
}}
onClick={() => this.setState({ isOpen: false })} />
<div style={{ position: 'relative' }}>
<div style={{ position: 'absolute', bottom: '40px', right: '-32px' }}>
<CustomColorPicker
initialColor={color}
customColors={customColors}
onClickCheckMark={this.onSelectCustomColor} />
</div>
</div>
</div>
)
}
</div>
</div>
);
}
}
export default compose(
connect(state => ({
organisationId: activeOrgIdSelector(state)
}), {}),
withProps(({ organisationId }) => ({
id: organisationId,
schema: 'organisation'
})),
withModel,
)(ColorPicker);
|
frontend/webapp/js/Event.js | damorton/dropwizardheroku-webgateway | import React from 'react';
import axios from 'axios';
class ActionControl extends React.Component {
constructor(props){
super(props);
this.state = {
id : props.id,
url: props.url
};
this.edit = this.edit.bind(this)
this.remove = this.remove.bind(this)
}
edit(){
}
remove(){
const requestUrlWithParam = this.state.url + '/' + this.state.id;
axios.delete(requestUrlWithParam).then(function(res) {
});
}
render(){
return (
<div className='ActionControl'>
<button className='ActionControl-edit' onClick={this.edit}>EDIT</button>
<button className='ActionControl-remove' onClick={this.remove}>X</button>
</div>
)
}
}
class Event extends React.Component {
constructor(props){
super(props);
this.state = {
data : props.data,
key: props.key,
url: props.url
};
}
render(){
return (
<li key={this.state.data.id}>
<div className='EventList-item'>
<h2 className='EventListItem-name'>{this.state.data.name}</h2>
<div>{this.state.data.description}</div>
<div>{this.state.data.location}</div>
<div>{this.state.data.date}</div>
<ActionControl url={this.state.url} id={this.state.data.id}/>
</div>
</li>
)
}
}
export default Event;
|
app/components/loader/index.js | ajaymathur/fun-community | import React from 'react';
import { View, ActivityIndicator } from 'react-native';
class Loader extends React.Component {
constructor(props) {
super( props );
}
render() {
return (
<View>
{this.props.showLoader ?
<ActivityIndicator
animating={true}
style={{height: 80}}
size="large"
color="#004aff"
/>
: null
}
</View>
)
}
}
Loader.propTypes = {
showLoader: React.PropTypes.bool.isRequired,
};
export default Loader;
|
src/components/Map/index.js | opentraffic/analyst-ui | import React from 'react'
import PropTypes from 'prop-types'
import { Map as Leaflet, ScaleControl } from 'react-leaflet'
import 'leaflet-editable'
import 'leaflet.path.drag'
import TangramLayer from './TangramLayer'
import 'leaflet/dist/leaflet.css'
import './Map.css'
const ATTRIBUTION = '<a href="https://mapzen.com/">Mapzen</a>, © <a href="https://www.openstreetmap.org/copyright">OpenStreetMap contributors</a>, <a href="https://whosonfirst.mapzen.com#License">Who’s on First</a>'
export default class Map extends React.Component {
static propTypes = {
className: PropTypes.string,
children: PropTypes.any,
center: PropTypes.array,
zoom: PropTypes.number,
onChange: PropTypes.func,
onClick: PropTypes.func,
refSpeedComparisonEnabled: PropTypes.bool,
refSpeedEnabled: PropTypes.bool,
recenterMap: PropTypes.func
}
static defaultProps = {
center: [0, 0],
zoom: 3,
onChange: function () {},
onClick: function () {}
}
componentDidMount () {
// Expose map globally for debug
window.map = this.map.leafletElement
}
// When map is dragged/zoomed and lat/lng/zoom are changed, update URL to reflect change
// Config is now also updated whenever lat/lng/zoom are changed
onChange = (event) => {
const newCenter = event.target.getCenter()
const newZoom = event.target.getZoom()
this.props.recenterMap([newCenter.lat, newCenter.lng], newZoom)
}
render () {
const { className, children, center, refSpeedComparisonEnabled, refSpeedEnabled, zoom, onClick, scene } = this.props
// The `editable` option is not provided by Leaflet but by Leaflet.Editable.
// It is passed to the options object via props.
return (
<Leaflet
className={className}
center={center}
zoom={zoom}
onClick={onClick}
onMoveEnd={this.onChange}
ref={(ref) => { this.map = ref }}
editable
>
<TangramLayer
refSpeedComparisonEnabled={refSpeedComparisonEnabled}
refSpeedEnabled={refSpeedEnabled}
scene={scene}
attribution={ATTRIBUTION} />
<ScaleControl />
{children}
</Leaflet>
)
}
}
|
annotate-gt/src/App.js | jkerfs/annotate-gt | import React, { Component } from 'react';
import './App.css';
import Opening from './Opening'
import Canvas from './Canvas'
import Finalize from './Finalize'
class App extends Component {
constructor() {
super()
this.state = {
comp: "Opening",
data: {}
}
}
handleStart(state) {
this.setState({comp: "Canvas"})
this.setState({color: state.color})
this.setState({mode: state.mode})
this.setState({files: state.files})
}
handleFinish(o) {
this.setState({data: o})
this.setState({comp: "Finish"})
}
handleRestart() {
this.setState({comp: "Opening"})
}
render() {
var body;
if (this.state.comp === "Canvas") {
console.log("Starting Canvas")
body = <Canvas mode={this.state.mode} color={this.state.color}
files={this.state.files} finish={(txt) => this.handleFinish(txt)}/>
}
else if (this.state.comp === "Finish") {
body = <Finalize restart={() => this.handleRestart()} data={this.state.data}/>
}
else {
body = <Opening onSubmit={(state) => this.handleStart(state)} />
}
return (
<div className="App">
<div className="App-header">
<h2>annotate-gt</h2>
</div>
<div className="ui-holder">
{ body }
</div>
</div>
);
}
}
export default App;
|
src/parser/shaman/elemental/CHANGELOG.js | fyruna/WoWAnalyzer | import { niseko, HawkCorrigan } from 'CONTRIBUTORS';
import React from 'react';
import SPELLS from 'common/SPELLS';
import SpellLink from 'common/SpellLink';
export default [
{
date: new Date('2019-05-06'),
changes: <>Added support for the damage part of <SpellLink id={SPELLS.IGNEOUS_POTENTIAL.id} />.</>,
contributors: [niseko],
},
{
date: new Date('2019-03-20'),
changes: <>Fixing <SpellLink id={SPELLS.MASTER_OF_THE_ELEMENTS_TALENT.id} />-Tracker and Damage Calculation.</>,
contributors: [HawkCorrigan],
},
{
date: new Date('2018-11-13'),
changes: <>Added a basic Checklist, with the cross-spec functionalities.</>,
contributors: [HawkCorrigan],
},
{
date: new Date('2018-11-04'),
changes: <>Added support for <SpellLink id={SPELLS.PACK_SPIRIT_TRAIT.id} /> and <SpellLink id={SPELLS.SERENE_SPIRIT_TRAIT.id} /> azerite traits.</>,
contributors: [niseko],
},
{
date: new Date('2018-11-01'),
changes: <>Added support for <SpellLink id={SPELLS.ASTRAL_SHIFT.id} /> damage reduction.</>,
contributors: [niseko],
},
{
date: new Date('2018-10-17'),
changes: <>Flagged the Elemental Shaman Analyzer as supported.</>,
contributors: [HawkCorrigan],
},
{
date: new Date('2018-10-15'),
changes: <>Added Checks for the correct usage of <SpellLink id={SPELLS.STORM_ELEMENTAL_TALENT.id} /> and <SpellLink id={SPELLS.FIRE_ELEMENTAL.id} /> when talented into <SpellLink id={SPELLS.PRIMAL_ELEMENTALIST_TALENT.id} />.</>,
contributors: [HawkCorrigan],
},
];
|
packages/mineral-ui-icons/src/IconLocalHotel.js | mineral-ui/mineral-ui | /* @flow */
import React from 'react';
import Icon from 'mineral-ui/Icon';
import type { IconProps } from 'mineral-ui/Icon/types';
/* eslint-disable prettier/prettier */
export default function IconLocalHotel(props: IconProps) {
const iconProps = {
rtl: false,
...props
};
return (
<Icon {...iconProps}>
<g>
<path d="M7 13c1.66 0 3-1.34 3-3S8.66 7 7 7s-3 1.34-3 3 1.34 3 3 3zm12-6h-8v7H3V5H1v15h2v-3h18v3h2v-9c0-2.21-1.79-4-4-4z"/>
</g>
</Icon>
);
}
IconLocalHotel.displayName = 'IconLocalHotel';
IconLocalHotel.category = 'maps';
|
client/src/app/components/forms/inputs/NoUiSlider.js | zraees/sms-project | import React from 'react'
import noUiSlider from 'nouislider'
export default class NoUiSlider extends React.Component {
componentDidMount() {
const slider = this.refs.slider;
const element = $(slider);
const props = this.props;
element.addClass('noUiSlider');
const options = {
range: {
min: props.rangeMin ? parseInt(props.rangeMin) : 0,
max: props.rangeMax ? parseInt(props.rangeMax) : 1000
},
start: props.start
};
if (props.step) options.step = parseInt(props.step);
// if (props.connect) options.connect = props.connect == 'true' ? true : props.connect;
noUiSlider.create(slider, options);
slider.noUiSlider.on('change', ()=>{
if(props.update){
$(props.update).text(JSON.stringify(element.val()));
}
});
}
render() {
return (
<div ref="slider"/>
)
}
} |
app/javascript/mastodon/features/ui/components/column_link.js | sylph-sin-tyaku/mastodon | import React from 'react';
import PropTypes from 'prop-types';
import { Link } from 'react-router-dom';
import Icon from 'mastodon/components/icon';
const ColumnLink = ({ icon, text, to, href, method, badge }) => {
const badgeElement = typeof badge !== 'undefined' ? <span className='column-link__badge'>{badge}</span> : null;
if (href) {
return (
<a href={href} className='column-link' data-method={method}>
<Icon id={icon} fixedWidth className='column-link__icon' />
{text}
{badgeElement}
</a>
);
} else {
return (
<Link to={to} className='column-link'>
<Icon id={icon} fixedWidth className='column-link__icon' />
{text}
{badgeElement}
</Link>
);
}
};
ColumnLink.propTypes = {
icon: PropTypes.string.isRequired,
text: PropTypes.string.isRequired,
to: PropTypes.string,
href: PropTypes.string,
method: PropTypes.string,
badge: PropTypes.node,
};
export default ColumnLink;
|
src/containers/search-bar/SearchBar.js | SalvaCarsi/SearchView | 'use strict';
import React, { Component } from 'react';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import SearchBarWrapper from '../../components/styled/SearchBarWrapper';
import { HeaderTextWrapper } from '../../components/styled/TextWrapper';
import Button from '../../components/styled/Button';
import InputWrapper from '../../components/styled/InputWrapper';
import * as actionsCreator from './actions';
export class SearchBar extends Component {
constructor(props) {
super(props);
this.state = {searchText: ''};
}
handleChange = (event) => {
this.setState({searchText: event.target.value});
};
handleSubmit = () => {
this.props.actions.searchQuestion(this.state.searchText);
};
render = () => {
return (
<SearchBarWrapper>
<HeaderTextWrapper>
Buscador de preguntas
</HeaderTextWrapper>
<InputWrapper value={this.state.value} onChange={this.handleChange} />
<Button onClick={this.handleSubmit}>Buscar</Button>
</SearchBarWrapper>
);
}
}
// Container
const mapStateToProps = state => ({searchText: state.searchBarReducer.searchText});
const mapDispatchToProps = dispatch => ({actions: bindActionCreators(actionsCreator, dispatch)});
export default connect(mapStateToProps, mapDispatchToProps)(SearchBar); |
src/components/todoForm.js | jonkemp/universal-react-todo-app | import React from 'react';
import TodoList from './todoList';
export default React.createClass({
getInitialState() {
return {items: ['One', 'Two', 'Three'], text: ''};
},
onChange(e) {
this.setState({text: e.target.value});
},
handleSubmit(e) {
e.preventDefault();
const nextItems = this.state.items.concat([this.state.text]);
const nextText = '';
this.setState({items: nextItems, text: nextText});
},
render() {
return <div>
<form onSubmit={this.handleSubmit.bind(this)}>
<input onChange={this.onChange.bind(this)} value={this.state.text} />
<button>{'Add #' + (this.state.items.length + 1)}</button>
</form>
<TodoList items={this.state.items} />
</div>;
}
});
|
consoles/my-joy-images/src/app.js | yldio/joyent-portal | import React from 'react';
import Helmet from 'react-helmet-async';
import { RootContainer } from 'joyent-ui-toolkit';
import Routes from '@root/routes';
export default () => (
<RootContainer>
<Helmet>
<title>Images</title>
</Helmet>
<Routes />
</RootContainer>
);
|
internals/templates/containers/App/index.js | plasticanthony/coffee-dates | /**
*
* App.react.js
*
* This component is the skeleton around the actual pages, and should only
* contain code that should be seen on all pages. (e.g. navigation bar)
*
* NOTE: while this component should technically be a stateless functional
* component (SFC), hot reloading does not currently support SFCs. If hot
* reloading is not a necessity for you then you can refactor it and remove
* the linting exception.
*/
import React from 'react';
export default class App extends React.PureComponent { // eslint-disable-line react/prefer-stateless-function
static propTypes = {
children: React.PropTypes.node,
};
render() {
return (
<div>
{React.Children.toArray(this.props.children)}
</div>
);
}
}
|
examples/kitchensink/app-color/components/Root.js | Travix-International/frint | import React from 'react';
import { observe } from 'frint-react';
import { Observable } from 'rxjs/Observable';
import { concatMap } from 'rxjs/operator/concatMap';
import { map } from 'rxjs/operator/map';
import { merge } from 'rxjs/operator/merge';
import { scan } from 'rxjs/operator/scan';
import PropTypes from 'prop-types';
import {
changeColor
} from '../actions/color';
import {
GREEN_COLOR,
RED_COLOR,
ORANGE_COLOR,
CHANGE_COLOR_ASYNC
} from '../constants';
class Root extends React.Component {
static propTypes = {
color: PropTypes.string,
counter: PropTypes.number,
incrementCounter: PropTypes.func,
decrementCounter: PropTypes.func,
changeColor: PropTypes.func,
changeColorAsync: PropTypes.func,
regionProps: PropTypes.object,
foo: PropTypes.object,
bar: PropTypes.object,
baz: PropTypes.object
};
render() {
const codeStyle = {
color: this.props.color,
backgroundColor: this.props.color
};
return (
<div>
<h5>App: Color</h5>
<p>Color value in <strong>ColorApp</strong>: <code style={codeStyle}>{this.props.color}</code></p>
<div>
<button
className="button"
onClick={() => this.props.changeColor(GREEN_COLOR)}
style={{ backgroundColor: GREEN_COLOR, color: '#fff' }}
>
Green
</button>
<button
className="button"
onClick={() => this.props.changeColor(RED_COLOR)}
style={{ backgroundColor: RED_COLOR, color: '#fff' }}
>
Red
</button>
<button
className="button"
onClick={() => this.props.changeColorAsync(ORANGE_COLOR)}
style={{ backgroundColor: ORANGE_COLOR, color: '#fff' }}
>
Async
</button>
</div>
<p>Counter value from <strong>CounterApp</strong>: <code>{this.props.counter}</code></p>
<p>
<a
href="#"
onClick={() => this.props.incrementCounter()}
>
Increment
</a> counter from here.
</p>
<div>
<p>
<strong>Region Props:</strong>
</p>
<pre><code>{JSON.stringify(this.props.regionProps, null, 2)}</code></pre>
</div>
<div>
<p>
<strong>Services:</strong>
</p>
<ul>
<li><strong>Foo</strong> (cascaded): is from <code>{this.props.foo.getAppName()}</code></li>
<li><strong>Bar</strong> (cascaded and scoped): is from <code>{this.props.bar.getAppName()}</code></li>
<li><strong>Baz</strong> (not cascaded): is unavaialble - <code>{this.props.baz}</code></li>
</ul>
</div>
</div>
);
}
}
export default observe(function (app) { // eslint-disable-line func-names
// self
const store = app.get('store');
const region = app.get('region');
const state$ = store.getState$()
::map((state) => {
return {
color: state.color.value,
};
});
const regionProps$ = region.getProps$()
::map((regionProps) => {
return {
regionProps,
};
});
const actions$ = Observable.of({
changeColor: (...args) => {
return store.dispatch(changeColor(...args));
},
changeColorAsync: (color) => {
return store.dispatch({
type: CHANGE_COLOR_ASYNC,
color,
});
},
});
const services$ = Observable.of({
foo: app.get('foo'),
bar: app.get('bar'),
baz: app.get('baz'),
});
// other app: CounterApp
const counterApp$ = app.getAppOnceAvailable$('CounterApp');
const counterAppState$ = counterApp$
::concatMap((counterApp) => {
return counterApp
.get('store')
.getState$();
})
::map((counterState) => {
return {
counter: counterState.counter.value
};
});
const counterAppActions$ = counterApp$
::map((counterApp) => {
const counterStore = counterApp.get('store');
return {
incrementCounter: () => {
return counterStore.dispatch({ type: 'INCREMENT_COUNTER' });
}
};
});
// combine them all into props
return state$
::merge(regionProps$)
::merge(actions$)
::merge(services$)
::merge(counterAppState$)
::merge(counterAppActions$)
::scan((props, emitted) => {
return {
...props,
...emitted,
};
}, {
// default props to start with
counter: 0,
});
})(Root);
|
src/types/bounds.js | uniphil/react-leaflet | import React from 'react';
import Leaflet from 'leaflet';
import latlngList from './latlngList';
export default React.PropTypes.oneOfType([
React.PropTypes.instanceOf(Leaflet.LatLngBounds),
latlngList,
]);
|
src/pages/About.js | TomClarkson/hanzi-gold-web | import React from 'react';
import ReactDisqusThread from 'react-disqus-thread';
export default class About extends React.Component {
render() {
return (
<div id="about-page">
<h1 className='lead-header'>Why was Hanzi Gold built?</h1>
<p className="lead">Hanzi Gold combines two of my passions; lanaguage learning and programming.</p>
<p className="lead" style={{marginBottom: 20}}>It was also built for two reasons. Firstly, to be a practical example of how to build
a production ready React application for the web and mobile, and secondly, to win tickets to attend the React conference.</p>
<p>I want to launch reactjscasts.com soon, and I believe Hanzi Gold is rich with features to make screencasts from.</p>
<p>For example, this application implements the Lietner spaced repetition system, which could be built with tdd in a screencast.</p>
<p>The screencasts will be great for a React developer wanting to make React Native apps
because it will compare different components and navigation paradigms and also how animations and business logic code can be re-used.</p>
<p>The next step for Hanzi Gold is to add a node server, this server will sync learning history between mobile and web.</p>
<p>Finally, I want to add hanzi sounds for comprehension and hanzi writing tests to the quiz and add a real time multiplayer mode to the quiz.</p>
<p className="preview-video">Now, preview what is to come. The video below showcases the app and shows how to build the quiz mode.</p>
</div>
);
}
} |
src/components/Preferences.js | chrisjohndigital/OpenLang | import React from 'react'
export class Preferences extends React.Component {
constructor(props) {
super();
this.state = {
value: false
};
this.handleChange = this.handleChange.bind(this);
}
handleChange(event) {
this.props.onPreferences(!this.state.value);
this.setState({
value: !this.state.value
});
}
render() {
return (
<div>
<form>
<label>
Record as simultaneous interpretation:
<input type="checkbox" name="dub" value="on" onChange={this.handleChange} />
</label>
</form>
</div>
)
}
componentDidMount() {
}
}
|
src/projects.js | kngroo/Kngr | import React, { Component } from 'react';
import { Link } from 'react-router';
import Gfycat from './gfycat';
require('./styles/projects.scss');
export default class Project extends Component {
constructor(props) {
super(props);
this.state = {
id: props.data.id,
title: props.data.title,
description: props.data.description
}
}
/* componentDidMount() {
this.setState({
id:
})
}*/
render() {
var link = '/projects/' + this.state.id;
return(
<li className="project-item">
<Link className="project-link" to={link}>{this.state.title}</Link>
<p>{this.state.description}</p>
</li>
)
}
}
export default class Projects extends Component {
constructor(props) {
super(props);
this.state = {
projects: []
}
}
componentDidMount() {
var projects = [
{
id: 0,
title: 'Gfycat Top 20',
description: 'Angular app for viewing trending gifs on Gfycat'
},
{
id: 1,
title: '360 Video Player',
description: 'Video player made with WebGl for viewing 360 video on the web'
}
];
this.setState({
projects: projects
});
}
render() {
var projects = [];
for (let i = 0; i < this.state.projects.length; i++) {
var project = this.state.projects[i];
projects.push(
<Project data={project}></Project>
)
}
return (
<section className="projects">
<ul className="projects-list">{projects}</ul>
</section>
)
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.